// Utilidades PURAS de los cobros recurrentes: fechas de calendario, estados y // formatos. Sin prisma ni fs — SEGURO PARA COMPONENTES "use client" (los // componentes del navegador importan de aqui, NUNCA de @/lib/cobros, que si // arrastra la BD y rompe el build de Next). // // La logica que toca la BD (generarCobros) vive en @/lib/cobros, que re-exporta // todo lo de este archivo para el lado servidor. // // CONVENCION DE FECHAS: una fecha de cobro es una FECHA DE CALENDARIO en // America/Mexico_City, persistida como medianoche UTC de ese calendario // (Date.UTC(y, m-1, d)). Se escribe con parseFechaCalendario() y se muestra // con formatFechaCobro(). Asi "sabado" es sabado en Mexico aunque el servidor // este en UTC. import type { ProgramaPago } from "@/generated/prisma/client"; export const ZONA_HORARIA = "America/Mexico_City"; export const ESTADOS_PAGO = { PENDIENTE: "pendiente", // generado, sin comprobante EN_REVISION: "en_revision", // comprobante subido, esperando al admin VERIFICADO: "verificado", // admin acepto el comprobante o registro el pago a mano RECHAZADO: "rechazado", // admin rechazo (el archivo se borro; se puede volver a subir) ANULADO: "anulado", // admin lo dejo sin cargo (semana sin servicio, cortesia) } as const; export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO]; // Estados en los que el cliente todavia DEBE el cobro: nunca subio comprobante // o se lo rechazaron. en_revision no cuenta (ya pago, falta que el admin lo // valide). Es la base del saldo pendiente y de los recordatorios. export const ESTADOS_POR_PAGAR: EstadoPago[] = [ESTADOS_PAGO.PENDIENTE, ESTADOS_PAGO.RECHAZADO]; export function esPorPagar(estado: string): boolean { return (ESTADOS_POR_PAGAR as string[]).includes(estado); } // RECORDATORIOS. Cada cuantos dias el scheduler vuelve a avisar al cliente de // lo que sigue por pagar (0 = sin recordatorio automatico; el envio manual // desde /cobros funciona igual). Se lee en servidor de COBROS_RECORDATORIO_DIAS. export const RECORDATORIO_DIAS_DEFAULT = 3; // Hora local de Mexico a partir de la cual el scheduler puede enviarlos, para // no mandar correos de cobranza a la 1 a. m. cuando cambia el dia. export const HORA_RECORDATORIOS = 9; // "YYYY-MM-DD" (input de formularios) -> Date en medianoche UTC del calendario. export function parseFechaCalendario(iso: string): Date { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim()); if (!m) throw new Error(`Fecha invalida: ${iso} (se espera YYYY-MM-DD)`); return new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))); } // Date -> { y, m, d } usando las partes UTC (la fecha ya es calendario). export function aCalendario(date: Date): { y: number; m: number; d: number } { return { y: date.getUTCFullYear(), m: date.getUTCMonth() + 1, d: date.getUTCDate() }; } // Fecha de calendario en America/Mexico_City (UTC midnight) del instante dado. // Para timestamps reales (createdAt, ultimoRecordatorioAt), no para fechas de // cobro, que ya son calendario. export function calendarioDe(instante: Date): Date { const iso = new Intl.DateTimeFormat("en-CA", { timeZone: ZONA_HORARIA, year: "numeric", month: "2-digit", day: "2-digit", }).format(instante); // "YYYY-MM-DD" return parseFechaCalendario(iso); } // Hoy en America/Mexico_City como fecha de calendario (UTC midnight). export function hoyCalendario(): Date { return calendarioDe(new Date()); } // Hora (0-23) actual en America/Mexico_City. export function horaMexico(instante: Date = new Date()): number { const h = new Intl.DateTimeFormat("en-US", { timeZone: ZONA_HORARIA, hour: "numeric", hourCycle: "h23", }).format(instante); return Number(h); } // Instante que representa un dia de pago (fecha de calendario MX): mediodia en // Mexico (18:00 UTC; sin horario de verano desde 2022). Para verificadoAt de // los pagos registrados a mano: a medianoche UTC se veria como el dia anterior // al pasarlo por calendarioDe(). export function instanteDePago(fecha: Date): Date { const { y, m, d } = aCalendario(fecha); return new Date(Date.UTC(y, m - 1, d, 18)); } export function sumarDias(d: Date, dias: number): Date { return new Date(d.getTime() + dias * 86400000); } // Dias completos entre una fecha de cobro y hoy MX (0 si vence hoy o despues). export function diasDeAtraso(fecha: Date, hoy: Date = hoyCalendario()): number { return Math.max(0, Math.round((hoy.getTime() - fecha.getTime()) / 86400000)); } const fmtFecha = new Intl.DateTimeFormat("es-MX", { weekday: "long", day: "2-digit", month: "long", year: "numeric", timeZone: "UTC", // la fecha YA es calendario en UTC; no convertir zona }); // "Sabado, 04 de julio de 2026" para mostrar en el panel/PDF/correo. export function formatFechaCobro(date: Date): string { const s = fmtFecha.format(date); return s.charAt(0).toUpperCase() + s.slice(1); } // Monto en su moneda: "$4,500" / "$4,500.50" / "USD 25". Sin decimales si es // entero, como formatCurrency; a diferencia de este, respeta USD. export function formatMonto(monto: number, moneda: string = "MXN"): string { return new Intl.NumberFormat("es-MX", { style: "currency", currency: moneda || "MXN", minimumFractionDigits: Number.isInteger(monto) ? 0 : 2, maximumFractionDigits: 2, }).format(monto); } // Totales por moneda en una linea: "$2,250" o "$1,500 + USD 100". export function formatTotales(totales: Record): string { const partes = Object.entries(totales).map(([moneda, total]) => formatMonto(total, moneda)); return partes.length ? partes.join(" + ") : "$0"; } const fmtDiaSemana = new Intl.DateTimeFormat("es-MX", { weekday: "short", timeZone: "UTC" }); const fmtMesCorto = new Intl.DateTimeFormat("es-MX", { month: "short", timeZone: "UTC" }); // "sáb 31 oct" (agrega el año si no es el de `hoy`). Para listas de cobros. export function formatFechaBreve(date: Date, hoy: Date = hoyCalendario()): string { const dia = fmtDiaSemana.format(date).replace(".", ""); const mes = fmtMesCorto.format(date).replace(".", ""); const anio = date.getUTCFullYear() !== hoy.getUTCFullYear() ? ` ${date.getUTCFullYear()}` : ""; return `${dia} ${date.getUTCDate()} ${mes}${anio}`; } // Dias de `hoy` a `fecha` (negativo si ya paso). Ambas son fechas de calendario. export function diasHasta(fecha: Date, hoy: Date = hoyCalendario()): number { return Math.round((fecha.getTime() - hoy.getTime()) / 86400000); } // "vence hoy" / "mañana" / "en 5 días" / "hace 1 día" / "hace 12 días". export function describirVencimiento(fecha: Date, hoy: Date = hoyCalendario()): string { const d = diasHasta(fecha, hoy); if (d === 0) return "vence hoy"; if (d === 1) return "mañana"; if (d > 1) return `en ${d} días`; return d === -1 ? "hace 1 día" : `hace ${-d} días`; } // Version corta: "04/07/2026". export function formatFechaCorta(date: Date): string { const { y, m, d } = aCalendario(date); return `${String(d).padStart(2, "0")}/${String(m).padStart(2, "0")}/${y}`; } // Todas las fechas de periodo de un programa desde fechaInicio hasta `hasta` // (inclusive), respetando fechaFin si existe. Cadena: // semanal -> diaSemana (0=dom..6=sab; si no viene, el mismo dia que fechaInicio) // quincenal -> dias 1 y 15 de cada mes // mensual -> diaMes (se recorta al ultimo dia del mes si no existe) export function fechasPeriodo( programa: Pick, hasta: Date ): Date[] { const inicio = aCalendario(programa.fechaInicio); const inicioD = new Date(Date.UTC(inicio.y, inicio.m - 1, inicio.d)); const fin = programa.fechaFin ? aCalendario(programa.fechaFin) : null; const finD = fin ? new Date(Date.UTC(fin.y, fin.m - 1, fin.d)) : null; const limite = finD && finD < hasta ? finD : hasta; if (inicioD > limite) return []; const out: Date[] = []; if (programa.frecuencia === "semanal") { const dia = programa.diaSemana ?? inicioD.getUTCDay(); let d = new Date(inicioD); let guard = 0; while (d.getUTCDay() !== dia && guard++ < 7) d = sumarDias(d, 1); while (d <= limite) { out.push(d); d = sumarDias(d, 7); } } else if (programa.frecuencia === "quincenal") { let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1)); while (mes <= limite) { for (const dia of [1, 15]) { const d = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), dia)); if (d >= inicioD && d <= limite) out.push(d); } mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1)); } } else { // mensual const diaMes = programa.diaMes ?? 1; let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1)); while (mes <= limite) { const ultimoDia = new Date( Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 0) ).getUTCDate(); const d = new Date( Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), Math.min(diaMes, ultimoDia)) ); if (d >= inicioD && d <= limite) out.push(d); mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1)); } } return out; } // Proxima fecha de cobro >= `desde` (por defecto hoy MX) para el panel admin. export function proximaFecha( programa: Pick, desde: Date = hoyCalendario() ): Date | null { const ventana = fechasPeriodo(programa, sumarDias(desde, 366)); return ventana.find((f) => f >= desde) ?? null; }