@fantastic.dev/better-stripe 0.61.0 → 0.63.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 (87) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +6 -2
  3. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  4. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  5. package/dist/client/paymentSource/resolver.d.ts +1 -0
  6. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  7. package/dist/client/paymentSource/resolver.js +11 -2
  8. package/dist/client/paymentSource/resolver.js.map +1 -1
  9. package/dist/client/paymentSource/zeroTierLines.d.ts +4 -0
  10. package/dist/client/paymentSource/zeroTierLines.d.ts.map +1 -0
  11. package/dist/client/paymentSource/zeroTierLines.js +35 -0
  12. package/dist/client/paymentSource/zeroTierLines.js.map +1 -0
  13. package/dist/client/usage/configuration.d.ts +13 -0
  14. package/dist/client/usage/configuration.d.ts.map +1 -0
  15. package/dist/client/usage/configuration.js +2 -0
  16. package/dist/client/usage/configuration.js.map +1 -0
  17. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  18. package/dist/client/usage/deliveryProvider.js +16 -0
  19. package/dist/client/usage/deliveryProvider.js.map +1 -1
  20. package/dist/client/usage/index.d.ts +2 -0
  21. package/dist/client/usage/index.d.ts.map +1 -1
  22. package/dist/client/usage/invoiceSale.d.ts.map +1 -1
  23. package/dist/client/usage/invoiceSale.js +15 -2
  24. package/dist/client/usage/invoiceSale.js.map +1 -1
  25. package/dist/client/usage/observationClient.d.ts +2 -2
  26. package/dist/client/usage/observationClient.d.ts.map +1 -1
  27. package/dist/client/usage/views.d.ts +24 -0
  28. package/dist/client/usage/views.d.ts.map +1 -0
  29. package/dist/client/usage/views.js +2 -0
  30. package/dist/client/usage/views.js.map +1 -0
  31. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  32. package/dist/component/payoutRelease/queries.d.ts +2 -2
  33. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  34. package/dist/react/index.d.ts +5 -0
  35. package/dist/react/index.d.ts.map +1 -1
  36. package/dist/react/index.js +3 -0
  37. package/dist/react/index.js.map +1 -1
  38. package/dist/react/workflows/Usage.types.d.ts +2 -23
  39. package/dist/react/workflows/Usage.types.d.ts.map +1 -1
  40. package/dist/react/workflows/Usage.types.js.map +1 -1
  41. package/dist/react/workflows/UsageConfiguration.d.ts +4 -0
  42. package/dist/react/workflows/UsageConfiguration.d.ts.map +1 -0
  43. package/dist/react/workflows/UsageConfiguration.js +19 -0
  44. package/dist/react/workflows/UsageConfiguration.js.map +1 -0
  45. package/dist/react/workflows/UsageConfiguration.types.d.ts +57 -0
  46. package/dist/react/workflows/UsageConfiguration.types.d.ts.map +1 -0
  47. package/dist/react/workflows/UsageConfiguration.types.js +2 -0
  48. package/dist/react/workflows/UsageConfiguration.types.js.map +1 -0
  49. package/dist/react/workflows/UsagePriceRow.d.ts +26 -0
  50. package/dist/react/workflows/UsagePriceRow.d.ts.map +1 -0
  51. package/dist/react/workflows/UsagePriceRow.js +40 -0
  52. package/dist/react/workflows/UsagePriceRow.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/useUsageConfiguration.d.ts +4 -0
  58. package/dist/react/workflows/useUsageConfiguration.d.ts.map +1 -0
  59. package/dist/react/workflows/useUsageConfiguration.js +84 -0
  60. package/dist/react/workflows/useUsageConfiguration.js.map +1 -0
  61. package/docs/README.md +4 -0
  62. package/docs/react-api.md +2 -0
  63. package/docs/usage-configuration.md +154 -0
  64. package/docs/usage-delivery.md +4 -0
  65. package/docs/usage-example.md +246 -0
  66. package/docs/usage-react.md +4 -0
  67. package/docs/usage-settlement.md +8 -3
  68. package/package.json +4 -2
  69. package/src/client/paymentSource/resolver.ts +14 -2
  70. package/src/client/paymentSource/zeroTierLines.ts +42 -0
  71. package/src/client/usage/configuration.ts +9 -0
  72. package/src/client/usage/deliveryProvider.test.ts +77 -37
  73. package/src/client/usage/deliveryProvider.ts +19 -0
  74. package/src/client/usage/index.ts +4 -0
  75. package/src/client/usage/invoiceSale.test.ts +68 -0
  76. package/src/client/usage/invoiceSale.ts +20 -2
  77. package/src/client/usage/views.ts +23 -0
  78. package/src/react/index.ts +16 -0
  79. package/src/react/workflows/Usage.types.ts +5 -29
  80. package/src/react/workflows/UsageConfiguration.test.tsx +393 -0
  81. package/src/react/workflows/UsageConfiguration.tsx +135 -0
  82. package/src/react/workflows/UsageConfiguration.types.ts +59 -0
  83. package/src/react/workflows/UsagePriceRow.test.tsx +140 -0
  84. package/src/react/workflows/UsagePriceRow.tsx +109 -0
  85. package/src/react/workflows/usage-configuration-validation.test.ts +107 -0
  86. package/src/react/workflows/usage-configuration-validation.ts +152 -0
  87. package/src/react/workflows/useUsageConfiguration.ts +99 -0
@@ -0,0 +1,140 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, render, screen } from "@testing-library/react";
3
+ import { afterEach, expect, it } from "vitest";
4
+ import * as ui from "../index.js";
5
+ import type { UsagePriceBinding } from "../../client/usage/catalogRead.js";
6
+ afterEach(cleanup);
7
+ const price: UsagePriceBinding = {
8
+ pricingMode: "metered",
9
+ stripePriceId: "price_usage",
10
+ stripeProductId: "prod_usage",
11
+ meterId: "mtr_usage",
12
+ active: true,
13
+ currency: "usd",
14
+ billingScheme: "per_unit",
15
+ unitAmountDecimal: "0.00125",
16
+ tiers: [],
17
+ interval: "month",
18
+ plan: {
19
+ key: "calls",
20
+ version: "v1",
21
+ model: "pay_as_you_go",
22
+ unit: { name: "call", precision: 2 },
23
+ rate: { currency: "usd", unitAmountDecimal: "0.125" },
24
+ },
25
+ };
26
+ it("reuses ordinary PriceCard formatting for fixed prices", () => {
27
+ expect(ui.UsagePriceRow).toBeTypeOf("function");
28
+ render(
29
+ <ui.UsagePriceRow
30
+ value={{
31
+ kind: "fixed",
32
+ price: {
33
+ stripePriceId: "price_fixed",
34
+ unitAmount: 900,
35
+ currency: "usd",
36
+ type: "recurring",
37
+ interval: "month",
38
+ active: true,
39
+ },
40
+ }}
41
+ />,
42
+ );
43
+ expect(screen.getByText("Fixed price")).toBeTruthy();
44
+ expect(screen.getByText("$9.00/month")).toBeTruthy();
45
+ });
46
+ it("shows exact whole-unit metered rates and the original version instead of treating null amount as free", () => {
47
+ expect(ui.UsagePriceRow).toBeTypeOf("function");
48
+ render(<ui.UsagePriceRow value={{ kind: "metered", price }} />);
49
+ expect(screen.getByText(/0.00125 USD per call/)).toBeTruthy();
50
+ expect(screen.getByText(/v1/)).toBeTruthy();
51
+ expect(screen.getByText(/sum aggregation/)).toBeTruthy();
52
+ });
53
+ it("labels supported managed graduated tiers separately from other tiers and transformations", () => {
54
+ expect(ui.UsagePriceRow).toBeTypeOf("function");
55
+ const { rerender } = render(
56
+ <ui.UsagePriceRow
57
+ value={{
58
+ kind: "metered",
59
+ price: {
60
+ ...price,
61
+ billingScheme: "tiered",
62
+ plan: {
63
+ ...price.plan,
64
+ model: "included_overage",
65
+ includedQuantity: "100",
66
+ reset: "billing_period",
67
+ },
68
+ },
69
+ }}
70
+ />,
71
+ );
72
+ expect(screen.getByText(/100 included/)).toBeTruthy();
73
+ rerender(
74
+ <ui.UsagePriceRow value={{ kind: "unsupported", reason: "tiered" }} />,
75
+ );
76
+ expect(screen.getByText(/Unsupported tiered pricing/)).toBeTruthy();
77
+ expect(screen.queryByText(/0.00/)).toBeNull();
78
+ rerender(
79
+ <ui.UsagePriceRow value={{ kind: "unsupported", reason: "transformed" }} />,
80
+ );
81
+ expect(screen.getByText(/Unsupported transformed pricing/)).toBeTruthy();
82
+ });
83
+ it("does not let legacy fixed rows misrepresent metered, tiered, transformed or missing amounts", () => {
84
+ expect(ui.UsagePriceRow).toBeTypeOf("function");
85
+ const fixed = {
86
+ stripePriceId: "price_bad",
87
+ currency: "usd",
88
+ type: "recurring",
89
+ interval: "month",
90
+ active: true,
91
+ unitAmount: 0,
92
+ };
93
+ const { rerender } = render(
94
+ <ui.UsagePriceRow
95
+ value={{ kind: "fixed", price: { ...fixed, usageType: "metered" } }}
96
+ />,
97
+ );
98
+ expect(screen.getByText(/Unsupported pricing terms/)).toBeTruthy();
99
+ rerender(
100
+ <ui.UsagePriceRow
101
+ value={{ kind: "fixed", price: { ...fixed, billingScheme: "tiered" } }}
102
+ />,
103
+ );
104
+ expect(screen.queryByText("$0.00/month")).toBeNull();
105
+ rerender(
106
+ <ui.UsagePriceRow
107
+ value={{
108
+ kind: "fixed",
109
+ price: { ...fixed, transformQuantity: { divideBy: 100 } },
110
+ }}
111
+ />,
112
+ );
113
+ expect(screen.queryByText("$0.00/month")).toBeNull();
114
+ rerender(
115
+ <ui.UsagePriceRow
116
+ value={{ kind: "fixed", price: { ...fixed, unitAmount: null } }}
117
+ />,
118
+ );
119
+ expect(screen.queryByText("$0.00/month")).toBeNull();
120
+ });
121
+ it("keeps unsupported fixed charge currency and increments unavailable without crashing", () => {
122
+ expect(ui.UsagePriceRow).toBeTypeOf("function");
123
+ const price = {
124
+ stripePriceId: "price_bad",
125
+ unitAmount: 1,
126
+ currency: "bhd",
127
+ type: "one_time",
128
+ active: true,
129
+ };
130
+ const { rerender } = render(
131
+ <ui.UsagePriceRow value={{ kind: "fixed", price }} />,
132
+ );
133
+ expect(screen.getByText(/Unsupported pricing terms/)).toBeTruthy();
134
+ rerender(
135
+ <ui.UsagePriceRow
136
+ value={{ kind: "fixed", price: { ...price, currency: "isk" } }}
137
+ />,
138
+ );
139
+ expect(screen.getByText(/Unsupported pricing terms/)).toBeTruthy();
140
+ });
@@ -0,0 +1,109 @@
1
+ "use client";
2
+ import type { ReactNode } from "react";
3
+ import type { UsagePriceBinding } from "../../client/usage/catalogRead.js";
4
+ import { PriceCard, type PriceCardPrice } from "../components/PriceCard.js";
5
+ import { chargeAmountToDecimal } from "../../client/charge-currency.js";
6
+ import { formatUsageEstimate } from "./usage-format.js";
7
+ export type UsageCatalogPrice =
8
+ | {
9
+ kind: "fixed";
10
+ price: PriceCardPrice & {
11
+ usageType?: string;
12
+ billingScheme?: string;
13
+ transformQuantity?: unknown;
14
+ };
15
+ }
16
+ | { kind: "metered"; price: UsagePriceBinding }
17
+ | { kind: "unsupported"; reason: "tiered" | "transformed" | "other" };
18
+ export type UsagePriceRowProps = {
19
+ value: UsageCatalogPrice;
20
+ productName?: string;
21
+ className?: string;
22
+ children?: (value: UsageCatalogPrice) => ReactNode;
23
+ };
24
+ /** Read-only catalog row. Only managed metered bindings carry original exact terms. */
25
+ export function UsagePriceRow({
26
+ value,
27
+ className,
28
+ productName,
29
+ children,
30
+ }: UsagePriceRowProps) {
31
+ if (children) return <>{children(value)}</>;
32
+ let contents: ReactNode;
33
+ if (value.kind === "fixed") {
34
+ const price = value.price;
35
+ const supported =
36
+ price.unitAmount != null &&
37
+ Number.isSafeInteger(price.unitAmount) &&
38
+ price.unitAmount >= 0 &&
39
+ chargeAmountToDecimal(price.unitAmount, price.currency) !== null &&
40
+ price.usageType !== "metered" &&
41
+ (!price.billingScheme || price.billingScheme === "per_unit") &&
42
+ price.transformQuantity == null;
43
+ contents = supported ? (
44
+ <>
45
+ <p>Fixed price</p>
46
+ <PriceCard price={price}>
47
+ {({ formattedPrice }) => <p>{formattedPrice}</p>}
48
+ </PriceCard>
49
+ </>
50
+ ) : (
51
+ <p>
52
+ Unsupported pricing terms. Read the original provider terms before
53
+ configuration.
54
+ </p>
55
+ );
56
+ } else if (value.kind === "unsupported") {
57
+ contents = (
58
+ <p>
59
+ {value.reason === "tiered"
60
+ ? "Unsupported tiered pricing"
61
+ : value.reason === "transformed"
62
+ ? "Unsupported transformed pricing"
63
+ : "Unsupported pricing terms"}
64
+ . No fixed or zero price is inferred.
65
+ </p>
66
+ );
67
+ } else {
68
+ const { plan } = value.price;
69
+ const amount = formatUsageEstimate(
70
+ plan.rate.unitAmountDecimal,
71
+ plan.rate.currency,
72
+ );
73
+ contents = (
74
+ <>
75
+ <p>
76
+ {plan.model === "included_overage"
77
+ ? "Included monthly units plus overages"
78
+ : plan.model === "prepaid"
79
+ ? "Prepaid paid credits"
80
+ : "Pay as you go"}
81
+ </p>
82
+ <p>Version {plan.version}. Monthly billing, sum aggregation.</p>
83
+ <p>
84
+ {amount ? `${amount} per ${plan.unit.name}` : "Rate unavailable"}.
85
+ Quantity precision {plan.unit.precision}.
86
+ </p>
87
+ {plan.model === "included_overage" && (
88
+ <p>
89
+ {plan.includedQuantity} included per billing period. Graduated free
90
+ tier, then overages.
91
+ </p>
92
+ )}
93
+ {plan.model === "prepaid" && (
94
+ <p>
95
+ Payment-backed issuer credits. Consumption is not a second cash
96
+ collection.
97
+ </p>
98
+ )}
99
+ <p>{value.price.active ? "Active" : "Inactive"} immutable price</p>
100
+ </>
101
+ );
102
+ }
103
+ return (
104
+ <div className={className} data-better-stripe="usage-price-row">
105
+ {productName && <h3>{productName}</h3>}
106
+ {contents}
107
+ </div>
108
+ );
109
+ }
@@ -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,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
+ }