DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`historico_absoluto`(IN idART INT, IN wh INT, IN datfecha DATETIME)
BEGIN

	DECLARE inv_calculado INT;
	DECLARE inv INT;
	DECLARE today DATETIME;
	DECLARE fecha_inv DATETIME;
	
	SET today = util.VN_CURDATE();

	CREATE OR REPLACE TEMPORARY TABLE historico_pasado
		SELECT *
			FROM (
				SELECT TR.landing Fecha,
						C.Cantidad Entrada,
						NULL Salida,
						(TR.received != FALSE) OK,
						P.Proveedor Alias,
						E.Referencia Referencia,
						E.Id_Entrada id,
						TR.delivered F5
					FROM Compres C -- mirar perque no entra en received
						INNER JOIN Entradas E USING (Id_Entrada)
						INNER JOIN travel TR ON TR.id = E.travel_id
						INNER JOIN Proveedores P USING (Id_Proveedor)
					WHERE TR.landing >= '2001-01-01'
						AND Id_proveedor <> 4
						AND wh IN (TR.warehouse_id , 0)
						AND C.Id_Article = idART
						AND E.Inventario = 0
						AND E.Redada = 0
				UNION ALL
				SELECT TR.shipment Fecha,
						NULL Entrada,
						C.Cantidad Salida,
						TR.delivered OK,
						P.Proveedor Alias,
						E.Referencia Referencia,
						E.Id_Entrada id,
						TR.delivered F5
					FROM Compres C
						INNER JOIN Entradas E USING (Id_Entrada)
						INNER JOIN travel TR ON TR.id = E.travel_id
						INNER JOIN Proveedores P USING (Id_Proveedor)
					WHERE TR.shipment >= '2001-01-01'
						AND wh = TR.warehouse_id_out
						AND Id_Proveedor <> 4
						AND C.Id_Article = idART
						AND E.Inventario = 0
						AND E.Redada = 0
				UNION ALL
				SELECT T.Fecha Fecha,
						NULL Entrada,
						M.Cantidad Salida,
						(M.OK <> 0 OR T.Etiquetasemitidas <> 0 OR T.Factura IS NOT NULL) OK,
						T.Alias Alias,
						T.Factura Referencia,
						T.Id_Ticket,
						T.PedidoImpreso
					FROM Movimientos M
						INNER JOIN Tickets T USING (Id_Ticket)
						JOIN Clientes C ON C.Id_Cliente = T.Id_Cliente
					WHERE T.Fecha >= '2001-01-01'
						AND M.Id_Article = idART
						AND wh IN (T.warehouse_id , 0)
			) t1 
			ORDER BY Fecha, Entrada DESC, OK DESC;

	SELECT sum(Entrada) - sum(Salida) INTO inv_calculado
		FROM historico_pasado
			WHERE Fecha < datfecha;

	SELECT p1.*, NULL v_virtual 
		FROM(
			SELECT datfecha Fecha,
				inv_calculado Entrada,
				NULL Salida,
				1 OK,
				'Inventario calculado' Alias,
				'' Referencia, 0 id,
				1 F5
			UNION ALL
			SELECT * 
				FROM historico_pasado
					WHERE Fecha >= datfecha
			) p1;
	
	DROP TEMPORARY TABLE historico_pasado;
END$$
DELIMITER ;
