@fantastic.dev/better-stripe 0.60.1 → 0.62.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/usage/index.d.ts +2 -0
  4. package/dist/client/usage/index.d.ts.map +1 -1
  5. package/dist/react/index.d.ts +17 -0
  6. package/dist/react/index.d.ts.map +1 -1
  7. package/dist/react/index.js +10 -0
  8. package/dist/react/index.js.map +1 -1
  9. package/dist/react/workflows/Pagination.d.ts +1 -0
  10. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  11. package/dist/react/workflows/Pagination.js +1 -0
  12. package/dist/react/workflows/Pagination.js.map +1 -1
  13. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  14. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  15. package/dist/react/workflows/Usage.fixtures.js +79 -0
  16. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  17. package/dist/react/workflows/Usage.types.d.ts +25 -0
  18. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  19. package/dist/react/workflows/Usage.types.js +11 -0
  20. package/dist/react/workflows/Usage.types.js.map +1 -0
  21. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  22. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  23. package/dist/react/workflows/UsageAllowance.js +21 -0
  24. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  25. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  26. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  27. package/dist/react/workflows/UsageBilling.js +40 -0
  28. package/dist/react/workflows/UsageBilling.js.map +1 -0
  29. package/dist/react/workflows/UsageConfiguration.d.ts +4 -0
  30. package/dist/react/workflows/UsageConfiguration.d.ts.map +1 -0
  31. package/dist/react/workflows/UsageConfiguration.js +19 -0
  32. package/dist/react/workflows/UsageConfiguration.js.map +1 -0
  33. package/dist/react/workflows/UsageConfiguration.types.d.ts +65 -0
  34. package/dist/react/workflows/UsageConfiguration.types.d.ts.map +1 -0
  35. package/dist/react/workflows/UsageConfiguration.types.js +2 -0
  36. package/dist/react/workflows/UsageConfiguration.types.js.map +1 -0
  37. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  38. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  39. package/dist/react/workflows/UsageCredits.js +25 -0
  40. package/dist/react/workflows/UsageCredits.js.map +1 -0
  41. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  42. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  43. package/dist/react/workflows/UsageHistory.js +74 -0
  44. package/dist/react/workflows/UsageHistory.js.map +1 -0
  45. package/dist/react/workflows/UsagePriceRow.d.ts +26 -0
  46. package/dist/react/workflows/UsagePriceRow.d.ts.map +1 -0
  47. package/dist/react/workflows/UsagePriceRow.js +40 -0
  48. package/dist/react/workflows/UsagePriceRow.js.map +1 -0
  49. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  50. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  51. package/dist/react/workflows/UsageSummary.js +54 -0
  52. package/dist/react/workflows/UsageSummary.js.map +1 -0
  53. package/dist/react/workflows/usage-configuration-validation.d.ts +4 -0
  54. package/dist/react/workflows/usage-configuration-validation.d.ts.map +1 -0
  55. package/dist/react/workflows/usage-configuration-validation.js +116 -0
  56. package/dist/react/workflows/usage-configuration-validation.js.map +1 -0
  57. package/dist/react/workflows/usage-format.d.ts +11 -0
  58. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  59. package/dist/react/workflows/usage-format.js +43 -0
  60. package/dist/react/workflows/usage-format.js.map +1 -0
  61. package/dist/react/workflows/usage-scope.d.ts +5 -0
  62. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  63. package/dist/react/workflows/usage-scope.js +26 -0
  64. package/dist/react/workflows/usage-scope.js.map +1 -0
  65. package/dist/react/workflows/useUsageConfiguration.d.ts +4 -0
  66. package/dist/react/workflows/useUsageConfiguration.d.ts.map +1 -0
  67. package/dist/react/workflows/useUsageConfiguration.js +84 -0
  68. package/dist/react/workflows/useUsageConfiguration.js.map +1 -0
  69. package/docs/README.md +4 -0
  70. package/docs/react-api.md +6 -0
  71. package/docs/usage-configuration.md +150 -0
  72. package/docs/usage-react.md +182 -0
  73. package/package.json +4 -2
  74. package/src/client/usage/index.ts +3 -0
  75. package/src/react/index.ts +36 -0
  76. package/src/react/workflows/Pagination.tsx +2 -0
  77. package/src/react/workflows/Usage.fixtures.ts +88 -0
  78. package/src/react/workflows/Usage.test.tsx +373 -0
  79. package/src/react/workflows/Usage.types.ts +39 -0
  80. package/src/react/workflows/UsageAllowance.tsx +114 -0
  81. package/src/react/workflows/UsageBilling.tsx +90 -0
  82. package/src/react/workflows/UsageConfiguration.test.tsx +393 -0
  83. package/src/react/workflows/UsageConfiguration.tsx +135 -0
  84. package/src/react/workflows/UsageConfiguration.types.ts +67 -0
  85. package/src/react/workflows/UsageCredits.tsx +112 -0
  86. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  87. package/src/react/workflows/UsageHistory.tsx +154 -0
  88. package/src/react/workflows/UsagePriceRow.test.tsx +140 -0
  89. package/src/react/workflows/UsagePriceRow.tsx +109 -0
  90. package/src/react/workflows/UsageSummary.tsx +204 -0
  91. package/src/react/workflows/usage-configuration-validation.test.ts +107 -0
  92. package/src/react/workflows/usage-configuration-validation.ts +152 -0
  93. package/src/react/workflows/usage-format.ts +48 -0
  94. package/src/react/workflows/usage-scope.ts +42 -0
  95. package/src/react/workflows/useUsageConfiguration.ts +99 -0
@@ -0,0 +1,393 @@
1
+ // @vitest-environment jsdom
2
+ import {
3
+ act,
4
+ cleanup,
5
+ fireEvent,
6
+ render,
7
+ screen,
8
+ waitFor,
9
+ } from "@testing-library/react";
10
+ import { afterEach, expect, it, vi } from "vitest";
11
+ import * as ui from "../index.js";
12
+ afterEach(cleanup);
13
+ const scope = {
14
+ identityKey: "admin-a",
15
+ accountKey: "issuer-a",
16
+ productKey: "calls",
17
+ role: "admin" as const,
18
+ ownershipLabel: "Issuer A",
19
+ canConfigure: true,
20
+ capability: "issuer_native" as const,
21
+ };
22
+ const initial = {
23
+ plan: {
24
+ key: "calls",
25
+ version: "v2",
26
+ model: "pay_as_you_go" as const,
27
+ unit: { name: "call", precision: 0 },
28
+ rate: { currency: "usd", unitAmountDecimal: "2" },
29
+ },
30
+ eventName: "calls_v2",
31
+ displayName: "API calls",
32
+ };
33
+ function field(name: string, value: string) {
34
+ fireEvent.change(screen.getByLabelText(name), { target: { value } });
35
+ }
36
+ function save() {
37
+ fireEvent.submit(screen.getByRole("form", { name: "Usage configuration" }));
38
+ }
39
+ it("saves exact supported native terms, creates a version and never submits host ownership", async () => {
40
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
41
+ const onSave = vi.fn().mockResolvedValue(undefined);
42
+ render(
43
+ <ui.UsageConfiguration
44
+ scope={scope}
45
+ initial={initial}
46
+ meters={[]}
47
+ onSave={onSave}
48
+ />,
49
+ );
50
+ expect(
51
+ screen.getByText(/Existing subscriptions keep their original prices/),
52
+ ).toBeTruthy();
53
+ field("Price per whole unit (USD)", "0.00125");
54
+ field("Quantity precision", "2");
55
+ save();
56
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
57
+ expect(onSave.mock.calls[0][0]).toEqual({
58
+ ...initial,
59
+ plan: {
60
+ ...initial.plan,
61
+ unit: { name: "call", precision: 2 },
62
+ rate: { currency: "usd", unitAmountDecimal: "0.125" },
63
+ },
64
+ });
65
+ expect(screen.getByRole("status").textContent).toMatch(/version saved/i);
66
+ });
67
+ it("validates included units against precision and native tier bounds, and resets per billing period", async () => {
68
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
69
+ const onSave = vi.fn().mockResolvedValue(undefined);
70
+ render(
71
+ <ui.UsageConfiguration
72
+ scope={scope}
73
+ initial={initial}
74
+ meters={[]}
75
+ onSave={onSave}
76
+ />,
77
+ );
78
+ field("Billing model", "included_overage");
79
+ field("Included units per billing period", "0");
80
+ save();
81
+ await waitFor(() =>
82
+ expect(screen.getByRole("alert").textContent).toMatch(/included/i),
83
+ );
84
+ expect(onSave).not.toHaveBeenCalled();
85
+ field("Included units per billing period", "9007199254740992");
86
+ save();
87
+ await waitFor(() => expect(screen.getByRole("alert")).toBeTruthy());
88
+ expect(onSave).not.toHaveBeenCalled();
89
+ field("Included units per billing period", "100");
90
+ save();
91
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
92
+ expect(onSave.mock.calls[0][0].plan).toMatchObject({
93
+ model: "included_overage",
94
+ includedQuantity: "100",
95
+ reset: "billing_period",
96
+ });
97
+ expect(screen.getByText(/Graduated pricing:/)).toBeTruthy();
98
+ });
99
+ it("configures paid credit packages, rejecting fractional backing and retaining issuer terms with manual top-up", async () => {
100
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
101
+ const onSave = vi.fn().mockResolvedValue(undefined);
102
+ render(
103
+ <ui.UsageConfiguration
104
+ scope={scope}
105
+ initial={initial}
106
+ meters={[]}
107
+ onSave={onSave}
108
+ />,
109
+ );
110
+ field("Billing model", "prepaid");
111
+ field("Credit package quantity", "3");
112
+ field("Price per whole unit (USD)", "0.001");
113
+ save();
114
+ await waitFor(() =>
115
+ expect(screen.getByRole("alert").textContent).toMatch(/whole minor/i),
116
+ );
117
+ expect(onSave).not.toHaveBeenCalled();
118
+ field("Price per whole unit (USD)", "0.02");
119
+ save();
120
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
121
+ expect(onSave.mock.calls[0][0]).toMatchObject({
122
+ plan: { model: "prepaid", insufficientBalance: "reject" },
123
+ creditPackage: { quantity: "3", topUp: "manual" },
124
+ });
125
+ expect(
126
+ screen.getByText(/Reject work when credits are insufficient/),
127
+ ).toBeTruthy();
128
+ expect(screen.queryByLabelText(/owner/i)).toBeNull();
129
+ });
130
+ it("selects immutable authorized meters, disables incompatible meters and preserves their original version", async () => {
131
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
132
+ const onSave = vi.fn().mockResolvedValue(undefined);
133
+ render(
134
+ <ui.UsageConfiguration
135
+ scope={{ ...scope, role: "seller" }}
136
+ initial={initial}
137
+ meters={[
138
+ {
139
+ id: "mtr_old",
140
+ active: true,
141
+ configuration: {
142
+ ...initial,
143
+ plan: { ...initial.plan, version: "v1" },
144
+ eventName: "calls_v1",
145
+ },
146
+ },
147
+ { id: "mtr_off", active: false, configuration: initial },
148
+ ]}
149
+ onSave={onSave}
150
+ />,
151
+ );
152
+ field("Meter", "mtr_old");
153
+ expect(
154
+ (screen.getByLabelText("Plan version") as HTMLInputElement).disabled,
155
+ ).toBe(true);
156
+ expect(
157
+ (screen.getByLabelText("Price per whole unit (USD)") as HTMLInputElement)
158
+ .value,
159
+ ).toBe("0.02");
160
+ save();
161
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
162
+ expect(onSave.mock.calls[0][0]).toMatchObject({
163
+ meterId: "mtr_old",
164
+ plan: { version: "v1" },
165
+ eventName: "calls_v1",
166
+ });
167
+ expect(
168
+ screen.getByRole("option", { name: /inactive/i }).getAttribute("disabled"),
169
+ ).not.toBeNull();
170
+ });
171
+ it("locks duplicate submissions, sanitizes provider errors and allows a same-terms retry", async () => {
172
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
173
+ let reject!: (error: Error) => void;
174
+ const onSave = vi
175
+ .fn()
176
+ .mockImplementationOnce(
177
+ () =>
178
+ new Promise((_, r) => {
179
+ reject = r;
180
+ }),
181
+ )
182
+ .mockResolvedValue(undefined);
183
+ render(
184
+ <ui.UsageConfiguration
185
+ scope={scope}
186
+ initial={initial}
187
+ meters={[]}
188
+ onSave={onSave}
189
+ />,
190
+ );
191
+ save();
192
+ save();
193
+ expect(onSave).toHaveBeenCalledTimes(1);
194
+ expect(
195
+ (screen.getByLabelText("Plan version") as HTMLInputElement).matches(
196
+ ":disabled",
197
+ ),
198
+ ).toBe(true);
199
+ await act(async () => reject(new Error("secret provider tenant-a")));
200
+ expect(screen.getByRole("alert").textContent).toBe(
201
+ "Configuration could not be saved. Retry the same terms or ask an administrator to reconcile the operation.",
202
+ );
203
+ save();
204
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(2));
205
+ });
206
+ it.each([
207
+ "identityKey",
208
+ "accountKey",
209
+ "productKey",
210
+ "role",
211
+ "ownershipLabel",
212
+ "canConfigure",
213
+ "capability",
214
+ ])("discards pending results and edits on %s scope change", async (key) => {
215
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
216
+ let resolve!: () => void;
217
+ const onSave = vi.fn().mockImplementation(
218
+ () =>
219
+ new Promise<void>((r) => {
220
+ resolve = r;
221
+ }),
222
+ );
223
+ const { rerender } = render(
224
+ <ui.UsageConfiguration
225
+ scope={scope}
226
+ initial={initial}
227
+ meters={[]}
228
+ onSave={onSave}
229
+ />,
230
+ );
231
+ field("Plan version", "private-edit");
232
+ save();
233
+ const next = {
234
+ ...scope,
235
+ [key]:
236
+ key === "canConfigure"
237
+ ? false
238
+ : key === "role"
239
+ ? "seller"
240
+ : key === "capability"
241
+ ? "unsupported"
242
+ : "scope-b",
243
+ } as typeof scope;
244
+ rerender(
245
+ <ui.UsageConfiguration
246
+ scope={next}
247
+ initial={initial}
248
+ meters={[]}
249
+ onSave={onSave}
250
+ />,
251
+ );
252
+ await act(async () => resolve());
253
+ expect(screen.queryByText(/version saved/i)).toBeNull();
254
+ const version = screen.queryByLabelText(
255
+ "Plan version",
256
+ ) as HTMLInputElement | null;
257
+ if (version) expect(version.value).toBe("v2");
258
+ });
259
+ it("leaves unavailable capability and read-only hosts unable to submit", () => {
260
+ expect(ui.UsageConfiguration).toBeTypeOf("function");
261
+ const onSave = vi.fn();
262
+ const { rerender } = render(
263
+ <ui.UsageConfiguration
264
+ scope={{ ...scope, capability: "unsupported" }}
265
+ initial={initial}
266
+ meters={[]}
267
+ onSave={onSave}
268
+ />,
269
+ );
270
+ expect(screen.getByText(/configuration unavailable/i)).toBeTruthy();
271
+ expect(screen.queryByRole("button", { name: /save/i })).toBeNull();
272
+ rerender(
273
+ <ui.UsageConfiguration
274
+ scope={{ ...scope, canConfigure: false }}
275
+ initial={initial}
276
+ meters={[]}
277
+ onSave={onSave}
278
+ />,
279
+ );
280
+ save();
281
+ expect(onSave).not.toHaveBeenCalled();
282
+ });
283
+ it("shares configuration payloads between component and serialized HTTP host adapters", async () => {
284
+ const componentSave = vi.fn().mockResolvedValue(undefined);
285
+ const apiSave = vi
286
+ .fn()
287
+ .mockImplementation(async (value) => JSON.parse(JSON.stringify(value)));
288
+ const { unmount } = render(
289
+ <ui.UsageConfiguration
290
+ scope={scope}
291
+ initial={initial}
292
+ meters={[]}
293
+ onSave={componentSave}
294
+ />,
295
+ );
296
+ field("Billing model", "included_overage");
297
+ field("Included units per billing period", "42");
298
+ save();
299
+ await waitFor(() => expect(componentSave).toHaveBeenCalledTimes(1));
300
+ unmount();
301
+ render(
302
+ <ui.UsageConfiguration
303
+ scope={scope}
304
+ initial={JSON.parse(JSON.stringify(initial))}
305
+ meters={[]}
306
+ onSave={apiSave}
307
+ />,
308
+ );
309
+ field("Billing model", "included_overage");
310
+ field("Included units per billing period", "42");
311
+ save();
312
+ await waitFor(() => expect(apiSave).toHaveBeenCalledTimes(1));
313
+ expect(apiSave.mock.calls[0][0]).toEqual(componentSave.mock.calls[0][0]);
314
+ });
315
+ it("exposes styling and render props without adding a second configuration engine", async () => {
316
+ const onSave = vi.fn().mockResolvedValue(undefined);
317
+ render(
318
+ <ui.UsageConfiguration
319
+ scope={scope}
320
+ initial={initial}
321
+ meters={[]}
322
+ onSave={onSave}
323
+ >
324
+ {(state) => (
325
+ <button
326
+ onClick={() => {
327
+ state.setField("version", "v3");
328
+ }}
329
+ >
330
+ Edit version {state.fields.version}
331
+ <span
332
+ onClick={(event) => {
333
+ event.stopPropagation();
334
+ void state.save();
335
+ }}
336
+ >
337
+ Submit
338
+ </span>
339
+ </button>
340
+ )}
341
+ </ui.UsageConfiguration>,
342
+ );
343
+ fireEvent.click(screen.getByRole("button"));
344
+ expect(screen.getByRole("button").textContent).toContain("v3");
345
+ fireEvent.click(screen.getByText("Submit"));
346
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
347
+ expect(onSave.mock.calls[0][0].plan.version).toBe("v3");
348
+ });
349
+ it.each(["pay_as_you_go", "included_overage", "prepaid"] as const)(
350
+ "preserves the exact original %s snapshot including lexical decimals",
351
+ async (model) => {
352
+ const onSave = vi.fn().mockResolvedValue(undefined);
353
+ const common = {
354
+ ...initial.plan,
355
+ version: "original",
356
+ unit: { name: "call", precision: 2 },
357
+ rate: { currency: "usd", unitAmountDecimal: "2.00" },
358
+ };
359
+ const plan: ui.UsageConfigurationValue["plan"] =
360
+ model === "included_overage"
361
+ ? {
362
+ ...common,
363
+ model,
364
+ includedQuantity: "100.00",
365
+ reset: "billing_period",
366
+ }
367
+ : model === "prepaid"
368
+ ? { ...common, model, insufficientBalance: "reject" }
369
+ : { ...common, model };
370
+ const original: ui.UsageConfigurationValue = {
371
+ ...initial,
372
+ plan,
373
+ ...(model === "prepaid"
374
+ ? { creditPackage: { quantity: "100.00", topUp: "manual" } }
375
+ : {}),
376
+ };
377
+ render(
378
+ <ui.UsageConfiguration
379
+ scope={scope}
380
+ initial={initial}
381
+ meters={[{ id: "mtr_original", active: true, configuration: original }]}
382
+ onSave={onSave}
383
+ />,
384
+ );
385
+ field("Meter", "mtr_original");
386
+ save();
387
+ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
388
+ expect(onSave.mock.calls[0][0]).toEqual({
389
+ ...original,
390
+ meterId: "mtr_original",
391
+ });
392
+ },
393
+ );
@@ -0,0 +1,135 @@
1
+ "use client";
2
+ import { useId } from "react";
3
+ import { useUsageConfiguration } from "./useUsageConfiguration.js";
4
+ import type {
5
+ UsageConfigurationFields,
6
+ UsageConfigurationProps,
7
+ } from "./UsageConfiguration.types.js";
8
+ /** Unstyled native catalog configuration. Host adapters own authorization and provider operations. */
9
+ export function UsageConfiguration(props: UsageConfigurationProps) {
10
+ const id = useId();
11
+ const state = useUsageConfiguration(props);
12
+ if (props.children) return <>{props.children(state)}</>;
13
+ if (props.scope.capability !== "issuer_native")
14
+ return (
15
+ <p role="status">
16
+ Native usage configuration unavailable for this account.
17
+ </p>
18
+ );
19
+ const input = (
20
+ field: keyof UsageConfigurationFields,
21
+ label: string,
22
+ inputMode?: "decimal" | "numeric",
23
+ ) => (
24
+ <label htmlFor={`${id}-${field}`}>
25
+ {label}
26
+ <input
27
+ id={`${id}-${field}`}
28
+ value={state.fields[field]}
29
+ inputMode={inputMode}
30
+ disabled={state.immutable}
31
+ onChange={(event) => state.setField(field, event.target.value)}
32
+ />
33
+ </label>
34
+ );
35
+ return (
36
+ <form
37
+ className={props.className}
38
+ data-better-stripe="usage-configuration"
39
+ aria-label="Usage configuration"
40
+ aria-busy={state.isPending}
41
+ onSubmit={(event) => {
42
+ event.preventDefault();
43
+ void state.save();
44
+ }}
45
+ >
46
+ <h3>Usage configuration</h3>
47
+ <p>
48
+ Owner: {props.scope.ownershipLabel}. Authorized {props.scope.role}{" "}
49
+ configuration.
50
+ </p>
51
+ <p>
52
+ Monthly billing with sum aggregation. Existing subscriptions keep their
53
+ original prices. Changed terms require a new version, event name and
54
+ price.
55
+ </p>
56
+ <fieldset disabled={state.disabled || state.isPending}>
57
+ <legend>Meter and immutable billing terms</legend>
58
+ <label htmlFor={`${id}-meter`}>Meter</label>
59
+ <select
60
+ id={`${id}-meter`}
61
+ value={state.meterId}
62
+ onChange={(event) => state.selectMeter(event.target.value)}
63
+ >
64
+ <option value="">Create new meter version</option>
65
+ {props.meters.map((meter) => (
66
+ <option key={meter.id} value={meter.id} disabled={!meter.active}>
67
+ {meter.configuration.displayName} ·{" "}
68
+ {meter.configuration.plan.version}
69
+ {meter.active ? "" : " (inactive)"}
70
+ </option>
71
+ ))}
72
+ </select>
73
+ <label htmlFor={`${id}-model`}>Billing model</label>
74
+ <select
75
+ id={`${id}-model`}
76
+ value={state.fields.model}
77
+ disabled={state.immutable}
78
+ onChange={(event) =>
79
+ state.setField(
80
+ "model",
81
+ event.target.value as UsageConfigurationFields["model"],
82
+ )
83
+ }
84
+ >
85
+ <option value="pay_as_you_go">Pay as you go</option>
86
+ <option value="included_overage">
87
+ Included monthly units plus overages
88
+ </option>
89
+ <option value="prepaid">Prepaid paid credits</option>
90
+ </select>
91
+ {input("key", "Plan key")}
92
+ {input("version", "Plan version")}
93
+ {input("eventName", "Meter event name")}
94
+ {input("displayName", "Meter display name")}
95
+ {input("unit", "Billable unit")}
96
+ {input("precision", "Quantity precision", "numeric")}
97
+ {input("currency", "Currency")}
98
+ {input(
99
+ "price",
100
+ `Price per whole unit (${state.fields.currency.toUpperCase()})`,
101
+ "decimal",
102
+ )}
103
+ {state.fields.model === "included_overage" && (
104
+ <>
105
+ {input("included", "Included units per billing period", "decimal")}
106
+ <p>
107
+ Graduated pricing: free included units, then the configured
108
+ overage rate. Reset at each original monthly billing period.
109
+ </p>
110
+ </>
111
+ )}
112
+ {state.fields.model === "prepaid" && (
113
+ <>
114
+ {input("packageQuantity", "Credit package quantity", "decimal")}
115
+ <p>
116
+ Manual top-up with a verified payment for the issuer's own
117
+ services. Retain original credit terms. Reject work when credits
118
+ are insufficient. No automatic top-up or monetary wallet.
119
+ </p>
120
+ </>
121
+ )}
122
+ <p>
123
+ Only managed monthly sum meters and exact per-unit rates or
124
+ included-unit graduated tiers are supported. Other tiers,
125
+ transformations and intervals require a supported server adapter.
126
+ </p>
127
+ <button type="submit">
128
+ {state.isPending ? "Saving…" : "Save configuration version"}
129
+ </button>
130
+ </fieldset>
131
+ {state.error && <p role="alert">{state.error}</p>}
132
+ {state.message && <p role="status">{state.message}</p>}
133
+ </form>
134
+ );
135
+ }
@@ -0,0 +1,67 @@
1
+ import type { ReactNode } from "react";
2
+ import type {
3
+ UsagePlan,
4
+ UsageBillingModel,
5
+ } from "../../client/usage/contracts.js";
6
+ /** Display/cache context from an authenticated host. Never use this as server authorization. */
7
+ export type UsageConfigurationScope = {
8
+ identityKey: string;
9
+ accountKey: string;
10
+ productKey: string;
11
+ role: "admin" | "seller";
12
+ ownershipLabel: string;
13
+ canConfigure: boolean;
14
+ /** Host has verified the configured issuer realm and supported native catalog. */
15
+ capability: "issuer_native" | "unsupported";
16
+ };
17
+ export type UsageConfigurationValue = {
18
+ plan: UsagePlan;
19
+ eventName: string;
20
+ displayName: string;
21
+ meterId?: string;
22
+ creditPackage?: { quantity: string; topUp: "manual" };
23
+ };
24
+ export type UsageMeterChoice = {
25
+ id: string;
26
+ active: boolean;
27
+ /** Original managed terms, derived and authorized by the host. */
28
+ configuration: UsageConfigurationValue;
29
+ };
30
+ export type UsageConfigurationFields = {
31
+ model: UsageBillingModel;
32
+ key: string;
33
+ version: string;
34
+ unit: string;
35
+ precision: string;
36
+ currency: string;
37
+ price: string;
38
+ included: string;
39
+ packageQuantity: string;
40
+ eventName: string;
41
+ displayName: string;
42
+ };
43
+ export type UsageConfigurationProps = {
44
+ scope: UsageConfigurationScope;
45
+ initial: UsageConfigurationValue;
46
+ /** A scoped page/subset of managed meters. Never treat a partial list as complete inventory. */
47
+ meters: readonly UsageMeterChoice[];
48
+ /** Reauthorize, derive ownership/product/realm and validate immutable terms on the server. */
49
+ onSave: (value: UsageConfigurationValue) => Promise<unknown>;
50
+ className?: string;
51
+ children?: (state: UsageConfigurationState) => ReactNode;
52
+ };
53
+ export type UsageConfigurationState = {
54
+ fields: UsageConfigurationFields;
55
+ setField: <K extends keyof UsageConfigurationFields>(
56
+ key: K,
57
+ value: UsageConfigurationFields[K],
58
+ ) => void;
59
+ meterId: string;
60
+ selectMeter: (id: string) => void;
61
+ immutable: boolean;
62
+ disabled: boolean;
63
+ isPending: boolean;
64
+ error: string | null;
65
+ message: string | undefined;
66
+ save: () => Promise<unknown>;
67
+ };
@@ -0,0 +1,112 @@
1
+ "use client";
2
+ import type { ReactNode } from "react";
3
+ import type { UsageAvailability } from "../../client/usage/boundaries.js";
4
+ import type {
5
+ UsageCreditBalance,
6
+ UsageCreditPurchase,
7
+ } from "../../client/usage/creditTerms.js";
8
+ import type { UsageCreditReconciliation } from "../../client/usage/creditObservation.js";
9
+ import { formatUsageEstimate } from "./usage-format.js";
10
+ export type UsageCreditsProps = {
11
+ balance: UsageAvailability<UsageCreditBalance> | undefined;
12
+ purchase?: UsageCreditPurchase | null;
13
+ currency?: string;
14
+ application?: UsageAvailability<UsageCreditReconciliation>;
15
+ className?: string;
16
+ children?: (
17
+ state: Omit<UsageCreditsProps, "children" | "className">,
18
+ ) => ReactNode;
19
+ };
20
+ export function UsageCredits({
21
+ balance,
22
+ purchase,
23
+ currency,
24
+ application,
25
+ children,
26
+ className,
27
+ }: UsageCreditsProps) {
28
+ if (children)
29
+ return <>{children({ balance, purchase, application, currency })}</>;
30
+ return (
31
+ <section
32
+ data-better-stripe="usage-credits"
33
+ className={className}
34
+ aria-label="Prepaid credits"
35
+ aria-busy={balance === undefined}
36
+ >
37
+ <h2>Prepaid credits</h2>
38
+ {!balance ? (
39
+ <p role="status">Loading credit balance…</p>
40
+ ) : balance.status !== "available" ? (
41
+ <p role="status">
42
+ Credit balance {balance.status}. Verified backing is required.
43
+ </p>
44
+ ) : (
45
+ <>
46
+ <dl>
47
+ {(
48
+ [
49
+ ["Available", balance.value.availableQuantity],
50
+ ["Reserved", balance.value.reservedQuantity],
51
+ ["Consumed", balance.value.consumedQuantity],
52
+ ["Expired", balance.value.expiredQuantity],
53
+ ["Frozen", balance.value.frozenQuantity],
54
+ ] as const
55
+ ).map(([label, quantity]) => (
56
+ <div key={label}>
57
+ <dt>{label}</dt>
58
+ <dd>
59
+ {quantity} {balance.value.unit}
60
+ </dd>
61
+ </div>
62
+ ))}
63
+ </dl>
64
+ {(balance.value.status === "held" ||
65
+ !/^0(?:\.0+)?$/.test(balance.value.frozenQuantity)) && (
66
+ <p role="status">Credits held. Reconciliation is required.</p>
67
+ )}
68
+ {/^0(?:\.0+)?$/.test(balance.value.availableQuantity) && (
69
+ <p role="status">
70
+ Insufficient credits for new work. A server reservation must
71
+ authorize consumption.
72
+ </p>
73
+ )}
74
+ </>
75
+ )}
76
+ {purchase && (
77
+ <p role="status">
78
+ {
79
+ {
80
+ pending: "Payment pending. No units granted yet.",
81
+ ready: "Payment verified and original credit grant retained.",
82
+ frozen: "Purchase frozen. Recovery is required.",
83
+ canceled: "Purchase canceled.",
84
+ }[purchase.state]
85
+ }{" "}
86
+ Purchase {purchase.purchaseId}: {purchase.quantity} units for{" "}
87
+ {formatUsageEstimate(String(purchase.amount), purchase.currency) ??
88
+ "unavailable amount"}
89
+ .
90
+ </p>
91
+ )}
92
+ {application &&
93
+ (application.status === "available" ? (
94
+ <p role="status">
95
+ Credit application {application.value.backing}.{" "}
96
+ {application.value.reason
97
+ ? "Reconciliation is required."
98
+ : `Pending finalization amount: ${formatUsageEstimate(String(application.value.pendingFinalizationAmount), currency ?? (balance?.status === "available" ? balance.value.currency : purchase?.currency) ?? "") ?? "unavailable"}.`}
99
+ </p>
100
+ ) : (
101
+ <p role="status">
102
+ Credit application {application.status}. Original invoice evidence
103
+ is not yet verified.
104
+ </p>
105
+ ))}
106
+ <p>
107
+ No cash is collected by consuming credits. This balance is not
108
+ withdrawable money.
109
+ </p>
110
+ </section>
111
+ );
112
+ }