diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql index 8b2a32e5d..ba044604a 100644 --- a/db/routines/vn/procedures/stockBought_calculate.sql +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -7,13 +7,13 @@ proc: BEGIN * Calculate the stock of the auction warehouse from the inventory date to vDated * without taking into account the outputs of the same day vDated * - * @param vDated Date to calculate the stock. + * @param vDated Date to calculate the stock */ IF vDated < util.VN_CURDATE() THEN LEAVE proc; END IF; - CREATE OR REPLACE TEMPORARY TABLE tStockBought + CREATE OR REPLACE TEMPORARY TABLE tCurrentData SELECT workerFk, reserve FROM stockBought WHERE dated = vDated @@ -21,15 +21,28 @@ proc: BEGIN DELETE FROM stockBought WHERE dated = vDated; + CREATE OR REPLACE TEMPORARY TABLE tStockSold + SELECT it.workerFk, + SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000) sold + FROM itemTicketOut ito + JOIN item i ON i.id = ito.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN ticket t ON t.id = ito.ticketFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk + JOIN volumeConfig vc + WHERE ito.shipped BETWEEN vDated AND util.dayEnd(vDated) + AND wh.code = 'VNH' + GROUP BY it.workerFk; + CALL item_calculateStock(vDated); - INSERT INTO stockBought(workerFk, bought, dated) + CREATE OR REPLACE TEMPORARY TABLE tStockBought SELECT it.workerFk, - ROUND(SUM( - (ti.quantity / b.packing) * - buy_getVolume(b.id) - ) / vc.palletM3 / 1000000, 1) bought, - vDated + SUM((ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / vc.palletM3 / 1000000 bought FROM itemType it JOIN item i ON i.typeFk = it.id LEFT JOIN tmp.item ti ON ti.itemFk = i.id @@ -43,20 +56,33 @@ proc: BEGIN GROUP BY it.workerFk HAVING bought; + + INSERT INTO stockBought(workerFk, bought, dated) + SELECT tb.workerFk, + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 1), + vDated + FROM tStockBought tb + LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; + UPDATE stockBought s - JOIN tStockBought ts ON ts.workerFk = s.workerFk + JOIN tCurrentData ts ON ts.workerFk = s.workerFk SET s.reserve = ts.reserve WHERE s.dated = vDated; INSERT INTO stockBought (workerFk, reserve, dated) SELECT ts.workerFk, ts.reserve, vDated - FROM tStockBought ts + FROM tCurrentData ts WHERE ts.workerFk NOT IN ( SELECT workerFk FROM stockBought WHERE dated = vDated ); - DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate; + UPDATE stockBought s + JOIN tStockSold ts ON ts.workerFk = s.workerFk + SET s.bought = IF(s.bought < ts.sold, ROUND(s.bought - ts.sold, 1), 0) + WHERE s.dated = vDated; + + DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; END$$ DELIMITER ;