salix/modules/entry/back/methods/entry/lastItemBuys.js

92 lines
2.7 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethod('lastItemBuys', {
description: 'Returns a list of items from last buys',
accepts: [
{
arg: 'id',
type: 'number',
required: true,
description: 'origin itemId',
http: {source: 'path'}
},
{
arg: 'filter',
type: 'object',
description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string`
}
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/:id/lastItemBuys`,
verb: 'GET'
}
});
Self.lastItemBuys = async(id, filter, options) => {
const conn = Self.dataSource.connector;
const models = Self.app.models;
const where = {isActive: true};
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
filter = mergeFilters(filter, {where});
const entry = await models.Entry.findById(id, {
include: [{
relation: 'travel',
scope: {
fields: ['warehouseInFk', 'landed'],
}
}]
}, myOptions);
const travel = entry.travel();
const stmts = [];
let stmt;
stmt = new ParameterizedSQL(`CALL buyUltimate(?, ?)`, [
travel.warehouseInFk,
travel.landed
]);
stmts.push(stmt);
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.item');
stmt = new ParameterizedSQL(
`CREATE TEMPORARY TABLE tmp.item
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT
i.*,
p.name AS producerName,
nk.name AS inkName
FROM item i
JOIN producer p ON p.id = i.producerFk
JOIN ink nk ON nk.id = i.inkFk
JOIN tmp.buyUltimate bu ON i.id = bu.itemFk
AND bu.warehouseFk = ?
`, [travel.warehouseInFk]);
stmts.push(stmt);
stmt = new ParameterizedSQL('SELECT * FROM tmp.item');
stmt.merge(conn.makeSuffix(filter));
const itemsIndex = stmts.push(stmt) - 1;
stmts.push('DROP TEMPORARY TABLE tmp.item');
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
return result[itemsIndex];
};
};