salix/modules/client/back/models/client-sample.js

59 lines
1.8 KiB
JavaScript
Raw Normal View History

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-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
if (sample.hasCompany && !changes.companyFk)
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;
});
// 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}
});
2022-09-26 11:33:27 +00:00
const 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
});
}
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
});
};