2022-05-02 09:18:39 +00:00
|
|
|
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'
|
2022-05-04 05:46:47 +00:00
|
|
|
}, ctx.options);
|
|
|
|
|
2022-05-02 09:18:39 +00:00
|
|
|
if (clientCredit.length > maxCreditRows) {
|
|
|
|
const creditToDestroy = [];
|
|
|
|
for (const [index, credit] of clientCredit.entries()) {
|
2022-05-04 05:46:47 +00:00
|
|
|
if (index >= maxCreditRows)
|
2022-05-02 09:18:39 +00:00
|
|
|
creditToDestroy.push(credit.id);
|
|
|
|
}
|
2022-05-03 13:17:34 +00:00
|
|
|
|
2022-05-02 09:18:39 +00:00
|
|
|
await models.ClientCredit.destroyAll({
|
|
|
|
id: {inq: creditToDestroy}
|
2022-05-04 05:46:47 +00:00
|
|
|
}, ctx.options);
|
2022-05-02 09:18:39 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|