DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_setProblemRounding`(
	vSelf INT
)
BEGIN
/**
 * Update the rounding problem for a sales line
 * @param vSelf Id sale
 */
	DECLARE vItemFk INT;
	DECLARE vWarehouseFk INT;
	DECLARE vShipped DATE;
	DECLARE vQuantity INT;

	SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity 
			INTO vItemFk, vWarehouseFk, vShipped, vQuantity
		FROM sale s 
			JOIN ticket t ON t.id = s.ticketFk 
		WHERE s.id = vSelf;

	CALL buyUltimate(vWarehouseFk, vShipped);	
	
	CREATE OR REPLACE TEMPORARY TABLE tmp.sale 
		SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem
			FROM tmp.buyUltimate bu
				JOIN buy b ON b.id = bu.buyFk
			WHERE bu.itemFk = vItemFk;

	CALL sale_setProblem('hasRounding');

	DROP TEMPORARY TABLE tmp.sale;
	DROP TEMPORARY TABLE tmp.buyUltimate;
END$$
DELIMITER ;