DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`comparativa_add_manual`(IN vStarted DATE, IN vEnded DATE)
BEGIN
/**
 * Recalcula la tabla Comparativa para dos valores dados
 *
 * @param vStarted fecha desde
 * @param vEnded fecha hasta
 */  

	DECLARE periodStart INT;
	DECLARE periodEnd INT;
	
	-- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar

	SELECT t.period INTO periodStart
		FROM vn.`time` t 
		WHERE t.dated = vStarted;
	
	SELECT t.period INTO periodEnd
		FROM vn.`time` t 
		WHERE t.dated = vEnded;
                
	DELETE FROM vn2008.Comparativa 
		WHERE Periodo BETWEEN periodStart AND periodEnd;

	INSERT INTO vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
		SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe)
			FROM bs.ventas v
				JOIN vn2008.time tm ON tm.date = v.fecha
				JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento
				JOIN vn2008.Tipos tp ON tp.tipo_id = v.tipo_id
				JOIN vn2008.reinos r ON r.id = tp.reino_id
				JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
			WHERE tm.period BETWEEN periodStart AND periodEnd
				AND t.Id_Cliente NOT IN(400,200)
				AND t.warehouse_id NOT IN (0,13)		
			GROUP BY m.Id_Article, Periodo, t.warehouse_id;
END$$
DELIMITER ;
