data-primals-engine 1.5.2 → 1.6.0

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 (63) hide show
  1. package/README.md +924 -915
  2. package/client/README.md +136 -136
  3. package/client/index.js +0 -1
  4. package/client/public/doc/API.postman_collection.json +213 -213
  5. package/client/public/react.svg +9 -9
  6. package/client/src/AddWidgetTypeModal.jsx +47 -47
  7. package/client/src/App.css +42 -42
  8. package/client/src/App.jsx +92 -150
  9. package/client/src/App.scss +6 -0
  10. package/client/src/AssistantChat.jsx +362 -363
  11. package/client/src/Button.jsx +12 -12
  12. package/client/src/Dashboard.jsx +480 -480
  13. package/client/src/DashboardHtmlViewItem.jsx +146 -146
  14. package/client/src/DashboardView.jsx +654 -654
  15. package/client/src/DataEditor.jsx +383 -383
  16. package/client/src/DataLayout.jsx +779 -808
  17. package/client/src/DataTable.jsx +782 -822
  18. package/client/src/DataTable.scss +186 -186
  19. package/client/src/GeolocationField.jsx +93 -93
  20. package/client/src/HistoryDialog.jsx +307 -307
  21. package/client/src/HistoryDialog.scss +319 -319
  22. package/client/src/HtmlViewBuilderModal.jsx +90 -90
  23. package/client/src/HtmlViewBuilderModal.scss +17 -17
  24. package/client/src/HtmlViewCard.jsx +43 -43
  25. package/client/src/ModelCreatorField.jsx +950 -950
  26. package/client/src/ModelList.jsx +280 -280
  27. package/client/src/Notification.jsx +136 -136
  28. package/client/src/PackGallery.jsx +391 -391
  29. package/client/src/PackGallery.scss +231 -231
  30. package/client/src/Pagination.jsx +143 -143
  31. package/client/src/RelationField.jsx +354 -354
  32. package/client/src/RelationSelectorWidget.jsx +172 -172
  33. package/client/src/RelationValue.jsx +2 -1
  34. package/client/src/contexts/CommandContext.jsx +260 -0
  35. package/client/src/contexts/ModelContext.jsx +4 -1
  36. package/client/src/contexts/UIContext.jsx +72 -72
  37. package/client/src/filter.js +263 -263
  38. package/client/src/index.css +90 -90
  39. package/package.json +6 -5
  40. package/perf/artillery-hooks.js +37 -37
  41. package/perf/setup.yml +25 -25
  42. package/src/constants.js +4 -0
  43. package/src/engine.js +335 -335
  44. package/src/events.js +232 -137
  45. package/src/filter.js +274 -274
  46. package/src/modules/assistant/assistant.js +225 -83
  47. package/src/modules/auth-google/index.js +50 -50
  48. package/src/modules/auth-microsoft/index.js +81 -81
  49. package/src/modules/data/data.core.js +118 -118
  50. package/src/modules/data/data.history.js +555 -555
  51. package/src/modules/data/data.operations.js +3401 -3381
  52. package/src/modules/data/data.relations.js +686 -686
  53. package/src/modules/data/data.routes.js +1879 -1879
  54. package/src/modules/data/data.validation.js +2 -2
  55. package/src/modules/file.js +247 -247
  56. package/src/packs.js +2 -2
  57. package/src/providers.js +2 -2
  58. package/src/services/stripe.js +196 -196
  59. package/src/sso.js +193 -193
  60. package/test/data.history.integration.test.js +264 -264
  61. package/test/data.integration.test.js +1206 -1206
  62. package/test/events.test.js +108 -10
  63. package/test/model.integration.test.js +377 -377
@@ -1,392 +1,392 @@
1
- import React, { useState } from 'react';
2
- import {useMutation, useQuery, useQueryClient} from 'react-query';
3
- import { Trans, useTranslation } from 'react-i18next';
4
- import {FaBoxOpen, FaChevronLeft, FaDownload, FaPlus, FaStar, FaTag, FaUser, FaUserCircle, FaTimes} from 'react-icons/fa';
5
- import Button from './Button.jsx';
6
- import { useNotificationContext } from './NotificationProvider.jsx';
7
- import { useModelContext } from './contexts/ModelContext.jsx';
8
- import { useAuthContext } from './contexts/AuthContext.jsx';
9
-
10
- import './PackGallery.scss';
11
- import {elementsPerPage} from "../../src/constants.js";
12
- import Markdown from "react-markdown";
13
- import {Dialog, DialogProvider} from "./Dialog.jsx";
14
- import {TextField, CheckboxField} from "./Field.jsx";
15
-
16
- // --- API Fetching Functions ---
17
- const fetchPacks = async (sortBy, lang, filterByUser = false, user) => {
18
- const url = `/api/packs?lang=${lang}&sortBy=${sortBy.field}&order=${sortBy.order}${filterByUser ? '&user='+user.username : ''}`;
19
- const response = await fetch(url);
20
- if (!response.ok) {
21
- throw new Error('Network response was not ok');
22
- }
23
- return response.json();
24
- };
25
-
26
- const fetchPackDetails = async (packId, lang) => {
27
- if (!packId) return null;
28
- const response = await fetch(`/api/packs/${packId}?lang=${lang}`);
29
- if (!response.ok) {
30
- throw new Error('Failed to fetch pack details');
31
- }
32
- return response.json();
33
- };
34
-
35
- // --- Sub-components ---
36
-
37
- // Carte pour afficher un pack dans la galerie
38
- const PackCard = ({ pack, onSelect }) => {
39
- const { t } = useTranslation();
40
- const { me: user } = useAuthContext();
41
-
42
- return (
43
- <div className="pack-card" onClick={() => onSelect(pack._id)}>
44
- <div className="pack-card-header">
45
- <h3><FaBoxOpen /> {pack.name}</h3>
46
- <div className="pack-header-right">
47
- <span className="pack-stars"><FaStar /> {pack.stars || 0}</span>
48
- {user && pack._user === user.username && (
49
- <span className="my-pack-badge" title={t('packs.myPack', 'Mon pack')}>
50
- <FaUserCircle />
51
- </span>
52
- )}
53
- </div>
54
- </div>
55
- <p className="pack-description">{pack.description?.substring(0, 120) || t('packs.noDescription', 'Aucune description.')}... </p>
56
- <div className="pack-card-footer">
57
- <span className="pack-author"><FaUser /> {pack._user}</span>
58
- <div className="pack-tags">
59
- {(pack.tags || []).map(tag => <span key={tag} className="tag"><FaTag /> {tag}</span>)}
60
- </div>
61
- </div>
62
- </div>
63
- );
64
- };
65
-
66
- // Vue détaillée d'un pack
67
- const PackDetail = ({ packId, onBack }) => {
68
- const { t,i18n } = useTranslation();
69
- const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
70
- const { addNotification } = useNotificationContext();
71
- const queryClient = useQueryClient();
72
- const { selectedModel, page, pagedFilters, pagedSort } = useModelContext();
73
- const { me: user } = useAuthContext();
74
- const { data: pack, isLoading, isError } = useQuery(['packDetails', packId], () => fetchPackDetails(packId, lang));
75
-
76
- const { mutate: updatePack, isLoading: isUpdating } = useMutation(
77
- updatePackMutationFn,
78
- {
79
- onSuccess: () => {
80
- addNotification({ status: 'completed', title: t('packs.update.success', 'Pack mis à jour avec succès !') });
81
- queryClient.invalidateQueries(['packDetails', packId]);
82
- queryClient.invalidateQueries('packs');
83
- },
84
- onError: (error) => {
85
- addNotification({ status: 'error', title: t('packs.update.error', 'Échec de la mise à jour du pack'), message: error.message });
86
- }
87
- }
88
- );
89
-
90
- const { mutate: installPack, isLoading: isInstalling } = useMutation(
91
- installPackMutationFn,
92
- {
93
- onSuccess: (data) => {
94
- addNotification({
95
- status: 'completed',
96
- title: t('datatable.pack.install.success', `Pack '${pack.name}' installé avec succès !`)
97
- });
98
- gtag('event', 'pack install '+pack.name);
99
- queryClient.invalidateQueries('api/models');
100
- queryClient.invalidateQueries(['api/data', selectedModel?.name, 'page', page, elementsPerPage, pagedFilters[selectedModel?.name], pagedSort[selectedModel?.name]]);
101
-
102
- onBack();
103
- },
104
- onError: (error) => {
105
- addNotification({
106
- status: 'error',
107
- title: t('datatable.pack.install.error', `Échec de l'installation du pack`),
108
- message: error.message
109
- });
110
- }
111
- }
112
- );
113
-
114
- const handleInstall = async () => {
115
- addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack '${pack.name}'...`) });
116
- installPack({ packId: pack._id, lang });
117
- };
118
-
119
- const handlePublicToggle = (e) => {
120
- const pr = !e;
121
- updatePack({ packId: pack._id, updateData: { private: pr } });
122
- };
123
-
124
- if (isLoading) return <div className="spinner-loader"></div>;
125
- if (isError) return <p className="error-text">{t('packs.error.details', 'Erreur lors du chargement des détails du pack.')}</p>;
126
- if (!pack) return null;
127
-
128
- const renderModelsList = (models) => {
129
- if (!models || models.length === 0) return t('packs.noModelsIncluded', 'Aucun modèle spécifié.');
130
-
131
- return models.map(model => {
132
- const modelName = typeof model === 'object' && model !== null ? model.name : model;
133
- return modelName;
134
- }).join(', ');
135
- };
136
-
137
- return (
138
- <div className="pack-detail">
139
- <Button onClick={onBack} className="back-button"><FaChevronLeft /> <Trans i18nKey="btns.back">Retour</Trans></Button>
140
- <div className="pack-detail-header">
141
- <h1>{pack.name}</h1>
142
- <div className="pack-detail-actions">
143
- {user && pack._user === user.username && (
144
- <div className="owner-actions">
145
- <span className="my-pack-indicator">
146
- <FaUserCircle /> <Trans i18nKey="packs.myPack">Mon pack</Trans>
147
- </span>
148
- <CheckboxField
149
- label={t('packs.public', 'Public')}
150
- checked={!pack.private}
151
- onChange={handlePublicToggle}
152
- disabled={isUpdating}
153
- title={t('packs.public.tooltip', 'Rendre ce pack visible par les autres utilisateurs dans la galerie.')}
154
- />
155
- </div>
156
- )}
157
- <Button onClick={handleInstall} disabled={isInstalling}>
158
- <FaDownload /> {isInstalling ? t('packs.installing', 'Installation...') : t('Installer')}
159
- </Button>
160
- </div>
161
- </div>
162
- <div className="pack-meta">
163
- <span><FaUser /> {pack._user}</span>
164
- <span><FaStar /> {pack.stars || 0}</span>
165
- <span><FaTag /> {(pack.tags || []).join(', ')}</span>
166
- </div>
167
- <div className="pack-content">
168
- <h2><Trans i18nKey="packs.description">Description</Trans></h2>
169
- <div className="description-content"><Markdown>{pack.description}</Markdown></div>
170
-
171
- <h2><Trans i18nKey="packs.modelsIncluded">Modèles inclus</Trans></h2>
172
- <p>{renderModelsList(pack.models)}</p>
173
-
174
- <h2><Trans i18nKey="packs.dataPreview">Aperçu des données à installer</Trans></h2>
175
- <div className="data-preview">
176
- <pre>{JSON.stringify(pack.data, null, 2)}</pre>
177
- </div>
178
- </div>
179
- </div>
180
- );
181
- };
182
-
183
- const installPackMutationFn = async ({packId, lang}) => {
184
- const response = await fetch(`/api/packs/${packId}/install?lang=${lang}`, {
185
- method: 'POST',
186
- headers: {
187
- 'Content-Type': 'application/json',
188
- },
189
- });
190
- if (!response.ok) {
191
- const errorData = await response.json();
192
- throw new Error(errorData.error || 'Failed to install pack');
193
- }
194
- return response.json();
195
- };
196
-
197
- const updatePackMutationFn = async ({ packId, updateData }) => {
198
- const response = await fetch(`/api/packs/${packId}`, {
199
- method: 'PATCH',
200
- headers: {
201
- 'Content-Type': 'application/json',
202
- },
203
- body: JSON.stringify(updateData),
204
- });
205
- if (!response.ok) {
206
- const errorData = await response.json();
207
- throw new Error(errorData.error || 'Failed to update pack');
208
- }
209
- return response.json();
210
- };
211
-
212
- // --- Main Gallery Component ---
213
- const PackGallery = () => {
214
- const { t, i18n } = useTranslation();
215
- const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
216
- const { addNotification } = useNotificationContext();
217
- const { me: user } = useAuthContext();
218
-
219
- const [showManualInstallDialog, setShowManualInstallDialog] = useState(false);
220
- const [manualPackJson, setManualPackJson] = useState('');
221
- const [view, setView] = useState('list');
222
- const [selectedPackId, setSelectedPackId] = useState(null);
223
- const [sortBy, setSortBy] = useState({ field: '_updatedAt', order: -1 });
224
- const [showOnlyMyPacks, setShowOnlyMyPacks] = useState(false);
225
-
226
- const queryClient = useQueryClient()
227
- const { data: packs, isLoading, isError } = useQuery(
228
- ['packs', sortBy, showOnlyMyPacks],
229
- () => fetchPacks(sortBy, lang, showOnlyMyPacks, user)
230
- );
231
-
232
- const handleSelectPack = (packId) => {
233
- setSelectedPackId(packId);
234
- setView('detail');
235
- };
236
-
237
- const handleManualInstall = async () => {
238
- try {
239
- const packData = JSON.parse(manualPackJson.trim());
240
- addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack personnalisé...`) });
241
-
242
- const response = await fetch('/api/packs/install', {
243
- method: 'POST',
244
- headers: {
245
- 'Content-Type': 'application/json',
246
- },
247
- body: JSON.stringify({ packData, lang }),
248
- });
249
-
250
- if (!response.ok) {
251
- throw new Error(await response.text());
252
- }
253
-
254
- addNotification({
255
- status: 'completed',
256
- title: t('datatable.pack.install.success', 'Pack installé avec succès !')
257
- });
258
- setShowManualInstallDialog(false);
259
- setManualPackJson('');
260
- queryClient.invalidateQueries(['packs', sortBy, showOnlyMyPacks]);
261
-
262
- } catch (error) {
263
- addNotification({
264
- status: 'error',
265
- title: t('datatable.pack.install.error', `Échec de l'installation`),
266
- message: error.message
267
- });
268
- }
269
- };
270
-
271
- const handleBackToList = () => {
272
- setSelectedPackId(null);
273
- setView('list');
274
- };
275
-
276
- const toggleMyPacksFilter = () => {
277
- setShowOnlyMyPacks(!showOnlyMyPacks);
278
- };
279
-
280
- const clearMyPacksFilter = () => {
281
- setShowOnlyMyPacks(false);
282
- };
283
-
284
- const renderContent = () => {
285
- if (view === 'detail') {
286
- return <PackDetail packId={selectedPackId} onBack={handleBackToList} />;
287
- }
288
-
289
- if (isLoading) return <div className="spinner-loader"></div>;
290
- if (isError) return <p className="error-text">{t('packs.error.loading', 'Erreur lors du chargement des packs.')}</p>;
291
-
292
- return (
293
- <>
294
- <div className="gallery-header">
295
- <h1>
296
- {showOnlyMyPacks
297
- ? <Trans i18nKey="packs.myPacksTitle">Mes Packs</Trans>
298
- : <Trans i18nKey="packs.galleryTitle">Galerie de Packs</Trans>
299
- }
300
- </h1>
301
- <div className="header-actions">
302
- <div className="sort-options">
303
- <span><Trans i18nKey="packs.sortBy">Trier par :</Trans></span>
304
- <Button onClick={() => setSortBy({ field: '_updatedAt', order: -1 })} className={sortBy.field === '_updatedAt' ? 'active' : ''}>
305
- <Trans i18nKey="packs.sort.lastUpdated">Derniers ajouts</Trans>
306
- </Button>
307
- <Button onClick={() => setSortBy({ field: 'stars', order: -1 })} className={sortBy.field === 'stars' ? 'active' : ''}>
308
- <Trans i18nKey="packs.sort.mostStarred">Plus populaires</Trans>
309
- </Button>
310
- </div>
311
- <div className="filter-actions">
312
- {showOnlyMyPacks && (
313
- <Button onClick={clearMyPacksFilter} className="clear-filter-btn">
314
- <FaTimes /> <Trans i18nKey="packs.clearFilter">Voir tous les packs</Trans>
315
- </Button>
316
- )}
317
- {user && !showOnlyMyPacks && (
318
- <Button
319
- onClick={toggleMyPacksFilter}
320
- className="my-packs-btn"
321
- >
322
- <FaUserCircle /> <Trans i18nKey="packs.myPacks">Mes packs</Trans>
323
- </Button>
324
- )}
325
- <Button
326
- onClick={() => setShowManualInstallDialog(true)}
327
- className="add-pack-button"
328
- >
329
- <FaPlus /> <Trans i18nKey="packs.manualInstall">Importer</Trans>
330
- </Button>
331
- </div>
332
- </div>
333
- </div>
334
-
335
- {showOnlyMyPacks && (
336
- <div className="filter-indicator">
337
- <FaUserCircle />
338
- <Trans i18nKey="packs.filteringMyPacks">Affichage de vos packs uniquement</Trans>
339
- </div>
340
- )}
341
-
342
- {showManualInstallDialog && (
343
- <DialogProvider>
344
- <Dialog
345
- isModal={true}
346
- onClose={() => setShowManualInstallDialog(false)}
347
- title={t('packs.manualInstall.title', 'Installation manuelle de pack')}
348
- >
349
- <div className="manual-install-dialog">
350
- <p>
351
- <Trans i18nKey="packs.manualInstall.instructions">
352
- Collez ici le JSON de configuration du pack que vous souhaitez installer.
353
- </Trans>
354
- </p>
355
- <TextField
356
- multiline={true}
357
- value={manualPackJson}
358
- onChange={(e) => setManualPackJson(e.target.value)}
359
- placeholder={t('packs.manualInstall.placeholder', '{"name": "Mon Pack", "description": "...", "models": [...], "data": [...]}')}
360
- rows={15}
361
- />
362
- <div className="flex actions right">
363
- <Button onClick={() => setShowManualInstallDialog(false)}><Trans i18nKey={"btns.cancel"}>Annuler</Trans></Button>
364
- <Button disabled={!manualPackJson.trim()} className="btn-primary" onClick={() => handleManualInstall()}><Trans i18nKey={"packs.install"}>Installer</Trans></Button>
365
- </div>
366
- </div>
367
- </Dialog>
368
- </DialogProvider>
369
- )}
370
-
371
- {(!packs || packs.length === 0) ? (
372
- showOnlyMyPacks
373
- ? <p className="no-packs-message">{t('packs.noMyPacks', 'Vous n\'avez créé aucun pack.')}</p>
374
- : <p className="no-packs-message">{t('packs.noPacks', 'Aucun pack n\'est disponible pour le moment.')}</p>
375
- ) : (
376
- <div className="pack-list">
377
- {packs.map(pack => (
378
- <PackCard key={pack._id} pack={pack} onSelect={handleSelectPack} />
379
- ))}
380
- </div>
381
- )}
382
- </>
383
- );
384
- };
385
- return (
386
- <div className="pack-gallery-container">
387
- {renderContent()}
388
- </div>
389
- );
390
- };
391
-
1
+ import React, { useState } from 'react';
2
+ import {useMutation, useQuery, useQueryClient} from 'react-query';
3
+ import { Trans, useTranslation } from 'react-i18next';
4
+ import {FaBoxOpen, FaChevronLeft, FaDownload, FaPlus, FaStar, FaTag, FaUser, FaUserCircle, FaTimes} from 'react-icons/fa';
5
+ import Button from './Button.jsx';
6
+ import { useNotificationContext } from './NotificationProvider.jsx';
7
+ import { useModelContext } from './contexts/ModelContext.jsx';
8
+ import { useAuthContext } from './contexts/AuthContext.jsx';
9
+
10
+ import './PackGallery.scss';
11
+ import {elementsPerPage} from "../../src/constants.js";
12
+ import Markdown from "react-markdown";
13
+ import {Dialog, DialogProvider} from "./Dialog.jsx";
14
+ import {TextField, CheckboxField} from "./Field.jsx";
15
+
16
+ // --- API Fetching Functions ---
17
+ const fetchPacks = async (sortBy, lang, filterByUser = false, user) => {
18
+ const url = `/api/packs?lang=${lang}&sortBy=${sortBy.field}&order=${sortBy.order}${filterByUser ? '&user='+user.username : ''}`;
19
+ const response = await fetch(url);
20
+ if (!response.ok) {
21
+ throw new Error('Network response was not ok');
22
+ }
23
+ return response.json();
24
+ };
25
+
26
+ const fetchPackDetails = async (packId, lang) => {
27
+ if (!packId) return null;
28
+ const response = await fetch(`/api/packs/${packId}?lang=${lang}`);
29
+ if (!response.ok) {
30
+ throw new Error('Failed to fetch pack details');
31
+ }
32
+ return response.json();
33
+ };
34
+
35
+ // --- Sub-components ---
36
+
37
+ // Carte pour afficher un pack dans la galerie
38
+ const PackCard = ({ pack, onSelect }) => {
39
+ const { t } = useTranslation();
40
+ const { me: user } = useAuthContext();
41
+
42
+ return (
43
+ <div className="pack-card" onClick={() => onSelect(pack._id)}>
44
+ <div className="pack-card-header">
45
+ <h3><FaBoxOpen /> {pack.name}</h3>
46
+ <div className="pack-header-right">
47
+ <span className="pack-stars"><FaStar /> {pack.stars || 0}</span>
48
+ {user && pack._user === user.username && (
49
+ <span className="my-pack-badge" title={t('packs.myPack', 'Mon pack')}>
50
+ <FaUserCircle />
51
+ </span>
52
+ )}
53
+ </div>
54
+ </div>
55
+ <p className="pack-description">{pack.description?.substring(0, 120) || t('packs.noDescription', 'Aucune description.')}... </p>
56
+ <div className="pack-card-footer">
57
+ <span className="pack-author"><FaUser /> {pack._user}</span>
58
+ <div className="pack-tags">
59
+ {(pack.tags || []).map(tag => <span key={tag} className="tag"><FaTag /> {tag}</span>)}
60
+ </div>
61
+ </div>
62
+ </div>
63
+ );
64
+ };
65
+
66
+ // Vue détaillée d'un pack
67
+ const PackDetail = ({ packId, onBack }) => {
68
+ const { t,i18n } = useTranslation();
69
+ const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
70
+ const { addNotification } = useNotificationContext();
71
+ const queryClient = useQueryClient();
72
+ const { selectedModel, page, pagedFilters, pagedSort } = useModelContext();
73
+ const { me: user } = useAuthContext();
74
+ const { data: pack, isLoading, isError } = useQuery(['packDetails', packId], () => fetchPackDetails(packId, lang));
75
+
76
+ const { mutate: updatePack, isLoading: isUpdating } = useMutation(
77
+ updatePackMutationFn,
78
+ {
79
+ onSuccess: () => {
80
+ addNotification({ status: 'completed', title: t('packs.update.success', 'Pack mis à jour avec succès !') });
81
+ queryClient.invalidateQueries(['packDetails', packId]);
82
+ queryClient.invalidateQueries('packs');
83
+ },
84
+ onError: (error) => {
85
+ addNotification({ status: 'error', title: t('packs.update.error', 'Échec de la mise à jour du pack'), message: error.message });
86
+ }
87
+ }
88
+ );
89
+
90
+ const { mutate: installPack, isLoading: isInstalling } = useMutation(
91
+ installPackMutationFn,
92
+ {
93
+ onSuccess: (data) => {
94
+ addNotification({
95
+ status: 'completed',
96
+ title: t('datatable.pack.install.success', `Pack '${pack.name}' installé avec succès !`)
97
+ });
98
+ gtag('event', 'pack install '+pack.name);
99
+ queryClient.invalidateQueries('api/models');
100
+ queryClient.invalidateQueries(['api/data', selectedModel?.name, 'page', page, elementsPerPage, pagedFilters[selectedModel?.name], pagedSort[selectedModel?.name]]);
101
+
102
+ onBack();
103
+ },
104
+ onError: (error) => {
105
+ addNotification({
106
+ status: 'error',
107
+ title: t('datatable.pack.install.error', `Échec de l'installation du pack`),
108
+ message: error.message
109
+ });
110
+ }
111
+ }
112
+ );
113
+
114
+ const handleInstall = async () => {
115
+ addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack '${pack.name}'...`) });
116
+ installPack({ packId: pack._id, lang });
117
+ };
118
+
119
+ const handlePublicToggle = (e) => {
120
+ const pr = !e;
121
+ updatePack({ packId: pack._id, updateData: { private: pr } });
122
+ };
123
+
124
+ if (isLoading) return <div className="spinner-loader"></div>;
125
+ if (isError) return <p className="error-text">{t('packs.error.details', 'Erreur lors du chargement des détails du pack.')}</p>;
126
+ if (!pack) return null;
127
+
128
+ const renderModelsList = (models) => {
129
+ if (!models || models.length === 0) return t('packs.noModelsIncluded', 'Aucun modèle spécifié.');
130
+
131
+ return models.map(model => {
132
+ const modelName = typeof model === 'object' && model !== null ? model.name : model;
133
+ return modelName;
134
+ }).join(', ');
135
+ };
136
+
137
+ return (
138
+ <div className="pack-detail">
139
+ <Button onClick={onBack} className="back-button"><FaChevronLeft /> <Trans i18nKey="btns.back">Retour</Trans></Button>
140
+ <div className="pack-detail-header">
141
+ <h1>{pack.name}</h1>
142
+ <div className="pack-detail-actions">
143
+ {user && pack._user === user.username && (
144
+ <div className="owner-actions">
145
+ <span className="my-pack-indicator">
146
+ <FaUserCircle /> <Trans i18nKey="packs.myPack">Mon pack</Trans>
147
+ </span>
148
+ <CheckboxField
149
+ label={t('packs.public', 'Public')}
150
+ checked={!pack.private}
151
+ onChange={handlePublicToggle}
152
+ disabled={isUpdating}
153
+ title={t('packs.public.tooltip', 'Rendre ce pack visible par les autres utilisateurs dans la galerie.')}
154
+ />
155
+ </div>
156
+ )}
157
+ <Button onClick={handleInstall} disabled={isInstalling}>
158
+ <FaDownload /> {isInstalling ? t('packs.installing', 'Installation...') : t('Installer')}
159
+ </Button>
160
+ </div>
161
+ </div>
162
+ <div className="pack-meta">
163
+ <span><FaUser /> {pack._user}</span>
164
+ <span><FaStar /> {pack.stars || 0}</span>
165
+ <span><FaTag /> {(pack.tags || []).join(', ')}</span>
166
+ </div>
167
+ <div className="pack-content">
168
+ <h2><Trans i18nKey="packs.description">Description</Trans></h2>
169
+ <div className="description-content"><Markdown>{pack.description}</Markdown></div>
170
+
171
+ <h2><Trans i18nKey="packs.modelsIncluded">Modèles inclus</Trans></h2>
172
+ <p>{renderModelsList(pack.models)}</p>
173
+
174
+ <h2><Trans i18nKey="packs.dataPreview">Aperçu des données à installer</Trans></h2>
175
+ <div className="data-preview">
176
+ <pre>{JSON.stringify(pack.data, null, 2)}</pre>
177
+ </div>
178
+ </div>
179
+ </div>
180
+ );
181
+ };
182
+
183
+ const installPackMutationFn = async ({packId, lang}) => {
184
+ const response = await fetch(`/api/packs/${packId}/install?lang=${lang}`, {
185
+ method: 'POST',
186
+ headers: {
187
+ 'Content-Type': 'application/json',
188
+ },
189
+ });
190
+ if (!response.ok) {
191
+ const errorData = await response.json();
192
+ throw new Error(errorData.error || 'Failed to install pack');
193
+ }
194
+ return response.json();
195
+ };
196
+
197
+ const updatePackMutationFn = async ({ packId, updateData }) => {
198
+ const response = await fetch(`/api/packs/${packId}`, {
199
+ method: 'PATCH',
200
+ headers: {
201
+ 'Content-Type': 'application/json',
202
+ },
203
+ body: JSON.stringify(updateData),
204
+ });
205
+ if (!response.ok) {
206
+ const errorData = await response.json();
207
+ throw new Error(errorData.error || 'Failed to update pack');
208
+ }
209
+ return response.json();
210
+ };
211
+
212
+ // --- Main Gallery Component ---
213
+ const PackGallery = () => {
214
+ const { t, i18n } = useTranslation();
215
+ const lang = (i18n.resolvedLanguage || i18n.language).split(/[-_]/)?.[0];
216
+ const { addNotification } = useNotificationContext();
217
+ const { me: user } = useAuthContext();
218
+
219
+ const [showManualInstallDialog, setShowManualInstallDialog] = useState(false);
220
+ const [manualPackJson, setManualPackJson] = useState('');
221
+ const [view, setView] = useState('list');
222
+ const [selectedPackId, setSelectedPackId] = useState(null);
223
+ const [sortBy, setSortBy] = useState({ field: '_updatedAt', order: -1 });
224
+ const [showOnlyMyPacks, setShowOnlyMyPacks] = useState(false);
225
+
226
+ const queryClient = useQueryClient()
227
+ const { data: packs, isLoading, isError } = useQuery(
228
+ ['packs', sortBy, showOnlyMyPacks],
229
+ () => fetchPacks(sortBy, lang, showOnlyMyPacks, user)
230
+ );
231
+
232
+ const handleSelectPack = (packId) => {
233
+ setSelectedPackId(packId);
234
+ setView('detail');
235
+ };
236
+
237
+ const handleManualInstall = async () => {
238
+ try {
239
+ const packData = JSON.parse(manualPackJson.trim());
240
+ addNotification({ status: 'info', title: t('packs.install.started', `Installation du pack personnalisé...`) });
241
+
242
+ const response = await fetch('/api/packs/install', {
243
+ method: 'POST',
244
+ headers: {
245
+ 'Content-Type': 'application/json',
246
+ },
247
+ body: JSON.stringify({ packData, lang }),
248
+ });
249
+
250
+ if (!response.ok) {
251
+ throw new Error(await response.text());
252
+ }
253
+
254
+ addNotification({
255
+ status: 'completed',
256
+ title: t('datatable.pack.install.success', 'Pack installé avec succès !')
257
+ });
258
+ setShowManualInstallDialog(false);
259
+ setManualPackJson('');
260
+ queryClient.invalidateQueries(['packs', sortBy, showOnlyMyPacks]);
261
+
262
+ } catch (error) {
263
+ addNotification({
264
+ status: 'error',
265
+ title: t('datatable.pack.install.error', `Échec de l'installation`),
266
+ message: error.message
267
+ });
268
+ }
269
+ };
270
+
271
+ const handleBackToList = () => {
272
+ setSelectedPackId(null);
273
+ setView('list');
274
+ };
275
+
276
+ const toggleMyPacksFilter = () => {
277
+ setShowOnlyMyPacks(!showOnlyMyPacks);
278
+ };
279
+
280
+ const clearMyPacksFilter = () => {
281
+ setShowOnlyMyPacks(false);
282
+ };
283
+
284
+ const renderContent = () => {
285
+ if (view === 'detail') {
286
+ return <PackDetail packId={selectedPackId} onBack={handleBackToList} />;
287
+ }
288
+
289
+ if (isLoading) return <div className="spinner-loader"></div>;
290
+ if (isError) return <p className="error-text">{t('packs.error.loading', 'Erreur lors du chargement des packs.')}</p>;
291
+
292
+ return (
293
+ <>
294
+ <div className="gallery-header">
295
+ <h1>
296
+ {showOnlyMyPacks
297
+ ? <Trans i18nKey="packs.myPacksTitle">Mes Packs</Trans>
298
+ : <Trans i18nKey="packs.galleryTitle">Galerie de Packs</Trans>
299
+ }
300
+ </h1>
301
+ <div className="header-actions">
302
+ <div className="sort-options">
303
+ <span><Trans i18nKey="packs.sortBy">Trier par :</Trans></span>
304
+ <Button onClick={() => setSortBy({ field: '_updatedAt', order: -1 })} className={sortBy.field === '_updatedAt' ? 'active' : ''}>
305
+ <Trans i18nKey="packs.sort.lastUpdated">Derniers ajouts</Trans>
306
+ </Button>
307
+ <Button onClick={() => setSortBy({ field: 'stars', order: -1 })} className={sortBy.field === 'stars' ? 'active' : ''}>
308
+ <Trans i18nKey="packs.sort.mostStarred">Plus populaires</Trans>
309
+ </Button>
310
+ </div>
311
+ <div className="filter-actions">
312
+ {showOnlyMyPacks && (
313
+ <Button onClick={clearMyPacksFilter} className="clear-filter-btn">
314
+ <FaTimes /> <Trans i18nKey="packs.clearFilter">Voir tous les packs</Trans>
315
+ </Button>
316
+ )}
317
+ {user && !showOnlyMyPacks && (
318
+ <Button
319
+ onClick={toggleMyPacksFilter}
320
+ className="my-packs-btn"
321
+ >
322
+ <FaUserCircle /> <Trans i18nKey="packs.myPacks">Mes packs</Trans>
323
+ </Button>
324
+ )}
325
+ <Button
326
+ onClick={() => setShowManualInstallDialog(true)}
327
+ className="add-pack-button"
328
+ >
329
+ <FaPlus /> <Trans i18nKey="packs.manualInstall">Importer</Trans>
330
+ </Button>
331
+ </div>
332
+ </div>
333
+ </div>
334
+
335
+ {showOnlyMyPacks && (
336
+ <div className="filter-indicator">
337
+ <FaUserCircle />
338
+ <Trans i18nKey="packs.filteringMyPacks">Affichage de vos packs uniquement</Trans>
339
+ </div>
340
+ )}
341
+
342
+ {showManualInstallDialog && (
343
+ <DialogProvider>
344
+ <Dialog
345
+ isModal={true}
346
+ onClose={() => setShowManualInstallDialog(false)}
347
+ title={t('packs.manualInstall.title', 'Installation manuelle de pack')}
348
+ >
349
+ <div className="manual-install-dialog">
350
+ <p>
351
+ <Trans i18nKey="packs.manualInstall.instructions">
352
+ Collez ici le JSON de configuration du pack que vous souhaitez installer.
353
+ </Trans>
354
+ </p>
355
+ <TextField
356
+ multiline={true}
357
+ value={manualPackJson}
358
+ onChange={(e) => setManualPackJson(e.target.value)}
359
+ placeholder={t('packs.manualInstall.placeholder', '{"name": "Mon Pack", "description": "...", "models": [...], "data": [...]}')}
360
+ rows={15}
361
+ />
362
+ <div className="flex actions right">
363
+ <Button onClick={() => setShowManualInstallDialog(false)}><Trans i18nKey={"btns.cancel"}>Annuler</Trans></Button>
364
+ <Button disabled={!manualPackJson.trim()} className="btn-primary" onClick={() => handleManualInstall()}><Trans i18nKey={"packs.install"}>Installer</Trans></Button>
365
+ </div>
366
+ </div>
367
+ </Dialog>
368
+ </DialogProvider>
369
+ )}
370
+
371
+ {(!packs || packs.length === 0) ? (
372
+ showOnlyMyPacks
373
+ ? <p className="no-packs-message">{t('packs.noMyPacks', 'Vous n\'avez créé aucun pack.')}</p>
374
+ : <p className="no-packs-message">{t('packs.noPacks', 'Aucun pack n\'est disponible pour le moment.')}</p>
375
+ ) : (
376
+ <div className="pack-list">
377
+ {packs.map(pack => (
378
+ <PackCard key={pack._id} pack={pack} onSelect={handleSelectPack} />
379
+ ))}
380
+ </div>
381
+ )}
382
+ </>
383
+ );
384
+ };
385
+ return (
386
+ <div className="pack-gallery-container">
387
+ {renderContent()}
388
+ </div>
389
+ );
390
+ };
391
+
392
392
  export default PackGallery;