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 | import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
Brain,
Table,
Save,
X,
ArrowLeft,
Code,
Loader2,
ExternalLink,
Trash2
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api, { workflowAPI } from '../../services/api';
import SchemaEditor, { parseSchema, createInitialFields, fieldsToSchemaWithRoot } from '../../components/SchemaEditor';
import toast from 'react-hot-toast';
import { handleApiError } from '../../utils/apiErrorHandler';
import { useOrganizationStore } from '../../store/organizationStore';
import ModelSelector from '../../components/ModelSelector';
import EntitySidebar from '../../components/EntitySidebar';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
export default function WorkflowEdit() {
const { id } = useParams();
const { currentOrganization } = useOrganizationStore();
const organizationId = currentOrganization?.id;
const navigate = useNavigate();
const queryClient = useQueryClient();
const isNew = id === 'new';
// Form state
const [formData, setFormData] = useState({
id: '',
name: '',
description: '',
mode: 'fact',
instruction: '',
maxFacts: 100,
schemaFields: createInitialFields(),
routerId: '',
targetKnowledgeBases: [],
llmModel: 'deepseek/deepseek-v4-flash'
});
// Fetch workflow details if editing
const { data: workflow, isLoading: isLoadingWorkflow } = useQuery({
queryKey: ['workflow', id],
queryFn: async () => {
if (isNew) return null;
const response = await workflowAPI.getConfig(id);
return response.data.data;
},
enabled: !isNew
});
const { data: workflowsList, isLoading: workflowsListLoading } = useQuery({
queryKey: ['workflows', organizationId],
queryFn: async () => {
const response = await workflowAPI.list();
return response.data.data || [];
}
});
// Fetch available routers
const { data: routers } = useQuery({
queryKey: ['routers'],
queryFn: async () => {
const response = await api.get('/knowledge-routers');
return response.data.data?.map(router => ({
id: router._id || router.id,
name: router.name || `Router ${router._id || router.id}`,
...router
})) || [];
}
});
// Initialize form when workflow data is loaded
useEffect(() => {
if (workflow && !isNew) {
let schemaFields = createInitialFields();
if (workflow.mode === 'data' && workflow.spec?.schema) {
schemaFields = parseSchema(workflow.spec.schema);
}
setFormData({
id: workflow._id || workflow.id,
name: workflow.name,
description: workflow.description || '',
mode: workflow.mode,
instruction: workflow.spec?.instruction || '',
maxFacts: workflow.spec?.maxFacts || 100,
schemaFields: schemaFields,
routerId: workflow.router_id || workflow.routerId || '',
targetKnowledgeBases: workflow.target_knowledge_bases || workflow.targetKnowledgeBases || [],
llmModel: workflow.llmModel || 'deepseek/deepseek-v4-flash'
});
}
}, [workflow, isNew]);
// Create/Update mutation
const saveWorkflow = useMutation({
mutationFn: async (data) => {
const spec = data.mode === 'fact'
? { instruction: data.instruction, maxFacts: data.maxFacts }
: { schema: fieldsToSchemaWithRoot(data.schemaFields) };
const payload = {
...data,
organizationId,
spec: spec,
router_id: data.routerId || null,
target_knowledge_bases: data.targetKnowledgeBases
};
if (!isNew && data.id) {
return workflowAPI.updateConfig(data.id, payload);
}
return workflowAPI.createConfig(payload);
},
onSuccess: () => {
toast.success(isNew ? 'Workflow créé' : 'Workflow mis à jour');
queryClient.invalidateQueries(['workflows']);
navigate(`/${organizationId}/backoffice/workflows`);
},
onError: (error) => {
toast.error(handleApiError(error));
}
});
const handleSubmit = (e) => {
e.preventDefault();
saveWorkflow.mutate(formData);
};
const deleteWorkflow = useMutation({
mutationFn: async () => {
return workflowAPI.deleteConfig(id);
},
onSuccess: () => {
toast.success('Workflow supprimé');
queryClient.invalidateQueries(['workflows']);
navigate(`/${organizationId}/backoffice/workflows`);
},
onError: (error) => {
toast.error(handleApiError(error));
}
});
const handleModeChange = (newMode) => {
setFormData({
...formData,
mode: newMode
});
};
const handleCancel = () => {
navigate(`/${organizationId}/backoffice/workflows`);
};
const sidebar = (
<EntitySidebar
items={workflowsList || []}
selectedId={isNew ? null : id}
getItemHref={(wf) => `/${organizationId}/backoffice/workflows/${wf._id || wf.id}`}
searchPlaceholder="Rechercher un workflow..."
emptyMessage="Aucun workflow disponible"
title="Workflows"
icon={Brain}
iconClass="text-purple-600"
backofficeTo={`/${organizationId}/backoffice/workflows/new`}
backofficeManageLabel="Créer un workflow"
backofficeCreateLabel="Créer un workflow"
createOnly
loading={workflowsListLoading}
filterFn={(wf) => `${wf.name} ${wf.description || ''}`}
renderItem={(wf, isSelected) => (
<>
<div className="flex items-center">
{wf.mode === 'fact' ? (
<Brain className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-purple-600' : 'text-gray-400'}`} />
) : (
<Table className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-indigo-600' : 'text-gray-400'}`} />
)}
<span className={`text-sm font-medium truncate flex-1 ${isSelected ? 'text-gray-900' : 'text-gray-700'}`}>
{wf.name}
</span>
<span className="text-xs text-gray-400">{wf.mode === 'fact' ? 'Faits' : 'Données'}</span>
</div>
{wf.description && (
<div className="text-xs text-gray-500 truncate mt-0.5">{wf.description}</div>
)}
</>
)}
/>
);
return (
<BackofficeEntityPage selectedId={isNew ? null : id} sidebar={sidebar}>
<div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
<div className="space-y-6">
<div className="flex justify-end gap-2">
{!isNew && (
<>
<Link
to={`/${organizationId}/workflow/${id}`}
className="flex items-center px-3 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
title="Exploiter ce workflow dans le frontoffice"
>
<ExternalLink className="w-4 h-4 mr-2" />
Exploiter
</Link>
<button
onClick={() => {
if (confirm('Êtes-vous sûr de vouloir supprimer ce workflow ?')) {
deleteWorkflow.mutate();
}
}}
className="flex items-center px-3 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50"
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
</button>
</>
)}
<button
type="submit"
form="workflow-edit-form"
disabled={saveWorkflow.isLoading}
className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
>
<Save className="w-4 h-4 mr-2" />
{saveWorkflow.isLoading ? 'Sauvegarde...' : isNew ? 'Créer' : 'Sauvegarder'}
</button>
</div>
{/* Form */}
<div className="bg-white rounded-lg shadow p-6">
<form id="workflow-edit-form" onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Nom</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
required
placeholder="Nom du synthétiseur"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Description <span className="text-gray-400 font-normal">(facultatif)</span>
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Décrivez ce que fait ce workflow pour aider les autres utilisateurs à comprendre son usage (ex: 'Extrait les informations de contact des fiches entreprise', 'Synthétise les données produit des catalogues', etc.)"
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
rows={3}
/>
<p className="mt-1 text-xs text-gray-500">
Cette description est visible par tous les utilisateurs pour comprendre le rôle de ce synthétiseur.
</p>
</div>
{/* Mode Selection */}
<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={formData.mode === 'fact'}
onChange={() => handleModeChange('fact')}
className="sr-only"
/>
<div className={`flex items-center gap-3 p-3 rounded-lg border-2 transition-colors ${
formData.mode === 'fact'
? 'border-purple-500 bg-purple-50'
: 'border-gray-200 hover:border-gray-300'
}`}>
<Brain className={`w-6 h-6 ${formData.mode === 'fact' ? 'text-purple-600' : 'text-gray-400'}`} />
<div>
<div className={`font-medium ${formData.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={formData.mode === 'data'}
onChange={() => handleModeChange('data')}
className="sr-only"
/>
<div className={`flex items-center gap-3 p-3 rounded-lg border-2 transition-colors ${
formData.mode === 'data'
? 'border-indigo-500 bg-indigo-50'
: 'border-gray-200 hover:border-gray-300'
}`}>
<Table className={`w-6 h-6 ${formData.mode === 'data' ? 'text-indigo-600' : 'text-gray-400'}`} />
<div>
<div className={`font-medium ${formData.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>
<div className="px-1 pb-1">
<p className="text-xs text-gray-500 mb-1">Modèle LLM pour l'extraction</p>
<ModelSelector
value={formData.llmModel}
onChange={(val) => setFormData({ ...formData, llmModel: val })}
/>
</div>
{/* Mode FACT: Instruction */}
{formData.mode === 'fact' && (
<>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Instruction d'extraction
</label>
<textarea
value={formData.instruction}
onChange={(e) => setFormData({ ...formData, instruction: e.target.value })}
placeholder="Décrivez quels faits extraire (ex: extraire les noms de personnes, dates, lieux...)"
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
rows={4}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Nombre max de faits
</label>
<input
type="number"
value={formData.maxFacts}
onChange={(e) => setFormData({ ...formData, maxFacts: parseInt(e.target.value) || 100 })}
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
min="1"
max="1000"
/>
</div>
</>
)}
{/* Mode DATA: Schema Editor */}
{formData.mode === 'data' && (
<div className="border rounded-lg p-4">
<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={formData.schemaFields}
onChange={(fields) => setFormData({ ...formData, schemaFields: fields })}
disabled={saveWorkflow.isLoading}
/>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Router (optionnel)</label>
<select
value={formData.routerId}
onChange={(e) => setFormData({ ...formData, routerId: e.target.value })}
className="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
>
<option value="">Aucun router</option>
{routers?.map((r) => (
<option key={r.id} value={r.id}>{r.name}</option>
))}
</select>
</div>
{isLoadingWorkflow && (
<span className="text-sm text-gray-500">Chargement des données...</span>
)}
</form>
</div>
</div>
</div>
</BackofficeEntityPage>
);
}
|