salix/modules/ticket/back/methods/expedition-state/addExpeditionState.js

67 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-08-24 10:47:10 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2023-10-24 09:47:54 +00:00
Self.remoteMethodCtx('addExpeditionState', {
description: 'Update an expedition state',
2023-07-26 10:36:30 +00:00
accessType: 'WRITE',
accepts: [
{
arg: 'expeditions',
type: ['object'],
required: true,
description: 'Array of objects containing expeditionFk and stateCode'
}
],
http: {
path: `/addExpeditionState`,
verb: 'post'
}
});
2023-10-24 09:47:54 +00:00
Self.addExpeditionState = async(ctx, expeditions, options) => {
const models = Self.app.models;
2023-10-24 09:47:54 +00:00
const userId = ctx.req.accessToken.userId;
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;
try {
for (const expedition of expeditions) {
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
);
if (!expeditionStateType)
2023-08-24 10:47:10 +00:00
throw new UserError(`Invalid state code: ${expedition.stateCode}.`);
const typeFk = expeditionStateType.id;
2023-08-24 10:47:10 +00:00
expeditionId = expedition.expeditionFk;
2024-06-06 10:28:34 +00:00
const isScannedExpedition = expedition.isScanned ?? false;
2023-08-24 10:47:10 +00:00
await models.ExpeditionState.create({
expeditionFk: expedition.expeditionFk,
typeFk,
2023-10-24 09:47:54 +00:00
userFk: userId,
2024-06-06 10:28:34 +00:00
isScanned: isScannedExpedition,
2023-08-25 12:37:32 +00:00
}, myOptions);
}
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}.`);
}
};
};