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

111 lines
3.4 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('priceDifference', {
description: 'Returns sales with price difference if the ticket is editable',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'Number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
},
{
arg: 'landed',
type: 'Date',
description: 'The landing date',
required: true
},
{
arg: 'addressId',
type: 'Number',
description: 'The address id',
required: true
},
{
arg: 'agencyModeId',
type: 'Number',
description: 'The agencyMode id',
required: true
},
{
arg: 'zoneId',
type: 'Number',
description: 'The zone id',
required: true
},
{
arg: 'warehouseId',
type: 'Number',
description: 'The warehouse id',
required: true
}],
returns: {
type: ['Object'],
root: true
},
http: {
path: `/:id/priceDifference`,
verb: 'POST'
}
});
Self.priceDifference = async(ctx, id, landed, addressId, agencyModeId, zoneId, warehouseId) => {
const models = Self.app.models;
const isEditable = await models.Ticket.isEditable(ctx, id);
const userId = ctx.req.accessToken.userId;
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss');
if (!isProductionBoss) {
const zone = await models.Agency.getShipped(landed, addressId, agencyModeId, warehouseId);
if (!zone || zone.id != zoneId)
throw new UserError(`You don't have privileges to change the zone`);
}
let salesObj = {};
salesObj.items = await models.Sale.find({
where: {
ticketFk: id
},
order: 'concept ASC',
include: [{
relation: 'item'
}]
});
salesObj.totalUnitPrice = 0.00;
salesObj.totalNewPrice = 0.00;
salesObj.totalDifference = 0.00;
const query = `CALL vn.ticket_priceDifference(?, ?, ?, ?, ?)`;
const args = [id, landed, addressId, zoneId, warehouseId];
const [difComponents] = await Self.rawSql(query, args);
const map = new Map();
difComponents.forEach(difComponent => {
map.set(difComponent.saleFk, difComponent);
});
salesObj.items.forEach(sale => {
const difComponent = map.get(sale.id);
if (difComponent)
sale.component = difComponent;
salesObj.totalUnitPrice += sale.price;
salesObj.totalNewPrice += sale.component.newPrice;
salesObj.totalDifference += sale.component.difference;
salesObj.totalUnitPrice = Math.round(salesObj.totalUnitPrice * 100) / 100;
salesObj.totalNewPrice = Math.round(salesObj.totalNewPrice * 100) / 100;
salesObj.totalDifference = Math.round(salesObj.totalDifference * 100) / 100;
});
return salesObj;
};
};