correjida ui

Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
fede committed 2026-11-30 18:28:43 -03:00
1 parent 12276acbd8
commit bc0db6dbee
2 files changed
+249 -137

No files matched your search

+188 -137
View File
@@ -3,16 +3,16 @@
import {
Button,
InlineNotification,
Modal,
NumberInput,
Select,
SelectItem,
TextInput,
DataTable
} from 'carbon-components-svelte';
import { Add, TrashCan, ArrowLeft } from 'carbon-icons-svelte';
import { Add, TrashCan, ArrowLeft, Search } from 'carbon-icons-svelte';
import { goto, invalidate } from '$app/navigation';
import { crearFactura } from '$lib/hooks/facturas/crearFactura';
import ModalBuscarCliente from './ModalBuscarCliente.svelte';
import type { Cliente, Repuesto, Almacen } from '../../../types';
let { data } = $props();
@@ -20,6 +20,10 @@
let error = $state('');
let enviando = $state(false);
// Aviso de stock bajo: solo se muestra cuando hay datos reales que lo justifiquen.
let hayStockBajo = $state(false);
let cantidadStockBajo = $state(0);
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 : []);
@@ -33,26 +37,39 @@
let observacion = $state('');
interface Item {
id: number;
repuestoId: number;
cantidad: number;
}
let items = $state<Item[]>([{ repuestoId: 0, cantidad: 1 }]);
let nextItemId = $state(1);
let items = $state<Item[]>([{ id: 0, repuestoId: 0, cantidad: 1 }]);
let pagoImporte = $state<number>(0);
let pagoFormaId = $state<number>(0);
let registrarPago = $state(false);
let modalClienteAbierto = $state(false);
let clienteSeleccionado = $derived(clientes.find((c) => c.ID === clienteId));
const itemHeaders = [
{ key: 'producto', value: 'Producto', empty: false },
{ key: 'cantidad', value: 'Cantidad', empty: false },
{ key: 'precioUnitario', value: 'Precio Unit.', empty: false },
{ key: 'subtotal', value: 'Subtotal', empty: false },
{ key: 'acciones', value: '', empty: false }
];
function agregarItem() {
items = [...items, { repuestoId: 0, cantidad: 1 }];
items = [...items, { id: nextItemId++, repuestoId: 0, cantidad: 1 }];
}
function quitarItem(i: number) {
items = items.filter((_, idx) => idx !== i);
if (items.length === 0) items = [{ repuestoId: 0, cantidad: 1 }];
function quitarItem(id: number) {
items = items.filter((it) => it.id !== id);
if (items.length === 0) items = [{ id: 0, repuestoId: 0, cantidad: 1 }];
nextItemId = Math.max(...items.map((it) => it.id)) + 1;
}
// El precio siempre sale del catálogo; el usuario sólo elige el repuesto
// y la cantidad.
function precioRepuesto(id: number): number {
const r = repuestos.find((x) => x.ID === id);
return r ? r.precio : 0;
@@ -80,11 +97,24 @@
let impuestos = $derived(baseImponible * 0.21);
let total = $derived(baseImponible + impuestos);
async function enviar() {
function onSeleccionarCliente(id: number) {
clienteId = id;
modalClienteAbierto = false;
}
function clienteDefault() {
const d = clientes.find((c) => c.ID === 40);
if (d) clienteId = d.ID;
else if (clientes.length > 0) clienteId = clientes[0].ID;
}
async function enviar(conPago = false) {
if (enviando) return;
enviando = true;
error = '';
if (conPago) registrarPago = true;
if (!clienteId) {
error = 'Seleccioná un cliente.';
enviando = false;
@@ -101,6 +131,11 @@
enviando = false;
return;
}
if (registrarPago && pagoImporte <= 0) {
error = 'Ingresá el importe del pago.';
enviando = false;
return;
}
const payload = {
clienteId,
@@ -142,148 +177,164 @@
<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 class="w-full space-y-4 px-4 md:px-6">
<!-- Aviso stock bajo: solo se muestra cuando hay productos con stock por debajo del umbral -->
{#if hayStockBajo}
<div class="rounded border border-yellow-300 bg-yellow-50 p-3 text-sm text-yellow-800">
⚠ Aviso: {cantidadStockBajo} producto(s) con stock por debajo del umbral mínimo
</div>
{/if}
<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}
<!-- Datos del Cliente -->
<div class="rounded border p-4">
<h2 class="mb-3 text-lg font-semibold">Datos del Cliente</h2>
<div class="space-y-4">
<div>
<span class="mt-2! block text-sm font-medium">Cliente</span>
<div class="flex flex-wrap items-center gap-2">
<TextInput
hideLabel
readonly
placeholder="Sin cliente seleccionado"
value={clienteSeleccionado ? `${clienteSeleccionado.nombre} (${clienteSeleccionado.cuit ?? ''})` : ''}
class="min-w-64 flex-1 border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
/>
{/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})`}
<Button size="small" icon={Search} onclick={() => (modalClienteAbierto = true)}>Buscar Cliente</Button>
<Button size="small" kind="secondary" onclick={clienteDefault}>Cliente Default</Button>
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<span class="mt-2! block text-sm font-medium">Email</span>
<TextInput
hideLabel
readonly
value={clienteSeleccionado?.email ?? '-'}
class="border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
/>
{/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>
<span class="mt-2! block text-sm font-medium">CUIT</span>
<TextInput
hideLabel
readonly
value={clienteSeleccionado?.cuit ?? '-'}
class="border-none focus:ring-0 focus:border-transparent bg-transparent px-3 py-2 text-sm"
/>
</div>
</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">
<TextInput
labelText="Precio Unit. (catálogo)"
value={formatMonto(precioRepuesto(it.repuestoId))}
readonly
/>
</div>
<div class="col-span-1 text-right text-sm">
{formatMonto(it.cantidad * precioRepuesto(it.repuestoId))}
</div>
<div class="col-span-1">
<Button
kind="danger-ghost"
size="small"
icon={TrashCan}
onclick={() => quitarItem(i)}
/>
</div>
</div>
{/each}
</div>
</div>
<!-- Almacén -->
<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">Totales</h2>
<div class="space-y-1 text-sm">
<div class="flex justify-between">
<span>Subtotal</span><span>{formatMonto(subtotal)}</span>
</div>
<div class="flex justify-between">
<span>Descuento</span><span>{formatMonto(descuentoTotal)}</span>
</div>
<div class="flex justify-between">
<span>IVA (21%)</span><span>{formatMonto(impuestos)}</span>
</div>
<div class="flex justify-between text-lg font-bold">
<span>Total</span><span>{formatMonto(total)}</span>
<!-- Ítems -->
<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="overflow-x-auto">
<DataTable headers={itemHeaders as any} rows={items} size="compact">
<svelte:fragment slot="cell" let:row let:cell>
{#if cell.key === 'producto'}
<Select hideLabel bind:selected={row.repuestoId} class="w-full">
<SelectItem value={0} text="Seleccioná" />
{#each repuestos as r (r.ID)}
<SelectItem value={r.ID} text={r.nombre} />
{/each}
</Select>
{:else if cell.key === 'cantidad'}
<NumberInput hideLabel bind:value={row.cantidad} min={0} step={1} class="w-full" />
{:else if cell.key === 'precioUnitario'}
<TextInput hideLabel readonly value={formatMonto(precioRepuesto(row.repuestoId))} class="w-full text-right" />
{:else if cell.key === 'subtotal'}
<TextInput hideLabel readonly value={formatMonto(row.cantidad * precioRepuesto(row.repuestoId))} class="w-full text-right" />
{:else if cell.key === 'acciones'}
<Button kind="danger-ghost" size="small" icon={TrashCan} onclick={() => quitarItem(row.id)} />
{/if}
</svelte:fragment>
</DataTable>
</div>
</div>
<!-- Descuento + Total -->
<div class="rounded border p-4">
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div>
<span class="mb-2! block text-sm font-medium">Descuento</span>
<Select hideLabel 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="flex flex-col justify-end">
<div class="space-y-1 text-sm">
<div class="flex justify-between"><span>Subtotal</span><span>{formatMonto(subtotal)}</span></div>
<div class="flex justify-between"><span>Descuento</span><span>{formatMonto(descuentoTotal)}</span></div>
<div class="flex justify-between"><span>IVA (21%)</span><span>{formatMonto(impuestos)}</span></div>
<div class="flex justify-between text-lg font-bold"><span>Total</span><span>{formatMonto(total)}</span></div>
</div>
</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}
<!-- Email + Observación -->
<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 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>
<!-- Pago -->
<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 pt-2">
<Button kind="secondary" onclick={() => goto('/facturas')}>Cancelar</Button>
<Button onclick={() => enviar(false)} disabled={enviando}>
{enviando ? 'Registrando...' : 'Registrar Venta'}
</Button>
<Button onclick={() => enviar(true)} disabled={enviando}>
{enviando ? 'Registrando...' : 'Registrar Venta y Pago'}
</Button>
</div>
</div>
</div>
<!-- Modal Buscar Cliente -->
<ModalBuscarCliente
bind:open={modalClienteAbierto}
{clientes}
onSeleccionar={onSeleccionarCliente}
/>
@@ -0,0 +1,61 @@
<script lang="ts">
import { Modal, TextInput, DataTable, Button } from 'carbon-components-svelte';
import type { Cliente } from '../../../types';
let { open = false, clientes = [], onSeleccionar }: {
open?: boolean;
clientes?: Cliente[];
onSeleccionar?: (id: number) => void;
} = $props();
let filtroCliente = $state('');
let clientesFiltrados = $derived(
clientes
.filter((c) => {
const q = filtroCliente.trim().toLowerCase();
if (!q) return true;
return (
c.nombre.toLowerCase().includes(q) ||
(c.cuit ?? '').toLowerCase().includes(q) ||
(c.email ?? '').toLowerCase().includes(q)
);
})
// DataTable requiere que cada fila tenga una propiedad 'id' única.
.map((c) => ({ ...c, id: c.ID }))
);
const clienteHeaders = [
{ key: 'nombre', value: 'Nombre', empty: false },
{ key: 'cuit', value: 'CUIT', empty: false },
{ key: 'email', value: 'Email', empty: false },
{ key: 'acciones', value: '', empty: false }
];
function seleccionarCliente(id: number) {
onSeleccionar?.(id);
}
</script>
<Modal bind:open={open} modalHeading="Buscar Cliente" primaryButtonText="Cerrar">
<div class="space-y-3">
<p class="text-sm text-gray-600">Buscá un cliente por nombre, CUIT o email.</p>
<TextInput labelText="Nombre / CUIT / Email" bind:value={filtroCliente} />
<div class="max-h-64 overflow-y-auto">
{#if clientesFiltrados.length > 0}
<DataTable headers={clienteHeaders as any} rows={clientesFiltrados} size="compact">
<svelte:fragment slot="cell" let:row let:cell>
{#if cell.key === 'acciones'}
<Button size="small" onclick={() => seleccionarCliente(row.ID)}>Seleccionar</Button>
{:else}
{cell.value}
{/if}
</svelte:fragment>
</DataTable>
{:else}
<p class="text-sm text-gray-500">No se encontraron clientes.</p>
{/if}
</div>
<p class="text-xs text-gray-500">Condición: para enviar el comprobante por email, el cliente debe estar validado y con email registrado.</p>
</div>
</Modal>