82 lines
2.5 KiB
JavaScript
82 lines
2.5 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethod('getWasteByWorker', {
|
|
description: 'Returns the details of losses by worker',
|
|
accessType: 'READ',
|
|
accepts: [],
|
|
returns: {
|
|
type: ['object'],
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/getWasteByWorker`,
|
|
verb: 'GET'
|
|
}
|
|
});
|
|
|
|
Self.getWasteByWorker = async options => {
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
const date = Date.vnNew();
|
|
date.setHours(0, 0, 0, 0);
|
|
const wastes = await Self.rawSql(`
|
|
SELECT *, 100 * dwindle / total AS percentage
|
|
FROM (
|
|
SELECT buyer,
|
|
ws.family,
|
|
sum(ws.saleTotal) AS total,
|
|
sum(ws.saleWaste) AS dwindle
|
|
FROM bs.waste ws
|
|
WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?))
|
|
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1)
|
|
GROUP BY buyer, family
|
|
) sub
|
|
ORDER BY percentage DESC`, [date, date], myOptions);
|
|
|
|
const wastesTotal = await Self.rawSql(`
|
|
SELECT *, 100 * dwindle / total AS percentage
|
|
FROM (
|
|
SELECT buyer,
|
|
sum(ws.saleTotal) AS total,
|
|
sum(ws.saleWaste) AS dwindle
|
|
FROM bs.waste ws
|
|
WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?))
|
|
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1)
|
|
GROUP BY buyer
|
|
) sub
|
|
ORDER BY percentage DESC`, [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,
|
|
lines: []
|
|
};
|
|
details.push(buyerDetail);
|
|
}
|
|
|
|
buyerDetail.lines.push(waste);
|
|
}
|
|
|
|
for (let waste of details) {
|
|
let buyerTotal = wastesTotal.find(totals => {
|
|
return waste.buyer == totals.buyer;
|
|
});
|
|
|
|
Object.assign(waste, buyerTotal);
|
|
}
|
|
|
|
return details;
|
|
};
|
|
};
|