@fantastic.dev/better-stripe 0.60.1 → 0.61.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 (66) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -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 +12 -0
  6. package/dist/react/index.d.ts.map +1 -1
  7. package/dist/react/index.js +7 -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/UsageCredits.d.ts +14 -0
  30. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  31. package/dist/react/workflows/UsageCredits.js +25 -0
  32. package/dist/react/workflows/UsageCredits.js.map +1 -0
  33. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  34. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  35. package/dist/react/workflows/UsageHistory.js +74 -0
  36. package/dist/react/workflows/UsageHistory.js.map +1 -0
  37. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  38. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  39. package/dist/react/workflows/UsageSummary.js +54 -0
  40. package/dist/react/workflows/UsageSummary.js.map +1 -0
  41. package/dist/react/workflows/usage-format.d.ts +11 -0
  42. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  43. package/dist/react/workflows/usage-format.js +43 -0
  44. package/dist/react/workflows/usage-format.js.map +1 -0
  45. package/dist/react/workflows/usage-scope.d.ts +5 -0
  46. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  47. package/dist/react/workflows/usage-scope.js +26 -0
  48. package/dist/react/workflows/usage-scope.js.map +1 -0
  49. package/docs/README.md +2 -0
  50. package/docs/react-api.md +4 -0
  51. package/docs/usage-react.md +182 -0
  52. package/package.json +2 -1
  53. package/src/client/usage/index.ts +3 -0
  54. package/src/react/index.ts +20 -0
  55. package/src/react/workflows/Pagination.tsx +2 -0
  56. package/src/react/workflows/Usage.fixtures.ts +88 -0
  57. package/src/react/workflows/Usage.test.tsx +373 -0
  58. package/src/react/workflows/Usage.types.ts +39 -0
  59. package/src/react/workflows/UsageAllowance.tsx +114 -0
  60. package/src/react/workflows/UsageBilling.tsx +90 -0
  61. package/src/react/workflows/UsageCredits.tsx +112 -0
  62. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  63. package/src/react/workflows/UsageHistory.tsx +154 -0
  64. package/src/react/workflows/UsageSummary.tsx +204 -0
  65. package/src/react/workflows/usage-format.ts +48 -0
  66. package/src/react/workflows/usage-scope.ts +42 -0
@@ -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
+ }
@@ -0,0 +1,206 @@
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 userEvent from "@testing-library/user-event";
11
+ import { afterEach, expect, it, vi } from "vitest";
12
+ import * as ui from "../index.js";
13
+ import { usageScope } from "./Usage.fixtures.js";
14
+ afterEach(cleanup);
15
+ const page = (
16
+ name: string,
17
+ cursor: string | null = null,
18
+ isDone = cursor === null,
19
+ ) => ({
20
+ status: "available" as const,
21
+ observedAt: 700,
22
+ value: { records: [{ id: name }], cursor, isDone },
23
+ });
24
+ it("loads bounded authorized pages and exposes the same pagination through render props", async () => {
25
+ expect(ui.UsageHistory).toBeTypeOf("function");
26
+ const load = vi
27
+ .fn()
28
+ .mockResolvedValueOnce(page("first", "next1"))
29
+ .mockResolvedValueOnce(page("second"));
30
+ render(
31
+ <ui.UsageHistory
32
+ scope={usageScope}
33
+ historyKey="events"
34
+ load={load}
35
+ limit={5}
36
+ getKey={(row: { id: string }) => row.id}
37
+ renderRecord={(row) => <span>{row.id}</span>}
38
+ />,
39
+ );
40
+ await screen.findByText("first");
41
+ expect(load).toHaveBeenCalledWith(usageScope, { cursor: null, limit: 5 });
42
+ fireEvent.click(screen.getByRole("button", { name: "Next" }));
43
+ await screen.findByText("second");
44
+ expect(load).toHaveBeenLastCalledWith(usageScope, {
45
+ cursor: "next1",
46
+ limit: 5,
47
+ });
48
+ expect(
49
+ (screen.getByRole("button", { name: "Next" }) as HTMLButtonElement)
50
+ .disabled,
51
+ ).toBe(true);
52
+ expect(
53
+ (screen.getByRole("button", { name: "Previous" }) as HTMLButtonElement)
54
+ .disabled,
55
+ ).toBe(false);
56
+ });
57
+ it("does not call an empty incomplete page complete or display unavailable history as zero", async () => {
58
+ expect(ui.UsageHistory).toBeTypeOf("function");
59
+ const load = vi
60
+ .fn()
61
+ .mockResolvedValueOnce({
62
+ status: "available",
63
+ observedAt: 700,
64
+ value: { records: [], cursor: "more", isDone: false, complete: false },
65
+ })
66
+ .mockResolvedValueOnce({
67
+ status: "unavailable",
68
+ reason: "read_unavailable",
69
+ retryable: true,
70
+ });
71
+ render(
72
+ <ui.UsageHistory
73
+ scope={usageScope}
74
+ historyKey="credits"
75
+ load={load}
76
+ getKey={(row: { id: string }) => row.id}
77
+ renderRecord={(row) => row.id}
78
+ />,
79
+ );
80
+ await screen.findByText(/History incomplete/);
81
+ expect(screen.queryByText(/No history/)).toBeNull();
82
+ fireEvent.click(screen.getByRole("button", { name: "Next" }));
83
+ await screen.findByText(/History unavailable/);
84
+ expect(screen.queryByText(/No history/)).toBeNull();
85
+ });
86
+ it("resets cursor and drops late history after tenant and period switches", async () => {
87
+ expect(ui.UsageHistory).toBeTypeOf("function");
88
+ let finish!: (value: ReturnType<typeof page>) => void;
89
+ const load = vi
90
+ .fn()
91
+ .mockResolvedValueOnce(page("original", "later"))
92
+ .mockImplementationOnce(
93
+ () =>
94
+ new Promise((resolve) => {
95
+ finish = resolve;
96
+ }),
97
+ )
98
+ .mockResolvedValueOnce(page("other tenant"));
99
+ const props = {
100
+ scope: usageScope,
101
+ historyKey: "events",
102
+ load,
103
+ getKey: (row: { id: string }) => row.id,
104
+ renderRecord: (row: { id: string }) => row.id,
105
+ };
106
+ const { rerender } = render(<ui.UsageHistory {...props} />);
107
+ await screen.findByText("original");
108
+ fireEvent.click(screen.getByRole("button", { name: "Next" }));
109
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(2));
110
+ const scope = {
111
+ ...usageScope,
112
+ accountKey: "other",
113
+ period: { start: 1200, end: 1800 },
114
+ };
115
+ rerender(<ui.UsageHistory {...props} scope={scope} />);
116
+ await screen.findByText("other tenant");
117
+ expect(load).toHaveBeenLastCalledWith(scope, { cursor: null, limit: 25 });
118
+ await act(async () => finish(page("late original")));
119
+ expect(screen.queryByText("late original")).toBeNull();
120
+ });
121
+
122
+ for (const cursor of ["", "c1"])
123
+ it(`holds a nonterminal ${cursor ? "repeated" : "empty"} cursor and retains previous-page navigation`, async () => {
124
+ const load = vi
125
+ .fn()
126
+ .mockResolvedValueOnce(page("first", "c1"))
127
+ .mockResolvedValueOnce(page("second", cursor, false))
128
+ .mockResolvedValueOnce(page("first", "c1"));
129
+ render(
130
+ <ui.UsageHistory
131
+ scope={usageScope}
132
+ historyKey="events"
133
+ load={load}
134
+ getKey={(row: { id: string }) => row.id}
135
+ renderRecord={(row) => row.id}
136
+ />,
137
+ );
138
+ await screen.findByText("first");
139
+ fireEvent.click(screen.getByRole("button", { name: "Next" }));
140
+ await screen.findByText("second");
141
+ expect(
142
+ (screen.getByRole("button", { name: "Next" }) as HTMLButtonElement)
143
+ .disabled,
144
+ ).toBe(true);
145
+ expect(screen.getByText(/History incomplete/)).toBeTruthy();
146
+ fireEvent.click(screen.getByRole("button", { name: "Previous" }));
147
+ await screen.findByText("first");
148
+ expect(
149
+ (screen.getByRole("button", { name: "Next" }) as HTMLButtonElement)
150
+ .disabled,
151
+ ).toBe(false);
152
+ });
153
+ it("holds a cursor that loops back to any earlier page in the current navigation path", async () => {
154
+ const load = vi
155
+ .fn()
156
+ .mockResolvedValueOnce(page("one", "c1"))
157
+ .mockResolvedValueOnce(page("two", "c2"))
158
+ .mockResolvedValueOnce(page("three", "c1"));
159
+ render(
160
+ <ui.UsageHistory
161
+ scope={usageScope}
162
+ historyKey="events"
163
+ load={load}
164
+ getKey={(row: { id: string }) => row.id}
165
+ renderRecord={(row) => row.id}
166
+ />,
167
+ );
168
+ for (const name of ["one", "two"]) {
169
+ await screen.findByText(name);
170
+ fireEvent.click(screen.getByRole("button", { name: "Next" }));
171
+ }
172
+ await screen.findByText("three");
173
+ expect(
174
+ (screen.getByRole("button", { name: "Next" }) as HTMLButtonElement)
175
+ .disabled,
176
+ ).toBe(true);
177
+ expect(screen.getByText(/History incomplete/)).toBeTruthy();
178
+ });
179
+
180
+ it("supports keyboard-only history pagination through labelled native buttons", async () => {
181
+ const user = userEvent.setup();
182
+ const load = vi
183
+ .fn()
184
+ .mockResolvedValueOnce(page("first", "next"))
185
+ .mockResolvedValueOnce(page("second"));
186
+ render(
187
+ <ui.UsageHistory
188
+ scope={usageScope}
189
+ historyKey="events"
190
+ load={load}
191
+ getKey={(row: { id: string }) => row.id}
192
+ renderRecord={(row) => row.id}
193
+ />,
194
+ );
195
+ await screen.findByText("first");
196
+ await user.tab();
197
+ expect(document.activeElement).toBe(
198
+ screen.getByRole("button", { name: "Refresh history" }),
199
+ );
200
+ await user.tab();
201
+ expect(document.activeElement).toBe(
202
+ screen.getByRole("button", { name: "Next" }),
203
+ );
204
+ await user.keyboard("{Enter}");
205
+ await screen.findByText("second");
206
+ });
@@ -0,0 +1,154 @@
1
+ "use client";
2
+ import type { ReactNode } from "react";
3
+ import type { UsageAvailability } from "../../client/usage/boundaries.js";
4
+ import { useWorkflowResource } from "./useWorkflowResource.js";
5
+ import { Pagination, useCursorPagination } from "./Pagination.js";
6
+ import { usageViewKey, type UsageViewScope } from "./Usage.types.js";
7
+ export type UsageHistoryPage<Row> = {
8
+ records: readonly Row[];
9
+ cursor: string | null;
10
+ isDone: boolean;
11
+ complete?: boolean;
12
+ };
13
+ export type UsageHistoryProps<Row> = {
14
+ scope: UsageViewScope;
15
+ /** Distinguish event, credit, allowance or delivery readers and their filters. */
16
+ historyKey: string;
17
+ load: (
18
+ scope: UsageViewScope,
19
+ page: { cursor: string | null; limit: number },
20
+ ) => Promise<UsageAvailability<UsageHistoryPage<Row>>>;
21
+ getKey: (record: Row) => string;
22
+ renderRecord: (record: Row) => ReactNode;
23
+ limit?: number;
24
+ label?: string;
25
+ className?: string;
26
+ children?: (state: ReturnType<typeof useUsageHistory<Row>>) => ReactNode;
27
+ };
28
+ export function useUsageHistory<Row>(
29
+ props: Pick<
30
+ UsageHistoryProps<Row>,
31
+ "scope" | "historyKey" | "load" | "limit"
32
+ >,
33
+ ) {
34
+ const limit = props.limit ?? 25;
35
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
36
+ throw new RangeError("Usage history page size must be 1–100");
37
+ const key = JSON.stringify([
38
+ usageViewKey(props.scope),
39
+ props.historyKey,
40
+ limit,
41
+ ]);
42
+ const navigation = useCursorPagination(key);
43
+ const resource = useWorkflowResource(
44
+ async () => {
45
+ try {
46
+ const result = await props.load(props.scope, {
47
+ cursor: navigation.cursor,
48
+ limit,
49
+ });
50
+ if (
51
+ result.status === "available" &&
52
+ (result.value.records.length > limit ||
53
+ (result.value.cursor !== null && result.value.cursor.length > 2048))
54
+ )
55
+ throw new Error("Invalid history page");
56
+ return result;
57
+ } catch {
58
+ throw new Error("History unavailable. Try again.");
59
+ }
60
+ },
61
+ JSON.stringify([key, navigation.cursor]),
62
+ );
63
+ const available =
64
+ resource.data?.status === "available" ? resource.data.value : null;
65
+ const advancing =
66
+ !!available &&
67
+ typeof available.cursor === "string" &&
68
+ available.cursor.length > 0 &&
69
+ !navigation.hasCursor(available.cursor);
70
+ const incomplete =
71
+ available?.complete === false ||
72
+ (!!available && !available.isDone && !advancing);
73
+ const canNext = !!available && !available.isDone && advancing;
74
+ return {
75
+ ...resource,
76
+ page: navigation.page,
77
+ canPrevious: navigation.canPrevious,
78
+ canNext,
79
+ isIncomplete: incomplete,
80
+ isEmpty:
81
+ !!available &&
82
+ available.records.length === 0 &&
83
+ available.isDone &&
84
+ !incomplete,
85
+ previous: () => {
86
+ if (!resource.isLoading) navigation.previous();
87
+ },
88
+ next: () => {
89
+ if (!resource.isLoading && canNext) navigation.next(available!.cursor!);
90
+ },
91
+ };
92
+ }
93
+ export function UsageHistory<Row>(props: UsageHistoryProps<Row>) {
94
+ return (
95
+ <UsageHistoryBody
96
+ key={JSON.stringify([
97
+ usageViewKey(props.scope),
98
+ props.historyKey,
99
+ props.limit ?? 25,
100
+ ])}
101
+ {...props}
102
+ />
103
+ );
104
+ }
105
+ function UsageHistoryBody<Row>(props: UsageHistoryProps<Row>) {
106
+ const state = useUsageHistory(props);
107
+ if (props.children) return <>{props.children(state)}</>;
108
+ const available =
109
+ state.data?.status === "available" ? state.data.value : null;
110
+ return (
111
+ <section
112
+ data-better-stripe="usage-history"
113
+ className={props.className}
114
+ aria-label={props.label ?? "Usage history"}
115
+ aria-busy={state.isLoading}
116
+ >
117
+ <h2>{props.label ?? "Usage history"}</h2>
118
+ <button type="button" disabled={state.isLoading} onClick={state.refresh}>
119
+ Refresh history
120
+ </button>
121
+ {state.isLoading && <p role="status">Loading history…</p>}
122
+ {(state.isLoading || state.error) && available && (
123
+ <p role="status">Displayed history may be stale.</p>
124
+ )}
125
+ {state.error && <p role="alert">{state.error}</p>}
126
+ {state.data && state.data.status !== "available" && (
127
+ <p role="status">
128
+ History {state.data.status}. Original scoped history is required.
129
+ </p>
130
+ )}
131
+ {state.isIncomplete && (
132
+ <p role="status">
133
+ History incomplete. This page does not establish complete totals.
134
+ </p>
135
+ )}
136
+ {state.isEmpty && <p>No history for this view.</p>}
137
+ {available && (
138
+ <ol>
139
+ {available.records.map((record) => (
140
+ <li key={props.getKey(record)}>{props.renderRecord(record)}</li>
141
+ ))}
142
+ </ol>
143
+ )}
144
+ <Pagination
145
+ page={state.page}
146
+ canPrevious={state.canPrevious}
147
+ canNext={state.canNext}
148
+ isLoading={state.isLoading}
149
+ onPrevious={state.previous}
150
+ onNext={state.next}
151
+ />
152
+ </section>
153
+ );
154
+ }
@@ -0,0 +1,204 @@
1
+ "use client";
2
+ import { usageSummaryMatches } from "./usage-scope.js";
3
+ import type { ReactNode } from "react";
4
+ import type { UsageAvailability } from "../../client/usage/boundaries.js";
5
+ import type { UsageLocalSummary } from "../../client/usage/summary.js";
6
+ import type { UsageAggregateObservation } from "../../client/usage/observationTypes.js";
7
+ import type { UsageViewScope } from "./Usage.types.js";
8
+ import { formatUsageEstimate, formatUsageTime } from "./usage-format.js";
9
+ export type UsageSummaryProps = {
10
+ scope: UsageViewScope;
11
+ summary: UsageAvailability<UsageLocalSummary> | undefined;
12
+ provider?: UsageAggregateObservation;
13
+ className?: string;
14
+ children?: (state: {
15
+ summary: UsageSummaryProps["summary"];
16
+ provider: UsageSummaryProps["provider"];
17
+ isLoading: boolean;
18
+ isEmpty: boolean;
19
+ }) => ReactNode;
20
+ };
21
+ const models = {
22
+ pay_as_you_go: "Pay as you go",
23
+ included_overage: "Included monthly usage with overages",
24
+ prepaid: "Prepaid credits",
25
+ };
26
+ const deliveryLabels = {
27
+ queued: "Queued delivery",
28
+ sending: "Sending delivery",
29
+ provider_accepted: "Provider accepted",
30
+ rejected: "Rejected delivery",
31
+ unknown: "Unknown delivery",
32
+ held: "Held delivery",
33
+ canceled: "Canceled usage",
34
+ };
35
+ export function UsageSummary(props: UsageSummaryProps) {
36
+ const provider =
37
+ props.provider?.status === "available" &&
38
+ (props.provider.value.period.start !== props.scope.period.start ||
39
+ props.provider.value.period.end !== props.scope.period.end)
40
+ ? {
41
+ status: "unavailable" as const,
42
+ reason: "observation_scope_mismatch",
43
+ retryable: true,
44
+ }
45
+ : props.provider;
46
+ const summary =
47
+ props.summary?.status === "available" &&
48
+ !usageSummaryMatches(props.scope, props.summary.value)
49
+ ? {
50
+ status: "unavailable" as const,
51
+ reason: "observation_scope_mismatch",
52
+ retryable: true,
53
+ }
54
+ : props.summary;
55
+ const available = summary?.status === "available" ? summary.value : null;
56
+ if (props.children)
57
+ return (
58
+ <>
59
+ {props.children({
60
+ summary,
61
+ provider,
62
+ isLoading: summary === undefined,
63
+ isEmpty: !!available?.complete && available.eventCount === 0,
64
+ })}
65
+ </>
66
+ );
67
+ return (
68
+ <section
69
+ data-better-stripe="usage-summary"
70
+ className={props.className}
71
+ aria-label="Usage summary"
72
+ aria-busy={summary === undefined}
73
+ >
74
+ <h2>Usage by meter</h2>
75
+ {!summary ? (
76
+ <p role="status">Loading usage…</p>
77
+ ) : summary.status !== "available" ? (
78
+ <p role="status">
79
+ Usage {summary.status}. Refresh when original usage evidence is
80
+ available.
81
+ </p>
82
+ ) : (
83
+ <>
84
+ <p>
85
+ Period {formatUsageTime(summary.value.period.start)} to{" "}
86
+ {formatUsageTime(summary.value.period.end)}
87
+ </p>
88
+ {!summary.value.complete && (
89
+ <p role="status">Local history incomplete. Totals are partial.</p>
90
+ )}
91
+ {summary.value.complete && summary.value.eventCount === 0 && (
92
+ <p>No usage in this period.</p>
93
+ )}
94
+ {summary.value.groups.map((group) => (
95
+ <article
96
+ key={JSON.stringify([
97
+ group.binding.stripePriceId,
98
+ group.subscription.subscriptionItemId,
99
+ group.subscription.period,
100
+ ])}
101
+ data-billing-model={group.binding.plan.model}
102
+ >
103
+ <h3>
104
+ {group.binding.plan.unit.name} ·{" "}
105
+ {models[group.binding.plan.model]}
106
+ </h3>
107
+ <p>
108
+ Plan {group.binding.plan.key}, version{" "}
109
+ {group.binding.plan.version}
110
+ </p>
111
+ <dl>
112
+ <dt>Accepted usage</dt>
113
+ <dd>
114
+ {group.acceptedQuantity} {group.binding.plan.unit.name}
115
+ </dd>
116
+ <dt>Billable after corrections</dt>
117
+ <dd>
118
+ {group.effectiveQuantity} {group.binding.plan.unit.name}
119
+ </dd>
120
+ <dt>Provider accepted</dt>
121
+ <dd>
122
+ {group.providerAcceptedQuantity}{" "}
123
+ {group.binding.plan.unit.name}
124
+ </dd>
125
+ {Object.entries(group.deliveryQuantities)
126
+ .filter(
127
+ ([kind, quantity]) =>
128
+ kind !== "provider_accepted" &&
129
+ !/^0(?:\.0+)?$/.test(quantity),
130
+ )
131
+ .map(([kind, quantity]) => (
132
+ <div key={kind}>
133
+ <dt>
134
+ {deliveryLabels[kind as keyof typeof deliveryLabels]}
135
+ </dt>
136
+ <dd>
137
+ {quantity} {group.binding.plan.unit.name}
138
+ </dd>
139
+ </div>
140
+ ))}
141
+ </dl>
142
+ {group.validationErrorEventCount > 0 && (
143
+ <p role="status">
144
+ Native validation rejected {group.validationErrorEventCount}{" "}
145
+ event(s).
146
+ </p>
147
+ )}
148
+ {group.estimate.status === "available" ? (
149
+ <p>
150
+ Estimated usage charge:{" "}
151
+ {formatUsageEstimate(
152
+ group.estimate.value.amountDecimal,
153
+ group.estimate.value.currency,
154
+ ) ?? "Unavailable"}
155
+ </p>
156
+ ) : (
157
+ <p>
158
+ Estimate {group.estimate.status}. Complete original usage and
159
+ pricing evidence is required.
160
+ </p>
161
+ )}
162
+ {group.included.status === "available" && (
163
+ <dl>
164
+ <dt>Included units</dt>
165
+ <dd>{group.included.value.included}</dd>
166
+ <dt>Remaining included units</dt>
167
+ <dd>{group.included.value.remaining}</dd>
168
+ <dt>Overage units</dt>
169
+ <dd>{group.included.value.overage}</dd>
170
+ </dl>
171
+ )}
172
+ </article>
173
+ ))}
174
+ <p>
175
+ Estimate only. Finalized invoices and verified payments determine
176
+ billing.
177
+ </p>
178
+ </>
179
+ )}
180
+ {!provider || provider.status !== "available" ? (
181
+ <p role="status">
182
+ Native aggregation {provider?.status ?? "unavailable"}. Refresh after
183
+ provider ingestion.
184
+ </p>
185
+ ) : (
186
+ <>
187
+ <p>Native aggregate: {provider.value.quantity}</p>
188
+ {provider.value.stale && (
189
+ <p role="status">Native aggregation stale.</p>
190
+ )}
191
+ {!provider.value.complete && (
192
+ <p role="status">
193
+ Native aggregation partial. More provider pages remain.
194
+ </p>
195
+ )}
196
+ <p>
197
+ Aggregation may be delayed. Provider acceptance does not prove
198
+ ingestion or payment.
199
+ </p>
200
+ </>
201
+ )}
202
+ </section>
203
+ );
204
+ }