import { prisma } from "@/lib/db"; import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators"; import { ESTADOS_PAGO, ESTADOS_POR_PAGAR, hoyCalendario, proximaFecha, totalesPorMoneda, } from "@/lib/cobros"; // Resumen del panel de cliente. Compartido entre GET /api/cliente/resumen y la // pagina de inicio (/cliente) para que ambas caras cuenten exactamente lo mismo. export interface ResumenCotizacion { id: string; numero: string; proyecto: string; fecha: Date; estado: string; esDoble: boolean; incluirIva: boolean; totales: ReturnType; totalesOpciones?: { "1": ReturnType; "2": ReturnType; }; } export interface ResumenCliente { cliente: { nombre: string; empresa: string | null }; cotizacionesActivas: number; cotizaciones: ResumenCotizacion[]; pagos: { // Cobros por pagar (pendientes o con comprobante rechazado) y su total // por moneda. pendientes: number; saldoPendiente: Record; // Fecha del cobro por pagar mas antiguo (null si no debe nada). masAntiguo: Date | null; enRevision: number; verificadosMes: number; proximos: Array<{ fecha: Date; monto: number; moneda: string; concepto: string }>; }; } export async function obtenerResumenCliente(clienteId: string): Promise { const cliente = await prisma.cliente.findUnique({ where: { id: clienteId }, select: { nombre: true, empresa: true }, }); if (!cliente) return null; const hoy = hoyCalendario(); const inicioMes = new Date(Date.UTC(hoy.getUTCFullYear(), hoy.getUTCMonth(), 1)); const [cotizacionesActivas, cotizacionesBrutas, porPagar, enRevision, verificadosMes, programas] = await Promise.all([ prisma.cotizacion.count({ where: { clienteId, estado: { not: "rechazada" } }, }), prisma.cotizacion.findMany({ where: { clienteId }, orderBy: { fecha: "desc" }, take: 5, select: { id: true, numero: true, proyecto: true, fecha: true, estado: true, esDoble: true, incluirIva: true, servicios: { select: { tipoPago: true, precio: true, seleccionado: true, opcion: true }, }, }, }), prisma.pagoRecurrente.findMany({ where: { estado: { in: ESTADOS_POR_PAGAR }, programa: { clienteId } }, orderBy: { fecha: "asc" }, select: { fecha: true, monto: true, programa: { select: { moneda: true } } }, }), prisma.pagoRecurrente.count({ where: { estado: ESTADOS_PAGO.EN_REVISION, programa: { clienteId } }, }), prisma.pagoRecurrente.count({ where: { estado: ESTADOS_PAGO.VERIFICADO, verificadoAt: { gte: inicioMes }, programa: { clienteId }, }, }), prisma.programaPago.findMany({ where: { clienteId, activo: true } }), ]); const cotizaciones: ResumenCotizacion[] = cotizacionesBrutas.map((c) => { const totales = calcularTotalesCotizacion(c.servicios, { incluirIva: c.incluirIva }); return { id: c.id, numero: c.numero, proyecto: c.proyecto, fecha: c.fecha, estado: c.estado, esDoble: c.esDoble, incluirIva: c.incluirIva, totales, ...(c.esDoble ? { totalesOpciones: { "1": calcularTotalesOpcion(c.servicios, "1"), "2": calcularTotalesOpcion(c.servicios, "2"), }, } : {}), }; }); const proximos = programas .map((p) => { const fecha = proximaFecha(p); return fecha ? { fecha, monto: p.monto, moneda: p.moneda, concepto: p.concepto } : null; }) .filter((x): x is { fecha: Date; monto: number; moneda: string; concepto: string } => x !== null) .sort((a, b) => a.fecha.getTime() - b.fecha.getTime()) .slice(0, 3); return { cliente, cotizacionesActivas, cotizaciones, pagos: { pendientes: porPagar.length, saldoPendiente: totalesPorMoneda(porPagar), masAntiguo: porPagar[0]?.fecha ?? null, enRevision, verificadosMes, proximos, }, }; }