DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`newItem`(IN vTicket INTEGER, IN vVolume INTEGER, IN vQuantity INTEGER)
BEGIN
	
	DECLARE vLandingWarehouse INT;
	DECLARE vLandingDate DATE;
    DECLARE vShipmentDate DATE;
    DECLARE vTravel INT;
    DECLARE vEntry INT;

	SELECT warehouse_id, Fecha, landing INTO vLandingWarehouse, vShipmentDate, vLandingDate FROM Tickets WHERE Id_Ticket = vTicket;

	-- seleccionamos travel
	SELECT id, Id_Entrada INTO vTravel, vEntry
		FROM travel t LEFT JOIN Entradas e ON t.id = e.travel_id
        WHERE t.landing = vLandingDate AND t.shipment = vShipmentDate AND t.warehouse_id_out = vLandingWarehouse AND t.warehouse_id = vWarehouse
			AND t.delivered = FALSE ; -- agency ??
	
    -- creamos el travel si es necesario
    IF NOT vTravel THEN
		INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
			VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, a);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    
    -- creamos la Entrada si es necesario
	IF NOT vEntry THEN
		INSERT INTO Entradas (Id_Proveedor, travel_id)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	END IF;

END$$
DELIMITER ;
