@fantastic.dev/better-stripe 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/MIGRATION.md +6 -0
  3. package/README.md +7 -1
  4. package/dist/client/connect/payoutSnapshot.d.ts +2 -0
  5. package/dist/client/connect/payoutSnapshot.d.ts.map +1 -1
  6. package/dist/client/connect/payoutSnapshot.js +2 -0
  7. package/dist/client/connect/payoutSnapshot.js.map +1 -1
  8. package/dist/client/index.d.ts +3 -3
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +3 -3
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/readContracts.d.ts +50 -0
  13. package/dist/client/readContracts.d.ts.map +1 -0
  14. package/dist/client/readContracts.js +24 -0
  15. package/dist/client/readContracts.js.map +1 -0
  16. package/dist/client/types/documents.d.ts +2 -0
  17. package/dist/client/types/documents.d.ts.map +1 -1
  18. package/dist/client/webhooks/processors.js +2 -0
  19. package/dist/client/webhooks/processors.js.map +1 -1
  20. package/dist/component/_generated/component.d.ts +177 -0
  21. package/dist/component/_generated/component.d.ts.map +1 -1
  22. package/dist/component/connect/mutations.d.ts +2 -0
  23. package/dist/component/connect/mutations.d.ts.map +1 -1
  24. package/dist/component/connect/mutations.js +8 -8
  25. package/dist/component/connect/mutations.js.map +1 -1
  26. package/dist/component/connect/queries.d.ts +102 -2
  27. package/dist/component/connect/queries.d.ts.map +1 -1
  28. package/dist/component/connect/queries.js +88 -45
  29. package/dist/component/connect/queries.js.map +1 -1
  30. package/dist/component/connect/schema.d.ts +12 -2
  31. package/dist/component/connect/schema.d.ts.map +1 -1
  32. package/dist/component/connect/schema.js +10 -1
  33. package/dist/component/connect/schema.js.map +1 -1
  34. package/dist/component/connect/validators.d.ts +13 -2
  35. package/dist/component/connect/validators.d.ts.map +1 -1
  36. package/dist/component/connect/validators.js +4 -0
  37. package/dist/component/connect/validators.js.map +1 -1
  38. package/dist/component/earnings/legacyReads.d.ts +51 -0
  39. package/dist/component/earnings/legacyReads.d.ts.map +1 -0
  40. package/dist/component/earnings/legacyReads.js +43 -0
  41. package/dist/component/earnings/legacyReads.js.map +1 -0
  42. package/dist/component/earnings/mutations.d.ts +9 -0
  43. package/dist/component/earnings/mutations.d.ts.map +1 -0
  44. package/dist/component/earnings/mutations.js +23 -0
  45. package/dist/component/earnings/mutations.js.map +1 -0
  46. package/dist/component/earnings/reads.d.ts +14 -0
  47. package/dist/component/earnings/reads.d.ts.map +1 -0
  48. package/dist/component/earnings/reads.js +28 -0
  49. package/dist/component/earnings/reads.js.map +1 -0
  50. package/dist/component/earnings/schema.d.ts +20 -0
  51. package/dist/component/earnings/schema.d.ts.map +1 -0
  52. package/dist/component/earnings/schema.js +12 -0
  53. package/dist/component/earnings/schema.js.map +1 -0
  54. package/dist/component/earnings/triggers.d.ts +1290 -0
  55. package/dist/component/earnings/triggers.d.ts.map +1 -0
  56. package/dist/component/earnings/triggers.js +68 -0
  57. package/dist/component/earnings/triggers.js.map +1 -0
  58. package/dist/component/products/queries.d.ts +47 -0
  59. package/dist/component/products/queries.d.ts.map +1 -1
  60. package/dist/component/products/queries.js +59 -0
  61. package/dist/component/products/queries.js.map +1 -1
  62. package/dist/component/schema.d.ts +31 -2
  63. package/dist/component/schema.js +2 -0
  64. package/dist/component/schema.js.map +1 -1
  65. package/dist/react/components/EarningsSummary.d.ts +3 -1
  66. package/dist/react/components/EarningsSummary.d.ts.map +1 -1
  67. package/dist/react/components/EarningsSummary.js +3 -3
  68. package/dist/react/components/EarningsSummary.js.map +1 -1
  69. package/dist/react/hooks/useCurrencyEarnings.d.ts +31 -0
  70. package/dist/react/hooks/useCurrencyEarnings.d.ts.map +1 -0
  71. package/dist/react/hooks/useCurrencyEarnings.js +30 -0
  72. package/dist/react/hooks/useCurrencyEarnings.js.map +1 -0
  73. package/dist/react/index.d.ts +3 -0
  74. package/dist/react/index.d.ts.map +1 -1
  75. package/dist/react/index.js +3 -0
  76. package/dist/react/index.js.map +1 -1
  77. package/docs/react-workflows.md +6 -0
  78. package/docs/read-contracts.md +136 -0
  79. package/package.json +3 -2
  80. package/src/client/connect/payoutSnapshot.test.ts +27 -0
  81. package/src/client/connect/payoutSnapshot.ts +4 -0
  82. package/src/client/index.ts +4 -4
  83. package/src/client/readContracts.ts +90 -0
  84. package/src/client/readPagination.test.ts +62 -0
  85. package/src/client/types/documents.ts +2 -0
  86. package/src/client/webhooks/payout-canceled.integration.test.ts +25 -0
  87. package/src/client/webhooks/processors.ts +2 -0
  88. package/src/component/_generated/api.ts +8 -0
  89. package/src/component/_generated/component.ts +201 -0
  90. package/src/component/connect/mutations.ts +8 -8
  91. package/src/component/connect/queries.ts +110 -48
  92. package/src/component/connect/schema.ts +10 -1
  93. package/src/component/connect/validators.ts +4 -0
  94. package/src/component/currency-migration.test.ts +119 -0
  95. package/src/component/currency-totals.test.ts +95 -0
  96. package/src/component/earnings/legacyReads.ts +59 -0
  97. package/src/component/earnings/mutations.ts +21 -0
  98. package/src/component/earnings/reads.ts +41 -0
  99. package/src/component/earnings/schema.ts +11 -0
  100. package/src/component/earnings/triggers.ts +91 -0
  101. package/src/component/products/queries.ts +74 -0
  102. package/src/component/public.test.ts +1 -1
  103. package/src/component/read-pagination.test.ts +193 -0
  104. package/src/component/schema.ts +2 -0
  105. package/src/react/components/EarningsSummary.tsx +5 -2
  106. package/src/react/hooks/useCurrencyEarnings.test.ts +59 -0
  107. package/src/react/hooks/useCurrencyEarnings.ts +73 -0
  108. package/src/react/index.ts +12 -0
  109. package/src/react/read-contracts.render.test.tsx +20 -0
@@ -0,0 +1,136 @@
1
+ # Reactive history and currency totals
2
+
3
+ `BetterStripe.paginateProducts`, `paginatePrices`, and `paginatePayouts` read
4
+ webhook-synchronized component records. They return standard Convex
5
+ `{ page, isDone, continueCursor }` results. Pass `paginationOpts` with an opaque
6
+ `cursor` or `null` and an integer `numItems` between 1 and 100. These readers use
7
+ one indexed pagination call per invocation, ordered newest first. Existing array
8
+ methods remain available. Neither an array preview nor one cursor page is an
9
+ exact financial total.
10
+
11
+ Products support `accountId` and `active`. Prices support the component's
12
+ `productId` and `active`; this ID differs from `stripeProductId`. Authorize the
13
+ parent product before exposing price reads. Payout history requires `accountId`
14
+ and optionally accepts `status`. No filter means no restriction on that field.
15
+ An omitted product account filter includes all accounts, including platform
16
+ products. Host applications must derive allowed account and product scope from
17
+ the authenticated user. A client-supplied account ID is not authorization.
18
+
19
+ The Vite reference provides bindings in `example/convex/readContracts.ts` and
20
+ `example/src/lib/stripe-hooks.ts`. Its selectable personas are demo identities.
21
+ Production hosts must replace them with session authorization.
22
+
23
+ ## React pagination
24
+
25
+ Wrap the public client method in an authorized host Convex query with
26
+ `paginationOptsValidator` in its arguments. Return the package result unchanged.
27
+ Bind that query with `useComponentPaginatedQuery` from the package React export.
28
+ This uses the helper-compatible hook to pin end cursors when another page loads.
29
+ Native `convex/react` pagination does not pin component helper cursors and can
30
+ leave gaps when new rows arrive between loaded pages.
31
+
32
+ ```tsx
33
+ const products = useComponentPaginatedQuery(
34
+ api.catalog.paginateProducts,
35
+ {}, // Host derives account scope from the session.
36
+ { initialNumItems: 25 },
37
+ );
38
+ const manager = useProductManager({
39
+ scopeKey: authenticatedUser.id,
40
+ createProduct,
41
+ createPrice,
42
+ updateProduct,
43
+ deactivateProduct,
44
+ deactivatePrice,
45
+ });
46
+ // Render products.results with the existing Products/useProductManager callbacks.
47
+ // Expand each product with a separate useComponentPaginatedQuery for its component productId.
48
+ // Do not join unbounded prices onto every product in a page.
49
+ <button
50
+ disabled={products.status !== "CanLoadMore"}
51
+ onClick={() => products.loadMore(25)}
52
+ >
53
+ Load more products
54
+ </button>;
55
+ ```
56
+
57
+ Use the standard `LoadingFirstPage`, `LoadingMore`, `CanLoadMore`, and `Exhausted`
58
+ statuses for loading, empty, and terminal states. Queries react to writes
59
+ and reset when their arguments change. Keep price hooks in a child component
60
+ keyed by product ID. Do not invoke hooks inside a variable-length loop. A payout
61
+ history binding uses the same contract. Pinned ranges can grow beyond the requested
62
+ page size. The server caps each read at 200 rows or 1 MB and returns split hints
63
+ for the hook to split large ranges without dropping rows. The `Payouts` workflow's live snapshot
64
+ loader remains a separate Stripe action API, not a substitute for reactive
65
+ component history or exact paid totals.
66
+
67
+ ## Exact totals by currency
68
+
69
+ Use `getAccountEarningsByCurrency` and `getAccountPayoutsByCurrency` through the
70
+ client or component. They return `totals` sorted by currency and bounded
71
+ `transfers` or `payouts` previews. `previewLimit` is an integer from 0 to 100,
72
+ defaulting to 50. Earnings totals include `gross`, `reversed`, `net`, and
73
+ `transferCount`; payout totals include `paidOut` and `payoutCount`. Only payouts
74
+ with status `paid` contribute to `paidOut`. Reinstatement transfers contribute to
75
+ gross, while the original transfer's reversal remains recorded.
76
+
77
+ All amounts use the currency's original minor units. Never add different
78
+ currencies, or apply a fixed two-decimal conversion to JPY or KWD. The package
79
+ maintains summaries transactionally with every supported transfer and payout
80
+ mutation, including reversal mutations. Reads examine at most 501 summary rows,
81
+ one unbackfilled-row probe, and 100 preview rows, regardless of history size.
82
+ Accounts with more than 500 distinct currency strings fail explicitly. Summary
83
+ updates serialize per account/currency through Convex OCC.
84
+
85
+ Bind authorized wrappers to `createUseCurrencyEarnings(useQuery, earningsRef,
86
+ payoutsRef)`. Its `totals` joins the two summaries by currency and never sums the
87
+ previews. Render an `EarningsSummary` for each currency, passing that row's
88
+ `currency` and only that currency's payout preview. The default earnings formatter handles supported ordinary charge currencies.
89
+ Pass an explicit `formatAmount` callback for other observed currency precision,
90
+ including KWD, or render the raw typed totals with your own currency policy.
91
+ Use `getAccountBalance` or
92
+ `getPayoutSnapshot` for per-currency available/pending balances. The component's
93
+ earnings ledger does not determine settlement availability.
94
+
95
+ ### Existing installations
96
+
97
+ After deploying the optional marker fields and summary table, invoke
98
+ `components.betterStripe.earnings.mutations.backfillCurrencyTotals` from a trusted
99
+ server migration. Run separately for `kind: "earnings"` and `kind: "payouts"`,
100
+ starting with `cursor: null` and continuing with each `continueCursor` until
101
+ `isDone`. Each mutation visits at most 100 rows. Retrying a page is safe, and
102
+ ordinary package writes can continue during migration. A row's marker and its
103
+ summary contribution commit together. New readers throw while an account has
104
+ unbackfilled rows, so callers cannot mistake incomplete totals for zero.
105
+
106
+ Keep raw imports and direct database edits out of normal application writes.
107
+ If importing historical ledger rows, omit `totalsRecorded` and run the backfill.
108
+ Never copy markers without their matching summaries.
109
+
110
+ Legacy `getAccountEarnings`, `getAccountPayouts`, and `createUseEarnings` retain
111
+ their single-currency shapes. The legacy queries now reject mixed-currency
112
+ accounts and direct callers to the new methods. Their historical scans remain
113
+ subject to Convex read limits; migrate busy accounts to the maintained summaries.
114
+ Full referred-sale history uses `paginateTransfersByAccount`, not the preview.
115
+
116
+ ## Payout failures
117
+
118
+ Component payout rows and live `RecipientPayoutRow` snapshots expose optional
119
+ `failureCode` and `failureMessage`. Signed payout events write the provider's
120
+ current snapshot to the existing payout identity. A later snapshot with absent
121
+ or null provider failure fields clears stored details. Legacy rows remain valid.
122
+ Ordinary event replay is deduplicated. This is snapshot reconciliation and does
123
+ not guarantee convergence for globally out-of-order events.
124
+
125
+ Host apps should translate known codes into safe recovery instructions and a
126
+ settings link. Do not log or blindly render raw provider messages. Authorize
127
+ reads using the recipient's shared connected account.
128
+
129
+ ## Publication and consumer acceptance
130
+
131
+ A source merge does not activate an API in a published package. DOJO-908,
132
+ DOJO-1037, DOJO-1041, and DOJO-2257 require a verified published version and
133
+ explicit consumer adoption, authorized adapters, translated UI, and their own
134
+ acceptance evidence. These package changes do not complete those tickets or add
135
+ a second Dojo financial ledger, payout table, catalog store, or webhook processor.
136
+ Use the repository release workflow; do not publish npm manually.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -62,7 +62,8 @@
62
62
  "docs/accounts-v2-preview.md",
63
63
  "docs/react-workflows-audit.md",
64
64
  "CHANGELOG.md",
65
- "MIGRATION.md"
65
+ "MIGRATION.md",
66
+ "docs/read-contracts.md"
66
67
  ],
67
68
  "scripts": {
68
69
  "build": "tsc --project ./tsconfig.build.json",
@@ -89,3 +89,30 @@ it("reports bounded upcoming previews and not-ready accounts explicitly", async
89
89
  reason: "account_unavailable",
90
90
  });
91
91
  });
92
+
93
+ it("exposes optional provider failure details in history", async () => {
94
+ const stripe = {
95
+ balance: { retrieve: async () => ({ available: [], pending: [] }) },
96
+ payouts: {
97
+ list: async (args: { status?: string }) => ({
98
+ data: args.status
99
+ ? []
100
+ : [
101
+ {
102
+ ...payout("po_failed", "failed"),
103
+ failure_code: "account_closed",
104
+ failure_message: "Bank account closed",
105
+ },
106
+ ],
107
+ has_more: false,
108
+ }),
109
+ },
110
+ };
111
+ const result = await getPayoutSnapshot(stripe as unknown as Stripe, {
112
+ stripeAccountId: "acct_a",
113
+ });
114
+ expect(result.payouts[0]).toMatchObject({
115
+ failureCode: "account_closed",
116
+ failureMessage: "Bank account closed",
117
+ });
118
+ });
@@ -8,6 +8,8 @@ export type RecipientPayoutRow = {
8
8
  status: string;
9
9
  arrivalDate: number | null;
10
10
  created: number;
11
+ failureCode?: string;
12
+ failureMessage?: string;
11
13
  };
12
14
  export type RecipientPayoutSnapshot = {
13
15
  balances: AccountBalance[];
@@ -31,6 +33,8 @@ const row = (p: Stripe.Payout): RecipientPayoutRow => ({
31
33
  status: p.status,
32
34
  arrivalDate: p.arrival_date ? p.arrival_date * 1000 : null,
33
35
  created: p.created * 1000,
36
+ ...(p.failure_code != null ? { failureCode: p.failure_code } : {}),
37
+ ...(p.failure_message != null ? { failureMessage: p.failure_message } : {}),
34
38
  });
35
39
  /** Account-scoped live balance and cursor history. Upcoming truncation is explicit. */
36
40
  export async function getPayoutSnapshot(
@@ -2,6 +2,7 @@ import type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js"
2
2
  export type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js";
3
3
  import * as intentsImpl from "./billing/intents.js";
4
4
  export type * from "./billing/intents.js";
5
+ import { ReadContractClient } from "./readContracts.js";
5
6
  import { CostRecoveryClient } from "./costRecovery.js";
6
7
  export * from "./charge-currency.js";
7
8
  export * from "./costRecovery.js";
@@ -107,7 +108,7 @@ export type { RefundActor } from "./connect/refunds.js";
107
108
  import type { RefundActor } from "./connect/refunds.js";
108
109
  export type { AccountBalance } from "./connect/payouts.js";
109
110
  export type { WedgedReversalClaim } from "./connect/transfers.js";
110
- import type { Component, RunCtx } from "./helpers.js";
111
+ import type { RunCtx } from "./helpers.js";
111
112
  import { getStripeClient } from "./helpers.js";
112
113
  import type {
113
114
  V2AccountRetrieveInclude,
@@ -210,8 +211,7 @@ export type BetterStripeComponent = ComponentApi;
210
211
 
211
212
  // BETTER STRIPE CLIENT
212
213
 
213
- export class BetterStripe {
214
- public component: Component;
214
+ export class BetterStripe extends ReadContractClient {
215
215
  readonly stripeApiVersion: SupportedStripeApiVersion;
216
216
  private _apiKey?: string;
217
217
  private _triggers?: SyncTriggers;
@@ -220,7 +220,7 @@ export class BetterStripe {
220
220
  private _statementDescriptorSuffix?: string;
221
221
 
222
222
  constructor(component: BetterStripeComponent, options?: BetterStripeOptions) {
223
- this.component = component;
223
+ super(component);
224
224
  this.stripeApiVersion = resolveStripeApiVersion(options?.stripeApiVersion);
225
225
  this._apiKey = options?.STRIPE_SECRET_KEY;
226
226
  this._triggers = options?.triggers;
@@ -0,0 +1,90 @@
1
+ import type { ComponentApi } from "../component/_generated/component.js";
2
+ import type { PaginationOptions, PaginationResult } from "convex/server";
3
+ import type { Component, RunCtx } from "./helpers.js";
4
+ import type { PayoutStatus } from "../component/connect/validators.js";
5
+ import type {
6
+ StripeComponentPayout,
7
+ StripeComponentProduct,
8
+ StripeComponentPrice,
9
+ } from "./types/documents.js";
10
+ import { componentRef } from "./webhooks/helpers.js";
11
+ /** Shared component readers inherited by BetterStripe. */
12
+ export class ReadContractClient {
13
+ constructor(public component: Component) {}
14
+ async paginateProducts(
15
+ ctx: RunCtx,
16
+ opts: {
17
+ accountId?: string;
18
+ active?: boolean;
19
+ paginationOpts: PaginationOptions;
20
+ },
21
+ ): Promise<PaginationResult<StripeComponentProduct>> {
22
+ return ctx.runQuery(
23
+ componentRef(this.component, "products/queries/paginateProducts"),
24
+ opts,
25
+ );
26
+ }
27
+ async paginatePrices(
28
+ ctx: RunCtx,
29
+ opts: {
30
+ productId?: string;
31
+ active?: boolean;
32
+ paginationOpts: PaginationOptions;
33
+ },
34
+ ): Promise<PaginationResult<StripeComponentPrice>> {
35
+ return ctx.runQuery(
36
+ componentRef(this.component, "products/queries/paginatePrices"),
37
+ opts,
38
+ );
39
+ }
40
+ async paginatePayouts(
41
+ ctx: RunCtx,
42
+ opts: {
43
+ accountId: string;
44
+ status?: PayoutStatus;
45
+ paginationOpts: PaginationOptions;
46
+ },
47
+ ): Promise<PaginationResult<StripeComponentPayout>> {
48
+ return ctx.runQuery(
49
+ componentRef(this.component, "connect/queries/paginatePayouts"),
50
+ opts,
51
+ );
52
+ }
53
+
54
+ async getAccountEarningsByCurrency(
55
+ ctx: RunCtx,
56
+ opts: { destinationAccountId: string; previewLimit?: number },
57
+ ): Promise<{
58
+ totals: {
59
+ currency: string;
60
+ gross: number;
61
+ reversed: number;
62
+ net: number;
63
+ transferCount: number;
64
+ }[];
65
+ transfers: ComponentApi["connect"]["queries"]["getAccountEarningsByCurrency"]["_returnType"]["transfers"];
66
+ }> {
67
+ return ctx.runQuery(
68
+ componentRef(
69
+ this.component,
70
+ "connect/queries/getAccountEarningsByCurrency",
71
+ ),
72
+ opts,
73
+ );
74
+ }
75
+ async getAccountPayoutsByCurrency(
76
+ ctx: RunCtx,
77
+ opts: { accountId: string; previewLimit?: number },
78
+ ): Promise<{
79
+ totals: { currency: string; paidOut: number; payoutCount: number }[];
80
+ payouts: StripeComponentPayout[];
81
+ }> {
82
+ return ctx.runQuery(
83
+ componentRef(
84
+ this.component,
85
+ "connect/queries/getAccountPayoutsByCurrency",
86
+ ),
87
+ opts,
88
+ );
89
+ }
90
+ }
@@ -0,0 +1,62 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "./index.js";
3
+ import { components } from "./setup.test.js";
4
+ it("forwards typed component cursors and account scope through public readers", async () => {
5
+ const bs = new BetterStripe(components.betterStripe, {
6
+ STRIPE_SECRET_KEY: "sk_test_reader_fixture",
7
+ });
8
+ const page = { page: [], isDone: true, continueCursor: "end" };
9
+ const ctx = { runQuery: vi.fn().mockResolvedValue(page) };
10
+ const paginationOpts = { numItems: 10, cursor: "opaque" };
11
+ expect(
12
+ await bs.paginatePayouts(ctx, {
13
+ accountId: "acct_a",
14
+ status: "paid",
15
+ paginationOpts,
16
+ }),
17
+ ).toBe(page);
18
+ expect(ctx.runQuery).toHaveBeenLastCalledWith(
19
+ components.betterStripe.connect.queries.paginatePayouts,
20
+ { accountId: "acct_a", status: "paid", paginationOpts },
21
+ );
22
+ expect(
23
+ await bs.paginateProducts(ctx, {
24
+ accountId: "acct_a",
25
+ active: true,
26
+ paginationOpts,
27
+ }),
28
+ ).toBe(page);
29
+ expect(ctx.runQuery).toHaveBeenLastCalledWith(
30
+ components.betterStripe.products.queries.paginateProducts,
31
+ { accountId: "acct_a", active: true, paginationOpts },
32
+ );
33
+ expect(
34
+ await bs.paginatePrices(ctx, {
35
+ productId: "prod_a",
36
+ active: false,
37
+ paginationOpts,
38
+ }),
39
+ ).toBe(page);
40
+ expect(ctx.runQuery).toHaveBeenLastCalledWith(
41
+ components.betterStripe.products.queries.paginatePrices,
42
+ { productId: "prod_a", active: false, paginationOpts },
43
+ );
44
+ });
45
+ it("forwards exact currency summary reads through the public client", async () => {
46
+ const bs = new BetterStripe(components.betterStripe);
47
+ const ctx = { runQuery: vi.fn().mockResolvedValue({ totals: [] }) };
48
+ expect(
49
+ await bs.getAccountEarningsByCurrency(ctx, {
50
+ destinationAccountId: "acct_a",
51
+ }),
52
+ ).toEqual({ totals: [] });
53
+ expect(ctx.runQuery).toHaveBeenLastCalledWith(
54
+ components.betterStripe.connect.queries.getAccountEarningsByCurrency,
55
+ { destinationAccountId: "acct_a" },
56
+ );
57
+ await bs.getAccountPayoutsByCurrency(ctx, { accountId: "acct_a" });
58
+ expect(ctx.runQuery).toHaveBeenLastCalledWith(
59
+ components.betterStripe.connect.queries.getAccountPayoutsByCurrency,
60
+ { accountId: "acct_a" },
61
+ );
62
+ });
@@ -124,6 +124,8 @@ export type StripeComponentPayout = {
124
124
  status: PayoutStatus;
125
125
  arrivalDate?: string;
126
126
  method?: string;
127
+ failureCode?: string;
128
+ failureMessage?: string;
127
129
  metadata?: Record<string, unknown>;
128
130
  };
129
131
 
@@ -190,3 +190,28 @@ it.each([
190
190
  expect(transport).not.toHaveBeenCalled();
191
191
  },
192
192
  );
193
+
194
+ it("persists signed failure details and clears them on a later snapshot", async () => {
195
+ const f = fixture("payout.failed", "failed");
196
+ f.event.data.object.failure_code = "account_closed";
197
+ f.event.data.object.failure_message = "Bank account closed";
198
+ expect((await f.deliver()).status).toBe(200);
199
+ const failed = await f.payout();
200
+ expect(failed).toMatchObject({
201
+ failureCode: "account_closed",
202
+ failureMessage: "Bank account closed",
203
+ accountId: "acct_qa_recipient",
204
+ });
205
+ expect((await f.deliver()).body).toMatchObject({ deduplicated: true });
206
+ expect(await f.payout()).toEqual(failed);
207
+ f.event.id = "evt_failure_cleared";
208
+ f.event.type = "payout.updated";
209
+ f.event.data.object.status = "pending";
210
+ f.event.data.object.failure_code = null;
211
+ f.event.data.object.failure_message = null;
212
+ expect((await f.deliver()).status).toBe(200);
213
+ const cleared = await f.payout();
214
+ expect(cleared?._id).toBe(failed?._id);
215
+ expect(cleared).not.toHaveProperty("failureCode");
216
+ expect(cleared).not.toHaveProperty("failureMessage");
217
+ });
@@ -921,6 +921,8 @@ async function handlePayoutEvent(
921
921
  "pending" | "paid" | "failed" | "canceled" | "in_transit",
922
922
  arrivalDate: epochToIso(payout.arrival_date),
923
923
  method: payout.method ?? undefined,
924
+ failureCode: payout.failure_code ?? undefined,
925
+ failureMessage: payout.failure_message ?? undefined,
924
926
  metadata: payout.metadata ?? undefined,
925
927
  });
926
928
  }
@@ -24,6 +24,10 @@ import type * as costRecovery_imports from "../costRecovery/imports.js";
24
24
  import type * as costRecovery_mutations from "../costRecovery/mutations.js";
25
25
  import type * as costRecovery_queries from "../costRecovery/queries.js";
26
26
  import type * as costRecovery_reservations from "../costRecovery/reservations.js";
27
+ import type * as earnings_legacyReads from "../earnings/legacyReads.js";
28
+ import type * as earnings_mutations from "../earnings/mutations.js";
29
+ import type * as earnings_reads from "../earnings/reads.js";
30
+ import type * as earnings_triggers from "../earnings/triggers.js";
27
31
  import type * as lib_fees from "../lib/fees.js";
28
32
  import type * as lib_idempotency from "../lib/idempotency.js";
29
33
  import type * as lib_paymentSeller from "../lib/paymentSeller.js";
@@ -62,6 +66,10 @@ const fullApi: ApiFromModules<{
62
66
  "costRecovery/mutations": typeof costRecovery_mutations;
63
67
  "costRecovery/queries": typeof costRecovery_queries;
64
68
  "costRecovery/reservations": typeof costRecovery_reservations;
69
+ "earnings/legacyReads": typeof earnings_legacyReads;
70
+ "earnings/mutations": typeof earnings_mutations;
71
+ "earnings/reads": typeof earnings_reads;
72
+ "earnings/triggers": typeof earnings_triggers;
65
73
  "lib/fees": typeof lib_fees;
66
74
  "lib/idempotency": typeof lib_idempotency;
67
75
  "lib/paymentSeller": typeof lib_paymentSeller;