refactor getComponentSum
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Bernat Exposito Domenech 2020-10-02 13:58:48 +02:00
parent a2232f659b
commit 161313ad15
1 changed files with 25 additions and 26 deletions

View File

@ -20,34 +20,33 @@ module.exports = Self => {
}); });
Self.getComponentsSum = async id => { Self.getComponentsSum = async id => {
const models = Self.app.models; const models = Self.app.models;
let salesComponents = [];
let componentsSum = []; let componentsSum = [];
let sales = await models.Sale.find({where: {ticketFk: id}}); let sales = await models.Sale.find({
let components = await models.Component.find(); include: {
if (sales.length > 0) { relation: 'components',
for (let sale of sales) { scope: {fields: ['value', 'componentFk'],
let myComponents = await models.SaleComponent.find({where: {saleFk: sale.id}}); include: {
salesComponents = salesComponents.concat(myComponents); relation: 'component',
} }
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]);
} }
},
acumulator[currentValue.componentFk].value += currentValue.value; where: {ticketFk: id}
return acumulator;
}); });
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
};
} }
return componentsSum; componentsSum[component.componentFk].value += component.value * sale.quantity;
}
}
return componentsSum.filter(component => {
return component != null;
});
}; };
}; };