Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14526f92f2 | ||
|
|
5e2b784c24 | ||
|
|
6402128dfc | ||
|
|
76e93e6615 |
+7
-1
@@ -43,7 +43,8 @@ MINIMAX_MODEL=MiniMax-M3
|
|||||||
VAPID_PUBLIC_KEY=
|
VAPID_PUBLIC_KEY=
|
||||||
VAPID_PRIVATE_KEY=
|
VAPID_PRIVATE_KEY=
|
||||||
# URL publica (links de correo y notificaciones). En Coolify: el dominio del servicio web.
|
# URL publica (links de correo y notificaciones). En Coolify: el dominio del servicio web.
|
||||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
# Variable de servidor: un NEXT_PUBLIC_* quedaria fijo en el bundle al compilar.
|
||||||
|
APP_URL=http://localhost:3000
|
||||||
|
|
||||||
# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log)
|
# SMTP de correos (opcionales: sin SMTP_HOST no se envia correo, solo avisa en log)
|
||||||
SMTP_HOST=
|
SMTP_HOST=
|
||||||
@@ -53,6 +54,11 @@ SMTP_PASS=
|
|||||||
SMTP_FROM=
|
SMTP_FROM=
|
||||||
SMTP_FROM_NAME=Cotizador E3
|
SMTP_FROM_NAME=Cotizador E3
|
||||||
|
|
||||||
|
# Recordatorio de pagos pendientes: cada cuantos dias se reenvia al cliente su
|
||||||
|
# estado de cuenta mientras siga debiendo cobros (desde las 9:00 hora de Mexico).
|
||||||
|
# 0 apaga el automatico; el boton "Enviar recordatorio" de /cobros sigue sirviendo.
|
||||||
|
COBROS_RECORDATORIO_DIAS=3
|
||||||
|
|
||||||
# Directorio de comprobantes. Local: vacio = <repo>/uploads.
|
# Directorio de comprobantes. Local: vacio = <repo>/uploads.
|
||||||
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml).
|
||||||
UPLOAD_DIR=
|
UPLOAD_DIR=
|
||||||
@@ -82,12 +82,15 @@ A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — se
|
|||||||
- **Fechas**: una fecha de cobro es fecha de calendario en `America/Mexico_City` persistida como medianoche UTC (`parseFechaCalendario` / `formatFechaCobro` / `formatFechaCorta`). No usar `new Date(iso)` directo.
|
- **Fechas**: una fecha de cobro es fecha de calendario en `America/Mexico_City` persistida como medianoche UTC (`parseFechaCalendario` / `formatFechaCobro` / `formatFechaCorta`). No usar `new Date(iso)` directo.
|
||||||
- **Scheduler**: `src/instrumentation.ts` importa `src/lib/scheduler.ts` **dentro del guard `NEXT_RUNTIME === "nodejs"`** (si lo mueves fuera, pg entra al bundle Edge y el build falla). Corre a los 20 s del arranque y cada 60 min: `generarCobros()` + `notificarCobrosNuevos()`.
|
- **Scheduler**: `src/instrumentation.ts` importa `src/lib/scheduler.ts` **dentro del guard `NEXT_RUNTIME === "nodejs"`** (si lo mueves fuera, pg entra al bundle Edge y el build falla). Corre a los 20 s del arranque y cada 60 min: `generarCobros()` + `notificarCobrosNuevos()`.
|
||||||
- **Notificaciones** (`src/lib/notificaciones.ts`): llamar **después** de persistir el cambio — `notificarCobrosNuevos(pagos)`, `notificarVerificacion(pagoId)`, `notificarRechazo(pagoId, motivo)`. Son best-effort; SMTP/VAPID sin configurar solo avisan en log (`email.ts` / `push.ts`), jamás tumbaron el flujo.
|
- **Notificaciones** (`src/lib/notificaciones.ts`): llamar **después** de persistir el cambio — `notificarCobrosNuevos(pagos)`, `notificarVerificacion(pagoId)`, `notificarRechazo(pagoId, motivo)`. Son best-effort; SMTP/VAPID sin configurar solo avisan en log (`email.ts` / `push.ts`), jamás tumbaron el flujo.
|
||||||
|
- **Recordatorios de pagos pendientes** (`enviarRecordatoriosPendientes` en `notificaciones.ts`): "por pagar" = `pendiente | rechazado` con `fecha <= hoy` (`ESTADOS_POR_PAGAR`, `pagosPorCobrar()` en `cobros.ts`, que incluye programas inactivos). Manda **un estado de cuenta por cliente** (lista, total por moneda, datos bancarios de Configuración) por correo + push y sella `ultimoRecordatorioAt` / `recordatoriosEnviados` **solo si algún canal lo entregó**. El scheduler lo corre desde las 9:00 MX cuando algún cobro lleva `COBROS_RECORDATORIO_DIAS` (default 3; 0 = apagado) sin aviso, y lo hace **antes** de `notificarCobrosNuevos` para no mandar dos correos al mismo cliente en una corrida. Envío manual: `POST /api/cobros/recordatorios` (`{ clienteId? }`, ignora la espera) desde la sección "Pagos por cobrar" de `/cobros`.
|
||||||
- **Subidas**: `src/lib/uploads.ts` (`guardarComprobante`/`eliminarComprobante`) convierte imágenes a WebP con sharp (máx 1920 px, q80), PDFs tal cual, 10 MB. Las rutas se guardan con separadores `/` aunque el dev corra en Windows. El rechazo borra el archivo del servidor y el cliente puede volver a subir.
|
- **Subidas**: `src/lib/uploads.ts` (`guardarComprobante`/`eliminarComprobante`) convierte imágenes a WebP con sharp (máx 1920 px, q80), PDFs tal cual, 10 MB. Las rutas se guardan con separadores `/` aunque el dev corra en Windows. El rechazo borra el archivo del servidor y el cliente puede volver a subir.
|
||||||
- **UI**: admin en `/cobros` (nav del Sidebar), panel cliente en `/cliente` (shell propio, sin el Sidebar de staff) con `public/sw.js` para Web Push.
|
- **UI**: admin en `/cobros` (nav del Sidebar), panel cliente en `/cliente` (shell propio, sin el Sidebar de staff) con `public/sw.js` para Web Push.
|
||||||
|
|
||||||
## Deployment (Coolify)
|
## Deployment (Coolify)
|
||||||
|
|
||||||
- Production stack: `docker-compose.coolify.yml` (postgres + web + api). In Coolify set **Docker Compose Location** to `/docker-compose.coolify.yml`. Local dev keeps using `docker-compose.yml` + `start.bat`.
|
- Production stack: postgres + web + api. The live Coolify app (`cotizador`, uuid `e6vie34d83iv5vw3eyzinl3s`, https://cotizador.urieljareth.org) has **Docker Compose Location `/docker-compose.yaml`** — the byte-identical copy — so both files must stay in sync. Local dev keeps using `docker-compose.yml` + `start.bat`.
|
||||||
|
- **Deploys come from GitHub `main` (`origin`), not Gitea.** Auto-deploy is on: a push to GitHub `main` *is* the deploy (~15 min full build). Pushing to `gitea` only mirrors the code. Don't also trigger the deploy API after a push, or two deploys race.
|
||||||
|
- `APP_URL` must be set in Coolify (`https://cotizador.urieljareth.org`): email links fall back to `http://localhost:3000` without it. **Never read a runtime value through a `NEXT_PUBLIC_*` name on the server** — Next inlines those at build time (even via a computed key), and the production image is built without them.
|
||||||
- The `web` container runs `prisma migrate deploy` on every start, and the seed only when `RUN_SEED=true`. Seed users/passwords come from `SEED_*` env vars (see `.env.example`) — `prisma/seed.ts` never overwrites an existing password unless the env var is set.
|
- The `web` container runs `prisma migrate deploy` on every start, and the seed only when `RUN_SEED=true`. Seed users/passwords come from `SEED_*` env vars (see `.env.example`) — `prisma/seed.ts` never overwrites an existing password unless the env var is set.
|
||||||
- `DATABASE_URL` is only used by the Prisma CLI (migrations); the apps use individual `DB_*` vars. Both must point to the same DB.
|
- `DATABASE_URL` is only used by the Prisma CLI (migrations); the apps use individual `DB_*` vars. Both must point to the same DB.
|
||||||
- Healthchecks: web `GET /api/health` (public in middleware, pings DB), api `GET /health`.
|
- Healthchecks: web `GET /api/health` (public in middleware, pings DB), api `GET /health`.
|
||||||
|
|||||||
@@ -56,7 +56,8 @@ services:
|
|||||||
- 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.
|
# URL publica: la usan los links de correo y de las notificaciones push.
|
||||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
# Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar).
|
||||||
|
- APP_URL=${APP_URL}
|
||||||
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
|
# 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.
|
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
|
||||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||||
@@ -68,6 +69,8 @@ services:
|
|||||||
- SMTP_PASS=${SMTP_PASS}
|
- SMTP_PASS=${SMTP_PASS}
|
||||||
- SMTP_FROM=${SMTP_FROM}
|
- SMTP_FROM=${SMTP_FROM}
|
||||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
||||||
|
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
||||||
|
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||||
- UPLOAD_DIR=/app/uploads
|
- UPLOAD_DIR=/app/uploads
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+4
-1
@@ -56,7 +56,8 @@ services:
|
|||||||
- 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.
|
# URL publica: la usan los links de correo y de las notificaciones push.
|
||||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
# Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar).
|
||||||
|
- APP_URL=${APP_URL}
|
||||||
# Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())"
|
# 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.
|
# La app funciona sin ellas: las notificaciones se omiten con aviso en log.
|
||||||
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
|
||||||
@@ -68,6 +69,8 @@ services:
|
|||||||
- SMTP_PASS=${SMTP_PASS}
|
- SMTP_PASS=${SMTP_PASS}
|
||||||
- SMTP_FROM=${SMTP_FROM}
|
- SMTP_FROM=${SMTP_FROM}
|
||||||
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
- SMTP_FROM_NAME=${SMTP_FROM_NAME:-Cotizador E3}
|
||||||
|
# Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado).
|
||||||
|
- COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3}
|
||||||
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
# Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente.
|
||||||
- UPLOAD_DIR=/app/uploads
|
- UPLOAD_DIR=/app/uploads
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "PagoRecurrente" ADD COLUMN "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN "ultimoRecordatorioAt" TIMESTAMP(3);
|
||||||
@@ -328,6 +328,11 @@ model PagoRecurrente {
|
|||||||
verificadoAt DateTime?
|
verificadoAt DateTime?
|
||||||
rechazadoAt DateTime?
|
rechazadoAt DateTime?
|
||||||
rechazoMotivo String?
|
rechazoMotivo String?
|
||||||
|
// Ultimo recordatorio de pago enviado al cliente mientras el cobro sigue
|
||||||
|
// por pagar (pendiente/rechazado). El scheduler lo usa para no repetir el
|
||||||
|
// aviso antes de COBROS_RECORDATORIO_DIAS; el envio manual lo ignora.
|
||||||
|
ultimoRecordatorioAt DateTime?
|
||||||
|
recordatoriosEnviados Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,19 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, useRef } from "react";
|
import { useState, useEffect, useCallback, useRef } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { RefreshCw } from "lucide-react";
|
||||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||||
import { ProgramasTabla } from "./ProgramasTabla";
|
import { ProgramasTabla } from "./ProgramasTabla";
|
||||||
import { PagosTabla } from "./PagosTabla";
|
import { PagosTabla } from "./PagosTabla";
|
||||||
import type { ProgramaRow, ClienteOpt, PagoRow } from "./types";
|
import { PorCobrarTabla } from "./PorCobrarTabla";
|
||||||
|
import type {
|
||||||
|
ProgramaRow,
|
||||||
|
ClienteOpt,
|
||||||
|
PagoRow,
|
||||||
|
SaldoClienteRow,
|
||||||
|
ResultadoRecordatorioRow,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
// Frecuencia legible en la tabla de programas.
|
// Frecuencia legible en la tabla de programas.
|
||||||
export function frecuenciaLegible(p: {
|
export function frecuenciaLegible(p: {
|
||||||
@@ -18,27 +26,52 @@ export function frecuenciaLegible(p: {
|
|||||||
"domingo",
|
"domingo",
|
||||||
"lunes",
|
"lunes",
|
||||||
"martes",
|
"martes",
|
||||||
"miercoles",
|
"miércoles",
|
||||||
"jueves",
|
"jueves",
|
||||||
"viernes",
|
"viernes",
|
||||||
"sabado",
|
"sábado",
|
||||||
];
|
];
|
||||||
if (p.frecuencia === "semanal") {
|
if (p.frecuencia === "semanal") {
|
||||||
const d = p.diaSemana ?? 0;
|
const d = p.diaSemana ?? 0;
|
||||||
return `Cada ${dias[d]}`;
|
return `Cada ${dias[d]}`;
|
||||||
}
|
}
|
||||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||||
return `Cada dia ${p.diaMes ?? 1}`;
|
return `Cada día ${p.diaMes ?? 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Por que un recordatorio no llego a nadie, en palabras del admin.
|
||||||
|
function motivoNoEntregado(
|
||||||
|
r: ResultadoRecordatorioRow,
|
||||||
|
canales: { correo: boolean; push: boolean }
|
||||||
|
): string {
|
||||||
|
if (!canales.correo && !canales.push) {
|
||||||
|
return "No hay SMTP (correo) ni VAPID (push) configurados en el servidor";
|
||||||
|
}
|
||||||
|
if (r.correo === "error") return "Falló el envío del correo; revisa el log del servidor";
|
||||||
|
if (r.correo === "sin_email") {
|
||||||
|
return "El cliente no tiene correo y no activó los avisos push";
|
||||||
|
}
|
||||||
|
if (r.correo === "omitido") {
|
||||||
|
return "SMTP no configurado y el cliente no activó los avisos push";
|
||||||
|
}
|
||||||
|
return "No se pudo entregar por ningún canal";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CobrosClient({
|
export function CobrosClient({
|
||||||
programas,
|
programas,
|
||||||
clientes,
|
clientes,
|
||||||
pagosIniciales,
|
pagosIniciales,
|
||||||
|
saldos,
|
||||||
|
diasRecordatorio,
|
||||||
|
enRevision,
|
||||||
}: {
|
}: {
|
||||||
programas: ProgramaRow[];
|
programas: ProgramaRow[];
|
||||||
clientes: ClienteOpt[];
|
clientes: ClienteOpt[];
|
||||||
pagosIniciales: PagoRow[];
|
pagosIniciales: PagoRow[];
|
||||||
|
saldos: SaldoClienteRow[];
|
||||||
|
diasRecordatorio: number;
|
||||||
|
// Comprobantes esperando aprobacion (para la franja de resumen).
|
||||||
|
enRevision: number;
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const showConfirm = useConfirm();
|
const showConfirm = useConfirm();
|
||||||
@@ -54,6 +87,7 @@ export function CobrosClient({
|
|||||||
const [clienteFiltro, setClienteFiltro] = useState("");
|
const [clienteFiltro, setClienteFiltro] = useState("");
|
||||||
const [desdeFiltro, setDesdeFiltro] = useState("");
|
const [desdeFiltro, setDesdeFiltro] = useState("");
|
||||||
const [hastaFiltro, setHastaFiltro] = useState("");
|
const [hastaFiltro, setHastaFiltro] = useState("");
|
||||||
|
const [enviandoRecordatorio, setEnviandoRecordatorio] = useState<string | null>(null);
|
||||||
|
|
||||||
const cargarPagos = useCallback(async () => {
|
const cargarPagos = useCallback(async () => {
|
||||||
setCargandoPagos(true);
|
setCargandoPagos(true);
|
||||||
@@ -89,7 +123,7 @@ export function CobrosClient({
|
|||||||
const ok = await showConfirm({
|
const ok = await showConfirm({
|
||||||
title: "Generar cobros",
|
title: "Generar cobros",
|
||||||
message:
|
message:
|
||||||
"Se generaran los cobros pendientes de todos los programas activos hasta hoy. Continuar?",
|
"Se generarán los cobros pendientes de todos los programas activos hasta hoy. ¿Continuar?",
|
||||||
confirmText: "Generar",
|
confirmText: "Generar",
|
||||||
});
|
});
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
@@ -106,13 +140,69 @@ export function CobrosClient({
|
|||||||
}
|
}
|
||||||
const n = data.generados ?? 0;
|
const n = data.generados ?? 0;
|
||||||
toast(
|
toast(
|
||||||
n > 0 ? `Se generaron ${n} cobros` : "No habia cobros pendientes",
|
n > 0 ? `Se generaron ${n} cobros` : "No había cobros pendientes",
|
||||||
"success"
|
"success"
|
||||||
);
|
);
|
||||||
cargarPagos();
|
cargarPagos();
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
toast("Error de conexion", "error");
|
toast("Error de conexión", "error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// saldo = null -> a todos los clientes con pagos vencidos.
|
||||||
|
const recordar = async (saldo: SaldoClienteRow | null) => {
|
||||||
|
const ok = await showConfirm({
|
||||||
|
title: "Enviar recordatorio de pago",
|
||||||
|
message: saldo
|
||||||
|
? `Se enviará a ${saldo.nombre} su estado de cuenta: ${saldo.pagos} ${saldo.pagos === 1 ? "cobro pendiente" : "cobros pendientes"} por ${formatTotales(saldo.totales)}, por correo y aviso push.`
|
||||||
|
: `Se enviará el estado de cuenta a ${saldos.length} ${saldos.length === 1 ? "cliente" : "clientes"} con pagos vencidos, por correo y aviso push.`,
|
||||||
|
confirmText: "Enviar",
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
setEnviandoRecordatorio(saldo?.clienteId ?? "*");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/cobros/recordatorios", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(saldo ? { clienteId: saldo.clienteId } : {}),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
toast(data.error || "Error al enviar el recordatorio", "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const resultados: ResultadoRecordatorioRow[] = data.resultados ?? [];
|
||||||
|
const canales = data.canales ?? { correo: false, push: false };
|
||||||
|
const entregados = resultados.filter((r) => r.entregado);
|
||||||
|
if (resultados.length === 0) {
|
||||||
|
toast("No hay pagos vencidos por recordar", "info");
|
||||||
|
} else if (entregados.length === resultados.length) {
|
||||||
|
toast(
|
||||||
|
entregados.length === 1
|
||||||
|
? `Recordatorio enviado a ${entregados[0].cliente}`
|
||||||
|
: `Recordatorio enviado a ${entregados.length} clientes`,
|
||||||
|
"success"
|
||||||
|
);
|
||||||
|
} else if (entregados.length > 0) {
|
||||||
|
const fallidos = resultados.filter((r) => !r.entregado).map((r) => r.cliente);
|
||||||
|
toast(
|
||||||
|
`Enviado a ${entregados.length} de ${resultados.length}. Sin entregar: ${fallidos.join(", ")}`,
|
||||||
|
"info"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast(
|
||||||
|
resultados.length === 1
|
||||||
|
? `No se envió: ${motivoNoEntregado(resultados[0], canales)}`
|
||||||
|
: `No se envió a ningún cliente: ${motivoNoEntregado(resultados[0], canales)}`,
|
||||||
|
"error"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
router.refresh();
|
||||||
|
} catch {
|
||||||
|
toast("Error de conexión", "error");
|
||||||
|
} finally {
|
||||||
|
setEnviandoRecordatorio(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -121,8 +211,8 @@ export function CobrosClient({
|
|||||||
const ok = await showConfirm({
|
const ok = await showConfirm({
|
||||||
title: activar ? "Activar programa" : "Desactivar programa",
|
title: activar ? "Activar programa" : "Desactivar programa",
|
||||||
message: activar
|
message: activar
|
||||||
? `Activar el programa "${p.concepto}"? Se generaran cobros en sus proximos periodos.`
|
? `¿Activar el programa "${p.concepto}"? Se generarán cobros en sus próximos periodos.`
|
||||||
: `Desactivar el programa "${p.concepto}"? No se generaran mas cobros, pero los existentes se conservan.`,
|
: `¿Desactivar el programa "${p.concepto}"? No se generarán más cobros, pero los existentes se conservan.`,
|
||||||
confirmText: activar ? "Activar" : "Desactivar",
|
confirmText: activar ? "Activar" : "Desactivar",
|
||||||
danger: !activar,
|
danger: !activar,
|
||||||
});
|
});
|
||||||
@@ -141,7 +231,7 @@ export function CobrosClient({
|
|||||||
toast(activar ? "Programa activado" : "Programa desactivado", "success");
|
toast(activar ? "Programa activado" : "Programa desactivado", "success");
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
toast("Error de conexion", "error");
|
toast("Error de conexión", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -163,8 +253,9 @@ export function CobrosClient({
|
|||||||
}
|
}
|
||||||
toast("Cobro verificado", "success");
|
toast("Cobro verificado", "success");
|
||||||
cargarPagos();
|
cargarPagos();
|
||||||
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
toast("Error de conexion", "error");
|
toast("Error de conexión", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -189,28 +280,85 @@ export function CobrosClient({
|
|||||||
}
|
}
|
||||||
toast("Comprobante rechazado", "success");
|
toast("Comprobante rechazado", "success");
|
||||||
cargarPagos();
|
cargarPagos();
|
||||||
|
// El cobro vuelve a estar por pagar: refresca el saldo por cliente.
|
||||||
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
toast("Error de conexion", "error");
|
toast("Error de conexión", "error");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const totalPorCobrar: Record<string, number> = {};
|
||||||
|
for (const s of saldos) {
|
||||||
|
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||||
|
totalPorCobrar[moneda] = (totalPorCobrar[moneda] ?? 0) + total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const programasActivos = programas.filter((p) => p.activo).length;
|
||||||
|
const resumen = [
|
||||||
|
{
|
||||||
|
href: "#por-cobrar",
|
||||||
|
label: "Por cobrar",
|
||||||
|
valor: saldos.length ? formatTotales(totalPorCobrar) : "$0",
|
||||||
|
detalle: saldos.length
|
||||||
|
? `${saldos.length} ${saldos.length === 1 ? "cliente con adeudo" : "clientes con adeudo"}`
|
||||||
|
: "Nadie tiene pagos vencidos",
|
||||||
|
alerta: saldos.length > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "#comprobantes",
|
||||||
|
label: "Comprobantes por revisar",
|
||||||
|
valor: String(enRevision),
|
||||||
|
detalle: enRevision ? "Esperan tu aprobación" : "Todo revisado",
|
||||||
|
alerta: enRevision > 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
href: "#programas",
|
||||||
|
label: "Programas activos",
|
||||||
|
valor: String(programasActivos),
|
||||||
|
detalle: `${programas.length - programasActivos} inactivos`,
|
||||||
|
alerta: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-10">
|
<div className="space-y-10">
|
||||||
<section>
|
<nav
|
||||||
<ProgramasTabla
|
aria-label="Resumen de cobros"
|
||||||
programas={programas}
|
className="grid grid-cols-1 sm:grid-cols-3 bg-card-bg rounded-xl border border-border divide-y sm:divide-y-0 sm:divide-x divide-border overflow-hidden"
|
||||||
clientes={clientes}
|
>
|
||||||
onToggleActivo={toggleActivo}
|
{resumen.map((r) => (
|
||||||
|
<a key={r.href} href={r.href} className="block px-5 py-4 hover:bg-gray-50 transition-colors">
|
||||||
|
<p className="text-xs font-medium text-muted">{r.label}</p>
|
||||||
|
<p className={`text-xl font-semibold tracking-tight tabular-nums mt-1 ${r.alerta ? "text-foreground" : "text-muted"}`}>
|
||||||
|
{r.valor}
|
||||||
|
</p>
|
||||||
|
<p className={`text-xs mt-0.5 ${r.alerta ? "text-amber-700" : "text-muted"}`}>{r.detalle}</p>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<section id="por-cobrar" className="scroll-mt-20">
|
||||||
|
<PorCobrarTabla
|
||||||
|
saldos={saldos}
|
||||||
|
diasRecordatorio={diasRecordatorio}
|
||||||
|
enviando={enviandoRecordatorio}
|
||||||
|
onRecordar={recordar}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section>
|
<section id="comprobantes" className="scroll-mt-20">
|
||||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||||
<h2 className="text-lg font-semibold">Cobros generados</h2>
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">Comprobantes y cobros</h2>
|
||||||
|
<p className="text-muted text-sm mt-1">
|
||||||
|
Revisa los comprobantes que suben tus clientes y consulta cualquier cobro generado.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={generarAhora}
|
onClick={generarAhora}
|
||||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90"
|
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
|
<RefreshCw className="w-4 h-4" />
|
||||||
Generar cobros ahora
|
Generar cobros ahora
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -225,7 +373,7 @@ export function CobrosClient({
|
|||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
<option value="pendiente">Pendiente</option>
|
<option value="pendiente">Pendiente</option>
|
||||||
<option value="en_revision">En revision</option>
|
<option value="en_revision">En revisión</option>
|
||||||
<option value="verificado">Verificado</option>
|
<option value="verificado">Verificado</option>
|
||||||
<option value="rechazado">Rechazado</option>
|
<option value="rechazado">Rechazado</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -272,6 +420,14 @@ export function CobrosClient({
|
|||||||
onRechazar={rechazar}
|
onRechazar={rechazar}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section id="programas" className="scroll-mt-20">
|
||||||
|
<ProgramasTabla
|
||||||
|
programas={programas}
|
||||||
|
clientes={clientes}
|
||||||
|
onToggleActivo={toggleActivo}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const ESTILOS: Record<string, { cls: string; label: string }> = {
|
|||||||
},
|
},
|
||||||
[ESTADOS_PAGO.EN_REVISION]: {
|
[ESTADOS_PAGO.EN_REVISION]: {
|
||||||
cls: "bg-blue-100 text-blue-800",
|
cls: "bg-blue-100 text-blue-800",
|
||||||
label: "En revision",
|
label: "En revisión",
|
||||||
},
|
},
|
||||||
[ESTADOS_PAGO.VERIFICADO]: {
|
[ESTADOS_PAGO.VERIFICADO]: {
|
||||||
cls: "bg-green-100 text-green-800",
|
cls: "bg-green-100 text-green-800",
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Check, X, FileText } from "lucide-react";
|
import { Check, X, FileText } from "lucide-react";
|
||||||
import { formatCurrency } from "@/lib/calculators";
|
import { formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
|
||||||
import { EstadoPagoBadge } from "./EstadoPagoBadge";
|
import { EstadoPagoBadge } from "./EstadoPagoBadge";
|
||||||
import type { PagoRow } from "./types";
|
import type { PagoRow } from "./types";
|
||||||
|
|
||||||
@@ -37,8 +36,8 @@ export function PagosTabla({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||||
<table className="w-full text-sm">
|
<table className="w-full min-w-[52rem] text-sm tabular-nums">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-border bg-gray-50">
|
<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">Fecha</th>
|
||||||
@@ -56,7 +55,7 @@ export function PagosTabla({
|
|||||||
<td className="px-5 py-3">{formatFechaCorta(new Date(p.fecha))}</td>
|
<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.concepto}</td>
|
||||||
<td className="px-5 py-3">{p.programa.cliente.nombre}</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-right">{formatMonto(p.monto, p.programa.moneda)}</td>
|
||||||
<td className="px-5 py-3 text-center">
|
<td className="px-5 py-3 text-center">
|
||||||
<EstadoPagoBadge estado={p.estado} />
|
<EstadoPagoBadge estado={p.estado} />
|
||||||
{p.estado === "rechazado" && p.rechazoMotivo && (
|
{p.estado === "rechazado" && p.rechazoMotivo && (
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { BellRing, Send } from "lucide-react";
|
||||||
|
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||||
|
import type { SaldoClienteRow } from "./types";
|
||||||
|
|
||||||
|
// Saldo vencido por cliente y envio del recordatorio de pago (estado de cuenta
|
||||||
|
// por correo + push). El scheduler lo reenvia solo cada `diasRecordatorio`
|
||||||
|
// dias; estos botones lo mandan en el momento.
|
||||||
|
export function PorCobrarTabla({
|
||||||
|
saldos,
|
||||||
|
diasRecordatorio,
|
||||||
|
enviando,
|
||||||
|
onRecordar,
|
||||||
|
}: {
|
||||||
|
saldos: SaldoClienteRow[];
|
||||||
|
diasRecordatorio: number;
|
||||||
|
// clienteId en envio, "*" para todos, null si no hay envio en curso.
|
||||||
|
enviando: string | null;
|
||||||
|
onRecordar: (saldo: SaldoClienteRow | null) => void;
|
||||||
|
}) {
|
||||||
|
const totalGeneral: Record<string, number> = {};
|
||||||
|
for (const s of saldos) {
|
||||||
|
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||||
|
totalGeneral[moneda] = (totalGeneral[moneda] ?? 0) + total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">Pagos por cobrar</h2>
|
||||||
|
<p className="text-muted text-sm mt-1">
|
||||||
|
{diasRecordatorio > 0
|
||||||
|
? `Cobros vencidos sin pago o con comprobante rechazado. El recordatorio se reenvía solo cada ${diasRecordatorio} ${diasRecordatorio === 1 ? "día" : "días"} a partir de las 9:00.`
|
||||||
|
: "Cobros vencidos sin pago o con comprobante rechazado. El recordatorio automático está desactivado (COBROS_RECORDATORIO_DIAS=0)."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{saldos.length > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={() => onRecordar(null)}
|
||||||
|
disabled={enviando !== null}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<BellRing className="w-4 h-4" />
|
||||||
|
{enviando === "*" ? "Enviando..." : "Recordar a todos"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{saldos.length === 0 ? (
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||||
|
<h3 className="text-lg font-semibold mb-2">Sin pagos vencidos</h3>
|
||||||
|
<p className="text-muted">Ningún cliente tiene cobros pendientes de pago.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[48rem] text-sm tabular-nums">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-border bg-gray-50">
|
||||||
|
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||||
|
<th className="text-center px-5 py-3 font-medium text-muted">Cobros</th>
|
||||||
|
<th className="text-right px-5 py-3 font-medium text-muted">Adeudo</th>
|
||||||
|
<th className="text-left px-5 py-3 font-medium text-muted">Más antiguo</th>
|
||||||
|
<th className="text-left px-5 py-3 font-medium text-muted">Último recordatorio</th>
|
||||||
|
<th className="text-center px-5 py-3 font-medium text-muted">Acción</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{saldos.map((s) => (
|
||||||
|
<tr key={s.clienteId} className="border-b border-border hover:bg-gray-50">
|
||||||
|
<td className="px-5 py-3">
|
||||||
|
<div className="font-medium">{s.nombre}</div>
|
||||||
|
{s.empresa && <div className="text-xs text-muted">{s.empresa}</div>}
|
||||||
|
</td>
|
||||||
|
<td className="px-5 py-3 text-center">{s.pagos}</td>
|
||||||
|
<td className="px-5 py-3 text-right font-medium whitespace-nowrap">
|
||||||
|
{formatTotales(s.totales)}
|
||||||
|
</td>
|
||||||
|
<td className="px-5 py-3">
|
||||||
|
<div>{formatFechaCorta(new Date(s.masAntigua))}</div>
|
||||||
|
<div className={`text-xs ${s.diasAtraso > 0 ? "text-danger" : "text-muted"}`}>
|
||||||
|
{s.diasAtraso === 0
|
||||||
|
? "vence hoy"
|
||||||
|
: `${s.diasAtraso} ${s.diasAtraso === 1 ? "día" : "días"} de atraso`}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-5 py-3 text-muted">
|
||||||
|
{s.ultimoRecordatorio
|
||||||
|
? formatFechaCorta(new Date(s.ultimoRecordatorio))
|
||||||
|
: "Nunca"}
|
||||||
|
</td>
|
||||||
|
<td className="px-5 py-3 text-center">
|
||||||
|
<button
|
||||||
|
onClick={() => onRecordar(s)}
|
||||||
|
disabled={enviando !== null || !s.contactable}
|
||||||
|
title={
|
||||||
|
s.contactable
|
||||||
|
? "Enviar estado de cuenta por correo y push"
|
||||||
|
: "El cliente no tiene email ni cuenta de panel"
|
||||||
|
}
|
||||||
|
className="inline-flex items-center gap-1 text-xs text-primary hover:underline disabled:opacity-40 disabled:no-underline disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
<Send className="w-3 h-3" />
|
||||||
|
{enviando === s.clienteId ? "Enviando..." : "Enviar recordatorio"}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr className="bg-gray-50">
|
||||||
|
<td className="px-5 py-3 font-medium" colSpan={2}>
|
||||||
|
Total por cobrar
|
||||||
|
</td>
|
||||||
|
<td className="px-5 py-3 text-right font-semibold whitespace-nowrap">
|
||||||
|
{formatTotales(totalGeneral)}
|
||||||
|
</td>
|
||||||
|
<td colSpan={3} />
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,18 +4,17 @@ import { useState } from "react";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Pencil, Power, Plus } from "lucide-react";
|
import { Pencil, Power, Plus } from "lucide-react";
|
||||||
import { useToast } from "@/components/ui/DialogProvider";
|
import { useToast } from "@/components/ui/DialogProvider";
|
||||||
import { formatCurrency } from "@/lib/calculators";
|
import { formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||||
import { formatFechaCorta } from "@/lib/cobros-fechas";
|
|
||||||
import type { ProgramaRow, ClienteOpt } from "./types";
|
import type { ProgramaRow, ClienteOpt } from "./types";
|
||||||
|
|
||||||
const DIAS = [
|
const DIAS = [
|
||||||
"Domingo",
|
"Domingo",
|
||||||
"Lunes",
|
"Lunes",
|
||||||
"Martes",
|
"Martes",
|
||||||
"Miercoles",
|
"Miércoles",
|
||||||
"Jueves",
|
"Jueves",
|
||||||
"Viernes",
|
"Viernes",
|
||||||
"Sabado",
|
"Sábado",
|
||||||
];
|
];
|
||||||
|
|
||||||
function frecuenciaTexto(p: {
|
function frecuenciaTexto(p: {
|
||||||
@@ -25,7 +24,7 @@ function frecuenciaTexto(p: {
|
|||||||
}): string {
|
}): string {
|
||||||
if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`;
|
if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`;
|
||||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||||
return `Cada dia ${p.diaMes ?? 1}`;
|
return `Cada día ${p.diaMes ?? 1}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function EstadoProgramaBadge({ activo }: { activo: boolean }) {
|
function EstadoProgramaBadge({ activo }: { activo: boolean }) {
|
||||||
@@ -154,7 +153,7 @@ export function ProgramasTabla({
|
|||||||
setDialogo(null);
|
setDialogo(null);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
toast("Error de conexion", "error");
|
toast("Error de conexión", "error");
|
||||||
} finally {
|
} finally {
|
||||||
setGuardando(false);
|
setGuardando(false);
|
||||||
}
|
}
|
||||||
@@ -162,7 +161,7 @@ export function ProgramasTabla({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||||
<h2 className="text-lg font-semibold">Programas de pago</h2>
|
<h2 className="text-lg font-semibold">Programas de pago</h2>
|
||||||
<button
|
<button
|
||||||
onClick={abrirNuevo}
|
onClick={abrirNuevo}
|
||||||
@@ -181,15 +180,15 @@ export function ProgramasTabla({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||||
<table className="w-full text-sm">
|
<table className="w-full min-w-[56rem] text-sm tabular-nums">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-border bg-gray-50">
|
<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">Concepto</th>
|
||||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</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-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">Frecuencia</th>
|
||||||
<th className="text-left px-5 py-3 font-medium text-muted">Proximo cobro</th>
|
<th className="text-left px-5 py-3 font-medium text-muted">Próximo 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">Estado</th>
|
||||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -204,7 +203,7 @@ export function ProgramasTabla({
|
|||||||
<div className="text-xs text-muted">{p.cliente.empresa}</div>
|
<div className="text-xs text-muted">{p.cliente.empresa}</div>
|
||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3 text-right">{formatCurrency(p.monto)}</td>
|
<td className="px-5 py-3 text-right">{formatMonto(p.monto, p.moneda)}</td>
|
||||||
<td className="px-5 py-3">{frecuenciaTexto(p)}</td>
|
<td className="px-5 py-3">{frecuenciaTexto(p)}</td>
|
||||||
<td className="px-5 py-3">
|
<td className="px-5 py-3">
|
||||||
{p.proximaFecha
|
{p.proximaFecha
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { proximaFecha } from "@/lib/cobros";
|
import {
|
||||||
|
agruparPorCliente,
|
||||||
|
calendarioDe,
|
||||||
|
diasDeAtraso,
|
||||||
|
diasRecordatorio,
|
||||||
|
pagosPorCobrar,
|
||||||
|
proximaFecha,
|
||||||
|
totalesPorMoneda,
|
||||||
|
} from "@/lib/cobros";
|
||||||
import { CobrosClient } from "./CobrosClient";
|
import { CobrosClient } from "./CobrosClient";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -22,7 +30,7 @@ type ProgramaConCliente = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function CobrosPage() {
|
export default async function CobrosPage() {
|
||||||
const [programas, clientes, pagosIniciales] = await Promise.all([
|
const [programas, clientes, pagosIniciales, porCobrar] = await Promise.all([
|
||||||
prisma.programaPago.findMany({
|
prisma.programaPago.findMany({
|
||||||
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
orderBy: [{ activo: "desc" }, { createdAt: "desc" }],
|
||||||
include: {
|
include: {
|
||||||
@@ -49,6 +57,7 @@ export default async function CobrosPage() {
|
|||||||
comprobante: true,
|
comprobante: true,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
pagosPorCobrar(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const programasData = (programas as ProgramaConCliente[]).map((p) => {
|
const programasData = (programas as ProgramaConCliente[]).map((p) => {
|
||||||
@@ -98,12 +107,35 @@ export default async function CobrosPage() {
|
|||||||
: null,
|
: null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Saldo vencido por cliente, del mas atrasado al mas reciente (pagosPorCobrar
|
||||||
|
// ya viene ordenado por fecha y el Map conserva el orden de aparicion).
|
||||||
|
const saldosData = [...agruparPorCliente(porCobrar)].map(([clienteId, lista]) => {
|
||||||
|
const cliente = lista[0].programa.cliente;
|
||||||
|
let ultimo: Date | null = null;
|
||||||
|
for (const p of lista) {
|
||||||
|
if (p.ultimoRecordatorioAt && (!ultimo || p.ultimoRecordatorioAt > ultimo)) {
|
||||||
|
ultimo = p.ultimoRecordatorioAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
clienteId,
|
||||||
|
nombre: cliente.nombre,
|
||||||
|
empresa: cliente.empresa,
|
||||||
|
pagos: lista.length,
|
||||||
|
totales: totalesPorMoneda(lista),
|
||||||
|
masAntigua: lista[0].fecha.toISOString(),
|
||||||
|
diasAtraso: diasDeAtraso(lista[0].fecha),
|
||||||
|
ultimoRecordatorio: ultimo ? calendarioDe(ultimo).toISOString() : null,
|
||||||
|
contactable: Boolean(cliente.email || cliente.usuario),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h1 className="text-2xl font-bold">Cobros recurrentes</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Cobros recurrentes</h1>
|
||||||
<p className="text-muted text-sm mt-1">
|
<p className="text-muted text-sm mt-1">
|
||||||
Programa cobros periodicos y revisa los comprobantes de tus clientes
|
Cobra a tiempo, revisa comprobantes y programa cobros periódicos
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -111,6 +143,9 @@ export default async function CobrosPage() {
|
|||||||
programas={programasData}
|
programas={programasData}
|
||||||
clientes={clientesData}
|
clientes={clientesData}
|
||||||
pagosIniciales={pagosData}
|
pagosIniciales={pagosData}
|
||||||
|
saldos={saldosData}
|
||||||
|
diasRecordatorio={diasRecordatorio()}
|
||||||
|
enRevision={pagosData.length}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -43,3 +43,32 @@ export type PagoRow = {
|
|||||||
};
|
};
|
||||||
comprobante: ComprobanteMeta | null;
|
comprobante: ComprobanteMeta | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Saldo vencido de un cliente (cobros pendientes o rechazados con fecha <= hoy).
|
||||||
|
export type SaldoClienteRow = {
|
||||||
|
clienteId: string;
|
||||||
|
nombre: string;
|
||||||
|
empresa: string | null;
|
||||||
|
pagos: number;
|
||||||
|
// Total por moneda: un cliente puede tener programas en MXN y USD.
|
||||||
|
totales: Record<string, number>;
|
||||||
|
masAntigua: string;
|
||||||
|
diasAtraso: number;
|
||||||
|
// Fecha de calendario MX del ultimo recordatorio entregado, o null.
|
||||||
|
ultimoRecordatorio: string | null;
|
||||||
|
// Hay a donde mandar el aviso: email del cliente o cuenta de panel.
|
||||||
|
contactable: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Respuesta de POST /api/cobros/recordatorios (espejo de ResultadoRecordatorio
|
||||||
|
// en src/lib/notificaciones.ts, que no se importa desde el navegador).
|
||||||
|
export type ResultadoRecordatorioRow = {
|
||||||
|
clienteId: string;
|
||||||
|
cliente: string;
|
||||||
|
pagos: number;
|
||||||
|
totales: Record<string, number>;
|
||||||
|
correo: "enviado" | "omitido" | "sin_email" | "error";
|
||||||
|
push: number;
|
||||||
|
entregado: boolean;
|
||||||
|
pagoIds: string[];
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { requireStaff } from "@/lib/auth";
|
||||||
|
import { smtpConfigurado } from "@/lib/email";
|
||||||
|
import { pushConfigurado } from "@/lib/push";
|
||||||
|
import { enviarRecordatoriosPendientes } from "@/lib/notificaciones";
|
||||||
|
|
||||||
|
const recordatoriosSchema = z.object({
|
||||||
|
clienteId: z.string().min(1, "Cliente invalido").optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/cobros/recordatorios — envia YA el recordatorio de pagos pendientes
|
||||||
|
// (estado de cuenta por correo+push) a un cliente o a todos los que deben.
|
||||||
|
// Es el envio manual: ignora la espera de COBROS_RECORDATORIO_DIAS que respeta
|
||||||
|
// el scheduler.
|
||||||
|
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 = recordatoriosSchema.safeParse(raw ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const resultados = await enviarRecordatoriosPendientes({
|
||||||
|
clienteId: parsed.data.clienteId,
|
||||||
|
forzar: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
resultados,
|
||||||
|
// Para que la UI explique por que no salio nada en lugar de fingir exito.
|
||||||
|
canales: { correo: smtpConfigurado(), push: pushConfigurado() },
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const msg = error instanceof Error ? error.message : "Error interno";
|
||||||
|
return NextResponse.json({ error: msg }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -172,10 +172,12 @@ export function ClienteShell({ nombre }: { nombre: string }) {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={activarNotificaciones}
|
onClick={activarNotificaciones}
|
||||||
disabled={activas || activando}
|
disabled={activas || activando}
|
||||||
className={`flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
|
aria-label={activas ? "Notificaciones activas" : "Activar notificaciones"}
|
||||||
|
title={activas ? "Recibirás avisos de cobros en este navegador" : "Recibe avisos de cobros en este navegador"}
|
||||||
|
className={`flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
||||||
activas
|
activas
|
||||||
? "bg-gray-100 text-muted cursor-not-allowed"
|
? "border-green-200 bg-green-50 text-green-700 cursor-default"
|
||||||
: "bg-primary text-white hover:opacity-90"
|
: "border-border hover:bg-gray-50 disabled:opacity-60"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{activas ? (
|
{activas ? (
|
||||||
@@ -184,16 +186,14 @@ export function ClienteShell({ nombre }: { nombre: string }) {
|
|||||||
<Bell className="w-4 h-4" />
|
<Bell className="w-4 h-4" />
|
||||||
)}
|
)}
|
||||||
<span className="hidden sm:inline">
|
<span className="hidden sm:inline">
|
||||||
{activas ? "Notificaciones activas" : "Activar notificaciones"}
|
{activas ? "Avisos activos" : activando ? "Activando…" : "Activar avisos"}
|
||||||
</span>
|
|
||||||
<span className="sm:hidden">
|
|
||||||
{activas ? "Activas" : "Avisos"}
|
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={cerrarSesion}
|
onClick={cerrarSesion}
|
||||||
|
aria-label="Cerrar sesión"
|
||||||
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"
|
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" />
|
<LogOut className="w-4 h-4" />
|
||||||
@@ -209,6 +209,7 @@ export function ClienteShell({ nombre }: { nombre: string }) {
|
|||||||
<Link
|
<Link
|
||||||
key={item.href}
|
key={item.href}
|
||||||
href={item.href}
|
href={item.href}
|
||||||
|
aria-current={activa ? "page" : undefined}
|
||||||
className={`flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-2.5 text-sm font-medium transition-colors ${
|
className={`flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-2.5 text-sm font-medium transition-colors ${
|
||||||
activa
|
activa
|
||||||
? "border-primary text-primary"
|
? "border-primary text-primary"
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { ChevronRight } from "lucide-react";
|
||||||
|
import { formatCurrency, formatDate } from "@/lib/calculators";
|
||||||
|
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||||
|
|
||||||
|
// Montos YA con IVA cuando la cotizacion lo incluye: quien llama decide.
|
||||||
|
export type MontosCotizacion = { unico: number; mensual: number };
|
||||||
|
|
||||||
|
function Montos({ montos }: { montos: MontosCotizacion }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{montos.unico > 0 && <span className="font-semibold">{formatCurrency(montos.unico)}</span>}
|
||||||
|
{montos.unico > 0 && montos.mensual > 0 && <span className="text-muted"> + </span>}
|
||||||
|
{montos.mensual > 0 && (
|
||||||
|
<span className={montos.unico > 0 ? "text-muted" : "font-semibold"}>
|
||||||
|
{formatCurrency(montos.mensual)}/mes
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{montos.unico === 0 && montos.mensual === 0 && <span className="text-muted">—</span>}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fila de cotizacion del panel cliente (inicio y listado). Lista, no tabla:
|
||||||
|
// en el telefono los montos bajan debajo del titulo en lugar de recortarse.
|
||||||
|
export function FilaCotizacion({
|
||||||
|
id,
|
||||||
|
numero,
|
||||||
|
proyecto,
|
||||||
|
fecha,
|
||||||
|
estado,
|
||||||
|
montos,
|
||||||
|
opciones,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
numero: string;
|
||||||
|
proyecto: string;
|
||||||
|
fecha: Date;
|
||||||
|
estado: string;
|
||||||
|
montos: MontosCotizacion;
|
||||||
|
// Doble propuesta: un total por opcion en lugar del total combinado.
|
||||||
|
opciones?: Array<{ clave: string; montos: MontosCotizacion }>;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<Link
|
||||||
|
href={`/cliente/cotizaciones/${id}`}
|
||||||
|
className="group flex items-center gap-4 px-5 py-4 transition-colors hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="font-medium text-primary">{numero}</span>
|
||||||
|
<EstadoBadge estado={estado} />
|
||||||
|
{opciones && (
|
||||||
|
<span className="rounded-full bg-primary-light px-2 py-0.5 text-[11px] font-semibold text-primary">
|
||||||
|
Doble propuesta
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-sm text-muted sm:truncate">
|
||||||
|
{proyecto} · {formatDate(fecha)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm tabular-nums sm:text-right">
|
||||||
|
{opciones ? (
|
||||||
|
opciones.map((o) => (
|
||||||
|
<p key={o.clave}>
|
||||||
|
<span className="text-muted">Opción {o.clave}: </span>
|
||||||
|
<Montos montos={o.montos} />
|
||||||
|
</p>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p>
|
||||||
|
<Montos montos={montos} />
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ChevronRight className="h-4 w-4 shrink-0 text-muted transition-transform group-hover:translate-x-0.5" />
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -96,7 +96,7 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
<ArrowLeft className="w-5 h-5" />
|
<ArrowLeft className="w-5 h-5" />
|
||||||
</Link>
|
</Link>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h1 className="text-2xl font-bold">{cot.numero}</h1>
|
<h1 className="text-2xl font-bold tracking-tight">{cot.numero}</h1>
|
||||||
<p className="text-muted text-sm truncate">
|
<p className="text-muted text-sm truncate">
|
||||||
{cot.proyecto} · {formatDate(cot.fecha)}
|
{cot.proyecto} · {formatDate(cot.fecha)}
|
||||||
</p>
|
</p>
|
||||||
@@ -168,11 +168,11 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm tabular-nums">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-border">
|
<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">Servicio</th>
|
||||||
<th className="text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
|
<th className="hidden sm:table-cell 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>
|
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -181,8 +181,11 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
<tr key={s.id} className="border-b border-border last:border-0">
|
<tr key={s.id} className="border-b border-border last:border-0">
|
||||||
<td className="px-5 py-3">
|
<td className="px-5 py-3">
|
||||||
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
||||||
|
<span className="block text-xs text-muted sm:hidden">
|
||||||
|
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||||
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3 text-muted">
|
<td className="hidden sm:table-cell px-5 py-3 text-muted">
|
||||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3 text-right font-medium">
|
<td className="px-5 py-3 text-right font-medium">
|
||||||
@@ -193,9 +196,9 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
{g.totales && (
|
{g.totales && (
|
||||||
<div className="px-5 py-4 border-t border-border grid grid-cols-2 gap-4 text-sm">
|
<div className="px-5 py-4 border-t border-border grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-2 text-sm tabular-nums">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted">Total unico{cot.incluirIva ? " (c/IVA)" : ""}</span>
|
<span className="text-muted">Total único{cot.incluirIva ? " (c/IVA)" : ""}</span>
|
||||||
<span className="font-semibold">
|
<span className="font-semibold">
|
||||||
{formatCurrency(totalConIva(g.totales.totalUnico))}
|
{formatCurrency(totalConIva(g.totales.totalUnico))}
|
||||||
</span>
|
</span>
|
||||||
@@ -221,11 +224,11 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
Esta cotización no tiene servicios registrados.
|
Esta cotización no tiene servicios registrados.
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm tabular-nums">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-border bg-gray-50">
|
<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">Servicio</th>
|
||||||
<th className="text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
|
<th className="hidden sm:table-cell 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>
|
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -234,8 +237,11 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
<tr key={s.id} className="border-b border-border hover:bg-gray-50 transition-colors">
|
<tr key={s.id} className="border-b border-border hover:bg-gray-50 transition-colors">
|
||||||
<td className="px-5 py-3">
|
<td className="px-5 py-3">
|
||||||
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
||||||
|
<span className="block text-xs text-muted sm:hidden">
|
||||||
|
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||||
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3 text-muted">
|
<td className="hidden sm:table-cell px-5 py-3 text-muted">
|
||||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3 text-right font-medium">
|
<td className="px-5 py-3 text-right font-medium">
|
||||||
@@ -262,10 +268,10 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
Opción {op}
|
Opción {op}
|
||||||
{meta?.titulo ? `: ${meta.titulo}` : ""}
|
{meta?.titulo ? `: ${meta.titulo}` : ""}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="mt-3 space-y-1 text-sm">
|
<div className="mt-3 space-y-1 text-sm tabular-nums">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted">
|
<span className="text-muted">
|
||||||
Total unico{cot.incluirIva ? " (c/IVA)" : ""}
|
Total único{cot.incluirIva ? " (c/IVA)" : ""}
|
||||||
</span>
|
</span>
|
||||||
<span className="font-semibold">
|
<span className="font-semibold">
|
||||||
{formatCurrency(totalConIva(t.totalUnico))}
|
{formatCurrency(totalConIva(t.totalUnico))}
|
||||||
@@ -285,11 +291,11 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="max-w-sm space-y-2 text-sm">
|
<div className="max-w-sm space-y-2 text-sm tabular-nums">
|
||||||
{totales.incluyeIva && (
|
{totales.incluyeIva && (
|
||||||
<>
|
<>
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted">Subtotal unico</span>
|
<span className="text-muted">Subtotal único</span>
|
||||||
<span>{formatCurrency(totales.subtotalUnico)}</span>
|
<span>{formatCurrency(totales.subtotalUnico)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
@@ -299,7 +305,7 @@ export default async function ClienteCotizacionDetallePage({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
|
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
|
||||||
<span>Total unico</span>
|
<span>Total único</span>
|
||||||
<span>{formatCurrency(totales.totalUnico)}</span>
|
<span>{formatCurrency(totales.totalUnico)}</span>
|
||||||
</div>
|
</div>
|
||||||
{totales.incluyeIva && (
|
{totales.incluyeIva && (
|
||||||
|
|||||||
@@ -1,20 +1,14 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { ArrowRight, FileText } from "lucide-react";
|
import { FileText } from "lucide-react";
|
||||||
import { requireRole } from "@/lib/auth";
|
import { requireRole } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import {
|
import { calcularTotalesCotizacion, calcularTotalesOpcion, conIva } from "@/lib/calculators";
|
||||||
IVA_RATE,
|
import { FilaCotizacion } from "../FilaCotizacion";
|
||||||
calcularTotalesCotizacion,
|
|
||||||
calcularTotalesOpcion,
|
|
||||||
formatCurrency,
|
|
||||||
formatDate,
|
|
||||||
} from "@/lib/calculators";
|
|
||||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
// Lista de cotizaciones del cliente: numero, proyecto, fecha, estado y totales.
|
// Lista de cotizaciones del cliente: numero, proyecto, fecha, estado y totales
|
||||||
|
// (con IVA cuando la cotizacion lo incluye; por opcion si es doble propuesta).
|
||||||
export default async function ClienteCotizacionesPage() {
|
export default async function ClienteCotizacionesPage() {
|
||||||
const session = await requireRole("cliente");
|
const session = await requireRole("cliente");
|
||||||
if (!session) redirect("/login?panel=cliente");
|
if (!session) redirect("/login?panel=cliente");
|
||||||
@@ -38,116 +32,53 @@ export default async function ClienteCotizacionesPage() {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h1 className="text-2xl font-bold">Mis cotizaciones</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Mis cotizaciones</h1>
|
||||||
<p className="text-muted text-sm mt-1">
|
<p className="text-muted text-sm mt-1">
|
||||||
{cotizaciones.length === 0
|
{cotizaciones.length === 0
|
||||||
? "Aún no tienes cotizaciones"
|
? "Aún no tienes cotizaciones"
|
||||||
: `${cotizaciones.length} cotizacion${cotizaciones.length === 1 ? "" : "es"} a tu nombre`}
|
: `${cotizaciones.length} ${cotizaciones.length === 1 ? "cotización" : "cotizaciones"} a tu nombre`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{cotizaciones.length === 0 ? (
|
{cotizaciones.length === 0 ? (
|
||||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
<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" />
|
<FileText className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||||
<h2 className="text-lg font-semibold mb-2">No hay cotizaciones todavía</h2>
|
<h2 className="text-lg font-semibold mb-2">No hay cotizaciones todavía</h2>
|
||||||
<p className="text-muted">
|
<p className="text-muted">
|
||||||
Cuando tengas una cotización disponible aparecerá en esta sección.
|
Cuando tengas una cotización disponible aparecerá en esta sección.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
<ul className="bg-card-bg rounded-xl border border-border divide-y divide-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) => {
|
{cotizaciones.map((c) => {
|
||||||
const totales = calcularTotalesCotizacion(c.servicios, {
|
const totales = calcularTotalesCotizacion(c.servicios, { incluirIva: c.incluirIva });
|
||||||
incluirIva: c.incluirIva,
|
|
||||||
});
|
|
||||||
const conIva = (m: number) =>
|
|
||||||
c.incluirIva ? Math.round(m * (1 + IVA_RATE) * 100) / 100 : m;
|
|
||||||
return (
|
return (
|
||||||
<tr key={c.id} className="border-b border-border hover:bg-gray-50 transition-colors">
|
<FilaCotizacion
|
||||||
<td className="px-5 py-3">
|
key={c.id}
|
||||||
<Link
|
id={c.id}
|
||||||
href={`/cliente/cotizaciones/${c.id}`}
|
numero={c.numero}
|
||||||
className="font-medium text-primary hover:underline"
|
proyecto={c.proyecto}
|
||||||
>
|
fecha={c.fecha}
|
||||||
{c.numero}
|
estado={c.estado}
|
||||||
</Link>
|
montos={{ unico: totales.totalUnico, mensual: totales.totalMensual }}
|
||||||
{c.esDoble && (
|
opciones={
|
||||||
<span className="ml-2 text-[11px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full bg-primary-light text-primary">
|
c.esDoble
|
||||||
Doble propuesta
|
? (["1", "2"] as const).map((op) => {
|
||||||
</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);
|
const t = calcularTotalesOpcion(c.servicios, op);
|
||||||
return (
|
return {
|
||||||
<p key={op} className="text-xs">
|
clave: op,
|
||||||
<span className="text-muted">Op {op}:</span>{" "}
|
montos: {
|
||||||
{t.totalUnico > 0 ? formatCurrency(conIva(t.totalUnico)) : "-"}
|
unico: conIva(t.totalUnico, c.incluirIva),
|
||||||
</p>
|
mensual: conIva(t.totalMensual, c.incluirIva),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
})
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</ul>
|
||||||
) : 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>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// Esqueleto del panel de cliente: las paginas son force-dynamic, asi que sin
|
||||||
|
// esto el clic en la navegacion no da senal hasta que responde el servidor.
|
||||||
|
export default function Loading() {
|
||||||
|
const bloque = "rounded-lg bg-gray-200/70 motion-safe:animate-pulse";
|
||||||
|
return (
|
||||||
|
<div aria-busy="true" aria-label="Cargando">
|
||||||
|
<div className={`${bloque} h-7 w-56 mb-2`} />
|
||||||
|
<div className={`${bloque} h-4 w-72 mb-8`} />
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border p-6 mb-8">
|
||||||
|
<div className={`${bloque} h-5 w-48 mb-3`} />
|
||||||
|
<div className={`${bloque} h-8 w-40`} />
|
||||||
|
</div>
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border divide-y divide-border">
|
||||||
|
{[0, 1, 2].map((i) => (
|
||||||
|
<div key={i} className="flex items-center justify-between gap-4 px-5 py-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className={`${bloque} h-4 w-44`} />
|
||||||
|
<div className={`${bloque} h-3 w-28`} />
|
||||||
|
</div>
|
||||||
|
<div className={`${bloque} h-5 w-20`} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+125
-114
@@ -1,19 +1,18 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import {
|
import { ArrowRight, CalendarClock, CircleCheck, Clock3, FileText, Inbox } from "lucide-react";
|
||||||
ArrowRight,
|
|
||||||
CalendarClock,
|
|
||||||
ClipboardList,
|
|
||||||
Clock3,
|
|
||||||
FileText,
|
|
||||||
Inbox,
|
|
||||||
ShieldCheck,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { requireRole } from "@/lib/auth";
|
import { requireRole } from "@/lib/auth";
|
||||||
import { formatCurrency, formatDate } from "@/lib/calculators";
|
import { conIva } from "@/lib/calculators";
|
||||||
import { formatFechaCorta } from "@/lib/cobros";
|
import {
|
||||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
describirVencimiento,
|
||||||
|
diasHasta,
|
||||||
|
formatFechaBreve,
|
||||||
|
formatMonto,
|
||||||
|
formatTotales,
|
||||||
|
hoyCalendario,
|
||||||
|
} from "@/lib/cobros";
|
||||||
import { obtenerResumenCliente } from "./resumen-data";
|
import { obtenerResumenCliente } from "./resumen-data";
|
||||||
|
import { FilaCotizacion } from "./FilaCotizacion";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
@@ -28,7 +27,7 @@ export default async function ClienteInicioPage() {
|
|||||||
if (!resumen) {
|
if (!resumen) {
|
||||||
return (
|
return (
|
||||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
<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" />
|
<Inbox className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||||
<h2 className="text-lg font-semibold mb-2">Cuenta sin cliente asociado</h2>
|
<h2 className="text-lg font-semibold mb-2">Cuenta sin cliente asociado</h2>
|
||||||
<p className="text-muted">
|
<p className="text-muted">
|
||||||
Tu usuario no tiene un cliente vinculado. Contacta al administrador para
|
Tu usuario no tiene un cliente vinculado. Contacta al administrador para
|
||||||
@@ -38,160 +37,172 @@ export default async function ClienteInicioPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const tarjetas = [
|
const hoy = hoyCalendario();
|
||||||
{
|
const { pagos } = resumen;
|
||||||
label: "Cotizaciones activas",
|
const debe = pagos.pendientes > 0;
|
||||||
value: resumen.cotizacionesActivas,
|
const proximo = pagos.proximos[0];
|
||||||
icon: FileText,
|
|
||||||
bg: "bg-primary-light",
|
const indicadores = [
|
||||||
color: "text-primary",
|
{ label: "En revisión", value: pagos.enRevision },
|
||||||
},
|
{ label: "Verificados este mes", value: pagos.verificadosMes },
|
||||||
{
|
{ label: "Cotizaciones activas", value: resumen.cotizacionesActivas },
|
||||||
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 (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h1 className="text-2xl font-bold">Hola, {resumen.cliente.nombre}</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Hola, {resumen.cliente.nombre}</h1>
|
||||||
<p className="text-muted text-sm mt-1">
|
{resumen.cliente.empresa && (
|
||||||
{resumen.cliente.empresa
|
<p className="text-muted text-sm mt-1">{resumen.cliente.empresa}</p>
|
||||||
? resumen.cliente.empresa + " · "
|
)}
|
||||||
: ""}
|
</div>
|
||||||
Consulta tus cotizaciones y el estado de tus pagos.
|
|
||||||
|
<section
|
||||||
|
aria-label="Estado de tus pagos"
|
||||||
|
className="bg-card-bg rounded-xl border border-border overflow-hidden mb-8"
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-5 p-5 sm:flex-row sm:items-center sm:justify-between sm:p-6">
|
||||||
|
{debe ? (
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-amber-50 text-amber-600">
|
||||||
|
<Clock3 className="w-6 h-6" />
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h2 className="font-semibold">
|
||||||
|
Tienes {pagos.pendientes} {pagos.pendientes === 1 ? "pago pendiente" : "pagos pendientes"}
|
||||||
|
</h2>
|
||||||
|
<p className="text-2xl font-bold tracking-tight tabular-nums mt-1">
|
||||||
|
{formatTotales(pagos.saldoPendiente)}
|
||||||
|
</p>
|
||||||
|
{pagos.masAntiguo && (
|
||||||
|
<p className="text-sm text-muted mt-1">
|
||||||
|
El más antiguo es del {formatFechaBreve(pagos.masAntiguo, hoy)}
|
||||||
|
{diasHasta(pagos.masAntiguo, hoy) <= 0 &&
|
||||||
|
` (${describirVencimiento(pagos.masAntiguo, hoy)})`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-green-50 text-green-600">
|
||||||
|
<CircleCheck className="w-6 h-6" />
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h2 className="font-semibold">Estás al día con tus pagos</h2>
|
||||||
|
<p className="text-sm text-muted mt-1">
|
||||||
|
{proximo
|
||||||
|
? `Tu próximo cobro es el ${formatFechaBreve(proximo.fecha, hoy)} por ${formatMonto(proximo.monto, proximo.moneda)}.`
|
||||||
|
: "No tienes cobros pendientes."}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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>
|
||||||
|
)}
|
||||||
|
<Link
|
||||||
|
href="/cliente/pagos"
|
||||||
|
className={`inline-flex shrink-0 items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-colors ${
|
||||||
|
debe
|
||||||
|
? "bg-primary text-white hover:bg-primary-dark"
|
||||||
|
: "border border-border hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{debe ? "Pagar y subir comprobante" : "Ver mis pagos"}
|
||||||
|
<ArrowRight className="w-4 h-4" />
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
<dl className="grid grid-cols-3 divide-x divide-border border-t border-border bg-gray-50/60">
|
||||||
|
{indicadores.map((i) => (
|
||||||
|
<div key={i.label} className="px-4 py-3 sm:px-6">
|
||||||
|
<dt className="text-xs text-muted">{i.label}</dt>
|
||||||
|
<dd className="text-lg font-semibold tabular-nums">{i.value}</dd>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div className="bg-card-bg rounded-xl border border-border mb-8">
|
<section 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">
|
<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">
|
<h2 className="font-semibold flex items-center gap-2">
|
||||||
<CalendarClock className="w-5 h-5 text-primary" />
|
<CalendarClock className="w-5 h-5 text-primary" />
|
||||||
Próximos cobros
|
Próximos cobros
|
||||||
</h2>
|
</h2>
|
||||||
<Link
|
<Link
|
||||||
href="/cliente/pagos"
|
href="/cliente/pagos"
|
||||||
className="text-sm text-primary hover:underline flex items-center gap-1"
|
className="text-sm text-primary hover:underline underline-offset-2 flex items-center gap-1"
|
||||||
>
|
>
|
||||||
Ver todos
|
Ver todos
|
||||||
<ArrowRight className="w-4 h-4" />
|
<ArrowRight className="w-4 h-4" />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{resumen.pagos.proximos.length === 0 ? (
|
{pagos.proximos.length === 0 ? (
|
||||||
<div className="p-8 text-center">
|
<p className="px-5 py-8 text-center text-sm text-muted">
|
||||||
<CalendarClock className="w-10 h-10 text-muted mx-auto mb-3" />
|
|
||||||
<p className="text-muted text-sm">
|
|
||||||
No tienes cobros programados por ahora.
|
No tienes cobros programados por ahora.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<ul className="divide-y divide-border">
|
<ul className="divide-y divide-border">
|
||||||
{resumen.pagos.proximos.map((p) => (
|
{pagos.proximos.map((p) => (
|
||||||
<li
|
<li
|
||||||
key={`${p.concepto}-${p.fecha.toISOString()}`}
|
key={`${p.concepto}-${p.fecha.toISOString()}`}
|
||||||
className="flex items-center justify-between gap-3 px-5 py-3"
|
className="flex items-center justify-between gap-3 px-5 py-3"
|
||||||
>
|
>
|
||||||
<div>
|
<div className="min-w-0">
|
||||||
<p className="font-medium text-sm">{p.concepto}</p>
|
<p className="font-medium text-sm truncate">{p.concepto}</p>
|
||||||
<p className="text-xs text-muted">{formatFechaCorta(p.fecha)}</p>
|
<p className="text-xs text-muted">
|
||||||
|
{formatFechaBreve(p.fecha, hoy)} · {describirVencimiento(p.fecha, hoy)}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<p className="font-semibold">{formatCurrency(p.monto)}</p>
|
<p className="font-semibold tabular-nums">{formatMonto(p.monto, p.moneda)}</p>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</section>
|
||||||
|
|
||||||
<div className="bg-card-bg rounded-xl border border-border">
|
<section className="bg-card-bg rounded-xl border border-border">
|
||||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||||
<h2 className="font-semibold text-lg">Últimas cotizaciones</h2>
|
<h2 className="font-semibold flex items-center gap-2">
|
||||||
|
<FileText className="w-5 h-5 text-primary" />
|
||||||
|
Últimas cotizaciones
|
||||||
|
</h2>
|
||||||
<Link
|
<Link
|
||||||
href="/cliente/cotizaciones"
|
href="/cliente/cotizaciones"
|
||||||
className="text-sm text-primary hover:underline flex items-center gap-1"
|
className="text-sm text-primary hover:underline underline-offset-2 flex items-center gap-1"
|
||||||
>
|
>
|
||||||
Ver todas
|
Ver todas
|
||||||
<ArrowRight className="w-4 h-4" />
|
<ArrowRight className="w-4 h-4" />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{resumen.cotizaciones.length === 0 ? (
|
{resumen.cotizaciones.length === 0 ? (
|
||||||
<div className="p-8 text-center">
|
<p className="px-5 py-8 text-center text-sm text-muted">
|
||||||
<FileText className="w-10 h-10 text-muted mx-auto mb-3" />
|
Todavía no tienes cotizaciones. En cuanto el administrador la envíe, aparecerá aquí.
|
||||||
<p className="text-muted text-sm">
|
|
||||||
Todavía no tienes cotizaciones. En cuanto el administrador la envíe,
|
|
||||||
aparecerá aquí.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
|
||||||
) : (
|
) : (
|
||||||
<ul className="divide-y divide-border">
|
<ul className="divide-y divide-border">
|
||||||
{resumen.cotizaciones.map((c) => (
|
{resumen.cotizaciones.map((c) => (
|
||||||
<li key={c.id}>
|
<FilaCotizacion
|
||||||
<Link
|
key={c.id}
|
||||||
href={`/cliente/cotizaciones/${c.id}`}
|
id={c.id}
|
||||||
className="flex items-center justify-between gap-3 px-5 py-3 hover:bg-gray-50 transition-colors"
|
numero={c.numero}
|
||||||
>
|
proyecto={c.proyecto}
|
||||||
<div className="min-w-0">
|
fecha={c.fecha}
|
||||||
<p className="font-medium text-sm text-primary">{c.numero}</p>
|
estado={c.estado}
|
||||||
<p className="text-xs text-muted truncate">{c.proyecto}</p>
|
montos={{ unico: c.totales.totalUnico, mensual: c.totales.totalMensual }}
|
||||||
</div>
|
opciones={
|
||||||
<div className="flex items-center gap-4 shrink-0">
|
c.totalesOpciones
|
||||||
<span className="text-xs text-muted hidden sm:block">
|
? (["1", "2"] as const).map((op) => ({
|
||||||
{formatDate(c.fecha)}
|
clave: op,
|
||||||
</span>
|
montos: {
|
||||||
<EstadoBadge estado={c.estado} />
|
unico: conIva(c.totalesOpciones![op].totalUnico, c.incluirIva),
|
||||||
<div className="text-right text-sm hidden md:block">
|
mensual: conIva(c.totalesOpciones![op].totalMensual, c.incluirIva),
|
||||||
{c.totales.totalUnico > 0 && (
|
},
|
||||||
<p className="font-medium">
|
}))
|
||||||
{formatCurrency(c.totales.totalUnico)}
|
: undefined
|
||||||
</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>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Check, Copy } from "lucide-react";
|
||||||
|
|
||||||
|
// Fila de dato bancario con boton de copiar: en el telefono, pegar la CLABE en
|
||||||
|
// la app del banco es el paso que mas falla si hay que transcribirla.
|
||||||
|
export function CopiarDato({ etiqueta, valor }: { etiqueta: string; valor: string }) {
|
||||||
|
const [copiado, setCopiado] = useState(false);
|
||||||
|
|
||||||
|
const copiar = async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(valor.replace(/\s+/g, ""));
|
||||||
|
setCopiado(true);
|
||||||
|
setTimeout(() => setCopiado(false), 1800);
|
||||||
|
} catch {
|
||||||
|
// Sin permiso de portapapeles el dato sigue visible y seleccionable.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="py-2.5">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<p className="text-xs text-muted">{etiqueta}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={copiar}
|
||||||
|
aria-label={`Copiar ${etiqueta}`}
|
||||||
|
className={`shrink-0 inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium transition-colors ${
|
||||||
|
copiado
|
||||||
|
? "border-green-200 bg-green-50 text-green-700"
|
||||||
|
: "border-border text-foreground hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{copiado ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
|
||||||
|
{copiado ? "Copiado" : "Copiar"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 font-medium tabular-nums tracking-wide select-all [overflow-wrap:anywhere]">
|
||||||
|
{valor}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,7 +7,14 @@ import { useToast } from "@/components/ui/DialogProvider";
|
|||||||
|
|
||||||
// Subida de comprobante para un cobro pendiente o rechazado. multipart/form-data
|
// 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.
|
// a POST /api/cliente/pagos/[id]/comprobante; en error muestra el {error} del server.
|
||||||
export function SubirComprobante({ pagoId }: { pagoId: string }) {
|
export function SubirComprobante({
|
||||||
|
pagoId,
|
||||||
|
variante = "secundario",
|
||||||
|
}: {
|
||||||
|
pagoId: string;
|
||||||
|
// "primario" en la lista de lo que hay que pagar, donde es LA accion.
|
||||||
|
variante?: "primario" | "secundario";
|
||||||
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const [subiendo, setSubiendo] = useState(false);
|
const [subiendo, setSubiendo] = useState(false);
|
||||||
@@ -41,11 +48,11 @@ export function SubirComprobante({ pagoId }: { pagoId: string }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<label
|
<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 ${
|
className={`inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium transition-colors ${
|
||||||
subiendo
|
variante === "primario"
|
||||||
? "opacity-60 cursor-wait text-muted"
|
? "bg-primary-light/70 text-primary-dark hover:bg-primary hover:text-white"
|
||||||
: "cursor-pointer hover:bg-gray-50"
|
: "border border-border hover:bg-gray-50"
|
||||||
}`}
|
} ${subiendo ? "opacity-60 cursor-wait" : "cursor-pointer"}`}
|
||||||
>
|
>
|
||||||
{subiendo ? (
|
{subiendo ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
|
|||||||
+242
-113
@@ -1,10 +1,22 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { CalendarClock, Inbox } from "lucide-react";
|
import { Check, CircleCheck, Clock3, FileText, Inbox } from "lucide-react";
|
||||||
import { requireRole } from "@/lib/auth";
|
import { requireRole } from "@/lib/auth";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { formatCurrency } from "@/lib/calculators";
|
import { getConfigBancaria } from "@/lib/config-helpers";
|
||||||
import { ESTADOS_PAGO, formatFechaCorta } from "@/lib/cobros";
|
import {
|
||||||
|
ESTADOS_PAGO,
|
||||||
|
describirVencimiento,
|
||||||
|
diasHasta,
|
||||||
|
esPorPagar,
|
||||||
|
formatFechaBreve,
|
||||||
|
formatMonto,
|
||||||
|
formatTotales,
|
||||||
|
hoyCalendario,
|
||||||
|
proximaFecha,
|
||||||
|
totalesPorMoneda,
|
||||||
|
} from "@/lib/cobros";
|
||||||
import { SubirComprobante } from "./SubirComprobante";
|
import { SubirComprobante } from "./SubirComprobante";
|
||||||
|
import { CopiarDato } from "./CopiarDato";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
@@ -18,167 +30,284 @@ const DIAS_SEMANA = [
|
|||||||
"sábado",
|
"sábado",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Pagos ya registrados que se ven sin desplegar el historial de cada programa.
|
||||||
|
const HISTORIAL_VISIBLE = 4;
|
||||||
|
|
||||||
function frecuenciaLegible(p: {
|
function frecuenciaLegible(p: {
|
||||||
frecuencia: string;
|
frecuencia: string;
|
||||||
diaSemana?: number | null;
|
diaSemana?: number | null;
|
||||||
diaMes?: number | null;
|
diaMes?: number | null;
|
||||||
}): string {
|
}): string {
|
||||||
if (p.frecuencia === "semanal") {
|
if (p.frecuencia === "semanal") return `cada ${DIAS_SEMANA[p.diaSemana ?? 0]}`;
|
||||||
return `Semanal (${DIAS_SEMANA[p.diaSemana ?? 0]})`;
|
if (p.frecuencia === "quincenal") return "los días 1 y 15";
|
||||||
}
|
if (p.frecuencia === "mensual") return `el día ${p.diaMes ?? 1} de cada mes`;
|
||||||
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;
|
return p.frecuencia;
|
||||||
}
|
}
|
||||||
|
|
||||||
function EstadoPagoBadge({
|
function EstadoHistorial({ estado }: { estado: string }) {
|
||||||
estado,
|
if (estado === ESTADOS_PAGO.VERIFICADO) {
|
||||||
rechazoMotivo,
|
return (
|
||||||
}: {
|
<span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2.5 py-0.5 text-xs font-medium text-green-700">
|
||||||
estado: string;
|
<Check className="w-3 h-3" />
|
||||||
rechazoMotivo?: string | null;
|
Verificado
|
||||||
}) {
|
</span>
|
||||||
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 (
|
return (
|
||||||
<div>
|
<span className="inline-flex items-center gap-1 rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
|
||||||
<span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${cls}`}>
|
<Clock3 className="w-3 h-3" />
|
||||||
{label}
|
En revisión
|
||||||
</span>
|
</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,
|
type FilaHistorial = {
|
||||||
// con subida de comprobante para los pendientes/rechazados.
|
id: string;
|
||||||
|
fecha: Date;
|
||||||
|
monto: number;
|
||||||
|
estado: string;
|
||||||
|
comprobante: { archivoNombre: string } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function FilaPago({ pago, moneda, hoy }: { pago: FilaHistorial; moneda: string; hoy: Date }) {
|
||||||
|
return (
|
||||||
|
<li className="flex flex-wrap items-center gap-x-4 gap-y-1.5 px-5 py-3 text-sm">
|
||||||
|
<span className="w-28 shrink-0">{formatFechaBreve(pago.fecha, hoy)}</span>
|
||||||
|
<EstadoHistorial estado={pago.estado} />
|
||||||
|
<span className="ml-auto font-medium tabular-nums">{formatMonto(pago.monto, moneda)}</span>
|
||||||
|
{pago.comprobante ? (
|
||||||
|
<a
|
||||||
|
href={`/api/comprobantes/${pago.id}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 text-primary hover:underline underline-offset-2"
|
||||||
|
title={pago.comprobante.archivoNombre}
|
||||||
|
>
|
||||||
|
<FileText className="w-3.5 h-3.5" />
|
||||||
|
Comprobante
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lo primero es lo que el cliente tiene que pagar (mas antiguo primero) con su
|
||||||
|
// boton de comprobante; al lado, los datos bancarios para copiar; abajo, el
|
||||||
|
// historial de cada programa.
|
||||||
export default async function ClientePagosPage() {
|
export default async function ClientePagosPage() {
|
||||||
const session = await requireRole("cliente");
|
const session = await requireRole("cliente");
|
||||||
if (!session) redirect("/login?panel=cliente");
|
if (!session) redirect("/login?panel=cliente");
|
||||||
if (!session.clienteId) redirect("/login?panel=cliente");
|
if (!session.clienteId) redirect("/login?panel=cliente");
|
||||||
|
|
||||||
const programas = await prisma.programaPago.findMany({
|
const [programas, banco] = await Promise.all([
|
||||||
|
prisma.programaPago.findMany({
|
||||||
where: { clienteId: session.clienteId },
|
where: { clienteId: session.clienteId },
|
||||||
orderBy: [{ activo: "desc" }, { concepto: "asc" }],
|
orderBy: [{ activo: "desc" }, { concepto: "asc" }],
|
||||||
include: {
|
include: {
|
||||||
pagos: {
|
pagos: {
|
||||||
orderBy: { fecha: "desc" },
|
orderBy: { fecha: "desc" },
|
||||||
include: { comprobante: { select: { archivoNombre: true, subidoAt: true } } },
|
include: { comprobante: { select: { archivoNombre: true } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
}),
|
||||||
|
getConfigBancaria(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const hoy = hoyCalendario();
|
||||||
|
|
||||||
|
// Lo que el cliente debe: pendientes + comprobantes rechazados.
|
||||||
|
const porPagar = programas
|
||||||
|
.flatMap((prog) =>
|
||||||
|
prog.pagos
|
||||||
|
.filter((pago) => esPorPagar(pago.estado))
|
||||||
|
.map((pago) => ({ ...pago, programa: { concepto: prog.concepto, moneda: prog.moneda } }))
|
||||||
|
)
|
||||||
|
.sort((a, b) => a.fecha.getTime() - b.fecha.getTime());
|
||||||
|
const enRevision = programas.reduce(
|
||||||
|
(n, prog) => n + prog.pagos.filter((p) => p.estado === ESTADOS_PAGO.EN_REVISION).length,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
|
||||||
|
const datosPago = [
|
||||||
|
["Titular", banco.razon_social],
|
||||||
|
["CLABE", banco.clabe_interbancaria],
|
||||||
|
["Cuenta", banco.cuenta_nacional],
|
||||||
|
].filter((par): par is [string, string] => Boolean(par[1]));
|
||||||
|
|
||||||
|
if (programas.length === 0) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold tracking-tight mb-8">Mis pagos</h1>
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||||
|
<Inbox className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Sin cobros programados</h2>
|
||||||
|
<p className="text-muted max-w-md mx-auto">
|
||||||
|
Cuando se configure un programa de pagos para ti, aparecerá aquí junto con cada
|
||||||
|
cobro generado.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h1 className="text-2xl font-bold">Mis pagos</h1>
|
<h1 className="text-2xl font-bold tracking-tight">Mis pagos</h1>
|
||||||
<p className="text-muted text-sm mt-1">
|
<p className="text-muted text-sm mt-1">
|
||||||
Historial de cobros recurrentes y carga de comprobantes
|
Paga tus cobros y sube el comprobante para que quede registrado.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-6 rounded-xl border border-border bg-card-bg p-4 text-sm text-muted">
|
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_18rem]">
|
||||||
Sube tu comprobante de pago (imagen o PDF). El administrador lo revisará y
|
<section aria-labelledby="titulo-por-pagar" className="min-w-0 lg:col-start-1 lg:row-start-1">
|
||||||
quedará como verificado.
|
{porPagar.length > 0 ? (
|
||||||
</div>
|
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||||
|
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 px-5 py-4 border-b border-border">
|
||||||
{programas.length === 0 ? (
|
<h2 id="titulo-por-pagar" className="text-lg font-semibold">
|
||||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
Por pagar
|
||||||
<Inbox className="w-16 h-16 text-muted mx-auto mb-4" />
|
</h2>
|
||||||
<h2 className="text-lg font-semibold mb-2">Sin cobros programados</h2>
|
<p className="text-sm text-muted">
|
||||||
<p className="text-muted">
|
{porPagar.length} {porPagar.length === 1 ? "cobro" : "cobros"} ·{" "}
|
||||||
Cuando se configure un programa de pagos para ti, aparecerá aquí junto
|
<span className="font-semibold text-foreground tabular-nums">
|
||||||
con cada cobro generado.
|
{formatTotales(totalesPorMoneda(porPagar))}
|
||||||
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<ul className="divide-y divide-border">
|
||||||
|
{porPagar.map((pago) => {
|
||||||
|
const vencido = diasHasta(pago.fecha, hoy) < 0;
|
||||||
|
const rechazado = pago.estado === ESTADOS_PAGO.RECHAZADO;
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={pago.id}
|
||||||
|
className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="font-medium">{pago.programa.concepto}</p>
|
||||||
|
<p className="text-sm text-muted mt-0.5">
|
||||||
|
{formatFechaBreve(pago.fecha, hoy)} ·{" "}
|
||||||
|
<span className={vencido ? "font-medium text-red-600" : "font-medium text-amber-700"}>
|
||||||
|
{describirVencimiento(pago.fecha, hoy)}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
{rechazado && (
|
||||||
|
<p className="text-sm text-red-700 mt-1.5">
|
||||||
|
Rechazamos el comprobante
|
||||||
|
{pago.rechazoMotivo ? `: ${pago.rechazoMotivo}` : ""}. Sube uno nuevo.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-4 sm:justify-end">
|
||||||
|
<span className="text-lg font-semibold tabular-nums">
|
||||||
|
{formatMonto(pago.monto, pago.programa.moneda)}
|
||||||
|
</span>
|
||||||
|
<SubirComprobante pagoId={pago.id} variante="primario" />
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
programas.map((prog) => (
|
<div className="bg-card-bg rounded-xl border border-border p-5 flex items-center gap-4">
|
||||||
<section key={prog.id} className="mb-8">
|
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-green-50 text-green-600">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
|
<CircleCheck className="w-6 h-6" />
|
||||||
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<h2 className="font-semibold text-lg flex items-center gap-2">
|
<h2 id="titulo-por-pagar" className="font-semibold">
|
||||||
<CalendarClock className="w-5 h-5 text-primary" />
|
Estás al día
|
||||||
{prog.concepto}
|
|
||||||
</h2>
|
</h2>
|
||||||
|
<p className="text-sm text-muted">
|
||||||
|
No tienes cobros pendientes de pago.
|
||||||
|
{enRevision > 0 &&
|
||||||
|
` ${enRevision} ${enRevision === 1 ? "comprobante está" : "comprobantes están"} en revisión.`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<aside className="space-y-4 lg:col-start-2 lg:row-start-1 lg:row-span-2 lg:self-start lg:sticky lg:top-32">
|
||||||
|
{datosPago.length > 0 && (
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border px-5 py-4">
|
||||||
|
<h2 className="font-semibold mb-1">Datos para tu pago</h2>
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{datosPago.map(([etiqueta, valor]) => (
|
||||||
|
<CopiarDato key={etiqueta} etiqueta={etiqueta} valor={valor} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="bg-card-bg rounded-xl border border-border px-5 py-4 text-sm">
|
||||||
|
<h2 className="font-semibold mb-2">Cómo se registra tu pago</h2>
|
||||||
|
<ol className="list-decimal space-y-1.5 pl-4 text-muted marker:text-muted">
|
||||||
|
<li>Haz la transferencia por el monto del cobro.</li>
|
||||||
|
<li>Sube el comprobante (imagen o PDF, hasta 10 MB) en ese cobro.</li>
|
||||||
|
<li>Lo revisamos y te avisamos cuando quede verificado.</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section aria-labelledby="titulo-historial" className="min-w-0 lg:col-start-1 lg:row-start-2">
|
||||||
|
<h2 id="titulo-historial" className="text-lg font-semibold mb-3 mt-2">
|
||||||
|
Historial
|
||||||
|
</h2>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{programas.map((prog) => {
|
||||||
|
const registrados = prog.pagos.filter((p) => !esPorPagar(p.estado));
|
||||||
|
const visibles = registrados.slice(0, HISTORIAL_VISIBLE);
|
||||||
|
const anteriores = registrados.slice(HISTORIAL_VISIBLE);
|
||||||
|
const proximo = prog.activo ? proximaFecha(prog, hoy) : null;
|
||||||
|
return (
|
||||||
|
<div key={prog.id} className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-2 px-5 py-4 border-b border-border">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h3 className="font-semibold">{prog.concepto}</h3>
|
||||||
<p className="text-sm text-muted mt-0.5">
|
<p className="text-sm text-muted mt-0.5">
|
||||||
{formatCurrency(prog.monto)} · {frecuenciaLegible(prog)} · {prog.moneda}
|
<span className="tabular-nums">{formatMonto(prog.monto, prog.moneda)}</span>{" "}
|
||||||
|
{frecuenciaLegible(prog)}
|
||||||
|
{proximo && ` · próximo: ${formatFechaBreve(proximo, hoy)}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{!prog.activo && (
|
{!prog.activo && (
|
||||||
<span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
|
<span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
|
||||||
Programa inactivo
|
Programa inactivo
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{registrados.length === 0 ? (
|
||||||
{prog.pagos.length === 0 ? (
|
<p className="px-5 py-4 text-sm text-muted">Aún no hay pagos registrados.</p>
|
||||||
<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">
|
<ul className="divide-y divide-border">
|
||||||
<thead>
|
{visibles.map((pago) => (
|
||||||
<tr className="border-b border-border bg-gray-50">
|
<FilaPago key={pago.id} pago={pago} moneda={prog.moneda} hoy={hoy} />
|
||||||
<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>
|
</ul>
|
||||||
</table>
|
{anteriores.length > 0 && (
|
||||||
</div>
|
<details className="group border-t border-border">
|
||||||
|
<summary className="cursor-pointer list-none px-5 py-3 text-sm font-medium text-primary hover:bg-gray-50 [&::-webkit-details-marker]:hidden">
|
||||||
|
<span className="group-open:hidden">
|
||||||
|
Ver {anteriores.length} {anteriores.length === 1 ? "pago anterior" : "pagos anteriores"}
|
||||||
|
</span>
|
||||||
|
<span className="hidden group-open:inline">Ocultar pagos anteriores</span>
|
||||||
|
</summary>
|
||||||
|
<ul className="divide-y divide-border border-t border-border">
|
||||||
|
{anteriores.map((pago) => (
|
||||||
|
<FilaPago key={pago.id} pago={pago} moneda={prog.moneda} hoy={hoy} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
)}
|
)}
|
||||||
</section>
|
</>
|
||||||
))
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators";
|
import { calcularTotalesCotizacion, calcularTotalesOpcion } from "@/lib/calculators";
|
||||||
import { ESTADOS_PAGO, hoyCalendario, proximaFecha } from "@/lib/cobros";
|
import {
|
||||||
|
ESTADOS_PAGO,
|
||||||
|
ESTADOS_POR_PAGAR,
|
||||||
|
hoyCalendario,
|
||||||
|
proximaFecha,
|
||||||
|
totalesPorMoneda,
|
||||||
|
} from "@/lib/cobros";
|
||||||
|
|
||||||
// Resumen del panel de cliente. Compartido entre GET /api/cliente/resumen y la
|
// 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.
|
// pagina de inicio (/cliente) para que ambas caras cuenten exactamente lo mismo.
|
||||||
@@ -12,6 +18,7 @@ export interface ResumenCotizacion {
|
|||||||
fecha: Date;
|
fecha: Date;
|
||||||
estado: string;
|
estado: string;
|
||||||
esDoble: boolean;
|
esDoble: boolean;
|
||||||
|
incluirIva: boolean;
|
||||||
totales: ReturnType<typeof calcularTotalesCotizacion>;
|
totales: ReturnType<typeof calcularTotalesCotizacion>;
|
||||||
totalesOpciones?: {
|
totalesOpciones?: {
|
||||||
"1": ReturnType<typeof calcularTotalesOpcion>;
|
"1": ReturnType<typeof calcularTotalesOpcion>;
|
||||||
@@ -24,10 +31,15 @@ export interface ResumenCliente {
|
|||||||
cotizacionesActivas: number;
|
cotizacionesActivas: number;
|
||||||
cotizaciones: ResumenCotizacion[];
|
cotizaciones: ResumenCotizacion[];
|
||||||
pagos: {
|
pagos: {
|
||||||
|
// Cobros por pagar (pendientes o con comprobante rechazado) y su total
|
||||||
|
// por moneda.
|
||||||
pendientes: number;
|
pendientes: number;
|
||||||
|
saldoPendiente: Record<string, number>;
|
||||||
|
// Fecha del cobro por pagar mas antiguo (null si no debe nada).
|
||||||
|
masAntiguo: Date | null;
|
||||||
enRevision: number;
|
enRevision: number;
|
||||||
verificadosMes: number;
|
verificadosMes: number;
|
||||||
proximos: Array<{ fecha: Date; monto: number; concepto: string }>;
|
proximos: Array<{ fecha: Date; monto: number; moneda: string; concepto: string }>;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +53,7 @@ export async function obtenerResumenCliente(clienteId: string): Promise<ResumenC
|
|||||||
const hoy = hoyCalendario();
|
const hoy = hoyCalendario();
|
||||||
const inicioMes = new Date(Date.UTC(hoy.getUTCFullYear(), hoy.getUTCMonth(), 1));
|
const inicioMes = new Date(Date.UTC(hoy.getUTCFullYear(), hoy.getUTCMonth(), 1));
|
||||||
|
|
||||||
const [cotizacionesActivas, cotizacionesBrutas, pendientes, enRevision, verificadosMes, programas] =
|
const [cotizacionesActivas, cotizacionesBrutas, porPagar, enRevision, verificadosMes, programas] =
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
prisma.cotizacion.count({
|
prisma.cotizacion.count({
|
||||||
where: { clienteId, estado: { not: "rechazada" } },
|
where: { clienteId, estado: { not: "rechazada" } },
|
||||||
@@ -63,8 +75,10 @@ export async function obtenerResumenCliente(clienteId: string): Promise<ResumenC
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
prisma.pagoRecurrente.count({
|
prisma.pagoRecurrente.findMany({
|
||||||
where: { estado: ESTADOS_PAGO.PENDIENTE, programa: { clienteId } },
|
where: { estado: { in: ESTADOS_POR_PAGAR }, programa: { clienteId } },
|
||||||
|
orderBy: { fecha: "asc" },
|
||||||
|
select: { fecha: true, monto: true, programa: { select: { moneda: true } } },
|
||||||
}),
|
}),
|
||||||
prisma.pagoRecurrente.count({
|
prisma.pagoRecurrente.count({
|
||||||
where: { estado: ESTADOS_PAGO.EN_REVISION, programa: { clienteId } },
|
where: { estado: ESTADOS_PAGO.EN_REVISION, programa: { clienteId } },
|
||||||
@@ -88,6 +102,7 @@ export async function obtenerResumenCliente(clienteId: string): Promise<ResumenC
|
|||||||
fecha: c.fecha,
|
fecha: c.fecha,
|
||||||
estado: c.estado,
|
estado: c.estado,
|
||||||
esDoble: c.esDoble,
|
esDoble: c.esDoble,
|
||||||
|
incluirIva: c.incluirIva,
|
||||||
totales,
|
totales,
|
||||||
...(c.esDoble
|
...(c.esDoble
|
||||||
? {
|
? {
|
||||||
@@ -103,9 +118,9 @@ export async function obtenerResumenCliente(clienteId: string): Promise<ResumenC
|
|||||||
const proximos = programas
|
const proximos = programas
|
||||||
.map((p) => {
|
.map((p) => {
|
||||||
const fecha = proximaFecha(p);
|
const fecha = proximaFecha(p);
|
||||||
return fecha ? { fecha, monto: p.monto, concepto: p.concepto } : null;
|
return fecha ? { fecha, monto: p.monto, moneda: p.moneda, concepto: p.concepto } : null;
|
||||||
})
|
})
|
||||||
.filter((x): x is { fecha: Date; monto: number; concepto: string } => x !== null)
|
.filter((x): x is { fecha: Date; monto: number; moneda: string; concepto: string } => x !== null)
|
||||||
.sort((a, b) => a.fecha.getTime() - b.fecha.getTime())
|
.sort((a, b) => a.fecha.getTime() - b.fecha.getTime())
|
||||||
.slice(0, 3);
|
.slice(0, 3);
|
||||||
|
|
||||||
@@ -113,6 +128,13 @@ export async function obtenerResumenCliente(clienteId: string): Promise<ResumenC
|
|||||||
cliente,
|
cliente,
|
||||||
cotizacionesActivas,
|
cotizacionesActivas,
|
||||||
cotizaciones,
|
cotizaciones,
|
||||||
pagos: { pendientes, enRevision, verificadosMes, proximos },
|
pagos: {
|
||||||
|
pendientes: porPagar.length,
|
||||||
|
saldoPendiente: totalesPorMoneda(porPagar),
|
||||||
|
masAntiguo: porPagar[0]?.fecha ?? null,
|
||||||
|
enRevision,
|
||||||
|
verificadosMes,
|
||||||
|
proximos,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-1
@@ -16,7 +16,9 @@
|
|||||||
--sidebar-active: #2563eb;
|
--sidebar-active: #2563eb;
|
||||||
--card-bg: #ffffff;
|
--card-bg: #ffffff;
|
||||||
--border: #e2e8f0;
|
--border: #e2e8f0;
|
||||||
--muted: #94a3b8;
|
/* Texto secundario: slate-500 da 4.8:1 sobre blanco (slate-400 se quedaba en
|
||||||
|
2.6:1, ilegible para cifras y fechas). */
|
||||||
|
--muted: #64748b;
|
||||||
}
|
}
|
||||||
|
|
||||||
@theme inline {
|
@theme inline {
|
||||||
@@ -49,3 +51,18 @@ body {
|
|||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: #cbd5e1 transparent;
|
scrollbar-color: #cbd5e1 transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
::selection {
|
||||||
|
background: var(--primary-light);
|
||||||
|
color: var(--primary-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Foco de teclado visible y consistente; el mouse no lo dispara. */
|
||||||
|
a:focus-visible,
|
||||||
|
button:focus-visible,
|
||||||
|
summary:focus-visible,
|
||||||
|
label:focus-within:has(input[type="file"]) {
|
||||||
|
outline: 2px solid var(--primary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|||||||
+35
-14
@@ -1,10 +1,23 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { Suspense, useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
|
||||||
|
// useSearchParams exige un limite de Suspense para que /login siga siendo
|
||||||
|
// estatica en el build.
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
<LoginForm />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LoginForm() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
// /login?panel=cliente: el middleware manda aqui a quien abre /cliente sin
|
||||||
|
// sesion; el formulario es el mismo, solo cambia el encabezado.
|
||||||
|
const esCliente = useSearchParams().get("panel") === "cliente";
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
@@ -30,37 +43,43 @@ export default function LoginPage() {
|
|||||||
router.refresh();
|
router.refresh();
|
||||||
} else {
|
} else {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setError(data.error || "Error al iniciar sesion");
|
setError(data.error || "No se pudo iniciar sesión");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
setError("Error de conexion");
|
setError("Sin conexión con el servidor. Intenta de nuevo.");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
<div className="min-h-screen flex items-center justify-center bg-background px-4">
|
||||||
<div className="w-full max-w-sm">
|
<div className="w-full max-w-sm">
|
||||||
<div className="bg-white rounded-xl shadow-lg border border-border p-8">
|
<div className="bg-white rounded-xl shadow-[0_8px_30px_-12px_rgba(15,23,42,0.18)] p-8">
|
||||||
<h1 className="text-2xl font-bold text-center mb-2">Cotizador</h1>
|
<h1 className="text-2xl font-bold tracking-tight text-center mb-1">
|
||||||
|
{esCliente ? "Portal de clientes" : "Cotizador"}
|
||||||
|
</h1>
|
||||||
<p className="text-center text-muted text-sm mb-6">
|
<p className="text-center text-muted text-sm mb-6">
|
||||||
Uriel Jareth Consulting
|
{esCliente
|
||||||
|
? "Consulta tus cotizaciones y registra tus pagos"
|
||||||
|
: "Uriel Jareth Consulting"}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-3 mb-4">
|
<div role="alert" className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-3 mb-4">
|
||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-muted mb-1">
|
<label htmlFor="login-email" className="block text-sm font-medium mb-1">
|
||||||
Email
|
Correo
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
|
id="login-email"
|
||||||
type="email"
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
required
|
required
|
||||||
@@ -70,15 +89,17 @@ export default function LoginPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-muted mb-1">
|
<label htmlFor="login-password" className="block text-sm font-medium mb-1">
|
||||||
Password
|
Contraseña
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
|
id="login-password"
|
||||||
type="password"
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
required
|
required
|
||||||
placeholder="Tu contrasena"
|
placeholder="Tu contraseña"
|
||||||
suppressHydrationWarning
|
suppressHydrationWarning
|
||||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -25,6 +25,23 @@ export const ESTADOS_PAGO = {
|
|||||||
|
|
||||||
export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO];
|
export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO];
|
||||||
|
|
||||||
|
// Estados en los que el cliente todavia DEBE el cobro: nunca subio comprobante
|
||||||
|
// o se lo rechazaron. en_revision no cuenta (ya pago, falta que el admin lo
|
||||||
|
// valide). Es la base del saldo pendiente y de los recordatorios.
|
||||||
|
export const ESTADOS_POR_PAGAR: EstadoPago[] = [ESTADOS_PAGO.PENDIENTE, ESTADOS_PAGO.RECHAZADO];
|
||||||
|
|
||||||
|
export function esPorPagar(estado: string): boolean {
|
||||||
|
return (ESTADOS_POR_PAGAR as string[]).includes(estado);
|
||||||
|
}
|
||||||
|
|
||||||
|
// RECORDATORIOS. Cada cuantos dias el scheduler vuelve a avisar al cliente de
|
||||||
|
// lo que sigue por pagar (0 = sin recordatorio automatico; el envio manual
|
||||||
|
// desde /cobros funciona igual). Se lee en servidor de COBROS_RECORDATORIO_DIAS.
|
||||||
|
export const RECORDATORIO_DIAS_DEFAULT = 3;
|
||||||
|
// Hora local de Mexico a partir de la cual el scheduler puede enviarlos, para
|
||||||
|
// no mandar correos de cobranza a la 1 a. m. cuando cambia el dia.
|
||||||
|
export const HORA_RECORDATORIOS = 9;
|
||||||
|
|
||||||
// "YYYY-MM-DD" (input de formularios) -> Date en medianoche UTC del calendario.
|
// "YYYY-MM-DD" (input de formularios) -> Date en medianoche UTC del calendario.
|
||||||
export function parseFechaCalendario(iso: string): Date {
|
export function parseFechaCalendario(iso: string): Date {
|
||||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim());
|
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim());
|
||||||
@@ -37,21 +54,43 @@ export function aCalendario(date: Date): { y: number; m: number; d: number } {
|
|||||||
return { y: date.getUTCFullYear(), m: date.getUTCMonth() + 1, d: date.getUTCDate() };
|
return { y: date.getUTCFullYear(), m: date.getUTCMonth() + 1, d: date.getUTCDate() };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hoy en America/Mexico_City como fecha de calendario (UTC midnight).
|
// Fecha de calendario en America/Mexico_City (UTC midnight) del instante dado.
|
||||||
export function hoyCalendario(): Date {
|
// Para timestamps reales (createdAt, ultimoRecordatorioAt), no para fechas de
|
||||||
|
// cobro, que ya son calendario.
|
||||||
|
export function calendarioDe(instante: Date): Date {
|
||||||
const iso = new Intl.DateTimeFormat("en-CA", {
|
const iso = new Intl.DateTimeFormat("en-CA", {
|
||||||
timeZone: ZONA_HORARIA,
|
timeZone: ZONA_HORARIA,
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "2-digit",
|
month: "2-digit",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
}).format(new Date()); // "YYYY-MM-DD"
|
}).format(instante); // "YYYY-MM-DD"
|
||||||
return parseFechaCalendario(iso);
|
return parseFechaCalendario(iso);
|
||||||
}
|
}
|
||||||
|
|
||||||
function sumarDias(d: Date, dias: number): Date {
|
// Hoy en America/Mexico_City como fecha de calendario (UTC midnight).
|
||||||
|
export function hoyCalendario(): Date {
|
||||||
|
return calendarioDe(new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hora (0-23) actual en America/Mexico_City.
|
||||||
|
export function horaMexico(instante: Date = new Date()): number {
|
||||||
|
const h = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone: ZONA_HORARIA,
|
||||||
|
hour: "numeric",
|
||||||
|
hourCycle: "h23",
|
||||||
|
}).format(instante);
|
||||||
|
return Number(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sumarDias(d: Date, dias: number): Date {
|
||||||
return new Date(d.getTime() + dias * 86400000);
|
return new Date(d.getTime() + dias * 86400000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dias completos entre una fecha de cobro y hoy MX (0 si vence hoy o despues).
|
||||||
|
export function diasDeAtraso(fecha: Date, hoy: Date = hoyCalendario()): number {
|
||||||
|
return Math.max(0, Math.round((hoy.getTime() - fecha.getTime()) / 86400000));
|
||||||
|
}
|
||||||
|
|
||||||
const fmtFecha = new Intl.DateTimeFormat("es-MX", {
|
const fmtFecha = new Intl.DateTimeFormat("es-MX", {
|
||||||
weekday: "long",
|
weekday: "long",
|
||||||
day: "2-digit",
|
day: "2-digit",
|
||||||
@@ -66,6 +105,48 @@ export function formatFechaCobro(date: Date): string {
|
|||||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Monto en su moneda: "$4,500" / "$4,500.50" / "USD 25". Sin decimales si es
|
||||||
|
// entero, como formatCurrency; a diferencia de este, respeta USD.
|
||||||
|
export function formatMonto(monto: number, moneda: string = "MXN"): string {
|
||||||
|
return new Intl.NumberFormat("es-MX", {
|
||||||
|
style: "currency",
|
||||||
|
currency: moneda || "MXN",
|
||||||
|
minimumFractionDigits: Number.isInteger(monto) ? 0 : 2,
|
||||||
|
maximumFractionDigits: 2,
|
||||||
|
}).format(monto);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Totales por moneda en una linea: "$2,250" o "$1,500 + USD 100".
|
||||||
|
export function formatTotales(totales: Record<string, number>): string {
|
||||||
|
const partes = Object.entries(totales).map(([moneda, total]) => formatMonto(total, moneda));
|
||||||
|
return partes.length ? partes.join(" + ") : "$0";
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtDiaSemana = new Intl.DateTimeFormat("es-MX", { weekday: "short", timeZone: "UTC" });
|
||||||
|
const fmtMesCorto = new Intl.DateTimeFormat("es-MX", { month: "short", timeZone: "UTC" });
|
||||||
|
|
||||||
|
// "sáb 31 oct" (agrega el año si no es el de `hoy`). Para listas de cobros.
|
||||||
|
export function formatFechaBreve(date: Date, hoy: Date = hoyCalendario()): string {
|
||||||
|
const dia = fmtDiaSemana.format(date).replace(".", "");
|
||||||
|
const mes = fmtMesCorto.format(date).replace(".", "");
|
||||||
|
const anio = date.getUTCFullYear() !== hoy.getUTCFullYear() ? ` ${date.getUTCFullYear()}` : "";
|
||||||
|
return `${dia} ${date.getUTCDate()} ${mes}${anio}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dias de `hoy` a `fecha` (negativo si ya paso). Ambas son fechas de calendario.
|
||||||
|
export function diasHasta(fecha: Date, hoy: Date = hoyCalendario()): number {
|
||||||
|
return Math.round((fecha.getTime() - hoy.getTime()) / 86400000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// "vence hoy" / "mañana" / "en 5 días" / "hace 1 día" / "hace 12 días".
|
||||||
|
export function describirVencimiento(fecha: Date, hoy: Date = hoyCalendario()): string {
|
||||||
|
const d = diasHasta(fecha, hoy);
|
||||||
|
if (d === 0) return "vence hoy";
|
||||||
|
if (d === 1) return "mañana";
|
||||||
|
if (d > 1) return `en ${d} días`;
|
||||||
|
return d === -1 ? "hace 1 día" : `hace ${-d} días`;
|
||||||
|
}
|
||||||
|
|
||||||
// Version corta: "04/07/2026".
|
// Version corta: "04/07/2026".
|
||||||
export function formatFechaCorta(date: Date): string {
|
export function formatFechaCorta(date: Date): string {
|
||||||
const { y, m, d } = aCalendario(date);
|
const { y, m, d } = aCalendario(date);
|
||||||
|
|||||||
+58
-1
@@ -1,5 +1,11 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { aCalendario, fechasPeriodo, hoyCalendario } from "@/lib/cobros-fechas";
|
import {
|
||||||
|
ESTADOS_POR_PAGAR,
|
||||||
|
RECORDATORIO_DIAS_DEFAULT,
|
||||||
|
aCalendario,
|
||||||
|
fechasPeriodo,
|
||||||
|
hoyCalendario,
|
||||||
|
} from "@/lib/cobros-fechas";
|
||||||
import type { PagoRecurrente } from "@/generated/prisma/client";
|
import type { PagoRecurrente } from "@/generated/prisma/client";
|
||||||
|
|
||||||
// LADO SERVIDOR de los cobros recurrentes. Las utilidades puras (fechas,
|
// LADO SERVIDOR de los cobros recurrentes. Las utilidades puras (fechas,
|
||||||
@@ -50,6 +56,57 @@ export async function generarCobros(
|
|||||||
return creados;
|
return creados;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// COBROS POR PAGAR (ya vencidos: fecha <= hoy MX) en estado pendiente o
|
||||||
|
// rechazado, del cliente indicado o de todos. Incluye los de programas
|
||||||
|
// inactivos: desactivar un programa frena cobros nuevos, no perdona deudas.
|
||||||
|
// Es la fuente unica del saldo pendiente (vista admin) y de los recordatorios.
|
||||||
|
export function pagosPorCobrar(clienteId?: string) {
|
||||||
|
return prisma.pagoRecurrente.findMany({
|
||||||
|
where: {
|
||||||
|
estado: { in: ESTADOS_POR_PAGAR },
|
||||||
|
fecha: { lte: hoyCalendario() },
|
||||||
|
...(clienteId ? { programa: { clienteId } } : {}),
|
||||||
|
},
|
||||||
|
orderBy: { fecha: "asc" },
|
||||||
|
include: {
|
||||||
|
programa: { include: { cliente: { include: { usuario: true } } } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PagoPorCobrar = Awaited<ReturnType<typeof pagosPorCobrar>>[number];
|
||||||
|
|
||||||
|
// Agrupa por cliente conservando el orden (fecha mas antigua primero).
|
||||||
|
export function agruparPorCliente(pagos: PagoPorCobrar[]): Map<string, PagoPorCobrar[]> {
|
||||||
|
const grupos = new Map<string, PagoPorCobrar[]>();
|
||||||
|
for (const p of pagos) {
|
||||||
|
const id = p.programa.clienteId;
|
||||||
|
const lista = grupos.get(id) ?? [];
|
||||||
|
lista.push(p);
|
||||||
|
grupos.set(id, lista);
|
||||||
|
}
|
||||||
|
return grupos;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suma por moneda: un cliente puede tener programas en MXN y USD y no se
|
||||||
|
// deben mezclar en un solo total.
|
||||||
|
export function totalesPorMoneda(pagos: Array<{ monto: number; programa: { moneda: string } }>) {
|
||||||
|
const totales: Record<string, number> = {};
|
||||||
|
for (const p of pagos) {
|
||||||
|
const moneda = p.programa.moneda || "MXN";
|
||||||
|
totales[moneda] = (totales[moneda] ?? 0) + p.monto;
|
||||||
|
}
|
||||||
|
return totales;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dias entre recordatorios automaticos (COBROS_RECORDATORIO_DIAS; 0 = apagado).
|
||||||
|
export function diasRecordatorio(): number {
|
||||||
|
const raw = process.env.COBROS_RECORDATORIO_DIAS;
|
||||||
|
if (raw === undefined || raw.trim() === "") return RECORDATORIO_DIAS_DEFAULT;
|
||||||
|
const n = Number(raw);
|
||||||
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : RECORDATORIO_DIAS_DEFAULT;
|
||||||
|
}
|
||||||
|
|
||||||
// Normaliza cualquier Date a medianoche UTC de su parte de calendario.
|
// Normaliza cualquier Date a medianoche UTC de su parte de calendario.
|
||||||
function aCalendarioFecha(date: Date): Date {
|
function aCalendarioFecha(date: Date): Date {
|
||||||
const { y, m, d } = aCalendario(date);
|
const { y, m, d } = aCalendario(date);
|
||||||
|
|||||||
+238
-16
@@ -1,7 +1,22 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { enviarCorreo } from "@/lib/email";
|
import { enviarCorreo, smtpConfigurado } from "@/lib/email";
|
||||||
import { enviarPush } from "@/lib/push";
|
import { enviarPush, pushConfigurado } from "@/lib/push";
|
||||||
import { ESTADOS_PAGO, formatFechaCobro, formatFechaCorta } from "@/lib/cobros";
|
import { getConfigBancaria } from "@/lib/config-helpers";
|
||||||
|
import {
|
||||||
|
ESTADOS_PAGO,
|
||||||
|
agruparPorCliente,
|
||||||
|
calendarioDe,
|
||||||
|
diasDeAtraso,
|
||||||
|
diasRecordatorio,
|
||||||
|
formatFechaCobro,
|
||||||
|
formatFechaCorta,
|
||||||
|
formatTotales,
|
||||||
|
hoyCalendario,
|
||||||
|
pagosPorCobrar,
|
||||||
|
sumarDias,
|
||||||
|
totalesPorMoneda,
|
||||||
|
type PagoPorCobrar,
|
||||||
|
} from "@/lib/cobros";
|
||||||
import type { PagoRecurrente } from "@/generated/prisma/client";
|
import type { PagoRecurrente } from "@/generated/prisma/client";
|
||||||
|
|
||||||
// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es
|
// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es
|
||||||
@@ -11,9 +26,30 @@ import type { PagoRecurrente } from "@/generated/prisma/client";
|
|||||||
// Los handlers de rutas solo necesitan:
|
// Los handlers de rutas solo necesitan:
|
||||||
// - tras generar cobros: notificarCobrosNuevos(pagos)
|
// - tras generar cobros: notificarCobrosNuevos(pagos)
|
||||||
// - al aprobar/rechazar: notificarVerificacion(pagoId) / notificarRechazo(pagoId)
|
// - al aprobar/rechazar: notificarVerificacion(pagoId) / notificarRechazo(pagoId)
|
||||||
|
// - cobranza de lo que sigue por pagar: enviarRecordatoriosPendientes()
|
||||||
|
|
||||||
const BASE_URL = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
|
// URL publica para los links de correo, leida AL ENVIAR. No usar un nombre
|
||||||
const PANEL_PAGOS = `${BASE_URL}/cliente/pagos`;
|
// NEXT_PUBLIC_*: Next lo incrusta en el bundle durante el build (tambien en el
|
||||||
|
// servidor, incluso con clave calculada) y la imagen de produccion se construye
|
||||||
|
// sin ese valor, asi que el link quedaba fijo en "http://localhost:3000".
|
||||||
|
function panelPagos(): string {
|
||||||
|
const base = process.env.APP_URL || "http://localhost:3000";
|
||||||
|
return `${base.replace(/\/+$/, "")}/cliente/pagos`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nombres, conceptos y motivos los captura una persona: no deben poder
|
||||||
|
// inyectar HTML en el correo.
|
||||||
|
function esc(s: string): string {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatoMoneda(monto: number, moneda: string): string {
|
||||||
|
return monto.toLocaleString("es-MX", { style: "currency", currency: moneda || "MXN" });
|
||||||
|
}
|
||||||
|
|
||||||
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
|
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
|
||||||
const botonHtml = boton
|
const botonHtml = boton
|
||||||
@@ -23,7 +59,7 @@ function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url:
|
|||||||
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
|
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
|
||||||
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
<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>
|
<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>
|
<h1 style="font-size:20px;color:#18181b;margin:0 0 16px">${esc(titulo)}</h1>
|
||||||
<div style="font-size:15px;color:#3f3f46;line-height:1.6">${cuerpo}</div>
|
<div style="font-size:15px;color:#3f3f46;line-height:1.6">${cuerpo}</div>
|
||||||
${botonHtml}
|
${botonHtml}
|
||||||
<p style="font-size:12px;color:#a1a1aa;margin:24px 0 0">Consultoría E3 · Querétaro, México</p>
|
<p style="font-size:12px;color:#a1a1aa;margin:24px 0 0">Consultoría E3 · Querétaro, México</p>
|
||||||
@@ -100,8 +136,8 @@ export async function notificarCobrosNuevos(pagos: PagoRecurrente[]): Promise<vo
|
|||||||
? `Se ${lista.length > 1 ? "generaron" : "generó"} ${lista.length} cobros de ${programa.concepto}`
|
? `Se ${lista.length > 1 ? "generaron" : "generó"} ${lista.length} cobros de ${programa.concepto}`
|
||||||
: `Nuevo cobro: ${programa.concepto}`;
|
: `Nuevo cobro: ${programa.concepto}`;
|
||||||
const cuerpo = `
|
const cuerpo = `
|
||||||
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
|
<p>Hola <strong>${esc(programa.cliente.nombre)}</strong>,</p>
|
||||||
<p>${plural ? `Se generaron <strong>${lista.length} cobros</strong>` : `Se generó un cobro`} de <strong>${programa.concepto}</strong>:</p>
|
<p>${plural ? `Se generaron <strong>${lista.length} cobros</strong>` : `Se generó un cobro`} de <strong>${esc(programa.concepto)}</strong>:</p>
|
||||||
<ul style="padding-left:20px">${filas}${extra}</ul>
|
<ul style="padding-left:20px">${filas}${extra}</ul>
|
||||||
<p>Sube tu comprobante de pago desde el panel para darlo por liquidado.</p>`;
|
<p>Sube tu comprobante de pago desde el panel para darlo por liquidado.</p>`;
|
||||||
|
|
||||||
@@ -114,7 +150,7 @@ export async function notificarCobrosNuevos(pagos: PagoRecurrente[]): Promise<vo
|
|||||||
userId,
|
userId,
|
||||||
destino,
|
destino,
|
||||||
titulo,
|
titulo,
|
||||||
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }),
|
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: panelPagos() }),
|
||||||
texto,
|
texto,
|
||||||
{
|
{
|
||||||
titulo: plural ? `${lista.length} cobros nuevos` : "Nuevo cobro pendiente",
|
titulo: plural ? `${lista.length} cobros nuevos` : "Nuevo cobro pendiente",
|
||||||
@@ -149,8 +185,8 @@ export async function notificarVerificacion(pagoId: string): Promise<void> {
|
|||||||
|
|
||||||
const titulo = `Pago verificado: ${programa.concepto}`;
|
const titulo = `Pago verificado: ${programa.concepto}`;
|
||||||
const cuerpo = `
|
const cuerpo = `
|
||||||
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
|
<p>Hola <strong>${esc(programa.cliente.nombre)}</strong>,</p>
|
||||||
<p>Tu pago corresponde al <strong>${formatFechaCobro(pago.fecha)}</strong> por
|
<p>Tu pago correspondiente al <strong>${formatFechaCobro(pago.fecha)}</strong> por
|
||||||
<strong>${pago.monto.toLocaleString("es-MX", { style: "currency", currency: programa.moneda })}</strong>
|
<strong>${pago.monto.toLocaleString("es-MX", { style: "currency", currency: programa.moneda })}</strong>
|
||||||
fue <strong>verificado</strong>. Ya aparece como liquidado en tu panel.</p>`;
|
fue <strong>verificado</strong>. Ya aparece como liquidado en tu panel.</p>`;
|
||||||
|
|
||||||
@@ -158,7 +194,7 @@ export async function notificarVerificacion(pagoId: string): Promise<void> {
|
|||||||
userId,
|
userId,
|
||||||
destino,
|
destino,
|
||||||
titulo,
|
titulo,
|
||||||
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: PANEL_PAGOS }),
|
plantilla(titulo, cuerpo, { texto: "Ver mis pagos", url: panelPagos() }),
|
||||||
`${programa.concepto}: pago del ${formatFechaCorta(pago.fecha)} verificado.`,
|
`${programa.concepto}: pago del ${formatFechaCorta(pago.fecha)} verificado.`,
|
||||||
{
|
{
|
||||||
titulo: "Pago verificado ✓",
|
titulo: "Pago verificado ✓",
|
||||||
@@ -183,17 +219,17 @@ export async function notificarRechazo(pagoId: string, motivo: string): Promise<
|
|||||||
|
|
||||||
const titulo = `Comprobante rechazado: ${programa.concepto}`;
|
const titulo = `Comprobante rechazado: ${programa.concepto}`;
|
||||||
const cuerpo = `
|
const cuerpo = `
|
||||||
<p>Hola <strong>${programa.cliente.nombre}</strong>,</p>
|
<p>Hola <strong>${esc(programa.cliente.nombre)}</strong>,</p>
|
||||||
<p>Rechazamos el comprobante del pago <strong>${formatFechaCobro(pago.fecha)}</strong>
|
<p>Rechazamos el comprobante del pago <strong>${formatFechaCobro(pago.fecha)}</strong>
|
||||||
(${programa.concepto}).</p>
|
(${esc(programa.concepto)}).</p>
|
||||||
${motivo ? `<p><strong>Motivo:</strong> ${motivo}</p>` : ""}
|
${motivo ? `<p><strong>Motivo:</strong> ${esc(motivo)}</p>` : ""}
|
||||||
<p>Puedes volver a subir un comprobante desde el panel.</p>`;
|
<p>Puedes volver a subir un comprobante desde el panel.</p>`;
|
||||||
|
|
||||||
await avisar(
|
await avisar(
|
||||||
userId,
|
userId,
|
||||||
destino,
|
destino,
|
||||||
titulo,
|
titulo,
|
||||||
plantilla(titulo, cuerpo, { texto: "Subir otro comprobante", url: PANEL_PAGOS }),
|
plantilla(titulo, cuerpo, { texto: "Subir otro comprobante", url: panelPagos() }),
|
||||||
`${programa.concepto}: comprobante del ${formatFechaCorta(pago.fecha)} rechazado. ${motivo || ""}`.trim(),
|
`${programa.concepto}: comprobante del ${formatFechaCorta(pago.fecha)} rechazado. ${motivo || ""}`.trim(),
|
||||||
{
|
{
|
||||||
titulo: "Comprobante rechazado",
|
titulo: "Comprobante rechazado",
|
||||||
@@ -205,3 +241,189 @@ export async function notificarRechazo(pagoId: string, motivo: string): Promise<
|
|||||||
console.error("[notificaciones] fallo al avisar rechazo", pagoId, e);
|
console.error("[notificaciones] fallo al avisar rechazo", pagoId, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Recordatorios de pagos pendientes (cobranza) ────────────────────────────
|
||||||
|
//
|
||||||
|
// notificarCobrosNuevos avisa UNA vez, cuando se genera el cobro. Si el cliente
|
||||||
|
// no paga, este es el aviso que se repite: un estado de cuenta por cliente con
|
||||||
|
// TODO lo que sigue por pagar (pendiente o con comprobante rechazado), el total
|
||||||
|
// por moneda y los datos bancarios de Configuracion.
|
||||||
|
//
|
||||||
|
// - Automatico (scheduler): solo a clientes con algun cobro que lleve
|
||||||
|
// COBROS_RECORDATORIO_DIAS dias sin aviso. 0 apaga el automatico.
|
||||||
|
// - Manual (POST /api/cobros/recordatorios): `forzar` ignora la espera.
|
||||||
|
//
|
||||||
|
// Al entregarse por algun canal se sella ultimoRecordatorioAt en esos cobros;
|
||||||
|
// si no salio por ningun lado no se sella, para reintentar en la siguiente
|
||||||
|
// corrida (por ejemplo, en cuanto se configure SMTP).
|
||||||
|
|
||||||
|
export type ResultadoCorreo = "enviado" | "omitido" | "sin_email" | "error";
|
||||||
|
|
||||||
|
export interface ResultadoRecordatorio {
|
||||||
|
clienteId: string;
|
||||||
|
cliente: string;
|
||||||
|
pagos: number;
|
||||||
|
totales: Record<string, number>;
|
||||||
|
correo: ResultadoCorreo;
|
||||||
|
// Notificaciones push entregadas (0 sin VAPID o sin suscripciones).
|
||||||
|
push: number;
|
||||||
|
// true si algun canal entrego el aviso (y por tanto se sello en los cobros).
|
||||||
|
entregado: boolean;
|
||||||
|
// Cobros incluidos en el estado de cuenta (el scheduler los usa para no
|
||||||
|
// mandar ademas el aviso de "cobro nuevo" de los que ya iban aqui).
|
||||||
|
pagoIds: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ultima vez que el cliente supo de este cobro, como fecha de calendario MX:
|
||||||
|
// al generarse, al rechazarle el comprobante o en el ultimo recordatorio.
|
||||||
|
function ultimoAviso(p: PagoPorCobrar): Date {
|
||||||
|
let ultimo = p.createdAt;
|
||||||
|
for (const d of [p.rechazadoAt, p.ultimoRecordatorioAt]) {
|
||||||
|
if (d && d > ultimo) ultimo = d;
|
||||||
|
}
|
||||||
|
return calendarioDe(ultimo);
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_FILAS_RECORDATORIO = 20;
|
||||||
|
|
||||||
|
function mensajeRecordatorio(
|
||||||
|
nombre: string,
|
||||||
|
lista: PagoPorCobrar[],
|
||||||
|
hoy: Date,
|
||||||
|
banco: Record<string, string>
|
||||||
|
) {
|
||||||
|
const n = lista.length;
|
||||||
|
const totalTexto = formatTotales(totalesPorMoneda(lista));
|
||||||
|
const titulo =
|
||||||
|
n === 1 ? `Recordatorio de pago: ${lista[0].programa.concepto}` : `Tienes ${n} pagos pendientes`;
|
||||||
|
|
||||||
|
const celda = "padding:8px;border-bottom:1px solid #e4e4e7;vertical-align:top";
|
||||||
|
const nota = "font-size:12px;color:#71717a";
|
||||||
|
const filas = lista
|
||||||
|
.slice(0, MAX_FILAS_RECORDATORIO)
|
||||||
|
.map((p) => {
|
||||||
|
const atraso = diasDeAtraso(p.fecha, hoy);
|
||||||
|
const cuando = atraso === 0 ? "vence hoy" : atraso === 1 ? "hace 1 día" : `hace ${atraso} días`;
|
||||||
|
const estado =
|
||||||
|
p.estado === ESTADOS_PAGO.RECHAZADO ? "Comprobante rechazado, vuelve a subirlo" : "Pendiente";
|
||||||
|
return `<tr>
|
||||||
|
<td style="${celda}">${formatFechaCorta(p.fecha)}<br><span style="${nota}">${cuando}</span></td>
|
||||||
|
<td style="${celda}">${esc(p.programa.concepto)}<br><span style="${nota}">${estado}</span></td>
|
||||||
|
<td style="${celda};text-align:right;white-space:nowrap">${formatoMoneda(p.monto, p.programa.moneda)}</td>
|
||||||
|
</tr>`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
const extra =
|
||||||
|
n > MAX_FILAS_RECORDATORIO
|
||||||
|
? `<p style="${nota}">…y ${n - MAX_FILAS_RECORDATORIO} cobros más. Consulta el detalle en tu panel.</p>`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
const datosPago = [
|
||||||
|
banco.razon_social && `Titular: <strong>${esc(banco.razon_social)}</strong>`,
|
||||||
|
banco.clabe_interbancaria && `CLABE: <strong>${esc(banco.clabe_interbancaria)}</strong>`,
|
||||||
|
banco.cuenta_nacional && `Cuenta: <strong>${esc(banco.cuenta_nacional)}</strong>`,
|
||||||
|
].filter(Boolean);
|
||||||
|
const bloqueBanco = datosPago.length
|
||||||
|
? `<div style="margin:20px 0;padding:16px;background:#f4f4f5;border-radius:8px;font-size:14px">
|
||||||
|
<p style="margin:0 0 8px;font-weight:600">Datos para tu pago</p>
|
||||||
|
${datosPago.map((d) => `<div>${d}</div>`).join("")}
|
||||||
|
</div>`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
const cuerpo = `
|
||||||
|
<p>Hola <strong>${esc(nombre)}</strong>,</p>
|
||||||
|
<p>Te recordamos que ${n === 1 ? "tienes un pago pendiente" : `tienes <strong>${n} pagos pendientes</strong>`}:</p>
|
||||||
|
<table style="width:100%;border-collapse:collapse;font-size:14px">${filas}</table>
|
||||||
|
${extra}
|
||||||
|
<p style="font-size:16px;margin:16px 0 0">Total pendiente: <strong>${totalTexto}</strong></p>
|
||||||
|
${bloqueBanco}
|
||||||
|
<p>Cuando realices el pago, sube tu comprobante en el panel para que lo verifiquemos.
|
||||||
|
Si ya pagaste, solo falta ese paso.</p>`;
|
||||||
|
|
||||||
|
const texto =
|
||||||
|
`${titulo}. Total pendiente: ${totalTexto}. ` +
|
||||||
|
lista
|
||||||
|
.slice(0, 5)
|
||||||
|
.map((p) => `${formatFechaCorta(p.fecha)} ${p.programa.concepto} ${formatoMoneda(p.monto, p.programa.moneda)}`)
|
||||||
|
.join("; ") +
|
||||||
|
`. Sube tu comprobante en ${panelPagos()}`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
titulo,
|
||||||
|
html: plantilla(titulo, cuerpo, { texto: "Subir comprobante", url: panelPagos() }),
|
||||||
|
texto,
|
||||||
|
push: {
|
||||||
|
titulo: n === 1 ? "Tienes un pago pendiente" : `Tienes ${n} pagos pendientes`,
|
||||||
|
cuerpo: `Total pendiente: ${totalTexto}`,
|
||||||
|
url: "/cliente/pagos",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function enviarRecordatoriosPendientes(
|
||||||
|
opts: { clienteId?: string; forzar?: boolean } = {}
|
||||||
|
): Promise<ResultadoRecordatorio[]> {
|
||||||
|
const dias = diasRecordatorio();
|
||||||
|
if (!opts.forzar && dias === 0) return [];
|
||||||
|
// Sin ningun canal configurado el automatico no tiene como entregar nada:
|
||||||
|
// no recorrer clientes cada hora solo para llenar el log de "omitido".
|
||||||
|
if (!opts.forzar && !smtpConfigurado() && !pushConfigurado()) return [];
|
||||||
|
|
||||||
|
const hoy = hoyCalendario();
|
||||||
|
const limite = sumarDias(hoy, -dias);
|
||||||
|
const grupos = agruparPorCliente(await pagosPorCobrar(opts.clienteId));
|
||||||
|
if (grupos.size === 0) return [];
|
||||||
|
const banco = await getConfigBancaria();
|
||||||
|
|
||||||
|
const resultados: ResultadoRecordatorio[] = [];
|
||||||
|
for (const [clienteId, lista] of grupos) {
|
||||||
|
// Basta con que UN cobro lleve `dias` sin aviso para que toque; entonces se
|
||||||
|
// manda la lista completa, no solo ese cobro.
|
||||||
|
if (!opts.forzar && !lista.some((p) => ultimoAviso(p) <= limite)) continue;
|
||||||
|
|
||||||
|
const cliente = lista[0].programa.cliente;
|
||||||
|
const resultado: ResultadoRecordatorio = {
|
||||||
|
clienteId,
|
||||||
|
cliente: cliente.nombre,
|
||||||
|
pagos: lista.length,
|
||||||
|
totales: totalesPorMoneda(lista),
|
||||||
|
correo: "sin_email",
|
||||||
|
push: 0,
|
||||||
|
entregado: false,
|
||||||
|
pagoIds: lista.map((p) => p.id),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const email = cliente.usuario?.email || cliente.email || null;
|
||||||
|
const userId = cliente.usuario?.id ?? null;
|
||||||
|
const mensaje = mensajeRecordatorio(cliente.nombre, lista, hoy, banco);
|
||||||
|
|
||||||
|
if (email) {
|
||||||
|
const r = await enviarCorreo({
|
||||||
|
to: email,
|
||||||
|
subject: mensaje.titulo,
|
||||||
|
html: mensaje.html,
|
||||||
|
text: mensaje.texto,
|
||||||
|
});
|
||||||
|
resultado.correo = r.ok ? "enviado" : r.omitido ? "omitido" : "error";
|
||||||
|
}
|
||||||
|
if (userId) {
|
||||||
|
resultado.push = (await enviarPush(userId, mensaje.push)).enviadas ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.entregado = resultado.correo === "enviado" || resultado.push > 0;
|
||||||
|
if (resultado.entregado) {
|
||||||
|
await prisma.pagoRecurrente.updateMany({
|
||||||
|
where: { id: { in: resultado.pagoIds } },
|
||||||
|
data: { ultimoRecordatorioAt: new Date(), recordatoriosEnviados: { increment: 1 } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[notificaciones] fallo el recordatorio del cliente", clienteId, e);
|
||||||
|
resultado.correo = "error";
|
||||||
|
}
|
||||||
|
resultados.push(resultado);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultados;
|
||||||
|
}
|
||||||
|
|||||||
+27
-4
@@ -1,5 +1,5 @@
|
|||||||
import { generarCobros } from "@/lib/cobros";
|
import { HORA_RECORDATORIOS, generarCobros, horaMexico } from "@/lib/cobros";
|
||||||
import { notificarCobrosNuevos } from "@/lib/notificaciones";
|
import { enviarRecordatoriosPendientes, notificarCobrosNuevos } from "@/lib/notificaciones";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Scheduler automático de cobros recurrentes.
|
* Scheduler automático de cobros recurrentes.
|
||||||
@@ -14,6 +14,12 @@ import { notificarCobrosNuevos } from "@/lib/notificaciones";
|
|||||||
* México (aprox. 06:00 UTC), sin esperar al día siguiente. La generación es
|
* 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.
|
* idempotente: aunque el proceso reinicie, no se duplican periodos.
|
||||||
*
|
*
|
||||||
|
* En la misma corrida, a partir de las HORA_RECORDATORIOS (9:00 MX), reenvía
|
||||||
|
* el estado de cuenta a los clientes que siguen debiendo cobros y no han
|
||||||
|
* recibido aviso en COBROS_RECORDATORIO_DIAS días (ver
|
||||||
|
* enviarRecordatoriosPendientes). El sello por cobro evita repetir el aviso
|
||||||
|
* en las corridas siguientes del mismo día.
|
||||||
|
*
|
||||||
* Este módulo solo se importa desde src/instrumentation.ts dentro del guard
|
* 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.
|
* de runtime nodejs — nunca debe entrar al bundle de edge ni al navegador.
|
||||||
*
|
*
|
||||||
@@ -30,8 +36,25 @@ export function iniciarSchedulerCobros(): void {
|
|||||||
async function ejecutar(): Promise<void> {
|
async function ejecutar(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const creados = await generarCobros();
|
const creados = await generarCobros();
|
||||||
if (creados.length) {
|
|
||||||
await notificarCobrosNuevos(creados);
|
// Recordatorio ANTES del aviso de cobro nuevo: el estado de cuenta ya
|
||||||
|
// lista los cobros recien generados, asi que a esos clientes no se les
|
||||||
|
// manda un segundo correo en la misma corrida.
|
||||||
|
const cubiertos = new Set<string>();
|
||||||
|
if (horaMexico() >= HORA_RECORDATORIOS) {
|
||||||
|
const avisos = await enviarRecordatoriosPendientes();
|
||||||
|
const entregados = avisos.filter((a) => a.entregado);
|
||||||
|
for (const a of entregados) for (const id of a.pagoIds) cubiertos.add(id);
|
||||||
|
if (avisos.length) {
|
||||||
|
console.log(
|
||||||
|
`[cobros-scheduler] recordatorios: ${entregados.length}/${avisos.length} clientes avisados`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const porAvisar = creados.filter((p) => !cubiertos.has(p.id));
|
||||||
|
if (porAvisar.length) {
|
||||||
|
await notificarCobrosNuevos(porAvisar);
|
||||||
}
|
}
|
||||||
console.log(`[cobros-scheduler] ${creados.length} cobros nuevos`);
|
console.log(`[cobros-scheduler] ${creados.length} cobros nuevos`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
Reference in New Issue
Block a user