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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 | import { useState, useEffect } from 'react'
import { useDropzone } from 'react-dropzone'
import { Brain, Upload, Globe, Table, X, Route, Settings, Type, FileType, Loader2, CheckCircle, AlertCircle, Code, Eye, Copy, Download, Clock } from 'lucide-react'
import { uploadFile } from '../../services/api'
import { useWorkflowStore } from '../../store/workflowStore'
import ModelSelector from '../../components/ModelSelector'
import { useOrganizationStore } from '../../store/organizationStore'
import SchemaEditor, { createInitialFields, fieldsToSchemaWithRoot } from '../../components/SchemaEditor'
import toast from 'react-hot-toast'
import SynthesisResults from '../../components/SynthesisResults'
// Import modaux
import MarkdownViewerModal from '../components/MarkdownViewerModal'
import FactsViewerModal from '../components/FactsViewerModal'
import DataViewerModal from '../components/DataViewerModal'
import RoutingViewerModal from '../components/RoutingViewerModal'
import PageViewerModal from '../components/PageViewerModal'
function ProgressBar({ step, progress, message, status }) {
const isProcessing = status === 'extracting' || status === 'processing' || status === 'running' || status === 'pending'
if (!isProcessing && progress == null) return null
const displayProgress = progress ?? 0
const stepLabels = {
received: 'Reçu',
extracting_web: 'Extraction web',
retrieving_web: 'Récupération contenu',
downloading_file: 'Téléchargement',
downloading_minio: 'Récupération fichier',
extracting_ocr: 'Extraction OCR',
uploading_extraction: 'Upload résultat',
preparing_synthesis: 'Préparation',
synthesizing: 'Synthèse IA',
uploading_result: 'Upload résultat',
routing_facts: 'Routage faits',
complete: 'Terminé',
failed: 'Échec',
}
return (
<div className="mb-4">
<div className="flex justify-between text-sm mb-1">
<span>{stepLabels[step] || message || 'En cours...'}</span>
<span>{Math.round(displayProgress)}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2.5 overflow-hidden">
<div
className="bg-purple-500 h-2.5 rounded-full transition-all duration-300 ease-out"
style={{ width: `${displayProgress}%` }}
/>
</div>
</div>
)
}
// Section Source avec 4 onglets
function SourceSection({ sourceType, onChange, datalabConfigured }) {
const [activeTab, setActiveTab] = useState(sourceType || 'input')
const [file, setFile] = useState(null)
const [inputText, setInputText] = useState('')
const [sourceText, setSourceText] = useState('')
const [url, setUrl] = useState('')
const [fileUrl, setFileUrl] = useState('')
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop: (acceptedFiles) => {
if (acceptedFiles.length > 0) {
setFile(acceptedFiles[0])
onChange({ type: 'fileUpload', file: acceptedFiles[0] })
setActiveTab('fileUpload')
}
}
})
const handleTabChange = (tabId) => {
setActiveTab(tabId)
onChange({ type: tabId })
}
const tabs = [
{ id: 'input', label: 'Texte', icon: Type, desc: 'Texte brut' },
{ id: 'web', label: 'Web', icon: Globe, desc: 'URL site web' },
{ id: 'fileUrl', label: 'Fichier URL', icon: FileType, desc: 'URL fichier', needsDatalab: true },
{ id: 'fileUpload', label: 'Upload', icon: Upload, desc: 'Uploader fichier', needsDatalab: true },
]
return (
<div className="space-y-4">
<div className="grid grid-cols-4 gap-2">
{tabs.map((tab) => {
const Icon = tab.icon
const isActive = activeTab === tab.id
const disabled = tab.needsDatalab && !datalabConfigured
return (
<button
key={tab.id}
onClick={() => !disabled && handleTabChange(tab.id)}
disabled={disabled}
title={disabled ? 'Clé API Datalab requise' : undefined}
className={`flex flex-col items-center p-3 rounded-lg border-2 transition-all ${
disabled
? 'border-gray-200 bg-amber-50 text-amber-400 cursor-not-allowed'
: isActive
? 'border-purple-500 bg-purple-50 text-purple-700'
: 'border-gray-200 text-gray-600 hover:bg-gray-50'
}`}
>
<Icon className={`w-6 h-6 mb-1 ${disabled ? 'text-amber-300' : isActive ? 'text-purple-600' : 'text-gray-400'}`} />
<span className="text-sm font-medium">{tab.label}</span>
<span className="text-xs opacity-75 hidden sm:block">{tab.desc}</span>
</button>
)
})}
</div>
<div className="bg-gray-50 rounded-lg p-4">
{activeTab === 'input' && (
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Texte à analyser</label>
<textarea
value={inputText}
onChange={(e) => { const val = e.target.value; setInputText(val); onChange({ type: 'input', input: val, sourceText }) }}
placeholder="Collez votre texte ici..."
rows={6}
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 bg-white resize-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Source (optionnel)</label>
<input
type="text"
value={sourceText}
onChange={(e) => { const val = e.target.value; setSourceText(val); onChange({ type: 'input', input: inputText, sourceText: val }) }}
placeholder="Ex: Document interne, Notes de réunion..."
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 bg-white"
/>
</div>
</div>
)}
{activeTab === 'web' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">URL du site web</label>
<input
type="url"
value={url}
onChange={(e) => { setUrl(e.target.value); onChange({ type: 'web', url: e.target.value }) }}
placeholder="https://example.com"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 bg-white"
/>
</div>
)}
{activeTab === 'fileUrl' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">URL du fichier</label>
<input
type="url"
value={fileUrl}
onChange={(e) => { setFileUrl(e.target.value); onChange({ type: 'fileUrl', fileUrl: e.target.value }) }}
placeholder="https://example.com/document.pdf"
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 bg-white"
/>
</div>
)}
{activeTab === 'fileUpload' && (
<div {...getRootProps()} className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer bg-white ${
isDragActive ? 'border-purple-500 bg-purple-50' : 'border-gray-300'
}`}>
<input {...getInputProps()} />
{file ? (
<div className="flex items-center justify-center gap-2">
<span className="font-medium">{file.name}</span>
<button onClick={(e) => { e.stopPropagation(); setFile(null); onChange({ type: 'fileUpload', file: null }) }}>
<X className="w-4 h-4 text-gray-400" />
</button>
</div>
) : (
<div>
<Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
<p className="text-gray-600">Glissez-déposez ou cliquez</p>
<p className="text-xs text-gray-400">PDF, DOCX, etc.</p>
</div>
)}
</div>
)}
</div>
</div>
)
}
// Section Synthetiser avec checkbox pour activer/désactiver
function SynthetiserSection({ config, onChange, llmModel, onLlmModelChange, openrouterConfigured }) {
const schemaFields = config.schemaFields || createInitialFields()
const handleModeChange = (mode) => {
onChange({ ...config, mode })
}
const toggleEnabled = () => {
if (!openrouterConfigured) return
onChange({ ...config, enabled: !config.enabled })
}
const isDisabled = !openrouterConfigured
return (
<div className="space-y-6">
{/* Checkbox pour activer/désactiver */}
<div className={`flex items-center justify-between p-4 rounded-lg ${isDisabled ? 'bg-amber-50 border border-amber-200' : 'bg-gray-50'}`}>
<div className="flex items-center gap-3">
<Brain className={`w-6 h-6 ${isDisabled ? 'text-amber-400' : 'text-purple-600'}`} />
<div>
<div className={`font-medium ${isDisabled ? 'text-amber-800' : 'text-gray-900'}`}>Activer la synthèse</div>
<div className={`text-sm ${isDisabled ? 'text-amber-600' : 'text-gray-500'}`}>
{isDisabled
? 'Clé API OpenRouter requise'
: config.enabled ? 'Extraction + Synthèse IA' : 'Extraction uniquement'
}
</div>
</div>
</div>
<label className={`relative inline-flex items-center ${isDisabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
<input
type="checkbox"
checked={config.enabled}
onChange={toggleEnabled}
disabled={isDisabled}
className="sr-only peer"
/>
<div className={`w-11 h-6 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all ${
isDisabled
? 'bg-amber-200 peer-focus:outline-none'
: 'bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 peer-checked:bg-purple-600'
}`}></div>
</label>
</div>
{/* Configuration de la synthèse (si activée) */}
{config.enabled && (
<>
<div>
<p className="text-xs text-gray-500 mb-1">Modèle LLM pour l'extraction</p>
<ModelSelector value={llmModel} onChange={onLlmModelChange} />
</div>
{/* Sélection mode */}
<div className="flex gap-4 p-4 bg-gray-50 rounded-lg">
<label className="flex-1 cursor-pointer">
<input type="radio" name="mode" value="fact" checked={config.mode === 'fact'} onChange={() => handleModeChange('fact')} className="sr-only" />
<div className={`flex items-center gap-3 p-3 rounded-lg border-2 ${config.mode === 'fact' ? 'border-purple-500 bg-purple-50' : 'border-gray-200'}`}>
<Brain className={`w-6 h-6 ${config.mode === 'fact' ? 'text-purple-600' : 'text-gray-400'}`} />
<div>
<div className={`font-medium ${config.mode === 'fact' ? 'text-purple-900' : 'text-gray-700'}`}>Mode Faits</div>
<div className="text-xs text-gray-500">Extraction de faits textuels</div>
</div>
</div>
</label>
<label className="flex-1 cursor-pointer">
<input type="radio" name="mode" value="data" checked={config.mode === 'data'} onChange={() => handleModeChange('data')} className="sr-only" />
<div className={`flex items-center gap-3 p-3 rounded-lg border-2 ${config.mode === 'data' ? 'border-indigo-500 bg-indigo-50' : 'border-gray-200'}`}>
<Table className={`w-6 h-6 ${config.mode === 'data' ? 'text-indigo-600' : 'text-gray-400'}`} />
<div>
<div className={`font-medium ${config.mode === 'data' ? 'text-indigo-900' : 'text-gray-700'}`}>Mode Données</div>
<div className="text-xs text-gray-500">Extraction structurée (JSON)</div>
</div>
</div>
</label>
</div>
{/* Mode FACT */}
{config.mode === 'fact' && (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Instruction d'extraction</label>
<textarea
value={config.instruction || ''}
onChange={(e) => onChange({ ...config, instruction: e.target.value })}
placeholder="Décrivez quels faits extraire..."
rows={4}
className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 resize-none"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Nombre max de faits</label>
<input
type="number"
value={config.maxItems || 10}
onChange={(e) => onChange({ ...config, maxItems: parseInt(e.target.value) || 10 })}
className="w-32 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
min="1"
max="1000"
/>
</div>
</div>
)}
{/* Mode DATA - Schema Editor identique au backoffice */}
{config.mode === 'data' && (
<div className="border rounded-lg p-4 bg-white">
<div className="flex items-center justify-between mb-4">
<h4 className="font-medium text-gray-900 flex items-center">
<Code className="w-4 h-4 mr-2" />
Schéma JSON
</h4>
<span className="text-xs text-gray-500">
Définissez la structure des données à extraire
</span>
</div>
<SchemaEditor
fields={schemaFields}
onChange={(fields) => {
onChange({ ...config, schemaFields: fields })
}}
disabled={false}
/>
</div>
)}
</>
)}
</div>
)
}
function RouterSection({ config, onChange, synthetiserEnabled }) {
const [routers, setRouters] = useState([])
const [loading, setLoading] = useState(true)
const { currentOrganization } = useOrganizationStore()
const orgId = currentOrganization?.id
useEffect(() => {
if (!orgId) return
fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:8000'}/api/v1/${orgId}/knowledge-routers`, {
headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` }
})
.then(r => r.json())
.then(data => {
if (data.success) setRouters(data.data || [])
})
.catch(console.error)
.finally(() => setLoading(false))
}, [orgId])
const handleChange = (routerId) => {
onChange({ ...config, routers: [routerId] })
}
const selectedId = config.routers?.[0] || ''
return (
<div className="space-y-4">
<div className={`flex items-center justify-between p-4 rounded-lg ${synthetiserEnabled ? 'bg-gray-50' : 'bg-gray-100 opacity-60'}`}>
<div className="flex items-center gap-3">
<Route className={`w-6 h-6 ${synthetiserEnabled ? 'text-purple-600' : 'text-gray-400'}`} />
<div>
<div className="font-medium text-gray-900">Activer le router</div>
<div className="text-sm text-gray-500">
{!synthetiserEnabled
? 'Nécessite la synthèse activée'
: config.enabled
? 'Envoi vers base de connaissances'
: 'Sans routage'}
</div>
</div>
</div>
<label className="relative inline-flex items-center cursor-pointer">
<input type="checkbox" checked={config.enabled} onChange={() => synthetiserEnabled && onChange({ ...config, enabled: !config.enabled })} className="sr-only peer" />
<div className={`w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600 ${!synthetiserEnabled ? 'opacity-50 cursor-not-allowed' : ''}`}></div>
</label>
</div>
{config.enabled && synthetiserEnabled && (
<div className="pl-4">
<label className="block text-sm font-medium text-gray-700 mb-2">Router (destination des faits)</label>
{loading ? (
<div className="px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-500">Chargement...</div>
) : routers.length === 0 ? (
<div className="px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 text-gray-500">
<p>Aucune base de connaissances disponible</p>
<a
href={`/${orgId}/backoffice/knowledge-routers/new`}
className="inline-block mt-2 text-sm text-purple-600 hover:text-purple-800 font-medium"
>
Créer un router
</a>
</div>
) : (
<select value={selectedId} onChange={(e) => handleChange(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 bg-white">
<option value="" disabled={selectedId !== ""}>Choisir un router...</option>
{routers.map(r => (
<option key={r._id || r.id} value={r._id || r.id}>{r.name || `Router ${r._id || r.id}`}</option>
))}
</select>
)}
<p className="mt-2 text-sm text-gray-500">Les faits extraits seront automatiquement envoyés vers la base de connaissances de ce router.</p>
</div>
)}
</div>
)
}
export default function GenericWorkflow() {
const { currentOrganization } = useOrganizationStore()
const orgId = currentOrganization?.id
const { syntheses, addSynthesis, updateSynthesis } = useWorkflowStore()
const [source, setSource] = useState({ type: 'input' })
const [synthetiser, setSynthetiser] = useState({
enabled: true,
mode: 'fact',
instruction: '',
maxItems: 10
})
const [router, setRouter] = useState({ enabled: false, routers: [] })
const [llmModel, setLlmModel] = useState('deepseek/deepseek-v4-flash')
const [isProcessing, setIsProcessing] = useState(false)
const [browserProvider, setBrowserProvider] = useState('playwright')
const brightdataConfigured = true
const browserlessConfigured = true
// Modaux
const [markdownModal, setMarkdownModal] = useState({ isOpen: false, content: '', title: '' })
const [factsModal, setFactsModal] = useState({ isOpen: false, content: '', title: '' })
const [dataModal, setDataModal] = useState({ isOpen: false, content: '', title: '' })
const [routingModal, setRoutingModal] = useState({ isOpen: false, routing: null, title: '' })
const [previewModal, setPreviewModal] = useState({ isOpen: false, pages: [], title: '' })
const connectSSE = async (jobId, synthesisId) => {
const response = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:8000'}/api/v1/jobs/${jobId}/status`, {
headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` }
})
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop()
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6))
updateSynthesis(synthesisId, { status: data.status, progress: data.progress, step: data.step, message: data.message })
if (data.type === 'completed' || data.status === 'completed') {
// Outputs are stored in MongoDB by the workflow - read immediately
const resultsRes = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:8000'}/api/v1/jobs/${jobId}/results`, {
headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` }
})
if (resultsRes.ok) {
const resultsData = await resultsRes.json()
updateSynthesis(synthesisId, {
status: 'completed',
outputs: resultsData.outputs || resultsData.data?.outputs
})
} else {
updateSynthesis(synthesisId, { status: 'completed' })
}
reader.cancel()
return
}
if (data.type === 'failed' || data.status === 'failed') {
const errorMessage = data.message || 'Job failed'
updateSynthesis(synthesisId, { status: 'failed', error: errorMessage })
toast.error(`Erreur: ${errorMessage}`)
reader.cancel()
return
}
}
}
}
}
const handleStart = async () => {
// Validation
if (source.type === 'input' && !source.input?.trim()) return toast.error('Entrez un texte')
if (source.type === 'web' && !source.url?.trim()) return toast.error('Entrez une URL')
if (source.type === 'fileUrl' && !source.fileUrl?.trim()) return toast.error('Entrez une URL de fichier')
if (source.type === 'fileUpload' && !source.file) return toast.error('Sélectionnez un fichier')
const synthesisId = Date.now()
addSynthesis({
id: synthesisId,
type: source.type,
url: source.url || source.fileUrl,
input: source.input,
file: source.file,
workflowName: 'Workflow Générique',
status: 'pending',
progress: 0,
step: 'connecting'
})
setIsProcessing(true)
try {
// Préparer payload
let payload = {}
if (source.type === 'input') {
const inputPayload = { content: source.input }
if (source.sourceText) inputPayload.source = source.sourceText
payload = { input: inputPayload }
} else {
payload.extractor = { type: source.type === 'fileUrl' || source.type === 'fileUpload' ? 'file' : 'web' }
if (source.type === 'web') payload.extractor.url = source.url
if (source.type === 'fileUrl') payload.extractor.fileUrl = source.fileUrl
if (source.type === 'fileUpload') {
const uploadResp = await uploadFile(source.file, orgId)
payload.extractor.fileId = uploadResp.data.data?.fileId
payload.extractor.filename = uploadResp.data.data?.filename
}
if (browserProvider !== 'playwright') {
payload.extractor.browserProvider = browserProvider
}
}
// Ajouter synthetiser si activé
if (synthetiser.enabled) {
payload.synthetiser = {
mode: synthetiser.mode,
spec: synthetiser.mode === 'fact'
? { instruction: synthetiser.instruction, maxFacts: synthetiser.maxItems }
: { schema: fieldsToSchemaWithRoot(synthetiser.schemaFields || createInitialFields()) }
}
}
// Ajouter router si activé
if (synthetiser.enabled && router.enabled && router.routers?.length > 0) {
payload.router = router.routers
}
payload.llmModel = llmModel
const response = await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:8000'}/api/v1/${currentOrganization?.id}/workflow/extract`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
},
body: JSON.stringify(payload)
})
const data = await response.json()
if (data.success && data.data?.jobId) {
updateSynthesis(synthesisId, { jobId: data.data.jobId, status: 'running' })
connectSSE(data.data.jobId, synthesisId)
toast.success('Extraction démarrée')
} else {
throw new Error(data.message || 'Erreur')
}
} catch (error) {
updateSynthesis(synthesisId, { status: 'failed', error: error.message })
toast.error(`Erreur: ${error.message}`)
} finally {
setIsProcessing(false)
}
}
// Helpers pour l'affichage des résultats
const getOutput = (synthesis, type) => synthesis.outputs?.find(o => o.type === type)
const getStatusColor = (status) => {
switch (status) {
case 'completed': return 'border-green-500'
case 'failed': return 'border-red-500'
case 'running': return 'border-purple-500'
default: return 'border-gray-300'
}
}
const getStatusIcon = (status) => {
switch (status) {
case 'completed': return <CheckCircle className="w-5 h-5 text-green-500" />
case 'failed': return <AlertCircle className="w-5 h-5 text-red-500" />
case 'running': return <Loader2 className="w-5 h-5 text-purple-500 animate-spin" />
default: return <Clock className="w-5 h-5 text-gray-400" />
}
}
const getTypeIcon = (type) => {
if (type === 'file' || type === 'fileUrl' || type === 'fileUpload') return <FileType className="w-4 h-4" />
if (type === 'input') return <Type className="w-4 h-4" />
return <Globe className="w-4 h-4" />
}
const getTypeLabel = (type) => {
if (type === 'file' || type === 'fileUrl' || type === 'fileUpload') return 'Fichier'
if (type === 'input') return 'Texte'
return 'Web'
}
const getPreviewUrls = (synthesis) => {
const outputs = synthesis.outputs || []
const imageOutputs = outputs
.filter(o => o.type === 'page-image')
.sort((a, b) => {
const getPageNum = (path) => {
const match = path?.match(/page-(\d+)/)
return match ? parseInt(match[1]) : 0
}
return getPageNum(a.outputPath) - getPageNum(b.outputPath)
})
return imageOutputs.map(o => ({
url: o.url || `http://localhost:9000/${o.bucket}/${o.outputPath}`,
page: o.metadata?.page || 1
}))
}
const hasPreview = (synthesis) => {
return getPreviewUrls(synthesis).length > 0
}
const viewExtraction = async (synthesis) => {
const extractionOutput = synthesis.outputs?.find(o => o.type === 'extraction')
if (!extractionOutput?.url) {
toast('Résultat non disponible')
return
}
try {
const response = await fetch(extractionOutput.url)
const content = await response.text()
const title = synthesis.file?.name || synthesis.url || synthesis.input?.substring(0, 50) || 'Extraction'
setMarkdownModal({ isOpen: true, content, title })
} catch (err) {
toast.error('Erreur lors du chargement')
}
}
const viewSynthesis = async (synthesis) => {
const factsOutput = synthesis.outputs?.find(o => o.type === 'facts' || o.type === 'data')
if (!factsOutput?.url) {
toast('Synthèse non disponible')
return
}
try {
const response = await fetch(factsOutput.url)
const text = await response.text()
if (factsOutput.type === 'data') {
setDataModal({ isOpen: true, content: text, title: synthesis.workflowName || 'Synthèse' })
} else {
setFactsModal({ isOpen: true, content: text, title: synthesis.workflowName || 'Synthèse' })
}
} catch (err) {
toast.error('Erreur lors du chargement')
}
}
const viewRouting = (synthesis) => {
const routingOutput = synthesis.outputs?.find(o => o.type === 'routing')
if (routingOutput) {
setRoutingModal({
isOpen: true,
routing: routingOutput,
title: synthesis.title || 'Routage'
})
}
}
const viewPreview = (synthesis) => {
const pages = getPreviewUrls(synthesis)
if (pages.length > 0) {
setPreviewModal({
isOpen: true,
pages,
title: synthesis.workflowName || synthesis.title || 'Aperçu'
})
} else {
toast('Aucun aperçu disponible')
}
}
const copyToClipboard = async (synthesis, type = 'synthesis') => {
const output = type === 'extraction'
? synthesis.outputs?.find(o => o.type === 'extraction')
: synthesis.outputs?.find(o => o.type === 'facts' || o.type === 'data')
if (!output?.url) {
toast('Résultat non disponible')
return
}
try {
const response = await fetch(output.url)
const content = await response.text()
await navigator.clipboard.writeText(content)
toast.success('Contenu copié !')
} catch (e) {
toast.error('Impossible de copier')
}
}
const downloadSynthesis = async (synthesis) => {
const output = synthesis.outputs?.find(o => o.type === 'facts' || o.type === 'data')
if (!output?.url) {
toast('Téléchargement non disponible')
return
}
const a = document.createElement('a')
a.href = output.url
a.download = 'extraction.json'
a.click()
}
const downloadExtraction = async (synthesis) => {
const output = synthesis.outputs?.find(o => o.type === 'extraction')
if (!output?.url) {
toast('Téléchargement non disponible')
return
}
const a = document.createElement('a')
a.href = output.url
a.download = `${synthesis.workflowName || 'extraction'}.md`
a.click()
}
return (
<div className="max-w-4xl mx-auto p-3 sm:p-6">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 flex items-center">
<Settings className="w-8 h-8 mr-3 text-purple-600" />
Extraction Manuelle
</h1>
<p className="text-gray-600 mt-2">Configurez manuellement votre extraction avec l'IA</p>
</div>
{/* Configuration */}
<div className="card space-y-8">
{/* Source */}
<div className="pb-6 border-b border-gray-200">
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
<span className="w-8 h-8 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center text-sm font-bold">1</span>
Source
</h2>
<SourceSection sourceType={source.type} onChange={setSource} datalabConfigured={true} />
</div>
{/* Navigateur (uniquement pour web/fileUrl) */}
{(source.type === 'web' || source.type === 'fileUrl') && (
<div className="pb-6 border-b border-gray-200">
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
<span className="w-8 h-8 rounded-full bg-green-100 text-green-600 flex items-center justify-center text-sm font-bold">1.5</span>
Navigateur
</h2>
<div className="space-y-3">
<select
value={browserProvider}
onChange={(e) => setBrowserProvider(e.target.value)}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 bg-white text-sm"
>
<option value="playwright">Playwright (intégré)</option>
{brightdataConfigured && <option value="brightdata">Bright Data</option>}
{browserlessConfigured && <option value="browserless">Browserless.io</option>}
</select>
<p className="text-xs text-gray-500">
{browserProvider === 'playwright' ? 'Navigateur headless intégré au serveur.' : ''}
{browserProvider === 'brightdata' ? 'Proxy résidentiel Bright Data (IP propre).' : ''}
{browserProvider === 'browserless' ? 'Navigateur cloud Browserless.io.' : ''}
</p>
</div>
</div>
)}
{/* Synthetiser */}
<div className="pb-6 border-b border-gray-200">
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
<span className="w-8 h-8 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center text-sm font-bold">2</span>
Synthèse
</h2>
<SynthetiserSection config={synthetiser} onChange={setSynthetiser} llmModel={llmModel} onLlmModelChange={setLlmModel} openrouterConfigured={true} />
</div>
{/* Router */}
<div className="pb-6 border-b border-gray-200">
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
<span className="w-8 h-8 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center text-sm font-bold">3</span>
Router
</h2>
<RouterSection
config={router}
onChange={setRouter}
synthetiserEnabled={synthetiser.enabled}
/>
</div>
{/* Bouton */}
<button
onClick={handleStart}
disabled={isProcessing}
className="w-full py-4 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center justify-center gap-2 font-semibold"
>
{isProcessing ? <Loader2 className="w-5 h-5 animate-spin" /> : <><Brain className="w-5 h-5" /> Démarrer</>}
</button>
</div>
{/* Active & Recent Extractions */}
<SynthesisResults
syntheses={syntheses}
onViewExtraction={viewExtraction}
onViewSynthesis={viewSynthesis}
onViewRouting={viewRouting}
onViewPreview={viewPreview}
onCopy={copyToClipboard}
onDownloadExtraction={downloadExtraction}
onDownloadSynthesis={downloadSynthesis}
/>
{/* Modaux */}
<MarkdownViewerModal isOpen={markdownModal.isOpen} onClose={() => setMarkdownModal({ isOpen: false })} content={markdownModal.content} title={markdownModal.title} />
<FactsViewerModal isOpen={factsModal.isOpen} onClose={() => setFactsModal({ isOpen: false })} content={factsModal.content} title={factsModal.title} />
<DataViewerModal isOpen={dataModal.isOpen} onClose={() => setDataModal({ isOpen: false })} content={dataModal.content} title={dataModal.title} />
<RoutingViewerModal isOpen={routingModal.isOpen} onClose={() => setRoutingModal({ isOpen: false })} routing={routingModal.routing} title={routingModal.title} />
<PageViewerModal isOpen={previewModal.isOpen} onClose={() => setPreviewModal({ isOpen: false })} pages={previewModal.pages} title={previewModal.title} />
</div>
)
}
|