Files
ETAApi/v1/src/lib/Handlers/Proposals.handler.js

87 lines
2.7 KiB
JavaScript

'user strict';
const { getModel } = require( '../Models' );
const vehiclesModel = require('../Models/vehicles.model');
const proposalsModel = getModel('proposals');
const loadsModel = getModel('loads');
const usersModel = getModel('users');
const companiesModel = getModel('companies');
const notificationsModel = getModel('notifications');
/**
* When the proposal is created then the load owner should be notified
* @param {*} id
* @param {*} newProposalData
* @returns
*/
async function onPostEvent( id , newProposalData ){
const proposal = await proposalsModel.findById( id );
const load = await loadsModel.findById( proposal.load );
const user = await usersModel.findById( load.posted_by );
const notification = new notificationsModel({
"owner": user.id,
"title": "New proposal",
"description": `${load.shipment_code}`,
"tag":"new_proposal",
"deleted":false
});
await notification.save();
}
/**
* When the proposal is accepted then the load should be updated to have the latest
* shipper, vehicle, etc.
* @param {*} id
* @param {*} newProposalData
* @returns
*/
async function onPatchEvent( id , newProposalData ){
const proposal = await proposalsModel.findById( id );
if( !newProposalData.is_accepted ){
const load = await loadsModel.findById( proposal.load );
/// Update Proposal:
/// Remove shipper
await proposalsModel.findByIdAndUpdate( id , {
shipper : null
} );
/// Update Load:
/// Remove carrier, driver and vehicle
await loadsModel.findByIdAndUpdate( proposal.load, {
carrier : null,
driver : null,
vehicle : null,
} );
const notification = new notificationsModel({
"owner": user.id,
"title": `Your proposal has been accepted!`,
"description": `${load.shipment_code}`,
"tag":"accepted_proposal",
"deleted":false
});
}else{
const shipper_user = await usersModel.findById( proposal.accepted_by );
const shipper = await companiesModel.findById( shipper_user.company );
const vehicle = await vehiclesModel.findById( proposal.vehicle );
/// Update Proposal:
/// Adding shipper to proposal
await proposalsModel.findByIdAndUpdate( id , {
shipper : shipper.id
} );
/// Update Load:
/// Add carrier, driver and vehicle
await loadsModel.findByIdAndUpdate( proposal.load, {
carrier : proposal.carrier,
driver : vehicle.driver,
vehicle : proposal.vehicle,
} );
}
}
module.exports = { onPostEvent, onPatchEvent };