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 => {
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);
let sales = await models.Sale.find({
include: {
relation: 'components',
scope: {fields: ['value', 'componentFk'],
include: {
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;
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
};
}
return componentsSum;
componentsSum[component.componentFk].value += component.value * sale.quantity;
}
}
return componentsSum.filter(component => {
return component != null;
});
};
};