const ParameterizedSQL = require('vn-loopback/node_modules/loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('listSaleTracking', { description: 'Returns all ticket sale trackings', accessType: 'READ', accepts: [{ arg: 'filter', type: 'Object', required: false, description: 'Filter defining where and paginated data', http: {source: 'query'} }], returns: { type: ["Object"], root: true }, http: { path: `/listSaleTracking`, verb: 'get' } }); Self.listSaleTracking = async filter => { let stmt = new ParameterizedSQL(` SELECT st.id, s.ticketFk, s.quantity, s.concept, s.itemFk, st.originalQuantity, st.created, st.workerFk, w.firstName, w.name, ste.name AS state FROM saleTracking st JOIN sale s ON s.id = st.saleFk JOIN worker w ON w.id = st.workerFk JOIN state ste ON ste.id = st.stateFk`); stmt.merge(Self.buildSuffix(filter)); let trackings = await Self.rawStmt(stmt); let salesFilter = { include: [ { relation: 'item', scope: { fields: ['itemFk', 'name'], include: { relation: 'tags', scope: { fields: ['tagFk', 'value'], include: { relation: 'tag', scope: { fields: ['name'] } }, limit: 6 } } } } ], where: {ticketFk: filter.where.ticketFk} }; let sales = await Self.app.models.Sale.find(salesFilter); trackings.forEach(tracking => { sales.forEach(sale => { if (tracking.itemFk == sale.itemFk) tracking.item = sale.item(); }); }); return trackings; }; };