data-primals-engine 1.3.0 → 1.3.2
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/CHANGELOG.md +440 -0
- package/Dockerfile +19 -9
- package/DockerfileTest +19 -9
- package/README.md +58 -24
- package/client/package-lock.json +172 -1
- package/client/package.json +1 -0
- package/client/src/App.scss +4 -0
- package/client/src/CalendarConfigModal.jsx +60 -21
- package/client/src/CalendarView.jsx +107 -0
- package/client/src/CalendarView.scss +9 -0
- package/client/src/DataLayout.jsx +54 -27
- package/client/src/DataTable.jsx +19 -2
- package/client/src/Dialog.scss +4 -3
- package/client/src/Field.jsx +3 -2
- package/client/src/HistoryDialog.jsx +253 -0
- package/client/src/HistoryDialog.scss +320 -0
- package/client/src/ModelCreator.jsx +36 -15
- package/client/src/ModelCreatorField.jsx +5 -6
- package/client/src/ViewSwitcher.jsx +6 -6
- package/client/src/hooks/useTutorials.jsx +1 -1
- package/client/src/translations.js +298 -1
- package/package.json +2 -2
- package/src/email.js +1 -1
- package/src/engine.js +6 -6
- package/src/events.js +15 -5
- package/src/gameObject.js +0 -29
- package/src/modules/data/data.history.js +490 -0
- package/src/modules/data/data.js +139 -108
- package/src/modules/data/data.routes.js +4 -4
- package/src/modules/mongodb.js +17 -1
- package/src/modules/user.js +9 -3
- package/src/packs.js +2 -1
- package/src/services/stripe.js +67 -13
- package/src/workers/crypto-worker.js +3 -3
- package/test/data.backup.integration.test.js +5 -0
- package/test/data.history.integration.test.js +193 -0
- package/test/data.integration.test.js +79 -39
- package/test/events.test.js +27 -27
- package/test/globalTeardown.js +1 -0
- package/test/model.integration.test.js +5 -0
- package/test/workflow.actions.integration.test.js +2 -0
- package/test/workflow.integration.test.js +2 -0
- package/test/workflow.robustness.test.js +2 -0
package/src/services/stripe.js
CHANGED
|
@@ -2,11 +2,38 @@ import Stripe from 'stripe';
|
|
|
2
2
|
import {editData, insertData, searchData} from '../modules/data/index.js';
|
|
3
3
|
import {getEnv} from "../modules/user.js";
|
|
4
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
|
+
}
|
|
5
26
|
|
|
6
27
|
/**
|
|
7
28
|
* Crée ou récupère un client Stripe pour un utilisateur de notre système.
|
|
8
29
|
*/
|
|
9
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
|
+
|
|
10
37
|
// Vérifier que l'utilisateur et son email de contact sont valides
|
|
11
38
|
if (!user || !user.contact || !user.contact.email) {
|
|
12
39
|
// Dans un vrai scénario, il faudrait peut-être chercher l'email directement sur le modèle user
|
|
@@ -33,30 +60,50 @@ async function getOrCreateCustomer(user, db) {
|
|
|
33
60
|
});
|
|
34
61
|
|
|
35
62
|
// Enregistrer le client dans notre BDD
|
|
36
|
-
const
|
|
63
|
+
const newCustomerData = {
|
|
37
64
|
user: user._id,
|
|
38
65
|
stripeCustomerId: stripeCustomer.id,
|
|
39
|
-
email: user.email
|
|
40
|
-
}
|
|
66
|
+
email: user.contact.email // Utiliser l'email de contact pour la cohérence
|
|
67
|
+
};
|
|
68
|
+
const { insertedIds } = await insertData('StripeCustomer', newCustomerData, {}, user);
|
|
41
69
|
|
|
42
|
-
|
|
43
|
-
return
|
|
70
|
+
// Pas besoin de refaire une recherche, on a déjà toutes les infos.
|
|
71
|
+
return { _id: insertedIds[0], ...newCustomerData };
|
|
44
72
|
}
|
|
45
73
|
/**
|
|
46
74
|
* Crée une session de checkout Stripe.
|
|
47
75
|
*/
|
|
48
|
-
export async function createCheckoutSession(priceId, user, db) {
|
|
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
|
+
|
|
49
86
|
const customer = await getOrCreateCustomer(user, db);
|
|
50
87
|
const session = await stripe.checkout.sessions.create({
|
|
51
88
|
payment_method_types: ['card'],
|
|
52
|
-
mode: 'subscription'
|
|
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`
|
|
53
94
|
});
|
|
95
|
+
return session;
|
|
54
96
|
}
|
|
55
97
|
|
|
56
98
|
/**
|
|
57
99
|
* Vérifie le statut d'une session de checkout.
|
|
58
100
|
*/
|
|
59
|
-
export async function verifyCheckoutSession(sessionId) {
|
|
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;
|
|
60
107
|
try {
|
|
61
108
|
const session = await stripe.checkout.sessions.retrieve(sessionId);
|
|
62
109
|
return {
|
|
@@ -81,12 +128,13 @@ export async function verifyCheckoutSession(sessionId) {
|
|
|
81
128
|
* @throws {Error} Si la signature est invalide ou si les en-têtes/body sont manquants.
|
|
82
129
|
*/
|
|
83
130
|
export async function verifyWebhookSignature(headers, rawBody, user) {
|
|
84
|
-
|
|
85
|
-
const env = await getEnv(user);
|
|
86
|
-
const stripe = env.STRIPE_SECRET_KEY ? new Stripe(env.STRIPE_SECRET_KEY) : null;
|
|
87
|
-
const webhookSecret = env.STRIPE_WEBHOOK_SECRET;
|
|
131
|
+
const stripeInfo = await getStripeClient(user);
|
|
88
132
|
|
|
89
|
-
if(
|
|
133
|
+
if (!stripeInfo) {
|
|
134
|
+
throw new Error("Stripe is not configured for this user.");
|
|
135
|
+
}
|
|
136
|
+
const { client: stripe, webhookSecret } = stripeInfo;
|
|
137
|
+
if (!stripe) {
|
|
90
138
|
throw new Error("Stripe unknown API key.");
|
|
91
139
|
}
|
|
92
140
|
if (!webhookSecret) {
|
|
@@ -110,6 +158,12 @@ export async function verifyWebhookSignature(headers, rawBody, user) {
|
|
|
110
158
|
* Crée un remboursement pour une commande spécifique.
|
|
111
159
|
*/
|
|
112
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
|
+
|
|
113
167
|
const returnRequest = await db.findOne('return', { _id: returnId });
|
|
114
168
|
if (!returnRequest) {
|
|
115
169
|
throw new Error("Return request not found.");
|
|
@@ -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
|
+
});
|