@fantastic.dev/better-stripe 0.59.0 → 0.60.1

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 (230) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +676 -50
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +322 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +644 -18
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +338 -25
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.d.ts +12 -1
  14. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  15. package/dist/client/paymentSource/resolver.fixtures.d.ts +220 -0
  16. package/dist/client/paymentSource/resolver.fixtures.d.ts.map +1 -0
  17. package/dist/client/paymentSource/resolver.fixtures.js +189 -0
  18. package/dist/client/paymentSource/resolver.fixtures.js.map +1 -0
  19. package/dist/client/paymentSource/resolver.js +28 -3
  20. package/dist/client/paymentSource/resolver.js.map +1 -1
  21. package/dist/client/settlement/execution.d.ts +25 -0
  22. package/dist/client/settlement/execution.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.js +2 -0
  24. package/dist/client/settlement/execution.js.map +1 -1
  25. package/dist/client/usage/catalogPrices.d.ts +1 -1
  26. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  27. package/dist/client/usage/catalogPrices.js +4 -4
  28. package/dist/client/usage/catalogPrices.js.map +1 -1
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.js +2 -2
  31. package/dist/client/usage/creditCapacity.d.ts.map +1 -1
  32. package/dist/client/usage/creditCapacity.js +7 -1
  33. package/dist/client/usage/creditCapacity.js.map +1 -1
  34. package/dist/client/usage/creditClient.d.ts +3 -0
  35. package/dist/client/usage/creditClient.d.ts.map +1 -1
  36. package/dist/client/usage/creditDelivery.d.ts.map +1 -1
  37. package/dist/client/usage/creditDelivery.js +4 -1
  38. package/dist/client/usage/creditDelivery.js.map +1 -1
  39. package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
  40. package/dist/client/usage/creditLifecycle.js +2 -1
  41. package/dist/client/usage/creditLifecycle.js.map +1 -1
  42. package/dist/client/usage/creditNative.d.ts +3 -0
  43. package/dist/client/usage/creditNative.d.ts.map +1 -1
  44. package/dist/client/usage/creditNative.js +3 -0
  45. package/dist/client/usage/creditNative.js.map +1 -1
  46. package/dist/client/usage/creditProvider.d.ts.map +1 -1
  47. package/dist/client/usage/creditProvider.js +2 -1
  48. package/dist/client/usage/creditProvider.js.map +1 -1
  49. package/dist/client/usage/creditRead.d.ts +1 -0
  50. package/dist/client/usage/creditRead.d.ts.map +1 -1
  51. package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
  52. package/dist/client/usage/creditReconciliation.js +11 -3
  53. package/dist/client/usage/creditReconciliation.js.map +1 -1
  54. package/dist/client/usage/creditRevenue.d.ts +22 -0
  55. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  56. package/dist/client/usage/creditRevenue.js +118 -0
  57. package/dist/client/usage/creditRevenue.js.map +1 -0
  58. package/dist/client/usage/creditSettlement.d.ts +29 -0
  59. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  60. package/dist/client/usage/creditSettlement.fixtures.d.ts +216 -0
  61. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  62. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  63. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  64. package/dist/client/usage/creditSettlement.js +70 -0
  65. package/dist/client/usage/creditSettlement.js.map +1 -0
  66. package/dist/client/usage/creditTransport.fixtures.d.ts +8 -1
  67. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  68. package/dist/client/usage/creditTransport.fixtures.js +27 -5
  69. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  70. package/dist/client/usage/index.d.ts +4 -0
  71. package/dist/client/usage/index.d.ts.map +1 -1
  72. package/dist/client/usage/invoiceSale.d.ts +22 -0
  73. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  74. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  75. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  76. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  77. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  78. package/dist/client/usage/invoiceSale.js +117 -0
  79. package/dist/client/usage/invoiceSale.js.map +1 -0
  80. package/dist/client/usage/observationClient.d.ts +2 -2
  81. package/dist/client/usage/observationClient.d.ts.map +1 -1
  82. package/dist/client/usage/settlement.d.ts +32 -0
  83. package/dist/client/usage/settlement.d.ts.map +1 -0
  84. package/dist/client/usage/settlement.js +60 -0
  85. package/dist/client/usage/settlement.js.map +1 -0
  86. package/dist/client/usage/settlementClient.d.ts +51 -0
  87. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  88. package/dist/client/usage/settlementClient.js +35 -0
  89. package/dist/client/usage/settlementClient.js.map +1 -0
  90. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
  91. package/dist/client/usage/subscriptionCancellation.js +3 -2
  92. package/dist/client/usage/subscriptionCancellation.js.map +1 -1
  93. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
  94. package/dist/client/usage/subscriptionCheckout.js +3 -2
  95. package/dist/client/usage/subscriptionCheckout.js.map +1 -1
  96. package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
  97. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
  98. package/dist/client/usage/subscriptionLifecycle.js +3 -2
  99. package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
  100. package/dist/client/usage/subscriptionProvider.d.ts +2 -0
  101. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
  102. package/dist/client/usage/subscriptionProvider.js +9 -2
  103. package/dist/client/usage/subscriptionProvider.js.map +1 -1
  104. package/dist/component/_generated/component.d.ts +146 -0
  105. package/dist/component/_generated/component.d.ts.map +1 -1
  106. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  107. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  108. package/dist/component/earnings/triggers.d.ts +172 -12
  109. package/dist/component/earnings/triggers.d.ts.map +1 -1
  110. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  111. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  112. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  113. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  114. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  115. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  116. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  117. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  118. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  119. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  120. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  121. package/dist/component/schema.d.ts +322 -9
  122. package/dist/component/settlement/mutations.d.ts +50 -0
  123. package/dist/component/settlement/mutations.d.ts.map +1 -1
  124. package/dist/component/settlement/mutations.js +8 -1
  125. package/dist/component/settlement/mutations.js.map +1 -1
  126. package/dist/component/settlement/queries.d.ts +25 -0
  127. package/dist/component/settlement/queries.d.ts.map +1 -1
  128. package/dist/component/settlement/schema.d.ts +128 -1
  129. package/dist/component/settlement/schema.d.ts.map +1 -1
  130. package/dist/component/settlement/schema.js +22 -0
  131. package/dist/component/settlement/schema.js.map +1 -1
  132. package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
  133. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
  134. package/dist/component/usage/allowance.fixtures.js +67 -0
  135. package/dist/component/usage/allowance.fixtures.js.map +1 -0
  136. package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
  137. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
  138. package/dist/component/usageCredits/accounting.fixtures.js +89 -0
  139. package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
  140. package/dist/component/usageCredits/helpers.d.ts +7 -0
  141. package/dist/component/usageCredits/helpers.d.ts.map +1 -1
  142. package/dist/component/usageCredits/helpers.js +5 -0
  143. package/dist/component/usageCredits/helpers.js.map +1 -1
  144. package/dist/component/usageCredits/mutations.d.ts +6 -0
  145. package/dist/component/usageCredits/mutations.d.ts.map +1 -1
  146. package/dist/component/usageCredits/mutations.js +70 -7
  147. package/dist/component/usageCredits/mutations.js.map +1 -1
  148. package/dist/component/usageCredits/purchase.d.ts +1 -0
  149. package/dist/component/usageCredits/purchase.d.ts.map +1 -1
  150. package/dist/component/usageCredits/queries.d.ts +10 -0
  151. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  152. package/dist/component/usageCredits/schema.d.ts +24 -4
  153. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  154. package/dist/component/usageCredits/schema.js +4 -0
  155. package/dist/component/usageCredits/schema.js.map +1 -1
  156. package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
  157. package/dist/component/usageSubscriptions/history.js +3 -1
  158. package/dist/component/usageSubscriptions/history.js.map +1 -1
  159. package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
  160. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
  161. package/dist/component/usageSubscriptions/mutations.js +19 -0
  162. package/dist/component/usageSubscriptions/mutations.js.map +1 -1
  163. package/dist/component/usageSubscriptions/queries.d.ts +2 -0
  164. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
  165. package/dist/component/usageSubscriptions/schema.d.ts +7 -2
  166. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
  167. package/dist/component/usageSubscriptions/schema.js +1 -0
  168. package/dist/component/usageSubscriptions/schema.js.map +1 -1
  169. package/docs/README.md +4 -0
  170. package/docs/settlement.md +4 -0
  171. package/docs/usage-credits.md +6 -1
  172. package/docs/usage-security.md +130 -0
  173. package/docs/usage-settlement.md +162 -0
  174. package/package.json +3 -1
  175. package/src/client/index.ts +9 -0
  176. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  177. package/src/client/paymentSource/resolver.test.ts +11 -207
  178. package/src/client/paymentSource/resolver.ts +54 -2
  179. package/src/client/settlement/execution.ts +24 -0
  180. package/src/client/usage/catalogPrices.ts +4 -2
  181. package/src/client/usage/client.ts +2 -2
  182. package/src/client/usage/creditBackingIsolation.test.ts +110 -0
  183. package/src/client/usage/creditCapacity.test.ts +80 -1
  184. package/src/client/usage/creditCapacity.ts +10 -1
  185. package/src/client/usage/creditDelivery.ts +4 -0
  186. package/src/client/usage/creditLifecycle.ts +2 -0
  187. package/src/client/usage/creditNative.ts +5 -0
  188. package/src/client/usage/creditProofBounds.test.ts +187 -0
  189. package/src/client/usage/creditProvider.test.ts +74 -0
  190. package/src/client/usage/creditProvider.ts +2 -0
  191. package/src/client/usage/creditReconciliation.ts +18 -3
  192. package/src/client/usage/creditRevenue.test.ts +105 -0
  193. package/src/client/usage/creditRevenue.ts +163 -0
  194. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  195. package/src/client/usage/creditSettlement.test.ts +66 -0
  196. package/src/client/usage/creditSettlement.ts +94 -0
  197. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  198. package/src/client/usage/creditTransport.fixtures.ts +31 -5
  199. package/src/client/usage/index.ts +9 -0
  200. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  201. package/src/client/usage/invoiceSale.test.ts +184 -0
  202. package/src/client/usage/invoiceSale.ts +155 -0
  203. package/src/client/usage/settlement.test.ts +179 -0
  204. package/src/client/usage/settlement.ts +81 -0
  205. package/src/client/usage/settlementClient.ts +84 -0
  206. package/src/client/usage/subscriptionCancellation.ts +3 -2
  207. package/src/client/usage/subscriptionCheckout.ts +7 -2
  208. package/src/client/usage/subscriptionClient.test.ts +60 -1
  209. package/src/client/usage/subscriptionLifecycle.ts +3 -2
  210. package/src/client/usage/subscriptionProvider.ts +27 -3
  211. package/src/component/_generated/component.ts +150 -1
  212. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  213. package/src/component/settlement/mutations.ts +10 -1
  214. package/src/component/settlement/schema.ts +26 -0
  215. package/src/component/settlement/settlement-claims.test.ts +54 -0
  216. package/src/component/usage/allowance.fixtures.ts +77 -0
  217. package/src/component/usage/allowance.test.ts +3 -66
  218. package/src/component/usage/allowanceBounds.test.ts +79 -0
  219. package/src/component/usage/historyIsolation.test.ts +124 -0
  220. package/src/component/usageCredits/accounting.fixtures.ts +96 -0
  221. package/src/component/usageCredits/accounting.test.ts +176 -82
  222. package/src/component/usageCredits/freshness.test.ts +33 -0
  223. package/src/component/usageCredits/helpers.ts +8 -0
  224. package/src/component/usageCredits/mutations.ts +83 -5
  225. package/src/component/usageCredits/quotas.test.ts +63 -0
  226. package/src/component/usageCredits/schema.ts +10 -0
  227. package/src/component/usageSubscriptions/history.test.ts +57 -0
  228. package/src/component/usageSubscriptions/history.ts +3 -1
  229. package/src/component/usageSubscriptions/mutations.ts +23 -0
  230. package/src/component/usageSubscriptions/schema.ts +1 -0
@@ -0,0 +1,173 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { componentRef } from "../webhooks/helpers.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { fixture } from "./creditSettlement.fixtures.js";
5
+ afterEach(() => vi.useRealTimers());
6
+ it("preserves original prepaid affiliate recovery through partial consumption/refund, dispute, won reinstatement and a held correction", async () => {
7
+ const f = await fixture({ fixedAmount: 7 });
8
+ expect(await f.settle()).toMatchObject({
9
+ status: "settled",
10
+ platformNet: 12,
11
+ });
12
+ const event = {
13
+ scope: f.purchase.scope,
14
+ binding: f.purchase.binding,
15
+ sourceEventId: "consume1",
16
+ quantity: "6",
17
+ occurredAt: 700,
18
+ },
19
+ subscription = f.view.bindings[0].subscription;
20
+ const reservation = await f.t.action((ctx) =>
21
+ f.client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
22
+ );
23
+ const receipt = await f.t.action((ctx) =>
24
+ f.client.usage.record(ctx as RunCtx, {
25
+ event,
26
+ subscription,
27
+ reservationId: reservation.reservationId,
28
+ }),
29
+ );
30
+ const claim = (state: "refund" | "open" | "won") =>
31
+ f.t.mutation(
32
+ componentRef(f.component, "connect/mutations/claimReversalSlices"),
33
+ {
34
+ sourceChargeId: "ch_topup1",
35
+ operationId: state === "refund" ? "re_partial" : "dp_credit",
36
+ mode:
37
+ state === "refund"
38
+ ? { kind: "fraction", chargeAmount: 20, amountRefunded: 10 }
39
+ : state === "won"
40
+ ? { kind: "fraction", chargeAmount: 20, amountRefunded: 0 }
41
+ : { kind: "amount", amount: 20 },
42
+ commissionExposure:
43
+ state === "refund"
44
+ ? {
45
+ kind: "refund",
46
+ chargeAmount: 20,
47
+ principal: 10,
48
+ finalized: true,
49
+ refundId: "re_partial",
50
+ }
51
+ : {
52
+ kind: "dispute",
53
+ chargeAmount: 20,
54
+ principal: 20,
55
+ finalized: false,
56
+ disputeState: state,
57
+ disputeId: "dp_credit",
58
+ refundedPrincipal: 10,
59
+ },
60
+ },
61
+ );
62
+ const rows = async () =>
63
+ (await f.t.query(
64
+ componentRef(f.component, "settlement/queries/listAffiliateObligations"),
65
+ {
66
+ affiliateAccountId: "acct_affiliate",
67
+ currency: "usd",
68
+ paginationOpts: { numItems: 10, cursor: null },
69
+ },
70
+ )) as {
71
+ page: Array<{
72
+ _id: string;
73
+ finalizedAmount: number;
74
+ provisionalAmount: number;
75
+ recoveredAmount: number;
76
+ restoredAmount: number;
77
+ }>;
78
+ };
79
+ f.state.refundedAmount = 10;
80
+ await claim("refund");
81
+ await f.t.mutation(
82
+ componentRef(f.component, "connect/mutations/recordTransferReversal"),
83
+ {
84
+ stripeTransferId: "tr_0",
85
+ reversedAmount: 4,
86
+ receipt: {
87
+ stripeReversalId: "trr_partial",
88
+ operationId: "re_partial",
89
+ amount: 4,
90
+ },
91
+ },
92
+ );
93
+ await claim("refund");
94
+ expect((await rows()).page[0]).toMatchObject({
95
+ finalizedAmount: 4,
96
+ recoveredAmount: 4,
97
+ });
98
+ await claim("open");
99
+ const obligationId = (await rows()).page[0]._id;
100
+ const recover = (await f.t.mutation(
101
+ componentRef(f.component, "affiliateRecovery/mutations/reserveOperation"),
102
+ { obligationId, kind: "recovery", now: 700000 },
103
+ )) as { _id: string; amount: number };
104
+ expect(recover.amount).toBe(3);
105
+ await f.t.mutation(
106
+ componentRef(f.component, "affiliateRecovery/mutations/beginOperation"),
107
+ { operationId: recover._id },
108
+ );
109
+ await f.t.mutation(
110
+ componentRef(f.component, "affiliateRecovery/mutations/completeOperation"),
111
+ {
112
+ operationId: recover._id,
113
+ state: "succeeded",
114
+ receiptId: "trr_dispute",
115
+ confirmedTransferReversed: 7,
116
+ },
117
+ );
118
+ await claim("won");
119
+ const restore = (await f.t.mutation(
120
+ componentRef(f.component, "affiliateRecovery/mutations/reserveOperation"),
121
+ { obligationId, kind: "restoration", now: 700000 },
122
+ )) as { _id: string; amount: number };
123
+ expect(restore.amount).toBe(3);
124
+ await f.t.mutation(
125
+ componentRef(f.component, "affiliateRecovery/mutations/beginOperation"),
126
+ { operationId: restore._id },
127
+ );
128
+ const confirmation = {
129
+ operationId: restore._id,
130
+ state: "succeeded",
131
+ receiptId: "tr_restore",
132
+ };
133
+ await f.t.mutation(
134
+ componentRef(f.component, "affiliateRecovery/mutations/completeOperation"),
135
+ confirmation,
136
+ );
137
+ await f.t.mutation(
138
+ componentRef(f.component, "affiliateRecovery/mutations/completeOperation"),
139
+ confirmation,
140
+ );
141
+ expect((await rows()).page[0]).toMatchObject({
142
+ finalizedAmount: 4,
143
+ provisionalAmount: 0,
144
+ recoveredAmount: 7,
145
+ restoredAmount: 3,
146
+ });
147
+ expect(await f.settle()).toMatchObject({
148
+ status: "rejected",
149
+ reason: "payment_not_payable",
150
+ });
151
+ expect(
152
+ await f.t.action((ctx) =>
153
+ f.client.usage.requestCorrection(
154
+ ctx as RunCtx,
155
+ {
156
+ scope: event.scope,
157
+ eventId: receipt.eventId,
158
+ correctionId: "after_refund",
159
+ actor: "operator1",
160
+ reason: "duplicate activity",
161
+ operation: "cancel",
162
+ },
163
+ f.options,
164
+ ),
165
+ ),
166
+ ).toMatchObject({ state: "held", restoredQuantity: "0" });
167
+ expect(
168
+ await f.t.query((ctx) =>
169
+ f.client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
170
+ ),
171
+ ).toMatchObject({ consumedQuantity: "6" });
172
+ expect(f.native).toHaveLength(1);
173
+ });
@@ -7,7 +7,12 @@ const response = (value: unknown) =>
7
7
  new Response(JSON.stringify(value), {
8
8
  headers: { "content-type": "application/json" },
9
9
  });
10
- export function creditFixture() {
10
+ export function creditFixture(
11
+ intercept?: (
12
+ input: string,
13
+ init?: RequestInit,
14
+ ) => Promise<Response | undefined>,
15
+ ) {
11
16
  vi.useFakeTimers();
12
17
  vi.setSystemTime(700000);
13
18
  const calls: Array<{
@@ -25,6 +30,13 @@ export function creditFixture() {
25
30
  incomplete: false,
26
31
  canceled: false,
27
32
  refunded: false,
33
+ refundedAmount: 0,
34
+ disputed: false,
35
+ feePending: false,
36
+ processingFee: 1,
37
+ paymentCustomer: "cus_buyer",
38
+ chargeCustomer: "cus_buyer",
39
+ summaryCustomer: "cus_buyer",
28
40
  failGrant: false,
29
41
  wrongPayer: false,
30
42
  paymentId: "pi_topup1",
@@ -32,6 +44,8 @@ export function creditFixture() {
32
44
  metadata: {} as Record<string, string>,
33
45
  };
34
46
  const f = fixture(false, false, async (input, init) => {
47
+ const override = await intercept?.(input, init);
48
+ if (override) return override;
35
49
  const path = new URL(input).pathname,
36
50
  method = init?.method ?? "GET",
37
51
  body = new URLSearchParams(String(init?.body ?? ""));
@@ -68,7 +82,7 @@ export function creditFixture() {
68
82
  });
69
83
  if (path === "/v1/billing/credit_balance_summary")
70
84
  return response({
71
- customer: "cus_buyer",
85
+ customer: state.summaryCustomer,
72
86
  customer_account: "acct_buyer",
73
87
  livemode: false,
74
88
  balances: [
@@ -219,7 +233,7 @@ export function creditFixture() {
219
233
  id: state.paymentId,
220
234
  object: "payment_intent",
221
235
  customer_account: state.wrongPayer ? "acct_other" : "acct_buyer",
222
- customer: "cus_buyer",
236
+ customer: state.paymentCustomer,
223
237
  livemode: false,
224
238
  currency: "usd",
225
239
  amount: 20,
@@ -244,8 +258,20 @@ export function creditFixture() {
244
258
  currency: "usd",
245
259
  livemode: false,
246
260
  refunded: state.refunded,
247
- amount_refunded: state.refunded ? 20 : 0,
248
- disputed: false,
261
+ amount_refunded: state.refunded ? 20 : state.refundedAmount,
262
+ disputed: state.disputed,
263
+ customer: state.chargeCustomer,
264
+ balance_transaction: state.feePending
265
+ ? null
266
+ : {
267
+ id: "txn_topup1",
268
+ object: "balance_transaction",
269
+ source: "ch_topup1",
270
+ currency: "usd",
271
+ amount: 20,
272
+ fee: state.processingFee,
273
+ net: 20 - state.processingFee,
274
+ },
249
275
  }
250
276
  : null,
251
277
  };
@@ -99,3 +99,12 @@ export type {
99
99
  UsageCorrectionHistoryPage,
100
100
  UsageCorrectionHistoryRecord,
101
101
  } from "./correctionRead.js";
102
+
103
+ export type {
104
+ UsageInvoiceSaleOptions,
105
+ VerifiedUsageInvoiceSale,
106
+ } from "./invoiceSale.js";
107
+ export type { UsageInvoiceSettlementOptions } from "./settlement.js";
108
+ export type { UsageCreditRevenue } from "./creditRevenue.js";
109
+
110
+ export type { UsageCreditSettlementOptions } from "./creditSettlement.js";
@@ -0,0 +1,103 @@
1
+ import { fixture as sourceFixture } from "../paymentSource/resolver.fixtures.js";
2
+ import { prepareUsageRecord } from "./records.js";
3
+ export function fixture() {
4
+ const f = sourceFixture();
5
+ const scope = {
6
+ stripeAccountId: "acct_platform",
7
+ customerAccount: "acct_customer",
8
+ meterId: "mtr_calls",
9
+ livemode: false,
10
+ };
11
+ const period = { start: 600, end: 1200 };
12
+ const binding = prepareUsageRecord({
13
+ scope,
14
+ binding: {
15
+ stripeCustomerId: "cus_buyer",
16
+ stripePriceId: "price_original",
17
+ eventName: "calls",
18
+ plan: {
19
+ key: "calls",
20
+ version: "v1",
21
+ model: "pay_as_you_go",
22
+ unit: { name: "call", precision: 0 },
23
+ rate: { currency: "usd", unitAmountDecimal: "2" },
24
+ },
25
+ },
26
+ sourceEventId: "proof",
27
+ quantity: "0",
28
+ occurredAt: 600,
29
+ }).binding;
30
+ const meter = {
31
+ id: "mtr_calls",
32
+ livemode: false,
33
+ status: "active",
34
+ event_name: "calls",
35
+ default_aggregation: { formula: "sum" },
36
+ customer_mapping: {
37
+ type: "by_id",
38
+ event_payload_key: "stripe_customer_id",
39
+ },
40
+ value_settings: { event_payload_key: "value" },
41
+ event_time_window: null,
42
+ };
43
+ const price = {
44
+ id: "price_original",
45
+ active: true,
46
+ livemode: false,
47
+ currency: "usd",
48
+ type: "recurring",
49
+ product: "prod_original",
50
+ lookup_key: "calls",
51
+ billing_scheme: "per_unit",
52
+ unit_amount_decimal: "2",
53
+ transform_quantity: null,
54
+ recurring: {
55
+ interval: "month",
56
+ interval_count: 1,
57
+ usage_type: "metered",
58
+ meter: "mtr_calls",
59
+ },
60
+ };
61
+ f.extra.set("/v1/account", { id: "acct_platform" });
62
+ f.extra.set("/v1/balance", { livemode: false });
63
+ f.extra.set("/v1/billing/meters/mtr_calls", meter);
64
+ f.extra.set("/v1/customers/acct_customer", {
65
+ id: "cus_buyer",
66
+ customer_account: "acct_customer",
67
+ livemode: false,
68
+ });
69
+ f.extra.set("/v1/prices/price_original", price);
70
+ Object.assign(f.payment, { customer: "cus_buyer" });
71
+ Object.assign(f.payment.latest_charge, {
72
+ customer: "cus_buyer",
73
+ refunded: false,
74
+ });
75
+ Object.assign(f.subscription, { customer: "cus_buyer" });
76
+ Object.assign(f.line, {
77
+ period,
78
+ quantity: null,
79
+ quantity_decimal: "500",
80
+ pretax_credit_amounts: [],
81
+ });
82
+ Object.assign(f.invoice, {
83
+ customer: "cus_buyer",
84
+ status_transitions: { finalized_at: 1200 },
85
+ lines: { data: [f.line], has_more: false },
86
+ });
87
+ const input = {
88
+ scope,
89
+ binding,
90
+ subscription: {
91
+ subscriptionId: "sub_source",
92
+ subscriptionItemId: "si_source",
93
+ stripePriceId: "price_original",
94
+ period,
95
+ interval: "month" as const,
96
+ },
97
+ period,
98
+ invoiceId: "in_source",
99
+ paymentIntentId: "pi_source",
100
+ gross: 1000,
101
+ };
102
+ return { ...f, meter, price, input };
103
+ }
@@ -0,0 +1,184 @@
1
+ import { BetterStripe } from "../index.js";
2
+ import { componentsGeneric } from "convex/server";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { expect, it } from "vitest";
5
+ import { fixture } from "./invoiceSale.fixtures.js";
6
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
7
+ it("resolves original metered invoice funding and actual costs even after current subscription prices change", async () => {
8
+ const f = fixture();
9
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
10
+ status: "ready",
11
+ value: {
12
+ meterId: "mtr_calls",
13
+ stripePriceId: "price_original",
14
+ stripeProductId: "prod_original",
15
+ invoicePaymentId: "inpay_source",
16
+ gross: 1000,
17
+ processingFee: 50,
18
+ period: { start: 600, end: 1200 },
19
+ },
20
+ });
21
+ expect(
22
+ f.requests.every((r) => r.method === "GET" && r.account === "undefined"),
23
+ ).toBe(true);
24
+ });
25
+
26
+ it("verifies included-overage cash against its original graduated price", async () => {
27
+ const f = fixture();
28
+ const plan = {
29
+ ...f.input.binding.plan,
30
+ model: "included_overage" as const,
31
+ includedQuantity: "10",
32
+ reset: "billing_period" as const,
33
+ };
34
+ Object.assign(f.price, {
35
+ billing_scheme: "tiered",
36
+ tiers_mode: "graduated",
37
+ unit_amount_decimal: null,
38
+ tiers: [
39
+ { up_to: 10, unit_amount_decimal: "0", flat_amount: null },
40
+ { up_to: null, unit_amount_decimal: "2", flat_amount: null },
41
+ ],
42
+ });
43
+ expect(
44
+ await getUsageInvoiceSale(f.sdk, {
45
+ ...f.input,
46
+ binding: { ...f.input.binding, plan },
47
+ }),
48
+ ).toMatchObject({
49
+ status: "ready",
50
+ value: { model: "included_overage", gross: 1000 },
51
+ });
52
+ });
53
+ it("does not recognize zero invoices, credit consumption, refunds, disputes or incomplete funding as a new sale", async () => {
54
+ for (const condition of [
55
+ "zero",
56
+ "prepaid",
57
+ "refund",
58
+ "dispute",
59
+ "incomplete",
60
+ "automatic_transfer",
61
+ ]) {
62
+ const f = fixture();
63
+ if (condition === "zero") f.invoice.amount_paid = 0;
64
+ if (condition === "refund") f.payment.latest_charge.amount_refunded = 100;
65
+ if (condition === "dispute") f.payment.latest_charge.disputed = true;
66
+ if (condition === "incomplete")
67
+ f.pages.set("funding:", { data: [f.funding], has_more: true });
68
+ if (condition === "automatic_transfer")
69
+ Object.assign(f.payment, {
70
+ transfer_data: { destination: "acct_seller" },
71
+ });
72
+ const input =
73
+ condition === "prepaid"
74
+ ? {
75
+ ...f.input,
76
+ binding: {
77
+ ...f.input.binding,
78
+ plan: {
79
+ ...f.input.binding.plan,
80
+ model: "prepaid" as const,
81
+ insufficientBalance: "reject" as const,
82
+ },
83
+ },
84
+ }
85
+ : f.input;
86
+ expect((await getUsageInvoiceSale(f.sdk, input)).status).not.toBe("ready");
87
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
88
+ }
89
+ });
90
+ it("rejects foreign original bindings, periods and mapped payer identities", async () => {
91
+ for (const condition of [
92
+ "realm",
93
+ "mode",
94
+ "payer",
95
+ "customer",
96
+ "meter",
97
+ "price_meter",
98
+ "product",
99
+ "period",
100
+ "item",
101
+ "proration",
102
+ ]) {
103
+ const f = fixture();
104
+ if (condition === "realm")
105
+ f.extra.set("/v1/account", { id: "acct_foreign" });
106
+ if (condition === "mode") f.payment.livemode = true;
107
+ if (condition === "payer") f.invoice.customer_account = "acct_other";
108
+ if (condition === "customer")
109
+ Object.assign(f.payment.latest_charge, { customer: "cus_other" });
110
+ if (condition === "meter") f.meter.id = "mtr_other";
111
+ if (condition === "price_meter") f.price.recurring.meter = "mtr_other";
112
+ if (condition === "product")
113
+ f.line.pricing.price_details.product = "prod_other";
114
+ if (condition === "period")
115
+ Object.assign(f.line, { period: { start: 1200, end: 1800 } });
116
+ if (condition === "item")
117
+ f.line.parent.subscription_item_details.subscription_item = "si_other";
118
+ if (condition === "proration")
119
+ f.line.parent.subscription_item_details.proration = true;
120
+ expect(
121
+ (await getUsageInvoiceSale(f.sdk, f.input)).status,
122
+ condition,
123
+ ).not.toBe("ready");
124
+ }
125
+ });
126
+
127
+ it("can settle original paid invoices after their immutable price is archived", async () => {
128
+ const f = fixture();
129
+ f.price.active = false;
130
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
131
+ status: "ready",
132
+ value: { stripePriceId: "price_original" },
133
+ });
134
+ });
135
+
136
+ it("requires the complete original invoice-line read to retain the same item and billing period", async () => {
137
+ for (const change of ["item", "period", "id"]) {
138
+ const f = fixture();
139
+ const line = structuredClone(f.line);
140
+ if (change === "item")
141
+ line.parent.subscription_item_details.subscription_item = "si_other";
142
+ if (change === "period")
143
+ Object.assign(line, { period: { start: 1200, end: 1800 } });
144
+ if (change === "id") line.id = "il_other";
145
+ f.extra.set("/v1/invoices/in_source/lines", {
146
+ object: "list",
147
+ data: [line],
148
+ has_more: false,
149
+ });
150
+ expect((await getUsageInvoiceSale(f.sdk, f.input)).status, change).not.toBe(
151
+ "ready",
152
+ );
153
+ }
154
+ });
155
+
156
+ it("keeps an unpaid invoice pending until native payment is verified", async () => {
157
+ const f = fixture();
158
+ f.invoice.status = "open";
159
+ f.invoice.amount_paid = 0;
160
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toEqual({
161
+ status: "not_ready",
162
+ reason: "provider_pending",
163
+ retryable: true,
164
+ });
165
+ });
166
+
167
+ it("exposes the scoped reader through stripe.usage with runtime-only credentials and the original API version", async () => {
168
+ const f = fixture(),
169
+ client = new BetterStripe(
170
+ componentsGeneric().betterStripe as unknown as Component,
171
+ );
172
+ expect(
173
+ await client.usage.getInvoiceSale({} as RunCtx, f.input, {
174
+ stripeSecretKey: "sk_test_usage_sale",
175
+ httpClient: f.httpClient,
176
+ }),
177
+ ).toMatchObject({ status: "ready" });
178
+ expect(
179
+ f.requests.every(
180
+ (r) =>
181
+ r.version === f.input.binding.apiVersion && r.account === "undefined",
182
+ ),
183
+ ).toBe(true);
184
+ });
@@ -0,0 +1,155 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type {
4
+ FinancialOutcome,
5
+ FinancialUnavailable,
6
+ } from "../financialOutcomes/contracts.js";
7
+ import { resolveVerifiedPaymentSource } from "../paymentSource/resolver.js";
8
+ import type { VerifiedPaymentSource } from "../paymentSource/contracts.js";
9
+ import {
10
+ observationOptions,
11
+ type UsageObservationOptions,
12
+ } from "./observationTypes.js";
13
+ import { observeUsageInvoice } from "./invoiceObservation.js";
14
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
15
+ export type UsageInvoiceSaleOptions = UsageObservationOptions & {
16
+ invoiceId: string;
17
+ paymentIntentId: string;
18
+ gross: number;
19
+ };
20
+ export type VerifiedUsageInvoiceSale = VerifiedPaymentSource & {
21
+ stripeAccountId: string;
22
+ meterId: string;
23
+ subscriptionItemId: string;
24
+ period: { start: number; end: number };
25
+ model: "pay_as_you_go" | "included_overage";
26
+ };
27
+ const unsupported = (): FinancialUnavailable => ({
28
+ status: "rejected",
29
+ reason: "unsupported_source",
30
+ retryable: false,
31
+ });
32
+ /** Native invoice/payment provenance only. Host authorizes original seller/product policy. */
33
+ export async function getUsageInvoiceSale(
34
+ stripe: Stripe,
35
+ input: UsageInvoiceSaleOptions,
36
+ ): Promise<FinancialOutcome<VerifiedUsageInvoiceSale>> {
37
+ try {
38
+ const opts = observationOptions(input);
39
+ z.string()
40
+ .regex(/^pi_[a-zA-Z0-9]+$/)
41
+ .max(100)
42
+ .parse(input.paymentIntentId);
43
+ if (opts.binding.plan.model === "prepaid") return unsupported();
44
+ const invoice = await observeUsageInvoice(stripe, opts, input.invoiceId);
45
+ if (invoice.status !== "available") return unsupported();
46
+ const value = invoice.value;
47
+ if (value.status === "draft" || value.status === "open")
48
+ return {
49
+ status: "not_ready",
50
+ reason: "provider_pending",
51
+ retryable: true,
52
+ };
53
+ if (
54
+ value.status !== "paid" ||
55
+ !value.finalized ||
56
+ BigInt(value.amountPaid) <= 0n
57
+ )
58
+ return {
59
+ status: "rejected",
60
+ reason: "payment_not_payable",
61
+ retryable: false,
62
+ };
63
+ const line = value.lines[0];
64
+ if (
65
+ !value.linesComplete ||
66
+ value.meterAmount.status !== "available" ||
67
+ value.lines.length !== 1 ||
68
+ !line ||
69
+ line.proration ||
70
+ line.creditAppliedAmount !== "0" ||
71
+ line.nativePeriod.start !== opts.subscription.period.start ||
72
+ line.nativePeriod.end !== opts.subscription.period.end ||
73
+ opts.period.start !== opts.subscription.period.start ||
74
+ opts.period.end !== opts.subscription.period.end
75
+ )
76
+ return unsupported();
77
+ const [price, customer] = await Promise.all([
78
+ stripe.prices.retrieve(opts.binding.stripePriceId, { expand: ["tiers"] }),
79
+ stripe.customers.retrieve(opts.scope.customerAccount),
80
+ ]);
81
+ if (
82
+ price.id !== opts.binding.stripePriceId ||
83
+ customer.deleted ||
84
+ customer.id !== opts.binding.stripeCustomerId ||
85
+ customer.customer_account !== opts.scope.customerAccount ||
86
+ customer.livemode !== opts.scope.livemode
87
+ )
88
+ return {
89
+ status: "conflict",
90
+ reason: "identity_changed",
91
+ retryable: false,
92
+ };
93
+ verifyPinnedUsagePrice(
94
+ price,
95
+ {
96
+ stripeAccountId: opts.scope.stripeAccountId,
97
+ livemode: opts.scope.livemode,
98
+ },
99
+ opts.binding.plan,
100
+ opts.scope.meterId,
101
+ false,
102
+ );
103
+ const source = await resolveVerifiedPaymentSource(
104
+ stripe,
105
+ {
106
+ paymentIntentId: input.paymentIntentId,
107
+ invoiceId: input.invoiceId,
108
+ subscriptionId: opts.subscription.subscriptionId,
109
+ customerAccountId: opts.scope.customerAccount,
110
+ gross: input.gross,
111
+ currency: opts.binding.plan.rate.currency,
112
+ },
113
+ {
114
+ requirePayable: true,
115
+ customerId: opts.binding.stripeCustomerId,
116
+ invoiceLine: {
117
+ id: line.lineId,
118
+ subscriptionItemId: opts.subscription.subscriptionItemId,
119
+ period: opts.subscription.period,
120
+ },
121
+ },
122
+ );
123
+ if (source.status !== "ready") return source;
124
+ const productId =
125
+ typeof price.product === "string" ? price.product : price.product.id;
126
+ if (
127
+ source.value.stripePriceId !== opts.binding.stripePriceId ||
128
+ source.value.stripeProductId !== productId ||
129
+ source.value.livemode !== opts.scope.livemode ||
130
+ String(source.value.gross) !== value.amountPaid
131
+ )
132
+ return {
133
+ status: "conflict",
134
+ reason: "identity_changed",
135
+ retryable: false,
136
+ };
137
+ return {
138
+ status: "ready",
139
+ value: {
140
+ ...source.value,
141
+ stripeAccountId: opts.scope.stripeAccountId,
142
+ meterId: opts.scope.meterId,
143
+ subscriptionItemId: opts.subscription.subscriptionItemId,
144
+ period: opts.subscription.period,
145
+ model: opts.binding.plan.model,
146
+ },
147
+ };
148
+ } catch {
149
+ return {
150
+ status: "unknown",
151
+ reason: "provider_outcome_unknown",
152
+ retryable: false,
153
+ };
154
+ }
155
+ }