Cobros recurrentes: panel de cliente, comprobantes verificados y notificaciones
- Panel de cliente con acceso propio (role=cliente): resumen, cotizaciones con descarga PDF y guia de pagos recurrentes con subida de comprobante (imagen->WebP o PDF). - Módulo admin /cobros: programas de pago (semanal/quincenal/mensual), generación idempotente manual y automatica cada hora (scheduler en instrumentation, zona America/Mexico_City), revisión de comprobantes con aprobar/rechazar (el rechazo borra el archivo del servidor y permite re-subir). - Cuentas de cliente creadas/rotadas/revocadas desde la página de clientes. - Notificaciones: servicio SMTP configurable por env (se omite con aviso si no hay credenciales) y Web Push con VAPID + service worker. - Separación de roles en middleware (cliente solo ve /cliente, staff no entra al panel de cliente; PDF y comprobantes son rutas compartidas con validación de pertenencia). - Producción: volumen uploads_data en ambos compose, env vars documentadas en .env.example, migración 20261020000000.
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import { ProgramasTabla } from "./ProgramasTabla";
|
||||
import { PagosTabla } from "./PagosTabla";
|
||||
import type { ProgramaRow, ClienteOpt, PagoRow } from "./types";
|
||||
|
||||
// Frecuencia legible en la tabla de programas.
|
||||
export function frecuenciaLegible(p: {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
}): string {
|
||||
const dias = [
|
||||
"domingo",
|
||||
"lunes",
|
||||
"martes",
|
||||
"miercoles",
|
||||
"jueves",
|
||||
"viernes",
|
||||
"sabado",
|
||||
];
|
||||
if (p.frecuencia === "semanal") {
|
||||
const d = p.diaSemana ?? 0;
|
||||
return `Cada ${dias[d]}`;
|
||||
}
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada dia ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
export function CobrosClient({
|
||||
programas,
|
||||
clientes,
|
||||
pagosIniciales,
|
||||
}: {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
pagosIniciales: PagoRow[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const showConfirm = useConfirm();
|
||||
const showPrompt = usePrompt();
|
||||
const toast = useToast();
|
||||
|
||||
// El servidor ya dejo cargado el filtro por defecto (en_revision); el effect
|
||||
// solo vuelve a consultar cuando el usuario cambia un filtro.
|
||||
const cargadoInicial = useRef(false);
|
||||
const [pagos, setPagos] = useState<PagoRow[]>(pagosIniciales);
|
||||
const [cargandoPagos, setCargandoPagos] = useState(false);
|
||||
const [estadoFiltro, setEstadoFiltro] = useState("en_revision");
|
||||
const [clienteFiltro, setClienteFiltro] = useState("");
|
||||
const [desdeFiltro, setDesdeFiltro] = useState("");
|
||||
const [hastaFiltro, setHastaFiltro] = useState("");
|
||||
|
||||
const cargarPagos = useCallback(async () => {
|
||||
setCargandoPagos(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (estadoFiltro) params.set("estado", estadoFiltro);
|
||||
if (clienteFiltro) params.set("clienteId", clienteFiltro);
|
||||
if (desdeFiltro) params.set("desde", desdeFiltro);
|
||||
if (hastaFiltro) params.set("hasta", hastaFiltro);
|
||||
const res = await fetch(`/api/cobros/pagos?${params.toString()}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setPagos(Array.isArray(data) ? data : []);
|
||||
}
|
||||
} catch {
|
||||
// silencioso: la tabla queda vacia
|
||||
} finally {
|
||||
setCargandoPagos(false);
|
||||
}
|
||||
}, [estadoFiltro, clienteFiltro, desdeFiltro, hastaFiltro]);
|
||||
|
||||
useEffect(() => {
|
||||
// Evita el render-inicial: el servidor ya dejo los pagos del filtro por
|
||||
// defecto. Solo se consulta cuando cambia un filtro.
|
||||
if (!cargadoInicial.current) {
|
||||
cargadoInicial.current = true;
|
||||
return;
|
||||
}
|
||||
cargarPagos();
|
||||
}, [cargarPagos]);
|
||||
|
||||
const generarAhora = async () => {
|
||||
const ok = await showConfirm({
|
||||
title: "Generar cobros",
|
||||
message:
|
||||
"Se generaran los cobros pendientes de todos los programas activos hasta hoy. Continuar?",
|
||||
confirmText: "Generar",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch("/api/cobros/generar", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al generar cobros", "error");
|
||||
return;
|
||||
}
|
||||
const n = data.generados ?? 0;
|
||||
toast(
|
||||
n > 0 ? `Se generaron ${n} cobros` : "No habia cobros pendientes",
|
||||
"success"
|
||||
);
|
||||
cargarPagos();
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActivo = async (p: ProgramaRow) => {
|
||||
const activar = !p.activo;
|
||||
const ok = await showConfirm({
|
||||
title: activar ? "Activar programa" : "Desactivar programa",
|
||||
message: activar
|
||||
? `Activar el programa "${p.concepto}"? Se generaran cobros en sus proximos periodos.`
|
||||
: `Desactivar el programa "${p.concepto}"? No se generaran mas cobros, pero los existentes se conservan.`,
|
||||
confirmText: activar ? "Activar" : "Desactivar",
|
||||
danger: !activar,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/programas/${p.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ activo: activar }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al actualizar", "error");
|
||||
return;
|
||||
}
|
||||
toast(activar ? "Programa activado" : "Programa desactivado", "success");
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const aprobar = async (pago: PagoRow) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Aprobar comprobante",
|
||||
message: `Marcar el cobro del ${formatFechaCorta(new Date(pago.fecha))} como verificado?`,
|
||||
confirmText: "Aprobar",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/aprobar`, {
|
||||
method: "POST",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al aprobar", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro verificado", "success");
|
||||
cargarPagos();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const rechazar = async (pago: PagoRow) => {
|
||||
const motivo = await showPrompt({
|
||||
title: "Rechazar comprobante",
|
||||
label: "Motivo del rechazo (opcional)",
|
||||
placeholder: "Ej. ilegible, monto incorrecto...",
|
||||
confirmText: "Rechazar",
|
||||
});
|
||||
if (motivo === null) return; // cancelado
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/rechazar`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ motivo: motivo.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al rechazar", "error");
|
||||
return;
|
||||
}
|
||||
toast("Comprobante rechazado", "success");
|
||||
cargarPagos();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-10">
|
||||
<section>
|
||||
<ProgramasTabla
|
||||
programas={programas}
|
||||
clientes={clientes}
|
||||
onToggleActivo={toggleActivo}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||
<h2 className="text-lg font-semibold">Cobros generados</h2>
|
||||
<button
|
||||
onClick={generarAhora}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90"
|
||||
>
|
||||
Generar cobros ahora
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-3 mb-4">
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Estado</label>
|
||||
<select
|
||||
value={estadoFiltro}
|
||||
onChange={(e) => setEstadoFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="pendiente">Pendiente</option>
|
||||
<option value="en_revision">En revision</option>
|
||||
<option value="verificado">Verificado</option>
|
||||
<option value="rechazado">Rechazado</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Cliente</label>
|
||||
<select
|
||||
value={clienteFiltro}
|
||||
onChange={(e) => setClienteFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{clientes.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Desde</label>
|
||||
<input
|
||||
type="date"
|
||||
value={desdeFiltro}
|
||||
onChange={(e) => setDesdeFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Hasta</label>
|
||||
<input
|
||||
type="date"
|
||||
value={hastaFiltro}
|
||||
onChange={(e) => setHastaFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PagosTabla
|
||||
pagos={pagos}
|
||||
cargando={cargandoPagos}
|
||||
onAprobar={aprobar}
|
||||
onRechazar={rechazar}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { ESTADOS_PAGO } from "@/lib/cobros-fechas";
|
||||
|
||||
// Badges de estado de cobro (colores locales, no reutiliza EstadoBadge que es
|
||||
// para cotizaciones). pendiente=amber, en_revision=azul, verificado=verde,
|
||||
// rechazado=rojizo.
|
||||
const ESTILOS: Record<string, { cls: string; label: string }> = {
|
||||
[ESTADOS_PAGO.PENDIENTE]: {
|
||||
cls: "bg-amber-100 text-amber-800",
|
||||
label: "Pendiente",
|
||||
},
|
||||
[ESTADOS_PAGO.EN_REVISION]: {
|
||||
cls: "bg-blue-100 text-blue-800",
|
||||
label: "En revision",
|
||||
},
|
||||
[ESTADOS_PAGO.VERIFICADO]: {
|
||||
cls: "bg-green-100 text-green-800",
|
||||
label: "Verificado",
|
||||
},
|
||||
[ESTADOS_PAGO.RECHAZADO]: {
|
||||
cls: "bg-red-100 text-red-800",
|
||||
label: "Rechazado",
|
||||
},
|
||||
};
|
||||
|
||||
export function EstadoPagoBadge({ estado }: { estado: string }) {
|
||||
const s = ESTILOS[estado] ?? {
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
label: estado,
|
||||
};
|
||||
return (
|
||||
<span
|
||||
className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${s.cls}`}
|
||||
>
|
||||
{s.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { Check, X, FileText } from "lucide-react";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import { EstadoPagoBadge } from "./EstadoPagoBadge";
|
||||
import type { PagoRow } from "./types";
|
||||
|
||||
export function PagosTabla({
|
||||
pagos,
|
||||
cargando,
|
||||
onAprobar,
|
||||
onRechazar,
|
||||
}: {
|
||||
pagos: PagoRow[];
|
||||
cargando: boolean;
|
||||
onAprobar: (p: PagoRow) => void;
|
||||
onRechazar: (p: PagoRow) => void;
|
||||
}) {
|
||||
if (cargando) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<p className="text-muted">Cargando cobros...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (pagos.length === 0) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">No hay cobros</h3>
|
||||
<p className="text-muted">
|
||||
Genera cobros con el boton o ajusta los filtros
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Fecha</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Comprobante</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pagos.map((p) => (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3">{formatFechaCorta(new Date(p.fecha))}</td>
|
||||
<td className="px-5 py-3">{p.programa.concepto}</td>
|
||||
<td className="px-5 py-3">{p.programa.cliente.nombre}</td>
|
||||
<td className="px-5 py-3 text-right">{formatCurrency(p.monto)}</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<EstadoPagoBadge estado={p.estado} />
|
||||
{p.estado === "rechazado" && p.rechazoMotivo && (
|
||||
<div className="text-xs text-muted mt-1">{p.rechazoMotivo}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
{p.comprobante ? (
|
||||
<a
|
||||
href={`/api/comprobantes/${p.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
>
|
||||
<FileText className="w-3 h-3" />
|
||||
Ver
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.estado === "en_revision" ? (
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => onAprobar(p)}
|
||||
className="text-xs text-success hover:underline flex items-center gap-1"
|
||||
>
|
||||
<Check className="w-3 h-3" />
|
||||
Aprobar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onRechazar(p)}
|
||||
className="text-xs text-danger hover:underline flex items-center gap-1"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
Rechazar
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Pencil, Power, Plus } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
||||
import type { ProgramaRow, ClienteOpt } from "./types";
|
||||
|
||||
const DIAS = [
|
||||
"Domingo",
|
||||
"Lunes",
|
||||
"Martes",
|
||||
"Miercoles",
|
||||
"Jueves",
|
||||
"Viernes",
|
||||
"Sabado",
|
||||
];
|
||||
|
||||
function frecuenciaTexto(p: {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
}): string {
|
||||
if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`;
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada dia ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
function EstadoProgramaBadge({ activo }: { activo: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
activo ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-700"
|
||||
}`}
|
||||
>
|
||||
{activo ? "Activo" : "Inactivo"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
type FormEstado = {
|
||||
concepto: string;
|
||||
monto: string;
|
||||
frecuencia: string;
|
||||
diaSemana: string;
|
||||
diaMes: string;
|
||||
fechaInicio: string;
|
||||
fechaFin: string;
|
||||
};
|
||||
|
||||
type DialogoState = null | "nuevo" | ProgramaRow;
|
||||
|
||||
const FORM_VACIO: FormEstado = {
|
||||
concepto: "",
|
||||
monto: "",
|
||||
frecuencia: "mensual",
|
||||
diaSemana: "1",
|
||||
diaMes: "1",
|
||||
fechaInicio: "",
|
||||
fechaFin: "",
|
||||
};
|
||||
|
||||
export function ProgramasTabla({
|
||||
programas,
|
||||
clientes,
|
||||
onToggleActivo,
|
||||
}: {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
onToggleActivo: (p: ProgramaRow) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [dialogo, setDialogo] = useState<DialogoState>(null);
|
||||
const [clienteId, setClienteId] = useState("");
|
||||
const [form, setForm] = useState<FormEstado>(FORM_VACIO);
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const abrirNuevo = () => {
|
||||
setClienteId(clientes[0]?.id ?? "");
|
||||
setForm(FORM_VACIO);
|
||||
setDialogo("nuevo");
|
||||
};
|
||||
|
||||
const abrirEditar = (p: ProgramaRow) => {
|
||||
setClienteId(p.cliente.id);
|
||||
setForm({
|
||||
concepto: p.concepto,
|
||||
monto: String(p.monto),
|
||||
frecuencia: p.frecuencia,
|
||||
diaSemana: String(p.diaSemana ?? 0),
|
||||
diaMes: String(p.diaMes ?? 1),
|
||||
fechaInicio: p.fechaInicio.slice(0, 10),
|
||||
fechaFin: p.fechaFin ? p.fechaFin.slice(0, 10) : "",
|
||||
});
|
||||
setDialogo(p);
|
||||
};
|
||||
|
||||
const set = (k: keyof FormEstado, v: string) =>
|
||||
setForm((f) => ({ ...f, [k]: v }));
|
||||
|
||||
const guardar = async () => {
|
||||
if (!form.concepto.trim()) {
|
||||
toast("El concepto es requerido", "error");
|
||||
return;
|
||||
}
|
||||
const monto = parseFloat(form.monto);
|
||||
if (!form.monto || isNaN(monto) || monto <= 0) {
|
||||
toast("El monto debe ser mayor a 0", "error");
|
||||
return;
|
||||
}
|
||||
if (!form.fechaInicio) {
|
||||
toast("La fecha de inicio es requerida", "error");
|
||||
return;
|
||||
}
|
||||
if (dialogo === "nuevo" && !clienteId) {
|
||||
toast("Selecciona un cliente", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
concepto: form.concepto.trim(),
|
||||
monto,
|
||||
frecuencia: form.frecuencia,
|
||||
fechaInicio: form.fechaInicio,
|
||||
};
|
||||
if (form.frecuencia === "semanal") payload.diaSemana = parseInt(form.diaSemana, 10);
|
||||
if (form.frecuencia === "mensual") payload.diaMes = parseInt(form.diaMes, 10);
|
||||
if (form.fechaFin) payload.fechaFin = form.fechaFin;
|
||||
|
||||
setGuardando(true);
|
||||
try {
|
||||
// El handler solo es invocado desde el dialogo abierto (dialogo != null).
|
||||
const actual = dialogo as NonNullable<DialogoState>;
|
||||
const esNuevo = actual === "nuevo";
|
||||
const url = esNuevo
|
||||
? "/api/cobros/programas"
|
||||
: `/api/cobros/programas/${actual.id}`;
|
||||
const method = esNuevo ? "POST" : "PATCH";
|
||||
const body = esNuevo ? { ...payload, clienteId } : payload;
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al guardar", "error");
|
||||
return;
|
||||
}
|
||||
toast(esNuevo ? "Programa creado" : "Programa actualizado", "success");
|
||||
setDialogo(null);
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast("Error de conexion", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Programas de pago</h2>
|
||||
<button
|
||||
onClick={abrirNuevo}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nuevo programa
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{programas.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">No hay programas de pago</h3>
|
||||
<p className="text-muted">
|
||||
Crea un programa para empezar a generar cobros recurrentes
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Frecuencia</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Proximo cobro</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{programas.map((p) => (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3 font-medium">{p.concepto}</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{p.cliente.nombre}</div>
|
||||
{p.cliente.empresa && (
|
||||
<div className="text-xs text-muted">{p.cliente.empresa}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right">{formatCurrency(p.monto)}</td>
|
||||
<td className="px-5 py-3">{frecuenciaTexto(p)}</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.proximaFecha
|
||||
? formatFechaCorta(new Date(p.proximaFecha))
|
||||
: "—"}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<EstadoProgramaBadge activo={p.activo} />
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => abrirEditar(p)}
|
||||
className="text-xs text-primary hover:underline flex items-center gap-1"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
Editar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onToggleActivo(p)}
|
||||
className={`text-xs hover:underline flex items-center gap-1 ${
|
||||
p.activo ? "text-danger" : "text-success"
|
||||
}`}
|
||||
>
|
||||
<Power className="w-3 h-3" />
|
||||
{p.activo ? "Desactivar" : "Activar"}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dialogo && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={() => setDialogo(null)}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-xl bg-card-bg border border-border shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="px-5 py-4 border-b border-border font-semibold">
|
||||
{dialogo === "nuevo" ? "Nuevo programa" : "Editar programa"}
|
||||
</div>
|
||||
<div className="p-5 space-y-3">
|
||||
{dialogo === "nuevo" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Cliente</label>
|
||||
<select
|
||||
value={clienteId}
|
||||
onChange={(e) => setClienteId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
{clientes.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
{c.empresa ? ` — ${c.empresa}` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Concepto</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.concepto}
|
||||
onChange={(e) => set("concepto", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
placeholder="Ej. Gestion de publicidad"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Monto</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={form.monto}
|
||||
onChange={(e) => set("monto", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Frecuencia</label>
|
||||
<select
|
||||
value={form.frecuencia}
|
||||
onChange={(e) => set("frecuencia", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="semanal">Semanal</option>
|
||||
<option value="quincenal">Quincenal</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
{form.frecuencia === "semanal" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Dia de la semana</label>
|
||||
<select
|
||||
value={form.diaSemana}
|
||||
onChange={(e) => set("diaSemana", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
{DIAS.map((d, i) => (
|
||||
<option key={i} value={String(i)}>
|
||||
{d}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{form.frecuencia === "mensual" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Dia del mes</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="31"
|
||||
value={form.diaMes}
|
||||
onChange={(e) => set("diaMes", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Fecha de inicio</label>
|
||||
<input
|
||||
type="date"
|
||||
value={form.fechaInicio}
|
||||
onChange={(e) => set("fechaInicio", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">
|
||||
Fecha de fin (opcional)
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={form.fechaFin}
|
||||
onChange={(e) => set("fechaFin", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-2">
|
||||
<button
|
||||
onClick={() => setDialogo(null)}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={guardar}
|
||||
disabled={guardando}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{guardando ? "Guardando..." : "Guardar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { proximaFecha } from "@/lib/cobros";
|
||||
import { CobrosClient } from "./CobrosClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Serializa los datos de la BD a formas planas (fechas -> ISO) para que el
|
||||
// componente cliente no dependa de tipos Prisma ni de Date no-serializable.
|
||||
type ProgramaConCliente = {
|
||||
id: string;
|
||||
concepto: string;
|
||||
monto: number;
|
||||
moneda: string;
|
||||
frecuencia: string;
|
||||
diaSemana: number | null;
|
||||
diaMes: number | null;
|
||||
activo: boolean;
|
||||
fechaInicio: Date;
|
||||
fechaFin: Date | null;
|
||||
cliente: { id: string; nombre: string; empresa: string | null };
|
||||
_count: { pagos: number };
|
||||
};
|
||||
|
||||
export default async function CobrosPage() {
|
||||
const [programas, clientes, pagosIniciales] = await Promise.all([
|
||||
prisma.programaPago.findMany({
|
||||
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
||||
include: {
|
||||
cliente: { select: { id: true, nombre: true, empresa: true } },
|
||||
_count: { select: { pagos: true } },
|
||||
},
|
||||
}),
|
||||
prisma.cliente.findMany({
|
||||
orderBy: { nombre: "asc" },
|
||||
select: { id: true, nombre: true, empresa: true },
|
||||
}),
|
||||
// Cobros en revision (filtro por defecto de la tabla) para render inicial.
|
||||
prisma.pagoRecurrente.findMany({
|
||||
where: { estado: "en_revision" },
|
||||
orderBy: { fecha: "desc" },
|
||||
include: {
|
||||
programa: {
|
||||
select: {
|
||||
concepto: true,
|
||||
moneda: true,
|
||||
cliente: { select: { id: true, nombre: true, empresa: true } },
|
||||
},
|
||||
},
|
||||
comprobante: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const programasData = (programas as ProgramaConCliente[]).map((p) => {
|
||||
const prox = proximaFecha(p);
|
||||
return {
|
||||
id: p.id,
|
||||
concepto: p.concepto,
|
||||
monto: p.monto,
|
||||
moneda: p.moneda,
|
||||
frecuencia: p.frecuencia,
|
||||
diaSemana: p.diaSemana,
|
||||
diaMes: p.diaMes,
|
||||
activo: p.activo,
|
||||
fechaInicio: p.fechaInicio.toISOString(),
|
||||
fechaFin: p.fechaFin ? p.fechaFin.toISOString() : null,
|
||||
cliente: p.cliente,
|
||||
pagosCount: p._count.pagos,
|
||||
proximaFecha: prox ? prox.toISOString() : null,
|
||||
};
|
||||
});
|
||||
|
||||
const clientesData = clientes.map((c) => ({
|
||||
id: c.id,
|
||||
nombre: c.nombre,
|
||||
empresa: c.empresa,
|
||||
}));
|
||||
|
||||
const pagosData = pagosIniciales.map((p) => ({
|
||||
id: p.id,
|
||||
fecha: p.fecha.toISOString(),
|
||||
monto: p.monto,
|
||||
estado: p.estado,
|
||||
rechazoMotivo: p.rechazoMotivo,
|
||||
programa: {
|
||||
concepto: p.programa.concepto,
|
||||
moneda: p.programa.moneda,
|
||||
cliente: p.programa.cliente,
|
||||
},
|
||||
comprobante: p.comprobante
|
||||
? {
|
||||
id: p.comprobante.id,
|
||||
archivoNombre: p.comprobante.archivoNombre,
|
||||
mime: p.comprobante.mime,
|
||||
tamano: p.comprobante.tamano,
|
||||
subidoAt: p.comprobante.subidoAt.toISOString(),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold">Cobros recurrentes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Programa cobros periodicos y revisa los comprobantes de tus clientes
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CobrosClient
|
||||
programas={programasData}
|
||||
clientes={clientesData}
|
||||
pagosIniciales={pagosData}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Tipos serializados que consume el cliente de la pagina /cobros.
|
||||
|
||||
export type ClienteOpt = {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
};
|
||||
|
||||
export type ProgramaRow = {
|
||||
id: string;
|
||||
concepto: string;
|
||||
monto: number;
|
||||
moneda: string;
|
||||
frecuencia: string;
|
||||
diaSemana: number | null;
|
||||
diaMes: number | null;
|
||||
activo: boolean;
|
||||
fechaInicio: string;
|
||||
fechaFin: string | null;
|
||||
cliente: ClienteOpt;
|
||||
pagosCount: number;
|
||||
proximaFecha: string | null;
|
||||
};
|
||||
|
||||
export type ComprobanteMeta = {
|
||||
id: string;
|
||||
archivoNombre: string;
|
||||
mime: string;
|
||||
tamano: number;
|
||||
subidoAt: string;
|
||||
};
|
||||
|
||||
export type PagoRow = {
|
||||
id: string;
|
||||
fecha: string;
|
||||
monto: number;
|
||||
estado: string;
|
||||
rechazoMotivo: string | null;
|
||||
programa: {
|
||||
concepto: string;
|
||||
moneda: string;
|
||||
cliente: { id: string; nombre: string; empresa: string | null };
|
||||
};
|
||||
comprobante: ComprobanteMeta | null;
|
||||
};
|
||||
Reference in New Issue
Block a user