salix/modules/ticket/back/methods/expedition/moveExpeditions.js

101 lines
3.0 KiB
JavaScript
Raw Normal View History

const UserError = require('vn-loopback/util/user-error');
2022-10-07 08:47:54 +00:00
module.exports = Self => {
Self.remoteMethodCtx('moveExpeditions', {
2022-10-07 08:47:54 +00:00
description: 'Move the selected expeditions to another ticket',
accessType: 'WRITE',
accepts: [{
arg: 'clientId',
type: 'number',
description: `The client id`,
required: true
},
{
arg: 'landed',
type: 'date',
2024-11-08 09:44:01 +00:00
description: `The landing date`,
required: true
},
{
arg: 'warehouseId',
type: 'number',
description: `The warehouse id`,
required: true
2022-10-07 08:47:54 +00:00
},
{
arg: 'addressId',
2022-10-07 08:47:54 +00:00
type: 'number',
description: `The address id`,
required: true
},
{
arg: 'agencyModeId',
type: 'any',
description: `The agencyMode id`
},
{
arg: 'routeId',
type: 'any',
description: `The route id`
},
{
arg: 'expeditionIds',
type: ['number'],
2022-10-07 08:47:54 +00:00
required: true,
description: 'The expeditions ids to move'
2022-10-07 08:47:54 +00:00
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/moveExpeditions`,
verb: 'POST'
}
});
Self.moveExpeditions = async(ctx, options) => {
2022-10-07 08:47:54 +00:00
const models = Self.app.models;
const args = ctx.args;
2022-10-07 08:47:54 +00:00
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
if (args.routeId) {
const route = await models.Route.findById(args.routeId, null, myOptions);
if (!route) throw new UserError('This route does not exists');
}
const ticket = await models.Ticket.new(ctx, myOptions);
2022-10-07 08:47:54 +00:00
const promises = [];
for (let expeditionsId of args.expeditionIds) {
const expeditionToUpdate = await models.Expedition.findById(expeditionsId, null, myOptions);
const expeditionUpdated = expeditionToUpdate.updateAttribute('ticketFk', ticket.id, myOptions);
2022-10-07 08:47:54 +00:00
promises.push(expeditionUpdated);
}
await Promise.all(promises);
2024-11-13 12:46:40 +00:00
await models.Ticket.updateAll({id: ticket.id}, {packages: promises.length}, myOptions);
2024-11-13 13:04:02 +00:00
const state = await models.State.findOne({where: {code: 'PACKED'}});
2022-10-07 08:47:54 +00:00
2024-11-13 12:46:40 +00:00
await models.Ticket.state(ctx, {
ticketFk: ticket.id,
stateFk: state.id,
userFk: ctx.req.accessToken.userId
}, myOptions);
2022-10-07 08:47:54 +00:00
2024-11-13 12:46:40 +00:00
if (tx) await tx.commit();
return ticket;
2022-10-07 08:47:54 +00:00
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};