DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBought_calculate`(
	vDated DATE
)
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.
 */
	IF vDated < util.VN_CURDATE() THEN
		LEAVE proc;
	END IF;

	CREATE OR REPLACE TEMPORARY TABLE tStockBought
		SELECT workerFk, reserve 
			FROM stockBought 
			WHERE dated = vDated
				AND reserve;

	DELETE FROM stockBought WHERE dated = vDated;

	CALL item_calculateStock(vDated);

	INSERT INTO stockBought(workerFk, bought, dated)
		SELECT it.workerFk,
				ROUND(SUM(
						(ti.quantity / b.packing) *
						buy_getVolume(b.id)
					) / vc.palletM3 / 1000000, 1) bought,
				vDated
			FROM itemType it
				JOIN item i ON i.typeFk = it.id
				LEFT JOIN tmp.item ti ON ti.itemFk = i.id
				JOIN itemCategory ic ON ic.id = it.categoryFk
				JOIN warehouse wh ON wh.code = 'VNH'
				JOIN tmp.buyUltimate bu ON bu.itemFk = i.id 
					AND bu.warehouseFk = wh.id
				JOIN buy b ON b.id = bu.buyFk
				JOIN volumeConfig vc
			WHERE ic.display
			GROUP BY it.workerFk
			HAVING bought;

	UPDATE stockBought s
			JOIN tStockBought 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
			WHERE ts.workerFk NOT IN (
				SELECT workerFk
					FROM stockBought
					WHERE dated = vDated
			);

	DROP TEMPORARY TABLE tStockBought, tmp.item, tmp.buyUltimate;
END$$
DELIMITER ;
