data-primals-engine 1.3.1 → 1.3.3-rc.1

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.
@@ -1,304 +1,490 @@
1
- import {isPlainObject} from "../../core.js";
2
- import {getCollection, getCollectionForUser, isObjectId, ObjectId} from "../mongodb.js";
3
- import {getModel, handleDemoInitialization} from "./data.js";
4
- import { Event} from "../../events.js"
5
- import {Logger} from "../../gameObject.js";
6
- import {hasPermission, middlewareAuthenticator, userInitiator} from "../user.js";
7
- import {isLocalUser} from "../../data.js";
8
-
9
- let logger;
10
- /**
11
- * Compare deux valeurs de manière récursive. Gère les ObjectId, les objets, les tableaux et les primitives.
12
- * @param {*} a - Première valeur.
13
- * @param {*} b - Deuxième valeur.
14
- * @returns {boolean} - True si les valeurs sont sémantiquement égales.
15
- */
16
- function isEqual(a, b) {
17
- if (a === b) return true;
18
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
19
- if (a instanceof ObjectId && b instanceof ObjectId) return a.toString() === b.toString();
20
- if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
21
- if (a.constructor !== b.constructor) return false;
22
-
23
- if (Array.isArray(a)) {
24
- if (a.length !== b.length) return false;
25
- for (let i = 0; i < a.length; i++) {
26
- if (!isEqual(a[i], b[i])) return false;
27
- }
28
- return true;
29
- }
30
-
31
- if (isPlainObject(a)) {
32
- const keys = Object.keys(a);
33
- if (keys.length !== Object.keys(b).length) return false;
34
- for (const key of keys) {
35
- if (!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key])) {
36
- return false;
37
- }
38
- }
39
- return true;
40
- }
41
-
42
- return false;
43
- }
44
- /**
45
- * Calcule la différence entre deux documents pour les champs historisés.
46
- * @param {object} beforeDoc - Le document avant modification.
47
- * @param {object} afterDoc - Le document après modification.
48
- * @param {string[]} historizedFields - La liste des champs à surveiller.
49
- * @returns {object} - Un objet contenant les changements, ou un objet vide si rien n'a changé.
50
- */
51
- function calculateDiff(beforeDoc, afterDoc, historizedFields) {
52
- const changes = {};
53
- for (const fieldName of historizedFields) {
54
- const beforeValue = beforeDoc[fieldName];
55
- const afterValue = afterDoc[fieldName];
56
-
57
- if (!isEqual(beforeValue, afterValue)) {
58
- changes[fieldName] = {
59
- from: beforeValue,
60
- to: afterValue
61
- };
62
- }
63
- }
64
- // Retourne null si aucun changement n'a été détecté, ce qui est plus facile à vérifier qu'un objet vide.
65
- return Object.keys(changes).length > 0 ? changes : null;
66
- }
67
-
68
-
69
- /**
70
- * @route GET /api/data/history/:modelName/:recordId
71
- * @desc Récupère l'historique d'un enregistrement spécifique pour le frontend.
72
- * @access Private (géré par middlewareAuthenticator)
73
- */
74
- export async function handleGetHistoryRequest(req, res) {
75
- const { modelName, recordId } = req.params;
76
- const user = req.me; // Le middleware d'authentification attache l'utilisateur à req.me
77
-
78
- try {
79
- // 1. Vérification des permissions (similaire à searchData)
80
- if (user && user.username !== 'demo' && isLocalUser(user) && (
81
- !await hasPermission(["API_ADMIN", "API_SEARCH_DATA", "API_SEARCH_DATA_"+modelName], user) ||
82
- await hasPermission(["API_SEARCH_DATA_NOT_"+modelName], user))) {
83
- return res.status(403).json({ success: false, error: i18n.t('api.permission.searchData') });
84
- }
85
-
86
- // 2. Validation des entrées
87
- if (!modelName || !recordId || !isObjectId(recordId)) {
88
- return res.status(400).json({ success: false, error: "Invalid model name or record ID." });
89
- }
90
-
91
- // 3. Récupération des données depuis la collection 'history'
92
- const historyCollection = getCollection('history');
93
- const historyData = await historyCollection.find({
94
- documentId: new ObjectId(recordId),
95
- model: modelName
96
- }).sort({ version: -1 }).toArray(); // Trier du plus récent au plus ancien
97
-
98
- // 4. Transformation des données pour correspondre au format attendu par le composant HistoryDialog.jsx
99
- const opMap = {
100
- create: 'i',
101
- update: 'u',
102
- delete: 'd'
103
- };
104
-
105
- const transformedHistory = historyData.map(entry => {
106
- const { documentId, version, operation, timestamp, user: historyUser, snapshot, changes, ...rest } = entry;
107
-
108
- // Le contenu est soit un snapshot complet, soit un objet de changements
109
- const dataPayload = snapshot || changes || {};
110
-
111
- // On exclut les métadonnées du payload pour ne pas les dupliquer
112
- const { _id: originalDocId, _model, _user, _hash, ...payloadFields } = dataPayload;
113
-
114
- return {
115
- ...rest, // Conserve l'_id du document d'historique lui-même
116
- _rid: documentId,
117
- _v: version,
118
- _op: opMap[operation] || operation, // 'create' -> 'i', 'update' -> 'u', etc.
119
- _updatedAt: timestamp,
120
- _user: historyUser?.username,
121
- ...payloadFields // Étale les champs du document (snapshot ou changes)
122
- };
123
- });
124
-
125
- res.json({ success: true, data: transformedHistory });
126
-
127
- } catch (error) {
128
- logger.error(`[handleGetHistoryRequest] Error fetching history for model ${modelName}, record ${recordId}:`, error);
129
- res.status(500).json({
130
- success: false,
131
- error: 'An internal server error occurred while fetching history.'
132
- });
133
- }
134
- }
135
-
136
-
137
- /**
138
- * Initialise les écouteurs d'événements pour le module d'historique.
139
- * @param {object} engine - L'instance du moteur.
140
- */
141
- export function onInit(engine) {
142
- logger = engine.getComponent(Logger);
143
-
144
- engine.get('/api/data/history/:modelName/:recordId', [middlewareAuthenticator, userInitiator], handleGetHistoryRequest);
145
-
146
- // --- Écouteur pour la CRÉATION de données (Version 1 - Snapshot) ---
147
- Event.Listen("OnDataAdded", async (engine, { modelName, insertedIds, user }) => {
148
- try {
149
- const model = await getModel(modelName, user);
150
- if (!model?.history?.enabled) return;
151
-
152
- const dataCollection = await getCollectionForUser(user);
153
- const historyCollection = getCollection('history');
154
-
155
- const newDocs = await dataCollection.find({ _id: { $in: insertedIds.map(id => new ObjectId(id)) } }).toArray();
156
-
157
- for (const doc of newDocs) {
158
- await historyCollection.insertOne({
159
- documentId: doc._id,
160
- model: modelName,
161
- timestamp: new Date(),
162
- user: { _id: user._id, username: user.username },
163
- version: 1,
164
- operation: 'create',
165
- snapshot: doc // Pour la création, on stocke un snapshot complet
166
- });
167
- logger.debug(`History v1 (create) created for ${modelName} document ${doc._id}`);
168
- }
169
- } catch (error) {
170
- logger.error("History Module (OnDataAdded) Error:", error);
171
- }
172
- }, "event", "system");
173
-
174
- // --- Écouteur pour la MODIFICATION de données (Versions > 1 - Diff) ---
175
- Event.Listen("OnDataEdited", async (engine, { modelName, user, before, after }) => {
176
- try {
177
- const model = await getModel(modelName, user);
178
- if (!model?.history?.enabled) return;
179
-
180
- // Détermine les champs à historiser. Si non spécifié, tous les champs le sont.
181
- const historizedFields = model.history.fields
182
- ? Object.keys(model.history.fields).filter(f => model.history.fields[f] === true)
183
- : model.fields.map(f => f.name);
184
-
185
- if (historizedFields.length === 0) return; // Pas de champs à suivre
186
-
187
- const historyCollection = getCollection('history');
188
-
189
- for (const afterDoc of after) {
190
- const beforeDoc = before.find(b => b._id.toString() === afterDoc._id.toString());
191
- if (!beforeDoc) {
192
- logger.warn(`History Module: Could not find 'before' state for document ${afterDoc._id}. Skipping history record.`);
193
- continue;
194
- }
195
-
196
- const changes = calculateDiff(beforeDoc, afterDoc, historizedFields);
197
-
198
- // S'il n'y a aucun changement sur les champs surveillés, on ne crée pas d'entrée.
199
- if (!changes) {
200
- continue;
201
- }
202
-
203
- // Récupérer la dernière version pour incrémenter
204
- const lastVersionDoc = await historyCollection.findOne({ documentId: afterDoc._id }, { sort: { version: -1 } });
205
- const newVersion = lastVersionDoc ? lastVersionDoc.version + 1 : 2; // v1 est la création
206
-
207
- await historyCollection.insertOne({
208
- documentId: afterDoc._id,
209
- model: modelName,
210
- timestamp: new Date(),
211
- user: { _id: user._id, username: user.username },
212
- version: newVersion,
213
- operation: 'update',
214
- changes: changes // On stocke uniquement les différences
215
- });
216
- logger.debug(`History v${newVersion} (update) created for ${modelName} document ${afterDoc._id}`);
217
- }
218
- } catch (error) {
219
- logger.error("History Module (OnDataEdited) Error:", error);
220
- }
221
- }, "event", "system");
222
-
223
- // --- Écouteur pour la SUPPRESSION de données (Snapshot final) ---
224
- Event.Listen("OnDataDeleted", async (engine, { modelName, user, before }) => {
225
- // 'before' est un tableau des documents complets juste avant leur suppression.
226
- try {
227
- const model = await getModel(modelName, user);
228
- if (!model?.history?.enabled) return;
229
-
230
- const historyCollection = getCollection('history');
231
-
232
- for (const deletedDoc of before) {
233
- // Récupérer la dernière version pour incrémenter
234
- const lastVersionDoc = await historyCollection.findOne({ documentId: deletedDoc._id }, { sort: { version: -1 } });
235
- // Si aucune version n'existe, c'est peut-être un cas où l'historique a été activé après la création.
236
- // On commence à 1, sinon on incrémente.
237
- const newVersion = lastVersionDoc ? lastVersionDoc.version + 1 : 1;
238
-
239
- await historyCollection.insertOne({
240
- documentId: deletedDoc._id,
241
- model: modelName,
242
- timestamp: new Date(),
243
- user: { _id: user._id, username: user.username },
244
- version: newVersion,
245
- operation: 'delete',
246
- // On stocke un snapshot final du document supprimé pour audit ou restauration.
247
- snapshot: deletedDoc
248
- });
249
- logger.debug(`History v${newVersion} (delete) created for ${modelName} document ${deletedDoc._id}`);
250
- }
251
- } catch (error) {
252
- logger.error("History Module (OnDataDeleted) Error:", error);
253
- }
254
- }, "event", "system");
255
-
256
- logger.info("History module initialized and listening for data events.");
257
- }
258
-
259
-
260
- /**
261
- * Purge (supprime définitivement) des documents et tout leur historique associé.
262
- * C'est une opération destructive à utiliser avec précaution.
263
- * @param {object} user - L'utilisateur effectuant l'opération (pour les permissions).
264
- * @param {string} modelName - Le nom du modèle concerné.
265
- * @param {object} filter - Le filtre MongoDB pour trouver les documents à purger.
266
- * @returns {Promise<{success: boolean, purgedCount: number, historyPurgedCount: number, error?: string}>}
267
- */
268
- export async function purgeData(user, modelName = null, filter=null) {
269
- const logger = new Logger("purgeData");
270
- try {
271
- const dataCollection = await getCollectionForUser(user);
272
- const historyCollection = getCollection('history');
273
-
274
- let m = modelName || { _model: modelName };
275
- const f= filter || { _user: user.username };
276
- // 1. Trouver les documents à purger pour récupérer leurs IDs
277
- const docsToPurge = await dataCollection.find({ ...m, ...f }).project({ _id: 1 }).toArray();
278
- if (docsToPurge.length === 0) {
279
- return { success: true, purgedCount: 0, historyPurgedCount: 0 };
280
- }
281
- const docIdsToPurge = docsToPurge.map(d => d._id);
282
-
283
- // 2. Purger l'historique associé à ces documents
284
- const historyResult = await historyCollection.deleteMany({ documentId: { $in: docIdsToPurge } });
285
-
286
- // 3. Purger les documents eux-mêmes
287
- const dataResult = await dataCollection.deleteMany({ _id: { $in: docIdsToPurge } });
288
-
289
- logger.info(`Purged ${dataResult.deletedCount} documents and ${historyResult.deletedCount} history entries for model '${modelName}'.`);
290
-
291
- // On pourrait aussi émettre un événement "OnDataPurged" ici si nécessaire
292
- await Event.Trigger("OnDataPurged", { user, modelName, purgedIds: docIdsToPurge });
293
-
294
- return {
295
- success: true,
296
- purgedCount: dataResult.deletedCount,
297
- historyPurgedCount: historyResult.deletedCount
298
- };
299
-
300
- } catch (error) {
301
- logger.error(`Error during data purge for model '${modelName}':`, error);
302
- return { success: false, purgedCount: 0, historyPurgedCount: 0, error: error.message };
303
- }
1
+ import {isPlainObject} from "../../core.js";
2
+ import {getCollection, getCollectionForUser, isObjectId, ObjectId} from "../mongodb.js";
3
+ import {getModel, handleDemoInitialization} from "./data.js";
4
+ import { Event} from "../../events.js"
5
+ import {Logger} from "../../gameObject.js";
6
+ import {hasPermission, middlewareAuthenticator, userInitiator} from "../user.js";
7
+ import {isLocalUser} from "../../data.js";
8
+
9
+ let logger;
10
+ /**
11
+ * Compare deux valeurs de manière récursive. Gère les ObjectId, les objets, les tableaux et les primitives.
12
+ * @param {*} a - Première valeur.
13
+ * @param {*} b - Deuxième valeur.
14
+ * @returns {boolean} - True si les valeurs sont sémantiquement égales.
15
+ */
16
+ function isEqual(a, b) {
17
+ if (a === b) return true;
18
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
19
+ if (a instanceof ObjectId && b instanceof ObjectId) return a.toString() === b.toString();
20
+ if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
21
+ if (a.constructor !== b.constructor) return false;
22
+
23
+ if (Array.isArray(a)) {
24
+ if (a.length !== b.length) return false;
25
+ for (let i = 0; i < a.length; i++) {
26
+ if (!isEqual(a[i], b[i])) return false;
27
+ }
28
+ return true;
29
+ }
30
+
31
+ if (isPlainObject(a)) {
32
+ const keys = Object.keys(a);
33
+ if (keys.length !== Object.keys(b).length) return false;
34
+ for (const key of keys) {
35
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key])) {
36
+ return false;
37
+ }
38
+ }
39
+ return true;
40
+ }
41
+
42
+ return false;
43
+ }
44
+ /**
45
+ * Calcule la différence entre deux documents pour les champs historisés.
46
+ * @param {object} beforeDoc - Le document avant modification.
47
+ * @param {object} afterDoc - Le document après modification.
48
+ * @param {string[]} historizedFields - La liste des champs à surveiller.
49
+ * @returns {object} - Un objet contenant les changements, ou un objet vide si rien n'a changé.
50
+ */
51
+ function calculateDiff(beforeDoc, afterDoc, historizedFields) {
52
+ const changes = {};
53
+ for (const fieldName of historizedFields) {
54
+ const beforeValue = beforeDoc[fieldName];
55
+ const afterValue = afterDoc[fieldName];
56
+
57
+ if (!isEqual(beforeValue, afterValue)) {
58
+ changes[fieldName] = {
59
+ from: beforeValue,
60
+ to: afterValue
61
+ };
62
+ }
63
+ }
64
+ // Retourne null si aucun changement n'a été détecté, ce qui est plus facile à vérifier qu'un objet vide.
65
+ return Object.keys(changes).length > 0 ? changes : null;
66
+ }
67
+ /**
68
+ * @route POST /api/data/history/:modelName/:recordId/revert/:version
69
+ * @desc Restaure un document à l'état d'une version spécifique.
70
+ * @access Private
71
+ */
72
+ export async function handleRevertToRevisionRequest(req, res) {
73
+ const { modelName, recordId, version } = req.params;
74
+ const user = req.me;
75
+
76
+ try {
77
+ // 1. Permissions check (user must be able to edit the data)
78
+ if (user && user.username !== 'demo' && isLocalUser(user) && (
79
+ !await hasPermission(["API_ADMIN", "API_EDIT_DATA", "API_EDIT_DATA_"+modelName], user) ||
80
+ await hasPermission(["API_EDIT_DATA_NOT_"+modelName], user))) {
81
+ return res.status(403).json({ success: false, error: i18n.t('api.permission.editData') });
82
+ }
83
+
84
+ // 2. Input validation
85
+ const versionInt = parseInt(version, 10);
86
+ if (!modelName || !recordId || !isObjectId(recordId) || !version || isNaN(versionInt)) {
87
+ return res.status(400).json({ success: false, error: "Invalid model name, record ID, or version." });
88
+ }
89
+
90
+ // 3. Get the current state of the document (for history diff)
91
+ const dataCollection = await getCollectionForUser(user);
92
+ const docId = new ObjectId(recordId);
93
+ const beforeDoc = await dataCollection.findOne({ _id: docId });
94
+
95
+ if (!beforeDoc) {
96
+ return res.status(404).json({ success: false, error: "Current document not found." });
97
+ }
98
+
99
+ // 4. Reconstruct the document to the target version
100
+ const documentStateAtVersion = await getDocumentAtVersion(recordId, modelName, versionInt);
101
+
102
+ if (!documentStateAtVersion) {
103
+ return res.status(404).json({ success: false, error: "Could not reconstruct document at the specified version." });
104
+ }
105
+
106
+ // 5. Calculate changes between current version and target version
107
+ const model = await getModel(modelName, user);
108
+ const historizedFields = model?.history?.fields
109
+ ? Object.keys(model.history.fields).filter(f => model.history.fields[f] === true)
110
+ : model.fields.map(f => f.name);
111
+
112
+ const changes = calculateDiff(beforeDoc, documentStateAtVersion, historizedFields);
113
+
114
+ // 6. Replace the document with the reverted state
115
+ const { _id, ...payloadForReplacement } = documentStateAtVersion;
116
+ const replaceResult = await dataCollection.replaceOne({ _id: docId }, payloadForReplacement);
117
+
118
+ // On ne crée une entrée d'historique que si des champs historisés ont changé.
119
+ // Le document a pu être modifié à cause de champs non-historisés, mais cela
120
+ // ne devrait pas créer une nouvelle version dans l'historique.
121
+ if (changes) {
122
+ // 7. Create a new history entry manually
123
+ const historyCollection = getCollection('history');
124
+
125
+ // Get last version number
126
+ const lastVersionDoc = await historyCollection.findOne(
127
+ { documentId: docId },
128
+ { projection: { version: 1 }, sort: { version: -1 } }
129
+ );
130
+ const newVersion = lastVersionDoc ? lastVersionDoc.version + 1 : 1;
131
+
132
+ await historyCollection.insertOne({
133
+ documentId: docId,
134
+ model: modelName,
135
+ timestamp: new Date(),
136
+ user: { _id: user._id, username: user.username },
137
+ version: newVersion,
138
+ operation: 'update', // Une restauration est enregistrée comme une 'update'
139
+ changes: changes
140
+ });
141
+
142
+ logger.info(`User ${user.username} reverted document ${modelName}:${recordId} to version ${version}. New history entry created (v${newVersion}).`);
143
+ } else if (replaceResult.modifiedCount > 0) {
144
+ logger.info(`Document ${modelName}:${recordId} was modified during revert, but no historized fields changed. No new history entry created.`);
145
+ }
146
+
147
+ res.json({ success: true, message: "Document successfully reverted." });
148
+
149
+ } catch (error) {
150
+ logger.error(`[handleRevertToRevisionRequest] Error reverting document ${modelName}:${recordId} to version ${version}:`, error);
151
+ res.status(500).json({
152
+ success: false,
153
+ error: 'An internal server error occurred during the revert operation.'
154
+ });
155
+ }
156
+ }
157
+
158
+
159
+ /**
160
+ * @route GET /api/data/history/:modelName/:recordId
161
+ * @desc Récupère l'historique d'un enregistrement spécifique pour le frontend.
162
+ * @access Private (géré par middlewareAuthenticator)
163
+ */
164
+ export async function handleGetHistoryRequest(req, res) {
165
+ const { modelName, recordId } = req.params;
166
+ const user = req.me; // Le middleware d'authentification attache l'utilisateur à req.me
167
+
168
+ try {
169
+ // 1. Vérification des permissions (similaire à searchData)
170
+ if (user && user.username !== 'demo' && isLocalUser(user) && (
171
+ !await hasPermission(["API_ADMIN", "API_SEARCH_DATA", "API_SEARCH_DATA_"+modelName], user) ||
172
+ await hasPermission(["API_SEARCH_DATA_NOT_"+modelName], user))) {
173
+ return res.status(403).json({ success: false, error: i18n.t('api.permission.searchData') });
174
+ }
175
+
176
+ // 2. Validation des entrées
177
+ if (!modelName || !recordId || !isObjectId(recordId)) {
178
+ return res.status(400).json({ success: false, error: "Invalid model name or record ID." });
179
+ }
180
+
181
+ // 3. Récupération des données depuis la collection 'history'
182
+ const historyCollection = getCollection('history');
183
+ const historyData = await historyCollection.find({
184
+ documentId: new ObjectId(recordId),
185
+ model: modelName
186
+ }).sort({ version: -1 }).toArray(); // Trier du plus récent au plus ancien
187
+
188
+ // 4. Transformation des données pour correspondre au format attendu par le composant HistoryDialog.jsx
189
+ const opMap = {
190
+ create: 'i',
191
+ update: 'u',
192
+ delete: 'd'
193
+ };
194
+
195
+ const transformedHistory = historyData.map(entry => {
196
+ const { documentId, version, operation, timestamp, user: historyUser, snapshot, changes, ...rest } = entry;
197
+
198
+ // Le contenu est soit un snapshot complet, soit un objet de changements
199
+ const dataPayload = snapshot || changes || {};
200
+
201
+ // On exclut les métadonnées du payload pour ne pas les dupliquer
202
+ const { _id: originalDocId, _model, _user, _hash, ...payloadFields } = dataPayload;
203
+
204
+ return {
205
+ ...rest, // Conserve l'_id du document d'historique lui-même
206
+ _rid: documentId,
207
+ _v: version,
208
+ _op: opMap[operation] || operation, // 'create' -> 'i', 'update' -> 'u', etc.
209
+ _updatedAt: timestamp,
210
+ _user: historyUser?.username,
211
+ ...payloadFields // Étale les champs du document (snapshot ou changes)
212
+ };
213
+ });
214
+
215
+ res.json({ success: true, data: transformedHistory });
216
+
217
+ } catch (error) {
218
+ logger.error(`[handleGetHistoryRequest] Error fetching history for model ${modelName}, record ${recordId}:`, error);
219
+ res.status(500).json({
220
+ success: false,
221
+ error: 'An internal server error occurred while fetching history.'
222
+ });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * @route GET /api/data/history/:modelName/:recordId/:version
228
+ * @desc Récupère un document à une version spécifique de son historique.
229
+ * @access Private (géré par middlewareAuthenticator)
230
+ */
231
+ export async function handleGetRevisionRequest(req, res) {
232
+ const { modelName, recordId, version } = req.params;
233
+ const user = req.me;
234
+
235
+ try {
236
+ // 1. Permissions check (same as getting history)
237
+ if (user && user.username !== 'demo' && isLocalUser(user) && (
238
+ !await hasPermission(["API_ADMIN", "API_SEARCH_DATA", "API_SEARCH_DATA_"+modelName], user) ||
239
+ await hasPermission(["API_SEARCH_DATA_NOT_"+modelName], user))) {
240
+ return res.status(403).json({ success: false, error: i18n.t('api.permission.searchData') });
241
+ }
242
+
243
+ // 2. Input validation
244
+ if (!modelName || !recordId || !isObjectId(recordId) || !version || isNaN(parseInt(version, 10))) {
245
+ return res.status(400).json({ success: false, error: "Invalid model name, record ID, or version." });
246
+ }
247
+
248
+ // 3. Reconstruct the document
249
+ const documentState = await getDocumentAtVersion(recordId, modelName, parseInt(version, 10));
250
+
251
+ if (!documentState) {
252
+ return res.status(404).json({ success: false, error: "Could not reconstruct document at the specified version." });
253
+ }
254
+
255
+ res.json({ success: true, data: documentState });
256
+
257
+ } catch (error) {
258
+ logger.error(`[handleGetRevisionRequest] Error fetching revision for model ${modelName}, record ${recordId}, version ${version}:`, error);
259
+ res.status(500).json({
260
+ success: false,
261
+ error: 'An internal server error occurred while fetching the revision.'
262
+ });
263
+ }
264
+ }
265
+
266
+
267
+ /**
268
+ * Initialise les écouteurs d'événements pour le module d'historique.
269
+ * @param {object} engine - L'instance du moteur.
270
+ */
271
+ export function onInit(engine) {
272
+ logger = engine.getComponent(Logger);
273
+
274
+ engine.get('/api/data/history/:modelName/:recordId', [middlewareAuthenticator, userInitiator], handleGetHistoryRequest);
275
+ engine.get('/api/data/history/:modelName/:recordId/:version', [middlewareAuthenticator, userInitiator], handleGetRevisionRequest);
276
+ engine.post('/api/data/history/:modelName/:recordId/revert/:version', [middlewareAuthenticator, userInitiator], handleRevertToRevisionRequest);
277
+
278
+ // --- Écouteur pour la CRÉATION de données (Version 1 - Snapshot) ---
279
+ Event.Listen("OnDataAdded", async (engine, { modelName, insertedIds, user }) => {
280
+ try {
281
+ const model = await getModel(modelName, user);
282
+ if (!model?.history?.enabled) return;
283
+
284
+ const dataCollection = await getCollectionForUser(user);
285
+ const historyCollection = getCollection('history');
286
+
287
+ const newDocs = await dataCollection.find({ _id: { $in: insertedIds.map(id => new ObjectId(id)) } }).toArray();
288
+
289
+ for (const doc of newDocs) {
290
+ await historyCollection.insertOne({
291
+ documentId: doc._id,
292
+ model: modelName,
293
+ timestamp: new Date(),
294
+ user: { _id: user._id, username: user.username },
295
+ version: 1,
296
+ operation: 'create',
297
+ snapshot: doc // Pour la création, on stocke un snapshot complet
298
+ });
299
+ logger.debug(`History v1 (create) created for ${modelName} document ${doc._id}`);
300
+ }
301
+ } catch (error) {
302
+ logger.error("History Module (OnDataAdded) Error:", error);
303
+ }
304
+ }, "event", "system");
305
+
306
+ // --- Écouteur pour la MODIFICATION de données (Versions > 1 - Diff) ---
307
+ Event.Listen("OnDataEdited", async (engine, { modelName, user, before, after }) => {
308
+ try {
309
+ const model = await getModel(modelName, user);
310
+ if (!model?.history?.enabled) return;
311
+
312
+ // Détermine les champs à historiser. Si non spécifié, tous les champs le sont.
313
+ const historizedFields = model.history.fields
314
+ ? Object.keys(model.history.fields).filter(f => model.history.fields[f] === true)
315
+ : model.fields.map(f => f.name);
316
+
317
+ if (historizedFields.length === 0) return; // Pas de champs à suivre
318
+
319
+ const historyCollection = getCollection('history');
320
+
321
+ for (const afterDoc of after) {
322
+ const beforeDoc = before.find(b => b._id.toString() === afterDoc._id.toString());
323
+ if (!beforeDoc) {
324
+ logger.warn(`History Module: Could not find 'before' state for document ${afterDoc._id}. Skipping history record.`);
325
+ continue;
326
+ }
327
+
328
+ const changes = calculateDiff(beforeDoc, afterDoc, historizedFields);
329
+
330
+ // S'il n'y a aucun changement sur les champs surveillés, on ne crée pas d'entrée.
331
+ if (!changes) {
332
+ continue;
333
+ }
334
+
335
+ // Récupérer la dernière version pour incrémenter
336
+ const lastVersionDoc = await historyCollection.findOne({ documentId: afterDoc._id }, { sort: { version: -1 } });
337
+ const newVersion = lastVersionDoc ? lastVersionDoc.version + 1 : 2; // v1 est la création
338
+
339
+ await historyCollection.insertOne({
340
+ documentId: afterDoc._id,
341
+ model: modelName,
342
+ timestamp: new Date(),
343
+ user: { _id: user._id, username: user.username },
344
+ version: newVersion,
345
+ operation: 'update',
346
+ changes: changes // On stocke uniquement les différences
347
+ });
348
+ logger.debug(`History v${newVersion} (update) created for ${modelName} document ${afterDoc._id}`);
349
+ }
350
+ } catch (error) {
351
+ logger.error("History Module (OnDataEdited) Error:", error);
352
+ }
353
+ }, "event", "system");
354
+
355
+ // --- Écouteur pour la SUPPRESSION de données (Snapshot final) ---
356
+ Event.Listen("OnDataDeleted", async (engine, { modelName, user, before }) => {
357
+ // 'before' est un tableau des documents complets juste avant leur suppression.
358
+ try {
359
+ const model = await getModel(modelName, user);
360
+ if (!model?.history?.enabled) return;
361
+
362
+ const historyCollection = getCollection('history');
363
+
364
+ for (const deletedDoc of before) {
365
+ // Récupérer la dernière version pour incrémenter
366
+ const lastVersionDoc = await historyCollection.findOne({ documentId: deletedDoc._id }, { sort: { version: -1 } });
367
+ // Si aucune version n'existe, c'est peut-être un cas où l'historique a été activé après la création.
368
+ // On commence à 1, sinon on incrémente.
369
+ const newVersion = lastVersionDoc ? lastVersionDoc.version + 1 : 1;
370
+
371
+ await historyCollection.insertOne({
372
+ documentId: deletedDoc._id,
373
+ model: modelName,
374
+ timestamp: new Date(),
375
+ user: { _id: user._id, username: user.username },
376
+ version: newVersion,
377
+ operation: 'delete',
378
+ // On stocke un snapshot final du document supprimé pour audit ou restauration.
379
+ snapshot: deletedDoc
380
+ });
381
+ logger.debug(`History v${newVersion} (delete) created for ${modelName} document ${deletedDoc._id}`);
382
+ }
383
+ } catch (error) {
384
+ logger.error("History Module (OnDataDeleted) Error:", error);
385
+ }
386
+ }, "event", "system");
387
+
388
+ logger.info("History module initialized and listening for data events.");
389
+ }
390
+
391
+ /**
392
+ * Reconstructs a document to a specific version from its history by finding the last
393
+ * available snapshot and applying subsequent changes.
394
+ * @param {ObjectId|string} documentId - The ID of the document.
395
+ * @param {string} modelName - The model name.
396
+ * @param {number} targetVersion - The version to reconstruct to.
397
+ * @returns {Promise<object|null>} - The reconstructed document object, or null if not found.
398
+ */
399
+ export async function getDocumentAtVersion(documentId, modelName, targetVersion) {
400
+ const historyCollection = getCollection('history');
401
+ const docId = typeof documentId === 'string' ? new ObjectId(documentId) : documentId;
402
+ const version = parseInt(targetVersion, 10);
403
+
404
+ // 1. Find the most recent snapshot at or before the target version.
405
+ const lastSnapshotEntry = await historyCollection.findOne({
406
+ documentId: docId,
407
+ model: modelName,
408
+ version: { $lte: version },
409
+ snapshot: { $exists: true }
410
+ }, { sort: { version: -1 } });
411
+
412
+ if (!lastSnapshotEntry) {
413
+ logger.warn(`No snapshot found for ${modelName}:${documentId} up to version ${version}. Cannot reconstruct.`);
414
+ return null;
415
+ }
416
+
417
+ // 2. Start with this snapshot.
418
+ let reconstructedDoc = lastSnapshotEntry.snapshot;
419
+
420
+ if (lastSnapshotEntry.version === version) {
421
+ return reconstructedDoc;
422
+ }
423
+
424
+ // 3. Find all 'update' operations between our snapshot's version and the target version.
425
+ const updatesToApply = await historyCollection.find({
426
+ documentId: docId,
427
+ model: modelName,
428
+ version: { $gt: lastSnapshotEntry.version, $lte: version },
429
+ operation: 'update'
430
+ }).sort({ version: 1 }).toArray();
431
+
432
+ // 4. Apply the changes sequentially.
433
+ for (const update of updatesToApply) {
434
+ if (update.changes) {
435
+ for (const fieldName in update.changes) {
436
+ if (Object.prototype.hasOwnProperty.call(update.changes, fieldName)) {
437
+ reconstructedDoc[fieldName] = update.changes[fieldName].to;
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+ return reconstructedDoc;
444
+ }
445
+
446
+ /**
447
+ * Purge (supprime définitivement) des documents et tout leur historique associé.
448
+ * C'est une opération destructive à utiliser avec précaution.
449
+ * @param {object} user - L'utilisateur effectuant l'opération (pour les permissions).
450
+ * @param {string} modelName - Le nom du modèle concerné.
451
+ * @param {object} filter - Le filtre MongoDB pour trouver les documents à purger.
452
+ * @returns {Promise<{success: boolean, purgedCount: number, historyPurgedCount: number, error?: string}>}
453
+ */
454
+ export async function purgeData(user, modelName = null, filter=null) {
455
+ const logger = new Logger("purgeData");
456
+ try {
457
+ const dataCollection = await getCollectionForUser(user);
458
+ const historyCollection = getCollection('history');
459
+
460
+ let m = modelName || { _model: modelName };
461
+ const f= filter || { _user: user.username };
462
+ // 1. Trouver les documents à purger pour récupérer leurs IDs
463
+ const docsToPurge = await dataCollection.find({ ...m, ...f }).project({ _id: 1 }).toArray();
464
+ if (docsToPurge.length === 0) {
465
+ return { success: true, purgedCount: 0, historyPurgedCount: 0 };
466
+ }
467
+ const docIdsToPurge = docsToPurge.map(d => d._id);
468
+
469
+ // 2. Purger l'historique associé à ces documents
470
+ const historyResult = await historyCollection.deleteMany({ documentId: { $in: docIdsToPurge } });
471
+
472
+ // 3. Purger les documents eux-mêmes
473
+ const dataResult = await dataCollection.deleteMany({ _id: { $in: docIdsToPurge } });
474
+
475
+ logger.info(`Purged ${dataResult.deletedCount} documents and ${historyResult.deletedCount} history entries for model '${modelName}'.`);
476
+
477
+ // On pourrait aussi émettre un événement "OnDataPurged" ici si nécessaire
478
+ await Event.Trigger("OnDataPurged", { user, modelName, purgedIds: docIdsToPurge });
479
+
480
+ return {
481
+ success: true,
482
+ purgedCount: dataResult.deletedCount,
483
+ historyPurgedCount: historyResult.deletedCount
484
+ };
485
+
486
+ } catch (error) {
487
+ logger.error(`Error during data purge for model '${modelName}':`, error);
488
+ return { success: false, purgedCount: 0, historyPurgedCount: 0, error: error.message };
489
+ }
304
490
  }