Files
SKEEN-Proyecto/frontend/src/pages/Cortes.tsx

594 lines
24 KiB
TypeScript

import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Plus, Lock, Receipt, Printer, ChevronLeft, ChevronRight, Download } from 'lucide-react';
import Layout from '../components/Layout';
import {
Card,
Button,
Input,
Modal,
Badge,
EmptyState,
PageHeader,
Skeleton,
MobileCard,
TextArea,
toast,
badgeForCashClosingState,
} from '../components/ui';
import { CortePrint } from '../components/CortePrint';
import { odooApi, type CashClosing } from '../services/odoo';
import { useAuth } from '../lib/auth';
import { exportToExcel } from '../lib/exporter';
const money = (v: number) =>
'$' + (v ?? 0).toLocaleString('es-MX', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const MES_ACTUAL = new Date().toISOString().slice(0, 7);
const PASOS = [
{ key: 'cash', titulo: 'Efectivo' },
{ key: 'card', titulo: 'Tarjeta' },
{ key: 'transfer', titulo: 'Transferencia' },
{ key: 'other', titulo: 'Otros' },
] as const;
const Cortes: FC = () => {
const { brand, can } = useAuth();
const [closings, setClosings] = useState<CashClosing[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [wizard, setWizard] = useState<CashClosing | null>(null);
const [step, setStep] = useState(0); // 0..3 métodos, 4 = resumen
const [countedCash, setCountedCash] = useState('');
const [countedCard, setCountedCard] = useState('');
const [countedTransfer, setCountedTransfer] = useState('');
const [countedOther, setCountedOther] = useState('');
const [notes, setNotes] = useState('');
const [printCorte, setPrintCorte] = useState<CashClosing | null>(null);
const [date, setDate] = useState(() => new Date().toISOString().split('T')[0]);
const [openingCash, setOpeningCash] = useState('');
const [submitting, setSubmitting] = useState(false);
// Mes para el resumen exportable
const [mes, setMes] = useState(MES_ACTUAL);
// --- Historial comparativo: últimos cortes CERRADOS y diferencias por usuario ---
const HISTORIAL_N = 14;
const cerrados = closings.filter((c) => c.state === 'closed');
const ultimosCerrados = cerrados.slice(0, HISTORIAL_N);
const porUsuario = (() => {
const map = new Map<string, { usuario: string; cortes: number; faltantes: number; sobrantes: number; neto: number; ultima: string }>();
for (const c of ultimosCerrados) {
const usuario = c.user || 'Usuario no disponible';
const row = map.get(usuario) || { usuario, cortes: 0, faltantes: 0, sobrantes: 0, neto: 0, ultima: c.date };
row.cortes += 1;
row.neto += c.difference || 0;
if ((c.difference || 0) < 0) row.faltantes += c.difference || 0;
else row.sobrantes += c.difference || 0;
if (c.date > row.ultima) row.ultima = c.date;
map.set(usuario, row);
}
return [...map.values()].sort((a, b) => a.neto - b.neto);
})();
const cortesDelMes = closings.filter((c) => (c.date || '').startsWith(mes));
const exportarMes = async () => {
if (cortesDelMes.length === 0) {
toast.error('No hay cortes en el mes seleccionado');
return;
}
try {
await exportToExcel({
filename: `cortes-${mes}`,
sheetName: 'Cortes',
title: `Cortes de caja ${brand.nombre}`,
subtitle: `Mes ${mes} · ${cortesDelMes.length} cortes`,
columns: [
{ header: 'Referencia', key: 'name' },
{ header: 'Fecha', key: 'date', format: 'date' },
{ header: 'Usuario', key: 'user' },
{ header: 'Estado', key: 'estado' },
{ header: 'Apertura', key: 'opening_cash', format: 'currency' },
{ header: 'Efectivo', key: 'total_cash', format: 'currency' },
{ header: 'Tarjeta', key: 'total_card', format: 'currency' },
{ header: 'Transferencia', key: 'total_transfer', format: 'currency' },
{ header: 'Otros', key: 'total_other', format: 'currency' },
{ header: 'Total ventas', key: 'total_sales', format: 'currency' },
{ header: 'Efectivo contado', key: 'counted_cash', format: 'currency' },
{ header: 'Diferencia', key: 'difference', format: 'currency' },
{ header: 'Notas', key: 'notes' },
],
rows: cortesDelMes.map((c) => ({
...c,
user: c.user || 'Usuario no disponible',
estado: c.state === 'closed' ? 'Cerrado' : 'Abierto',
})),
totals: {
name: '',
total_cash: cortesDelMes.reduce((a, c) => a + (c.total_cash || 0), 0),
total_card: cortesDelMes.reduce((a, c) => a + (c.total_card || 0), 0),
total_transfer: cortesDelMes.reduce((a, c) => a + (c.total_transfer || 0), 0),
total_other: cortesDelMes.reduce((a, c) => a + (c.total_other || 0), 0),
total_sales: cortesDelMes.reduce((a, c) => a + (c.total_sales || 0), 0),
difference: cortesDelMes.reduce((a, c) => a + (c.difference || 0), 0),
},
});
toast.success(`Resumen de ${mes} descargado (${cortesDelMes.length} cortes)`);
} catch (err) {
toast.error('Error al exportar');
console.error(err);
}
};
const load = async () => {
try {
setLoading(true);
setError(null);
const res = await odooApi.getCashClosings();
if (res.status === 'success') setClosings(res.cash_closings);
} catch (err) {
setError('Error al cargar cortes');
toast.error('Error al cargar cortes');
console.error(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
load();
}, []);
const abrirWizard = (c: CashClosing) => {
setWizard(c);
setStep(0);
setCountedCash('');
setCountedCard('');
setCountedTransfer('');
setCountedOther('');
setNotes('');
};
const esperado = (c: CashClosing, key: string) => {
if (key === 'cash') return c.opening_cash + c.total_cash;
if (key === 'card') return c.total_card;
if (key === 'transfer') return c.total_transfer;
return c.total_other;
};
const valorContado = (key: string) => {
if (key === 'cash') return parseFloat(countedCash || '0') || 0;
if (key === 'card') return parseFloat(countedCard || '0') || 0;
if (key === 'transfer') return parseFloat(countedTransfer || '0') || 0;
return parseFloat(countedOther || '0') || 0;
};
const diffColor = (diff: number) =>
diff < 0 ? 'text-rose-600' : diff > 0 ? 'text-emerald-600' : 'text-theme-muted';
const create = async () => {
const value = parseFloat(openingCash);
if (Number.isNaN(value) || value < 0) {
toast.error('Ingresa un efectivo inicial válido');
return;
}
try {
setSubmitting(true);
await odooApi.createCashClosing({ date, opening_cash: value });
toast.success('Caja abierta');
setCreateOpen(false);
setOpeningCash('');
await load();
} catch (err) {
toast.error('Error al crear corte');
console.error(err);
} finally {
setSubmitting(false);
}
};
const cerrarCaja = async () => {
if (!wizard) return;
try {
setSubmitting(true);
await odooApi.closeCashClosing(wizard.id, {
counted_cash: valorContado('cash'),
counted_card: valorContado('card'),
counted_transfer: valorContado('transfer'),
counted_other: valorContado('other'),
notes,
});
toast.success('Caja cerrada');
setWizard(null);
await load();
} catch (err) {
toast.error('Error al cerrar caja');
console.error(err);
} finally {
setSubmitting(false);
}
};
const renderUser = (user: string | false) => {
if (!user) return 'Usuario no disponible';
return user;
};
const differenceColor = (diff: number) => {
if (diff > 0) return 'text-emerald-600';
if (diff < 0) return 'text-rose-600';
return 'text-theme-muted';
};
// --- Contenido de un paso del asistente ---
const renderPaso = () => {
if (!wizard) return null;
if (step < PASOS.length) {
const { key, titulo } = PASOS[step];
const esp = esperado(wizard, key);
const cont = valorContado(key);
const diff = cont - esp;
const setters: Record<string, (v: string) => void> = {
cash: setCountedCash, card: setCountedCard,
transfer: setCountedTransfer, other: setCountedOther,
};
const values: Record<string, string> = {
cash: countedCash, card: countedCard,
transfer: countedTransfer, other: countedOther,
};
const informativo = key !== 'cash';
return (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="p-3 rounded-lg bg-theme-bg">
<p className="text-xs text-theme-muted">
{key === 'cash' ? 'Efectivo esperado (apertura + cobros)' : `${titulo} registrado en el sistema`}
</p>
<p className="text-lg font-semibold text-theme-heading">{money(esp)}</p>
</div>
<div className="p-3 rounded-lg bg-theme-bg">
<p className="text-xs text-theme-muted">{cont > 0 || values[key] ? 'Diferencia' : 'Aún sin contar'}</p>
<p className={`text-lg font-semibold ${diffColor(diff)}`}>
{values[key] ? `${diff > 0 ? 'Sobrante +' : diff < 0 ? 'Faltante ' : ''}${money(diff)}` : '—'}
</p>
</div>
</div>
<Input
label={key === 'cash' ? 'Efectivo contado físicamente' : informativo ? `${titulo} contado (opcional, igual al registrado)` : 'Contado'}
type="number"
min={0}
step={0.01}
value={values[key]}
placeholder={key === 'cash' ? undefined : money(esp)}
onChange={(e) => setters[key](e.target.value)}
autoFocus
/>
{key === 'cash' && countedCash && (
<p className={`text-sm font-medium ${diffColor(diff)}`}>
{diff === 0 && 'El efectivo cuadra.'}
{diff < 0 && `Faltan ${money(-diff)} en la caja.`}
{diff > 0 && `Sobran ${money(diff)} en la caja.`}
</p>
)}
</div>
);
}
// Resumen
return (
<div className="space-y-3 text-sm">
<table className="w-full">
<thead>
<tr className="text-xs uppercase text-theme-muted border-b border-theme-border">
<th className="text-left py-1.5">Método</th>
<th className="text-right py-1.5">Esperado</th>
<th className="text-right py-1.5">Contado</th>
<th className="text-right py-1.5">Diferencia</th>
</tr>
</thead>
<tbody className="divide-y divide-theme-border">
{PASOS.map(({ key, titulo }) => {
const esp = esperado(wizard, key);
const cont = valorContado(key);
const diff = cont - esp;
return (
<tr key={key}>
<td className="py-1.5">{titulo}</td>
<td className="py-1.5 text-right">{money(esp)}</td>
<td className="py-1.5 text-right">{money(cont)}</td>
<td className={`py-1.5 text-right font-semibold ${diffColor(diff)}`}>
{diff > 0 ? '+' : ''}{money(diff)}
</td>
</tr>
);
})}
</tbody>
</table>
<TextArea
label="Notas del corte"
rows={2}
value={notes}
onChange={(e) => setNotes(e.target.value)}
/>
</div>
);
};
return (
<Layout title="Cortes de Caja" subtitle="Arqueos y cierres">
<PageHeader title="Cortes de Caja" subtitle="Abre y cierra turnos">
<Input
type="month"
value={mes}
onChange={(e) => setMes(e.target.value || MES_ACTUAL)}
aria-label="Mes a exportar"
className="sm:max-w-[160px]"
/>
<Button variant="outline" onClick={exportarMes} disabled={cortesDelMes.length === 0}>
<Download size={16} className="mr-2" />
Exportar resumen
</Button>
<Button onClick={() => setCreateOpen(true)}>
<Plus size={16} className="mr-2" />
Abrir caja
</Button>
</PageHeader>
<Card>
<Card.Body>
{error && <p className="text-rose-600 text-sm mb-4">{error}</p>}
{loading ? (
<Skeleton count={5} className="h-14 w-full" />
) : closings.length === 0 ? (
<EmptyState
title="Sin cortes"
subtitle="No hay cortes de caja registrados."
actionLabel="Abrir caja"
onAction={() => setCreateOpen(true)}
icon={<Receipt size={28} />}
/>
) : (
<>
<div className="hidden sm:block overflow-x-auto">
<table className="w-full">
<thead className="bg-theme-bg">
<tr>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Referencia</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Fecha</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Usuario</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Apertura</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden lg:table-cell">Ventas</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Diferencia</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Estado</th>
<th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Acciones</th>
</tr>
</thead>
<tbody className="divide-y">
{closings.map((c) => (
<tr key={c.id} className="hover:bg-theme-bg">
<td className="p-3 text-sm text-theme-muted">{c.name}</td>
<td className="p-3 text-sm text-theme-muted">{c.date}</td>
<td className="p-3 text-sm text-theme-muted hidden md:table-cell">{renderUser(c.user)}</td>
<td className="p-3 text-sm text-theme-heading">${c.opening_cash}</td>
<td className="p-3 text-sm text-theme-heading hidden lg:table-cell">${c.total_sales}</td>
<td className={`p-3 text-sm font-semibold ${differenceColor(c.difference)}`}>
{c.difference > 0 ? '+' : ''}${c.difference}
</td>
<td className="p-3">
<Badge variant={badgeForCashClosingState(c.state)}>{c.state}</Badge>
</td>
<td className="p-3 whitespace-nowrap">
{c.state !== 'closed' && (
<Button variant="ghost" size="sm" onClick={() => abrirWizard(c)} title="Cierre guiado">
<Lock size={16} className="text-theme-heading" />
</Button>
)}
<Button variant="ghost" size="sm" onClick={() => setPrintCorte(c)} title="Imprimir corte">
<Printer size={16} className="text-theme-heading" />
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="sm:hidden space-y-3">
{closings.map((c) => (
<MobileCard
key={c.id}
title={c.name}
subtitle={<Badge variant={badgeForCashClosingState(c.state)}>{c.state}</Badge>}
rows={[
{ label: 'Fecha', value: c.date },
{ label: 'Usuario', value: renderUser(c.user) },
{ label: 'Apertura', value: `$${c.opening_cash}` },
{ label: 'Diferencia', value: `${c.difference > 0 ? '+' : ''}$${c.difference}` },
]}
actions={
<>
{c.state !== 'closed' && (
<Button variant="ghost" size="sm" onClick={() => abrirWizard(c)}>
<Lock size={16} />
</Button>
)}
<Button variant="ghost" size="sm" onClick={() => setPrintCorte(c)}>
<Printer size={16} />
</Button>
</>
}
/>
))}
</div>
</>
)}
</Card.Body>
</Card>
<Modal
isOpen={createOpen}
onClose={() => setCreateOpen(false)}
title="Abrir caja"
maxWidth="sm"
footer={
<>
<Button variant="outline" onClick={() => setCreateOpen(false)}>Cancelar</Button>
<Button onClick={create} loading={submitting}>Abrir caja</Button>
</>
}
>
<div className="space-y-4">
<Input
label="Fecha"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<Input
label="Efectivo inicial (fondo de caja)"
type="number"
min={0}
step={0.01}
value={openingCash}
onChange={(e) => setOpeningCash(e.target.value)}
/>
</div>
</Modal>
{/* Asistente de cierre guiado */}
<Modal
isOpen={!!wizard}
onClose={() => setWizard(null)}
title={`Cierre guiado · ${wizard?.name || ''}`}
maxWidth="md"
footer={
<div className="flex items-center justify-between w-full">
<Button
variant="outline"
onClick={() => setStep((s) => Math.max(0, s - 1))}
disabled={step === 0}
>
<ChevronLeft size={16} className="mr-1" />
Anterior
</Button>
{step < PASOS.length ? (
<Button onClick={() => setStep((s) => Math.min(PASOS.length, s + 1))}>
{step === PASOS.length - 1 ? 'Ver resumen' : 'Siguiente'}
<ChevronRight size={16} className="ml-1" />
</Button>
) : (
<Button onClick={cerrarCaja} loading={submitting} disabled={!can('caja.cerrar')}
title={can('caja.cerrar') ? undefined : 'Sin permiso para cerrar caja'}>
<Lock size={16} className="mr-1.5" />
Cerrar caja
</Button>
)}
</div>
}
>
{wizard && (
<div className="space-y-4">
{/* Indicador de pasos */}
<div className="flex items-center gap-1.5 flex-wrap">
{[...PASOS.map((p) => p.titulo), 'Resumen'].map((t, i) => (
<span
key={t}
className={`px-2 py-0.5 rounded-full text-xs font-medium ${
i === step ? 'bg-theme-accent text-theme-inverse'
: i < step ? 'bg-theme-accent-bg text-theme-heading'
: 'bg-theme-bg text-theme-muted'
}`}
>
{i + 1}. {t}
</span>
))}
</div>
<p className="text-sm text-theme-muted">
Ventas del día: <span className="font-medium text-theme-heading">{money(wizard.total_sales)}</span>
{' · '}Fondo inicial: <span className="font-medium text-theme-heading">{money(wizard.opening_cash)}</span>
</p>
{renderPaso()}
</div>
)}
</Modal>
{/* Historial comparativo de diferencias (para detectar patrones por usuario) */}
<Card className="mt-4">
<Card.Body>
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<div>
<h3 className="font-heading text-lg text-theme-heading">Historial comparativo de diferencias</h3>
<p className="text-xs text-theme-muted">Últimos {HISTORIAL_N} cortes cerrados. Negativo = faltante, positivo = sobrante.</p>
</div>
{ultimosCerrados.length > 0 && (
<span className="text-xs text-theme-muted">
Diferencia acumulada: <span className={`font-semibold ${differenceColor(ultimosCerrados.reduce((a, c) => a + (c.difference || 0), 0))}`}>
{money(ultimosCerrados.reduce((a, c) => a + (c.difference || 0), 0))}
</span>
</span>
)}
</div>
{ultimosCerrados.length === 0 ? (
<p className="text-sm text-theme-muted">Aún no hay cortes cerrados.</p>
) : (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<div className="lg:col-span-2 overflow-x-auto">
<table className="w-full">
<thead className="bg-theme-bg">
<tr>
<th className="text-left p-2 text-xs font-medium text-theme-muted uppercase">Fecha</th>
<th className="text-left p-2 text-xs font-medium text-theme-muted uppercase">Usuario</th>
<th className="text-right p-2 text-xs font-medium text-theme-muted uppercase">Contado</th>
<th className="text-right p-2 text-xs font-medium text-theme-muted uppercase">Diferencia</th>
</tr>
</thead>
<tbody className="divide-y">
{ultimosCerrados.map((c) => (
<tr key={c.id} className="hover:bg-theme-bg">
<td className="p-2 text-sm text-theme-muted">{c.date}</td>
<td className="p-2 text-sm text-theme-muted">{c.user || 'Usuario no disponible'}</td>
<td className="p-2 text-sm text-right text-theme-heading">{money(c.counted_cash ?? 0)}</td>
<td className={`p-2 text-sm text-right font-semibold ${differenceColor(c.difference)}`}>
{c.difference > 0 ? '+' : ''}{money(c.difference)}
</td>
</tr>
))}
</tbody>
</table>
</div>
<div>
<p className="text-xs font-medium text-theme-muted uppercase mb-2">Resumen por usuario</p>
<div className="space-y-2">
{porUsuario.map((u) => (
<div key={u.usuario} className="rounded-xl border border-theme-border bg-theme-bg p-2.5">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium text-theme-heading truncate">{u.usuario}</span>
<span className={`text-sm font-semibold ${differenceColor(u.neto)}`}>
{u.neto > 0 ? '+' : ''}{money(u.neto)}
</span>
</div>
<p className="text-[11px] text-theme-muted">
{u.cortes} {u.cortes === 1 ? 'corte' : 'cortes'}
{u.faltantes !== 0 ? ` · faltantes ${money(u.faltantes)}` : ''}
{u.sobrantes !== 0 ? ` · sobrantes ${money(u.sobrantes)}` : ''}
</p>
</div>
))}
</div>
</div>
</div>
)}
</Card.Body>
</Card>
<CortePrint corte={printCorte} onClose={() => setPrintCorte(null)} />
</Layout>
);
};
export default Cortes;