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

51 lines
1.5 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.validatesPresenceOf('typeFk', {
message: 'Sample type cannot be blank'
});
Self.observe('before save', async function(ctx) {
let models = Self.app.models;
let changes = ctx.data || ctx.instance;
let sample = await models.Sample.findById(changes.typeFk);
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);
changes.workerFk = worker.id;
});
};