data-primals-engine 1.5.1 → 1.6.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 (70) hide show
  1. package/README.md +924 -913
  2. package/client/README.md +136 -136
  3. package/client/index.js +0 -1
  4. package/client/public/doc/API.postman_collection.json +213 -213
  5. package/client/public/react.svg +9 -9
  6. package/client/src/AddWidgetTypeModal.jsx +47 -47
  7. package/client/src/App.css +42 -42
  8. package/client/src/App.jsx +92 -150
  9. package/client/src/App.scss +7 -1
  10. package/client/src/AssistantChat.jsx +362 -363
  11. package/client/src/Button.jsx +12 -12
  12. package/client/src/Dashboard.jsx +480 -480
  13. package/client/src/DashboardHtmlViewItem.jsx +146 -146
  14. package/client/src/DashboardView.jsx +654 -654
  15. package/client/src/DataEditor.jsx +383 -383
  16. package/client/src/DataLayout.jsx +779 -806
  17. package/client/src/DataTable.jsx +782 -822
  18. package/client/src/DataTable.scss +186 -186
  19. package/client/src/GeolocationField.jsx +93 -93
  20. package/client/src/HistoryDialog.jsx +307 -285
  21. package/client/src/HistoryDialog.scss +319 -319
  22. package/client/src/HtmlViewBuilderModal.jsx +90 -90
  23. package/client/src/HtmlViewBuilderModal.scss +17 -17
  24. package/client/src/HtmlViewCard.jsx +43 -43
  25. package/client/src/ModelCreatorField.jsx +950 -950
  26. package/client/src/ModelList.jsx +7 -2
  27. package/client/src/Notification.jsx +136 -136
  28. package/client/src/PackGallery.jsx +391 -391
  29. package/client/src/PackGallery.scss +231 -231
  30. package/client/src/Pagination.jsx +143 -143
  31. package/client/src/RelationField.jsx +354 -354
  32. package/client/src/RelationSelectorWidget.jsx +172 -172
  33. package/client/src/RelationValue.jsx +2 -1
  34. package/client/src/contexts/CommandContext.jsx +260 -0
  35. package/client/src/contexts/ModelContext.jsx +4 -1
  36. package/client/src/contexts/UIContext.jsx +72 -72
  37. package/client/src/filter.js +263 -262
  38. package/client/src/index.css +90 -90
  39. package/package.json +11 -10
  40. package/perf/artillery-hooks.js +37 -37
  41. package/perf/setup.yml +25 -25
  42. package/src/constants.js +4 -0
  43. package/src/core.js +8 -1
  44. package/src/engine.js +335 -293
  45. package/src/events.js +140 -21
  46. package/src/filter.js +274 -274
  47. package/src/index.js +3 -0
  48. package/src/modules/assistant/assistant.js +323 -192
  49. package/src/modules/assistant/constants.js +2 -1
  50. package/src/modules/auth-google/index.js +50 -50
  51. package/src/modules/auth-microsoft/index.js +81 -81
  52. package/src/modules/data/data.core.js +118 -118
  53. package/src/modules/data/data.history.js +555 -531
  54. package/src/modules/data/data.operations.js +145 -26
  55. package/src/modules/data/data.relations.js +686 -686
  56. package/src/modules/data/data.routes.js +1879 -1879
  57. package/src/modules/data/data.validation.js +2 -2
  58. package/src/modules/file.js +247 -247
  59. package/src/modules/user.js +1 -0
  60. package/src/modules/workflow.js +2 -2
  61. package/src/openai.jobs.js +3 -2
  62. package/src/packs.js +2 -2
  63. package/src/providers.js +2 -2
  64. package/src/services/stripe.js +196 -196
  65. package/src/sso.js +193 -193
  66. package/src/workers/import-export-worker.js +1 -1
  67. package/test/data.history.integration.test.js +72 -0
  68. package/test/data.integration.test.js +92 -1
  69. package/test/events.test.js +108 -10
  70. package/test/model.integration.test.js +377 -377
@@ -1,196 +1,196 @@
1
- import Stripe from 'stripe';
2
- import {editData, insertData, searchData} from '../modules/data/index.js';
3
- import {getEnv} from "../modules/user.js";
4
- import {safeAssignObject} from "../core.js";
5
-
6
- const stripeInstances = {};
7
-
8
- /**
9
- * Retrieves a cached or creates a new Stripe client instance for a given user.
10
- * This function centralizes API key retrieval and client initialization.
11
- * @param {object} user - The user object.
12
- * @returns {Promise<{client: Stripe, webhookSecret: string}|null>} The Stripe client and webhook secret, or null if not configured.
13
- */
14
- async function getStripeClient(user) {
15
- const userId = user._id.toString();
16
- if (!stripeInstances[userId]) {
17
- const env = await getEnv(user);
18
- if (env.STRIPE_SECRET_KEY) {
19
- safeAssignObject(stripeInstances, userId, {
20
- client: new Stripe(env.STRIPE_SECRET_KEY),
21
- webhookSecret: env.STRIPE_WEBHOOK_SECRET
22
- });
23
- }
24
- }
25
- return stripeInstances[userId] || null;
26
- }
27
-
28
- /**
29
- * Crée ou récupère un client Stripe pour un utilisateur de notre système.
30
- */
31
- async function getOrCreateCustomer(user, db) {
32
- const stripeInfo = await getStripeClient(user);
33
- if (!stripeInfo?.client) {
34
- throw new Error("Stripe is not configured for this user.");
35
- }
36
- const { client: stripe } = stripeInfo;
37
-
38
- // Vérifier que l'utilisateur et son email de contact sont valides
39
- if (!user || !user.contact || !user.contact.email) {
40
- // Dans un vrai scénario, il faudrait peut-être chercher l'email directement sur le modèle user
41
- const userRecord = await db.findOne('user', {_id: user._id});
42
- if(!userRecord || !userRecord.contact || !userRecord.contact.email) {
43
- throw new Error("User or user contact email is missing.");
44
- }
45
- user = userRecord;
46
- }
47
-
48
- const existingCustomer = await db.findOne('StripeCustomer', { user: user._id });
49
-
50
- if (existingCustomer) {
51
- return existingCustomer;
52
- }
53
-
54
- // Créer le client sur Stripe
55
- const stripeCustomer = await stripe.customers.create({
56
- email: user.contact.email,
57
- name: user.username,
58
- metadata: {
59
- userId: user._id.toString() // Lien vers notre système
60
- }
61
- });
62
-
63
- // Enregistrer le client dans notre BDD
64
- const newCustomerData = {
65
- user: user._id,
66
- stripeCustomerId: stripeCustomer.id,
67
- email: user.contact.email // Utiliser l'email de contact pour la cohérence
68
- };
69
- const { insertedIds } = await insertData('StripeCustomer', newCustomerData, {}, user);
70
-
71
- // Pas besoin de refaire une recherche, on a déjà toutes les infos.
72
- return { _id: insertedIds[0], ...newCustomerData };
73
- }
74
- /**
75
- * Crée une session de checkout Stripe.
76
- */
77
- export async function createCheckoutSession(priceId, user, db, mode = 'subscription') {
78
- const stripeInfo = await getStripeClient(user);
79
- if (!stripeInfo?.client) {
80
- throw new Error("Stripe is not configured for this user.");
81
- }
82
- const { client: stripe } = stripeInfo;
83
-
84
- const env = await getEnv(user);
85
- const appBaseUrl = env.APP_BASE_URL || 'https://your-domain.com'; // Fallback
86
-
87
- const customer = await getOrCreateCustomer(user, db);
88
- const session = await stripe.checkout.sessions.create({
89
- payment_method_types: ['card'],
90
- mode: mode, // 'subscription' or 'payment'
91
- customer: customer.stripeCustomerId,
92
- line_items: [{ price: priceId, quantity: 1 }],
93
- success_url: `${appBaseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
94
- cancel_url: `${appBaseUrl}/cancel`
95
- });
96
- return session;
97
- }
98
-
99
- /**
100
- * Vérifie le statut d'une session de checkout.
101
- */
102
- export async function verifyCheckoutSession(sessionId, user) {
103
- const stripeInfo = await getStripeClient(user);
104
- if (!stripeInfo?.client) {
105
- throw new Error("Stripe is not configured for this user.");
106
- }
107
- const { client: stripe } = stripeInfo;
108
- try {
109
- const session = await stripe.checkout.sessions.retrieve(sessionId);
110
- return {
111
- status: session.status,
112
- payment_status: session.payment_status,
113
- customer: session.customer,
114
- subscription: session.subscription
115
- };
116
- } catch (error) {
117
- console.error("Error verifying checkout session:", error);
118
- throw new Error("Could not verify checkout session.");
119
- }
120
- }
121
-
122
- /**
123
- * Vérifie la signature d'un webhook Stripe pour s'assurer qu'il est authentique.
124
- * C'est une étape de sécurité cruciale.
125
- *
126
- * @param {object} headers - Les en-têtes de la requête (notamment 'stripe-signature').
127
- * @param {string} rawBody - Le corps brut de la requête.
128
- * @returns {Stripe.Event} L'objet événement Stripe vérifié.
129
- * @throws {Error} Si la signature est invalide ou si les en-têtes/body sont manquants.
130
- */
131
- export async function verifyWebhookSignature(headers, rawBody, user) {
132
- const stripeInfo = await getStripeClient(user);
133
-
134
- if (!stripeInfo) {
135
- throw new Error("Stripe is not configured for this user.");
136
- }
137
- const { client: stripe, webhookSecret } = stripeInfo;
138
- if (!stripe) {
139
- throw new Error("Stripe unknown API key.");
140
- }
141
- if (!webhookSecret) {
142
- throw new Error("Stripe webhook secret (STRIPE_WEBHOOK_SECRET) is not configured on the server.");
143
- }
144
-
145
- const signature = headers['stripe-signature'];
146
- if (!signature) {
147
- throw new Error("Missing 'stripe-signature' header.");
148
- }
149
-
150
- try {
151
- return stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
152
- } catch (err) {
153
- console.error(`❌ Error verifying Stripe webhook signature: ${err.message}`);
154
- throw new Error(`Webhook signature verification failed: ${err.message}`);
155
- }
156
- }
157
-
158
- /**
159
- * Crée un remboursement pour une commande spécifique.
160
- */
161
- export async function createRefund(returnId, db, user) {
162
- const stripeInfo = await getStripeClient(user);
163
- if (!stripeInfo?.client) {
164
- throw new Error("Stripe is not configured for this user.");
165
- }
166
- const { client: stripe } = stripeInfo;
167
-
168
- const returnRequest = await db.findOne('return', { _id: returnId });
169
- if (!returnRequest) {
170
- throw new Error("Return request not found.");
171
- }
172
-
173
- // Trouver la commande et le paiement associés
174
- const order = await db.findOne('order', { _id: returnRequest.order });
175
- if (!order || !order.paymentIntentId) {
176
- throw new Error("Associated order or its paymentIntentId not found.");
177
- }
178
-
179
- const refund = await stripe.refunds.create({
180
- payment_intent: order.paymentIntentId,
181
- amount: Math.round(returnRequest.amount * 100), // Stripe attend le montant en centimes
182
- reason: 'requested_by_customer',
183
- metadata: {
184
- returnId: returnId.toString(),
185
- orderId: order.orderId
186
- }
187
- });
188
-
189
- // Mettre à jour le statut de la demande de retour dans notre BDD
190
- await editData('return', { _id: returnId }, {
191
- status: 'refunded',
192
- refundDate: new Date()
193
- }, {}, user);
194
-
195
- return { refundId: refund.id, status: refund.status };
196
- }
1
+ import Stripe from 'stripe';
2
+ import {editData, insertData, searchData} from '../modules/data/index.js';
3
+ import {getEnv} from "../modules/user.js";
4
+ import {safeAssignObject} from "../core.js";
5
+
6
+ const stripeInstances = {};
7
+
8
+ /**
9
+ * Retrieves a cached or creates a new Stripe client instance for a given user.
10
+ * This function centralizes API key retrieval and client initialization.
11
+ * @param {object} user - The user object.
12
+ * @returns {Promise<{client: Stripe, webhookSecret: string}|null>} The Stripe client and webhook secret, or null if not configured.
13
+ */
14
+ async function getStripeClient(user) {
15
+ const userId = user._id.toString();
16
+ if (!stripeInstances[userId]) {
17
+ const env = await getEnv(user);
18
+ if (env.STRIPE_SECRET_KEY) {
19
+ safeAssignObject(stripeInstances, userId, {
20
+ client: new Stripe(env.STRIPE_SECRET_KEY),
21
+ webhookSecret: env.STRIPE_WEBHOOK_SECRET
22
+ });
23
+ }
24
+ }
25
+ return stripeInstances[userId] || null;
26
+ }
27
+
28
+ /**
29
+ * Crée ou récupère un client Stripe pour un utilisateur de notre système.
30
+ */
31
+ async function getOrCreateCustomer(user, db) {
32
+ const stripeInfo = await getStripeClient(user);
33
+ if (!stripeInfo?.client) {
34
+ throw new Error("Stripe is not configured for this user.");
35
+ }
36
+ const { client: stripe } = stripeInfo;
37
+
38
+ // Vérifier que l'utilisateur et son email de contact sont valides
39
+ if (!user || !user.contact || !user.contact.email) {
40
+ // Dans un vrai scénario, il faudrait peut-être chercher l'email directement sur le modèle user
41
+ const userRecord = await db.findOne('user', {_id: user._id});
42
+ if(!userRecord || !userRecord.contact || !userRecord.contact.email) {
43
+ throw new Error("User or user contact email is missing.");
44
+ }
45
+ user = userRecord;
46
+ }
47
+
48
+ const existingCustomer = await db.findOne('StripeCustomer', { user: user._id });
49
+
50
+ if (existingCustomer) {
51
+ return existingCustomer;
52
+ }
53
+
54
+ // Créer le client sur Stripe
55
+ const stripeCustomer = await stripe.customers.create({
56
+ email: user.contact.email,
57
+ name: user.username,
58
+ metadata: {
59
+ userId: user._id.toString() // Lien vers notre système
60
+ }
61
+ });
62
+
63
+ // Enregistrer le client dans notre BDD
64
+ const newCustomerData = {
65
+ user: user._id,
66
+ stripeCustomerId: stripeCustomer.id,
67
+ email: user.contact.email // Utiliser l'email de contact pour la cohérence
68
+ };
69
+ const { insertedIds } = await insertData('StripeCustomer', newCustomerData, {}, user);
70
+
71
+ // Pas besoin de refaire une recherche, on a déjà toutes les infos.
72
+ return { _id: insertedIds[0], ...newCustomerData };
73
+ }
74
+ /**
75
+ * Crée une session de checkout Stripe.
76
+ */
77
+ export async function createCheckoutSession(priceId, user, db, mode = 'subscription') {
78
+ const stripeInfo = await getStripeClient(user);
79
+ if (!stripeInfo?.client) {
80
+ throw new Error("Stripe is not configured for this user.");
81
+ }
82
+ const { client: stripe } = stripeInfo;
83
+
84
+ const env = await getEnv(user);
85
+ const appBaseUrl = env.APP_BASE_URL || 'https://your-domain.com'; // Fallback
86
+
87
+ const customer = await getOrCreateCustomer(user, db);
88
+ const session = await stripe.checkout.sessions.create({
89
+ payment_method_types: ['card'],
90
+ mode: mode, // 'subscription' or 'payment'
91
+ customer: customer.stripeCustomerId,
92
+ line_items: [{ price: priceId, quantity: 1 }],
93
+ success_url: `${appBaseUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
94
+ cancel_url: `${appBaseUrl}/cancel`
95
+ });
96
+ return session;
97
+ }
98
+
99
+ /**
100
+ * Vérifie le statut d'une session de checkout.
101
+ */
102
+ export async function verifyCheckoutSession(sessionId, user) {
103
+ const stripeInfo = await getStripeClient(user);
104
+ if (!stripeInfo?.client) {
105
+ throw new Error("Stripe is not configured for this user.");
106
+ }
107
+ const { client: stripe } = stripeInfo;
108
+ try {
109
+ const session = await stripe.checkout.sessions.retrieve(sessionId);
110
+ return {
111
+ status: session.status,
112
+ payment_status: session.payment_status,
113
+ customer: session.customer,
114
+ subscription: session.subscription
115
+ };
116
+ } catch (error) {
117
+ console.error("Error verifying checkout session:", error);
118
+ throw new Error("Could not verify checkout session.");
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Vérifie la signature d'un webhook Stripe pour s'assurer qu'il est authentique.
124
+ * C'est une étape de sécurité cruciale.
125
+ *
126
+ * @param {object} headers - Les en-têtes de la requête (notamment 'stripe-signature').
127
+ * @param {string} rawBody - Le corps brut de la requête.
128
+ * @returns {Stripe.Event} L'objet événement Stripe vérifié.
129
+ * @throws {Error} Si la signature est invalide ou si les en-têtes/body sont manquants.
130
+ */
131
+ export async function verifyWebhookSignature(headers, rawBody, user) {
132
+ const stripeInfo = await getStripeClient(user);
133
+
134
+ if (!stripeInfo) {
135
+ throw new Error("Stripe is not configured for this user.");
136
+ }
137
+ const { client: stripe, webhookSecret } = stripeInfo;
138
+ if (!stripe) {
139
+ throw new Error("Stripe unknown API key.");
140
+ }
141
+ if (!webhookSecret) {
142
+ throw new Error("Stripe webhook secret (STRIPE_WEBHOOK_SECRET) is not configured on the server.");
143
+ }
144
+
145
+ const signature = headers['stripe-signature'];
146
+ if (!signature) {
147
+ throw new Error("Missing 'stripe-signature' header.");
148
+ }
149
+
150
+ try {
151
+ return stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
152
+ } catch (err) {
153
+ console.error(`❌ Error verifying Stripe webhook signature: ${err.message}`);
154
+ throw new Error(`Webhook signature verification failed: ${err.message}`);
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Crée un remboursement pour une commande spécifique.
160
+ */
161
+ export async function createRefund(returnId, db, user) {
162
+ const stripeInfo = await getStripeClient(user);
163
+ if (!stripeInfo?.client) {
164
+ throw new Error("Stripe is not configured for this user.");
165
+ }
166
+ const { client: stripe } = stripeInfo;
167
+
168
+ const returnRequest = await db.findOne('return', { _id: returnId });
169
+ if (!returnRequest) {
170
+ throw new Error("Return request not found.");
171
+ }
172
+
173
+ // Trouver la commande et le paiement associés
174
+ const order = await db.findOne('order', { _id: returnRequest.order });
175
+ if (!order || !order.paymentIntentId) {
176
+ throw new Error("Associated order or its paymentIntentId not found.");
177
+ }
178
+
179
+ const refund = await stripe.refunds.create({
180
+ payment_intent: order.paymentIntentId,
181
+ amount: Math.round(returnRequest.amount * 100), // Stripe attend le montant en centimes
182
+ reason: 'requested_by_customer',
183
+ metadata: {
184
+ returnId: returnId.toString(),
185
+ orderId: order.orderId
186
+ }
187
+ });
188
+
189
+ // Mettre à jour le statut de la demande de retour dans notre BDD
190
+ await editData('return', { _id: returnId }, {
191
+ status: 'refunded',
192
+ refundDate: new Date()
193
+ }, {}, user);
194
+
195
+ return { refundId: refund.id, status: refund.status };
196
+ }