@teaploy/megaprint
Version:
Megaprint npm integration
207 lines (206 loc) • 8.89 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
};
var _signedXML, _xmlBuilder;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Invoice = void 0;
/* eslint-disable no-console */
const lodash_1 = require("lodash");
const xml2js_1 = require("xml2js");
const utils_1 = require("../utils");
const moment = require("moment");
class Invoice {
constructor(localIdentifier, receptor, currencyCode, items, configuration) {
this.identifier = '';
this.total = 0;
this.pdfBase64 = '';
_signedXML.set(this, '');
_xmlBuilder.set(this, new xml2js_1.Builder({ headless: true, cdata: true }));
this.localIdentifier = localIdentifier.toUpperCase();
this.receptor = receptor;
this.currencyCode = currencyCode;
this.items = items;
this.configuration = configuration;
if (!configuration) {
throw new Error('Invalid configuration');
}
let taxes = [];
items.forEach((item) => {
taxes = [...taxes, ...item.getTaxes()];
this.total += item.total;
});
this.taxesSummary = lodash_1.chain(taxes)
.groupBy('tax')
.map((item, key) => ({
name: key,
total: lodash_1.sumBy(item, 'total'),
}))
.value();
}
toXML() {
const xmlBuilder = new xml2js_1.Builder({ headless: true, cdata: true });
return xmlBuilder.buildObject(this.toDte());
}
generate() {
return __awaiter(this, void 0, void 0, function* () {
yield this.init();
yield this.signXML();
yield this.registerDocument();
return this;
});
}
generatePdf() {
return __awaiter(this, void 0, void 0, function* () {
if (!this.identifier) {
throw new Error("Invoice wasn't generated");
}
this.pdfBase64 = yield Invoice.downloadPdf(this.configuration, this.identifier);
return this.pdfBase64;
});
}
static getPdf(configuration, identifier) {
return __awaiter(this, void 0, void 0, function* () {
yield configuration.init();
return Invoice.downloadPdf(configuration, identifier);
});
}
init() {
return __awaiter(this, void 0, void 0, function* () {
yield this.configuration.init();
});
}
signXML() {
return __awaiter(this, void 0, void 0, function* () {
const body = __classPrivateFieldGet(this, _xmlBuilder).buildObject({
FirmaDocumentoRequest: {
$: { id: this.localIdentifier },
xml_dte: {
_: this.toXML(),
},
},
});
const signedXml = yield utils_1.Request.post(utils_1.Actions.signXml, body, this.configuration.environment, this.configuration.apiToken);
if (signedXml.FirmaDocumentoResponse.tipo_respuesta[0] === '1') {
console.error(signedXml.FirmaDocumentoResponse.listado_errores[0].error);
throw new Error('Invalid Invoice');
}
__classPrivateFieldSet(this, _signedXML, signedXml.FirmaDocumentoResponse.xml_dte[0]);
});
}
registerDocument() {
return __awaiter(this, void 0, void 0, function* () {
const body = __classPrivateFieldGet(this, _xmlBuilder).buildObject({
RegistraDocumentoXMLRequest: {
$: { id: this.localIdentifier },
xml_dte: {
_: __classPrivateFieldGet(this, _signedXML),
},
},
});
const registeredDocument = yield utils_1.Request.post(utils_1.Actions.registerDocument, body, this.configuration.environment, this.configuration.apiToken);
if (registeredDocument.RegistraDocumentoXMLResponse.tipo_respuesta[0] === '1') {
console.error(registeredDocument.RegistraDocumentoXMLResponse.listado_errores[0]
.error);
throw new Error('Error registering Invoice');
}
this.identifier = registeredDocument.RegistraDocumentoXMLResponse.uuid[0];
});
}
static downloadPdf(configuration, identifier) {
return __awaiter(this, void 0, void 0, function* () {
const body = new xml2js_1.Builder({ headless: true, cdata: true }).buildObject({
RetornaPDFRequest: {
uuid: {
_: identifier,
},
},
});
const getPdf = yield utils_1.Request.post(utils_1.Actions.getPdf, body, configuration.environment, configuration.apiToken);
if (getPdf.RetornaPDFResponse.tipo_respuesta[0] === '1') {
console.error(getPdf.RetornaPDFResponse.listado_errores[0].error);
throw new Error('Error getting PDF');
}
return getPdf.RetornaPDFResponse.pdf[0];
});
}
toDte() {
const invoiceDate = moment().utcOffset(-360).format();
return {
'dte:GTDocumento': {
$: {
'xmlns:dte': 'http://www.sat.gob.gt/dte/fel/0.2.0',
'xmlns:xd': 'http://www.w3.org/2000/09/xmldsig#',
Version: '0.1',
},
'dte:SAT': {
$: {
ClaseDocumento: 'dte',
},
'dte:DTE': {
$: {
ID: 'DatosCertificados',
},
'dte:DatosEmision': {
$: {
ID: 'DatosEmision',
},
'dte:DatosGenerales': {
$: {
CodigoMoneda: this.currencyCode,
FechaHoraEmision: invoiceDate,
Tipo: 'FACT',
},
},
'dte:Emisor': this.configuration.emitter.toDte(),
'dte:Receptor': this.receptor.toDte(),
'dte:Frases': {
'dte:Frase': {
$: {
CodigoEscenario: 1,
TipoFrase: 1,
},
},
},
'dte:Items': {
'dte:Item': this.items.map((item, index) => item.toDte(index + 1)),
},
'dte:Totales': {
'dte:TotalImpuestos': this.taxesSummary.map((tax) => ({
'dte:TotalImpuesto': {
$: {
NombreCorto: tax.name,
TotalMontoImpuesto: tax.total.toFixed(2),
},
},
})),
'dte:GranTotal': this.total.toFixed(2),
},
},
},
},
},
};
}
}
exports.Invoice = Invoice;
_signedXML = new WeakMap(), _xmlBuilder = new WeakMap();