feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC

This commit is contained in:
urieljareth
2026-11-25 00:55:18 -06:00
parent 75180b0fe4
commit 0d4f19f35d
111 changed files with 7167 additions and 1272 deletions
@@ -0,0 +1,139 @@
-- AlterTable: campos opcionales de aprobacion, envio, cierre y autoria de agente en Cotizacion
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaPorId" TEXT;
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaAt" TIMESTAMP(3);
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobacionMetodo" TEXT;
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaAt" TIMESTAMP(3);
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaPor" TEXT;
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaCanal" TEXT;
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaDestino" TEXT;
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aceptadaAt" TIMESTAMP(3);
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "rechazadaAt" TIMESTAMP(3);
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "vencidaAt" TIMESTAMP(3);
ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "creadaPorAgente" TEXT;
-- CreateTable: AgentApiKey
CREATE TABLE IF NOT EXISTS "AgentApiKey" (
"id" TEXT NOT NULL,
"nombre" TEXT NOT NULL,
"prefijo" TEXT NOT NULL,
"keyHash" TEXT NOT NULL,
"scopes" TEXT[],
"rateLimitPerMin" INTEGER NOT NULL DEFAULT 60,
"activo" BOOLEAN NOT NULL DEFAULT true,
"revokedAt" TIMESTAMP(3),
"lastUsedAt" TIMESTAMP(3),
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id")
);
-- CreateTable: AuditLog
CREATE TABLE IF NOT EXISTS "AuditLog" (
"id" TEXT NOT NULL,
"actorTipo" TEXT NOT NULL,
"actorId" TEXT,
"actorNombre" TEXT NOT NULL,
"accion" TEXT NOT NULL,
"recursoTipo" TEXT NOT NULL,
"recursoId" TEXT,
"ip" TEXT,
"requestId" TEXT,
"exito" BOOLEAN NOT NULL DEFAULT true,
"detalle" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable: ApprovalToken
CREATE TABLE IF NOT EXISTS "ApprovalToken" (
"id" TEXT NOT NULL,
"cotizacionId" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"expiraAt" TIMESTAMP(3) NOT NULL,
"usadoAt" TIMESTAMP(3),
"usadoIp" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ApprovalToken_pkey" PRIMARY KEY ("id")
);
-- CreateTable: IdempotencyKey
CREATE TABLE IF NOT EXISTS "IdempotencyKey" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"method" TEXT NOT NULL,
"path" TEXT NOT NULL,
"requestHash" TEXT NOT NULL,
"statusCode" INTEGER NOT NULL,
"responseBody" JSONB NOT NULL,
"expiraAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id")
);
-- CreateTable: WebhookEndpoint
CREATE TABLE IF NOT EXISTS "WebhookEndpoint" (
"id" TEXT NOT NULL,
"nombre" TEXT NOT NULL,
"url" TEXT NOT NULL,
"secret" TEXT NOT NULL,
"eventos" TEXT[],
"activo" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id")
);
-- CreateTable: WebhookDelivery
CREATE TABLE IF NOT EXISTS "WebhookDelivery" (
"id" TEXT NOT NULL,
"endpointId" TEXT,
"url" TEXT NOT NULL,
"evento" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"statusCode" INTEGER,
"exito" BOOLEAN NOT NULL DEFAULT false,
"intentos" INTEGER NOT NULL DEFAULT 1,
"error" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_nombre_key" ON "AgentApiKey"("nombre");
CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_keyHash_key" ON "AgentApiKey"("keyHash");
CREATE INDEX IF NOT EXISTS "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
CREATE INDEX IF NOT EXISTS "AuditLog_accion_idx" ON "AuditLog"("accion");
CREATE INDEX IF NOT EXISTS "AuditLog_recursoTipo_recursoId_idx" ON "AuditLog"("recursoTipo", "recursoId");
CREATE INDEX IF NOT EXISTS "AuditLog_actorNombre_idx" ON "AuditLog"("actorNombre");
CREATE UNIQUE INDEX IF NOT EXISTS "ApprovalToken_tokenHash_key" ON "ApprovalToken"("tokenHash");
CREATE INDEX IF NOT EXISTS "ApprovalToken_cotizacionId_idx" ON "ApprovalToken"("cotizacionId");
CREATE UNIQUE INDEX IF NOT EXISTS "IdempotencyKey_key_key" ON "IdempotencyKey"("key");
CREATE INDEX IF NOT EXISTS "IdempotencyKey_expiraAt_idx" ON "IdempotencyKey"("expiraAt");
CREATE UNIQUE INDEX IF NOT EXISTS "WebhookEndpoint_nombre_key" ON "WebhookEndpoint"("nombre");
CREATE INDEX IF NOT EXISTS "WebhookDelivery_evento_idx" ON "WebhookDelivery"("evento");
CREATE INDEX IF NOT EXISTS "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt");
-- AddForeignKey (idempotent)
DO $$ BEGIN
ALTER TABLE "ApprovalToken" ADD CONSTRAINT "ApprovalToken_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
DO $$ BEGIN
ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE SET NULL ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
+110
View File
@@ -68,6 +68,17 @@ model Cotizacion {
observacionesInternas String?
clienteId String
asesorId String
aprobadaPorId String?
aprobadaAt DateTime?
aprobacionMetodo String?
enviadaAt DateTime?
enviadaPor String?
enviadaCanal String?
enviadaDestino String?
aceptadaAt DateTime?
rechazadaAt DateTime?
vencidaAt DateTime?
creadaPorAgente String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -78,6 +89,7 @@ model Cotizacion {
registrosHoras RegistroHoras[]
propuestasIA PropuestaIA[]
programasPago ProgramaPago[]
approvalTokens ApprovalToken[]
@@index([clienteId])
@@index([asesorId])
@@ -380,3 +392,101 @@ model SuscripcionPush {
@@index([userId])
}
// ============================================================================
// API para Agentes, Auditoria, Aprobacion, Idempotencia y Webhooks
// ============================================================================
model AgentApiKey {
id String @id @default(cuid())
nombre String @unique
prefijo String
keyHash String @unique
scopes String[]
rateLimitPerMin Int @default(60)
activo Boolean @default(true)
revokedAt DateTime?
lastUsedAt DateTime?
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model AuditLog {
id String @id @default(cuid())
actorTipo String
actorId String?
actorNombre String
accion String
recursoTipo String
recursoId String?
ip String?
requestId String?
exito Boolean @default(true)
detalle Json?
createdAt DateTime @default(now())
@@index([createdAt])
@@index([accion])
@@index([recursoTipo, recursoId])
@@index([actorNombre])
}
model ApprovalToken {
id String @id @default(cuid())
cotizacionId String
tokenHash String @unique
expiraAt DateTime
usadoAt DateTime?
usadoIp String?
createdAt DateTime @default(now())
cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade)
@@index([cotizacionId])
}
model IdempotencyKey {
id String @id @default(cuid())
key String @unique
method String
path String
requestHash String
statusCode Int
responseBody Json
expiraAt DateTime
createdAt DateTime @default(now())
@@index([expiraAt])
}
model WebhookEndpoint {
id String @id @default(cuid())
nombre String @unique
url String
secret String
eventos String[]
activo Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
entregas WebhookDelivery[]
}
model WebhookDelivery {
id String @id @default(cuid())
endpointId String?
url String
evento String
payload Json
statusCode Int?
exito Boolean @default(false)
intentos Int @default(1)
error String?
createdAt DateTime @default(now())
endpoint WebhookEndpoint? @relation(fields: [endpointId], references: [id], onDelete: SetNull)
@@index([evento])
@@index([createdAt])
}
+8 -7
View File
@@ -7,6 +7,7 @@ const adapter = new PrismaPg({
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",
});
const prisma = new PrismaClient({ adapter });
@@ -16,7 +17,7 @@ async function main() {
// Credentials come from env. Without SEED_*_PASSWORD the user is created
// with a default password only if it doesn't exist yet (never overwritten).
const adminEmail = process.env.SEED_ADMIN_EMAIL || "admin@e3.local";
const adminEmail = process.env.SEED_ADMIN_EMAIL || "admin@urieljareth.com";
const adminPassword = process.env.SEED_ADMIN_PASSWORD;
if (!adminPassword) {
console.warn(
@@ -567,7 +568,7 @@ async function main() {
},
{
nombre: "Plan de Acompanamiento Integral",
descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando E3, 3 operando en conjunto y 3 meses operando en acompanamiento)",
descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando Uriel Jareth Consulting, 3 operando en conjunto y 3 meses operando en acompanamiento)",
fase: 0,
tipoPago: "mensual",
precioBase: 9000,
@@ -585,7 +586,7 @@ async function main() {
},
// ──────────────────────────────────────────────────────────────
// SERVICIOS NIVELADOS (Catalogo E3 - Cotizacion Final)
// SERVICIOS NIVELADOS (Catalogo Uriel Jareth Consulting - Cotizacion Final)
// Precios convertidos de USD a MXN al tipo de cambio 17.30
// Niveles: Emprendedor / PYME / Empresario / Corporativo
// ──────────────────────────────────────────────────────────────
@@ -1966,7 +1967,7 @@ async function main() {
},
{
clave: "domicilio_fiscal",
valor: "EMILIANO ZAPATA S/N, CUAMIO, CUITZEO, MICHOACAN DE OCAMPO CP 58855",
valor: "",
},
{
clave: "cuenta_nacional",
@@ -2002,7 +2003,7 @@ async function main() {
},
{
clave: "no_incluye",
valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por E3 y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional).",
valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por Uriel Jareth Consulting y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional).",
},
{
clave: "notas_adicionales",
@@ -2010,11 +2011,11 @@ async function main() {
},
{
clave: "color_primario",
valor: "#2563eb",
valor: "#0400C4",
},
{
clave: "color_secundario",
valor: "#1e293b",
valor: "#0F172A",
},
{
clave: "logo_base64",