DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`buyOut_refreshSale`(
	`vTable` VARCHAR(255),
	`vId` INT)
BEGIN
	DECLARE vAliveDate DATE;

	SELECT util.VN_CURDATE() - INTERVAL saleLife MONTH
		INTO vAliveDate
		FROM config LIMIT 1;

	CREATE OR REPLACE TEMPORARY TABLE tLotStatus
		ENGINE = MEMORY
		SELECT lotFk,
				@isExcluded := s.quantity < 0 isExcluded,
				NOT @isExcluded AND t.shipped >= vAliveDate isIncluded
			FROM vn.sale s
				JOIN vn.ticket t ON t.id = s.ticketFk
			WHERE
				   (vTable = 'lot' AND s.lotFk = vId)
				OR (vTable = 'ticket' AND t.id = vId);

	CREATE OR REPLACE TEMPORARY TABLE tLotAlive
		ENGINE = MEMORY
		SELECT
				oo.lotFk,
				t.warehouseFk,
				t.shipped dated,
				s.itemFk,
				s.quantity,
				s.created,
				s.isPicked
			FROM tLotStatus oo
				JOIN vn.sale s ON s.lotFk = oo.lotFk
				JOIN vn.ticket t ON t.id = s.ticketFk
			WHERE oo.isIncluded;

	CALL buyOut_refresh(vTable, vId, 'sale');

	DROP TEMPORARY TABLE tLotStatus, tLotAlive;
END$$
DELIMITER ;
