module.exports = Self => { Self.observe('after save', async ctx => { const instance = ctx.instance; const models = Self.app.models; const clientConfig = await models.ClientConfig.findOne(); const maxCreditRows = clientConfig.maxCreditRows; const clientCredit = await models.ClientCredit.find({ where: {clientFk: instance.clientFk}, order: 'created DESC', limit: maxCreditRows }, ctx.options); const lastCredit = clientCredit[maxCreditRows - 1]; if (lastCredit) { await models.ClientCredit.destroyAll({ clientFk: instance.clientFk, created: {lt: lastCredit.created} }, ctx.options); } }); };