DROP procedure IF EXISTS `vn`.`collection_updateSale`;


DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`collection_updateSale`(
	vSaleFk INT,
    vOriginalQuantity INT,
    vWorkerFk INT,
    vStateFk INT,
    vTicketFk INT)
BEGIN
	
    DECLARE vNumPrepared INT;
	DECLARE vNumTotal INT;

	REPLACE INTO vn.saleTracking(saleFk,isChecked, originalQuantity, workerFk, actionFk,stateFk) 
		VALUES(vSaleFk,1,vOriginalQuantity,vWorkerFk,vStateFk,vStateFk);
        
	UPDATE vn.sale SET isPicked = 1 
    WHERE id = vSaleFk;
        
	SELECT COUNT(s.id) INTO vNumPrepared
    FROM vn.sale s
    WHERE s.ticketFk = vTicketFk AND s.isPicked = 1;
    
    SELECT COUNT(s.id) INTO vNumTotal
    FROM vn.sale s
    WHERE s.ticketFk = vTicketFk;
    
    IF vNumPrepared = vNumTotal THEN
    
		INSERT INTO vncontrol.inter
		SET state_id = vStateFk, Id_Ticket = vTicketFk, Id_Trabajador = vWorkerFk;
        
        CALL vn.collection_update(vTicketFk);
        
	END IF;
	
    
END$$

DELIMITER ;