@donotdev/functions 0.2.2 → 0.3.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.
- package/README.md +1 -1
- package/lib/chunks/chunk-522YXGDA.js +23 -0
- package/lib/chunks/chunk-522YXGDA.js.map +7 -0
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/chunk-OKRR7ST5.js +22 -0
- package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +13 -10
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -9
- package/lib/supabase/crud/entityStore.d.ts +67 -14
- package/lib/supabase/crud/update.d.ts +7 -10
- package/lib/supabase/index.d.ts +5 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +33 -1
- package/src/firebase/auth/setCustomClaims.ts +6 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +37 -19
- package/src/firebase/crud/bulk.ts +30 -10
- package/src/firebase/crud/create.ts +40 -26
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +12 -14
- package/src/firebase/crud/list.ts +23 -12
- package/src/firebase/crud/update.ts +49 -25
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +112 -82
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/logger.ts +37 -38
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +4 -42
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +50 -0
- package/src/supabase/crud/create.ts +27 -33
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +107 -18
- package/src/supabase/crud/get.ts +5 -13
- package/src/supabase/crud/list.ts +28 -21
- package/src/supabase/crud/update.ts +29 -24
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +8 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +34 -6
- package/src/vercel/api/crud/create.ts +22 -21
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +10 -8
- package/src/vercel/api/crud/list.ts +10 -8
- package/src/vercel/api/crud/update.ts +25 -20
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -192
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -22,6 +22,7 @@ import { stripe, validateStripeEnvironment, initStripe } from '../../shared/bill
|
|
|
22
22
|
import { createBaseFunction } from '../baseFunction.js';
|
|
23
23
|
import { STRIPE_CONFIG } from '../config/constants.js';
|
|
24
24
|
import { stripeSecretKey } from '../config/secrets.js';
|
|
25
|
+
import { isOneOf, pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
|
|
25
26
|
|
|
26
27
|
const changePlanSchema = v.object({
|
|
27
28
|
userId: v.string(),
|
|
@@ -98,8 +99,8 @@ async function changePlanLogic(
|
|
|
98
99
|
'trialing',
|
|
99
100
|
'incomplete',
|
|
100
101
|
] as const;
|
|
101
|
-
const status = validStatuses
|
|
102
|
-
?
|
|
102
|
+
const status = isOneOf(validStatuses, updatedSubscription.status)
|
|
103
|
+
? updatedSubscription.status
|
|
103
104
|
: 'incomplete';
|
|
104
105
|
|
|
105
106
|
// Update Firebase Auth claims
|
|
@@ -109,9 +110,9 @@ async function changePlanLogic(
|
|
|
109
110
|
tier: billingItem.tier,
|
|
110
111
|
status,
|
|
111
112
|
subscriptionEnd: new Date(
|
|
112
|
-
(updatedSubscription
|
|
113
|
+
pinnedSubscriptionPeriod(updatedSubscription).current_period_end * 1000
|
|
113
114
|
).toISOString(),
|
|
114
|
-
cancelAtPeriodEnd:
|
|
115
|
+
cancelAtPeriodEnd: updatedSubscription.cancel_at_period_end,
|
|
115
116
|
subscriptionId: updatedSubscription.id,
|
|
116
117
|
customerId: updatedSubscription.customer as string,
|
|
117
118
|
},
|
|
@@ -119,7 +120,7 @@ async function changePlanLogic(
|
|
|
119
120
|
async getUser(uid: string) {
|
|
120
121
|
return getFirebaseAdminAuth().getUser(uid);
|
|
121
122
|
},
|
|
122
|
-
async setCustomUserClaims(uid: string, claims: Record<string,
|
|
123
|
+
async setCustomUserClaims(uid: string, claims: Record<string, unknown>) {
|
|
123
124
|
await getFirebaseAdminAuth().setCustomUserClaims(uid, claims);
|
|
124
125
|
},
|
|
125
126
|
}
|
|
@@ -56,10 +56,12 @@ async function createCustomerPortalLogic(
|
|
|
56
56
|
// Get customer ID from user claims
|
|
57
57
|
const user = await getFirebaseAdminAuth().getUser(userId);
|
|
58
58
|
// ... (rest of logic)
|
|
59
|
-
const currentClaims =
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
59
|
+
const currentClaims: Record<string, unknown> = user.customClaims || {};
|
|
60
|
+
const subscription = currentClaims.subscription as
|
|
61
|
+
| { customerId?: string }
|
|
62
|
+
| undefined;
|
|
63
|
+
const customerId: string | undefined =
|
|
64
|
+
subscription?.customerId || user.customClaims?.stripeCustomerId;
|
|
63
65
|
|
|
64
66
|
if (!customerId) {
|
|
65
67
|
throw handleError(new Error('No Stripe customer ID found for user'));
|
|
@@ -19,6 +19,7 @@ import { getFirebaseAdminAuth } from '@donotdev/firebase/server';
|
|
|
19
19
|
import { stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
|
|
20
20
|
import { createBaseFunction } from '../baseFunction.js';
|
|
21
21
|
import { STRIPE_CONFIG } from '../config/constants.js';
|
|
22
|
+
import { pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
25
|
* Schema for refreshing subscription status
|
|
@@ -70,12 +71,12 @@ async function refreshSubscriptionStatusLogic(
|
|
|
70
71
|
...currentClaims.subscription,
|
|
71
72
|
status: subscription.status,
|
|
72
73
|
currentPeriodStart: new Date(
|
|
73
|
-
(subscription
|
|
74
|
+
pinnedSubscriptionPeriod(subscription).current_period_start * 1000
|
|
74
75
|
).toISOString(),
|
|
75
76
|
currentPeriodEnd: new Date(
|
|
76
|
-
(subscription
|
|
77
|
+
pinnedSubscriptionPeriod(subscription).current_period_end * 1000
|
|
77
78
|
).toISOString(),
|
|
78
|
-
cancelAtPeriodEnd:
|
|
79
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
79
80
|
},
|
|
80
81
|
};
|
|
81
82
|
|
|
@@ -86,9 +87,9 @@ async function refreshSubscriptionStatusLogic(
|
|
|
86
87
|
userId,
|
|
87
88
|
status: subscription.status,
|
|
88
89
|
currentPeriodEnd: new Date(
|
|
89
|
-
(subscription
|
|
90
|
+
pinnedSubscriptionPeriod(subscription).current_period_end * 1000
|
|
90
91
|
).toISOString(),
|
|
91
|
-
cancelAtPeriodEnd:
|
|
92
|
+
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
92
93
|
};
|
|
93
94
|
}
|
|
94
95
|
|
|
@@ -101,6 +102,7 @@ async function refreshSubscriptionStatusLogic(
|
|
|
101
102
|
* @author AMBROISE PARK Consulting
|
|
102
103
|
*/
|
|
103
104
|
export const refreshSubscriptionStatus = (
|
|
105
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
104
106
|
customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
|
|
105
107
|
) => {
|
|
106
108
|
const schema = customSchema || refreshSubscriptionStatusSchema;
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { logger } from 'firebase-functions/v2';
|
|
13
|
-
import { onRequest } from 'firebase-functions/v2/https';
|
|
13
|
+
import { onRequest, type Request } from 'firebase-functions/v2/https';
|
|
14
14
|
import type { HttpsFunction } from 'firebase-functions/v2/https';
|
|
15
15
|
|
|
16
16
|
import type { StripeBackConfig } from '@donotdev/core/server';
|
|
@@ -31,10 +31,10 @@ import { stripeSecretKey, stripeWebhookSecret } from '../config/secrets.js'; //
|
|
|
31
31
|
/**
|
|
32
32
|
* Read raw body from request stream
|
|
33
33
|
*/
|
|
34
|
-
async function getRawBody(req:
|
|
34
|
+
async function getRawBody(req: Request): Promise<Buffer> {
|
|
35
35
|
// If rawBody is already available, use it
|
|
36
|
-
if (
|
|
37
|
-
return
|
|
36
|
+
if (req.rawBody && Buffer.isBuffer(req.rawBody)) {
|
|
37
|
+
return req.rawBody;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
// Otherwise, read from stream
|
|
@@ -51,8 +51,19 @@ const tx = {
|
|
|
51
51
|
}),
|
|
52
52
|
};
|
|
53
53
|
|
|
54
|
+
/** Stored rows read before validation (status rule); every id exists unless listed in `missingIds`. */
|
|
55
|
+
let storedRows: Record<string, Record<string, unknown>> = {};
|
|
56
|
+
const missingIds = new Set<string>();
|
|
57
|
+
|
|
54
58
|
const mockDb = {
|
|
55
59
|
collection: vi.fn(() => mockCollection()),
|
|
60
|
+
getAll: vi.fn(async (...refs: MockRef[]) =>
|
|
61
|
+
refs.map((ref) => ({
|
|
62
|
+
id: ref.id,
|
|
63
|
+
exists: !missingIds.has(ref.id),
|
|
64
|
+
data: () => storedRows[ref.id] ?? { status: 'available' },
|
|
65
|
+
}))
|
|
66
|
+
),
|
|
56
67
|
runTransaction: vi.fn(async (fn: (t: typeof tx) => Promise<any>) => {
|
|
57
68
|
runTransactionInvocations += 1;
|
|
58
69
|
if (simulateRollback) {
|
|
@@ -74,11 +85,12 @@ vi.mock('@donotdev/firebase/server', () => ({
|
|
|
74
85
|
}));
|
|
75
86
|
|
|
76
87
|
// Import AFTER mocks are in place.
|
|
77
|
-
import { BulkCollisionError } from '@donotdev/core/server';
|
|
88
|
+
import { BulkCollisionError, createSchemas } from '@donotdev/core/server';
|
|
78
89
|
|
|
79
90
|
import { bulkEntityLogicFactory } from '../bulk';
|
|
80
91
|
|
|
81
92
|
import * as v from 'valibot';
|
|
93
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
82
94
|
|
|
83
95
|
// ---------------------------------------------------------------------------
|
|
84
96
|
// Fixtures
|
|
@@ -110,6 +122,8 @@ function resetState() {
|
|
|
110
122
|
mintedIdCounter = 0;
|
|
111
123
|
runTransactionInvocations = 0;
|
|
112
124
|
simulateRollback = null;
|
|
125
|
+
storedRows = {};
|
|
126
|
+
missingIds.clear();
|
|
113
127
|
tx.set.mockClear();
|
|
114
128
|
tx.update.mockClear();
|
|
115
129
|
tx.delete.mockClear();
|
|
@@ -330,3 +344,38 @@ describe('bulkEntityLogicFactory', () => {
|
|
|
330
344
|
expect(runTransactionInvocations).toBe(1);
|
|
331
345
|
});
|
|
332
346
|
});
|
|
347
|
+
|
|
348
|
+
describe('bulkEntityLogicFactory — status rule on the stored row', () => {
|
|
349
|
+
const schemas = createSchemas(contactEntity);
|
|
350
|
+
const logic = () =>
|
|
351
|
+
bulkEntityLogicFactory(COLLECTION, schemas.create as never, schemas.draft as never, schemas.update as never, access);
|
|
352
|
+
|
|
353
|
+
beforeEach(() => {
|
|
354
|
+
resetState();
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
it('edit of a stored draft without a status is a draft write (empty required field accepted)', async () => {
|
|
358
|
+
storedRows = { c1: { name: 'Ana', status: 'draft' } };
|
|
359
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { name: null } }] }, ctx)).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
360
|
+
// Same patch on a published row: rejected
|
|
361
|
+
storedRows = { c1: { name: 'Ana', status: 'available' } };
|
|
362
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { name: null } }] }, ctx)).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
it('publishing a draft through a status-only patch checks the whole stored row', async () => {
|
|
366
|
+
storedRows = { c1: { status: 'draft' } };
|
|
367
|
+
await expect(logic()({ updates: [{ id: 'c1', patch: { status: 'available' } }] }, ctx)).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
368
|
+
expect(runTransactionInvocations).toBe(0);
|
|
369
|
+
storedRows = { c1: { name: 'Ana', status: 'draft' } };
|
|
370
|
+
await logic()({ updates: [{ id: 'c1', patch: { status: 'available' } }] }, ctx);
|
|
371
|
+
const updateCall = txCalls.find((c) => c.op === 'update') as { data: Record<string, unknown> };
|
|
372
|
+
expect(updateCall.data.status).toBe('available');
|
|
373
|
+
expect(updateCall.data).not.toHaveProperty('name');
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it('rejects an update of a missing row before opening the transaction', async () => {
|
|
377
|
+
missingIds.add('gone');
|
|
378
|
+
await expect(logic()({ updates: [{ id: 'gone', patch: { name: 'X' } }] }, ctx)).rejects.toMatchObject({ code: 'not-found' });
|
|
379
|
+
expect(runTransactionInvocations).toBe(0);
|
|
380
|
+
});
|
|
381
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// packages/functions/src/firebase/crud/__tests__/create.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Unit tests for the Firestore create logic: status rule
|
|
5
|
+
* (`DEFAULT_STATUS_VALUE`, `writeSchemaFor`) and parse-output writes.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
9
|
+
|
|
10
|
+
vi.mock('firebase-functions/v2', () => ({
|
|
11
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), log: vi.fn() },
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
/** Last document added to the mock Firestore. */
|
|
15
|
+
let added: Record<string, unknown> = {};
|
|
16
|
+
const add = vi.fn(async (data: Record<string, unknown>) => {
|
|
17
|
+
added = data;
|
|
18
|
+
return { get: async () => ({ id: 'n1', data: () => added }) };
|
|
19
|
+
});
|
|
20
|
+
const mockDb = { collection: vi.fn(() => ({ add })) };
|
|
21
|
+
|
|
22
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
23
|
+
getFirebaseAdminFirestore: () => mockDb,
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
// Import AFTER mocks are in place.
|
|
27
|
+
import { createSchemas } from '@donotdev/core/server';
|
|
28
|
+
|
|
29
|
+
import { createEntityLogicFactory } from '../create';
|
|
30
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
31
|
+
|
|
32
|
+
const schemas = createSchemas(contactEntity);
|
|
33
|
+
|
|
34
|
+
const logic = createEntityLogicFactory('contacts', schemas.create as never, schemas.draft as never);
|
|
35
|
+
const context = { uid: 'u1', userRole: 'user', request: {} } as never;
|
|
36
|
+
const run = (payload: Record<string, unknown>) => logic({ payload }, context);
|
|
37
|
+
|
|
38
|
+
describe('createEntity status rule and writes', () => {
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
add.mockClear();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('a create without status is published (DEFAULT_STATUS_VALUE) and validated as a create', async () => {
|
|
44
|
+
await expect(run({ phone: '+33 6 12 34 56 78' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
45
|
+
await run({ name: 'Ana' });
|
|
46
|
+
expect(added.status).toBe('available');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('a draft is validated with the draft schema: required may be empty, filled values keep their format', async () => {
|
|
50
|
+
await run({ status: 'draft', name: null });
|
|
51
|
+
expect(added.status).toBe('draft');
|
|
52
|
+
await expect(run({ status: 'draft', phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('writes the parse output: unknown, hidden and generated keys never reach the DB', async () => {
|
|
56
|
+
await run({ name: 'Ana', secret: 's', role: 'admin', createdById: 'evil', id: 'x' });
|
|
57
|
+
expect(added).not.toHaveProperty('secret');
|
|
58
|
+
expect(added).not.toHaveProperty('role');
|
|
59
|
+
expect(added).not.toHaveProperty('id');
|
|
60
|
+
// createdById comes from the server metadata only
|
|
61
|
+
expect(added.createdById).toBe('u1');
|
|
62
|
+
expect(added.name).toBe('Ana');
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// packages/functions/src/firebase/crud/__tests__/update.test.ts
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
4
|
+
|
|
5
|
+
vi.mock('firebase-functions/v2', () => ({
|
|
6
|
+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), log: vi.fn() },
|
|
7
|
+
}));
|
|
8
|
+
|
|
9
|
+
/** Stored document of the mock Firestore (one collection, one document). */
|
|
10
|
+
let stored: Record<string, unknown> = {};
|
|
11
|
+
const update = vi.fn(async (data: Record<string, unknown>) => {
|
|
12
|
+
stored = { ...stored, ...data };
|
|
13
|
+
});
|
|
14
|
+
const docRef = {
|
|
15
|
+
get: vi.fn(async () => ({ exists: true, id: 'c1', data: () => stored })),
|
|
16
|
+
update,
|
|
17
|
+
};
|
|
18
|
+
const mockDb = { collection: vi.fn(() => ({ doc: () => docRef })) };
|
|
19
|
+
|
|
20
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
21
|
+
getFirebaseAdminFirestore: () => mockDb,
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
// Import AFTER mocks are in place.
|
|
25
|
+
import { createSchemas } from '@donotdev/core/server';
|
|
26
|
+
|
|
27
|
+
import { updateEntityLogicFactory } from '../update';
|
|
28
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
29
|
+
|
|
30
|
+
const schemas = createSchemas(contactEntity);
|
|
31
|
+
|
|
32
|
+
const logic = updateEntityLogicFactory('contacts', schemas.update as never, schemas.draft as never);
|
|
33
|
+
const context = { uid: 'u1', userRole: 'user', request: {} } as never;
|
|
34
|
+
const run = (payload: Record<string, unknown>) => logic({ id: 'c1', payload }, context);
|
|
35
|
+
|
|
36
|
+
describe('updateEntity validation (same rules as the client)', () => {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
update.mockClear();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('non-draft: checks what the update writes against the update schema', async () => {
|
|
42
|
+
// Legacy document with a required field empty: an update of another field passes
|
|
43
|
+
stored = { name: null, status: 'available' };
|
|
44
|
+
await expect(run({ phone: '+33 6 12 34 56 78' })).resolves.toBeDefined();
|
|
45
|
+
await expect(run({ name: null })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
46
|
+
await expect(run({ name: '' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
47
|
+
await expect(run({ phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('draft: required fields may be empty, filled ones keep their format', async () => {
|
|
51
|
+
stored = { name: 'Ana', status: 'draft' };
|
|
52
|
+
await expect(run({ name: null })).resolves.toBeDefined();
|
|
53
|
+
await expect(run({ phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
54
|
+
expect(update).toHaveBeenCalledTimes(1);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('writes the parse output of the sent keys, never the raw payload', async () => {
|
|
58
|
+
stored = { name: 'Ana', status: 'available' };
|
|
59
|
+
await run({ phone: '+33 6 12 34 56 78', createdById: 'evil', role: 'admin' });
|
|
60
|
+
const written = update.mock.calls[0]![0];
|
|
61
|
+
expect(written).toMatchObject({ phone: '+33 6 12 34 56 78' });
|
|
62
|
+
expect(written).not.toHaveProperty('role');
|
|
63
|
+
expect(written.createdById).toBeUndefined();
|
|
64
|
+
expect(written).not.toHaveProperty('name');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('status rule: the sent status wins over the stored one (writeSchemaFor)', async () => {
|
|
68
|
+
// Publishing a draft: the patch is checked against the update schema
|
|
69
|
+
stored = { name: null, status: 'draft' };
|
|
70
|
+
await expect(run({ status: 'available', name: '' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
71
|
+
// Back to draft from a published document: the merged document against the draft schema
|
|
72
|
+
stored = { name: 'Ana', status: 'available' };
|
|
73
|
+
await expect(run({ status: 'draft', name: null })).resolves.toBeDefined();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('publishing a draft through a status-only patch checks the whole merged document', async () => {
|
|
77
|
+
update.mockClear();
|
|
78
|
+
// Stored null required field
|
|
79
|
+
stored = { name: null, status: 'draft' };
|
|
80
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
81
|
+
// Required key absent from the stored document (counted as null)
|
|
82
|
+
stored = { status: 'draft' };
|
|
83
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
84
|
+
expect(update).not.toHaveBeenCalled();
|
|
85
|
+
// Filled in: published; only the sent keys are written
|
|
86
|
+
stored = { name: 'Ana', status: 'draft' };
|
|
87
|
+
await expect(run({ status: 'available' })).resolves.toBeDefined();
|
|
88
|
+
const written = update.mock.calls[0]![0];
|
|
89
|
+
expect(written.status).toBe('available');
|
|
90
|
+
expect(written).not.toHaveProperty('name');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('soft-deleting a draft stays relaxed (deleted is hidden)', async () => {
|
|
94
|
+
stored = { name: null, status: 'draft' };
|
|
95
|
+
await expect(run({ status: 'deleted' })).resolves.toBeDefined();
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -13,11 +13,10 @@
|
|
|
13
13
|
import type { CallableRequest } from 'firebase-functions/v2/https';
|
|
14
14
|
import * as v from 'valibot';
|
|
15
15
|
|
|
16
|
-
import {
|
|
17
|
-
import type { UserRole } from '@donotdev/core/server';
|
|
16
|
+
import { isFieldVisible, VISIBILITY } from '@donotdev/core/server';
|
|
17
|
+
import type { UserRole, Visibility } from '@donotdev/core/server';
|
|
18
18
|
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
|
|
19
19
|
|
|
20
|
-
import { isFieldVisible } from '../../shared/schema.js';
|
|
21
20
|
import { DoNotDevError } from '../../shared/utils.js';
|
|
22
21
|
import { createBaseFunction } from '../baseFunction.js';
|
|
23
22
|
import { CRUD_CONFIG } from '../config/constants.js';
|
|
@@ -37,6 +36,7 @@ export interface MetricDefinition {
|
|
|
37
36
|
filter?: {
|
|
38
37
|
field: string;
|
|
39
38
|
operator: '==' | '!=' | '>' | '<' | '>=' | '<=';
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
|
|
40
40
|
value: any;
|
|
41
41
|
};
|
|
42
42
|
}
|
|
@@ -56,12 +56,14 @@ export interface AggregateConfig {
|
|
|
56
56
|
/** Group by configurations */
|
|
57
57
|
groupBy?: GroupByDefinition[];
|
|
58
58
|
/** Optional global filters */
|
|
59
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported request type; consumers reading where values would get unknown (breaking)
|
|
59
60
|
where?: Array<[string, any, any]>;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
/** Request schema for aggregate function */
|
|
63
64
|
interface AggregateRequest {
|
|
64
65
|
/** Optional runtime filters (merged with config filters) */
|
|
66
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported request type; consumers reading where values would get unknown (breaking)
|
|
65
67
|
where?: Array<[string, any, any]>;
|
|
66
68
|
/** Optional date range filter */
|
|
67
69
|
dateRange?: {
|
|
@@ -75,27 +77,42 @@ interface AggregateRequest {
|
|
|
75
77
|
* Extracts visibility from a Valibot field schema
|
|
76
78
|
*/
|
|
77
79
|
function getFieldVisibilityFromSchema(
|
|
78
|
-
schema:
|
|
80
|
+
schema: unknown,
|
|
79
81
|
fieldName: string
|
|
80
|
-
):
|
|
81
|
-
if (
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
): unknown {
|
|
83
|
+
if (typeof schema !== 'object' || schema === null) return undefined;
|
|
84
|
+
if (!('entries' in schema)) return undefined;
|
|
85
|
+
const { entries } = schema;
|
|
86
|
+
if (typeof entries !== 'object' || entries === null) return undefined;
|
|
87
|
+
const field: unknown = (entries as Record<string, unknown>)[fieldName];
|
|
88
|
+
if (!field || (typeof field !== 'object' && typeof field !== 'function')) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
return 'visibility' in field ? field.visibility : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const FIELD_VISIBILITY_LEVELS: readonly string[] = Object.values(VISIBILITY);
|
|
95
|
+
|
|
96
|
+
function isFieldVisibility(value: unknown): value is Visibility {
|
|
97
|
+
return typeof value === 'string' && FIELD_VISIBILITY_LEVELS.includes(value);
|
|
84
98
|
}
|
|
85
99
|
|
|
86
100
|
/**
|
|
87
|
-
* Checks if user can access a field for aggregation
|
|
101
|
+
* Checks if user can access a field for aggregation (core visibility rule,
|
|
102
|
+
* `isFieldVisible`; `owner` fields need a document and are denied here)
|
|
88
103
|
*/
|
|
89
104
|
function canAggregateField(
|
|
90
105
|
fieldName: string,
|
|
91
|
-
schema:
|
|
92
|
-
|
|
106
|
+
schema: unknown,
|
|
107
|
+
userRole: UserRole
|
|
93
108
|
): boolean {
|
|
94
109
|
// '*' is always allowed (count all)
|
|
95
110
|
if (fieldName === '*') return true;
|
|
96
111
|
|
|
97
112
|
const visibility = getFieldVisibilityFromSchema(schema, fieldName);
|
|
98
|
-
|
|
113
|
+
// Unknown visibility levels are denied
|
|
114
|
+
if (visibility !== undefined && !isFieldVisibility(visibility)) return false;
|
|
115
|
+
return isFieldVisible(visibility, userRole);
|
|
99
116
|
}
|
|
100
117
|
|
|
101
118
|
/**
|
|
@@ -122,13 +139,14 @@ function getPriceOrNumberValue(raw: unknown): number {
|
|
|
122
139
|
* For structured price fields uses effective (discounted) price (expected revenue).
|
|
123
140
|
* Plain numbers are used as-is.
|
|
124
141
|
*/
|
|
125
|
-
function getNumericValue(doc: Record<string,
|
|
142
|
+
function getNumericValue(doc: Record<string, unknown>, field: string): number {
|
|
126
143
|
return getPriceOrNumberValue(doc[field]);
|
|
127
144
|
}
|
|
128
145
|
|
|
129
146
|
/**
|
|
130
147
|
* Computes a single metric on a dataset
|
|
131
148
|
*/
|
|
149
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: filter comparisons rely on JS relational coercion over mixed DB values (null/number/string), which TS rejects on unknown
|
|
132
150
|
function computeMetric(docs: any[], metric: MetricDefinition): number | null {
|
|
133
151
|
// Apply metric-level filter if specified
|
|
134
152
|
let filtered = docs;
|
|
@@ -214,7 +232,7 @@ function computeMetric(docs: any[], metric: MetricDefinition): number | null {
|
|
|
214
232
|
*/
|
|
215
233
|
function aggregateEntitiesLogicFactory(
|
|
216
234
|
collection: string,
|
|
217
|
-
documentSchema: v.
|
|
235
|
+
documentSchema: v.GenericSchema,
|
|
218
236
|
config: AggregateConfig
|
|
219
237
|
) {
|
|
220
238
|
return async function aggregateEntitiesLogic(
|
|
@@ -227,7 +245,6 @@ function aggregateEntitiesLogicFactory(
|
|
|
227
245
|
) {
|
|
228
246
|
const db = getFirebaseAdminFirestore();
|
|
229
247
|
const { userRole } = context;
|
|
230
|
-
const isAdmin = hasRoleAccess(userRole, 'admin');
|
|
231
248
|
|
|
232
249
|
// Validate that user can access the fields being aggregated
|
|
233
250
|
const allFields = new Set<string>();
|
|
@@ -239,7 +256,7 @@ function aggregateEntitiesLogicFactory(
|
|
|
239
256
|
});
|
|
240
257
|
|
|
241
258
|
for (const field of allFields) {
|
|
242
|
-
if (!canAggregateField(field, documentSchema,
|
|
259
|
+
if (!canAggregateField(field, documentSchema, userRole)) {
|
|
243
260
|
throw new DoNotDevError(
|
|
244
261
|
`Access denied: cannot aggregate field '${field}'`,
|
|
245
262
|
'permission-denied'
|
|
@@ -282,7 +299,7 @@ function aggregateEntitiesLogicFactory(
|
|
|
282
299
|
// Functions (default 256MB memory).
|
|
283
300
|
const MAX_AGGREGATE_DOCS = 10_000;
|
|
284
301
|
const snapshot = await query.limit(MAX_AGGREGATE_DOCS).get();
|
|
285
|
-
const docs: Record<string,
|
|
302
|
+
const docs: Record<string, unknown>[] = snapshot.docs.map((doc) => ({
|
|
286
303
|
id: doc.id,
|
|
287
304
|
...doc.data(),
|
|
288
305
|
}));
|
|
@@ -302,7 +319,7 @@ function aggregateEntitiesLogicFactory(
|
|
|
302
319
|
> = {};
|
|
303
320
|
if (config.groupBy) {
|
|
304
321
|
for (const groupConfig of config.groupBy) {
|
|
305
|
-
const groupedDocs = new Map<string,
|
|
322
|
+
const groupedDocs = new Map<string, Record<string, unknown>[]>();
|
|
306
323
|
|
|
307
324
|
// Group documents by field value
|
|
308
325
|
for (const doc of docs) {
|
|
@@ -390,11 +407,12 @@ function aggregateEntitiesLogicFactory(
|
|
|
390
407
|
*/
|
|
391
408
|
export const aggregateEntities = (
|
|
392
409
|
collection: string,
|
|
410
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
393
411
|
documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
394
412
|
config: AggregateConfig
|
|
395
413
|
) => {
|
|
396
414
|
const requestSchema = v.object({
|
|
397
|
-
where: v.optional(v.array(v.tuple([v.string(), v.
|
|
415
|
+
where: v.optional(v.array(v.tuple([v.string(), v.unknown(), v.unknown()]))),
|
|
398
416
|
dateRange: v.optional(
|
|
399
417
|
v.object({
|
|
400
418
|
field: v.string(),
|
|
@@ -21,7 +21,7 @@ import type {
|
|
|
21
21
|
} from 'firebase-functions/v2/https';
|
|
22
22
|
import type * as v from 'valibot';
|
|
23
23
|
|
|
24
|
-
import { BulkRequestSchema
|
|
24
|
+
import { BulkRequestSchema } from '@donotdev/core/server';
|
|
25
25
|
import type {
|
|
26
26
|
BulkRequest,
|
|
27
27
|
BulkResponse,
|
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
createMetadata,
|
|
34
34
|
executeBulk,
|
|
35
35
|
prepareForFirestore,
|
|
36
|
+
transformFirestoreData,
|
|
36
37
|
updateMetadata,
|
|
37
38
|
} from '../../shared/index.js';
|
|
38
39
|
import { createBaseFunction } from '../baseFunction.js';
|
|
@@ -84,13 +85,17 @@ interface BulkAccess {
|
|
|
84
85
|
*/
|
|
85
86
|
export function bulkEntityLogicFactory(
|
|
86
87
|
collection: string,
|
|
88
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
87
89
|
createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
90
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
88
91
|
draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
92
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
89
93
|
updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
90
94
|
access: BulkAccess
|
|
91
95
|
) {
|
|
92
96
|
return async function bulkEntityLogic(
|
|
93
97
|
data: BulkEntityRequest,
|
|
98
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: request data is validated by the bulk schema before use; the callable payload type is erased here
|
|
94
99
|
context: { uid: string; userRole: UserRole; request: CallableRequest<any> }
|
|
95
100
|
): Promise<BulkResponse> {
|
|
96
101
|
const { uid, userRole } = context;
|
|
@@ -120,16 +125,28 @@ export function bulkEntityLogicFactory(
|
|
|
120
125
|
userRole,
|
|
121
126
|
// Mint ids via Firestore's `doc()` — gives us stable ids across retry
|
|
122
127
|
// of the transaction callback (Firestore may run it more than once).
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
128
|
+
// Stored rows of the updated ids: their status decides each patch's schema.
|
|
129
|
+
readStored: async (ids) => {
|
|
130
|
+
const snapshots = await getFirebaseAdminFirestore().getAll(
|
|
131
|
+
...ids.map((id) => col().doc(id))
|
|
132
|
+
);
|
|
133
|
+
const rows = new Map<string, Record<string, unknown>>();
|
|
134
|
+
for (const snapshot of snapshots) {
|
|
135
|
+
if (snapshot.exists) {
|
|
136
|
+
rows.set(
|
|
137
|
+
snapshot.id,
|
|
138
|
+
transformFirestoreData(snapshot.data() as Record<string, unknown>)
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return rows;
|
|
132
143
|
},
|
|
144
|
+
mintInsertId: () => col().doc().id,
|
|
145
|
+
// The row carries its status: the CRUD create rules set it (prepareCreate).
|
|
146
|
+
stampInsertMetadata: (row, creatorUid) => ({
|
|
147
|
+
...prepareForFirestore(row),
|
|
148
|
+
...createMetadata(creatorUid),
|
|
149
|
+
}),
|
|
133
150
|
stampUpdateMetadata: (patch, editorUid) => ({
|
|
134
151
|
...prepareForFirestore(patch),
|
|
135
152
|
...updateMetadata(editorUid),
|
|
@@ -229,8 +246,11 @@ export function bulkEntityLogicFactory(
|
|
|
229
246
|
*/
|
|
230
247
|
export const bulkEntity = (
|
|
231
248
|
collection: string,
|
|
249
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
232
250
|
createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
251
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
233
252
|
draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
253
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
|
|
234
254
|
updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
235
255
|
access: BulkAccess
|
|
236
256
|
): CallableFunction<BulkEntityRequest, Promise<BulkResponse>> => {
|