@fantastic.dev/better-stripe 0.24.0 → 0.25.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 (147) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +7 -1
  3. package/dist/client/billing/checkout.d.ts +3 -43
  4. package/dist/client/billing/checkout.d.ts.map +1 -1
  5. package/dist/client/billing/checkout.js +5 -260
  6. package/dist/client/billing/checkout.js.map +1 -1
  7. package/dist/client/billing/checkoutRequest.d.ts +129 -0
  8. package/dist/client/billing/checkoutRequest.d.ts.map +1 -0
  9. package/dist/client/billing/checkoutRequest.js +263 -0
  10. package/dist/client/billing/checkoutRequest.js.map +1 -0
  11. package/dist/client/billing/preparedCheckout.d.ts +22 -0
  12. package/dist/client/billing/preparedCheckout.d.ts.map +1 -0
  13. package/dist/client/billing/preparedCheckout.js +86 -0
  14. package/dist/client/billing/preparedCheckout.js.map +1 -0
  15. package/dist/client/checkoutRequests.d.ts +80 -0
  16. package/dist/client/checkoutRequests.d.ts.map +1 -0
  17. package/dist/client/checkoutRequests.js +28 -0
  18. package/dist/client/checkoutRequests.js.map +1 -0
  19. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +464 -0
  20. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  21. package/dist/client/connect/payoutCollection.d.ts +21 -0
  22. package/dist/client/connect/payoutCollection.d.ts.map +1 -0
  23. package/dist/client/connect/payoutCollection.js +47 -0
  24. package/dist/client/connect/payoutCollection.js.map +1 -0
  25. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +1805 -0
  26. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -0
  27. package/dist/client/connect/payoutExecutionTestHelpers.js +194 -0
  28. package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -0
  29. package/dist/client/connect/payoutSyncTestHelpers.d.ts +232 -0
  30. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  31. package/dist/client/connect/payoutWorker.d.ts +48 -0
  32. package/dist/client/connect/payoutWorker.d.ts.map +1 -0
  33. package/dist/client/connect/payoutWorker.js +78 -0
  34. package/dist/client/connect/payoutWorker.js.map +1 -0
  35. package/dist/client/index.d.ts +4 -11
  36. package/dist/client/index.d.ts.map +1 -1
  37. package/dist/client/index.js +4 -9
  38. package/dist/client/index.js.map +1 -1
  39. package/dist/client/payoutPolicy.d.ts +67 -0
  40. package/dist/client/payoutPolicy.d.ts.map +1 -1
  41. package/dist/client/payoutPolicy.js +10 -0
  42. package/dist/client/payoutPolicy.js.map +1 -1
  43. package/dist/client/readContracts.d.ts +11 -1
  44. package/dist/client/readContracts.d.ts.map +1 -1
  45. package/dist/client/readContracts.js +10 -0
  46. package/dist/client/readContracts.js.map +1 -1
  47. package/dist/component/_generated/component.d.ts +293 -0
  48. package/dist/component/_generated/component.d.ts.map +1 -1
  49. package/dist/component/core/mutations.d.ts.map +1 -1
  50. package/dist/component/core/mutations.js +2 -0
  51. package/dist/component/core/mutations.js.map +1 -1
  52. package/dist/component/core/resetSafety.d.ts +4 -0
  53. package/dist/component/core/resetSafety.d.ts.map +1 -0
  54. package/dist/component/core/resetSafety.js +54 -0
  55. package/dist/component/core/resetSafety.js.map +1 -0
  56. package/dist/component/earnings/triggers.d.ts +418 -0
  57. package/dist/component/earnings/triggers.d.ts.map +1 -1
  58. package/dist/component/earnings/triggers.js +2 -0
  59. package/dist/component/earnings/triggers.js.map +1 -1
  60. package/dist/component/payoutPolicy/schema.d.ts +2 -0
  61. package/dist/component/payoutPolicy/schema.d.ts.map +1 -1
  62. package/dist/component/payoutPolicy/schema.js +3 -1
  63. package/dist/component/payoutPolicy/schema.js.map +1 -1
  64. package/dist/component/payoutRelease/mutations.js +1 -1
  65. package/dist/component/payoutRelease/schema.d.ts +1 -0
  66. package/dist/component/payoutRelease/schema.d.ts.map +1 -1
  67. package/dist/component/payoutRelease/schema.js +1 -0
  68. package/dist/component/payoutRelease/schema.js.map +1 -1
  69. package/dist/component/payoutSnapshots/localState.d.ts +89 -0
  70. package/dist/component/payoutSnapshots/localState.d.ts.map +1 -0
  71. package/dist/component/payoutSnapshots/localState.js +186 -0
  72. package/dist/component/payoutSnapshots/localState.js.map +1 -0
  73. package/dist/component/payoutSnapshots/mutations.d.ts +108 -0
  74. package/dist/component/payoutSnapshots/mutations.d.ts.map +1 -0
  75. package/dist/component/payoutSnapshots/mutations.js +263 -0
  76. package/dist/component/payoutSnapshots/mutations.js.map +1 -0
  77. package/dist/component/payoutSnapshots/revisions.d.ts +12 -0
  78. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -0
  79. package/dist/component/payoutSnapshots/revisions.js +173 -0
  80. package/dist/component/payoutSnapshots/revisions.js.map +1 -0
  81. package/dist/component/payoutSnapshots/schema.d.ts +285 -0
  82. package/dist/component/payoutSnapshots/schema.d.ts.map +1 -0
  83. package/dist/component/payoutSnapshots/schema.js +108 -0
  84. package/dist/component/payoutSnapshots/schema.js.map +1 -0
  85. package/dist/component/payoutSnapshots/scope.d.ts +7 -0
  86. package/dist/component/payoutSnapshots/scope.d.ts.map +1 -0
  87. package/dist/component/payoutSnapshots/scope.js +8 -0
  88. package/dist/component/payoutSnapshots/scope.js.map +1 -0
  89. package/dist/component/payoutWorker/helpers.d.ts +30 -0
  90. package/dist/component/payoutWorker/helpers.d.ts.map +1 -0
  91. package/dist/component/payoutWorker/helpers.js +21 -0
  92. package/dist/component/payoutWorker/helpers.js.map +1 -0
  93. package/dist/component/payoutWorker/mutations.d.ts +68 -0
  94. package/dist/component/payoutWorker/mutations.d.ts.map +1 -0
  95. package/dist/component/payoutWorker/mutations.js +161 -0
  96. package/dist/component/payoutWorker/mutations.js.map +1 -0
  97. package/dist/component/payoutWorker/queries.d.ts +123 -0
  98. package/dist/component/payoutWorker/queries.d.ts.map +1 -0
  99. package/dist/component/payoutWorker/queries.js +61 -0
  100. package/dist/component/payoutWorker/queries.js.map +1 -0
  101. package/dist/component/payoutWorker/schema.d.ts +91 -0
  102. package/dist/component/payoutWorker/schema.d.ts.map +1 -0
  103. package/dist/component/payoutWorker/schema.js +27 -0
  104. package/dist/component/payoutWorker/schema.js.map +1 -0
  105. package/dist/component/schema.d.ts +232 -0
  106. package/dist/component/schema.js +10 -0
  107. package/dist/component/schema.js.map +1 -1
  108. package/docs/read-contracts.md +48 -0
  109. package/docs/settlement.md +128 -1
  110. package/package.json +1 -1
  111. package/src/client/billing/checkout.ts +11 -359
  112. package/src/client/billing/checkoutRequest.ts +362 -0
  113. package/src/client/billing/prepared-checkout.test.ts +430 -0
  114. package/src/client/billing/preparedCheckout.ts +143 -0
  115. package/src/client/checkoutRequests.ts +40 -0
  116. package/src/client/connect/payoutCollection.test.ts +74 -0
  117. package/src/client/connect/payoutCollection.ts +82 -0
  118. package/src/client/connect/payoutExecution.test.ts +1 -211
  119. package/src/client/connect/payoutExecutionTestHelpers.ts +213 -0
  120. package/src/client/connect/payoutWorker.test.ts +145 -0
  121. package/src/client/connect/payoutWorker.ts +144 -0
  122. package/src/client/index.ts +10 -21
  123. package/src/client/payoutPolicy.ts +26 -1
  124. package/src/client/readContracts.ts +23 -0
  125. package/src/component/_generated/api.ts +16 -0
  126. package/src/component/_generated/component.ts +361 -0
  127. package/src/component/core/mutations.ts +2 -0
  128. package/src/component/core/resetSafety.ts +67 -0
  129. package/src/component/earnings/triggers.ts +2 -0
  130. package/src/component/payout-reset-safety.test.ts +148 -0
  131. package/src/component/payout-revisions.test.ts +125 -0
  132. package/src/component/payout-snapshots.test.ts +395 -0
  133. package/src/component/payout-worker.test.ts +165 -0
  134. package/src/component/payoutPolicy/schema.ts +3 -1
  135. package/src/component/payoutRelease/mutations.ts +1 -1
  136. package/src/component/payoutRelease/schema.ts +1 -0
  137. package/src/component/payoutSnapshots/localState.ts +238 -0
  138. package/src/component/payoutSnapshots/mutations.ts +275 -0
  139. package/src/component/payoutSnapshots/revisions.ts +247 -0
  140. package/src/component/payoutSnapshots/schema.ts +125 -0
  141. package/src/component/payoutSnapshots/scope.ts +7 -0
  142. package/src/component/payoutWorker/helpers.ts +30 -0
  143. package/src/component/payoutWorker/mutations.ts +181 -0
  144. package/src/component/payoutWorker/queries.ts +64 -0
  145. package/src/component/payoutWorker/schema.ts +26 -0
  146. package/src/component/public.test.ts +2 -2
  147. package/src/component/schema.ts +18 -0
@@ -0,0 +1,82 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { snapshotDoc } from "../../component/payoutSnapshots/schema.js";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { validateIdentity } from "../../component/payoutRelease/helpers.js";
7
+ export type PayoutCollectionState = Infer<typeof snapshotDoc>;
8
+ export type PayoutCollectionScope = {
9
+ accountId: string;
10
+ ownerKey: string;
11
+ operationKey: string;
12
+ };
13
+ export type PayoutCollectionOptions = PayoutCollectionScope & {
14
+ expectedRevision: number;
15
+ expectedStep?: number;
16
+ batchSize?: number;
17
+ };
18
+ /** Resume one bounded local-ledger step. local_ready does not authorize a payout. */
19
+ export async function collectPayoutSnapshot(
20
+ component: Component,
21
+ ctx: RunCtx,
22
+ opts: PayoutCollectionOptions,
23
+ ): Promise<PayoutCollectionState> {
24
+ validateIdentity(opts);
25
+ if (
26
+ !Number.isSafeInteger(opts.expectedRevision) ||
27
+ opts.expectedRevision < -1 ||
28
+ (opts.expectedStep !== undefined &&
29
+ (!Number.isSafeInteger(opts.expectedStep) || opts.expectedStep < 0)) ||
30
+ (opts.batchSize !== undefined &&
31
+ (!Number.isInteger(opts.batchSize) ||
32
+ opts.batchSize < 1 ||
33
+ opts.batchSize > 25))
34
+ )
35
+ throw new Error("Invalid local collection revision, step or batch.");
36
+ const scope = {
37
+ accountId: opts.accountId,
38
+ ownerKey: opts.ownerKey,
39
+ operationKey: opts.operationKey,
40
+ };
41
+ const state = (await runMutationOrThrow(
42
+ ctx,
43
+ componentRef(component, "payoutSnapshots/mutations/begin"),
44
+ { ...scope, expectedRevision: opts.expectedRevision },
45
+ )) as PayoutCollectionState;
46
+ if (!state.readOnly) throw new Error("Collection is financially bound.");
47
+ if (opts.expectedStep === undefined) return state;
48
+ return (await runMutationOrThrow(
49
+ ctx,
50
+ componentRef(component, "payoutSnapshots/mutations/advance"),
51
+ {
52
+ ...scope,
53
+ expectedStep: opts.expectedStep,
54
+ ...(opts.batchSize !== undefined ? { batchSize: opts.batchSize } : {}),
55
+ },
56
+ )) as PayoutCollectionState;
57
+ }
58
+ /** Delete only read-only cache state in bounded batches; never financial records. */
59
+ export async function discardPayoutSnapshot(
60
+ component: Component,
61
+ ctx: RunCtx,
62
+ opts: PayoutCollectionScope & { batchSize?: number },
63
+ ): Promise<PayoutCollectionState | null> {
64
+ validateIdentity(opts);
65
+ if (
66
+ opts.batchSize !== undefined &&
67
+ (!Number.isInteger(opts.batchSize) ||
68
+ opts.batchSize < 1 ||
69
+ opts.batchSize > 100)
70
+ )
71
+ throw new Error("Invalid collection cleanup batch.");
72
+ return (await runMutationOrThrow(
73
+ ctx,
74
+ componentRef(component, "payoutSnapshots/mutations/discard"),
75
+ {
76
+ accountId: opts.accountId,
77
+ ownerKey: opts.ownerKey,
78
+ operationKey: opts.operationKey,
79
+ ...(opts.batchSize !== undefined ? { batchSize: opts.batchSize } : {}),
80
+ },
81
+ )) as PayoutCollectionState | null;
82
+ }
@@ -1,216 +1,6 @@
1
1
  // @vitest-environment edge-runtime
2
- import { convexTest } from "convex-test";
3
- import { makeFunctionReference } from "convex/server";
4
2
  import { expect, it, vi } from "vitest";
5
- import type Stripe from "stripe";
6
- import schema from "../../component/schema.js";
7
- import type { Component, RunCtx } from "../helpers.js";
8
- import { releaseRecipientPayout } from "./payoutExecution.js";
9
- const modules = import.meta.glob("../../component/**/*.*s");
10
- const symbol = Symbol.for("toReferencePath");
11
- const component = {
12
- payoutPolicy: {
13
- queries: { get: { [symbol]: "betterStripe/payoutPolicy/queries/get" } },
14
- },
15
- } as unknown as Component;
16
- const scope = {
17
- accountId: "acct_recipient",
18
- ownerKey: "owner",
19
- operationKey: "release-1",
20
- currency: "usd",
21
- independentLiabilities: 0,
22
- };
23
- async function setup(amounts = [600, 400]) {
24
- const t = convexTest(schema, modules);
25
- await t.run(async (ctx) => {
26
- await ctx.db.insert("payoutPolicies", {
27
- accountId: scope.accountId,
28
- ownerKey: scope.ownerKey,
29
- mode: "custom",
30
- status: "ready",
31
- revision: 0,
32
- operationKey: "enable",
33
- country: "US",
34
- thresholds: [{ currency: "usd", amount: 1000 }],
35
- holdDeadline: Date.now() + 86400000,
36
- });
37
- for (let i = 0; i < amounts.length; i++)
38
- await ctx.db.insert("transfers", {
39
- stripeTransferId: `tr_${i}`,
40
- destinationAccountId: scope.accountId,
41
- sourceChargeId: `ch_${i}`,
42
- amount: amounts[i],
43
- currency: "usd",
44
- status: "paid",
45
- role: i % 2 ? "affiliate" : "store",
46
- });
47
- });
48
- const path = (ref: Record<symbol, string>) =>
49
- ref[symbol].replace("betterStripe/", "").replace(/\/(\w+)$/, ":$1");
50
- const ctx = {
51
- runQuery: (ref: Record<symbol, string>, args: never) =>
52
- t.query(makeFunctionReference<"query">(path(ref)), args),
53
- runMutation: (ref: Record<symbol, string>, args: never) =>
54
- t.mutation(makeFunctionReference<"mutation">(path(ref)), args),
55
- } as unknown as RunCtx;
56
- let transactions = amounts.map((amount, i) => ({
57
- id: `txn_${i}`,
58
- source: `py_${i}`,
59
- amount,
60
- fee: 0,
61
- net: amount,
62
- currency: "usd",
63
- created: 100,
64
- available_on: 200,
65
- status: "available",
66
- type: "payment",
67
- exchange_rate: null,
68
- }));
69
- let payout: Record<string, unknown> | undefined;
70
- const provider = {
71
- accounts: {
72
- listExternalAccounts: vi.fn(async () => ({
73
- data: [
74
- {
75
- id: "ba_one",
76
- object: "bank_account",
77
- currency: "usd",
78
- default_for_currency: true,
79
- },
80
- ],
81
- has_more: false,
82
- })),
83
- },
84
- transfers: {
85
- retrieve: vi.fn(async (id: string) => {
86
- const i = Number(id.slice(3));
87
- return {
88
- id,
89
- destination: scope.accountId,
90
- destination_payment: `py_${i}`,
91
- source_transaction: `ch_${i}`,
92
- amount: amounts[i],
93
- currency: "usd",
94
- amount_reversed: 0,
95
- };
96
- }),
97
- listReversals: vi.fn(async () => ({ data: [], has_more: false })),
98
- },
99
- charges: {
100
- retrieve: vi.fn(async (id: string) => {
101
- const i = Number(id.slice(3));
102
- return {
103
- id,
104
- source_transfer: `tr_${i}`,
105
- amount: amounts[i],
106
- currency: "usd",
107
- paid: true,
108
- status: "succeeded",
109
- balance_transaction: `txn_${i}`,
110
- };
111
- }),
112
- },
113
- balanceTransactions: {
114
- list: vi.fn(async (params: { source?: string; limit?: number }) => ({
115
- data: params.source
116
- ? transactions.filter((t) => t.source === params.source)
117
- : transactions.slice(0, params.limit),
118
- has_more: false,
119
- })),
120
- retrieve: vi.fn(async (id: string) =>
121
- transactions.find((t) => t.id === id),
122
- ),
123
- },
124
- balance: {
125
- retrieve: vi.fn(async () => ({
126
- available: [
127
- {
128
- currency: "usd",
129
- amount: transactions
130
- .filter((t) => t.status === "available")
131
- .reduce((a, t) => a + t.net, 0),
132
- source_types: {
133
- card: transactions
134
- .filter((t) => t.status === "available")
135
- .reduce((a, t) => a + t.net, 0),
136
- },
137
- },
138
- ],
139
- pending: [],
140
- })),
141
- },
142
- payouts: {
143
- list: vi.fn(async () => ({
144
- data: payout ? [payout] : [],
145
- has_more: false,
146
- })),
147
- retrieve: vi.fn(async () => payout),
148
- create: vi.fn(
149
- async (params: {
150
- amount: number;
151
- currency: string;
152
- metadata: object;
153
- }) => {
154
- payout = {
155
- id: "po_one",
156
- ...params,
157
- status: "paid",
158
- automatic: false,
159
- method: "standard",
160
- type: "bank_account",
161
- source_type: "card",
162
- destination: "ba_one",
163
- created: Math.floor(Date.now() / 1000),
164
- arrival_date: Math.floor(Date.now() / 1000),
165
- balance_transaction: "txn_debit",
166
- failure_balance_transaction: null,
167
- reversed_by: null,
168
- };
169
- transactions = [
170
- {
171
- id: "txn_debit",
172
- source: "po_one",
173
- amount: -params.amount,
174
- fee: 0,
175
- net: -params.amount,
176
- currency: "usd",
177
- created: Math.floor(Date.now() / 1000),
178
- available_on: Math.floor(Date.now() / 1000),
179
- status: "available",
180
- type: "payout",
181
- exchange_rate: null,
182
- },
183
- ...transactions,
184
- ];
185
- return payout;
186
- },
187
- ),
188
- },
189
- };
190
- const verify = vi.fn(async () => ({
191
- status: "verified" as const,
192
- policy: (await t.run((ctx) => ctx.db.query("payoutPolicies").first()))!,
193
- }));
194
- const run = (extra = {}) =>
195
- releaseRecipientPayout(
196
- provider as unknown as Stripe,
197
- component,
198
- ctx,
199
- { ...scope, ...extra },
200
- verify,
201
- );
202
- return {
203
- t,
204
- ctx,
205
- provider,
206
- verify,
207
- run,
208
- setTransactions: (rows: typeof transactions) => {
209
- transactions = rows;
210
- },
211
- transactions: () => transactions,
212
- };
213
- }
3
+ import { setup, scope } from "./payoutExecutionTestHelpers.js";
214
4
  it("automatically releases combined creator and affiliate funds exactly once", async () => {
215
5
  const s = await setup();
216
6
  expect(await s.run()).toMatchObject({
@@ -0,0 +1,213 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { vi } from "vitest";
5
+ import type Stripe from "stripe";
6
+ import schema from "../../component/schema.js";
7
+ import type { Component, RunCtx } from "../helpers.js";
8
+ import { releaseRecipientPayout } from "./payoutExecution.js";
9
+ const modules = import.meta.glob("../../component/**/*.*s");
10
+ const symbol = Symbol.for("toReferencePath");
11
+ export const component = {
12
+ payoutPolicy: {
13
+ queries: { get: { [symbol]: "betterStripe/payoutPolicy/queries/get" } },
14
+ },
15
+ } as unknown as Component;
16
+ export const scope = {
17
+ accountId: "acct_recipient",
18
+ ownerKey: "owner",
19
+ operationKey: "release-1",
20
+ currency: "usd",
21
+ independentLiabilities: 0,
22
+ };
23
+ export async function setup(amounts = [600, 400]) {
24
+ const t = convexTest(schema, modules);
25
+ await t.run(async (ctx) => {
26
+ await ctx.db.insert("payoutPolicies", {
27
+ accountId: scope.accountId,
28
+ ownerKey: scope.ownerKey,
29
+ mode: "custom",
30
+ status: "ready",
31
+ revision: 0,
32
+ operationKey: "enable",
33
+ country: "US",
34
+ thresholds: [{ currency: "usd", amount: 1000 }],
35
+ holdDeadline: Date.now() + 86400000,
36
+ });
37
+ for (let i = 0; i < amounts.length; i++)
38
+ await ctx.db.insert("transfers", {
39
+ stripeTransferId: `tr_${i}`,
40
+ destinationAccountId: scope.accountId,
41
+ sourceChargeId: `ch_${i}`,
42
+ amount: amounts[i],
43
+ currency: "usd",
44
+ status: "paid",
45
+ role: i % 2 ? "affiliate" : "store",
46
+ });
47
+ });
48
+ const path = (ref: Record<symbol, string>) =>
49
+ ref[symbol].replace("betterStripe/", "").replace(/\/(\w+)$/, ":$1");
50
+ const ctx = {
51
+ runQuery: (ref: Record<symbol, string>, args: never) =>
52
+ t.query(makeFunctionReference<"query">(path(ref)), args),
53
+ runMutation: (ref: Record<symbol, string>, args: never) =>
54
+ t.mutation(makeFunctionReference<"mutation">(path(ref)), args),
55
+ } as unknown as RunCtx;
56
+ let transactions = amounts.map((amount, i) => ({
57
+ id: `txn_${i}`,
58
+ source: `py_${i}`,
59
+ amount,
60
+ fee: 0,
61
+ net: amount,
62
+ currency: "usd",
63
+ created: 100,
64
+ available_on: 200,
65
+ status: "available",
66
+ type: "payment",
67
+ exchange_rate: null,
68
+ }));
69
+ let payout: Record<string, unknown> | undefined;
70
+ const provider = {
71
+ accounts: {
72
+ listExternalAccounts: vi.fn(async () => ({
73
+ data: [
74
+ {
75
+ id: "ba_one",
76
+ object: "bank_account",
77
+ currency: "usd",
78
+ default_for_currency: true,
79
+ },
80
+ ],
81
+ has_more: false,
82
+ })),
83
+ },
84
+ transfers: {
85
+ retrieve: vi.fn(async (id: string) => {
86
+ const i = Number(id.slice(3));
87
+ return {
88
+ id,
89
+ destination: scope.accountId,
90
+ destination_payment: `py_${i}`,
91
+ source_transaction: `ch_${i}`,
92
+ amount: amounts[i],
93
+ currency: "usd",
94
+ amount_reversed: 0,
95
+ };
96
+ }),
97
+ listReversals: vi.fn(async () => ({ data: [], has_more: false })),
98
+ },
99
+ charges: {
100
+ retrieve: vi.fn(async (id: string) => {
101
+ const i = Number(id.slice(3));
102
+ return {
103
+ id,
104
+ source_transfer: `tr_${i}`,
105
+ amount: amounts[i],
106
+ currency: "usd",
107
+ paid: true,
108
+ status: "succeeded",
109
+ balance_transaction: `txn_${i}`,
110
+ };
111
+ }),
112
+ },
113
+ balanceTransactions: {
114
+ list: vi.fn(async (params: { source?: string; limit?: number }) => ({
115
+ data: params.source
116
+ ? transactions.filter((t) => t.source === params.source)
117
+ : transactions.slice(0, params.limit),
118
+ has_more: false,
119
+ })),
120
+ retrieve: vi.fn(async (id: string) =>
121
+ transactions.find((t) => t.id === id),
122
+ ),
123
+ },
124
+ balance: {
125
+ retrieve: vi.fn(async () => ({
126
+ available: [
127
+ {
128
+ currency: "usd",
129
+ amount: transactions
130
+ .filter((t) => t.status === "available")
131
+ .reduce((a, t) => a + t.net, 0),
132
+ source_types: {
133
+ card: transactions
134
+ .filter((t) => t.status === "available")
135
+ .reduce((a, t) => a + t.net, 0),
136
+ },
137
+ },
138
+ ],
139
+ pending: [],
140
+ })),
141
+ },
142
+ payouts: {
143
+ list: vi.fn(async () => ({
144
+ data: payout ? [payout] : [],
145
+ has_more: false,
146
+ })),
147
+ retrieve: vi.fn(async () => payout),
148
+ create: vi.fn(
149
+ async (params: {
150
+ amount: number;
151
+ currency: string;
152
+ metadata: object;
153
+ }) => {
154
+ payout = {
155
+ id: "po_one",
156
+ ...params,
157
+ status: "paid",
158
+ automatic: false,
159
+ method: "standard",
160
+ type: "bank_account",
161
+ source_type: "card",
162
+ destination: "ba_one",
163
+ created: Math.floor(Date.now() / 1000),
164
+ arrival_date: Math.floor(Date.now() / 1000),
165
+ balance_transaction: "txn_debit",
166
+ failure_balance_transaction: null,
167
+ reversed_by: null,
168
+ };
169
+ transactions = [
170
+ {
171
+ id: "txn_debit",
172
+ source: "po_one",
173
+ amount: -params.amount,
174
+ fee: 0,
175
+ net: -params.amount,
176
+ currency: "usd",
177
+ created: Math.floor(Date.now() / 1000),
178
+ available_on: Math.floor(Date.now() / 1000),
179
+ status: "available",
180
+ type: "payout",
181
+ exchange_rate: null,
182
+ },
183
+ ...transactions,
184
+ ];
185
+ return payout;
186
+ },
187
+ ),
188
+ },
189
+ };
190
+ const verify = vi.fn(async () => ({
191
+ status: "verified" as const,
192
+ policy: (await t.run((ctx) => ctx.db.query("payoutPolicies").first()))!,
193
+ }));
194
+ const run = (extra = {}) =>
195
+ releaseRecipientPayout(
196
+ provider as unknown as Stripe,
197
+ component,
198
+ ctx,
199
+ { ...scope, ...extra },
200
+ verify,
201
+ );
202
+ return {
203
+ t,
204
+ ctx,
205
+ provider,
206
+ verify,
207
+ run,
208
+ setTransactions: (rows: typeof transactions) => {
209
+ transactions = rows;
210
+ },
211
+ transactions: () => transactions,
212
+ };
213
+ }
@@ -0,0 +1,145 @@
1
+ // @vitest-environment edge-runtime
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import type Stripe from "stripe";
4
+ import { setup, scope, component } from "./payoutExecutionTestHelpers.js";
5
+ import { reconcileRecipientPayout } from "./payoutReconciliation.js";
6
+ import { PayoutWorkerClient } from "./payoutWorker.js";
7
+ import { changeBalance } from "../../component/affiliateRecovery/accounting.js";
8
+ afterEach(() => vi.useRealTimers());
9
+ async function worker(amounts?: number[]) {
10
+ const s = await setup(amounts);
11
+ const client = new PayoutWorkerClient(
12
+ component,
13
+ (_ctx, opts) => s.run(opts),
14
+ (_ctx, opts) =>
15
+ reconcileRecipientPayout(
16
+ s.provider as unknown as Stripe,
17
+ component,
18
+ s.ctx,
19
+ opts,
20
+ ),
21
+ );
22
+ const run = () => client.run(s.ctx, scope);
23
+ return { ...s, client, run };
24
+ }
25
+ it("the recurring worker releases combined money once, records its result and waits for the next attempt", async () => {
26
+ const s = await worker();
27
+ expect(await s.run()).toMatchObject({
28
+ status: "completed",
29
+ job: { lastReason: "paid", hasOperation: false },
30
+ payout: { claim: { amount: 1000, status: "paid" } },
31
+ });
32
+ expect(await s.run()).toMatchObject({ status: "held", reason: "not_due" });
33
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
34
+ const state = await s.client.get(s.ctx, scope);
35
+ expect(state?.nextAttemptAt).toBeGreaterThan(Date.now());
36
+ });
37
+ it("the next recurring attempt carries below-minimum balances and pays when new funding qualifies", async () => {
38
+ vi.useFakeTimers();
39
+ const amounts = [599, 400];
40
+ const s = await worker(amounts);
41
+ expect(await s.run()).toMatchObject({
42
+ payout: { status: "held", reason: "below_threshold", matureUnpaid: 999 },
43
+ });
44
+ vi.advanceTimersByTime(300000);
45
+ expect(await s.run()).toMatchObject({
46
+ payout: { reason: "below_threshold" },
47
+ });
48
+ expect(s.provider.payouts.create).not.toHaveBeenCalled();
49
+ amounts.push(1);
50
+ await s.t.run((ctx) =>
51
+ ctx.db.insert("transfers", {
52
+ stripeTransferId: "tr_2",
53
+ destinationAccountId: scope.accountId,
54
+ sourceChargeId: "ch_2",
55
+ amount: 1,
56
+ currency: "usd",
57
+ status: "paid",
58
+ role: "affiliate",
59
+ }),
60
+ );
61
+ s.setTransactions([
62
+ ...s.transactions(),
63
+ {
64
+ ...s.transactions()[0],
65
+ id: "txn_2",
66
+ source: "py_2",
67
+ amount: 1,
68
+ net: 1,
69
+ },
70
+ ]);
71
+ vi.advanceTimersByTime(300000);
72
+ expect(await s.run()).toMatchObject({
73
+ payout: { claim: { status: "paid", amount: 1000 } },
74
+ });
75
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
76
+ });
77
+ it("unknown provider outcomes keep the same durable attempt and never blindly recreate", async () => {
78
+ vi.useFakeTimers();
79
+ const s = await worker();
80
+ s.provider.payouts.create.mockRejectedValueOnce(
81
+ new Error("network outcome unknown"),
82
+ );
83
+ await expect(s.run()).rejects.toThrow("network outcome unknown");
84
+ const first = await s.client.get(s.ctx, scope);
85
+ expect(first).toMatchObject({
86
+ hasOperation: true,
87
+ lastReason: "worker_error",
88
+ });
89
+ vi.advanceTimersByTime(300000);
90
+ expect(await s.run()).toMatchObject({
91
+ payout: { status: "held", reason: "payout_unidentified" },
92
+ });
93
+ expect((await s.client.get(s.ctx, scope))?.operationKey).toBe(
94
+ first?.operationKey,
95
+ );
96
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
97
+ });
98
+ it("concurrent recurring workers share the lease instead of canceling each other's unattempted claim", async () => {
99
+ const s = await worker();
100
+ const results = await Promise.all([s.run(), s.run()]);
101
+ expect(results.map((r) => r.status).sort()).toEqual(["completed", "held"]);
102
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
103
+ });
104
+ it("a successful payout with a lost response is recovered after opting out without another create", async () => {
105
+ vi.useFakeTimers();
106
+ const s = await worker();
107
+ const create = s.provider.payouts.create.getMockImplementation()!;
108
+ s.provider.payouts.create.mockImplementationOnce(async (params) => {
109
+ await create(params);
110
+ throw new Error("response lost after provider accepted");
111
+ });
112
+ await expect(s.run()).rejects.toThrow(/response lost/);
113
+ await s.t.run((ctx) =>
114
+ changeBalance(ctx, scope.accountId, "usd", { outstandingDebt: 100 }),
115
+ );
116
+ await s.t.run(async (ctx) => {
117
+ const policy = await ctx.db.query("payoutPolicies").first();
118
+ await ctx.db.patch("payoutPolicies", policy!._id, {
119
+ mode: "stripe_managed",
120
+ thresholds: [],
121
+ revision: 1,
122
+ });
123
+ });
124
+ vi.advanceTimersByTime(300000);
125
+ expect(await s.run()).toMatchObject({
126
+ payout: { claim: { status: "paid", amount: 1000 } },
127
+ job: { hasOperation: false },
128
+ });
129
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
130
+ });
131
+ it("reports affiliate recovery holds before a fresh attempt without creating a payout", async () => {
132
+ const s = await worker();
133
+ await s.t.run((ctx) =>
134
+ changeBalance(ctx, scope.accountId, "usd", { outstandingDebt: 100 }),
135
+ );
136
+ expect(await s.run()).toMatchObject({
137
+ status: "held",
138
+ reason: "affiliate_recovery_pending",
139
+ });
140
+ expect(await s.client.get(s.ctx, scope)).toMatchObject({
141
+ lastReason: "affiliate_recovery_pending",
142
+ hasOperation: false,
143
+ });
144
+ expect(s.provider.payouts.create).not.toHaveBeenCalled();
145
+ });