All files / apps/web/src/frontoffice/pages KnowledgeBase.jsx

0% Statements 0/71
0% Branches 0/86
0% Functions 0/16
0% Lines 0/67

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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Search, Database, Filter, ExternalLink, Brain, AlertTriangle, Settings } from 'lucide-react'
import { listKnowledgeBases, searchKnowledgeBase } from '../../services/api'
import EntitySidebar from '../../components/EntitySidebar'
import EntityPage from '../../components/EntityPage'
import ItemRecap from '../../components/ItemRecap'
import toast from 'react-hot-toast'
import { useOrganizationStore } from '../../store/organizationStore'
 
function KnowledgeBase() {
  const { kbId } = useParams()
  const { currentOrganization } = useOrganizationStore()
  const organizationId = currentOrganization?.id
  
  // Knowledge bases available to user
  const [knowledgeBases, setKnowledgeBases] = useState([])
  const [selectedKb, setSelectedKb] = useState(null)
  const [isLoadingKbs, setIsLoadingKbs] = useState(true)
  
  // Search states
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState([])
  const [searchTotal, setSearchTotal] = useState(0)
  const [isSearching, setIsSearching] = useState(false)
  const [embedderWarning, setEmbedderWarning] = useState(null)
  
  // Score threshold (default 80%)
  const [scoreThreshold, setScoreThreshold] = useState(0.85)
  const [semanticRatio, setSemanticRatio] = useState(0.5)
  
  // Filters
  const [filters, setFilters] = useState({
    sortBy: 'relevance' // 'relevance', 'date'
  })
 
  // Load available knowledge bases when org changes
  useEffect(() => {
    if (currentOrganization?.id) {
      loadKnowledgeBases()
    }
  }, [currentOrganization?.id])
 
  // Sélection pilotée par l'URL (kbId)
  useEffect(() => {
    if (knowledgeBases.length === 0) return
    if (kbId) {
      const kb = knowledgeBases.find((k) => k._id === kbId)
      setSelectedKb(kb || null)
    } else {
      setSelectedKb(null)
    }
    setSearchResults([])
    setSearchQuery('')
  }, [kbId, knowledgeBases])
 
  const loadKnowledgeBases = async () => {
    try {
      const response = await listKnowledgeBases()
      if (response.data.success) {
        const kbs = response.data.data.knowledge_bases || []
        setKnowledgeBases(kbs)
      }
    } catch (error) {
      console.error('Error loading KBs:', error)
      toast.error('Erreur lors du chargement des bases de connaissances')
    } finally {
      setIsLoadingKbs(false)
    }
  }
 
  const handleSearch = async () => {
    if (!selectedKb || !searchQuery.trim()) {
      if (!selectedKb) {
        toast.error('Veuillez sélectionner une base de connaissances')
      }
      return
    }
    
    setIsSearching(true)
    setEmbedderWarning(null)
    try {
      const params = {
        q: searchQuery,
        limit: 20,
        hybrid: { semanticRatio },
        score_threshold: scoreThreshold,
      }
      const response = await searchKnowledgeBase(selectedKb._id, params)
      setSearchResults(response.data.facts || [])
      setSearchTotal(response.data.total || 0)
      if (response.data.warning) {
          setEmbedderWarning(response.data.warning)
        }
    } catch (error) {
      toast.error('Erreur lors de la recherche')
      console.error(error)
    } finally {
      setIsSearching(false)
    }
  }
 
  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleSearch()
    }
  }
 
  const getScoreColor = (score) => {
    if (score >= 0.15) return 'text-green-600 bg-green-100'
    if (score >= 0.08) return 'text-yellow-600 bg-yellow-100'
    return 'text-red-600 bg-red-100'
  }
 
  return (
    <EntityPage
      selectedId={kbId}
      sidebar={
        <EntitySidebar
          items={knowledgeBases}
          selectedId={selectedKb?._id}
          getItemHref={(kb) =>
            organizationId ? `/${organizationId}/knowledge-base/${kb._id}` : null
          }
          searchPlaceholder="Rechercher une base..."
          emptyMessage="Aucune base de connaissances"
          title="Knowledge Base"
          icon={Database}
          iconClass="text-green-600"
          backofficeTo={organizationId ? `/${organizationId}/backoffice/knowledge` : null}
          backofficeManageLabel="Gérer les bases"
          backofficeCreateLabel="Créer une base"
          loading={isLoadingKbs}
          filterFn={(kb) => `${kb.name} ${kb.description || ''}`}
          renderItem={(kb, isSelected) => (
            <>
              <div className="flex items-center">
                <Database className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-green-600' : 'text-gray-400'}`} />
                <span className={`text-sm font-medium truncate ${isSelected ? 'text-gray-900' : 'text-gray-700'}`}>
                  {kb.name}
                </span>
              </div>
              <div className="text-xs text-gray-500 mt-0.5">{kb.fact_count || 0} faits indexés</div>
            </>
          )}
        />
      }
    >
      {!selectedKb ? (
        <div className="flex-1 min-h-0 flex items-center justify-center">
          <div className="text-center">
            <Database className="w-16 h-16 mx-auto mb-4 text-gray-300" />
            <p className="text-gray-500">Sélectionnez une base de connaissances pour commencer</p>
          </div>
        </div>
      ) : (
        <>
          <ItemRecap
            name={selectedKb.name}
            description={selectedKb.description}
            meta={
              <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
                {selectedKb.fact_count || 0} faits indexés
              </span>
            }
            actions={
              organizationId ? (
                <Link
                  to={`/${organizationId}/backoffice/knowledge/${selectedKb._id}`}
                  title="Modifier dans le backoffice"
                  className="p-1.5 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100"
                >
                  <Settings className="w-4 h-4" />
                </Link>
              ) : null
            }
          />
          <div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
            {/* Search Interface */}
            <div className="card mb-6">
                {/* Search Input */}
                <div className="flex gap-2">
                  <div className="flex-1 relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input
                      type="text"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      onKeyPress={handleKeyPress}
                      placeholder={`Rechercher dans "${selectedKb.name}"...`}
                      className="input w-full pl-10"
                    />
                  </div>
                  <button
                    onClick={handleSearch}
                    disabled={!searchQuery.trim() || isSearching}
                    className="btn-primary inline-flex items-center disabled:opacity-50"
                  >
                    {isSearching ? (
                      <span className="animate-pulse">Recherche...</span>
                    ) : (
                      <>
                        <Search className="w-5 h-5 mr-2" />
                        Rechercher
                      </>
                    )}
                  </button>
                </div>
 
                {/* Filters */}
                <div className="mt-4 flex flex-wrap items-center gap-4 text-sm">
                  <div className="flex items-center">
                    <Filter className="w-4 h-4 text-gray-400 mr-2" />
                    <span className="text-gray-600">Filtres:</span>
                  </div>
                  
                  {/* Score Threshold Slider */}
                  <div className="flex items-center gap-2 px-3 py-1 bg-indigo-50 rounded-lg border border-indigo-200">
                    <Brain className="w-4 h-4 text-indigo-600" />
                    <label className="text-gray-600 text-xs whitespace-nowrap">Seuil:</label>
                    <input
                      type="range"
                      min="0.5"
                      max="0.95"
                      step="0.05"
                      value={scoreThreshold}
                      onChange={(e) => setScoreThreshold(parseFloat(e.target.value))}
                      className="w-20 accent-indigo-600"
                    />
                    <span className="text-xs font-medium text-indigo-700 min-w-[35px]">
                      {Math.round(scoreThreshold * 100)}%
                    </span>
                  </div>
 
                  {/* Semantic Ratio Slider */}
                  <div className="flex items-center gap-2 px-3 py-1 bg-blue-50 rounded-lg border border-blue-200">
                    <Brain className="w-4 h-4 text-blue-600" />
                    <label className="text-gray-600 text-xs whitespace-nowrap">Vectoriel:</label>
                    <input
                      type="range"
                      min="0"
                      max="1"
                      step="0.1"
                      value={semanticRatio}
                      onChange={(e) => setSemanticRatio(parseFloat(e.target.value))}
                      className="w-20 accent-blue-600"
                    />
                    <span className="text-xs font-medium text-blue-700 min-w-[35px]">
                      {Math.round(semanticRatio * 100)}%
                    </span>
                    <div className="text-xs text-gray-400 ml-1">
                      {semanticRatio === 0 ? 'que mots-clés' : semanticRatio === 1 ? 'que vectoriel' : `${Math.round(semanticRatio * 100)}%`}
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    <label className="text-gray-600">Trier par:</label>
                    <select
                      value={filters.sortBy}
                      onChange={(e) => setFilters({...filters, sortBy: e.target.value})}
                      className="text-sm border border-gray-300 rounded px-2 py-1"
                    >
                      <option value="relevance">Pertinence</option>
                      <option value="date">Date</option>
                    </select>
                  </div>
                </div>
              </div>
 
              {/* Embedder Warning */}
              {embedderWarning && (
                <div className="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-start gap-2">
                  <AlertTriangle className="w-5 h-5 text-amber-500 mt-0.5 shrink-0" />
                  <div className="text-sm text-amber-800">
                    <p className="font-medium mb-1">Attention : recherche vectorielle limitée</p>
                    <p>{embedderWarning}</p>
                  </div>
                </div>
              )}
 
              {/* Results */}
              {searchResults.length > 0 && (
                <div className="card">
                  <div className="flex items-center justify-between mb-4">
                    <h2 className="text-lg font-semibold">
                      Résultats ({searchResults.length}{searchTotal > searchResults.length ? ` sur ${searchTotal}` : ''})
                    </h2>
                    <span className="text-sm text-gray-500">
                      dans "{selectedKb?.name}"
                    </span>
                  </div>
 
                  <div className="space-y-3">
                    {searchResults.map((result, index) => (
                      <div key={index} className="p-4 bg-gray-50 rounded-lg border-l-4 border-green-500">
                        <div className="mb-3 text-gray-900">
                          <span className="font-medium">{result.text || 'Fait sans texte'}</span>
                        </div>
 
                        <div className="flex items-center justify-between text-sm">
                          <div className="flex items-center gap-3">
                            {result.score !== undefined && (
                              <span className={`px-2 py-1 rounded text-xs font-medium ${getScoreColor(result.score)}`}>
                                Score: {(result.score * 100).toFixed(1)}%
                              </span>
                            )}
                            {result.source && (
                              <span className="text-gray-500 bg-gray-100 px-2 py-1 rounded text-xs">
                                {result.source}
                              </span>
                            )}
                            {result.timestamp && (
                              <span className="text-gray-500">
                                {new Date(result.timestamp).toLocaleDateString()}
                              </span>
                            )}
                          </div>
                          {result.url && (
                            <a 
                              href={result.url} 
                              target="_blank" 
                              rel="noopener noreferrer"
                              className="text-indigo-600 hover:text-indigo-800 flex items-center text-xs font-medium px-2 py-1 bg-indigo-50 rounded border border-indigo-200"
                            >
                              <ExternalLink className="w-3 h-3 mr-1" />
                              {result.url.includes('minio') || result.url.includes('.pdf') ? 'PDF Source' : 'Source'}
                            </a>
                          )}
                        </div>
 
                        {result.metadata && (
                          <div className="mt-2 pt-2 border-t border-gray-200 text-xs text-gray-400">
                            {result.metadata.description && <span>📝 {result.metadata.description}</span>}
                            {result.metadata.title && <span className="ml-2">📄 {result.metadata.title}</span>}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}
 
              {/* No Results */}
              {searchQuery && searchResults.length === 0 && !isSearching && (
                <div className="card text-center py-12">
                  <Database className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                  <p className="text-gray-500">Aucun résultat trouvé pour "{searchQuery}"</p>
                  <p className="text-sm text-gray-400 mt-2">
                    Essayez avec d'autres termes ou vérifiez la base sélectionnée
                  </p>
                </div>
              )}
          </div>
        </>
      )}
    </EntityPage>
  )
}
 
export default KnowledgeBase