@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,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
+ }
@@ -0,0 +1,107 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ configurationFields,
4
+ validateConfiguration,
5
+ } from "./usage-configuration-validation.js";
6
+ import type { UsageConfigurationValue } from "./UsageConfiguration.types.js";
7
+ const original: UsageConfigurationValue = {
8
+ plan: {
9
+ key: "calls",
10
+ version: "v1",
11
+ model: "pay_as_you_go",
12
+ unit: { name: "call", precision: 0 },
13
+ rate: { currency: "usd", unitAmountDecimal: "2" },
14
+ },
15
+ eventName: "calls_v1",
16
+ displayName: "Calls",
17
+ };
18
+ it.each([
19
+ ["precision", "1.5"],
20
+ ["precision", "7"],
21
+ ["key", ""],
22
+ ["version", " "],
23
+ ["unit", ""],
24
+ ["eventName", "has spaces"],
25
+ ["displayName", ""],
26
+ ["currency", "bhd"],
27
+ ["currency", "zzz"],
28
+ ["price", "-1"],
29
+ ["price", "1e2"],
30
+ ["price", "0.000000000000001"],
31
+ ["price", "99999999999999"],
32
+ ["model", "unsupported"],
33
+ ])(
34
+ "rejects invalid %s=%s instead of provisioning or rounding",
35
+ (key, value) => {
36
+ expect(() =>
37
+ validateConfiguration({ ...configurationFields(original), [key]: value }),
38
+ ).toThrow();
39
+ },
40
+ );
41
+ it("rejects rates that fit the shared contract but exceed native scaled decimal precision", () => {
42
+ expect(() =>
43
+ validateConfiguration({
44
+ ...configurationFields(original),
45
+ precision: "6",
46
+ price: "0.000000001",
47
+ }),
48
+ ).toThrow(/precision/);
49
+ });
50
+ it.each(["0", "0.001", "9999999999999999999"])(
51
+ "rejects invalid credit package %s",
52
+ (packageQuantity) => {
53
+ expect(() =>
54
+ validateConfiguration({
55
+ ...configurationFields(original),
56
+ model: "prepaid",
57
+ packageQuantity,
58
+ }),
59
+ ).toThrow(/Paid credits/);
60
+ },
61
+ );
62
+ it("roundtrips fractional zero-decimal currency rates as exact major units", () => {
63
+ const value = {
64
+ ...original,
65
+ plan: {
66
+ ...original.plan,
67
+ rate: { currency: "jpy", unitAmountDecimal: "0.125" },
68
+ },
69
+ };
70
+ const fields = configurationFields(value);
71
+ expect(fields.price).toBe("0.125");
72
+ expect(validateConfiguration(fields)).toEqual(value);
73
+ });
74
+ it("rejects prepaid packages which violate special currency charge increments", () => {
75
+ expect(() =>
76
+ validateConfiguration({
77
+ ...configurationFields(original),
78
+ currency: "isk",
79
+ price: "0.02",
80
+ model: "prepaid",
81
+ packageQuantity: "1",
82
+ }),
83
+ ).toThrow(/Paid credits/);
84
+ });
85
+ it.each(["jpy", "usd", "isk"])(
86
+ "preserves large exact native per-unit rates in %s",
87
+ (currency) => {
88
+ const value = {
89
+ ...original,
90
+ plan: {
91
+ ...original.plan,
92
+ rate: { currency, unitAmountDecimal: "999999999999.125" },
93
+ },
94
+ };
95
+ expect(validateConfiguration(configurationFields(value))).toEqual(value);
96
+ },
97
+ );
98
+ it("allows exact paid packages for fractional rates when consumption uses whole-backed batches", () => {
99
+ const result = validateConfiguration({
100
+ ...configurationFields(original),
101
+ model: "prepaid",
102
+ price: "0.001",
103
+ packageQuantity: "1000",
104
+ });
105
+ expect(result.plan.rate.unitAmountDecimal).toBe("0.1");
106
+ expect(result.creditPackage).toEqual({ quantity: "1000", topUp: "manual" });
107
+ });
@@ -0,0 +1,152 @@
1
+ import {
2
+ chargeAmountToDecimal,
3
+ getChargeCurrencyMetadata,
4
+ } from "../../client/charge-currency.js";
5
+ import {
6
+ defineUsagePlan,
7
+ parseUsageQuantity,
8
+ } from "../../client/usage/contracts.js";
9
+ import { scaledUsageRate } from "../../client/usage/catalogMath.js";
10
+ import { creditCost } from "../../client/usage/creditTerms.js";
11
+ import type {
12
+ UsageConfigurationFields,
13
+ UsageConfigurationValue,
14
+ } from "./UsageConfiguration.types.js";
15
+ function invalid(message: string): never {
16
+ throw new Error(message);
17
+ }
18
+ /** Exact major-currency input to the existing decimal minor-unit rate contract. */
19
+ function minorRate(price: string, currency: string): string {
20
+ const metadata = getChargeCurrencyMetadata(currency);
21
+ if (!metadata) return invalid("Choose a supported charge currency.");
22
+ if (!/^(0|[1-9]\d{0,13})(\.\d{1,14})?$/.test(price))
23
+ return invalid("Enter a nonnegative decimal price without rounding.");
24
+ const [whole, fraction = ""] = price.split(".");
25
+ const padded = fraction.padEnd(metadata.apiDecimals, "0");
26
+ const integer = BigInt(
27
+ whole + padded.slice(0, metadata.apiDecimals),
28
+ ).toString();
29
+ const decimal = padded.slice(metadata.apiDecimals).replace(/0+$/, "");
30
+ return decimal ? `${integer}.${decimal}` : integer;
31
+ }
32
+ export function configurationFields(
33
+ value: UsageConfigurationValue,
34
+ ): UsageConfigurationFields {
35
+ const { plan } = value;
36
+ const metadata = getChargeCurrencyMetadata(plan.rate.currency);
37
+ const [whole, fraction = ""] = plan.rate.unitAmountDecimal.split(".");
38
+ const scale = (metadata?.apiDecimals ?? 0) + fraction.length;
39
+ const digits = (whole + fraction).padStart(scale + 1, "0");
40
+ const integer = BigInt(scale ? digits.slice(0, -scale) : digits).toString();
41
+ const decimal = (scale ? digits.slice(-scale) : "").replace(/0+$/, "");
42
+ const formatted = metadata
43
+ ? integer +
44
+ (decimal ? `.${decimal}` : metadata.displayDecimals ? ".00" : "")
45
+ : "";
46
+ return {
47
+ model: plan.model,
48
+ key: plan.key,
49
+ version: plan.version,
50
+ unit: plan.unit.name,
51
+ precision: String(plan.unit.precision),
52
+ currency: plan.rate.currency,
53
+ price: formatted,
54
+ included:
55
+ plan.model === "included_overage" ? plan.includedQuantity : "1000",
56
+ packageQuantity: value.creditPackage?.quantity ?? "100",
57
+ eventName: value.eventName,
58
+ displayName: value.displayName,
59
+ };
60
+ }
61
+ export function validateConfiguration(
62
+ fields: UsageConfigurationFields,
63
+ meterId?: string,
64
+ ): UsageConfigurationValue {
65
+ const precision = Number(fields.precision);
66
+ if (!/^[0-6]$/.test(fields.precision))
67
+ return invalid("Quantity precision must be between 0 and 6.");
68
+ if (
69
+ !fields.key.trim() ||
70
+ fields.key.length > 100 ||
71
+ !fields.version.trim() ||
72
+ fields.version.length > 100
73
+ )
74
+ return invalid(
75
+ "Enter a plan key and a new version, each at most 100 characters.",
76
+ );
77
+ if (!fields.unit.trim() || fields.unit.length > 100)
78
+ return invalid("Enter a billable unit name of at most 100 characters.");
79
+ if (
80
+ !/^[\w.-]{1,100}$/.test(fields.eventName) ||
81
+ !fields.displayName.trim() ||
82
+ fields.displayName.length > 100
83
+ )
84
+ return invalid(
85
+ "Enter a valid meter event name and display name, each at most 100 characters.",
86
+ );
87
+ const currency = fields.currency.toLowerCase();
88
+ const rate = minorRate(fields.price, currency);
89
+ try {
90
+ scaledUsageRate(rate, precision);
91
+ } catch {
92
+ return invalid(
93
+ "The rate exceeds native decimal precision or amount bounds. Change the rate or quantity precision.",
94
+ );
95
+ }
96
+ const common = {
97
+ key: fields.key,
98
+ version: fields.version,
99
+ unit: { name: fields.unit, precision },
100
+ rate: { currency, unitAmountDecimal: rate },
101
+ };
102
+ if (fields.model === "included_overage") {
103
+ try {
104
+ const included = BigInt(
105
+ parseUsageQuantity(fields.included, precision).scaledQuantity,
106
+ );
107
+ if (included < 1n || included > BigInt(Number.MAX_SAFE_INTEGER))
108
+ throw new Error();
109
+ } catch {
110
+ return invalid(
111
+ "Included units must be positive, exact at the selected precision and within native tier bounds.",
112
+ );
113
+ }
114
+ }
115
+ const plan = defineUsagePlan(
116
+ fields.model === "included_overage"
117
+ ? {
118
+ ...common,
119
+ model: fields.model,
120
+ includedQuantity: fields.included,
121
+ reset: "billing_period",
122
+ }
123
+ : fields.model === "prepaid"
124
+ ? { ...common, model: fields.model, insufficientBalance: "reject" }
125
+ : { ...common, model: fields.model },
126
+ );
127
+ let creditPackage: UsageConfigurationValue["creditPackage"];
128
+ if (plan.model === "prepaid") {
129
+ try {
130
+ const quantity = parseUsageQuantity(fields.packageQuantity, precision);
131
+ if (
132
+ chargeAmountToDecimal(
133
+ creditCost(plan, quantity.scaledQuantity),
134
+ currency,
135
+ ) === null
136
+ )
137
+ throw new Error();
138
+ creditPackage = { quantity: quantity.quantity, topUp: "manual" };
139
+ } catch {
140
+ return invalid(
141
+ "Paid credits require a positive package quantity with whole minor currency backing and supported charge increments, within the native payment bound.",
142
+ );
143
+ }
144
+ }
145
+ return {
146
+ plan,
147
+ eventName: fields.eventName,
148
+ displayName: fields.displayName,
149
+ ...(meterId ? { meterId } : {}),
150
+ ...(creditPackage ? { creditPackage } : {}),
151
+ };
152
+ }
@@ -0,0 +1,48 @@
1
+ import { getChargeCurrencyMetadata } from "../../client/charge-currency.js";
2
+ /** Native metered rates/estimates use minor currency decimals. Preserve fractional cents and large quantities. */
3
+ export function formatUsageEstimate(
4
+ amountDecimal: string,
5
+ currency: string,
6
+ ): string | null {
7
+ const metadata = getChargeCurrencyMetadata(currency);
8
+ if (!metadata || !/^\d+(?:\.\d+)?$/.test(amountDecimal)) return null;
9
+ const [whole, fraction = ""] = amountDecimal.split(".");
10
+ const digits = (whole + fraction).replace(/^0+(?=\d)/, "");
11
+ const scale = metadata.apiDecimals + fraction.length;
12
+ const padded = digits.padStart(scale + 1, "0");
13
+ const major = scale ? padded.slice(0, -scale) : padded;
14
+ let minor = scale ? padded.slice(-scale).replace(/0+$/, "") : "";
15
+ if (metadata.displayDecimals === 0 && minor) return null;
16
+ minor = minor.padEnd(metadata.displayDecimals, "0");
17
+ return `${major}${minor ? "." + minor : ""} ${metadata.currency.toUpperCase()}`;
18
+ }
19
+
20
+ /** Normalize only the visual progress position; keep all visible quantities exact. */
21
+ export function allowanceProgress(value: {
22
+ consumedQuantity: string;
23
+ reservedQuantity: string;
24
+ includedQuantity: string;
25
+ }): number | null {
26
+ const quantities = [
27
+ value.consumedQuantity,
28
+ value.reservedQuantity,
29
+ value.includedQuantity,
30
+ ];
31
+ if (quantities.some((quantity) => !/^\d{1,18}(?:\.\d{1,6})?$/.test(quantity)))
32
+ return null;
33
+ const [consumed, reserved, included] = quantities.map((quantity) => {
34
+ const [whole, fraction = ""] = quantity.split(".");
35
+ return BigInt(whole + fraction.padEnd(6, "0"));
36
+ });
37
+ if (included === 0n) return null;
38
+ const ratio = ((consumed + reserved) * 10000n) / included;
39
+ return Number(ratio > 10000n ? 10000n : ratio);
40
+ }
41
+
42
+ /** Numeric usage periods can exceed Date's supported display range. */
43
+ export function formatUsageTime(seconds: number): string {
44
+ const value = new Date(seconds * 1000);
45
+ return Number.isFinite(value.getTime())
46
+ ? value.toISOString()
47
+ : "Time unavailable";
48
+ }
@@ -0,0 +1,42 @@
1
+ import type { UsageBillingSnapshot, UsageViewScope } from "./Usage.types.js";
2
+ import type { UsageLocalSummary } from "../../client/usage/summary.js";
3
+ export function usageSummaryMatches(
4
+ scope: UsageViewScope,
5
+ value: UsageLocalSummary,
6
+ ) {
7
+ return (
8
+ value.period.start === scope.period.start &&
9
+ value.period.end === scope.period.end &&
10
+ value.groups.every(
11
+ (group) =>
12
+ group.binding.plan.rate.currency.toLowerCase() ===
13
+ scope.currency.toLowerCase() &&
14
+ (group.estimate.status !== "available" ||
15
+ group.estimate.value.currency.toLowerCase() ===
16
+ scope.currency.toLowerCase()),
17
+ )
18
+ );
19
+ }
20
+ export function usageSnapshotMatches(
21
+ scope: UsageViewScope,
22
+ value: UsageBillingSnapshot,
23
+ ) {
24
+ const periodMatches = (period: { start: number; end: number }) =>
25
+ period.start === scope.period.start && period.end === scope.period.end;
26
+ const currencyMatches = (currency: string) =>
27
+ currency.toLowerCase() === scope.currency.toLowerCase();
28
+ return (
29
+ (value.summary.status !== "available" ||
30
+ usageSummaryMatches(scope, value.summary.value)) &&
31
+ (value.provider?.status !== "available" ||
32
+ periodMatches(value.provider.value.period)) &&
33
+ (value.allowance?.status !== "available" ||
34
+ !value.allowance.value ||
35
+ (periodMatches(value.allowance.value.period) &&
36
+ currencyMatches(value.allowance.value.committedEstimate.currency) &&
37
+ currencyMatches(value.allowance.value.projectedEstimate.currency))) &&
38
+ (value.credits?.status !== "available" ||
39
+ currencyMatches(value.credits.value.currency)) &&
40
+ (!value.purchase || currencyMatches(value.purchase.currency))
41
+ );
42
+ }
@@ -0,0 +1,99 @@
1
+ "use client";
2
+ import { useState } from "react";
3
+ import { defineUsagePlan } from "../../client/usage/contracts.js";
4
+ import { useWorkflowAction } from "./useWorkflowAction.js";
5
+ import {
6
+ configurationFields,
7
+ validateConfiguration,
8
+ } from "./usage-configuration-validation.js";
9
+ import type {
10
+ UsageConfigurationProps,
11
+ UsageConfigurationState,
12
+ } from "./UsageConfiguration.types.js";
13
+ /** Shared form lifecycle for component and HTTP adapters. Server authorization is mandatory. */
14
+ export function useUsageConfiguration(
15
+ props: UsageConfigurationProps,
16
+ ): UsageConfigurationState {
17
+ const key = JSON.stringify([props.scope, props.initial, props.meters]);
18
+ const initial = {
19
+ key,
20
+ meterId: props.initial.meterId ?? "",
21
+ fields: configurationFields(props.initial),
22
+ };
23
+ const [state, setState] = useState(initial);
24
+ if (state.key !== key) setState(initial);
25
+ const disabled =
26
+ !props.scope.canConfigure || props.scope.capability !== "issuer_native";
27
+ const immutable = state.meterId !== "";
28
+ const action = useWorkflowAction(async () => {
29
+ if (disabled) throw new Error("Configuration is read-only for this scope.");
30
+ let value = validateConfiguration(state.fields, state.meterId);
31
+ if (immutable) {
32
+ const meter = props.meters.find((item) => item.id === state.meterId);
33
+ if (
34
+ !meter?.active ||
35
+ JSON.stringify(
36
+ validateConfiguration(
37
+ configurationFields(meter.configuration),
38
+ meter.id,
39
+ ),
40
+ ) !== JSON.stringify(value)
41
+ )
42
+ throw new Error(
43
+ "Select an active managed meter with unchanged original terms.",
44
+ );
45
+ // Native intent fingerprints retain the original lexical decimal snapshot.
46
+ value = {
47
+ ...value,
48
+ plan: defineUsagePlan(meter.configuration.plan),
49
+ ...(value.creditPackage
50
+ ? {
51
+ creditPackage: {
52
+ ...value.creditPackage,
53
+ quantity:
54
+ meter.configuration.creditPackage?.quantity ??
55
+ value.creditPackage.quantity,
56
+ },
57
+ }
58
+ : {}),
59
+ };
60
+ }
61
+ try {
62
+ await props.onSave(value);
63
+ } catch {
64
+ throw new Error(
65
+ "Configuration could not be saved. Retry the same terms or ask an administrator to reconcile the operation.",
66
+ );
67
+ }
68
+ return "Configuration version saved. Existing subscriptions keep their original prices.";
69
+ }, key);
70
+ return {
71
+ fields: state.fields,
72
+ meterId: state.meterId,
73
+ immutable,
74
+ disabled,
75
+ isPending: action.isPending,
76
+ error: action.error,
77
+ message: action.result,
78
+ save: action.run,
79
+ setField: (field, value) => {
80
+ if (disabled || immutable || action.isPending) return;
81
+ action.reset();
82
+ setState((current) => ({
83
+ ...current,
84
+ fields: { ...current.fields, [field]: value },
85
+ }));
86
+ },
87
+ selectMeter: (meterId) => {
88
+ if (disabled || action.isPending) return;
89
+ const meter = props.meters.find((item) => item.id === meterId);
90
+ if (meterId && !meter?.active) return;
91
+ action.reset();
92
+ setState({
93
+ key,
94
+ meterId,
95
+ fields: configurationFields(meter?.configuration ?? props.initial),
96
+ });
97
+ },
98
+ };
99
+ }