Private
Public Access
commit parcial: refactor de decorator factura, añadida parcialemnte
funcionalidad de facturas tengo sueño Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
3c4bc5c008
commit
42bf987ffc
19 files changed
+525
-37
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export interface ItemFacturaPayload {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
export interface PagoFacturaPayload {
|
||||
formaDePagoId: number;
|
||||
importe: number;
|
||||
fecha?: string;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface CrearFacturaPayload {
|
||||
clienteId: number;
|
||||
almacenId: number;
|
||||
items: ItemFacturaPayload[];
|
||||
descuentoId?: number;
|
||||
pagos?: PagoFacturaPayload[];
|
||||
enviarEmail?: boolean;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export async function crearFactura(payload: CrearFacturaPayload) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/`, {
|
||||
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';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerDescuentos(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/descuentos/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerFormasPago(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/formas-pago/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<h1 class="page-title">Gestión de Facturas</h1>
|
||||
{#if puedeVentas}
|
||||
<Button icon={Add} onclick={() => (info = 'La creación de facturas se implementa en CU-02.')}>
|
||||
<Button icon={Add} onclick={() => goto('/facturas/nueva')}>
|
||||
Nueva Factura
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput,
|
||||
DataTable
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan, ArrowLeft } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
|
||||
import type { Cliente, Repuesto, Almacen } from '../../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let clientes = $derived<Cliente[]>(Array.isArray(data.clientes) ? data.clientes : []);
|
||||
let repuestos = $derived<Repuesto[]>(Array.isArray(data.repuestos) ? data.repuestos : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let descuentos = $derived<any[]>(Array.isArray(data.descuentos) ? data.descuentos : []);
|
||||
let formasPago = $derived<any[]>(Array.isArray(data.formasPago) ? data.formasPago : []);
|
||||
|
||||
let clienteId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
let descuentoId = $state<number>(0);
|
||||
let enviarEmail = $state(false);
|
||||
let observacion = $state('');
|
||||
|
||||
interface Item {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
let items = $state<Item[]>([{ repuestoId: 0, cantidad: 1, precioUnitario: 0 }]);
|
||||
|
||||
let pagoImporte = $state<number>(0);
|
||||
let pagoFormaId = $state<number>(0);
|
||||
let registrarPago = $state(false);
|
||||
|
||||
function agregarItem() {
|
||||
items = [...items, { repuestoId: 0, cantidad: 1, precioUnitario: 0 }];
|
||||
}
|
||||
|
||||
function quitarItem(i: number) {
|
||||
items = items.filter((_, idx) => idx !== i);
|
||||
if (items.length === 0) items = [{ repuestoId: 0, cantidad: 1, precioUnitario: 0 }];
|
||||
}
|
||||
|
||||
function precioRepuesto(id: number): number {
|
||||
const r = repuestos.find((x) => x.ID === id);
|
||||
return r ? r.precio : 0;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
for (const it of items) {
|
||||
if (it.repuestoId > 0 && it.precioUnitario === 0) {
|
||||
it.precioUnitario = precioRepuesto(it.repuestoId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let subtotal = $derived(
|
||||
items.reduce((acc, it) => acc + (it.cantidad > 0 ? it.cantidad * (it.precioUnitario || 0) : 0), 0)
|
||||
);
|
||||
|
||||
let descuentoTotal = $derived.by(() => {
|
||||
const d = descuentos.find((x) => x.ID === descuentoId);
|
||||
if (!d) return 0;
|
||||
if (d.Tipo === 'PORCENTAJE') return subtotal * (d.Valor / 100);
|
||||
return Math.min(d.Valor, subtotal);
|
||||
});
|
||||
|
||||
let baseImponible = $derived(subtotal - descuentoTotal);
|
||||
let impuestos = $derived(baseImponible * 0.21);
|
||||
let total = $derived(baseImponible + impuestos);
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!clienteId) { error = 'Seleccioná un cliente.'; enviando = false; return; }
|
||||
if (!almacenId) { error = 'Seleccioná un almacén.'; enviando = false; return; }
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidad > 0);
|
||||
if (itemsValidos.length === 0) { error = 'Agregá al menos un ítem válido.'; enviando = false; return; }
|
||||
|
||||
const payload = {
|
||||
clienteId,
|
||||
almacenId,
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidad: i.cantidad,
|
||||
precioUnitario: i.precioUnitario || precioRepuesto(i.repuestoId)
|
||||
})),
|
||||
descuentoId: descuentoId || undefined,
|
||||
pagos: registrarPago && pagoImporte > 0 ? [{ formaDePagoId: pagoFormaId, importe: pagoImporte }] : undefined,
|
||||
enviarEmail,
|
||||
observacion: observacion.trim() || undefined
|
||||
};
|
||||
|
||||
const res = await crearFactura(payload);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('facturas:load');
|
||||
void goto('/facturas');
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</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">Crear Factura de Venta</h1>
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<div class="space-y-4">
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Datos del Cliente</h2>
|
||||
<Select labelText="Cliente" bind:selected={clienteId}>
|
||||
<SelectItem value={0} text="Seleccioná un cliente" />
|
||||
{#each clientes as c (c.ID)}
|
||||
<SelectItem value={c.ID} text={`${c.nombre} (${c.cuit ?? ''})`} />
|
||||
{/each}
|
||||
</Select>
|
||||
{#if clienteId}
|
||||
{@const c = clientes.find((x) => x.ID === clienteId)}
|
||||
{#if c}
|
||||
<p class="mt-2 text-sm text-gray-400">Email: {c.email ?? '-'} · CUIT: {c.cuit ?? '-'}</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Almacén</h2>
|
||||
<Select labelText="Almacén de origen" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Descuento</h2>
|
||||
<Select labelText="Descuento" bind:selected={descuentoId}>
|
||||
<SelectItem value={0} text="Sin descuento" />
|
||||
{#each descuentos as d (d.ID)}
|
||||
<SelectItem value={d.ID} text={`${d.Nombre} (${d.Tipo === 'PORCENTAJE' ? d.Valor + '%' : '$' + d.Valor})`} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" bind:checked={enviarEmail} />
|
||||
<span>Enviar comprobante por email al cliente</span>
|
||||
</label>
|
||||
<div class="mt-3">
|
||||
<TextInput labelText="Observación" bind:value={observacion} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="rounded border p-4">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold">Ítems de la Venta</h2>
|
||||
<Button size="small" icon={Add} onclick={agregarItem}>Agregar Ítem</Button>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
{#each items as it, i (i)}
|
||||
<div class="grid grid-cols-12 items-end gap-2">
|
||||
<div class="col-span-5">
|
||||
<Select labelText="Producto" bind:selected={it.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
<div class="col-span-2">
|
||||
<NumberInput labelText="Cantidad" bind:value={it.cantidad} min={0} step={1} />
|
||||
</div>
|
||||
<div class="col-span-3">
|
||||
<NumberInput labelText="Precio Unit." bind:value={it.precioUnitario} min={0} step={0.01} />
|
||||
</div>
|
||||
<div class="col-span-1 text-right text-sm">
|
||||
{(it.cantidad * (it.precioUnitario || 0)).toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}
|
||||
</div>
|
||||
<div class="col-span-1">
|
||||
<Button kind="danger-ghost" size="small" icon={TrashCan} onclick={() => quitarItem(i)} />
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<h2 class="mb-3 text-lg font-semibold">Totales</h2>
|
||||
<div class="space-y-1 text-sm">
|
||||
<div class="flex justify-between"><span>Subtotal</span><span>{subtotal.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between"><span>Descuento</span><span>{descuentoTotal.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between"><span>IVA (21%)</span><span>{impuestos.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
<div class="flex justify-between text-lg font-bold"><span>Total</span><span>{total.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' })}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded border p-4">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" bind:checked={registrarPago} />
|
||||
<span>Registrar pago inmediato</span>
|
||||
</label>
|
||||
{#if registrarPago}
|
||||
<div class="mt-3 grid grid-cols-2 gap-3">
|
||||
<Select labelText="Forma de pago" bind:selected={pagoFormaId}>
|
||||
<SelectItem value={0} text="Seleccioná" />
|
||||
{#each formasPago as f (f.ID)}
|
||||
<SelectItem value={f.ID} text={f.descripcion ?? f.Descripcion} />
|
||||
{/each}
|
||||
</Select>
|
||||
<NumberInput labelText="Importe" bind:value={pagoImporte} min={0} step={0.01} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button kind="secondary" onclick={() => goto('/facturas')}>Cancelar</Button>
|
||||
<Button onclick={enviar} disabled={enviando}>
|
||||
{enviando ? 'Registrando...' : 'Registrar Venta'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,28 @@
|
||||
import { obtenerFacturas } from '$lib/hooks/facturas/obtenerFacturas';
|
||||
import { obtenerClientes } from '$lib/hooks/clientes/obtenerClientes';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerDescuentos } from '$lib/hooks/facturas/obtenerDescuentos';
|
||||
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends }) {
|
||||
depends('facturas:nueva:load');
|
||||
const [clientes, repuestos, almacenes, descuentos, formasPago] = await Promise.all([
|
||||
obtenerClientes(fetch),
|
||||
obtenerRepuestos(fetch),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerDescuentos(fetch),
|
||||
obtenerFormasPago(fetch)
|
||||
]);
|
||||
return {
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
repuestos: Array.isArray(repuestos) ? repuestos : [],
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
descuentos: Array.isArray(descuentos) ? descuentos : [],
|
||||
formasPago: Array.isArray(formasPago) ? formasPago : [],
|
||||
errorClientes: typeof clientes === 'string' ? clientes : '',
|
||||
errorRepuestos: typeof repuestos === 'string' ? repuestos : ''
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user