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 Self.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 zoneShipped = await models.Agency.getShipped(landed, addressId, agencyModeId, warehouseId); if (!zoneShipped || zoneShipped.zoneFk != zoneId) throw new UserError(`You don't have privileges to change the zone`); } let salesObj = { items: await models.Sale.find({ where: { ticketFk: id }, order: 'concept ASC', include: 'item' }), totalUnitPrice: 0.00, totalNewPrice: 0.00, 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(); // Sale price component, one per sale for (difComponent of difComponents) map.set(difComponent.saleFk, difComponent); function round(value) { return Math.round(value * 100) / 100; } for (sale of salesObj.items) { const difComponent = map.get(sale.id); if (difComponent) { sale.component = difComponent; salesObj.totalDifference += difComponent.difference; salesObj.totalDifference = round(salesObj.totalDifference); salesObj.totalNewPrice += difComponent.newPrice; salesObj.totalNewPrice = round(salesObj.totalNewPrice); } salesObj.totalUnitPrice += sale.price; salesObj.totalUnitPrice = round(salesObj.totalUnitPrice); } return salesObj; }; };