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

0% Statements 0/104
0% Branches 0/106
0% Functions 0/41
0% Lines 0/84

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { useState } from 'react';
import { Upload, Plus, Trash2, BookOpen, FileCode, X, PenLine } from 'lucide-react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import api from '../../services/api';
 
/**
 * Éditeur PARTAGÉ des sources OWL/SHACL (KB sémantique, workflow manuel, workflow prédéfini).
 *
 * Le bouton « + Ajouter » crée une LIGNE dans laquelle on choisit :
 *   - une ontologie prête à l'emploi (bibliothèque), OU
 *   - un upload de fichier, OU
 *   - une saisie/collage de texte.
 * Une source = { libraryId, builtinId?, key?, name, format } ou { key, name, format }.
 */
export default function SemanticSourcesEditor({ organizationId, value, onChange, disabled = false, hint = null, kinds = ['ontology', 'shapes'] }) {
  const ontologySources = value?.ontologySources || [];
  const shapesSources = value?.shapesSources || [];
  const queryClient = useQueryClient();
  const [busy, setBusy] = useState(false);
  const [saveToLibrary, setSaveToLibrary] = useState(true);
  const [drafts, setDrafts] = useState({ ontology: [], shapes: [] });
 
  const { data: library = [] } = useQuery({
    queryKey: ['ontology-library', organizationId],
    queryFn: async () => {
      const res = await api.get('/ontology-library');
      return res.data.data?.entries || [];
    },
    enabled: !!organizationId,
  });
 
  const set = (patch) => onChange({ ontologySources, shapesSources, ...patch });
  const sourcesOf = (kind) => (kind === 'ontology' ? ontologySources : shapesSources);
  const setSources = (kind, list) => set(kind === 'ontology' ? { ontologySources: list } : { shapesSources: list });
 
  const addDraft = (kind, withLibrary) => setDrafts((d) => ({ ...d, [kind]: [...d[kind], { mode: withLibrary ? 'library' : 'file', text: '' }] }));
  const removeDraft = (kind, i) => setDrafts((d) => ({ ...d, [kind]: d[kind].filter((_, idx) => idx !== i) }));
  const setDraft = (kind, i, patch) => setDrafts((d) => ({ ...d, [kind]: d[kind].map((x, idx) => (idx === i ? { ...x, ...patch } : x)) }));
 
  const commit = (kind, draftIndex, newSources) => {
    setSources(kind, [...sourcesOf(kind), ...newSources]);
    removeDraft(kind, draftIndex);
  };
 
  const uploadAsset = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    const res = await api.post(`/${organizationId}/semantic-assets`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return res.data?.data;
  };
 
  const toLibraryEntry = async ({ name, format, key, size }) => {
    const res = await api.post('/ontology-library', { organizationId, name, format, key, size });
    queryClient.invalidateQueries(['ontology-library', organizationId]);
    return res.data?.data?.entry;
  };
 
  const sourceFromFile = async (kind, file) => {
    const data = await uploadAsset(file);
    const format = /\.(jsonld|json)$/i.test(file.name) ? 'jsonld' : 'turtle';
    if (kind === 'ontology' && saveToLibrary) {
      const entry = await toLibraryEntry({ name: data.filename, format, key: data.key, size: data.size });
      if (entry) return { libraryId: String(entry._id), key: entry.key, name: entry.name, format: entry.format };
    }
    return { key: data.key, name: data.filename, format };
  };
 
  const commitFromFile = async (kind, i, files) => {
    const arr = Array.from(files || []);
    if (!arr.length) return;
    setBusy(true);
    try {
      const added = [];
      for (const file of arr) added.push(await sourceFromFile(kind, file));
      commit(kind, i, added);
      toast.success(kind === 'ontology' ? 'Ontologie(s) ajoutée(s)' : 'Shapes ajoutés');
    } catch (e) {
      toast.error(e.response?.data?.message || "Erreur lors de l'import");
    } finally {
      setBusy(false);
    }
  };
 
  const commitFromText = async (kind, i, text) => {
    if (!text.trim()) return;
    setBusy(true);
    try {
      const file = new File([new Blob([text], { type: 'text/turtle' })], `${kind}-colle-${Date.now()}.ttl`, { type: 'text/turtle' });
      const source = await sourceFromFile(kind, file);
      commit(kind, i, [source]);
      toast.success('Source ajoutée');
    } catch (e) {
      toast.error(e.response?.data?.message || 'Erreur');
    } finally {
      setBusy(false);
    }
  };
 
  const commitFromLibrary = (kind, i, entryId) => {
    const entry = library.find((e) => String(e._id) === String(entryId));
    if (!entry) return;
    commit(kind, i, [{ libraryId: String(entry._id), builtinId: entry.builtinId || null, key: entry.key || null, name: entry.name, format: entry.format || 'turtle' }]);
  };
 
  const removeSource = (kind, index) => setSources(kind, sourcesOf(kind).filter((_, i) => i !== index));
 
  const modeButton = (active, onClick, Icon, label) => (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled || busy}
      className={`inline-flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border-2 transition-all ${
        active ? 'border-teal-500 bg-teal-50 text-teal-700' : 'border-gray-200 text-gray-600 hover:bg-gray-50'
      }`}
    >
      <Icon className="w-3.5 h-3.5" /> {label}
    </button>
  );
 
  const renderDraft = (kind, draft, i, accept, withLibrary) => (
    <div className="p-3 rounded-lg border-2 border-dashed border-gray-300 bg-white space-y-2">
      <div className="flex flex-wrap items-center gap-2">
        {withLibrary && modeButton(draft.mode === 'library', () => setDraft(kind, i, { mode: 'library' }), BookOpen, 'Bibliothèque')}
        {modeButton(draft.mode === 'file', () => setDraft(kind, i, { mode: 'file' }), Upload, 'Fichier')}
        {modeButton(draft.mode === 'text', () => setDraft(kind, i, { mode: 'text' }), PenLine, 'Saisie')}
        <button type="button" onClick={() => removeDraft(kind, i)} className="ml-auto p-1.5 text-gray-400 hover:text-red-500 rounded-lg" title="Annuler">
          <X className="w-4 h-4" />
        </button>
      </div>
 
      {draft.mode === 'library' && (
        <select
          value=""
          onChange={(e) => commitFromLibrary(kind, i, e.target.value)}
          disabled={disabled || busy}
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white text-gray-700 focus:ring-2 focus:ring-teal-500"
        >
          <option value="">Choisir une ontologie…</option>
          {library.map((e) => (
            <option key={e._id} value={e._id}>{e.name}{e.scope === 'builtin' ? ' ★' : ''}</option>
          ))}
        </select>
      )}
 
      {draft.mode === 'file' && (
        <div className="space-y-2">
          <label className={`inline-flex items-center gap-2 px-3 py-2 text-sm border border-gray-300 rounded-lg ${disabled || busy ? 'opacity-50' : 'cursor-pointer hover:bg-gray-50'}`}>
            <Upload className="w-4 h-4" /> Choisir un fichier
            <input type="file" multiple accept={accept} disabled={disabled || busy} className="hidden"
              onChange={(e) => { commitFromFile(kind, i, e.target.files); e.target.value = ''; }} />
          </label>
          {kind === 'ontology' && (
            <label className="flex items-center gap-2 text-xs text-gray-600">
              <input type="checkbox" checked={saveToLibrary} onChange={(e) => setSaveToLibrary(e.target.checked)} />
              Enregistrer dans la bibliothèque d'ontologies
            </label>
          )}
        </div>
      )}
 
      {draft.mode === 'text' && (
        <div className="space-y-2">
          <textarea
            value={draft.text || ''}
            onChange={(e) => setDraft(kind, i, { text: e.target.value })}
            rows={4}
            placeholder={kind === 'ontology' ? '@prefix owl: <http://www.w3.org/2002/07/owl#> .' : '@prefix sh: <http://www.w3.org/ns/shacl#> .'}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm focus:ring-2 focus:ring-teal-500"
          />
          <div className="flex flex-wrap items-center gap-3">
            <button
              type="button"
              onClick={() => commitFromText(kind, i, draft.text || '')}
              disabled={disabled || busy || !(draft.text || '').trim()}
              className="inline-flex items-center gap-2 px-3 py-2 text-sm bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
            >
              <Upload className="w-4 h-4" /> Ajouter le contenu
            </button>
            {kind === 'ontology' && (
              <label className="flex items-center gap-2 text-xs text-gray-600">
                <input type="checkbox" checked={saveToLibrary} onChange={(e) => setSaveToLibrary(e.target.checked)} />
                Bibliothèque
              </label>
            )}
          </div>
        </div>
      )}
    </div>
  );
 
  const renderSection = (kind, accept, withLibrary) => {
    const sources = sourcesOf(kind);
    const list = drafts[kind] || [];
    return (
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-sm font-medium text-gray-700">{kind === 'ontology' ? 'Ontologies' : 'Shapes SHACL'}</p>
          <button
            type="button"
            onClick={() => addDraft(kind, withLibrary)}
            disabled={disabled || busy}
            className="inline-flex items-center gap-1 px-3 py-1.5 text-sm border border-dashed border-gray-300 rounded-lg text-gray-600 hover:border-teal-400 hover:text-teal-600 disabled:opacity-50"
          >
            <Plus className="w-4 h-4" /> Ajouter
          </button>
        </div>
 
        <div className="space-y-2">
          {sources.map((s, i) => (
            <div key={`src-${i}`} className="flex items-center justify-between p-3 rounded-lg border border-gray-200 bg-gray-50">
              <div className="flex items-center gap-3 min-w-0">
                {s.builtinId ? (
                  <BookOpen className="w-4 h-4 text-teal-600 flex-shrink-0" />
                ) : (
                  <FileCode className="w-4 h-4 text-teal-600 flex-shrink-0" />
                )}
                <span className="text-sm text-gray-900 truncate">{s.name || s.key}</span>
                {s.libraryId && <span className="text-xs text-gray-400 flex-shrink-0">bibliothèque</span>}
              </div>
              <button type="button" onClick={() => removeSource(kind, i)} disabled={disabled || busy}
                title="Retirer" className="p-2 text-red-500 hover:bg-red-50 rounded-lg disabled:opacity-40">
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          ))}
 
          {list.map((draft, i) => renderDraft(kind, draft, i, accept, withLibrary))}
 
          {sources.length === 0 && list.length === 0 && <p className="text-xs text-gray-400">Aucune source.</p>}
        </div>
      </div>
    );
  };
 
  return (
    <div className="space-y-5 border rounded-lg p-4 bg-white">
      {hint && <p className="text-xs text-gray-500">{hint}</p>}
      {kinds.includes('ontology') && renderSection('ontology', '.ttl,.turtle,.jsonld,.json,.owl,.rdf,.nt', true)}
      {kinds.includes('shapes') && renderSection('shapes', '.ttl,.turtle,.jsonld,.json,.nt', false)}
    </div>
  );
}