Private
Public Access
falta testeo
This commit is contained in:
1 parent
9205fea8d8
commit
61ca620c8e
50 files changed
+3061
-1112
No files matched your search
@@ -9,3 +9,14 @@
|
||||
font-size: 1.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* En los temas oscuros el icono nativo del calendario es negro y se pierde.
|
||||
Le damos un fondo claro para que quede visible. */
|
||||
[theme='g80'] input[type='date']::-webkit-calendar-picker-indicator,
|
||||
[theme='g90'] input[type='date']::-webkit-calendar-picker-indicator,
|
||||
[theme='g100'] input[type='date']::-webkit-calendar-picker-indicator {
|
||||
background-color: #fff;
|
||||
border-radius: 2px;
|
||||
cursor: pointer;
|
||||
opacity: 1;
|
||||
}
|
||||
@@ -61,8 +61,8 @@
|
||||
datePickerType="range"
|
||||
on:change={(e) => {
|
||||
const dates = e.detail as { selectedDates: Date[] };
|
||||
filtros.fechaInicio = dates.selectedDates[0] ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1] ?? '';
|
||||
filtros.fechaInicio = dates.selectedDates[0]?.toISOString().slice(0, 10) ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1]?.toISOString().slice(0, 10) ?? '';
|
||||
}}
|
||||
>
|
||||
<DatePickerInput labelText="Fecha inicio" placeholder="mm/dd/yyyy" />
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
DataTableSkeleton,
|
||||
InlineNotification,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import { InventoryManagement, Play, Return } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import ModalStructured from '$lib/components/ModalStructured.svelte';
|
||||
import FiltrosStock from './FiltrosStock.svelte';
|
||||
import TablaStock from './TablaStock.svelte';
|
||||
import TrasladarStockForm from './TrasladarStockForm.svelte';
|
||||
import AjustarStockForm from './AjustarStockForm.svelte';
|
||||
import ReservarStockForm from './ReservarStockForm.svelte';
|
||||
import ComentarStockForm from './ComentarStockForm.svelte';
|
||||
import IngresarStockForm from './IngresarStockForm.svelte';
|
||||
import DevolucionStockForm from './DevolucionStockForm.svelte';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import { liberarReserva } from '$lib/hooks/stock/liberarReserva';
|
||||
import type { Almacen, Cliente, ReservaStock, StockItem } from '../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
|
||||
$effect(() => {
|
||||
if (data.error) error = data.error;
|
||||
});
|
||||
|
||||
let stock = $derived<StockItem[]>(Array.isArray(data.stock) ? data.stock : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let clientes = $derived<Cliente[]>(Array.isArray(data.clientes) ? data.clientes : []);
|
||||
let reservas = $derived<ReservaStock[]>(Array.isArray(data.reservas) ? data.reservas : []);
|
||||
let filtros = $derived(data.filtros ?? { q: '', almacenId: 0, estado: '' });
|
||||
let cargando = $derived(data.stock === undefined || data.stock === null);
|
||||
|
||||
const headers = [
|
||||
{ key: 'repuesto', value: 'Repuesto' },
|
||||
{ key: 'descripcion', value: 'Descripción' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cantidad' },
|
||||
{ key: 'reservada', value: 'Reservado' },
|
||||
{ key: 'disponible', value: 'Disponible' },
|
||||
{ key: 'observacion', value: 'Observación' },
|
||||
{ key: 'estado', value: 'Estado' }
|
||||
];
|
||||
|
||||
let openIngreso = $state(false);
|
||||
let openDevolucion = $state(false);
|
||||
let openInfo = $state(false);
|
||||
let openTraslado = $state(false);
|
||||
let openAjuste = $state(false);
|
||||
let openReserva = $state(false);
|
||||
let openComentario = $state(false);
|
||||
|
||||
let stockTraslado = $state<StockItem | null>(null);
|
||||
let stockAjuste = $state<StockItem | null>(null);
|
||||
let stockReserva = $state<StockItem | null>(null);
|
||||
let stockComentario = $state<StockItem | null>(null);
|
||||
let stockInfo = $state<Record<string, unknown> | null>(null);
|
||||
|
||||
function buscar(f: { q: string; almacenId: number; estado: string }) {
|
||||
const params = new URLSearchParams();
|
||||
if (f.q) params.set('q', f.q);
|
||||
if (f.almacenId) params.set('almacenId', String(f.almacenId));
|
||||
if (f.estado) params.set('estado', f.estado);
|
||||
const query = params.toString();
|
||||
void goto(`/stock${query ? `?${query}` : ''}`, { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function limpiarFiltros() {
|
||||
void goto('/stock', { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function verRegistro(s: StockItem) {
|
||||
stockInfo = {
|
||||
Repuesto: s.repuesto?.nombre ?? s.repuestoId,
|
||||
Descripción: s.repuesto?.descripcion || '-',
|
||||
Almacén: s.almacen?.codigo ?? s.almacenId,
|
||||
Cantidad: formatearCantidad(s.cantidad),
|
||||
Reservado: formatearCantidad(s.cantidadReservada),
|
||||
Disponible: formatearCantidad(s.cantidad - s.cantidadReservada),
|
||||
Observación: s.observacion || '-'
|
||||
};
|
||||
openInfo = true;
|
||||
}
|
||||
|
||||
async function liberar(r: ReservaStock) {
|
||||
const res = await liberarReserva(r.ID);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
return;
|
||||
}
|
||||
await invalidate('stock:load');
|
||||
}
|
||||
|
||||
function fecha(v?: string) {
|
||||
if (!v) return '-';
|
||||
const d = new Date(v);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex justify-between">
|
||||
<h1 class="page-title">Gestión de Stock</h1>
|
||||
<div class="flex flex-wrap justify-end gap-2">
|
||||
<Button icon={InventoryManagement} onclick={() => (openIngreso = true)}>
|
||||
Registrar Ingreso
|
||||
</Button>
|
||||
<Button kind="tertiary" icon={Return} onclick={() => (openDevolucion = true)}>
|
||||
Registrar Devolución
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FiltrosStock {almacenes} valores={filtros} onBuscar={buscar} onLimpiar={limpiarFiltros} />
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if cargando}
|
||||
<DataTableSkeleton {headers} rows={5} size="compact" showHeader={false} showToolbar={false} />
|
||||
{:else}
|
||||
<TablaStock
|
||||
{stock}
|
||||
onTrasladar={(s) => {
|
||||
stockTraslado = s;
|
||||
openTraslado = true;
|
||||
}}
|
||||
onAjustar={(s) => {
|
||||
stockAjuste = s;
|
||||
openAjuste = true;
|
||||
}}
|
||||
onReservar={(s) => {
|
||||
stockReserva = s;
|
||||
openReserva = true;
|
||||
}}
|
||||
onComentar={(s) => {
|
||||
stockComentario = s;
|
||||
openComentario = true;
|
||||
}}
|
||||
onVer={verRegistro}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if data.reservasError}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Reservas"
|
||||
subtitle={data.reservasError}
|
||||
hideCloseButton
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if !cargando}
|
||||
<TableContainer title="Reservas activas">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Repuesto</TableHeader>
|
||||
<TableHeader>Almacén</TableHeader>
|
||||
<TableHeader>Cantidad</TableHeader>
|
||||
<TableHeader>Cliente</TableHeader>
|
||||
<TableHeader>Vencimiento</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if reservas.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={6}>No hay reservas activas.</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each reservas as r (r.ID)}
|
||||
<TableRow>
|
||||
<TableCell>{r.repuesto?.nombre ?? r.repuesto_id}</TableCell>
|
||||
<TableCell>{r.almacen?.codigo ?? r.almacen_id}</TableCell>
|
||||
<TableCell>{formatearCantidad(r.cantidad)}</TableCell>
|
||||
<TableCell>{r.cliente?.nombre ?? '-'}</TableCell>
|
||||
<TableCell>{fecha(r.fecha_vencimiento)}</TableCell>
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Play} onclick={() => liberar(r)}>
|
||||
Liberar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<IngresarStockForm bind:open={openIngreso} {almacenes} onClose={() => (openIngreso = false)} />
|
||||
|
||||
<DevolucionStockForm
|
||||
bind:open={openDevolucion}
|
||||
{almacenes}
|
||||
onClose={() => (openDevolucion = false)}
|
||||
/>
|
||||
|
||||
<TrasladarStockForm
|
||||
bind:open={openTraslado}
|
||||
stock={stockTraslado}
|
||||
{almacenes}
|
||||
onClose={() => {
|
||||
openTraslado = false;
|
||||
stockTraslado = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<AjustarStockForm
|
||||
bind:open={openAjuste}
|
||||
stock={stockAjuste}
|
||||
onClose={() => {
|
||||
openAjuste = false;
|
||||
stockAjuste = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ReservarStockForm
|
||||
bind:open={openReserva}
|
||||
stock={stockReserva}
|
||||
{clientes}
|
||||
onClose={() => {
|
||||
openReserva = false;
|
||||
stockReserva = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ComentarStockForm
|
||||
bind:open={openComentario}
|
||||
stock={stockComentario}
|
||||
onClose={() => {
|
||||
openComentario = false;
|
||||
stockComentario = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ModalStructured objeto={stockInfo} bind:open={openInfo} />
|
||||
@@ -0,0 +1,34 @@
|
||||
import { obtenerStock } from '$lib/hooks/stock/obtenerStock';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerClientes } from '$lib/hooks/clientes/obtenerClientes';
|
||||
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends, url }) {
|
||||
depends('stock:load');
|
||||
|
||||
const almacenParam = url.searchParams.get('almacenId');
|
||||
const filtros = {
|
||||
q: url.searchParams.get('q') ?? '',
|
||||
almacenId: almacenParam ? Number(almacenParam) || undefined : undefined,
|
||||
estado: url.searchParams.get('estado') ?? ''
|
||||
};
|
||||
|
||||
const [stock, almacenes, clientes, reservas] = await Promise.all([
|
||||
obtenerStock(fetch, filtros),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerClientes(fetch),
|
||||
obtenerReservas(fetch)
|
||||
]);
|
||||
|
||||
return {
|
||||
stock,
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
reservas: Array.isArray(reservas) ? reservas : [],
|
||||
reservasError: typeof reservas === 'string' ? reservas : '',
|
||||
error: typeof stock === 'string' ? stock : '',
|
||||
filtros
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<script lang="ts">
|
||||
import { Modal, NumberInput, TextInput, InlineNotification } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { ajustarStock } from '$lib/hooks/stock/ajustarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
} = $props();
|
||||
|
||||
let cantidadReal = $state(0);
|
||||
let motivo = $state('');
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const actual = $derived(stock?.cantidad ?? 0);
|
||||
const reservada = $derived(stock?.cantidadReservada ?? 0);
|
||||
const diferencia = $derived(cantidadReal - actual);
|
||||
const bajoMinimo = $derived(
|
||||
cantidadReal < (stock?.repuesto?.stockMinimo ?? 0) && (stock?.repuesto?.stockMinimo ?? 0) > 0
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
cantidadReal = stock?.cantidad ?? 0;
|
||||
motivo = '';
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (cantidadReal < 0) {
|
||||
error = 'La cantidad real no puede ser negativa.';
|
||||
} else if (!motivo.trim()) {
|
||||
error = 'Ingresá el motivo del ajuste.';
|
||||
} else if (cantidadReal < reservada) {
|
||||
error = `La cantidad no puede quedar por debajo de lo reservado (${formatearCantidad(reservada)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await ajustarStock({
|
||||
stockId: stock.id,
|
||||
cantidadReal,
|
||||
motivo,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="ajustarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="ajustarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Ajustar stock"
|
||||
primaryButtonText="Guardar ajuste"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Stock actual</p>
|
||||
<p class="font-semibold">{formatearCantidad(actual)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Reservado</p>
|
||||
<p class="font-semibold">{formatearCantidad(reservada)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NumberInput
|
||||
labelText="Nuevo stock (cantidad real)"
|
||||
bind:value={cantidadReal}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<p class="mt-2 text-sm text-gray-400">
|
||||
Diferencia: <span class="font-semibold"
|
||||
>{diferencia > 0 ? '+' : ''}{formatearCantidad(diferencia)}</span
|
||||
>
|
||||
</p>
|
||||
|
||||
{#if bajoMinimo}
|
||||
<div class="mt-4">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Stock bajo mínimo"
|
||||
subtitle="El nuevo stock queda por debajo del mínimo configurado para el repuesto."
|
||||
hideCloseButton
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Motivo" bind:value={motivo} maxlength={60} required />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
import { InlineNotification, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { comentarStock } from '$lib/hooks/stock/comentarStock';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
} = $props();
|
||||
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
observacion = stock?.observacion ?? '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const texto = observacion.trim();
|
||||
if (texto.length > 60) {
|
||||
error = 'La observación no puede superar los 60 caracteres.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await comentarStock(stock.id, texto);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="comentarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="comentarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar observación"
|
||||
primaryButtonText="Guardar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4">
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
labelText="Observación"
|
||||
bind:value={observacion}
|
||||
maxlength={60}
|
||||
placeholder="Máximo 60 caracteres"
|
||||
helperText="Dejá el campo vacío para quitar la observación."
|
||||
/>
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,211 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan } from 'carbon-icons-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { registrarDevolucion } from '$lib/hooks/stock/registrarDevolucion';
|
||||
import { obtenerFacturas } from '$lib/hooks/facturas/obtenerFacturas';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import type { Almacen, FacturaResumen, Repuesto } from '../../types';
|
||||
|
||||
interface ItemDevolucion {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let facturas = $state<FacturaResumen[]>([]);
|
||||
let repuestos = $state<Repuesto[]>([]);
|
||||
let cargandoCatalogos = $state(false);
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let facturaId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
let motivo = $state('');
|
||||
let items = $state<ItemDevolucion[]>([]);
|
||||
|
||||
function itemVacio(): ItemDevolucion {
|
||||
return { repuestoId: 0, cantidad: 0, precioUnitario: 0 };
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
facturaId = 0;
|
||||
almacenId = almacenes[0]?.id ?? 0;
|
||||
motivo = '';
|
||||
items = [itemVacio()];
|
||||
error = '';
|
||||
enviando = false;
|
||||
|
||||
let cancelado = false;
|
||||
cargandoCatalogos = true;
|
||||
(async () => {
|
||||
const [f, r] = await Promise.all([obtenerFacturas(), obtenerRepuestos()]);
|
||||
if (cancelado) return;
|
||||
facturas = Array.isArray(f) ? f : [];
|
||||
repuestos = Array.isArray(r) ? r : [];
|
||||
cargandoCatalogos = false;
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidad > 0);
|
||||
|
||||
if (!facturaId) {
|
||||
error = 'Seleccioná la factura de origen.';
|
||||
} else if (!motivo.trim()) {
|
||||
error = 'Ingresá el motivo de la devolución.';
|
||||
} else if (itemsValidos.length === 0) {
|
||||
error = 'Agregá al menos un ítem con repuesto y cantidad.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await registrarDevolucion({
|
||||
facturaId,
|
||||
almacenId: almacenId || undefined,
|
||||
motivo: motivo.trim(),
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidad: i.cantidad,
|
||||
precioUnitario: i.precioUnitario
|
||||
}))
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="devolucionStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="devolucionStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar devolución"
|
||||
primaryButtonText="Confirmar devolución"
|
||||
primaryButtonDisabled={enviando || cargandoCatalogos}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Select labelText="Factura" bind:selected={facturaId}>
|
||||
<SelectItem value={0} text="Seleccioná una factura" />
|
||||
{#each facturas as f (f.ID)}
|
||||
<SelectItem
|
||||
value={f.ID}
|
||||
text={`${f.numero ? `#${f.numero}` : `Factura ${f.ID}`}${f.cliente?.nombre ? ` · ${f.cliente.nombre}` : ''}`}
|
||||
/>
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Almacén de destino" 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="mt-4">
|
||||
<TextInput labelText="Motivo" bind:value={motivo} maxlength={60} />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex items-center justify-between">
|
||||
<p class="text-base font-semibold">Ítems devueltos</p>
|
||||
<Button kind="ghost" size="small" icon={Add} onclick={() => (items = [...items, itemVacio()])}
|
||||
>Agregar ítem</Button
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-col gap-4">
|
||||
{#each items as item, i (i)}
|
||||
<div class="rounded border border-gray-700 p-3">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="text-sm font-semibold">Ítem {i + 1}</p>
|
||||
{#if items.length > 1}
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => (items = items.filter((_, idx) => idx !== i))}>Quitar</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<Select labelText="Repuesto" bind:selected={item.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná un repuesto" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad"
|
||||
bind:value={item.cantidad}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
labelText="Precio unitario"
|
||||
bind:value={item.precioUnitario}
|
||||
min={0}
|
||||
step={0.01}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { Tag } from 'carbon-components-svelte';
|
||||
|
||||
let { cantidad = 0, reservada = 0, minimo = 0 } = $props();
|
||||
|
||||
const estado = $derived(
|
||||
cantidad <= 0 ? 'AGOTADO' : minimo > 0 && cantidad < minimo ? 'BAJO' : 'OK'
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if estado === 'AGOTADO'}
|
||||
<Tag type="red">Agotado</Tag>
|
||||
{:else if estado === 'BAJO'}
|
||||
<Tag type="magenta">Bajo mínimo</Tag>
|
||||
{:else}
|
||||
<Tag type="green">OK</Tag>
|
||||
{/if}
|
||||
@@ -0,0 +1,62 @@
|
||||
<script lang="ts">
|
||||
import { Button, Select, SelectItem, TextInput } from 'carbon-components-svelte';
|
||||
import { Close, Search } from 'carbon-icons-svelte';
|
||||
import type { Almacen } from '../../types';
|
||||
|
||||
let {
|
||||
almacenes = [],
|
||||
valores = { q: '', almacenId: 0, estado: '' },
|
||||
onBuscar,
|
||||
onLimpiar
|
||||
}: {
|
||||
almacenes?: Almacen[];
|
||||
valores?: { q?: string; almacenId?: number; estado?: string };
|
||||
onBuscar?: (filtros: { q: string; almacenId: number; estado: string }) => void;
|
||||
onLimpiar?: () => void;
|
||||
} = $props();
|
||||
|
||||
let q = $state('');
|
||||
let almacenId = $state<number>(0);
|
||||
let estado = $state('');
|
||||
|
||||
$effect(() => {
|
||||
q = valores.q ?? '';
|
||||
almacenId = valores.almacenId ?? 0;
|
||||
estado = valores.estado ?? '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<form
|
||||
class="mb-6 flex flex-wrap items-end gap-4"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onBuscar?.({ q, almacenId: Number(almacenId) || 0, estado });
|
||||
}}
|
||||
>
|
||||
<div class="min-w-60 flex-1">
|
||||
<TextInput
|
||||
labelText="Buscar repuesto"
|
||||
placeholder="Nombre, descripción o código"
|
||||
bind:value={q}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Select labelText="Almacén" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Todos los almacenes" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Estado" bind:selected={estado}>
|
||||
<SelectItem value="" text="Todos" />
|
||||
<SelectItem value="NORMAL" text="OK" />
|
||||
<SelectItem value="BAJO_MINIMO" text="Bajo mínimo" />
|
||||
<SelectItem value="AGOTADO" text="Agotado" />
|
||||
</Select>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Button type="submit" icon={Search}>Buscar</Button>
|
||||
<Button kind="ghost" icon={Close} onclick={() => onLimpiar?.()}>Limpiar</Button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,250 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan } from 'carbon-icons-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { ingresarStock } from '$lib/hooks/stock/ingresarStock';
|
||||
import { obtenerProveedores } from '$lib/hooks/proveedores/obtenerProveedores';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import type { Almacen, Proveedor, Repuesto } from '../../types';
|
||||
|
||||
interface ItemIngreso {
|
||||
repuestoId: number;
|
||||
cantidadEsperada: number;
|
||||
cantidadRecibida: number;
|
||||
unidadMedida: string;
|
||||
observacion: string;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let proveedores = $state<Proveedor[]>([]);
|
||||
let repuestos = $state<Repuesto[]>([]);
|
||||
let cargandoCatalogos = $state(false);
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let proveedorId = $state<number>(0);
|
||||
let numero = $state('');
|
||||
let fechaEmision = $state(new Date().toISOString().slice(0, 10));
|
||||
let almacenDestinoId = $state<number>(0);
|
||||
let observacion = $state('');
|
||||
let items = $state<ItemIngreso[]>([]);
|
||||
|
||||
function itemVacio(): ItemIngreso {
|
||||
return {
|
||||
repuestoId: 0,
|
||||
cantidadEsperada: 0,
|
||||
cantidadRecibida: 0,
|
||||
unidadMedida: 'Unidad',
|
||||
observacion: ''
|
||||
};
|
||||
}
|
||||
|
||||
const diferencias = $derived(
|
||||
items.filter((i) => i.cantidadEsperada !== i.cantidadRecibida).length
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
// Reiniciar formulario al abrir.
|
||||
proveedorId = 0;
|
||||
numero = '';
|
||||
fechaEmision = new Date().toISOString().slice(0, 10);
|
||||
almacenDestinoId = almacenes[0]?.id ?? 0;
|
||||
observacion = '';
|
||||
items = [itemVacio()];
|
||||
error = '';
|
||||
enviando = false;
|
||||
|
||||
let cancelado = false;
|
||||
cargandoCatalogos = true;
|
||||
(async () => {
|
||||
const [p, r] = await Promise.all([obtenerProveedores(), obtenerRepuestos()]);
|
||||
if (cancelado) return;
|
||||
proveedores = Array.isArray(p) ? p : [];
|
||||
repuestos = Array.isArray(r) ? r : [];
|
||||
cargandoCatalogos = false;
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidadRecibida > 0);
|
||||
|
||||
if (!proveedorId) {
|
||||
error = 'Seleccioná un proveedor.';
|
||||
} else if (!numero.trim()) {
|
||||
error = 'Ingresá el número de remito.';
|
||||
} else if (!fechaEmision) {
|
||||
error = 'Ingresá la fecha de emisión.';
|
||||
} else if (!almacenDestinoId) {
|
||||
error = 'Seleccioná el almacén destino.';
|
||||
} else if (itemsValidos.length === 0) {
|
||||
error = 'Agregá al menos un ítem con repuesto y cantidad recibida.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await ingresarStock({
|
||||
proveedorId,
|
||||
numero: numero.trim(),
|
||||
fechaEmision: `${fechaEmision}T00:00:00Z`,
|
||||
almacenDestinoId,
|
||||
observacion,
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidadEsperada: i.cantidadEsperada,
|
||||
cantidadRecibida: i.cantidadRecibida,
|
||||
unidadMedida: i.unidadMedida || 'Unidad',
|
||||
observacion: i.observacion
|
||||
}))
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="ingresarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="ingresarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar ingreso de stock"
|
||||
primaryButtonText="Confirmar ingreso"
|
||||
primaryButtonDisabled={enviando || cargandoCatalogos}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Select labelText="Proveedor" bind:selected={proveedorId}>
|
||||
<SelectItem value={0} text="Seleccioná un proveedor" />
|
||||
{#each proveedores as p (p.ID)}
|
||||
<SelectItem value={p.ID} text={p.cuit ? `${p.nombre} · ${p.cuit}` : p.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Almacén destino" bind:selected={almacenDestinoId}>
|
||||
<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>
|
||||
|
||||
<TextInput labelText="N° de remito" bind:value={numero} maxlength={30} />
|
||||
|
||||
<TextInput labelText="Fecha de emisión" type="date" bind:value={fechaEmision} />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex items-center justify-between">
|
||||
<p class="text-base font-semibold">Ítems del remito</p>
|
||||
<Button kind="ghost" size="small" icon={Add} onclick={() => (items = [...items, itemVacio()])}
|
||||
>Agregar ítem</Button
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if diferencias > 0}
|
||||
<div class="mt-3">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Hay diferencias"
|
||||
subtitle={`${diferencias} ítem(s) con cantidad recibida distinta de la esperada.`}
|
||||
hideCloseButton
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-3 flex flex-col gap-4">
|
||||
{#each items as item, i (i)}
|
||||
<div class="rounded border border-gray-700 p-3">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="text-sm font-semibold">Ítem {i + 1}</p>
|
||||
{#if items.length > 1}
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => (items = items.filter((_, idx) => idx !== i))}>Quitar</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<Select labelText="Repuesto" bind:selected={item.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná un repuesto" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<TextInput labelText="Unidad de medida" bind:value={item.unidadMedida} maxlength={20} />
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad esperada"
|
||||
bind:value={item.cantidadEsperada}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad recibida"
|
||||
bind:value={item.cantidadRecibida}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { reservarStock } from '$lib/hooks/stock/reservarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { Cliente, StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null,
|
||||
clientes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
clientes?: Cliente[];
|
||||
} = $props();
|
||||
|
||||
let cantidad = $state(0);
|
||||
let clienteId = $state('');
|
||||
let fechaVencimiento = $state('');
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const disponible = $derived(stock ? stock.cantidad - stock.cantidadReservada : 0);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
cantidad = 0;
|
||||
clienteId = '';
|
||||
fechaVencimiento = '';
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!clienteId) {
|
||||
error = 'Seleccioná un cliente.';
|
||||
} else if (clientes.length === 0) {
|
||||
error = 'No hay clientes cargados.';
|
||||
} else if (cantidad <= 0) {
|
||||
error = 'La cantidad debe ser mayor a cero.';
|
||||
} else if (cantidad > disponible) {
|
||||
error = `La cantidad supera el disponible (${formatearCantidad(disponible)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await reservarStock({
|
||||
repuestoId: stock.repuestoId,
|
||||
almacenId: stock.almacenId,
|
||||
cantidad,
|
||||
clienteId: Number(clienteId),
|
||||
fechaVencimiento: fechaVencimiento ? `${fechaVencimiento}T00:00:00Z` : null,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="reservarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="reservarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Reservar stock"
|
||||
primaryButtonText="Reservar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Disponible</p>
|
||||
<p class="font-semibold">{formatearCantidad(disponible)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad a reservar"
|
||||
bind:value={cantidad}
|
||||
min={0}
|
||||
max={disponible}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<div class="mt-4">
|
||||
<Select labelText="Cliente" bind:selected={clienteId} required>
|
||||
<SelectItem value="" text="Seleccionar cliente" />
|
||||
{#each clientes as cliente (cliente.ID)}
|
||||
<SelectItem value={String(cliente.ID)} text={cliente.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
{#if clientes.length === 0}
|
||||
<p class="mt-1 text-sm text-gray-500">No hay clientes cargados.</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput
|
||||
labelText="Fecha de vencimiento (opcional)"
|
||||
type="date"
|
||||
bind:value={fechaVencimiento}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import {
|
||||
AddComment,
|
||||
ArrowsHorizontal,
|
||||
Information,
|
||||
SettingsAdjust,
|
||||
Time
|
||||
} from 'carbon-icons-svelte';
|
||||
import EstadoStockTag from './EstadoStockTag.svelte';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
stock = [],
|
||||
onTrasladar,
|
||||
onAjustar,
|
||||
onReservar,
|
||||
onComentar,
|
||||
onVer
|
||||
}: {
|
||||
stock?: StockItem[];
|
||||
onTrasladar?: (s: StockItem) => void;
|
||||
onAjustar?: (s: StockItem) => void;
|
||||
onReservar?: (s: StockItem) => void;
|
||||
onComentar?: (s: StockItem) => void;
|
||||
onVer?: (s: StockItem) => void;
|
||||
} = $props();
|
||||
|
||||
const headers = [
|
||||
{ key: 'repuesto', value: 'Repuesto' },
|
||||
{ key: 'descripcion', value: 'Descripción' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cantidad' },
|
||||
{ key: 'reservada', value: 'Reservado' },
|
||||
{ key: 'disponible', value: 'Disponible' },
|
||||
{ key: 'observacion', value: 'Observación' },
|
||||
{ key: 'estado', value: 'Estado' }
|
||||
];
|
||||
</script>
|
||||
|
||||
<TableContainer title="Existencias">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{#each headers as header}
|
||||
<TableHeader>{header.value}</TableHeader>
|
||||
{/each}
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if stock.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={headers.length + 1}>
|
||||
No hay stock para mostrar con los filtros seleccionados.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each stock as s (s.id)}
|
||||
<TableRow>
|
||||
<TableCell>{s.repuesto?.nombre ?? s.repuestoId}</TableCell>
|
||||
<TableCell title={s.repuesto?.descripcion ?? ''}
|
||||
>{s.repuesto?.descripcion || '-'}</TableCell
|
||||
>
|
||||
<TableCell>{s.almacen?.codigo ?? s.almacenId}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidad)}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidadReservada)}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidad - s.cantidadReservada)}</TableCell>
|
||||
<TableCell>{s.observacion || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<EstadoStockTag
|
||||
cantidad={s.cantidad}
|
||||
reservada={s.cantidadReservada}
|
||||
minimo={s.repuesto?.stockMinimo ?? 0}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={ArrowsHorizontal}
|
||||
onclick={() => onTrasladar?.(s)}>Trasladar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={SettingsAdjust} onclick={() => onAjustar?.(s)}
|
||||
>Ajustar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={Time} onclick={() => onReservar?.(s)}
|
||||
>Reservar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={AddComment} onclick={() => onComentar?.(s)}
|
||||
>Comentar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={Information} onclick={() => onVer?.(s)}
|
||||
>Ver registro</Button
|
||||
>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { trasladarStock } from '$lib/hooks/stock/trasladarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { Almacen, StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let almacenDestinoId = $state<number>(0);
|
||||
let cantidad = $state(0);
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const disponible = $derived(stock ? stock.cantidad - stock.cantidadReservada : 0);
|
||||
const destinos = $derived(almacenes.filter((a) => a.id !== stock?.almacenId));
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
almacenDestinoId = 0;
|
||||
cantidad = 0;
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!almacenDestinoId) {
|
||||
error = 'Seleccioná el almacén destino.';
|
||||
} else if (cantidad <= 0) {
|
||||
error = 'La cantidad debe ser mayor a cero.';
|
||||
} else if (cantidad > disponible) {
|
||||
error = `La cantidad supera el disponible (${formatearCantidad(disponible)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await trasladarStock({
|
||||
repuestoId: stock.repuestoId,
|
||||
almacenOrigenId: stock.almacenId,
|
||||
almacenDestinoId,
|
||||
cantidad,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="trasladarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="trasladarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Trasladar stock"
|
||||
primaryButtonText="Trasladar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén origen</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Disponible para trasladar</p>
|
||||
<p class="font-semibold">{formatearCantidad(disponible)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Select labelText="Almacén destino" bind:selected={almacenDestinoId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each destinos as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<div class="mt-4">
|
||||
<NumberInput
|
||||
labelText="Cantidad"
|
||||
bind:value={cantidad}
|
||||
min={0}
|
||||
max={disponible}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,10 @@
|
||||
// Formatea cantidades de stock sin separador decimal por coma.
|
||||
// Enteros como "7" y fracciones como "7.5" o "0.25".
|
||||
export function formatearCantidad(valor: number | null | undefined): string {
|
||||
if (valor === null || valor === undefined || Number.isNaN(valor)) return '-';
|
||||
|
||||
const redondeado = Math.round(valor * 1000) / 1000;
|
||||
if (Number.isInteger(redondeado)) return String(redondeado);
|
||||
|
||||
return redondeado.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
|
||||
}
|
||||
Reference in new issue
Block a user