data-primals-engine 1.7.1 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +9 -9
  2. package/client/package-lock.json +8430 -8121
  3. package/client/package.json +7 -4
  4. package/client/src/APIInfo.jsx +1 -1
  5. package/client/src/App.jsx +2 -1
  6. package/client/src/App.scss +1635 -1626
  7. package/client/src/AssistantChat.jsx +2 -3
  8. package/client/src/CalendarView.jsx +1 -0
  9. package/client/src/ContentView.jsx +3 -3
  10. package/client/src/Dashboard.jsx +5 -2
  11. package/client/src/DashboardChart.jsx +1 -0
  12. package/client/src/DashboardFlexViewItem.jsx +1 -0
  13. package/client/src/DashboardHtmlViewItem.jsx +1 -0
  14. package/client/src/DashboardView.jsx +2 -0
  15. package/client/src/DataEditor.jsx +0 -1
  16. package/client/src/DataImporter.jsx +489 -468
  17. package/client/src/DataLayout.jsx +25 -23
  18. package/client/src/DataTable.jsx +6 -5
  19. package/client/src/Dialog.jsx +92 -90
  20. package/client/src/Dialog.scss +122 -116
  21. package/client/src/DisplayFlexNodeRenderer.jsx +1 -0
  22. package/client/src/DocumentationPageLayout.scss +1 -1
  23. package/client/src/FlexBuilderControls.jsx +1 -0
  24. package/client/src/FlexBuilderPreview.jsx +1 -1
  25. package/client/src/FlexNode.jsx +1 -1
  26. package/client/src/HistoryDialog.jsx +3 -2
  27. package/client/src/KPIWidget.jsx +1 -1
  28. package/client/src/KanbanView.jsx +1 -0
  29. package/client/src/ModelCreator.jsx +4 -0
  30. package/client/src/ModelList.jsx +1 -0
  31. package/client/src/PackGallery.jsx +5 -4
  32. package/client/src/RTETrans.jsx +1 -1
  33. package/client/src/RelationField.jsx +2 -0
  34. package/client/src/RelationSelectorWidget.jsx +2 -0
  35. package/client/src/RelationValue.jsx +1 -0
  36. package/client/src/RestoreDialog.jsx +1 -0
  37. package/client/src/ViewSwitcher.jsx +1 -1
  38. package/client/src/WorkflowEditor.jsx +3 -0
  39. package/client/src/contexts/CommandContext.jsx +2 -1
  40. package/client/src/contexts/ModelContext.jsx +3 -3
  41. package/client/src/hooks/data.js +1 -0
  42. package/client/src/hooks/useValidation.js +1 -0
  43. package/client/src/translations.js +24 -24
  44. package/client/vite.config.js +31 -30
  45. package/doc/AI-assistance.md +87 -63
  46. package/doc/Concepts.md +122 -0
  47. package/doc/Custom-Endpoints.md +31 -0
  48. package/doc/Event-system.md +13 -14
  49. package/doc/Home.md +33 -0
  50. package/doc/Modules.md +83 -0
  51. package/doc/Packs-gallery.md +8 -23
  52. package/doc/Workflows.md +32 -0
  53. package/doc/automation-workflows.md +141 -102
  54. package/doc/dashboards-kpis-charts.md +47 -49
  55. package/doc/data-management.md +126 -120
  56. package/doc/data-models.md +68 -75
  57. package/doc/roles-permissions.md +144 -43
  58. package/doc/sharding-replication.md +158 -0
  59. package/doc/users.md +54 -30
  60. package/package.json +27 -17
  61. package/server.js +37 -37
  62. package/src/ai.jobs.js +135 -0
  63. package/src/constants.js +560 -545
  64. package/src/data.js +521 -518
  65. package/src/email.js +157 -154
  66. package/src/engine.js +167 -49
  67. package/src/gameObject.js +6 -0
  68. package/src/i18n.js +0 -1
  69. package/src/modules/assistant/assistant.js +782 -763
  70. package/src/modules/assistant/constants.js +23 -16
  71. package/src/modules/assistant/providers.js +77 -37
  72. package/src/modules/auth-google/index.js +53 -50
  73. package/src/modules/bucket.js +346 -335
  74. package/src/modules/data/data.backup.js +400 -376
  75. package/src/modules/data/data.cluster.js +559 -0
  76. package/src/modules/data/data.core.js +11 -8
  77. package/src/modules/data/data.js +311 -311
  78. package/src/modules/data/data.operations.js +3666 -3555
  79. package/src/modules/data/data.relations.js +1 -0
  80. package/src/modules/data/data.replication.js +125 -0
  81. package/src/modules/data/data.routes.js +2206 -1879
  82. package/src/modules/data/data.scheduling.js +2 -1
  83. package/src/modules/file.js +248 -247
  84. package/src/modules/mongodb.js +76 -73
  85. package/src/modules/user.js +18 -2
  86. package/src/modules/worker-script-runner.js +97 -0
  87. package/src/modules/workflow.js +177 -52
  88. package/src/packs.js +5701 -5701
  89. package/src/providers.js +298 -297
  90. package/src/sso.js +91 -25
  91. package/test/assistant.test.js +207 -206
  92. package/test/cluster.test.js +221 -0
  93. package/test/core.test.js +0 -2
  94. package/test/data.integration.test.js +1425 -1416
  95. package/test/import_export.integration.test.js +210 -210
  96. package/test/replication.test.js +163 -0
  97. package/test/workflow.actions.integration.test.js +487 -475
  98. package/test/workflow.integration.test.js +332 -329
  99. package/doc/core-concepts.md +0 -33
@@ -1,469 +1,490 @@
1
- import {useAuthContext} from "./contexts/AuthContext.jsx";
2
- import {useModelContext} from "./contexts/ModelContext.jsx";
3
- import {useNotificationContext} from "./NotificationProvider.jsx";
4
- import {useEffect, useRef, useState} from "react";
5
- import {Trans, useTranslation} from "react-i18next";
6
- import {useMutation, useQueryClient} from "react-query";
7
- import useLocalStorage from "./hooks/useLocalStorage.js";
8
- import {getUserId} from "../../src/data.js";
9
- import {kilobytes, maxBytesPerSecondThrottleData, maxFileSize} from "../../src/constants";
10
- import {FileField, ModelField} from "./Field.jsx";
11
- import Button from "./Button.jsx";
12
- import {FaInfo, FaTrash} from "react-icons/fa";
13
- import {Dialog} from "./Dialog.jsx";
14
- import readXlsxFile from 'read-excel-file'
15
- // Ajoutez cette constante pour la clé de sessionStorage
16
- const SESSION_STORAGE_IMPORT_JOBS_KEY = 'activeImportJobs';
17
-
18
- export function DataImporter({onClose}) {
19
- const [previewData, setPreviewData] = useState(null);
20
- const [file, setFile] = useState(null);
21
- const {selectedModel, page} = useModelContext();
22
-
23
- const isCsvFile = file && (file.name.endsWith('.csv') || file.type === 'text/csv');
24
- const isExcelFile = file && ((file.name.endsWith('.xlsx') ||
25
- ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
26
- 'application/vnd.ms-excel'].includes(file.type)));
27
-
28
- const {me} = useAuthContext();
29
- const {t, i18n} = useTranslation();
30
-
31
- const queryClient = useQueryClient();
32
- const {addNotification} = useNotificationContext();
33
-
34
- const [hasHeaders, setHasHeaders] = useState(true);
35
- const [csvHeaders, setCSVHeaders] = useState(selectedModel.fields.map(field => field.name));
36
-
37
- // --- MODIFIÉ : État pour gérer plusieurs tâches d'importation ---
38
- // Cet objet stockera les données de progression de chaque tâche, indexées par leur jobId
39
- const [importJobs, setImportJobs] = useState({});
40
- // Cette liste stockera les IDs des tâches qui sont actuellement suivies via SSE
41
- const [activeJobIds, setActiveJobIds] = useState([]);
42
-
43
- // Référence pour stocker les instances EventSource, indexées par jobId
44
- const eventSourceRefs = useRef({});
45
-
46
- const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
47
-
48
- const [storedJobIds, setStoredJobIds] = useLocalStorage(SESSION_STORAGE_IMPORT_JOBS_KEY, []);
49
- // --- NOUVEAU : Charger/Sauvegarder les IDs des tâches actives depuis sessionStorage ---
50
- useEffect(() => {
51
- // Charger les IDs des tâches actives depuis sessionStorage au montage
52
- setActiveJobIds(storedJobIds);
53
-
54
- // Pour chaque jobId stockpour obtenir le dernier statut
55
- storedJobIds.forEach(jobId => {
56
- startProgressTracking(jobId);
57
- });
58
-
59
- // Fonction de nettoyage : fermer toutes les connexions EventSource lors du démontage du composant
60
- return () => {
61
- Object.values(eventSourceRefs.current).forEach(es => es.close());
62
- eventSourceRefs.current = {}; // Effacer les références
63
- };
64
- }, []); // S'exécute une seule fois au montage
65
-
66
- // --- NOUVEAU : Effet pour mettre à jour sessionStorage lorsque activeJobIds change ---
67
- useEffect(() => {
68
- setStoredJobIds(activeJobIds);
69
- }, [activeJobIds]);
70
-
71
-
72
- // Mutation pour initier l'importation (envoi du fichier au serveur)
73
- const {isLoading, mutate: importMutation} = useMutation(async () => {
74
- console.log('Initiating data import...');
75
- const params = new FormData();
76
- params.append('model', selectedModel?.name);
77
- params.append("_user", getUserId(me));
78
- params.append("hasHeaders", !!hasHeaders);
79
- params.append("csvHeaders", csvHeaders.join(','));
80
- if (file) {
81
- params.append("file", file);
82
- } else {
83
- addNotification({ title: t('dataimporter.noFileSelected', 'Veuillez sélectionner un fichier à importer.'), status: 'warning' });
84
- return Promise.reject(new Error("No file selected"));
85
- }
86
-
87
- try {
88
- const response = await fetch(`/api/data/import?lang=${lang}`, {
89
- method: 'POST',
90
- body: params
91
- });
92
-
93
- if (response.status === 202) {
94
- const { job } = await response.json();
95
- const { jobId} = job;
96
-
97
- // --- MODIFIÉ : Ajouter le nouvel jobId à activeJobIds et à l'état importJobs ---
98
- setActiveJobIds(prevIds => [...prevIds, jobId]);
99
- setImportJobs(prevJobs => ({
100
- ...prevJobs,
101
- [jobId]: {
102
- jobId,
103
- status: 'pending',
104
- totalRecords: 0,
105
- processedRecords: 0,
106
- errors: [],
107
- // Ajoutez d'autres champs initiaux que vous souhaitez afficher immédiatement
108
- }
109
- }));
110
- startProgressTracking(jobId); // Commencer le suivi de cette nouvelle tâche
111
- addNotification({
112
- title: t('dataimporter.initiated', 'Importation initiée. Suivi de la progression...'),
113
- icon: <FaInfo/>,
114
- status: 'info'
115
- });
116
- } else {
117
- const errorData = await response.json();
118
- addNotification({
119
- title: errorData.error || t('dataimporter.error', 'Erreur lors de l\'importation.'),
120
- status: 'error'
121
- });
122
- }
123
- } catch (e) {
124
- addNotification({
125
- title: e.message || t('dataimporter.networkError', 'Erreur réseau lors de l\'importation.'),
126
- status: 'error'
127
- });
128
- }
129
- });
130
-
131
- // Fonction pour démarrer le suivi de la progression via Server-Sent Events (SSE) pour un jobId spécifique
132
-
133
- // Fonction pour démarrer le suivi de la progression via Server-Sent Events (SSE) pour un jobId spécifique
134
- const startProgressTracking = (jobId) => {
135
- // Fermer toute connexion EventSource existante pour ce jobId pour éviter les doublons
136
- if (eventSourceRefs.current[jobId]) {
137
- eventSourceRefs.current[jobId].close();
138
- }
139
-
140
- const eventSource = new EventSource(`/api/import/progress/${jobId}`);
141
- eventSourceRefs.current[jobId] = eventSource; // Stocker l'instance pour le nettoyage
142
-
143
- eventSource.onmessage = (event) => {
144
- const data = JSON.parse(event.data);
145
- // --- MODIFIÉ : Mettre à jour la progression de la tâche spécifique ---
146
- setImportJobs(prevJobs => ({
147
- ...prevJobs,
148
- [jobId]: data
149
- }));
150
-
151
- // Si la tâche est terminée (succès ou échec), fermer la connexion SSE.
152
- // NE PAS la retirer de activeJobIds ici, pour qu'elle persiste au rafraîchissement.
153
- // Elle sera retirar le bouton "Effacer".
154
- if (data.status === 'completed' || data.status === 'failed' || data.status === 'not_found') {
155
- eventSource.close();
156
- delete eventSourceRefs.current[jobId]; // Supprimer la référence de l'EventSource
157
-
158
- // --- LIGNE MODIFIÉE/SUPPRIMÉE ---
159
- // Supprimez ou commentez la ligne suivante :
160
- // setActiveJobIds(prevIds => prevIds.filter(id => id !== jobId));
161
-
162
- queryClient.invalidateQueries(['api/data', selectedModel.name, 'page', page]); // Rafraîchir les données du tableau
163
-
164
- if (data.status === 'completed') {
165
- addNotification({
166
- title: t('dataimporter.success', 'Importation des données réussie.'),
167
- icon: <FaInfo/>,
168
- status: 'completed'
169
- });
170
- } else if (data.status === 'failed') {
171
- addNotification({
172
- title: t('dataimporter.failed', 'Importation échouée. Voir les détails pour les erreurs.'),
173
- status: 'error'
174
- });
175
- } else if (data.status === 'not_found') {
176
- addNotification({
177
- title: t('dataimporter.jobNotFound', 'Tâche d\'importation non trouvée ou déjà terminée.'),
178
- status: 'warning'
179
- });
180
- }
181
- }
182
- };
183
-
184
- eventSource.onerror = (error) => {
185
- console.error(`EventSource error for job ${jobId}:`, error);
186
- eventSource.close();
187
- delete eventSourceRefs.current[jobId];
188
- setStoredJobIds(prevIds => prevIds.filter(id => id !== jobId));
189
- };
190
- };
191
-
192
- const handleImportClick = () => {
193
- importMutation();
194
- };
195
-
196
- const handleCloseModal = () => {
197
- // Fermer toutes les connexions EventSource avant de fermer la modale
198
- Object.values(eventSourceRefs.current).forEach(es => es.close());
199
- eventSourceRefs.current = {}; // Effacer les références
200
- onClose();
201
- };
202
- const handleFilePreview = async (file) => {
203
- console.log('handleFilePreview');
204
- if (!file) {
205
- setPreviewData(null);
206
- return;
207
- }
208
-
209
- const isExcelFile = file && ((file.name.endsWith('.xlsx') ||
210
- ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
211
- 'application/vnd.ms-excel'].includes(file.type)));
212
-
213
- if (isExcelFile) {
214
- console.log('excel');
215
- try {
216
- const arrayBuffer = await file.arrayBuffer();
217
- const rows = await readXlsxFile(arrayBuffer);
218
- setPreviewData(rows);
219
- console.log(rows);
220
- } catch (error) {
221
- console.error('Error reading Excel file:', error);
222
- addNotification({
223
- title: t('dataimporter.excelReadError', 'Erreur lors de la lecture du fichier Excel'),
224
- status: 'error'
225
- });
226
- }
227
- } else {
228
- setPreviewData(null);
229
- }
230
- };
231
-
232
- // Déterminer si une importation est actuellement en cours (pour désactiver les boutons)
233
- const isAnyImportInProgress = Object.values(importJobs).some(job => job.status === 'pending' || job.status === 'processing');
234
-
235
- // Filtrer et trier les tâches à afficher (par exemple, les tâches en cours en premier)
236
- const jobsToDisplay = Object.values(importJobs).sort((a, b) => {
237
- // Trier par statut (en attente/en cours en premier, puis échoué, puis terminé)
238
- const statusOrder = { 'pending': 1, 'processing': 2, 'failed': 3, 'completed': 4, 'not_found': 5 };
239
- return statusOrder[a.status] - statusOrder[b.status];
240
- });
241
-
242
- const { models } = useModelContext();
243
-
244
- return (
245
- <Dialog isClosable={true} isModal={true} onClose={handleCloseModal}>
246
- <>
247
- <h2>
248
- <Trans i18nKey="dataimporter.title" values={{model: t('model_' + selectedModel?.name, selectedModel?.name)}}>
249
- Importer des données dans {t('model_' + selectedModel?.name, selectedModel?.name)}
250
- </Trans>
251
- </h2>
252
- <p className="msg msg-info">
253
- <Trans i18nKey="dataimporter.info" values={{constante: (maxBytesPerSecondThrottleData / kilobytes) + 'ko/s'}}></Trans>
254
- </p>
255
-
256
- {/* Toujours afficher le formulaire de sélection de fichier et le bouton d'importation */}
257
- <FileField
258
- name="file"
259
- maxSize={maxFileSize}
260
- mimeTypes={[
261
- 'application/json',
262
- 'text/csv',
263
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
264
- 'application/vnd.ms-excel'
265
- ]}
266
- type="file"
267
- multiple={false}
268
- onChange={async (files) => {
269
- const newFile = files && files.length > 0 ? files[files.length - 1].file : null;
270
- setFile(newFile);
271
- await handleFilePreview(newFile);
272
- }}
273
- />
274
-
275
- {file && (isExcelFile || isCsvFile) && (
276
- <div className="checkbox-label flex flex-row">
277
- {isCsvFile && (<label htmlFor="hasHeadersCheckbox">
278
- <input
279
- type="checkbox"
280
- id="hasHeadersCheckbox"
281
- checked={hasHeaders}
282
- onChange={(e) => setHasHeaders(e.target.checked)}
283
- />
284
- <Trans i18nKey="dataimporter.hasCsvHeaders"></Trans>
285
- </label>)}
286
- {(!hasHeaders || isExcelFile) && (
287
- <table>
288
- <thead>
289
- <tr>
290
- <th><Trans i18nKey={"dataimporter.columnType"} values={[isExcelFile?'Excel':'CSV']}>Numéro de colonne</Trans></th>
291
- <th><Trans i18nKey="dataimporter.field">Champ du modèle</Trans></th>
292
- </tr>
293
- </thead>
294
- <tbody>
295
- {selectedModel?.fields.map((field, index) => {
296
- const currentFieldValue = csvHeaders[index] || '';
297
- const fieldObject = selectedModel.fields.find(f => f.name === currentFieldValue);
298
-
299
- return (
300
- <tr key={`${selectedModel.name}-csvmap-${index}`}>
301
- <td><Trans i18nKey="dataimporter.column" values={[index + 1]}>colonne {index + 1}</Trans></td>
302
- <td>
303
- <div className="flex">
304
- <ModelField
305
- disableable={true}
306
- showModel={false}
307
- value={selectedModel.name}
308
- fieldValue={currentFieldValue}
309
- onChange={({name: propName, value: selectedValue}) => {
310
- const newCsvHeaders = [...csvHeaders];
311
- newCsvHeaders[index] = selectedValue?.field ?? '';
312
- setCSVHeaders(newCsvHeaders);
313
- }}
314
- fields={true}
315
- model={selectedModel}
316
- field={fieldObject}
317
- />
318
- <Button className="flex" onClick={() => {
319
- const newHeaders = [...csvHeaders];
320
- newHeaders.splice(index, 1);
321
- setCSVHeaders(newHeaders);
322
- }}><FaTrash/></Button>
323
- </div>
324
- </td>
325
- </tr>
326
- );
327
- })}
328
- <tr>
329
- <td colSpan={2}>
330
- <Button onClick={() => {
331
- const csvH = [...csvHeaders];
332
- csvH.push('');
333
- setCSVHeaders(csvH)
334
- }}><Trans i18nKey="dataimporter.addColumn">Ajouter une colonne</Trans></Button>
335
- </td>
336
- </tr>
337
- </tbody>
338
- </table>
339
- )}
340
- </div>
341
- )}
342
-
343
- {previewData && (
344
- <div className="excel-preview mt-4">
345
- <h3><Trans i18nKey="dataimporter.excelPreview">Aperçu des données Excel</Trans></h3>
346
- <div className="msg msg-tiny">
347
- <Trans i18nKey="dataimporter.previewNote">
348
- Note: Ceci est un aperçu des premières lignes. Les cellules vides sont affichées comme "(vide)".
349
- </Trans>
350
- </div>
351
- <div className="preview-table-container" style={{ maxHeight: '300px', overflow: 'auto' }}>
352
- <table className="preview-table">
353
- <thead>
354
- <tr>
355
- {previewData[0].map((_, colIndex) => {
356
- // Récupérer le nom du champ mappé pour cette colonne depuis l'état `csvHeaders`
357
- const mappedFieldName = csvHeaders[colIndex];
358
-
359
- // Si un champ est mappé, on affiche son nom traduit.
360
- // Sinon, on affiche un nom générique comme "Colonne X".
361
- const headerLabel = mappedFieldName
362
- ? t(`field_${mappedFieldName}`, mappedFieldName)
363
- : t('dataimporter.column', 'Colonne {{count}}', { count: colIndex + 1 });
364
-
365
- return (
366
- <th key={`header-${colIndex}`}>
367
- {headerLabel}
368
- </th>
369
- );
370
- })}
371
- </tr>
372
- </thead>
373
- <tbody>
374
- {previewData.map((row, rowIndex) => (
375
- <tr key={`row-${rowIndex}`}>
376
- {row.map((cell, cellIndex) => (
377
- <td
378
- key={`cell-${rowIndex}-${cellIndex}`}
379
- style={{
380
- border: '1px solid #ddd',
381
- padding: '4px',
382
- backgroundColor: rowIndex === 0 && hasHeaders ? '#f0f0f0' : 'transparent'
383
- }}
384
- >
385
- {cell !== null ? String(cell) : <span style={{ color: '#999' }}><Trans i18nKey="dataimporter.nullValue">(vide)</Trans></span>}
386
- </td>
387
- ))}
388
- </tr>
389
- ))}
390
- </tbody>
391
- </table>
392
- </div>
393
- </div>
394
- )}
395
- <div>
396
- <Button onClick={handleImportClick} disabled={isLoading || !file}>
397
- <Trans i18nKey="btns.import">Importer</Trans>
398
- </Button>
399
- </div>
400
-
401
- {/* Afficher la progression pour toutes les tâches d'importation actives/suivies */}
402
- {jobsToDisplay.length > 0 && (
403
- <div className="import-jobs-list">
404
- <h3><Trans i18nKey="dataimporter.activeImports">Importations en cours / terminées</Trans></h3>
405
- {jobsToDisplay.map(job => {
406
- const progressPercentage = job.totalRecords > 0
407
- ? (job.processedRecords / job.totalRecords) * 100
408
- : 0;
409
- const isJobFinished = job.status === 'completed' || job.status === 'failed' || job.status === 'not_found';
410
-
411
- return (
412
- <div key={job.jobId} className="import-progress-container">
413
- <h4><Trans i18nKey="dataimporter.jobId">Tâche ID:</Trans> {job.jobId?.substring(0, 8)}...</h4>
414
- <p>
415
- <Trans i18nKey="dataimporter.status">Statut:</Trans>{' '}
416
- <strong>{t(`dataimporter.status.${job.status}`, job.status)}</strong>
417
- </p>
418
- {job.totalRecords > 0 && (
419
- <p>
420
- <Trans i18nKey="dataimporter.recordsProcessed">Enregistrements traités:</Trans>{' '}
421
- {job.processedRecords} / {job.totalRecords}
422
- </p>
423
- )}
424
- <div className="progress-bar-wrapper">
425
- <div
426
- className="progress-bar"
427
- style={{ width: `${progressPercentage}%` }}
428
- >
429
- {progressPercentage.toFixed(0)}%
430
- </div>
431
- </div>
432
-
433
- {job.errors && job.errors.length > 0 && (
434
- <div className="import-errors">
435
- <h4><Trans i18nKey="dataimporter.errors">Erreurs:</Trans></h4>
436
- <ul>
437
- {job.errors.map((error, index) => (
438
- <li key={index}>{error}</li>
439
- ))}
440
- </ul>
441
- </div>
442
- )}
443
- {isJobFinished && (
444
- <div className="flex justify-end mt-2">
445
- <Button onClick={() => {
446
- setImportJobs(prevJobs => {
447
- const newJobs = { ...prevJobs };
448
- delete newJobs[job.jobId];
449
- return newJobs;
450
- });
451
- setActiveJobIds(prevIds => prevIds.filter(id => id !== job.jobId));
452
- }}><Trans i18nKey="btns.clear">Effacer</Trans></Button>
453
- </div>
454
- )}
455
- </div>
456
- );
457
- })}
458
- </div>
459
- )}
460
-
461
- <div className="flex justify-end mt-4">
462
- <Button onClick={handleCloseModal} disabled={isAnyImportInProgress}>
463
- <Trans i18nKey="btns.close">Fermer</Trans>
464
- </Button>
465
- </div>
466
- </>
467
- </Dialog>
468
- );
1
+ import {useAuthContext} from "./contexts/AuthContext.jsx";
2
+ import {useModelContext} from "./contexts/ModelContext.jsx";
3
+ import {useNotificationContext} from "./NotificationProvider.jsx";
4
+ import {useEffect, useRef, useState} from "react";
5
+ import {Trans, useTranslation} from "react-i18next";
6
+ import {useMutation, useQueryClient} from "react-query";
7
+ import useLocalStorage from "./hooks/useLocalStorage.js";
8
+ import {getUserId} from "../../src/data.js";
9
+ import {kilobytes, maxBytesPerSecondThrottleData, maxFileSize} from "../../src/constants";
10
+ import {FileField, ModelField} from "./Field.jsx";
11
+ import Button from "./Button.jsx";
12
+ import {FaInfo, FaTrash} from "react-icons/fa";
13
+ import {Dialog, DialogProvider} from "./Dialog.jsx";
14
+ import readXlsxFile from 'read-excel-file'
15
+ // Ajoutez cette constante pour la clé de sessionStorage
16
+ const SESSION_STORAGE_IMPORT_JOBS_KEY = 'activeImportJobs';
17
+
18
+ export function DataImporter({onClose}) {
19
+ const [previewData, setPreviewData] = useState(null);
20
+ const [file, setFile] = useState(null);
21
+ const {selectedModel, page} = useModelContext();
22
+
23
+ const isCsvFile = file && (file.name.endsWith('.csv') || file.type === 'text/csv');
24
+ const isExcelFile = file && ((file.name.endsWith('.xlsx') ||
25
+ ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
26
+ 'application/vnd.ms-excel'].includes(file.type)));
27
+
28
+ const {me} = useAuthContext();
29
+ const {t, i18n} = useTranslation();
30
+
31
+ const queryClient = useQueryClient();
32
+ const {addNotification} = useNotificationContext();
33
+
34
+ const [hasHeaders, setHasHeaders] = useState(true);
35
+ const [csvHeaders, setCSVHeaders] = useState(selectedModel.fields.map(field => field.name));
36
+
37
+ // --- MODIFIÉ : État pour gérer plusieurs tâches d'importation ---
38
+ // Cet objet stockera les données de progression de chaque tâche, indexées par leur jobId
39
+ const [importJobs, setImportJobs] = useState({});
40
+ // Cette liste stockera les IDs des tâches qui sont actuellement suivies via SSE
41
+ const [activeJobIds, setActiveJobIds] = useState([]);
42
+
43
+ // Référence pour stocker les instances EventSource, indexées par jobId
44
+ const eventSourceRefs = useRef({});
45
+
46
+ const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
47
+
48
+ const [storedJobIds, setStoredJobIds] = useLocalStorage(SESSION_STORAGE_IMPORT_JOBS_KEY, []);
49
+ // --- NOUVEAU : Charger/Sauvegarder les IDs des tâches actives depuis sessionStorage ---
50
+ useEffect(() => {
51
+ const validJobIds = [];
52
+ const checkJobsPromises = storedJobIds.map(jobId =>
53
+ fetch(`/api/import/progress/${jobId}`)
54
+ .then(res => res.json())
55
+ .then(jobData => {
56
+ if (jobData.status !== 'not_found') {
57
+ validJobIds.push(jobId);
58
+ // Mettre à jour l'état initial avec les données fraîches
59
+ setImportJobs(prevJobs => ({
60
+ ...prevJobs,
61
+ [jobId]: { ...jobData, jobId: jobId } // Assurer que jobId est dans l'objet
62
+ }));
63
+ }
64
+ })
65
+ .catch(() => {
66
+ // Ignorer les erreurs de réseau, le job sera simplement retiré
67
+ })
68
+ );
69
+
70
+ Promise.all(checkJobsPromises).then(() => {
71
+ setActiveJobIds(validJobIds);
72
+ // Démarrer le suivi SSE uniquement pour les tâches valides
73
+ validJobIds.forEach(jobId => startProgressTracking(jobId));
74
+ });
75
+
76
+ // Fonction de nettoyage : fermer toutes les connexions EventSource lors du démontage du composant
77
+ return () => {
78
+ Object.values(eventSourceRefs.current).forEach(es => es.close());
79
+ eventSourceRefs.current = {}; // Effacer les références
80
+ };
81
+ }, []); // S'exécute une seule fois au montage
82
+
83
+ // --- NOUVEAU : Effet pour mettre à jour sessionStorage lorsque activeJobIds change ---
84
+ useEffect(() => {
85
+ setStoredJobIds(activeJobIds);
86
+ }, [activeJobIds]);
87
+
88
+
89
+ // Mutation pour initier l'importation (envoi du fichier au serveur)
90
+ const {isLoading, mutate: importMutation} = useMutation(async () => {
91
+ console.log('Initiating data import...');
92
+ const params = new FormData();
93
+ params.append('model', selectedModel?.name);
94
+ params.append("_user", getUserId(me));
95
+ params.append("hasHeaders", !!hasHeaders);
96
+ params.append("csvHeaders", csvHeaders.join(','));
97
+ if (file) {
98
+ params.append("file", file);
99
+ } else {
100
+ addNotification({ title: t('dataimporter.noFileSelected', 'Veuillez sélectionner un fichier à importer.'), status: 'warning' });
101
+ return Promise.reject(new Error("No file selected"));
102
+ }
103
+
104
+ try {
105
+ const response = await fetch(`/api/data/import?lang=${lang}`, {
106
+ method: 'POST',
107
+ credentials: "include",
108
+ body: params
109
+ });
110
+
111
+ if (response.status === 200) {
112
+ const { jobId } = await response.json();
113
+
114
+ // --- MODIFIÉ : Ajouter le nouvel jobId à activeJobIds et à l'état importJobs ---
115
+ setActiveJobIds(prevIds => [...prevIds, jobId]);
116
+ setImportJobs(prevJobs => ({
117
+ ...prevJobs,
118
+ [jobId]: {
119
+ jobId,
120
+ status: 'pending',
121
+ totalRecords: 0,
122
+ processedRecords: 0,
123
+ errors: [],
124
+ // Ajoutez d'autres champs initiaux que vous souhaitez afficher immédiatement
125
+ }
126
+ }));
127
+ startProgressTracking(jobId); // Commencer le suivi de cette nouvelle tâche
128
+ addNotification({
129
+ title: t('dataimporter.initiated', 'Importation initiée. Suivi de la progression...'),
130
+ icon: <FaInfo/>,
131
+ status: 'info'
132
+ });
133
+ } else {
134
+ const errorData = await response.json();
135
+ addNotification({
136
+ title: errorData.error || t('dataimporter.error', 'Erreur lors de l\'importation.'),
137
+ status: 'error'
138
+ });
139
+ }
140
+ } catch (e) {
141
+ addNotification({
142
+ title: e.message || t('dataimporter.networkError', 'Erreur réseau lors de l\'importation.'),
143
+ status: 'error'
144
+ });
145
+ }
146
+ });
147
+
148
+ // Fonction pour démarrer le suivi de la progression via Server-Sent Events (SSE) pour un jobId spécifique
149
+
150
+ // Fonction pour démarrer le suivi de la progression via Server-Sent Events (SSE) pour un jobId spécifique
151
+ const startProgressTracking = (jobId) => {
152
+ // Fermer toute connexion EventSource existante pour ce jobId pour éviter les doublons
153
+ if (eventSourceRefs.current[jobId]) {
154
+ eventSourceRefs.current[jobId].close();
155
+ }
156
+
157
+ const eventSource = new EventSource(`/api/import/progress/${jobId}`);
158
+ eventSourceRefs.current[jobId] = eventSource; // Stocker l'instance pour le nettoyage
159
+
160
+ eventSource.onmessage = (event) => {
161
+ const data = JSON.parse(event.data);
162
+ // --- MODIFIÉ : Mettre à jour la progression de la tâche spécifique ---
163
+ setImportJobs(prevJobs => ({
164
+ ...prevJobs,
165
+ [jobId]: {
166
+ ...data,
167
+ jobId: jobId // Assurer que le jobId est toujours présent dans l'objet de la tâche
168
+ }
169
+ }));
170
+
171
+ // Si la tâche est terminée (succès ou échec), fermer la connexion SSE.
172
+ // NE PAS la retirer de activeJobIds ici, pour qu'elle persiste au rafraîchissement.
173
+ // Elle sera retirar le bouton "Effacer".
174
+ if (data.status === 'completed' || data.status === 'failed' || data.status === 'not_found') {
175
+ queryClient.invalidateQueries(['api/data', selectedModel.name, 'page', page]); // Rafraîchir les données du tableau
176
+ queryClient.invalidateQueries(['api/data', selectedModel.name]); // Invalider toutes les requêtes pour ce modèle
177
+
178
+ if (data.status === 'completed') {
179
+ addNotification({
180
+ title: t('dataimporter.success', 'Importation des données réussie.'),
181
+ icon: <FaInfo/>,
182
+ status: 'completed'
183
+ });
184
+ } else if (data.status === 'failed') {
185
+ addNotification({
186
+ title: t('dataimporter.failed', 'Importation échouée. Voir les détails pour les erreurs.'),
187
+ status: 'error'
188
+ });
189
+ } else if (data.status === 'not_found') {
190
+ addNotification({
191
+ title: t('dataimporter.jobNotFound', 'Tâche d\'importation non trouvée ou déjà terminée.'),
192
+ status: 'warning'
193
+ });
194
+ }
195
+ // On ferme la connexion SSE et on retire la référence
196
+ eventSource.close();
197
+ delete eventSourceRefs.current[jobId];
198
+ }
199
+ };
200
+
201
+ eventSource.onerror = (error) => {
202
+ console.error(`EventSource error for job ${jobId}:`, error);
203
+ eventSource.close();
204
+ delete eventSourceRefs.current[jobId];
205
+ setStoredJobIds(prevIds => prevIds.filter(id => id !== jobId));
206
+ };
207
+ };
208
+
209
+ const handleImportClick = () => {
210
+ importMutation();
211
+ };
212
+
213
+ const handleCloseModal = () => {
214
+ // Fermer toutes les connexions EventSource avant de fermer la modale
215
+ Object.values(eventSourceRefs.current).forEach(es => es.close());
216
+ eventSourceRefs.current = {}; // Effacer les références
217
+ onClose();
218
+ };
219
+ const handleFilePreview = async (file) => {
220
+ console.log('handleFilePreview');
221
+ if (!file) {
222
+ setPreviewData(null);
223
+ return;
224
+ }
225
+
226
+ const isExcelFile = file && ((file.name.endsWith('.xlsx') ||
227
+ ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
228
+ 'application/vnd.ms-excel'].includes(file.type)));
229
+
230
+ if (isExcelFile) {
231
+ console.log('excel');
232
+ try {
233
+ const arrayBuffer = await file.arrayBuffer();
234
+ const rows = await readXlsxFile(arrayBuffer);
235
+ setPreviewData(rows);
236
+ } catch (error) {
237
+ console.error('Error reading Excel file:', error);
238
+ addNotification({
239
+ title: t('dataimporter.excelReadError', 'Erreur lors de la lecture du fichier Excel'),
240
+ status: 'error'
241
+ });
242
+ }
243
+ } else {
244
+ setPreviewData(null);
245
+ }
246
+ };
247
+
248
+ // Déterminer si une importation est actuellement en cours (pour désactiver les boutons)
249
+ const isAnyImportInProgress = Object.values(importJobs).some(job => job.status === 'pending' || job.status === 'processing');
250
+
251
+ // Filtrer et trier les tâches à afficher (par exemple, les tâches en cours en premier)
252
+ const jobsToDisplay = Object.values(importJobs).sort((a, b) => {
253
+ // Trier par statut (en attente/en cours en premier, puis échoué, puis terminé)
254
+ const statusOrder = { 'pending': 1, 'processing': 2, 'failed': 3, 'completed': 4, 'not_found': 5 };
255
+ return statusOrder[a.status] - statusOrder[b.status];
256
+ });
257
+
258
+ const { models } = useModelContext();
259
+
260
+ return (
261
+ <Dialog isClosable={true} isModal={true} onClose={handleCloseModal}>
262
+ <>
263
+ <h2>
264
+ <Trans i18nKey="dataimporter.title" values={{model: t('model_' + selectedModel?.name, selectedModel?.name)}}>
265
+ Importer des données dans {t('model_' + selectedModel?.name, selectedModel?.name)}
266
+ </Trans>
267
+ </h2>
268
+ <p className="msg msg-info">
269
+ <Trans i18nKey="dataimporter.info" values={{constante: (maxBytesPerSecondThrottleData / kilobytes) + 'ko/s'}}></Trans>
270
+ </p>
271
+
272
+ {/* Toujours afficher le formulaire de sélection de fichier et le bouton d'importation */}
273
+ <FileField
274
+ name="file"
275
+ maxSize={maxFileSize}
276
+ mimeTypes={[
277
+ 'application/json',
278
+ 'text/csv',
279
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
280
+ 'application/vnd.ms-excel'
281
+ ]}
282
+ type="file"
283
+ multiple={false}
284
+ onChange={async (files) => {
285
+ const newFile = files && files.length > 0 ? files[files.length - 1].file : null;
286
+ setFile(newFile);
287
+ await handleFilePreview(newFile);
288
+ }}
289
+ />
290
+
291
+ {file && (isExcelFile || isCsvFile) && (
292
+ <div className="checkbox-label flex flex-row">
293
+ {isCsvFile && (<label htmlFor="hasHeadersCheckbox">
294
+ <input
295
+ type="checkbox"
296
+ id="hasHeadersCheckbox"
297
+ checked={hasHeaders}
298
+ onChange={(e) => setHasHeaders(e.target.checked)}
299
+ />
300
+ <Trans i18nKey="dataimporter.hasCsvHeaders"></Trans>
301
+ </label>)}
302
+ {(!hasHeaders || isExcelFile) && (
303
+ <table>
304
+ <thead>
305
+ <tr>
306
+ <th><Trans i18nKey={"dataimporter.columnType"} values={[isExcelFile?'Excel':'CSV']}>Numéro de colonne</Trans></th>
307
+ <th><Trans i18nKey="dataimporter.field">Champ du modèle</Trans></th>
308
+ </tr>
309
+ </thead>
310
+ <tbody>
311
+ {selectedModel?.fields.map((field, index) => {
312
+ const currentFieldValue = csvHeaders[index] || '';
313
+ const fieldObject = selectedModel.fields.find(f => f.name === currentFieldValue);
314
+
315
+ return (
316
+ <tr key={`${selectedModel.name}-csvmap-${index}`}>
317
+ <td><Trans i18nKey="dataimporter.column" values={[index + 1]}>colonne {index + 1}</Trans></td>
318
+ <td>
319
+ <div className="flex">
320
+ <ModelField
321
+ disableable={true}
322
+ showModel={false}
323
+ value={selectedModel.name}
324
+ fieldValue={currentFieldValue}
325
+ onChange={({name: propName, value: selectedValue}) => {
326
+ const newCsvHeaders = [...csvHeaders];
327
+ newCsvHeaders[index] = selectedValue?.field ?? '';
328
+ setCSVHeaders(newCsvHeaders);
329
+ }}
330
+ fields={true}
331
+ model={selectedModel}
332
+ field={fieldObject}
333
+ />
334
+ <Button className="flex" onClick={() => {
335
+ const newHeaders = [...csvHeaders];
336
+ newHeaders.splice(index, 1);
337
+ setCSVHeaders(newHeaders);
338
+ }}><FaTrash/></Button>
339
+ </div>
340
+ </td>
341
+ </tr>
342
+ );
343
+ })}
344
+ <tr>
345
+ <td colSpan={2}>
346
+ <Button onClick={() => {
347
+ const csvH = [...csvHeaders];
348
+ csvH.push('');
349
+ setCSVHeaders(csvH)
350
+ }}><Trans i18nKey="dataimporter.addColumn">Ajouter une colonne</Trans></Button>
351
+ </td>
352
+ </tr>
353
+ </tbody>
354
+ </table>
355
+ )}
356
+ </div>
357
+ )}
358
+
359
+ {previewData && (
360
+ <div className="excel-preview mt-4">
361
+ <h3><Trans i18nKey="dataimporter.excelPreview">Aperçu des données Excel</Trans></h3>
362
+ <div className="msg msg-tiny">
363
+ <Trans i18nKey="dataimporter.previewNote">
364
+ Note: Ceci est un aperçu des premières lignes. Les cellules vides sont affichées comme "(vide)".
365
+ </Trans>
366
+ </div>
367
+ <div className="preview-table-container" style={{ maxHeight: '300px', overflow: 'auto' }}>
368
+ <table className="preview-table">
369
+ <thead>
370
+ <tr>
371
+ {previewData[0].map((_, colIndex) => {
372
+ // Récupérer le nom du champ mappé pour cette colonne depuis l'état `csvHeaders`
373
+ const mappedFieldName = csvHeaders[colIndex];
374
+
375
+ // Si un champ est mappé, on affiche son nom traduit.
376
+ // Sinon, on affiche un nom générique comme "Colonne X".
377
+ const headerLabel = mappedFieldName
378
+ ? t(`field_${mappedFieldName}`, mappedFieldName)
379
+ : t('dataimporter.column', 'Colonne {{count}}', { count: colIndex + 1 });
380
+
381
+ return (
382
+ <th key={`header-${colIndex}`}>
383
+ {headerLabel}
384
+ </th>
385
+ );
386
+ })}
387
+ </tr>
388
+ </thead>
389
+ <tbody>
390
+ {previewData.map((row, rowIndex) => (
391
+ <tr key={`row-${rowIndex}`}>
392
+ {row.map((cell, cellIndex) => (
393
+ <td
394
+ key={`cell-${rowIndex}-${cellIndex}`}
395
+ style={{
396
+ border: '1px solid #ddd',
397
+ padding: '4px',
398
+ backgroundColor: rowIndex === 0 && hasHeaders ? '#f0f0f0' : 'transparent'
399
+ }}
400
+ >
401
+ {cell !== null ? String(cell) : <span style={{ color: '#999' }}><Trans i18nKey="dataimporter.nullValue">(vide)</Trans></span>}
402
+ </td>
403
+ ))}
404
+ </tr>
405
+ ))}
406
+ </tbody>
407
+ </table>
408
+ </div>
409
+ </div>
410
+ )}
411
+ <div>
412
+ <Button onClick={handleImportClick} disabled={isLoading || !file}>
413
+ <Trans i18nKey="btns.import">Importer</Trans>
414
+ </Button>
415
+ </div>
416
+
417
+ {/* Afficher la progression pour toutes les tâches d'importation actives/suivies */}
418
+ {jobsToDisplay.length > 0 && (
419
+ <div className="import-jobs-list">
420
+ <h3><Trans i18nKey="dataimporter.activeImports">Importations en cours / terminées</Trans></h3>
421
+ {jobsToDisplay.map(job => {
422
+ const progressPercentage = job.totalRecords > 0
423
+ ? (job.processedRecords / job.totalRecords) * 100
424
+ : 0;
425
+ const isJobFinished = job.status === 'completed' || job.status === 'failed' || job.status === 'not_found';
426
+
427
+ return (
428
+ <div key={job.jobId} className="import-progress-container">
429
+ <h4><Trans i18nKey="dataimporter.jobId">Tâche ID:</Trans> {job.jobId?.substring(0, 8)}...</h4>
430
+ <p>
431
+ <Trans i18nKey="dataimporter.status">Statut:</Trans>{' '}
432
+ <strong>{t(`dataimporter.status.${job.status}`, job.status)}</strong>
433
+ </p>
434
+ {job.totalRecords > 0 && (
435
+ <p>
436
+ <Trans i18nKey="dataimporter.recordsProcessed">Enregistrements traités:</Trans>{' '}
437
+ {job.processedRecords} / {job.totalRecords}
438
+ </p>
439
+ )}
440
+ <div className="progress-bar-wrapper">
441
+ <div
442
+ className="progress-bar"
443
+ style={{ width: `${progressPercentage}%` }}
444
+ >
445
+ {progressPercentage.toFixed(0)}%
446
+ </div>
447
+ </div>
448
+
449
+ {job.errors && job.errors.length > 0 && (
450
+ <div className="import-errors">
451
+ <h4><Trans i18nKey="dataimporter.errors">Erreurs:</Trans></h4>
452
+ <ul>
453
+ {job.errors.map((error, index) => (
454
+ <li key={index}>{error}</li>
455
+ ))}
456
+ </ul>
457
+ </div>
458
+ )}
459
+ {isJobFinished && (
460
+ <div className="flex justify-end mt-2">
461
+ <Button onClick={async () => {
462
+ // 1. Appeler l'API pour supprimer le job côté serveur
463
+ await fetch(`/api/import/job/${job.jobId}`, { method: 'DELETE', credentials: "include" });
464
+
465
+ // 2. Mettre à jour l'état local côté client
466
+ setActiveJobIds(prev => prev.filter(id => id !== job.jobId));
467
+ setImportJobs(prev => {
468
+ const newState = { ...prev };
469
+ delete newState[job.jobId];
470
+ return newState;
471
+ });
472
+ addNotification({ title: t('dataimporter.jobCleared', 'Tâche effacée.'), status: 'info' });
473
+ }}><Trans i18nKey="btns.clear">Effacer</Trans></Button>
474
+ </div>
475
+ )}
476
+ </div>
477
+ );
478
+ })}
479
+ </div>
480
+ )}
481
+
482
+ <div className="flex justify-end mt-4">
483
+ <Button onClick={handleCloseModal} disabled={isAnyImportInProgress}>
484
+ <Trans i18nKey="btns.close">Fermer</Trans>
485
+ </Button>
486
+ </div>
487
+ </>
488
+ </Dialog>
489
+ );
469
490
  }