const axios = require('axios'); const {DOMParser} = require('xmldom'); const fs = require('fs'); const ejs = require('ejs'); module.exports = Self => { Self.remoteMethod('createShipment', { description: 'Create an expedition and return a base64Binary label', accessType: 'WRITE', accepts: [{ arg: 'expeditionFk', type: 'number', required: true }], returns: { type: ['object'], root: true }, http: { path: `/createShipment`, verb: 'POST' } }); Self.createShipment = async expeditionFk => { const models = Self.app.models; const mrw = await models.MrwConfig.findOne(); const [expeditionData] = await Self.rawSql( `SELECT CASE co.code WHEN 'ES' THEN a.postalCode WHEN 'PT' THEN LEFT(a.postalCode, 4) WHEN 'AD' THEN REPLACE(a.postalCode, 'AD', '00') END postalCode, a.city, a.street, co.code countryCode, c.fi, c.name clientName, c.phone, DATE_FORMAT(e.created, '%d/%m/%Y') created, e.id expeditionId, LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), 4 ,'0') serviceType, IFNULL(mw.weekdays, "N") weekDays FROM expedition e JOIN packaging pa ON pa.id = e.packagingFk JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code LEFT JOIN mrwServiceWeekday mw ON mw.params = DATE_FORMAT(e.created, '%a') JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id JOIN province p ON a.provinceFk = p.id JOIN country co ON co.id = p.countryFk WHERE e.id = ?`, [expeditionFk] ); const shipmentTemplate = fs.readFileSync(__dirname + '/createShipment.ejs', 'utf-8'); const renderedShipment = ejs.render(shipmentTemplate, {mrw, expeditionData}); const shipmentResponse = await axios.post(mrw.url, renderedShipment, { headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' } }); const parser = new DOMParser(); const shipmentXmlDoc = parser.parseFromString(shipmentResponse.data, 'text/xml'); const shipmentId = shipmentXmlDoc.getElementsByTagName('NumeroEnvio')[0].textContent; const getLabelTemplate = fs.readFileSync(__dirname + '/getLabel.ejs', 'utf-8'); const renderedGetLabel = ejs.render(getLabelTemplate, {mrw, shipmentId}); const getLabelResponse = await axios.post(mrw.url, renderedGetLabel, { headers: { 'Content-Type': 'text/xml; charset=utf-8' } }); const getLabelXmlDoc = parser.parseFromString(getLabelResponse.data, 'text/xml'); const base64Binary = getLabelXmlDoc.getElementsByTagName('EtiquetaFile')[0]?.textContent; const expedition = await models.Expedition.findById(expeditionFk); await expedition.updateAttribute('externalId', shipmentId); return base64Binary; }; };