DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `stock`.`stock_sync`()
BEGIN
/**
 * Synchronizes all out of sync items. It can be called in parallel
 * since it generates a lock for each item (and warehouse) synchronization
 * process, see stock_syncItem().
 */
	DECLARE vDone BOOL;
	DECLARE vWarehouseFk INT;
	DECLARE vItemFk INT;

	DECLARE vItems CURSOR FOR
		SELECT itemFk, warehouseFk FROM buyLot WHERE !isSync
		UNION
		SELECT itemFk, warehouseFk FROM buyOut WHERE !isSync;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	OPEN vItems;
	itemLoop: LOOP
		SET vDone = FALSE;
		FETCH vItems INTO vItemFk, vWarehouseFk;

		IF vDone THEN
			LEAVE itemLoop;
		END IF;

		CALL stock_syncItem(vItemFk, vWarehouseFk, 0);
	END LOOP;
	CLOSE vItems;
END$$
DELIMITER ;
