@fantastic.dev/better-stripe 0.60.0 → 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 (193) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +26 -6
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +26 -6
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/creditCapacity.d.ts.map +1 -1
  12. package/dist/client/usage/creditCapacity.js +7 -1
  13. package/dist/client/usage/creditCapacity.js.map +1 -1
  14. package/dist/client/usage/creditClient.d.ts +3 -0
  15. package/dist/client/usage/creditClient.d.ts.map +1 -1
  16. package/dist/client/usage/creditDelivery.d.ts.map +1 -1
  17. package/dist/client/usage/creditDelivery.js +4 -1
  18. package/dist/client/usage/creditDelivery.js.map +1 -1
  19. package/dist/client/usage/creditLifecycle.d.ts.map +1 -1
  20. package/dist/client/usage/creditLifecycle.js +2 -1
  21. package/dist/client/usage/creditLifecycle.js.map +1 -1
  22. package/dist/client/usage/creditNative.d.ts +3 -0
  23. package/dist/client/usage/creditNative.d.ts.map +1 -1
  24. package/dist/client/usage/creditNative.js +3 -0
  25. package/dist/client/usage/creditNative.js.map +1 -1
  26. package/dist/client/usage/creditProvider.d.ts.map +1 -1
  27. package/dist/client/usage/creditProvider.js +2 -1
  28. package/dist/client/usage/creditProvider.js.map +1 -1
  29. package/dist/client/usage/creditRead.d.ts +1 -0
  30. package/dist/client/usage/creditRead.d.ts.map +1 -1
  31. package/dist/client/usage/creditReconciliation.d.ts.map +1 -1
  32. package/dist/client/usage/creditReconciliation.js +11 -3
  33. package/dist/client/usage/creditReconciliation.js.map +1 -1
  34. package/dist/client/usage/creditSettlement.fixtures.d.ts +1 -0
  35. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -1
  36. package/dist/client/usage/creditTransport.fixtures.d.ts +1 -0
  37. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  38. package/dist/client/usage/creditTransport.fixtures.js +2 -1
  39. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  40. package/dist/client/usage/index.d.ts +2 -0
  41. package/dist/client/usage/index.d.ts.map +1 -1
  42. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -1
  43. package/dist/client/usage/subscriptionCancellation.js +3 -2
  44. package/dist/client/usage/subscriptionCancellation.js.map +1 -1
  45. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -1
  46. package/dist/client/usage/subscriptionCheckout.js +3 -2
  47. package/dist/client/usage/subscriptionCheckout.js.map +1 -1
  48. package/dist/client/usage/subscriptionLifecycle.d.ts +1 -0
  49. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -1
  50. package/dist/client/usage/subscriptionLifecycle.js +3 -2
  51. package/dist/client/usage/subscriptionLifecycle.js.map +1 -1
  52. package/dist/client/usage/subscriptionProvider.d.ts +2 -0
  53. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -1
  54. package/dist/client/usage/subscriptionProvider.js +9 -2
  55. package/dist/client/usage/subscriptionProvider.js.map +1 -1
  56. package/dist/component/_generated/component.d.ts +21 -0
  57. package/dist/component/_generated/component.d.ts.map +1 -1
  58. package/dist/component/earnings/triggers.d.ts +16 -6
  59. package/dist/component/earnings/triggers.d.ts.map +1 -1
  60. package/dist/component/schema.d.ts +13 -3
  61. package/dist/component/usage/allowance.fixtures.d.ts +4212 -0
  62. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -0
  63. package/dist/component/usage/allowance.fixtures.js +67 -0
  64. package/dist/component/usage/allowance.fixtures.js.map +1 -0
  65. package/dist/component/usageCredits/accounting.fixtures.d.ts +4235 -0
  66. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -0
  67. package/dist/component/usageCredits/accounting.fixtures.js +89 -0
  68. package/dist/component/usageCredits/accounting.fixtures.js.map +1 -0
  69. package/dist/component/usageCredits/helpers.d.ts +7 -0
  70. package/dist/component/usageCredits/helpers.d.ts.map +1 -1
  71. package/dist/component/usageCredits/helpers.js +5 -0
  72. package/dist/component/usageCredits/helpers.js.map +1 -1
  73. package/dist/component/usageCredits/mutations.d.ts +6 -0
  74. package/dist/component/usageCredits/mutations.d.ts.map +1 -1
  75. package/dist/component/usageCredits/mutations.js +70 -7
  76. package/dist/component/usageCredits/mutations.js.map +1 -1
  77. package/dist/component/usageCredits/purchase.d.ts +1 -0
  78. package/dist/component/usageCredits/purchase.d.ts.map +1 -1
  79. package/dist/component/usageCredits/queries.d.ts +10 -0
  80. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  81. package/dist/component/usageCredits/schema.d.ts +24 -4
  82. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  83. package/dist/component/usageCredits/schema.js +4 -0
  84. package/dist/component/usageCredits/schema.js.map +1 -1
  85. package/dist/component/usageSubscriptions/history.d.ts.map +1 -1
  86. package/dist/component/usageSubscriptions/history.js +3 -1
  87. package/dist/component/usageSubscriptions/history.js.map +1 -1
  88. package/dist/component/usageSubscriptions/mutations.d.ts +5 -0
  89. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -1
  90. package/dist/component/usageSubscriptions/mutations.js +19 -0
  91. package/dist/component/usageSubscriptions/mutations.js.map +1 -1
  92. package/dist/component/usageSubscriptions/queries.d.ts +2 -0
  93. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -1
  94. package/dist/component/usageSubscriptions/schema.d.ts +7 -2
  95. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -1
  96. package/dist/component/usageSubscriptions/schema.js +1 -0
  97. package/dist/component/usageSubscriptions/schema.js.map +1 -1
  98. package/dist/react/index.d.ts +12 -0
  99. package/dist/react/index.d.ts.map +1 -1
  100. package/dist/react/index.js +7 -0
  101. package/dist/react/index.js.map +1 -1
  102. package/dist/react/workflows/Pagination.d.ts +1 -0
  103. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  104. package/dist/react/workflows/Pagination.js +1 -0
  105. package/dist/react/workflows/Pagination.js.map +1 -1
  106. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  107. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  108. package/dist/react/workflows/Usage.fixtures.js +79 -0
  109. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  110. package/dist/react/workflows/Usage.types.d.ts +25 -0
  111. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  112. package/dist/react/workflows/Usage.types.js +11 -0
  113. package/dist/react/workflows/Usage.types.js.map +1 -0
  114. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  115. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  116. package/dist/react/workflows/UsageAllowance.js +21 -0
  117. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  118. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  119. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  120. package/dist/react/workflows/UsageBilling.js +40 -0
  121. package/dist/react/workflows/UsageBilling.js.map +1 -0
  122. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  123. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  124. package/dist/react/workflows/UsageCredits.js +25 -0
  125. package/dist/react/workflows/UsageCredits.js.map +1 -0
  126. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  127. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  128. package/dist/react/workflows/UsageHistory.js +74 -0
  129. package/dist/react/workflows/UsageHistory.js.map +1 -0
  130. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  131. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  132. package/dist/react/workflows/UsageSummary.js +54 -0
  133. package/dist/react/workflows/UsageSummary.js.map +1 -0
  134. package/dist/react/workflows/usage-format.d.ts +11 -0
  135. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  136. package/dist/react/workflows/usage-format.js +43 -0
  137. package/dist/react/workflows/usage-format.js.map +1 -0
  138. package/dist/react/workflows/usage-scope.d.ts +5 -0
  139. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  140. package/dist/react/workflows/usage-scope.js +26 -0
  141. package/dist/react/workflows/usage-scope.js.map +1 -0
  142. package/docs/README.md +4 -0
  143. package/docs/react-api.md +4 -0
  144. package/docs/usage-credits.md +6 -1
  145. package/docs/usage-react.md +182 -0
  146. package/docs/usage-security.md +130 -0
  147. package/package.json +3 -1
  148. package/src/client/usage/creditBackingIsolation.test.ts +110 -0
  149. package/src/client/usage/creditCapacity.test.ts +80 -1
  150. package/src/client/usage/creditCapacity.ts +10 -1
  151. package/src/client/usage/creditDelivery.ts +4 -0
  152. package/src/client/usage/creditLifecycle.ts +2 -0
  153. package/src/client/usage/creditNative.ts +5 -0
  154. package/src/client/usage/creditProofBounds.test.ts +187 -0
  155. package/src/client/usage/creditProvider.test.ts +74 -0
  156. package/src/client/usage/creditProvider.ts +2 -0
  157. package/src/client/usage/creditReconciliation.ts +18 -3
  158. package/src/client/usage/creditTransport.fixtures.ts +2 -1
  159. package/src/client/usage/index.ts +3 -0
  160. package/src/client/usage/subscriptionCancellation.ts +3 -2
  161. package/src/client/usage/subscriptionCheckout.ts +7 -2
  162. package/src/client/usage/subscriptionClient.test.ts +60 -1
  163. package/src/client/usage/subscriptionLifecycle.ts +3 -2
  164. package/src/client/usage/subscriptionProvider.ts +27 -3
  165. package/src/component/_generated/component.ts +40 -1
  166. package/src/component/usage/allowance.fixtures.ts +77 -0
  167. package/src/component/usage/allowance.test.ts +3 -66
  168. package/src/component/usage/allowanceBounds.test.ts +79 -0
  169. package/src/component/usage/historyIsolation.test.ts +124 -0
  170. package/src/component/usageCredits/accounting.fixtures.ts +96 -0
  171. package/src/component/usageCredits/accounting.test.ts +176 -82
  172. package/src/component/usageCredits/freshness.test.ts +33 -0
  173. package/src/component/usageCredits/helpers.ts +8 -0
  174. package/src/component/usageCredits/mutations.ts +83 -5
  175. package/src/component/usageCredits/quotas.test.ts +63 -0
  176. package/src/component/usageCredits/schema.ts +10 -0
  177. package/src/component/usageSubscriptions/history.test.ts +57 -0
  178. package/src/component/usageSubscriptions/history.ts +3 -1
  179. package/src/component/usageSubscriptions/mutations.ts +23 -0
  180. package/src/component/usageSubscriptions/schema.ts +1 -0
  181. package/src/react/index.ts +20 -0
  182. package/src/react/workflows/Pagination.tsx +2 -0
  183. package/src/react/workflows/Usage.fixtures.ts +88 -0
  184. package/src/react/workflows/Usage.test.tsx +373 -0
  185. package/src/react/workflows/Usage.types.ts +39 -0
  186. package/src/react/workflows/UsageAllowance.tsx +114 -0
  187. package/src/react/workflows/UsageBilling.tsx +90 -0
  188. package/src/react/workflows/UsageCredits.tsx +112 -0
  189. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  190. package/src/react/workflows/UsageHistory.tsx +154 -0
  191. package/src/react/workflows/UsageSummary.tsx +204 -0
  192. package/src/react/workflows/usage-format.ts +48 -0
  193. package/src/react/workflows/usage-scope.ts +42 -0
@@ -0,0 +1,90 @@
1
+ "use client";
2
+ import { usageSnapshotMatches } from "./usage-scope.js";
3
+ import type { ReactNode } from "react";
4
+ import { useWorkflowResource } from "./useWorkflowResource.js";
5
+ import { UsageSummary } from "./UsageSummary.js";
6
+ import { UsageAllowance } from "./UsageAllowance.js";
7
+ import { UsageCredits } from "./UsageCredits.js";
8
+ import {
9
+ usageViewKey,
10
+ type UsageBillingSnapshot,
11
+ type UsageViewScope,
12
+ } from "./Usage.types.js";
13
+ export type UsageBillingProps = {
14
+ scope: UsageViewScope;
15
+ /** Authenticate and derive the original native binding in the host, including every refresh. */
16
+ load: (scope: UsageViewScope) => Promise<UsageBillingSnapshot>;
17
+ unit?: string;
18
+ className?: string;
19
+ children?: (state: ReturnType<typeof useUsageBilling>) => ReactNode;
20
+ };
21
+ export function useUsageBilling({
22
+ scope,
23
+ load,
24
+ }: Pick<UsageBillingProps, "scope" | "load">) {
25
+ const resource = useWorkflowResource(async () => {
26
+ try {
27
+ const data = await load(scope);
28
+ if (!usageSnapshotMatches(scope, data))
29
+ throw new Error("Observation scope mismatch");
30
+ return data;
31
+ } catch {
32
+ throw new Error("Usage unavailable. Try again.");
33
+ }
34
+ }, usageViewKey(scope));
35
+ return resource;
36
+ }
37
+ /** Shared workflow for component-backed and via-API host adapters. No browser provider credentials. */
38
+ export function UsageBilling(props: UsageBillingProps) {
39
+ return <UsageBillingBody key={usageViewKey(props.scope)} {...props} />;
40
+ }
41
+ function UsageBillingBody(props: UsageBillingProps) {
42
+ const state = useUsageBilling(props);
43
+ if (props.children) return <>{props.children(state)}</>;
44
+ return (
45
+ <section
46
+ data-better-stripe="usage-billing"
47
+ className={props.className}
48
+ aria-label="Metered billing"
49
+ aria-busy={state.isLoading}
50
+ >
51
+ <button type="button" onClick={state.refresh} disabled={state.isLoading}>
52
+ Refresh usage
53
+ </button>
54
+ {state.error && <p role="alert">{state.error}</p>}
55
+ {(state.isLoading || state.error) && state.data && (
56
+ <p role="status">
57
+ Refreshing usage. Displayed observations may be stale.
58
+ </p>
59
+ )}
60
+ <UsageSummary
61
+ scope={props.scope}
62
+ summary={
63
+ state.data?.summary ??
64
+ (state.error
65
+ ? {
66
+ status: "unavailable",
67
+ reason: "read_unavailable",
68
+ retryable: true,
69
+ }
70
+ : undefined)
71
+ }
72
+ provider={state.data?.provider}
73
+ />
74
+ {state.data?.allowance && (
75
+ <UsageAllowance
76
+ allowance={state.data.allowance}
77
+ unit={props.unit ?? "units"}
78
+ />
79
+ )}
80
+ {state.data?.credits && (
81
+ <UsageCredits
82
+ currency={props.scope.currency}
83
+ balance={state.data.credits}
84
+ purchase={state.data.purchase}
85
+ application={state.data.creditApplication}
86
+ />
87
+ )}
88
+ </section>
89
+ );
90
+ }
@@ -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
+ }