2018-12-27 11:54:16 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
2022-09-26 11:33:27 +00:00
|
|
|
const LoopBackContext = require('loopback-context');
|
2018-08-02 07:49:00 +00:00
|
|
|
|
2018-07-31 09:08:22 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
Self.validatesPresenceOf('typeFk', {
|
|
|
|
message: 'Sample type cannot be blank'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.observe('before save', async function(ctx) {
|
2022-09-26 11:33:27 +00:00
|
|
|
const models = Self.app.models;
|
|
|
|
const changes = ctx.data || ctx.instance;
|
2018-07-31 09:08:22 +00:00
|
|
|
|
2022-09-26 11:33:27 +00:00
|
|
|
const sample = await models.Sample.findById(changes.typeFk);
|
2018-07-31 09:08:22 +00:00
|
|
|
|
2019-03-05 09:10:43 +00:00
|
|
|
if (sample.hasCompany && !changes.companyFk)
|
2018-08-02 07:49:00 +00:00
|
|
|
throw new UserError('Choose a company');
|
2018-07-31 09:08:22 +00:00
|
|
|
|
2019-05-08 08:42:26 +00:00
|
|
|
const mandateSamples = [
|
|
|
|
{sample: 'sepa-core', type: 'CORE'},
|
|
|
|
{sample: 'client-lcr', type: 'LCR'}
|
|
|
|
];
|
|
|
|
|
|
|
|
const mandate = mandateSamples.find(mandate => {
|
|
|
|
return mandate.sample === sample.code;
|
|
|
|
});
|
|
|
|
|
2019-03-05 09:10:43 +00:00
|
|
|
// Renew mandate
|
2019-05-08 08:42:26 +00:00
|
|
|
if (mandate) {
|
2022-09-26 11:33:27 +00:00
|
|
|
const mandateType = await models.MandateType.findOne({
|
2019-05-08 08:42:26 +00:00
|
|
|
where: {name: mandate.type}
|
2019-03-05 09:10:43 +00:00
|
|
|
});
|
|
|
|
|
2022-09-26 11:33:27 +00:00
|
|
|
const oldMandate = await models.Mandate.findOne({
|
2019-03-05 09:10:43 +00:00
|
|
|
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
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-26 11:33:27 +00:00
|
|
|
const loopBackContext = LoopBackContext.getCurrentContext();
|
2018-07-31 09:08:22 +00:00
|
|
|
|
2022-09-26 11:33:27 +00:00
|
|
|
changes.userFk = loopBackContext.active.accessToken.userId;
|
2018-07-31 09:08:22 +00:00
|
|
|
});
|
|
|
|
};
|