const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('priceDifference', { description: 'Returns sales with price difference if the ticket is editable', accessType: 'READ', accepts: [{ arg: 'ticketFk', type: 'number', required: true, description: 'ticket id', http: {source: 'path'} }, { arg: 'data', type: 'Object', required: true, description: 'landed, addressFk, agencyModeFk', http: {source: 'body'} }], returns: { type: ['Object'], root: true }, http: { path: `/:ticketFk/priceDifference`, verb: 'post' } }); Self.priceDifference = async(ticketFk, data) => { let thisTicketIsEditable = await Self.app.models.Ticket.isEditable(ticketFk); if (!thisTicketIsEditable) throw new UserError(`The sales of this ticket can't be modified`); let filter = { where: { ticketFk: ticketFk }, order: 'concept ASC', include: [{ relation: 'item' }] }; let salesObj = {}; salesObj.items = await Self.find(filter); salesObj.totalUnitPrice = 0.00; salesObj.totalNewPrice = 0.00; salesObj.totalDifference = 0.00; let query = `CALL vn.ticketComponentPriceDifference(?, ?, ?, ?, ?)`; let [differences] = await Self.rawSql(query, [ ticketFk, data.landed, data.addressFk, data.agencyModeFk, data.warehouseFk ]); salesObj.items.forEach(sale => { differences.forEach(difference => { if (sale.id == difference.saleFk) sale.component = difference; }); 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; }; };