107 lines
3.2 KiB
JavaScript
107 lines
3.2 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethodCtx('reserve', {
|
|
description: 'Change the state of a ticket',
|
|
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, options) => {
|
|
const $t = ctx.req.__; // $translate
|
|
const models = Self.app.models;
|
|
const myOptions = {};
|
|
let tx;
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
const salesIds = sales.map(sale => sale.id);
|
|
|
|
await models.Sale.canEdit(ctx, salesIds, myOptions);
|
|
|
|
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.updateAll({id: sale.id}, {reserved: reserved}, myOptions);
|
|
|
|
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']
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}, myOptions);
|
|
|
|
const salesPerson = ticket.client().salesPersonUser();
|
|
if (salesPerson) {
|
|
const url = await Self.app.models.Url.getUrl();
|
|
|
|
const message = $t('Changed sale reserved state', {
|
|
ticketId: ticketId,
|
|
ticketUrl: `${url}ticket/${ticketId}/sale`,
|
|
changes: changesMade
|
|
});
|
|
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions);
|
|
}
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return result;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|