feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
// Alcances validos para claves de agentes. JAMAS incluir un scope de aprobacion:
|
||||
// aprobar una cotizacion es exclusivamente accion humana de Jareth.
|
||||
export const AGENT_SCOPES = [
|
||||
"catalogo:leer",
|
||||
"clientes:leer",
|
||||
"clientes:escribir",
|
||||
"cotizaciones:leer",
|
||||
"cotizaciones:leer_aceptadas",
|
||||
"cotizaciones:borrador",
|
||||
"cotizaciones:enviar",
|
||||
"cobros:leer",
|
||||
"cobros:registrar",
|
||||
] as const;
|
||||
|
||||
export type AgentScope = (typeof AGENT_SCOPES)[number];
|
||||
|
||||
export const API_KEY_PREFIX = "ujc_live_";
|
||||
|
||||
export type ActorContext =
|
||||
| {
|
||||
type: "user";
|
||||
userId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
clienteId?: string;
|
||||
}
|
||||
| {
|
||||
type: "agent";
|
||||
keyId: string;
|
||||
nombre: string;
|
||||
prefijo: string;
|
||||
scopes: string[];
|
||||
rateLimitPerMin: number;
|
||||
};
|
||||
|
||||
export function esScopeValido(scope: string): scope is AgentScope {
|
||||
return (AGENT_SCOPES as readonly string[]).includes(scope);
|
||||
}
|
||||
|
||||
export function hashSecret(raw: string): string {
|
||||
return createHash("sha256").update(raw, "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export function generateApiKey(): { rawKey: string; prefijo: string; keyHash: string } {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
const rawKey = `${API_KEY_PREFIX}${token}`;
|
||||
const prefijo = rawKey.slice(0, 14);
|
||||
const keyHash = hashSecret(rawKey);
|
||||
return { rawKey, prefijo, keyHash };
|
||||
}
|
||||
|
||||
export function tienePrefijoApiKey(raw: string): boolean {
|
||||
return raw.startsWith(API_KEY_PREFIX) && raw.length >= API_KEY_PREFIX.length + 16;
|
||||
}
|
||||
|
||||
export function actorTieneScope(
|
||||
actor: ActorContext,
|
||||
requiredScopes: AgentScope[],
|
||||
mode: "any" | "all" = "any"
|
||||
): boolean {
|
||||
if (actor.type === "user") {
|
||||
return actor.role !== "cliente";
|
||||
}
|
||||
if (requiredScopes.length === 0) return true;
|
||||
if (mode === "all") {
|
||||
return requiredScopes.every((s) => actor.scopes.includes(s));
|
||||
}
|
||||
return requiredScopes.some((s) => actor.scopes.includes(s));
|
||||
}
|
||||
|
||||
export function esAgenteSoloAceptadas(actor: ActorContext): boolean {
|
||||
return (
|
||||
actor.type === "agent" &&
|
||||
actor.scopes.includes("cotizaciones:leer_aceptadas") &&
|
||||
!actor.scopes.includes("cotizaciones:leer")
|
||||
);
|
||||
}
|
||||
|
||||
// Verifica si `verificarContacto` (email o telefono) coincide con el cliente de la cotizacion.
|
||||
// Para email: exacto case-insensitive. Para telefono: coincidencia en los ultimos 10 digitos MX.
|
||||
export function coincideContacto(
|
||||
verificarContacto: string,
|
||||
cliente: { email?: string | null; telefono?: string | null }
|
||||
): boolean {
|
||||
const valor = (verificarContacto || "").trim();
|
||||
if (!valor) return false;
|
||||
|
||||
if (valor.includes("@")) {
|
||||
const emailCliente = (cliente.email || "").trim().toLowerCase();
|
||||
return Boolean(emailCliente) && emailCliente === valor.toLowerCase();
|
||||
}
|
||||
|
||||
const digitosEntrada = valor.replace(/\D/g, "");
|
||||
const digitosCliente = (cliente.telefono || "").replace(/\D/g, "");
|
||||
if (digitosEntrada.length < 10 || digitosCliente.length < 10) return false;
|
||||
return digitosEntrada.slice(-10) === digitosCliente.slice(-10);
|
||||
}
|
||||
|
||||
// Rate limiter en memoria con ventana deslizante de 60 segundos por keyId.
|
||||
const WINDOW_MS = 60_000;
|
||||
const buckets = new Map<string, number[]>();
|
||||
|
||||
export interface RateLimitResult {
|
||||
ok: boolean;
|
||||
limit: number;
|
||||
remaining: number;
|
||||
resetAt: number; // epoch seconds
|
||||
retryAfterSeconds: number;
|
||||
}
|
||||
|
||||
export function checkRateLimit(
|
||||
keyId: string,
|
||||
limitPerMin: number,
|
||||
nowMs: number = Date.now()
|
||||
): RateLimitResult {
|
||||
const limit = Math.max(1, limitPerMin || 60);
|
||||
const cutoff = nowMs - WINDOW_MS;
|
||||
const timestamps = (buckets.get(keyId) ?? []).filter((ts) => ts > cutoff);
|
||||
|
||||
if (timestamps.length >= limit) {
|
||||
const oldest = timestamps[0] ?? nowMs;
|
||||
const resetMs = oldest + WINDOW_MS;
|
||||
const retryAfterSeconds = Math.max(1, Math.ceil((resetMs - nowMs) / 1000));
|
||||
buckets.set(keyId, timestamps);
|
||||
return {
|
||||
ok: false,
|
||||
limit,
|
||||
remaining: 0,
|
||||
resetAt: Math.ceil(resetMs / 1000),
|
||||
retryAfterSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
timestamps.push(nowMs);
|
||||
buckets.set(keyId, timestamps);
|
||||
const oldest = timestamps[0] ?? nowMs;
|
||||
const resetMs = oldest + WINDOW_MS;
|
||||
return {
|
||||
ok: true,
|
||||
limit,
|
||||
remaining: Math.max(0, limit - timestamps.length),
|
||||
resetAt: Math.ceil(resetMs / 1000),
|
||||
retryAfterSeconds: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRateLimitHeaders(rl: RateLimitResult): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
"X-RateLimit-Limit": String(rl.limit),
|
||||
"X-RateLimit-Remaining": String(rl.remaining),
|
||||
"X-RateLimit-Reset": String(rl.resetAt),
|
||||
};
|
||||
if (!rl.ok) {
|
||||
headers["Retry-After"] = String(rl.retryAfterSeconds);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function resetRateLimiterForTests(): void {
|
||||
buckets.clear();
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { registrarAuditoria, obtenerIp } from "@/lib/audit";
|
||||
import {
|
||||
AGENT_SCOPES,
|
||||
API_KEY_PREFIX,
|
||||
actorTieneScope,
|
||||
buildRateLimitHeaders,
|
||||
checkRateLimit,
|
||||
coincideContacto,
|
||||
esAgenteSoloAceptadas,
|
||||
esScopeValido,
|
||||
generateApiKey,
|
||||
hashSecret,
|
||||
resetRateLimiterForTests,
|
||||
tienePrefijoApiKey,
|
||||
type ActorContext,
|
||||
type AgentScope,
|
||||
type RateLimitResult,
|
||||
} from "@/lib/agent-auth-core";
|
||||
|
||||
export {
|
||||
AGENT_SCOPES,
|
||||
API_KEY_PREFIX,
|
||||
actorTieneScope,
|
||||
buildRateLimitHeaders,
|
||||
checkRateLimit,
|
||||
coincideContacto,
|
||||
esAgenteSoloAceptadas,
|
||||
esScopeValido,
|
||||
generateApiKey,
|
||||
hashSecret,
|
||||
obtenerIp,
|
||||
resetRateLimiterForTests,
|
||||
tienePrefijoApiKey,
|
||||
type ActorContext,
|
||||
type AgentScope,
|
||||
type RateLimitResult,
|
||||
};
|
||||
|
||||
function extraerApiKey(request: NextRequest): string | null {
|
||||
const direct = request.headers.get("x-api-key")?.trim();
|
||||
if (direct) return direct;
|
||||
const auth = request.headers.get("authorization")?.trim();
|
||||
if (auth && auth.toLowerCase().startsWith("bearer ")) {
|
||||
const token = auth.slice(7).trim();
|
||||
if (token) return token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface AuthAttemptResult {
|
||||
actor: ActorContext | null;
|
||||
rateLimited?: boolean;
|
||||
rateLimit?: RateLimitResult;
|
||||
invalidKey?: boolean;
|
||||
}
|
||||
|
||||
export async function authenticateActor(request: NextRequest): Promise<AuthAttemptResult> {
|
||||
// 1. Sesion humana por cookie JWT (siempre tiene prioridad en el navegador)
|
||||
const session = await getSession();
|
||||
if (session) {
|
||||
return {
|
||||
actor: {
|
||||
type: "user",
|
||||
userId: session.userId,
|
||||
email: session.email,
|
||||
name: session.name,
|
||||
role: session.role || "asesor",
|
||||
clienteId: session.clienteId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 2. API Key para agentes (X-API-Key o Authorization: Bearer)
|
||||
const rawKey = extraerApiKey(request);
|
||||
if (!rawKey) return { actor: null };
|
||||
|
||||
const keyHash = hashSecret(rawKey);
|
||||
const record = await prisma.agentApiKey.findFirst({
|
||||
where: {
|
||||
keyHash,
|
||||
activo: true,
|
||||
revokedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
return { actor: null, invalidKey: true };
|
||||
}
|
||||
|
||||
const rl = checkRateLimit(record.id, record.rateLimitPerMin);
|
||||
if (!rl.ok) {
|
||||
return {
|
||||
actor: {
|
||||
type: "agent",
|
||||
keyId: record.id,
|
||||
nombre: record.nombre,
|
||||
prefijo: record.prefijo,
|
||||
scopes: record.scopes,
|
||||
rateLimitPerMin: record.rateLimitPerMin,
|
||||
},
|
||||
rateLimited: true,
|
||||
rateLimit: rl,
|
||||
};
|
||||
}
|
||||
|
||||
// Actualizar lastUsedAt en background si pasaron >60s
|
||||
const ahora = Date.now();
|
||||
if (!record.lastUsedAt || ahora - record.lastUsedAt.getTime() > 60_000) {
|
||||
void prisma.agentApiKey
|
||||
.update({
|
||||
where: { id: record.id },
|
||||
data: { lastUsedAt: new Date(ahora) },
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
return {
|
||||
actor: {
|
||||
type: "agent",
|
||||
keyId: record.id,
|
||||
nombre: record.nombre,
|
||||
prefijo: record.prefijo,
|
||||
scopes: record.scopes,
|
||||
rateLimitPerMin: record.rateLimitPerMin,
|
||||
},
|
||||
rateLimit: rl,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RequireActorOptions {
|
||||
scopes?: AgentScope[];
|
||||
scopeMode?: "any" | "all";
|
||||
adminOnly?: boolean;
|
||||
staffOnly?: boolean;
|
||||
allowCliente?: boolean;
|
||||
accionBloqueo?: string;
|
||||
recursoTipo?: string;
|
||||
recursoId?: string;
|
||||
}
|
||||
|
||||
export type RequireActorResult =
|
||||
| { ok: true; actor: ActorContext; rateLimitHeaders: Record<string, string> }
|
||||
| { ok: false; response: NextResponse };
|
||||
|
||||
export async function requireActor(
|
||||
request: NextRequest,
|
||||
opts: RequireActorOptions = {}
|
||||
): Promise<RequireActorResult> {
|
||||
const attempt = await authenticateActor(request);
|
||||
const rlHeaders = attempt.rateLimit ? buildRateLimitHeaders(attempt.rateLimit) : {};
|
||||
|
||||
if (attempt.rateLimited && attempt.actor) {
|
||||
await registrarAuditoria({
|
||||
actor: attempt.actor,
|
||||
accion: "auth.rate_limit",
|
||||
recursoTipo: opts.recursoTipo || "api",
|
||||
recursoId: opts.recursoId,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: {
|
||||
path: request.nextUrl.pathname,
|
||||
limit: attempt.rateLimit?.limit,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: "Limite de peticiones por minuto excedido. Intenta de nuevo mas tarde." },
|
||||
{ status: 429, headers: rlHeaders }
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (!attempt.actor) {
|
||||
if (attempt.invalidKey) {
|
||||
await registrarAuditoria({
|
||||
actor: { type: "system", nombre: "api-key-invalida" },
|
||||
accion: "auth.api_key_invalida",
|
||||
recursoTipo: opts.recursoTipo || "api",
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { path: request.nextUrl.pathname },
|
||||
});
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: "No autenticado" }, { status: 401 }),
|
||||
};
|
||||
}
|
||||
|
||||
const actor = attempt.actor;
|
||||
|
||||
// adminOnly: exclusivamente usuario humano con role === "admin"
|
||||
if (opts.adminOnly) {
|
||||
if (actor.type !== "user" || actor.role !== "admin") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: opts.accionBloqueo || "auth.admin_requerido",
|
||||
recursoTipo: opts.recursoTipo || "api",
|
||||
recursoId: opts.recursoId,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { path: request.nextUrl.pathname, actorType: actor.type },
|
||||
});
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: "Accion restringida exclusivamente a un administrador humano" },
|
||||
{ status: 403, headers: rlHeaders }
|
||||
),
|
||||
};
|
||||
}
|
||||
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||
}
|
||||
|
||||
// staffOnly: exclusivamente usuario humano staff (admin o asesor)
|
||||
if (opts.staffOnly) {
|
||||
if (actor.type !== "user" || actor.role === "cliente") {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: opts.accionBloqueo || "auth.staff_requerido",
|
||||
recursoTipo: opts.recursoTipo || "api",
|
||||
recursoId: opts.recursoId,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: { path: request.nextUrl.pathname, actorType: actor.type },
|
||||
});
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: "Accion restringida a personal humano" },
|
||||
{ status: 403, headers: rlHeaders }
|
||||
),
|
||||
};
|
||||
}
|
||||
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||
}
|
||||
|
||||
// Usuarios cliente: bloqueados salvo allowCliente
|
||||
if (actor.type === "user" && actor.role === "cliente") {
|
||||
if (!opts.allowCliente) {
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: "No autorizado" }, { status: 403 }),
|
||||
};
|
||||
}
|
||||
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||
}
|
||||
|
||||
// Usuarios staff (admin/asesor) pasan scopes de agente
|
||||
if (actor.type === "user") {
|
||||
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||
}
|
||||
|
||||
// Agente: validar scopes
|
||||
if (opts.scopes && opts.scopes.length > 0) {
|
||||
const okScope = actorTieneScope(actor, opts.scopes, opts.scopeMode ?? "any");
|
||||
if (!okScope) {
|
||||
await registrarAuditoria({
|
||||
actor,
|
||||
accion: opts.accionBloqueo || "auth.scope_insuficiente",
|
||||
recursoTipo: opts.recursoTipo || "api",
|
||||
recursoId: opts.recursoId,
|
||||
request,
|
||||
exito: false,
|
||||
detalle: {
|
||||
path: request.nextUrl.pathname,
|
||||
requiredScopes: opts.scopes,
|
||||
actorScopes: actor.scopes,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: "Alcance insuficiente para esta operacion",
|
||||
requiredScopes: opts.scopes,
|
||||
},
|
||||
{ status: 403, headers: rlHeaders }
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, actor, rateLimitHeaders: rlHeaders };
|
||||
}
|
||||
|
||||
export function applyHeaders(response: NextResponse, headers: Record<string, string>): NextResponse {
|
||||
for (const [k, v] of Object.entries(headers)) {
|
||||
response.headers.set(k, v);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { ESTADOS_COTIZACION, type EstadoCotizacion } from "@/lib/calculators";
|
||||
import type { ActorContext } from "@/lib/agent-auth-core";
|
||||
|
||||
export { ESTADOS_COTIZACION, type EstadoCotizacion };
|
||||
|
||||
export type ViaTransicion = "aprobar" | "enlace_firmado" | "enviar" | "estado" | "put";
|
||||
|
||||
export interface ValidarTransicionInput {
|
||||
actual: string;
|
||||
nuevo: string;
|
||||
actor: ActorContext | { type: "enlace_firmado" };
|
||||
viaEndpoint: ViaTransicion;
|
||||
aprobadaAt?: Date | string | null;
|
||||
}
|
||||
|
||||
export interface ValidarTransicionResult {
|
||||
ok: boolean;
|
||||
status?: 400 | 403 | 409;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function esEstadoValido(estado: string): estado is EstadoCotizacion {
|
||||
return (ESTADOS_COTIZACION as readonly string[]).includes(estado);
|
||||
}
|
||||
|
||||
export function validarTransicionEstado(input: ValidarTransicionInput): ValidarTransicionResult {
|
||||
const { actual, nuevo, actor, viaEndpoint, aprobadaAt } = input;
|
||||
|
||||
if (!esEstadoValido(nuevo)) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
error: `Estado invalido. Permitidos: ${ESTADOS_COTIZACION.join(", ")}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (actual === nuevo) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const esAdminHumano = actor.type === "user" && actor.role === "admin";
|
||||
const esStaffHumano = actor.type === "user" && actor.role !== "cliente";
|
||||
const esEnlaceFirmado = actor.type === "enlace_firmado" && viaEndpoint === "enlace_firmado";
|
||||
const esAgente = actor.type === "agent";
|
||||
|
||||
// REGLA DE HIERRO 1: Nadie salvo admin humano o enlace firmado de un solo uso puede aprobar.
|
||||
if (nuevo === "aprobada") {
|
||||
if (!esAdminHumano && !esEnlaceFirmado) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 403,
|
||||
error: "Solo un administrador humano o el enlace firmado puede aprobar una cotizacion",
|
||||
};
|
||||
}
|
||||
if (actual !== "borrador") {
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
error: `Solo se puede aprobar una cotizacion en borrador (estado actual: ${actual})`,
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// REGLA DE HIERRO 2: Nadie puede pasar a "enviada" sin estar previamente aprobada (con aprobadaAt).
|
||||
if (nuevo === "enviada") {
|
||||
if (esAgente && viaEndpoint !== "enviar") {
|
||||
return {
|
||||
ok: false,
|
||||
status: 403,
|
||||
error: "Los agentes solo pueden enviar cotizaciones mediante POST /api/cotizaciones/:id/enviar",
|
||||
};
|
||||
}
|
||||
if (actual !== "aprobada" || !aprobadaAt) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
error: "La cotizacion debe estar aprobada por el administrador antes de enviarse",
|
||||
};
|
||||
}
|
||||
if (esAgente) {
|
||||
if (!actor.scopes.includes("cotizaciones:enviar")) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 403,
|
||||
error: "El agente no tiene el alcance cotizaciones:enviar",
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
if (!esStaffHumano) {
|
||||
return { ok: false, status: 403, error: "No autorizado para enviar cotizaciones" };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// Reabrir a borrador: solo admin humano desde aprobada, rechazada o vencida.
|
||||
if (nuevo === "borrador") {
|
||||
if (!esAdminHumano) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 403,
|
||||
error: "Solo un administrador humano puede regresar una cotizacion a borrador",
|
||||
};
|
||||
}
|
||||
if (!["aprobada", "rechazada", "vencida"].includes(actual)) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
error: `No se puede regresar a borrador desde el estado ${actual}`,
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// Estados de cierre post-envio: aceptada | rechazada | vencida
|
||||
if (["aceptada", "rechazada", "vencida"].includes(nuevo)) {
|
||||
if (!esStaffHumano) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 403,
|
||||
error: "Solo el equipo humano puede marcar una cotizacion como aceptada, rechazada o vencida",
|
||||
};
|
||||
}
|
||||
if (actual !== "enviada") {
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
error: `Solo se puede pasar a ${nuevo} desde el estado enviada (estado actual: ${actual})`,
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
status: 409,
|
||||
error: `Transicion no permitida de ${actual} a ${nuevo}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { hashSecret } from "@/lib/agent-auth-core";
|
||||
import { enviarCorreo } from "@/lib/email";
|
||||
import { calcularTotalesCotizacion, formatCurrency, formatDate } from "@/lib/calculators";
|
||||
import { registrarAuditoria } from "@/lib/audit";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
import {
|
||||
ESTADOS_COTIZACION,
|
||||
validarTransicionEstado,
|
||||
type EstadoCotizacion,
|
||||
type ValidarTransicionInput,
|
||||
type ValidarTransicionResult,
|
||||
type ViaTransicion,
|
||||
} from "@/lib/aprobacion-core";
|
||||
|
||||
export {
|
||||
ESTADOS_COTIZACION,
|
||||
validarTransicionEstado,
|
||||
type EstadoCotizacion,
|
||||
type ValidarTransicionInput,
|
||||
type ValidarTransicionResult,
|
||||
type ViaTransicion,
|
||||
};
|
||||
|
||||
const APPROVAL_TTL_MS = 72 * 60 * 60 * 1000; // 72 horas
|
||||
|
||||
export function appBaseUrl(): string {
|
||||
return (process.env.APP_URL || "http://localhost:3000").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function escHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
export async function resolverAdminNotifyEmail(): Promise<string | null> {
|
||||
const fromEnv = process.env.ADMIN_NOTIFY_EMAIL?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
const admin = await prisma.user.findFirst({
|
||||
where: { role: "admin" },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { email: true },
|
||||
});
|
||||
return admin?.email ?? null;
|
||||
}
|
||||
|
||||
export async function crearEnlaceAprobacion(
|
||||
cotizacionId: string
|
||||
): Promise<{ url: string; expiraAt: Date }> {
|
||||
const now = new Date();
|
||||
const expiraAt = new Date(now.getTime() + APPROVAL_TTL_MS);
|
||||
const rawToken = randomBytes(32).toString("hex");
|
||||
const tokenHash = hashSecret(rawToken);
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Invalida tokens previos sin usar de esta cotizacion
|
||||
await tx.approvalToken.updateMany({
|
||||
where: { cotizacionId, usadoAt: null },
|
||||
data: { expiraAt: now },
|
||||
});
|
||||
await tx.approvalToken.create({
|
||||
data: {
|
||||
cotizacionId,
|
||||
tokenHash,
|
||||
expiraAt,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
url: `${appBaseUrl()}/aprobar/${rawToken}`,
|
||||
expiraAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function notificarJarethBorrador(
|
||||
cotizacion: {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
moneda: string;
|
||||
vigencia: Date;
|
||||
incluirIva: boolean;
|
||||
cliente: { nombre: string; empresa?: string | null };
|
||||
servicios: Array<{ tipoPago: string; precio: number; seleccionado?: boolean }>;
|
||||
},
|
||||
enlaceAprobacion: { url: string; expiraAt: Date },
|
||||
creadoPor: string
|
||||
): Promise<{ ok: boolean; omitido?: boolean; destino?: string; error?: string }> {
|
||||
try {
|
||||
const destino = await resolverAdminNotifyEmail();
|
||||
if (!destino) {
|
||||
console.warn("[aprobacion] no hay ADMIN_NOTIFY_EMAIL ni usuario admin para notificar");
|
||||
return { ok: false, omitido: true };
|
||||
}
|
||||
|
||||
const totales = calcularTotalesCotizacion(cotizacion.servicios, {
|
||||
incluirIva: cotizacion.incluirIva,
|
||||
});
|
||||
const partesMonto: string[] = [];
|
||||
if (totales.totalUnico > 0) partesMonto.push(`Único: ${formatCurrency(totales.totalUnico)}`);
|
||||
if (totales.totalMensual > 0) partesMonto.push(`Mensual: ${formatCurrency(totales.totalMensual)}/mes`);
|
||||
const montoTexto = partesMonto.length ? partesMonto.join(" · ") : "$0";
|
||||
const panelUrl = `${appBaseUrl()}/cotizaciones/${cotizacion.id}`;
|
||||
|
||||
const subject = `[Aprobación requerida] Borrador ${cotizacion.numero} — ${cotizacion.cliente.empresa || cotizacion.cliente.nombre}`;
|
||||
const html = `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||
<div style="max-width:580px;margin:0 auto;padding:32px 16px">
|
||||
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||
<p style="font-size:12px;letter-spacing:0.06em;color:#0400c4;font-weight:700;margin:0 0 6px">URIEL JARETH CONSULTING · APROBACIÓN</p>
|
||||
<h1 style="font-size:20px;color:#0f172a;margin:0 0 12px">Nuevo borrador listo para revisión</h1>
|
||||
<p style="font-size:14px;color:#334155;line-height:1.6;margin:0 0 16px">
|
||||
Se generó un borrador de cotización y requiere tu aprobación humana antes de poder enviarse al cliente.
|
||||
</p>
|
||||
<div style="padding:14px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;color:#0f172a;line-height:1.7">
|
||||
<div><strong>Folio:</strong> ${escHtml(cotizacion.numero)}</div>
|
||||
<div><strong>Cliente:</strong> ${escHtml(cotizacion.cliente.nombre)}${cotizacion.cliente.empresa ? ` (${escHtml(cotizacion.cliente.empresa)})` : ""}</div>
|
||||
<div><strong>Proyecto:</strong> ${escHtml(cotizacion.proyecto)}</div>
|
||||
<div><strong>Total (${escHtml(cotizacion.moneda)}):</strong> ${escHtml(montoTexto)}</div>
|
||||
<div><strong>Vigencia:</strong> ${escHtml(formatDate(cotizacion.vigencia))}</div>
|
||||
<div><strong>Creada por:</strong> ${escHtml(creadoPor)}</div>
|
||||
</div>
|
||||
<p style="margin:24px 0 12px">
|
||||
<a href="${enlaceAprobacion.url}" style="display:inline-block;background:#0400c4;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">
|
||||
Revisar y aprobar cotización
|
||||
</a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#475569;margin:0 0 12px">
|
||||
O ábrela en el panel: <a href="${panelUrl}" style="color:#0400c4">${panelUrl}</a>
|
||||
</p>
|
||||
<p style="font-size:12px;color:#94a3b8;margin:16px 0 0">
|
||||
Este enlace de aprobación es de un solo uso y expira el ${escHtml(enlaceAprobacion.expiraAt.toISOString())}. No lo compartas con terceros.
|
||||
</p>
|
||||
</div>
|
||||
</div></body></html>`;
|
||||
|
||||
const text = [
|
||||
`Nuevo borrador de cotización ${cotizacion.numero}`,
|
||||
`Cliente: ${cotizacion.cliente.nombre}${cotizacion.cliente.empresa ? ` (${cotizacion.cliente.empresa})` : ""}`,
|
||||
`Proyecto: ${cotizacion.proyecto}`,
|
||||
`Total (${cotizacion.moneda}): ${montoTexto}`,
|
||||
`Creada por: ${creadoPor}`,
|
||||
`Enlace de aprobación (un solo uso): ${enlaceAprobacion.url}`,
|
||||
`Panel: ${panelUrl}`,
|
||||
].join("\n");
|
||||
|
||||
const res = await enviarCorreo({ to: destino, subject, html, text });
|
||||
return { ...res, destino };
|
||||
} catch (err) {
|
||||
console.error("[aprobacion] fallo al notificar a Jareth:", err);
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function notificarJarethWhatsAppFueraVentana(
|
||||
cotizacion: { id: string; numero: string; cliente: { nombre: string; empresa?: string | null } },
|
||||
destino: string,
|
||||
detalle?: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const adminEmail = await resolverAdminNotifyEmail();
|
||||
if (!adminEmail) return false;
|
||||
const panelUrl = `${appBaseUrl()}/cotizaciones/${cotizacion.id}`;
|
||||
const res = await enviarCorreo({
|
||||
to: adminEmail,
|
||||
subject: `[WhatsApp 24h] No se pudo enviar cotización ${cotizacion.numero}`,
|
||||
html: `<p>La cotización <strong>${escHtml(cotizacion.numero)}</strong> para <strong>${escHtml(cotizacion.cliente.nombre)}</strong> no pudo enviarse por WhatsApp a <code>${escHtml(destino)}</code> porque la conversación está fuera de la ventana de 24 horas.</p><p>${detalle ? escHtml(detalle) : ""}</p><p>Revisa o reenvía por correo desde: <a href="${panelUrl}">${panelUrl}</a></p>`,
|
||||
text: `La cotización ${cotizacion.numero} para ${cotizacion.cliente.nombre} no pudo enviarse por WhatsApp (${destino}): fuera de ventana de 24h. Panel: ${panelUrl}`,
|
||||
});
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function aprobarCotizacionConToken(
|
||||
rawToken: string,
|
||||
ip: string | null
|
||||
): Promise<
|
||||
| { ok: true; cotizacionId: string; numero: string; aprobadaAt: Date }
|
||||
| { ok: false; status: 404 | 409 | 410; error: string }
|
||||
> {
|
||||
const tokenHash = hashSecret(rawToken);
|
||||
const now = new Date();
|
||||
|
||||
const resultado = await prisma.$transaction(async (tx) => {
|
||||
const token = await tx.approvalToken.findUnique({
|
||||
where: { tokenHash },
|
||||
include: { cotizacion: { include: { cliente: true } } },
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
return { ok: false as const, status: 404 as const, error: "Enlace de aprobacion invalido" };
|
||||
}
|
||||
if (token.usadoAt) {
|
||||
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ya fue utilizado" };
|
||||
}
|
||||
if (token.expiraAt <= now) {
|
||||
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ha expirado" };
|
||||
}
|
||||
if (token.cotizacion.estado !== "borrador") {
|
||||
return {
|
||||
ok: false as const,
|
||||
status: 409 as const,
|
||||
error: `La cotizacion ya no esta en borrador (estado actual: ${token.cotizacion.estado})`,
|
||||
};
|
||||
}
|
||||
|
||||
// Consumo atomico condicional para evitar doble aprobacion concurrente
|
||||
const claimed = await tx.approvalToken.updateMany({
|
||||
where: { id: token.id, usadoAt: null, expiraAt: { gt: now } },
|
||||
data: { usadoAt: now, usadoIp: ip },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
return { ok: false as const, status: 410 as const, error: "Este enlace de aprobacion ya fue utilizado" };
|
||||
}
|
||||
|
||||
// Invalida cualquier otro token pendiente de la misma cotizacion
|
||||
await tx.approvalToken.updateMany({
|
||||
where: { cotizacionId: token.cotizacionId, usadoAt: null, id: { not: token.id } },
|
||||
data: { expiraAt: now },
|
||||
});
|
||||
|
||||
const cot = await tx.cotizacion.update({
|
||||
where: { id: token.cotizacionId },
|
||||
data: {
|
||||
estado: "aprobada",
|
||||
aprobadaAt: now,
|
||||
aprobacionMetodo: "enlace_firmado",
|
||||
},
|
||||
include: { cliente: true, servicios: true },
|
||||
});
|
||||
|
||||
const tot = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
|
||||
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
||||
|
||||
return {
|
||||
ok: true as const,
|
||||
cotizacionId: cot.id,
|
||||
numero: cot.numero,
|
||||
proyecto: cot.proyecto,
|
||||
moneda: cot.moneda,
|
||||
total: totalWebhook,
|
||||
aprobadaAt: now,
|
||||
cliente: cot.cliente,
|
||||
};
|
||||
});
|
||||
|
||||
if (!resultado.ok) return resultado;
|
||||
|
||||
await registrarAuditoria({
|
||||
actor: { type: "system", nombre: "enlace_firmado" },
|
||||
accion: "cotizacion.aprobar",
|
||||
recursoTipo: "cotizacion",
|
||||
recursoId: resultado.cotizacionId,
|
||||
exito: true,
|
||||
detalle: { metodo: "enlace_firmado", ip },
|
||||
});
|
||||
|
||||
void emitirWebhook("cotizacion.aprobada", {
|
||||
cotizacionId: resultado.cotizacionId,
|
||||
numero: resultado.numero,
|
||||
folio: resultado.numero,
|
||||
titulo: resultado.proyecto,
|
||||
proyecto: resultado.proyecto,
|
||||
moneda: resultado.moneda,
|
||||
total: resultado.total,
|
||||
url: `${appBaseUrl()}/cotizaciones/${resultado.cotizacionId}`,
|
||||
estado: "aprobada",
|
||||
aprobadaAt: resultado.aprobadaAt.toISOString(),
|
||||
aprobacionMetodo: "enlace_firmado",
|
||||
cliente: {
|
||||
id: resultado.cliente.id,
|
||||
nombre: resultado.cliente.nombre,
|
||||
empresa: resultado.cliente.empresa,
|
||||
email: resultado.cliente.email,
|
||||
telefono: resultado.cliente.telefono,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
cotizacionId: resultado.cotizacionId,
|
||||
numero: resultado.numero,
|
||||
aprobadaAt: resultado.aprobadaAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { ActorContext } from "@/lib/agent-auth-core";
|
||||
|
||||
export type AuditActor =
|
||||
| ActorContext
|
||||
| { type: "system"; nombre?: string; id?: string };
|
||||
|
||||
export function obtenerIp(request?: NextRequest | Request | null): string | null {
|
||||
if (!request) return null;
|
||||
const xff = request.headers.get("x-forwarded-for");
|
||||
if (xff) {
|
||||
const first = xff.split(",")[0]?.trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return request.headers.get("x-real-ip")?.trim() || null;
|
||||
}
|
||||
|
||||
export async function registrarAuditoria(params: {
|
||||
actor?: AuditActor | null;
|
||||
accion: string;
|
||||
recursoTipo: string;
|
||||
recursoId?: string | null;
|
||||
request?: NextRequest | Request | null;
|
||||
exito?: boolean;
|
||||
detalle?: Record<string, unknown> | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
let actorTipo = "system";
|
||||
let actorId: string | null = null;
|
||||
let actorNombre = "system";
|
||||
|
||||
if (params.actor) {
|
||||
if (params.actor.type === "user") {
|
||||
actorTipo = "user";
|
||||
actorId = params.actor.userId;
|
||||
actorNombre = params.actor.email || params.actor.name || params.actor.userId;
|
||||
} else if (params.actor.type === "agent") {
|
||||
actorTipo = "agent";
|
||||
actorId = params.actor.keyId;
|
||||
actorNombre = params.actor.nombre;
|
||||
} else {
|
||||
actorTipo = "system";
|
||||
actorId = params.actor.id ?? null;
|
||||
actorNombre = params.actor.nombre ?? "system";
|
||||
}
|
||||
}
|
||||
|
||||
const requestId = params.request?.headers.get("x-request-id") ?? null;
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
actorTipo,
|
||||
actorId,
|
||||
actorNombre,
|
||||
accion: params.accion,
|
||||
recursoTipo: params.recursoTipo,
|
||||
recursoId: params.recursoId ?? null,
|
||||
ip: obtenerIp(params.request),
|
||||
requestId,
|
||||
exito: params.exito ?? true,
|
||||
detalle: (params.detalle ?? undefined) as Prisma.InputJsonValue | undefined,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[audit] fallo al registrar AuditLog:", params.accion, err);
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,7 @@ export const PLANES_BUCEFALO = [
|
||||
{ nivel: "empresarial", label: "Empresarial", precio: 7500 },
|
||||
] as const;
|
||||
|
||||
export const ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"] as const;
|
||||
export const ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"] as const;
|
||||
export type EstadoCotizacion = (typeof ESTADOS_COTIZACION)[number];
|
||||
|
||||
// ----- Registro de horas (notas de pago) -----
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { prisma } from "./db";
|
||||
|
||||
export const DEFAULT_COLOR_PRIMARIO = "#0400C4";
|
||||
export const DEFAULT_COLOR_SECUNDARIO = "#0F172A";
|
||||
|
||||
export async function getConfigBranding() {
|
||||
try {
|
||||
const configs = await prisma.configuracion.findMany({
|
||||
@@ -8,13 +11,24 @@ export async function getConfigBranding() {
|
||||
const map: Record<string, string> = {};
|
||||
for (const c of configs) map[c.clave] = c.valor;
|
||||
return {
|
||||
colorPrimario: map.color_primario || undefined,
|
||||
colorSecundario: map.color_secundario || undefined,
|
||||
logoBase64: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":").slice(1).join(":") : map.logo_base64) : undefined,
|
||||
logoMime: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":")[0] : "image/png") : undefined,
|
||||
colorPrimario: map.color_primario || DEFAULT_COLOR_PRIMARIO,
|
||||
colorSecundario: map.color_secundario || DEFAULT_COLOR_SECUNDARIO,
|
||||
logoBase64: map.logo_base64
|
||||
? map.logo_base64.includes(":")
|
||||
? map.logo_base64.split(":").slice(1).join(":")
|
||||
: map.logo_base64
|
||||
: undefined,
|
||||
logoMime: map.logo_base64
|
||||
? map.logo_base64.includes(":")
|
||||
? map.logo_base64.split(":")[0]
|
||||
: "image/png"
|
||||
: undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
return {
|
||||
colorPrimario: DEFAULT_COLOR_PRIMARIO,
|
||||
colorSecundario: DEFAULT_COLOR_SECUNDARIO,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||
import { sanitizeFilename } from "@/lib/calculators";
|
||||
|
||||
export async function generarPDFCotizacion(cotizacionId: string) {
|
||||
const [cot, config, branding, bonos] = await Promise.all([
|
||||
prisma.cotizacion.findUnique({
|
||||
where: { id: cotizacionId },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: { select: { id: true, name: true, email: true, role: true } },
|
||||
servicios: {
|
||||
include: { servicioCatalogo: true },
|
||||
orderBy: [{ fase: "asc" }, { createdAt: "asc" }],
|
||||
},
|
||||
planBucefalo: true,
|
||||
},
|
||||
}),
|
||||
getConfigBancaria(),
|
||||
getConfigBranding(),
|
||||
prisma.bono.findMany({ where: { activo: true }, orderBy: { numero: "asc" } }),
|
||||
]);
|
||||
|
||||
if (!cot) return null;
|
||||
|
||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||
const filename = `${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}.pdf`;
|
||||
|
||||
const buffer = await generateCotizacionPDF({
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
clienteEmpresa: cot.cliente.empresa || "",
|
||||
asesorNombre: cot.asesor.name,
|
||||
fecha: cot.fecha,
|
||||
vigencia: cot.vigencia,
|
||||
moneda: cot.moneda,
|
||||
tipoCambio: cot.tipoCambio,
|
||||
proyecto: cot.proyecto,
|
||||
esquemaPago: cot.esquemaPago,
|
||||
servicios: cot.servicios
|
||||
.filter((s) => s.seleccionado)
|
||||
.map((s) => ({
|
||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precio,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
||||
esPersonalizado: s.esPersonalizado,
|
||||
horas: s.horas ?? undefined,
|
||||
tarifaHora: s.tarifaHora ?? undefined,
|
||||
modeloCobro: s.modeloCobro ?? undefined,
|
||||
montoMinimo: s.montoMinimo ?? undefined,
|
||||
horasIncluidas: s.horasIncluidas ?? undefined,
|
||||
opcion: s.opcion ?? undefined,
|
||||
})),
|
||||
esDoble: cot.esDoble,
|
||||
opcionesMetadata: cot.opcionesMetadata as never,
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
|
||||
incluirBonos: cot.incluirBonos,
|
||||
bonos,
|
||||
incluirIva: cot.incluirIva,
|
||||
// Solo el texto del cliente. observacionesInternas no se pasa nunca.
|
||||
observaciones: cot.observaciones,
|
||||
configBancaria: config,
|
||||
...branding,
|
||||
});
|
||||
|
||||
return { buffer, filename, cot };
|
||||
}
|
||||
@@ -11,6 +11,7 @@ function createPrismaClient() {
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "postgres",
|
||||
password: process.env.DB_PASSWORD || "postgres",
|
||||
// Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data.
|
||||
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
|
||||
+90
-3
@@ -9,8 +9,14 @@ import type { Transporter } from "nodemailer";
|
||||
// SMTP_PORT=587 (587=starttls, 465=ssl, 25=negociacion)
|
||||
// SMTP_USER=usuario
|
||||
// SMTP_PASS=contrasena
|
||||
// SMTP_FROM=co[email protected] (opcional, por defecto SMTP_USER)
|
||||
// SMTP_FROM_NAME=Cotizador E3 (opcional)
|
||||
// SMTP_FROM=co[email protected] (opcional, por defecto SMTP_USER)
|
||||
// SMTP_FROM_NAME=Uriel Jareth Consulting (opcional)
|
||||
|
||||
export interface AdjuntoCorreo {
|
||||
filename: string;
|
||||
content: Buffer;
|
||||
contentType?: string;
|
||||
}
|
||||
|
||||
export interface ResultadoEnvio {
|
||||
ok: boolean;
|
||||
@@ -49,11 +55,20 @@ export function reiniciarTransport() {
|
||||
transport = undefined;
|
||||
}
|
||||
|
||||
function escHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
export async function enviarCorreo(opciones: {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
text?: string;
|
||||
attachments?: AdjuntoCorreo[];
|
||||
}): Promise<ResultadoEnvio> {
|
||||
const t = obtenerTransport();
|
||||
if (!t) {
|
||||
@@ -62,11 +77,16 @@ export async function enviarCorreo(opciones: {
|
||||
}
|
||||
try {
|
||||
await t.sendMail({
|
||||
from: `"${process.env.SMTP_FROM_NAME || "Cotizador E3"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
|
||||
from: `"${process.env.SMTP_FROM_NAME || "Uriel Jareth Consulting"}" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
|
||||
to: opciones.to,
|
||||
subject: opciones.subject,
|
||||
html: opciones.html,
|
||||
text: opciones.text,
|
||||
attachments: opciones.attachments?.map((a) => ({
|
||||
filename: a.filename,
|
||||
content: a.content,
|
||||
contentType: a.contentType || "application/pdf",
|
||||
})),
|
||||
});
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
@@ -75,3 +95,70 @@ export async function enviarCorreo(opciones: {
|
||||
return { ok: false, error: msg };
|
||||
}
|
||||
}
|
||||
|
||||
export async function enviarCotizacionPorCorreo(opts: {
|
||||
to: string;
|
||||
numero: string;
|
||||
clienteNombre: string;
|
||||
empresa?: string | null;
|
||||
proyecto: string;
|
||||
resumenTotales: string;
|
||||
vigenciaTexto: string;
|
||||
pdfBuffer: Buffer;
|
||||
pdfFilename: string;
|
||||
mensajePersonalizado?: string;
|
||||
}): Promise<ResultadoEnvio> {
|
||||
const asunto = `Cotización ${opts.numero} — ${opts.proyecto} | Uriel Jareth Consulting`;
|
||||
const mensajeExtra = opts.mensajePersonalizado?.trim()
|
||||
? `<p style="margin:12px 0;white-space:pre-line">${escHtml(opts.mensajePersonalizado.trim())}</p>`
|
||||
: "";
|
||||
const empresaTexto = opts.empresa ? ` (${escHtml(opts.empresa)})` : "";
|
||||
const html = `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||
<div style="max-width:580px;margin:0 auto;padding:32px 16px">
|
||||
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||
<p style="font-size:12px;letter-spacing:0.06em;color:#0400c4;font-weight:700;margin:0 0 6px">URIEL JARETH CONSULTING</p>
|
||||
<h1 style="font-size:20px;color:#0f172a;margin:0 0 16px">Cotización ${escHtml(opts.numero)}</h1>
|
||||
<p style="font-size:15px;color:#334155;line-height:1.6;margin:0 0 12px">
|
||||
Hola <strong>${escHtml(opts.clienteNombre)}</strong>${empresaTexto},
|
||||
</p>
|
||||
<p style="font-size:15px;color:#334155;line-height:1.6;margin:0 0 16px">
|
||||
Adjuntamos en formato PDF la propuesta para <strong>${escHtml(opts.proyecto)}</strong>.
|
||||
</p>
|
||||
${mensajeExtra}
|
||||
<div style="margin:18px 0;padding:14px 16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;color:#0f172a">
|
||||
<div><strong>Folio:</strong> ${escHtml(opts.numero)}</div>
|
||||
<div><strong>Resumen:</strong> ${escHtml(opts.resumenTotales)}</div>
|
||||
<div><strong>Vigencia:</strong> ${escHtml(opts.vigenciaTexto)}</div>
|
||||
</div>
|
||||
<p style="font-size:14px;color:#475569;line-height:1.6;margin:16px 0 0">
|
||||
Quedamos atentos a cualquier duda o ajuste que necesites revisar.
|
||||
</p>
|
||||
<p style="font-size:12px;color:#94a3b8;margin:24px 0 0">Uriel Jareth Consulting · urieljareth.com</p>
|
||||
</div>
|
||||
</div></body></html>`;
|
||||
|
||||
const text = [
|
||||
`Hola ${opts.clienteNombre},`,
|
||||
`Adjuntamos en PDF la cotización ${opts.numero} para ${opts.proyecto}.`,
|
||||
opts.mensajePersonalizado?.trim() || "",
|
||||
`Resumen: ${opts.resumenTotales}`,
|
||||
`Vigencia: ${opts.vigenciaTexto}`,
|
||||
"Uriel Jareth Consulting · urieljareth.com",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
return enviarCorreo({
|
||||
to: opts.to,
|
||||
subject: asunto,
|
||||
html,
|
||||
text,
|
||||
attachments: [
|
||||
{
|
||||
filename: opts.pdfFilename.endsWith(".pdf") ? opts.pdfFilename : `${opts.pdfFilename}.pdf`,
|
||||
content: opts.pdfBuffer,
|
||||
contentType: "application/pdf",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ export interface ExcelData {
|
||||
colorSecundario: string;
|
||||
incluirIva?: boolean;
|
||||
/** Texto que SI ve el cliente. El Excel es un documento del cliente (lleva razon
|
||||
* social, "En atencion a:", domicilio fiscal y nota legal), no una herramienta
|
||||
* social, "En atencion a:" y nota legal), no una herramienta
|
||||
* interna: por eso `observacionesInternas` NO se declara aqui. */
|
||||
observaciones?: string | null;
|
||||
}
|
||||
@@ -119,16 +119,16 @@ function setWrapped(
|
||||
}
|
||||
|
||||
export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
||||
const PRIMARY = argb(data.colorPrimario || "#2563eb");
|
||||
const PRIMARY_LIGHT = argb(data.colorPrimario || "#2563eb", "18");
|
||||
const SECONDARY = argb(data.colorSecundario || "#1e293b");
|
||||
const PRIMARY = argb(data.colorPrimario || "#0400C4");
|
||||
const PRIMARY_LIGHT = argb(data.colorPrimario || "#0400C4", "18");
|
||||
const SECONDARY = argb(data.colorSecundario || "#0F172A");
|
||||
const WHITE = "FFFFFFFF";
|
||||
const LIGHT_BG = "FFF8FAFC";
|
||||
const MUTED = "FF64748B";
|
||||
const BORDER_COLOR = "FFE2E8F0";
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = "Cotizador E3";
|
||||
workbook.creator = "Cotizador — Uriel Jareth Consulting";
|
||||
workbook.created = new Date();
|
||||
|
||||
const headerFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: WHITE } };
|
||||
@@ -405,7 +405,7 @@ export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
||||
setWrapped(ws, row, "B", notaResumen, mergedWidth(ws, "B", "K"), { fontSize: 9 });
|
||||
|
||||
// Observaciones del cliente. Solo este campo: el Excel lleva razon social,
|
||||
// "En atencion a:" y domicilio fiscal, o sea que es un documento que el cliente
|
||||
// "En atencion a:" y nota legal, o sea que es un documento que el cliente
|
||||
// recibe. observacionesInternas no existe en ExcelData a proposito.
|
||||
if (data.observaciones && data.observaciones.trim()) {
|
||||
row += 2;
|
||||
@@ -556,13 +556,7 @@ export async function buildCotizacionExcel(data: ExcelData): Promise<Buffer> {
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = data.razonSocial;
|
||||
dw.getCell(`B${r}`).font = { ...boldFont, color: { argb: PRIMARY } };
|
||||
if (data.domicilioFiscal) {
|
||||
r++;
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = data.domicilioFiscal;
|
||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
||||
setWrapped(dw, r, "B", data.domicilioFiscal, mergedWidth(dw, "B", "J"), { fontSize: 9 });
|
||||
}
|
||||
// Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados.
|
||||
}
|
||||
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { hashSecret } from "@/lib/agent-auth-core";
|
||||
|
||||
const TTL_MS = 24 * 60 * 60 * 1000; // 24 horas
|
||||
|
||||
export interface IdempotentContext {
|
||||
rawBody: string;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
export async function withIdempotency(
|
||||
request: NextRequest,
|
||||
actorKey: string,
|
||||
handler: (ctx: IdempotentContext) => Promise<NextResponse>
|
||||
): Promise<NextResponse> {
|
||||
const rawBody = await request.text();
|
||||
let parsedBody: unknown = null;
|
||||
if (rawBody.trim()) {
|
||||
try {
|
||||
parsedBody = JSON.parse(rawBody);
|
||||
} catch {
|
||||
parsedBody = null;
|
||||
}
|
||||
}
|
||||
|
||||
const idemHeader = request.headers.get("idempotency-key")?.trim();
|
||||
if (!idemHeader) {
|
||||
return handler({ rawBody, body: parsedBody });
|
||||
}
|
||||
|
||||
const method = request.method.toUpperCase();
|
||||
const pathname = request.nextUrl.pathname;
|
||||
const composedKey = `${actorKey}:${method}:${pathname}:${idemHeader}`;
|
||||
const requestHash = hashSecret(rawBody);
|
||||
const now = new Date();
|
||||
|
||||
const existing = await prisma.idempotencyKey.findUnique({
|
||||
where: { key: composedKey },
|
||||
});
|
||||
|
||||
if (existing && existing.expiraAt > now) {
|
||||
if (existing.requestHash !== requestHash) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Conflicto de idempotencia: Idempotency-Key ya fue usada con un cuerpo distinto",
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
const replayed = NextResponse.json(existing.responseBody, {
|
||||
status: existing.statusCode,
|
||||
});
|
||||
replayed.headers.set("X-Idempotency-Replayed", "true");
|
||||
return replayed;
|
||||
}
|
||||
|
||||
if (existing && existing.expiraAt <= now) {
|
||||
await prisma.idempotencyKey.delete({ where: { key: composedKey } }).catch(() => {});
|
||||
}
|
||||
|
||||
const response = await handler({ rawBody, body: parsedBody });
|
||||
|
||||
if (response.status < 500) {
|
||||
try {
|
||||
const cloned = response.clone();
|
||||
const responseJson = await cloned.json().catch(() => ({ ok: response.ok }));
|
||||
await prisma.idempotencyKey.upsert({
|
||||
where: { key: composedKey },
|
||||
create: {
|
||||
key: composedKey,
|
||||
method,
|
||||
path: pathname,
|
||||
requestHash,
|
||||
statusCode: response.status,
|
||||
responseBody: responseJson as Prisma.InputJsonValue,
|
||||
expiraAt: new Date(Date.now() + TTL_MS),
|
||||
},
|
||||
update: {
|
||||
requestHash,
|
||||
statusCode: response.status,
|
||||
responseBody: responseJson as Prisma.InputJsonValue,
|
||||
expiraAt: new Date(Date.now() + TTL_MS),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[idempotency] fallo al guardar clave:", err);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -70,8 +70,8 @@ export async function generateNotaHorasPDF(data: NotaHorasPDFData): Promise<Buff
|
||||
const logoBuffer = data.logoBase64 ? await toPngBuffer(data.logoBase64, data.logoMime) : undefined;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const PRIMARY = data.colorPrimario || "#2563eb";
|
||||
const DARK = data.colorSecundario || "#111827";
|
||||
const PRIMARY = data.colorPrimario || "#0400C4";
|
||||
const DARK = data.colorSecundario || "#0F172A";
|
||||
const MUTED = "#6b7280";
|
||||
const BORDER = "#d1d5db";
|
||||
const HEAD_BG = "#f3f4f6";
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type PagoPorCobrar,
|
||||
} from "@/lib/cobros";
|
||||
import type { PagoRecurrente } from "@/generated/prisma/client";
|
||||
import { emitirWebhook } from "@/lib/webhooks";
|
||||
|
||||
// Orquestacion de avisos al cliente: correo SMTP + Web Push. Todo es
|
||||
// best-effort: un fallo de correo/push jamas revienta el flujo que lo llamo
|
||||
@@ -53,16 +54,16 @@ function formatoMoneda(monto: number, moneda: string): string {
|
||||
|
||||
function plantilla(titulo: string, cuerpo: string, boton?: { texto: string; url: string }): string {
|
||||
const botonHtml = boton
|
||||
? `<p style="margin:24px 0"><a href="${boton.url}" style="background:#0f172a;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">${boton.texto}</a></p>`
|
||||
? `<p style="margin:24px 0"><a href="${boton.url}" style="background:#0400c4;color:#fff;padding:12px 20px;border-radius:8px;text-decoration:none;font-weight:600">${boton.texto}</a></p>`
|
||||
: "";
|
||||
return `<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,Helvetica,sans-serif">
|
||||
<div style="max-width:560px;margin:0 auto;padding:32px 16px">
|
||||
<div style="background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:32px">
|
||||
<p style="font-size:13px;color:#71717a;margin:0 0 4px">COTIZADOR E3</p>
|
||||
<p style="font-size:13px;color:#64748b;margin:0 0 4px">URIEL JARETH CONSULTING</p>
|
||||
<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>
|
||||
${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">Uriel Jareth Consulting · urieljareth.com</p>
|
||||
</div>
|
||||
</div></body></html>`;
|
||||
}
|
||||
@@ -422,6 +423,29 @@ export async function enviarRecordatoriosPendientes(
|
||||
console.error("[notificaciones] fallo el recordatorio del cliente", clienteId, e);
|
||||
resultado.correo = "error";
|
||||
}
|
||||
// Emision best-effort del webhook pago.vencido sin alterar ni duplicar correos/push.
|
||||
void emitirWebhook("pago.vencido", {
|
||||
clienteId,
|
||||
cliente: {
|
||||
id: clienteId,
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa ?? null,
|
||||
email: cliente.usuario?.email || cliente.email || null,
|
||||
},
|
||||
totales: resultado.totales,
|
||||
pagos: lista.map((p) => ({
|
||||
id: p.id,
|
||||
programaId: p.programaId,
|
||||
concepto: p.programa.concepto,
|
||||
fecha: p.fecha.toISOString().slice(0, 10),
|
||||
monto: p.monto,
|
||||
moneda: p.programa.moneda,
|
||||
estado: p.estado,
|
||||
diasAtraso: diasDeAtraso(p.fecha, hoy),
|
||||
})),
|
||||
recordatorioEntregado: resultado.entregado,
|
||||
});
|
||||
|
||||
resultados.push(resultado);
|
||||
}
|
||||
|
||||
|
||||
@@ -90,8 +90,8 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
|
||||
: undefined;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const PRIMARY = data.colorPrimario || "#2563eb";
|
||||
const DARK = data.colorSecundario || "#1e293b";
|
||||
const PRIMARY = data.colorPrimario || "#0400C4";
|
||||
const DARK = data.colorSecundario || "#0F172A";
|
||||
const MUTED = "#64748b";
|
||||
const BORDER = "#cbd5e1";
|
||||
const LIGHT_BG = "#f1f5f9";
|
||||
|
||||
@@ -38,7 +38,7 @@ export interface DatosPropuestaPDF {
|
||||
const COLOR_SEMAFORO: Record<string, string> = {
|
||||
rojo: "#dc2626",
|
||||
ambar: "#d97706",
|
||||
azul: "#2563eb",
|
||||
azul: "#0400C4",
|
||||
verde: "#16a34a",
|
||||
};
|
||||
const ETIQUETA_SEMAFORO: Record<string, string> = {
|
||||
@@ -102,8 +102,8 @@ function crearLienzo(): { lienzo: Lienzo; listo: Promise<Buffer> } {
|
||||
}
|
||||
|
||||
export async function generarPropuestaPDF(d: DatosPropuestaPDF): Promise<Buffer> {
|
||||
const PRIMARY = hexSeguro(d.branding.colorPrimario, "#2563eb");
|
||||
const DARK = hexSeguro(d.branding.colorSecundario, "#1e293b");
|
||||
const PRIMARY = hexSeguro(d.branding.colorPrimario, "#0400C4");
|
||||
const DARK = hexSeguro(d.branding.colorSecundario, "#0F172A");
|
||||
const MUTED = "#64748b";
|
||||
const BORDER = "#e2e8f0";
|
||||
|
||||
@@ -420,7 +420,7 @@ export async function generarAnexoInternoPDF(d: DatosPropuestaPDF): Promise<Buff
|
||||
const { lienzo, listo } = crearLienzo();
|
||||
const { doc, W, L, maxY, mTop } = lienzo;
|
||||
let y = mTop;
|
||||
const DARK = "#1e293b";
|
||||
const DARK = "#0F172A";
|
||||
const MUTED = "#64748b";
|
||||
const need = (h: number, yy: number) => (yy + h > maxY ? (doc.addPage(), mTop) : yy);
|
||||
const txtH = (s: string, w: number, size: number) =>
|
||||
|
||||
@@ -13,7 +13,7 @@ export const SYSTEM_BASE = `
|
||||
# QUIEN ERES
|
||||
|
||||
Consultor senior de digitalizacion de negocios para PyMEs mexicanas. Redactas la parte
|
||||
narrativa de las propuestas de Consultoria E3 (Queretaro, Mexico). No eres vendedor: eres
|
||||
narrativa de las propuestas de Uriel Jareth Consulting. No eres vendedor: eres
|
||||
diagnosticador. Tu trabajo es explicar por que la inversion tiene sentido, nunca decidir
|
||||
cuanto cuesta.
|
||||
|
||||
@@ -24,7 +24,7 @@ porque.
|
||||
# LOS PRINCIPIOS QUE NO SE NEGOCIAN
|
||||
|
||||
P1. NO TOCAS LOS NUMEROS. No calculas, propones ni mencionas precios, totales, IVA ni
|
||||
descuentos de E3. Ni siquiera los ves. Para referirte a una partida usa su
|
||||
descuentos de Uriel Jareth Consulting. Ni siquiera los ves. Para referirte a una partida usa su
|
||||
refPartida (P01, P02...). El sistema inyecta los importes despues de ti.
|
||||
Si escribes una cifra en pesos, solo puede ser el costo del problema DEL CLIENTE:
|
||||
lo que le cuesta hoy no resolverlo. Nunca un precio nuestro.
|
||||
@@ -84,9 +84,9 @@ de verdad. Pero si no hay evidencia de alguno de los cuatro, omitelo antes que i
|
||||
ecosistema, disruptivo, robusto, potenciar, empoderar, solucion integral.
|
||||
3. El CRM se llama Bucefalo. No menciones ningun otro CRM, por ningun motivo, aunque el
|
||||
cliente haya nombrado uno en la reunion.
|
||||
4. E3 ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing
|
||||
4. Uriel Jareth Consulting ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing
|
||||
tradicional, impresos o diseno para imprenta, va a exclusiones aclarando que no es un
|
||||
servicio de E3.
|
||||
servicio de Uriel Jareth Consulting.
|
||||
5. Moneda MXN, IVA 16%, facturacion CFDI. Jamas montos en dolares ni en USD.
|
||||
6. No prometas resultados garantizados de mercado: ni ventas, ni posicion numero uno en
|
||||
Google, ni cantidad de prospectos. Prometes entregables, procesos y metricas de
|
||||
@@ -199,7 +199,7 @@ Reglas de este paso:
|
||||
No inventes factores de relleno para llenar el hueco: un array vacio dice la verdad,
|
||||
"herramienta_actual=0 x canal=1" no dice nada.
|
||||
- Recuerda P1: montoAnualMXN es lo que el problema le cuesta AL CLIENTE cada ano. No es
|
||||
un precio de E3 ni tiene relacion con lo que cotizamos.
|
||||
un precio de Uriel Jareth Consulting ni tiene relacion con lo que cotizamos.
|
||||
- Los resultados a lograr son de negocio y medibles. "Mejorar la presencia digital" no es
|
||||
un resultado; "ningun mensaje sin respuesta en mas de 24 horas" si lo es.`;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { z } from "zod";
|
||||
* Contrato con el modelo. MiniMax no soporta structured outputs, asi que estos
|
||||
* schemas viajan como `input_schema` de una herramienta y Zod valida la respuesta.
|
||||
*
|
||||
* REGLA ESTRUCTURAL: ningun schema de aqui contiene un campo de dinero DE E3.
|
||||
* REGLA ESTRUCTURAL: ningun schema de aqui contiene un campo de dinero DE Uriel Jareth Consulting.
|
||||
* El modelo devuelve `refPartida` y prosa; los precios, totales e IVA los inyecta
|
||||
* el codigo al renderizar. `montoAnualMXN` si existe, pero es lo que el problema
|
||||
* le cuesta AL CLIENTE cada ano — no un precio nuestro.
|
||||
@@ -112,7 +112,7 @@ export const diagnosticoSchema = z
|
||||
.number()
|
||||
.nullable()
|
||||
.default(null)
|
||||
.describe("Costo ANUAL del problema DEL CLIENTE. No es un precio de E3. Omitelo si no hay cifras."),
|
||||
.describe("Costo ANUAL del problema DEL CLIENTE. No es un precio de Uriel Jareth Consulting. Omitelo si no hay cifras."),
|
||||
confianza: z.enum(CONFIANZA),
|
||||
hechos: z.array(z.string().regex(ID_HECHO)),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export const EVENTOS_WEBHOOK = [
|
||||
"cotizacion.creada",
|
||||
"cotizacion.aprobada",
|
||||
"cotizacion.enviada",
|
||||
"cotizacion.aceptada",
|
||||
"cotizacion.rechazada",
|
||||
"cotizacion.vencida",
|
||||
"pago.registrado",
|
||||
"pago.vencido",
|
||||
] as const;
|
||||
|
||||
export type EventoWebhook = (typeof EVENTOS_WEBHOOK)[number];
|
||||
|
||||
export function esEventoWebhookValido(ev: string): boolean {
|
||||
return ev === "*" || (EVENTOS_WEBHOOK as readonly string[]).includes(ev);
|
||||
}
|
||||
|
||||
export function firmarPayload(payloadStr: string, secret: string): string {
|
||||
const digest = createHmac("sha256", secret).update(payloadStr, "utf8").digest("hex");
|
||||
return `sha256=${digest}`;
|
||||
}
|
||||
|
||||
export function verificarFirma(
|
||||
payloadStr: string,
|
||||
secret: string,
|
||||
signatureHeader: string
|
||||
): boolean {
|
||||
if (!secret || !signatureHeader || !signatureHeader.startsWith("sha256=")) {
|
||||
return false;
|
||||
}
|
||||
const expected = firmarPayload(payloadStr, secret);
|
||||
const a = Buffer.from(expected, "utf8");
|
||||
const b = Buffer.from(signatureHeader, "utf8");
|
||||
if (a.length !== b.length) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
EVENTOS_WEBHOOK,
|
||||
esEventoWebhookValido,
|
||||
firmarPayload,
|
||||
verificarFirma,
|
||||
type EventoWebhook,
|
||||
} from "@/lib/webhooks-core";
|
||||
|
||||
export {
|
||||
EVENTOS_WEBHOOK,
|
||||
esEventoWebhookValido,
|
||||
firmarPayload,
|
||||
verificarFirma,
|
||||
type EventoWebhook,
|
||||
};
|
||||
|
||||
interface DestinoWebhook {
|
||||
endpointId: string | null;
|
||||
nombre: string;
|
||||
url: string;
|
||||
secret: string;
|
||||
}
|
||||
|
||||
function esperar(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function enviarConReintentos(
|
||||
destino: DestinoWebhook,
|
||||
evento: EventoWebhook,
|
||||
deliveryId: string,
|
||||
timestamp: string,
|
||||
payloadStr: string
|
||||
): Promise<{ statusCode: number | null; exito: boolean; intentos: number; error: string | null }> {
|
||||
const maxIntentos = 3; // 1 intento inicial + hasta 2 reintentos
|
||||
const firma = firmarPayload(payloadStr, destino.secret);
|
||||
|
||||
let lastStatus: number | null = null;
|
||||
let lastError: string | null = null;
|
||||
|
||||
for (let intento = 1; intento <= maxIntentos; intento++) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 8000);
|
||||
try {
|
||||
const res = await fetch(destino.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Cotizador-Event": evento,
|
||||
"X-Cotizador-Timestamp": timestamp,
|
||||
"X-Cotizador-Delivery-Id": deliveryId,
|
||||
"X-Cotizador-Signature": firma,
|
||||
},
|
||||
body: payloadStr,
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
lastStatus = res.status;
|
||||
|
||||
if (res.ok) {
|
||||
return { statusCode: res.status, exito: true, intentos: intento, error: null };
|
||||
}
|
||||
|
||||
lastError = `HTTP ${res.status}`;
|
||||
// Solo reintentar ante 5xx
|
||||
if (res.status < 500 || intento === maxIntentos) {
|
||||
return { statusCode: res.status, exito: false, intentos: intento, error: lastError };
|
||||
}
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
lastError = err instanceof Error ? err.message : String(err);
|
||||
if (intento === maxIntentos) {
|
||||
return { statusCode: lastStatus, exito: false, intentos: intento, error: lastError };
|
||||
}
|
||||
}
|
||||
await esperar(500 * intento);
|
||||
}
|
||||
|
||||
return { statusCode: lastStatus, exito: false, intentos: maxIntentos, error: lastError };
|
||||
}
|
||||
|
||||
export async function emitirWebhook(
|
||||
evento: EventoWebhook,
|
||||
data: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
try {
|
||||
const endpoints = await prisma.webhookEndpoint.findMany({
|
||||
where: { activo: true },
|
||||
});
|
||||
|
||||
const destinos: DestinoWebhook[] = endpoints
|
||||
.filter((ep) => ep.eventos.includes("*") || ep.eventos.includes(evento))
|
||||
.map((ep) => ({
|
||||
endpointId: ep.id,
|
||||
nombre: ep.nombre,
|
||||
url: ep.url,
|
||||
secret: ep.secret,
|
||||
}));
|
||||
|
||||
const envUrl = process.env.WEBHOOK_N8N_URL?.trim();
|
||||
const envSecret = process.env.WEBHOOK_N8N_SECRET?.trim();
|
||||
if (envUrl && envSecret && !destinos.some((d) => d.url === envUrl)) {
|
||||
destinos.push({
|
||||
endpointId: null,
|
||||
nombre: "env-n8n",
|
||||
url: envUrl,
|
||||
secret: envSecret,
|
||||
});
|
||||
}
|
||||
|
||||
if (destinos.length === 0) return;
|
||||
|
||||
const timestampIso = new Date().toISOString();
|
||||
const timestampUnix = String(Math.floor(Date.now() / 1000));
|
||||
|
||||
await Promise.all(
|
||||
destinos.map(async (destino) => {
|
||||
const deliveryId = randomUUID();
|
||||
const envelope = {
|
||||
id: deliveryId,
|
||||
event: evento,
|
||||
timestamp: timestampIso,
|
||||
data,
|
||||
};
|
||||
const payloadStr = JSON.stringify(envelope);
|
||||
|
||||
const res = await enviarConReintentos(destino, evento, deliveryId, timestampUnix, payloadStr);
|
||||
|
||||
await prisma.webhookDelivery
|
||||
.create({
|
||||
data: {
|
||||
endpointId: destino.endpointId,
|
||||
url: destino.url,
|
||||
evento,
|
||||
payload: envelope as Prisma.InputJsonValue,
|
||||
statusCode: res.statusCode,
|
||||
exito: res.exito,
|
||||
intentos: res.intentos,
|
||||
error: res.error,
|
||||
},
|
||||
})
|
||||
.catch((e) => console.error("[webhooks] error guardando WebhookDelivery:", e));
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[webhooks] error emitiendo", evento, err);
|
||||
}
|
||||
}
|
||||
|
||||
export interface WhatsAppN8nPayload {
|
||||
cotizacionId: string;
|
||||
numero: string;
|
||||
folio?: string;
|
||||
estado?: string;
|
||||
aprobadaAt?: string | null;
|
||||
cliente: {
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
telefono: string | null;
|
||||
email: string | null;
|
||||
};
|
||||
destino: string;
|
||||
chatwootConversationId?: number | string | null;
|
||||
mensaje: string;
|
||||
pdfFilename: string;
|
||||
pdfBase64: string;
|
||||
pdfUrl: string;
|
||||
}
|
||||
|
||||
export interface WhatsAppN8nResponse {
|
||||
ok: boolean;
|
||||
delivered: boolean;
|
||||
reason?: string;
|
||||
statusCode?: number;
|
||||
error?: string;
|
||||
raw?: unknown;
|
||||
}
|
||||
|
||||
export async function invocarEnvioWhatsAppN8n(
|
||||
payload: WhatsAppN8nPayload
|
||||
): Promise<WhatsAppN8nResponse> {
|
||||
const url = process.env.WEBHOOK_WHATSAPP_SEND_URL?.trim();
|
||||
const secret = process.env.WEBHOOK_N8N_SECRET?.trim();
|
||||
if (!url || !secret) {
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: "not_configured",
|
||||
error: "WEBHOOK_WHATSAPP_SEND_URL o WEBHOOK_N8N_SECRET no estan configurados",
|
||||
};
|
||||
}
|
||||
|
||||
const deliveryId = randomUUID();
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
const payloadStr = JSON.stringify(payload);
|
||||
const firma = firmarPayload(payloadStr, secret);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 15_000);
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Cotizador-Event": "cotizacion.enviar_whatsapp",
|
||||
"X-Cotizador-Timestamp": timestamp,
|
||||
"X-Cotizador-Delivery-Id": deliveryId,
|
||||
"X-Cotizador-Signature": firma,
|
||||
},
|
||||
body: payloadStr,
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
statusCode: res.status,
|
||||
reason: typeof data?.reason === "string" ? data.reason : `http_${res.status}`,
|
||||
error: typeof data?.error === "string" ? data.error : `Error HTTP ${res.status} en n8n`,
|
||||
raw: data,
|
||||
};
|
||||
}
|
||||
|
||||
const delivered = data && typeof data.delivered === "boolean" ? data.delivered : true;
|
||||
const reason = typeof data?.reason === "string" ? data.reason : undefined;
|
||||
return {
|
||||
ok: delivered,
|
||||
delivered,
|
||||
reason,
|
||||
statusCode: res.status,
|
||||
error: delivered ? undefined : (typeof data?.error === "string" ? data.error : reason),
|
||||
raw: data,
|
||||
};
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: "network_error",
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user