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


if bolCLIENT then

	select m.Id_Article
         , Article
		 , IF(Cantidad < 0, - Cantidad, NULL) as Entrada
		 , IF(Cantidad < 0, NULL, Cantidad) as  Salida
		 , 'T' as Tabla
		 , t.Id_Ticket  as Registro
		 , t.Fecha
		 , w.name as Almacen
		 , cast(Preu as Decimal(5,2)) Precio
         , c.Cliente as Proveedor
         , abbreviation as Empresa
	from Movimientos m
    join Articles a using(Id_Article)
	join Tickets t using(Id_Ticket)
    join empresa e on e.id = t.empresa_id
    join warehouse w on w.id = t.warehouse_id
	join Consignatarios cs using(Id_Consigna)
    join Clientes c on c.Id_Cliente = cs.Id_Cliente
    where cs.Id_Cliente = idPEOPLE
	and m.Id_Article = idARTICLE
	and t.Fecha > '2010-01-01';

else

select Id_Article, Tabla, Registro, Fecha, Article
, w.name as Almacen,  Entrada, Salida, Proveedor, cast(Precio as Decimal(5,2)) Precio

from

(select Id_Article
      , IF(Cantidad > 0, Cantidad, NULL) as Entrada
      , IF(Cantidad > 0, NULL,- Cantidad) as Salida
      , 'E' as Tabla
      , Id_Entrada as Registro
      , landing as Fecha
      , tr.warehouse_id
      , Costefijo as Precio
from Compres c
join Entradas e using(Id_Entrada)
join travel tr on tr.id = travel_id
where Id_Proveedor = idPEOPLE
and Id_Article = idARTICLE
and landing >= '2010-01-01'

union all

select Id_Article
	 , IF(Cantidad < 0, - Cantidad, NULL) as Entrada
	 , IF(Cantidad < 0, NULL, Cantidad) as  Salida
     , 'T'
     , Id_Ticket
     , Fecha
     , t.warehouse_id
     , Preu
from Movimientos m
join Tickets t using(Id_Ticket)
join Consignatarios cs using(Id_Consigna)
join proveedores_clientes pc on pc.Id_Cliente = cs.Id_Cliente
where Id_Proveedor = idPEOPLE
and Id_Article = idARTICLE
and t.Fecha > '2010-01-01') mov

join Articles a using(Id_Article)
join Proveedores p on Id_Proveedor = idPEOPLE
join warehouse w on w.id = mov.warehouse_id
;

end if;

END$$
DELIMITER ;
