DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` FUNCTION `vn`.`barcodeToItem`(vBarcode VARCHAR(22))
	RETURNS int(11)
	DETERMINISTIC
BEGIN
	
/**
 * Obtiene el id del artículo
 *
 * @param vBarcode código de barras
 * 
 * return id del item
 */

	DECLARE vItemFk INT;

	SELECT id INTO vItemFk
		FROM vn.item
        WHERE id = vBarcode OR comment = vBarcode
       	LIMIT 1;
        
	IF vItemFk THEN 
		RETURN vItemFk;
	END IF;

	SELECT itemFk INTO vItemFk 
		FROM buy 
        WHERE id = vBarcode;
	
    IF vItemFk THEN 
		RETURN vItemFk;
	END IF;
    
	SELECT itemFk INTO vItemFk 
		FROM itemBarcode 
        WHERE code = vBarcode;
       
   IF vItemFk THEN 
		RETURN vItemFk;
	END IF;

	SELECT i.id INTO vItemFk 
	        	FROM vn.item i
	        	WHERE i.name LIKE CONCAT('%',vBarcode,'%')
	        	ORDER BY i.id ASC
	       		LIMIT 1;
	       
	RETURN vItemFk;
    
END$$
DELIMITER ;
