Disable & create new mandate when sending a new core sample #1207
gitea/salix/test This commit looks good Details
gitea/salix/master This commit looks good Details

This commit is contained in:
Joan Sanchez 2019-03-05 10:10:43 +01:00
parent ef483bcc12
commit 8e45858cd0
1 changed files with 32 additions and 4 deletions

View File

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