USE `vn`;
DROP procedure IF EXISTS `ticketComponentUpdate`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentUpdate`(
	 vTicketFk INT,
     vClientFk INT,
     vAgencyModeFk INT,
     vAddressFk INT,
     vWarehouseFk TINYINT,
     vCompanyFk SMALLINT,
     vShipped DATETIME,
     vLanded DATE,
     vIsDeleted BOOLEAN,
     vHasToBeUnrouted BOOLEAN,
     vOption INT)
BEGIN

    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	START TRANSACTION;
    
	UPDATE ticket t 
		SET 
			t.clientFk = vClientFk,
			t.agencyModeFk = vAgencyModeFk,
			t.addressFk = vAddressFk,
			t.warehouseFk = vWarehouseFk,
            t.companyFk = vCompanyFk,
			t.landed = vLanded,
			t.shipped = vShipped,
            t.isDeleted = vIsDeleted
		WHERE
			t.id = vTicketFk;
            
	IF vHasToBeUnrouted THEN
		UPDATE ticket t SET t.routeFk = NULL
			WHERE t.id = vTicketFk;
    END IF;
            
	IF vOption <> 8 THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.sale;
		CREATE TEMPORARY TABLE tmp.sale
			(PRIMARY KEY (saleFk))
            ENGINE = MEMORY
			SELECT id AS saleFk, vWarehouseFk warehouseFk
				FROM sale s WHERE s.ticketFk = vTicketFk;

		CALL ticketComponentUpdateSale (vOption);

        DROP TEMPORARY TABLE tmp.sale;
	END IF;
	COMMIT;
END$$

DELIMITER ;

