const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('getStockBoughtDetail', { description: 'Returns the detail of stock bought for a given date and a worker', accessType: 'READ', accepts: [{ arg: 'workerFk', type: 'number', description: 'The worker to filter', required: true, }, { arg: 'dated', type: 'string', description: 'The date to filter', required: true, }, { arg: 'filter', type: 'object', } ], returns: { type: ['object'], root: true }, http: { path: `/getStockBoughtDetail`, verb: 'GET' } }); Self.getStockBoughtDetail = async(workerFk, dated, filter, options) => { const conn = Self.dataSource.connector; const myOptions = {}; let tx; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const stmts = []; stmts.push(new ParameterizedSQL(`CALL vn.item_calculateStock(?)`, [dated])); const query = new ParameterizedSQL( `SELECT b.entryFk entryFk, i.id itemFk, i.name itemName, ti.quantity, ROUND((ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id) ) / (vc.trolleyM3 * 1000000), 2) volume, b.packagingFk packagingFk, b.packing FROM tmp.item ti JOIN item i ON i.id = ti.itemFk JOIN itemType it ON i.typeFk = it.id JOIN itemCategory ic ON ic.id = it.categoryFk JOIN worker w ON w.id = it.workerFk JOIN auctionConfig ac JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = ac.warehouseFk JOIN buy b ON b.id = bu.buyFk JOIN volumeConfig vc WHERE ic.display AND w.id = ?`, [workerFk] ); stmts.push(query.merge(conn.makeSuffix(filter))); stmts.push(new ParameterizedSQL(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate`)); const sql = ParameterizedSQL.join(stmts, ';'); const result = await conn.executeStmt(sql, myOptions); if (tx) await tx.commit(); return result[1]; } catch (e) { await tx.rollback(); throw e; } }; };