export async function emitirDocumentoPorOrden(orden: {
id: string;
requiereFactura: boolean;
receptor?: { rut: string; razonSocial: string; giro: string; direccion: string; comuna: string; email?: string };
items: Array<{ nombre: string; cantidad: number; precioBruto: number; sku?: string }>;
despacho: number;
}) {
const payload = {
tipo_dte: orden.requiereFactura ? 33 : 39,
referencia_externa: orden.id,
precios_incluyen_iva: true,
...(orden.requiereFactura && orden.receptor
? {
receptor: {
rut: orden.receptor.rut,
razon_social: orden.receptor.razonSocial,
giro: orden.receptor.giro,
direccion: orden.receptor.direccion,
comuna: orden.receptor.comuna,
email: orden.receptor.email,
},
}
: {}),
items: orden.items.map((i) => ({
nombre: i.nombre.slice(0, 80),
cantidad: i.cantidad,
precio_unitario: i.precioBruto,
sku: i.sku,
})),
despacho: orden.despacho,
};
const res = await fetch("https://api.ia-erp.cl/v1/dte", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.IA_ERP_API_KEY}`,
"Idempotency-Key": `ORD-${orden.id}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(45_000),
});
if (res.status === 201 || res.status === 200) {
return res.json();
}
const problem = await res.json();
throw new Error(`Error IA ERP [${problem.code}]: ${problem.detail} (req=${problem.instance})`);
}