All files / apps/web/src/backoffice/components KnowledgeBaseSidebar.jsx

0% Statements 0/54
0% Branches 0/84
0% Functions 0/15
0% Lines 0/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172                                                                                                                                                                                                                                                                                                                                                       
import { Link, useSearchParams } from 'react-router-dom';
import { Database, Layers, Code, Settings, Network, Table, MessageSquare } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import api from '../../services/api';
import EntitySidebar from '../../components/EntitySidebar';
import { useOrganizationStore } from '../../store/organizationStore';
import { useKnowledgeBaseFilterStore } from '../../store/knowledgeBaseFilterStore';
 
export default function KnowledgeBaseSidebar({ selectedId, collapsed, onCollapsedChange, dark = false }) {
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const [searchParams] = useSearchParams();
  const view = searchParams.get('view');
  const baseType = useKnowledgeBaseFilterStore((s) => s.baseType);
  const setBaseType = useKnowledgeBaseFilterStore((s) => s.setBaseType);
 
  const { data: kbs, isLoading: kbsLoading } = useQuery({
    queryKey: ['knowledge-bases', organizationId],
    queryFn: async () => {
      const response = await api.get('/knowledge-bases');
      return response.data.data?.knowledge_bases || response.data || [];
    }
  });
 
  const { data: virtualKbs, isLoading: virtualKbsLoading } = useQuery({
    queryKey: ['virtual-kbs', organizationId],
    queryFn: async () => {
      const r = await api.get('/virtual-kbs');
      return r.data.data || [];
    }
  });
 
  const { data: semanticKbs, isLoading: semanticKbsLoading } = useQuery({
    queryKey: ['semantic-kbs', organizationId],
    queryFn: async () => {
      const r = await api.get('/semantic-kbs');
      return r.data.data?.semantic_kbs || r.data.data || [];
    }
  });
 
  // « real » regroupe les KB d'assertions, de data ET sémantiques.
  const realItems = [
    ...(kbs || []).map((k) => ({ ...k, _kind: 'kb' })),
    ...(semanticKbs || []).map((k) => ({ ...k, _kind: 'semantic' })),
  ];
  const items = baseType === 'virtual' ? (virtualKbs || []) : realItems;
  const itemsLoading =
    baseType === 'virtual' ? virtualKbsLoading : kbsLoading || semanticKbsLoading;
 
  // Couleurs adaptées au fond (sombre pour le backoffice)
  const inactiveBtn = dark
    ? 'bg-slate-800 text-slate-300 border-slate-700 hover:bg-slate-700'
    : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50';
  const itemText = (isSelected) => (isSelected ? (dark ? 'text-white' : 'text-gray-900') : (dark ? 'text-slate-300' : 'text-gray-700'));
  const itemSub = dark ? 'text-slate-400' : 'text-gray-500';
  const itemIcon = (isSelected, color) =>
    isSelected ? (dark ? `${color}-400` : `${color}-600`) : (dark ? 'text-slate-500' : 'text-gray-400');
 
  return (
    <EntitySidebar
      items={items}
      selectedId={selectedId}
      collapsed={collapsed}
      dark={dark}
      onCollapsedChange={onCollapsedChange}
      getItemHref={(item) => {
        if (baseType === 'virtual') return `/${organizationId}/backoffice/knowledge/virtual/${item._id}`;
        if (item._kind === 'semantic') return `/${organizationId}/backoffice/knowledge/semantic/${item._id}`;
        return `/${organizationId}/backoffice/knowledge/${item._id}`;
      }}
      searchPlaceholder={baseType === 'virtual' ? 'Rechercher une base virtuelle...' : 'Rechercher une base...'}
      emptyMessage={baseType === 'virtual' ? 'Aucune base virtuelle' : 'Aucune base disponible'}
      title="Knowledge Bases"
      icon={Database}
      iconClass={dark ? 'text-green-400' : 'text-green-600'}
      backofficeTo={`/${organizationId}/backoffice/knowledge/new`}
      backofficeManageLabel="Créer une base"
      backofficeCreateLabel="Créer une base"
      createOnly
      loading={itemsLoading}
      titleActions={
        <>
          <Link
            to={`/${organizationId}/backoffice/knowledge?view=mcp`}
            title="API MCP"
            className={`px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1 transition-colors ${
              view === 'mcp'
                ? 'bg-indigo-600 text-white'
                : inactiveBtn
            }`}
          >
            <Code className="w-3 h-3" />
            MCP
          </Link>
          <Link
            to={`/${organizationId}/backoffice/knowledge?view=settings`}
            title="Maintenance"
            className={`px-2 py-1 rounded-md text-xs font-medium flex items-center justify-center transition-colors ${
              view === 'settings'
                ? 'bg-indigo-600 text-white'
                : inactiveBtn
            }`}
          >
            <Settings className="w-3 h-3" />
          </Link>
        </>
      }
      filter={
        <div className="flex gap-1">
          <button
            onClick={() => setBaseType('real')}
            className={`flex-1 px-2 py-1 text-xs font-medium rounded-md transition-colors ${
              baseType === 'real'
                ? 'bg-green-600 text-white'
                : inactiveBtn
            }`}
          >
            Bases réelles
          </button>
          <button
            onClick={() => setBaseType('virtual')}
            className={`flex-1 px-2 py-1 text-xs font-medium rounded-md transition-colors ${
              baseType === 'virtual'
                ? 'bg-purple-600 text-white'
                : inactiveBtn
            }`}
          >
            Bases virtuelles
          </button>
        </div>
      }
      filterFn={(item) => `${item.name} ${item.description || ''}`}
      renderItem={(item, isSelected) => {
        const isVirtual = baseType === 'virtual';
        const isSemantic = item._kind === 'semantic';
        const isData = item.type === 'data';
        // Icône/couleur par TYPE de base : assertion (bulle), data (table), sémantique (graphe).
        let Icon = MessageSquare;
        let color = 'text-purple';
        if (isVirtual) {
          Icon = Layers;
          color = 'text-purple';
        } else if (isSemantic) {
          Icon = Network;
          color = 'text-teal';
        } else if (isData) {
          Icon = Table;
          color = 'text-indigo';
        }
        const count = (item.assertion_count ?? item.fact_count) || 0;
        const subtitle = isVirtual
          ? `${item.kbIds?.length || 0} KB incluse${(item.kbIds?.length || 0) > 1 ? 's' : ''}`
          : isSemantic
            ? `${item.stats?.triples ?? 0} triplets${item.stats?.mergesProposed ? ` · ${item.stats.mergesProposed} conflit${item.stats.mergesProposed > 1 ? 's' : ''}` : ''}`
            : isData
              ? `${count} éléments`
              : `${count} assertions`;
        return (
          <>
            <div className="flex items-center">
              <Icon className={`w-4 h-4 mr-2 flex-shrink-0 ${itemIcon(isSelected, color)}`} />
              <span className={`text-sm font-medium truncate flex-1 ${itemText(isSelected)}`}>
                {item.name}
              </span>
            </div>
            <div className={`text-xs mt-0.5 ${itemSub}`}>{subtitle}</div>
          </>
        );
      }}
    />
  );
}