const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('deleteExpeditions', { description: 'Delete the selected expeditions', accessType: 'WRITE', accepts: [{ arg: 'expeditionIds', type: ['number'], required: true, description: 'The expeditions ids to delete' }], http: { path: `/deleteExpeditions`, verb: 'POST' }, returns: { type: ['object'], root: true } }); Self.deleteExpeditions = async(ctx, expeditionIds) => { const models = Self.app.models; const $t = ctx.req.__; const notDeletedExpeditions = []; const deletedExpeditions = []; for (let expeditionId of expeditionIds) { const filter = { fields: [], where: { id: expeditionId }, include: [ { relation: 'agencyMode', scope: { fields: ['code'], } } ] }; const expedition = await models.Expedition.findOne(filter); const {code} = expedition.agencyMode(); let isDeleted = true; if (code?.toLowerCase()?.includes('mrw')) { const result = await models.MrwConfig.cancelShipment(expeditionId); isDeleted = result; } if (code?.toLowerCase()?.substring(0, 10) == 'viaexpress') { const result = await models.ViaexpressConfig.deleteExpedition(expeditionId); if (result !== 'true') isDeleted = false; } if (!isDeleted) notDeletedExpeditions.push(expeditionId); else { const deletedExpedition = await models.Expedition.destroyById(expeditionId); deletedExpeditions.push(deletedExpedition); } } if (notDeletedExpeditions.length) { throw new UserError( $t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()}) ); } return deletedExpeditions; }; };