call spQuery_Packing_Mercaderia_Preventa(1, '2011-12-27',NULL, NULL, NULL,'');

DROP PROCEDURE IF EXISTS spQuery_Packing_Mercaderia_Preventa;
CREATE PROCEDURE spQuery_Packing_Mercaderia_Preventa(
  varEmpresa   int,
  varFechaIni  date,
  varFechaFin  date,
  varProveedor int,
  varVendedor  text,  
  varRuta      text
  )
BEGIN
  DECLARE varCadVen, varCadRut, varCadPro, varCadIni, varCadFin TEXT DEFAULT '';
  
	if varVendedor <> '' AND varVendedor <> 'Todos' then
    set varCadVen = CONCAT(" and V.id_trabajador in ", varVendedor);
  end if;
  if varRuta <> '' and varRuta is not null then
    set varCadRut = CONCAT(" and V.id_ruta in ", varRuta," ");
  end if;
  
  if varProveedor <> '' and varProveedor is not null then
    set varCadPro = CONCAT(" and P.id_proveedor = ", varProveedor," ");
  end if;
  
  if varFechaIni <> '' and varFechaIni is not null then
    set varCadIni = CONCAT(" and V.fecha_pedido >= '", varFechaIni,"' ");
  end if;
  
  if varFechaFin <> '' and varFechaFin is not null then
    set varCadFin = CONCAT(" and V.fecha_pedido <= '", varFechaFin,"' ");
  end if;
  
  SET @sql = CONCAT("select P.id_proveedor as CPRO, L.nombre as PROVEEDOR, ",
                    "D.id_producto as CART, P.descripcion as ARTICULO, D.id_um as UM, ",
                    "count(distinct V.id_cliente) as PDV, ",
                    "sum(D.cantidad_ped) as CANTIDAD, ",
                    "(select sum(cantidad) from _sv_kardex K where K.id_producto = D.id_producto and id_almacen=1 and id_local=1) as STOK, ",
                    "sum(D.total) as MONTO ",
                    "from _sv_pedido_detalle D ",
                    "inner join _sv_pedido V ON D.id_pedido = V.id_pedido ",
                    "inner join _sv_producto P ON D.id_producto = P.id_producto ",
                    "inner join _sv_proveedor L ON P.id_proveedor = L.id_proveedor ",                    
                    "where V._estado = 'A' ",
                    "AND D._estado = 'A' ",
                    "AND V.estado  = 'IN' ",
                    "AND V.id_empresa = ", varEmpresa, " ",
                    varCadVen, varCadRut, varCadIni, varCadFin, varCadPro,
                    "group by D.id_producto, P.descripcion, D.id_um, P.id_proveedor, L.nombre ",
                    "order by P.id_proveedor, P.descripcion;");
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;


select * from _sv_kardex