diff --git a/api/app/routers/cobros.py b/api/app/routers/cobros.py index 675bf21..5c7890b 100644 --- a/api/app/routers/cobros.py +++ b/api/app/routers/cobros.py @@ -142,6 +142,7 @@ async def list_pagos_cobro( "rechazoMotivo": r["rechazoMotivo"], "ultimoRecordatorioAt": r["ultimoRecordatorioAt"].isoformat() if r["ultimoRecordatorioAt"] else None, "recordatoriosEnviados": r["recordatoriosEnviados"], + "vencidoNotificadoAt": r["vencidoNotificadoAt"].isoformat() if ("vencidoNotificadoAt" in r and r["vencidoNotificadoAt"]) else None, "nota": r["nota"], "programa": { "concepto": r["programa_concepto"], diff --git a/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql b/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql new file mode 100644 index 0000000..9f74d53 --- /dev/null +++ b/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql @@ -0,0 +1,3 @@ +-- Additive idempotency stamp for pago.vencido webhook emission +ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3); +CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 82459be..11f0cda 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -357,6 +357,9 @@ model PagoRecurrente { // aviso antes de COBROS_RECORDATORIO_DIAS; el envio manual lo ignora. ultimoRecordatorioAt DateTime? recordatoriosEnviados Int @default(0) + // Sello idempotente para el webhook pago.vencido: se escribe atomicamente la + // primera vez que el cobro se notifica como vencido (1 evento por cobro). + vencidoNotificadoAt DateTime? // Nota interna del admin (no la ve el cliente): forma de pago o abonos al // registrar un pago manual, o el motivo al anular un cobro. nota String? @@ -369,6 +372,7 @@ model PagoRecurrente { @@unique([programaId, fecha]) @@index([estado]) @@index([fecha]) + @@index([vencidoNotificadoAt]) } // Comprobante de pago subido por el cliente (imagen o PDF). El archivo vive en diff --git a/src/app/api/cobros/pagos/[id]/aprobar/route.ts b/src/app/api/cobros/pagos/[id]/aprobar/route.ts index fc722a1..5fa3cd2 100644 --- a/src/app/api/cobros/pagos/[id]/aprobar/route.ts +++ b/src/app/api/cobros/pagos/[id]/aprobar/route.ts @@ -23,7 +23,7 @@ export async function POST( where: { id }, include: { programa: { - include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true } } }, + include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true, telefono: true } } }, }, }, }); diff --git a/src/app/api/cobros/pagos/[id]/registrar/route.ts b/src/app/api/cobros/pagos/[id]/registrar/route.ts index a50d286..55d95aa 100644 --- a/src/app/api/cobros/pagos/[id]/registrar/route.ts +++ b/src/app/api/cobros/pagos/[id]/registrar/route.ts @@ -51,7 +51,7 @@ export async function POST( where: { id }, include: { programa: { - include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true } } }, + include: { cliente: { select: { id: true, nombre: true, empresa: true, email: true, telefono: true } } }, }, }, }); diff --git a/src/app/api/cotizaciones/[id]/route.ts b/src/app/api/cotizaciones/[id]/route.ts index 72f6e5a..b0cf5b1 100644 --- a/src/app/api/cotizaciones/[id]/route.ts +++ b/src/app/api/cotizaciones/[id]/route.ts @@ -10,7 +10,7 @@ import { requireActor, } from "@/lib/agent-auth"; import { registrarAuditoria } from "@/lib/audit"; -import { validarTransicionEstado } from "@/lib/aprobacion"; +import { appBaseUrl, validarTransicionEstado } from "@/lib/aprobacion"; import { emitirWebhook, type EventoWebhook } from "@/lib/webhooks"; import { evaluarRestriccionSoloAdmin } from "@/lib/solo-admin-core"; @@ -262,12 +262,18 @@ export async function PUT( void emitirWebhook(ev, { cotizacionId: updated.id, numero: updated.numero, + folio: updated.numero, + titulo: updated.proyecto, + proyecto: updated.proyecto, + moneda: updated.moneda, + url: `${appBaseUrl()}/cotizaciones/${updated.id}`, estado: updated.estado, cliente: { id: existing.cliente.id, nombre: existing.cliente.nombre, empresa: existing.cliente.empresa, email: existing.cliente.email, + telefono: existing.cliente.telefono, }, }); } diff --git a/src/lib/notificaciones.ts b/src/lib/notificaciones.ts index 3532600..82d74dc 100644 --- a/src/lib/notificaciones.ts +++ b/src/lib/notificaciones.ts @@ -19,6 +19,7 @@ import { } from "@/lib/cobros"; import type { PagoRecurrente } from "@/generated/prisma/client"; import { emitirWebhook } from "@/lib/webhooks"; +import { emitirPagosVencidosIdempotente } from "@/lib/pago-vencido-core"; // Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es // best-effort: un fallo de correo/push jamas revienta el flujo que lo llamo @@ -423,28 +424,49 @@ export async function enviarRecordatoriosPendientes( console.error("[notificaciones] fallo el recordatorio del cliente", clienteId, e); resultado.correo = "error"; } - // Emision best-effort del webhook pago.vencido sin alterar ni duplicar correos/push. - void emitirWebhook("pago.vencido", { - clienteId, - cliente: { - id: clienteId, - nombre: cliente.nombre, - empresa: cliente.empresa ?? null, - email: cliente.usuario?.email || cliente.email || null, - }, - totales: resultado.totales, - pagos: lista.map((p) => ({ - id: p.id, - programaId: p.programaId, - concepto: p.programa.concepto, - fecha: p.fecha.toISOString().slice(0, 10), - monto: p.monto, - moneda: p.programa.moneda, - estado: p.estado, - diasAtraso: diasDeAtraso(p.fecha, hoy), - })), - recordatorioEntregado: resultado.entregado, - }); + // Emision idempotente de pago.vencido: reclama atomicamente cada cobro sin + // vencidoNotificadoAt para emitir 1 solo evento por pago, nunca en cada + // corrida horaria del scheduler ni en reinicios del contenedor. + try { + const ahoraSello = new Date(); + await emitirPagosVencidosIdempotente( + { + clienteId, + cliente: { + id: clienteId, + nombre: cliente.nombre, + empresa: cliente.empresa ?? null, + email: cliente.usuario?.email || cliente.email || null, + telefono: cliente.telefono ?? null, + }, + pagos: lista.map((p) => ({ + id: p.id, + programaId: p.programaId, + concepto: p.programa.concepto, + fecha: p.fecha, + monto: p.monto, + moneda: p.programa.moneda, + estado: p.estado, + vencidoNotificadoAt: p.vencidoNotificadoAt, + })), + hoy, + ahora: ahoraSello, + recordatorioEntregado: resultado.entregado, + }, + { + reclamarPagoVencido: async (pagoId, fechaSello) => { + const claim = await prisma.pagoRecurrente.updateMany({ + where: { id: pagoId, vencidoNotificadoAt: null }, + data: { vencidoNotificadoAt: fechaSello }, + }); + return claim.count === 1; + }, + emitir: (evento, data) => emitirWebhook(evento, data), + } + ); + } catch (e) { + console.error("[notificaciones] fallo emision idempotente pago.vencido", clienteId, e); + } resultados.push(resultado); } diff --git a/src/lib/pago-vencido-core.ts b/src/lib/pago-vencido-core.ts new file mode 100644 index 0000000..9e6832b --- /dev/null +++ b/src/lib/pago-vencido-core.ts @@ -0,0 +1,125 @@ +import { diasDeAtraso } from "./cobros-fechas"; + +export interface PagoVencidoCandidato { + id: string; + programaId: string; + concepto: string; + fecha: Date; + monto: number; + moneda: string; + estado: string; + vencidoNotificadoAt: Date | null; +} + +export interface ClientePagoVencido { + id: string; + nombre: string; + empresa: string | null; + email: string | null; + telefono: string | null; +} + +export interface ParamsEmisionPagoVencido { + clienteId: string; + cliente: ClientePagoVencido; + pagos: PagoVencidoCandidato[]; + hoy: Date; + ahora?: Date; + recordatorioEntregado: boolean; +} + +export interface DepsEmisionPagoVencido { + /** + * Reclamo atomico en BD (ej. UPDATE ... WHERE id = $1 AND vencidoNotificadoAt IS NULL). + * Debe devolver true solo si esta ejecucion paso el campo de null a una fecha. + */ + reclamarPagoVencido: (pagoId: string, fechaSello: Date) => Promise; + emitir: (evento: "pago.vencido", payload: Record) => Promise; +} + +export interface ResultadoEmisionPagoVencido { + emitido: boolean; + emitidos: number; + pagoIds: string[]; + payload: Record | null; +} + +function sumarTotales(pagos: PagoVencidoCandidato[]): Record { + const totales: Record = {}; + for (const p of pagos) { + const moneda = p.moneda || "MXN"; + totales[moneda] = Number(((totales[moneda] ?? 0) + p.monto).toFixed(2)); + } + return totales; +} + +export function construirPayloadPagoVencido( + params: Pick< + ParamsEmisionPagoVencido, + "clienteId" | "cliente" | "hoy" | "recordatorioEntregado" + >, + reclamados: PagoVencidoCandidato[] +): Record { + return { + clienteId: params.clienteId, + cliente: { + id: params.cliente.id || params.clienteId, + nombre: params.cliente.nombre, + empresa: params.cliente.empresa ?? null, + email: params.cliente.email ?? null, + telefono: params.cliente.telefono ?? null, + }, + totales: sumarTotales(reclamados), + pagos: reclamados.map((p) => ({ + id: p.id, + programaId: p.programaId, + concepto: p.concepto, + fecha: p.fecha.toISOString().slice(0, 10), + monto: p.monto, + moneda: p.moneda, + estado: p.estado, + diasAtraso: diasDeAtraso(p.fecha, params.hoy), + })), + recordatorioEntregado: params.recordatorioEntregado, + }; +} + +/** + * Emite el webhook `pago.vencido` a lo sumo UNA vez por PagoRecurrente. + * Filtra cobros que ya tienen `vencidoNotificadoAt` y reclama atomicamente + * cada candidato antes de emitir, evitando duplicados entre corridas horarias, + * reinicios del contenedor, envios forzados o carreras concurrentes. + */ +export async function emitirPagosVencidosIdempotente( + params: ParamsEmisionPagoVencido, + deps: DepsEmisionPagoVencido +): Promise { + const candidatos = params.pagos.filter((p) => !p.vencidoNotificadoAt); + if (candidatos.length === 0) { + return { emitido: false, emitidos: 0, pagoIds: [], payload: null }; + } + + const fechaSello = params.ahora ?? new Date(); + const reclamados: PagoVencidoCandidato[] = []; + + for (const pago of candidatos) { + const ganado = await deps.reclamarPagoVencido(pago.id, fechaSello); + if (ganado) { + reclamados.push(pago); + } + } + + if (reclamados.length === 0) { + return { emitido: false, emitidos: 0, pagoIds: [], payload: null }; + } + + const payload = construirPayloadPagoVencido(params, reclamados); + await deps.emitir("pago.vencido", payload); + + return { + emitido: true, + emitidos: reclamados.length, + pagoIds: reclamados.map((p) => p.id), + payload, + }; +} diff --git a/tests/pago-vencido-idempotency.test.ts b/tests/pago-vencido-idempotency.test.ts new file mode 100644 index 0000000..25c6e6a --- /dev/null +++ b/tests/pago-vencido-idempotency.test.ts @@ -0,0 +1,207 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + emitirPagosVencidosIdempotente, + type ClientePagoVencido, + type PagoVencidoCandidato, +} from "../src/lib/pago-vencido-core"; + +function crearStoreSimulado(pagosIniciales: PagoVencidoCandidato[]) { + const filas = new Map(pagosIniciales.map((p) => [p.id, { ...p }])); + const emitidos: Array<{ evento: string; payload: Record }> = []; + + const deps = { + reclamarPagoVencido: async (pagoId: string, fechaSello: Date): Promise => { + const fila = filas.get(pagoId); + if (!fila || fila.vencidoNotificadoAt !== null) return false; + fila.vencidoNotificadoAt = fechaSello; + return true; + }, + emitir: async (evento: "pago.vencido", payload: Record) => { + emitidos.push({ evento, payload }); + }, + }; + + const listar = () => Array.from(filas.values()).map((p) => ({ ...p })); + return { filas, emitidos, deps, listar }; +} + +describe("Idempotencia de webhook pago.vencido", () => { + const clienteSinEmail: ClientePagoVencido = { + id: "cli_insta_001", + nombre: "Jose Saul Escobedo Sierra", + empresa: "Instituto Santiago Tapia", + email: null, + telefono: "+52 443 142 2031", + }; + + const hoy = new Date("2026-11-25T00:00:00.000Z"); + + it("emite exactamente 1 evento en la corrida 1 y 0 en corridas 2 y 3 (incluso sin email/push)", async () => { + const store = crearStoreSimulado([ + { + id: "pago_01", + programaId: "prog_01", + concepto: "Pago semanal", + fecha: new Date("2026-11-11T00:00:00.000Z"), + monto: 3000, + moneda: "MXN", + estado: "pendiente", + vencidoNotificadoAt: null, + }, + { + id: "pago_02", + programaId: "prog_01", + concepto: "Pago semanal", + fecha: new Date("2026-11-18T00:00:00.000Z"), + monto: 3000, + moneda: "MXN", + estado: "pendiente", + vencidoNotificadoAt: null, + }, + ]); + + // Corrida 1 (scheduler inicial) + const r1 = await emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: store.listar(), + hoy, + ahora: new Date("2026-11-25T16:00:00.000Z"), + recordatorioEntregado: false, + }, + store.deps + ); + assert.equal(r1.emitido, true); + assert.equal(r1.emitidos, 2); + assert.deepEqual(r1.pagoIds, ["pago_01", "pago_02"]); + assert.equal(store.emitidos.length, 1); + + const payload = store.emitidos[0].payload; + assert.equal(payload.clienteId, "cli_insta_001"); + assert.deepEqual(payload.cliente, { + id: "cli_insta_001", + nombre: "Jose Saul Escobedo Sierra", + empresa: "Instituto Santiago Tapia", + email: null, + telefono: "+52 443 142 2031", + }); + assert.deepEqual(payload.totales, { MXN: 6000 }); + + // Corrida 2 (60 minutos despues o reinicio del contenedor) + const r2 = await emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: store.listar(), + hoy, + ahora: new Date("2026-11-25T17:00:00.000Z"), + recordatorioEntregado: false, + }, + store.deps + ); + assert.equal(r2.emitido, false); + assert.equal(r2.emitidos, 0); + assert.equal(store.emitidos.length, 1); + + // Corrida 3 (recordatorio forzado manual) + const r3 = await emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: store.listar(), + hoy, + ahora: new Date("2026-11-25T18:00:00.000Z"), + recordatorioEntregado: true, + }, + store.deps + ); + assert.equal(r3.emitido, false); + assert.equal(r3.emitidos, 0); + assert.equal(store.emitidos.length, 1); + }); + + it("cuando vence un cobro nuevo adicional, emite solo el nuevo y no re-emite los ya sellados", async () => { + const store = crearStoreSimulado([ + { + id: "pago_viejo", + programaId: "prog_01", + concepto: "Pago semanal", + fecha: new Date("2026-11-18T00:00:00.000Z"), + monto: 3000, + moneda: "MXN", + estado: "pendiente", + vencidoNotificadoAt: new Date("2026-11-20T15:00:00.000Z"), + }, + { + id: "pago_nuevo", + programaId: "prog_01", + concepto: "Pago semanal", + fecha: new Date("2026-11-25T00:00:00.000Z"), + monto: 3000, + moneda: "MXN", + estado: "pendiente", + vencidoNotificadoAt: null, + }, + ]); + + const r = await emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: store.listar(), + hoy, + ahora: new Date("2026-11-25T16:00:00.000Z"), + recordatorioEntregado: false, + }, + store.deps + ); + assert.equal(r.emitido, true); + assert.deepEqual(r.pagoIds, ["pago_nuevo"]); + assert.equal(store.emitidos.length, 1); + assert.deepEqual(store.emitidos[0].payload.totales, { MXN: 3000 }); + }); + + it("resuelve carreras concurrentes reclamando atomicamente 1 sola emision", async () => { + const store = crearStoreSimulado([ + { + id: "pago_race", + programaId: "prog_01", + concepto: "Mensualidad", + fecha: new Date("2026-11-24T00:00:00.000Z"), + monto: 5000, + moneda: "MXN", + estado: "pendiente", + vencidoNotificadoAt: null, + }, + ]); + + const snapshot = store.listar(); + const [a, b] = await Promise.all([ + emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: snapshot, + hoy, + recordatorioEntregado: false, + }, + store.deps + ), + emitirPagosVencidosIdempotente( + { + clienteId: clienteSinEmail.id, + cliente: clienteSinEmail, + pagos: snapshot, + hoy, + recordatorioEntregado: false, + }, + store.deps + ), + ]); + + assert.equal(Number(a.emitido) + Number(b.emitido), 1); + assert.equal(store.emitidos.length, 1); + }); +});