From 161313ad15b69235d0f73d5cd16e7cf34d77b24f Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 2 Oct 2020 13:58:48 +0200 Subject: [PATCH] refactor getComponentSum --- .../back/methods/ticket/getComponentsSum.js | 51 +++++++++---------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/modules/ticket/back/methods/ticket/getComponentsSum.js b/modules/ticket/back/methods/ticket/getComponentsSum.js index c5333288e..c611913d8 100644 --- a/modules/ticket/back/methods/ticket/getComponentsSum.js +++ b/modules/ticket/back/methods/ticket/getComponentsSum.js @@ -20,34 +20,33 @@ module.exports = Self => { }); Self.getComponentsSum = async id => { const models = Self.app.models; - let salesComponents = []; let componentsSum = []; - let sales = await models.Sale.find({where: {ticketFk: id}}); - let components = await models.Component.find(); - if (sales.length > 0) { - for (let sale of sales) { - let myComponents = await models.SaleComponent.find({where: {saleFk: sale.id}}); - salesComponents = salesComponents.concat(myComponents); - } - - salesComponents.reduce((acumulator, currentValue) => { - if (!acumulator[currentValue.componentFk]) { - let defaultValue = 0; - let tarjetComponent = components.find(component => component.id === currentValue.componentFk); - - acumulator[currentValue.componentFk] = { - componentFk: currentValue.componentFk, - value: defaultValue, - name: tarjetComponent.name - }; - componentsSum.push(acumulator[currentValue.componentFk]); + let sales = await models.Sale.find({ + include: { + relation: 'components', + scope: {fields: ['value', 'componentFk'], + include: { + relation: 'component', + } } - - acumulator[currentValue.componentFk].value += currentValue.value; - - return acumulator; - }); + }, + where: {ticketFk: id} + }); + for (let sale of sales) { + for (let component of sale.components()) { + let componentId = componentsSum[component.componentFk]; + if (!componentId) { + componentsSum[component.componentFk] = { + componentFk: component.componentFk, + value: 0, + name: component.component().name + }; + } + componentsSum[component.componentFk].value += component.value * sale.quantity; + } } - return componentsSum; + return componentsSum.filter(component => { + return component != null; + }); }; };