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

169 lines
5.6 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
},
{
arg: 'manaCode',
description: 'The type of mana',
type: 'string',
required: false
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/updateDiscount`,
verb: 'post'
}
});
Self.updateDiscount = async(ctx, id, salesIds, newDiscount, manaCode, 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 filter = {
where: {
id: {inq: salesIds}
},
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
fields: ['id', 'clientFk']
}
}
};
const sales = await models.Sale.find(filter, myOptions);
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, myOptions);
const roles = await models.Account.getRoles(userId, myOptions);
const hasAllowedRoles = roles.filter(role =>
role == 'salesPerson' || role == 'claimManager'
);
const state = await Self.app.models.TicketState.findOne({
where: {ticketFk: id}
}, myOptions);
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'}, myOptions);
const componentCode = usesMana ? manaCode : 'buyerDiscount';
const discountComponent = await models.Component.findOne({
where: {code: componentCode}}, myOptions);
const componentId = discountComponent.id;
const promises = [];
let changesMade = '';
for (let sale of sales) {
const oldDiscount = sale.discount;
const value = ((-sale.price * newDiscount) / 100);
const newComponent = models.SaleComponent.upsert({
saleFk: sale.id,
value: value,
componentFk: componentId}, myOptions);
const updatedSale = sale.updateAttribute('discount', newDiscount, myOptions);
promises.push(newComponent, updatedSale);
const change = `${oldDiscount}% ➔ *${newDiscount}%*`;
changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${change}`;
}
await Promise.all(promises);
await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?)', [id], myOptions);
const ticket = await models.Ticket.findById(id, {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser',
scope: {
fields: ['id', 'name']
}
}
}
}
}, myOptions);
const salesPerson = ticket.client().salesPersonUser();
if (salesPerson) {
const origin = ctx.req.headers.origin;
const message = $t('Changed sale discount', {
ticketId: id,
ticketUrl: `${origin}/#!/ticket/${id}/sale`,
changes: changesMade
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions);
}
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};