const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('listSaleTracking', { description: 'Returns all ticket sale trackings', accessType: 'READ', accepts: [{ arg: 'filter', type: 'Object', description: 'Filter defining where and paginated data' }], 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, u.nickname userNickname, ste.name AS state FROM saleTracking st JOIN sale s ON s.id = st.saleFk JOIN worker w ON w.id = st.workerFk JOIN account.user u ON u.id = w.userFk JOIN state ste ON ste.id = st.stateFk`); stmt.merge(Self.makeSuffix(filter)); let trackings = await Self.rawStmt(stmt); let salesFilter = { include: [ { relation: 'item' } ], 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; }; };