module.exports = Self => { Self.remoteMethod('getSuggestedTickets', { description: 'Returns an array of suggested tickets for the given route', accessType: 'READ', accepts: [{ arg: 'id', type: 'number', required: true, description: 'The route id', http: {source: 'path'} }], returns: { type: ['object'], root: true }, http: { path: `/:id/getSuggestedTickets`, verb: 'GET' } }); Self.getSuggestedTickets = async(id, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const route = await Self.app.models.Route.findById(id, { include: { relation: 'agencyMode', scope: { fields: ['name'] } } }, myOptions); const zoneAgencyModes = await Self.app.models.ZoneAgencyMode.find({ where: { agencyModeFk: route.agencyModeFk } }, myOptions); const zoneIds = []; for (let zoneAgencyMode of zoneAgencyModes) zoneIds.push(zoneAgencyMode.zoneFk); const minDate = new Date(route.dated); minDate.setHours(0, 0, 0, 0); const maxDate = new Date(route.dated); maxDate.setHours(23, 59, 59, 59); let tickets = await Self.app.models.Ticket.find({ where: { zoneFk: {inq: zoneIds}, routeFk: null, landed: {between: [minDate, maxDate]} }, include: [ { relation: 'warehouse', scope: { fields: ['id', 'name'] } }, { relation: 'zone', scope: { fields: ['id', 'name'] } }, { relation: 'agencyMode', scope: { fields: ['id', 'name'] } }, { relation: 'address', scope: { fields: ['street', 'city', 'provinceFk', 'phone', 'nickname', 'postalCode'], include: { relation: 'province', scope: { fields: ['name'] } } } }, ] }, myOptions); return tickets.map(ticket => { const simpleTicket = ticket.toJSON(); return { ...simpleTicket, agencyName: route.agencyMode().name }; }); }; };