DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`entryFromOrder`(IN vShipmentWarehouse INTEGER, IN vLandingWarehouse INTEGER, IN vItem INTEGER,
		IN vAmount INTEGER,IN vVolume INTEGER,vCost DECIMAL(10,2), IN vRetailedPrice DECIMAL(10,2), vInOutDate DATE)
BEGIN

    DECLARE vTravel INT;
    DECLARE vEntry INT;
    DECLARE vBucket VARCHAR(10);

	-- 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 = vInOutDate AND t.shipment = vInOutDate AND t.warehouse_id_out = vShipmentWarehouse 
			AND t.warehouse_id = vLandingWarehouse AND agency_id = 15
	LIMIT 1; 

    -- creamos el travel si es necesario
    IF NOT IFNULL(vTravel,0) THEN
		INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
			VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse, 15);
		SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;
    -- creamos la Entrada si es necesario
	IF NOT IFNULL(vEntry,0) THEN
		INSERT INTO Entradas (Id_Proveedor, travel_id)
				VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
		SELECT LAST_INSERT_ID() INTO vEntry;
	END IF;
   
	 -- creamos el cubo si es necesario
	SELECT Id_Cubo INTO vBucket FROM Cubos WHERE Volumen = vVolume LIMIT 1;
    
	IF NOT IFNULL(vBucket,'') > '' THEN
		INSERT INTO Cubos (Id_Cubo, Volumen)
				VALUES (CONCAT('dm',vVolume/1000), vVolume);
		SELECT LAST_INSERT_ID() INTO vBucket;
	END IF;
    
	INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, Embalajefijo,
				Comisionfija, Tarifa2, Tarifa3) 
	 VALUES(vItem,
			vAmount,
			vEntry,
			vBucket,
			1,
			1,
			0,
			vCost,
			0,
			0,
			0,
			vRetailedPrice,
			vRetailedPrice);
END$$
DELIMITER ;
