module.exports = Self => { Self.remoteMethod('priceDifference', { description: 'Returns sales with price difference', 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 filter = { where: { ticketFk: ticketFk }, order: 'concept ASC', include: [{ relation: 'item', scope: { include: { relation: 'tags', scope: { fields: ['tagFk', 'value'], include: { relation: 'tag', scope: { fields: ['name'] } }, limit: 6 } }, fields: ['itemFk', 'name'] } }] }; 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; }); return salesObj; }; };