DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT)
	RETURNS tinyint(1)
	DETERMINISTIC
BEGIN
/**
* Comprueba si las expediciones del pallet son todas
* de la misma ruta.
*
* @param vExpeditionFk numero de expedition a comprobar
* @param vPalletFk numero de pallet
* @return vHasDistinctRoutes
*/
	DECLARE vRouteFk INT;
	DECLARE vHasDistinctRoutes BOOL;

	SELECT t.routeFk INTO vRouteFk
		FROM vn.expedition e 
			JOIN vn.ticket t ON e.ticketFk = t.id
		WHERE e.id = vExpeditionFk;
	
	SELECT COUNT(*) > 0 INTO vHasDistinctRoutes
		FROM vn.expeditionScan es
			JOIN vn.expedition e ON es.expeditionFk = e.id
			JOIN vn.ticket t ON e.ticketFk = t.id
				WHERE es.palletFk = vPalletFk
				AND t.routeFk <> vRouteFk;
		
	RETURN vHasDistinctRoutes;

END$$
DELIMITER ;
