salix/modules/ticket/back/methods/ticket/getComponentsSum.js

58 lines
1.8 KiB
JavaScript

module.exports = Self => {
Self.remoteMethod('getComponentsSum', {
description: 'Returns a list of component and their sum from a ticket',
accessType: 'READ',
accepts: {
arg: 'id',
type: 'number',
required: true,
description: 'ticket id',
http: {source: 'path'}
},
returns: {
type: 'number',
root: true
},
http: {
path: `/:id/getComponentsSum`,
verb: 'GET'
}
});
Self.getComponentsSum = async(id, options) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const componentsSum = [];
const sales = await models.Sale.find({
include: {
relation: 'components',
scope: {fields: ['value', 'componentFk'],
include: {
relation: 'component',
}
}
},
where: {ticketFk: id}
}, myOptions);
for (let sale of sales) {
for (let component of sale.components()) {
const 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.filter(component => {
return component != null;
});
};
};