@meterbox/react 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  CreditBalance,
40
40
  CreditGrantsTable,
41
41
  CreditUtilization,
42
+ InvoiceHistory,
42
43
  UsageChart,
43
44
  CheckoutButton,
44
45
  } from "@meterbox/react";
@@ -62,6 +63,12 @@ whichever interval was selected, ready to hand straight to
62
63
  `<CheckoutButton billingInterval>`. `PricingTable.annualPriceUsd(plan)` is
63
64
  exposed as a static if you need the same total outside the grid.
64
65
 
66
+ Plans from the snapshot (or the customer portal's plan list) also carry
67
+ `usage`, and each card then shows what an AI product's customers actually
68
+ pay for usage: the amounts included each month, what happens past them
69
+ (billed, stopped until next month, or an upgrade), and every model's input
70
+ and output rates per 1M tokens, tier ladders included.
71
+
65
72
  ### `<PlanComparison from to onSwitch? />`
66
73
 
67
74
  Side-by-side comparison of two plan records with added / removed feature
@@ -124,6 +131,13 @@ Table of active grants: source, amount, remaining, expiry, status. Pass
124
131
  Inline SVG line + area chart of credit balance over time, fed by
125
132
  `GET /v1/customer-portal/:id/credits/timeseries`.
126
133
 
134
+ ### `<InvoiceHistory invoices? | baseUrl customerId customerToken />`
135
+
136
+ The invoices the customer received, newest first: date, number, status and
137
+ amount, with a link to download each Stripe invoice's PDF and to its hosted
138
+ page (labelled "Pay" while it's due). Self-fetches
139
+ `GET /v1/customer-portal/:id/invoices` with the customer token.
140
+
127
141
  ### `<UsageChart series valueKey? height? label? />`
128
142
 
129
143
  Tiny inline SVG bar chart of a time series, typically the day-grain rollup
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meterbox/react",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Embeddable React components for Meterbox: pricing tables, subscription preview, credit balance and usage charts. Presentational by default, with data fetched by your backend via @meterbox/node.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://meterbox.ai",
@@ -0,0 +1,172 @@
1
+ /**
2
+ * <InvoiceHistory ... />
3
+ *
4
+ * The invoices a customer received, newest first, each with its PDF and the
5
+ * payment provider's hosted page (where an open invoice can be paid).
6
+ *
7
+ * 1. **Presentational**: <InvoiceHistory invoices={...} />, with the
8
+ * `invoices` array from `GET /v1/customer-portal/:id/invoices`.
9
+ * 2. **Self-fetching** (browser-safe):
10
+ * <InvoiceHistory baseUrl="https://meterbox.ai"
11
+ * customerId="cus_42"
12
+ * customerToken={jwt} />
13
+ * Fetches that endpoint with the customer-scoped JWT.
14
+ */
15
+
16
+ const React = require("react");
17
+
18
+ const styles = {
19
+ card: {
20
+ fontFamily: "system-ui, -apple-system, sans-serif",
21
+ color: "#111",
22
+ border: "1px solid #e5e7eb",
23
+ borderRadius: 12,
24
+ padding: 16,
25
+ background: "#fff",
26
+ display: "grid",
27
+ gap: 12,
28
+ maxWidth: 720,
29
+ },
30
+ title: { fontSize: 14, fontWeight: 700 },
31
+ table: { width: "100%", borderCollapse: "collapse", fontSize: 13 },
32
+ th: {
33
+ textAlign: "left",
34
+ padding: "6px 8px",
35
+ borderBottom: "1px solid #e5e7eb",
36
+ opacity: 0.6,
37
+ fontWeight: 600,
38
+ },
39
+ td: { padding: "6px 8px", borderBottom: "1px solid #f3f4f6" },
40
+ links: { display: "flex", gap: 10 },
41
+ link: { color: "#5045e8", textDecoration: "none", fontWeight: 600 },
42
+ muted: { opacity: 0.6 },
43
+ };
44
+
45
+ const STATUS = { open: "Due", paid: "Paid", void: "Void", uncollectible: "Uncollectible" };
46
+
47
+ // Amounts arrive in the currency's minor unit (cents for USD, yen for JPY).
48
+ function money(minor, currency) {
49
+ const code = String(currency || "usd").toUpperCase();
50
+ try {
51
+ const format = new Intl.NumberFormat(undefined, { style: "currency", currency: code });
52
+ const digits = format.resolvedOptions().maximumFractionDigits;
53
+ return format.format(minor / 10 ** digits);
54
+ } catch (_) {
55
+ return `${code} ${minor}`;
56
+ }
57
+ }
58
+
59
+ async function fetchInvoices({ baseUrl, customerId, customerToken, fetchImpl }) {
60
+ const url = `${String(baseUrl).replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
61
+ customerId,
62
+ )}/invoices`;
63
+ const res = await fetchImpl(url, {
64
+ method: "GET",
65
+ headers: { Authorization: `Bearer ${customerToken}` },
66
+ });
67
+ const json = await res.json();
68
+ if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
69
+ return json.invoices || [];
70
+ }
71
+
72
+ function InvoiceHistory({ invoices, baseUrl, customerId, customerToken, fetch: fetchImpl }) {
73
+ const selfFetch = !invoices && baseUrl && customerId && customerToken;
74
+ const [fetched, setFetched] = React.useState(null);
75
+ const [error, setError] = React.useState(null);
76
+
77
+ React.useEffect(() => {
78
+ if (!selfFetch) return undefined;
79
+ let cancelled = false;
80
+ setError(null);
81
+ fetchInvoices({ baseUrl, customerId, customerToken, fetchImpl: fetchImpl || globalThis.fetch })
82
+ .then((list) => {
83
+ if (!cancelled) setFetched(list);
84
+ })
85
+ .catch((err) => {
86
+ if (!cancelled) setError(err.message || "Could not load invoices.");
87
+ });
88
+ return () => {
89
+ cancelled = true;
90
+ };
91
+ }, [selfFetch, baseUrl, customerId, customerToken, fetchImpl]);
92
+
93
+ const list = invoices || fetched;
94
+ let body;
95
+ if (error) {
96
+ body = React.createElement("span", { role: "alert", style: { color: "#dc2626" } }, error);
97
+ } else if (!list) {
98
+ body = React.createElement("span", { style: styles.muted }, "Loading invoices…");
99
+ } else if (list.length === 0) {
100
+ body = React.createElement("span", { style: styles.muted }, "No invoices yet.");
101
+ } else {
102
+ body = React.createElement(
103
+ "table",
104
+ { style: styles.table },
105
+ React.createElement(
106
+ "thead",
107
+ null,
108
+ React.createElement(
109
+ "tr",
110
+ null,
111
+ ["Date", "Invoice", "Status", "Amount", ""].map((h) =>
112
+ React.createElement("th", { key: h || "links", style: styles.th }, h),
113
+ ),
114
+ ),
115
+ ),
116
+ React.createElement(
117
+ "tbody",
118
+ null,
119
+ list.map((inv) =>
120
+ React.createElement(
121
+ "tr",
122
+ { key: inv.id },
123
+ React.createElement("td", { style: styles.td }, String(inv.created_at).slice(0, 10)),
124
+ React.createElement("td", { style: styles.td }, inv.number || inv.id),
125
+ React.createElement("td", { style: styles.td }, STATUS[inv.status] || inv.status),
126
+ React.createElement("td", { style: styles.td }, money(inv.amount_due, inv.currency)),
127
+ React.createElement(
128
+ "td",
129
+ { style: styles.td },
130
+ React.createElement(
131
+ "span",
132
+ { style: styles.links },
133
+ inv.pdf_url &&
134
+ React.createElement(
135
+ "a",
136
+ {
137
+ href: inv.pdf_url,
138
+ target: "_blank",
139
+ rel: "noopener noreferrer",
140
+ style: styles.link,
141
+ "aria-label": `Download PDF of ${inv.number || inv.id}`,
142
+ },
143
+ "PDF",
144
+ ),
145
+ inv.hosted_invoice_url &&
146
+ React.createElement(
147
+ "a",
148
+ {
149
+ href: inv.hosted_invoice_url,
150
+ target: "_blank",
151
+ rel: "noopener noreferrer",
152
+ style: styles.link,
153
+ },
154
+ inv.status === "open" ? "Pay" : "View",
155
+ ),
156
+ ),
157
+ ),
158
+ ),
159
+ ),
160
+ ),
161
+ );
162
+ }
163
+
164
+ return React.createElement(
165
+ "div",
166
+ { className: "meterbox-invoice-history", style: styles.card },
167
+ React.createElement("div", { style: styles.title }, "Invoices"),
168
+ body,
169
+ );
170
+ }
171
+
172
+ module.exports = InvoiceHistory;
@@ -21,6 +21,11 @@
21
21
  * total divided back into a misleading "$X/mo" figure — a shopper who
22
22
  * commits annually is billed once for the year, not monthly.
23
23
  *
24
+ * A plan with `usage` (the pricing snapshot and the customer portal's plan
25
+ * list carry it) also shows its included amounts, what happens past them,
26
+ * and its models' input and output rates per 1M tokens, tier ladders
27
+ * included.
28
+ *
24
29
  * Pure presentational + inline styles — no CSS pipeline required from the
25
30
  * tenant.
26
31
  */
@@ -94,6 +99,13 @@ const styles = {
94
99
  cursor: "pointer",
95
100
  },
96
101
  ctaCurrent: { background: "#e5e7eb", color: "#111", cursor: "default" },
102
+ usage: {
103
+ display: "grid",
104
+ gap: 4,
105
+ fontSize: 12,
106
+ borderTop: "1px solid #e5e7eb",
107
+ paddingTop: 10,
108
+ },
97
109
  badge: {
98
110
  fontSize: 11,
99
111
  fontWeight: 600,
@@ -118,6 +130,64 @@ function formatPrice(amount, currency = "USD") {
118
130
  }
119
131
  }
120
132
 
133
+ const PAST_INCLUDED = {
134
+ billed: "Past that, per 1M tokens:",
135
+ blocked: "Usage stops there until next month.",
136
+ upgrade: "Past that, your plan is upgraded automatically.",
137
+ };
138
+
139
+ function compact(n) {
140
+ return new Intl.NumberFormat("en", { notation: "compact" }).format(n);
141
+ }
142
+
143
+ function rate(perUnit) {
144
+ const v = Math.round(perUnit * 1e6) / 1e6;
145
+ return `$${v > 0 && v < 0.01 ? v.toPrecision(2) : v.toFixed(2)}`;
146
+ }
147
+
148
+ /** "$3.00 to 10M then $2.50" — a tier ladder priced per 1,000 units × `scale`. */
149
+ function ladderText(tiers, scale) {
150
+ return tiers
151
+ .map((t) => rate(t.per_1k * scale) + (t.up_to == null ? "" : ` to ${compact(t.up_to)}`))
152
+ .join(" then ");
153
+ }
154
+
155
+ /** Included amounts, what happens past them, and the models' rates. */
156
+ function PlanUsage({ usage }) {
157
+ const { included, overage, models, api_call_overage_tiers: callTiers } = usage;
158
+ const parts = [
159
+ [included.input_tokens, "input tokens"],
160
+ [included.output_tokens, "output tokens"],
161
+ [included.api_calls, "API calls"],
162
+ ]
163
+ .filter(([n]) => n > 0)
164
+ .map(([n, label]) => `${compact(n)} ${label}`);
165
+ const billed = overage === "billed";
166
+ return React.createElement(
167
+ "div",
168
+ { className: "meterbox-plan-usage", style: styles.usage },
169
+ parts.length > 0 && React.createElement("div", null, `Includes ${parts.join(", ")} a month`),
170
+ React.createElement(
171
+ "div",
172
+ { style: { opacity: 0.75 } },
173
+ billed && parts.length === 0 ? "Per 1M tokens:" : PAST_INCLUDED[overage],
174
+ ),
175
+ billed
176
+ ? models.map((m) =>
177
+ React.createElement(
178
+ "div",
179
+ { key: m.id },
180
+ `${m.name}: ${ladderText(m.input_tiers, 1000)} in, ${ladderText(m.output_tiers, 1000)} out`,
181
+ ),
182
+ )
183
+ : models.length > 0 &&
184
+ React.createElement("div", null, `Models: ${models.map((m) => m.name).join(", ")}`),
185
+ billed &&
186
+ callTiers &&
187
+ React.createElement("div", null, `API calls: ${ladderText(callTiers, 1)} per 1K`),
188
+ );
189
+ }
190
+
121
191
  /** A plan from the public snapshot, in the shape the table renders. */
122
192
  function fromSnapshot(p) {
123
193
  return {
@@ -128,6 +198,7 @@ function fromSnapshot(p) {
128
198
  stripe_price_monthly_usd: p.price ? p.price.monthly_usd : 0,
129
199
  annual_free_months: p.annual_free_months == null ? null : p.annual_free_months,
130
200
  localized_prices: p.localized_prices || [],
201
+ usage: p.usage || null,
131
202
  };
132
203
  }
133
204
 
@@ -257,6 +328,7 @@ function PricingTable({
257
328
  React.createElement("li", { key: f }, `• ${f.replace(/_/g, " ")}`),
258
329
  ),
259
330
  ),
331
+ plan.usage && React.createElement(PlanUsage, { usage: plan.usage }),
260
332
  React.createElement(
261
333
  "button",
262
334
  {
package/src/index.js CHANGED
@@ -6,8 +6,8 @@
6
6
  * `@meterbox/node` and passes it as props. No admin key in the
7
7
  * browser bundle.
8
8
  * • **Self-fetching** — `SubscriptionPreview`, `PlanChangeCard`,
9
- * `CreditBalance`, `CreditGrantsTable`, `CreditUtilization`, and
10
- * `OutcomeHistory` can fetch their own data from the
9
+ * `CreditBalance`, `CreditGrantsTable`, `CreditUtilization`,
10
+ * `OutcomeHistory` and `InvoiceHistory` can fetch their own data from the
11
11
  * `/v1/customer-portal/*` endpoints using a short-lived customer-scoped
12
12
  * JWT minted server-side (`POST /v1/tokens/:id`).
13
13
  *
@@ -26,6 +26,7 @@ const CreditBalance = require("./CreditBalance");
26
26
  const CreditGrantsTable = require("./CreditGrantsTable");
27
27
  const CreditUtilization = require("./CreditUtilization");
28
28
  const OutcomeHistory = require("./OutcomeHistory");
29
+ const InvoiceHistory = require("./InvoiceHistory");
29
30
  const UsageChart = require("./UsageChart");
30
31
  const Paywall = require("./Paywall");
31
32
  const UsageProgress = require("./UsageProgress");
@@ -41,6 +42,7 @@ module.exports = {
41
42
  CreditGrantsTable,
42
43
  CreditUtilization,
43
44
  OutcomeHistory,
45
+ InvoiceHistory,
44
46
  UsageChart,
45
47
  Paywall,
46
48
  UsageProgress,