Corte de caja asistido (esperado vs contado, diferencias, PDF) y fotos antes/despues con comparacion en expediente

This commit is contained in:
2026-09-08 07:27:57 +00:00
parent e8690dd74e
commit 4f9a16103f
7 changed files with 672 additions and 81 deletions

View File

@@ -0,0 +1,115 @@
import type { FC } from 'react';
import { Printer } from 'lucide-react';
import { Button, Modal } from './ui';
import type { CashClosing } from '../services/odoo';
// Corte de caja imprimible. Sigue el patrón de impresión existente
// (RecetaPrint / EstadoCuentaPrint / TicketPrint): contenido en un
// div.print-ticket + window.print(); el CSS de @media print en index.css
// oculta el resto de la página.
interface ClinicSettings {
name: string;
phone: string;
address: string;
}
const clinicSettings = (): ClinicSettings => {
try {
const saved = localStorage.getItem('skeen_clinic_settings');
if (saved) return JSON.parse(saved);
} catch {
// ignore
}
return { name: 'SKEEN Derma Experts', phone: '', address: '' };
};
const money = (v: number) =>
'$' + (v ?? 0).toLocaleString('es-MX', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
export const CortePrint: FC<{ corte: CashClosing | null; onClose: () => void }> = ({ corte, onClose }) => {
if (!corte) return null;
const clinic = clinicSettings();
const fila = (label: string, valor: number) => (
<tr>
<td className="py-1 pr-2">{label}</td>
<td className="py-1 text-right">{money(valor)}</td>
</tr>
);
const filaDiff = (label: string, esperado: number, contado: number, diff: number) => (
<tr>
<td className="py-1 pr-2">{label}</td>
<td className="py-1 text-right">{money(esperado)}</td>
<td className="py-1 text-right">{money(contado)}</td>
<td className={'py-1 text-right font-semibold ' + (diff < 0 ? 'text-rose-700' : diff > 0 ? 'text-emerald-700' : '')}>
{diff > 0 ? '+' : ''}{money(diff)}
</td>
</tr>
);
return (
<Modal isOpen={!!corte} onClose={onClose} title={`Corte de caja ${corte.name}`} maxWidth="lg">
<div className="print-ticket bg-white text-[#222] p-5 rounded-xl border border-theme-border text-[13px] leading-snug">
<div className="text-center mb-3">
<p className="font-bold text-[15px]">{clinic.name}</p>
{clinic.address && <p className="text-[11px] text-[#555]">{clinic.address}</p>}
{clinic.phone && <p className="text-[11px] text-[#555]">{clinic.phone}</p>}
<p className="font-semibold mt-1">CORTE DE CAJA {corte.name}</p>
<p className="text-[11px] text-[#555]">Fecha: {corte.date} · Cerró: {corte.user || '—'}</p>
</div>
<table className="w-full text-[12px]">
<thead>
<tr className="border-b border-[#ccc] text-[10px] uppercase text-[#666]">
<th className="text-left py-1">Método</th>
<th className="text-right py-1">Esperado</th>
<th className="text-right py-1">Contado</th>
<th className="text-right py-1">Diferencia</th>
</tr>
</thead>
<tbody className="border-b border-[#ccc]">
{filaDiff('Efectivo', corte.opening_cash + corte.total_cash, corte.counted_cash, corte.diff_cash)}
{filaDiff('Tarjeta', corte.total_card, corte.counted_card, corte.diff_card)}
{filaDiff('Transferencia', corte.total_transfer, corte.counted_transfer, corte.diff_transfer)}
{filaDiff('Otros', corte.total_other, corte.counted_other, corte.diff_other)}
</tbody>
<tbody>
{fila('Ventas totales del día', corte.total_sales)}
{fila('Efectivo esperado (apertura + cobros)', corte.opening_cash + corte.total_cash)}
{fila('Efectivo de cierre registrado', corte.closing_cash)}
</tbody>
<tbody className="border-t border-[#ccc]">
<tr className="font-bold">
<td className="py-1.5 pr-2">Diferencia total del corte</td>
<td className={'py-1.5 text-right ' + (corte.difference < 0 ? 'text-rose-700' : corte.difference > 0 ? 'text-emerald-700' : '')}>
{corte.difference > 0 ? '+' : ''}{money(corte.difference)}
</td>
</tr>
</tbody>
</table>
{corte.notes && (
<div className="mt-3 text-[12px]">
<p className="font-semibold">Notas:</p>
<p className="whitespace-pre-wrap">{corte.notes}</p>
</div>
)}
<div className="mt-6 flex justify-between text-[11px] text-[#555]">
<span>_____________________<br />Entregó (cajero)</span>
<span>_____________________<br />Recibió (administración)</span>
</div>
<p className="mt-4 text-center text-[10px] text-[#888]">Impreso el {new Date().toLocaleString('es-MX')}</p>
</div>
<div className="flex justify-end mt-3">
<Button onClick={() => window.print()}>
<Printer size={14} className="mr-1.5" />
Imprimir
</Button>
</div>
</Modal>
);
};

View File

@@ -1,7 +1,7 @@
import type { FC } from 'react';
import { useEffect, useState, useCallback, useRef } from 'react';
import { FileText, X, Upload } from 'lucide-react';
import { Button, Modal, Skeleton, toast } from './ui';
import { useEffect, useState, useCallback, useRef, useMemo } from 'react';
import { FileText, X, Upload, GitCompare, Tag } from 'lucide-react';
import { Button, Modal, Select, Skeleton, toast } from './ui';
import { odooApi, type PatientAdjunto } from '../services/odoo';
interface PatientAdjuntosProps {
@@ -13,12 +13,25 @@ interface PatientAdjuntosProps {
const MAX_BYTES = 10 * 1024 * 1024;
const CLASIF_LABEL: Record<string, string> = {
antes: 'Antes',
despues: 'Después',
sin_clasificar: '',
};
export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, editable = true, onChange }) => {
const [adjuntos, setAdjuntos] = useState<PatientAdjunto[]>([]);
const [loading, setLoading] = useState(true);
const [uploading, setUploading] = useState(false);
const [visor, setVisor] = useState<PatientAdjunto | null>(null);
const [nuevaClasif, setNuevaClasif] = useState('sin_clasificar');
const [clasificando, setClasificando] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
// Comparación antes/después
const [compAbierta, setCompAbierta] = useState(false);
const [compServicio, setCompServicio] = useState('');
const [compAntes, setCompAntes] = useState('');
const [compDespues, setCompDespues] = useState('');
const load = useCallback(async () => {
try {
@@ -55,9 +68,11 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
name: file.name,
file_b64,
mimetype: file.type || 'application/octet-stream',
antes_despues: kind === 'imagen' ? nuevaClasif : undefined,
});
if (res.status === 'success') {
toast.success('Archivo subido');
if (kind === 'imagen') setNuevaClasif('sin_clasificar');
await load();
onChange?.();
}
@@ -84,13 +99,47 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
}
};
const clasificar = async (adjId: number, antes_despues: string) => {
try {
setClasificando(true);
await odooApi.updatePatientAdjunto(adjId, { antes_despues });
if (visor) setVisor({ ...visor, antes_despues: antes_despues as PatientAdjunto['antes_despues'] });
toast.success(
antes_despues === 'sin_clasificar' ? 'Clasificación quitada'
: antes_despues === 'antes' ? 'Marcada como Antes' : 'Marcada como Después',
);
await load();
} catch (err) {
toast.error('Error al clasificar la foto');
console.error(err);
} finally {
setClasificando(false);
}
};
const imagenes = adjuntos.filter((a) => a.mimetype.startsWith('image/'));
const docs = adjuntos.filter((a) => !a.mimetype.startsWith('image/'));
// Comparación: opciones por servicio y fotos antes/después
const servicios = useMemo(() => {
const map = new Map<number, string>();
imagenes.forEach((a) => { if (a.servicio_id) map.set(a.servicio_id, a.servicio); });
return Array.from(map.entries());
}, [imagenes]);
const fotosFiltradas = useMemo(
() => (compServicio ? imagenes.filter((a) => String(a.servicio_id) === compServicio) : imagenes),
[imagenes, compServicio],
);
const fotosAntes = fotosFiltradas.filter((a) => a.antes_despues === 'antes');
const fotosDespues = fotosFiltradas.filter((a) => a.antes_despues === 'despues');
const fotoAntes = fotosAntes.find((a) => String(a.id) === compAntes) || fotosAntes[0];
const fotoDespues = fotosDespues.find((a) => String(a.id) === compDespues) || fotosDespues[0];
return (
<div>
{editable && (
<div className="mb-3">
<div className="mb-3 flex items-center gap-2 flex-wrap">
<input
ref={fileRef}
type="file"
@@ -102,6 +151,25 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
<Upload size={14} className="mr-1.5" />
{kind === 'imagen' ? 'Subir foto' : 'Escanear / Subir expediente'}
</Button>
{kind === 'imagen' && (
<Select
value={nuevaClasif}
onChange={(e) => setNuevaClasif(e.target.value)}
className="!w-auto text-sm"
title="Clasificación de la próxima foto"
options={[
{ value: 'sin_clasificar', label: 'Clasificar como: Sin clasificar' },
{ value: 'antes', label: 'Clasificar como: Antes' },
{ value: 'despues', label: 'Clasificar como: Después' },
]}
/>
)}
{kind === 'imagen' && fotosAntes.length > 0 && fotosDespues.length > 0 && (
<Button variant="outline" size="sm" onClick={() => setCompAbierta(true)}>
<GitCompare size={14} className="mr-1.5" />
Comparación
</Button>
)}
</div>
)}
@@ -124,6 +192,15 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
className="w-full h-24 object-cover rounded-xl border border-theme-border"
/>
</button>
{a.antes_despues !== 'sin_clasificar' && (
<span
className={`absolute top-1 left-1 px-1.5 py-0.5 rounded-full text-[10px] font-semibold text-white ${
a.antes_despues === 'antes' ? 'bg-blue-600' : 'bg-emerald-600'
}`}
>
{CLASIF_LABEL[a.antes_despues]}
</span>
)}
{editable && (
<button
type="button"
@@ -163,7 +240,7 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
</>
)}
{/* Visor de imagen */}
{/* Visor de imagen con clasificación */}
<Modal
isOpen={!!visor}
onClose={() => setVisor(null)}
@@ -171,12 +248,125 @@ export const PatientAdjuntos: FC<PatientAdjuntosProps> = ({ patientId, kind, edi
maxWidth="2xl"
>
{visor && (
<div className="space-y-3">
<img
src={odooApi.patientAdjuntoUrl(visor.url)}
alt={visor.name}
className="w-full rounded-xl"
/>
{visor.servicio && (
<p className="text-xs text-theme-muted flex items-center">
<Tag size={12} className="mr-1" />
Servicio: {visor.servicio}
</p>
)}
{editable && (
<div className="flex items-center gap-2 flex-wrap border-t border-theme-border pt-3">
<span className="text-xs text-theme-muted mr-1">Clasificar:</span>
<Button
size="sm"
variant={visor.antes_despues === 'antes' ? undefined : 'outline'}
onClick={() => clasificar(visor.id, 'antes')}
loading={clasificando && visor.antes_despues !== 'antes'}
>
Antes
</Button>
<Button
size="sm"
variant={visor.antes_despues === 'despues' ? undefined : 'outline'}
onClick={() => clasificar(visor.id, 'despues')}
loading={clasificando && visor.antes_despues !== 'despues'}
>
Después
</Button>
{visor.antes_despues !== 'sin_clasificar' && (
<Button
size="sm"
variant="ghost"
onClick={() => clasificar(visor.id, 'sin_clasificar')}
loading={clasificando}
>
Quitar marca
</Button>
)}
</div>
)}
</div>
)}
</Modal>
{/* Comparación antes / después */}
<Modal
isOpen={compAbierta}
onClose={() => setCompAbierta(false)}
title="Comparación antes / después"
maxWidth="2xl"
>
<div className="space-y-4">
{servicios.length > 1 && (
<Select
label="Servicio"
value={compServicio}
onChange={(e) => { setCompServicio(e.target.value); setCompAntes(''); setCompDespues(''); }}
options={[
{ value: '', label: 'Todos los servicios' },
...servicios.map(([id, nombre]) => ({ value: String(id), label: nombre })),
]}
/>
)}
<div className="grid grid-cols-2 gap-3">
<Select
label={`Foto Antes (${fotosAntes.length})`}
value={fotoAntes ? String(fotoAntes.id) : ''}
onChange={(e) => setCompAntes(e.target.value)}
options={
fotosAntes.length === 0
? [{ value: '', label: 'Sin fotos marcadas como Antes' }]
: fotosAntes.map((a) => ({ value: String(a.id), label: a.name || `Foto #${a.id}` }))
}
/>
<Select
label={`Foto Después (${fotosDespues.length})`}
value={fotoDespues ? String(fotoDespues.id) : ''}
onChange={(e) => setCompDespues(e.target.value)}
options={
fotosDespues.length === 0
? [{ value: '', label: 'Sin fotos marcadas como Después' }]
: fotosDespues.map((a) => ({ value: String(a.id), label: a.name || `Foto #${a.id}` }))
}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<p className="text-xs font-semibold text-blue-600 uppercase mb-1">Antes</p>
{fotoAntes ? (
<img
src={odooApi.patientAdjuntoUrl(fotoAntes.url)}
alt={fotoAntes.name}
className="w-full rounded-xl border border-theme-border"
/>
) : (
<div className="h-40 rounded-xl bg-theme-bg flex items-center justify-center text-sm text-theme-muted">
Sin foto Antes
</div>
)}
</div>
<div>
<p className="text-xs font-semibold text-emerald-600 uppercase mb-1">Después</p>
{fotoDespues ? (
<img
src={odooApi.patientAdjuntoUrl(fotoDespues.url)}
alt={fotoDespues.name}
className="w-full rounded-xl border border-theme-border"
/>
) : (
<div className="h-40 rounded-xl bg-theme-bg flex items-center justify-center text-sm text-theme-muted">
Sin foto Después
</div>
)}
</div>
</div>
</div>
</Modal>
</div>
);

View File

@@ -1,6 +1,6 @@
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Plus, Lock, Receipt } from 'lucide-react';
import { Plus, Lock, Receipt, Printer, ChevronLeft, ChevronRight } from 'lucide-react';
import Layout from '../components/Layout';
import {
Card,
@@ -12,20 +12,38 @@ import {
PageHeader,
Skeleton,
MobileCard,
TextArea,
toast,
badgeForCashClosingState,
} from '../components/ui';
import { CortePrint } from '../components/CortePrint';
import { odooApi, type CashClosing } from '../services/odoo';
const money = (v: number) =>
'$' + (v ?? 0).toLocaleString('es-MX', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const PASOS = [
{ key: 'cash', titulo: 'Efectivo' },
{ key: 'card', titulo: 'Tarjeta' },
{ key: 'transfer', titulo: 'Transferencia' },
{ key: 'other', titulo: 'Otros' },
] as const;
const Cortes: FC = () => {
const [closings, setClosings] = useState<CashClosing[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [closeOpen, setCloseOpen] = useState<CashClosing | null>(null);
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 [closingCash, setClosingCash] = useState('');
const [submitting, setSubmitting] = useState(false);
const load = async () => {
@@ -47,6 +65,33 @@ const Cortes: FC = () => {
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) {
@@ -68,19 +113,19 @@ const Cortes: FC = () => {
}
};
const close = async () => {
if (!closeOpen) return;
const value = parseFloat(closingCash);
if (Number.isNaN(value) || value < 0) {
toast.error('Ingresa un efectivo final válido');
return;
}
const cerrarCaja = async () => {
if (!wizard) return;
try {
setSubmitting(true);
await odooApi.closeCashClosing(closeOpen.id, value);
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');
setCloseOpen(null);
setClosingCash('');
setWizard(null);
await load();
} catch (err) {
toast.error('Error al cerrar caja');
@@ -96,11 +141,104 @@ const Cortes: FC = () => {
};
const differenceColor = (diff: number) => {
if (diff > 0) return 'text-theme-heading';
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">
@@ -154,12 +292,15 @@ const Cortes: FC = () => {
<td className="p-3">
<Badge variant={badgeForCashClosingState(c.state)}>{c.state}</Badge>
</td>
<td className="p-3">
<td className="p-3 whitespace-nowrap">
{c.state !== 'closed' && (
<Button variant="ghost" size="sm" onClick={() => setCloseOpen(c)} title="Cerrar caja">
<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>
))}
@@ -180,11 +321,16 @@ const Cortes: FC = () => {
{ label: 'Diferencia', value: `${c.difference > 0 ? '+' : ''}$${c.difference}` },
]}
actions={
c.state !== 'closed' && (
<Button variant="ghost" size="sm" onClick={() => setCloseOpen(c)}>
<Lock size={16} className="text-theme-heading" />
<>
{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>
</>
}
/>
))}
@@ -214,7 +360,7 @@ const Cortes: FC = () => {
onChange={(e) => setDate(e.target.value)}
/>
<Input
label="Efectivo inicial"
label="Efectivo inicial (fondo de caja)"
type="number"
min={0}
step={0.01}
@@ -224,37 +370,63 @@ const Cortes: FC = () => {
</div>
</Modal>
{/* Asistente de cierre guiado */}
<Modal
isOpen={!!closeOpen}
onClose={() => setCloseOpen(null)}
title="Cerrar caja"
maxWidth="sm"
isOpen={!!wizard}
onClose={() => setWizard(null)}
title={`Cierre guiado · ${wizard?.name || ''}`}
maxWidth="md"
footer={
<>
<Button variant="outline" onClick={() => setCloseOpen(null)}>Cancelar</Button>
<Button onClick={close} loading={submitting}>Cerrar caja</Button>
</>
<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}>
<Lock size={16} className="mr-1.5" />
Cerrar caja
</Button>
)}
</div>
}
>
{closeOpen && (
{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">
Corte: <span className="font-medium text-theme-heading">{closeOpen.name}</span>
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>
<p className="text-sm text-theme-muted">
Ventas registradas: <span className="font-medium text-theme-heading">${closeOpen.total_sales}</span>
</p>
<Input
label="Efectivo final"
type="number"
min={0}
step={0.01}
value={closingCash}
onChange={(e) => setClosingCash(e.target.value)}
/>
{renderPaso()}
</div>
)}
</Modal>
<CortePrint corte={printCorte} onClose={() => setPrintCorte(null)} />
</Layout>
);
};

View File

@@ -213,6 +213,11 @@ export interface PatientAdjunto {
name: string;
mimetype: string;
notes: string;
antes_despues: 'sin_clasificar' | 'antes' | 'despues';
visita_id: number | null;
cita_id: number | null;
servicio_id: number | null;
servicio: string;
create_date: string | null;
url: string;
}
@@ -420,6 +425,15 @@ export interface CashClosing {
total_sales: number;
closing_cash: number;
difference: number;
counted_cash: number;
counted_card: number;
counted_transfer: number;
counted_other: number;
diff_cash: number;
diff_card: number;
diff_transfer: number;
diff_other: number;
notes: string;
state: string;
}
@@ -1038,7 +1052,7 @@ export const odooApi = {
return data;
},
async uploadVisitaAdjunto(id: number, payload: { kind: string; name: string; file_b64: string; mimetype: string; notes?: string }): Promise<{ status: string; visita: Visita }> {
async uploadVisitaAdjunto(id: number, payload: { kind: string; name: string; file_b64: string; mimetype: string; notes?: string; antes_despues?: string }): Promise<{ status: string; visita: Visita }> {
const { data } = await axios.post(`${ODOO_BASE}/skeen/frontend/v1/visitas/${id}/adjuntos`, payload);
return data;
},
@@ -1098,7 +1112,7 @@ export const odooApi = {
return data;
},
async uploadPatientAdjunto(id: number, payload: { kind: string; name: string; file_b64: string; mimetype: string; notes?: string }): Promise<{ status: string; adjunto: PatientAdjunto }> {
async uploadPatientAdjunto(id: number, payload: { kind: string; name: string; file_b64: string; mimetype: string; notes?: string; antes_despues?: string }): Promise<{ status: string; adjunto: PatientAdjunto }> {
const { data } = await axios.post(`${ODOO_BASE}/skeen/frontend/v1/patients/${id}/adjuntos`, payload);
return data;
},
@@ -1328,8 +1342,13 @@ export const odooApi = {
return data;
},
async closeCashClosing(id: number, closing_cash: number): Promise<{ status: string; cash_closing: CashClosing }> {
const { data } = await axios.post(`${ODOO_BASE}/skeen/frontend/v1/cash_closings/${id}/close`, { closing_cash });
async closeCashClosing(id: number, payload: { closing_cash?: number; counted_cash?: number; counted_card?: number; counted_transfer?: number; counted_other?: number; notes?: string }): Promise<{ status: string; cash_closing: CashClosing }> {
const { data } = await axios.post(`${ODOO_BASE}/skeen/frontend/v1/cash_closings/${id}/close`, payload);
return data;
},
async updatePatientAdjunto(adjId: number, payload: { antes_despues?: string; visita_id?: number | null; cita_id?: number | null; servicio_id?: number | null }): Promise<{ status: string; adjunto: PatientAdjunto }> {
const { data } = await axios.put(`${ODOO_BASE}/skeen/frontend/v1/patients/adjuntos/${adjId}`, payload);
return data;
},

View File

@@ -18,3 +18,13 @@ class SkeenPatientAdjunto(models.Model):
file = fields.Binary(string='Contenido', attachment=True, required=True)
mimetype = fields.Char(string='Tipo MIME')
notes = fields.Char(string='Notas')
# Clasificación de fotos del expediente (antes/después de un tratamiento)
antes_despues = fields.Selection([
('sin_clasificar', 'Sin clasificar'),
('antes', 'Antes'),
('despues', 'Después'),
], string='Clasificación', default='sin_clasificar')
visita_id = fields.Many2one('skeen.visita', string='Visita',
ondelete='set null')
cita_id = fields.Many2one('skeen.cita', string='Cita', ondelete='set null')
servicio_id = fields.Many2one('skeen.servicio', string='Servicio')

View File

@@ -261,9 +261,18 @@ class SkeenCorteCaja(models.Model):
total_other = fields.Float(string='Otros', compute='_compute_totals', store=True)
total_sales = fields.Float(string='Total Ventas', compute='_compute_totals', store=True)
# Cierre
# Cierre guiado: efectivo contado por el cajero y conteo informativo
# de los demás métodos.
counted_cash = fields.Float(string='Efectivo Contado', default=0.0)
counted_card = fields.Float(string='Tarjeta Contada', default=0.0)
counted_transfer = fields.Float(string='Transferencia Contada', default=0.0)
counted_other = fields.Float(string='Otros Contados', default=0.0)
closing_cash = fields.Float(string='Efectivo Cierre', default=0.0)
difference = fields.Float(string='Diferencia', compute='_compute_difference', store=True)
diff_cash = fields.Float(string='Diferencia Efectivo', compute='_compute_difference', store=True)
diff_card = fields.Float(string='Diferencia Tarjeta', compute='_compute_difference', store=True)
diff_transfer = fields.Float(string='Diferencia Transferencia', compute='_compute_difference', store=True)
diff_other = fields.Float(string='Diferencia Otros', compute='_compute_difference', store=True)
# Estado
state = fields.Selection([
@@ -276,32 +285,44 @@ class SkeenCorteCaja(models.Model):
@api.depends('date')
def _compute_totals(self):
for corte in self:
ventas = self.env['skeen.venta'].search([
('date', '=', corte.date),
('state', 'in', ('confirmed', 'paid', 'partial')),
])
# Sumar también pagos por método
corte.update(corte._totals_from_payments())
def _totals_from_payments(self):
"""Sumatorias por método de pago para la fecha del corte."""
self.ensure_one()
pagos = self.env['skeen.pago'].search([
('payment_date', '>=', corte.date.strftime('%Y-%m-%d 00:00:00')),
('payment_date', '<=', corte.date.strftime('%Y-%m-%d 23:59:59')),
('payment_date', '>=', self.date.strftime('%Y-%m-%d 00:00:00')),
('payment_date', '<=', self.date.strftime('%Y-%m-%d 23:59:59')),
('state', '=', 'completed'),
])
cash = sum(p.amount for p in pagos if p.payment_method == 'cash')
card = sum(p.amount for p in pagos if p.payment_method in ('card', 'stripe', 'mercadopago'))
transfer = sum(p.amount for p in pagos if p.payment_method == 'transfer')
other = sum(p.amount for p in pagos if p.payment_method not in ('cash', 'card', 'stripe', 'mercadopago', 'transfer'))
return {
'total_cash': cash,
'total_card': card,
'total_transfer': transfer,
'total_other': other,
'total_sales': cash + card + transfer + other,
}
corte.total_cash = cash
corte.total_card = card
corte.total_transfer = transfer
corte.total_other = other
corte.total_sales = cash + card + transfer + other
def refresh_totals(self):
"""Recalcula y persiste los totales del día (pagos pueden llegar después
de abrir la caja)."""
for corte in self:
corte.write(corte._totals_from_payments())
@api.depends('opening_cash', 'total_cash', 'closing_cash')
@api.depends('opening_cash', 'total_cash', 'total_card', 'total_transfer', 'total_other',
'closing_cash', 'counted_cash', 'counted_card', 'counted_transfer', 'counted_other')
def _compute_difference(self):
for corte in self:
expected = corte.opening_cash + corte.total_cash
corte.difference = corte.closing_cash - expected
corte.diff_cash = corte.counted_cash - expected
corte.diff_card = corte.counted_card - corte.total_card
corte.diff_transfer = corte.counted_transfer - corte.total_transfer
corte.diff_other = corte.counted_other - corte.total_other
@api.model_create_multi
def create(self, vals_list):

View File

@@ -1341,6 +1341,11 @@ class SkeenFrontendController(http.Controller):
'name': a.name or '',
'mimetype': a.mimetype or '',
'notes': a.notes or '',
'antes_despues': a.antes_despues,
'visita_id': a.visita_id.id if a.visita_id else None,
'cita_id': a.cita_id.id if a.cita_id else None,
'servicio_id': a.servicio_id.id if a.servicio_id else None,
'servicio': a.servicio_id.name if a.servicio_id else '',
'create_date': a.create_date.strftime('%Y-%m-%d %H:%M') if a.create_date else None,
'url': f'/skeen/frontend/v1/patients/adjuntos/{a.id}/file',
}
@@ -1383,18 +1388,50 @@ class SkeenFrontendController(http.Controller):
return json_response({'status': 'error', 'message': 'Archivo vacío'}, 400)
if len(raw) > 10 * 1024 * 1024:
return json_response({'status': 'error', 'message': 'El archivo excede 10 MB'}, 400)
adj = request.env['skeen.patient.adjunto'].sudo().create({
adj_vals = {
'partner_id': patient.id,
'kind': kind,
'name': data.get('name') or 'archivo',
'file': file_b64,
'mimetype': data.get('mimetype') or '',
'notes': data.get('notes', ''),
})
}
if data.get('antes_despues') in ('sin_clasificar', 'antes', 'despues'):
adj_vals['antes_despues'] = data['antes_despues']
for key in ('visita_id', 'cita_id', 'servicio_id'):
if data.get(key):
adj_vals[key] = int(data[key])
adj = request.env['skeen.patient.adjunto'].sudo().create(adj_vals)
# Si clasifican la foto y no dieron servicio, heredarlo de la visita
if adj.visita_id and not adj.servicio_id:
adj.servicio_id = adj.visita_id.servicio_id
return json_response({'status': 'success', 'adjunto': self._patient_adjunto_to_dict(adj)}, 201)
except Exception as e:
return json_response({'status': 'error', 'message': str(e)}, 500)
@http.route('/skeen/frontend/v1/patients/adjuntos/<int:adj_id>', type='http', auth='none', methods=['PUT'], csrf=False)
@require_role('recepcion')
def update_patient_adjunto(self, adj_id, **kw):
"""Actualiza la clasificación antes/después (y contexto) de un adjunto."""
try:
adj = request.env['skeen.patient.adjunto'].sudo().browse(adj_id)
if not adj.exists():
return json_response({'status': 'error', 'message': 'Adjunto no encontrado'}, 404)
data = _parse_json_body()
vals = {}
if data.get('antes_despues') in ('sin_clasificar', 'antes', 'despues'):
vals['antes_despues'] = data['antes_despues']
for key in ('visita_id', 'cita_id', 'servicio_id'):
if key in data:
vals[key] = int(data[key]) if data.get(key) else None
if vals:
adj.write(vals)
if adj.visita_id and not adj.servicio_id:
adj.servicio_id = adj.visita_id.servicio_id
return json_response({'status': 'success', 'adjunto': self._patient_adjunto_to_dict(adj)})
except Exception as e:
return json_response({'status': 'error', 'message': str(e)}, 500)
@http.route('/skeen/frontend/v1/patients/adjuntos/<int:adj_id>', type='http', auth='none', methods=['DELETE'], csrf=False)
@require_role('recepcion')
def delete_patient_adjunto(self, adj_id, **kw):
@@ -2664,6 +2701,9 @@ class SkeenFrontendController(http.Controller):
if kw.get('date'):
domain.append(('date', '=', kw.get('date')))
closings = request.env['skeen.corte.caja'].sudo().search(domain, order='date desc', limit=100)
# Los pagos pueden llegar después de abrir la caja: refrescar
# los esperados de los cortes abiertos.
closings.filtered(lambda c: c.state == 'open').refresh_totals()
return json_response({
'status': 'success',
'cash_closings': [self._cash_closing_to_dict(c) for c in closings],
@@ -2693,9 +2733,24 @@ class SkeenFrontendController(http.Controller):
closing = request.env['skeen.corte.caja'].sudo().browse(closing_id)
if not closing.exists():
return json_response({'status': 'error', 'message': 'Corte no encontrado'}, 404)
closing.refresh_totals()
data = _parse_json_body()
if 'closing_cash' in data:
closing.write({'closing_cash': data['closing_cash']})
vals = {}
for key in ('closing_cash', 'counted_cash', 'counted_card',
'counted_transfer', 'counted_other'):
if key in data:
try:
vals[key] = float(data[key] or 0)
except (TypeError, ValueError):
return json_response({'status': 'error', 'message': f'Valor inválido: {key}'}, 400)
if 'notes' in data:
vals['notes'] = data.get('notes', '')
# Compatibilidad: si solo se envió el conteo, el cierre de efectivo
# registrado es el contado (difference del listado usa closing_cash).
if 'closing_cash' not in vals and 'counted_cash' in vals:
vals['closing_cash'] = vals['counted_cash']
if vals:
closing.write(vals)
closing.action_close()
return json_response({'status': 'success', 'cash_closing': self._cash_closing_to_dict(closing)})
except Exception as e:
@@ -2715,6 +2770,15 @@ class SkeenFrontendController(http.Controller):
'total_sales': c.total_sales,
'closing_cash': c.closing_cash,
'difference': c.difference,
'counted_cash': c.counted_cash,
'counted_card': c.counted_card,
'counted_transfer': c.counted_transfer,
'counted_other': c.counted_other,
'diff_cash': c.diff_cash,
'diff_card': c.diff_card,
'diff_transfer': c.diff_transfer,
'diff_other': c.diff_other,
'notes': c.notes or '',
'state': c.state,
}