Private
Public Access
hecha funcionalidad de modificacion/cancelacion de facturas
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
94a4e292c4
commit
6331e16dc5
39 files changed
+2283
-104
No files matched your search
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function cancelarFactura(facturaId: number, motivo: string) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/${facturaId}/cancelar`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify({ motivo })
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'No se pudo cancelar la factura';
|
||||
} catch {
|
||||
return 'No se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export interface ItemModificarFactura {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
export interface ModificarFacturaPayload {
|
||||
items: ItemModificarFactura[];
|
||||
motivo: string;
|
||||
}
|
||||
|
||||
export async function modificarFactura(facturaId: number, payload: ModificarFacturaPayload) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/${facturaId}`, {
|
||||
method: 'PUT',
|
||||
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 ?? 'No se pudo modificar la factura';
|
||||
} catch {
|
||||
return 'No se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
import type { Factura } from '../../types';
|
||||
import ModalVerComprobante from './ModalVerComprobante.svelte';
|
||||
import RegistrarPagoModal from './RegistrarPagoModal.svelte';
|
||||
import CancelarFacturaModal from './CancelarFacturaModal.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -59,6 +60,8 @@
|
||||
let openVer = $state(false);
|
||||
let facturaPago = $state<Factura | null>(null);
|
||||
let openPago = $state(false);
|
||||
let facturaCancelar = $state<Factura | null>(null);
|
||||
let openCancelar = $state(false);
|
||||
|
||||
function buscar() {
|
||||
const params = new URLSearchParams();
|
||||
@@ -237,7 +240,8 @@
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={Edit}
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Modificar</Button
|
||||
disabled={f.estado !== 'EMITIDA' && f.estado !== 'PAGADA'}
|
||||
onclick={() => goto(`/facturas/${f.ID}/modificar`)}>Modificar</Button
|
||||
>
|
||||
<Button
|
||||
kind="ghost"
|
||||
@@ -255,7 +259,11 @@
|
||||
kind="danger-ghost"
|
||||
size="small"
|
||||
icon={Close}
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Cancelar</Button
|
||||
disabled={f.estado !== 'EMITIDA'}
|
||||
onclick={() => {
|
||||
facturaCancelar = f;
|
||||
openCancelar = true;
|
||||
}}>Cancelar</Button
|
||||
>
|
||||
</div>
|
||||
</TableCell>
|
||||
@@ -274,3 +282,14 @@
|
||||
factura={facturaPago}
|
||||
onClose={() => (facturaPago = null)}
|
||||
/>
|
||||
<CancelarFacturaModal
|
||||
bind:open={openCancelar}
|
||||
factura={facturaCancelar}
|
||||
onClose={() => (facturaCancelar = null)}
|
||||
onCancelada={(resultado) => {
|
||||
info = resultado.nota
|
||||
? `Factura cancelada. Se emitió ${resultado.nota.numero} por ${formatMonto(resultado.nota.importe)}.`
|
||||
: 'Factura cancelada correctamente.';
|
||||
facturaCancelar = null;
|
||||
}}
|
||||
/>
|
||||
@@ -0,0 +1,145 @@
|
||||
<script lang="ts">
|
||||
import { Button, InlineNotification, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { cancelarFactura } from '$lib/hooks/facturas/cancelarFactura';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import type { AjusteFacturaResponse, Almacen, Factura } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
factura = null,
|
||||
onCancelada,
|
||||
onClose
|
||||
}: {
|
||||
open?: boolean;
|
||||
factura?: Factura | null;
|
||||
onCancelada?: (resultado: AjusteFacturaResponse) => void;
|
||||
onClose?: () => void;
|
||||
} = $props();
|
||||
|
||||
let motivo = $state('');
|
||||
let enviando = $state(false);
|
||||
let error = $state('');
|
||||
let almacenes = $state<Almacen[]>([]);
|
||||
|
||||
let cliente = $derived(factura?.cliente?.nombre ?? '-');
|
||||
let total = $derived(Number(factura?.total ?? 0));
|
||||
let almacen = $derived(almacenes.find((item) => item.id === factura?.almacenId));
|
||||
let almacenTexto = $derived(
|
||||
almacen
|
||||
? `${almacen.codigo}${almacen.ubicacion ? ` · ${almacen.ubicacion}` : ''}`
|
||||
: factura?.almacenId
|
||||
? `Almacén ${factura.almacenId}`
|
||||
: '-'
|
||||
);
|
||||
|
||||
function formatMonto(valor?: number): string {
|
||||
if (valor === undefined || valor === null) return '-';
|
||||
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
function cerrar() {
|
||||
open = false;
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function cargarAlmacenes() {
|
||||
const res = await obtenerAlmacenes(fetch);
|
||||
almacenes = Array.isArray(res) ? res : [];
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
motivo = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
void cargarAlmacenes();
|
||||
});
|
||||
|
||||
async function confirmar() {
|
||||
if (enviando || !factura) return;
|
||||
error = '';
|
||||
|
||||
const motivoLimpio = motivo.trim();
|
||||
if (!motivoLimpio) {
|
||||
error = 'Ingresá el motivo de la cancelación.';
|
||||
return;
|
||||
}
|
||||
if (motivoLimpio.length > 40) {
|
||||
error = 'El motivo no puede superar los 40 caracteres.';
|
||||
return;
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
const respuesta = await cancelarFactura(factura.ID, motivoLimpio);
|
||||
enviando = false;
|
||||
|
||||
if (typeof respuesta === 'string') {
|
||||
error = respuesta;
|
||||
return;
|
||||
}
|
||||
|
||||
await invalidate('facturas:load');
|
||||
open = false;
|
||||
onCancelada?.(respuesta as AjusteFacturaResponse);
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="cancelar-factura-form"
|
||||
onsubmit={(event) => {
|
||||
event.preventDefault();
|
||||
confirmar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
bind:open
|
||||
modalHeading={`Cancelar Factura ${factura?.numero ?? ''}`}
|
||||
secondaryButtonText="Volver"
|
||||
primaryButtonText={enviando ? 'Cancelando...' : 'Confirmar Cancelación'}
|
||||
primaryButtonDisabled={enviando}
|
||||
formId="cancelar-factura-form"
|
||||
hasForm
|
||||
on:click:button--secondary={cerrar}
|
||||
danger
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Atención"
|
||||
subtitle="Esta acción generará automáticamente una Nota de Crédito asociada a esta factura."
|
||||
hideCloseButton
|
||||
/>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Cliente</span>
|
||||
<span class="block py-2">{cliente}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Total</span>
|
||||
<span class="block py-2">{formatMonto(total)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Almacén de devolución</span>
|
||||
<span class="block py-2">{almacenTexto}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<TextInput
|
||||
labelText="Motivo de Cancelación"
|
||||
bind:value={motivo}
|
||||
maxlength={40}
|
||||
placeholder="Detallá el motivo de la cancelación"
|
||||
disabled={enviando}
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">{motivo.length}/40</p>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -229,6 +229,36 @@
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
<!-- Notas de crédito y débito asociadas -->
|
||||
{#if comprobante.notas && comprobante.notas.length > 0}
|
||||
<div class="space-y-2">
|
||||
<TableContainer title="Notas de ajuste">
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Fecha</TableHeader>
|
||||
<TableHeader>Nota</TableHeader>
|
||||
<TableHeader>Motivo</TableHeader>
|
||||
<TableHeader>Importe</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each comprobante.notas as nota (nota.id)}
|
||||
<TableRow>
|
||||
<TableCell>{formatFecha(nota.fecha)}</TableCell>
|
||||
<TableCell>
|
||||
<Tag type={nota.tipo === 'CREDITO' ? 'red' : 'green'}>{nota.numero}</Tag>
|
||||
</TableCell>
|
||||
<TableCell class="text-gray-500">{nota.motivo}</TableCell>
|
||||
<TableCell class="text-right font-medium">{formatMonto(nota.importe)}</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Pagos realizados usando Carbon Table -->
|
||||
<div class="space-y-2">
|
||||
<TableContainer>
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
DataTable,
|
||||
InlineNotification,
|
||||
NumberInput,
|
||||
TextInput,
|
||||
Tag
|
||||
} from 'carbon-components-svelte';
|
||||
import { ArrowLeft, Save } from 'carbon-icons-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { untrack } from 'svelte';
|
||||
import { modificarFactura } from '$lib/hooks/facturas/modificarFactura';
|
||||
import type { AjusteFacturaResponse, Almacen, ComprobanteResponse } from '../../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
interface Fila {
|
||||
key: number;
|
||||
repuestoId: number;
|
||||
nombre: string;
|
||||
cantidadOriginal: number;
|
||||
precioOriginal: number;
|
||||
incluir: boolean;
|
||||
cantidad: number;
|
||||
precio: number;
|
||||
}
|
||||
|
||||
let comprobante = $derived<ComprobanteResponse | null>(data.comprobante ?? null);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let almacenActual = $derived(almacenes.find((almacen) => almacen.id === comprobante?.almacenId));
|
||||
let error = $state('');
|
||||
let info = $state('');
|
||||
let enviando = $state(false);
|
||||
let resultado = $state<AjusteFacturaResponse | null>(null);
|
||||
let motivo = $state('');
|
||||
|
||||
let filas = $state<Fila[]>(
|
||||
untrack(() =>
|
||||
(data.comprobante?.detalles ?? []).map((detalle, indice) => ({
|
||||
key: indice,
|
||||
repuestoId: Number(detalle.repuestoId),
|
||||
nombre: detalle.repuestoNombre ?? `Repuesto ${detalle.repuestoId}`,
|
||||
cantidadOriginal: Number(detalle.cantidad),
|
||||
precioOriginal: Number(detalle.precioUnitario),
|
||||
incluir: false,
|
||||
cantidad: Number(detalle.cantidad),
|
||||
precio:
|
||||
data.preciosActuales?.[Number(detalle.repuestoId)] ??
|
||||
Number(detalle.precioUnitario)
|
||||
}))
|
||||
)
|
||||
);
|
||||
|
||||
function redondear(valor: number): number {
|
||||
return Math.round((valor + Number.EPSILON) * 100) / 100;
|
||||
}
|
||||
|
||||
function formatFecha(iso?: string): string {
|
||||
if (!iso) return '-';
|
||||
try {
|
||||
return new Date(iso).toLocaleDateString('es-AR');
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function formatMonto(valor?: number): string {
|
||||
if (valor === undefined || valor === null) return '-';
|
||||
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
const headers = [
|
||||
{ key: 'ajustar', value: 'Ajustar', empty: false },
|
||||
{ key: 'nombre', value: 'Ítem', empty: false },
|
||||
{ key: 'cantidadOriginal', value: 'Cant. Original', empty: false },
|
||||
{ key: 'cantidadAjustada', value: 'Cant. Ajustada', empty: false },
|
||||
{ key: 'precioOriginal', value: 'Precio Unit. Original', empty: false },
|
||||
{ key: 'precioAjustado', value: 'Precio Unit. Ajustado', empty: false },
|
||||
{ key: 'subtotal', value: 'Subtotal del Ajuste', empty: false }
|
||||
];
|
||||
|
||||
const headersDatos = [
|
||||
{ key: 'campo', value: 'Campo' },
|
||||
{ key: 'valor', value: 'Valor' }
|
||||
];
|
||||
|
||||
let filasDatos = $derived.by(() => {
|
||||
if (!comprobante) return [];
|
||||
const filas = [
|
||||
{ id: 'cliente', campo: 'Cliente', valor: comprobante.cliente?.nombre ?? '-' },
|
||||
{ id: 'fecha', campo: 'Fecha', valor: formatFecha(comprobante.FechaEmision) },
|
||||
{
|
||||
id: 'almacen',
|
||||
campo: 'Almacén',
|
||||
valor: almacenActual
|
||||
? `${almacenActual.codigo}${almacenActual.ubicacion ? ` · ${almacenActual.ubicacion}` : ''}`
|
||||
: comprobante.almacenId
|
||||
? `Almacén ${comprobante.almacenId}`
|
||||
: '-'
|
||||
},
|
||||
{ id: 'total', campo: 'Total', valor: formatMonto(comprobante.total) },
|
||||
{ id: 'estado', campo: 'Estado', valor: comprobante.estado }
|
||||
];
|
||||
if (comprobante.motivoUltimaEdicion) {
|
||||
filas.push({
|
||||
id: 'ultima-edicion',
|
||||
campo: 'Última edición',
|
||||
valor: comprobante.motivoUltimaEdicion
|
||||
});
|
||||
}
|
||||
return filas;
|
||||
});
|
||||
|
||||
const headersResumen = [
|
||||
{ key: 'concepto', value: 'Concepto', empty: false },
|
||||
{ key: 'monto', value: 'Monto', empty: false }
|
||||
];
|
||||
|
||||
let filasResumen = $derived.by(() => [
|
||||
{ id: 'subtotal', concepto: 'Subtotal', monto: formatMonto(subtotalNuevo) },
|
||||
{ id: 'descuento', concepto: 'Descuento', monto: formatMonto(descuentoNuevo) },
|
||||
{ id: 'iva', concepto: `IVA (${alicuota}%)`, monto: formatMonto(impuestosNuevos) },
|
||||
{ id: 'total', concepto: 'Total nuevo', monto: formatMonto(totalNuevo) }
|
||||
]);
|
||||
|
||||
function subtotalAjuste(fila: Fila): number {
|
||||
if (!fila.incluir) return 0;
|
||||
return redondear(fila.cantidad * fila.precio - fila.cantidadOriginal * fila.precioOriginal);
|
||||
}
|
||||
|
||||
let subtotalOriginal = $derived(
|
||||
redondear(
|
||||
(comprobante?.detalles ?? []).reduce(
|
||||
(acc, detalle) => acc + Number(detalle.cantidad) * Number(detalle.precioUnitario),
|
||||
0
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
let subtotalNuevo = $derived(
|
||||
redondear(
|
||||
filas.reduce((acc, fila) => {
|
||||
if (!fila.incluir) return acc + fila.cantidadOriginal * fila.precioOriginal;
|
||||
return acc + fila.cantidad * fila.precio;
|
||||
}, 0)
|
||||
)
|
||||
);
|
||||
|
||||
let descuentoOriginal = $derived(Number(comprobante?.descuentoTotal ?? 0));
|
||||
|
||||
// El backend conserva la proporción de descuento vigente; se replica para
|
||||
// que el monto proyectado en pantalla coincida con el que se persistirá.
|
||||
let descuentoNuevo = $derived.by(() => {
|
||||
const baseOriginal = Number(comprobante?.subtotal ?? subtotalOriginal);
|
||||
if (baseOriginal <= 0 || descuentoOriginal <= 0) return 0;
|
||||
const proporcionado = subtotalNuevo * (descuentoOriginal / baseOriginal);
|
||||
return redondear(Math.min(proporcionado, subtotalNuevo));
|
||||
});
|
||||
|
||||
let alicuota = $derived(Number(comprobante?.alicuotaIva ?? 21));
|
||||
let baseNueva = $derived(redondear(subtotalNuevo - descuentoNuevo));
|
||||
let impuestosNuevos = $derived(redondear((baseNueva * alicuota) / 100));
|
||||
let totalNuevo = $derived(redondear(baseNueva + impuestosNuevos));
|
||||
let totalActual = $derived(Number(comprobante?.total ?? 0));
|
||||
let diferencia = $derived(redondear(totalNuevo - totalActual));
|
||||
|
||||
let tipoNota = $derived(
|
||||
diferencia < -0.004
|
||||
? 'Nota de Crédito (Bajar Monto)'
|
||||
: diferencia > 0.004
|
||||
? 'Nota de Débito (Subir Monto)'
|
||||
: 'Sin cambios'
|
||||
);
|
||||
|
||||
let filasSeleccionadas = $derived(filas.filter((fila) => fila.incluir).length);
|
||||
|
||||
async function guardar() {
|
||||
if (enviando) return;
|
||||
error = '';
|
||||
|
||||
if (!comprobante) {
|
||||
error = 'No se pudo cargar la factura.';
|
||||
return;
|
||||
}
|
||||
if (filasSeleccionadas === 0) {
|
||||
error = 'Tildá al menos un ítem para ajustar.';
|
||||
return;
|
||||
}
|
||||
const motivoLimpio = motivo.trim();
|
||||
if (!motivoLimpio) {
|
||||
error = 'Ingresá el motivo de la modificación.';
|
||||
return;
|
||||
}
|
||||
if (motivoLimpio.length > 40) {
|
||||
error = 'El motivo no puede superar los 40 caracteres.';
|
||||
return;
|
||||
}
|
||||
if (Math.abs(diferencia) < 0.005) {
|
||||
error = 'La modificación no produce cambios de importe.';
|
||||
return;
|
||||
}
|
||||
for (const fila of filas) {
|
||||
if (!fila.incluir) continue;
|
||||
if (!(fila.cantidad > 0)) {
|
||||
error = `La cantidad de "${fila.nombre}" debe ser mayor a cero.`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
const respuesta = await modificarFactura(comprobante.ID, {
|
||||
items: filas.map((fila) => ({
|
||||
repuestoId: fila.repuestoId,
|
||||
cantidad: fila.incluir ? fila.cantidad : fila.cantidadOriginal,
|
||||
precioUnitario: fila.incluir ? fila.precio : fila.precioOriginal
|
||||
})),
|
||||
motivo: motivoLimpio
|
||||
});
|
||||
enviando = false;
|
||||
|
||||
if (typeof respuesta === 'string') {
|
||||
error = respuesta;
|
||||
return;
|
||||
}
|
||||
|
||||
resultado = respuesta as AjusteFacturaResponse;
|
||||
info = resultado.nota
|
||||
? `Factura modificada. Se emitió ${resultado.nota.numero} por ${formatMonto(resultado.nota.importe)}.`
|
||||
: 'Factura modificada correctamente.';
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="mb-4 flex items-center gap-2">
|
||||
<Button kind="ghost" icon={ArrowLeft} onclick={() => goto('/facturas')}>Volver</Button>
|
||||
<h1 class="page-title">
|
||||
Modificar Factura {comprobante?.numero ?? ''}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
{#if info}
|
||||
<InlineNotification kind="success" title="Modificación exitosa" subtitle={info} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if !comprobante}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Factura no disponible"
|
||||
subtitle={data.error || 'No se pudo cargar la factura solicitada.'}
|
||||
hideCloseButton
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-full space-y-4 px-4 md:px-6">
|
||||
<!-- Datos actuales -->
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Datos Actuales</h2>
|
||||
<DataTable size="compact" headers={headersDatos} rows={filasDatos as any} />
|
||||
</div>
|
||||
|
||||
<!-- Ítems -->
|
||||
<div class="rounded border p-4">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 class="text-lg font-semibold">Ítems de la Factura</h2>
|
||||
<p class="text-sm text-gray-600">Tildá los ítems que se ajustan</p>
|
||||
</div>
|
||||
<DataTable size="compact" {headers} rows={filas as any}>
|
||||
<svelte:fragment slot="cell" let:row let:cell>
|
||||
{@const fila = row as unknown as Fila}
|
||||
{#if cell.key === 'ajustar'}
|
||||
<Checkbox hideLabel labelText="Ajustar" bind:checked={fila.incluir} />
|
||||
{:else if cell.key === 'nombre'}
|
||||
{fila.nombre}
|
||||
{:else if cell.key === 'cantidadOriginal'}
|
||||
{fila.cantidadOriginal}
|
||||
{:else if cell.key === 'cantidadAjustada'}
|
||||
<NumberInput
|
||||
hideLabel
|
||||
labelText="Cantidad ajustada"
|
||||
bind:value={fila.cantidad}
|
||||
min={0}
|
||||
step={1}
|
||||
disabled={!fila.incluir}
|
||||
class="w-full"
|
||||
/>
|
||||
{:else if cell.key === 'precioOriginal'}
|
||||
{formatMonto(fila.precioOriginal)}
|
||||
{:else if cell.key === 'precioAjustado'}
|
||||
{formatMonto(fila.precio)}
|
||||
{:else if cell.key === 'subtotal'}
|
||||
{formatMonto(subtotalAjuste(fila))}
|
||||
{/if}
|
||||
</svelte:fragment>
|
||||
</DataTable>
|
||||
<p class="mt-2 text-xs text-gray-500">
|
||||
El precio unitario ajustado se toma del precio actual del producto y no es editable.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Nota de ajuste -->
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Tipo de Nota</h2>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Tipo</span>
|
||||
<span class="block py-2">{tipoNota}</span>
|
||||
<p class="text-sm text-gray-600">
|
||||
El tipo se determina automáticamente según el signo de la diferencia.
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div>
|
||||
<span class="block text-sm font-medium">Monto Total del Ajuste (calculado)</span>
|
||||
<span class="block py-2">{formatMonto(diferencia)}</span>
|
||||
</div>
|
||||
<div class="space-y-1 text-sm">
|
||||
<DataTable size="compact" headers={headersResumen} rows={filasResumen as any} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<TextInput
|
||||
labelText="Motivo General"
|
||||
bind:value={motivo}
|
||||
maxlength={40}
|
||||
placeholder="Detallá el motivo de la modificación"
|
||||
disabled={!!resultado}
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500">{motivo.length}/40</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<Button kind="secondary" onclick={() => goto('/facturas')} disabled={enviando}>
|
||||
{resultado ? 'Volver al listado' : 'Cancelar'}
|
||||
</Button>
|
||||
{#if !resultado}
|
||||
<Button icon={Save} onclick={guardar} disabled={enviando}>
|
||||
{enviando ? 'Guardando...' : 'Guardar Cambios'}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,52 @@
|
||||
import { obtenerComprobante } from '$lib/hooks/facturas/comprobante';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import type { Almacen, ComprobanteResponse, Repuesto } from '../../../../types';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, params, depends }) {
|
||||
depends('facturas:modificar:load');
|
||||
|
||||
const id = Number(params.id);
|
||||
if (!id || Number.isNaN(id)) {
|
||||
return {
|
||||
comprobante: null,
|
||||
preciosActuales: {} as Record<number, number>,
|
||||
almacenes: [] as Almacen[],
|
||||
error: 'Factura inválida'
|
||||
};
|
||||
}
|
||||
|
||||
const [comprobante, repuestosRes, almacenesRes] = await Promise.all([
|
||||
obtenerComprobante(fetch, id),
|
||||
obtenerRepuestos(fetch),
|
||||
obtenerAlmacenes(fetch)
|
||||
]);
|
||||
|
||||
if (typeof comprobante === 'string') {
|
||||
return {
|
||||
comprobante: null,
|
||||
preciosActuales: {} as Record<number, number>,
|
||||
almacenes: [] as Almacen[],
|
||||
error: comprobante
|
||||
};
|
||||
}
|
||||
|
||||
const repuestos = Array.isArray(repuestosRes) ? (repuestosRes as Repuesto[]) : [];
|
||||
const preciosActuales: Record<number, number> = {};
|
||||
for (const repuesto of repuestos) {
|
||||
const precio = Number(repuesto.precio);
|
||||
if (Number.isFinite(precio)) {
|
||||
preciosActuales[Number(repuesto.ID)] = precio;
|
||||
}
|
||||
}
|
||||
const almacenes = Array.isArray(almacenesRes) ? (almacenesRes as Almacen[]) : [];
|
||||
|
||||
return {
|
||||
comprobante: comprobante as ComprobanteResponse,
|
||||
preciosActuales,
|
||||
almacenes,
|
||||
error: ''
|
||||
};
|
||||
}
|
||||
Vendored
+32
@@ -326,6 +326,7 @@ export interface Factura {
|
||||
Observacion?: string;
|
||||
Version?: number;
|
||||
ClienteID?: number;
|
||||
almacenId?: number;
|
||||
cliente?: Cliente;
|
||||
ProveedorID?: number | null;
|
||||
proveedor?: Proveedor | null;
|
||||
@@ -345,6 +346,25 @@ export interface PagoResumen {
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface NotaResumen {
|
||||
id: number;
|
||||
tipo: 'CREDITO' | 'DEBITO';
|
||||
numero: string;
|
||||
motivo: string;
|
||||
importe: number;
|
||||
fecha: string;
|
||||
facturaId: number;
|
||||
}
|
||||
|
||||
export interface AjusteFacturaResponse {
|
||||
factura: Factura;
|
||||
nota?: NotaResumen;
|
||||
diferencia: number;
|
||||
saldoAnterior: number;
|
||||
saldoNuevo: number;
|
||||
stocks?: StockDisponible[];
|
||||
}
|
||||
|
||||
export interface ComprobanteResponse {
|
||||
ID: number;
|
||||
numero?: string;
|
||||
@@ -358,6 +378,7 @@ export interface ComprobanteResponse {
|
||||
saldo?: number;
|
||||
FechaEmision?: string;
|
||||
Observacion?: string;
|
||||
almacenId?: number;
|
||||
cliente?: {
|
||||
ID: number;
|
||||
nombre: string;
|
||||
@@ -366,6 +387,17 @@ export interface ComprobanteResponse {
|
||||
};
|
||||
detalles?: FacturaDetalle[];
|
||||
pagos: PagoResumen[];
|
||||
notas?: NotaResumen[];
|
||||
historial?: Array<{
|
||||
fecha: string;
|
||||
usuarioId: number;
|
||||
motivo: string;
|
||||
totalAnterior: number;
|
||||
totalNuevo: number;
|
||||
notaTipo?: string;
|
||||
notaId?: number;
|
||||
}>;
|
||||
motivoUltimaEdicion?: string;
|
||||
}
|
||||
|
||||
export interface FacturaResumen {
|
||||
|
||||
Reference in new issue
Block a user