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

123 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 = {
fields: ['id', 'ticketFk', 'price'],
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 isEditable = await models.Ticket.isEditable(ctx, id);
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
const ticket = await models.Ticket.findById(id, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
});
const salesPersonId = ticket.client().salesPersonFk;
const usesMana = await models.WorkerMana.findOne({
where: {
workerFk: salesPersonId
},
fields: 'amount'}, options);
const componentCode = usesMana ? 'mana' : 'buyerDiscount';
const discountComponent = await models.ComponentRate.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 = models.Sale.update({id: sale.id},
{discount: newDiscount}, options);
promises.push([newComponent, updatedSale]);
}
await Promise.all(promises);
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [salesPersonId], options);
await tx.commit();
} catch (error) {
await tx.rollback();
throw error;
}
};
};