salix/back/methods/mrw-config/createShipment.js

86 lines
3.3 KiB
JavaScript

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(ms.serviceType, 4 ,'0') serviceType,
pa.height,
pa.depth,
pa.width
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
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 getLableXmlDoc = parser.parseFromString(getLabelResponse.data, 'text/xml');
const base64Binary = getLableXmlDoc.getElementsByTagName('EtiquetaFile')[0]?.textContent;
const expedition = await models.Expedition.findById(expeditionFk);
await expedition.updateAttribute('externalId', shipmentId);
return base64Binary;
};
};