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 | import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
Brain,
Table,
Save,
Play,
Trash2
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { workflowAPI } from '../../services/api';
import DestinationsEditor, {
workflowToDisplayDestination,
workflowRefinementMode,
} from '../components/DestinationsEditor';
import toast from 'react-hot-toast';
import { handleApiError } from '../../utils/apiErrorHandler';
import { useOrganizationStore } from '../../store/organizationStore';
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
// Le raffinage (mode/spec/modèle) est porté par chaque destination,
// pas par le workflow lui-même.
const [formData, setFormData] = useState({
id: '',
name: '',
description: '',
destinations: [],
});
// 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 || [];
}
});
// Initialize form when workflow data is loaded
useEffect(() => {
if (workflow && !isNew) {
// Les destinations « Afficher » sont stockées dans destinations[] comme les autres.
const destinations = workflow.destinations || [];
// Rétrocompatibilité : un workflow ancien sans destination « Afficher » mais avec un
// raffinage significatif au niveau workflow (mode/spec/llmModel) expose une
// destination « Afficher » synthétisée — sans la dupliquer si un display existe déjà.
const hasDisplay = destinations.some((d) => d.type === 'display');
const legacyDisplay = hasDisplay ? null : workflowToDisplayDestination(workflow);
setFormData({
id: workflow._id || workflow.id,
name: workflow.name,
description: workflow.description || '',
destinations: legacyDisplay ? [legacyDisplay, ...destinations] : [...destinations],
});
}
}, [workflow, isNew]);
// Create/Update mutation
const saveWorkflow = useMutation({
mutationFn: async (data) => {
// Les destinations (dont « Afficher ») sont stockées telles quelles dans destinations[].
// Le raffinage de repli du workflow (mode/spec/llmModel) reste optionnel
// côté backend : on ne la dérive plus de la première destination « Afficher ».
const payload = {
name: data.name,
description: data.description,
organizationId,
destinations: data.destinations,
};
if (!isNew && data.id) {
return workflowAPI.updateConfig(data.id, payload);
}
return workflowAPI.createConfig(payload);
},
onSuccess: () => {
toast.success(isNew ? 'Workflow prédéfini créé' : 'Workflow prédéfini 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 prédéfini supprimé');
queryClient.invalidateQueries(['workflows']);
navigate(`/${organizationId}/backoffice/workflows`);
},
onError: (error) => {
toast.error(handleApiError(error));
}
});
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 prédéfinis"
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">
{workflowRefinementMode(wf) === 'data' ? (
<Table className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-indigo-400' : 'text-slate-500'}`} />
) : (
<Brain className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-purple-400' : 'text-slate-500'}`} />
)}
<span className={`text-sm font-medium truncate flex-1 ${isSelected ? 'text-white' : 'text-slate-300'}`}>
{wf.name}
</span>
<span className="text-xs text-slate-500">{workflowRefinementMode(wf) === 'data' ? 'Données' : 'Assertions'}</span>
</div>
{wf.description && (
<div className="text-xs text-slate-400 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 flex-wrap justify-end gap-2">
{!isNew && (
<>
<Link
to={`/${organizationId}/workflow/${id}`}
className="flex items-center px-2 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
title="Ouvrir dans le frontoffice"
>
<Play className="w-4 h-4" />
</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 raffineur"
/>
</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: 'Obtient les informations de contact des fiches entreprise', 'Raffine 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 raffineur.
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Destinations</label>
<DestinationsEditor
value={formData.destinations}
onChange={(destinations) => setFormData({ ...formData, destinations })}
disabled={saveWorkflow.isLoading}
/>
<p className="text-xs text-gray-500 mt-2">
Chaque destination définit son propre raffinage (mode, instruction ou schéma, modèle LLM)
et sa cible : affichage (aucune cible), KB interne ou API externe. Une destination
« Afficher » n'a aucune cible et conserve son raffinage.
</p>
</div>
{isLoadingWorkflow && (
<span className="text-sm text-gray-500">Chargement des données...</span>
)}
</form>
</div>
</div>
</div>
</BackofficeEntityPage>
);
}
|