module.exports = Self => { Self.remoteMethod('getPalletMatchState', { description: 'Get list of pallet from truckFk with true or false if state is matched', accessType: 'WRITE', accepts: [{ arg: 'truckFk', type: 'number', required: true, description: 'The truckFk id' }, { arg: 'state', type: 'string', required: true, description: 'State code' }], returns: { type: 'object', root: true }, http: { path: `/getPalletMatchState`, verb: 'GET' } }); Self.getPalletMatchState = async(truckFk, state, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); const result = await Self.rawSql(` WITH tPallet AS( SELECT ep.id pallet, e.id expedition, e.stateTypeFk FROM vn.expeditionPallet ep JOIN vn.expeditionScan es ON es.palletFk = ep.id JOIN expedition e ON e.id = es.expeditionFk WHERE ep.truckFk = ? ),totalPalletExpedition AS( SELECT t.*, COUNT(expedition) totalPalletExpedition FROM tPallet t GROUP BY expedition ),totalPalletExpeditionCode AS( SELECT t.*, COUNT(expedition) totalPalletExpeditionCode FROM tPallet t JOIN vn.expeditionStateType est ON est.id = t.stateTypeFk WHERE code = ? GROUP BY expedition ) SELECT t.pallet, tpe.totalPalletExpedition = tpec.totalPalletExpeditionCode hasMatchStateCode FROM tPallet t LEFT JOIN totalPalletExpedition tpe ON tpe.expedition = t.expedition LEFT JOIN totalPalletExpeditionCode tpec ON tpec.expedition = t.expedition GROUP BY t.pallet;`, [truckFk, state], myOptions); return result; }; };