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

117 lines
3.6 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('getSales', {
description: 'New filter',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/:id/getSales`,
verb: 'get'
}
});
Self.getSales = async(ctx, id, options) => {
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
if (typeof options == 'object')
Object.assign(myOptions, options);
const sales = await models.Sale.find({
include: {
relation: 'item',
scope: {
fields: [
'id',
'name',
'subName',
'itemPackingTypeFk',
'size',
'tag5',
'value5',
'tag6',
'value6',
'tag7',
'value7',
'tag8',
'value8',
'tag9',
'value9',
'tag10',
'value10'
]
}
},
where: {ticketFk: id},
order: 'concept'
}, myOptions);
// Get items available
const query = `CALL ticketGetVisibleAvailable(?)`;
const [salesAvailable] = await Self.rawSql(query, [id], myOptions);
const itemAvailable = new Map();
for (let sale of salesAvailable) {
itemAvailable.set(sale.itemFk, {
visible: sale.visible,
available: sale.available
});
}
// Get claimed sales
const saleIds = sales.map(sale => sale.id);
const claims = await models.ClaimBeginning.find({
fields: ['claimFk', 'saleFk'],
where: {saleFk: {inq: saleIds}},
}, myOptions);
const claimedSales = new Map();
for (let claim of claims)
claimedSales.set(claim.saleFk, claim);
// Get problems
const problemsQuery = `CALL sale_getProblemsByTicket(?, FALSE)`;
const [problems] = await Self.rawSql(problemsQuery, [id], myOptions);
const saleProblems = new Map();
for (let problem of problems)
saleProblems.set(problem.saleFk, problem);
const ticketLog = await Self.rawSql(`SELECT DISTINCT changedModelId
FROM ticketLog tl
WHERE changedModel = 'Sale'
AND originFk = ?`, [id], myOptions);
const salesWithLogs = ticketLog.map(sale => {
return sale.changedModelId;
});
for (let sale of sales) {
const problems = saleProblems.get(sale.id);
const itemStock = itemAvailable.get(sale.itemFk);
sale.available = itemStock.available;
sale.visible = itemStock.visible;
sale.claim = claimedSales.get(sale.id);
if (problems) {
sale.itemShortage = problems.itemShortage;
sale.hasTicketRequest = problems.hasTicketRequest;
sale.hasComponentLack = problems.hasComponentLack;
}
if (salesWithLogs.includes(sale.id))
sale.$hasLogs = true;
}
return sales;
};
};