122 lines
3.5 KiB
TypeScript
122 lines
3.5 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/db";
|
|
import { applyHeaders, requireActor } from "@/lib/agent-auth";
|
|
import { registrarAuditoria } from "@/lib/audit";
|
|
import { emitirWebhook } from "@/lib/webhooks";
|
|
import { calcularTotalesCotizacion } from "@/lib/calculators";
|
|
import { appBaseUrl } from "@/lib/aprobacion";
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await params;
|
|
const auth = await requireActor(request, {
|
|
adminOnly: true,
|
|
accionBloqueo: "cotizacion.aprobar_bloqueado",
|
|
recursoTipo: "cotizacion",
|
|
recursoId: id,
|
|
});
|
|
if (!auth.ok) return auth.response;
|
|
|
|
const { actor, rateLimitHeaders } = auth;
|
|
if (actor.type !== "user" || actor.role !== "admin") {
|
|
return NextResponse.json({ error: "Solo un administrador humano puede aprobar" }, { status: 403 });
|
|
}
|
|
|
|
const cot = await prisma.cotizacion.findUnique({
|
|
where: { id },
|
|
include: { cliente: true, servicios: true },
|
|
});
|
|
if (!cot) {
|
|
return applyHeaders(
|
|
NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 }),
|
|
rateLimitHeaders
|
|
);
|
|
}
|
|
|
|
if (cot.estado !== "borrador") {
|
|
return applyHeaders(
|
|
NextResponse.json(
|
|
{ error: `Solo se pueden aprobar cotizaciones en borrador (estado actual: ${cot.estado})` },
|
|
{ status: 409 }
|
|
),
|
|
rateLimitHeaders
|
|
);
|
|
}
|
|
|
|
const now = new Date();
|
|
const updated = await prisma.$transaction(async (tx) => {
|
|
await tx.approvalToken.updateMany({
|
|
where: { cotizacionId: id, usadoAt: null },
|
|
data: { expiraAt: now },
|
|
});
|
|
|
|
return tx.cotizacion.update({
|
|
where: { id },
|
|
data: {
|
|
estado: "aprobada",
|
|
aprobadaPorId: actor.userId,
|
|
aprobadaAt: now,
|
|
aprobacionMetodo: "web_admin",
|
|
},
|
|
include: { cliente: true },
|
|
});
|
|
});
|
|
|
|
await registrarAuditoria({
|
|
actor,
|
|
accion: "cotizacion.aprobar",
|
|
recursoTipo: "cotizacion",
|
|
recursoId: id,
|
|
request,
|
|
exito: true,
|
|
detalle: {
|
|
numero: updated.numero,
|
|
metodo: "web_admin",
|
|
},
|
|
});
|
|
|
|
const tot = calcularTotalesCotizacion(cot.servicios, { incluirIva: cot.incluirIva });
|
|
const totalWebhook = Number((tot.totalUnico + tot.totalMensual).toFixed(2));
|
|
|
|
void emitirWebhook("cotizacion.aprobada", {
|
|
cotizacionId: updated.id,
|
|
numero: updated.numero,
|
|
folio: updated.numero,
|
|
titulo: updated.proyecto,
|
|
proyecto: updated.proyecto,
|
|
moneda: updated.moneda,
|
|
total: totalWebhook,
|
|
url: `${appBaseUrl()}/cotizaciones/${updated.id}`,
|
|
estado: "aprobada",
|
|
aprobadaAt: now.toISOString(),
|
|
aprobadaPorId: actor.userId,
|
|
aprobacionMetodo: "web_admin",
|
|
cliente: {
|
|
id: updated.cliente.id,
|
|
nombre: updated.cliente.nombre,
|
|
empresa: updated.cliente.empresa,
|
|
email: updated.cliente.email,
|
|
telefono: updated.cliente.telefono,
|
|
},
|
|
});
|
|
|
|
return applyHeaders(
|
|
NextResponse.json({
|
|
ok: true,
|
|
id: updated.id,
|
|
numero: updated.numero,
|
|
estado: updated.estado,
|
|
aprobadaAt: updated.aprobadaAt,
|
|
aprobacionMetodo: updated.aprobacionMetodo,
|
|
}),
|
|
rateLimitHeaders
|
|
);
|
|
} catch (error: unknown) {
|
|
const msg = error instanceof Error ? error.message : "Error interno";
|
|
return NextResponse.json({ error: msg }, { status: 500 });
|
|
}
|
|
}
|