@fantastic.dev/better-stripe 0.59.0 → 0.60.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 (124) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +650 -44
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +309 -6
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +618 -12
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +325 -22
  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/creditRevenue.d.ts +22 -0
  32. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  33. package/dist/client/usage/creditRevenue.js +118 -0
  34. package/dist/client/usage/creditRevenue.js.map +1 -0
  35. package/dist/client/usage/creditSettlement.d.ts +29 -0
  36. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  37. package/dist/client/usage/creditSettlement.fixtures.d.ts +215 -0
  38. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  39. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  40. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  41. package/dist/client/usage/creditSettlement.js +70 -0
  42. package/dist/client/usage/creditSettlement.js.map +1 -0
  43. package/dist/client/usage/creditTransport.fixtures.d.ts +7 -1
  44. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  45. package/dist/client/usage/creditTransport.fixtures.js +25 -4
  46. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  47. package/dist/client/usage/index.d.ts +4 -0
  48. package/dist/client/usage/index.d.ts.map +1 -1
  49. package/dist/client/usage/invoiceSale.d.ts +22 -0
  50. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  51. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  52. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  53. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  54. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  55. package/dist/client/usage/invoiceSale.js +117 -0
  56. package/dist/client/usage/invoiceSale.js.map +1 -0
  57. package/dist/client/usage/observationClient.d.ts +2 -2
  58. package/dist/client/usage/observationClient.d.ts.map +1 -1
  59. package/dist/client/usage/settlement.d.ts +32 -0
  60. package/dist/client/usage/settlement.d.ts.map +1 -0
  61. package/dist/client/usage/settlement.js +60 -0
  62. package/dist/client/usage/settlement.js.map +1 -0
  63. package/dist/client/usage/settlementClient.d.ts +51 -0
  64. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  65. package/dist/client/usage/settlementClient.js +35 -0
  66. package/dist/client/usage/settlementClient.js.map +1 -0
  67. package/dist/component/_generated/component.d.ts +125 -0
  68. package/dist/component/_generated/component.d.ts.map +1 -1
  69. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  70. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  71. package/dist/component/earnings/triggers.d.ts +156 -6
  72. package/dist/component/earnings/triggers.d.ts.map +1 -1
  73. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  74. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  75. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  76. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  77. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  78. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  79. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  80. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  81. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  82. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  83. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  84. package/dist/component/schema.d.ts +309 -6
  85. package/dist/component/settlement/mutations.d.ts +50 -0
  86. package/dist/component/settlement/mutations.d.ts.map +1 -1
  87. package/dist/component/settlement/mutations.js +8 -1
  88. package/dist/component/settlement/mutations.js.map +1 -1
  89. package/dist/component/settlement/queries.d.ts +25 -0
  90. package/dist/component/settlement/queries.d.ts.map +1 -1
  91. package/dist/component/settlement/schema.d.ts +128 -1
  92. package/dist/component/settlement/schema.d.ts.map +1 -1
  93. package/dist/component/settlement/schema.js +22 -0
  94. package/dist/component/settlement/schema.js.map +1 -1
  95. package/docs/README.md +2 -0
  96. package/docs/settlement.md +4 -0
  97. package/docs/usage-settlement.md +162 -0
  98. package/package.json +2 -1
  99. package/src/client/index.ts +9 -0
  100. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  101. package/src/client/paymentSource/resolver.test.ts +11 -207
  102. package/src/client/paymentSource/resolver.ts +54 -2
  103. package/src/client/settlement/execution.ts +24 -0
  104. package/src/client/usage/catalogPrices.ts +4 -2
  105. package/src/client/usage/client.ts +2 -2
  106. package/src/client/usage/creditRevenue.test.ts +105 -0
  107. package/src/client/usage/creditRevenue.ts +163 -0
  108. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  109. package/src/client/usage/creditSettlement.test.ts +66 -0
  110. package/src/client/usage/creditSettlement.ts +94 -0
  111. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  112. package/src/client/usage/creditTransport.fixtures.ts +29 -4
  113. package/src/client/usage/index.ts +9 -0
  114. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  115. package/src/client/usage/invoiceSale.test.ts +184 -0
  116. package/src/client/usage/invoiceSale.ts +155 -0
  117. package/src/client/usage/settlement.test.ts +179 -0
  118. package/src/client/usage/settlement.ts +81 -0
  119. package/src/client/usage/settlementClient.ts +84 -0
  120. package/src/component/_generated/component.ts +110 -0
  121. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  122. package/src/component/settlement/mutations.ts +10 -1
  123. package/src/component/settlement/schema.ts +26 -0
  124. package/src/component/settlement/settlement-claims.test.ts +54 -0
@@ -0,0 +1,105 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { creditFixture } from "./creditTransport.fixtures.js";
5
+ afterEach(() => vi.useRealTimers());
6
+ it("recognizes only the original verified paid credit purchase, without creating a second sale as units are consumed", async () => {
7
+ const f = creditFixture(),
8
+ client = new BetterStripe(f.component),
9
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
10
+ const view = await f.ready();
11
+ await f.t.action((ctx) =>
12
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
13
+ );
14
+ f.state.paid = true;
15
+ await f.t.action((ctx) =>
16
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
17
+ );
18
+ const read = () =>
19
+ f.t.action((ctx) =>
20
+ client.usage.getCreditPurchaseRevenue(ctx as RunCtx, f.purchase, options),
21
+ );
22
+ const first = await read();
23
+ expect(first).toMatchObject({
24
+ status: "ready",
25
+ value: {
26
+ paymentIntentId: "pi_topup1",
27
+ chargeId: "ch_topup1",
28
+ creditGrantId: "credgr_topup1",
29
+ gross: 20,
30
+ processingFee: 1,
31
+ ownership: "issuer",
32
+ stripePriceId: "price_calls",
33
+ stripeProductId: "prod_calls",
34
+ },
35
+ });
36
+ const event = {
37
+ ...f.purchase,
38
+ sourceEventId: "consume1",
39
+ quantity: "6",
40
+ occurredAt: 700,
41
+ };
42
+ const {
43
+ ownership: _ownership,
44
+ purchaseId: _purchase,
45
+ rollover: _rollover,
46
+ ...usage
47
+ } = event;
48
+ const subscription = view.bindings[0].subscription;
49
+ const reservation = await f.t.action((ctx) =>
50
+ client.usage.reserveCredits(ctx as RunCtx, { event: usage, subscription }),
51
+ );
52
+ await f.t.action((ctx) =>
53
+ client.usage.record(ctx as RunCtx, {
54
+ event: usage,
55
+ subscription,
56
+ reservationId: reservation.reservationId,
57
+ }),
58
+ );
59
+ expect(await read()).toEqual(first);
60
+ f.state.refunded = true;
61
+ expect(await read()).toMatchObject({
62
+ status: "rejected",
63
+ reason: "payment_not_payable",
64
+ });
65
+ expect(
66
+ f.calls.filter(
67
+ (c) => c.path === "/v1/payment_intents" && c.method === "POST",
68
+ ),
69
+ ).toHaveLength(1);
70
+ });
71
+
72
+ it("holds foreign mapped native customers and missing processing fees", async () => {
73
+ for (const condition of [
74
+ "payment_customer",
75
+ "charge_customer",
76
+ "fee_pending",
77
+ "dispute",
78
+ ]) {
79
+ const f = creditFixture(),
80
+ client = new BetterStripe(f.component),
81
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
82
+ await f.ready();
83
+ await f.t.action((ctx) =>
84
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
85
+ );
86
+ f.state.paid = true;
87
+ await f.t.action((ctx) =>
88
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
89
+ );
90
+ if (condition === "payment_customer") f.state.paymentCustomer = "cus_other";
91
+ if (condition === "charge_customer") f.state.chargeCustomer = "cus_other";
92
+ if (condition === "fee_pending") f.state.feePending = true;
93
+ if (condition === "dispute") f.state.disputed = true;
94
+ const result = await f.t.action((ctx) =>
95
+ client.usage.getCreditPurchaseRevenue(ctx as RunCtx, f.purchase, options),
96
+ );
97
+ expect(result.status, condition).not.toBe("ready");
98
+ if (condition === "fee_pending")
99
+ expect(result).toMatchObject({
100
+ status: "not_ready",
101
+ reason: "fee_pending",
102
+ retryable: true,
103
+ });
104
+ }
105
+ });
@@ -0,0 +1,163 @@
1
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
2
+ import type Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import type { FinancialOutcome } from "../financialOutcomes/contracts.js";
5
+ import type { UsageCreditPurchaseOptions } from "./creditTerms.js";
6
+ import { UsageCreditRecoveryError } from "./creditTerms.js";
7
+ import { findCreditPurchase } from "./creditRead.js";
8
+ import {
9
+ verifyCreditRealm,
10
+ paymentIdentity,
11
+ verifiedCreditPayment,
12
+ } from "./creditNative.js";
13
+ import { paymentCreditProof } from "./creditProofs.js";
14
+ import { saleAmountFailure } from "../paymentSource/economics.js";
15
+ export type UsageCreditRevenue = {
16
+ purchaseId: string;
17
+ paymentIntentId: string;
18
+ chargeId: string;
19
+ creditGrantId: string;
20
+ stripeAccountId: string;
21
+ customerAccount: string;
22
+ livemode: boolean;
23
+ stripePriceId: string;
24
+ stripeProductId: string;
25
+ gross: number;
26
+ processingFee: number;
27
+ currency: string;
28
+ ownership: "issuer";
29
+ };
30
+ /** Original issuer-service revenue only. Credit consumption never creates a second sale. */
31
+ export async function getCreditPurchaseRevenue(
32
+ stripe: Stripe,
33
+ component: Component,
34
+ ctx: RunCtx,
35
+ input: UsageCreditPurchaseOptions,
36
+ ): Promise<FinancialOutcome<UsageCreditRevenue>> {
37
+ try {
38
+ const { row, terms } = await findCreditPurchase(component, ctx, input);
39
+ if (row.state === "frozen" || row.state === "canceled")
40
+ return {
41
+ status: "rejected",
42
+ reason: "payment_not_payable",
43
+ retryable: false,
44
+ };
45
+ if (
46
+ row.state !== "ready" ||
47
+ !row.paymentIntentId ||
48
+ !row.paymentProofJson ||
49
+ !row.creditGrantId
50
+ )
51
+ return {
52
+ status: "not_ready",
53
+ reason: "provider_pending",
54
+ retryable: true,
55
+ };
56
+ await verifyCreditRealm(stripe, terms, false);
57
+ const [payment, price] = await Promise.all([
58
+ stripe.paymentIntents.retrieve(row.paymentIntentId, {
59
+ expand: ["latest_charge.balance_transaction"],
60
+ }),
61
+ stripe.prices.retrieve(terms.binding.stripePriceId, {
62
+ expand: ["tiers"],
63
+ }),
64
+ ]);
65
+ paymentIdentity(payment, terms, row.key, row.paymentIntentId);
66
+ const proof = verifiedCreditPayment(payment, terms),
67
+ retained = paymentCreditProof.parse(JSON.parse(row.paymentProofJson));
68
+ if (
69
+ !proof ||
70
+ proof.chargeId !== retained.chargeId ||
71
+ price.id !== terms.binding.stripePriceId
72
+ )
73
+ return {
74
+ status: "conflict",
75
+ reason: "identity_changed",
76
+ retryable: false,
77
+ };
78
+ verifyPinnedUsagePrice(
79
+ price,
80
+ {
81
+ stripeAccountId: terms.scope.stripeAccountId,
82
+ livemode: terms.scope.livemode,
83
+ },
84
+ terms.binding.plan,
85
+ terms.scope.meterId,
86
+ false,
87
+ );
88
+ const charge = payment.latest_charge;
89
+ if (!charge || typeof charge === "string")
90
+ return {
91
+ status: "not_ready",
92
+ reason: "provider_pending",
93
+ retryable: true,
94
+ };
95
+ const customerId = (value: string | { id: string } | null | undefined) =>
96
+ typeof value === "string" ? value : value?.id;
97
+ if (
98
+ customerId(payment.customer) !== terms.binding.stripeCustomerId ||
99
+ customerId(charge.customer) !== terms.binding.stripeCustomerId ||
100
+ charge.transfer
101
+ )
102
+ return {
103
+ status: "conflict",
104
+ reason: "identity_changed",
105
+ retryable: false,
106
+ };
107
+ const balanceRef = charge.balance_transaction;
108
+ if (!balanceRef)
109
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
110
+ const balance =
111
+ typeof balanceRef === "string"
112
+ ? await stripe.balanceTransactions.retrieve(balanceRef)
113
+ : balanceRef;
114
+ const sourceId =
115
+ typeof balance.source === "string" ? balance.source : balance.source?.id;
116
+ if (
117
+ (typeof balanceRef === "string" && balance.id !== balanceRef) ||
118
+ balance.object !== "balance_transaction" ||
119
+ sourceId !== charge.id ||
120
+ saleAmountFailure(payment, charge, balance) ||
121
+ balance.amount !== terms.amount ||
122
+ balance.net !== balance.amount - balance.fee ||
123
+ !Number.isSafeInteger(balance.amount) ||
124
+ !Number.isSafeInteger(balance.net)
125
+ )
126
+ return {
127
+ status: "rejected",
128
+ reason: "unsupported_source",
129
+ retryable: false,
130
+ };
131
+ return {
132
+ status: "ready",
133
+ value: {
134
+ purchaseId: terms.purchaseId,
135
+ paymentIntentId: proof.paymentIntentId,
136
+ chargeId: proof.chargeId,
137
+ creditGrantId: row.creditGrantId,
138
+ stripeAccountId: terms.scope.stripeAccountId,
139
+ customerAccount: terms.scope.customerAccount,
140
+ livemode: terms.scope.livemode,
141
+ stripePriceId: price.id,
142
+ stripeProductId:
143
+ typeof price.product === "string" ? price.product : price.product.id,
144
+ gross: terms.amount,
145
+ processingFee: balance.fee,
146
+ currency: payment.currency,
147
+ ownership: "issuer",
148
+ },
149
+ };
150
+ } catch (error) {
151
+ if (error instanceof UsageCreditRecoveryError)
152
+ return {
153
+ status: "rejected",
154
+ reason: "payment_not_payable",
155
+ retryable: false,
156
+ };
157
+ return {
158
+ status: "unknown",
159
+ reason: "provider_outcome_unknown",
160
+ retryable: false,
161
+ };
162
+ }
163
+ }
@@ -0,0 +1,70 @@
1
+ import type { SourceHttpClient } from "../paymentSource/resolver.fixtures.js";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { creditFixture } from "./creditTransport.fixtures.js";
5
+ export async function fixture(
6
+ affiliate: { basisPoints?: number; fixedAmount?: number } = {
7
+ basisPoints: 1000,
8
+ },
9
+ ) {
10
+ const native: Record<string, unknown>[] = [];
11
+ const response = (data: unknown) =>
12
+ new Response(JSON.stringify(data), {
13
+ headers: { "content-type": "application/json" },
14
+ });
15
+ const f = creditFixture(async (input, init) => {
16
+ const path = new URL(input).pathname;
17
+ if (path === "/v1/charges/ch_topup1")
18
+ return response({ id: "ch_topup1", created: 700 });
19
+ if (path !== "/v1/transfers") return;
20
+ if ((init?.method ?? "GET") === "GET")
21
+ return response({ object: "list", data: native, has_more: false });
22
+ const body = new URLSearchParams(String(init?.body ?? ""));
23
+ const transfer = {
24
+ id: `tr_${native.length}`,
25
+ amount: Number(body.get("amount")),
26
+ currency: body.get("currency"),
27
+ destination: body.get("destination"),
28
+ source_transaction: body.get("source_transaction"),
29
+ metadata: {
30
+ bsRole: body.get("metadata[bsRole]"),
31
+ bsSourceCharge: body.get("metadata[bsSourceCharge]"),
32
+ },
33
+ };
34
+ native.push(transfer);
35
+ return response(transfer);
36
+ });
37
+ const client = new BetterStripe(f.component),
38
+ options = {
39
+ stripeSecretKey: "sk_test_credit",
40
+ httpClient: f.httpClient as SourceHttpClient,
41
+ };
42
+ const view = await f.ready();
43
+ await f.t.action((ctx) =>
44
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
45
+ );
46
+ f.state.paid = true;
47
+ await f.t.action((ctx) =>
48
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
49
+ );
50
+ const input = {
51
+ ...f.purchase,
52
+ policy: {
53
+ affiliate: { destinationAccountId: "acct_affiliate", ...affiliate },
54
+ },
55
+ };
56
+ const settle = () =>
57
+ f.t.action((ctx) =>
58
+ client.usage.settleCreditPurchase(ctx as RunCtx, input, options),
59
+ );
60
+ return {
61
+ ...f,
62
+ httpClient: f.httpClient as SourceHttpClient,
63
+ native,
64
+ client,
65
+ options,
66
+ view,
67
+ input,
68
+ settle,
69
+ };
70
+ }
@@ -0,0 +1,66 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { fixture } from "./creditSettlement.fixtures.js";
4
+ afterEach(() => vi.useRealTimers());
5
+ it("pays an issuer-service purchase affiliate once and never pays again for credit consumption", async () => {
6
+ const f = await fixture(),
7
+ { native, client, options, view, input, settle } = f;
8
+ const first = await settle();
9
+ expect(first).toMatchObject({
10
+ status: "settled",
11
+ gross: 20,
12
+ processingFee: 1,
13
+ platformNet: 18,
14
+ creditSource: { purchaseId: "topup1", creditGrantId: "credgr_topup1" },
15
+ transfers: [{ role: "affiliate", amount: 1 }],
16
+ });
17
+ const event = {
18
+ scope: f.purchase.scope,
19
+ binding: f.purchase.binding,
20
+ sourceEventId: "consume1",
21
+ quantity: "6",
22
+ occurredAt: 700,
23
+ },
24
+ subscription = view.bindings[0].subscription;
25
+ const reservation = await f.t.action((ctx) =>
26
+ client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
27
+ );
28
+ await f.t.action((ctx) =>
29
+ client.usage.record(ctx as RunCtx, {
30
+ event,
31
+ subscription,
32
+ reservationId: reservation.reservationId,
33
+ }),
34
+ );
35
+ expect(await settle()).toEqual(first);
36
+ expect(native).toHaveLength(1);
37
+ f.state.processingFee = 2;
38
+ expect(await settle()).toMatchObject({
39
+ status: "conflict",
40
+ reason: "identity_changed",
41
+ });
42
+ expect(native).toHaveLength(1);
43
+ f.state.processingFee = 1;
44
+ f.state.refunded = true;
45
+ expect(await settle()).toMatchObject({
46
+ status: "rejected",
47
+ reason: "payment_not_payable",
48
+ });
49
+ expect(native).toHaveLength(1);
50
+ for (const unsupported of [
51
+ {
52
+ ...input,
53
+ policy: { ...input.policy, creatorAccountId: "acct_reseller" },
54
+ },
55
+ { ...input, ownership: "reseller" },
56
+ ])
57
+ expect(
58
+ await f.t.action((ctx) =>
59
+ client.usage.settleCreditPurchase(
60
+ ctx as RunCtx,
61
+ unsupported as typeof input,
62
+ options,
63
+ ),
64
+ ),
65
+ ).toMatchObject({ status: "rejected", reason: "unsupported_source" });
66
+ });
@@ -0,0 +1,94 @@
1
+ import { componentRef } from "../webhooks/helpers.js";
2
+ import type { ResolvedSettlement } from "../settlement/execution.js";
3
+ import { z } from "zod";
4
+ import { getCreditPurchaseRevenue } from "./creditRevenue.js";
5
+ import { allocateSale } from "../settlement/allocation.js";
6
+ import { executeResolvedTransfers } from "../settlement/execution.js";
7
+ import type Stripe from "stripe";
8
+ import type { Component, RunCtx } from "../helpers.js";
9
+ import type { UsageCreditPurchaseOptions } from "./creditTerms.js";
10
+ import type { SaleAllocationOptions } from "../settlement/allocation.js";
11
+ export type UsageCreditSettlementOptions = UsageCreditPurchaseOptions & {
12
+ policy: {
13
+ affiliate?: SaleAllocationOptions["affiliate"];
14
+ feeBasisPoints?: number;
15
+ };
16
+ };
17
+ const policySchema = z.strictObject({
18
+ feeBasisPoints: z.number().int().min(0).max(10000).optional(),
19
+ affiliate: z
20
+ .strictObject({
21
+ destinationAccountId: z.string().min(1).max(100),
22
+ basisPoints: z.number().int().min(0).max(10000).optional(),
23
+ fixedAmount: z
24
+ .number()
25
+ .int()
26
+ .nonnegative()
27
+ .max(Number.MAX_SAFE_INTEGER)
28
+ .optional(),
29
+ })
30
+ .optional(),
31
+ });
32
+ /** Retain issuer revenue; an authorized affiliate is paid from the original purchase only. No reseller redemption. */
33
+ export async function settleCreditPurchase(
34
+ stripe: Stripe,
35
+ component: Component,
36
+ ctx: RunCtx,
37
+ input: UsageCreditSettlementOptions,
38
+ ) {
39
+ const { policy, ...purchase } = input;
40
+ const parsed = policySchema.safeParse(policy);
41
+ if (!parsed.success || purchase.ownership !== "issuer")
42
+ return {
43
+ status: "rejected" as const,
44
+ reason: "unsupported_source" as const,
45
+ retryable: false as const,
46
+ };
47
+ const source = await getCreditPurchaseRevenue(
48
+ stripe,
49
+ component,
50
+ ctx,
51
+ purchase,
52
+ );
53
+ if (source.status !== "ready") return source;
54
+ const value = source.value;
55
+ const prior = (await ctx.runQuery(
56
+ componentRef(component, "settlement/queries/getSettlementAllocation"),
57
+ { sourceChargeId: value.chargeId },
58
+ )) as ResolvedSettlement | null;
59
+ if (
60
+ prior &&
61
+ (prior.gross !== value.gross ||
62
+ prior.currency !== value.currency ||
63
+ prior.processingFee !== value.processingFee)
64
+ )
65
+ return {
66
+ status: "conflict" as const,
67
+ reason: "identity_changed" as const,
68
+ retryable: false as const,
69
+ };
70
+ const allocation = allocateSale({
71
+ ...parsed.data,
72
+ creatorAccountId: value.stripeAccountId,
73
+ gross: value.gross,
74
+ processingFee: value.processingFee,
75
+ });
76
+ return executeResolvedTransfers(stripe, component, ctx, {
77
+ sourceChargeId: value.chargeId,
78
+ paymentIntentId: value.paymentIntentId,
79
+ creditSource: {
80
+ stripeAccountId: value.stripeAccountId,
81
+ customerAccount: value.customerAccount,
82
+ livemode: value.livemode,
83
+ purchaseId: value.purchaseId,
84
+ creditGrantId: value.creditGrantId,
85
+ stripePriceId: value.stripePriceId,
86
+ stripeProductId: value.stripeProductId,
87
+ },
88
+ gross: value.gross,
89
+ currency: value.currency,
90
+ processingFee: value.processingFee,
91
+ platformNet: allocation.platformNet + allocation.creatorNet,
92
+ transfers: allocation.transfers.filter((leg) => leg.role !== "store"),
93
+ });
94
+ }
@@ -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
+ });