data-primals-engine 1.4.2 → 1.5.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 (59) hide show
  1. package/README.md +878 -856
  2. package/client/package-lock.json +82 -0
  3. package/client/package.json +2 -0
  4. package/client/src/App.jsx +1 -1
  5. package/client/src/App.scss +25 -7
  6. package/client/src/AssistantChat.scss +3 -2
  7. package/client/src/ConditionBuilder.jsx +1 -1
  8. package/client/src/ConditionBuilder2.jsx +2 -1
  9. package/client/src/DashboardView.jsx +569 -569
  10. package/client/src/DataEditor.jsx +376 -368
  11. package/client/src/DataLayout.jsx +4 -10
  12. package/client/src/DataTable.jsx +858 -817
  13. package/client/src/Field.jsx +1825 -1784
  14. package/client/src/FlexDataRenderer.jsx +2 -0
  15. package/client/src/FlexTreeUtils.js +1 -1
  16. package/client/src/GeolocationField.jsx +94 -0
  17. package/client/src/KPIDialog.jsx +11 -1
  18. package/client/src/ModelCreator.jsx +1 -2
  19. package/client/src/ModelCreatorField.jsx +24 -27
  20. package/client/src/ModelList.jsx +1 -1
  21. package/client/src/RelationField.jsx +2 -2
  22. package/client/src/constants.js +3 -3
  23. package/client/src/filter.js +0 -155
  24. package/client/src/hooks/useTutorials.jsx +62 -65
  25. package/client/src/translations.js +14 -2
  26. package/package.json +2 -1
  27. package/perf/README.md +147 -0
  28. package/perf/artillery-hooks.js +37 -0
  29. package/perf/perf-shot-hardwork.yml +84 -0
  30. package/perf/perf-shot-search.yml +45 -0
  31. package/perf/setup.yml +26 -0
  32. package/server.js +1 -1
  33. package/src/constants.js +264 -31
  34. package/src/core.js +15 -1
  35. package/src/data.js +1 -1
  36. package/src/defaultModels.js +1544 -1540
  37. package/src/email.js +5 -2
  38. package/src/engine.js +10 -3
  39. package/src/filter.js +274 -260
  40. package/src/i18n.js +187 -177
  41. package/src/modules/assistant/assistant.js +3 -1
  42. package/src/modules/bucket.js +12 -15
  43. package/src/modules/data/data.backup.js +11 -8
  44. package/src/modules/data/data.core.js +2 -1
  45. package/src/modules/data/data.js +6 -3
  46. package/src/modules/data/data.operations.js +610 -168
  47. package/src/modules/data/data.routes.js +1821 -1785
  48. package/src/modules/data/data.scheduling.js +2 -1
  49. package/src/modules/data/data.validation.js +7 -1
  50. package/src/modules/file.js +4 -2
  51. package/src/modules/user.js +4 -1
  52. package/src/modules/workflow.js +9 -10
  53. package/src/openai.jobs.js +2 -0
  54. package/src/packs.js +22 -5
  55. package/src/providers.js +22 -7
  56. package/swagger-en.yml +133 -0
  57. package/test/data.integration.test.js +1060 -981
  58. package/test/import_export.integration.test.js +1 -1
  59. package/test/model.integration.test.js +377 -221
package/src/email.js CHANGED
@@ -3,6 +3,7 @@ import nodemailer from "nodemailer";
3
3
  import juice from "juice";
4
4
  import {Event} from "./events.js";
5
5
  import {emailDefaultConfig} from "./constants.js";
6
+ import {Config} from "./config.js";
6
7
 
7
8
  // Le transporteur par défaut, utilisé si aucune config spécifique n'est fournie.
8
9
  const defaultTransporter = nodemailer.createTransport({
@@ -45,12 +46,14 @@ const createTransporter = (smtpConfig) => {
45
46
  * @param {string|null} tpl - Le template HTML à utiliser.
46
47
  */
47
48
  export const sendEmail = async (email = "", data, smtpConfig = null, lang, tpl = null) => {
48
- const contactEmail = smtpConfig ? (smtpConfig.from || emailDefaultConfig.from) :"Our company <noreply@ourdomain.tld>";
49
+
50
+ const cfg = Config.Get('emailDefaultConfig', emailDefaultConfig);
51
+ const contactEmail = smtpConfig ? (smtpConfig.from || cfg.from) :"Our company <noreply@ourdomain.tld>";
49
52
  const emails = Array.isArray(email) ? email : [email];
50
53
  if (emails.length === 0) return false;
51
54
 
52
55
  // Choisir le transporteur à utiliser
53
- const transporter = smtpConfig ? createTransporter(smtpConfig||emailDefaultConfig) : defaultTransporter;
56
+ const transporter = smtpConfig ? createTransporter(smtpConfig||cfg) : defaultTransporter;
54
57
 
55
58
  Event.Listen("OnEmailTemplate", (data, lang) => data.content, "event", "system");
56
59
 
package/src/engine.js CHANGED
@@ -7,7 +7,7 @@ import process from "process";
7
7
  import {
8
8
  cookiesSecret,
9
9
  databasePoolSize,
10
- dbName,
10
+ dbName as dbNameBase,
11
11
  tlsAllowInvalidCertificates, tlsAllowInvalidHostnames
12
12
  } from "./constants.js";
13
13
  import http from "http";
@@ -22,6 +22,8 @@ import {Event} from "./events.js";
22
22
  import path from "node:path";
23
23
  import { fileURLToPath } from 'node:url';
24
24
  import {validateModelStructure} from "./modules/data/data.validation.js";
25
+ import { setSafeRegex } from "./filter.js";
26
+ import safeRegexCallback from "safe-regex";
25
27
  import {createModel, deleteModels, getModels, installAllPacks} from "./modules/data/data.operations.js";
26
28
  // Constants
27
29
 
@@ -30,7 +32,7 @@ import {createModel, deleteModels, getModels, installAllPacks} from "./modules/d
30
32
  const __filename = fileURLToPath(import.meta.url);
31
33
  const __dirname = path.dirname(__filename);
32
34
 
33
-
35
+ let dbName = Config.Get('dbName', dbNameBase);
34
36
  let caFile, certFile, keyFile;
35
37
  try {
36
38
  if (process.env.CA_CERT)
@@ -97,6 +99,9 @@ export const MongoDatabase = MongoClient.db(dbName);
97
99
 
98
100
  export const Engine = {
99
101
  Create: async (options = { app : null}) => {
102
+ // On injecte la dépendance safe-regex dans le module de filtrage au tout début.
103
+ setSafeRegex(safeRegexCallback);
104
+
100
105
  const engine = GameObject.Create("Engine");
101
106
  console.log("Creating engine", Config.Get('modules'));
102
107
  const logger = engine.addComponent(Logger);
@@ -122,7 +127,9 @@ export const Engine = {
122
127
  uploadDir: process.cwd()+'/uploads/tmp',
123
128
  multiples: true // req.files to be arrays of files
124
129
  }));
125
- app.use(cookieParser(process.env.COOKIES_SECRET || cookiesSecret));
130
+
131
+ const cs = Config.Get('cookieSecret', process.env.COOKIES_SECRET || cookiesSecret)
132
+ app.use(cookieParser(cs));
126
133
  app.use(requestIp.mw())
127
134
 
128
135
  engine.use = (...args) => {
package/src/filter.js CHANGED
@@ -1,261 +1,275 @@
1
- import safeRegex from 'safe-regex';
2
- /**
3
- * Evaluates a single condition against form data.
4
- * @param {object} currentModelDef - The definition of the current model.
5
- * @param {object} condition - The condition to evaluate.
6
- * @param {object} formData - The form data.
7
- * @param {object[]} allModels - An array of all model definitions.
8
- * @param {object} user - The current user.
9
- * @returns {boolean} - True if the condition is met, false otherwise.
10
- */
11
- const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user) => {
12
- // Condition est directement un filtre MongoDB, donc on l'applique
13
- // en utilisant les opérateurs et les valeurs qu'il contient.
14
-
15
- if (!condition || typeof condition !== 'object') {
16
- console.warn("[Client Eval] Condition is not an object:", condition);
17
- return true; // Permissive default
18
- }
19
-
20
- // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
21
- if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
22
- const fieldName = Object.keys(condition)[0];
23
- const value = condition[fieldName];
24
- return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
25
- }
26
-
27
- // Gestion des opérateurs d'agrégation (commencent par $)
28
- const operator = Object.keys(condition)[0];
29
- if (operator === '$eq' && Array.isArray(condition[operator])) {
30
- // Cas spécial pour {$eq: ['$field', value]}
31
- const [fieldPath, expectedValue] = condition[operator];
32
- if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
33
- const fieldName = fieldPath.substring(1); // Enlève le $ devant
34
- return formData[fieldName] == expectedValue;
35
- }
36
- }
37
-
38
- // Si la condition contient des opérateurs logiques, on les gère ici
39
- if (condition.$and || condition.$or || condition.$not || condition.$nor) {
40
- console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
41
- return true; // Permissive default
42
- }
43
-
44
- if (condition.$find) {
45
- const fieldName = Object.keys(condition)[0];
46
- const fieldValue = formData[fieldName];
47
- const findCondition = condition.$find;
48
-
49
- if (!Array.isArray(fieldValue)) return false;
50
-
51
- return fieldValue.some(item => {
52
- // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
53
- if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
54
- const [fieldPath, value] = findCondition.$eq;
55
- if (fieldPath.startsWith("$$this.")) {
56
- const fieldToCheck = fieldPath.replace("$$this.", "");
57
- return item[fieldToCheck] == value;
58
- }
59
- }
60
-
61
- // Sinon, évaluation normale
62
- const tempData = { ...item };
63
- return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
64
- });
65
- }
66
-
67
- // Si la condition contient un opérateur $exists, on le gère ici
68
- if (condition.$exists !== undefined) {
69
- const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
70
- const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
71
- const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
72
- return exists === shouldExist;
73
- }
74
-
75
- // Si la condition contient un opérateur $find, on le gère ici
76
- if (condition.$find) {
77
- // Récupérer le nom du champ
78
- const fieldName = Object.keys(condition)[0];
79
- const fieldValue = formData[fieldName];
80
- try {
81
- // Assuming evaluateSingleCondition handles $find
82
- return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
83
- } catch (error) {
84
- console.error("Error evaluating $find condition:", condition, error);
85
- return false;
86
- }
87
- }
88
-
89
- // Récupérer le nom du champ et la condition
90
- const fieldName = Object.keys(condition)[0];
91
- const fieldValue = condition[fieldName];
92
-
93
- // Récupérer la définition du champ
94
- const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
95
-
96
- // Si la définition du champ n'est pas trouvée, on retourne true
97
- if (!fieldDef) {
98
- console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
99
- return true; // Permissive default
100
- }
101
-
102
- let targetValue = formData[fieldName];
103
- let processedConditionValue = fieldValue;
104
-
105
- // 1. Handle $exists (on the first field)
106
- // 2. Convert condition value based on operator's expected input type
107
- const fieldType = fieldDef?.type; // Type of the first field
108
-
109
- try {
110
- processedConditionValue = convertValueType(fieldValue, fieldType);
111
- } catch (e) {
112
- logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
113
- return false;
114
- }
115
-
116
- return evaluateComparison(fieldValue, targetValue, processedConditionValue, condition);
117
-
118
- function logClientEvalWarning(message, details) {
119
- console.warn(`[Client Eval] ${message}:`, details);
120
- }
121
-
122
- function convertValueType(value, inputType) {
123
- switch (inputType) {
124
- case 'number':
125
- const numValue = parseFloat(value);
126
- if (isNaN(numValue)) {
127
- throw new Error(`Invalid number value: ${value}`);
128
- }
129
- return numValue;
130
- case 'boolean':
131
- return String(value).toLowerCase() === 'true';
132
- case 'csv':
133
- return String(value).split(',').map(item => item.trim()).filter(Boolean);
134
- case 'text':
135
- default:
136
- return String(value);
137
- }
138
- }
139
-
140
- function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
141
- try {
142
- switch (typeof operator === 'object' ? Object.keys(operator)[0] : null) {
143
- case '$eq': return targetValue === processedConditionValue;
144
- case '$ne': return targetValue !== processedConditionValue;
145
- case '$gt': return targetValue > processedConditionValue;
146
- case '$lt': return targetValue < processedConditionValue;
147
- case '$gte': return targetValue >= processedConditionValue;
148
- case '$lte': return targetValue <= processedConditionValue;
149
- case '$regex':
150
- if (typeof targetValue !== 'string') return false;
151
- if (typeof processedConditionValue !== 'string') return false;
152
- try {
153
- if( safeRegex(processedConditionValue)) {
154
- const regex = new RegExp(processedConditionValue, 'i');
155
- return regex.test(targetValue);
156
- }
157
- return false;
158
- } catch (e) {
159
- logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
160
- return false;
161
- }
162
- case '$in':
163
- return Array.isArray(processedConditionValue) && processedConditionValue.includes(String(targetValue));
164
- case '$nin':
165
- return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(String(targetValue));
166
- default:
167
- logClientEvalWarning(`Unhandled operator in client evaluation logic: ${operator}`, condition);
168
- return true; // Permissive default
169
- }
170
- } catch (evalError) {
171
- logClientEvalWarning(`Error during client condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
172
- return false;
173
- }
174
- }
175
- };
176
-
177
- export const isConditionMet = (model, cond, formData, allModels, user) => {
178
- const condition = cond;
179
-
180
- if (!condition) return true;
181
-
182
- if (typeof condition !== 'object' || condition === null) {
183
- return true;
184
- }
185
-
186
- // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
187
- // Dans ce mode, la condition doit être un objet avec un seul opérateur.
188
- if (!model) {
189
- const keys = Object.keys(condition);
190
- if (keys.length !== 1 || !keys[0].startsWith('$')) {
191
- console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
192
- return false; // Plus sûr que true pour éviter les faux positifs
193
- }
194
-
195
- const operator = keys[0];
196
- const operands = condition[operator];
197
-
198
- switch (operator) {
199
- // Opérateurs logiques (récursifs)
200
- case '$and':
201
- return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user));
202
- case '$or':
203
- return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user));
204
- case '$not':
205
- return !isConditionMet(null, operands, formData, allModels, user);
206
- case '$nor':
207
- return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user));
208
-
209
- // Opérateurs de comparaison (terminaux)
210
- case '$eq':
211
- return Array.isArray(operands) && operands[0] === operands[1];
212
- case '$ne':
213
- return Array.isArray(operands) && operands[0] !== operands[1];
214
- case '$in':
215
- return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
216
- case '$nin':
217
- return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
218
- case '$gt':
219
- return Array.isArray(operands) && operands[0] > operands[1];
220
- case '$gte':
221
- return Array.isArray(operands) && operands[0] >= operands[1];
222
- case '$lt':
223
- return Array.isArray(operands) && operands[0] < operands[1];
224
- case '$lte':
225
- return Array.isArray(operands) && operands[0] <= operands[1];
226
-
227
- default:
228
- console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
229
- return false;
230
- }
231
- }
232
-
233
- // --- Logique existante pour l'évaluation AVEC modèle ---
234
-
235
- if (condition.$and && Array.isArray(condition.$and)) {
236
- if (condition.$and.length === 0) return true;
237
- return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user));
238
- }
239
- if (condition.$or && Array.isArray(condition.$or)) {
240
- if (condition.$or.length === 0) return false;
241
- return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user));
242
- }
243
- if (condition.$not) {
244
- return !isConditionMet(model, condition.$not, formData, allModels, user);
245
- }
246
- if (condition.$nor && Array.isArray(condition.$nor)) {
247
- if (condition.$nor.length === 0) return true;
248
- return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user));
249
- }
250
-
251
- // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
252
- if (Object.keys(condition).length === 1) {
253
- const operator = Object.keys(condition)[0];
254
- if (operator.startsWith('$') && operator !== '$find' &&
255
- Array.isArray(condition[operator])) {
256
- return evaluateSingleCondition(model, condition, formData, allModels, user);
257
- }
258
- }
259
-
260
- return evaluateSingleCondition(model, condition, formData, allModels, user);
1
+
2
+ let safeRegex = null; // Par défaut, aucune fonction de validation n'est définie.
3
+
4
+ /**
5
+ * Permet d'injecter une fonction de validation de regex (côté serveur).
6
+ * @param {function} validator - La fonction qui valide une regex, ex: la fonction du module 'safe-regex'.
7
+ */
8
+ export function setSafeRegex(validator) {
9
+ safeRegex = validator;
10
+ }
11
+
12
+ /**
13
+ * Evaluates a single condition against form data.
14
+ * @param {object} currentModelDef - The definition of the current model.
15
+ * @param {object} condition - The condition to evaluate.
16
+ * @param {object} formData - The form data.
17
+ * @param {object[]} allModels - An array of all model definitions.
18
+ * @param {object} user - The current user.
19
+ * @returns {boolean} - True if the condition is met, false otherwise.
20
+ */
21
+ const evaluateSingleCondition = (currentModelDef, condition, formData, allModels, user, checkRegex =true) => {
22
+ // Condition est directement un filtre MongoDB, donc on l'applique
23
+ // en utilisant les opérateurs et les valeurs qu'il contient.
24
+
25
+ if (!condition || typeof condition !== 'object') {
26
+ console.warn("[Client Eval] Condition is not an object:", condition);
27
+ return true; // Permissive default
28
+ }
29
+
30
+ // Si la condition est de la forme {field: value}, on la transforme en {$eq: value}
31
+ if (!Object.keys(condition)[0].startsWith('$') && typeof condition[Object.keys(condition)[0]] !== 'object') {
32
+ const fieldName = Object.keys(condition)[0];
33
+ const value = condition[fieldName];
34
+ return evaluateSingleCondition(currentModelDef, {[fieldName]: {$eq: value}}, formData, allModels, user);
35
+ }
36
+
37
+ // Gestion des opérateurs d'agrégation (commencent par $)
38
+ const operator = Object.keys(condition)[0];
39
+ if ((operator === '$eq' || operator === '$ne') && Array.isArray(condition[operator])) {
40
+ // Cas spécial pour {$op: ['$field', value]}
41
+ const [fieldPath, expectedValue] = condition[operator];
42
+ if (typeof fieldPath === 'string' && fieldPath.startsWith('$')) {
43
+ const fieldName = fieldPath.substring(1); // Enlève le $ devant
44
+ const actualValue = formData[fieldName];
45
+ if (operator === '$eq') return actualValue == expectedValue;
46
+ if (operator === '$ne') return actualValue != expectedValue;
47
+ }
48
+ }
49
+
50
+ // Si la condition contient des opérateurs logiques, on les gère ici
51
+ if (condition.$and || condition.$or || condition.$not || condition.$nor) {
52
+ console.warn("[Client Eval] Condition logique détectée dans evaluateSingleCondition, ce n'est pas attendu. Devrait être géré par isConditionMet.");
53
+ return true; // Permissive default
54
+ }
55
+
56
+ if (condition.$find) {
57
+ const fieldName = Object.keys(condition)[0];
58
+ const fieldValue = formData[fieldName];
59
+ const findCondition = condition.$find;
60
+
61
+ if (!Array.isArray(fieldValue)) return false;
62
+
63
+ return fieldValue.some(item => {
64
+ // Gestion spéciale pour la syntaxe $eq: ["$$this.field", value]
65
+ if (findCondition.$eq && Array.isArray(findCondition.$eq)) {
66
+ const [fieldPath, value] = findCondition.$eq;
67
+ if (fieldPath.startsWith("$$this.")) {
68
+ const fieldToCheck = fieldPath.replace("$$this.", "");
69
+ return item[fieldToCheck] == value;
70
+ }
71
+ }
72
+
73
+ // Sinon, évaluation normale
74
+ const tempData = { ...item };
75
+ return evaluateSingleCondition(currentModelDef, findCondition, tempData, allModels, user);
76
+ });
77
+ }
78
+
79
+ // Si la condition contient un opérateur $exists, on le gère ici
80
+ if (condition.$exists !== undefined) {
81
+ const fieldName = Object.keys(condition)[0]; // Récupérer le nom du champ
82
+ const shouldExist = condition.$exists; // Récupérer la valeur de $exists (true ou false)
83
+ const exists = Object.prototype.hasOwnProperty.call(formData, fieldName) && formData[fieldName] !== undefined && formData[fieldName] !== null;
84
+ return exists === shouldExist;
85
+ }
86
+
87
+ // Si la condition contient un opérateur $find, on le gère ici
88
+ if (condition.$find) {
89
+ // Récupérer le nom du champ
90
+ const fieldName = Object.keys(condition)[0];
91
+ const fieldValue = formData[fieldName];
92
+ try {
93
+ // Assuming evaluateSingleCondition handles $find
94
+ return evaluateSingleCondition(currentModelDef, condition.$find, formData, allModels, user);
95
+ } catch (error) {
96
+ console.error("Error evaluating $find condition:", condition, error);
97
+ return false;
98
+ }
99
+ }
100
+
101
+ // Récupérer le nom du champ et la condition
102
+ const fieldName = Object.keys(condition)[0];
103
+ const fieldValue = condition[fieldName];
104
+
105
+ // Récupérer la définition du champ
106
+ const fieldDef = currentModelDef?.fields.find(f => f.name === fieldName);
107
+
108
+ // Si la définition du champ n'est pas trouvée, on retourne true
109
+ if (!fieldDef) {
110
+ console.warn(`[Client Eval] Field definition not found for field: ${fieldName}`);
111
+ return true; // Permissive default
112
+ }
113
+
114
+ let targetValue = formData[fieldName];
115
+ let processedConditionValue = fieldValue;
116
+
117
+ // 1. Handle $exists (on the first field)
118
+ // 2. Convert condition value based on operator's expected input type
119
+ const fieldType = fieldDef?.type; // Type of the first field
120
+
121
+ try {
122
+ processedConditionValue = convertValueType(fieldValue, fieldType);
123
+ } catch (e) {
124
+ logClientEvalWarning(`Error converting value type: ${e.message}`, condition);
125
+ return false;
126
+ }
127
+
128
+ return evaluateComparison(fieldValue, targetValue, processedConditionValue, condition);
129
+
130
+ function logClientEvalWarning(message, details) {
131
+ console.warn(`[Client Eval] ${message}:`, details);
132
+ }
133
+
134
+ function convertValueType(value, inputType) {
135
+ switch (inputType) {
136
+ case 'number':
137
+ const numValue = parseFloat(value);
138
+ if (isNaN(numValue)) {
139
+ throw new Error(`Invalid number value: ${value}`);
140
+ }
141
+ return numValue;
142
+ case 'boolean':
143
+ return String(value).toLowerCase() === 'true';
144
+ case 'csv':
145
+ return String(value).split(',').map(item => item.trim()).filter(Boolean);
146
+ case 'text':
147
+ default:
148
+ return String(value);
149
+ }
150
+ }
151
+
152
+ function evaluateComparison(operator, targetValue, processedConditionValue, condition) {
153
+ try {
154
+ switch (typeof operator === 'object' ? Object.keys(operator)[0] : null) {
155
+ case '$eq': return targetValue === processedConditionValue;
156
+ case '$ne': return targetValue !== processedConditionValue;
157
+ case '$gt': return targetValue > processedConditionValue;
158
+ case '$lt': return targetValue < processedConditionValue;
159
+ case '$gte': return targetValue >= processedConditionValue;
160
+ case '$lte': return targetValue <= processedConditionValue;
161
+ case '$regex':
162
+ if (typeof targetValue !== 'string') return false;
163
+ if (typeof processedConditionValue !== 'string') return false;
164
+ try {
165
+ // On vérifie si la fonction a été injectée ET si la regex est sûre.
166
+ // Côté client, `safeRegex` sera null, donc la vérification est simplement ignorée.
167
+ if( checkRegex && safeRegex && safeRegex(processedConditionValue)) {
168
+ const regex = new RegExp(processedConditionValue, 'i');
169
+ return regex.test(targetValue);
170
+ }
171
+ return false;
172
+ } catch (e) {
173
+ logClientEvalWarning(`Invalid regex pattern: ${processedConditionValue}`, condition);
174
+ return false;
175
+ }
176
+ case '$in':
177
+ return Array.isArray(processedConditionValue) && processedConditionValue.includes(String(targetValue));
178
+ case '$nin':
179
+ return !Array.isArray(processedConditionValue) || !processedConditionValue.includes(String(targetValue));
180
+ default:
181
+ logClientEvalWarning(`Unhandled operator in client evaluation logic: ${operator}`, condition);
182
+ return true; // Permissive default
183
+ }
184
+ } catch (evalError) {
185
+ logClientEvalWarning(`Error during client condition evaluation: ${operator}, targetValue=${targetValue}, processedConditionValue=${processedConditionValue}`, condition);
186
+ return false;
187
+ }
188
+ }
189
+ };
190
+
191
+ export const isConditionMet = (model, cond, formData, allModels, user,checkRegex=true) => {
192
+ const condition = cond;
193
+
194
+ if (!condition) return true;
195
+
196
+ if (typeof condition !== 'object' || condition === null) {
197
+ return true;
198
+ }
199
+
200
+ // Cas spécial: Évaluation sans modèle (ex: pour les webhooks où la condition est déjà résolue)
201
+ // Dans ce mode, la condition doit être un objet avec un seul opérateur.
202
+ if (!model) {
203
+ const keys = Object.keys(condition);
204
+ if (keys.length !== 1 || !keys[0].startsWith('$')) {
205
+ console.warn('[isConditionMet] Condition invalide pour une évaluation sans modèle. Attendu : { "$opérateur": [...] }. Reçu :', condition);
206
+ return false; // Plus sûr que true pour éviter les faux positifs
207
+ }
208
+
209
+ const operator = keys[0];
210
+ const operands = condition[operator];
211
+
212
+ switch (operator) {
213
+ // Opérateurs logiques (récursifs)
214
+ case '$and':
215
+ return Array.isArray(operands) && operands.every(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
216
+ case '$or':
217
+ return Array.isArray(operands) && operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
218
+ case '$not':
219
+ return !isConditionMet(null, operands, formData, allModels, user);
220
+ case '$nor':
221
+ return Array.isArray(operands) && !operands.some(sub => isConditionMet(null, sub, formData, allModels, user,checkRegex));
222
+
223
+ // Opérateurs de comparaison (terminaux)
224
+ case '$eq':
225
+ return Array.isArray(operands) && operands[0] === operands[1];
226
+ case '$ne':
227
+ return Array.isArray(operands) && operands[0] !== operands[1];
228
+ case '$in':
229
+ return Array.isArray(operands) && Array.isArray(operands[1]) && operands[1].includes(operands[0]);
230
+ case '$nin':
231
+ return Array.isArray(operands) && Array.isArray(operands[1]) && !operands[1].includes(operands[0]);
232
+ case '$gt':
233
+ return Array.isArray(operands) && operands[0] > operands[1];
234
+ case '$gte':
235
+ return Array.isArray(operands) && operands[0] >= operands[1];
236
+ case '$lt':
237
+ return Array.isArray(operands) && operands[0] < operands[1];
238
+ case '$lte':
239
+ return Array.isArray(operands) && operands[0] <= operands[1];
240
+
241
+ default:
242
+ console.warn(`[isConditionMet] Opérateur non supporté '${operator}' pour une évaluation sans modèle.`);
243
+ return false;
244
+ }
245
+ }
246
+
247
+ // --- Logique existante pour l'évaluation AVEC modèle ---
248
+
249
+ if (condition.$and && Array.isArray(condition.$and)) {
250
+ if (condition.$and.length === 0) return true;
251
+ return condition.$and.every(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
252
+ }
253
+ if (condition.$or && Array.isArray(condition.$or)) {
254
+ if (condition.$or.length === 0) return false;
255
+ return condition.$or.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
256
+ }
257
+ if (condition.$not) {
258
+ return !isConditionMet(model, condition.$not, formData, allModels, user,checkRegex);
259
+ }
260
+ if (condition.$nor && Array.isArray(condition.$nor)) {
261
+ if (condition.$nor.length === 0) return true;
262
+ return !condition.$nor.some(sub => isConditionMet(model, sub, formData, allModels, user,checkRegex));
263
+ }
264
+
265
+ // Cas 3: Syntaxe d'agrégation {$eq: ['$field', value]}
266
+ if (Object.keys(condition).length === 1) {
267
+ const operator = Object.keys(condition)[0];
268
+ if (operator.startsWith('$') && operator !== '$find' &&
269
+ Array.isArray(condition[operator])) {
270
+ return evaluateSingleCondition(model, condition, formData, allModels, user,checkRegex);
271
+ }
272
+ }
273
+
274
+ return evaluateSingleCondition(model, condition, formData, allModels, user, checkRegex);
261
275
  };