@fantastic.dev/better-stripe 0.47.1 → 0.48.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +1 -1
- package/dist/client/billing/historyPages.d.ts +22 -0
- package/dist/client/billing/historyPages.d.ts.map +1 -0
- package/dist/client/billing/historyPages.js +8 -0
- package/dist/client/billing/historyPages.js.map +1 -0
- package/dist/client/billing/subscriptions.d.ts +2 -3
- package/dist/client/billing/subscriptions.d.ts.map +1 -1
- package/dist/client/billing/subscriptions.js.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +5 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +10 -0
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/core/accounts.d.ts +2 -3
- package/dist/client/core/accounts.d.ts.map +1 -1
- package/dist/client/core/accounts.js.map +1 -1
- package/dist/client/index.d.ts +3 -6
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/originalIdReadOptions.d.ts +10 -0
- package/dist/client/originalIdReadOptions.d.ts.map +1 -0
- package/dist/client/originalIdReadOptions.js +2 -0
- package/dist/client/originalIdReadOptions.js.map +1 -0
- package/dist/client/publicTypes.d.ts +2 -0
- package/dist/client/publicTypes.d.ts.map +1 -1
- package/dist/client/readContracts.d.ts +4 -0
- package/dist/client/readContracts.d.ts.map +1 -1
- package/dist/client/readContracts.js +8 -0
- package/dist/client/readContracts.js.map +1 -1
- package/dist/client/webhooks/handler.d.ts.map +1 -1
- package/dist/client/webhooks/handler.js +6 -3
- package/dist/client/webhooks/handler.js.map +1 -1
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -65
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/client/webhooks/refundDelivery.d.ts +5 -0
- package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
- package/dist/client/webhooks/refundDelivery.js +28 -0
- package/dist/client/webhooks/refundDelivery.js.map +1 -0
- package/dist/client/webhooks/refundRecovery.d.ts +5 -0
- package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
- package/dist/client/webhooks/refundRecovery.js +36 -0
- package/dist/client/webhooks/refundRecovery.js.map +1 -0
- package/dist/component/_generated/api.d.ts +4 -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 +102 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/billing/queries.d.ts +1 -0
- package/dist/component/billing/queries.d.ts.map +1 -1
- package/dist/component/billing/queries.js +10 -4
- package/dist/component/billing/queries.js.map +1 -1
- package/dist/component/billing/schema.d.ts +5 -0
- package/dist/component/billing/schema.d.ts.map +1 -1
- package/dist/component/billing/schema.js +13 -0
- package/dist/component/billing/schema.js.map +1 -1
- package/dist/component/billingHistory/queries.d.ts +97 -0
- package/dist/component/billingHistory/queries.d.ts.map +1 -0
- package/dist/component/billingHistory/queries.js +65 -0
- package/dist/component/billingHistory/queries.js.map +1 -0
- package/dist/component/billingHistory/scope.d.ts +23 -0
- package/dist/component/billingHistory/scope.d.ts.map +1 -0
- package/dist/component/billingHistory/scope.js +54 -0
- package/dist/component/billingHistory/scope.js.map +1 -0
- package/dist/component/core/queries.d.ts +1 -0
- package/dist/component/core/queries.d.ts.map +1 -1
- package/dist/component/core/queries.js +7 -4
- package/dist/component/core/queries.js.map +1 -1
- package/dist/component/earnings/triggers.d.ts +10 -0
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/refundHistory/queries.d.ts +1 -1
- package/dist/component/refundSync/mutations.d.ts +1 -1
- package/dist/component/refundSync/mutations.d.ts.map +1 -1
- package/dist/component/schema.d.ts +5 -0
- package/docs/billing-history.md +13 -0
- package/docs/personal-account-mapping.md +30 -0
- package/docs/refund-context.md +42 -9
- package/package.json +2 -1
- package/src/client/billing/historyPages.test.ts +58 -0
- package/src/client/billing/historyPages.ts +48 -0
- package/src/client/billing/subscriptions.ts +2 -1
- package/src/client/core/accounts.ts +2 -1
- package/src/client/index.ts +6 -2
- package/src/client/originalIdReadOptions.test.ts +63 -0
- package/src/client/originalIdReadOptions.ts +10 -0
- package/src/client/publicTypes.ts +12 -0
- package/src/client/readContracts.ts +16 -0
- package/src/client/webhooks/handler.ts +7 -3
- package/src/client/webhooks/processors.test.ts +9 -7
- package/src/client/webhooks/processors.ts +3 -88
- package/src/client/webhooks/refund-delivery.test.ts +512 -0
- package/src/client/webhooks/refundDelivery.ts +42 -0
- package/src/client/webhooks/refundRecovery.ts +52 -0
- package/src/client/webhooks.test.ts +35 -42
- package/src/component/_generated/api.ts +4 -0
- package/src/component/_generated/component.ts +130 -2
- package/src/component/billing/queries.ts +9 -4
- package/src/component/billing/schema.ts +13 -0
- package/src/component/billingHistory/guards.test.ts +235 -0
- package/src/component/billingHistory/options.test.ts +35 -0
- package/src/component/billingHistory/pages.test.ts +74 -0
- package/src/component/billingHistory/queries.ts +88 -0
- package/src/component/billingHistory/scope.ts +77 -0
- package/src/component/core/original-id-unique.test.ts +209 -0
- package/src/component/core/queries.ts +6 -4
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Component billing history pages
|
|
2
|
+
|
|
3
|
+
`paginateSubscriptions` and `paginateCheckoutSessions` read the existing synchronized component tables. Each requires an original `userId` selected by a trusted host and accepts an optional exact `accountId`, typed `status`, and Convex `paginationOpts`. Selectors must be nonempty, trimmed original strings without control characters; they are rejected rather than normalized. There is no new lifetime or legacy-ID length cap. The account predicate is conjunctive with the buyer predicate. A user-only page includes valid legacy rows without an account ID; adding an account predicate intentionally excludes them.
|
|
4
|
+
|
|
5
|
+
Use independent cursors for the two readers. Page sizes are 1–100; they bound one page, never lifetime history. Optional caller read ceilings must be positive safe integers; stricter ceilings are preserved within the package policy of 200 rows/1 MB per invocation. Cursors bind the reader kind, buyer, optional account and status. Forward returned continuation and split cursors unchanged. Preserve `endCursor`, `pageStatus` and split obligations when a reactive pinned range grows. Cursor encoding is context binding, not authentication or a signed capability. Authorize every request and continued page before calling the package.
|
|
6
|
+
|
|
7
|
+
These are cached observations, not an atomic provider history certificate. Exhaustion means the selected component range was exhausted at that query, not that every provider event arrived. No reads synchronize or mutate provider resources. A completed Checkout session, an invoice, a trial and a paid one-time order are different facts; hosts must use their original request/fulfillment bindings and qualified payment evidence before making purchase or access decisions.
|
|
8
|
+
|
|
9
|
+
The SDK returns server-side component documents, including fields inappropriate for browsers. A host must whitelist its response: never forward Checkout `clientSecret`, `url` or arbitrary metadata. Do not infer buyer ownership from a caller-supplied account ID or remap historical buyers to a current account. Community, session and enabled-actor authorization remain app-owned. Missing or conflicting provenance is unavailable, not an empty successful financial history.
|
|
10
|
+
|
|
11
|
+
The matching Vite reference is `example/convex/billing/history/queries.ts`. Unlike the old synthetic-persona demo routes, this opt-in adapter requires a genuine Convex authenticated identity mapped uniquely through the existing `authTokenIdentifier` index, then an existing buyer/customer role. The ordinary demo does not configure authentication or mint that mapping; it therefore fails closed. A production host must supply its real account restriction and domain authorization checks rather than treating the example's demo role as a complete security model. The adapter takes no browser buyer/account selectors and whitelists safe observations.
|
|
12
|
+
|
|
13
|
+
Existing array readers retain their behavior. `listCheckoutSessionsByUser` remains a first-50 preview; it is not the pagination API. `getCheckoutSessionPageFromStripe` remains separate live provider discovery. Consumers can expose one authorized entrypoint returning both pages with independent cursors; these methods do not require a shared stream or a new ledger. In Dojo, DOJO-962 owns that authorized composition and DOJO-2238 owns the caller/UI migration; no UI or entitlement activation ships in this package slice.
|
|
@@ -52,3 +52,33 @@ available balance or permission to create a refund. Original invoice allocation,
|
|
|
52
52
|
buyer, currency, charge, refund history and creation-time revalidation remain
|
|
53
53
|
separate requirements. Closed-account history uses the dedicated historical
|
|
54
54
|
provenance APIs; this reader never revives a closed account.
|
|
55
|
+
|
|
56
|
+
## Exact original provider-ID reads
|
|
57
|
+
|
|
58
|
+
For an immutable historical purchase link, use
|
|
59
|
+
`stripe.getAccountByStripeId(ctx, { stripeAccountId, requireUnique: true })` and
|
|
60
|
+
`stripe.getSubscriptionByStripeId(ctx, { stripeSubscriptionId, requireUnique: true })`.
|
|
61
|
+
The exported `AccountByStripeIdOptions` and `SubscriptionByStripeIdOptions` types
|
|
62
|
+
include this optional flag. Each exact provider-ID index examines at most two
|
|
63
|
+
matches and returns the unchanged document only when exactly one exists. Zero
|
|
64
|
+
matches and multiple matches both return `null`; neither result authorizes a
|
|
65
|
+
fallback to another account or subscription. Component errors still propagate.
|
|
66
|
+
|
|
67
|
+
Ambiguity is global to the provider ID, before any caller ownership, organization,
|
|
68
|
+
status or closure qualification. A canceled subscription or a closed original
|
|
69
|
+
account remains readable when its provider ID is unique, even when the buyer has
|
|
70
|
+
a different current account. This does not revive the account or establish its
|
|
71
|
+
current provider usability. No provider reads or writes occur. Omitting
|
|
72
|
+
`requireUnique`, or passing `false`, preserves the existing first-match behavior.
|
|
73
|
+
Component-ID getters and array readers are unchanged.
|
|
74
|
+
|
|
75
|
+
Authenticate the host viewer and derive both original IDs from its immutable
|
|
76
|
+
purchase record before these reads. Then compare the returned original buyer,
|
|
77
|
+
account, tenant and purchase bindings under the host's current authorization
|
|
78
|
+
policy before projecting private fields. Uniqueness alone proves none of those
|
|
79
|
+
bindings, provider freshness, paid access or permission to cancel or refund.
|
|
80
|
+
The server-only Vite reference
|
|
81
|
+
[`requireOriginalSubscription`](../example/convex/billing/history/originalSubscription.ts)
|
|
82
|
+
authenticates the actual example buyer and compares both returned records to
|
|
83
|
+
that buyer and the supplied trusted original association. It is not a public
|
|
84
|
+
browser-ID endpoint or a complete historical purchase authorization policy.
|
package/docs/refund-context.md
CHANGED
|
@@ -129,11 +129,11 @@ history is not cardinality bounded: native resource limits can abort the whole
|
|
|
129
129
|
accepting transaction, preserving the last committed projection. There is no
|
|
130
130
|
partial sum, silent truncation or all-backlog-capacity guarantee.
|
|
131
131
|
|
|
132
|
-
This primitive does
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
132
|
+
This standalone primitive does not run application callbacks or transfer recovery.
|
|
133
|
+
The maintained signed route uses the qualified callback seam below. Direct legacy
|
|
134
|
+
`upsertRefund`/raw-dispatcher calls remain outside generation fencing; hosts must
|
|
135
|
+
not reapply notification snapshots after qualified acceptance. No convergence
|
|
136
|
+
claim covers independent legacy writers.
|
|
137
137
|
The server-only Vite reference is
|
|
138
138
|
[`example/convex/connect/refundSync.ts`](../example/convex/connect/refundSync.ts).
|
|
139
139
|
|
|
@@ -160,7 +160,40 @@ reconciliation; the package does not silently retry a raw upsert as fallback.
|
|
|
160
160
|
|
|
161
161
|
The direct-component path returns the same accepted observation and rejects
|
|
162
162
|
superseded results. It has no application callback because no host handler was
|
|
163
|
-
registered.
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
163
|
+
registered. A successful or unchanged mirror is not proof that a prior provider
|
|
164
|
+
reversal or financial recovery completed.
|
|
165
|
+
|
|
166
|
+
### Signed refund delivery and recovery
|
|
167
|
+
|
|
168
|
+
The existing single `registerRoutes` endpoint verifies the signature before any
|
|
169
|
+
provider access. For `refund.created`, `refund.updated` and `refund.failed`, only
|
|
170
|
+
the signed refund ID and `event.account` select the original refund/API realm.
|
|
171
|
+
The package retrieves current provider state, qualifies it and accepts its durable
|
|
172
|
+
generation through the transaction above. It never substitutes notification
|
|
173
|
+
status, metadata or `event.created` for current state. A legitimate current
|
|
174
|
+
bank-return transition remains valid after a previous succeeded observation.
|
|
175
|
+
|
|
176
|
+
Required synchronization failures return non-2xx and retain failed/retryable event
|
|
177
|
+
ledger state. This applies independently of optional application-hook retry policy.
|
|
178
|
+
An in-flight duplicate returns retryable failure; a processed duplicate does not
|
|
179
|
+
read or notify again. Existing stale-processing recovery reopens an abandoned
|
|
180
|
+
attempt. Superseded observations cannot invoke changed callbacks or be acknowledged
|
|
181
|
+
as reconciled merely because a later generation started. Retry does not prove that
|
|
182
|
+
a later provider observation or economic operation succeeded.
|
|
183
|
+
|
|
184
|
+
After acceptance, current succeeded state can select the existing platform split
|
|
185
|
+
recovery operation. An unchanged mirror still checks that operation: an earlier
|
|
186
|
+
reversal failure or lost response is handled by its existing claim, original
|
|
187
|
+
idempotency key and transfer-receipt reconciliation. The synchronization layer
|
|
188
|
+
adds no reversal calculation or new financial retry permission. A connected refund
|
|
189
|
+
with no platform split obligation can synchronize; a connected refund associated
|
|
190
|
+
with platform recovery legs is held before any unscoped platform provider operation.
|
|
191
|
+
Its qualified mirror may already be committed, but the delivery remains retryable
|
|
192
|
+
and must not advertise complete economic recovery.
|
|
193
|
+
|
|
194
|
+
Refund `onCreate`/`onUpdate` callbacks receive qualified current stored rows and run
|
|
195
|
+
only for changed acceptance. Generic `onEvent`/`events` hooks keep their existing
|
|
196
|
+
verified `Stripe.Event` notification payload; that payload is not authoritative
|
|
197
|
+
current refund state or financial-completion evidence. Async hooks keep their
|
|
198
|
+
existing committed-document/scheduling contract. No live-provider atomicity or
|
|
199
|
+
all-history/native-capacity guarantee is introduced.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.1",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -65,6 +65,7 @@
|
|
|
65
65
|
"CHANGELOG.md",
|
|
66
66
|
"MIGRATION.md",
|
|
67
67
|
"docs/read-contracts.md",
|
|
68
|
+
"docs/billing-history.md",
|
|
68
69
|
"docs/invoice-payment-pages.md",
|
|
69
70
|
"docs/checkout-session-pages.md",
|
|
70
71
|
"docs/refund-context.md",
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { expect, it, vi } from "vitest";
|
|
2
|
+
import { components } from "../setup.test.js";
|
|
3
|
+
import { ReadContractClient } from "../readContracts.js";
|
|
4
|
+
|
|
5
|
+
it("exposes both independent bounded billing history readers on the public client", () => {
|
|
6
|
+
expect(ReadContractClient.prototype).toHaveProperty(
|
|
7
|
+
"paginateSubscriptions",
|
|
8
|
+
expect.any(Function),
|
|
9
|
+
);
|
|
10
|
+
expect(ReadContractClient.prototype).toHaveProperty(
|
|
11
|
+
"paginateCheckoutSessions",
|
|
12
|
+
expect.any(Function),
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("forwards the original buyer/account and independent cursors without provider operations", async () => {
|
|
17
|
+
const client = new ReadContractClient(components.betterStripe);
|
|
18
|
+
const result = { page: [], isDone: true, continueCursor: "original_cursor" };
|
|
19
|
+
const runQuery = vi.fn().mockResolvedValue(result);
|
|
20
|
+
const ctx = { runQuery };
|
|
21
|
+
const subscriptions = {
|
|
22
|
+
userId: "original_buyer",
|
|
23
|
+
accountId: "acct_original",
|
|
24
|
+
status: "trialing" as const,
|
|
25
|
+
paginationOpts: { cursor: "subscription_cursor", numItems: 17 },
|
|
26
|
+
};
|
|
27
|
+
const sessions = {
|
|
28
|
+
userId: "original_buyer",
|
|
29
|
+
status: "complete" as const,
|
|
30
|
+
paginationOpts: { cursor: "checkout_cursor", numItems: 19 },
|
|
31
|
+
};
|
|
32
|
+
expect(await client.paginateSubscriptions(ctx, subscriptions)).toBe(result);
|
|
33
|
+
expect(await client.paginateCheckoutSessions(ctx, sessions)).toBe(result);
|
|
34
|
+
expect(runQuery).toHaveBeenNthCalledWith(
|
|
35
|
+
1,
|
|
36
|
+
components.betterStripe.billingHistory.queries.paginateSubscriptions,
|
|
37
|
+
subscriptions,
|
|
38
|
+
);
|
|
39
|
+
expect(runQuery).toHaveBeenNthCalledWith(
|
|
40
|
+
2,
|
|
41
|
+
components.betterStripe.billingHistory.queries.paginateCheckoutSessions,
|
|
42
|
+
sessions,
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("propagates component read errors without returning an empty success page", async () => {
|
|
47
|
+
const client = new ReadContractClient(components.betterStripe);
|
|
48
|
+
const runQuery = vi.fn().mockRejectedValue(new Error("read failed"));
|
|
49
|
+
await expect(
|
|
50
|
+
client.paginateSubscriptions(
|
|
51
|
+
{ runQuery },
|
|
52
|
+
{
|
|
53
|
+
userId: "original",
|
|
54
|
+
paginationOpts: { cursor: null, numItems: 10 },
|
|
55
|
+
},
|
|
56
|
+
),
|
|
57
|
+
).rejects.toThrow("read failed");
|
|
58
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { PaginationOptions, PaginationResult } from "convex/server";
|
|
2
|
+
import type {
|
|
3
|
+
CheckoutSessionStatus,
|
|
4
|
+
SubscriptionStatus,
|
|
5
|
+
} from "../../component/billing/validators.js";
|
|
6
|
+
import type { Component, RunCtx } from "../helpers.js";
|
|
7
|
+
import type { Doc } from "../../component/_generated/dataModel.js";
|
|
8
|
+
import { componentRef } from "../webhooks/helpers.js";
|
|
9
|
+
|
|
10
|
+
/** A trusted host supplies the authorized original buyer; the cursor is not authorization. */
|
|
11
|
+
export type SubscriptionHistoryPageOptions = {
|
|
12
|
+
userId: string;
|
|
13
|
+
accountId?: string;
|
|
14
|
+
status?: SubscriptionStatus;
|
|
15
|
+
paginationOpts: PaginationOptions;
|
|
16
|
+
};
|
|
17
|
+
export type CheckoutSessionHistoryPageOptions = {
|
|
18
|
+
userId: string;
|
|
19
|
+
accountId?: string;
|
|
20
|
+
status?: CheckoutSessionStatus;
|
|
21
|
+
paginationOpts: PaginationOptions;
|
|
22
|
+
};
|
|
23
|
+
export type SubscriptionHistoryPage = PaginationResult<Doc<"subscriptions">>;
|
|
24
|
+
export type CheckoutSessionHistoryPage = PaginationResult<
|
|
25
|
+
Doc<"checkoutSessions">
|
|
26
|
+
>;
|
|
27
|
+
|
|
28
|
+
export function paginateSubscriptions(
|
|
29
|
+
component: Component,
|
|
30
|
+
ctx: RunCtx,
|
|
31
|
+
opts: SubscriptionHistoryPageOptions,
|
|
32
|
+
): Promise<SubscriptionHistoryPage> {
|
|
33
|
+
return ctx.runQuery(
|
|
34
|
+
componentRef(component, "billingHistory/queries/paginateSubscriptions"),
|
|
35
|
+
opts,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function paginateCheckoutSessions(
|
|
40
|
+
component: Component,
|
|
41
|
+
ctx: RunCtx,
|
|
42
|
+
opts: CheckoutSessionHistoryPageOptions,
|
|
43
|
+
): Promise<CheckoutSessionHistoryPage> {
|
|
44
|
+
return ctx.runQuery(
|
|
45
|
+
componentRef(component, "billingHistory/queries/paginateCheckoutSessions"),
|
|
46
|
+
opts,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SubscriptionByStripeIdOptions } from "../originalIdReadOptions.js";
|
|
1
2
|
import { subscriptionRouting } from "./subscriptionRouting.js";
|
|
2
3
|
import { cancelsAtPeriodEnd } from "./subscriptionCancellation.js";
|
|
3
4
|
import { resolveOwnerAccount } from "../utils/owner.js";
|
|
@@ -240,7 +241,7 @@ export async function getSubscription(
|
|
|
240
241
|
export async function getSubscriptionByStripeId(
|
|
241
242
|
component: Component,
|
|
242
243
|
ctx: RunCtx,
|
|
243
|
-
opts:
|
|
244
|
+
opts: SubscriptionByStripeIdOptions,
|
|
244
245
|
): Promise<StripeComponentSubscription | null> {
|
|
245
246
|
return (await ctx.runQuery(
|
|
246
247
|
componentRef(component, "billing/queries/getSubscriptionByStripeId"),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AccountByStripeIdOptions } from "../originalIdReadOptions.js";
|
|
1
2
|
import { addCustomerConfiguration } from "./accountConfigurations.js";
|
|
2
3
|
import { idempotencyOptions } from "./idempotency.js";
|
|
3
4
|
export type CreateAccountOptions = {
|
|
@@ -299,7 +300,7 @@ export async function getAccountByOrgId(
|
|
|
299
300
|
export async function getAccountByStripeId(
|
|
300
301
|
component: Component,
|
|
301
302
|
ctx: RunCtx,
|
|
302
|
-
opts:
|
|
303
|
+
opts: AccountByStripeIdOptions,
|
|
303
304
|
): Promise<StripeComponentAccount | null> {
|
|
304
305
|
return (await ctx.runQuery(
|
|
305
306
|
componentRef(component, "core/queries/getAccountByStripeId"),
|
package/src/client/index.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AccountByStripeIdOptions,
|
|
3
|
+
SubscriptionByStripeIdOptions,
|
|
4
|
+
} from "./originalIdReadOptions.js";
|
|
1
5
|
import { refundReconciliationResult } from "./webhooks/refundReconciliationValidators.js";
|
|
2
6
|
import type { RefundReconciliationResult } from "./webhooks/refundReconciliationValidators.js";
|
|
3
7
|
import { reconcileRefundAndTrigger } from "./webhooks/refundReconciliation.js";
|
|
@@ -403,7 +407,7 @@ export class BetterStripe extends PaymentSourceClient {
|
|
|
403
407
|
|
|
404
408
|
async getAccountByStripeId(
|
|
405
409
|
ctx: RunCtx,
|
|
406
|
-
opts:
|
|
410
|
+
opts: AccountByStripeIdOptions,
|
|
407
411
|
): Promise<StripeComponentAccount | null> {
|
|
408
412
|
return accountsImpl.getAccountByStripeId(this.component, ctx, opts);
|
|
409
413
|
}
|
|
@@ -694,7 +698,7 @@ export class BetterStripe extends PaymentSourceClient {
|
|
|
694
698
|
|
|
695
699
|
async getSubscriptionByStripeId(
|
|
696
700
|
ctx: RunCtx,
|
|
697
|
-
opts:
|
|
701
|
+
opts: SubscriptionByStripeIdOptions,
|
|
698
702
|
): Promise<StripeComponentSubscription | null> {
|
|
699
703
|
return subscriptionsImpl.getSubscriptionByStripeId(
|
|
700
704
|
this.component,
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { expect, it, vi } from "vitest";
|
|
2
|
+
import { BetterStripe } from "./index.js";
|
|
3
|
+
import { components } from "./setup.test.js";
|
|
4
|
+
import type {
|
|
5
|
+
AccountByStripeIdOptions,
|
|
6
|
+
SubscriptionByStripeIdOptions,
|
|
7
|
+
} from "./publicTypes.js";
|
|
8
|
+
|
|
9
|
+
it.each([undefined, false, true])(
|
|
10
|
+
"forwards requireUnique=%s unchanged through both public SDK methods",
|
|
11
|
+
async (requireUnique) => {
|
|
12
|
+
const client = new BetterStripe(components.betterStripe);
|
|
13
|
+
const row = { observed: true };
|
|
14
|
+
const runQuery = vi.fn().mockResolvedValue(row);
|
|
15
|
+
const account: AccountByStripeIdOptions = {
|
|
16
|
+
stripeAccountId: "acct_original",
|
|
17
|
+
...(requireUnique === undefined ? {} : { requireUnique }),
|
|
18
|
+
};
|
|
19
|
+
const subscription: SubscriptionByStripeIdOptions = {
|
|
20
|
+
stripeSubscriptionId: "sub_original",
|
|
21
|
+
...(requireUnique === undefined ? {} : { requireUnique }),
|
|
22
|
+
};
|
|
23
|
+
expect(await client.getAccountByStripeId({ runQuery }, account)).toBe(row);
|
|
24
|
+
expect(
|
|
25
|
+
await client.getSubscriptionByStripeId({ runQuery }, subscription),
|
|
26
|
+
).toBe(row);
|
|
27
|
+
expect(runQuery).toHaveBeenNthCalledWith(
|
|
28
|
+
1,
|
|
29
|
+
components.betterStripe.core.queries.getAccountByStripeId,
|
|
30
|
+
account,
|
|
31
|
+
);
|
|
32
|
+
expect(runQuery).toHaveBeenNthCalledWith(
|
|
33
|
+
2,
|
|
34
|
+
components.betterStripe.billing.queries.getSubscriptionByStripeId,
|
|
35
|
+
subscription,
|
|
36
|
+
);
|
|
37
|
+
},
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
it("propagates unique-read failures without inventing missing records", async () => {
|
|
41
|
+
const client = new BetterStripe(components.betterStripe);
|
|
42
|
+
const runQuery = vi
|
|
43
|
+
.fn()
|
|
44
|
+
.mockRejectedValue(new Error("component unavailable"));
|
|
45
|
+
await expect(
|
|
46
|
+
client.getAccountByStripeId(
|
|
47
|
+
{ runQuery },
|
|
48
|
+
{
|
|
49
|
+
stripeAccountId: "acct_original",
|
|
50
|
+
requireUnique: true,
|
|
51
|
+
},
|
|
52
|
+
),
|
|
53
|
+
).rejects.toThrow("component unavailable");
|
|
54
|
+
await expect(
|
|
55
|
+
client.getSubscriptionByStripeId(
|
|
56
|
+
{ runQuery },
|
|
57
|
+
{
|
|
58
|
+
stripeSubscriptionId: "sub_original",
|
|
59
|
+
requireUnique: true,
|
|
60
|
+
},
|
|
61
|
+
),
|
|
62
|
+
).rejects.toThrow("component unavailable");
|
|
63
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Trusted-host exact-ID lookup; uniqueness is not ownership or provider usability. */
|
|
2
|
+
export type AccountByStripeIdOptions = {
|
|
3
|
+
stripeAccountId: string;
|
|
4
|
+
requireUnique?: boolean;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export type SubscriptionByStripeIdOptions = {
|
|
8
|
+
stripeSubscriptionId: string;
|
|
9
|
+
requireUnique?: boolean;
|
|
10
|
+
};
|
|
@@ -91,3 +91,15 @@ export type {
|
|
|
91
91
|
PrepareBalanceFundingOptions,
|
|
92
92
|
SetBalanceFundingOptions,
|
|
93
93
|
} from "./billing/balanceFunding.js";
|
|
94
|
+
|
|
95
|
+
export type {
|
|
96
|
+
SubscriptionHistoryPageOptions,
|
|
97
|
+
CheckoutSessionHistoryPageOptions,
|
|
98
|
+
SubscriptionHistoryPage,
|
|
99
|
+
CheckoutSessionHistoryPage,
|
|
100
|
+
} from "./billing/historyPages.js";
|
|
101
|
+
|
|
102
|
+
export type {
|
|
103
|
+
AccountByStripeIdOptions,
|
|
104
|
+
SubscriptionByStripeIdOptions,
|
|
105
|
+
} from "./originalIdReadOptions.js";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as historyPages from "./billing/historyPages.js";
|
|
1
2
|
import { OperationEvidenceClient } from "./operationEvidence.js";
|
|
2
3
|
import {
|
|
3
4
|
normalizeRefundCommandBindings,
|
|
@@ -24,6 +25,21 @@ import { componentRef } from "./webhooks/helpers.js";
|
|
|
24
25
|
/** Shared component readers inherited by BetterStripe. */
|
|
25
26
|
export class ReadContractClient {
|
|
26
27
|
constructor(public component: Component) {}
|
|
28
|
+
/** Cached buyer observations only; the host authorizes exact selectors on every page. */
|
|
29
|
+
paginateSubscriptions(
|
|
30
|
+
ctx: RunCtx,
|
|
31
|
+
opts: historyPages.SubscriptionHistoryPageOptions,
|
|
32
|
+
) {
|
|
33
|
+
return historyPages.paginateSubscriptions(this.component, ctx, opts);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
paginateCheckoutSessions(
|
|
37
|
+
ctx: RunCtx,
|
|
38
|
+
opts: historyPages.CheckoutSessionHistoryPageOptions,
|
|
39
|
+
) {
|
|
40
|
+
return historyPages.paginateCheckoutSessions(this.component, ctx, opts);
|
|
41
|
+
}
|
|
42
|
+
|
|
27
43
|
get operationEvidence() {
|
|
28
44
|
return new OperationEvidenceClient(this.component);
|
|
29
45
|
}
|
|
@@ -186,6 +186,10 @@ export async function handleWebhookRequest(
|
|
|
186
186
|
console.error("[better-stripe] retryOnHookError selector failed:", error);
|
|
187
187
|
return jsonResponse({ error: "Webhook retry policy failed" }, 500);
|
|
188
188
|
}
|
|
189
|
+
// Refund synchronization is required independently of optional app hook policy.
|
|
190
|
+
const requiresLedgerSuccess =
|
|
191
|
+
requiresHookSuccess ||
|
|
192
|
+
["refund.created", "refund.updated", "refund.failed"].includes(event.type);
|
|
189
193
|
// --- Atomic webhook dedup via event ledger ---
|
|
190
194
|
const eventId = event.id;
|
|
191
195
|
console.info(
|
|
@@ -202,7 +206,7 @@ export async function handleWebhookRequest(
|
|
|
202
206
|
},
|
|
203
207
|
);
|
|
204
208
|
if (dedupStatus !== "inserted") {
|
|
205
|
-
if (
|
|
209
|
+
if (requiresLedgerSuccess && dedupStatus === "processing") {
|
|
206
210
|
return jsonResponse({ error: "Event processing in progress" }, 503);
|
|
207
211
|
}
|
|
208
212
|
console.info(`[better-stripe] ↳ deduplicated (already processed)`);
|
|
@@ -214,7 +218,7 @@ export async function handleWebhookRequest(
|
|
|
214
218
|
`[better-stripe] Webhook ledger insert failed for ${eventId}:`,
|
|
215
219
|
error,
|
|
216
220
|
);
|
|
217
|
-
if (
|
|
221
|
+
if (requiresLedgerSuccess)
|
|
218
222
|
return jsonResponse({ error: "Webhook ledger unavailable" }, 500);
|
|
219
223
|
}
|
|
220
224
|
|
|
@@ -270,7 +274,7 @@ export async function handleWebhookRequest(
|
|
|
270
274
|
},
|
|
271
275
|
);
|
|
272
276
|
} catch {
|
|
273
|
-
if (
|
|
277
|
+
if (requiresLedgerSuccess)
|
|
274
278
|
return jsonResponse({ error: "Webhook completion unavailable" }, 500);
|
|
275
279
|
/* ledger update best-effort */
|
|
276
280
|
}
|
|
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
5
5
|
import { computeReversalSlices } from "../../component/lib/reversals.js";
|
|
6
6
|
import type { WebhookContext } from "./helpers.js";
|
|
7
7
|
import { processEvent } from "./processors.js";
|
|
8
|
+
import { processRefund } from "../../../tests/fixtures/refund-recovery.js";
|
|
8
9
|
|
|
9
10
|
const TO_REF = Symbol.for("toReferencePath");
|
|
10
11
|
|
|
@@ -98,6 +99,7 @@ function makeStripe() {
|
|
|
98
99
|
return {
|
|
99
100
|
payouts: { retrieve: vi.fn() },
|
|
100
101
|
refunds: {
|
|
102
|
+
retrieve: vi.fn(),
|
|
101
103
|
list: vi.fn(() =>
|
|
102
104
|
(async function* () {
|
|
103
105
|
yield { amount: 5000, status: "succeeded" };
|
|
@@ -2382,7 +2384,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2382
2384
|
amount_refunded: 5000,
|
|
2383
2385
|
});
|
|
2384
2386
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2385
|
-
await
|
|
2387
|
+
await processRefund(whCtx, refundEvent());
|
|
2386
2388
|
expect(stripe.transfers.createReversal).toHaveBeenCalledTimes(2);
|
|
2387
2389
|
expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
|
|
2388
2390
|
"tr_s",
|
|
@@ -2409,7 +2411,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2409
2411
|
amount_refunded: 10000,
|
|
2410
2412
|
});
|
|
2411
2413
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2412
|
-
await
|
|
2414
|
+
await processRefund(whCtx, refundEvent({ amount: 10000 }));
|
|
2413
2415
|
expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
|
|
2414
2416
|
"tr_s",
|
|
2415
2417
|
{ amount: 7000 },
|
|
@@ -2437,7 +2439,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2437
2439
|
amount_refunded: 7000, // cumulative: 5000 + this refund's 2000
|
|
2438
2440
|
});
|
|
2439
2441
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2440
|
-
await
|
|
2442
|
+
await processRefund(whCtx, refundEvent({ id: "re_2", amount: 2000 }));
|
|
2441
2443
|
expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
|
|
2442
2444
|
"tr_s",
|
|
2443
2445
|
{ amount: 1400 },
|
|
@@ -2460,14 +2462,14 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2460
2462
|
amount_refunded: 5000,
|
|
2461
2463
|
});
|
|
2462
2464
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2463
|
-
await
|
|
2465
|
+
await processRefund(whCtx, refundEvent());
|
|
2464
2466
|
expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
|
|
2465
2467
|
});
|
|
2466
2468
|
it("skips clawback quietly for a refund on a non-split sale", async () => {
|
|
2467
2469
|
const ctx = makeCtx({ query: [] });
|
|
2468
2470
|
const stripe = makeStripe();
|
|
2469
2471
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2470
|
-
await
|
|
2472
|
+
await processRefund(whCtx, refundEvent());
|
|
2471
2473
|
expect(stripe.charges.retrieve).not.toHaveBeenCalled();
|
|
2472
2474
|
expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
|
|
2473
2475
|
});
|
|
@@ -2475,7 +2477,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2475
2477
|
const ctx = makeCtx({ query: ledgerLegs() });
|
|
2476
2478
|
const stripe = makeStripe();
|
|
2477
2479
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2478
|
-
await
|
|
2480
|
+
await processRefund(whCtx, refundEvent({ status: "pending" }));
|
|
2479
2481
|
expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
|
|
2480
2482
|
});
|
|
2481
2483
|
it("propagates a reversal failure so the event is marked failed and Stripe retries", async () => {
|
|
@@ -2488,7 +2490,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
|
|
|
2488
2490
|
});
|
|
2489
2491
|
stripe.transfers.createReversal.mockRejectedValue(new Error("stripe down"));
|
|
2490
2492
|
const whCtx = makeWhCtx({ ctx, stripe });
|
|
2491
|
-
await expect(
|
|
2493
|
+
await expect(processRefund(whCtx, refundEvent())).rejects.toThrow(
|
|
2492
2494
|
"stripe down",
|
|
2493
2495
|
);
|
|
2494
2496
|
});
|
|
@@ -1,15 +1,12 @@
|
|
|
1
|
+
import { handleRefundEvent } from "./refundDelivery.js";
|
|
1
2
|
import { handlePayoutEvent } from "./payoutReconciliation.js";
|
|
2
3
|
import { reconcileDisputeMoney } from "./disputeRecovery.js";
|
|
3
|
-
import { successfulRefundPrincipal } from "../connect/refundPrincipal.js";
|
|
4
4
|
import { subscriptionRouting } from "../billing/subscriptionRouting.js";
|
|
5
5
|
import { cancelsAtPeriodEnd } from "../billing/subscriptionCancellation.js";
|
|
6
6
|
import type Stripe from "stripe";
|
|
7
7
|
|
|
8
8
|
import type { SplitRecipient } from "../../component/lib/fees.js";
|
|
9
|
-
import {
|
|
10
|
-
createSplitTransfers,
|
|
11
|
-
reverseTransfersForRefund,
|
|
12
|
-
} from "../connect/transfers.js";
|
|
9
|
+
import { createSplitTransfers } from "../connect/transfers.js";
|
|
13
10
|
import { validateStatementDescriptorSuffix } from "../core/descriptors.js";
|
|
14
11
|
import { computeFee } from "../core/fees.js";
|
|
15
12
|
import type { PlatformFeeConfig } from "../types.js";
|
|
@@ -110,7 +107,7 @@ export async function processEvent(
|
|
|
110
107
|
case "refund.created":
|
|
111
108
|
case "refund.updated":
|
|
112
109
|
case "refund.failed":
|
|
113
|
-
await handleRefundEvent(whCtx, obj as Stripe.Refund);
|
|
110
|
+
await handleRefundEvent(whCtx, obj as Stripe.Refund, event.account);
|
|
114
111
|
break;
|
|
115
112
|
case "application_fee.refunded":
|
|
116
113
|
// Keep feeCollectedAmount/feeRefundedAmount accurate on the linked
|
|
@@ -902,88 +899,6 @@ async function upsertPaymentFromStripe(
|
|
|
902
899
|
}
|
|
903
900
|
|
|
904
901
|
// Stripe types Refund.status as `string | null`; clamp to the documented union.
|
|
905
|
-
const REFUND_STATUSES = new Set([
|
|
906
|
-
"pending",
|
|
907
|
-
"requires_action",
|
|
908
|
-
"succeeded",
|
|
909
|
-
"failed",
|
|
910
|
-
"canceled",
|
|
911
|
-
]);
|
|
912
|
-
const REFUND_REASONS = new Set([
|
|
913
|
-
"duplicate",
|
|
914
|
-
"fraudulent",
|
|
915
|
-
"requested_by_customer",
|
|
916
|
-
"expired_uncaptured_charge",
|
|
917
|
-
]);
|
|
918
|
-
|
|
919
|
-
async function handleRefundEvent(
|
|
920
|
-
whCtx: WebhookContext,
|
|
921
|
-
refund: Stripe.Refund,
|
|
922
|
-
): Promise<void> {
|
|
923
|
-
const paymentIntentId =
|
|
924
|
-
typeof refund.payment_intent === "string"
|
|
925
|
-
? refund.payment_intent
|
|
926
|
-
: (refund.payment_intent?.id ?? undefined);
|
|
927
|
-
const chargeId =
|
|
928
|
-
typeof refund.charge === "string"
|
|
929
|
-
? refund.charge
|
|
930
|
-
: (refund.charge?.id ?? undefined);
|
|
931
|
-
|
|
932
|
-
const status =
|
|
933
|
-
refund.status && REFUND_STATUSES.has(refund.status)
|
|
934
|
-
? refund.status
|
|
935
|
-
: "pending";
|
|
936
|
-
const reason =
|
|
937
|
-
refund.reason && REFUND_REASONS.has(refund.reason)
|
|
938
|
-
? refund.reason
|
|
939
|
-
: undefined;
|
|
940
|
-
|
|
941
|
-
await dispatchUpsert(whCtx, "refundUpserted", {
|
|
942
|
-
stripeRefundId: refund.id,
|
|
943
|
-
stripePaymentIntentId: paymentIntentId,
|
|
944
|
-
stripeChargeId: chargeId,
|
|
945
|
-
amount: refund.amount,
|
|
946
|
-
currency: refund.currency,
|
|
947
|
-
status,
|
|
948
|
-
reason,
|
|
949
|
-
failureReason: refund.failure_reason ?? undefined,
|
|
950
|
-
metadata: refund.metadata ?? undefined,
|
|
951
|
-
});
|
|
952
|
-
|
|
953
|
-
// Split-sale clawback (BTS-34): when a separate-charges sale is refunded,
|
|
954
|
-
// pull the refunded share back from each recipient pro-rata. Only ledger
|
|
955
|
-
// legs identify a split sale — destination-charge auto-transfers are not in
|
|
956
|
-
// the ledger and are handled by Stripe-native `reverse_transfer` at refund
|
|
957
|
-
// creation. Runs on `refund.updated` too so a pending→succeeded refund
|
|
958
|
-
// (e.g. ACH) still claws back. Errors propagate → event `failed` → Stripe
|
|
959
|
-
// retries; `reverseTransfersForRefund`'s delta-to-target math makes the
|
|
960
|
-
// re-run converge without double-reversing.
|
|
961
|
-
if (status !== "succeeded" || !chargeId) return;
|
|
962
|
-
const legs = ((await whCtx.ctx.runQuery(
|
|
963
|
-
componentRef(whCtx.component, "connect/queries/listTransfersByCharge"),
|
|
964
|
-
{ sourceChargeId: chargeId },
|
|
965
|
-
)) ?? []) as unknown[];
|
|
966
|
-
if (legs.length === 0) {
|
|
967
|
-
const obligations = (await whCtx.ctx.runQuery(
|
|
968
|
-
componentRef(
|
|
969
|
-
whCtx.component,
|
|
970
|
-
"affiliateRecovery/queries/chargeObligations",
|
|
971
|
-
),
|
|
972
|
-
{ sourceChargeId: chargeId },
|
|
973
|
-
)) as unknown[] | null;
|
|
974
|
-
if (!obligations?.length) return;
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
// Fetch succeeded refunds: charge.amount_refunded can include pending funds.
|
|
978
|
-
const charge = await whCtx.stripe.charges.retrieve(chargeId);
|
|
979
|
-
await reverseTransfersForRefund(whCtx.stripe, whCtx.component, whCtx.ctx, {
|
|
980
|
-
sourceChargeId: chargeId,
|
|
981
|
-
refundId: refund.id,
|
|
982
|
-
chargeAmount: charge.amount,
|
|
983
|
-
amountRefunded: await successfulRefundPrincipal(whCtx.stripe, chargeId),
|
|
984
|
-
});
|
|
985
|
-
}
|
|
986
|
-
|
|
987
902
|
/**
|
|
988
903
|
* Denormalize fee-refund state from `application_fee.refunded` (BTS-34, folded
|
|
989
904
|
* in from BTS-51): set the linked payment's `feeRefundedAmount` and correct
|