From 86b7e9cabe7b214ef019062b13cbf5299b91fd7c Mon Sep 17 00:00:00 2001 From: vicent Date: Fri, 14 Oct 2022 14:30:37 +0200 Subject: [PATCH] fix: only can exists 'mana' or 'manaClaim' discount. Never both --- .../back/methods/ticket/updateDiscount.js | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index b1291a45b..99daac512 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -115,10 +115,43 @@ module.exports = Self => { for (let sale of sales) { const oldDiscount = sale.discount; const value = ((-sale.price * newDiscount) / 100); - const newComponent = models.SaleComponent.upsert({ - saleFk: sale.id, - value: value, - componentFk: componentId}, myOptions); + + const manaComponent = await models.Component.findOne({ + where: {code: 'mana'} + }, myOptions); + + const manaClaimComponent = await models.Component.findOne({ + where: {code: 'manaClaim'} + }, myOptions); + + const oldComponent = await models.SaleComponent.find({ + where: { + and: [ + {saleFk: sale.id}, + {componentFk: {inq: [manaComponent.id, manaClaimComponent.id]}} + ] + } + }, myOptions); + + let newComponent; + if (oldComponent) { + const filter = { + saleFk: sale.id, + componentFk: oldComponent.componentFk + }; + await models.SaleComponent.destroyAll(filter, myOptions); + + newComponent = models.SaleComponent.create({ + saleFk: sale.id, + value: value, + componentFk: componentId + }, myOptions); + } else { + newComponent = models.SaleComponent.create({ + saleFk: sale.id, + value: value, + componentFk: componentId}, myOptions); + } const updatedSale = sale.updateAttribute('discount', newDiscount, myOptions);