Files
SKEEN-Proyecto/frontend/src/components/compras/CompraFormModal.tsx

241 lines
10 KiB
TypeScript

import type { FC } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Modal, Button, Input, TextArea, Select, toast } from '../ui';
import { odooApi, type Compra, type InventoryItem, type MonedaCompra, type Proveedor } from '../../services/odoo';
import { MONEDA_OPTIONS, fmtMoney } from './shared';
interface LineaForm {
item_id: string;
cantidad_pedida: string;
costo_unitario: string;
descuento: string;
lote: string;
fecha_caducidad: string;
}
const emptyLinea: LineaForm = {
item_id: '', cantidad_pedida: '1', costo_unitario: '0', descuento: '0',
lote: '', fecha_caducidad: '',
};
interface Props {
isOpen: boolean;
onClose: () => void;
compra: Compra | null;
onDone: (compraId?: number) => void;
}
const hoy = () => new Date().toISOString().slice(0, 10);
const CompraFormModal: FC<Props> = ({ isOpen, onClose, compra, onDone }) => {
const [proveedores, setProveedores] = useState<Proveedor[]>([]);
const [items, setItems] = useState<InventoryItem[]>([]);
const [partnerId, setPartnerId] = useState('');
const [fecha, setFecha] = useState(hoy());
const [entrega, setEntrega] = useState('');
const [moneda, setMoneda] = useState<MonedaCompra>('MXN');
const [descuento, setDescuento] = useState('0');
const [referencia, setReferencia] = useState('');
const [notas, setNotas] = useState('');
const [lineas, setLineas] = useState<LineaForm[]>([{ ...emptyLinea }]);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!isOpen) return;
odooApi.getProveedores({ page_size: 500 })
.then((res) => { if (res.status === 'success') setProveedores(res.proveedores || []); })
.catch(() => {});
odooApi.getInventory()
.then((res) => setItems(res.items || []))
.catch(() => {});
}, [isOpen]);
useEffect(() => {
if (!isOpen) return;
if (compra) {
setPartnerId(String(compra.partner_id));
setFecha(compra.fecha || hoy());
setEntrega(compra.fecha_entrega_esperada || '');
setMoneda(compra.moneda);
setDescuento(String(compra.descuento || 0));
setReferencia(compra.referencia_factura || '');
setNotas(compra.notas || '');
setLineas((compra.lineas || []).map((l) => ({
item_id: String(l.item_id),
cantidad_pedida: String(l.cantidad_pedida),
costo_unitario: String(l.costo_unitario),
descuento: String(l.descuento || 0),
lote: l.lote || '',
fecha_caducidad: l.fecha_caducidad || '',
})));
} else {
setPartnerId(''); setFecha(hoy()); setEntrega(''); setMoneda('MXN');
setDescuento('0'); setReferencia(''); setNotas('');
setLineas([{ ...emptyLinea }]);
}
}, [isOpen, compra]);
const itemMap = useMemo(() => new Map(items.map((i) => [i.id, i])), [items]);
const setLinea = (idx: number, patch: Partial<LineaForm>) =>
setLineas((prev) => prev.map((l, i) => (i === idx ? { ...l, ...patch } : l)));
const onPickItem = (idx: number, itemId: string) => {
const it = itemMap.get(Number(itemId));
const costo = it ? (it.ultimo_costo || it.costo_promedio || it.cost || 0) : 0;
setLinea(idx, { item_id: itemId, costo_unitario: String(costo) });
};
const subtotalLinea = (l: LineaForm) =>
Math.max(0, (parseFloat(l.cantidad_pedida) || 0) * (parseFloat(l.costo_unitario) || 0) - (parseFloat(l.descuento) || 0));
const subtotal = lineas.reduce((s, l) => s + subtotalLinea(l), 0);
const desc = parseFloat(descuento) || 0;
const guardar = async () => {
if (!partnerId) { toast.error('Selecciona un proveedor'); return; }
const payload = lineas
.filter((l) => l.item_id && (parseFloat(l.cantidad_pedida) || 0) > 0)
.map((l) => ({
item_id: Number(l.item_id),
cantidad_pedida: parseFloat(l.cantidad_pedida) || 0,
costo_unitario: parseFloat(l.costo_unitario) || 0,
descuento: parseFloat(l.descuento) || 0,
lote: l.lote,
fecha_caducidad: l.fecha_caducidad || null,
}));
if (payload.length === 0) { toast.error('Agrega al menos una línea con artículo y cantidad'); return; }
setSaving(true);
try {
const body = {
partner_id: Number(partnerId),
fecha,
fecha_entrega_esperada: entrega || null,
moneda,
descuento: desc,
notas,
referencia_factura: referencia,
lineas: payload,
};
if (compra) {
await odooApi.updateCompra(compra.id, body);
} else {
await odooApi.crearOrdenCompra(body);
}
toast.success(compra ? 'Compra actualizada' : 'Compra creada');
onDone(compra?.id);
onClose();
} catch (err) {
const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
toast.error(msg || 'No se pudo guardar la compra');
} finally {
setSaving(false);
}
};
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title={compra ? `Editar compra ${compra.folio}` : 'Nueva orden de compra'}
maxWidth="full"
footer={(
<div className="flex items-center justify-between gap-2 w-full">
<span className="text-sm text-theme-muted">
Subtotal <strong className="text-theme-heading">{fmtMoney(subtotal, moneda)}</strong>
{desc > 0 && <> · Descuento <strong className="text-theme-heading">{fmtMoney(desc, moneda)}</strong></>}
</span>
<div className="flex gap-2">
<Button variant="outline" onClick={onClose}>Cancelar</Button>
<Button onClick={guardar} loading={saving}>Guardar</Button>
</div>
</div>
)}
>
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<Select
label="Proveedor"
options={[{ value: '', label: 'Selecciona…' }, ...proveedores.map((p) => ({ value: String(p.id), label: p.name }))]}
value={partnerId}
onChange={(e) => setPartnerId(e.target.value)}
/>
<Input label="Fecha" type="date" value={fecha} onChange={(e) => setFecha(e.target.value)} />
<Input label="Entrega esperada" type="date" value={entrega} onChange={(e) => setEntrega(e.target.value)} />
<Select label="Moneda" options={MONEDA_OPTIONS} value={moneda} onChange={(e) => setMoneda(e.target.value as MonedaCompra)} />
<Input label="Descuento global" type="number" value={descuento} onChange={(e) => setDescuento(e.target.value)} />
<Input label="Referencia / factura" value={referencia} onChange={(e) => setReferencia(e.target.value)} />
</div>
<div className="overflow-x-auto border border-theme-border rounded-xl">
<table className="w-full text-sm">
<thead className="bg-theme-bg text-theme-muted text-[11px] uppercase">
<tr>
<th className="text-left px-3 py-2 min-w-[200px]">Artículo</th>
<th className="text-right px-3 py-2 w-24">Cantidad</th>
<th className="text-right px-3 py-2 w-28">Costo unit.</th>
<th className="text-right px-3 py-2 w-24">Desc.</th>
<th className="text-left px-3 py-2 w-32">Lote</th>
<th className="text-left px-3 py-2 w-40">Caducidad</th>
<th className="text-right px-3 py-2 w-24">Subtotal</th>
<th className="px-3 py-2 w-10"></th>
</tr>
</thead>
<tbody className="divide-y divide-theme-border">
{lineas.map((l, idx) => (
<tr key={idx}>
<td className="px-3 py-2">
<Select
options={[{ value: '', label: 'Selecciona…' }, ...items.map((it) => ({ value: String(it.id), label: it.name }))]}
value={l.item_id}
onChange={(e) => onPickItem(idx, e.target.value)}
/>
</td>
<td className="px-3 py-2">
<Input type="number" value={l.cantidad_pedida} onChange={(e) => setLinea(idx, { cantidad_pedida: e.target.value })} />
</td>
<td className="px-3 py-2">
<Input type="number" value={l.costo_unitario} onChange={(e) => setLinea(idx, { costo_unitario: e.target.value })} />
</td>
<td className="px-3 py-2">
<Input type="number" value={l.descuento} onChange={(e) => setLinea(idx, { descuento: e.target.value })} />
</td>
<td className="px-3 py-2">
<Input value={l.lote} onChange={(e) => setLinea(idx, { lote: e.target.value })} />
</td>
<td className="px-3 py-2">
<Input type="date" value={l.fecha_caducidad} onChange={(e) => setLinea(idx, { fecha_caducidad: e.target.value })} />
</td>
<td className="px-3 py-2 text-right tabular-nums">{fmtMoney(subtotalLinea(l), moneda)}</td>
<td className="px-3 py-2">
<button
type="button"
className="p-1.5 rounded-lg hover:bg-rose-50 text-rose-600"
onClick={() => setLineas((prev) => prev.length > 1 ? prev.filter((_, i) => i !== idx) : prev)}
title="Quitar línea"
>
<Trash2 size={15} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<Button variant="outline" size="sm" onClick={() => setLineas((prev) => [...prev, { ...emptyLinea }])}>
<Plus size={14} className="mr-1.5" />Agregar línea
</Button>
<TextArea label="Observaciones" rows={2} value={notas} onChange={(e) => setNotas(e.target.value)} />
<p className="text-[11px] text-theme-muted">
Los impuestos se calculan según la configuración de impuestos de la clínica. Si no están
activos, la compra queda sin impuesto.
</p>
</div>
</Modal>
);
};
export default CompraFormModal;