DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`entryFromTicket`(IN vTicket INTEGER, IN vLandingWarehouse INTEGER)
BEGIN

    DECLARE vShipmentWarehouse INT;
    DECLARE vLandingDate DATE;
    DECLARE vShipmentDate DATE;
    DECLARE vTravel INT;
    DECLARE vEntry INT;

    SELECT warehouse_id, Fecha, Fecha INTO vShipmentWarehouse, 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 = vShipmentWarehouse 
            AND t.warehouse_id = vLandingWarehouse
            AND agency_id = 15
        LIMIT 1;

    -- creamos el travel si es necesario
    IF vTravel IS NULL THEN 
   		SELECT vLandingDate;
	    INSERT INTO travel (shipment, landing, warehouse_id, warehouse_id_out, agency_id)
	        VALUES (vShipmentDate, vLandingDate, vLandingWarehouse, vShipmentWarehouse, 15);
        SELECT LAST_INSERT_ID() INTO vTravel;
    END IF;

    -- creamos la Entrada si es necesario
    IF vEntry IS NULL THEN
        INSERT INTO Entradas (Id_Proveedor, travel_id)
            VALUES (13, vTravel); -- proveedor 'MOVIMIENTO ALMACEN'
        SELECT LAST_INSERT_ID() INTO vEntry;
    END IF;

    CALL vn.buyUltimate(vShipmentWarehouse,vShipmentDate);   

    INSERT INTO Compres(Id_Article,Cantidad, Id_Entrada, Id_Cubo, Packing, `grouping`, caja, Costefijo, Portefijo, Embalajefijo, Comisionfija, Tarifa2, Tarifa3) 
     SELECT m.Id_Article,
            m.Cantidad,
            vEntry,
            c.Id_Cubo,
            c.Packing,
            IF(c.`grouping`,c.`grouping`,1),
            c.caja,
            Costefijo,
            c.Portefijo,
            c.Embalajefijo,
            c.Comisionfija,
            m.Preu Tarifa2,
            m.Preu Tarifa3
        FROM Movimientos m
            JOIN Articles a ON m.Id_Article = a.Id_Article
            LEFT JOIN tmp.buyUltimate b ON m.Id_Article = b.itemFk AND b.warehouseFk = vShipmentWarehouse
            LEFT JOIN Compres c ON c.Id_Compra = b.buyFk
        WHERE m.Id_Ticket = vTicket;
END$$
DELIMITER ;
