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, } ], returns: { type: ['object'], root: true }, http: { path: `/getStockBoughtDetail`, verb: 'GET' } }); Self.getStockBoughtDetail = async(workerFk, dated) => { const models = Self.app.models; await models.StockBought.rawSql(`CALL vn.item_calculateStock(?)`, [dated]); const tx = await models.Collection.beginTransaction({}); const options = {transaction: tx}; let result; try { await models.StockBought.rawSql(`CALL vn.item_calculateStock(?)`, [dated], options); result = await Self.rawSql( `SELECT b.entryFk entryFk, i.id itemFk, i.name itemName, ti.quantity, (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) / (vc.trolleyM3 * 1000000) 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], options ); await Self.rawSql(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate;`, [], options); } catch (e) { await tx.rollback(); throw e; } return result; }; };