From 8e45858cd007b8af125668a72b7b95574ed44dd7 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 5 Mar 2019 10:10:43 +0100 Subject: [PATCH] Disable & create new mandate when sending a new core sample #1207 --- modules/client/back/models/client-sample.js | 36 ++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/modules/client/back/models/client-sample.js b/modules/client/back/models/client-sample.js index a6509efb2..b36d27f84 100644 --- a/modules/client/back/models/client-sample.js +++ b/modules/client/back/models/client-sample.js @@ -7,16 +7,44 @@ module.exports = Self => { Self.observe('before save', async function(ctx) { let models = Self.app.models; - let data = ctx.instance; + let changes = ctx.data || ctx.instance; - let sample = await models.Sample.findById(data.typeFk); + let sample = await models.Sample.findById(changes.typeFk); - if (sample.hasCompany && !data.companyFk) + if (sample.hasCompany && !changes.companyFk) throw new UserError('Choose a company'); + // Renew mandate + if (sample.code === 'sepa-core') { + let mandateType = await models.MandateType.findOne({ + where: {name: 'CORE'} + }); + + let oldMandate = await models.Mandate.findOne({ + where: { + clientFk: changes.clientFk, + companyFk: changes.companyFk, + mandateTypeFk: mandateType.id, + finished: null + } + }); + + // Disable old mandate + if (oldMandate) + oldMandate.updateAttribute('finished', new Date()); + + // Create a new mandate + await models.Mandate.create({ + clientFk: changes.clientFk, + companyFk: changes.companyFk, + mandateTypeFk: mandateType.id + }); + } + + // Apply workerFk let filter = {where: {userFk: ctx.options.accessToken.userId}}; let worker = await Self.app.models.Worker.findOne(filter); - data.workerFk = worker.id; + changes.workerFk = worker.id; }); };