refs #5811 feat: al borrar expedicion borrar de viaexpress #1754

Merged
jorgep merged 15 commits from 5811-ticket.expedition_deleteViaexpress into dev 2023-11-27 07:36:28 +00:00
9 changed files with 161 additions and 39 deletions

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<DeleteEnvio xmlns="http://82.223.6.71:82">
<IdCliente><%= viaexpressConfig.client %></IdCliente>
<Usuario><%= viaexpressConfig.user %></Usuario>
<Password><%= viaexpressConfig.password %></Password>
<etiqueta><%= externalId %></etiqueta>
</DeleteEnvio>
</soap12:Body>
</soap12:Envelope>

View File

@ -0,0 +1,45 @@
const axios = require('axios');
const {DOMParser} = require('xmldom');
module.exports = Self => {
Self.remoteMethod('deleteExpedition', {
description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API',
accessType: 'WRITE',
accepts: [{
arg: 'expeditionFk',
type: 'number',
required: true
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/deleteExpedition`,
verb: 'POST'
}
});
Self.deleteExpedition = async expeditionFk => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
fields: ['url']
});
const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk);
const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, {
headers: {
'Content-Type': 'application/soap+xml; charset=utf-8'
}
});
const xmlString = response.data;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0];
const result = resultElement.textContent;
return result;
};
};

View File

@ -0,0 +1,44 @@
const fs = require('fs');
const ejs = require('ejs');
module.exports = Self => {
Self.remoteMethod('deleteExpeditionRenderer', {
description: 'Renders the data from an XML',
accessType: 'READ',
accepts: [{
arg: 'expeditionFk',
type: 'number',
required: true
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/deleteExpeditionRenderer`,
verb: 'GET'
}
});
Self.deleteExpeditionRenderer = async expeditionFk => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
fields: ['client', 'user', 'password']
});
const expedition = await models.Expedition.findOne({
fields: ['id', 'externalId'],
where: {id: expeditionFk}
});
const data = {
viaexpressConfig,
externalId: expedition.externalId
};
const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8');
const renderedXml = ejs.render(template, data);
return renderedXml;
};
};

View File

@ -1,4 +1,6 @@
module.exports = Self => { module.exports = Self => {
require('../methods/viaexpress-config/internationalExpedition')(Self); require('../methods/viaexpress-config/internationalExpedition')(Self);
require('../methods/viaexpress-config/renderer')(Self); require('../methods/viaexpress-config/renderer')(Self);
require('../methods/viaexpress-config/deleteExpedition')(Self);
require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self);
}; };

View File

@ -199,5 +199,6 @@
"You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets",
"Try again": "Try again", "Try again": "Try again",
"keepPrice": "keepPrice", "keepPrice": "keepPrice",
"Cannot past travels with entries": "Cannot past travels with entries" "Cannot past travels with entries": "Cannot past travels with entries",
"It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}"
} }

View File

@ -328,5 +328,6 @@
"User disabled": "Usuario desactivado", "User disabled": "Usuario desactivado",
"The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima",
"quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima",
"Cannot past travels with entries": "No se pueden pasar envíos con entradas" "Cannot past travels with entries": "No se pueden pasar envíos con entradas",
} "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}"
}

View File

@ -1,6 +1,7 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('deleteExpeditions', { Self.remoteMethodCtx('deleteExpeditions', {
description: 'Delete the selected expeditions', description: 'Delete the selected expeditions',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [{ accepts: [{
@ -9,44 +10,59 @@ module.exports = Self => {
required: true, required: true,
description: 'The expeditions ids to delete' description: 'The expeditions ids to delete'
}], }],
returns: {
type: ['object'],
root: true
},
http: { http: {
path: `/deleteExpeditions`, path: `/deleteExpeditions`,
verb: 'POST' verb: 'POST'
},
returns: {
type: ['object'],
root: true
} }
}); });
Self.deleteExpeditions = async(expeditionIds, options) => { Self.deleteExpeditions = async(ctx, expeditionIds) => {
const models = Self.app.models; const models = Self.app.models;
const myOptions = {}; const $t = ctx.req.__;
let tx; const notDeletedExpeditions = [];
const deletedExpeditions = [];
if (typeof options == 'object') for (let expeditionId of expeditionIds) {
Object.assign(myOptions, options); const filter = {
fields: [],
where: {
id: expeditionId
},
include: [
{
relation: 'agencyMode',
scope: {
fields: ['code'],
}
}
]
};
if (!myOptions.transaction) { const expedition = await models.Expedition.findOne(filter);
tx = await Self.beginTransaction({}); const {code} = expedition.agencyMode();
myOptions.transaction = tx;
}
try { if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') {
const promises = []; const isDeleted = await models.ViaexpressConfig.deleteExpedition(expeditionId);
for (let expeditionId of expeditionIds) {
const deletedExpedition = models.Expedition.destroyById(expeditionId, myOptions); if (isDeleted === 'true') {
promises.push(deletedExpedition); const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition);
} else notDeletedExpeditions.push(expeditionId);
} else {
const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition);
} }
const deletedExpeditions = await Promise.all(promises);
if (tx) await tx.commit();
return deletedExpeditions;
} catch (e) {
if (tx) await tx.rollback();
throw e;
} }
if (notDeletedExpeditions.length) {
throw new UserError(
$t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()})
);
}
return deletedExpeditions;
}; };
}; };

View File

@ -2,17 +2,16 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context'); const LoopBackContext = require('loopback-context');
describe('ticket deleteExpeditions()', () => { describe('ticket deleteExpeditions()', () => {
let ctx;
beforeAll(async() => { beforeAll(async() => {
const activeCtx = { ctx = {
accessToken: {userId: 9}, accessToken: {userId: 9},
http: { req: {
req: { headers: {origin: 'http://localhost'}
headers: {origin: 'http://localhost'}
}
} }
}; };
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx active: ctx
}); });
}); });
@ -23,7 +22,7 @@ describe('ticket deleteExpeditions()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
const expeditionIds = [12, 13]; const expeditionIds = [12, 13];
const result = await models.Expedition.deleteExpeditions(expeditionIds, options); const result = await models.Expedition.deleteExpeditions(ctx, expeditionIds, options);
expect(result.length).toEqual(2); expect(result.length).toEqual(2);

View File

@ -20,6 +20,9 @@
}, },
"counter": { "counter": {
"type": "number" "type": "number"
},
"externalId": {
"type": "string"
} }
}, },
"relations": { "relations": {
@ -30,7 +33,7 @@
}, },
"agencyMode": { "agencyMode": {
"type": "belongsTo", "type": "belongsTo",
"model": "agency-mode", "model": "AgencyMode",
"foreignKey": "agencyModeFk" "foreignKey": "agencyModeFk"
}, },
"worker": { "worker": {