salix/modules/ticket/back/methods/sale/moveToTicket.js

91 lines
3.0 KiB
JavaScript
Raw Normal View History

2018-12-27 11:54:16 +00:00
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('moveToTicket', {
description: 'Moves lines to a new or a given ticket',
accepts: [{
arg: 'params',
type: 'object',
required: true,
description: 'currentTicket, receiverTicket, [sales IDs], removeEmptyTicket',
http: {source: 'body'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/moveToTicket`,
verb: 'post'
}
});
Self.moveToTicket = async(ctx, params) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
let currentTicket = await models.Ticket.findById(params.currentTicket.currentTicketId);
let newTicketData = {};
let receiverTicket = params.receiverTicket;
let isCurrentTicketEditable = await models.Ticket.isEditable(params.currentTicket.currentTicketId);
if (!isCurrentTicketEditable)
throw new UserError(`The sales of the current ticket can't be modified`);
if (params.receiverTicket.id) {
let isReceiverTicketEditable = await models.Ticket.isEditable(params.receiverTicket.id);
if (!isReceiverTicketEditable)
throw new UserError(`The sales of the receiver ticket can't be modified`);
}
if (!params.receiverTicket.id) {
let travelDates = await models.Agency.getFirstShipped(params.currentTicket);
if (!travelDates)
throw new UserError(`Invalid parameters to create a new ticket`);
2019-06-07 11:07:23 +00:00
let shipped = new Date(travelDates.shipped);
let landed = new Date(travelDates.landed);
newTicketData = {
clientFk: params.currentTicket.clientFk,
addressFk: params.currentTicket.addressFk,
agencyModeFk: params.currentTicket.agencyModeFk,
warehouseFk: params.currentTicket.warehouseFk,
shipped: shipped,
landed: landed,
userId: userId
};
}
2019-06-13 07:21:36 +00:00
let tx = await Self.beginTransaction({});
try {
2019-06-13 07:21:36 +00:00
let options = {transaction: tx};
if (!params.receiverTicket.id)
receiverTicket = await models.Ticket.new(ctx, newTicketData, options);
let promises = [];
for (let sale of params.sales) {
promises.push(
models.Sale.update(
{id: sale.id},
{ticketFk: receiverTicket.id},
options
)
);
}
if (params.removeEmptyTicket)
promises.push(currentTicket.updateAttributes({isDeleted: true}, options));
await Promise.all(promises);
2019-06-13 07:21:36 +00:00
await tx.commit();
return receiverTicket;
} catch (error) {
2019-06-13 07:21:36 +00:00
await tx.rollback();
throw error;
}
};
};