module.exports = Self => { require('../methods/mrw-config/createShipment')(Self); require('../methods/mrw-config/getLabel')(Self); require('../methods/mrw-config/cancelShipment')(Self); const fs = require('fs'); const ejs = require('ejs'); const UserError = require('vn-loopback/util/user-error'); const {DOMParser} = require('xmldom'); const axios = require('axios'); Self.getConfig = async function() { const mrw = await Self.app.models.MrwConfig.findOne(null); if (!mrw) throw new UserError(`MRW service is not configured`); return mrw; }; Self.getTextByTag = function(xmlDoc, tag) { return xmlDoc?.getElementsByTagName(tag)[0]?.textContent; }; Self.sendXmlDoc = async function(path, params, contentType) { const parser = new DOMParser(); const xmlTemplate = fs.readFileSync(path, 'utf-8'); const renderedTemplate = ejs.render(xmlTemplate, params); const data = await axios.post(params.mrw.url, renderedTemplate, { headers: { 'Content-Type': `${contentType}; charset=utf-8` } }); return parser.parseFromString(data.data, 'text/xml'); }; Self.getClientType = async function(expeditionFk) { if (!expeditionFk) throw new UserError(`No expeditionFk defined`); const {clientTypeWidth} = await Self.getConfig(); const result = await Self.app.models.Expedition.findById(expeditionFk, {include: [{ relation: 'ticket', scope: { include: { relation: 'agencyMode', scope: { include: { relation: 'mrwService', } } } } }]} ); const clientType = result?.ticket()?.agencyMode()?.mrwService()?.clientType; if (!clientType || !clientTypeWidth) throw new UserError(`ClientType not available`); return clientType.toString().padStart(clientTypeWidth, '0'); }; };