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

29 lines
903 B
JavaScript

module.exports = Self => {
Self.observe('after save', async ctx => {
const instance = ctx.instance;
const models = Self.app.models;
const clientConfig = await models.ClientConfig.findOne({
where: {id: 1}
});
const maxCreditRows = clientConfig.maxCreditRows;
const clientCredit = await models.ClientCredit.find({
where: {clientFk: instance.clientFk},
order: 'created DESC'
}, ctx.options);
if (clientCredit.length > maxCreditRows) {
const creditToDestroy = [];
for (const [index, credit] of clientCredit.entries()) {
if (index >= maxCreditRows)
creditToDestroy.push(credit.id);
}
await models.ClientCredit.destroyAll({
id: {inq: creditToDestroy}
}, ctx.options);
}
});
};