Disable & create new mandate when sending a new core sample #1207
This commit is contained in:
parent
ef483bcc12
commit
8e45858cd0
|
@ -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;
|
||||
});
|
||||
};
|
||||
|
|
Loading…
Reference in New Issue