77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethod('getWasteByItem', {
|
|
description: 'Returns the details of losses by worker and item',
|
|
accessType: 'READ',
|
|
accepts: [
|
|
{
|
|
arg: 'buyer',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'The buyer name'
|
|
},
|
|
{
|
|
arg: 'family',
|
|
type: 'string',
|
|
required: true,
|
|
description: 'The item family name'
|
|
}
|
|
],
|
|
returns: {
|
|
type: ['object'],
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/getWasteByItem`,
|
|
verb: 'GET'
|
|
}
|
|
});
|
|
|
|
Self.getWasteByItem = async(buyer, family, options) => {
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
const date = new Date();
|
|
date.setHours(0, 0, 0, 0);
|
|
const wastes = await Self.rawSql(`
|
|
SELECT *, 100 * dwindle / total AS percentage
|
|
FROM (
|
|
SELECT buyer,
|
|
ws.family,
|
|
ws.itemFk,
|
|
sum(ws.saleTotal) AS total,
|
|
sum(ws.saleWaste) AS dwindle
|
|
FROM bs.waste ws
|
|
WHERE buyer = ? AND family = ?
|
|
AND year = YEAR(TIMESTAMPADD(WEEK,-1, ?))
|
|
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1)
|
|
GROUP BY buyer, itemFk
|
|
) sub
|
|
ORDER BY family, percentage DESC`, [buyer, family, date, date], myOptions);
|
|
|
|
const details = [];
|
|
|
|
for (let waste of wastes) {
|
|
const buyerName = waste.buyer;
|
|
|
|
let buyerDetail = details.find(waste => {
|
|
return waste.buyer == buyerName;
|
|
});
|
|
|
|
if (!buyerDetail) {
|
|
buyerDetail = {
|
|
buyer: buyerName,
|
|
family: waste.family,
|
|
lines: []
|
|
};
|
|
details.push(buyerDetail);
|
|
}
|
|
|
|
buyerDetail.lines.push(waste);
|
|
}
|
|
|
|
return details;
|
|
};
|
|
};
|