97 lines
3.0 KiB
JavaScript
97 lines
3.0 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 models = Self.app.models;
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
const user = await models.VnUser.findOne({
|
|
fields: ['id'],
|
|
where: {name: buyer}
|
|
});
|
|
|
|
const itemType = await models.ItemType.findOne({
|
|
fields: ['id'],
|
|
where: {name: family}
|
|
}, options);
|
|
|
|
const date = Date.vnNew();
|
|
date.setHours(0, 0, 0, 0);
|
|
const wastes = await Self.rawSql(`
|
|
SELECT *, 100 * dwindle / total percentage
|
|
FROM (
|
|
SELECT u.name buyer,
|
|
it.name family,
|
|
w.itemFk,
|
|
SUM(w.saleTotal) total,
|
|
SUM(
|
|
w.saleExternalWaste +
|
|
w.saleFaultWaste +
|
|
w.saleContainerWaste +
|
|
w.saleBreakWaste +
|
|
w.saleOtherWaste
|
|
) dwindle
|
|
FROM bs.waste w
|
|
JOIN account.user u ON u.id = w.buyerFk
|
|
JOIN vn.itemType it ON it.id = w.itemTypeFk
|
|
WHERE w.buyerFk = ? AND w.itemTypeFk = ?
|
|
AND w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
|
|
AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
|
|
GROUP BY w.buyerFk, w.itemFk
|
|
) sub
|
|
ORDER BY family, percentage DESC
|
|
`, [user.id, itemType.id, 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;
|
|
};
|
|
};
|