DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`getAlert3StateTest`(vTicket INT)
	RETURNS varchar(45) CHARSET latin1 COLLATE latin1_swedish_ci
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN
	DECLARE vDeliveryType INTEGER DEFAULT 0;
		DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
		DECLARE vCode VARCHAR(45);
		
	SELECT 
		a.Vista
	INTO vDeliveryType 
		FROM vn2008.Tickets t
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
	WHERE Id_Ticket = vTicket;
		
		CASE vDeliveryType
			WHEN 1 THEN -- AGENCIAS
				SET vCode = 'DELIVERED';
					   
			WHEN 2 THEN -- REPARTO
				SET vCode = 'ON_DELIVERY';
					
			ELSE -- MERCADO, OTROS
				SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp
					FROM vn2008.Tickets t 
						LEFT JOIN vn2008.warehouse_pickup w 
							ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id
					WHERE t.Id_Ticket = vTicket;
						
			IF isWaitingForPickUp THEN
				SET vCode = 'WAITING_FOR_PICKUP';
					ELSE
				SET vCode = 'DELIVERED';
			END IF;
		END CASE;
	RETURN vCode;
END$$
DELIMITER ;
