salix/modules/ticket/back/methods/ticket/updateDiscount.js

122 lines
3.9 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
description: 'The ticket id',
type: 'number',
required: true,
http: {source: 'path'}
},
{
arg: 'salesIds',
description: 'The sales id',
type: ['number'],
required: true,
}, {
arg: 'newDiscount',
description: 'The new discount',
type: 'number',
required: true
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/updateDiscount`,
verb: 'post'
}
});
Self.updateDiscount = async(ctx, id, salesIds, newDiscount) => {
const models = Self.app.models;
const tx = await Self.beginTransaction({});
try {
const options = {transaction: tx};
const filter = {
where: {
id: {inq: salesIds}
},
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
fields: ['id', 'clientFk']
}
}
};
let sales = await models.Sale.find(filter, options);
if (sales.length === 0)
throw new UserError('Please select at least one sale');
const allFromSameTicket = sales.every(sale => sale.ticketFk === id);
if (!allFromSameTicket)
throw new UserError('All sales must belong to the same ticket');
const userId = ctx.req.accessToken.userId;
const isLocked = await models.Ticket.isLocked(id);
const roles = await models.Account.getRoles(userId);
const hasAllowedRoles = roles.filter(role =>
role == 'salesPerson' || role == 'claimManager'
);
const state = await Self.app.models.TicketState.findOne({
where: {ticketFk: id}
});
const alertLevel = state ? state.alertLevel : null;
if (isLocked || (!hasAllowedRoles && alertLevel > 0))
throw new UserError(`The sales of this ticket can't be modified`);
const usesMana = await models.WorkerMana.findOne({
where: {
workerFk: userId
},
fields: 'amount'}, options);
const componentCode = usesMana ? 'mana' : 'buyerDiscount';
const discountComponent = await models.Component.findOne({
where: {code: componentCode}}, options);
const componentId = discountComponent.id;
let promises = [];
for (let sale of sales) {
const value = ((-sale.price * newDiscount) / 100);
const newComponent = models.SaleComponent.upsert({
saleFk: sale.id,
value: value,
componentFk: componentId}, options);
const updatedSale = sale.updateAttribute('discount', newDiscount, options);
promises.push(newComponent, updatedSale);
}
await Promise.all(promises);
const query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [userId], options);
await tx.commit();
} catch (error) {
await tx.rollback();
throw error;
}
};
};