From ea4190f15cd9227aece6361a981be22f8f7f665d Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 24 Jul 2023 13:32:28 +0200 Subject: [PATCH] refs #5216 update expedition state added --- .../expedition-state/updateExpeditionState.js | 71 +++++++++++++++++++ .../ticket/back/models/expedition-state.js | 1 + 2 files changed, 72 insertions(+) create mode 100644 modules/ticket/back/methods/expedition-state/updateExpeditionState.js diff --git a/modules/ticket/back/methods/expedition-state/updateExpeditionState.js b/modules/ticket/back/methods/expedition-state/updateExpeditionState.js new file mode 100644 index 000000000..ce5144d30 --- /dev/null +++ b/modules/ticket/back/methods/expedition-state/updateExpeditionState.js @@ -0,0 +1,71 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethod('updateExpedtionState', { + description: 'Update an expedition state', + accepts: [ + { + arg: 'expeditions', + type: [ + { + expeditionFk: 'number', + stateCode: 'string' + } + ], + required: true, + description: 'Array of objects containing expeditionFk and stateCode' + } + ], + http: { + path: `/updateExpeditionState`, + verb: 'post' + } + }); + + Self.updateExpedtionState = async(expeditions, options) => { + 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; + } + + if (expeditions.length === 0) + return false; + + const promises = []; + try { + const conn = Self.dataSource.connector; + for (const expedition of expeditions) { + const stmt = new ParameterizedSQL( + `SELECT id FROM vn.expeditionStateType WHERE code = ?`, + [expedition.stateCode] + ); + const result = await conn.query(stmt); + if (result.length === 0) + throw new Error(`The state code '${exp.stateCode}' does not exist.`); + + const typeFk = result[0].id; + + const newExpeditionState = await models.Self.create({ + expeditionFk: expedition.expeditionFk, + typeFk, + }); + } + + await Promise.all(promises); + + if (tx) await tx.commit(); + + return true; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/models/expedition-state.js b/modules/ticket/back/models/expedition-state.js index af76af718..041c57be6 100644 --- a/modules/ticket/back/models/expedition-state.js +++ b/modules/ticket/back/models/expedition-state.js @@ -1,3 +1,4 @@ module.exports = function(Self) { require('../methods/expedition-state/filter')(Self); + require('../methods/expedition-state/updateExpeditionState')(Self); };