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; }); };