2018-12-27 11:54:16 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
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) {
|
|
|
|
let models = Self.app.models;
|
2019-03-05 09:10:43 +00:00
|
|
|
let changes = ctx.data || ctx.instance;
|
2018-07-31 09:08:22 +00:00
|
|
|
|
2019-03-05 09:10:43 +00:00
|
|
|
let 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-03-05 09:10:43 +00:00
|
|
|
// 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
|
2018-07-31 09:08:22 +00:00
|
|
|
let filter = {where: {userFk: ctx.options.accessToken.userId}};
|
|
|
|
let worker = await Self.app.models.Worker.findOne(filter);
|
|
|
|
|
2019-03-05 09:10:43 +00:00
|
|
|
changes.workerFk = worker.id;
|
2018-07-31 09:08:22 +00:00
|
|
|
});
|
|
|
|
};
|