@fantastic.dev/better-stripe 0.68.0 → 0.69.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.
@@ -0,0 +1,251 @@
1
+ # Native metering protocol diagnostics
2
+
3
+ The optional admin diagnostics at
4
+ `/demo/metered-usage?diagnostics=protocol` exercise isolated native Stripe resources.
5
+ They are separate from the [product and customer walkthrough](usage-example.md).
6
+ Each diagnostic run provisions a dedicated Accounts v2 customer, test clock,
7
+ product, meter, price and managed subscription. Its original fixture and financial
8
+ history remain retained. These are developer protocol exercises, not seller
9
+ product configuration.
10
+ Start with [sandbox setup](metering-setup.md). Use your existing Stripe sandbox;
11
+ no Metronome account or token is needed. Run the example backend and frontend
12
+ from the `example` directory with `pnpm dev`. Keep test keys in the backend
13
+ Convex environment. Do not copy secret values into commands, screenshots, source
14
+ files or browser storage.
15
+
16
+ ## Demo security model
17
+
18
+ This repository's persona switcher is a test-only convenience, not authentication.
19
+ Choose Admin, then Metered billing → Developer protocol diagnostics. Each operation rechecks
20
+ the server's persona binding and test key. If an authenticated identity is present,
21
+ it must match the persona's stored token identifier. Visitor and affiliate
22
+ personas cannot operate the workflow. Do not expose these demo endpoints as a
23
+ production billing service.
24
+
25
+ In your app, replace the persona lookup with real authentication and server-owned
26
+ customer, product, entitlement and recipient authorization. Never trust a browser
27
+ account ID, product ID, price, rate or settlement policy. See
28
+ [authorization and recovery](usage-security.md).
29
+
30
+ Admin and seller personas can configure the unit, precision, currency, exact price,
31
+ version and model-specific terms before setup. Customers run the server-owned
32
+ defaults. Setup retries retain the original native identities and configuration.
33
+ A saved meter and subscription keep their original terms. Archive a resolved run
34
+ before configuring its replacement.
35
+
36
+ ## Pay as you go
37
+
38
+ 1. Select Pay as you go, then Set up sandbox.
39
+ 2. Run five units three times. The default price is USD 1 per call.
40
+ 3. Replay last work. Its source identity, quantity and occurrence time stay fixed;
41
+ the synthetic application work and usage acceptance happen once.
42
+ 4. Observe native usage. If delivery is queued, use Resume queued deliveries.
43
+ Stripe aggregation is asynchronous. Refresh until the aggregate is 15.
44
+ 5. Close or resume original billing period. This fences new work, checks complete
45
+ local/native equality, drains reservations and checks every correction and
46
+ purchase intent. It advances only this run's test clock.
47
+ 6. Resume after the clock is ready. The server finds the unique original cycle
48
+ invoice, verifies its meter lines, finalizes it and pays with Stripe's sandbox
49
+ card. The default invoice is USD 15.
50
+
51
+ The outcome separately shows invoice payment, original cash verification, actual
52
+ processing fees and any verified recipient transfers. A paid invoice alone does
53
+ not imply that settlement is ready.
54
+
55
+ ## Included monthly usage and overages
56
+
57
+ Select Included monthly usage. The defaults include ten calls per original
58
+ monthly period, then USD 1 per additional call. Run three five-unit jobs. The
59
+ package allowance view shows 15 consumed, ten included, five billable overage
60
+ units and the soft-limit warning at 12. The native invoice is USD 5.
61
+
62
+ Closing the period observes the next native subscription period. When that period
63
+ is active on the Convex server, its separate allowance starts at zero consumed
64
+ and ten remaining included units. The old period and history stay unchanged. A
65
+ test clock can move ahead of real time; future renewal allowance is explicitly
66
+ unavailable. Its view stays read-only until the period is active on the server and
67
+ new event times are inside the provider's real acceptance window. This demo does not forge
68
+ future work timestamps to simulate another month's consumption.
69
+
70
+ ## Paid prepaid credits
71
+
72
+ 1. Select Prepaid credits and set up its dedicated sandbox resources.
73
+ 2. Run five units before funding. Work is held and does not execute.
74
+ 3. Create credit purchase. The default original purchase is ten units for USD 10.
75
+ Pending payment grants no usable credit.
76
+ 4. Confirm sandbox card. The backend uses Stripe's test card and the package
77
+ verifies the original captured PaymentIntent, customer and paid credit grant.
78
+ 5. Run two five-unit jobs. Replay a successful job before creating another one to
79
+ demonstrate idempotency. Another five-unit job is denied after exhaustion.
80
+ 6. Observe native usage, then close and resume the period. The native credit grant
81
+ covers the consumption invoice. The demo refuses to pay any positive prepaid
82
+ invoice remainder with a second cash payment.
83
+
84
+ The USD 10 purchase is the only cash source. Credit consumption collects no new
85
+ cash. The package reconciles native credit transactions against complete invoice
86
+ history. Unavailable observations are shown explicitly, never as a zero balance.
87
+
88
+ For production, send the package purchase result's `clientSecret` only to the
89
+ properly authenticated purchaser's Stripe payment UI. Do not store or log it.
90
+ Confirming a payment in the UI is not proof of usable credits; call
91
+ `observeCreditPurchase` and wait for the verified ready grant. See
92
+ [paid credit accounting](usage-credits.md).
93
+
94
+ Prepaid is limited to the issuer's own services. A seller persona cannot redeem
95
+ credits into reseller proceeds. An authorized affiliate can be paid once from the
96
+ original purchase; usage does not produce another affiliate sale.
97
+
98
+ ## Corrections and retained failures
99
+
100
+ Before closing, Correct last accepted event cancels its original native event
101
+ through the package. Repeated correction requests keep the same correction ID.
102
+ Wait for confirmation and native reaggregation. A new application job can then
103
+ use the released capacity. For example, record 15 units, cancel the last five,
104
+ then record a different five-unit job. Effective usage is 15, and history retains
105
+ 20 originally accepted units plus the five canceled units.
106
+
107
+ Unknown delivery outcomes stay held. Resume queued deliveries schedules only
108
+ records that the package still classifies as queued; it never resends unknown
109
+ attempts. Do not replace the source event ID, change the occurrence time, create
110
+ a new run to relabel the same work or invent a provider event identifier. Resolve
111
+ the original attempt with verified native evidence using the operational runbook.
112
+ A billing or cleanup guard failure preserves all work, purchase and correction
113
+ intents for reconciliation.
114
+
115
+ The fixture timestamps _new synthetic jobs_ at its retained test clock's original
116
+ period start. This keeps native meter events and paid grants on the same logical
117
+ clock. Retrying a job never changes that timestamp. Real applications must use
118
+ the actual occurrence time of their business event. Delivery checks both real
119
+ provider limits and an attached sandbox clock before a native event write.
120
+
121
+ ## Ownership and routing
122
+
123
+ Customer and admin runs use direct issuer billing. Seller runs pin their original
124
+ server-owned seller account and, when available, an existing demo affiliate at
125
+ setup. The demo policy is a 10% inclusive platform fee and a 20% affiliate share
126
+ of the eligible remainder, with recurring commission eligibility. The package
127
+ uses actual processing fees and verifies native payment provenance, recipient
128
+ capabilities and transfer identity. Unsupported Connect configurations remain
129
+ held. Accounts v2 payer configuration is separate from merchant or recipient
130
+ configuration; a customer account is not automatically eligible to receive money.
131
+ Prepaid settlement retains issuer revenue and accepts only eligible affiliate
132
+ policy, never seller or collaborator redemption.
133
+
134
+ ## Scoped cleanup and reset
135
+
136
+ Cleanup re-reads the original paid invoice, payment and settlement before stopping
137
+ resources. Saved success alone cannot authorize a reset after a refund, dispute or
138
+ incomplete settlement recovery. Unavailable fresh evidence keeps the run retained.
139
+
140
+ Use Archive or resume scoped cleanup after the original invoice and cash evidence
141
+ are verified. It refuses unresolved delivery, corrections, reservations, purchases,
142
+ credit backing or settlement. Unspent paid credits require verified refund or
143
+ expiry; cleanup cannot wipe them.
144
+
145
+ Cleanup requests period-end cancellation, advances only the owned test clock to
146
+ the cancellation boundary, checks the final native cycle invoice and retires the
147
+ managed enrollment. It deactivates only the owned price, meter and product. It
148
+ retains the native payer, clock, invoice/payment evidence and every component
149
+ history record. It does not clear any Convex table or another developer's data.
150
+ After successful archival, Start new sandbox run creates new isolated resources.
151
+ Admin or seller can save a new version before starting that replacement.
152
+
153
+ Empty or unresolved runs can require operator reconciliation rather than automatic
154
+ archive. In particular, unknown provider outcomes must remain visible and retained.
155
+ Never delete a clock or payer to make financial evidence disappear.
156
+
157
+ ## Model configuration snippets
158
+
159
+ Use the same versioned unit and exact minor-currency rate in each model:
160
+
161
+ ```ts
162
+ import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
163
+ const terms = {
164
+ key: "api-calls",
165
+ version: "v1",
166
+ unit: { name: "call", precision: 0 },
167
+ rate: { currency: "usd", unitAmountDecimal: "100" },
168
+ } as const;
169
+ ```
170
+
171
+ Pay as you go bills every effective unit:
172
+
173
+ ```ts
174
+ const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
175
+ ```
176
+
177
+ Included monthly usage grants ten units before overages in each original period:
178
+
179
+ ```ts
180
+ const included = defineUsagePlan({
181
+ ...terms,
182
+ model: "included_overage",
183
+ includedQuantity: "10",
184
+ reset: "billing_period",
185
+ });
186
+ ```
187
+
188
+ Prepaid consumption requires verified paid grants and rejects insufficient credit:
189
+
190
+ ```ts
191
+ const prepaid = defineUsagePlan({
192
+ ...terms,
193
+ model: "prepaid",
194
+ insufficientBalance: "reject",
195
+ });
196
+ // After server authorization and native binding setup:
197
+ const purchase = await stripe.usage.purchaseCredits(
198
+ ctx,
199
+ {
200
+ ...originalCreditBinding,
201
+ purchaseId: originalBusinessPurchaseId,
202
+ quantity: "10",
203
+ ownership: "issuer",
204
+ rollover: "retain_original_terms",
205
+ },
206
+ { stripeSecretKey },
207
+ );
208
+ // Return clientSecret only to the authorized purchaser's payment UI.
209
+ // Observe the original purchase after payment; wait for its ready grant.
210
+ ```
211
+
212
+ Use `ensureUsageMeter`, `ensureUsagePrice` and `usage.ensureSubscription` to bind
213
+ the chosen plan to the server-authorized native payer. The exact implementations
214
+ are in the example's `meteredUsage/setup.ts` and `meteredUsage/funding.ts`.
215
+
216
+ ## Package calls behind the example
217
+
218
+ Server code imports neutral types from `@fantastic.dev/better-stripe/usage`; UI
219
+ code uses `@fantastic.dev/better-stripe/react`. The example backend lives under
220
+ `example/convex/meteredUsage`. Its atomic synthetic-work mutation follows this
221
+ pattern, using server-authorized original terms:
222
+
223
+ ```ts
224
+ const reservation =
225
+ model === "prepaid"
226
+ ? await stripe.usage.reserveCredits(ctx, { event, subscription })
227
+ : await stripe.usage.reserveAllowance(ctx, { event, subscription });
228
+ // Handle denied/released reservations before doing any application work.
229
+ const receipt = await stripe.usage.record(ctx, {
230
+ event,
231
+ subscription,
232
+ reservationId: reservation.reservationId,
233
+ });
234
+ // Persist synthetic DB work and receipt in this same mutation transaction.
235
+ ```
236
+
237
+ Schedule delivery from an action after the transaction commits:
238
+
239
+ ```ts
240
+ await stripe.usage.startDelivery(ctx, {
241
+ scope: original.scope,
242
+ eventId: receipt.eventId,
243
+ provider: internal.meteredUsage.delivery.deliver,
244
+ });
245
+ ```
246
+
247
+ For external application work, use a durable idempotent work protocol with the
248
+ original business identity. A database transaction cannot make an external side
249
+ effect atomic. See [ledger](usage-ledger.md), [delivery](usage-delivery.md),
250
+ [limits](usage-limits.md), [corrections](usage-corrections.md) and
251
+ [settlement](usage-settlement.md) for the complete contracts.
@@ -72,6 +72,37 @@ network-failure recordings.
72
72
  | Prepaid refunds, disputes, won reinstatement, consumed backing, affiliate recovery and no second sale on redemption | `src/client/usage/creditSettlementRecovery.test.ts`, `src/component/usageCredits/accounting.test.ts`, `src/client/usage/creditRevenue.test.ts` |
73
73
  | Saved success cannot bypass later cash uncertainty or unresolved settlement during cleanup | `example/convex/meteredUsage/revenue.test.ts`, `example/convex/meteredUsage/cleanupRefresh.test.ts` |
74
74
 
75
+ ## Product integration acceptance
76
+
77
+ The [October 19 product-flow evidence](evidence/native-metering/product-flows-2026-10-19.json)
78
+ comes from the product example, separately from the isolated protocol fixtures above:
79
+
80
+ - Maya's original USD 20 membership: 75 delivered minutes, 60 included and 15
81
+ overage; native draft total USD 35, including the base fee.
82
+ - Additional coaching minutes: five delivered pay-as-you-go minutes and a native
83
+ draft total of USD 5.
84
+ - Platform report credits: original USD 10 payment and paid grant verified,
85
+ ten reports consumed, zero credits remaining. Replaying the same request
86
+ returns the same receipt; an eleventh report is denied without work. The native
87
+ draft rates USD 10 of usage, covered by credits, with total and paid both zero.
88
+
89
+ These are test-mode observations, not finalized renewal or seller-settlement
90
+ proof. Exact native meter summaries reject partial-minute subscription boundaries.
91
+ The draft invoices remain estimates. Mixed fixed-fee and usage settlement stays
92
+ held. The earlier unsupported automatic-collection prepaid test enrollment was
93
+ retained and its renewal canceled; corrected enrollments use `send_invoice`.
94
+
95
+ The product regression suite covers store enablement, ownership, immutable
96
+ product/enrollment identities, bounded catalog pages, initial/current base-payment
97
+ proof, atomic allowance and work, strict credit purchase arguments, retry identity,
98
+ cancellation freshness and both React integration views:
99
+
100
+ ```sh
101
+ pnpm exec vitest run example/convex/meteredProducts example/src/components/metered-products.test.tsx example/convex/storefront/storefront.actions.test.ts
102
+ ```
103
+
104
+ Follow [the product walkthrough](usage-example.md) to reproduce through the UI.
105
+
75
106
  ## Comparison and hold rules
76
107
 
77
108
  Compare explicit original scope, meter, price/version, subscription item and
package/docs/webhooks.md CHANGED
@@ -7,9 +7,9 @@
7
7
  Register the webhook endpoint on your Convex HTTP router:
8
8
 
9
9
  ```typescript
10
- import { registerRoutes } from "@fantastic.dev/better-stripe";
10
+ import { stripe } from "./stripe"; // Your configured BetterStripe instance.
11
11
 
12
- registerRoutes(http, components.betterStripe, {
12
+ stripe.registerRoutes(http, {
13
13
  webhookPath: "/stripe/webhook", // Default path
14
14
  stripeSecretKey: process.env.STRIPE_SECRET_KEY,
15
15
  webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
@@ -47,7 +47,15 @@ const v2 = await stripe.setupEventDestination(ctx, {
47
47
  });
48
48
  ```
49
49
 
50
- The method is idempotent — it finds an existing destination matching the URL and payload type, updates its events, or creates a new one.
50
+ The method finds an existing destination matching URL and payload type and
51
+ updates its events, or creates a new one. It rejects incompatible existing
52
+ snapshot versions and customer-preview event scopes instead of silently
53
+ migrating them. Preserve the original destination and signing secret until its
54
+ explicit replacement is configured. See [preview webhook migration](accounts-v2-preview.md).
55
+
56
+ The instance method `stripe.registerRoutes` inherits the configured SDK key and
57
+ API version. Standalone `registerRoutes(http, components.betterStripe, config)`
58
+ remains available; supply the same `stripeApiVersion` explicitly for a preview client.
51
59
 
52
60
  #### Admin UI setup
53
61
 
@@ -57,12 +65,19 @@ The example app includes an `/admin/setup` page that handles webhook creation, e
57
65
 
58
66
  ```typescript
59
67
  import {
60
- BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot events (20 events)
61
- BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin events (12 events)
62
- ALL_BETTER_STRIPE_EVENTS, // Combined (32 events)
68
+ BETTER_STRIPE_WEBHOOK_EVENTS, // Default V1 snapshot event names
69
+ BETTER_STRIPE_V2_WEBHOOK_EVENTS, // Default Connect V2 thin event names
70
+ ALL_BETTER_STRIPE_EVENTS, // Combined defaults, not every optional event handler
63
71
  } from "@fantastic.dev/better-stripe";
64
72
  ```
65
73
 
74
+ Customer-only preview clients select `BETTER_STRIPE_CUSTOMER_ACCOUNT_EVENTS`
75
+ for their default thin destination instead of the Connect list. Metered billing
76
+ also handles `v1.billing.meter.error_report_triggered` and
77
+ `v1.billing.meter.no_meter_found` as signed thin events. Those names are not in
78
+ `ALL_BETTER_STRIPE_EVENTS`; configure them explicitly as described in
79
+ [asynchronous metering errors](usage-delivery.md#receive-asynchronous-native-validation-errors).
80
+
66
81
  ### Event Processing
67
82
 
68
83
  Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
@@ -70,11 +85,34 @@ Records synced from Stripe objects without `userId` metadata are stored unattrib
70
85
  The webhook handler processes events through these steps:
71
86
 
72
87
  1. Verify Stripe signature
73
- 2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processing`, `processed`, or `ignored`, return 200 immediately. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
88
+ 2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processed`, `ignored`, or still within its processing lease, return 200 immediately. A stale processing lease can be retried. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
74
89
  3. Upsert the component-owned domain table. When `webhooks` is configured, the upsert runs through `syncWebhook` — an internal mutation that performs the upsert **and** the sync trigger in the same transaction.
75
90
  4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
76
91
  5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
77
92
 
93
+ ### Required V1 hook delivery
94
+
95
+ By default, `onEvent` and `events[type]` callbacks are best-effort.
96
+ For selected verified V1 events, `retryOnHookError(event)` can require them to
97
+ succeed before acknowledgment:
98
+
99
+ ```ts
100
+ retryOnHookError: (event) => event.type === "checkout.session.completed",
101
+ ```
102
+
103
+ For that selection, component processing commits first; the callbacks run before
104
+ the event is marked processed. Callback failures return 500 and permit redelivery.
105
+ A concurrent in-flight delivery returns 503, and a failed reservation/completion
106
+ also returns 500. An abandoned processing lease becomes retryable after ten
107
+ minutes. Sync triggers and callbacks must remain idempotent by `event.id` or a
108
+ durable business key because they can run again after partial success.
109
+
110
+ Unselected callbacks, V2 hooks and scheduled `asyncWebhook` hooks keep best-effort
111
+ acknowledgment behavior. Required fulfillment belongs in the selected V1
112
+ `onEvent`/`events` path, not a scheduled hook. Refund synchronization independently
113
+ requires ledger success even without an application retry selector. See
114
+ [the migration contract](../MIGRATION.md#remove-dojos-consumer-patch).
115
+
78
116
  ### Ledger-Based Deduplication
79
117
 
80
118
  The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.68.0",
4
- "description": "A Convex component for Stripe V2 Accounts API integration.",
3
+ "version": "0.69.0",
4
+ "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
7
7
  "convex",
8
- "component"
8
+ "component",
9
+ "billing",
10
+ "subscriptions",
11
+ "metered-billing",
12
+ "usage-based-billing",
13
+ "stripe-connect",
14
+ "react"
9
15
  ],
10
16
  "homepage": "https://github.com/FantasticDevHQ/better-stripe#readme",
11
17
  "bugs": {
@@ -61,63 +67,11 @@
61
67
  "files": [
62
68
  "dist",
63
69
  "src",
64
- "docs/react-workflows.md",
65
- "docs/settlement.md",
66
- "docs/affiliate-clawbacks.md",
67
- "docs/accounts-v2-preview.md",
68
- "docs/react-workflows-audit.md",
69
- "CHANGELOG.md",
70
- "MIGRATION.md",
71
- "docs/read-contracts.md",
72
- "docs/billing-history.md",
73
- "docs/subscription-payment-methods.md",
74
- "docs/invoice-payment-pages.md",
75
- "docs/checkout-session-pages.md",
76
- "docs/refund-context.md",
77
- "docs/refund-command-evidence.md",
78
- "docs/personal-account-mapping.md",
79
- "docs/financial-ownership.md",
80
- "docs/financial-observations.md",
81
- "docs/architecture/component-extraction.md",
82
- "docs/architecture/durable-execution.md",
83
- "docs/architecture/recovery-workflow.md",
84
- "docs/balance-funding-state.md",
85
- "docs/balance-funding-workflow.md",
86
- "docs/processing-cost-reconciliation.md",
87
- "docs/example-balance-funding-cutover.md",
88
- "docs/example-recovery-cutover.md",
89
- "docs/releasing.md",
90
- "docs/release-handoff.md",
91
- "docs/setup-intent-recovery.md",
92
- "docs/metered-usage.md",
93
- "docs/metering-setup.md",
94
- "docs/README.md",
95
- "docs/overview.md",
96
- "docs/client-api.md",
97
- "docs/webhooks.md",
98
- "docs/marketplace.md",
99
- "docs/react-api.md",
100
- "docs/testing.md",
101
- "docs/configuration.md",
102
- "docs/architecture.md",
103
- "docs/development.md",
104
- "docs/usage-ledger.md",
105
- "docs/usage-catalog.md",
106
- "docs/usage-delivery.md",
107
- "docs/usage-observations.md",
108
- "docs/usage-subscriptions.md",
109
- "docs/usage-credits.md",
110
- "docs/usage-limits.md",
111
- "docs/usage-corrections.md",
112
- "docs/usage-settlement.md",
113
- "docs/usage-security.md",
114
- "docs/usage-react.md",
70
+ "docs/*.md",
71
+ "docs/architecture/*.md",
115
72
  "docs/evidence/native-metering",
116
- "docs/usage-configuration.md",
117
- "docs/usage-example.md",
118
- "docs/payout-revision-migration.md",
119
- "docs/usage-verification.md",
120
- "docs/usage-rollout.md"
73
+ "CHANGELOG.md",
74
+ "MIGRATION.md"
121
75
  ],
122
76
  "scripts": {
123
77
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -153,7 +107,8 @@
153
107
  "check:ci-parity": "repo-gates check-ci-parity",
154
108
  "check:coverage": "node scripts/check-coverage.mjs",
155
109
  "format:check": "pnpm run format",
156
- "check:agents": "repo-gates check-agents"
110
+ "check:agents": "repo-gates check-agents",
111
+ "check:package": "pnpm run build:clean && vitest run scripts/documentation-contracts.test.mjs scripts/packed-docs.test.mjs scripts/public-docs.test.mjs scripts/usage-contracts-packed.test.mjs scripts/usage-composition-packed.test.mjs scripts/usage-models-packed.test.mjs"
157
112
  },
158
113
  "dependencies": {
159
114
  "@convex-dev/workflow": "0.4.10",
@@ -29,3 +29,16 @@ it("creates redirect Checkout with flexible mixed items and no metered quantitie
29
29
  managedCheckoutParams(subscriptionTerms(request), "intent"),
30
30
  ).toThrow();
31
31
  });
32
+ it("keeps the native metered checkout in its immutable configured currency", () => {
33
+ const terms = subscriptionTerms({
34
+ ...request,
35
+ collection: {
36
+ method: "checkout",
37
+ successUrl: "https://example.test/success",
38
+ cancelUrl: "https://example.test/cancel",
39
+ },
40
+ });
41
+ expect(managedCheckoutParams(terms, "intent").adaptive_pricing).toEqual({
42
+ enabled: false,
43
+ });
44
+ });
@@ -28,6 +28,8 @@ export function managedCheckoutParams(
28
28
  );
29
29
  return {
30
30
  mode: "subscription",
31
+ // Rates, paid credits and invoice verification retain this currency.
32
+ adaptive_pricing: { enabled: false },
31
33
  customer_account: terms.meters[0].scope.customerAccount,
32
34
  success_url: terms.collection.successUrl,
33
35
  cancel_url: terms.collection.cancelUrl,
@@ -371,3 +371,18 @@ it("labels a complete empty local period without inferring zero from partial his
371
371
  rerender(<ui.UsageSummary scope={usageScope} {...data} />);
372
372
  expect(screen.getByText("No usage in this period.")).toBeTruthy();
373
373
  });
374
+ it("explains partial-minute native summaries as unsupported instead of promising refresh will resolve them", () => {
375
+ render(
376
+ <ui.UsageSummary
377
+ scope={usageScope}
378
+ summary={usageSnapshot().summary}
379
+ provider={{
380
+ status: "unsupported",
381
+ reason: "minute_alignment_required",
382
+ retryable: false,
383
+ }}
384
+ />,
385
+ );
386
+ expect(screen.getByText(/partial-minute billing boundaries/)).toBeTruthy();
387
+ expect(screen.queryByText(/Refresh after provider ingestion/)).toBeNull();
388
+ });
@@ -179,8 +179,11 @@ export function UsageSummary(props: UsageSummaryProps) {
179
179
  )}
180
180
  {!provider || provider.status !== "available" ? (
181
181
  <p role="status">
182
- Native aggregation {provider?.status ?? "unavailable"}. Refresh after
183
- provider ingestion.
182
+ Native aggregation {provider?.status ?? "unavailable"}.{" "}
183
+ {provider?.status === "unsupported" &&
184
+ provider.reason === "minute_alignment_required"
185
+ ? "Exact summaries do not support partial-minute billing boundaries. Reconcile with the native invoice instead."
186
+ : "Refresh after provider ingestion."}
184
187
  </p>
185
188
  ) : (
186
189
  <>