@fantastic.dev/better-stripe 0.30.2 → 0.30.3

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 (49) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +10 -1
  3. package/docs/affiliate-clawbacks.md +5 -5
  4. package/docs/settlement.md +1 -1
  5. package/package.json +2 -2
  6. package/src/component/{affiliate-direct-payout.test.ts → affiliatePayouts/affiliate-direct-payout.test.ts} +6 -7
  7. package/src/component/{affiliate-component-pagination.test.ts → affiliateRecovery/affiliate-component-pagination.test.ts} +7 -10
  8. package/src/component/{affiliate-recovery-lifecycle.test.ts → affiliateRecovery/affiliate-recovery-lifecycle.test.ts} +6 -7
  9. package/src/component/billing/checkout.test.ts +89 -0
  10. package/src/component/billing/invoices.test.ts +294 -0
  11. package/src/component/{store-subscriptions.test.ts → billing/store-subscriptions.test.ts} +2 -3
  12. package/src/component/{subscription-scoping.test.ts → billing/subscription-scoping.test.ts} +2 -4
  13. package/src/component/billing/subscriptions.test.ts +477 -0
  14. package/src/component/{connect.test.ts → connect/connect.test.ts} +2 -4
  15. package/src/component/{fee-routing.test.ts → connect/fee-routing.test.ts} +2 -4
  16. package/src/component/connect/payments.test.ts +88 -0
  17. package/src/component/connect/payouts.test.ts +173 -0
  18. package/src/component/{reversal-races.test.ts → connect/reversal-races.test.ts} +4 -6
  19. package/src/component/{seller-case-ownership.test.ts → connect/seller-case-ownership.test.ts} +2 -3
  20. package/src/component/{transfers.test.ts → connect/transfers.test.ts} +3 -5
  21. package/src/component/core/accounts.test.ts +266 -0
  22. package/src/component/{config-queries.test.ts → core/config-queries.test.ts} +2 -4
  23. package/src/component/{payout-reset-safety.test.ts → core/payout-reset-safety.test.ts} +1 -2
  24. package/src/component/core/reset.test.ts +124 -0
  25. package/src/component/{cost-recovery.test.ts → costRecovery/cost-recovery.test.ts} +1 -2
  26. package/src/component/{currency-migration.test.ts → earnings/currency-migration.test.ts} +2 -3
  27. package/src/component/{currency-totals.test.ts → earnings/currency-totals.test.ts} +2 -3
  28. package/src/component/{earnings-totals.test.ts → earnings/earnings-totals.test.ts} +3 -5
  29. package/src/component/{summary-arithmetic.test.ts → earnings/summary-arithmetic.test.ts} +2 -3
  30. package/src/component/{payout-policy-adoption.test.ts → payoutPolicy/payout-policy-adoption.test.ts} +2 -3
  31. package/src/component/{payout-policy.test.ts → payoutPolicy/payout-policy.test.ts} +1 -2
  32. package/src/component/{payout-adoption.test.ts → payoutRelease/payout-adoption.test.ts} +2 -6
  33. package/src/component/{payout-fees.test.ts → payoutRelease/payout-fees.test.ts} +2 -3
  34. package/src/component/{payout-recovery-integration.test.ts → payoutRelease/payout-recovery-integration.test.ts} +3 -4
  35. package/src/component/{payout-release-snapshot.test.ts → payoutRelease/payout-release-snapshot.test.ts} +1 -2
  36. package/src/component/{payout-release.test.ts → payoutRelease/payout-release.test.ts} +2 -3
  37. package/src/component/{payout-revisions.test.ts → payoutSnapshots/payout-revisions.test.ts} +1 -2
  38. package/src/component/{payout-snapshots.test.ts → payoutSnapshots/payout-snapshots.test.ts} +4 -5
  39. package/src/component/{payout-sync.test.ts → payoutSync/payout-sync.test.ts} +1 -2
  40. package/src/component/{payout-component-pagination.test.ts → payoutWorker/payout-component-pagination.test.ts} +8 -9
  41. package/src/component/{payout-worker.test.ts → payoutWorker/payout-worker.test.ts} +1 -2
  42. package/src/component/products/products.test.ts +239 -0
  43. package/src/component/{read-pagination.test.ts → products/read-pagination.test.ts} +2 -3
  44. package/src/component/{refund-history.test.ts → refundHistory/refund-history.test.ts} +2 -3
  45. package/src/component/{affiliate-clawbacks.test.ts → settlement/affiliate-clawbacks.test.ts} +3 -4
  46. package/src/component/{settlement-claims.test.ts → settlement/settlement-claims.test.ts} +2 -3
  47. package/src/component/webhooks/events.test.ts +121 -0
  48. package/src/component/{triggers.test.ts → webhooks/triggers.test.ts} +2 -4
  49. package/src/component/public.test.ts +0 -1858
@@ -1,1858 +0,0 @@
1
- // @vitest-environment edge-runtime
2
- import { convexTest } from "convex-test";
3
- import { describe, expect, it } from "vitest";
4
-
5
- import type { TableNames } from "./_generated/dataModel";
6
- import { api } from "./_generated/api.js";
7
- import schema from "./schema.js";
8
-
9
- const modules = import.meta.glob("./**/*.*s");
10
-
11
- describe("core — account mutations and queries", () => {
12
- it("upsertAccount: inserts new account", async () => {
13
- const t = convexTest(schema, modules);
14
-
15
- await t.mutation(api.core.mutations.upsertAccount, {
16
- stripeAccountId: "acct_001",
17
- userId: "user_001",
18
- name: "Test Account",
19
- email: "test@example.com",
20
- });
21
-
22
- const account = await t.query(api.core.queries.getAccountByUserId, {
23
- userId: "user_001",
24
- });
25
-
26
- expect(account).not.toBeNull();
27
- expect(account!.stripeAccountId).toBe("acct_001");
28
- expect(account!.userId).toBe("user_001");
29
- expect(account!.name).toBe("Test Account");
30
- expect(account!.onboardingStatus).toBe("pending");
31
- });
32
-
33
- it("upsertAccount: updates existing account by stripeAccountId", async () => {
34
- const t = convexTest(schema, modules);
35
-
36
- await t.mutation(api.core.mutations.upsertAccount, {
37
- stripeAccountId: "acct_002",
38
- userId: "user_002",
39
- name: "Original Name",
40
- });
41
-
42
- await t.mutation(api.core.mutations.upsertAccount, {
43
- stripeAccountId: "acct_002",
44
- userId: "user_002",
45
- name: "Updated Name",
46
- });
47
-
48
- const account = await t.query(api.core.queries.getAccountByUserId, {
49
- userId: "user_002",
50
- });
51
-
52
- expect(account).not.toBeNull();
53
- expect(account!.name).toBe("Updated Name");
54
- });
55
-
56
- it("getAccountByUserId: returns matching account", async () => {
57
- const t = convexTest(schema, modules);
58
-
59
- await t.mutation(api.core.mutations.upsertAccount, {
60
- stripeAccountId: "acct_003",
61
- userId: "user_003",
62
- email: "found@example.com",
63
- });
64
-
65
- const account = await t.query(api.core.queries.getAccountByUserId, {
66
- userId: "user_003",
67
- });
68
-
69
- expect(account).not.toBeNull();
70
- expect(account!.userId).toBe("user_003");
71
- expect(account!.email).toBe("found@example.com");
72
- });
73
-
74
- it("getAccountByUserId: returns null for unknown user", async () => {
75
- const t = convexTest(schema, modules);
76
-
77
- const account = await t.query(api.core.queries.getAccountByUserId, {
78
- userId: "user_nonexistent",
79
- });
80
-
81
- expect(account).toBeNull();
82
- });
83
-
84
- it("getAccountOnboardingStatus reflects missingRequirements and readiness", async () => {
85
- const t = convexTest(schema, modules);
86
-
87
- await t.mutation(api.core.mutations.upsertAccount, {
88
- stripeAccountId: "acct_004",
89
- userId: "user_004",
90
- onboardingStatus: "complete",
91
- });
92
-
93
- const account = await t.query(api.core.queries.getAccountByStripeId, {
94
- stripeAccountId: "acct_004",
95
- });
96
-
97
- const status = await t.query(api.core.queries.getAccountOnboardingStatus, {
98
- accountId: account!._id,
99
- });
100
-
101
- expect(status).not.toBeNull();
102
- expect(status!.isReady).toBe(true);
103
- expect(status!.onboardingStatus).toBe("complete");
104
- expect(status!.missingRequirements).toEqual([]);
105
- });
106
- });
107
-
108
- describe("products — product and price mutations and queries", () => {
109
- it("upsertProduct + getProductByStripeId round trip", async () => {
110
- const t = convexTest(schema, modules);
111
-
112
- await t.mutation(api.products.mutations.upsertProduct, {
113
- stripeProductId: "prod_001",
114
- name: "Pro Plan",
115
- active: true,
116
- });
117
-
118
- const product = await t.query(api.products.queries.getProductByStripeId, {
119
- stripeProductId: "prod_001",
120
- });
121
-
122
- expect(product).not.toBeNull();
123
- expect(product!.name).toBe("Pro Plan");
124
- expect(product!.active).toBe(true);
125
- });
126
-
127
- it("upsertPrice + listPricesByProduct", async () => {
128
- const t = convexTest(schema, modules);
129
-
130
- await t.mutation(api.products.mutations.upsertProduct, {
131
- stripeProductId: "prod_002",
132
- name: "Starter Plan",
133
- active: true,
134
- });
135
-
136
- await t.mutation(api.products.mutations.upsertPrice, {
137
- stripePriceId: "price_001",
138
- productId: "internal_prod_002",
139
- stripeProductId: "prod_002",
140
- unitAmount: 1000,
141
- currency: "usd",
142
- active: true,
143
- type: "recurring",
144
- interval: "month",
145
- });
146
-
147
- await t.mutation(api.products.mutations.upsertPrice, {
148
- stripePriceId: "price_002",
149
- productId: "internal_prod_002",
150
- stripeProductId: "prod_002",
151
- unitAmount: 10000,
152
- currency: "usd",
153
- active: true,
154
- type: "recurring",
155
- interval: "year",
156
- });
157
-
158
- const prices = await t.query(api.products.queries.listPricesByProduct, {
159
- stripeProductId: "prod_002",
160
- });
161
-
162
- expect(prices).toHaveLength(2);
163
- });
164
- });
165
-
166
- describe("billing — subscription mutations and queries", () => {
167
- it("upsertSubscription + getActiveSubscription", async () => {
168
- const t = convexTest(schema, modules);
169
-
170
- await t.mutation(api.billing.mutations.upsertSubscription, {
171
- stripeSubscriptionId: "sub_001",
172
- userId: "user_010",
173
- status: "active",
174
- cancelAtPeriodEnd: false,
175
- isTrialing: false,
176
- });
177
-
178
- const sub = await t.query(api.billing.queries.getActiveSubscription, {
179
- userId: "user_010",
180
- });
181
-
182
- expect(sub).not.toBeNull();
183
- expect(sub!.stripeSubscriptionId).toBe("sub_001");
184
- expect(sub!.status).toBe("active");
185
- });
186
-
187
- it("getTrialStatus: returns trial days remaining", async () => {
188
- const t = convexTest(schema, modules);
189
-
190
- const trialStart = "2030-01-01T00:00:00.000Z";
191
- const trialEnd = "2030-01-08T00:00:00.000Z";
192
-
193
- await t.mutation(api.billing.mutations.upsertSubscription, {
194
- stripeSubscriptionId: "sub_trial_001",
195
- userId: "user_trial",
196
- status: "trialing",
197
- cancelAtPeriodEnd: false,
198
- isTrialing: true,
199
- trialStart,
200
- trialEnd,
201
- });
202
-
203
- const doc = await t.query(api.billing.queries.getSubscriptionByStripeId, {
204
- stripeSubscriptionId: "sub_trial_001",
205
- });
206
-
207
- const trialStatus = await t.query(api.billing.queries.getTrialStatus, {
208
- subscriptionId: doc!._id,
209
- });
210
-
211
- expect(trialStatus).not.toBeNull();
212
- expect(trialStatus!.isTrialing).toBe(true);
213
- expect(trialStatus!.daysRemaining).toBeGreaterThanOrEqual(6);
214
- expect(trialStatus!.status).toBe("trialing");
215
- });
216
-
217
- // BTS-33: dunning tracks the delinquent subscription lifecycle. Stripe moves a
218
- // subscription to `past_due` on the first failed recurring charge and to
219
- // `unpaid` once smart retries are exhausted — both must round-trip the table.
220
- it.each(["past_due", "unpaid"] as const)(
221
- "persists the delinquent subscription status %s",
222
- async (status) => {
223
- const t = convexTest(schema, modules);
224
-
225
- await t.mutation(api.billing.mutations.upsertSubscription, {
226
- stripeSubscriptionId: `sub_${status}`,
227
- userId: "user_dunning",
228
- status,
229
- cancelAtPeriodEnd: false,
230
- isTrialing: false,
231
- });
232
-
233
- const doc = await t.query(api.billing.queries.getSubscriptionByStripeId, {
234
- stripeSubscriptionId: `sub_${status}`,
235
- });
236
- expect(doc!.status).toBe(status);
237
- },
238
- );
239
- });
240
-
241
- describe("billing — checkout session mutations and queries", () => {
242
- it("upsertCheckoutSession + getCheckoutSessionByStripeId", async () => {
243
- const t = convexTest(schema, modules);
244
-
245
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
246
- stripeSessionId: "cs_001",
247
- userId: "user_020",
248
- mode: "subscription",
249
- status: "open",
250
- });
251
-
252
- const session = await t.query(
253
- api.billing.queries.getCheckoutSessionByStripeId,
254
- {
255
- stripeSessionId: "cs_001",
256
- },
257
- );
258
-
259
- expect(session).not.toBeNull();
260
- expect(session!.mode).toBe("subscription");
261
- expect(session!.status).toBe("open");
262
- });
263
- });
264
-
265
- describe("billing — invoice mutations and queries", () => {
266
- it("rejects an invalid invoice status with a validation error", async () => {
267
- const t = convexTest(schema, modules);
268
-
269
- await expect(
270
- t.mutation(api.billing.mutations.upsertInvoice, {
271
- stripeInvoiceId: "inv_bad_status",
272
- userId: "user_030",
273
- // @ts-expect-error — invalid status must be rejected by the validator
274
- status: "not_a_real_status",
275
- currency: "usd",
276
- amountDue: 1000,
277
- amountPaid: 0,
278
- }),
279
- ).rejects.toThrow(/Validator error/);
280
- });
281
-
282
- it("upsertInvoice + listInvoices", async () => {
283
- const t = convexTest(schema, modules);
284
-
285
- await t.mutation(api.billing.mutations.upsertInvoice, {
286
- stripeInvoiceId: "inv_001",
287
- userId: "user_030",
288
- status: "paid",
289
- currency: "usd",
290
- amountDue: 2000,
291
- amountPaid: 2000,
292
- });
293
-
294
- await t.mutation(api.billing.mutations.upsertInvoice, {
295
- stripeInvoiceId: "inv_002",
296
- userId: "user_030",
297
- status: "open",
298
- currency: "usd",
299
- amountDue: 5000,
300
- amountPaid: 0,
301
- });
302
-
303
- const invoices = await t.query(api.billing.queries.listInvoices, {
304
- userId: "user_030",
305
- });
306
-
307
- expect(invoices).toHaveLength(2);
308
- });
309
-
310
- it("getInvoiceByStripeId: returns matching invoice", async () => {
311
- const t = convexTest(schema, modules);
312
-
313
- await t.mutation(api.billing.mutations.upsertInvoice, {
314
- stripeInvoiceId: "inv_by_stripe_001",
315
- userId: "user_031",
316
- status: "paid",
317
- currency: "usd",
318
- amountDue: 1500,
319
- amountPaid: 1500,
320
- });
321
-
322
- const invoice = await t.query(api.billing.queries.getInvoiceByStripeId, {
323
- stripeInvoiceId: "inv_by_stripe_001",
324
- });
325
-
326
- expect(invoice).not.toBeNull();
327
- expect(invoice!.stripeInvoiceId).toBe("inv_by_stripe_001");
328
- expect(invoice!.userId).toBe("user_031");
329
- expect(invoice!.amountDue).toBe(1500);
330
- });
331
-
332
- // BTS-33: a failed subscription invoice carries the smart-retry schedule
333
- // (`next_payment_attempt`) and attempt count so a dunning hook can tell the
334
- // buyer when Stripe will retry. Both persist as optional invoice fields.
335
- it("persists smart-retry metadata (nextPaymentAttempt + attemptCount)", async () => {
336
- const t = convexTest(schema, modules);
337
-
338
- await t.mutation(api.billing.mutations.upsertInvoice, {
339
- stripeInvoiceId: "inv_retry_001",
340
- userId: "user_dunning",
341
- status: "open",
342
- currency: "usd",
343
- amountDue: 5000,
344
- amountPaid: 0,
345
- nextPaymentAttempt: "2030-02-01T00:00:00.000Z",
346
- attemptCount: 1,
347
- });
348
-
349
- const invoice = await t.query(api.billing.queries.getInvoiceByStripeId, {
350
- stripeInvoiceId: "inv_retry_001",
351
- });
352
- expect(invoice!.status).toBe("open");
353
- expect(invoice!.nextPaymentAttempt).toBe("2030-02-01T00:00:00.000Z");
354
- expect(invoice!.attemptCount).toBe(1);
355
- });
356
-
357
- it("getInvoiceByStripeId: returns null for unknown id", async () => {
358
- const t = convexTest(schema, modules);
359
-
360
- const invoice = await t.query(api.billing.queries.getInvoiceByStripeId, {
361
- stripeInvoiceId: "inv_does_not_exist",
362
- });
363
-
364
- expect(invoice).toBeNull();
365
- });
366
- });
367
-
368
- describe("core — clearAllTables", () => {
369
- it("clearAllTables: removes all records from every table", async () => {
370
- const t = convexTest(schema, modules);
371
-
372
- // Seed one row in every schema table so a drifted clear list is caught.
373
- await t.mutation(api.core.mutations.upsertAccount, {
374
- stripeAccountId: "acct_clear",
375
- userId: "user_clear",
376
- });
377
-
378
- await t.mutation(api.products.mutations.upsertProduct, {
379
- stripeProductId: "prod_clear",
380
- name: "To Be Cleared",
381
- active: true,
382
- });
383
-
384
- await t.mutation(api.products.mutations.upsertPrice, {
385
- stripePriceId: "price_clear",
386
- productId: "internal_prod_clear",
387
- stripeProductId: "prod_clear",
388
- unitAmount: 1000,
389
- currency: "usd",
390
- active: true,
391
- type: "one_time",
392
- });
393
-
394
- await t.mutation(api.billing.mutations.upsertSubscription, {
395
- stripeSubscriptionId: "sub_clear",
396
- userId: "user_clear",
397
- status: "active",
398
- cancelAtPeriodEnd: false,
399
- isTrialing: false,
400
- });
401
-
402
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
403
- stripeSessionId: "cs_clear",
404
- userId: "user_clear",
405
- mode: "subscription",
406
- status: "open",
407
- });
408
-
409
- await t.mutation(api.billing.mutations.upsertInvoice, {
410
- stripeInvoiceId: "inv_clear",
411
- userId: "user_clear",
412
- status: "paid",
413
- currency: "usd",
414
- amountDue: 1000,
415
- amountPaid: 1000,
416
- });
417
-
418
- await t.mutation(api.connect.mutations.upsertPayment, {
419
- stripePaymentIntentId: "pi_clear",
420
- userId: "user_clear",
421
- amount: 1000,
422
- currency: "usd",
423
- status: "succeeded",
424
- });
425
-
426
- await t.mutation(api.connect.mutations.upsertPayout, {
427
- stripePayoutId: "po_clear",
428
- accountId: "acct_clear",
429
- amount: 1000,
430
- currency: "usd",
431
- status: "paid",
432
- });
433
-
434
- await t.mutation(api.connect.mutations.upsertRefund, {
435
- stripeRefundId: "re_clear",
436
- amount: 1000,
437
- currency: "usd",
438
- status: "succeeded",
439
- });
440
-
441
- await t.mutation(api.connect.mutations.upsertDispute, {
442
- stripeDisputeId: "dp_clear",
443
- amount: 1000,
444
- currency: "usd",
445
- status: "needs_response",
446
- reason: "product_not_received",
447
- isChargeRefundable: true,
448
- });
449
-
450
- await t.mutation(api.connect.mutations.upsertTransfer, {
451
- stripeTransferId: "tr_clear",
452
- destinationAccountId: "acct_dest_clear",
453
- amount: 1000,
454
- currency: "usd",
455
- status: "paid",
456
- });
457
-
458
- await t.run(async (ctx) => {
459
- await ctx.db.insert("transferReversalOps", {
460
- operationId: "op_clear",
461
- sourceChargeId: "ch_clear",
462
- slices: [],
463
- });
464
- });
465
-
466
- await t.mutation(api.webhooks.mutations.insertWebhookEvent, {
467
- stripeEventId: "evt_clear",
468
- eventType: "invoice.paid",
469
- });
470
-
471
- const result = await t.mutation(api.core.mutations.clearAllTables, {});
472
- const tableCount = Object.keys(schema.tables).length;
473
-
474
- expect(result.cleared).toBe(20);
475
- expect(result.tables).toHaveLength(tableCount);
476
-
477
- for (const tableName of Object.keys(schema.tables) as TableNames[]) {
478
- const remaining = await t.run(async (ctx) =>
479
- ctx.db.query(tableName).collect(),
480
- );
481
- expect(remaining).toHaveLength(0);
482
- }
483
- });
484
- });
485
-
486
- // =============================================================================
487
- // CORE — additional account queries and mutations
488
- // =============================================================================
489
-
490
- describe("core — getAccountByOrgId", () => {
491
- it("returns account matching orgId", async () => {
492
- const t = convexTest(schema, modules);
493
-
494
- await t.mutation(api.core.mutations.upsertAccount, {
495
- stripeAccountId: "acct_org_001",
496
- userId: "user_org_001",
497
- orgId: "org_001",
498
- name: "Org Account",
499
- });
500
-
501
- const account = await t.query(api.core.queries.getAccountByOrgId, {
502
- orgId: "org_001",
503
- });
504
-
505
- expect(account).not.toBeNull();
506
- expect(account!.orgId).toBe("org_001");
507
- expect(account!.stripeAccountId).toBe("acct_org_001");
508
- });
509
-
510
- it("returns null for unknown orgId", async () => {
511
- const t = convexTest(schema, modules);
512
-
513
- const account = await t.query(api.core.queries.getAccountByOrgId, {
514
- orgId: "org_nonexistent",
515
- });
516
-
517
- expect(account).toBeNull();
518
- });
519
- });
520
-
521
- describe("core — deleteAccountByStripeId", () => {
522
- it("deletes existing account and returns true", async () => {
523
- const t = convexTest(schema, modules);
524
-
525
- await t.mutation(api.core.mutations.upsertAccount, {
526
- stripeAccountId: "acct_del_001",
527
- userId: "user_del_001",
528
- });
529
-
530
- const result = await t.mutation(
531
- api.core.mutations.deleteAccountByStripeId,
532
- {
533
- stripeAccountId: "acct_del_001",
534
- },
535
- );
536
-
537
- expect(result).toBe(true);
538
-
539
- const account = await t.query(api.core.queries.getAccountByStripeId, {
540
- stripeAccountId: "acct_del_001",
541
- });
542
- expect(account).toBeNull();
543
- });
544
-
545
- it("returns false for nonexistent account", async () => {
546
- const t = convexTest(schema, modules);
547
-
548
- const result = await t.mutation(
549
- api.core.mutations.deleteAccountByStripeId,
550
- {
551
- stripeAccountId: "acct_nonexistent",
552
- },
553
- );
554
-
555
- expect(result).toBe(false);
556
- });
557
- });
558
-
559
- describe("core — upsertAccountInternal", () => {
560
- it("inserts account with required onboardingStatus", async () => {
561
- const t = convexTest(schema, modules);
562
-
563
- await t.mutation(api.core.mutations.upsertAccountInternal, {
564
- stripeAccountId: "acct_int_001",
565
- userId: "user_int_001",
566
- onboardingStatus: "in_progress",
567
- });
568
-
569
- const account = await t.query(api.core.queries.getAccountByStripeId, {
570
- stripeAccountId: "acct_int_001",
571
- });
572
-
573
- expect(account).not.toBeNull();
574
- expect(account!.onboardingStatus).toBe("in_progress");
575
- });
576
-
577
- it("updates existing account onboardingStatus", async () => {
578
- const t = convexTest(schema, modules);
579
-
580
- await t.mutation(api.core.mutations.upsertAccountInternal, {
581
- stripeAccountId: "acct_int_002",
582
- userId: "user_int_002",
583
- onboardingStatus: "pending",
584
- });
585
-
586
- await t.mutation(api.core.mutations.upsertAccountInternal, {
587
- stripeAccountId: "acct_int_002",
588
- userId: "user_int_002",
589
- onboardingStatus: "complete",
590
- missingRequirements: [],
591
- });
592
-
593
- const account = await t.query(api.core.queries.getAccountByStripeId, {
594
- stripeAccountId: "acct_int_002",
595
- });
596
-
597
- expect(account!.onboardingStatus).toBe("complete");
598
- expect(account!.missingRequirements).toEqual([]);
599
- });
600
- });
601
-
602
- describe("core — onboarding status edge cases", () => {
603
- it("getAccountOnboardingStatus returns null for nonexistent account", async () => {
604
- const t = convexTest(schema, modules);
605
-
606
- // Insert then delete to get a valid but missing ID
607
- await t.mutation(api.core.mutations.upsertAccount, {
608
- stripeAccountId: "acct_ghost",
609
- userId: "user_ghost",
610
- });
611
-
612
- const account = await t.query(api.core.queries.getAccountByStripeId, {
613
- stripeAccountId: "acct_ghost",
614
- });
615
-
616
- await t.mutation(api.core.mutations.deleteAccountByStripeId, {
617
- stripeAccountId: "acct_ghost",
618
- });
619
-
620
- const status = await t.query(api.core.queries.getAccountOnboardingStatus, {
621
- accountId: account!._id,
622
- });
623
-
624
- expect(status).toBeNull();
625
- });
626
-
627
- it("incomplete account has isReady false and missingRequirements", async () => {
628
- const t = convexTest(schema, modules);
629
-
630
- await t.mutation(api.core.mutations.upsertAccountInternal, {
631
- stripeAccountId: "acct_incomplete",
632
- userId: "user_incomplete",
633
- onboardingStatus: "restricted",
634
- missingRequirements: ["external_account", "tos_acceptance"],
635
- });
636
-
637
- const account = await t.query(api.core.queries.getAccountByStripeId, {
638
- stripeAccountId: "acct_incomplete",
639
- });
640
-
641
- const status = await t.query(api.core.queries.getAccountOnboardingStatus, {
642
- accountId: account!._id,
643
- });
644
-
645
- expect(status!.isReady).toBe(false);
646
- expect(status!.onboardingStatus).toBe("restricted");
647
- expect(status!.missingRequirements).toEqual([
648
- "external_account",
649
- "tos_acceptance",
650
- ]);
651
- });
652
- });
653
-
654
- // =============================================================================
655
- // PRODUCTS — additional filter tests
656
- // =============================================================================
657
-
658
- describe("products — listProducts with filters", () => {
659
- it("filters by active status", async () => {
660
- const t = convexTest(schema, modules);
661
-
662
- await t.mutation(api.products.mutations.upsertProduct, {
663
- stripeProductId: "prod_active",
664
- name: "Active Product",
665
- active: true,
666
- });
667
-
668
- await t.mutation(api.products.mutations.upsertProduct, {
669
- stripeProductId: "prod_inactive",
670
- name: "Inactive Product",
671
- active: false,
672
- });
673
-
674
- const activeProducts = await t.query(api.products.queries.listProducts, {
675
- active: true,
676
- });
677
- const inactiveProducts = await t.query(api.products.queries.listProducts, {
678
- active: false,
679
- });
680
-
681
- expect(activeProducts).toHaveLength(1);
682
- expect(activeProducts[0].name).toBe("Active Product");
683
- expect(inactiveProducts).toHaveLength(1);
684
- expect(inactiveProducts[0].name).toBe("Inactive Product");
685
- });
686
-
687
- it("filters by accountId", async () => {
688
- const t = convexTest(schema, modules);
689
-
690
- await t.mutation(api.products.mutations.upsertProduct, {
691
- stripeProductId: "prod_acct_a",
692
- name: "Account A Product",
693
- active: true,
694
- accountId: "acct_a",
695
- });
696
-
697
- await t.mutation(api.products.mutations.upsertProduct, {
698
- stripeProductId: "prod_acct_b",
699
- name: "Account B Product",
700
- active: true,
701
- accountId: "acct_b",
702
- });
703
-
704
- const products = await t.query(api.products.queries.listProducts, {
705
- accountId: "acct_a",
706
- });
707
-
708
- expect(products).toHaveLength(1);
709
- expect(products[0].name).toBe("Account A Product");
710
- });
711
- });
712
-
713
- describe("products — price queries", () => {
714
- it("getPriceByStripeId round trip", async () => {
715
- const t = convexTest(schema, modules);
716
-
717
- await t.mutation(api.products.mutations.upsertPrice, {
718
- stripePriceId: "price_lookup",
719
- productId: "internal_prod",
720
- stripeProductId: "prod_lookup",
721
- unitAmount: 5000,
722
- currency: "eur",
723
- active: true,
724
- type: "one_time",
725
- });
726
-
727
- const price = await t.query(api.products.queries.getPriceByStripeId, {
728
- stripePriceId: "price_lookup",
729
- });
730
-
731
- expect(price).not.toBeNull();
732
- expect(price!.unitAmount).toBe(5000);
733
- expect(price!.currency).toBe("eur");
734
- expect(price!.type).toBe("one_time");
735
- });
736
-
737
- it("listPrices filters by active", async () => {
738
- const t = convexTest(schema, modules);
739
-
740
- await t.mutation(api.products.mutations.upsertPrice, {
741
- stripePriceId: "price_active",
742
- productId: "prod_x",
743
- stripeProductId: "prod_x",
744
- unitAmount: 100,
745
- currency: "usd",
746
- active: true,
747
- type: "one_time",
748
- });
749
-
750
- await t.mutation(api.products.mutations.upsertPrice, {
751
- stripePriceId: "price_archived",
752
- productId: "prod_x",
753
- stripeProductId: "prod_x",
754
- unitAmount: 200,
755
- currency: "usd",
756
- active: false,
757
- type: "one_time",
758
- });
759
-
760
- const activePrices = await t.query(api.products.queries.listPrices, {
761
- active: true,
762
- });
763
- expect(activePrices).toHaveLength(1);
764
- expect(activePrices[0].stripePriceId).toBe("price_active");
765
- });
766
-
767
- it("upsertPrice updates existing price", async () => {
768
- const t = convexTest(schema, modules);
769
-
770
- await t.mutation(api.products.mutations.upsertPrice, {
771
- stripePriceId: "price_upd",
772
- productId: "prod_u",
773
- stripeProductId: "prod_u",
774
- unitAmount: 1000,
775
- currency: "usd",
776
- active: true,
777
- type: "recurring",
778
- interval: "month",
779
- });
780
-
781
- await t.mutation(api.products.mutations.upsertPrice, {
782
- stripePriceId: "price_upd",
783
- productId: "prod_u",
784
- stripeProductId: "prod_u",
785
- unitAmount: 1000,
786
- currency: "usd",
787
- active: false,
788
- type: "recurring",
789
- interval: "month",
790
- });
791
-
792
- const price = await t.query(api.products.queries.getPriceByStripeId, {
793
- stripePriceId: "price_upd",
794
- });
795
-
796
- expect(price!.active).toBe(false);
797
- });
798
- });
799
-
800
- // =============================================================================
801
- // BILLING — additional subscription query tests
802
- // =============================================================================
803
-
804
- describe("billing — listSubscriptions with filters", () => {
805
- it("filters by status", async () => {
806
- const t = convexTest(schema, modules);
807
-
808
- await t.mutation(api.billing.mutations.upsertSubscription, {
809
- stripeSubscriptionId: "sub_active",
810
- userId: "user_a",
811
- status: "active",
812
- cancelAtPeriodEnd: false,
813
- isTrialing: false,
814
- });
815
-
816
- await t.mutation(api.billing.mutations.upsertSubscription, {
817
- stripeSubscriptionId: "sub_canceled",
818
- userId: "user_b",
819
- status: "canceled",
820
- cancelAtPeriodEnd: false,
821
- isTrialing: false,
822
- });
823
-
824
- const active = await t.query(api.billing.queries.listSubscriptions, {
825
- status: "active",
826
- });
827
- const canceled = await t.query(api.billing.queries.listSubscriptions, {
828
- status: "canceled",
829
- });
830
-
831
- expect(active).toHaveLength(1);
832
- expect(active[0].stripeSubscriptionId).toBe("sub_active");
833
- expect(canceled).toHaveLength(1);
834
- expect(canceled[0].stripeSubscriptionId).toBe("sub_canceled");
835
- });
836
-
837
- it("rejects an invalid status with a validation error", async () => {
838
- const t = convexTest(schema, modules);
839
-
840
- await expect(
841
- t.query(api.billing.queries.listSubscriptions, {
842
- // @ts-expect-error — invalid status must be rejected by the validator
843
- status: "not_a_real_status",
844
- }),
845
- ).rejects.toThrow(/Validator error/);
846
- });
847
-
848
- it("respects limit", async () => {
849
- const t = convexTest(schema, modules);
850
-
851
- for (let i = 0; i < 5; i++) {
852
- await t.mutation(api.billing.mutations.upsertSubscription, {
853
- stripeSubscriptionId: `sub_limit_${i}`,
854
- userId: `user_limit_${i}`,
855
- status: "active",
856
- cancelAtPeriodEnd: false,
857
- isTrialing: false,
858
- });
859
- }
860
-
861
- const limited = await t.query(api.billing.queries.listSubscriptions, {
862
- limit: 2,
863
- });
864
-
865
- expect(limited).toHaveLength(2);
866
- });
867
-
868
- it("filters by accountId", async () => {
869
- const t = convexTest(schema, modules);
870
-
871
- await t.mutation(api.billing.mutations.upsertSubscription, {
872
- stripeSubscriptionId: "sub_acct_a1",
873
- accountId: "acct_sub_a",
874
- userId: "user_sub_acct_a",
875
- status: "active",
876
- cancelAtPeriodEnd: false,
877
- isTrialing: false,
878
- });
879
-
880
- await t.mutation(api.billing.mutations.upsertSubscription, {
881
- stripeSubscriptionId: "sub_acct_a2",
882
- accountId: "acct_sub_a",
883
- userId: "user_sub_acct_a",
884
- status: "canceled",
885
- cancelAtPeriodEnd: false,
886
- isTrialing: false,
887
- });
888
-
889
- await t.mutation(api.billing.mutations.upsertSubscription, {
890
- stripeSubscriptionId: "sub_acct_b1",
891
- accountId: "acct_sub_b",
892
- userId: "user_sub_acct_b",
893
- status: "active",
894
- cancelAtPeriodEnd: false,
895
- isTrialing: false,
896
- });
897
-
898
- const subs = await t.query(api.billing.queries.listSubscriptions, {
899
- accountId: "acct_sub_a",
900
- });
901
-
902
- expect(subs).toHaveLength(2);
903
- for (const sub of subs) {
904
- expect(sub.accountId).toBe("acct_sub_a");
905
- }
906
-
907
- const statusFiltered = await t.query(
908
- api.billing.queries.listSubscriptions,
909
- {
910
- accountId: "acct_sub_a",
911
- status: "active",
912
- },
913
- );
914
-
915
- expect(statusFiltered).toHaveLength(1);
916
- expect(statusFiltered[0].stripeSubscriptionId).toBe("sub_acct_a1");
917
- });
918
- });
919
-
920
- describe("billing — listSubscriptionsByOrg", () => {
921
- it("returns subscriptions for the given org", async () => {
922
- const t = convexTest(schema, modules);
923
-
924
- await t.mutation(api.billing.mutations.upsertSubscription, {
925
- stripeSubscriptionId: "sub_org_a",
926
- userId: "user_org_a",
927
- orgId: "org_a",
928
- status: "active",
929
- cancelAtPeriodEnd: false,
930
- isTrialing: false,
931
- });
932
-
933
- await t.mutation(api.billing.mutations.upsertSubscription, {
934
- stripeSubscriptionId: "sub_org_b",
935
- userId: "user_org_b",
936
- orgId: "org_b",
937
- status: "active",
938
- cancelAtPeriodEnd: false,
939
- isTrialing: false,
940
- });
941
-
942
- const orgASubs = await t.query(api.billing.queries.listSubscriptionsByOrg, {
943
- orgId: "org_a",
944
- });
945
-
946
- expect(orgASubs).toHaveLength(1);
947
- expect(orgASubs[0].stripeSubscriptionId).toBe("sub_org_a");
948
- });
949
-
950
- it("filters by status within org", async () => {
951
- const t = convexTest(schema, modules);
952
-
953
- await t.mutation(api.billing.mutations.upsertSubscription, {
954
- stripeSubscriptionId: "sub_org_active",
955
- userId: "user_x",
956
- orgId: "org_x",
957
- status: "active",
958
- cancelAtPeriodEnd: false,
959
- isTrialing: false,
960
- });
961
-
962
- await t.mutation(api.billing.mutations.upsertSubscription, {
963
- stripeSubscriptionId: "sub_org_canceled",
964
- userId: "user_x",
965
- orgId: "org_x",
966
- status: "canceled",
967
- cancelAtPeriodEnd: false,
968
- isTrialing: false,
969
- });
970
-
971
- const active = await t.query(api.billing.queries.listSubscriptionsByOrg, {
972
- orgId: "org_x",
973
- status: "active",
974
- });
975
-
976
- expect(active).toHaveLength(1);
977
- expect(active[0].status).toBe("active");
978
- });
979
- });
980
-
981
- describe("billing — getActiveSubscription with orgId", () => {
982
- it("finds active subscription by orgId", async () => {
983
- const t = convexTest(schema, modules);
984
-
985
- await t.mutation(api.billing.mutations.upsertSubscription, {
986
- stripeSubscriptionId: "sub_org_act",
987
- userId: "user_oa",
988
- orgId: "org_act",
989
- status: "active",
990
- cancelAtPeriodEnd: false,
991
- isTrialing: false,
992
- });
993
-
994
- const sub = await t.query(api.billing.queries.getActiveSubscription, {
995
- userId: "user_oa",
996
- orgId: "org_act",
997
- });
998
-
999
- expect(sub).not.toBeNull();
1000
- expect(sub!.stripeSubscriptionId).toBe("sub_org_act");
1001
- });
1002
-
1003
- it("finds trialing subscription as active", async () => {
1004
- const t = convexTest(schema, modules);
1005
-
1006
- await t.mutation(api.billing.mutations.upsertSubscription, {
1007
- stripeSubscriptionId: "sub_trial_act",
1008
- userId: "user_trial_act",
1009
- status: "trialing",
1010
- cancelAtPeriodEnd: false,
1011
- isTrialing: true,
1012
- });
1013
-
1014
- const sub = await t.query(api.billing.queries.getActiveSubscription, {
1015
- userId: "user_trial_act",
1016
- });
1017
-
1018
- expect(sub).not.toBeNull();
1019
- expect(sub!.status).toBe("trialing");
1020
- });
1021
-
1022
- it("returns null when no active subscription exists", async () => {
1023
- const t = convexTest(schema, modules);
1024
-
1025
- await t.mutation(api.billing.mutations.upsertSubscription, {
1026
- stripeSubscriptionId: "sub_canceled_only",
1027
- userId: "user_canceled",
1028
- status: "canceled",
1029
- cancelAtPeriodEnd: false,
1030
- isTrialing: false,
1031
- });
1032
-
1033
- const sub = await t.query(api.billing.queries.getActiveSubscription, {
1034
- userId: "user_canceled",
1035
- });
1036
-
1037
- expect(sub).toBeNull();
1038
- });
1039
- });
1040
-
1041
- describe("billing — listCheckoutSessionsByUser", () => {
1042
- it("lists sessions for the given user", async () => {
1043
- const t = convexTest(schema, modules);
1044
-
1045
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
1046
- stripeSessionId: "cs_u1_a",
1047
- userId: "user_cs_1",
1048
- mode: "subscription",
1049
- status: "complete",
1050
- });
1051
-
1052
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
1053
- stripeSessionId: "cs_u1_b",
1054
- userId: "user_cs_1",
1055
- mode: "payment",
1056
- status: "open",
1057
- });
1058
-
1059
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
1060
- stripeSessionId: "cs_u2",
1061
- userId: "user_cs_2",
1062
- mode: "subscription",
1063
- status: "open",
1064
- });
1065
-
1066
- const sessions = await t.query(
1067
- api.billing.queries.listCheckoutSessionsByUser,
1068
- { userId: "user_cs_1" },
1069
- );
1070
-
1071
- expect(sessions).toHaveLength(2);
1072
- });
1073
-
1074
- it("filters by status", async () => {
1075
- const t = convexTest(schema, modules);
1076
-
1077
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
1078
- stripeSessionId: "cs_filter_open",
1079
- userId: "user_filter",
1080
- mode: "subscription",
1081
- status: "open",
1082
- });
1083
-
1084
- await t.mutation(api.billing.mutations.upsertCheckoutSession, {
1085
- stripeSessionId: "cs_filter_complete",
1086
- userId: "user_filter",
1087
- mode: "subscription",
1088
- status: "complete",
1089
- });
1090
-
1091
- const open = await t.query(api.billing.queries.listCheckoutSessionsByUser, {
1092
- userId: "user_filter",
1093
- status: "open",
1094
- });
1095
-
1096
- expect(open).toHaveLength(1);
1097
- expect(open[0].status).toBe("open");
1098
- });
1099
- });
1100
-
1101
- describe("billing — listInvoices with filters", () => {
1102
- it("filters by subscriptionId", async () => {
1103
- const t = convexTest(schema, modules);
1104
-
1105
- await t.mutation(api.billing.mutations.upsertInvoice, {
1106
- stripeInvoiceId: "inv_sub_a",
1107
- userId: "user_inv",
1108
- subscriptionId: "sub_inv_a",
1109
- status: "paid",
1110
- currency: "usd",
1111
- amountDue: 1000,
1112
- amountPaid: 1000,
1113
- });
1114
-
1115
- await t.mutation(api.billing.mutations.upsertInvoice, {
1116
- stripeInvoiceId: "inv_sub_b",
1117
- userId: "user_inv",
1118
- subscriptionId: "sub_inv_b",
1119
- status: "paid",
1120
- currency: "usd",
1121
- amountDue: 2000,
1122
- amountPaid: 2000,
1123
- });
1124
-
1125
- const invoices = await t.query(api.billing.queries.listInvoices, {
1126
- subscriptionId: "sub_inv_a",
1127
- });
1128
-
1129
- expect(invoices).toHaveLength(1);
1130
- expect(invoices[0].stripeInvoiceId).toBe("inv_sub_a");
1131
- });
1132
-
1133
- it("filters by status", async () => {
1134
- const t = convexTest(schema, modules);
1135
-
1136
- await t.mutation(api.billing.mutations.upsertInvoice, {
1137
- stripeInvoiceId: "inv_st_paid",
1138
- userId: "user_st",
1139
- status: "paid",
1140
- currency: "usd",
1141
- amountDue: 1000,
1142
- amountPaid: 1000,
1143
- });
1144
-
1145
- await t.mutation(api.billing.mutations.upsertInvoice, {
1146
- stripeInvoiceId: "inv_st_open",
1147
- userId: "user_st",
1148
- status: "open",
1149
- currency: "usd",
1150
- amountDue: 2000,
1151
- amountPaid: 0,
1152
- });
1153
-
1154
- const paidOnly = await t.query(api.billing.queries.listInvoices, {
1155
- userId: "user_st",
1156
- status: "paid",
1157
- });
1158
-
1159
- expect(paidOnly).toHaveLength(1);
1160
- expect(paidOnly[0].status).toBe("paid");
1161
- });
1162
-
1163
- it("filters by accountId", async () => {
1164
- const t = convexTest(schema, modules);
1165
-
1166
- await t.mutation(api.billing.mutations.upsertInvoice, {
1167
- stripeInvoiceId: "inv_acct_a1",
1168
- userId: "user_acct_a",
1169
- accountId: "acct_inv_a",
1170
- status: "paid",
1171
- currency: "usd",
1172
- amountDue: 1000,
1173
- amountPaid: 1000,
1174
- });
1175
-
1176
- await t.mutation(api.billing.mutations.upsertInvoice, {
1177
- stripeInvoiceId: "inv_acct_a2",
1178
- userId: "user_acct_a",
1179
- accountId: "acct_inv_a",
1180
- status: "open",
1181
- currency: "usd",
1182
- amountDue: 2000,
1183
- amountPaid: 0,
1184
- });
1185
-
1186
- await t.mutation(api.billing.mutations.upsertInvoice, {
1187
- stripeInvoiceId: "inv_acct_b1",
1188
- userId: "user_acct_b",
1189
- accountId: "acct_inv_b",
1190
- status: "paid",
1191
- currency: "usd",
1192
- amountDue: 3000,
1193
- amountPaid: 3000,
1194
- });
1195
-
1196
- const invoices = await t.query(api.billing.queries.listInvoices, {
1197
- accountId: "acct_inv_a",
1198
- });
1199
-
1200
- expect(invoices).toHaveLength(2);
1201
- for (const invoice of invoices) {
1202
- expect(invoice.accountId).toBe("acct_inv_a");
1203
- }
1204
-
1205
- const statusFiltered = await t.query(api.billing.queries.listInvoices, {
1206
- accountId: "acct_inv_a",
1207
- status: "paid",
1208
- });
1209
-
1210
- expect(statusFiltered).toHaveLength(1);
1211
- expect(statusFiltered[0].stripeInvoiceId).toBe("inv_acct_a1");
1212
- });
1213
- });
1214
-
1215
- describe("billing — subscription backfills orphaned invoices", () => {
1216
- it("upsertSubscription patches orphaned invoices with userId", async () => {
1217
- const t = convexTest(schema, modules);
1218
-
1219
- // Insert an invoice linked to a subscription but without userId
1220
- await t.run(async (ctx) => {
1221
- await ctx.db.insert("invoices", {
1222
- stripeInvoiceId: "inv_orphan",
1223
- userId: "",
1224
- subscriptionId: "sub_backfill",
1225
- status: "paid",
1226
- currency: "usd",
1227
- amountDue: 3000,
1228
- amountPaid: 3000,
1229
- });
1230
- });
1231
-
1232
- // Now upsert the subscription — should backfill the invoice
1233
- await t.mutation(api.billing.mutations.upsertSubscription, {
1234
- stripeSubscriptionId: "sub_backfill",
1235
- userId: "user_backfill",
1236
- status: "active",
1237
- cancelAtPeriodEnd: false,
1238
- isTrialing: false,
1239
- });
1240
-
1241
- const invoices = await t.query(api.billing.queries.listInvoices, {
1242
- userId: "user_backfill",
1243
- });
1244
-
1245
- expect(invoices).toHaveLength(1);
1246
- expect(invoices[0].stripeInvoiceId).toBe("inv_orphan");
1247
- });
1248
- });
1249
-
1250
- // =============================================================================
1251
- // CONNECT — payment and payout mutations and queries
1252
- // =============================================================================
1253
-
1254
- describe("connect — payment mutations and queries", () => {
1255
- it("upsertPayment inserts new payment", async () => {
1256
- const t = convexTest(schema, modules);
1257
-
1258
- await t.mutation(api.connect.mutations.upsertPayment, {
1259
- stripePaymentIntentId: "pi_001",
1260
- userId: "user_pay_001",
1261
- amount: 5000,
1262
- currency: "usd",
1263
- status: "succeeded",
1264
- });
1265
-
1266
- const payments = await t.run(async (ctx) => {
1267
- return await ctx.db.query("payments").collect();
1268
- });
1269
-
1270
- expect(payments).toHaveLength(1);
1271
- expect(payments[0]).toMatchObject({
1272
- stripePaymentIntentId: "pi_001",
1273
- amount: 5000,
1274
- status: "succeeded",
1275
- });
1276
- });
1277
-
1278
- it("upsertPayment updates existing payment by stripePaymentIntentId", async () => {
1279
- const t = convexTest(schema, modules);
1280
-
1281
- await t.mutation(api.connect.mutations.upsertPayment, {
1282
- stripePaymentIntentId: "pi_002",
1283
- userId: "user_pay_002",
1284
- amount: 3000,
1285
- currency: "usd",
1286
- status: "processing",
1287
- });
1288
-
1289
- await t.mutation(api.connect.mutations.upsertPayment, {
1290
- stripePaymentIntentId: "pi_002",
1291
- userId: "user_pay_002",
1292
- amount: 3000,
1293
- currency: "usd",
1294
- status: "succeeded",
1295
- });
1296
-
1297
- const payments = await t.run(async (ctx) => {
1298
- return await ctx.db.query("payments").collect();
1299
- });
1300
-
1301
- expect(payments).toHaveLength(1);
1302
- expect(payments[0].status).toBe("succeeded");
1303
- });
1304
-
1305
- it("getPaymentByStripeId: returns matching payment", async () => {
1306
- const t = convexTest(schema, modules);
1307
-
1308
- await t.mutation(api.connect.mutations.upsertPayment, {
1309
- stripePaymentIntentId: "pi_by_stripe_001",
1310
- userId: "user_pay_003",
1311
- amount: 4200,
1312
- currency: "usd",
1313
- status: "succeeded",
1314
- });
1315
-
1316
- const payment = await t.query(api.connect.queries.getPaymentByStripeId, {
1317
- stripePaymentIntentId: "pi_by_stripe_001",
1318
- });
1319
-
1320
- expect(payment).not.toBeNull();
1321
- expect(payment!.stripePaymentIntentId).toBe("pi_by_stripe_001");
1322
- expect(payment!.userId).toBe("user_pay_003");
1323
- expect(payment!.amount).toBe(4200);
1324
- });
1325
-
1326
- it("getPaymentByStripeId: returns null for unknown id", async () => {
1327
- const t = convexTest(schema, modules);
1328
-
1329
- const payment = await t.query(api.connect.queries.getPaymentByStripeId, {
1330
- stripePaymentIntentId: "pi_does_not_exist",
1331
- });
1332
-
1333
- expect(payment).toBeNull();
1334
- });
1335
- });
1336
-
1337
- describe("connect — payout mutations and queries", () => {
1338
- it("upsertPayout + getPayout round trip", async () => {
1339
- const t = convexTest(schema, modules);
1340
-
1341
- await t.mutation(api.connect.mutations.upsertPayout, {
1342
- stripePayoutId: "po_001",
1343
- accountId: "acct_po_001",
1344
- amount: 10000,
1345
- currency: "usd",
1346
- status: "pending",
1347
- });
1348
-
1349
- const payouts = await t.run(async (ctx) => {
1350
- return await ctx.db.query("payouts").collect();
1351
- });
1352
-
1353
- expect(payouts).toHaveLength(1);
1354
-
1355
- const payout = await t.query(api.connect.queries.getPayout, {
1356
- payoutId: payouts[0]._id,
1357
- });
1358
-
1359
- expect(payout).toMatchObject({
1360
- stripePayoutId: "po_001",
1361
- amount: 10000,
1362
- status: "pending",
1363
- });
1364
- });
1365
-
1366
- it("upsertPayout updates existing payout", async () => {
1367
- const t = convexTest(schema, modules);
1368
-
1369
- await t.mutation(api.connect.mutations.upsertPayout, {
1370
- stripePayoutId: "po_002",
1371
- accountId: "acct_po_002",
1372
- amount: 7500,
1373
- currency: "usd",
1374
- status: "pending",
1375
- });
1376
-
1377
- await t.mutation(api.connect.mutations.upsertPayout, {
1378
- stripePayoutId: "po_002",
1379
- accountId: "acct_po_002",
1380
- amount: 7500,
1381
- currency: "usd",
1382
- status: "paid",
1383
- arrivalDate: "2030-01-15",
1384
- });
1385
-
1386
- const payouts = await t.run(async (ctx) => {
1387
- return await ctx.db.query("payouts").collect();
1388
- });
1389
-
1390
- expect(payouts).toHaveLength(1);
1391
- expect(payouts[0].status).toBe("paid");
1392
- expect(payouts[0].arrivalDate).toBe("2030-01-15");
1393
- });
1394
-
1395
- it("listPayouts: filters by accountId", async () => {
1396
- const t = convexTest(schema, modules);
1397
-
1398
- await t.mutation(api.connect.mutations.upsertPayout, {
1399
- stripePayoutId: "po_acct_a",
1400
- accountId: "acct_a",
1401
- amount: 1000,
1402
- currency: "usd",
1403
- status: "paid",
1404
- });
1405
-
1406
- await t.mutation(api.connect.mutations.upsertPayout, {
1407
- stripePayoutId: "po_acct_b",
1408
- accountId: "acct_b",
1409
- amount: 2000,
1410
- currency: "usd",
1411
- status: "paid",
1412
- });
1413
-
1414
- const payouts = await t.query(api.connect.queries.listPayouts, {
1415
- accountId: "acct_a",
1416
- });
1417
-
1418
- expect(payouts).toHaveLength(1);
1419
- expect(payouts[0].stripePayoutId).toBe("po_acct_a");
1420
- });
1421
-
1422
- it("listPayouts: filters by status", async () => {
1423
- const t = convexTest(schema, modules);
1424
-
1425
- await t.mutation(api.connect.mutations.upsertPayout, {
1426
- stripePayoutId: "po_pending",
1427
- accountId: "acct_st",
1428
- amount: 500,
1429
- currency: "usd",
1430
- status: "pending",
1431
- });
1432
-
1433
- await t.mutation(api.connect.mutations.upsertPayout, {
1434
- stripePayoutId: "po_paid",
1435
- accountId: "acct_st",
1436
- amount: 1500,
1437
- currency: "usd",
1438
- status: "paid",
1439
- });
1440
-
1441
- const pending = await t.query(api.connect.queries.listPayouts, {
1442
- status: "pending",
1443
- });
1444
-
1445
- expect(pending).toHaveLength(1);
1446
- expect(pending[0].stripePayoutId).toBe("po_pending");
1447
- });
1448
-
1449
- it("listPayouts: returns all when no filter", async () => {
1450
- const t = convexTest(schema, modules);
1451
-
1452
- await t.mutation(api.connect.mutations.upsertPayout, {
1453
- stripePayoutId: "po_all_1",
1454
- accountId: "acct_all",
1455
- amount: 100,
1456
- currency: "usd",
1457
- status: "pending",
1458
- });
1459
-
1460
- await t.mutation(api.connect.mutations.upsertPayout, {
1461
- stripePayoutId: "po_all_2",
1462
- accountId: "acct_all",
1463
- amount: 200,
1464
- currency: "eur",
1465
- status: "paid",
1466
- });
1467
-
1468
- const all = await t.query(api.connect.queries.listPayouts, {});
1469
-
1470
- expect(all).toHaveLength(2);
1471
- });
1472
-
1473
- it("getPayoutByStripeId: returns matching payout", async () => {
1474
- const t = convexTest(schema, modules);
1475
-
1476
- await t.mutation(api.connect.mutations.upsertPayout, {
1477
- stripePayoutId: "po_by_stripe_001",
1478
- accountId: "acct_po_stripe",
1479
- amount: 8800,
1480
- currency: "usd",
1481
- status: "paid",
1482
- });
1483
-
1484
- const payout = await t.query(api.connect.queries.getPayoutByStripeId, {
1485
- stripePayoutId: "po_by_stripe_001",
1486
- });
1487
-
1488
- expect(payout).not.toBeNull();
1489
- expect(payout!.stripePayoutId).toBe("po_by_stripe_001");
1490
- expect(payout!.accountId).toBe("acct_po_stripe");
1491
- expect(payout!.amount).toBe(8800);
1492
- });
1493
-
1494
- it("getPayoutByStripeId: returns null for unknown id", async () => {
1495
- const t = convexTest(schema, modules);
1496
-
1497
- const payout = await t.query(api.connect.queries.getPayoutByStripeId, {
1498
- stripePayoutId: "po_does_not_exist",
1499
- });
1500
-
1501
- expect(payout).toBeNull();
1502
- });
1503
- });
1504
-
1505
- // =============================================================================
1506
- // WEBHOOKS — listWebhookEvents with filters
1507
- // =============================================================================
1508
-
1509
- describe("webhooks — listWebhookEvents", () => {
1510
- it("returns all events in descending order", async () => {
1511
- const t = convexTest(schema, modules);
1512
-
1513
- await t.run(async (ctx) => {
1514
- await ctx.db.insert("webhookEvents", {
1515
- stripeEventId: "evt_list_1",
1516
- eventType: "invoice.paid",
1517
- status: "processed",
1518
- processedAt: Date.now() - 1000,
1519
- });
1520
- await ctx.db.insert("webhookEvents", {
1521
- stripeEventId: "evt_list_2",
1522
- eventType: "checkout.session.completed",
1523
- status: "processed",
1524
- processedAt: Date.now(),
1525
- });
1526
- });
1527
-
1528
- const events = await t.query(api.webhooks.queries.listWebhookEvents, {});
1529
-
1530
- expect(events).toHaveLength(2);
1531
- // Most recent first
1532
- expect(events[0].stripeEventId).toBe("evt_list_2");
1533
- });
1534
-
1535
- it("filters by eventType", async () => {
1536
- const t = convexTest(schema, modules);
1537
-
1538
- await t.run(async (ctx) => {
1539
- await ctx.db.insert("webhookEvents", {
1540
- stripeEventId: "evt_type_1",
1541
- eventType: "invoice.paid",
1542
- status: "processed",
1543
- processedAt: Date.now(),
1544
- });
1545
- await ctx.db.insert("webhookEvents", {
1546
- stripeEventId: "evt_type_2",
1547
- eventType: "checkout.session.completed",
1548
- status: "processed",
1549
- processedAt: Date.now(),
1550
- });
1551
- });
1552
-
1553
- const invoiceEvents = await t.query(
1554
- api.webhooks.queries.listWebhookEvents,
1555
- {
1556
- eventType: "invoice.paid",
1557
- },
1558
- );
1559
-
1560
- expect(invoiceEvents).toHaveLength(1);
1561
- expect(invoiceEvents[0].eventType).toBe("invoice.paid");
1562
- });
1563
-
1564
- it("filters by status", async () => {
1565
- const t = convexTest(schema, modules);
1566
-
1567
- await t.run(async (ctx) => {
1568
- await ctx.db.insert("webhookEvents", {
1569
- stripeEventId: "evt_st_1",
1570
- eventType: "invoice.paid",
1571
- status: "processed",
1572
- processedAt: Date.now(),
1573
- });
1574
- await ctx.db.insert("webhookEvents", {
1575
- stripeEventId: "evt_st_2",
1576
- eventType: "invoice.paid",
1577
- status: "failed",
1578
- processedAt: Date.now(),
1579
- lastError: "Something went wrong",
1580
- });
1581
- });
1582
-
1583
- const failed = await t.query(api.webhooks.queries.listWebhookEvents, {
1584
- status: "failed",
1585
- });
1586
-
1587
- expect(failed).toHaveLength(1);
1588
- expect(failed[0].stripeEventId).toBe("evt_st_2");
1589
- });
1590
-
1591
- it("combines eventType and status filters", async () => {
1592
- const t = convexTest(schema, modules);
1593
-
1594
- await t.run(async (ctx) => {
1595
- await ctx.db.insert("webhookEvents", {
1596
- stripeEventId: "evt_combo_1",
1597
- eventType: "invoice.paid",
1598
- status: "processed",
1599
- processedAt: Date.now(),
1600
- });
1601
- await ctx.db.insert("webhookEvents", {
1602
- stripeEventId: "evt_combo_2",
1603
- eventType: "invoice.paid",
1604
- status: "failed",
1605
- processedAt: Date.now(),
1606
- });
1607
- await ctx.db.insert("webhookEvents", {
1608
- stripeEventId: "evt_combo_3",
1609
- eventType: "checkout.session.completed",
1610
- status: "failed",
1611
- processedAt: Date.now(),
1612
- });
1613
- });
1614
-
1615
- const result = await t.query(api.webhooks.queries.listWebhookEvents, {
1616
- eventType: "invoice.paid",
1617
- status: "failed",
1618
- });
1619
-
1620
- expect(result).toHaveLength(1);
1621
- expect(result[0].stripeEventId).toBe("evt_combo_2");
1622
- });
1623
- });
1624
-
1625
- // =============================================================================
1626
- // REGRESSION: filter-after-take completeness (plan 002)
1627
- // =============================================================================
1628
-
1629
- describe("regression — listSubscriptions returns complete results beyond limit", () => {
1630
- it("returns all active subscriptions even when canceled ones fill the default limit", async () => {
1631
- const t = convexTest(schema, modules);
1632
- const accountId = "acct_regression_sub";
1633
-
1634
- // Insert 55 canceled then 5 active subscriptions for the same accountId.
1635
- // Old code: take(50) → JS filter → returns 0 active. New code: compound index → 5.
1636
- for (let i = 0; i < 55; i++) {
1637
- await t.mutation(api.billing.mutations.upsertSubscription, {
1638
- stripeSubscriptionId: `sub_canceled_${i}`,
1639
- accountId,
1640
- userId: "user_regression_sub",
1641
- status: "canceled",
1642
- cancelAtPeriodEnd: false,
1643
- isTrialing: false,
1644
- });
1645
- }
1646
- for (let i = 0; i < 5; i++) {
1647
- await t.mutation(api.billing.mutations.upsertSubscription, {
1648
- stripeSubscriptionId: `sub_active_${i}`,
1649
- accountId,
1650
- userId: "user_regression_sub",
1651
- status: "active",
1652
- cancelAtPeriodEnd: false,
1653
- isTrialing: false,
1654
- });
1655
- }
1656
-
1657
- const result = await t.query(api.billing.queries.listSubscriptions, {
1658
- accountId,
1659
- status: "active",
1660
- });
1661
-
1662
- expect(result).toHaveLength(5);
1663
- expect(result.every((s) => s.status === "active")).toBe(true);
1664
- });
1665
-
1666
- it("respects limit when filtering by status via compound index", async () => {
1667
- const t = convexTest(schema, modules);
1668
- const accountId = "acct_regression_sub_limit";
1669
-
1670
- for (let i = 0; i < 60; i++) {
1671
- await t.mutation(api.billing.mutations.upsertSubscription, {
1672
- stripeSubscriptionId: `sub_lim_active_${i}`,
1673
- accountId,
1674
- userId: "user_regression_sub_limit",
1675
- status: "active",
1676
- cancelAtPeriodEnd: false,
1677
- isTrialing: false,
1678
- });
1679
- }
1680
-
1681
- const result = await t.query(api.billing.queries.listSubscriptions, {
1682
- accountId,
1683
- status: "active",
1684
- limit: 10,
1685
- });
1686
-
1687
- expect(result).toHaveLength(10);
1688
- });
1689
- });
1690
-
1691
- describe("regression — listInvoices returns complete results beyond limit (userId branch)", () => {
1692
- it("returns all paid invoices even when other statuses fill the default limit", async () => {
1693
- const t = convexTest(schema, modules);
1694
- const userId = "user_regression_inv";
1695
-
1696
- // Insert 55 open then 5 paid invoices for the same userId.
1697
- for (let i = 0; i < 55; i++) {
1698
- await t.mutation(api.billing.mutations.upsertInvoice, {
1699
- stripeInvoiceId: `inv_open_${i}`,
1700
- userId,
1701
- status: "open",
1702
- currency: "usd",
1703
- amountDue: 1000,
1704
- amountPaid: 0,
1705
- });
1706
- }
1707
- for (let i = 0; i < 5; i++) {
1708
- await t.mutation(api.billing.mutations.upsertInvoice, {
1709
- stripeInvoiceId: `inv_paid_${i}`,
1710
- userId,
1711
- status: "paid",
1712
- currency: "usd",
1713
- amountDue: 1000,
1714
- amountPaid: 1000,
1715
- });
1716
- }
1717
-
1718
- const result = await t.query(api.billing.queries.listInvoices, {
1719
- userId,
1720
- status: "paid",
1721
- });
1722
-
1723
- expect(result).toHaveLength(5);
1724
- expect(result.every((i) => i.status === "paid")).toBe(true);
1725
- });
1726
- });
1727
-
1728
- describe("regression — listProducts returns complete results beyond limit", () => {
1729
- it("returns all inactive products even when active ones fill the default limit", async () => {
1730
- const t = convexTest(schema, modules);
1731
- const accountId = "acct_regression_prod";
1732
-
1733
- // Insert 55 active then 5 inactive products for the same accountId.
1734
- for (let i = 0; i < 55; i++) {
1735
- await t.mutation(api.products.mutations.upsertProduct, {
1736
- stripeProductId: `prod_active_${i}`,
1737
- accountId,
1738
- name: `Active Product ${i}`,
1739
- active: true,
1740
- });
1741
- }
1742
- for (let i = 0; i < 5; i++) {
1743
- await t.mutation(api.products.mutations.upsertProduct, {
1744
- stripeProductId: `prod_inactive_${i}`,
1745
- accountId,
1746
- name: `Inactive Product ${i}`,
1747
- active: false,
1748
- });
1749
- }
1750
-
1751
- const result = await t.query(api.products.queries.listProducts, {
1752
- accountId,
1753
- active: false,
1754
- });
1755
-
1756
- // Old code: take(50) → JS filter on active===false → returns 0. New: compound index → 5.
1757
- expect(result).toHaveLength(5);
1758
- expect(result.every((p) => p.active === false)).toBe(true);
1759
- });
1760
- });
1761
-
1762
- describe("guard — empty userId/orgId never matches user-scoped queries", () => {
1763
- it("getActiveSubscription({ userId: '' }) returns null even when an unattributed row exists", async () => {
1764
- const t = convexTest(schema, modules);
1765
-
1766
- // Insert an unattributed subscription (the sentinel row written by webhook processors).
1767
- await t.mutation(api.billing.mutations.upsertSubscription, {
1768
- stripeSubscriptionId: "sub_unattr_001",
1769
- userId: "",
1770
- status: "active",
1771
- cancelAtPeriodEnd: false,
1772
- isTrialing: false,
1773
- });
1774
-
1775
- const result = await t.query(api.billing.queries.getActiveSubscription, {
1776
- userId: "",
1777
- });
1778
-
1779
- expect(result).toBeNull();
1780
- });
1781
-
1782
- it("listSubscriptionsByUser({ userId: '' }) returns [] even when an unattributed row exists", async () => {
1783
- const t = convexTest(schema, modules);
1784
-
1785
- await t.mutation(api.billing.mutations.upsertSubscription, {
1786
- stripeSubscriptionId: "sub_unattr_002",
1787
- userId: "",
1788
- status: "active",
1789
- cancelAtPeriodEnd: false,
1790
- isTrialing: false,
1791
- });
1792
-
1793
- const result = await t.query(api.billing.queries.listSubscriptionsByUser, {
1794
- userId: "",
1795
- });
1796
-
1797
- expect(result).toEqual([]);
1798
- });
1799
-
1800
- it("listSubscriptionsByUser({ userId: 'user_1' }) returns only the user_1 row, not the '' row", async () => {
1801
- const t = convexTest(schema, modules);
1802
-
1803
- // Insert one unattributed and one attributed subscription.
1804
- await t.mutation(api.billing.mutations.upsertSubscription, {
1805
- stripeSubscriptionId: "sub_unattr_003",
1806
- userId: "",
1807
- status: "active",
1808
- cancelAtPeriodEnd: false,
1809
- isTrialing: false,
1810
- });
1811
- await t.mutation(api.billing.mutations.upsertSubscription, {
1812
- stripeSubscriptionId: "sub_user1_001",
1813
- userId: "user_1",
1814
- status: "active",
1815
- cancelAtPeriodEnd: false,
1816
- isTrialing: false,
1817
- });
1818
-
1819
- const result = await t.query(api.billing.queries.listSubscriptionsByUser, {
1820
- userId: "user_1",
1821
- });
1822
-
1823
- expect(result).toHaveLength(1);
1824
- expect(result[0].stripeSubscriptionId).toBe("sub_user1_001");
1825
- });
1826
-
1827
- it("listInvoices({ userId: '' }) falls through to the unfiltered branch", async () => {
1828
- const t = convexTest(schema, modules);
1829
-
1830
- // Insert one unattributed invoice and one attributed invoice.
1831
- await t.mutation(api.billing.mutations.upsertInvoice, {
1832
- stripeInvoiceId: "inv_unattr_001",
1833
- userId: "",
1834
- status: "paid",
1835
- currency: "usd",
1836
- amountDue: 1000,
1837
- amountPaid: 1000,
1838
- });
1839
- await t.mutation(api.billing.mutations.upsertInvoice, {
1840
- stripeInvoiceId: "inv_user2_001",
1841
- userId: "user_2",
1842
- status: "paid",
1843
- currency: "usd",
1844
- amountDue: 2000,
1845
- amountPaid: 2000,
1846
- });
1847
-
1848
- // With userId: "" the guard causes fallthrough to the unfiltered take — both rows should appear.
1849
- const result = await t.query(api.billing.queries.listInvoices, {
1850
- userId: "",
1851
- });
1852
-
1853
- expect(result.length).toBeGreaterThanOrEqual(2);
1854
- const ids = result.map((i) => i.stripeInvoiceId);
1855
- expect(ids).toContain("inv_unattr_001");
1856
- expect(ids).toContain("inv_user2_001");
1857
- });
1858
- });