2023-08-24 10:47:10 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
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;
|
|
|
|
}
|
2023-08-24 10:47:10 +00:00
|
|
|
let expeditionId;
|
2023-07-24 11:32:28 +00:00
|
|
|
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-08-25 12:37:32 +00:00
|
|
|
}, myOptions
|
2023-07-24 11:32:28 +00:00
|
|
|
);
|
2023-08-24 08:01:07 +00:00
|
|
|
if (!expeditionStateType)
|
2023-08-24 10:47:10 +00:00
|
|
|
throw new UserError(`Invalid state code: ${expedition.stateCode}.`);
|
2023-07-24 11:32:28 +00:00
|
|
|
|
2023-07-26 11:33:56 +00:00
|
|
|
const typeFk = expeditionStateType.id;
|
2023-08-24 10:47:10 +00:00
|
|
|
expeditionId = expedition.expeditionFk;
|
2023-08-24 08:01:07 +00:00
|
|
|
|
2023-08-24 10:47:10 +00:00
|
|
|
await models.ExpeditionState.create({
|
2023-07-24 11:32:28 +00:00
|
|
|
expeditionFk: expedition.expeditionFk,
|
|
|
|
typeFk,
|
2023-08-25 12:37:32 +00:00
|
|
|
}, myOptions);
|
2023-07-24 11:32:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
} catch (e) {
|
|
|
|
if (tx) await tx.rollback();
|
2023-08-24 10:47:10 +00:00
|
|
|
if (e instanceof UserError)
|
|
|
|
throw e;
|
|
|
|
|
|
|
|
throw new UserError(`Invalid expedition id: ${expeditionId}.`);
|
2023-07-24 11:32:28 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|