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

98 lines
3.2 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('updateQuantity', {
description: 'Changes the quantity of a sale',
2019-05-22 10:35:24 +00:00
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'sale ID',
http: {source: 'path'}
}, {
arg: 'quantity',
type: 'number',
required: true,
description: 'newQuantity'
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/updateQuantity`,
verb: 'post'
}
});
Self.updateQuantity = async(ctx, id, newQuantity, options) => {
const models = Self.app.models;
const $t = ctx.req.__; // $translate
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
await models.Sale.canEdit(ctx, [id], myOptions);
const filter = {
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
}
}
}
}
}
};
const sale = await models.Sale.findById(id, filter, myOptions);
const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*');
if (newQuantity > sale.quantity && !isRoleAdvanced)
throw new UserError('The new quantity should be smaller than the old one');
const oldQuantity = sale.quantity;
const result = await sale.updateAttributes({quantity: newQuantity}, myOptions);
const salesPerson = sale.ticket().client().salesPersonUser();
if (salesPerson) {
const origin = ctx.req.headers.origin;
const message = $t('Changed sale quantity', {
ticketId: sale.ticket().id,
itemId: sale.itemFk,
concept: sale.concept,
oldQuantity: oldQuantity,
newQuantity: newQuantity,
ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`,
itemUrl: `${origin}/#!/item/${sale.itemFk}/summary`
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions);
}
if (tx) await tx.commit();
return result;
} catch (error) {
if (tx) await tx.rollback();
throw error;
}
};
};