hecho lo ded Registro de pagos

Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
fede committed 2026-11-30 22:51:55 -03:00
1 parent b68db07c92
commit 09830e15ec
19 files changed
+722 -46

No files matched your search

@@ -1,10 +1,11 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
export async function obtenerFormasPago(fetch2?: Function) {
export async function obtenerFormasPago(fetch2?: Function, soloActivas = false) {
const fetchfn = fetch2 ? fetch2 : fetch;
const qs = soloActivas ? '?activas=true' : '';
try {
const req = await fetchfn(`${API_URL}/formas-pago/`, {
const req = await fetchfn(`${API_URL}/formas-pago/${qs}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
});
@@ -0,0 +1,24 @@
import { API_URL } from '$lib/env';
import { getToken } from '../token';
export interface RegistrarPagoPayload {
formaDePagoId: number;
importe: number;
fecha?: string;
observacion?: string;
}
export async function registrarPago(facturaId: number, payload: RegistrarPagoPayload) {
try {
const req = await fetch(`${API_URL}/facturas/${facturaId}/pagos`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
body: JSON.stringify(payload)
});
const data = await req.json();
if (req.ok) return data;
return data.error ?? 'error';
} catch {
return 'no se pudo alcanzar el servidor';
}
}
+20 -8
View File
@@ -16,14 +16,14 @@
Tag,
TextInput,
Select,
SelectItem,
Modal
SelectItem
} from 'carbon-components-svelte';
import { Add, View, Edit, Money, Close, Search } from 'carbon-icons-svelte';
import { goto } from '$app/navigation';
import { getPermissions } from '$lib/hooks/token';
import type { Factura } from '../../types';
import ModalVerComprobante from './ModalVerComprobante.svelte';
import RegistrarPagoModal from './RegistrarPagoModal.svelte';
let { data } = $props();
@@ -39,7 +39,7 @@
);
let cargando = $derived(data.facturas === undefined || data.facturas === null);
let puedeVentas = $derived(getPermissions().includes(13));
let puedeVentas = $derived(getPermissions().includes(15));
let numero = $state('');
let cliente = $state('');
@@ -57,6 +57,8 @@
let facturaId = $state(0);
let openVer = $state(false);
let facturaPago = $state<Factura | null>(null);
let openPago = $state(false);
function buscar() {
const params = new URLSearchParams();
@@ -129,7 +131,7 @@
}}
>
<div class="min-w-56 flex-1">
<TextInput labelText="Buscar" placeholder="N° factura o cliente" bind:value={numero} />
<TextInput labelText="Buscar" placeholder="N° factura" bind:value={numero} />
</div>
<div class="min-w-40">
<TextInput labelText="Cliente" placeholder="Nombre del cliente" bind:value={cliente} />
@@ -241,14 +243,19 @@
kind="ghost"
size="small"
icon={Money}
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}
>Registrar Pago</Button
disabled={f.estado === 'CANCELADA' ||
f.estado === 'PAGADA' ||
(f.saldo ?? 0) <= 0}
onclick={() => {
facturaPago = f;
openPago = true;
}}>Registrar Pago</Button
>
<Button
kind="danger-ghost"
size="small"
icon={Close}
disabled={f.estado === 'CANCELADA'}>Cancelar</Button
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Cancelar</Button
>
</div>
</TableCell>
@@ -261,4 +268,9 @@
{/if}
</div>
<ModalVerComprobante bind:open={openVer} {facturaId} />
<ModalVerComprobante bind:open={openVer} {facturaId} />
<RegistrarPagoModal
bind:open={openPago}
factura={facturaPago}
onClose={() => (facturaPago = null)}
/>
@@ -0,0 +1,226 @@
<script lang="ts">
import {
InlineNotification,
Modal,
NumberInput,
Select,
SelectItem,
TextInput
} from 'carbon-components-svelte';
import { invalidate } from '$app/navigation';
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
import { registrarPago } from '$lib/hooks/facturas/registrarPago';
import type { Factura, FormaDePago } from '../../types';
let {
open = $bindable(),
factura = null,
onClose
}: {
open?: boolean;
factura?: Factura | null;
onClose?: () => void;
} = $props();
let monto = $state(0);
let formaDePagoId = $state(0);
let fecha = $state('');
let observacion = $state('');
let formasPago = $state<FormaDePago[]>([]);
let cargandoFormas = $state(false);
let enviando = $state(false);
let error = $state('');
const saldo = $derived(factura ? Number(factura.saldo ?? 0) : 0);
const total = $derived(factura ? Number(factura.total ?? 0) : 0);
const bloqueada = $derived(
!factura || factura.estado === 'PAGADA' || factura.estado === 'CANCELADA' || saldo <= 0.005
);
function redondear2(valor: number): number {
return Math.round(valor * 100) / 100;
}
function hoyISO(): string {
const hoy = new Date();
const mes = String(hoy.getMonth() + 1).padStart(2, '0');
const dia = String(hoy.getDate()).padStart(2, '0');
return `${hoy.getFullYear()}-${mes}-${dia}`;
}
function formatMonto(valor?: number): string {
if (valor === undefined || valor === null) return '-';
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
}
function handleClose() {
open = false;
onClose?.();
}
async function cargarFormas() {
cargandoFormas = true;
const res = await obtenerFormasPago(fetch, true);
cargandoFormas = false;
if (Array.isArray(res)) {
formasPago = res;
} else {
formasPago = [];
error = typeof res === 'string' ? res : 'no se pudieron cargar las formas de pago';
}
}
$effect(() => {
if (!open) return;
monto = redondear2(factura?.saldo ?? 0);
formaDePagoId = 0;
fecha = hoyISO();
observacion = '';
error = '';
enviando = false;
void cargarFormas();
});
async function enviar() {
if (enviando || !factura) return;
error = '';
const importe = Number(monto ?? 0);
if (!Number.isFinite(importe) || importe <= 0) {
error = 'El importe debe ser mayor a cero.';
return;
}
if (Math.abs(importe - redondear2(importe)) > 0.000005) {
error = 'El importe debe tener como máximo 2 decimales.';
return;
}
if (importe > saldo + 0.005) {
error = `El importe supera el saldo pendiente (${formatMonto(saldo)}).`;
return;
}
if (!formaDePagoId) {
error = 'Seleccioná una forma de pago.';
return;
}
if (!fecha) {
error = 'Ingresá la fecha de pago.';
return;
}
if (fecha > hoyISO()) {
error = 'La fecha de pago no puede ser futura.';
return;
}
enviando = true;
const res = await registrarPago(factura.ID, {
formaDePagoId: Number(formaDePagoId),
importe,
fecha,
observacion: observacion.trim() || undefined
});
enviando = false;
if (typeof res === 'string') {
error = res;
return;
}
await invalidate('facturas:load');
open = false;
onClose?.();
}
</script>
<form
id="registrarPagoForm"
onsubmit={(e) => {
e.preventDefault();
void enviar();
}}
>
<Modal
formId="registrarPagoForm"
bind:open
size="lg"
modalHeading={`Registrar Pago - Factura ${factura?.numero ?? ''}`}
primaryButtonText="Registrar Pago"
primaryButtonDisabled={enviando || bloqueada || cargandoFormas}
secondaryButtonText="Cancelar"
on:click:button--secondary={handleClose}
on:close={handleClose}
>
{#if error}
<div class="mb-4">
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
</div>
{/if}
{#if bloqueada}
<div class="mb-4">
<InlineNotification
kind="warning"
title="Sin saldo pendiente"
subtitle="La factura ya está saldada o cancelada y no admite pagos."
hideCloseButton
/>
</div>
{/if}
<div class="mb-5 grid grid-cols-1 gap-3 sm:grid-cols-2">
<div class="sm:col-span-2">
<p class="text-sm text-gray-400">Cliente</p>
<p class="font-semibold">{factura?.cliente?.nombre ?? '-'}</p>
</div>
<div>
<p class="text-sm text-gray-400">Total Factura</p>
<p class="font-semibold">{formatMonto(total)}</p>
</div>
<div>
<p class="text-sm text-gray-400">Saldo Pendiente</p>
<p class="font-semibold">{formatMonto(saldo)}</p>
</div>
</div>
<div class="space-y-4">
<NumberInput
labelText="Monto a Pagar"
bind:value={monto}
min={0.01}
max={saldo}
step={0.01}
allowEmpty
disabled={bloqueada}
/>
<Select
labelText="Medio de Pago"
bind:selected={formaDePagoId}
disabled={cargandoFormas || bloqueada}
>
<SelectItem value={0} text="Seleccioná una forma de pago" />
{#each formasPago as forma (forma.ID)}
<SelectItem value={forma.ID} text={forma.descripcion} />
{/each}
</Select>
{#if !cargandoFormas && formasPago.length === 0}
<p class="text-sm text-gray-500">No hay formas de pago configuradas.</p>
{/if}
<TextInput
labelText="Fecha de Pago"
type="date"
bind:value={fecha}
max={hoyISO()}
disabled={bloqueada}
/>
<TextInput
labelText="Observación (opcional)"
bind:value={observacion}
maxlength={255}
disabled={bloqueada}
/>
</div>
</Modal>
</form>
@@ -2,7 +2,7 @@
import { Modal, TextInput, DataTable, Button } from 'carbon-components-svelte';
import type { Cliente } from '../../../types';
let { open = false, clientes = [], onSeleccionar }: {
let { open = $bindable(false), clientes = [], onSeleccionar }: {
open?: boolean;
clientes?: Cliente[];
onSeleccionar?: (id: number) => void;
+1 -1
View File
@@ -120,7 +120,7 @@
<Select labelText="Almacén" bind:selected={filtros.almacenId}>
<SelectItem value={0} text="Todos" />
{#each data.almacenes as a (a.id)}
<SelectItem value={a.id} text={a.nombre} />
<SelectItem value={a.id} text={a.codigo} />
{/each}
</Select>
+14
View File
@@ -372,3 +372,17 @@ export interface FormaDePago extends BaseModel {
empresaId?: number;
descripcion: string;
}
export interface RegistrarPagoPayload {
formaDePagoId: number;
importe: number;
fecha?: string;
observacion?: string;
}
export interface RegistrarPagoResponse {
pago: PagoResumen;
factura: Factura;
saldoAnterior: number;
saldoNuevo: number;
}