diff --git a/modules/client/back/models/client-credit.js b/modules/client/back/models/client-credit.js index 96ac5a22a..01fe8214a 100644 --- a/modules/client/back/models/client-credit.js +++ b/modules/client/back/models/client-credit.js @@ -3,28 +3,21 @@ module.exports = Self => { const instance = ctx.instance; const models = Self.app.models; - const clientConfig = await models.ClientConfig.findOne({ - where: {id: 1} - }); + const clientConfig = await models.ClientConfig.findOne(); const maxCreditRows = clientConfig.maxCreditRows; const clientCredit = await models.ClientCredit.find({ where: {clientFk: instance.clientFk}, - order: 'created DESC' - }); - if (clientCredit.length > maxCreditRows) { - const creditToDestroy = []; - for (const [index, credit] of clientCredit.entries()) { - console.log(index); - if (index >= maxCreditRows) { - console.log(index, 'BORRAR'); - creditToDestroy.push(credit.id); - } - } + order: 'created DESC', + limit: maxCreditRows + }, ctx.options); + const lastCredit = clientCredit[maxCreditRows - 1]; + if (lastCredit) { await models.ClientCredit.destroyAll({ - id: {inq: creditToDestroy} - }); + clientFk: instance.clientFk, + created: {lt: lastCredit.created} + }, ctx.options); } }); }; diff --git a/modules/client/back/models/specs/clientCredit.spec.js b/modules/client/back/models/specs/clientCredit.spec.js index 4d4c2bdee..7a42b7531 100644 --- a/modules/client/back/models/specs/clientCredit.spec.js +++ b/modules/client/back/models/specs/clientCredit.spec.js @@ -16,8 +16,8 @@ describe('Client Credit', () => { const ctx = {options}; const salesAssistant = await models.Account.findOne({ where: {name: 'salesAssistant'} - }, options); - ctx.options.accessToken = {userId: salesAssistant.id}; + }, ctx.options); + await models.ClientCredit.create({ amount: 355, clientFk: instance.id, @@ -25,8 +25,8 @@ describe('Client Credit', () => { }, ctx.options); rowsAfter = await models.ClientCredit.find({ - where: {clientFk: instance.id} - }, options); + where: {clientFk: instance.id}, + }, ctx.options); await tx.rollback(); } catch (e) {