data-primals-engine 1.2.0 → 1.2.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.
package/README.md CHANGED
@@ -9,6 +9,11 @@
9
9
 
10
10
  > Whether you're building a CRM, e-commerce site, CMS, or SaaS platform, **data-primals-engine** provides the strong foundations so you can focus on what makes your application unique.
11
11
 
12
+ <p align="center">
13
+ <a href="https://data.primals.net/prez1.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez1.jpg" width="35%"></a>
14
+ <a href="https://data.primals.net/prez6.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez6.jpg" width="35%"></a>
15
+ <a href="https://data.primals.net/api-docs" target="_blank"><img alt="Dark" src="https://data.primals.net/prez5.jpg" width="25%"></a>
16
+ </p>
12
17
  ---
13
18
 
14
19
  ## 🚀 Key Features
@@ -85,8 +90,8 @@ MONGO_DB_URL=mongodb://127.0.0.1:27017
85
90
  | SMTP_USER | Username for SMTP authentication. | user@example.com |
86
91
  | SMTP_PASS | Password for SMTP authentication. | password |
87
92
  | TLS | Encrypted connection (TLS) mode. Disabled by default | 0/1 false/true |
88
- | CERT | Path to cert file. | certs/ca.crt |
89
- | CA_CERT | Path to CA cert file. | certs/cert.pem |
93
+ | CA_CERT | Path to CA cert file. | certs/ca.crt |
94
+ | CERT | Path to cert file. | certs/cert.pem |
90
95
  | CERT_KEY | Path to the key file for your certificate. | certs/key.pem |
91
96
 
92
97
  ### Start the server
@@ -168,12 +173,11 @@ Activatable features:
168
173
  ### 🎫 Support Ticket System
169
174
  - Create ticket model with [open, pending, resolved] statuses
170
175
  - Configure notification workflows
171
- - Add custom endpoints for analytics
176
+ - Add custom endpoints or dashboards/kpi for analytics
172
177
 
173
178
  ### 🤖 AI Chatbot
174
179
  - Define your model
175
180
  - Set up workflow: "When new entry → generate AI content"
176
- - Connect to frontend chat interface
177
181
 
178
182
  ---
179
183
 
@@ -617,4 +621,4 @@ Distributed under the **MIT License**. See `LICENSE` file.
617
621
 
618
622
  ---
619
623
 
620
- ## [🔼](#) Back to Top
624
+ ## [🔼](https://github.com/anonympins/data-primals-engine?tab=readme-ov-file#data-primals-engine) Back to Top
@@ -1083,11 +1083,15 @@ h2.shadow {
1083
1083
  }
1084
1084
 
1085
1085
  .condition-details {
1086
- padding-left: 20px; // Indentation
1086
+ padding-left: 4px;
1087
+ margin-left:2px;
1088
+ @media only screen and (min-width: 480px) {
1089
+ padding-left: 20px; // Indentation
1090
+ margin-left: 10px;
1091
+ margin-top: 5px;
1092
+ margin-bottom: 10px;
1093
+ }
1087
1094
  border-left: 2px solid #eee; // Ligne visuelle
1088
- margin-left: 10px;
1089
- margin-top: 5px;
1090
- margin-bottom: 10px;
1091
1095
  gap: 5px; // Espacement entre les éléments de condition
1092
1096
  }
1093
1097
 
@@ -1290,9 +1294,10 @@ select[multiple]{
1290
1294
  }
1291
1295
 
1292
1296
  .datalayout {
1293
- padding: 0 16px;
1297
+ @media only screen and (min-width: 480px) {
1298
+ padding: 0 16px;
1299
+ }
1294
1300
  }
1295
-
1296
1301
  .main-menu {
1297
1302
  padding: 16px 0;
1298
1303
  @media only screen and (max-width: 479px) {
@@ -8,6 +8,30 @@ import {FaRepeat} from "react-icons/fa6";
8
8
  import {useAuthContext} from "./contexts/AuthContext.jsx";
9
9
 
10
10
 
11
+ // Déterminer si le champ doit être une date
12
+ const isDateArg = (operator, argIndex) => {
13
+ if (!operator) return false;
14
+
15
+ const opConfig = MONGO_CALC_OPERATORS[operator];
16
+ if (!opConfig) {
17
+ console.warn(`Opérateur non trouvé: ${operator}`);
18
+ return false;
19
+ }
20
+
21
+ // Cas spécial pour les opérateurs de date
22
+ if (operator === '$dateAdd' || operator === '$dateSubtract') {
23
+ return argIndex === 0; // Seul le premier argument est une date
24
+ }
25
+
26
+ // Pour les autres opérateurs marqués isDate (comme $hour, $second, etc.)
27
+ if (opConfig.isDate) {
28
+ return true; // Tous les arguments sont des dates pour ces opérateurs
29
+ }
30
+
31
+ return false;
32
+ };
33
+
34
+
11
35
  const OperatorSelector = ({ onSelect }) => {
12
36
  const [search, setSearch] = useState('');
13
37
 
@@ -117,10 +141,12 @@ const ExpressionField = ({ value, onChange, path = [], fieldNames, isRoot = fals
117
141
  setEditing(false);
118
142
  };
119
143
 
144
+ console.log(path);
145
+ console.log(isDateArg(path[path.length - 1]));
120
146
 
121
147
  const renderArgument = (arg, index, parentOperator, args) => {
122
148
  const isSimpleValue = typeof arg !== 'object' || arg === null || Array.isArray(arg);
123
-
149
+ const parentOpConfig = MONGO_CALC_OPERATORS[parentOperator];
124
150
  // Fonction pour mettre à jour cet argument spécifique
125
151
  const handleArgChange = (newArgValue) => {
126
152
  const updatedArgs = [...args];
@@ -148,8 +174,6 @@ const ExpressionField = ({ value, onChange, path = [], fieldNames, isRoot = fals
148
174
  onChange({ [parentOperator]: updatedArgs }, path);
149
175
  }
150
176
  };
151
- const parentOpConfig = MONGO_CALC_OPERATORS[parentOperator];
152
-
153
177
  return (
154
178
  <div key={`arg-${index}`} className="expression-arg">
155
179
  <div className="arg-content">
@@ -163,10 +187,11 @@ const ExpressionField = ({ value, onChange, path = [], fieldNames, isRoot = fals
163
187
  updatedArgs[index] = newValue;
164
188
  onChange({ [parentOperator]: updatedArgs }, path);
165
189
  }}
190
+ isDate={isDateArg(path[path.length - 1], 0)} // Utilis
166
191
  fieldNames={fieldNames}
167
192
  isInFindContext={isInFindContext}
168
193
  />
169
- {!parentOpConfig?.disableAdvancedValue && (<button
194
+ {!parentOpConfig?.disableAdvancedValue && !isDateArg(path[path.length -1]) && (<button
170
195
  type="button"
171
196
  className="switch-to-expr"
172
197
  onClick={() => handleArgChange({ $eq: [arg, ""] })}
@@ -281,6 +306,7 @@ const ExpressionField = ({ value, onChange, path = [], fieldNames, isRoot = fals
281
306
  onChange={handleFieldChange}
282
307
  fieldNames={fieldNames}
283
308
  isFieldName={true}
309
+ isDate={isDateArg(path[path.length - 1])}
284
310
  currentModelFields={currentModelFields} // Passer les champs complets
285
311
  onlyRelations={true}
286
312
  />
@@ -607,12 +633,13 @@ const ExpressionField = ({ value, onChange, path = [], fieldNames, isRoot = fals
607
633
  }}
608
634
  fieldNames={fieldNames}
609
635
  isInFindContext={isInFindContext}
636
+ isDate={isDateArg(path[path.length - 1])}
610
637
  currentModelFields={currentModelFields} // On propage le contexte
611
638
  />
612
639
 
613
640
  {/* --- MODIFICATION --- */}
614
641
  {/* On affiche le bouton de conversion uniquement si l'opérateur parent le permet */}
615
- {parentOpConfig?.disableAdvancedValue !== true && (
642
+ {parentOpConfig?.disableAdvancedValue !== true && !isDateArg(path[path.length - 1]) && (
616
643
  <button
617
644
  type="button"
618
645
  className="switch-to-expr"
@@ -637,11 +664,13 @@ const FieldInput = ({
637
664
  isFieldName = false,
638
665
  isInFindContext = false,
639
666
  currentModelFields = [],
640
- onlyRelations = false
667
+ onlyRelations = false,
668
+ isDate = false
641
669
  }) => {
642
670
  const [inputValue, setInputValue] = useState(value);
643
671
  const [suggestions, setSuggestions] = useState([]);
644
672
  const [showSuggestions, setShowSuggestions] = useState(false);
673
+ const [showDatePicker, setShowDatePicker] = useState(false);
645
674
 
646
675
  useEffect(() => {
647
676
  setInputValue(value);
@@ -685,6 +714,18 @@ const FieldInput = ({
685
714
  setShowSuggestions(false);
686
715
  };
687
716
 
717
+ // Si c'est un champ date, on affiche le datepicker
718
+ if (isDate) {
719
+ return (
720
+ <div className="date-input-container">
721
+ <input
722
+ type="datetime-local"
723
+ value={inputValue ? new Date(inputValue).toISOString().slice(0, 16) : ''}
724
+ onChange={(e) => handleDateChange(e.target.value)}
725
+ />
726
+ </div>
727
+ );
728
+ }
688
729
  return (
689
730
  <div className="field-input-container">
690
731
  <input
@@ -493,7 +493,7 @@ const CheckboxField = forwardRef(
493
493
  };
494
494
  return (
495
495
  <>
496
- <div className={cn({field: true, "field-checkbox": true})}>
496
+ <div className={cn({field: true, "field-checkbox": true,"field-bg": true})}>
497
497
  <div className="inline"><input
498
498
  aria-required={required}
499
499
  aria-readonly={readOnly}
@@ -526,7 +526,7 @@ const ModelCreator = forwardRef(({ initialPrompt = '', onModelGenerated, autoGen
526
526
  {/* Colonne de droite: Formulaire du modèle sélectionné */}
527
527
  <div className="model-form-container">
528
528
  {/* Le formulaire existant est placé ici */}
529
- <div className="flex">
529
+ <div className="flex field-bg">
530
530
  <label htmlFor="modelName"><Trans i18nKey={"modelcreator.name"}>Nom:</Trans></label>
531
531
  </div>
532
532
  <TextField
@@ -539,7 +539,7 @@ const ModelCreator = forwardRef(({ initialPrompt = '', onModelGenerated, autoGen
539
539
  required
540
540
  />
541
541
 
542
- <div className="flex">
542
+ <div className="flex field-bg">
543
543
  <label htmlFor="modelDescription"><Trans i18nKey={"modelcreator.description"}>Description:</Trans></label>
544
544
  </div>
545
545
  <TextField
@@ -570,7 +570,7 @@ const ModelCreator = forwardRef(({ initialPrompt = '', onModelGenerated, autoGen
570
570
  {/* Affichage du formulaire en mode manuel ou édition */}
571
571
  {(!useAI || initialModel) && (
572
572
  <div className="model-form-container">
573
- <div className="flex">
573
+ <div className="flex field-bg">
574
574
  <label htmlFor="modelName"><Trans i18nKey={"modelcreator.name"}>Nom:</Trans></label>
575
575
  </div>
576
576
  <TextField
@@ -583,7 +583,7 @@ const ModelCreator = forwardRef(({ initialPrompt = '', onModelGenerated, autoGen
583
583
  required
584
584
  />
585
585
 
586
- <div className="flex">
586
+ <div className="flex field-bg">
587
587
  <label htmlFor="modelDescription"><Trans i18nKey={"modelcreator.description"}>Description:</Trans></label>
588
588
  </div>
589
589
  <TextField
@@ -2,6 +2,7 @@
2
2
  flex: 1;
3
3
  max-width: 720px;
4
4
  form {
5
+ padding: 0;
5
6
  @media only screen and (min-width: 480px){
6
7
  padding: 16px;
7
8
  }
@@ -151,4 +152,13 @@
151
152
  }
152
153
  }
153
154
  }
155
+ }
156
+
157
+ .field-bg {
158
+ background: #fcfcfc;
159
+ background: linear-gradient(180deg, rgba(252, 252, 252, 1) 0%, rgba(242, 242, 242, 1) 55%, rgba(242, 242, 242, 1) 100%);
160
+ }
161
+
162
+ .mg-item{
163
+ margin: 10px 0;
154
164
  }
@@ -61,7 +61,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
61
61
  </div>
62
62
  <div className="flex flex-row flex-stretch">
63
63
 
64
- <div className="flex fieldName">{hint('modelcreator.name.hint')}
64
+ <div className="flex fieldName field-bg">{hint('modelcreator.name.hint')}
65
65
  <div className="flex flex-no-gap flex-no-wrap flex-1">
66
66
  <TextField
67
67
  label={t('modelcreator.fieldName')}
@@ -88,7 +88,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
88
88
 
89
89
  <div className="flex">
90
90
  {hint('modelcreator.type.hint')}
91
- <div className="flex flex-1 flex-stretch flex-no-gap">
91
+ <div className="flex flex-1 flex-stretch field-bg flex-no-gap">
92
92
 
93
93
  <SelectField
94
94
  label={t('modelcreator.type', 'Type de champ')}
@@ -453,16 +453,15 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
453
453
  </div>
454
454
 
455
455
  {!['file', 'relation', 'array', 'calculated'].includes(field.type) && (<div
456
- className="flex flex-no-wrap">
457
- {hint('modelcreator.default.hint')}
456
+ className="flex flex-no-wrap field-bg mg-item">
458
457
 
459
458
  {['string_t', 'string', 'richtext', 'password', 'url', 'phone', 'email'].includes(field.type) && (<>
460
- <label className="flex flex-1">
461
- <Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>
462
- <input
463
- type="text"
459
+ {hint('modelcreator.default.hint')}
460
+ <div className="flex flex-1">
461
+ <TextField
464
462
  className="flex-1"
465
463
  value={field.default}
464
+ label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
466
465
  disabled={modelLocked || (isLocalUser(me) && field.locked)}
467
466
  onChange={(e) => {
468
467
  const newFields = [...fields];
@@ -470,9 +469,10 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
470
469
  setFields(newFields);
471
470
  }}
472
471
  />
473
- </label>
472
+ </div>
474
473
  </>)}
475
474
  {['number'].includes(field.type) && (<>
475
+ {hint('modelcreator.default.hint')}
476
476
  <NumberField
477
477
  label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
478
478
  type="number"
@@ -491,6 +491,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
491
491
  />
492
492
  </>)}
493
493
  {['enum'].includes(field.type) && (<>
494
+ {hint('modelcreator.default.hint')}
494
495
  <SelectField
495
496
  label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
496
497
  value={field.default}
@@ -505,6 +506,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
505
506
  />
506
507
  </>)}
507
508
  {['code'].includes(field.type) && (<>
509
+ {hint('modelcreator.default.hint')}
508
510
  <CodeField
509
511
  label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
510
512
  value={field.language === 'json' ? JSON.stringify(field.default, 2, null) : field.default}
@@ -516,6 +518,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
516
518
  />
517
519
  </>)}
518
520
  {['boolean'].includes(field.type) && (<>
521
+ {hint('modelcreator.default.hint')}
519
522
  <div className="checkbox-label flex flex-1">
520
523
  <CheckboxField
521
524
  label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
@@ -530,6 +533,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
530
533
  </div>
531
534
  </>)}
532
535
  {['color'].includes(field.type) && (<>
536
+ {hint('modelcreator.default.hint')}
533
537
  <ColorField
534
538
  label={<Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>}
535
539
  value={field.default || null} name={field.name}
@@ -543,6 +547,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
543
547
  />
544
548
  </>)}
545
549
  {['date', 'datetime'].includes(field.type) && (<>
550
+ {hint('modelcreator.default.hint')}
546
551
  <label className="flex flex-1">
547
552
  <Trans i18nKey={"modelcreator.default"}>Valeur par défaut :</Trans>
548
553
  <input
@@ -562,7 +567,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
562
567
 
563
568
 
564
569
  {(['number', 'datetime', 'date'].includes(field.itemsType || field.type)) && (
565
- <><label className="flex">
570
+ <><label className="flex field-bg mg-item">
566
571
  {hint('modelcreator.min.hint')}
567
572
  <span><Trans
568
573
  i18nKey={"modelcreator.min"}>Valeur minimale :</Trans></span>
@@ -581,7 +586,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
581
586
  }}
582
587
  /></div>
583
588
  </label>
584
- <label className="flex">
589
+ <label className="flex field-bg mg-item">
585
590
  {hint('modelcreator.max.hint')}
586
591
  <span><Trans i18nKey={"modelcreator.max"}>Valeur maximale :</Trans></span>
587
592
  <div className="flex flex-1"><input
@@ -601,13 +606,12 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
601
606
  </label>
602
607
  </>
603
608
  )}
604
- <div className="flex flex-no-wrap">
609
+ <div className="flex flex-no-wrap mg-item">
605
610
  {hint('modelcreator.condition.hint')}
606
611
 
607
- <label className="checkbox-label flex flex-1"><Trans
608
- i18nKey={"modelcreator.condition"}>Condition</Trans> :
609
- <input
610
- type="checkbox"
612
+ <CheckboxField
613
+ label={<Trans
614
+ i18nKey={"modelcreator.condition"}>Condition</Trans>}
611
615
  disabled={modelLocked || (isLocalUser(me) && field.locked)}
612
616
  checked={field.condition !== undefined}
613
617
  onChange={(e) => {
@@ -620,7 +624,6 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
620
624
  setFields(newFields);
621
625
  }}
622
626
  />
623
- </label>
624
627
  </div>
625
628
  {field.condition !== undefined && (
626
629
  <div className={"condition-details flex flex-start"}>
@@ -691,10 +694,10 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
691
694
 
692
695
 
693
696
  {mainFieldsTypes.includes(field.itemsType || field.type) && (<div
694
- className="flex flex-no-wrap"
697
+ className="flex flex-no-wrap mg-item"
695
698
  title={t("modelcreator.field.asMain", "Une information principale sera affichée dans le titre de l'enregistrement")}>
696
699
  {hint('modelcreator.asMain.hint')}
697
- <label className="checkbox-label flex flex-1">
700
+ <div className="flex flex-1">
698
701
 
699
702
  <CheckboxField
700
703
  label={<Trans i18nKey={"modelcreator.asMain"}>Information principale :</Trans>}
@@ -707,7 +710,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
707
710
  }}
708
711
  help={field.asMain && t('modelcreator.asMain.hint')}
709
712
  />
710
- </label>
713
+ </div>
711
714
  </div>)}
712
715
 
713
716
  <div className="flex flex-row flex-stretch">
@@ -729,7 +732,7 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
729
732
  </div>
730
733
 
731
734
 
732
- <label className="flex">
735
+ <label className="flex mg-item ">
733
736
  {hint('modelcreator.color.hint')}
734
737
  <Trans i18nKey={"field.color"}>Color :</Trans>
735
738
  <ColorField
@@ -763,19 +766,16 @@ const ModelCreatorField = ({model, handleRenameField, handleRemoveField, handleU
763
766
 
764
767
  <div className={"flex flex-no-wrap"}>
765
768
  {hint('modelcreator.anonymized.hint')}
766
- <label className={"checkbox-label flex flex-1"}>
767
- <Trans i18nKey={"modelcreator.anonymized"}>Donnée anonymisée :</Trans>
768
- <input
769
- type="checkbox"
770
- disabled={modelLocked || (isLocalUser(me) && field.locked)}
771
- checked={field.anonymized}
772
- onChange={(e) => {
773
- const newFields = [...fields];
774
- newFields[index].anonymized = e.target.checked;
775
- setFields(newFields);
776
- }}
777
- />
778
- </label>
769
+ <CheckboxField
770
+ label={<Trans i18nKey={"modelcreator.anonymized"}>Donnée anonymisée :</Trans>}
771
+ disabled={modelLocked || (isLocalUser(me) && field.locked)}
772
+ checked={field.anonymized}
773
+ onChange={(e) => {
774
+ const newFields = [...fields];
775
+ newFields[index].anonymized = e.target.checked;
776
+ setFields(newFields);
777
+ }}
778
+ />
779
779
  </div>
780
780
 
781
781
 
@@ -28,6 +28,7 @@ import css from 'highlight.js/lib/languages/css'
28
28
  import js from 'highlight.js/lib/languages/javascript'
29
29
  import ts from 'highlight.js/lib/languages/typescript'
30
30
  import html from 'highlight.js/lib/languages/xml'
31
+ import {escapeHtml, escapeRegex} from "data-primals-engine/core";
31
32
  // create a lowlight instance
32
33
  const lowlight = createLowlight(all)
33
34
 
@@ -43,7 +44,7 @@ const code = (c) => {
43
44
  const doc = document.createElement('div');
44
45
  doc.innerHTML = c;
45
46
  doc.querySelectorAll('code').forEach(cc =>{
46
- cc.innerHTML = cc.textContent
47
+ cc.innerHTML = escapeHtml(cc.textContent)
47
48
  .replace(/\r\n|\n/g, "<br />")
48
49
  .replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
49
50
  })
@@ -53,6 +53,8 @@ export const MONGO_CALC_OPERATORS = {
53
53
  $ln: { label: 'ln', multi: false },
54
54
  $log10: { label: 'log', multi: false },
55
55
  $concat: { label: 'concat', multi: true },
56
+
57
+ // Date-specific
56
58
  $year: { label: 'year', multi: false, isDate: true },
57
59
  $month: { label: 'month', multi: false, isDate: true },
58
60
  $dayOfMonth: { label: 'dayOfMonth', multi: false, isDate: true },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "data-primals-engine",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "data-primals-engine is the package responsible from handling large amount of data in a practical and performant way. It can handle large amount of data in a practical and performant way. It can also get workflow models working (for automation), and fully supports internationalisation.",
5
5
  "main": "src/engine.js",
6
6
  "type": "module",
@@ -30,7 +30,8 @@
30
30
  "resolutions": {
31
31
  "tar-fs": "3.0.9",
32
32
  "on-headers": "1.1.0",
33
- "brace-expansion": "2.0.2"
33
+ "brace-expansion": "2.0.2",
34
+ "prismjs": "1.30.0"
34
35
  },
35
36
  "repository": {
36
37
  "type": "git",
package/src/core.js CHANGED
@@ -9,6 +9,12 @@ export function escapeRegex(string) {
9
9
  return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
10
10
  }
11
11
 
12
+ export function escapeHtml(string){
13
+ return string.replace(/(javascript|data|vbscript):/gi, '').replace(/[^\w-_. ]/gi, function (c) {
14
+ return `&#${c.charCodeAt(0)};`;
15
+ });
16
+ }
17
+
12
18
  export const isDate = dt => String(new Date(dt)) !== 'Invalid Date'
13
19
 
14
20
  export const safeAssignObject = (obj, key, value) => {
@@ -46,6 +46,39 @@ export const defaultModels = {
46
46
  { name: 'tokens', type: 'relation', multiple: true, relation: 'token' }
47
47
  ]
48
48
  },
49
+ userPermission: {
50
+ "name": "userPermission",
51
+ "description": "Gère les exceptions aux permissions des rôles pour un utilisateur (ajouts ou retraits, permanents ou temporaires).",
52
+ "fields": [
53
+ {
54
+ "name": "user",
55
+ "type": "relation",
56
+ "relation": "user",
57
+ "required": true,
58
+ "index": true
59
+ },
60
+ {
61
+ "name": "permission",
62
+ "type": "relation",
63
+ "relation": "permission",
64
+ "required": true,
65
+ "index": true
66
+ },
67
+ {
68
+ "name": "isGranted",
69
+ "type": "boolean",
70
+ "required": true,
71
+ "hint": "True pour accorder la permission, False pour la révoquer explicitement."
72
+ },
73
+ {
74
+ "name": "expiresAt",
75
+ "type": "datetime",
76
+ "required": false,
77
+ "index": true,
78
+ "hint": "Si défini, l'exception (l'octroi ou la révocation) est temporaire."
79
+ }
80
+ ]
81
+ },
49
82
  token: {
50
83
  name: 'token',
51
84
  "description": "",
@@ -88,73 +88,128 @@ export async function onInit(defaultEngine) {
88
88
  engine = defaultEngine;
89
89
  logger = engine.getComponent(Logger);
90
90
  }
91
+ /**
92
+ * Calcule et retourne l'ensemble des permissions actives pour un utilisateur.
93
+ * Cette fonction interne est la pierre angulaire de la nouvelle logique de permission.
94
+ * 1. Elle récupère toutes les permissions de base issues des rôles de l'utilisateur.
95
+ * 2. Elle applique ensuite les "exceptions" (ajouts ou retraits de permissions) qui sont valides (non expirées).
96
+ * @param {object} user - L'objet utilisateur pour lequel calculer les permissions.
97
+ * @returns {Promise<Set<string>>} Un Set contenant les noms de toutes les permissions actives.
98
+ * @private
99
+ */
100
+ export async function getUserActivePermissions(user) {
101
+ const datasCollection = await getCollectionForUser(user);
102
+ const now = new Date();
103
+ const activePermissions = new Set();
91
104
 
92
- export async function hasPermission(permissionNames, user) {
93
- if( !isLocalUser(user)){
94
- return user.roles?.some(f => permissionNames.includes(f));
95
- }
96
- try {
97
- // Si on a une string on le transforme en tableau.
98
- const permissionNamesArray = Array.isArray(permissionNames) ? permissionNames : [permissionNames];
99
- const collection = await getCollectionForUser(user);
105
+ // --- ÉTAPE 1: Récupérer les permissions de base des rôles ---
106
+ if (user.roles && user.roles.length > 0) {
107
+ const roleIds = user.roles.map(id => new ObjectId(id));
100
108
 
101
- const job = [
109
+ const rolePermissions = await datasCollection.aggregate([
110
+ { $match: { _id: { $in: roleIds }, _model: "role" } },
111
+ { $unwind: "$permissions" },
112
+ { $addFields: { "permissionId": { "$toObjectId": "$permissions" } } },
102
113
  {
103
114
  $lookup: {
104
- from: 'datas',
105
- let: { rolesIds: (user.roles ||[]).map(m => new ObjectId(m)) },
106
- pipeline: [
107
- {
108
- $match: {
109
- $expr: {
110
- $and: [
111
- { $in: ['$_id', '$$rolesIds'] }
112
- ]
113
- }
114
- }
115
- },
116
- {
117
- $lookup: {
118
- from: 'datas',
119
- let: { rolePermissions: {
120
- "$map": {
121
- "input": "$permissions",
122
- "in": { "$toObjectId": "$$this" }
123
- }
124
- } },
125
- pipeline: [
126
- {
127
- $match: {
128
- $expr: {
129
- $and: [
130
- { $in: ['$_id', '$$rolePermissions'] }
131
- ]
132
- }
133
- }
134
- },
135
- { $limit: 1 }
136
- ],
137
- as: 'permissions'
138
- }
139
- },
140
- { $unwind: { path: '$permissions', preserveNullAndEmptyArrays: true } }
141
- ],
142
- as: 'roles'
115
+ from: datasCollection.collectionName, // Utiliser la même collection
116
+ localField: "permissionId",
117
+ foreignField: "_id",
118
+ as: "permissionDoc"
143
119
  }
144
120
  },
145
- { $unwind: { path: '$roles', preserveNullAndEmptyArrays: true } },
146
- { $match: { 'roles.permissions.name': { $in: permissionNamesArray } } }, // Match if permissions.name in array
147
- { $limit: 1 },
148
- { $project: { _id: 0, hasPermission: { $cond: [{ $in: ['$roles.permissions.name', permissionNamesArray] }, true, false] } } } //check the value
149
- ];
150
- const result = await collection.aggregate(job).toArray();
151
- return result.length === 1 && result[0].hasPermission;
121
+ { $unwind: "$permissionDoc" },
122
+ { $group: { _id: "$permissionDoc.name" } }
123
+ ]).toArray();
124
+
125
+ rolePermissions.forEach(p => p._id && activePermissions.add(p._id));
126
+ }
127
+
128
+ // --- ÉTAPE 2: Appliquer les exceptions de permission ---
129
+ const exceptions = await datasCollection.aggregate([
130
+ {
131
+ $match: {
132
+ _model: "userPermission",
133
+ user: user._id, // Pas besoin de convertir en ObjectId si c'est déjà une string
134
+ $or: [
135
+ { expiresAt: { $exists: false } },
136
+ { expiresAt: { $gt: now } }
137
+ ]
138
+ }
139
+ },
140
+ {
141
+ $lookup: {
142
+ from: datasCollection.collectionName,
143
+ let: { permissionId: "$permission" },
144
+ pipeline: [
145
+ {
146
+ $match: {
147
+ $expr: {
148
+ $eq: [
149
+ "$_id",
150
+ { $toObjectId: "$$permissionId" } // Conversion ici
151
+ ]
152
+ }
153
+ }
154
+ },
155
+ { $project: { name: 1 } }
156
+ ],
157
+ as: 'permissionDoc'
158
+ }
159
+ },
160
+ { $unwind: '$permissionDoc' }
161
+ ]).toArray();
162
+
163
+ // Appliquer les exceptions
164
+ for (const exception of exceptions) {
165
+ const permissionName = exception.permissionDoc?.name;
166
+ if (!permissionName) continue;
167
+
168
+ if (exception.isGranted) {
169
+ activePermissions.add(permissionName);
170
+ } else {
171
+ activePermissions.delete(permissionName);
172
+ }
173
+ }
174
+
175
+ return activePermissions;
176
+ }
177
+
178
+ /**
179
+ * Vérifie si un utilisateur possède au moins une des permissions spécifiées.
180
+ * Cette fonction utilise la nouvelle logique basée sur les rôles et les exceptions de permission.
181
+ * @param {string|string[]} permissionNames - Le nom de la permission ou un tableau de noms.
182
+ * @param {object} user - L'objet utilisateur authentifié.
183
+ * @returns {Promise<boolean>} - True si l'utilisateur a la permission, sinon false.
184
+ */
185
+ export async function hasPermission(permissionNames, user) {
186
+ // Garde la compatibilité pour les utilisateurs non-locaux (ex: système)
187
+ if (!isLocalUser(user)) {
188
+ const userRoles = new Set(user.roles || []);
189
+ const requiredPermissions = Array.isArray(permissionNames) ? permissionNames : [permissionNames];
190
+ return requiredPermissions.some(p => userRoles.has(p));
191
+ }
192
+
193
+ try {
194
+ const requiredPermissions = Array.isArray(permissionNames) ? permissionNames : [permissionNames];
195
+ // Si aucune permission n'est requise, on autorise
196
+ if (requiredPermissions.length === 0) {
197
+ return true;
198
+ }
199
+
200
+ // 1. Obtenir l'ensemble final et à jour des permissions de l'utilisateur
201
+ const activePermissions = await getUserActivePermissions(user);
202
+
203
+ // 2. Vérifier si au moins une des permissions requises est dans l'ensemble des permissions actives
204
+ return requiredPermissions.some(pName => activePermissions.has(pName));
205
+
152
206
  } catch (e) {
153
- logger.error(e);
207
+ logger.error("Erreur lors de la vérification des permissions :", e);
154
208
  return false;
155
209
  }
156
210
  }
157
211
 
212
+
158
213
  /**
159
214
  * Calcule l'utilisation totale de l'espace de stockage pour un utilisateur en octets.
160
215
  * Cela inclut la taille des documents dans sa collection de données et la taille de ses fichiers uploadés.
@@ -0,0 +1,203 @@
1
+ import { expect, describe, it, beforeEach, beforeAll, afterAll } from 'vitest';
2
+ import { hasPermission, getUserActivePermissions } from '../src/modules/user.js';
3
+ import {initEngine} from "data-primals-engine/setenv";
4
+ import {generateUniqueName} from "../src/setenv.js";
5
+ import {
6
+ getCollectionForUser as getAppUserCollection,
7
+ modelsCollection as getAppModelsCollection
8
+ } from "data-primals-engine/modules/mongodb";
9
+ import {Config} from "../src/index.js";
10
+ let permRead, permWrite, permDelete, permManage;
11
+ let roleEditor;
12
+ let testUser, adminUser, roleViewer;
13
+ let currentTestUser;
14
+ let testModelsColInstance, testDatasColInstance;
15
+ // Cette fonction va remplacer la logique de votre beforeEach pour la création de contexte
16
+ async function setupTestContext() {
17
+
18
+
19
+ // Créer un utilisateur unique pour ce test
20
+ const username = generateUniqueName('testuserDataIntegration');
21
+ currentTestUser = {
22
+ username,
23
+ userPlan: 'free',
24
+ _model: 'user',
25
+ _user: username,
26
+ email: generateUniqueName('test') + '@example.com'
27
+ };
28
+
29
+ // Initialize collection instances after the engine is ready
30
+ testModelsColInstance = getAppModelsCollection;
31
+ testDatasColInstance = await getAppUserCollection(currentTestUser);
32
+
33
+ await testDatasColInstance.deleteMany({}); // Nettoyage de la base de test
34
+ // 1. Créer les permissions
35
+ const permissions = await testDatasColInstance.insertMany([
36
+ { _model: 'permission', name: 'post:read', description: 'Lire les articles' },
37
+ { _model: 'permission', name: 'post:write', description: 'Écrire des articles' },
38
+ { _model: 'permission', name: 'post:delete', description: 'Supprimer des articles' },
39
+ { _model: 'permission', name: 'user:manage', description: 'Gérer les utilisateurs' }
40
+ ]);
41
+ permRead = permissions.insertedIds[0];
42
+ permWrite = permissions.insertedIds[1];
43
+ permDelete = permissions.insertedIds[2];
44
+ permManage = permissions.insertedIds[3];
45
+
46
+ // 2. Créer les rôles
47
+ const roles = await testDatasColInstance.insertMany([
48
+ { _user: currentTestUser.username, _model: 'role', name: 'Viewer', permissions: [permRead.toString()] },
49
+ { _user: currentTestUser.username, _model: 'role', name: 'Editor', permissions: [permRead.toString(), permWrite.toString()] }
50
+ ]);
51
+ roleViewer = roles.insertedIds[0];
52
+ roleEditor = roles.insertedIds[1];
53
+
54
+ // 3. Créer les utilisateurs
55
+ const users = await testDatasColInstance.insertMany([
56
+ { _user: currentTestUser.username, _model: 'user', roles: [roleEditor.toString()] },
57
+ { _user: currentTestUser.username, _model: 'user', roles: [roleEditor.toString()] }
58
+ ]);
59
+ testUser = {...currentTestUser, _id: users.insertedIds[0].toString(), roles: [roleEditor.toString()] };
60
+ adminUser = {...currentTestUser, _id: users.insertedIds[1].toString(), roles: [roleEditor.toString()] };
61
+ };
62
+ let engine;
63
+ describe('User Permission Logic', () => {
64
+
65
+ // --- SETUP : Création des données de test avant tous les tests ---
66
+ beforeAll(async () => {
67
+ Config.Set("modules", ["mongodb", "data", "file", "bucket", "workflow","user", "assistant"]);
68
+ engine = await initEngine();
69
+
70
+ });
71
+
72
+ // --- Tests pour la fonction principale de calcul ---
73
+ describe('getUserActivePermissions()', () => {
74
+
75
+
76
+ beforeEach(async () =>{
77
+ await setupTestContext();
78
+ })
79
+ it('should return base permissions from the user\'s role', async () => {
80
+ const permissions = await getUserActivePermissions(testUser);
81
+ expect(permissions).to.be.an.instanceOf(Set);
82
+ expect(permissions.size).to.equal(2);
83
+ expect(permissions.has('post:read')).to.be.true;
84
+ expect(permissions.has('post:write')).to.be.true;
85
+ expect(permissions.has('post:delete')).to.be.false;
86
+ });
87
+
88
+ it('should grant a temporary permission via an exception', async () => {
89
+
90
+ // Ajoute une exception qui donne la permission de supprimer, expirant demain
91
+ const futureDate = new Date();
92
+ futureDate.setDate(futureDate.getDate() + 1);
93
+
94
+ await testDatasColInstance.insertOne({
95
+ _model: 'userPermission',
96
+ user: testUser._id,
97
+ permission: permDelete,
98
+ isGranted: true,
99
+ expiresAt: futureDate
100
+ });
101
+
102
+ const permissions = await getUserActivePermissions(testUser);
103
+ expect(permissions.size).to.equal(3);
104
+ expect(permissions.has('post:delete')).to.be.true;
105
+
106
+ // Nettoyage de l'exception pour ne pas affecter les autres tests
107
+ await testDatasColInstance.deleteOne({ _model: 'userPermission', user: testUser._id });
108
+ });
109
+
110
+ it('should NOT grant an expired temporary permission', async () => {
111
+ // Ajoute une exception qui a expiré hier
112
+ const pastDate = new Date();
113
+ pastDate.setDate(pastDate.getDate() - 1);
114
+
115
+ await testDatasColInstance.insertOne({
116
+ _model: 'userPermission',
117
+ user: testUser._id,
118
+ permission: permDelete,
119
+ isGranted: true,
120
+ expiresAt: pastDate
121
+ });
122
+
123
+ const permissions = await getUserActivePermissions(testUser);
124
+ expect(permissions.size).to.equal(2); // Revient la normale
125
+ expect(permissions.has('post:delete')).to.be.false;
126
+
127
+ await testDatasColInstance.deleteOne({ _model: 'userPermission', user: testUser._id });
128
+ });
129
+
130
+ it('should revoke a base permission via an exception', async () => {
131
+ // L'utilisateur est "Editor", mais on lui retire le droit d'écriture temporairement
132
+ const futureDate = new Date();
133
+ futureDate.setDate(futureDate.getDate() + 1);
134
+
135
+ await testDatasColInstance.insertOne({
136
+ _model: 'userPermission',
137
+ user: testUser._id,
138
+ permission: permWrite,
139
+ isGranted: false, // Révocation
140
+ expiresAt: futureDate
141
+ });
142
+
143
+ const permissions = await getUserActivePermissions(testUser);
144
+ expect(permissions.size).to.equal(1);
145
+ expect(permissions.has('post:read')).to.be.true;
146
+ expect(permissions.has('post:write')).to.be.false; // La permission a été retirée
147
+
148
+ await testDatasColInstance.deleteOne({ _model: 'userPermission', user: testUser._id });
149
+ });
150
+
151
+ it('should restore a revoked permission if the revocation has expired', async () => {
152
+ // La révocation a expiré, l'utilisateur devrait retrouver son droit d'écriture
153
+ const pastDate = new Date();
154
+ pastDate.setDate(pastDate.getDate() - 1);
155
+
156
+ await testDatasColInstance.insertOne({
157
+ _model: 'userPermission',
158
+ user: testUser._id,
159
+ permission: permWrite,
160
+ isGranted: false,
161
+ expiresAt: pastDate
162
+ });
163
+
164
+ const permissions = await getUserActivePermissions(testUser);
165
+ expect(permissions.size).to.equal(2);
166
+ expect(permissions.has('post:write')).to.be.true; // La permission est de retour
167
+
168
+ await testDatasColInstance.deleteOne({ _model: 'userPermission', user: testUser._id });
169
+ });
170
+ });
171
+
172
+ // --- Tests pour la fonction publique `hasPermission` ---
173
+ describe('hasPermission()', () => {
174
+ beforeEach(async () => {
175
+ await setupTestContext();
176
+ });
177
+ it('should return true for a permission the user has', async () => {
178
+
179
+
180
+ console.log(await testDatasColInstance.find({ _model: 'permission' }).toArray());
181
+ console.log(await testDatasColInstance.find({ _model: 'role' }).toArray());
182
+ console.log(await testDatasColInstance.find({ _model: 'user' }).toArray());
183
+ console.log(await testDatasColInstance.find({ _model: 'userPermission' }).toArray());
184
+ const result = await hasPermission('post:read', testUser);
185
+ expect(result).to.be.true;
186
+ });
187
+
188
+ it('should return false for a permission the user does not have', async () => {
189
+ const result = await hasPermission('user:manage', testUser);
190
+ expect(result).to.be.false;
191
+ });
192
+
193
+ it('should return true if user has at least one of the required permissions', async () => {
194
+ const result = await hasPermission(['user:manage', 'post:write'], testUser);
195
+ expect(result).to.be.true;
196
+ });
197
+
198
+ it('should return false if user has none of the required permissions', async () => {
199
+ const result = await hasPermission(['user:manage', 'post:delete'], testUser);
200
+ expect(result).to.be.false;
201
+ });
202
+ });
203
+ });