DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_setProblemRounding`(
	vSelf INT
)
BEGIN
/**
 * Update the rounding problem for the sales lines of a ticket
 *
 * @param vSelf Id de ticket
 */
	DECLARE vWarehouseFk INT;
	DECLARE vDated DATE;

	SELECT warehouseFk, shipped 
			INTO vWarehouseFk, vDated
		FROM ticket
		WHERE id = vSelf;

	CALL buy_getUltimate(NULL, vWarehouseFk, vDated);	
	
	CREATE OR REPLACE TEMPORARY TABLE tmp.sale
		(INDEX(saleFk, isProblemCalcNeeded)) 
		SELECT s.id saleFk , 
				MOD(s.quantity, b.`grouping`) hasProblem, 
				ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
			FROM ticket t
				JOIN sale s ON s.ticketFk = t.id
				JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
				JOIN buy b ON b.id = bu.buyFk
			WHERE t.id = vSelf;

	CALL sale_setProblem('hasRounding');

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