feat: Adding Loads/Vehicle events to populate data among different

tables

fix(proposals): When patch event happens without is_accepted field, this
is detected as a rejection event.
This commit is contained in:
Josepablo C
2025-07-14 16:37:22 -06:00
parent 494d8cad7f
commit 9ffa97ac0b
10 changed files with 350 additions and 34 deletions

View File

@@ -0,0 +1,60 @@
'user strict';
const { getModel } = require( '../../../Models' );
const loadsModel = getModel('loads');
const vehiclesModel = getModel('vehicles');
const proposalsModel = getModel('proposals');
/**
* When a load is delivered, notify all involved parties
* @param {*} userId -> Responsible of the change
* @param {*} elementId -> Element Affected
*/
async function onDelivered( userId, elementId ){
const load = await loadsModel.findById( elementId );
const proposal_list = await proposalsModel.find({
load: load.id,
is_accepted: true,
is_completed: false
});
const vehicle_list = await vehiclesModel.find({
active_load: load.id
});
const current_date = new Date();
/// Update Load: Remove vehicle and driver reference for data safety.
await loadsModel.findByIdAndUpdate( proposal.load, {
driver: null,
vehicle: null,
status: "Closed",
delivered_date: current_date,
load_status_updated: current_date,
});
/// Update proposals related to this load. Ideally, just one.
// remove vehicle for data safety.
for( const proposal of proposal_list ){
await proposalsModel.findByIdAndUpdate(
proposal.id,
{
is_completed : true,
vehicle : null,
}
);
}
/// Update vehicles related to this load. Ideally, just one.
for( const vehicle of vehicle_list ){
await vehiclesModel.findByIdAndUpdate(
vehicle.id,
{
active_load: null,
load_shipper: null,
status: "Free"
}
);
}
}
module.exports = { onDelivered };