UNPKG

@dueheads/citi-bank-boleto-sdk

Version:

SDK para registro de boletos na API do Citibank via mTLS.

133 lines (132 loc) 5.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CitiBankBoletoSDK = void 0; const api_request_1 = require("./api.request"); const xml_builder_1 = require("./xml.builder"); const response_handler_1 = require("./response.handler"); const data_interpreter_1 = require("./data.interpreter"); class CitiBankBoletoSDK { constructor(config) { this.hooks = {}; this.boletoBuilder = {}; this.config = config; this.request = new api_request_1.ApiRequest(config); this.xmlBuilder = new xml_builder_1.XMLBuilder(); this.responseHandler = new response_handler_1.ResponseHandler(); this.dataInterpreter = new data_interpreter_1.DataInterpreter(); } log(message, data) { if (this.config.debug) { const timestamp = new Date().toISOString(); console.log(`[CitiBankSDK - ${timestamp}]: ${message}`, data !== undefined ? data : ''); } } onSuccess(callback) { this.hooks.onSuccess = callback; return this; } onError(callback) { this.hooks.onError = callback; return this; } onFail(callback) { this.hooks.onFail = callback; return this; } clearHooks() { this.hooks = {}; } clearBuilder() { this.boletoBuilder = {}; } // --- MÉTODOS DO BUILDER --- setBeneficiario(beneficiario) { this.boletoBuilder.dadosBeneficiario = beneficiario; return this; } setPagador(pagador) { // CORREÇÃO: Inicializa 'dados' se for nulo, sem usar 'as any'. if (!this.boletoBuilder.dados) { this.boletoBuilder.dados = {}; } this.boletoBuilder.dados.pagador = pagador; return this; } setSacador(sacador) { // CORREÇÃO: Inicializa 'dados' se for nulo, sem usar 'as any'. if (!this.boletoBuilder.dados) { this.boletoBuilder.dados = {}; } this.boletoBuilder.dados.sacador = sacador; return this; } setDocumento(documento) { // CORREÇÃO: Inicializa 'dados' se for nulo, sem usar 'as any'. if (!this.boletoBuilder.dados) { this.boletoBuilder.dados = {}; } this.boletoBuilder.dados.documento = documento; return this; } async registraBoleto() { this.log("Iniciando registro de boleto a partir do builder."); const { dadosBeneficiario, dados } = this.boletoBuilder; // A validação continua a mesma, garantindo que todos os dados foram fornecidos. if (!dadosBeneficiario || !dados?.pagador || !dados?.documento || dados.sacador === undefined) { const error = new Error("Dados incompletos. É necessário chamar setBeneficiario(), setPagador(), setDocumento() e setSacador() antes de usar send()."); this.log("Erro de validação do builder.", error.message); this.hooks.onFail?.(error); this.clearBuilder(); this.clearHooks(); return { httpStatus: 400, faultCode: 'SDKValidationError', faultString: error.message, }; } const payload = this.boletoBuilder; this.clearBuilder(); return this.executeRegistration(payload); } async registraBoletoWithPayload(inputData) { this.log("Iniciando processo de registro de boleto com payload direto.", inputData); return this.executeRegistration(inputData); } async executeRegistration(payload) { this.log("Executando registro do boleto.", payload); try { const boletoDataFinal = this.dataInterpreter.toSdkFormat(payload); const xmlPayload = this.xmlBuilder.build(boletoDataFinal); this.log("XML de remessa gerado.", xmlPayload); const apiResponseXml = await this.request.post(xmlPayload); this.log("Resposta XML recebida da API.", apiResponseXml); const structuredResponse = this.responseHandler.parse(apiResponseXml); this.log("Resposta da API processada.", structuredResponse); if ('barcode' in structuredResponse) { this.hooks.onSuccess?.(structuredResponse); } else if ('errors' in structuredResponse) { this.hooks.onError?.(structuredResponse); } else { this.hooks.onFail?.(structuredResponse); } return structuredResponse; } catch (error) { const catchedError = error instanceof Error ? error : new Error('Erro desconhecido'); this.log("Ocorreu uma exceção fatal.", catchedError); this.hooks.onFail?.(catchedError); return { httpStatus: 500, faultCode: 'SDKException', faultString: catchedError.message, }; } finally { this.log("Finalizando processo e limpando hooks."); this.clearHooks(); } } } exports.CitiBankBoletoSDK = CitiBankBoletoSDK;