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:
urieljareth
2026-10-21 12:01:56 -06:00
parent 3a1eaf6e5b
commit 6d2143e1c4
56 changed files with 5587 additions and 157 deletions
+27 -7
View File
@@ -1,7 +1,7 @@
# Cotizador E3 — variables de entorno # Cotizador E3 — variables de entorno
# Copia este archivo a .env (local) o configúralas en Coolify (producción). # Copia este archivo a .env (local) o configúralas en Coolify (producción).
# ── Base de datos (compartida por Next.js y el API Python) ── # ── Base de datos (compartida por Next.js y el API Python) ──
DB_HOST=localhost DB_HOST=localhost
DB_PORT=5432 DB_PORT=5432
DB_USER=postgres DB_USER=postgres
@@ -9,17 +9,17 @@ DB_PASSWORD=postgres
DB_NAME=cotizador_e3 DB_NAME=cotizador_e3
# Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines, # Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines,
# se construye automáticamente desde las DB_* (ver prisma.config.ts). # se construye automáticamente desde las DB_* (ver prisma.config.ts).
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3" DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3"
# ── Auth ── # ── Auth ──
# OBLIGATORIA. Genera una con: openssl rand -base64 32 # OBLIGATORIA. Genera una con: openssl rand -base64 32
JWT_SECRET= JWT_SECRET=
# ── API Python (api/) — clave para agentes de IA / n8n ── # ── API Python (api/) — clave para agentes de IA / n8n ──
API_KEY= API_KEY=
# ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ── # ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ──
RUN_SEED=false RUN_SEED=false
SEED_ADMIN_EMAIL=[email protected] SEED_ADMIN_EMAIL=[email protected]
SEED_ADMIN_PASSWORD= SEED_ADMIN_PASSWORD=
@@ -36,3 +36,23 @@ SEED_ASESOR_NAME=
MINIMAX_API_KEY= MINIMAX_API_KEY=
MINIMAX_BASE_URL=https://api.minimax.io/anthropic MINIMAX_BASE_URL=https://api.minimax.io/anthropic
MINIMAX_MODEL=MiniMax-M3 MINIMAX_MODEL=MiniMax-M3
# --- Notificaciones (panel de cliente) ---
# Web Push. Genera el par con: node -e "require('web-push').generateVAPIDKeys()|console.log"
# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log).
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# URL publica (links de correo y notificaciones). En Coolify: el dominio del servicio web.
NEXT_PUBLIC_APP_URL=http://localhost:3000
# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log)
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=
SMTP_FROM_NAME=Cotizador E3
# Directorio de comprobantes. Local: vacio = <repo>/uploads.
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
UPLOAD_DIR=
+3
View File
@@ -60,3 +60,6 @@ next-env.d.ts
# claude local settings # claude local settings
.claude/settings.local.json .claude/settings.local.json
# Comprobantes de pago subidos por los clientes (nunca se commitean)
uploads/
+18
View File
@@ -55,6 +55,23 @@ services:
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
- SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD}
- SEED_ASESOR_NAME=${SEED_ASESOR_NAME} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME}
# URL publica: la usan los links de correo y de las notificaciones push.
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
# SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log.
- SMTP_HOST=${SMTP_HOST}
- SMTP_PORT=${SMTP_PORT:-587}
- SMTP_USER=${SMTP_USER}
- SMTP_PASS=${SMTP_PASS}
- SMTP_FROM=${SMTP_FROM}
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
- UPLOAD_DIR=/app/uploads
volumes:
- uploads_data:/app/uploads
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -94,3 +111,4 @@ services:
volumes: volumes:
postgres_data: postgres_data:
uploads_data:
+18
View File
@@ -55,6 +55,23 @@ services:
- SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL}
- SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD}
- SEED_ASESOR_NAME=${SEED_ASESOR_NAME} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME}
# URL publica: la usan los links de correo y de las notificaciones push.
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
# SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log.
- SMTP_HOST=${SMTP_HOST}
- SMTP_PORT=${SMTP_PORT:-587}
- SMTP_USER=${SMTP_USER}
- SMTP_PASS=${SMTP_PASS}
- SMTP_FROM=${SMTP_FROM}
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
- UPLOAD_DIR=/app/uploads
volumes:
- uploads_data:/app/uploads
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -94,3 +111,4 @@ services:
volumes: volumes:
postgres_data: postgres_data:
uploads_data:
+3 -1
View File
@@ -1,7 +1,9 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
serverExternalPackages: ["pdfkit"], // sharp/nodemailer/web-push traen binarios o crypto nativo: empaquetarlos
// rompe el build de produccion.
serverExternalPackages: ["pdfkit", "sharp", "nodemailer", "web-push"],
poweredByHeader: false, poweredByHeader: false,
}; };
+883 -143
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -26,11 +26,14 @@
"jose": "^6.2.3", "jose": "^6.2.3",
"lucide-react": "^1.11.0", "lucide-react": "^1.11.0",
"next": "16.2.4", "next": "16.2.4",
"nodemailer": "^10.1.7",
"pdfkit": "^0.18.0", "pdfkit": "^0.18.0",
"pg": "^8.20.0", "pg": "^8.20.0",
"prisma": "^7.8.0", "prisma": "^7.8.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"sharp": "^0.35.5",
"web-push": "^3.6.7",
"zod": "^4.3.6", "zod": "^4.3.6",
"zustand": "^5.0.12" "zustand": "^5.0.12"
}, },
@@ -38,9 +41,11 @@
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
"@types/node": "^20", "@types/node": "^20",
"@types/nodemailer": "^8.0.2",
"@types/pdfkit": "^0.17.6", "@types/pdfkit": "^0.17.6",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/web-push": "^3.6.4",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.2.4", "eslint-config-next": "16.2.4",
"tailwindcss": "^4", "tailwindcss": "^4",
@@ -0,0 +1,109 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "clienteId" TEXT;
-- CreateTable
CREATE TABLE "ProgramaPago" (
"id" TEXT NOT NULL,
"clienteId" TEXT NOT NULL,
"cotizacionId" TEXT,
"concepto" TEXT NOT NULL,
"monto" DOUBLE PRECISION NOT NULL,
"moneda" TEXT NOT NULL DEFAULT 'MXN',
"frecuencia" TEXT NOT NULL DEFAULT 'semanal',
"diaSemana" INTEGER,
"diaMes" INTEGER,
"fechaInicio" TIMESTAMP(3) NOT NULL,
"fechaFin" TIMESTAMP(3),
"activo" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PagoRecurrente" (
"id" TEXT NOT NULL,
"programaId" TEXT NOT NULL,
"fecha" TIMESTAMP(3) NOT NULL,
"monto" DOUBLE PRECISION NOT NULL,
"estado" TEXT NOT NULL DEFAULT 'pendiente',
"verificadoAt" TIMESTAMP(3),
"rechazadoAt" TIMESTAMP(3),
"rechazoMotivo" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ComprobantePago" (
"id" TEXT NOT NULL,
"pagoId" TEXT NOT NULL,
"archivoRuta" TEXT NOT NULL,
"archivoNombre" TEXT NOT NULL,
"mime" TEXT NOT NULL,
"tamano" INTEGER NOT NULL,
"subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SuscripcionPush" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"endpoint" TEXT NOT NULL,
"p256dh" TEXT NOT NULL,
"auth" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId");
-- CreateIndex
CREATE INDEX "ProgramaPago_activo_idx" ON "ProgramaPago"("activo");
-- CreateIndex
CREATE INDEX "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado");
-- CreateIndex
CREATE INDEX "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha");
-- CreateIndex
CREATE UNIQUE INDEX "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha");
-- CreateIndex
CREATE UNIQUE INDEX "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId");
-- CreateIndex
CREATE UNIQUE INDEX "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint");
-- CreateIndex
CREATE INDEX "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "User_clienteId_key" ON "User"("clienteId");
-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+98
View File
@@ -12,11 +12,16 @@ model User {
email String @unique email String @unique
password String password String
name String name String
// "admin" | "asesor" | "cliente". Un usuario con role="cliente" DEBE tener
// clienteId: su sesion da acceso unicamente al panel /cliente de ese Cliente.
role String @default("asesor") role String @default("asesor")
clienteId String? @unique
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
cotizaciones Cotizacion[] @relation("AsesorCotizaciones") cotizaciones Cotizacion[] @relation("AsesorCotizaciones")
cliente Cliente? @relation("ClienteUsuario", fields: [clienteId], references: [id])
suscripcionesPush SuscripcionPush[]
} }
model Cliente { model Cliente {
@@ -30,6 +35,9 @@ model Cliente {
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
cotizaciones Cotizacion[] cotizaciones Cotizacion[]
// Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente.
usuario User? @relation("ClienteUsuario")
programasPago ProgramaPago[]
@@index([nombre, empresa]) @@index([nombre, empresa])
} }
@@ -67,6 +75,7 @@ model Cotizacion {
planBucefalo PlanBucefaloCotizacion? planBucefalo PlanBucefaloCotizacion?
registrosHoras RegistroHoras[] registrosHoras RegistroHoras[]
propuestasIA PropuestaIA[] propuestasIA PropuestaIA[]
programasPago ProgramaPago[]
@@index([clienteId]) @@index([clienteId])
@@index([asesorId]) @@index([asesorId])
@@ -271,3 +280,92 @@ model FinanciamientoPlan {
montoMinimo Float montoMinimo Float
iva Float @default(0.16) iva Float @default(0.16)
} }
// Programa de cobros recurrentes configurado por el administrador.
// Ejemplo real: Instituto Santiago Tapia — cada sabado se genera un cobro de $750
// por la administracion web. La generacion es idempotente: un PagoRecurrente por
// (programaId, fecha), calculado desde fechaInicio con la cadencia.
model ProgramaPago {
id String @id @default(cuid())
clienteId String
// Vinculo opcional con la cotizacion que origina el servicio recurrente.
cotizacionId String?
concepto String
monto Float
moneda String @default("MXN")
// "semanal" | "quincenal" | "mensual"
frecuencia String @default("semanal")
// Dia de la semana 0=domingo..6=sabado (requerido si frecuencia=semanal).
diaSemana Int?
// Dia del mes 1..31 (requerido si frecuencia=mensual; quincenal usa dia 1 y 15).
diaMes Int?
fechaInicio DateTime
fechaFin DateTime?
activo Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
cliente Cliente @relation(fields: [clienteId], references: [id], onDelete: Cascade)
cotizacion Cotizacion? @relation(fields: [cotizacionId], references: [id], onDelete: SetNull)
pagos PagoRecurrente[]
@@index([clienteId])
@@index([activo])
}
// Un cobro generado para un periodo concreto (ej. sabado 2026-07-04).
// estados: pendiente (sin comprobante) | en_revision (comprobante subido,
// esperando admin) | verificado (admin aprobo) | rechazado (admin rechazo y
// borro el archivo; el cliente puede volver a subir).
model PagoRecurrente {
id String @id @default(cuid())
programaId String
// Fecha del periodo (medianoche America/Mexico_City al momento de generar).
fecha DateTime
monto Float
estado String @default("pendiente")
// Fecha en que el admin valido el comprobante (estado=verificado).
verificadoAt DateTime?
rechazadoAt DateTime?
rechazoMotivo String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
programa ProgramaPago @relation(fields: [programaId], references: [id], onDelete: Cascade)
comprobante ComprobantePago?
@@unique([programaId, fecha])
@@index([estado])
@@index([fecha])
}
// Comprobante de pago subido por el cliente (imagen o PDF). El archivo vive en
// UPLOAD_DIR/comprobantes/ y se sirve solo por un route handler autenticado
// (nunca desde /public). Al rechazar, el admin borra el archivo del servidor
// y se elimina este registro; el cliente vuelve a "pendiente".
model ComprobantePago {
id String @id @default(cuid())
pagoId String @unique
archivoRuta String // relativa a UPLOAD_DIR, ej. "comprobantes/<pagoId>/<uuid>.webp"
archivoNombre String // nombre original que vio el cliente
mime String // image/webp | application/pdf
tamano Int // bytes finales en disco
subidoAt DateTime @default(now())
pago PagoRecurrente @relation(fields: [pagoId], references: [id], onDelete: Cascade)
}
// Suscripcion Web Push del navegador del cliente (endpoint VAPID + claves p256dh/auth).
model SuscripcionPush {
id String @id @default(cuid())
userId String
endpoint String @unique
p256dh String
auth String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
usuario User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
}
+37
View File
@@ -0,0 +1,37 @@
// Service worker del panel de cliente: solo notificaciones push.
// Sin estrategias de cache — el panel siempre va a red.
self.addEventListener("push", (event) => {
let data = {};
try {
data = event.data ? event.data.json() : {};
} catch {
data = {};
}
const titulo = (data && data.titulo) || "Cotizador E3";
const cuerpo = (data && data.cuerpo) || "";
const url = (data && data.url) || "/cliente/pagos";
event.waitUntil(
self.registration.showNotification(titulo, {
body: cuerpo,
icon: "/favicon.ico",
data: { url },
})
);
});
self.addEventListener("notificationclick", (event) => {
const data = event.notification.data || {};
const url = data.url || "/cliente/pagos";
event.notification.close();
event.waitUntil(
self.clients
.matchAll({ type: "window", includeUncontrolled: true })
.then((cs) => {
const existing = cs.find((c) => "focus" in c);
return existing
? existing.navigate(url).then(() => existing.focus())
: self.clients.openWindow(url);
})
);
});
+173 -1
View File
@@ -1,7 +1,9 @@
"use client"; "use client";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { Search } from "lucide-react"; import { useRouter } from "next/navigation";
import { KeyRound, Search, Trash2 } from "lucide-react";
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton"; import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton";
interface Cliente { interface Cliente {
@@ -11,10 +13,23 @@ interface Cliente {
email: string | null; email: string | null;
telefono: string | null; telefono: string | null;
_count: { cotizaciones: number }; _count: { cotizaciones: number };
usuario: { id: string; email: string } | null;
} }
type DialogoAcceso = {
cliente: Cliente;
modo: "crear" | "rotar";
email: string;
password: string;
} | null;
export function ClientesList({ clientes }: { clientes: Cliente[] }) { export function ClientesList({ clientes }: { clientes: Cliente[] }) {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [dialogo, setDialogo] = useState<DialogoAcceso>(null);
const [guardando, setGuardando] = useState(false);
const router = useRouter();
const showConfirm = useConfirm();
const toast = useToast();
const filtered = useMemo(() => { const filtered = useMemo(() => {
if (!search) return clientes; if (!search) return clientes;
@@ -27,6 +42,73 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
); );
}, [clientes, search]); }, [clientes, search]);
const abrirDialogo = (cliente: Cliente, modo: "crear" | "rotar") => {
setDialogo({
cliente,
modo,
email: modo === "rotar" ? cliente.usuario?.email || "" : "",
password: "",
});
};
const guardarAcceso = async () => {
if (!dialogo) return;
const email = dialogo.email.trim();
const password = dialogo.password;
if (!email) {
toast("El email es requerido", "error");
return;
}
if (password.length < 6) {
toast("La contrasena debe tener al menos 6 caracteres", "error");
return;
}
setGuardando(true);
try {
const res = await fetch(`/api/clientes/${dialogo.cliente.id}/acceso`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (!res.ok) {
toast(data.error || "Error al guardar acceso", "error");
return;
}
toast(dialogo.modo === "crear" ? "Acceso creado" : "Acceso actualizado", "success");
setDialogo(null);
router.refresh();
} catch {
toast("Error de conexion", "error");
} finally {
setGuardando(false);
}
};
const revocarAcceso = async (cliente: Cliente) => {
const ok = await showConfirm({
title: "Revocar acceso",
message: `Eliminar la cuenta de panel de ${cliente.nombre}? El cliente dejara de poder iniciar sesion.`,
confirmText: "Revocar",
danger: true,
});
if (!ok) return;
try {
const res = await fetch(`/api/clientes/${cliente.id}/acceso`, {
method: "DELETE",
});
const data = await res.json();
if (!res.ok) {
toast(data.error || "Error al revocar acceso", "error");
return;
}
toast("Acceso revocado", "success");
router.refresh();
} catch {
toast("Error de conexion", "error");
}
};
return ( return (
<> <>
<div className="mb-4"> <div className="mb-4">
@@ -66,6 +148,9 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
<th className="text-center px-5 py-3 font-medium text-muted"> <th className="text-center px-5 py-3 font-medium text-muted">
Cotizaciones Cotizaciones
</th> </th>
<th className="text-left px-5 py-3 font-medium text-muted">
Acceso panel
</th>
<th className="text-center px-5 py-3 font-medium text-muted w-16" /> <th className="text-center px-5 py-3 font-medium text-muted w-16" />
</tr> </tr>
</thead> </thead>
@@ -84,6 +169,34 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
{c._count.cotizaciones} {c._count.cotizaciones}
</span> </span>
</td> </td>
<td className="px-5 py-3">
{c.usuario ? (
<div className="flex items-center gap-2">
<span className="text-muted">{c.usuario.email}</span>
<button
onClick={() => abrirDialogo(c, "rotar")}
className="text-xs text-primary hover:underline flex items-center gap-1"
>
<KeyRound className="w-3 h-3" />
Rotar
</button>
<button
onClick={() => revocarAcceso(c)}
className="text-xs text-danger hover:underline flex items-center gap-1"
>
<Trash2 className="w-3 h-3" />
Revocar
</button>
</div>
) : (
<button
onClick={() => abrirDialogo(c, "crear")}
className="px-3 py-1 rounded-lg text-xs text-white bg-primary hover:opacity-90"
>
Crear acceso
</button>
)}
</td>
<td className="px-5 py-3 text-center"> <td className="px-5 py-3 text-center">
<NuevaCotizacionClienteButton <NuevaCotizacionClienteButton
clienteNombre={c.nombre} clienteNombre={c.nombre}
@@ -98,6 +211,65 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
</table> </table>
</div> </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.modo === "crear"
? `Crear acceso para ${dialogo.cliente.nombre}`
: `Rotar acceso de ${dialogo.cliente.nombre}`}
</div>
<div className="p-5 space-y-3">
<div>
<label className="block text-xs text-muted mb-1">Email</label>
<input
type="email"
value={dialogo.email}
onChange={(e) =>
setDialogo((d) => (d ? { ...d, email: e.target.value } : d))
}
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
placeholder="[email protected]"
/>
</div>
<div>
<label className="block text-xs text-muted mb-1">Contrasena</label>
<input
type="password"
value={dialogo.password}
onChange={(e) =>
setDialogo((d) => (d ? { ...d, password: e.target.value } : d))
}
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
placeholder="Minimo 6 caracteres"
/>
</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={guardarAcceso}
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>
)}
</> </>
); );
} }
+2
View File
@@ -12,6 +12,7 @@ export default async function ClientesPage() {
email: true, email: true,
telefono: true, telefono: true,
_count: { select: { cotizaciones: true } }, _count: { select: { cotizaciones: true } },
usuario: { select: { id: true, email: true } },
}, },
}); });
@@ -52,6 +53,7 @@ function ClientesListWrapper({
email: string | null; email: string | null;
telefono: string | null; telefono: string | null;
_count: { cotizaciones: number }; _count: { cotizaciones: number };
usuario: { id: string; email: string } | null;
}[]; }[];
}) { }) {
return <ClientesList clientes={clientes} />; return <ClientesList clientes={clientes} />;
+277
View File
@@ -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>
);
}
+39
View File
@@ -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>
);
}
+109
View File
@@ -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>
);
}
+377
View File
@@ -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>
)}
</>
);
}
+117
View File
@@ -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>
);
}
+45
View File
@@ -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;
};
+9 -1
View File
@@ -38,10 +38,18 @@ export async function POST(request: NextRequest) {
email: user.email, email: user.email,
name: user.name, name: user.name,
role: user.role, role: user.role,
// Requerido para que el panel cliente pueda acotar sus consultas.
...(user.role === "cliente" && user.clienteId ? { clienteId: user.clienteId } : {}),
}); });
const response = NextResponse.json({ const response = NextResponse.json({
user: { id: user.id, name: user.name, email: user.email, role: user.role }, user: {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
clienteId: user.clienteId ?? null,
},
}); });
response.cookies.set(setSessionCookie(token)); response.cookies.set(setSessionCookie(token));
return response; return response;
@@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators";
// GET /api/cliente/cotizaciones/[id] — detalle completo de una cotizacion
// propia (servicios, planBucefalo, doble propuesta, cliente).
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
if (!session.clienteId) {
return NextResponse.json(
{ error: "La sesion no tiene un cliente asociado" },
{ status: 400 }
);
}
const { id } = await params;
const cot = await prisma.cotizacion.findFirst({
where: { id, clienteId: session.clienteId },
include: {
cliente: { select: { nombre: true, empresa: true, email: true } },
servicios: {
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
select: {
id: true,
nombre: true,
esPersonalizado: true,
opcion: true,
fase: true,
tipoPago: true,
precio: true,
modeloCobro: true,
horas: true,
tarifaHora: true,
tiempoEntrega: true,
notas: true,
},
},
planBucefalo: true,
},
});
if (!cot) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
return NextResponse.json({
...cot,
totales: calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva }),
...(cot.esDoble
? {
totalesOpciones: {
"1": calcularTotalesOpcion(cot.servicios, "1"),
"2": calcularTotalesOpcion(cot.servicios, "2"),
},
}
: {}),
});
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+73
View File
@@ -0,0 +1,73 @@
import { NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators";
// GET /api/cliente/cotizaciones — lista de cotizaciones del cliente con
// servicios y totales (por opcion si es doble propuesta).
export async function GET() {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
if (!session.clienteId) {
return NextResponse.json(
{ error: "La sesion no tiene un cliente asociado" },
{ status: 400 }
);
}
const cotizaciones = await prisma.cotizacion.findMany({
where: { clienteId: session.clienteId },
orderBy: { fecha: "desc" },
include: {
servicios: {
select: {
id: true,
nombre: true,
esPersonalizado: true,
opcion: true,
fase: true,
tipoPago: true,
precio: true,
modeloCobro: true,
horas: true,
tarifaHora: true,
},
},
planBucefalo: {
select: { nivel: true, precio: true, seleccionado: true },
},
},
});
const salida = cotizaciones.map((c) => ({
id: c.id,
numero: c.numero,
proyecto: c.proyecto,
fecha: c.fecha,
vigencia: c.vigencia,
estado: c.estado,
moneda: c.moneda,
esDoble: c.esDoble,
incluirIva: c.incluirIva,
servicios: c.servicios,
planBucefalo: c.planBucefalo,
totales: calcularTotalesCotizacion(c.servicios, { incluirIva: c.incluirIva }),
...(c.esDoble
? {
totalesOpciones: {
"1": calcularTotalesOpcion(c.servicios, "1"),
"2": calcularTotalesOpcion(c.servicios, "2"),
},
}
: {}),
}));
return NextResponse.json(salida);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,112 @@
import { NextRequest, NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ESTADOS_PAGO } from "@/lib/cobros";
import { ErrorUpload, eliminarComprobante, guardarComprobante } from "@/lib/uploads";
// POST /api/cliente/pagos/[id]/comprobante — el cliente sube su comprobante
// (imagen o PDF) para un cobro pendiente o rechazado. El pago pasa a
// "en_revision". Las notificaciones al admin NO se disparan aqui (las hace
// el frente que implementa verificacion/rechazo).
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
if (!session.clienteId) {
return NextResponse.json(
{ error: "La sesion no tiene un cliente asociado" },
{ status: 400 }
);
}
const { id } = await params;
const pago = await prisma.pagoRecurrente.findUnique({
where: { id },
include: {
programa: { select: { clienteId: true } },
comprobante: true,
},
});
if (!pago || pago.programa.clienteId !== session.clienteId) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
if (pago.estado === ESTADOS_PAGO.EN_REVISION) {
return NextResponse.json(
{ error: "Ya enviaste un comprobante; espera la revisión." },
{ status: 409 }
);
}
if (pago.estado === ESTADOS_PAGO.VERIFICADO) {
return NextResponse.json(
{ error: "Este cobro ya fue verificado." },
{ status: 409 }
);
}
const formData = await request.formData();
const file = formData.get("file");
if (!(file instanceof File) || file.size === 0) {
return NextResponse.json(
{ error: "Debes seleccionar un archivo." },
{ status: 400 }
);
}
// Comprobante residual (p.ej. un rechazo cuyo registro no se limpio):
// borrar archivo del disco y registro antes de guardar el nuevo.
if (pago.comprobante) {
await eliminarComprobante(pago.comprobante.archivoRuta);
await prisma.comprobantePago
.delete({ where: { pagoId: pago.id } })
.catch(() => {});
}
let guardado;
try {
guardado = await guardarComprobante(pago.id, file);
} catch (e) {
if (e instanceof ErrorUpload) {
return NextResponse.json({ error: e.message }, { status: 400 });
}
throw e;
}
const [, actualizado] = await prisma.$transaction([
prisma.comprobantePago.create({
data: {
pagoId: pago.id,
archivoRuta: guardado.ruta,
archivoNombre: guardado.nombreOriginal,
mime: guardado.mime,
tamano: guardado.tamano,
},
}),
prisma.pagoRecurrente.update({
where: { id: pago.id },
data: {
estado: ESTADOS_PAGO.EN_REVISION,
rechazadoAt: null,
rechazoMotivo: null,
},
include: {
programa: {
select: { concepto: true, frecuencia: true, monto: true, moneda: true },
},
comprobante: true,
},
}),
]);
return NextResponse.json(actualizado);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+36
View File
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
// GET /api/cliente/pagos — todos los cobros recurrentes del cliente
// (fecha descendente) con los datos del programa y la metadata del comprobante.
export async function GET() {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
if (!session.clienteId) {
return NextResponse.json(
{ error: "La sesion no tiene un cliente asociado" },
{ status: 400 }
);
}
const pagos = await prisma.pagoRecurrente.findMany({
where: { programa: { clienteId: session.clienteId } },
orderBy: { fecha: "desc" },
include: {
programa: {
select: { concepto: true, frecuencia: true, monto: true, moneda: true },
},
comprobante: true,
},
});
return NextResponse.json(pagos);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+24
View File
@@ -0,0 +1,24 @@
import { NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { llavePublicaPush } from "@/lib/push";
// GET /api/cliente/push/config — llave VAPID publica para suscribir el
// navegador. 501 si el servidor no tiene las claves configuradas.
export async function GET() {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
const publicKey = llavePublicaPush();
if (!publicKey) {
return NextResponse.json({ error: "No configurado" }, { status: 501 });
}
return NextResponse.json({ publicKey });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
// El endpoint del navegador es unico a nivel global (indice @unique); el
// upsert lo re-registra al usuario actual por si cambio de cuenta.
const suscripcionSchema = z.object({
endpoint: z.string().min(1),
p256dh: z.string().min(1),
auth: z.string().min(1),
});
const endpointSchema = z.object({
endpoint: z.string().min(1),
});
// POST /api/cliente/push/suscribir — guarda (o refresca) la suscripcion Web
// Push del navegador del cliente.
export async function POST(request: NextRequest) {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
const body = await request.json();
const parsed = suscripcionSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const { endpoint, p256dh, auth } = parsed.data;
const sub = await prisma.suscripcionPush.upsert({
where: { endpoint },
create: { userId: session.userId, endpoint, p256dh, auth },
update: { userId: session.userId, p256dh, auth },
});
return NextResponse.json({ id: sub.id, endpoint: sub.endpoint });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
// DELETE /api/cliente/push/suscribir — elimina la suscripcion del usuario
// actual (solo la suya; nunca toca las de otros usuarios).
export async function DELETE(request: NextRequest) {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
const body = await request.json();
const parsed = endpointSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const resultado = await prisma.suscripcionPush.deleteMany({
where: { userId: session.userId, endpoint: parsed.data.endpoint },
});
return NextResponse.json({ ok: true, eliminadas: resultado.count });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { requireRole } from "@/lib/auth";
import { obtenerResumenCliente } from "@/app/cliente/resumen-data";
// GET /api/cliente/resumen — tarjetas y proximos cobros del panel de cliente.
export async function GET() {
try {
const session = await requireRole("cliente");
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 401 });
}
if (!session.clienteId) {
return NextResponse.json(
{ error: "La sesion no tiene un cliente asociado" },
{ status: 400 }
);
}
const resumen = await obtenerResumenCliente(session.clienteId);
if (!resumen) {
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
}
return NextResponse.json({
cliente: resumen.cliente,
cotizaciones: resumen.cotizaciones,
pagos: resumen.pagos,
});
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+124
View File
@@ -0,0 +1,124 @@
import { NextRequest, NextResponse } from "next/server";
import { hash } from "bcryptjs";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { accesoClienteSchema } from "@/lib/schemas";
// POST /api/clientes/[id]/acceso — crea o rota la cuenta de panel del cliente.
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { id } = await params;
const body = await request.json();
const parsed = accesoClienteSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const { email, password } = parsed.data;
const cliente = await prisma.cliente.findUnique({
where: { id },
include: { usuario: true },
});
if (!cliente) {
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
}
const passwordHash = await hash(password, 10);
// ¿El email pertenece a OTRO usuario (no vinculado a este cliente)?
const otro = await prisma.user.findFirst({
where: { email, NOT: { clienteId: id } },
});
if (otro) {
return NextResponse.json(
{ error: "Ese email ya esta en uso por otro usuario" },
{ status: 409 }
);
}
if (cliente.usuario) {
// Rotar acceso: actualiza email+password del usuario vinculado.
const actualizado = await prisma.user.update({
where: { id: cliente.usuario.id },
data: { email, password: passwordHash },
});
return NextResponse.json({
id: actualizado.id,
email: actualizado.email,
name: actualizado.name,
role: actualizado.role,
});
}
const nuevo = await prisma.user.create({
data: {
email,
password: passwordHash,
name: cliente.nombre,
role: "cliente",
clienteId: id,
},
});
return NextResponse.json(
{
id: nuevo.id,
email: nuevo.email,
name: nuevo.name,
role: nuevo.role,
},
{ status: 201 }
);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
// DELETE /api/clientes/[id]/acceso — elimina la cuenta de panel (cascada limpia
// suscripciones push).
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { id } = await params;
const cliente = await prisma.cliente.findUnique({
where: { id },
include: { usuario: true },
});
if (!cliente) {
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
}
if (!cliente.usuario) {
return NextResponse.json(
{ error: "Este cliente no tiene acceso de panel" },
{ status: 404 }
);
}
await prisma.user.delete({ where: { id: cliente.usuario.id } });
return NextResponse.json({ ok: true });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+48
View File
@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireStaff } from "@/lib/auth";
import { generarCobros, parseFechaCalendario } from "@/lib/cobros";
import { notificarCobrosNuevos } from "@/lib/notificaciones";
const generarSchema = z.object({
programaId: z.string().optional(),
hasta: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Fecha invalida (se espera YYYY-MM-DD)")
.optional(),
});
// POST /api/cobros/generar — genera los cobros vencidos (idempotente) y
// notifica por correo+push a los clientes afectados.
export async function POST(request: NextRequest) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const raw = await request.json().catch(() => ({}));
const parsed = generarSchema.safeParse(raw ?? {});
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const { programaId, hasta } = parsed.data;
const creados = await generarCobros({
programaId,
hasta: hasta ? parseFechaCalendario(hasta) : undefined,
});
if (creados.length) {
await notificarCobrosNuevos(creados);
}
return NextResponse.json({ generados: creados.length });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { ESTADOS_PAGO } from "@/lib/cobros";
import { notificarVerificacion } from "@/lib/notificaciones";
// POST /api/cobros/pagos/[id]/aprobar — valida un comprobante en revision.
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { id } = await params;
const pago = await prisma.pagoRecurrente.findUnique({ where: { id } });
if (!pago) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
if (pago.estado !== ESTADOS_PAGO.EN_REVISION) {
return NextResponse.json(
{ error: "Solo se pueden aprobar cobros en revision" },
{ status: 409 }
);
}
const actualizado = await prisma.pagoRecurrente.update({
where: { id },
data: {
estado: ESTADOS_PAGO.VERIFICADO,
verificadoAt: new Date(),
rechazadoAt: null,
rechazoMotivo: null,
},
});
await notificarVerificacion(id);
return NextResponse.json(actualizado);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { ESTADOS_PAGO } from "@/lib/cobros";
import { eliminarComprobante } from "@/lib/uploads";
import { notificarRechazo } from "@/lib/notificaciones";
// POST /api/cobros/pagos/[id]/rechazar — rechaza el comprobante, borra el
// archivo del disco y el registro, y notifica al cliente.
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { id } = await params;
const raw = await request.json().catch(() => ({}));
const motivo: string | null =
typeof raw?.motivo === "string" && raw.motivo.trim()
? raw.motivo.trim()
: null;
const pago = await prisma.pagoRecurrente.findUnique({
where: { id },
include: { comprobante: true },
});
if (!pago) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
if (pago.comprobante) {
await eliminarComprobante(pago.comprobante.archivoRuta);
await prisma.comprobantePago.delete({ where: { pagoId: id } });
}
const actualizado = await prisma.pagoRecurrente.update({
where: { id },
data: {
estado: ESTADOS_PAGO.RECHAZADO,
rechazadoAt: new Date(),
rechazoMotivo: motivo,
verificadoAt: null,
},
});
await notificarRechazo(id, motivo || "");
return NextResponse.json(actualizado);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+51
View File
@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { parseFechaCalendario } from "@/lib/cobros";
// GET /api/cobros/pagos?estado=&programaId=&desde=&hasta=
// Pagos ordenados por fecha desc con programa+cliente y comprobante.
export async function GET(request: NextRequest) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { searchParams } = new URL(request.url);
const estado = searchParams.get("estado");
const programaId = searchParams.get("programaId");
const desde = searchParams.get("desde");
const hasta = searchParams.get("hasta");
const where: Record<string, unknown> = {};
if (estado) where.estado = estado;
if (programaId) where.programaId = programaId;
if (desde || hasta) {
where.fecha = {
...(desde ? { gte: parseFechaCalendario(desde) } : {}),
...(hasta ? { lte: parseFechaCalendario(hasta) } : {}),
};
}
const pagos = await prisma.pagoRecurrente.findMany({
where,
orderBy: { fecha: "desc" },
include: {
programa: {
select: {
concepto: true,
moneda: true,
cliente: { select: { id: true, nombre: true, empresa: true } },
},
},
comprobante: true,
},
});
return NextResponse.json(pagos);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { programaPagoPatchSchema } from "@/lib/schemas";
import { parseFechaCalendario } from "@/lib/cobros";
// PATCH /api/cobros/programas/[id] — actualiza campos editables (incluido
// `activo`). No existe DELETE: se desactiva con { activo: false }.
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const { id } = await params;
const previo = await prisma.programaPago.findUnique({ where: { id } });
if (!previo) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
const body = await request.json();
const parsed = programaPagoPatchSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const data = parsed.data;
// Combinar con lo previo para normalizar diaSemana/diaMes segun la
// frecuencia resultante (quincenal no usa dia; semanal limpia diaMes, etc.).
const frecuencia = data.frecuencia ?? previo.frecuencia;
let diaSemana = data.diaSemana ?? previo.diaSemana;
let diaMes = data.diaMes ?? previo.diaMes;
if (frecuencia === "quincenal") {
diaSemana = null;
diaMes = null;
} else if (frecuencia === "semanal") {
diaMes = null;
} else if (frecuencia === "mensual") {
diaSemana = null;
}
const actualizado = await prisma.programaPago.update({
where: { id },
data: {
...(data.concepto !== undefined ? { concepto: data.concepto } : {}),
...(data.monto !== undefined ? { monto: data.monto } : {}),
...(data.frecuencia !== undefined ? { frecuencia: data.frecuencia } : {}),
diaSemana,
diaMes,
...(data.fechaInicio !== undefined
? { fechaInicio: parseFechaCalendario(data.fechaInicio) }
: {}),
...(data.fechaFin !== undefined
? {
fechaFin: data.fechaFin
? parseFechaCalendario(data.fechaFin)
: null,
}
: {}),
...(data.activo !== undefined ? { activo: data.activo } : {}),
},
});
return NextResponse.json(actualizado);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+85
View File
@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireStaff } from "@/lib/auth";
import { programaPagoSchema } from "@/lib/schemas";
import { parseFechaCalendario, proximaFecha } from "@/lib/cobros";
// GET /api/cobros/programas — lista programas con cliente, conteo de pagos y
// proxima fecha calculada. Solo staff.
export async function GET() {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const programas = await prisma.programaPago.findMany({
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
include: {
cliente: { select: { id: true, nombre: true, empresa: true } },
_count: { select: { pagos: true } },
},
});
const salida = programas.map((p) => {
const prox = proximaFecha(p);
return {
...p,
proximaFecha: prox ? prox.toISOString().slice(0, 10) : null,
};
});
return NextResponse.json(salida);
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
// POST /api/cobros/programas — crea un programa de pago recurrente.
export async function POST(request: NextRequest) {
try {
const session = await requireStaff();
if (!session) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const body = await request.json();
const parsed = programaPagoSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
{ status: 400 }
);
}
const data = parsed.data;
const cliente = await prisma.cliente.findUnique({
where: { id: data.clienteId },
select: { id: true },
});
if (!cliente) {
return NextResponse.json({ error: "Cliente no encontrado" }, { status: 404 });
}
const programa = await prisma.programaPago.create({
data: {
clienteId: data.clienteId,
cotizacionId: data.cotizacionId || null,
concepto: data.concepto,
monto: data.monto,
frecuencia: data.frecuencia,
diaSemana: data.diaSemana ?? null,
diaMes: data.diaMes ?? null,
fechaInicio: parseFechaCalendario(data.fechaInicio),
fechaFin: data.fechaFin ? parseFechaCalendario(data.fechaFin) : null,
activo: true,
},
});
return NextResponse.json(programa, { status: 201 });
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
@@ -0,0 +1,75 @@
import { readFile } from "fs/promises";
import { NextRequest, NextResponse } from "next/server";
import path from "path";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";
import { archivoExiste, rutaAbsoluta } from "@/lib/uploads";
// GET /api/comprobantes/[pagoId] — sirve el archivo del comprobante.
// Acceso: staff O (cliente dueño del programa). Validación de pertenencia aqui
// además del gate de middleware (ruta compartida).
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ pagoId: string }> }
) {
try {
const { pagoId } = await params;
const session = await getSession();
const staff = session && session.role !== "cliente";
const clienteId = session?.clienteId;
const pago = await prisma.pagoRecurrente.findUnique({
where: { id: pagoId },
include: {
comprobante: true,
programa: { select: { clienteId: true } },
},
});
if (!pago) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
const esDueno =
session?.role === "cliente" && clienteId === pago.programa.clienteId;
if (!staff && !esDueno) {
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
}
const comprobante = pago.comprobante;
if (!comprobante) {
return NextResponse.json(
{ error: "Sin comprobante para este cobro" },
{ status: 404 }
);
}
if (!(await archivoExiste(comprobante.archivoRuta))) {
return NextResponse.json(
{ error: "El archivo del comprobante ya no existe" },
{ status: 404 }
);
}
const abs = rutaAbsoluta(comprobante.archivoRuta);
if (!abs) {
return NextResponse.json({ error: "Ruta invalida" }, { status: 404 });
}
const data = await readFile(abs);
const ext = path.extname(abs).slice(1) || "bin";
const nombre = `comprobante.${ext.replace(/[^a-zA-Z0-9]/g, "")}`;
return new NextResponse(new Uint8Array(data), {
headers: {
"Content-Type": comprobante.mime,
"Content-Disposition": `inline; filename="${nombre}"`,
"Cache-Control": "private, no-store",
},
});
} catch (error: unknown) {
const msg = error instanceof Error ? error.message : "Error interno";
return NextResponse.json({ error: msg }, { status: 500 });
}
}
+13
View File
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db"; import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";
import { generateCotizacionPDF } from "@/lib/pdf-generator"; import { generateCotizacionPDF } from "@/lib/pdf-generator";
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers"; import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
import { sanitizeFilename } from "@/lib/calculators"; import { sanitizeFilename } from "@/lib/calculators";
@@ -10,6 +11,18 @@ export async function GET(
) { ) {
try { try {
const { id } = await params; const { id } = await params;
// Ruta compartida (staff + cliente): el cliente solo puede descargar sus
// propias cotizaciones; para staff no se toca nada mas del handler.
const session = await getSession();
if (session?.role === "cliente") {
const propia = await prisma.cotizacion.findUnique({
where: { id },
select: { clienteId: true },
});
if (!propia || propia.clienteId !== session.clienteId) {
return NextResponse.json({ error: "No encontrado" }, { status: 404 });
}
}
const [cot, config, branding, bonos] = await Promise.all([ const [cot, config, branding, bonos] = await Promise.all([
prisma.cotizacion.findUnique({ prisma.cotizacion.findUnique({
where: { id }, where: { id },
+227
View File
@@ -0,0 +1,227 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
Bell,
BellRing,
CreditCard,
FileText,
Home,
LogOut,
Sparkles,
} from "lucide-react";
import { useToast } from "@/components/ui/DialogProvider";
const NAV = [
{ href: "/cliente", label: "Inicio", icon: Home },
{ href: "/cliente/cotizaciones", label: "Cotizaciones", icon: FileText },
{ href: "/cliente/pagos", label: "Pagos", icon: CreditCard },
];
function esActiva(pathname: string, href: string): boolean {
if (href === "/cliente") return pathname === href;
return pathname === href || pathname.startsWith(href + "/");
}
// Header del panel cliente: marca, nombre, nav con estado activo, activacion
// de notificaciones push y cierre de sesion.
export function ClienteShell({ nombre }: { nombre: string }) {
const pathname = usePathname();
const router = useRouter();
const toast = useToast();
const [activas, setActivas] = useState(false);
const [activando, setActivando] = useState(false);
// Si el navegador ya tiene una suscripcion registrada, el boton queda
// deshabilitado como "Notificaciones activas".
useEffect(() => {
let cancelado = false;
(async () => {
try {
if (
"serviceWorker" in navigator &&
"PushManager" in window &&
typeof Notification !== "undefined" &&
Notification.permission === "granted"
) {
const reg = await navigator.serviceWorker.register("/sw.js");
const sub = await reg.pushManager.getSubscription();
if (!cancelado && sub) setActivas(true);
}
} catch {
// Sin subscription previa el boton sigue disponible para activar.
}
})();
return () => {
cancelado = true;
};
}, []);
const cerrarSesion = async () => {
try {
await fetch("/api/auth/logout", { method: "POST" });
} catch {
// Aunque falle la peticion, limpiamos la navegacion local.
}
router.push("/login");
router.refresh();
};
const activarNotificaciones = async () => {
if (activando || activas) return;
setActivando(true);
try {
if (
!("serviceWorker" in navigator) ||
!("PushManager" in window) ||
typeof Notification === "undefined"
) {
toast("Las notificaciones no están disponibles", "error");
return;
}
const res = await fetch("/api/cliente/push/config");
if (res.status === 401 || res.status === 501) {
toast("Las notificaciones no están disponibles", "error");
return;
}
if (!res.ok) {
toast("Las notificaciones no están disponibles", "error");
return;
}
const data = (await res.json()) as { publicKey?: string };
if (!data.publicKey) {
toast("Las notificaciones no están disponibles", "error");
return;
}
if (Notification.permission === "denied") {
toast(
"El navegador bloqueó las notificaciones. Actívalas en la configuración del sitio.",
"error"
);
return;
}
let permiso: NotificationPermission = Notification.permission;
if (permiso === "default") {
permiso = await Notification.requestPermission();
}
if (permiso !== "granted") {
toast("No se otorgó el permiso de notificaciones", "error");
return;
}
const reg = await navigator.serviceWorker.register("/sw.js");
let sub = await reg.pushManager.getSubscription();
if (!sub) {
sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: data.publicKey,
});
}
const json = sub.toJSON();
if (!json.endpoint || !json.keys?.p256dh || !json.keys?.auth) {
toast("No se pudo registrar la suscripción", "error");
return;
}
const guardar = await fetch("/api/cliente/push/suscribir", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
endpoint: json.endpoint,
p256dh: json.keys.p256dh,
auth: json.keys.auth,
}),
});
if (!guardar.ok) {
const err = (await guardar.json().catch(() => ({}))) as { error?: string };
toast(err.error || "No se pudieron activar las notificaciones", "error");
return;
}
setActivas(true);
toast("Notificaciones activadas", "success");
} catch {
toast("No se pudieron activar las notificaciones", "error");
} finally {
setActivando(false);
}
};
return (
<header className="sticky top-0 z-40 bg-card-bg border-b border-border">
<div className="mx-auto max-w-5xl px-4 lg:px-8">
<div className="flex h-16 items-center justify-between gap-3">
<Link href="/cliente" className="flex items-center gap-2.5 min-w-0">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary text-white">
<Sparkles className="w-4 h-4" />
</span>
<span className="min-w-0">
<span className="block font-bold leading-tight">Cotizador E3</span>
<span className="block text-xs text-muted truncate">{nombre}</span>
</span>
</Link>
<div className="flex items-center gap-2">
<button
type="button"
onClick={activarNotificaciones}
disabled={activas || activando}
className={`flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
activas
? "bg-gray-100 text-muted cursor-not-allowed"
: "bg-primary text-white hover:opacity-90"
}`}
>
{activas ? (
<BellRing className="w-4 h-4" />
) : (
<Bell className="w-4 h-4" />
)}
<span className="hidden sm:inline">
{activas ? "Notificaciones activas" : "Activar notificaciones"}
</span>
<span className="sm:hidden">
{activas ? "Activas" : "Avisos"}
</span>
</button>
<button
type="button"
onClick={cerrarSesion}
className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
>
<LogOut className="w-4 h-4" />
<span className="hidden sm:inline">Cerrar sesión</span>
</button>
</div>
</div>
<nav className="flex items-center gap-1 -mt-px overflow-x-auto">
{NAV.map((item) => {
const activa = esActiva(pathname, item.href);
return (
<Link
key={item.href}
href={item.href}
className={`flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-2.5 text-sm font-medium transition-colors ${
activa
? "border-primary text-primary"
: "border-transparent text-muted hover:text-primary"
}`}
>
<item.icon className="w-4 h-4" />
{item.label}
</Link>
);
})}
</nav>
</div>
</header>
);
}
+336
View File
@@ -0,0 +1,336 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Download, FileText } from "lucide-react";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import {
IVA_RATE,
conIva,
calcularTotalesCotizacion,
calcularTotalesOpcion,
formatCurrency,
formatDate,
type MetaOpcion,
} from "@/lib/calculators";
import { EstadoBadge } from "@/components/EstadoBadge";
export const dynamic = "force-dynamic";
const TIPO_PAGO_LABEL: Record<string, string> = {
unico: "Único",
mensual: "Mensual",
};
// Detalle de una cotizacion del cliente: servicios (respetando doble
// propuesta), totales con IVA y descarga del PDF.
export default async function ClienteCotizacionDetallePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const session = await requireRole("cliente");
if (!session) redirect("/login?panel=cliente");
if (!session.clienteId) redirect("/login?panel=cliente");
const { id } = await params;
const cot = await prisma.cotizacion.findFirst({
where: { id, clienteId: session.clienteId },
include: {
cliente: { select: { nombre: true, empresa: true } },
servicios: {
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
include: { servicioCatalogo: { select: { nombre: true } } },
},
planBucefalo: true,
},
});
if (!cot) notFound();
const totales = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
const opcionesMeta =
((cot.opcionesMetadata as { "1"?: MetaOpcion; "2"?: MetaOpcion } | null) ?? {});
const totalConIva = (monto: number) => conIva(monto, cot.incluirIva);
// Grupos de partidas para doble propuesta: cada servicio se lista una sola
// vez, debajo de su opcion ("ambas"/sin opcion => compartidas). Los TOTALES
// por opcion SI incluyen las partidas "ambas" (calcularTotalesOpcion).
const gruposDoble = cot.esDoble
? [
{
clave: "1",
titulo: `Opción 1${opcionesMeta["1"]?.titulo ? `: ${opcionesMeta["1"].titulo}` : ""}`,
descripcion: opcionesMeta["1"]?.descripcion,
servicios: cot.servicios.filter((s) => s.opcion === "1"),
totales: calcularTotalesOpcion(cot.servicios, "1"),
},
{
clave: "2",
titulo: `Opción 2${opcionesMeta["2"]?.titulo ? `: ${opcionesMeta["2"].titulo}` : ""}`,
descripcion: opcionesMeta["2"]?.descripcion,
servicios: cot.servicios.filter((s) => s.opcion === "2"),
totales: calcularTotalesOpcion(cot.servicios, "2"),
},
{
clave: "ambas",
titulo: "Partidas compartidas",
descripcion: undefined,
servicios: cot.servicios.filter((s) => s.opcion === "ambas" || !s.opcion),
totales: null,
},
].filter((g) => g.servicios.length > 0)
: [];
const serviciosVisibles = cot.esDoble ? [] : cot.servicios.filter((s) => s.seleccionado);
return (
<div>
<div className="flex flex-wrap items-center justify-between gap-3 mb-6">
<div className="flex items-center gap-3 min-w-0">
<Link
href="/cliente/cotizaciones"
className="p-2 hover:bg-gray-100 rounded-lg"
aria-label="Volver a cotizaciones"
>
<ArrowLeft className="w-5 h-5" />
</Link>
<div className="min-w-0">
<h1 className="text-2xl font-bold">{cot.numero}</h1>
<p className="text-muted text-sm truncate">
{cot.proyecto} · {formatDate(cot.fecha)}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<EstadoBadge estado={cot.estado} />
<a
href={`/api/export/pdf/${cot.id}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors font-medium text-sm"
>
<Download className="w-4 h-4" />
Descargar PDF
</a>
</div>
</div>
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
<h2 className="font-semibold text-lg mb-4">Información general</h2>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
<div>
<span className="text-muted">Cliente</span>
<p className="font-medium">{cot.cliente.nombre}</p>
</div>
<div>
<span className="text-muted">Empresa</span>
<p className="font-medium">{cot.cliente.empresa || "-"}</p>
</div>
<div>
<span className="text-muted">Vigencia</span>
<p className="font-medium">{formatDate(cot.vigencia)}</p>
</div>
<div>
<span className="text-muted">Moneda</span>
<p className="font-medium">{cot.moneda}</p>
</div>
</div>
</div>
{cot.planBucefalo?.seleccionado && (
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6 flex items-center justify-between gap-3">
<div>
<h3 className="font-semibold flex items-center gap-2">
<FileText className="w-4 h-4 text-primary" />
Plan Bucéfalo
</h3>
<p className="text-sm text-muted mt-1 capitalize">
Nivel {cot.planBucefalo.nivel} · CRM para tu operación
</p>
</div>
<p className="font-semibold">{formatCurrency(cot.planBucefalo.precio)}/mes</p>
</div>
)}
{cot.esDoble ? (
<div className="space-y-6 mb-6">
{gruposDoble.map((g) => (
<div
key={g.clave}
className="bg-card-bg rounded-xl border border-border overflow-hidden"
>
<div className="px-5 py-4 border-b border-border bg-primary-light/20">
<h2 className="font-semibold text-lg text-primary">{g.titulo}</h2>
{g.descripcion && (
<p className="text-sm text-muted mt-1 whitespace-pre-wrap">
{g.descripcion}
</p>
)}
</div>
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left px-5 py-3 font-medium text-muted">Servicio</th>
<th className="text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
</tr>
</thead>
<tbody>
{g.servicios.map((s) => (
<tr key={s.id} className="border-b border-border last:border-0">
<td className="px-5 py-3">
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
</td>
<td className="px-5 py-3 text-muted">
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
</td>
<td className="px-5 py-3 text-right font-medium">
{formatCurrency(s.precio)}
</td>
</tr>
))}
</tbody>
</table>
{g.totales && (
<div className="px-5 py-4 border-t border-border grid grid-cols-2 gap-4 text-sm">
<div className="flex justify-between">
<span className="text-muted">Total unico{cot.incluirIva ? " (c/IVA)" : ""}</span>
<span className="font-semibold">
{formatCurrency(totalConIva(g.totales.totalUnico))}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted">Total mensual{cot.incluirIva ? " (c/IVA)" : ""}</span>
<span className="font-semibold">
{formatCurrency(totalConIva(g.totales.totalMensual))}
</span>
</div>
</div>
)}
</div>
))}
</div>
) : (
<div className="bg-card-bg rounded-xl border border-border overflow-hidden mb-6">
<div className="px-5 py-4 border-b border-border">
<h2 className="font-semibold text-lg">Servicios</h2>
</div>
{serviciosVisibles.length === 0 ? (
<div className="p-8 text-center text-muted text-sm">
Esta cotización no tiene servicios registrados.
</div>
) : (
<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">Servicio</th>
<th className="text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
</tr>
</thead>
<tbody>
{serviciosVisibles.map((s) => (
<tr key={s.id} className="border-b border-border hover:bg-gray-50 transition-colors">
<td className="px-5 py-3">
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
</td>
<td className="px-5 py-3 text-muted">
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
</td>
<td className="px-5 py-3 text-right font-medium">
{formatCurrency(s.precio)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
)}
<div className="bg-card-bg rounded-xl border border-border p-5">
<h2 className="font-semibold text-lg mb-4">Totales</h2>
{cot.esDoble ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{(["1", "2"] as const).map((op) => {
const t = calcularTotalesOpcion(cot.servicios, op);
const meta = opcionesMeta[op];
return (
<div key={op} className="border border-primary/30 rounded-lg p-4 bg-primary-light/10">
<h3 className="font-semibold text-primary">
Opción {op}
{meta?.titulo ? `: ${meta.titulo}` : ""}
</h3>
<div className="mt-3 space-y-1 text-sm">
<div className="flex justify-between">
<span className="text-muted">
Total unico{cot.incluirIva ? " (c/IVA)" : ""}
</span>
<span className="font-semibold">
{formatCurrency(totalConIva(t.totalUnico))}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted">
Total mensual{cot.incluirIva ? " (c/IVA)" : ""}
</span>
<span className="font-semibold">
{formatCurrency(totalConIva(t.totalMensual))}
</span>
</div>
</div>
</div>
);
})}
</div>
) : (
<div className="max-w-sm space-y-2 text-sm">
{totales.incluyeIva && (
<>
<div className="flex justify-between">
<span className="text-muted">Subtotal unico</span>
<span>{formatCurrency(totales.subtotalUnico)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted">IVA ({Math.round(IVA_RATE * 100)}%)</span>
<span>{formatCurrency(totales.ivaUnico)}</span>
</div>
</>
)}
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
<span>Total unico</span>
<span>{formatCurrency(totales.totalUnico)}</span>
</div>
{totales.incluyeIva && (
<>
<div className="flex justify-between pt-2">
<span className="text-muted">Subtotal mensual</span>
<span>{formatCurrency(totales.subtotalMensual)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted">IVA ({Math.round(IVA_RATE * 100)}%)</span>
<span>{formatCurrency(totales.ivaMensual)}</span>
</div>
</>
)}
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
<span>Total mensual</span>
<span>{formatCurrency(totales.totalMensual)}</span>
</div>
{!totales.incluyeIva && (
<p className="text-xs text-muted">Los precios no incluyen IVA.</p>
)}
</div>
)}
</div>
{cot.observaciones && (
<div className="bg-card-bg rounded-xl border border-border p-5 mt-6">
<h3 className="font-semibold mb-2">Observaciones</h3>
<p className="text-sm text-muted whitespace-pre-wrap">{cot.observaciones}</p>
</div>
)}
</div>
);
}
+154
View File
@@ -0,0 +1,154 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { ArrowRight, FileText } from "lucide-react";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import {
IVA_RATE,
calcularTotalesCotizacion,
calcularTotalesOpcion,
formatCurrency,
formatDate,
} from "@/lib/calculators";
import { EstadoBadge } from "@/components/EstadoBadge";
export const dynamic = "force-dynamic";
// Lista de cotizaciones del cliente: numero, proyecto, fecha, estado y totales.
export default async function ClienteCotizacionesPage() {
const session = await requireRole("cliente");
if (!session) redirect("/login?panel=cliente");
if (!session.clienteId) redirect("/login?panel=cliente");
const cotizaciones = await prisma.cotizacion.findMany({
where: { clienteId: session.clienteId },
orderBy: { fecha: "desc" },
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 } },
},
});
return (
<div>
<div className="mb-8">
<h1 className="text-2xl font-bold">Mis cotizaciones</h1>
<p className="text-muted text-sm mt-1">
{cotizaciones.length === 0
? "Aún no tienes cotizaciones"
: `${cotizaciones.length} cotizacion${cotizaciones.length === 1 ? "" : "es"} a tu nombre`}
</p>
</div>
{cotizaciones.length === 0 ? (
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
<FileText className="w-16 h-16 text-muted mx-auto mb-4" />
<h2 className="text-lg font-semibold mb-2">No hay cotizaciones todavía</h2>
<p className="text-muted">
Cuando tengas una cotización disponible aparecerá en esta sección.
</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">No. Cotizacion</th>
<th className="text-left px-5 py-3 font-medium text-muted">Proyecto</th>
<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">Estado</th>
<th className="text-right px-5 py-3 font-medium text-muted">Total Unico</th>
<th className="text-right px-5 py-3 font-medium text-muted">Total Mensual</th>
<th className="text-right px-5 py-3 font-medium text-muted"> </th>
</tr>
</thead>
<tbody>
{cotizaciones.map((c) => {
const totales = calcularTotalesCotizacion(c.servicios, {
incluirIva: c.incluirIva,
});
const conIva = (m: number) =>
c.incluirIva ? Math.round(m * (1 + IVA_RATE) * 100) / 100 : m;
return (
<tr key={c.id} className="border-b border-border hover:bg-gray-50 transition-colors">
<td className="px-5 py-3">
<Link
href={`/cliente/cotizaciones/${c.id}`}
className="font-medium text-primary hover:underline"
>
{c.numero}
</Link>
{c.esDoble && (
<span className="ml-2 text-[11px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full bg-primary-light text-primary">
Doble propuesta
</span>
)}
</td>
<td className="px-5 py-3 text-muted">{c.proyecto}</td>
<td className="px-5 py-3 text-muted">{formatDate(c.fecha)}</td>
<td className="px-5 py-3">
<EstadoBadge estado={c.estado} />
</td>
<td className="px-5 py-3 text-right font-medium">
{c.esDoble ? (
<div className="space-y-0.5">
{(["1", "2"] as const).map((op) => {
const t = calcularTotalesOpcion(c.servicios, op);
return (
<p key={op} className="text-xs">
<span className="text-muted">Op {op}:</span>{" "}
{t.totalUnico > 0 ? formatCurrency(conIva(t.totalUnico)) : "-"}
</p>
);
})}
</div>
) : totales.totalUnico > 0 ? (
formatCurrency(totales.totalUnico)
) : (
"-"
)}
</td>
<td className="px-5 py-3 text-right font-medium">
{c.esDoble ? (
<div className="space-y-0.5">
{(["1", "2"] as const).map((op) => {
const t = calcularTotalesOpcion(c.servicios, op);
return (
<p key={op} className="text-xs">
<span className="text-muted">Op {op}:</span>{" "}
{t.totalMensual > 0 ? formatCurrency(conIva(t.totalMensual)) : "-"}
</p>
);
})}
</div>
) : totales.totalMensual > 0 ? (
formatCurrency(totales.totalMensual)
) : (
"-"
)}
</td>
<td className="px-5 py-3 text-right">
<Link
href={`/cliente/cotizaciones/${c.id}`}
className="text-xs text-primary hover:underline inline-flex items-center gap-1"
>
Ver
<ArrowRight className="w-3 h-3" />
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
import { redirect } from "next/navigation";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { DialogProvider } from "@/components/ui/DialogProvider";
import { ClienteShell } from "./ClienteShell";
// Shell propio del panel de cliente: NO comparte el layout de (app) ni el
// Sidebar del staff. requireRole es la segunda barrera ademas del middleware.
export default async function ClienteLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await requireRole("cliente");
if (!session) redirect("/login?panel=cliente");
const cliente = session.clienteId
? await prisma.cliente.findUnique({
where: { id: session.clienteId },
select: { nombre: true },
})
: null;
return (
<DialogProvider>
<div className="min-h-screen bg-background">
<ClienteShell nombre={cliente?.nombre || session.name} />
<main className="mx-auto w-full max-w-5xl px-4 lg:px-8 py-6 lg:py-8">
{children}
</main>
</div>
</DialogProvider>
);
}
+197
View File
@@ -0,0 +1,197 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import {
ArrowRight,
CalendarClock,
ClipboardList,
Clock3,
FileText,
Inbox,
ShieldCheck,
} from "lucide-react";
import { requireRole } from "@/lib/auth";
import { formatCurrency, formatDate } from "@/lib/calculators";
import { formatFechaCorta } from "@/lib/cobros";
import { EstadoBadge } from "@/components/EstadoBadge";
import { obtenerResumenCliente } from "./resumen-data";
export const dynamic = "force-dynamic";
export default async function ClienteInicioPage() {
const session = await requireRole("cliente");
if (!session) redirect("/login?panel=cliente");
const resumen = session.clienteId
? await obtenerResumenCliente(session.clienteId)
: null;
if (!resumen) {
return (
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
<Inbox className="w-16 h-16 text-muted mx-auto mb-4" />
<h2 className="text-lg font-semibold mb-2">Cuenta sin cliente asociado</h2>
<p className="text-muted">
Tu usuario no tiene un cliente vinculado. Contacta al administrador para
darlo de alta.
</p>
</div>
);
}
const tarjetas = [
{
label: "Cotizaciones activas",
value: resumen.cotizacionesActivas,
icon: FileText,
bg: "bg-primary-light",
color: "text-primary",
},
{
label: "Pagos pendientes",
value: resumen.pagos.pendientes,
icon: Clock3,
bg: "bg-amber-100",
color: "text-amber-600",
},
{
label: "En revisión",
value: resumen.pagos.enRevision,
icon: ClipboardList,
bg: "bg-blue-100",
color: "text-blue-600",
},
{
label: "Verificados este mes",
value: resumen.pagos.verificadosMes,
icon: ShieldCheck,
bg: "bg-green-100",
color: "text-green-600",
},
];
return (
<div>
<div className="mb-8">
<h1 className="text-2xl font-bold">Hola, {resumen.cliente.nombre}</h1>
<p className="text-muted text-sm mt-1">
{resumen.cliente.empresa
? resumen.cliente.empresa + " · "
: ""}
Consulta tus cotizaciones y el estado de tus pagos.
</p>
</div>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
{tarjetas.map((t) => (
<div key={t.label} className="bg-card-bg rounded-xl border border-border p-5">
<div className="flex items-center gap-3">
<div className={`${t.bg} p-2.5 rounded-lg`}>
<t.icon className={`w-5 h-5 ${t.color}`} />
</div>
<div className="min-w-0">
<p className="text-2xl font-bold">{t.value}</p>
<p className="text-muted text-sm">{t.label}</p>
</div>
</div>
</div>
))}
</div>
<div className="bg-card-bg rounded-xl border border-border mb-8">
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
<h2 className="font-semibold text-lg flex items-center gap-2">
<CalendarClock className="w-5 h-5 text-primary" />
Próximos cobros
</h2>
<Link
href="/cliente/pagos"
className="text-sm text-primary hover:underline flex items-center gap-1"
>
Ver todos
<ArrowRight className="w-4 h-4" />
</Link>
</div>
{resumen.pagos.proximos.length === 0 ? (
<div className="p-8 text-center">
<CalendarClock className="w-10 h-10 text-muted mx-auto mb-3" />
<p className="text-muted text-sm">
No tienes cobros programados por ahora.
</p>
</div>
) : (
<ul className="divide-y divide-border">
{resumen.pagos.proximos.map((p) => (
<li
key={`${p.concepto}-${p.fecha.toISOString()}`}
className="flex items-center justify-between gap-3 px-5 py-3"
>
<div>
<p className="font-medium text-sm">{p.concepto}</p>
<p className="text-xs text-muted">{formatFechaCorta(p.fecha)}</p>
</div>
<p className="font-semibold">{formatCurrency(p.monto)}</p>
</li>
))}
</ul>
)}
</div>
<div className="bg-card-bg rounded-xl border border-border">
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
<h2 className="font-semibold text-lg">Últimas cotizaciones</h2>
<Link
href="/cliente/cotizaciones"
className="text-sm text-primary hover:underline flex items-center gap-1"
>
Ver todas
<ArrowRight className="w-4 h-4" />
</Link>
</div>
{resumen.cotizaciones.length === 0 ? (
<div className="p-8 text-center">
<FileText className="w-10 h-10 text-muted mx-auto mb-3" />
<p className="text-muted text-sm">
Todavía no tienes cotizaciones. En cuanto el administrador la envíe,
aparecerá aquí.
</p>
</div>
) : (
<ul className="divide-y divide-border">
{resumen.cotizaciones.map((c) => (
<li key={c.id}>
<Link
href={`/cliente/cotizaciones/${c.id}`}
className="flex items-center justify-between gap-3 px-5 py-3 hover:bg-gray-50 transition-colors"
>
<div className="min-w-0">
<p className="font-medium text-sm text-primary">{c.numero}</p>
<p className="text-xs text-muted truncate">{c.proyecto}</p>
</div>
<div className="flex items-center gap-4 shrink-0">
<span className="text-xs text-muted hidden sm:block">
{formatDate(c.fecha)}
</span>
<EstadoBadge estado={c.estado} />
<div className="text-right text-sm hidden md:block">
{c.totales.totalUnico > 0 && (
<p className="font-medium">
{formatCurrency(c.totales.totalUnico)}
</p>
)}
{c.totales.totalMensual > 0 && (
<p className="text-xs text-muted">
{formatCurrency(c.totales.totalMensual)}/mes
</p>
)}
</div>
<ArrowRight className="w-4 h-4 text-muted" />
</div>
</Link>
</li>
))}
</ul>
)}
</div>
</div>
);
}
@@ -0,0 +1,65 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Upload } from "lucide-react";
import { useToast } from "@/components/ui/DialogProvider";
// Subida de comprobante para un cobro pendiente o rechazado. multipart/form-data
// a POST /api/cliente/pagos/[id]/comprobante; en error muestra el {error} del server.
export function SubirComprobante({ pagoId }: { pagoId: string }) {
const router = useRouter();
const toast = useToast();
const [subiendo, setSubiendo] = useState(false);
const onChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setSubiendo(true);
try {
const fd = new FormData();
fd.append("file", file);
const res = await fetch(`/api/cliente/pagos/${pagoId}/comprobante`, {
method: "POST",
body: fd,
});
if (!res.ok) {
const data = (await res.json().catch(() => ({}))) as { error?: string };
toast(data.error || "No se pudo subir el comprobante", "error");
} else {
toast("Comprobante enviado. Espera la revisión del administrador.", "success");
router.refresh();
}
} catch {
toast("Error de conexión al subir el comprobante", "error");
} finally {
setSubiendo(false);
// Permite volver a elegir el mismo archivo tras un error.
e.target.value = "";
}
};
return (
<label
className={`inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-sm font-medium transition-colors ${
subiendo
? "opacity-60 cursor-wait text-muted"
: "cursor-pointer hover:bg-gray-50"
}`}
>
{subiendo ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
{subiendo ? "Subiendo…" : "Subir comprobante"}
<input
type="file"
accept="image/jpeg,image/png,image/webp,application/pdf"
className="sr-only"
onChange={onChange}
disabled={subiendo}
/>
</label>
);
}
+184
View File
@@ -0,0 +1,184 @@
import { redirect } from "next/navigation";
import { CalendarClock, Inbox } from "lucide-react";
import { requireRole } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { formatCurrency } from "@/lib/calculators";
import { ESTADOS_PAGO, formatFechaCorta } from "@/lib/cobros";
import { SubirComprobante } from "./SubirComprobante";
export const dynamic = "force-dynamic";
const DIAS_SEMANA = [
"domingo",
"lunes",
"martes",
"miércoles",
"jueves",
"viernes",
"sábado",
];
function frecuenciaLegible(p: {
frecuencia: string;
diaSemana?: number | null;
diaMes?: number | null;
}): string {
if (p.frecuencia === "semanal") {
return `Semanal (${DIAS_SEMANA[p.diaSemana ?? 0]})`;
}
if (p.frecuencia === "quincenal") {
return "Quincenal (días 1 y 15)";
}
if (p.frecuencia === "mensual") {
return `Mensual (día ${p.diaMes ?? 1})`;
}
return p.frecuencia;
}
function EstadoPagoBadge({
estado,
rechazoMotivo,
}: {
estado: string;
rechazoMotivo?: string | null;
}) {
let cls = "bg-amber-100 text-amber-700";
let label = "Pendiente de pago";
if (estado === ESTADOS_PAGO.EN_REVISION) {
cls = "bg-blue-100 text-blue-700";
label = "En revisión";
} else if (estado === ESTADOS_PAGO.VERIFICADO) {
cls = "bg-green-100 text-green-700";
label = "Verificado ✓";
} else if (estado === ESTADOS_PAGO.RECHAZADO) {
cls = "bg-red-100 text-red-700";
label = "Rechazado";
}
return (
<div>
<span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${cls}`}>
{label}
</span>
{estado === ESTADOS_PAGO.RECHAZADO && rechazoMotivo && (
<p className="text-xs text-muted mt-1">Motivo: {rechazoMotivo}</p>
)}
</div>
);
}
// Guia de pagos recurrentes: un bloque por programa y su tabla de cobros,
// con subida de comprobante para los pendientes/rechazados.
export default async function ClientePagosPage() {
const session = await requireRole("cliente");
if (!session) redirect("/login?panel=cliente");
if (!session.clienteId) redirect("/login?panel=cliente");
const programas = await prisma.programaPago.findMany({
where: { clienteId: session.clienteId },
orderBy: [{ activo: "desc" }, { concepto: "asc" }],
include: {
pagos: {
orderBy: { fecha: "desc" },
include: { comprobante: { select: { archivoNombre: true, subidoAt: true } } },
},
},
});
return (
<div>
<div className="mb-8">
<h1 className="text-2xl font-bold">Mis pagos</h1>
<p className="text-muted text-sm mt-1">
Historial de cobros recurrentes y carga de comprobantes
</p>
</div>
<div className="mb-6 rounded-xl border border-border bg-card-bg p-4 text-sm text-muted">
Sube tu comprobante de pago (imagen o PDF). El administrador lo revisará y
quedará como verificado.
</div>
{programas.length === 0 ? (
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
<Inbox className="w-16 h-16 text-muted mx-auto mb-4" />
<h2 className="text-lg font-semibold mb-2">Sin cobros programados</h2>
<p className="text-muted">
Cuando se configure un programa de pagos para ti, aparecerá aquí junto
con cada cobro generado.
</p>
</div>
) : (
programas.map((prog) => (
<section key={prog.id} className="mb-8">
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<div>
<h2 className="font-semibold text-lg flex items-center gap-2">
<CalendarClock className="w-5 h-5 text-primary" />
{prog.concepto}
</h2>
<p className="text-sm text-muted mt-0.5">
{formatCurrency(prog.monto)} · {frecuenciaLegible(prog)} · {prog.moneda}
</p>
</div>
{!prog.activo && (
<span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
Programa inactivo
</span>
)}
</div>
{prog.pagos.length === 0 ? (
<div className="bg-card-bg rounded-xl border border-border p-8 text-center text-sm text-muted">
Aún no se han generado cobros de este programa.
</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">Fecha</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">Estado</th>
<th className="text-left px-5 py-3 font-medium text-muted">Acción</th>
</tr>
</thead>
<tbody>
{prog.pagos.map((pago) => (
<tr key={pago.id} className="border-b border-border hover:bg-gray-50 transition-colors">
<td className="px-5 py-3">{formatFechaCorta(pago.fecha)}</td>
<td className="px-5 py-3 text-right font-medium">
{formatCurrency(pago.monto)}
</td>
<td className="px-5 py-3">
<EstadoPagoBadge
estado={pago.estado}
rechazoMotivo={pago.rechazoMotivo}
/>
</td>
<td className="px-5 py-3">
{pago.estado === ESTADOS_PAGO.PENDIENTE ||
pago.estado === ESTADOS_PAGO.RECHAZADO ? (
<SubirComprobante pagoId={pago.id} />
) : (
<a
href={`/api/comprobantes/${pago.id}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary text-sm hover:underline"
>
Ver comprobante
</a>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
))
)}
</div>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { prisma } from "@/lib/db";
import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators";
import { ESTADOS_PAGO, hoyCalendario, proximaFecha } 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;
totales: ReturnType<typeof calcularTotalesCotizacion>;
totalesOpciones?: {
"1": ReturnType<typeof calcularTotalesOpcion>;
"2": ReturnType<typeof calcularTotalesOpcion>;
};
}
export interface ResumenCliente {
cliente: { nombre: string; empresa: string | null };
cotizacionesActivas: number;
cotizaciones: ResumenCotizacion[];
pagos: {
pendientes: number;
enRevision: number;
verificadosMes: number;
proximos: Array<{ fecha: Date; monto: number; concepto: string }>;
};
}
export async function obtenerResumenCliente(clienteId: string): Promise<ResumenCliente | null> {
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, pendientes, 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.count({
where: { estado: ESTADOS_PAGO.PENDIENTE, programa: { clienteId } },
}),
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,
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, concepto: p.concepto } : null;
})
.filter((x): x is { fecha: Date; monto: number; concepto: string } => x !== null)
.sort((a, b) => a.fecha.getTime() - b.fecha.getTime())
.slice(0, 3);
return {
cliente,
cotizacionesActivas,
cotizaciones,
pagos: { pendientes, enRevision, verificadosMes, proximos },
};
}
+4 -1
View File
@@ -23,7 +23,10 @@ export default function LoginPage() {
}); });
if (res.ok) { if (res.ok) {
router.push("/"); const data = await res.json();
// Cada rol entra a su propio panel.
const destino = data?.user?.role === "cliente" ? "/cliente" : "/";
router.push(destino);
router.refresh(); router.refresh();
} else { } else {
const data = await res.json(); const data = await res.json();
+2
View File
@@ -7,6 +7,7 @@ import {
FileText, FileText,
Database, Database,
Users, Users,
Receipt,
Settings, Settings,
Menu, Menu,
X, X,
@@ -20,6 +21,7 @@ const navigation = [
{ name: "Cotizaciones", href: "/cotizaciones", icon: FileText }, { name: "Cotizaciones", href: "/cotizaciones", icon: FileText },
{ name: "Catalogo", href: "/catalogo", icon: Database }, { name: "Catalogo", href: "/catalogo", icon: Database },
{ name: "Clientes", href: "/clientes", icon: Users }, { name: "Clientes", href: "/clientes", icon: Users },
{ name: "Cobros", href: "/cobros", icon: Receipt },
{ name: "Configuracion", href: "/configuracion", icon: Settings }, { name: "Configuracion", href: "/configuracion", icon: Settings },
]; ];
+17
View File
@@ -0,0 +1,17 @@
/**
* Punto de arranque del scheduler de cobros recurrentes.
*
* Next compila instrumentation.ts PARA DOS RUNTIMES (node y edge). El scheduler
* toca Prisma/correo/push, así que solo existe en el bundle de node: el import
* dinámico vive DENTRO del guard `NEXT_RUNTIME === "nodejs"` para que el
* compilador elimine la rama muerta en edge y no intente empaquetar pg ahí.
*
* La lógica (guard anti-timers-duplicados, primera ejecución a los 20 s y
* cada 60 min) está en src/lib/scheduler.ts — ver su cabecera.
*/
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { iniciarSchedulerCobros } = await import("./lib/scheduler");
iniciarSchedulerCobros();
}
}
+20
View File
@@ -12,6 +12,10 @@ export interface SessionPayload {
email: string; email: string;
name: string; name: string;
role: string; role: string;
// Presente solo cuando role === "cliente": identifica el registro de Cliente
// al que esta vinculada la cuenta. Las rutas del panel cliente lo usan para
// acotar las consultas sin tocar la BD.
clienteId?: string;
} }
export async function createSession(payload: SessionPayload): Promise<string> { export async function createSession(payload: SessionPayload): Promise<string> {
@@ -64,3 +68,19 @@ export function clearSessionCookie() {
maxAge: 0, maxAge: 0,
}; };
} }
// Segunda barrera ademas del middleware: la usa cada route handler para no
// depender unicamente del gate de borde. Devuelve null si no hay sesion o si
// el rol no coincide.
export async function requireRole(rol: string): Promise<SessionPayload | null> {
const session = await getSession();
if (!session || session.role !== rol) return null;
return session;
}
// Sesion de administrador/asesor (cualquier rol que no sea "cliente").
export async function requireStaff(): Promise<SessionPayload | null> {
const session = await getSession();
if (!session || session.role === "cliente") return null;
return session;
}
+137
View File
@@ -0,0 +1,137 @@
// 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
RECHAZADO: "rechazado", // admin rechazo (el archivo se borro; se puede volver a subir)
} as const;
export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO];
// "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() };
}
// Hoy en America/Mexico_City como fecha de calendario (UTC midnight).
export function hoyCalendario(): Date {
const iso = new Intl.DateTimeFormat("en-CA", {
timeZone: ZONA_HORARIA,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(new Date()); // "YYYY-MM-DD"
return parseFechaCalendario(iso);
}
function sumarDias(d: Date, dias: number): Date {
return new Date(d.getTime() + dias * 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);
}
// 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<ProgramaPago, "frecuencia" | "diaSemana" | "diaMes" | "fechaInicio" | "fechaFin">,
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<ProgramaPago, "frecuencia" | "diaSemana" | "diaMes" | "fechaInicio" | "fechaFin">,
desde: Date = hoyCalendario()
): Date | null {
const ventana = fechasPeriodo(programa, sumarDias(desde, 366));
return ventana.find((f) => f >= desde) ?? null;
}
+57
View File
@@ -0,0 +1,57 @@
import { prisma } from "@/lib/db";
import { aCalendario, fechasPeriodo, hoyCalendario } from "@/lib/cobros-fechas";
import type { PagoRecurrente } from "@/generated/prisma/client";
// LADO SERVIDOR de los cobros recurrentes. Las utilidades puras (fechas,
// estados, formatos) viven en @/lib/cobros-fechas y se re-exportan aqui para
// que el codigo de servidor siga importando de "@/lib/cobros".
//
// IMPORTANTE para componentes "use client": importen de "@/lib/cobros-fechas".
// Importar de "@/lib/cobros" desde el navegador arrastra prisma/pg y rompe el
// build de Next.
export * from "@/lib/cobros-fechas";
// GENERACION IDEMPOTENTE. Crea los PagoRecurrente que ya tocan (fecha <= hoy
// MX, o <= `hasta` si se pide generar adelantado) para uno o todos los
// programas activos. Repetir la llamada no duplica: la restriccion unica
// (programaId, fecha) absorbe los cruces.
//
// Devuelve los pagos REALMENTE creados (los ya existentes se ignoran), que es
// lo que el caller debe notificar por correo/push.
export async function generarCobros(
opts: { programaId?: string; hasta?: Date } = {}
): Promise<PagoRecurrente[]> {
const hasta = aCalendarioFecha(opts.hasta ?? hoyCalendario());
const programas = await prisma.programaPago.findMany({
where: {
activo: true,
...(opts.programaId ? { id: opts.programaId } : {}),
},
});
const creados: PagoRecurrente[] = [];
for (const programa of programas) {
const fechas = fechasPeriodo(programa, hasta);
for (const fecha of fechas) {
try {
const pago = await prisma.pagoRecurrente.create({
data: { programaId: programa.id, fecha, monto: programa.monto },
});
creados.push(pago);
} catch (e) {
// P2002: (programaId, fecha) ya existe -> periodo ya generado.
if ((e as { code?: string }).code !== "P2002") throw e;
}
}
}
return creados;
}
// Normaliza cualquier Date a medianoche UTC de su parte de calendario.
function aCalendarioFecha(date: Date): Date {
const { y, m, d } = aCalendario(date);
return new Date(Date.UTC(y, m - 1, d));
}
+77
View File
@@ -0,0 +1,77 @@
import nodemailer from "nodemailer";
import type { Transporter } from "nodemailer";
// Servicio de correo SMTP configurable por variables de entorno. Si no hay
// configuracion, los envios se omiten con un aviso en lugar de tumbar el flujo:
// la app debe seguir funcionando con SMTP sin dar de alta.
//
// SMTP_HOST=smtp.ejemplo.com
// SMTP_PORT=587 (587=starttls, 465=ssl, 25=negociacion)
// SMTP_USER=usuario
// SMTP_PASS=contrasena
// [email protected] (opcional, por defecto SMTP_USER)
// SMTP_FROM_NAME=Cotizador E3 (opcional)
export interface ResultadoEnvio {
ok: boolean;
// true cuando no hay SMTP configurado y el envio se omitio a proposito.
omitido?: boolean;
error?: string;
}
let transport: Transporter | null | undefined;
function crearTransport(): Transporter | null {
const host = process.env.SMTP_HOST;
if (!host) return null;
const port = parseInt(process.env.SMTP_PORT || "587", 10);
return nodemailer.createTransport({
host,
port,
secure: port === 465,
auth: process.env.SMTP_USER
? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
: undefined,
});
}
export function smtpConfigurado(): boolean {
return Boolean(process.env.SMTP_HOST);
}
function obtenerTransport(): Transporter | null {
if (transport === undefined) transport = crearTransport();
return transport;
}
// Solo para tests/rotacion de credenciales: olvida el transport cacheado.
export function reiniciarTransport() {
transport = undefined;
}
export async function enviarCorreo(opciones: {
to: string;
subject: string;
html: string;
text?: string;
}): Promise<ResultadoEnvio> {
const t = obtenerTransport();
if (!t) {
console.warn("[email] SMTP no configurado (SMTP_HOST ausente); se omite el envio a", opciones.to);
return { ok: false, omitido: true };
}
try {
await t.sendMail({
from: `"${process.env.SMTP_FROM_NAME || "Cotizador E3"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
to: opciones.to,
subject: opciones.subject,
html: opciones.html,
text: opciones.text,
});
return { ok: true };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error("[email] fallo el envio a", opciones.to, "-", msg);
return { ok: false, error: msg };
}
}
+207
View File
@@ -0,0 +1,207 @@
import { prisma } from "@/lib/db";
import { enviarCorreo } from "@/lib/email";
import { enviarPush } from "@/lib/push";
import { ESTADOS_PAGO, formatFechaCobro, formatFechaCorta } from "@/lib/cobros";
import type { PagoRecurrente } from "@/generated/prisma/client";
// 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
// (el estado en BD ya quedo escrito antes de notificar).
//
// Los handlers de rutas solo necesitan:
// - tras generar cobros: notificarCobrosNuevos(pagos)
// - al aprobar/rechazar: notificarVerificacion(pagoId) / notificarRechazo(pagoId)
const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
const PANEL_PAGOS = `${BASE_URL}/cliente/pagos`;
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
const botonHtml = boton
? `<p style="margin:24px 0"><a href="${boton.url}" style="background:#0f172a;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">${boton.texto}</a></p>`
: "";
return `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
<p style="font-size:13px;color:#71717a;margin:0 0 4px">COTIZADOR E3</p>
<h1 style="font-size:20px;color:#18181b;margin:0 0 16px">${titulo}</h1>
<div style="font-size:15px;color:#3f3f46;line-height:1.6">${cuerpo}</div>
${botonHtml}
<p style="font-size:12px;color:#a1a1aa;margin:24px 0 0">Consultoría E3 · Querétaro, México</p>
</div>
</div></body></html>`;
}
function clienteDestino(usuario: { email: string } | null, emailCliente: string | null): string | null {
return usuario?.email || emailCliente || null;
}
async function avisar(
userId: string | null,
email: string | null,
asunto: string,
html: string,
texto: string,
push: { titulo: string; cuerpo: string; url?: string }
): Promise<void> {
if (email) {
await enviarCorreo({ to: email, subject: asunto, html, text: texto });
}
if (userId) {
await enviarPush(userId, push);
}
}
type ProgramaConCliente = {
id: string;
concepto: string;
monto: number;
moneda: string;
cliente: { nombre: string; email: string | null; usuario: { id: string; email: string } | null };
};
// Llamada tras generarCobros(): un resumen POR CLIENTE con todos los cobros
// nuevos de la corrida (evita 52 correos si alguien genera un anio de golpe).
export async function notificarCobrosNuevos(pagos: PagoRecurrente[]): Promise<void> {
if (pagos.length === 0) return;
const porPrograma = new Map<string, PagoRecurrente[]>();
for (const p of pagos) {
const lista = porPrograma.get(p.programaId) ?? [];
lista.push(p);
porPrograma.set(p.programaId, lista);
}
for (const [programaId, lista] of porPrograma) {
try {
const programa = (await prisma.programaPago.findUnique({
where: { id: programaId },
include: { cliente: { include: { usuario: true } } },
})) as ProgramaConCliente | null;
if (!programa) continue;
const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email);
const userId = programa.cliente.usuario?.id ?? null;
if (!destino && !userId) continue;
lista.sort((a, b) => a.fecha.getTime() - b.fecha.getTime());
const primero = lista[0];
const formatoMonto = (m: number) =>
m.toLocaleString("es-MX", { style: "currency", currency: programa.moneda || "MXN" });
const filas = lista
.slice(0, 12)
.map((p) => `<li>${formatFechaCobro(p.fecha)} — ${formatoMonto(p.monto)}</li>`)
.join("");
const extra =
lista.length > 12 ? `<li>…y ${lista.length - 12} cobros más (ver panel)</li>` : "";
const plural = lista.length > 1;
const titulo = plural
? `Se ${lista.length > 1 ? "generaron" : "generó"} ${lista.length} cobros de ${programa.concepto}`
: `Nuevo cobro: ${programa.concepto}`;
const cuerpo = `
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
<p>${plural ? `Se generaron <strong>${lista.length} cobros</strong>` : `Se generó un cobro`} de <strong>${programa.concepto}</strong>:</p>
<ul style="padding-left:20px">${filas}${extra}</ul>
<p>Sube tu comprobante de pago desde el panel para darlo por liquidado.</p>`;
const texto = `${titulo}. Fechas: ${lista
.slice(0, 5)
.map((p) => formatFechaCorta(p.fecha))
.join(", ")}. Entra al panel para subir tu comprobante.`;
await avisar(
userId,
destino,
titulo,
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }),
texto,
{
titulo: plural ? `${lista.length} cobros nuevos` : "Nuevo cobro pendiente",
cuerpo: `${programa.concepto} — ${formatoMonto(primero.monto)} (${formatFechaCorta(primero.fecha)})`,
url: "/cliente/pagos",
}
);
} catch (e) {
console.error("[notificaciones] fallo al avisar cobros nuevos del programa", programaId, e);
}
}
}
async function cargarPago(pagoId: string) {
return prisma.pagoRecurrente.findUnique({
where: { id: pagoId },
include: {
programa: { include: { cliente: { include: { usuario: true } } } },
},
});
}
// Tras marcar un cobro como VERIFICADO en el panel admin.
export async function notificarVerificacion(pagoId: string): Promise<void> {
try {
const pago = await cargarPago(pagoId);
if (!pago || pago.estado !== ESTADOS_PAGO.VERIFICADO) return;
const programa = pago.programa as unknown as ProgramaConCliente;
const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email);
const userId = programa.cliente.usuario?.id ?? null;
if (!destino && !userId) return;
const titulo = `Pago verificado: ${programa.concepto}`;
const cuerpo = `
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
<p>Tu pago corresponde al <strong>${formatFechaCobro(pago.fecha)}</strong> por
<strong>${pago.monto.toLocaleString("es-MX", { style: "currency", currency: programa.moneda })}</strong>
fue <strong>verificado</strong>. Ya aparece como liquidado en tu panel.</p>`;
await avisar(
userId,
destino,
titulo,
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }),
`${programa.concepto}: pago del ${formatFechaCorta(pago.fecha)} verificado.`,
{
titulo: "Pago verificado ✓",
cuerpo: `${programa.concepto} — ${formatFechaCorta(pago.fecha)}`,
url: "/cliente/pagos",
}
);
} catch (e) {
console.error("[notificaciones] fallo al avisar verificacion", pagoId, e);
}
}
// Tras RECHAZAR el comprobante (el archivo ya se borro del servidor).
export async function notificarRechazo(pagoId: string, motivo: string): Promise<void> {
try {
const pago = await cargarPago(pagoId);
if (!pago) return;
const programa = pago.programa as unknown as ProgramaConCliente;
const destino = clienteDestino(programa.cliente.usuario, programa.cliente.email);
const userId = programa.cliente.usuario?.id ?? null;
if (!destino && !userId) return;
const titulo = `Comprobante rechazado: ${programa.concepto}`;
const cuerpo = `
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
<p>Rechazamos el comprobante del pago <strong>${formatFechaCobro(pago.fecha)}</strong>
(${programa.concepto}).</p>
${motivo ? `<p><strong>Motivo:</strong> ${motivo}</p>` : ""}
<p>Puedes volver a subir un comprobante desde el panel.</p>`;
await avisar(
userId,
destino,
titulo,
plantilla(titulo, cuerpo, { texto: "Subir otro comprobante", url: PANEL_PAGOS }),
`${programa.concepto}: comprobante del ${formatFechaCorta(pago.fecha)} rechazado. ${motivo || ""}`.trim(),
{
titulo: "Comprobante rechazado",
cuerpo: `${programa.concepto} — ${formatFechaCorta(pago.fecha)}. Motivo: ${motivo || "sin detalle"}`,
url: "/cliente/pagos",
}
);
} catch (e) {
console.error("[notificaciones] fallo al avisar rechazo", pagoId, e);
}
}
+85
View File
@@ -0,0 +1,85 @@
import webpush from "web-push";
import { prisma } from "@/lib/db";
// Web Push (VAPID). Requiere VAPID_PUBLIC_KEY y VAPID_PRIVATE_KEY en el entorno:
// node -e "console.log(require('web-push').generateVAPIDKeys())"
// Sin claves, las funciones se omiten con aviso (la app no debe tumbarse).
// La llave publica se entrega al panel cliente via GET /api/cliente/push/config.
export interface ResultadoPush {
ok: boolean;
omitido?: boolean;
error?: string;
enviadas?: number;
}
function claves(): { publica: string; privada: string } | null {
const publica = process.env.VAPID_PUBLIC_KEY;
const privada = process.env.VAPID_PRIVATE_KEY;
if (!publica || !privada) return null;
return { publica, privada };
}
export function pushConfigurado(): boolean {
return Boolean(claves());
}
export function llavePublicaPush(): string | null {
return claves()?.publica ?? null;
}
let vapidListo = false;
function asegurarVapid() {
if (vapidListo) return;
const k = claves();
if (!k) return;
webpush.setVapidDetails(
"mailto:" + (process.env.VAPID_SUBJECT || process.env.SMTP_FROM || "admin@localhost"),
k.publica,
k.privada
);
vapidListo = true;
}
// Envia una notificacion push a TODAS las suscripciones del usuario.
// Los endpoints muertos (404/410) se purgan en el intento.
export async function enviarPush(
userId: string,
payload: { titulo: string; cuerpo: string; url?: string }
): Promise<ResultadoPush> {
const k = claves();
if (!k) {
console.warn("[push] VAPID no configurado; se omite la notificacion a", userId);
return { ok: false, omitido: true };
}
asegurarVapid();
const subs = await prisma.suscripcionPush.findMany({ where: { userId } });
if (subs.length === 0) return { ok: true, enviadas: 0 };
const body = JSON.stringify(payload);
let enviadas = 0;
let fallo: string | undefined;
for (const sub of subs) {
try {
await webpush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
body
);
enviadas++;
} catch (e) {
const status = (e as { statusCode?: number }).statusCode;
if (status === 404 || status === 410) {
// Suscripcion invalidada por el navegador: limpiarla.
await prisma.suscripcionPush.delete({ where: { id: sub.id } }).catch(() => {});
} else {
fallo = e instanceof Error ? e.message : String(e);
console.error("[push] fallo el envio a", sub.endpoint.slice(0, 60), "-", fallo);
}
}
}
return { ok: enviadas > 0 || !fallo, enviadas, error: fallo };
}
+53
View File
@@ -0,0 +1,53 @@
import { generarCobros } from "@/lib/cobros";
import { notificarCobrosNuevos } from "@/lib/notificaciones";
/**
* Scheduler automático de cobros recurrentes.
*
* Qué hace: cada hora genera de forma idempotente los cobros recurrentes
* vencidos (src/lib/cobros.ts opera en la zona America/Mexico_City) y, si se
* creó alguno, notifica a los clientes afectados por correo + push
* (src/lib/notificaciones.ts, best-effort).
*
* Por qué cada hora (y no diario): el servidor puede estar en UTC, así que un
* cobro que vence un sábado en México se emite apenas empieza el sábado en
* México (aprox. 06:00 UTC), sin esperar al día siguiente. La generación es
* idempotente: aunque el proceso reinicie, no se duplican periodos.
*
* Este módulo solo se importa desde src/instrumentation.ts dentro del guard
* de runtime nodejs — nunca debe entrar al bundle de edge ni al navegador.
*
* El guard en globalThis evita timers duplicados con HMR o reinicios.
*/
export function iniciarSchedulerCobros(): void {
const g = globalThis as unknown as { __cotizadorSchedulerActivo?: boolean };
if (g.__cotizadorSchedulerActivo) return;
g.__cotizadorSchedulerActivo = true;
const PRIMERA_EJECUCION_MS = 20_000; // dar tiempo a que la BD esté lista al arrancar
const INTERVALO_MS = 60 * 60 * 1000; // cada 60 minutos
async function ejecutar(): Promise<void> {
try {
const creados = await generarCobros();
if (creados.length) {
await notificarCobrosNuevos(creados);
}
console.log(`[cobros-scheduler] ${creados.length} cobros nuevos`);
} catch (e) {
console.error("[cobros-scheduler] error", e);
}
}
// Nunca una promesa sin catch: ejecutar() ya trae try/catch interno total,
// pero setInterval/setTimeout no await, así que encadenamos .catch igual.
setTimeout(() => {
void ejecutar().catch((e) => console.error("[cobros-scheduler] error", e));
}, PRIMERA_EJECUCION_MS);
setInterval(() => {
void ejecutar().catch((e) => console.error("[cobros-scheduler] error", e));
}, INTERVALO_MS);
console.log("[cobros-scheduler] scheduler activo (primera ejecución en 20s, luego cada 60 min)");
}
+77
View File
@@ -137,3 +137,80 @@ export function validateOrError<T>(
if (result.success) return result.data; if (result.success) return result.data;
return { error: result.error.issues.map((i) => i.message).join(", ") }; return { error: result.error.issues.map((i) => i.message).join(", ") };
} }
// ============================================================================
// Cobros recurrentes (Frente A: modulo admin)
// ============================================================================
const fechaISO = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Fecha invalida (se espera YYYY-MM-DD)");
const FRECUENCIAS = ["semanal", "quincenal", "mensual"] as const;
// Reglas condicionales de la frecuencia. Se comparten entre create y patch
// (en patch los campos opcionales se completan con los valores previos antes
// de validar, via `valoresFrecuencia`).
function erroresFrecuencia(
frecuencia: string,
diaSemana: number | null | undefined,
diaMes: number | null | undefined,
addIssue: (path: (string | number)[], message: string) => void
) {
if (frecuencia === "semanal" && (diaSemana === null || diaSemana === undefined)) {
addIssue(["diaSemana"], "Para frecuencia semanal se requiere diaSemana (0-6)");
}
if (frecuencia === "mensual" && (diaMes === null || diaMes === undefined)) {
addIssue(["diaMes"], "Para frecuencia mensual se requiere diaMes (1-31)");
}
}
export const programaPagoSchema = z
.object({
clienteId: z.string().min(1, "El cliente es requerido"),
cotizacionId: z.string().min(1).optional(),
concepto: z.string().min(1, "El concepto es requerido"),
monto: z.number().positive("El monto debe ser mayor a 0"),
frecuencia: z.enum(FRECUENCIAS, { message: "Frecuencia invalida" }),
diaSemana: z.number().int().min(0).max(6).optional(),
diaMes: z.number().int().min(1).max(31).optional(),
fechaInicio: fechaISO,
fechaFin: fechaISO.optional(),
})
.superRefine((val, ctx) => {
erroresFrecuencia(
val.frecuencia,
val.diaSemana,
val.diaMes,
(path, message) => ctx.addIssue({ code: "custom", path, message })
);
});
export const programaPagoPatchSchema = z
.object({
concepto: z.string().min(1, "El concepto es requerido").optional(),
monto: z.number().positive("El monto debe ser mayor a 0").optional(),
frecuencia: z.enum(FRECUENCIAS, { message: "Frecuencia invalida" }).optional(),
diaSemana: z.number().int().min(0).max(6).optional(),
diaMes: z.number().int().min(1).max(31).optional(),
fechaInicio: fechaISO.optional(),
fechaFin: fechaISO.nullable().optional(),
activo: z.boolean().optional(),
cotizacionId: z.string().min(1).nullable().optional(),
})
.superRefine((val, ctx) => {
// En un patch parcial los campos de dia pueden no venir: la condicion solo
// aplica si trae frecuencia (si no, el handler combina con el registro previo).
if (!val.frecuencia) return;
erroresFrecuencia(
val.frecuencia,
val.diaSemana,
val.diaMes,
(path, message) => ctx.addIssue({ code: "custom", path, message })
);
});
export const accesoClienteSchema = z.object({
email: z.string().email("Email invalido"),
password: z.string().min(6, "La contrasena debe tener al menos 6 caracteres"),
});
+138
View File
@@ -0,0 +1,138 @@
import { randomUUID } from "crypto";
import { mkdir, unlink, writeFile, stat } from "fs/promises";
import path from "path";
import sharp from "sharp";
// Almacenamiento de comprobantes de pago (imagenes o PDF) fuera de /public:
// los archivos solo se sirven por un route handler autenticado.
//
// UPLOAD_DIR/uploads (por defecto <cwd>/uploads) <- en Coolify es un volumen
// comprobantes/<pagoId>/<uuid>.webp|pdf
//
// Las imagenes se normalizan a WebP (calidad aceptable, tamano razonable) con
// limite de ancho; los PDF se guardan tal cual.
const MAX_BYTES = 10 * 1024 * 1024; // 10 MB del archivo original
const MAX_ANCHO = 1920;
const MIME_IMAGENES = new Set(["image/jpeg", "image/png", "image/webp", "image/heic", "image/heif"]);
const MIME_PDF = "application/pdf";
export interface GuardadoComprobante {
ruta: string; // relativa a UPLOAD_DIR (clave de ComprobantePago.archivoRuta)
mime: string; // image/webp | application/pdf
tamano: number; // bytes finales en disco
nombreOriginal: string;
}
export class ErrorUpload extends Error {
constructor(message: string) {
super(message);
this.name = "ErrorUpload";
}
}
export function directorioUploads(): string {
// turbopackIgnore: sin esto NFT tracer sigue process.cwd() y "traza" el
// proyecto completo (next.config.ts y demas) al bundle de esta ruta.
return process.env.UPLOAD_DIR || path.join(/*turbopackIgnore: true*/ process.cwd(), "uploads");
}
export function esImagen(mime: string): boolean {
return MIME_IMAGENES.has(mime);
}
export function esPdf(mime: string): boolean {
return mime === MIME_PDF;
}
export function esComprobantePermitido(mime: string): boolean {
return esImagen(mime) || esPdf(mime);
}
// Convierte un File de FormData a disco. Lanza ErrorUpload con mensaje en
// espanol si el archivo no es permitido o excede el limite.
export async function guardarComprobante(pagoId: string, file: File): Promise<GuardadoComprobante> {
if (!file || file.size === 0) throw new ErrorUpload("Debes seleccionar un archivo.");
if (file.size > MAX_BYTES) {
throw new ErrorUpload(`El archivo supera el limite de ${Math.round(MAX_BYTES / 1024 / 1024)} MB.`);
}
if (!esComprobantePermitido(file.type)) {
throw new ErrorUpload("Solo se aceptan imagenes (JPG, PNG, WebP) o PDF.");
}
const original = Buffer.from(await file.arrayBuffer());
// La ruta SE ALMACENA con separadores posix aunque el dev corra en Windows:
// los registros viajan a produccion (Linux) y alli un "\" no resuelve nada.
const subdir = "comprobantes/" + pagoId;
const absSubdir = path.join(directorioUploads(), "comprobantes", pagoId);
await mkdir(absSubdir, { recursive: true });
let bytes: Buffer;
let ext: string;
let mime: string;
if (esImagen(file.type)) {
try {
bytes = await sharp(original)
.rotate() // respeta orientacion EXIF
.resize({ width: MAX_ANCHO, withoutEnlargement: true })
.webp({ quality: 80, effort: 4 })
.toBuffer();
} catch {
throw new ErrorUpload("No se pudo procesar la imagen. Prueba con JPG o PNG.");
}
ext = "webp";
mime = "image/webp";
} else {
bytes = original;
ext = "pdf";
mime = MIME_PDF;
}
const nombre = `${randomUUID()}.${ext}`;
const abs = path.join(absSubdir, nombre);
await writeFile(abs, bytes);
return {
ruta: `${subdir}/${nombre}`,
mime,
tamano: bytes.length,
nombreOriginal: file.name || nombre,
};
}
// Borra el archivo del disco (rechazo del admin). Devuelve true si existia.
// Cualquier ruta que intente salir de UPLOAD_DIR se rechaza.
export async function eliminarComprobante(rutaRelativa: string): Promise<boolean> {
const abs = rutaAbsoluta(rutaRelativa);
if (!abs) return false;
try {
await unlink(abs);
return true;
} catch {
return false;
}
}
// Resuelve una ruta relativa a una absoluta DENTRO de UPLOAD_DIR; null si es
// invalida o intenta escapar (path traversal).
export function rutaAbsoluta(rutaRelativa: string): string | null {
if (!rutaRelativa) return null;
const base = directorioUploads();
const abs = path.resolve(base, rutaRelativa);
const rel = path.relative(base, abs);
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
return abs;
}
// Verifica que el archivo siga en disco y devuelve su tamano.
export async function archivoExiste(rutaRelativa: string): Promise<boolean> {
const abs = rutaAbsoluta(rutaRelativa);
if (!abs) return false;
try {
const s = await stat(abs);
return s.isFile();
} catch {
return false;
}
}
+45 -3
View File
@@ -6,13 +6,38 @@ const PUBLIC_PATHS = [
"/api/auth/login", "/api/auth/login",
"/api/auth/logout", "/api/auth/logout",
"/api/health", "/api/health",
// El service worker debe poder cargarse sin sesion: el navegador lo pide
// fuera del contexto de la pagina autenticada.
"/sw.js",
]; ];
// Prefijos a los que SOLO el rol "cliente" tiene acceso.
const CLIENTE_PATHS = ["/cliente", "/api/cliente"];
// Rutas autenticadas a las que acceden AMBOS roles; la pertenencia (cliente
// dueño de la cotizacion/comprobante) se valida dentro del route handler.
const RUTAS_COMPARTIDAS = ["/api/comprobantes", "/api/export/pdf"];
function isClientePath(pathname: string): boolean {
return CLIENTE_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"));
}
function esRutaCompartida(pathname: string): boolean {
return RUTAS_COMPARTIDAS.some((p) => pathname === p || pathname.startsWith(p + "/"));
}
function deny(request: NextRequest, pathname: string, message: string, destinoPagina: string): NextResponse {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: message }, { status: 403 });
}
return NextResponse.redirect(new URL(destinoPagina, request.url));
}
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl; const { pathname } = request.nextUrl;
const isPublic = const isPublic =
PUBLIC_PATHS.some((p) => pathname.startsWith(p)) || PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/")) ||
pathname.startsWith("/_next") || pathname.startsWith("/_next") ||
pathname === "/favicon.ico"; pathname === "/favicon.ico";
@@ -25,7 +50,9 @@ export async function middleware(request: NextRequest) {
if (isApi) { if (isApi) {
return NextResponse.json({ error: "No autenticado" }, { status: 401 }); return NextResponse.json({ error: "No autenticado" }, { status: 401 });
} }
return NextResponse.redirect(new URL("/login", request.url)); // El panel de cliente tiene su propia ruta de entrada.
const destino = isClientePath(pathname) ? "/login?panel=cliente" : "/login";
return NextResponse.redirect(new URL(destino, request.url));
} }
const session = await verifySession(token); const session = await verifySession(token);
@@ -40,9 +67,24 @@ export async function middleware(request: NextRequest) {
return response; return response;
} }
const rol = session.role || "asesor";
const esCliente = rol === "cliente";
// Separacion de paneles: cliente no ve nada del admin y viceversa,
// salvo las rutas compartidas donde el handler valida la pertenencia.
if (esCliente && !isClientePath(pathname) && !esRutaCompartida(pathname)) {
// Cliente colado en rutas del admin: devolverlo a su panel.
return deny(request, pathname, "Acceso restringido al panel de cliente", "/cliente");
}
if (!esCliente && isClientePath(pathname)) {
// Staff abriendo el panel de cliente: volver a su dashboard.
return deny(request, pathname, "Acceso restringido al panel de clientes", "/");
}
const requestHeaders = new Headers(request.headers); const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-user-id", session.userId); requestHeaders.set("x-user-id", session.userId);
requestHeaders.set("x-user-role", session.role || "asesor"); requestHeaders.set("x-user-role", rol);
if (session.clienteId) requestHeaders.set("x-cliente-id", session.clienteId);
return NextResponse.next({ return NextResponse.next({
request: { headers: requestHeaders }, request: { headers: requestHeaders },