@fantastic.dev/better-stripe 0.56.0 → 0.58.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 +18 -0
- package/README.md +5 -1
- package/dist/client/billing/setup-intent-read.d.ts +12 -1
- package/dist/client/billing/setup-intent-read.d.ts.map +1 -1
- package/dist/client/billing/setup-intent-read.js +13 -8
- package/dist/client/billing/setup-intent-read.js.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +366 -2
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +183 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +183 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -12
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -20
- package/dist/client/index.js.map +1 -1
- package/dist/client/types/triggers.d.ts +3 -1
- package/dist/client/types/triggers.d.ts.map +1 -1
- package/dist/client/usage/allowanceClient.d.ts +51 -0
- package/dist/client/usage/allowanceClient.d.ts.map +1 -0
- package/dist/client/usage/allowanceClient.js +64 -0
- package/dist/client/usage/allowanceClient.js.map +1 -0
- package/dist/client/usage/allowanceTerms.d.ts +64 -0
- package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
- package/dist/client/usage/allowanceTerms.js +101 -0
- package/dist/client/usage/allowanceTerms.js.map +1 -0
- package/dist/client/usage/client.d.ts +2 -2
- package/dist/client/usage/client.d.ts.map +1 -1
- package/dist/client/usage/client.js +4 -4
- package/dist/client/usage/client.js.map +1 -1
- package/dist/client/usage/creditCapacity.d.ts +5 -0
- package/dist/client/usage/creditCapacity.d.ts.map +1 -0
- package/dist/client/usage/creditCapacity.js +47 -0
- package/dist/client/usage/creditCapacity.js.map +1 -0
- package/dist/client/usage/creditClient.d.ts +104 -0
- package/dist/client/usage/creditClient.d.ts.map +1 -0
- package/dist/client/usage/creditClient.js +111 -0
- package/dist/client/usage/creditClient.js.map +1 -0
- package/dist/client/usage/creditDelivery.d.ts +6 -0
- package/dist/client/usage/creditDelivery.d.ts.map +1 -0
- package/dist/client/usage/creditDelivery.js +71 -0
- package/dist/client/usage/creditDelivery.js.map +1 -0
- package/dist/client/usage/creditInvoice.d.ts +6 -0
- package/dist/client/usage/creditInvoice.d.ts.map +1 -0
- package/dist/client/usage/creditInvoice.js +63 -0
- package/dist/client/usage/creditInvoice.js.map +1 -0
- package/dist/client/usage/creditLifecycle.d.ts +14 -0
- package/dist/client/usage/creditLifecycle.d.ts.map +1 -0
- package/dist/client/usage/creditLifecycle.js +90 -0
- package/dist/client/usage/creditLifecycle.js.map +1 -0
- package/dist/client/usage/creditNative.d.ts +20 -0
- package/dist/client/usage/creditNative.d.ts.map +1 -0
- package/dist/client/usage/creditNative.js +100 -0
- package/dist/client/usage/creditNative.js.map +1 -0
- package/dist/client/usage/creditObservation.d.ts +23 -0
- package/dist/client/usage/creditObservation.d.ts.map +1 -0
- package/dist/client/usage/creditObservation.js +54 -0
- package/dist/client/usage/creditObservation.js.map +1 -0
- package/dist/client/usage/creditProofs.d.ts +50 -0
- package/dist/client/usage/creditProofs.d.ts.map +1 -0
- package/dist/client/usage/creditProofs.js +58 -0
- package/dist/client/usage/creditProofs.js.map +1 -0
- package/dist/client/usage/creditProvider.d.ts +11 -0
- package/dist/client/usage/creditProvider.d.ts.map +1 -0
- package/dist/client/usage/creditProvider.js +195 -0
- package/dist/client/usage/creditProvider.js.map +1 -0
- package/dist/client/usage/creditRead.d.ts +47 -0
- package/dist/client/usage/creditRead.d.ts.map +1 -0
- package/dist/client/usage/creditRead.js +18 -0
- package/dist/client/usage/creditRead.js.map +1 -0
- package/dist/client/usage/creditReconciliation.d.ts +20 -0
- package/dist/client/usage/creditReconciliation.d.ts.map +1 -0
- package/dist/client/usage/creditReconciliation.js +157 -0
- package/dist/client/usage/creditReconciliation.js.map +1 -0
- package/dist/client/usage/creditTerms.d.ts +89 -0
- package/dist/client/usage/creditTerms.d.ts.map +1 -0
- package/dist/client/usage/creditTerms.js +76 -0
- package/dist/client/usage/creditTerms.js.map +1 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts +101 -0
- package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -0
- package/dist/client/usage/creditTransport.fixtures.js +271 -0
- package/dist/client/usage/creditTransport.fixtures.js.map +1 -0
- package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
- package/dist/client/usage/deliveryProvider.js +2 -0
- package/dist/client/usage/deliveryProvider.js.map +1 -1
- package/dist/client/usage/index.d.ts +4 -0
- package/dist/client/usage/index.d.ts.map +1 -1
- package/dist/client/usage/index.js +1 -0
- package/dist/client/usage/index.js.map +1 -1
- package/dist/client/usage/records.d.ts +2 -0
- package/dist/client/usage/records.d.ts.map +1 -1
- package/dist/client/usage/records.js +22 -0
- package/dist/client/usage/records.js.map +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -1
- package/dist/client/usage/subscriptionTransport.fixtures.js +4 -1
- package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -1
- package/dist/client/usage/summary.js +2 -2
- package/dist/client/usage/summary.js.map +1 -1
- package/dist/client/usageExports.d.ts +16 -0
- package/dist/client/usageExports.d.ts.map +1 -0
- package/dist/client/usageExports.js +3 -0
- package/dist/client/usageExports.js.map +1 -0
- package/dist/client/webhooks/subscriptionDeleted.d.ts +5 -0
- package/dist/client/webhooks/subscriptionDeleted.d.ts.map +1 -0
- package/dist/client/webhooks/subscriptionDeleted.js +34 -0
- package/dist/client/webhooks/subscriptionDeleted.js.map +1 -0
- package/dist/component/_generated/api.d.ts +18 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +360 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.d.ts.map +1 -1
- package/dist/component/accountClosure/mutations.js +10 -0
- package/dist/component/accountClosure/mutations.js.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +16 -16
- package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/queries.d.ts +1 -1
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/earnings/triggers.d.ts +352 -18
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/schema.d.ts +183 -1
- package/dist/component/schema.js +8 -0
- package/dist/component/schema.js.map +1 -1
- package/dist/component/usage/mutations.d.ts.map +1 -1
- package/dist/component/usage/mutations.js +7 -0
- package/dist/component/usage/mutations.js.map +1 -1
- package/dist/component/usage/schema.d.ts +15 -1
- package/dist/component/usage/schema.d.ts.map +1 -1
- package/dist/component/usage/schema.js +12 -0
- package/dist/component/usage/schema.js.map +1 -1
- package/dist/component/usageAllowance/helpers.d.ts +78 -0
- package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
- package/dist/component/usageAllowance/helpers.js +99 -0
- package/dist/component/usageAllowance/helpers.js.map +1 -0
- package/dist/component/usageAllowance/mutations.d.ts +37 -0
- package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
- package/dist/component/usageAllowance/mutations.js +99 -0
- package/dist/component/usageAllowance/mutations.js.map +1 -0
- package/dist/component/usageAllowance/queries.d.ts +36 -0
- package/dist/component/usageAllowance/queries.d.ts.map +1 -0
- package/dist/component/usageAllowance/queries.js +113 -0
- package/dist/component/usageAllowance/queries.js.map +1 -0
- package/dist/component/usageAllowance/reservations.d.ts +25 -0
- package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
- package/dist/component/usageAllowance/reservations.js +150 -0
- package/dist/component/usageAllowance/reservations.js.map +1 -0
- package/dist/component/usageAllowance/schema.d.ts +77 -0
- package/dist/component/usageAllowance/schema.d.ts.map +1 -0
- package/dist/component/usageAllowance/schema.js +32 -0
- package/dist/component/usageAllowance/schema.js.map +1 -0
- package/dist/component/usageCredits/helpers.d.ts +205 -0
- package/dist/component/usageCredits/helpers.d.ts.map +1 -0
- package/dist/component/usageCredits/helpers.js +129 -0
- package/dist/component/usageCredits/helpers.js.map +1 -0
- package/dist/component/usageCredits/mutations.d.ts +80 -0
- package/dist/component/usageCredits/mutations.d.ts.map +1 -0
- package/dist/component/usageCredits/mutations.js +344 -0
- package/dist/component/usageCredits/mutations.js.map +1 -0
- package/dist/component/usageCredits/purchase.d.ts +23 -0
- package/dist/component/usageCredits/purchase.d.ts.map +1 -0
- package/dist/component/usageCredits/purchase.js +166 -0
- package/dist/component/usageCredits/purchase.js.map +1 -0
- package/dist/component/usageCredits/queries.d.ts +184 -0
- package/dist/component/usageCredits/queries.d.ts.map +1 -0
- package/dist/component/usageCredits/queries.js +243 -0
- package/dist/component/usageCredits/queries.js.map +1 -0
- package/dist/component/usageCredits/reservations.d.ts +16 -0
- package/dist/component/usageCredits/reservations.d.ts.map +1 -0
- package/dist/component/usageCredits/reservations.js +161 -0
- package/dist/component/usageCredits/reservations.js.map +1 -0
- package/dist/component/usageCredits/schema.d.ts +282 -0
- package/dist/component/usageCredits/schema.d.ts.map +1 -0
- package/dist/component/usageCredits/schema.js +92 -0
- package/dist/component/usageCredits/schema.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/setup-intent-recovery.md +7 -0
- package/docs/usage-credits.md +255 -0
- package/docs/usage-ledger.md +7 -0
- package/docs/usage-limits.md +217 -0
- package/docs/webhooks.md +15 -1
- package/package.json +3 -1
- package/src/client/billing/setup-intent-read.test.ts +40 -0
- package/src/client/billing/setup-intent-read.ts +23 -9
- package/src/client/index.ts +9 -67
- package/src/client/types/triggers.ts +2 -0
- package/src/client/usage/allowanceClient.test.ts +93 -0
- package/src/client/usage/allowanceClient.ts +134 -0
- package/src/client/usage/allowanceTerms.test.ts +131 -0
- package/src/client/usage/allowanceTerms.ts +172 -0
- package/src/client/usage/client.ts +4 -4
- package/src/client/usage/creditCapacity.test.ts +83 -0
- package/src/client/usage/creditCapacity.ts +76 -0
- package/src/client/usage/creditClient.test.ts +221 -0
- package/src/client/usage/creditClient.ts +246 -0
- package/src/client/usage/creditDelivery.ts +105 -0
- package/src/client/usage/creditInvoice.test.ts +149 -0
- package/src/client/usage/creditInvoice.ts +87 -0
- package/src/client/usage/creditLifecycle.ts +175 -0
- package/src/client/usage/creditNative.ts +148 -0
- package/src/client/usage/creditObservation.test.ts +150 -0
- package/src/client/usage/creditObservation.ts +82 -0
- package/src/client/usage/creditProofs.ts +61 -0
- package/src/client/usage/creditProvider.test.ts +202 -0
- package/src/client/usage/creditProvider.ts +304 -0
- package/src/client/usage/creditRead.ts +32 -0
- package/src/client/usage/creditReconciliation.ts +213 -0
- package/src/client/usage/creditTerms.test.ts +48 -0
- package/src/client/usage/creditTerms.ts +140 -0
- package/src/client/usage/creditTransport.fixtures.ts +282 -0
- package/src/client/usage/deliveryProvider.ts +2 -0
- package/src/client/usage/index.ts +16 -0
- package/src/client/usage/record-composition.test.ts +195 -0
- package/src/client/usage/records.ts +26 -0
- package/src/client/usage/subscriptionTransport.fixtures.ts +6 -0
- package/src/client/usage/summary.test.ts +1 -1
- package/src/client/usage/summary.ts +2 -2
- package/src/client/usageExports.ts +56 -0
- package/src/client/webhook-handlers.test.ts +0 -34
- package/src/client/webhooks/subscription-deleted-dispatch.test.ts +61 -0
- package/src/client/webhooks/subscription-deleted.integration.test.ts +313 -0
- package/src/client/webhooks/subscriptionDeleted.ts +56 -0
- package/src/component/_generated/api.ts +18 -0
- package/src/component/_generated/component.ts +486 -0
- package/src/component/accountClosure/mutations.ts +14 -0
- package/src/component/schema.ts +16 -0
- package/src/component/usage/allowance.test.ts +435 -0
- package/src/component/usage/ledger.test.ts +8 -15
- package/src/component/usage/mutations.ts +22 -0
- package/src/component/usage/schema.ts +14 -0
- package/src/component/usageAllowance/helpers.ts +137 -0
- package/src/component/usageAllowance/mutations.ts +139 -0
- package/src/component/usageAllowance/queries.ts +133 -0
- package/src/component/usageAllowance/reservations.ts +220 -0
- package/src/component/usageAllowance/schema.ts +36 -0
- package/src/component/usageCredits/accounting.test.ts +389 -0
- package/src/component/usageCredits/helpers.ts +160 -0
- package/src/component/usageCredits/mutations.ts +451 -0
- package/src/component/usageCredits/purchase.ts +219 -0
- package/src/component/usageCredits/queries.ts +300 -0
- package/src/component/usageCredits/reservations.ts +214 -0
- package/src/component/usageCredits/schema.ts +106 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
2
|
+
import { UsageCreditRecoveryError } from "./creditTerms.js";
|
|
3
|
+
import type Stripe from "stripe";
|
|
4
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
5
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
6
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
7
|
+
import type { PreparedUsageRecord } from "./records.js";
|
|
8
|
+
import { creditNativeObservation } from "./creditProofs.js";
|
|
9
|
+
import { creditPurchaseTerms } from "./creditTerms.js";
|
|
10
|
+
import {
|
|
11
|
+
creditRequire,
|
|
12
|
+
paymentIdentity,
|
|
13
|
+
verifiedCreditPayment,
|
|
14
|
+
} from "./creditNative.js";
|
|
15
|
+
export async function verifyCreditDelivery(
|
|
16
|
+
stripe: Stripe,
|
|
17
|
+
component: Component,
|
|
18
|
+
ctx: RunCtx,
|
|
19
|
+
event: Doc<"usageEvents">,
|
|
20
|
+
record: PreparedUsageRecord,
|
|
21
|
+
) {
|
|
22
|
+
if (record.binding.plan.model !== "prepaid") return;
|
|
23
|
+
const saved = (await ctx.runQuery(
|
|
24
|
+
componentRef(component, "usageCredits/queries/deliveryBacking"),
|
|
25
|
+
{
|
|
26
|
+
scope: record.scope,
|
|
27
|
+
eventId: event._id,
|
|
28
|
+
},
|
|
29
|
+
)) as {
|
|
30
|
+
held: boolean;
|
|
31
|
+
purchases: Doc<"usageCreditPurchases">[];
|
|
32
|
+
grants: Doc<"usageCreditGrants">[];
|
|
33
|
+
};
|
|
34
|
+
creditRequire(
|
|
35
|
+
!saved.held && saved.grants.length > 0 && saved.grants.length <= 10,
|
|
36
|
+
"Credit delivery backing held",
|
|
37
|
+
);
|
|
38
|
+
for (let index = 0; index < saved.grants.length; index++) {
|
|
39
|
+
const local = saved.grants[index],
|
|
40
|
+
purchase = saved.purchases[index],
|
|
41
|
+
terms = creditPurchaseTerms(JSON.parse(purchase.termsJson));
|
|
42
|
+
const [grant, payment, summary] = await Promise.all([
|
|
43
|
+
stripe.billing.creditGrants.retrieve(local.creditGrantId),
|
|
44
|
+
stripe.paymentIntents.retrieve(local.paymentIntentId, {
|
|
45
|
+
expand: ["latest_charge"],
|
|
46
|
+
}),
|
|
47
|
+
stripe.billing.creditBalanceSummaries.retrieve({
|
|
48
|
+
customer_account: record.scope.customerAccount,
|
|
49
|
+
filter: { type: "credit_grant", credit_grant: local.creditGrantId },
|
|
50
|
+
}),
|
|
51
|
+
]);
|
|
52
|
+
paymentIdentity(payment, terms, purchase.key, local.paymentIntentId);
|
|
53
|
+
try {
|
|
54
|
+
creditRequire(
|
|
55
|
+
verifiedCreditPayment(payment, terms),
|
|
56
|
+
"Credit payment no longer verified",
|
|
57
|
+
);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof UsageCreditRecoveryError)
|
|
60
|
+
await runMutationOrThrow(
|
|
61
|
+
ctx,
|
|
62
|
+
componentRef(component, "usageCredits/mutations/freezePurchase"),
|
|
63
|
+
{
|
|
64
|
+
key: purchase.key,
|
|
65
|
+
paymentIntentId: local.paymentIntentId,
|
|
66
|
+
reason: error.reason,
|
|
67
|
+
refundedAmount:
|
|
68
|
+
typeof payment.latest_charge === "object"
|
|
69
|
+
? payment.latest_charge?.amount_refunded
|
|
70
|
+
: undefined,
|
|
71
|
+
},
|
|
72
|
+
);
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
const native = summary.balances[0]?.ledger_balance.monetary;
|
|
76
|
+
const available = summary.balances[0]?.available_balance.monetary;
|
|
77
|
+
const last = local.nativeObservationJson
|
|
78
|
+
? creditNativeObservation.parse(JSON.parse(local.nativeObservationJson))
|
|
79
|
+
: null;
|
|
80
|
+
// A changed balance requires invoice/source reconciliation before a new send.
|
|
81
|
+
// Grant creation is the initial authoritative funding observation.
|
|
82
|
+
const expected = last?.ledgerAmount ?? terms.amount;
|
|
83
|
+
creditRequire(
|
|
84
|
+
grant.id === local.creditGrantId &&
|
|
85
|
+
!grant.voided_at &&
|
|
86
|
+
grant.customer_account === record.scope.customerAccount &&
|
|
87
|
+
grant.livemode === record.scope.livemode &&
|
|
88
|
+
grant.metadata?.bsUsageCredit === purchase.key &&
|
|
89
|
+
(grant.expires_at === null ||
|
|
90
|
+
grant.expires_at >
|
|
91
|
+
JSON.parse(event.subscriptionJson).period.end + 72 * 3600) &&
|
|
92
|
+
grant.applicability_config.scope.prices?.length === 1 &&
|
|
93
|
+
grant.applicability_config.scope.prices[0].id ===
|
|
94
|
+
record.binding.stripePriceId &&
|
|
95
|
+
summary.livemode === record.scope.livemode &&
|
|
96
|
+
summary.customer_account === record.scope.customerAccount &&
|
|
97
|
+
summary.balances.length === 1 &&
|
|
98
|
+
native?.currency === terms.binding.plan.rate.currency &&
|
|
99
|
+
native.value === expected &&
|
|
100
|
+
available?.currency === native.currency &&
|
|
101
|
+
available.value === native.value,
|
|
102
|
+
"Credit delivery requires current native backing reconciliation",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import Stripe from "stripe";
|
|
2
|
+
import { componentsGeneric } from "convex/server";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { verifyCreditInvoice } from "./creditInvoice.js";
|
|
5
|
+
import { creditPurchaseTerms } from "./creditTerms.js";
|
|
6
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
7
|
+
const terms = creditPurchaseTerms({
|
|
8
|
+
scope: {
|
|
9
|
+
stripeAccountId: "acct_platform",
|
|
10
|
+
customerAccount: "acct_buyer",
|
|
11
|
+
meterId: "mtr_calls",
|
|
12
|
+
livemode: false,
|
|
13
|
+
},
|
|
14
|
+
binding: {
|
|
15
|
+
stripeCustomerId: "cus_buyer",
|
|
16
|
+
stripePriceId: "price_calls",
|
|
17
|
+
eventName: "calls",
|
|
18
|
+
plan: {
|
|
19
|
+
key: "calls",
|
|
20
|
+
version: "v1",
|
|
21
|
+
model: "prepaid",
|
|
22
|
+
unit: { name: "call", precision: 0 },
|
|
23
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
24
|
+
insufficientBalance: "reject",
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
purchaseId: "topup1",
|
|
28
|
+
quantity: "10",
|
|
29
|
+
ownership: "issuer",
|
|
30
|
+
rollover: "retain_original_terms",
|
|
31
|
+
});
|
|
32
|
+
function fixture() {
|
|
33
|
+
const native = {
|
|
34
|
+
id: "in_usage",
|
|
35
|
+
livemode: false,
|
|
36
|
+
customer_account: "acct_buyer",
|
|
37
|
+
customer: "cus_buyer",
|
|
38
|
+
currency: "usd",
|
|
39
|
+
status: "paid",
|
|
40
|
+
amount_paid: 0,
|
|
41
|
+
amount_due: 0,
|
|
42
|
+
status_transitions: { finalized_at: 1300 },
|
|
43
|
+
parent: { subscription_details: { subscription: "sub_original" } },
|
|
44
|
+
lines: {
|
|
45
|
+
has_more: false,
|
|
46
|
+
data: [
|
|
47
|
+
{
|
|
48
|
+
id: "il_usage",
|
|
49
|
+
amount: 12,
|
|
50
|
+
currency: "usd",
|
|
51
|
+
quantity_decimal: "6",
|
|
52
|
+
period: { start: 600, end: 1200 },
|
|
53
|
+
pricing: {
|
|
54
|
+
price_details: { price: "price_calls" },
|
|
55
|
+
unit_amount_decimal: "2",
|
|
56
|
+
},
|
|
57
|
+
parent: {
|
|
58
|
+
subscription_item_details: {
|
|
59
|
+
subscription: "sub_original",
|
|
60
|
+
subscription_item: "si_original",
|
|
61
|
+
proration: false,
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
pretax_credit_amounts: [
|
|
65
|
+
{
|
|
66
|
+
type: "credit_balance_transaction",
|
|
67
|
+
credit_balance_transaction: "cbtxn_applied",
|
|
68
|
+
amount: 12,
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
const stripe = new Stripe("sk_test_credit_invoice", {
|
|
76
|
+
httpClient: Stripe.createFetchHttpClient(
|
|
77
|
+
async () =>
|
|
78
|
+
new Response(JSON.stringify(native), {
|
|
79
|
+
headers: { "content-type": "application/json" },
|
|
80
|
+
}),
|
|
81
|
+
),
|
|
82
|
+
});
|
|
83
|
+
const requests: unknown[] = [],
|
|
84
|
+
local = { complete: true, valid: true, scaledQuantity: "6" };
|
|
85
|
+
const ctx = {
|
|
86
|
+
runQuery: async (_reference: unknown, args: unknown) => {
|
|
87
|
+
requests.push(args);
|
|
88
|
+
return local;
|
|
89
|
+
},
|
|
90
|
+
} as unknown as RunCtx;
|
|
91
|
+
const tx = {
|
|
92
|
+
id: "cbtxn_applied",
|
|
93
|
+
debit: {
|
|
94
|
+
type: "credits_applied",
|
|
95
|
+
amount: { type: "monetary", monetary: { currency: "usd", value: 12 } },
|
|
96
|
+
credits_applied: { invoice: "in_usage", invoice_line_item: "il_usage" },
|
|
97
|
+
},
|
|
98
|
+
} as unknown as Stripe.Billing.CreditBalanceTransaction;
|
|
99
|
+
const component = componentsGeneric().betterStripe as unknown as Component;
|
|
100
|
+
const read = () => verifyCreditInvoice(stripe, component, ctx, terms, tx);
|
|
101
|
+
return { native, stripe, requests, local, tx, read };
|
|
102
|
+
}
|
|
103
|
+
it("proves a fully credit-funded original invoice line without treating paid as new cash", async () => {
|
|
104
|
+
const f = fixture();
|
|
105
|
+
expect(await f.read()).toBe(true);
|
|
106
|
+
expect(f.requests).toMatchObject([
|
|
107
|
+
{
|
|
108
|
+
subscriptionId: "sub_original",
|
|
109
|
+
subscriptionItemId: "si_original",
|
|
110
|
+
start: 600,
|
|
111
|
+
end: 1200,
|
|
112
|
+
},
|
|
113
|
+
]);
|
|
114
|
+
});
|
|
115
|
+
it("refuses foreign payer, changed price, truncated lines, proration and changed credit provenance", async () => {
|
|
116
|
+
const foreign = fixture();
|
|
117
|
+
foreign.native.customer_account = "acct_other";
|
|
118
|
+
expect(await foreign.read()).toBe(false);
|
|
119
|
+
const changed = fixture();
|
|
120
|
+
changed.native.lines.data[0].pricing.price_details.price = "price_new";
|
|
121
|
+
expect(await changed.read()).toBe(false);
|
|
122
|
+
const partial = fixture();
|
|
123
|
+
partial.native.lines.has_more = true;
|
|
124
|
+
expect(await partial.read()).toBe(false);
|
|
125
|
+
const prorated = fixture();
|
|
126
|
+
prorated.native.lines.data[0].parent.subscription_item_details.proration = true;
|
|
127
|
+
expect(await prorated.read()).toBe(false);
|
|
128
|
+
const other = fixture();
|
|
129
|
+
other.native.lines.data[0].pretax_credit_amounts[0].credit_balance_transaction =
|
|
130
|
+
"cbtxn_other";
|
|
131
|
+
expect(await other.read()).toBe(false);
|
|
132
|
+
});
|
|
133
|
+
it("requires exact complete local quantities and successful native delivery", async () => {
|
|
134
|
+
for (const local of [
|
|
135
|
+
{ complete: false, valid: true, scaledQuantity: "6" },
|
|
136
|
+
{ complete: true, valid: false, scaledQuantity: "6" },
|
|
137
|
+
{ complete: true, valid: true, scaledQuantity: "7" },
|
|
138
|
+
]) {
|
|
139
|
+
const f = fixture();
|
|
140
|
+
Object.assign(f.local, local);
|
|
141
|
+
expect(await f.read()).toBe(false);
|
|
142
|
+
}
|
|
143
|
+
const fractional = fixture();
|
|
144
|
+
fractional.native.lines.data[0].quantity_decimal = "6.1";
|
|
145
|
+
expect(await fractional.read()).toBe(false);
|
|
146
|
+
const extraCharge = fixture();
|
|
147
|
+
extraCharge.native.lines.data[0].pretax_credit_amounts[0].amount = 10;
|
|
148
|
+
expect(await extraCharge.read()).toBe(false);
|
|
149
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
3
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
4
|
+
import { creditCost, type UsageCreditPurchaseTerms } from "./creditTerms.js";
|
|
5
|
+
import { creditRequire } from "./creditNative.js";
|
|
6
|
+
const id = (value: string | { id: string } | null | undefined) =>
|
|
7
|
+
typeof value === "string" ? value : value?.id;
|
|
8
|
+
/** Prove the credit-funded line against immutable original accepted usage, never current prices. */
|
|
9
|
+
export async function verifyCreditInvoice(
|
|
10
|
+
stripe: Stripe,
|
|
11
|
+
component: Component,
|
|
12
|
+
ctx: RunCtx,
|
|
13
|
+
terms: UsageCreditPurchaseTerms,
|
|
14
|
+
transaction: Stripe.Billing.CreditBalanceTransaction,
|
|
15
|
+
): Promise<boolean> {
|
|
16
|
+
const debit = transaction.debit,
|
|
17
|
+
source = debit?.credits_applied;
|
|
18
|
+
if (debit?.type !== "credits_applied" || !source) return false;
|
|
19
|
+
const invoiceId = id(source.invoice);
|
|
20
|
+
creditRequire(invoiceId, "Credit invoice identity unavailable");
|
|
21
|
+
const invoice = await stripe.invoices.retrieve(invoiceId);
|
|
22
|
+
const subscriptionId = id(invoice.parent?.subscription_details?.subscription);
|
|
23
|
+
if (
|
|
24
|
+
invoice.id !== invoiceId ||
|
|
25
|
+
!subscriptionId ||
|
|
26
|
+
invoice.livemode !== terms.scope.livemode ||
|
|
27
|
+
invoice.customer_account !== terms.scope.customerAccount ||
|
|
28
|
+
id(invoice.customer) !== terms.binding.stripeCustomerId ||
|
|
29
|
+
invoice.currency !== terms.binding.plan.rate.currency ||
|
|
30
|
+
!["open", "paid", "uncollectible"].includes(invoice.status ?? "") ||
|
|
31
|
+
!invoice.status_transitions.finalized_at ||
|
|
32
|
+
invoice.lines.has_more ||
|
|
33
|
+
invoice.lines.data.length > 100
|
|
34
|
+
)
|
|
35
|
+
return false;
|
|
36
|
+
const line = invoice.lines.data.find(
|
|
37
|
+
(l) => l.id === source.invoice_line_item,
|
|
38
|
+
);
|
|
39
|
+
const parent = line?.parent?.subscription_item_details;
|
|
40
|
+
const raw = line?.quantity_decimal?.toString();
|
|
41
|
+
if (
|
|
42
|
+
!line ||
|
|
43
|
+
!parent ||
|
|
44
|
+
parent.subscription !== subscriptionId ||
|
|
45
|
+
!parent.subscription_item ||
|
|
46
|
+
parent.proration ||
|
|
47
|
+
line.pricing?.price_details?.price !== terms.binding.stripePriceId ||
|
|
48
|
+
line.currency !== terms.binding.plan.rate.currency ||
|
|
49
|
+
!raw ||
|
|
50
|
+
!/^\d+(\.0+)?$/.test(raw)
|
|
51
|
+
)
|
|
52
|
+
return false;
|
|
53
|
+
const local = (await ctx.runQuery(
|
|
54
|
+
componentRef(component, "usageCredits/queries/invoiceUsage"),
|
|
55
|
+
{
|
|
56
|
+
bindingJson: JSON.stringify({
|
|
57
|
+
scope: terms.scope,
|
|
58
|
+
binding: terms.binding,
|
|
59
|
+
}),
|
|
60
|
+
subscriptionId,
|
|
61
|
+
subscriptionItemId: parent.subscription_item,
|
|
62
|
+
start: line.period.start,
|
|
63
|
+
end: line.period.end,
|
|
64
|
+
},
|
|
65
|
+
)) as { complete: boolean; valid: boolean; scaledQuantity: string };
|
|
66
|
+
const scaled = BigInt(raw.split(".")[0]);
|
|
67
|
+
if (
|
|
68
|
+
!local.complete ||
|
|
69
|
+
!local.valid ||
|
|
70
|
+
scaled !== BigInt(local.scaledQuantity) ||
|
|
71
|
+
scaled === 0n ||
|
|
72
|
+
line.amount !== creditCost(terms.binding.plan, scaled.toString())
|
|
73
|
+
)
|
|
74
|
+
return false;
|
|
75
|
+
const credits = line.pretax_credit_amounts ?? [];
|
|
76
|
+
return (
|
|
77
|
+
credits.some(
|
|
78
|
+
(c) =>
|
|
79
|
+
c.type === "credit_balance_transaction" &&
|
|
80
|
+
id(c.credit_balance_transaction) === transaction.id &&
|
|
81
|
+
c.amount === debit.amount.monetary?.value,
|
|
82
|
+
) &&
|
|
83
|
+
credits
|
|
84
|
+
.filter((c) => c.type === "credit_balance_transaction")
|
|
85
|
+
.reduce((sum, c) => sum + BigInt(c.amount), 0n) === BigInt(line.amount)
|
|
86
|
+
);
|
|
87
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { findCreditPurchase } from "./creditRead.js";
|
|
2
|
+
import { reconcileCreditPurchase } from "./creditReconciliation.js";
|
|
3
|
+
import type Stripe from "stripe";
|
|
4
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
5
|
+
import { runMutationOrThrow } from "../helpers.js";
|
|
6
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
7
|
+
import {
|
|
8
|
+
UsageCreditError,
|
|
9
|
+
type UsageCreditPurchaseOptions,
|
|
10
|
+
} from "./creditTerms.js";
|
|
11
|
+
import {
|
|
12
|
+
creditCall,
|
|
13
|
+
creditRequire,
|
|
14
|
+
verifyCreditRealm,
|
|
15
|
+
discoverCredit,
|
|
16
|
+
paymentIdentity,
|
|
17
|
+
verifiedCreditPayment,
|
|
18
|
+
} from "./creditNative.js";
|
|
19
|
+
import { creditPurchaseView } from "./creditProvider.js";
|
|
20
|
+
export async function cancelCreditPurchase(
|
|
21
|
+
stripe: Stripe,
|
|
22
|
+
component: Component,
|
|
23
|
+
ctx: RunCtx,
|
|
24
|
+
input: UsageCreditPurchaseOptions,
|
|
25
|
+
) {
|
|
26
|
+
return creditCall(async () => {
|
|
27
|
+
const { row, terms } = await findCreditPurchase(component, ctx, input);
|
|
28
|
+
await verifyCreditRealm(stripe, terms);
|
|
29
|
+
creditRequire(
|
|
30
|
+
!row.creditGrantId && !row.paymentProofJson,
|
|
31
|
+
"Paid credit purchases require refund recovery",
|
|
32
|
+
);
|
|
33
|
+
let payment = row.paymentIntentId
|
|
34
|
+
? await stripe.paymentIntents.retrieve(row.paymentIntentId)
|
|
35
|
+
: await discoverCredit(row.key, (cursor) =>
|
|
36
|
+
stripe.paymentIntents.list({
|
|
37
|
+
customer_account: terms.scope.customerAccount,
|
|
38
|
+
limit: 100,
|
|
39
|
+
...(cursor ? { starting_after: cursor } : {}),
|
|
40
|
+
}),
|
|
41
|
+
);
|
|
42
|
+
if (!payment) {
|
|
43
|
+
if (row.paymentAttemptedAt === undefined) {
|
|
44
|
+
await runMutationOrThrow(
|
|
45
|
+
ctx,
|
|
46
|
+
componentRef(component, "usageCredits/mutations/cancelUnstarted"),
|
|
47
|
+
{ key: row.key },
|
|
48
|
+
);
|
|
49
|
+
return creditPurchaseView({ ...row, state: "canceled" });
|
|
50
|
+
}
|
|
51
|
+
throw new UsageCreditError(
|
|
52
|
+
"unknown_create_outcome",
|
|
53
|
+
"Unknown original payment requires reconciliation before abandonment",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
paymentIdentity(payment, terms, row.key, row.paymentIntentId);
|
|
57
|
+
await runMutationOrThrow(
|
|
58
|
+
ctx,
|
|
59
|
+
componentRef(component, "usageCredits/mutations/pinPayment"),
|
|
60
|
+
{ key: row.key, paymentIntentId: payment.id },
|
|
61
|
+
);
|
|
62
|
+
if (payment.status !== "canceled") {
|
|
63
|
+
creditRequire(
|
|
64
|
+
[
|
|
65
|
+
"requires_payment_method",
|
|
66
|
+
"requires_confirmation",
|
|
67
|
+
"requires_action",
|
|
68
|
+
].includes(payment.status),
|
|
69
|
+
"Pending or successful payment requires observation before cancellation",
|
|
70
|
+
);
|
|
71
|
+
payment = await stripe.paymentIntents.cancel(
|
|
72
|
+
payment.id,
|
|
73
|
+
{ cancellation_reason: "requested_by_customer" },
|
|
74
|
+
{ idempotencyKey: "bs_usage_credit_cancel_" + row.key },
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
creditRequire(
|
|
78
|
+
payment.status === "canceled",
|
|
79
|
+
"Native credit payment cancellation unconfirmed",
|
|
80
|
+
);
|
|
81
|
+
paymentIdentity(payment, terms, row.key, row.paymentIntentId);
|
|
82
|
+
await runMutationOrThrow(
|
|
83
|
+
ctx,
|
|
84
|
+
componentRef(component, "usageCredits/mutations/cancelPurchase"),
|
|
85
|
+
{ key: row.key, paymentIntentId: payment.id },
|
|
86
|
+
);
|
|
87
|
+
return creditPurchaseView({
|
|
88
|
+
...row,
|
|
89
|
+
state: "canceled",
|
|
90
|
+
paymentIntentId: payment.id,
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Disable only wholly unspent native credits before the existing monetary refund API. */
|
|
96
|
+
export async function prepareCreditRefund(
|
|
97
|
+
stripe: Stripe,
|
|
98
|
+
component: Component,
|
|
99
|
+
ctx: RunCtx,
|
|
100
|
+
input: UsageCreditPurchaseOptions,
|
|
101
|
+
) {
|
|
102
|
+
return creditCall(async () => {
|
|
103
|
+
const { row, terms } = await findCreditPurchase(component, ctx, input);
|
|
104
|
+
await verifyCreditRealm(stripe, terms, false);
|
|
105
|
+
creditRequire(
|
|
106
|
+
row.creditGrantId && row.paymentIntentId,
|
|
107
|
+
"Verified credit purchase required",
|
|
108
|
+
);
|
|
109
|
+
const originalPayment = await stripe.paymentIntents.retrieve(
|
|
110
|
+
row.paymentIntentId,
|
|
111
|
+
{ expand: ["latest_charge"] },
|
|
112
|
+
);
|
|
113
|
+
paymentIdentity(originalPayment, terms, row.key, row.paymentIntentId);
|
|
114
|
+
creditRequire(
|
|
115
|
+
verifiedCreditPayment(originalPayment, terms),
|
|
116
|
+
"Original credit purchase payment unavailable",
|
|
117
|
+
);
|
|
118
|
+
const observation = await reconcileCreditPurchase(
|
|
119
|
+
stripe,
|
|
120
|
+
component,
|
|
121
|
+
ctx,
|
|
122
|
+
input,
|
|
123
|
+
);
|
|
124
|
+
creditRequire(
|
|
125
|
+
observation.status === "available" &&
|
|
126
|
+
observation.value.applied === 0 &&
|
|
127
|
+
observation.value.reinstated === 0 &&
|
|
128
|
+
(observation.value.ledgerAmount === terms.amount ||
|
|
129
|
+
(observation.value.ledgerAmount === 0 &&
|
|
130
|
+
observation.value.expired + observation.value.voided ===
|
|
131
|
+
terms.amount)),
|
|
132
|
+
"Current credit reconciliation required",
|
|
133
|
+
);
|
|
134
|
+
await runMutationOrThrow(
|
|
135
|
+
ctx,
|
|
136
|
+
componentRef(component, "usageCredits/mutations/prepareRefund"),
|
|
137
|
+
{ key: row.key },
|
|
138
|
+
);
|
|
139
|
+
const grant = await stripe.billing.creditGrants.retrieve(row.creditGrantId);
|
|
140
|
+
creditRequire(
|
|
141
|
+
grant.id === row.creditGrantId &&
|
|
142
|
+
grant.customer_account === terms.scope.customerAccount &&
|
|
143
|
+
grant.livemode === terms.scope.livemode &&
|
|
144
|
+
grant.metadata?.bsUsageCredit === row.key,
|
|
145
|
+
"Original credit grant identity mismatch",
|
|
146
|
+
);
|
|
147
|
+
if (
|
|
148
|
+
!grant.voided_at &&
|
|
149
|
+
(grant.expires_at === null || grant.expires_at > Date.now() / 1000)
|
|
150
|
+
)
|
|
151
|
+
await stripe.billing.creditGrants.expire(
|
|
152
|
+
grant.id,
|
|
153
|
+
{},
|
|
154
|
+
{ idempotencyKey: "bs_usage_credit_expire_" + row.key },
|
|
155
|
+
);
|
|
156
|
+
const result = await reconcileCreditPurchase(stripe, component, ctx, input);
|
|
157
|
+
creditRequire(
|
|
158
|
+
result.status === "available" &&
|
|
159
|
+
result.value.backing === "sufficient" &&
|
|
160
|
+
result.value.ledgerAmount === 0 &&
|
|
161
|
+
result.value.applied === 0 &&
|
|
162
|
+
result.value.reinstated === 0 &&
|
|
163
|
+
result.value.expired + result.value.voided === terms.amount,
|
|
164
|
+
"Native credit expiration not yet confirmed",
|
|
165
|
+
);
|
|
166
|
+
return {
|
|
167
|
+
paymentIntentId: row.paymentIntentId,
|
|
168
|
+
amount: terms.amount,
|
|
169
|
+
currency: terms.binding.plan.rate.currency,
|
|
170
|
+
creditGrantId: row.creditGrantId,
|
|
171
|
+
creditState: "disabled" as const,
|
|
172
|
+
cashRefund: "required" as const,
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { UsageCreditPurchaseTerms } from "./creditTerms.js";
|
|
3
|
+
import { UsageCreditError, UsageCreditRecoveryError } from "./creditTerms.js";
|
|
4
|
+
import { verifyRealm } from "./catalogTypes.js";
|
|
5
|
+
import { verifyPinnedUsagePrice } from "./catalogPrices.js";
|
|
6
|
+
import { paymentCreditProof } from "./creditProofs.js";
|
|
7
|
+
export async function creditCall<T>(call: () => Promise<T>): Promise<T> {
|
|
8
|
+
try {
|
|
9
|
+
return await call();
|
|
10
|
+
} catch (error) {
|
|
11
|
+
if (error instanceof UsageCreditError) throw error;
|
|
12
|
+
throw new UsageCreditError(
|
|
13
|
+
"provider_unavailable",
|
|
14
|
+
"Native usage credits unavailable",
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function creditRequire(
|
|
19
|
+
condition: unknown,
|
|
20
|
+
message: string,
|
|
21
|
+
): asserts condition {
|
|
22
|
+
if (!condition)
|
|
23
|
+
throw new UsageCreditError("reconciliation_required", message);
|
|
24
|
+
}
|
|
25
|
+
export async function verifyCreditRealm(
|
|
26
|
+
stripe: Stripe,
|
|
27
|
+
terms: UsageCreditPurchaseTerms,
|
|
28
|
+
checkPrice = true,
|
|
29
|
+
) {
|
|
30
|
+
const scope = {
|
|
31
|
+
stripeAccountId: terms.scope.stripeAccountId,
|
|
32
|
+
livemode: terms.scope.livemode,
|
|
33
|
+
};
|
|
34
|
+
await verifyRealm(stripe, scope);
|
|
35
|
+
const customer = await stripe.customers.retrieve(terms.scope.customerAccount);
|
|
36
|
+
creditRequire(
|
|
37
|
+
!customer.deleted &&
|
|
38
|
+
customer.id === terms.binding.stripeCustomerId &&
|
|
39
|
+
customer.customer_account === terms.scope.customerAccount &&
|
|
40
|
+
customer.livemode === terms.scope.livemode,
|
|
41
|
+
"Native credit customer scope mismatch",
|
|
42
|
+
);
|
|
43
|
+
if (!checkPrice) return;
|
|
44
|
+
const price = await stripe.prices.retrieve(terms.binding.stripePriceId, {
|
|
45
|
+
expand: ["tiers"],
|
|
46
|
+
});
|
|
47
|
+
creditRequire(
|
|
48
|
+
price.id === terms.binding.stripePriceId,
|
|
49
|
+
"Native credit price identity mismatch",
|
|
50
|
+
);
|
|
51
|
+
verifyPinnedUsagePrice(price, scope, terms.binding.plan, terms.scope.meterId);
|
|
52
|
+
}
|
|
53
|
+
export function paymentIdentity(
|
|
54
|
+
payment: Stripe.PaymentIntent,
|
|
55
|
+
terms: UsageCreditPurchaseTerms,
|
|
56
|
+
key: string,
|
|
57
|
+
pinned?: string,
|
|
58
|
+
) {
|
|
59
|
+
creditRequire(
|
|
60
|
+
payment.object === "payment_intent" &&
|
|
61
|
+
(!pinned || payment.id === pinned) &&
|
|
62
|
+
payment.customer_account === terms.scope.customerAccount &&
|
|
63
|
+
payment.livemode === terms.scope.livemode &&
|
|
64
|
+
payment.currency === terms.binding.plan.rate.currency &&
|
|
65
|
+
payment.amount === terms.amount &&
|
|
66
|
+
payment.metadata.bsUsageCredit === key &&
|
|
67
|
+
!payment.transfer_data &&
|
|
68
|
+
!payment.on_behalf_of &&
|
|
69
|
+
!payment.application_fee_amount,
|
|
70
|
+
"Native credit payment scope or identity mismatch",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
export function verifiedCreditPayment(
|
|
74
|
+
payment: Stripe.PaymentIntent,
|
|
75
|
+
terms: UsageCreditPurchaseTerms,
|
|
76
|
+
) {
|
|
77
|
+
if (payment.status !== "succeeded") return null;
|
|
78
|
+
const charge = payment.latest_charge;
|
|
79
|
+
creditRequire(
|
|
80
|
+
payment.amount_received === terms.amount &&
|
|
81
|
+
charge &&
|
|
82
|
+
typeof charge !== "string" &&
|
|
83
|
+
charge.object === "charge" &&
|
|
84
|
+
charge.payment_intent === payment.id &&
|
|
85
|
+
charge.paid &&
|
|
86
|
+
charge.captured &&
|
|
87
|
+
charge.status === "succeeded" &&
|
|
88
|
+
charge.amount === terms.amount &&
|
|
89
|
+
charge.amount_captured === terms.amount &&
|
|
90
|
+
charge.currency === terms.binding.plan.rate.currency &&
|
|
91
|
+
charge.livemode === terms.scope.livemode,
|
|
92
|
+
"Credit payment success is not verified",
|
|
93
|
+
);
|
|
94
|
+
if (charge.disputed || charge.refunded || charge.amount_refunded !== 0)
|
|
95
|
+
throw new UsageCreditRecoveryError(
|
|
96
|
+
charge.disputed ? "payment_disputed" : "payment_refunded",
|
|
97
|
+
);
|
|
98
|
+
return paymentCreditProof.parse({
|
|
99
|
+
paymentIntentId: payment.id,
|
|
100
|
+
chargeId: charge.id,
|
|
101
|
+
amount: terms.amount,
|
|
102
|
+
currency: payment.currency,
|
|
103
|
+
customerAccount: terms.scope.customerAccount,
|
|
104
|
+
livemode: terms.scope.livemode,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
export function creditCreateWindow(firstAttemptAt: number) {
|
|
108
|
+
if (Date.now() / 1000 - firstAttemptAt >= 23 * 3600)
|
|
109
|
+
throw new UsageCreditError(
|
|
110
|
+
"unknown_create_outcome",
|
|
111
|
+
"Native credit creation requires reconciliation after its safe retry window",
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
export async function discoverCredit<
|
|
115
|
+
T extends { id: string; metadata: Stripe.Metadata | null },
|
|
116
|
+
>(
|
|
117
|
+
key: string,
|
|
118
|
+
list: (cursor?: string) => Promise<Stripe.ApiList<T>>,
|
|
119
|
+
): Promise<T | null> {
|
|
120
|
+
let cursor: string | undefined,
|
|
121
|
+
found: T | null = null;
|
|
122
|
+
for (let page = 0; page < 10; page++) {
|
|
123
|
+
const result = await list(cursor);
|
|
124
|
+
creditRequire(
|
|
125
|
+
result.data.length <= 100,
|
|
126
|
+
"Native credit discovery incomplete",
|
|
127
|
+
);
|
|
128
|
+
for (const row of result.data) {
|
|
129
|
+
if (row.metadata?.bsUsageCredit !== key) continue;
|
|
130
|
+
creditRequire(
|
|
131
|
+
!found || found.id === row.id,
|
|
132
|
+
"Ambiguous native credit identity",
|
|
133
|
+
);
|
|
134
|
+
found = row;
|
|
135
|
+
}
|
|
136
|
+
if (!result.has_more) return found;
|
|
137
|
+
const next = result.data[result.data.length - 1]?.id;
|
|
138
|
+
creditRequire(
|
|
139
|
+
next && next !== cursor,
|
|
140
|
+
"Native credit discovery incomplete",
|
|
141
|
+
);
|
|
142
|
+
cursor = next;
|
|
143
|
+
}
|
|
144
|
+
throw new UsageCreditError(
|
|
145
|
+
"reconciliation_required",
|
|
146
|
+
"Native credit discovery incomplete",
|
|
147
|
+
);
|
|
148
|
+
}
|