@fantastic.dev/better-stripe 0.38.0 → 0.40.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.
- package/CHANGELOG.md +34 -0
- package/MIGRATION.md +9 -0
- package/README.md +21 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/costRecovery-invoices.d.ts.map +1 -1
- package/dist/client/costRecovery-invoices.js +3 -5
- package/dist/client/costRecovery-invoices.js.map +1 -1
- package/dist/client/costRecovery.d.ts +18 -0
- package/dist/client/costRecovery.d.ts.map +1 -1
- package/dist/client/costRecovery.js +4 -0
- package/dist/client/costRecovery.js.map +1 -1
- package/dist/client/index.d.ts +4 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/paymentSource/client.d.ts +21 -0
- package/dist/client/paymentSource/client.d.ts.map +1 -0
- package/dist/client/paymentSource/client.js +8 -0
- package/dist/client/paymentSource/client.js.map +1 -0
- package/dist/client/paymentSource/contracts.d.ts +30 -0
- package/dist/client/paymentSource/contracts.d.ts.map +1 -0
- package/dist/client/paymentSource/contracts.js +16 -0
- package/dist/client/paymentSource/contracts.js.map +1 -0
- package/dist/client/paymentSource/economics.d.ts +12 -0
- package/dist/client/paymentSource/economics.d.ts.map +1 -0
- package/dist/client/paymentSource/economics.js +13 -0
- package/dist/client/paymentSource/economics.js.map +1 -0
- package/dist/client/paymentSource/funding.d.ts +10 -0
- package/dist/client/paymentSource/funding.d.ts.map +1 -0
- package/dist/client/paymentSource/funding.js +12 -0
- package/dist/client/paymentSource/funding.js.map +1 -0
- package/dist/client/paymentSource/history.d.ts +13 -0
- package/dist/client/paymentSource/history.d.ts.map +1 -0
- package/dist/client/paymentSource/history.js +41 -0
- package/dist/client/paymentSource/history.js.map +1 -0
- package/dist/client/paymentSource/resolver.d.ts +6 -0
- package/dist/client/paymentSource/resolver.d.ts.map +1 -0
- package/dist/client/paymentSource/resolver.js +222 -0
- package/dist/client/paymentSource/resolver.js.map +1 -0
- package/dist/client/processingCostDeficit/index.d.ts +27 -0
- package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
- package/dist/client/processingCostDeficit/index.js +54 -0
- package/dist/client/processingCostDeficit/index.js.map +1 -0
- package/dist/client/settlement/verifiedSale.d.ts.map +1 -1
- package/dist/client/settlement/verifiedSale.js +4 -6
- package/dist/client/settlement/verifiedSale.js.map +1 -1
- package/dist/component/_generated/api.d.ts +284 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +527 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/helpers.d.ts +86 -0
- package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
- package/dist/component/balanceFunding/helpers.js +68 -0
- package/dist/component/balanceFunding/helpers.js.map +1 -0
- package/dist/component/balanceFunding/importHandler.d.ts +13 -0
- package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
- package/dist/component/balanceFunding/importHandler.js +130 -0
- package/dist/component/balanceFunding/importHandler.js.map +1 -0
- package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
- package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
- package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
- package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
- package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
- package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
- package/dist/component/balanceFunding/mutationValidators.js +55 -0
- package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
- package/dist/component/balanceFunding/mutations.d.ts +335 -0
- package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
- package/dist/component/balanceFunding/mutations.js +106 -0
- package/dist/component/balanceFunding/mutations.js.map +1 -0
- package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
- package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
- package/dist/component/balanceFunding/preparationHandlers.js +165 -0
- package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
- package/dist/component/balanceFunding/queries.d.ts +151 -0
- package/dist/component/balanceFunding/queries.d.ts.map +1 -0
- package/dist/component/balanceFunding/queries.js +180 -0
- package/dist/component/balanceFunding/queries.js.map +1 -0
- package/dist/component/balanceFunding/schema.d.ts +748 -0
- package/dist/component/balanceFunding/schema.d.ts.map +1 -0
- package/dist/component/balanceFunding/schema.js +124 -0
- package/dist/component/balanceFunding/schema.js.map +1 -0
- package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
- package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
- package/dist/component/balanceFunding/stateHandlers.js +160 -0
- package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/convex.config.js +2 -0
- package/dist/component/convex.config.js.map +1 -1
- package/dist/component/costRecovery/completion.d.ts +1 -0
- package/dist/component/costRecovery/completion.d.ts.map +1 -1
- package/dist/component/costRecovery/helpers.d.ts +1 -0
- package/dist/component/costRecovery/helpers.d.ts.map +1 -1
- package/dist/component/costRecovery/mutations.d.ts +5 -0
- package/dist/component/costRecovery/mutations.d.ts.map +1 -1
- package/dist/component/costRecovery/preparation.d.ts +50 -0
- package/dist/component/costRecovery/preparation.d.ts.map +1 -0
- package/dist/component/costRecovery/preparation.js +108 -0
- package/dist/component/costRecovery/preparation.js.map +1 -0
- package/dist/component/costRecovery/queries.d.ts +1 -0
- package/dist/component/costRecovery/queries.d.ts.map +1 -1
- package/dist/component/costRecovery/reservations.d.ts +2 -0
- package/dist/component/costRecovery/reservations.d.ts.map +1 -1
- package/dist/component/costRecovery/schema.d.ts +7 -2
- package/dist/component/costRecovery/schema.d.ts.map +1 -1
- package/dist/component/costRecovery/schema.js +1 -0
- package/dist/component/costRecovery/schema.js.map +1 -1
- package/dist/component/durableExecution/runtime.d.ts +3 -0
- package/dist/component/durableExecution/runtime.d.ts.map +1 -0
- package/dist/component/durableExecution/runtime.js +12 -0
- package/dist/component/durableExecution/runtime.js.map +1 -0
- package/dist/component/earnings/triggers.d.ts +242 -2
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/schema.d.ts +253 -1
- package/dist/component/schema.js +4 -0
- package/dist/component/schema.js.map +1 -1
- package/docs/settlement.md +48 -0
- package/package.json +4 -2
- package/src/client/costRecovery-invoices.ts +3 -7
- package/src/client/costRecovery.test.ts +34 -0
- package/src/client/costRecovery.ts +21 -0
- package/src/client/index.ts +7 -2
- package/src/client/paymentSource/client.ts +13 -0
- package/src/client/paymentSource/contracts.ts +33 -0
- package/src/client/paymentSource/economics.ts +20 -0
- package/src/client/paymentSource/funding.ts +23 -0
- package/src/client/paymentSource/history.ts +48 -0
- package/src/client/paymentSource/resolver.test.ts +582 -0
- package/src/client/paymentSource/resolver.ts +350 -0
- package/src/client/processingCostDeficit/README.md +35 -0
- package/src/client/processingCostDeficit/calculator.test.ts +176 -0
- package/src/client/processingCostDeficit/index.ts +91 -0
- package/src/client/settlement/verifiedSale.ts +4 -10
- package/src/component/_generated/api.ts +23 -1
- package/src/component/_generated/component.ts +693 -0
- package/src/component/balanceFunding/failure.test.ts +116 -0
- package/src/component/balanceFunding/helpers.ts +102 -0
- package/src/component/balanceFunding/import.test.ts +221 -0
- package/src/component/balanceFunding/importHandler.ts +146 -0
- package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
- package/src/component/balanceFunding/lookup.test.ts +113 -0
- package/src/component/balanceFunding/mutationValidators.ts +63 -0
- package/src/component/balanceFunding/mutations.ts +136 -0
- package/src/component/balanceFunding/preparation.test.ts +146 -0
- package/src/component/balanceFunding/preparationHandlers.ts +204 -0
- package/src/component/balanceFunding/queries.ts +221 -0
- package/src/component/balanceFunding/requestLookup.test.ts +160 -0
- package/src/component/balanceFunding/schema.ts +169 -0
- package/src/component/balanceFunding/state.test.ts +352 -0
- package/src/component/balanceFunding/stateHandlers.ts +198 -0
- package/src/component/balanceFunding/validation.test.ts +100 -0
- package/src/component/convex.config.ts +2 -0
- package/src/component/costRecovery/preparation.test.ts +355 -0
- package/src/component/costRecovery/preparation.ts +124 -0
- package/src/component/costRecovery/schema.ts +1 -0
- package/src/component/durableExecution/composition.test.ts +568 -0
- package/src/component/durableExecution/runtime.ts +12 -0
- package/src/component/schema.ts +8 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type {
|
|
3
|
+
FinancialOutcome,
|
|
4
|
+
FinancialUnavailable,
|
|
5
|
+
} from "../financialOutcomes/contracts.js";
|
|
6
|
+
import {
|
|
7
|
+
paymentSourceOptions,
|
|
8
|
+
type VerifiedPaymentSource,
|
|
9
|
+
type VerifiedPaymentSourceOptions,
|
|
10
|
+
} from "./contracts.js";
|
|
11
|
+
import { completeHistory } from "./history.js";
|
|
12
|
+
import { saleAmountFailure } from "./economics.js";
|
|
13
|
+
import { singleInvoiceFunding } from "./funding.js";
|
|
14
|
+
|
|
15
|
+
const reject = (
|
|
16
|
+
reason: Extract<FinancialUnavailable, { status: "rejected" }>["reason"],
|
|
17
|
+
): FinancialUnavailable => ({ status: "rejected", reason, retryable: false });
|
|
18
|
+
const identity = (): FinancialUnavailable => ({
|
|
19
|
+
status: "conflict",
|
|
20
|
+
reason: "identity_changed",
|
|
21
|
+
retryable: false,
|
|
22
|
+
});
|
|
23
|
+
const incomplete = (): FinancialUnavailable => ({
|
|
24
|
+
status: "unknown",
|
|
25
|
+
reason: "history_incomplete",
|
|
26
|
+
retryable: false,
|
|
27
|
+
});
|
|
28
|
+
class SourceUnavailable extends Error {
|
|
29
|
+
constructor(readonly outcome: FinancialUnavailable) {
|
|
30
|
+
super(outcome.reason);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function requireSource(
|
|
34
|
+
condition: unknown,
|
|
35
|
+
outcome: FinancialUnavailable,
|
|
36
|
+
): asserts condition {
|
|
37
|
+
if (!condition) throw new SourceUnavailable(outcome);
|
|
38
|
+
}
|
|
39
|
+
const objectId = (value: string | { id: string } | null | undefined) => {
|
|
40
|
+
const candidate = typeof value === "string" ? value : value?.id;
|
|
41
|
+
return typeof candidate === "string" && candidate.length > 0
|
|
42
|
+
? candidate
|
|
43
|
+
: undefined;
|
|
44
|
+
};
|
|
45
|
+
const integer = (value: number) => Number.isSafeInteger(value) && value >= 0;
|
|
46
|
+
|
|
47
|
+
/** Read-only provenance. Current subscription items and application metadata never prove original price/funding. */
|
|
48
|
+
export async function resolveVerifiedPaymentSource(
|
|
49
|
+
stripe: Stripe,
|
|
50
|
+
input: VerifiedPaymentSourceOptions,
|
|
51
|
+
): Promise<FinancialOutcome<VerifiedPaymentSource>> {
|
|
52
|
+
const parsed = paymentSourceOptions.safeParse(input);
|
|
53
|
+
if (!parsed.success) return reject("invalid_scope");
|
|
54
|
+
const opts = parsed.data;
|
|
55
|
+
const requestOptions = opts.stripeAccountId
|
|
56
|
+
? { stripeAccount: opts.stripeAccountId }
|
|
57
|
+
: undefined;
|
|
58
|
+
try {
|
|
59
|
+
const payment = await stripe.paymentIntents.retrieve(
|
|
60
|
+
opts.paymentIntentId,
|
|
61
|
+
{ expand: ["latest_charge.balance_transaction"] },
|
|
62
|
+
requestOptions,
|
|
63
|
+
);
|
|
64
|
+
requireSource(
|
|
65
|
+
payment.object === "payment_intent" &&
|
|
66
|
+
payment.id === opts.paymentIntentId,
|
|
67
|
+
identity(),
|
|
68
|
+
);
|
|
69
|
+
if (payment.status === "processing")
|
|
70
|
+
return {
|
|
71
|
+
status: "not_ready",
|
|
72
|
+
reason: "provider_pending",
|
|
73
|
+
retryable: true,
|
|
74
|
+
};
|
|
75
|
+
if (payment.status !== "succeeded") return reject("payment_not_payable");
|
|
76
|
+
const charge = payment.latest_charge;
|
|
77
|
+
if (!charge || typeof charge === "string")
|
|
78
|
+
return {
|
|
79
|
+
status: "not_ready",
|
|
80
|
+
reason: "provider_pending",
|
|
81
|
+
retryable: true,
|
|
82
|
+
};
|
|
83
|
+
requireSource(
|
|
84
|
+
charge.object === "charge" &&
|
|
85
|
+
typeof charge.id === "string" &&
|
|
86
|
+
!!charge.id &&
|
|
87
|
+
objectId(charge.payment_intent) === payment.id,
|
|
88
|
+
identity(),
|
|
89
|
+
);
|
|
90
|
+
requireSource(
|
|
91
|
+
payment.currency === opts.currency,
|
|
92
|
+
reject("currency_mismatch"),
|
|
93
|
+
);
|
|
94
|
+
requireSource(
|
|
95
|
+
integer(payment.amount_received) &&
|
|
96
|
+
payment.amount_received === opts.gross &&
|
|
97
|
+
payment.amount === opts.gross,
|
|
98
|
+
reject("unsupported_source"),
|
|
99
|
+
);
|
|
100
|
+
requireSource(
|
|
101
|
+
charge.paid &&
|
|
102
|
+
charge.captured &&
|
|
103
|
+
charge.status === "succeeded" &&
|
|
104
|
+
charge.amount_captured === opts.gross,
|
|
105
|
+
reject("unsupported_source"),
|
|
106
|
+
);
|
|
107
|
+
requireSource(
|
|
108
|
+
typeof payment.livemode === "boolean" &&
|
|
109
|
+
charge.livemode === payment.livemode,
|
|
110
|
+
identity(),
|
|
111
|
+
);
|
|
112
|
+
requireSource(
|
|
113
|
+
typeof payment.customer_account === "string" &&
|
|
114
|
+
!!payment.customer_account,
|
|
115
|
+
reject("unsupported_source"),
|
|
116
|
+
);
|
|
117
|
+
if (opts.customerAccountId)
|
|
118
|
+
requireSource(
|
|
119
|
+
payment.customer_account === opts.customerAccountId,
|
|
120
|
+
identity(),
|
|
121
|
+
);
|
|
122
|
+
const customerAccountId = payment.customer_account!;
|
|
123
|
+
const balanceRef = charge.balance_transaction;
|
|
124
|
+
if (!balanceRef)
|
|
125
|
+
return { status: "not_ready", reason: "fee_pending", retryable: true };
|
|
126
|
+
const balance =
|
|
127
|
+
typeof balanceRef === "string"
|
|
128
|
+
? await stripe.balanceTransactions.retrieve(
|
|
129
|
+
balanceRef,
|
|
130
|
+
{},
|
|
131
|
+
requestOptions,
|
|
132
|
+
)
|
|
133
|
+
: balanceRef;
|
|
134
|
+
if (typeof balanceRef === "string")
|
|
135
|
+
requireSource(balance.id === balanceRef, identity());
|
|
136
|
+
requireSource(
|
|
137
|
+
balance.object === "balance_transaction" &&
|
|
138
|
+
typeof balance.id === "string" &&
|
|
139
|
+
!!balance.id &&
|
|
140
|
+
objectId(balance.source) === charge.id,
|
|
141
|
+
identity(),
|
|
142
|
+
);
|
|
143
|
+
const amountFailure = saleAmountFailure(payment, charge, balance);
|
|
144
|
+
requireSource(amountFailure !== "currency", reject("currency_mismatch"));
|
|
145
|
+
requireSource(
|
|
146
|
+
!amountFailure &&
|
|
147
|
+
integer(balance.amount) &&
|
|
148
|
+
integer(balance.net) &&
|
|
149
|
+
balance.amount === opts.gross &&
|
|
150
|
+
balance.amount - balance.fee === balance.net,
|
|
151
|
+
reject("unsupported_source"),
|
|
152
|
+
);
|
|
153
|
+
const read = <T extends { id: string }>(
|
|
154
|
+
fetch: (
|
|
155
|
+
cursor: string | undefined,
|
|
156
|
+
limit: number,
|
|
157
|
+
) => Promise<Stripe.ApiList<T>>,
|
|
158
|
+
) => completeHistory(fetch, opts.maxHistoryPages, opts.maxHistoryItems);
|
|
159
|
+
const inverse = await read((cursor, limit) =>
|
|
160
|
+
stripe.invoicePayments.list(
|
|
161
|
+
{
|
|
162
|
+
payment: { type: "payment_intent", payment_intent: payment.id },
|
|
163
|
+
limit,
|
|
164
|
+
...(cursor ? { starting_after: cursor } : {}),
|
|
165
|
+
},
|
|
166
|
+
requestOptions,
|
|
167
|
+
),
|
|
168
|
+
);
|
|
169
|
+
if (inverse.status !== "complete") return inverse;
|
|
170
|
+
for (const row of inverse.data) {
|
|
171
|
+
requireSource(
|
|
172
|
+
row.object === "invoice_payment" &&
|
|
173
|
+
["paid", "open", "canceled"].includes(row.status),
|
|
174
|
+
incomplete(),
|
|
175
|
+
);
|
|
176
|
+
requireSource(
|
|
177
|
+
row.payment.type === "payment_intent" &&
|
|
178
|
+
objectId(row.payment.payment_intent) === payment.id &&
|
|
179
|
+
row.livemode === payment.livemode,
|
|
180
|
+
identity(),
|
|
181
|
+
);
|
|
182
|
+
requireSource(
|
|
183
|
+
row.currency === opts.currency,
|
|
184
|
+
reject("currency_mismatch"),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const original = singleInvoiceFunding(inverse.data, opts.gross);
|
|
188
|
+
requireSource(original, reject("unsupported_source"));
|
|
189
|
+
const invoiceId = objectId(original!.invoice);
|
|
190
|
+
requireSource(invoiceId, identity());
|
|
191
|
+
if (opts.invoiceId) requireSource(invoiceId === opts.invoiceId, identity());
|
|
192
|
+
const invoice = await stripe.invoices.retrieve(
|
|
193
|
+
invoiceId!,
|
|
194
|
+
{},
|
|
195
|
+
requestOptions,
|
|
196
|
+
);
|
|
197
|
+
requireSource(
|
|
198
|
+
invoice.object === "invoice" &&
|
|
199
|
+
invoice.id === invoiceId &&
|
|
200
|
+
invoice.customer_account === customerAccountId &&
|
|
201
|
+
invoice.livemode === payment.livemode,
|
|
202
|
+
identity(),
|
|
203
|
+
);
|
|
204
|
+
requireSource(
|
|
205
|
+
invoice.currency === opts.currency,
|
|
206
|
+
reject("currency_mismatch"),
|
|
207
|
+
);
|
|
208
|
+
if (invoice.status !== "paid")
|
|
209
|
+
return {
|
|
210
|
+
status: "not_ready",
|
|
211
|
+
reason: "provider_pending",
|
|
212
|
+
retryable: true,
|
|
213
|
+
};
|
|
214
|
+
requireSource(
|
|
215
|
+
[invoice.amount_paid, invoice.amount_due, invoice.total].every(
|
|
216
|
+
(value) => integer(value) && value === opts.gross,
|
|
217
|
+
) &&
|
|
218
|
+
invoice.amount_remaining === 0 &&
|
|
219
|
+
invoice.amount_overpaid === 0,
|
|
220
|
+
reject("unsupported_source"),
|
|
221
|
+
);
|
|
222
|
+
const funding = await read((cursor, limit) =>
|
|
223
|
+
stripe.invoicePayments.list(
|
|
224
|
+
{
|
|
225
|
+
invoice: invoice.id,
|
|
226
|
+
limit,
|
|
227
|
+
...(cursor ? { starting_after: cursor } : {}),
|
|
228
|
+
},
|
|
229
|
+
requestOptions,
|
|
230
|
+
),
|
|
231
|
+
);
|
|
232
|
+
if (funding.status !== "complete") return funding;
|
|
233
|
+
for (const row of funding.data) {
|
|
234
|
+
requireSource(
|
|
235
|
+
row.object === "invoice_payment" &&
|
|
236
|
+
["paid", "open", "canceled"].includes(row.status),
|
|
237
|
+
incomplete(),
|
|
238
|
+
);
|
|
239
|
+
requireSource(
|
|
240
|
+
objectId(row.invoice) === invoice.id &&
|
|
241
|
+
row.livemode === payment.livemode,
|
|
242
|
+
identity(),
|
|
243
|
+
);
|
|
244
|
+
requireSource(
|
|
245
|
+
row.currency === opts.currency,
|
|
246
|
+
reject("currency_mismatch"),
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
const funded = singleInvoiceFunding(funding.data, invoice.amount_paid);
|
|
250
|
+
requireSource(funded, reject("unsupported_source"));
|
|
251
|
+
requireSource(
|
|
252
|
+
funded!.id === original!.id &&
|
|
253
|
+
objectId(funded!.payment.payment_intent) === payment.id,
|
|
254
|
+
identity(),
|
|
255
|
+
);
|
|
256
|
+
requireSource(
|
|
257
|
+
original!.amount_requested === opts.gross &&
|
|
258
|
+
funded!.amount_requested === opts.gross,
|
|
259
|
+
reject("unsupported_source"),
|
|
260
|
+
);
|
|
261
|
+
const subscriptionId = objectId(
|
|
262
|
+
invoice.parent?.subscription_details?.subscription,
|
|
263
|
+
);
|
|
264
|
+
if (opts.subscriptionId)
|
|
265
|
+
requireSource(subscriptionId === opts.subscriptionId, identity());
|
|
266
|
+
if (subscriptionId) {
|
|
267
|
+
const subscription = await stripe.subscriptions.retrieve(
|
|
268
|
+
subscriptionId,
|
|
269
|
+
{},
|
|
270
|
+
requestOptions,
|
|
271
|
+
);
|
|
272
|
+
requireSource(
|
|
273
|
+
subscription.object === "subscription" &&
|
|
274
|
+
subscription.id === subscriptionId &&
|
|
275
|
+
subscription.customer_account === customerAccountId &&
|
|
276
|
+
subscription.livemode === payment.livemode,
|
|
277
|
+
identity(),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
const lines = await read((cursor, limit) =>
|
|
281
|
+
stripe.invoices.listLineItems(
|
|
282
|
+
invoice.id,
|
|
283
|
+
{ limit, ...(cursor ? { starting_after: cursor } : {}) },
|
|
284
|
+
requestOptions,
|
|
285
|
+
),
|
|
286
|
+
);
|
|
287
|
+
if (lines.status !== "complete") return lines;
|
|
288
|
+
requireSource(lines.data.length === 1, reject("unsupported_source"));
|
|
289
|
+
const line = lines.data[0]!;
|
|
290
|
+
requireSource(
|
|
291
|
+
line.object === "line_item" &&
|
|
292
|
+
line.invoice === invoice.id &&
|
|
293
|
+
line.livemode === payment.livemode,
|
|
294
|
+
identity(),
|
|
295
|
+
);
|
|
296
|
+
requireSource(line.currency === opts.currency, reject("currency_mismatch"));
|
|
297
|
+
requireSource(
|
|
298
|
+
integer(line.amount) &&
|
|
299
|
+
line.amount > 0 &&
|
|
300
|
+
Number.isSafeInteger(line.quantity) &&
|
|
301
|
+
line.quantity! > 0,
|
|
302
|
+
reject("unsupported_source"),
|
|
303
|
+
);
|
|
304
|
+
const parent = line.parent;
|
|
305
|
+
const lineSubscription =
|
|
306
|
+
parent?.subscription_item_details?.subscription ??
|
|
307
|
+
parent?.invoice_item_details?.subscription ??
|
|
308
|
+
undefined;
|
|
309
|
+
requireSource(lineSubscription === subscriptionId, identity());
|
|
310
|
+
requireSource(
|
|
311
|
+
!parent?.subscription_item_details?.proration &&
|
|
312
|
+
!parent?.invoice_item_details?.proration,
|
|
313
|
+
reject("unsupported_source"),
|
|
314
|
+
);
|
|
315
|
+
const price = line.pricing?.price_details;
|
|
316
|
+
const priceId = objectId(price?.price);
|
|
317
|
+
const productId = objectId(price?.product);
|
|
318
|
+
requireSource(
|
|
319
|
+
line.pricing?.type === "price_details" && priceId && productId,
|
|
320
|
+
reject("unsupported_source"),
|
|
321
|
+
);
|
|
322
|
+
return {
|
|
323
|
+
status: "ready",
|
|
324
|
+
value: {
|
|
325
|
+
paymentIntentId: payment.id,
|
|
326
|
+
chargeId: charge.id,
|
|
327
|
+
invoiceId: invoice.id,
|
|
328
|
+
invoicePaymentId: funded!.id,
|
|
329
|
+
...(subscriptionId ? { subscriptionId } : {}),
|
|
330
|
+
customerAccountId,
|
|
331
|
+
...(opts.stripeAccountId
|
|
332
|
+
? { stripeAccountId: opts.stripeAccountId }
|
|
333
|
+
: {}),
|
|
334
|
+
stripePriceId: priceId,
|
|
335
|
+
stripeProductId: productId,
|
|
336
|
+
gross: opts.gross,
|
|
337
|
+
processingFee: balance.fee,
|
|
338
|
+
currency: opts.currency,
|
|
339
|
+
livemode: payment.livemode,
|
|
340
|
+
},
|
|
341
|
+
};
|
|
342
|
+
} catch (error) {
|
|
343
|
+
if (error instanceof SourceUnavailable) return error.outcome;
|
|
344
|
+
return {
|
|
345
|
+
status: "unknown",
|
|
346
|
+
reason: "provider_outcome_unknown",
|
|
347
|
+
retryable: false,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Processing-cost deficit
|
|
2
|
+
|
|
3
|
+
`calculateProcessingCostDeficit` is a pure SDK calculation. The host authorizes
|
|
4
|
+
the original same-currency source and explicitly chooses liability and rounding.
|
|
5
|
+
The helper creates no charges, claims or transfers. The example's existing
|
|
6
|
+
business policy stays in the host until its financial cutover.
|
|
7
|
+
|
|
8
|
+
All amounts use nonnegative safe integer API ledger units. Gross must be positive
|
|
9
|
+
and the original inclusive selling fee cannot exceed gross. Currency must have
|
|
10
|
+
supported package charge-currency metadata. Metadata does not establish account,
|
|
11
|
+
country or payment-method eligibility. This helper does not convert display
|
|
12
|
+
amounts or validate a provider-specific charge/transfer quantum.
|
|
13
|
+
|
|
14
|
+
Required policy fields:
|
|
15
|
+
|
|
16
|
+
- `liability.processingCosts: "uncovered"` subtracts the proportional retained
|
|
17
|
+
inclusive selling fee from processing costs and floors the liability at zero.
|
|
18
|
+
- `"all"` assigns all processing costs; `"none"` assigns none.
|
|
19
|
+
- `liability.disputeCosts: "all" | "none"` selects dispute-cost liability
|
|
20
|
+
independently. Actual credited costs should be resolved before calling.
|
|
21
|
+
- `rounding: "nearest" | "floor" | "ceil"` applies to the retained fee.
|
|
22
|
+
Nearest rounds a positive exact half up. No policy has a default.
|
|
23
|
+
|
|
24
|
+
The calculation caps overlapping refunded/disputed principal at original gross.
|
|
25
|
+
It returns normalized currency, retained fee, processing liability, dispute
|
|
26
|
+
liability and total `amountDue`. Unsafe input amounts or totals are rejected.
|
|
27
|
+
|
|
28
|
+
The old example formula's ordinary fixtures use processing `"uncovered"`,
|
|
29
|
+
disputes `"all"` and rounding `"nearest"`. USD, JPY, ISK and UGX fixture values
|
|
30
|
+
retain their historical integer-unit results. Multiplication and division now
|
|
31
|
+
use exact integers. At gross 9007199254740991, selling fee 9007199254740990 and
|
|
32
|
+
returned principal 3002399751580330, retained fee is exactly 6004799503160660.
|
|
33
|
+
The old floating-point intermediate incorrectly rounded it to 6004799503160661.
|
|
34
|
+
This correction intentionally preserves a one-unit liability that the old
|
|
35
|
+
formula lost. No host calculation changes until its caller adopts this API.
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
calculateProcessingCostDeficit,
|
|
4
|
+
type ProcessingCostDeficitOptions,
|
|
5
|
+
} from "./index.js";
|
|
6
|
+
|
|
7
|
+
const original: ProcessingCostDeficitOptions = {
|
|
8
|
+
currency: "usd",
|
|
9
|
+
gross: 10000,
|
|
10
|
+
sellingFee: 900,
|
|
11
|
+
processingFee: 320,
|
|
12
|
+
principalReturned: 10000,
|
|
13
|
+
disputeFees: 0,
|
|
14
|
+
liability: { processingCosts: "uncovered", disputeCosts: "all" },
|
|
15
|
+
rounding: "nearest",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe("explicit processing cost liability", () => {
|
|
19
|
+
it("passes uncovered costs on a full return under the host-selected policy", () => {
|
|
20
|
+
expect(calculateProcessingCostDeficit(original)).toEqual({
|
|
21
|
+
currency: "usd",
|
|
22
|
+
retainedFee: 0,
|
|
23
|
+
processingLiability: 320,
|
|
24
|
+
disputeLiability: 0,
|
|
25
|
+
amountDue: 320,
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
it.each(["usd", "jpy", "isk", "ugx"])(
|
|
29
|
+
"matches historical integer-unit rounding for ordinary %s values",
|
|
30
|
+
(currency) => {
|
|
31
|
+
for (const principalReturned of [0, 1, 1000, 5000, 9999, 10000, 12000]) {
|
|
32
|
+
for (const sellingFee of [0, 320, 490, 900]) {
|
|
33
|
+
const retainedFee = Math.round(
|
|
34
|
+
(sellingFee * (10000 - Math.min(10000, principalReturned))) / 10000,
|
|
35
|
+
);
|
|
36
|
+
const result = calculateProcessingCostDeficit({
|
|
37
|
+
...original,
|
|
38
|
+
currency,
|
|
39
|
+
principalReturned,
|
|
40
|
+
sellingFee,
|
|
41
|
+
disputeFees: 1500,
|
|
42
|
+
});
|
|
43
|
+
expect(result.retainedFee).toBe(retainedFee);
|
|
44
|
+
expect(result.amountDue).toBe(Math.max(0, 320 - retainedFee) + 1500);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
);
|
|
49
|
+
it("lets the host retain all liability instead of assuming a seller pays", () => {
|
|
50
|
+
expect(
|
|
51
|
+
calculateProcessingCostDeficit({
|
|
52
|
+
...original,
|
|
53
|
+
disputeFees: 1500,
|
|
54
|
+
liability: { processingCosts: "none", disputeCosts: "none" },
|
|
55
|
+
}),
|
|
56
|
+
).toMatchObject({
|
|
57
|
+
processingLiability: 0,
|
|
58
|
+
disputeLiability: 0,
|
|
59
|
+
amountDue: 0,
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
it("supports all processing costs with an independent dispute policy", () => {
|
|
63
|
+
expect(
|
|
64
|
+
calculateProcessingCostDeficit({
|
|
65
|
+
...original,
|
|
66
|
+
principalReturned: 0,
|
|
67
|
+
disputeFees: 1500,
|
|
68
|
+
liability: { processingCosts: "all", disputeCosts: "none" },
|
|
69
|
+
}),
|
|
70
|
+
).toMatchObject({
|
|
71
|
+
retainedFee: 900,
|
|
72
|
+
processingLiability: 320,
|
|
73
|
+
amountDue: 320,
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
it.each([
|
|
77
|
+
["nearest", 5, 0],
|
|
78
|
+
["floor", 4, 1],
|
|
79
|
+
["ceil", 5, 0],
|
|
80
|
+
] as const)(
|
|
81
|
+
"uses the selected %s rounding for retained fee",
|
|
82
|
+
(rounding, retainedFee, amountDue) => {
|
|
83
|
+
expect(
|
|
84
|
+
calculateProcessingCostDeficit({
|
|
85
|
+
...original,
|
|
86
|
+
gross: 10,
|
|
87
|
+
sellingFee: 5,
|
|
88
|
+
processingFee: 5,
|
|
89
|
+
principalReturned: 1,
|
|
90
|
+
rounding,
|
|
91
|
+
}),
|
|
92
|
+
).toMatchObject({ retainedFee, amountDue });
|
|
93
|
+
},
|
|
94
|
+
);
|
|
95
|
+
it("does not lose a unit when an intermediate product exceeds safe integer precision", () => {
|
|
96
|
+
expect(
|
|
97
|
+
calculateProcessingCostDeficit({
|
|
98
|
+
...original,
|
|
99
|
+
gross: 9007199254740991,
|
|
100
|
+
sellingFee: 9007199254740990,
|
|
101
|
+
principalReturned: 3002399751580330,
|
|
102
|
+
processingFee: 6004799503160661,
|
|
103
|
+
}),
|
|
104
|
+
).toMatchObject({ retainedFee: 6004799503160660, amountDue: 1 });
|
|
105
|
+
});
|
|
106
|
+
it("caps overlapping returned principal at original gross and includes actual dispute costs", () => {
|
|
107
|
+
expect(
|
|
108
|
+
calculateProcessingCostDeficit({
|
|
109
|
+
...original,
|
|
110
|
+
principalReturned: 20000,
|
|
111
|
+
disputeFees: 1500,
|
|
112
|
+
}),
|
|
113
|
+
).toMatchObject({ retainedFee: 0, amountDue: 1820 });
|
|
114
|
+
});
|
|
115
|
+
it("normalizes currency codes without converting any ledger units", () => {
|
|
116
|
+
expect(
|
|
117
|
+
calculateProcessingCostDeficit({ ...original, currency: "USD" }).currency,
|
|
118
|
+
).toBe("usd");
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
describe("invalid financial inputs", () => {
|
|
123
|
+
it.each([null, undefined])(
|
|
124
|
+
"rejects an absent options object %s",
|
|
125
|
+
(options) => {
|
|
126
|
+
expect(() =>
|
|
127
|
+
calculateProcessingCostDeficit(
|
|
128
|
+
options as unknown as ProcessingCostDeficitOptions,
|
|
129
|
+
),
|
|
130
|
+
).toThrow(RangeError);
|
|
131
|
+
},
|
|
132
|
+
);
|
|
133
|
+
it.each([
|
|
134
|
+
"gross",
|
|
135
|
+
"sellingFee",
|
|
136
|
+
"processingFee",
|
|
137
|
+
"principalReturned",
|
|
138
|
+
"disputeFees",
|
|
139
|
+
] as const)("rejects invalid %s values", (field) => {
|
|
140
|
+
for (const value of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
|
|
141
|
+
expect(() =>
|
|
142
|
+
calculateProcessingCostDeficit({ ...original, [field]: value }),
|
|
143
|
+
).toThrow(RangeError);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
it.each([
|
|
147
|
+
{ gross: 0 },
|
|
148
|
+
{ sellingFee: 10001 },
|
|
149
|
+
{ currency: "unknown" },
|
|
150
|
+
{ currency: "kwd" },
|
|
151
|
+
{ rounding: "random" },
|
|
152
|
+
{ liability: { processingCosts: "seller", disputeCosts: "all" } },
|
|
153
|
+
{ liability: { processingCosts: "uncovered", disputeCosts: "seller" } },
|
|
154
|
+
{ liability: undefined },
|
|
155
|
+
{ rounding: undefined },
|
|
156
|
+
])(
|
|
157
|
+
"rejects missing/unsupported currency, policy or amount combinations %j",
|
|
158
|
+
(invalid) => {
|
|
159
|
+
expect(() =>
|
|
160
|
+
calculateProcessingCostDeficit({
|
|
161
|
+
...original,
|
|
162
|
+
...invalid,
|
|
163
|
+
} as ProcessingCostDeficitOptions),
|
|
164
|
+
).toThrow(RangeError);
|
|
165
|
+
},
|
|
166
|
+
);
|
|
167
|
+
it("rejects an unrepresentable total even when each input is a safe integer", () => {
|
|
168
|
+
expect(() =>
|
|
169
|
+
calculateProcessingCostDeficit({
|
|
170
|
+
...original,
|
|
171
|
+
processingFee: Number.MAX_SAFE_INTEGER,
|
|
172
|
+
disputeFees: 1,
|
|
173
|
+
}),
|
|
174
|
+
).toThrow(RangeError);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { getChargeCurrencyMetadata } from "../charge-currency.js";
|
|
2
|
+
|
|
3
|
+
export type ProcessingCostDeficitOptions = {
|
|
4
|
+
currency: string;
|
|
5
|
+
gross: number;
|
|
6
|
+
sellingFee: number;
|
|
7
|
+
processingFee: number;
|
|
8
|
+
principalReturned: number;
|
|
9
|
+
disputeFees: number;
|
|
10
|
+
liability: {
|
|
11
|
+
processingCosts: "uncovered" | "all" | "none";
|
|
12
|
+
disputeCosts: "all" | "none";
|
|
13
|
+
};
|
|
14
|
+
rounding: "nearest" | "floor" | "ceil";
|
|
15
|
+
};
|
|
16
|
+
export type ProcessingCostDeficit = {
|
|
17
|
+
currency: string;
|
|
18
|
+
retainedFee: number;
|
|
19
|
+
processingLiability: number;
|
|
20
|
+
disputeLiability: number;
|
|
21
|
+
amountDue: number;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Pure same-currency ledger calculation. Host selects liability and rounding.
|
|
26
|
+
* All amounts are nonnegative integer API units, not decimal/display amounts.
|
|
27
|
+
* This does not establish provider eligibility or create a charge/transfer.
|
|
28
|
+
*/
|
|
29
|
+
export function calculateProcessingCostDeficit(
|
|
30
|
+
options: ProcessingCostDeficitOptions,
|
|
31
|
+
): ProcessingCostDeficit {
|
|
32
|
+
if (!options || typeof options !== "object")
|
|
33
|
+
throw new RangeError("Processing cost options are required.");
|
|
34
|
+
const currency =
|
|
35
|
+
typeof options.currency === "string"
|
|
36
|
+
? getChargeCurrencyMetadata(options.currency)
|
|
37
|
+
: null;
|
|
38
|
+
if (
|
|
39
|
+
!currency ||
|
|
40
|
+
[
|
|
41
|
+
options.gross,
|
|
42
|
+
options.sellingFee,
|
|
43
|
+
options.processingFee,
|
|
44
|
+
options.principalReturned,
|
|
45
|
+
options.disputeFees,
|
|
46
|
+
].some((amount) => !Number.isSafeInteger(amount) || amount < 0) ||
|
|
47
|
+
options.gross === 0 ||
|
|
48
|
+
options.sellingFee > options.gross ||
|
|
49
|
+
!["nearest", "floor", "ceil"].includes(options.rounding) ||
|
|
50
|
+
!["uncovered", "all", "none"].includes(
|
|
51
|
+
options.liability?.processingCosts,
|
|
52
|
+
) ||
|
|
53
|
+
!["all", "none"].includes(options.liability?.disputeCosts)
|
|
54
|
+
)
|
|
55
|
+
throw new RangeError(
|
|
56
|
+
"Invalid processing cost amounts, currency or policy.",
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
const gross = BigInt(options.gross);
|
|
60
|
+
const remaining =
|
|
61
|
+
gross - BigInt(Math.min(options.gross, options.principalReturned));
|
|
62
|
+
const numerator = BigInt(options.sellingFee) * remaining;
|
|
63
|
+
const remainder = numerator % gross;
|
|
64
|
+
const increment =
|
|
65
|
+
options.rounding === "ceil"
|
|
66
|
+
? remainder > 0n
|
|
67
|
+
: options.rounding === "nearest"
|
|
68
|
+
? 2n * remainder >= gross
|
|
69
|
+
: false;
|
|
70
|
+
const retainedFee = Number(numerator / gross + (increment ? 1n : 0n));
|
|
71
|
+
const processingLiability =
|
|
72
|
+
options.liability.processingCosts === "none"
|
|
73
|
+
? 0
|
|
74
|
+
: options.liability.processingCosts === "all"
|
|
75
|
+
? options.processingFee
|
|
76
|
+
: Math.max(0, options.processingFee - retainedFee);
|
|
77
|
+
const disputeLiability =
|
|
78
|
+
options.liability.disputeCosts === "all" ? options.disputeFees : 0;
|
|
79
|
+
const amountDue = processingLiability + disputeLiability;
|
|
80
|
+
if (!Number.isSafeInteger(amountDue))
|
|
81
|
+
throw new RangeError(
|
|
82
|
+
"Processing cost liability exceeds safe integer units.",
|
|
83
|
+
);
|
|
84
|
+
return {
|
|
85
|
+
currency: currency.currency,
|
|
86
|
+
retainedFee,
|
|
87
|
+
processingLiability,
|
|
88
|
+
disputeLiability,
|
|
89
|
+
amountDue,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type Stripe from "stripe";
|
|
2
|
+
import { saleAmountFailure } from "../paymentSource/economics.js";
|
|
2
3
|
import { isBetterStripeError, throwStripeError } from "../errors.js";
|
|
3
4
|
export type VerifiedSaleOptions = {
|
|
4
5
|
paymentIntentId: string;
|
|
@@ -62,20 +63,13 @@ export async function getVerifiedSale(
|
|
|
62
63
|
reason: "processing_fee_unavailable",
|
|
63
64
|
retryable: true,
|
|
64
65
|
};
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
charge.currency !== payment.currency
|
|
68
|
-
)
|
|
66
|
+
const amountFailure = saleAmountFailure(payment, charge, balance);
|
|
67
|
+
if (amountFailure === "currency")
|
|
69
68
|
throwStripeError(
|
|
70
69
|
"INVALID_CONFIGURATION",
|
|
71
70
|
"Settlement currency must match the payment and processing currency.",
|
|
72
71
|
);
|
|
73
|
-
if (
|
|
74
|
-
![payment.amount_received, balance.fee].every(Number.isSafeInteger) ||
|
|
75
|
-
balance.fee < 0 ||
|
|
76
|
-
balance.fee > payment.amount_received ||
|
|
77
|
-
charge.amount !== payment.amount_received
|
|
78
|
-
)
|
|
72
|
+
if (amountFailure === "amounts")
|
|
79
73
|
throwStripeError(
|
|
80
74
|
"INVALID_CONFIGURATION",
|
|
81
75
|
"Unsupported payment or processing amounts.",
|