data-primals-engine 1.2.6 → 1.3.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +440 -0
  2. package/README.md +782 -712
  3. package/client/src/App.jsx +13 -20
  4. package/client/src/App.scss +4 -0
  5. package/client/src/AssistantChat.jsx +5 -4
  6. package/client/src/DataEditor.jsx +1 -1
  7. package/client/src/DataLayout.jsx +2 -2
  8. package/client/src/DataTable.jsx +66 -5
  9. package/client/src/ExportDialog.jsx +2 -2
  10. package/client/src/Field.jsx +5 -4
  11. package/client/src/HistoryDialog.jsx +96 -0
  12. package/client/src/HistoryDialog.scss +73 -0
  13. package/client/src/KanbanCard.jsx +4 -2
  14. package/client/src/KanbanConfigModal.jsx +5 -7
  15. package/client/src/ModelCreator.jsx +36 -15
  16. package/client/src/ModelCreatorField.jsx +14 -15
  17. package/client/src/PackGallery.jsx +89 -9
  18. package/client/src/PackGallery.scss +58 -4
  19. package/client/src/RTETrans.jsx +11 -0
  20. package/client/src/RelationValue.jsx +3 -4
  21. package/client/src/constants.js +1 -1
  22. package/client/src/core/data.js +2 -1
  23. package/client/src/hooks/useTutorials.jsx +1 -1
  24. package/client/src/translations.js +217 -0
  25. package/package.json +9 -2
  26. package/server.js +4 -4
  27. package/src/HistoryDialog.jsx +86 -0
  28. package/src/HistoryDialog.scss +77 -0
  29. package/src/constants.js +6 -0
  30. package/src/defaultModels.js +23 -10
  31. package/src/email.js +1 -1
  32. package/src/engine.js +6 -6
  33. package/src/events.js +15 -5
  34. package/src/gameObject.js +0 -29
  35. package/src/i18n.js +1 -1
  36. package/src/modules/{assistant.js → assistant/assistant.js} +42 -27
  37. package/src/modules/assistant/constants.js +16 -0
  38. package/src/modules/data/data.history.js +304 -0
  39. package/src/modules/data/data.js +306 -238
  40. package/src/modules/data/data.routes.js +33 -7
  41. package/src/modules/mongodb.js +17 -1
  42. package/src/modules/user.js +21 -4
  43. package/src/modules/workflow.js +133 -48
  44. package/src/packs.js +1016 -9
  45. package/src/services/index.js +11 -0
  46. package/src/services/stripe.js +195 -0
  47. package/src/workers/crypto-worker.js +3 -3
  48. package/test/data.backup.integration.test.js +5 -0
  49. package/test/data.history.integration.test.js +193 -0
  50. package/test/data.integration.test.js +144 -41
  51. package/test/events.test.js +27 -27
  52. package/test/globalTeardown.js +1 -0
  53. package/test/model.integration.test.js +5 -0
  54. package/test/workflow.actions.integration.test.js +4 -2
  55. package/test/workflow.integration.test.js +3 -1
  56. package/test/workflow.robustness.test.js +2 -0
@@ -0,0 +1,11 @@
1
+ import * as stripeService from './stripe.js';
2
+ // Importez d'autres services ici à l'avenir
3
+ // import * as anotherService from './anotherService.js';
4
+
5
+ /**
6
+ * Registre central de tous les services exposés au moteur de workflow.
7
+ */
8
+ export const services = {
9
+ stripe: stripeService,
10
+ // anotherService: anotherService,
11
+ };
@@ -0,0 +1,195 @@
1
+ import Stripe from 'stripe';
2
+ import {editData, insertData, searchData} from '../modules/data/index.js';
3
+ import {getEnv} from "../modules/user.js";
4
+
5
+ const stripeInstances = {};
6
+
7
+ /**
8
+ * Retrieves a cached or creates a new Stripe client instance for a given user.
9
+ * This function centralizes API key retrieval and client initialization.
10
+ * @param {object} user - The user object.
11
+ * @returns {Promise<{client: Stripe, webhookSecret: string}|null>} The Stripe client and webhook secret, or null if not configured.
12
+ */
13
+ async function getStripeClient(user) {
14
+ const userId = user._id.toString();
15
+ if (!stripeInstances[userId]) {
16
+ const env = await getEnv(user);
17
+ if (env.STRIPE_SECRET_KEY) {
18
+ stripeInstances[userId] = {
19
+ client: new Stripe(env.STRIPE_SECRET_KEY),
20
+ webhookSecret: env.STRIPE_WEBHOOK_SECRET
21
+ };
22
+ }
23
+ }
24
+ return stripeInstances[userId] || null;
25
+ }
26
+
27
+ /**
28
+ * Crée ou récupère un client Stripe pour un utilisateur de notre système.
29
+ */
30
+ async function getOrCreateCustomer(user, db) {
31
+ const stripeInfo = await getStripeClient(user);
32
+ if (!stripeInfo?.client) {
33
+ throw new Error("Stripe is not configured for this user.");
34
+ }
35
+ const { client: stripe } = stripeInfo;
36
+
37
+ // Vérifier que l'utilisateur et son email de contact sont valides
38
+ if (!user || !user.contact || !user.contact.email) {
39
+ // Dans un vrai scénario, il faudrait peut-être chercher l'email directement sur le modèle user
40
+ const userRecord = await db.findOne('user', {_id: user._id});
41
+ if(!userRecord || !userRecord.contact || !userRecord.contact.email) {
42
+ throw new Error("User or user contact email is missing.");
43
+ }
44
+ user = userRecord;
45
+ }
46
+
47
+ const existingCustomer = await db.findOne('StripeCustomer', { user: user._id });
48
+
49
+ if (existingCustomer) {
50
+ return existingCustomer;
51
+ }
52
+
53
+ // Créer le client sur Stripe
54
+ const stripeCustomer = await stripe.customers.create({
55
+ email: user.contact.email,
56
+ name: user.username,
57
+ metadata: {
58
+ userId: user._id.toString() // Lien vers notre système
59
+ }
60
+ });
61
+
62
+ // Enregistrer le client dans notre BDD
63
+ const newCustomerData = {
64
+ user: user._id,
65
+ stripeCustomerId: stripeCustomer.id,
66
+ email: user.contact.email // Utiliser l'email de contact pour la cohérence
67
+ };
68
+ const { insertedIds } = await insertData('StripeCustomer', newCustomerData, {}, user);
69
+
70
+ // Pas besoin de refaire une recherche, on a déjà toutes les infos.
71
+ return { _id: insertedIds[0], ...newCustomerData };
72
+ }
73
+ /**
74
+ * Crée une session de checkout Stripe.
75
+ */
76
+ export async function createCheckoutSession(priceId, user, db, mode = 'subscription') {
77
+ const stripeInfo = await getStripeClient(user);
78
+ if (!stripeInfo?.client) {
79
+ throw new Error("Stripe is not configured for this user.");
80
+ }
81
+ const { client: stripe } = stripeInfo;
82
+
83
+ const env = await getEnv(user);
84
+ const appBaseUrl = env.APP_BASE_URL || 'https://your-domain.com'; // Fallback
85
+
86
+ const customer = await getOrCreateCustomer(user, db);
87
+ const session = await stripe.checkout.sessions.create({
88
+ payment_method_types: ['card'],
89
+ mode: mode, // 'subscription' or 'payment'
90
+ customer: customer.stripeCustomerId,
91
+ line_items: [{ price: priceId, quantity: 1 }],
92
+ success_url: `${appBaseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
93
+ cancel_url: `${appBaseUrl}/cancel`
94
+ });
95
+ return session;
96
+ }
97
+
98
+ /**
99
+ * Vérifie le statut d'une session de checkout.
100
+ */
101
+ export async function verifyCheckoutSession(sessionId, user) {
102
+ const stripeInfo = await getStripeClient(user);
103
+ if (!stripeInfo?.client) {
104
+ throw new Error("Stripe is not configured for this user.");
105
+ }
106
+ const { client: stripe } = stripeInfo;
107
+ try {
108
+ const session = await stripe.checkout.sessions.retrieve(sessionId);
109
+ return {
110
+ status: session.status,
111
+ payment_status: session.payment_status,
112
+ customer: session.customer,
113
+ subscription: session.subscription
114
+ };
115
+ } catch (error) {
116
+ console.error("Error verifying checkout session:", error);
117
+ throw new Error("Could not verify checkout session.");
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Vérifie la signature d'un webhook Stripe pour s'assurer qu'il est authentique.
123
+ * C'est une étape de sécurité cruciale.
124
+ *
125
+ * @param {object} headers - Les en-têtes de la requête (notamment 'stripe-signature').
126
+ * @param {string} rawBody - Le corps brut de la requête.
127
+ * @returns {Stripe.Event} L'objet événement Stripe vérifié.
128
+ * @throws {Error} Si la signature est invalide ou si les en-têtes/body sont manquants.
129
+ */
130
+ export async function verifyWebhookSignature(headers, rawBody, user) {
131
+ const stripeInfo = await getStripeClient(user);
132
+
133
+ if (!stripeInfo) {
134
+ throw new Error("Stripe is not configured for this user.");
135
+ }
136
+ const { client: stripe, webhookSecret } = stripeInfo;
137
+ if (!stripe) {
138
+ throw new Error("Stripe unknown API key.");
139
+ }
140
+ if (!webhookSecret) {
141
+ throw new Error("Stripe webhook secret (STRIPE_WEBHOOK_SECRET) is not configured on the server.");
142
+ }
143
+
144
+ const signature = headers['stripe-signature'];
145
+ if (!signature) {
146
+ throw new Error("Missing 'stripe-signature' header.");
147
+ }
148
+
149
+ try {
150
+ return stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
151
+ } catch (err) {
152
+ console.error(`❌ Error verifying Stripe webhook signature: ${err.message}`);
153
+ throw new Error(`Webhook signature verification failed: ${err.message}`);
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Crée un remboursement pour une commande spécifique.
159
+ */
160
+ export async function createRefund(returnId, db, user) {
161
+ const stripeInfo = await getStripeClient(user);
162
+ if (!stripeInfo?.client) {
163
+ throw new Error("Stripe is not configured for this user.");
164
+ }
165
+ const { client: stripe } = stripeInfo;
166
+
167
+ const returnRequest = await db.findOne('return', { _id: returnId });
168
+ if (!returnRequest) {
169
+ throw new Error("Return request not found.");
170
+ }
171
+
172
+ // Trouver la commande et le paiement associés
173
+ const order = await db.findOne('order', { _id: returnRequest.order });
174
+ if (!order || !order.paymentIntentId) {
175
+ throw new Error("Associated order or its paymentIntentId not found.");
176
+ }
177
+
178
+ const refund = await stripe.refunds.create({
179
+ payment_intent: order.paymentIntentId,
180
+ amount: Math.round(returnRequest.amount * 100), // Stripe attend le montant en centimes
181
+ reason: 'requested_by_customer',
182
+ metadata: {
183
+ returnId: returnId.toString(),
184
+ orderId: order.orderId
185
+ }
186
+ });
187
+
188
+ // Mettre à jour le statut de la demande de retour dans notre BDD
189
+ await editData('return', { _id: returnId }, {
190
+ status: 'refunded',
191
+ refundDate: new Date()
192
+ }, {}, user);
193
+
194
+ return { refundId: refund.id, status: refund.status };
195
+ }
@@ -46,20 +46,20 @@ parentPort.on('message', async ({ action, payload }) => {
46
46
  let result;
47
47
  switch (action) {
48
48
  case 'encrypt':
49
- console.log(`[Worker] Received action: ${action} for file: ${payload.filePath}`);
49
+ //console.log(`[Worker] Received action: ${action} for file: ${payload.filePath}`);
50
50
  await encryptFile(payload.filePath, payload.password);
51
51
  parentPort.postMessage({ success: true }); // Pas de données à retourner
52
52
  break;
53
53
 
54
54
  case 'decrypt':
55
- console.log(`[Worker] Received action: ${action} for file: ${payload.filePath}`);
55
+ //console.log(`[Worker] Received action: ${action} for file: ${payload.filePath}`);
56
56
  await decryptFile(payload.filePath, payload.password);
57
57
  parentPort.postMessage({ success: true }); // Pas de données à retourner
58
58
  break;
59
59
 
60
60
 
61
61
  case 'hash':
62
- console.log(`[Worker] Received action: hash`);
62
+ //console.log(`[Worker] Received action: hash`);
63
63
  if (!payload.data) throw new Error('Data to hash is missing in payload.');
64
64
  // Le worker gère à la fois la génération du "salt" et le hachage
65
65
  const salt = await bcrypt.genSalt(10);
@@ -21,6 +21,7 @@ import process from "node:process";
21
21
  import { dumpUserData, loadFromDump } from '../src/index.js';
22
22
  import fs from "node:fs";
23
23
  import {initEngine} from "../src/setenv.js";
24
+ import {purgeData} from "../src/modules/data/data.history.js";
24
25
 
25
26
  vi.mock('../src/engine', async(importOriginal) => {
26
27
  const mod = await importOriginal() // type is inferred
@@ -78,6 +79,8 @@ beforeAll(async () => {
78
79
 
79
80
  afterAll(async () => {
80
81
 
82
+ await purgeData(mockUser, testModelDefinition.name);
83
+
81
84
  delete process.env.DB_URL;
82
85
  delete process.env.DB_NAME;
83
86
 
@@ -95,10 +98,12 @@ afterAll(async () => {
95
98
  beforeAll(async () =>{
96
99
  Config.Set("modules", ["mongodb", "data", "file", "bucket", "workflow","user", "assistant"]);
97
100
  await initEngine();
101
+
98
102
  })
99
103
  beforeEach(async () => {
100
104
  testModelsColInstance = getAppModelsCollection;
101
105
  testDatasColInstance = await getAppUserCollection(mockUser);
106
+
102
107
  });
103
108
 
104
109
  describe('Data Backup and Restore Integration', () => {
@@ -0,0 +1,193 @@
1
+ // __tests__/data.history.integration.test.js
2
+ import { ObjectId } from 'mongodb';
3
+ import { expect, describe, it, beforeAll, afterAll, beforeEach } from 'vitest';
4
+ import { Config } from '../src/config.js';
5
+ import { sleep } from '../src/core.js';
6
+ import { insertData, editData, deleteModels } from '../src/index.js';
7
+ import { getCollection, getCollectionForUser } from '../src/modules/mongodb.js';
8
+ import { generateUniqueName, initEngine } from "../src/setenv.js";
9
+ import {purgeData} from "../src/modules/data/data.history.js";
10
+ import {MongoDatabase} from "../src/engine.js";
11
+
12
+ let engine;
13
+ let testUser;
14
+ let historyCollection;
15
+ let datasCollection;
16
+ let modelsCollection;
17
+
18
+ describe('Data History Module Integration Tests', () => {
19
+
20
+ beforeAll(async () => {
21
+ // IMPORTANT: Add the history module to the engine configuration for tests
22
+ Config.Set("modules", ["mongodb", "data", "file", "bucket", "workflow", "user", "assistant"]);
23
+ engine = await initEngine();
24
+
25
+ // Setup a single user for all tests in this suite
26
+ testUser = {
27
+ username: generateUniqueName('testUserHistory'),
28
+ userPlan: 'free',
29
+ email: generateUniqueName('test') + '@example.com'
30
+ };
31
+
32
+ // Initialize collection instances
33
+ historyCollection = getCollection('history');
34
+ datasCollection = await getCollectionForUser(testUser);
35
+ modelsCollection = getCollection('models');
36
+ });
37
+
38
+ afterAll(async () =>{
39
+ await purgeData(testUser);
40
+ await datasCollection.drop();
41
+ })
42
+
43
+ // Clean up collections before each test to ensure isolation
44
+ beforeEach(async () => {
45
+ await historyCollection.deleteMany({ 'user.username': testUser.username });
46
+ await datasCollection.deleteMany({ _user: testUser.username });
47
+ await modelsCollection.deleteMany({ _user: testUser.username });
48
+ });
49
+
50
+ afterAll(async () => {
51
+ // Final cleanup
52
+ await historyCollection.deleteMany({ 'user.username': testUser.username });
53
+ await datasCollection.deleteMany({ _user: testUser.username });
54
+ await modelsCollection.deleteMany({ _user: testUser.username });
55
+ });
56
+
57
+ it('should create a full snapshot history record on document creation', async () => {
58
+ // 1. Define and create a model with history enabled
59
+ const modelName = generateUniqueName('productHistory');
60
+ const productModelDef = {
61
+ name: modelName,
62
+ description:"",
63
+ _user: testUser.username,
64
+ history: {
65
+ enabled: true,
66
+ // For creation, all fields are snapshotted regardless of this config
67
+ fields: {
68
+ price: true,
69
+ stock: true
70
+ }
71
+ },
72
+ fields: [
73
+ { name: 'name', type: 'string', required: true },
74
+ { name: 'price', type: 'number' },
75
+ { name: 'stock', type: 'number' },
76
+ { name: 'description', type: 'string' }
77
+ ]
78
+ };
79
+ await modelsCollection.insertOne(productModelDef);
80
+
81
+ // 2. Insert a new document
82
+ const initialData = {
83
+ name: 'Super Widget',
84
+ price: 99.99,
85
+ stock: 100,
86
+ description: 'A very super widget.'
87
+ };
88
+ const insertResult = await insertData(modelName, initialData, {}, testUser);
89
+ expect(insertResult.success).toBe(true);
90
+ const docId = new ObjectId(insertResult.insertedIds[0]);
91
+
92
+ // 3. Verify the history record
93
+ const historyRecord = await historyCollection.findOne({ documentId: new ObjectId(docId) });
94
+
95
+ expect(historyRecord).not.toBeNull();
96
+ expect(historyRecord.documentId.toString()).toBe(docId.toString());
97
+ expect(historyRecord.model).toBe(modelName);
98
+ expect(historyRecord.version).toBe(1);
99
+ expect(historyRecord.operation).toBe('create');
100
+ expect(historyRecord.user.username).toBe(testUser.username);
101
+
102
+ // 4. Verify the snapshot
103
+ expect(historyRecord.snapshot).not.toBeNull();
104
+ expect(historyRecord.snapshot.name).toBe('Super Widget');
105
+ expect(historyRecord.snapshot.price).toBe(99.99);
106
+ expect(historyRecord.snapshot.stock).toBe(100);
107
+ expect(historyRecord.snapshot.description).toBe('A very super widget.');
108
+ expect(historyRecord.changes).toBeUndefined(); // No 'changes' field on creation
109
+ });
110
+
111
+ it('should create a diff history record on document update for historized fields only', async () => {
112
+ // 1. Define and create a model with specific history fields
113
+ const modelName = generateUniqueName('productHistorySelective');
114
+ const productModelDef = {
115
+ name: modelName,
116
+ description:"",
117
+ _user: testUser.username,
118
+ history: {
119
+ enabled: true,
120
+ fields: {
121
+ price: true, // Track this
122
+ stock: true // Track this
123
+ // 'description' is NOT tracked
124
+ }
125
+ },
126
+ fields: [
127
+ { name: 'name', type: 'string', required: true },
128
+ { name: 'price', type: 'number' },
129
+ { name: 'stock', type: 'number' },
130
+ { name: 'description', type: 'string' }
131
+ ]
132
+ };
133
+ await modelsCollection.insertOne(productModelDef);
134
+
135
+ // 2. Insert the initial document
136
+ const initialData = { name: 'Selective Widget', price: 50, stock: 200, description: 'Initial description.' };
137
+ const insertResult = await insertData(modelName, initialData, {}, testUser);
138
+ const docId = new ObjectId(insertResult.insertedIds[0]);
139
+
140
+ // 3. Edit the document: change one historized field and one non-historized field
141
+ const updateData = { price: 55.5, description: 'Updated description.' };
142
+ const editResult = await editData(modelName, { _id: docId }, updateData, {}, testUser);
143
+ expect(editResult.success).toBe(true);
144
+
145
+ // 4. Verify the new history record (v2)
146
+ const historyRecord = await historyCollection.findOne({ documentId: docId, version: 2 });
147
+
148
+ expect(historyRecord).not.toBeNull();
149
+ expect(historyRecord.operation).toBe('update');
150
+ expect(historyRecord.snapshot).toBeUndefined(); // No 'snapshot' on update
151
+
152
+ // 5. Verify the 'changes' object
153
+ const changes = historyRecord.changes;
154
+ expect(changes).not.toBeNull();
155
+ expect(changes.price).toBeDefined();
156
+ expect(changes.price.from).toBe(50);
157
+ expect(changes.price.to).toBe(55.5);
158
+ expect(changes.description).toBeUndefined();
159
+ expect(changes.stock).toBeUndefined();
160
+ });
161
+
162
+ it('should NOT create a history record if only non-historized fields are updated', async () => {
163
+ // 1. Setup model
164
+ const modelName = generateUniqueName('productHistoryNoOp');
165
+ const productModelDef = {
166
+ name: modelName,
167
+ description:"",
168
+ _user: testUser.username,
169
+ history: { enabled: true, fields: { price: true } },
170
+ fields: [
171
+ { name: 'name', type: 'string', required: true },
172
+ { name: 'price', type: 'number' },
173
+ { name: 'description', type: 'string' }
174
+ ]
175
+ };
176
+ await modelsCollection.insertOne(productModelDef);
177
+
178
+ // 2. Insert initial document
179
+ const initialData = { name: 'No-Op Widget', price: 10, description: 'Initial.' };
180
+ const insertResult = await insertData(modelName, initialData, {}, testUser);
181
+ const docId = new ObjectId(insertResult.insertedIds[0]);
182
+
183
+ // 3. Edit ONLY a non-historized field
184
+ const updateData = { description: 'This change should not be recorded.' };
185
+ await editData(modelName, { _id: docId }, updateData, {}, testUser);
186
+
187
+ await sleep(2000);
188
+
189
+ // 4. Verify that NO new history record was created (only the 'create' record exists)
190
+ const historyCount = await historyCollection.countDocuments({ documentId: docId });
191
+ expect(historyCount).toBe(1);
192
+ });
193
+ });