2023-07-24 11:32:28 +00:00
|
|
|
module.exports = Self => {
|
2023-07-26 10:36:30 +00:00
|
|
|
Self.remoteMethod('addExpeditionState', {
|
2023-07-24 11:32:28 +00:00
|
|
|
description: 'Update an expedition state',
|
2023-07-26 10:36:30 +00:00
|
|
|
accessType: 'WRITE',
|
2023-07-24 11:32:28 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'expeditions',
|
2023-08-24 08:01:07 +00:00
|
|
|
type: ['object'],
|
2023-07-24 11:32:28 +00:00
|
|
|
required: true,
|
|
|
|
description: 'Array of objects containing expeditionFk and stateCode'
|
|
|
|
}
|
|
|
|
],
|
2023-07-26 11:33:56 +00:00
|
|
|
returns: {
|
|
|
|
type: 'boolean',
|
|
|
|
root: true
|
|
|
|
},
|
2023-07-24 11:32:28 +00:00
|
|
|
http: {
|
2023-08-24 08:01:07 +00:00
|
|
|
path: `/addExpeditionState`,
|
2023-07-24 11:32:28 +00:00
|
|
|
verb: 'post'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-07-26 11:33:56 +00:00
|
|
|
Self.addExpeditionState = async(expeditions, options) => {
|
2023-07-24 11:32:28 +00:00
|
|
|
const models = Self.app.models;
|
|
|
|
let tx;
|
|
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
|
|
Object.assign(myOptions, options);
|
|
|
|
|
|
|
|
if (!myOptions.transaction) {
|
|
|
|
tx = await Self.beginTransaction({});
|
|
|
|
myOptions.transaction = tx;
|
|
|
|
}
|
|
|
|
|
|
|
|
const promises = [];
|
|
|
|
try {
|
|
|
|
for (const expedition of expeditions) {
|
2023-07-26 11:33:56 +00:00
|
|
|
const expeditionStateType = await models.ExpeditionStateType.findOne(
|
2023-07-26 10:36:30 +00:00
|
|
|
{
|
|
|
|
fields: ['id'],
|
|
|
|
where: {code: expedition.stateCode}
|
|
|
|
}
|
2023-07-24 11:32:28 +00:00
|
|
|
);
|
2023-08-24 08:01:07 +00:00
|
|
|
if (!expeditionStateType)
|
|
|
|
throw new Error(`The state code: ${expedition.stateCode} does not exist.`);
|
2023-07-24 11:32:28 +00:00
|
|
|
|
2023-07-26 11:33:56 +00:00
|
|
|
const typeFk = expeditionStateType.id;
|
2023-08-24 08:01:07 +00:00
|
|
|
|
|
|
|
const existsExpedition = await models.Expedition.findOne({
|
|
|
|
fields: ['id'],
|
|
|
|
where: {id: expedition.expeditionFk}
|
|
|
|
});
|
|
|
|
if (!existsExpedition)
|
|
|
|
throw new Error(`The expedition with id: ${expedition.expeditionFk} does not exist.`);
|
|
|
|
|
2023-07-26 11:33:56 +00:00
|
|
|
const newExpeditionState = models.ExpeditionState.create({
|
2023-07-24 11:32:28 +00:00
|
|
|
expeditionFk: expedition.expeditionFk,
|
|
|
|
typeFk,
|
|
|
|
});
|
2023-07-25 14:32:38 +00:00
|
|
|
promises.push(newExpeditionState);
|
2023-07-24 11:32:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await Promise.all(promises);
|
|
|
|
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
} catch (e) {
|
|
|
|
if (tx) await tx.rollback();
|
2023-08-24 08:01:07 +00:00
|
|
|
throw e;
|
2023-07-24 11:32:28 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|