DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT)
	RETURNS int(11)
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN
	
	/**
	 * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén.
	 * Si no existe lo genera.
	 * 
	 * @param vLanded Fecha de llegada al almacén
	 * @param vWarehouseFk Identificador de vn.warehouse
	 */

	DECLARE vTravelFk INT;

	IF vLanded THEN
	
		SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk 
			FROM vn.travel tr
				JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
				JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
            		JOIN vn.agencyMode am ON am.id = tr.agencyModeFk
			WHERE wIn.id = vWarehouseFk
				AND wOut.name = 'Holanda'
                	AND am.name = 'LOGIFLORA'
				AND landed = vLanded;

		IF NOT vTravelFk THEN
		
			INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk)
				SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id 
					FROM vn.warehouse wOut 
						JOIN vn.agencyMode am ON am.name = 'LOGIFLORA'
					WHERE wOut.name = 'Holanda';
					
			SELECT MAX(tr.id) INTO vTravelFk 
				FROM vn.travel tr
					JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk
					JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk
						WHERE wIn.id = vWarehouseFk
							AND wOut.name = 'Holanda'
							AND landed = vLanded;
		END IF;
        
	END IF;
    
	RETURN vTravelFk;
    
END$$
DELIMITER ;
