// Emite una factura con la API de FacturacionDPY (Node 18+, sin dependencias). import { randomUUID } from 'node:crypto'; import { writeFile } from 'node:fs/promises'; const API = (process.env.DPYF_API_URL ?? 'https://facturacion.desarrollospy.de/api/v1').replace(/\/+$/, ''); const CLAVE = process.env.DPYF_API_KEY; const SIMULAR = process.env.DPYF_SIMULAR; if (!CLAVE) throw new Error('Falta DPYF_API_KEY'); const pedido = { tipo: 'factura', external_id: `ejemplo-javascript-${randomUUID().slice(0, 8)}`, // SOP-1 es tu código interno: como no está en el catálogo, el ítem lleva descripción y precio. items: [{ codigo: 'SOP-1', descripcion: 'Servicio de soporte mensual', cantidad: 1, precio: 10000, iva: 10 }], }; async function llamar(metodo, ruta, cuerpo, encabezados = {}) { const respuesta = await fetch(API + ruta, { method: metodo, headers: { Authorization: `Bearer ${CLAVE}`, ...(cuerpo ? { 'Content-Type': 'application/json' } : {}), ...encabezados }, body: cuerpo ? JSON.stringify(cuerpo) : undefined, }); return respuesta; } async function problema(respuesta) { const p = await respuesta.json(); return `${p.code}: ${p.mensaje}${p.campo ? ` (campo ${p.campo})` : ''}${p.como_resolver ? ` -> ${p.como_resolver}` : ''}`; } const esperar = ms => new Promise(r => setTimeout(r, ms)); let respuesta = await llamar('POST', '/documentos/validar', pedido); if (respuesta.status !== 200) throw new Error('El pedido no es válido: ' + (await problema(respuesta))); console.log('Validación previa: OK, total', (await respuesta.json()).total); const claveIdempotencia = randomUUID(); // guardala junto al pedido: se reusa en cada reintento const encabezados = { 'Idempotency-Key': claveIdempotencia, ...(SIMULAR ? { 'DPYF-Simular': SIMULAR } : {}) }; respuesta = await llamar('POST', '/documentos?esperar=8s', pedido, encabezados); if (respuesta.status !== 200 && respuesta.status !== 202) { throw new Error(`No se emitió (${respuesta.status}): ` + (await problema(respuesta))); } let documento = await respuesta.json(); console.log(`Factura ${documento.numero} CDC ${documento.cdc}: ${documento.estado}`); // Seguir el estado hasta la respuesta del SIFEN (mejor: webhook documento.aprobado / documento.rechazado). const limite = Date.now() + 15 * 60_000; while (['en_proceso', 'firmado', 'enviado'].includes(documento.estado) && Date.now() < limite) { await esperar(15_000); respuesta = await llamar('GET', `/documentos/${documento.cdc}`); if (respuesta.ok) { documento = await respuesta.json(); console.log(' estado:', documento.estado); } } const sifen = documento.sifen ?? {}; console.log('Resultado:', documento.estado, sifen.codigo ?? '', sifen.mensaje ?? ''); if (documento.estado === 'aprobado') { respuesta = await llamar('GET', `/documentos/${documento.cdc}/kude.pdf?formato=a4`); if (respuesta.ok) { const nombre = `kude-${documento.cdc}.pdf`; await writeFile(nombre, Buffer.from(await respuesta.arrayBuffer())); console.log('KuDE guardado en', nombre); } }