UNPKG

nodefact

Version:

Biblioteca para facturación electrónica en Perú con Node.js. Compatible con UBL 2.1 y servicios web de SUNAT.

193 lines (192 loc) 7.1 kB
"use strict"; /** * Módulo SUNAT - Comunicación con los servicios web de SUNAT * * Este módulo proporciona funcionalidades para la comunicación con los servicios web * de SUNAT para el envío de documentos electrónicos. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.SunatClient = exports.SunatEndpoints = exports.SunatError = void 0; exports.createSunatClient = createSunatClient; const soap = __importStar(require("soap")); const core_1 = require("../core"); /** * Clase para errores de comunicación con SUNAT */ class SunatError extends core_1.NodeFactError { constructor(message) { super(message); this.name = 'SunatError'; } } exports.SunatError = SunatError; /** * Endpoints de los servicios web de SUNAT */ var SunatEndpoints; (function (SunatEndpoints) { SunatEndpoints["PRODUCCION_FACTURA"] = "https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService"; SunatEndpoints["PRODUCCION_GUIA"] = "https://e-guiaremision.sunat.gob.pe/ol-ti-itemision-guia-gem/billService"; SunatEndpoints["PRODUCCION_RETENCION"] = "https://e-factura.sunat.gob.pe/ol-ti-itemision-otroscpe-gem/billService"; SunatEndpoints["BETA_FACTURA"] = "https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService"; SunatEndpoints["BETA_GUIA"] = "https://e-beta.sunat.gob.pe/ol-ti-itemision-guia-gem-beta/billService"; SunatEndpoints["BETA_RETENCION"] = "https://e-beta.sunat.gob.pe/ol-ti-itemision-otroscpe-gem-beta/billService"; SunatEndpoints["HOMOLOGACION_FACTURA"] = "https://e-factura.sunat.gob.pe/ol-ti-itcpfegem-sqa/billService"; SunatEndpoints["HOMOLOGACION_GUIA"] = "https://e-guiaremision.sunat.gob.pe/ol-ti-itemision-guia-gem-sqa/billService"; SunatEndpoints["HOMOLOGACION_RETENCION"] = "https://e-factura.sunat.gob.pe/ol-ti-itemision-otroscpe-gem-sqa/billService"; })(SunatEndpoints || (exports.SunatEndpoints = SunatEndpoints = {})); /** * Cliente para la comunicación con los servicios web de SUNAT */ class SunatClient { constructor(options) { this.client = null; this.options = { ...options, timeout: options.timeout || 30000, }; } /** * Inicializa el cliente SOAP */ async initClient() { if (this.client) { return this.client; } try { this.client = await soap.createClientAsync(this.options.endpoint, { endpoint: this.options.endpoint, timeout: this.options.timeout, }); // Configurar autenticación // El formato de autenticación para SUNAT es: RUC + Usuario SOL + ":" + Clave SOL // Ejemplo: 20123456789MODDATOS:moddatos const auth = `${this.options.credentials.ruc}${this.options.credentials.usuario}:${this.options.credentials.clave}`; const authBase64 = Buffer.from(auth).toString('base64'); this.client.addHttpHeader('Authorization', `Basic ${authBase64}`); return this.client; } catch (err) { const error = err; throw new SunatError(`Error al inicializar el cliente SOAP: ${error.message}`); } } /** * Envía un documento a SUNAT * @param fileName Nombre del archivo ZIP * @param contentBase64 Contenido del archivo ZIP en base64 * @returns Resultado de la operación */ async sendBill(fileName, contentBase64) { try { const client = await this.initClient(); const result = await client.sendBillAsync({ fileName, contentFile: contentBase64, }); return { success: true, cdr: result[0].applicationResponse, }; } catch (err) { const error = err; return { success: false, error: `Error al enviar documento: ${error.message}`, }; } } /** * Envía un resumen diario o comunicación de baja a SUNAT * @param fileName Nombre del archivo ZIP * @param contentBase64 Contenido del archivo ZIP en base64 * @returns Resultado de la operación */ async sendSummary(fileName, contentBase64) { try { const client = await this.initClient(); const result = await client.sendSummaryAsync({ fileName, contentFile: contentBase64, }); return { success: true, ticket: result[0].ticket, }; } catch (err) { const error = err; return { success: false, error: `Error al enviar resumen: ${error.message}`, }; } } /** * Consulta el estado de un ticket * @param ticket Número de ticket * @returns Resultado de la operación */ async getStatus(ticket) { try { const client = await this.initClient(); const result = await client.getStatusAsync({ ticket, }); return { success: true, cdr: result[0].status.content, }; } catch (err) { const error = err; return { success: false, error: `Error al consultar ticket: ${error.message}`, }; } } } exports.SunatClient = SunatClient; /** * Crea un cliente para la comunicación con los servicios web de SUNAT * @param options Opciones para el cliente * @returns Cliente SUNAT */ function createSunatClient(options) { return new SunatClient(options); }