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

89 lines
3.1 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 transaction = await Self.beginTransaction({});
let options = {transaction};
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);
let shipped = new Date(travelDates.vShipped);
shipped.setMinutes(shipped.getMinutes() + shipped.getTimezoneOffset());
let landed = new Date(travelDates.vLanded);
landed.setMinutes(landed.getMinutes() + landed.getTimezoneOffset());
newTicketData = {
clientFk: params.currentTicket.clientFk,
addressFk: params.currentTicket.addressFk,
agencyModeFk: params.currentTicket.agencyModeFk,
warehouseFk: params.currentTicket.warehouseFk,
shipped: shipped,
landed: landed,
userId: userId
};
}
try {
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);
await transaction.commit();
return receiverTicket;
} catch (error) {
await transaction.rollback();
throw error;
}
};
};