salix/modules/ticket/back/methods/ticket/getPossibleStowaways.js

71 lines
2.1 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('getPossibleStowaways', {
description: 'Returns a list of allowed tickets for a stowaway ticket',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'ticket id',
http: {source: 'path'}
}],
returns: {
root: true
},
http: {
path: `/:id/getPossibleStowaways`,
verb: 'GET'
}
});
Self.getPossibleStowaways = async ticketFk => {
const models = Self.app.models;
const canHaveStowaway = await models.Ticket.canHaveStowaway(ticketFk);
if (!canHaveStowaway)
throw new UserError(`Can't create stowaway for this ticket`);
let ship = await models.Ticket.findById(ticketFk);
if (!ship || !ship.shipped)
return [];
let lowestDate = new Date(ship.shipped.getTime());
lowestDate.setHours(0, 0, -1, 0);
let highestDate = new Date(ship.shipped.getTime());
highestDate.setHours(23, 59, 59);
let possibleStowaways = await models.Ticket.find({
where: {
id: {neq: ticketFk},
clientFk: ship.clientFk,
addressFk: ship.addressFk,
agencyModeFk: ship.agencyModeFk,
warehouseFk: {neq: ship.warehouseFk},
shipped: {
between: [lowestDate.toJSON(), highestDate.toJSON()]
}
},
include: [
{relation: 'agencyMode'},
{relation: 'warehouse'},
{relation: 'state',
scope: {
fields: ['stateFk'],
include: {
relation: 'state',
fields: ['id', 'name'],
}
},
},
]
});
return possibleStowaways;
};
};