@fantastic.dev/better-stripe 0.68.1 → 0.70.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 +12 -0
- package/README.md +1 -1
- package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
- package/dist/client/usage/subscriptionCheckout.js +2 -0
- package/dist/client/usage/subscriptionCheckout.js.map +1 -1
- package/dist/react/workflows/Products.d.ts +2 -2
- package/dist/react/workflows/Products.d.ts.map +1 -1
- package/dist/react/workflows/Products.js +8 -4
- package/dist/react/workflows/Products.js.map +1 -1
- package/dist/react/workflows/UsageSummary.d.ts.map +1 -1
- package/dist/react/workflows/UsageSummary.js +4 -1
- package/dist/react/workflows/UsageSummary.js.map +1 -1
- package/docs/evidence/native-metering/product-flows-2026-10-19.json +553 -0
- package/docs/metered-usage.md +1 -1
- package/docs/metering-setup.md +36 -26
- package/docs/react-workflows.md +35 -0
- package/docs/usage-example.md +159 -244
- package/docs/usage-protocol-diagnostics.md +251 -0
- package/docs/usage-verification.md +31 -0
- package/package.json +1 -1
- package/src/client/usage/subscriptionCheckout.test.ts +13 -0
- package/src/client/usage/subscriptionCheckout.ts +2 -0
- package/src/react/workflows/Products.test.tsx +194 -2
- package/src/react/workflows/Products.tsx +53 -43
- package/src/react/workflows/Usage.test.tsx +15 -0
- package/src/react/workflows/UsageSummary.tsx +5 -2
|
@@ -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/package.json
CHANGED
|
@@ -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,
|
|
@@ -1,8 +1,200 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
act,
|
|
4
|
+
cleanup,
|
|
5
|
+
fireEvent,
|
|
6
|
+
render,
|
|
7
|
+
renderHook,
|
|
8
|
+
screen,
|
|
9
|
+
} from "@testing-library/react";
|
|
3
10
|
import { afterEach, expect, it, vi } from "vitest";
|
|
4
|
-
import { useProductManager } from "./Products.js";
|
|
11
|
+
import { Products, useProductManager } from "./Products.js";
|
|
5
12
|
afterEach(cleanup);
|
|
13
|
+
it("supports editing and archiving without advertising creation capabilities", async () => {
|
|
14
|
+
const updateProduct = vi.fn().mockResolvedValue(null);
|
|
15
|
+
const deactivateProduct = vi.fn().mockResolvedValue(null);
|
|
16
|
+
render(
|
|
17
|
+
<Products
|
|
18
|
+
scopeKey="owner"
|
|
19
|
+
products={[
|
|
20
|
+
{
|
|
21
|
+
stripeProductId: "prod_original",
|
|
22
|
+
name: "Original plan",
|
|
23
|
+
active: true,
|
|
24
|
+
prices: [],
|
|
25
|
+
},
|
|
26
|
+
]}
|
|
27
|
+
updateProduct={updateProduct}
|
|
28
|
+
deactivateProduct={deactivateProduct}
|
|
29
|
+
/>,
|
|
30
|
+
);
|
|
31
|
+
expect(screen.queryByRole("button", { name: "Create product" })).toBeNull();
|
|
32
|
+
expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
|
|
33
|
+
fireEvent.click(screen.getByRole("button", { name: "Edit product" }));
|
|
34
|
+
fireEvent.change(screen.getByLabelText("Product name"), {
|
|
35
|
+
target: { value: "Updated plan" },
|
|
36
|
+
});
|
|
37
|
+
await act(async () => {
|
|
38
|
+
fireEvent.click(screen.getByRole("button", { name: "Save product" }));
|
|
39
|
+
});
|
|
40
|
+
expect(updateProduct).toHaveBeenCalledWith({
|
|
41
|
+
stripeProductId: "prod_original",
|
|
42
|
+
name: "Updated plan",
|
|
43
|
+
description: undefined,
|
|
44
|
+
});
|
|
45
|
+
await act(async () => {
|
|
46
|
+
fireEvent.click(screen.getByRole("button", { name: "Archive product" }));
|
|
47
|
+
});
|
|
48
|
+
expect(deactivateProduct).toHaveBeenCalledWith({
|
|
49
|
+
stripeProductId: "prod_original",
|
|
50
|
+
});
|
|
51
|
+
expect(updateProduct).toHaveBeenCalledTimes(1);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("reports unavailable creation without calling a different capability", async () => {
|
|
55
|
+
const updateProduct = vi.fn();
|
|
56
|
+
const { result } = renderHook(() =>
|
|
57
|
+
useProductManager({ scopeKey: "owner", updateProduct }),
|
|
58
|
+
);
|
|
59
|
+
act(() =>
|
|
60
|
+
result.current.setNewProduct({ name: "Original plan", description: "" }),
|
|
61
|
+
);
|
|
62
|
+
await act(async () => {
|
|
63
|
+
await result.current.handleCreateProduct();
|
|
64
|
+
});
|
|
65
|
+
expect(result.current.error).toBe("Product creation is not configured.");
|
|
66
|
+
expect(result.current.newProduct.name).toBe("Original plan");
|
|
67
|
+
expect(updateProduct).not.toHaveBeenCalled();
|
|
68
|
+
act(() =>
|
|
69
|
+
result.current.setNewPrice({
|
|
70
|
+
amount: "1500",
|
|
71
|
+
currency: "usd",
|
|
72
|
+
interval: "month",
|
|
73
|
+
}),
|
|
74
|
+
);
|
|
75
|
+
await act(async () => {
|
|
76
|
+
await result.current.handleAddPrice("prod_original");
|
|
77
|
+
});
|
|
78
|
+
expect(result.current.error).toBe("Price creation is not configured.");
|
|
79
|
+
expect(result.current.newPrice.amount).toBe("1500");
|
|
80
|
+
expect(updateProduct).not.toHaveBeenCalled();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("allows product creation without exposing price creation", async () => {
|
|
84
|
+
const createProduct = vi.fn().mockResolvedValue("prod_new");
|
|
85
|
+
render(
|
|
86
|
+
<Products
|
|
87
|
+
scopeKey="product-editor"
|
|
88
|
+
createProduct={createProduct}
|
|
89
|
+
products={[
|
|
90
|
+
{
|
|
91
|
+
stripeProductId: "prod_original",
|
|
92
|
+
name: "Original plan",
|
|
93
|
+
active: true,
|
|
94
|
+
prices: [],
|
|
95
|
+
},
|
|
96
|
+
]}
|
|
97
|
+
/>,
|
|
98
|
+
);
|
|
99
|
+
expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
|
|
100
|
+
fireEvent.change(screen.getByLabelText("Product name"), {
|
|
101
|
+
target: { value: " New plan " },
|
|
102
|
+
});
|
|
103
|
+
await act(async () => {
|
|
104
|
+
fireEvent.click(screen.getByRole("button", { name: "Create product" }));
|
|
105
|
+
});
|
|
106
|
+
expect(createProduct).toHaveBeenCalledWith({
|
|
107
|
+
name: "New plan",
|
|
108
|
+
description: undefined,
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("allows price creation without exposing product creation", async () => {
|
|
113
|
+
const createPrice = vi.fn().mockResolvedValue("price_new");
|
|
114
|
+
render(
|
|
115
|
+
<Products
|
|
116
|
+
scopeKey="price-editor"
|
|
117
|
+
createPrice={createPrice}
|
|
118
|
+
products={[
|
|
119
|
+
{
|
|
120
|
+
stripeProductId: "prod_original",
|
|
121
|
+
name: "Original plan",
|
|
122
|
+
active: true,
|
|
123
|
+
prices: [],
|
|
124
|
+
},
|
|
125
|
+
]}
|
|
126
|
+
/>,
|
|
127
|
+
);
|
|
128
|
+
expect(screen.queryByRole("button", { name: "Create product" })).toBeNull();
|
|
129
|
+
fireEvent.click(screen.getByRole("button", { name: "Add price" }));
|
|
130
|
+
fireEvent.change(screen.getByLabelText("Price in minor units"), {
|
|
131
|
+
target: { value: "1500" },
|
|
132
|
+
});
|
|
133
|
+
await act(async () => {
|
|
134
|
+
fireEvent.click(screen.getByRole("button", { name: "Create price" }));
|
|
135
|
+
});
|
|
136
|
+
expect(createPrice).toHaveBeenCalledWith({
|
|
137
|
+
stripeProductId: "prod_original",
|
|
138
|
+
unitAmount: 1500,
|
|
139
|
+
currency: "usd",
|
|
140
|
+
type: "recurring",
|
|
141
|
+
interval: "month",
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("hides an open price form when creation becomes unavailable", () => {
|
|
146
|
+
const products = [
|
|
147
|
+
{
|
|
148
|
+
stripeProductId: "prod_original",
|
|
149
|
+
name: "Original plan",
|
|
150
|
+
active: true,
|
|
151
|
+
prices: [],
|
|
152
|
+
},
|
|
153
|
+
];
|
|
154
|
+
const createPrice = vi.fn();
|
|
155
|
+
const { rerender } = render(
|
|
156
|
+
<Products scopeKey="owner" products={products} createPrice={createPrice} />,
|
|
157
|
+
);
|
|
158
|
+
fireEvent.click(screen.getByRole("button", { name: "Add price" }));
|
|
159
|
+
expect(screen.getByLabelText("Price in minor units")).toBeDefined();
|
|
160
|
+
rerender(<Products scopeKey="owner" products={products} />);
|
|
161
|
+
expect(screen.queryByLabelText("Price in minor units")).toBeNull();
|
|
162
|
+
expect(screen.queryByRole("button", { name: "Add price" })).toBeNull();
|
|
163
|
+
expect(createPrice).not.toHaveBeenCalled();
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("keeps the new scope's draft after an old creation finishes", async () => {
|
|
167
|
+
let finish!: () => void;
|
|
168
|
+
const createProduct = () =>
|
|
169
|
+
new Promise<void>((resolve) => {
|
|
170
|
+
finish = resolve;
|
|
171
|
+
});
|
|
172
|
+
const { result, rerender } = renderHook(
|
|
173
|
+
({ scopeKey }) => useProductManager({ scopeKey, createProduct }),
|
|
174
|
+
{ initialProps: { scopeKey: "original-owner" } },
|
|
175
|
+
);
|
|
176
|
+
act(() =>
|
|
177
|
+
result.current.setNewProduct({ name: "Original draft", description: "" }),
|
|
178
|
+
);
|
|
179
|
+
let pending!: Promise<void>;
|
|
180
|
+
act(() => {
|
|
181
|
+
pending = result.current.handleCreateProduct();
|
|
182
|
+
});
|
|
183
|
+
rerender({ scopeKey: "new-owner" });
|
|
184
|
+
act(() =>
|
|
185
|
+
result.current.setNewProduct({
|
|
186
|
+
name: "New owner's draft",
|
|
187
|
+
description: "",
|
|
188
|
+
}),
|
|
189
|
+
);
|
|
190
|
+
await act(async () => {
|
|
191
|
+
finish();
|
|
192
|
+
await pending;
|
|
193
|
+
});
|
|
194
|
+
expect(result.current.newProduct.name).toBe("New owner's draft");
|
|
195
|
+
expect(result.current.error).toBeNull();
|
|
196
|
+
});
|
|
197
|
+
|
|
6
198
|
it("validates product names and price minor units before mutation", async () => {
|
|
7
199
|
const createProduct = vi.fn().mockResolvedValue("prod_test");
|
|
8
200
|
const createPrice = vi.fn().mockResolvedValue("price_test");
|
|
@@ -12,8 +12,8 @@ export type PriceInput = {
|
|
|
12
12
|
};
|
|
13
13
|
export type ProductActions = {
|
|
14
14
|
scopeKey: string;
|
|
15
|
-
createProduct
|
|
16
|
-
createPrice
|
|
15
|
+
createProduct?: (args: ProductInput) => Promise<unknown>;
|
|
16
|
+
createPrice?: (args: PriceInput) => Promise<unknown>;
|
|
17
17
|
updateProduct?: (
|
|
18
18
|
args: ProductInput & { stripeProductId: string },
|
|
19
19
|
) => Promise<unknown>;
|
|
@@ -46,6 +46,8 @@ export function useProductManager(props: ProductActions) {
|
|
|
46
46
|
setCommand(command);
|
|
47
47
|
switch (command.type) {
|
|
48
48
|
case "create": {
|
|
49
|
+
if (!props.createProduct)
|
|
50
|
+
throw new Error("Product creation is not configured.");
|
|
49
51
|
if (!fields.newProduct.name.trim())
|
|
50
52
|
throw new Error("Enter a product name.");
|
|
51
53
|
await props.createProduct({
|
|
@@ -55,6 +57,8 @@ export function useProductManager(props: ProductActions) {
|
|
|
55
57
|
break;
|
|
56
58
|
}
|
|
57
59
|
case "price": {
|
|
60
|
+
if (!props.createPrice)
|
|
61
|
+
throw new Error("Price creation is not configured.");
|
|
58
62
|
const unitAmount = Number(fields.newPrice.amount);
|
|
59
63
|
if (
|
|
60
64
|
!/^\d+$/.test(fields.newPrice.amount) ||
|
|
@@ -186,39 +190,41 @@ function ProductsBody(props: ProductsProps) {
|
|
|
186
190
|
<section data-better-stripe="products" aria-busy={state.isPending}>
|
|
187
191
|
<h2>Products</h2>
|
|
188
192
|
{state.error && <p role="alert">{state.error}</p>}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
event
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
193
|
+
{props.createProduct && (
|
|
194
|
+
<form
|
|
195
|
+
onSubmit={(event) => {
|
|
196
|
+
event.preventDefault();
|
|
197
|
+
void state.handleCreateProduct();
|
|
198
|
+
}}
|
|
199
|
+
>
|
|
200
|
+
<label htmlFor={`${id}-name`}>Product name</label>
|
|
201
|
+
<input
|
|
202
|
+
id={`${id}-name`}
|
|
203
|
+
required
|
|
204
|
+
value={state.newProduct.name}
|
|
205
|
+
onChange={(event) =>
|
|
206
|
+
state.setNewProduct({
|
|
207
|
+
...state.newProduct,
|
|
208
|
+
name: event.target.value,
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
/>
|
|
212
|
+
<label htmlFor={`${id}-description`}>Description</label>
|
|
213
|
+
<input
|
|
214
|
+
id={`${id}-description`}
|
|
215
|
+
value={state.newProduct.description}
|
|
216
|
+
onChange={(event) =>
|
|
217
|
+
state.setNewProduct({
|
|
218
|
+
...state.newProduct,
|
|
219
|
+
description: event.target.value,
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
/>
|
|
223
|
+
<button type="submit" disabled={state.isPending}>
|
|
224
|
+
{state.isCreatingProduct ? "Creating…" : "Create product"}
|
|
225
|
+
</button>
|
|
226
|
+
</form>
|
|
227
|
+
)}
|
|
222
228
|
{result.isLoading ? (
|
|
223
229
|
<p role="status">Loading products…</p>
|
|
224
230
|
) : !result.products.length ? (
|
|
@@ -246,13 +252,17 @@ function ProductsBody(props: ProductsProps) {
|
|
|
246
252
|
)}
|
|
247
253
|
</div>
|
|
248
254
|
))}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
255
|
+
{props.createPrice && (
|
|
256
|
+
<button
|
|
257
|
+
type="button"
|
|
258
|
+
disabled={state.isPending}
|
|
259
|
+
onClick={() =>
|
|
260
|
+
state.setShowAddPriceFor(product.stripeProductId)
|
|
261
|
+
}
|
|
262
|
+
>
|
|
263
|
+
Add price
|
|
264
|
+
</button>
|
|
265
|
+
)}
|
|
256
266
|
{props.updateProduct && (
|
|
257
267
|
<button
|
|
258
268
|
type="button"
|
|
@@ -281,7 +291,7 @@ function ProductsBody(props: ProductsProps) {
|
|
|
281
291
|
</article>
|
|
282
292
|
))
|
|
283
293
|
)}
|
|
284
|
-
{state.showAddPriceFor && (
|
|
294
|
+
{props.createPrice && state.showAddPriceFor && (
|
|
285
295
|
<form
|
|
286
296
|
onSubmit={(event) => {
|
|
287
297
|
event.preventDefault();
|