DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`embalajes_stocks`(IN idPEOPLE INT, IN bolCLIENT BOOLEAN)
BEGIN

	IF bolCLIENT THEN

		SELECT m.Id_Article, Article, - cast(sum(m.Cantidad) as decimal) Saldo
			FROM Movimientos m
				JOIN Articles a ON m.Id_Article = a.Id_Article
				JOIN Tipos tp ON tp.tipo_id = a.tipo_id 
				JOIN vn.ticket t ON t.id = m.Id_Ticket
				JOIN Consignatarios cs ON cs.Id_Consigna = t.addressFk
			WHERE cs.Id_Cliente = idPEOPLE
				AND Tipo = 'Contenedores'
				AND t.shipped > '2010-01-01'
			GROUP BY m.Id_Article;

	ELSE

		SELECT Id_Article, Article, sum(Cantidad) Saldo
		FROM
		(SELECT Id_Article, Cantidad
			FROM Compres c
				JOIN Articles a using(Id_Article)
				JOIN Tipos tp using(tipo_id)
				JOIN Entradas e using(Id_Entrada)
				JOIN travel tr ON tr.id = travel_id
			WHERE Id_Proveedor = idPEOPLE
				AND landing >= '2010-01-01'
				AND reino_id = 6

		union all

		SELECT Id_Article,  - Cantidad
			FROM Movimientos m
				JOIN Articles a using(Id_Article)
				JOIN Tipos tp using(tipo_id)
				JOIN vn.ticket t ON t.id = m.Id_Ticket
				JOIN Consignatarios cs ON cs.Id_Consigna = t.addressFk
				JOIN proveedores_clientes pc ON pc.Id_Cliente = cs.Id_Cliente
			WHERE Id_Proveedor = idPEOPLE
				AND reino_id = 6
				AND t.shipped > '2010-01-01') mov

		JOIN Articles a using(Id_Article)
		GROUP BY Id_Article;

	END IF;

END$$
DELIMITER ;
