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

97 lines
2.9 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 => {
2019-07-22 11:14:00 +00:00
Self.remoteMethodCtx('reserve', {
description: 'Change the state of a ticket',
2019-05-22 10:35:24 +00:00
accessType: 'WRITE',
accepts: [
{
arg: 'ticketId',
type: 'number',
required: true,
description: 'The ticket id'
},
{
arg: 'sales',
type: ['object'],
required: true,
description: 'The sale to reserve'
},
{
arg: 'reserved',
type: 'boolean',
required: true
}
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/reserve`,
verb: 'POST'
}
});
Self.reserve = async(ctx, ticketId, sales, reserved) => {
const $t = ctx.req.__; // $translate
const models = Self.app.models;
const isTicketEditable = await models.Ticket.isEditable(ctx, ticketId);
if (!isTicketEditable)
throw new UserError(`The sales of this ticket can't be modified`);
const canEditSale = await models.Sale.canEdit(ctx, sales);
if (!canEditSale)
throw new UserError(`Sale(s) blocked, please contact production`);
let changesMade = '';
const promises = [];
for (let sale of sales) {
if (sale.reserved != reserved) {
const oldState = sale.reserved ? 'reserved' : 'regular';
const newState = reserved ? 'reserved' : 'regular';
const reservedSale = models.Sale.update({id: sale.id}, {reserved: reserved});
promises.push(reservedSale);
changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`;
}
}
const result = await Promise.all(promises);
const ticket = await models.Ticket.findById(ticketId, {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
}
}
}
});
const salesPerson = ticket.client().salesPersonUser();
if (salesPerson) {
const origin = ctx.req.headers.origin;
const message = $t('Changed sale reserved state', {
ticketId: ticketId,
ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`,
changes: changesMade
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
}
return result;
};
};