module.exports = Self => { Self.remoteMethod('summary', { description: 'Returns a ticket summary', accessType: 'READ', accepts: [{ arg: 'id', type: 'number', required: true, description: 'ticket id', http: {source: 'path'} }], returns: { type: [this.modelName], root: true }, http: { path: `/:id/summary`, verb: 'GET' } }); Self.summary = async ticketFk => { let models = Self.app.models; let summaryObj = await getTicketData(Self, ticketFk); summaryObj.sales = await getSales(models.Sale, ticketFk); summaryObj.subTotal = getSubTotal(summaryObj.sales); summaryObj.VAT = await models.Ticket.getVAT(ticketFk); summaryObj.total = await models.Ticket.getTotal(ticketFk); return summaryObj; }; async function getTicketData(Self, ticketFk) { let filter = { include: [ {relation: 'warehouse', scope: {fields: ['name']}}, {relation: 'agencyMode', scope: {fields: ['name']}}, { relation: 'client', scope: { fields: ['salesPersonFk', 'name'], include: { relation: 'salesPerson', fields: ['firstName', 'name'] } } }, { relation: 'address', scope: { fields: ['street', 'city', 'provinceFk', 'phone'], include: { relation: 'province', scope: { fields: ['name'] } } } }, { relation: 'notes', scope: { fields: ['id', 'observationTypeFk', 'description'], include: { relation: 'observationType', fields: ['description'] } } }, { relation: 'tracking', scope: { fields: ['stateFk'], include: { relation: 'state', fields: ['name'] } } } ], where: {id: ticketFk} }; return await Self.findOne(filter); } async function getSales(Sale, ticketFk) { let filter = { where: { ticketFk: ticketFk }, order: 'itemFk ASC', include: [{ relation: 'item', scope: { include: { relation: 'tags', scope: { fields: ['tagFk', 'value'], include: { relation: 'tag', scope: { fields: ['name'] } }, limit: 6 } }, fields: ['itemFk', 'name'] } }] }; return await Sale.find(filter); } function getSubTotal(sales) { let subTotal = 0.00; sales.forEach(sale => { subTotal += sale.quantity * sale.price; }); return subTotal; } };