DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`ticketComponentUpdate`(
	 vTicketFk INT,
	vClientFk INT,
	vAgencyModeFk INT,
	vAddressFk INT,
	vWarehouseFk TINYINT,
	vCompanyFk SMALLINT,
	vShipped DATETIME,
	vLanded DATE,
	vIsDeleted BOOLEAN,
	vHasToBeUnrouted BOOLEAN,
	vOption VARCHAR(25))
BEGIN

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

	START TRANSACTION;

	IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
	
		UPDATE ticket t 
				JOIN address a ON a.id = vAddressFk
			SET t.nickname = a.nickname
			WHERE t.id = vTicketFk;
	END IF;

	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;

	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;
	COMMIT;
END$$
DELIMITER ;
