@meterbox/react 0.1.2 → 0.1.4

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,12 +39,13 @@ import {
39
39
  CreditBalance,
40
40
  CreditGrantsTable,
41
41
  CreditUtilization,
42
+ InvoiceHistory,
42
43
  UsageChart,
43
44
  CheckoutButton,
44
45
  } from "@meterbox/react";
45
46
  ```
46
47
 
47
- ### `<PricingTable plans currentPlanId? currency? onSelect? />` or `<PricingTable baseUrl publishableKey … />`
48
+ ### `<PricingTable plans currentPlanId? currency? onSelect? customerEmail? />` or `<PricingTable baseUrl publishableKey … />`
48
49
 
49
50
  On a public page with no backend of its own, pass `baseUrl` and a
50
51
  publishable key (`mb_pub_...`, from Settings > API keys) instead of `plans`.
@@ -62,6 +63,11 @@ 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
+ From the snapshot, the featured plan is highlighted with its badge ("Most
67
+ popular"), a plan's free trial shows as "14-day free trial", and, without
68
+ `onSelect`, each plan's button is its own call-to-action link (e.g. Enterprise
69
+ to a contact page); `customerEmail` fills `{CUSTOMER_EMAIL}` in it.
70
+
65
71
  Plans from the snapshot (or the customer portal's plan list) also carry
66
72
  `usage`, and each card then shows what an AI product's customers actually
67
73
  pay for usage: the amounts included each month, what happens past them
@@ -130,6 +136,13 @@ Table of active grants: source, amount, remaining, expiry, status. Pass
130
136
  Inline SVG line + area chart of credit balance over time, fed by
131
137
  `GET /v1/customer-portal/:id/credits/timeseries`.
132
138
 
139
+ ### `<InvoiceHistory invoices? | baseUrl customerId customerToken />`
140
+
141
+ The invoices the customer received, newest first: date, number, status and
142
+ amount, with a link to download each Stripe invoice's PDF and to its hosted
143
+ page (labelled "Pay" while it's due). Self-fetches
144
+ `GET /v1/customer-portal/:id/invoices` with the customer token.
145
+
133
146
  ### `<UsageChart series valueKey? height? label? />`
134
147
 
135
148
  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.2",
3
+ "version": "0.1.4",
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;
@@ -26,6 +26,11 @@
26
26
  * and its models' input and output rates per 1M tokens, tier ladders
27
27
  * included.
28
28
  *
29
+ * From the snapshot, the featured plan is highlighted with its `badge`, a
30
+ * plan's `trial_days` shows as "14-day free trial", and without `onSelect`
31
+ * each plan's button is its call-to-action link (`customerEmail` fills
32
+ * {CUSTOMER_EMAIL} in it).
33
+ *
29
34
  * Pure presentational + inline styles — no CSS pipeline required from the
30
35
  * tenant.
31
36
  */
@@ -99,6 +104,7 @@ const styles = {
99
104
  cursor: "pointer",
100
105
  },
101
106
  ctaCurrent: { background: "#e5e7eb", color: "#111", cursor: "default" },
107
+ trial: { fontSize: 13, fontWeight: 600 },
102
108
  usage: {
103
109
  display: "grid",
104
110
  gap: 4,
@@ -188,6 +194,19 @@ function PlanUsage({ usage }) {
188
194
  );
189
195
  }
190
196
 
197
+ // A plan's call-to-action link from the snapshot, {CUSTOMER_EMAIL} filled in;
198
+ // null unless it's an http(s), mailto: or tel: link.
199
+ function ctaLink(plan, customerEmail) {
200
+ if (!plan.cta?.url) return null;
201
+ const email = encodeURIComponent(customerEmail || "");
202
+ const url = plan.cta.url
203
+ .split("{CUSTOMER_EMAIL}")
204
+ .join(email)
205
+ .split("%7BCUSTOMER_EMAIL%7D")
206
+ .join(email);
207
+ return /^(https?:|mailto:|tel:)/i.test(url) ? { url, label: plan.cta.label } : null;
208
+ }
209
+
191
210
  /** A plan from the public snapshot, in the shape the table renders. */
192
211
  function fromSnapshot(p) {
193
212
  return {
@@ -199,6 +218,10 @@ function fromSnapshot(p) {
199
218
  annual_free_months: p.annual_free_months == null ? null : p.annual_free_months,
200
219
  localized_prices: p.localized_prices || [],
201
220
  usage: p.usage || null,
221
+ highlight: !!p.highlight,
222
+ badge: p.badge || null,
223
+ trial_days: p.trial_days || null,
224
+ cta: p.cta || null,
202
225
  };
203
226
  }
204
227
 
@@ -217,6 +240,7 @@ function PricingTable({
217
240
  currentPlanId,
218
241
  currency = "USD",
219
242
  onSelect,
243
+ customerEmail,
220
244
  baseUrl,
221
245
  publishableKey,
222
246
  fetch: fetchImpl,
@@ -289,13 +313,18 @@ function PricingTable({
289
313
  // annual_free_months always shows its monthly price, even while the
290
314
  // toggle above is set to "Annual" for its siblings.
291
315
  const annual = billingInterval === "annual" ? annualPriceUsd(plan) : null;
316
+ const link = !onSelect && !isCurrent ? ctaLink(plan, customerEmail) : null;
292
317
  return React.createElement(
293
318
  "div",
294
319
  {
295
320
  key: plan.id,
296
- style: isCurrent ? { ...styles.card, ...styles.cardCurrent } : styles.card,
321
+ style:
322
+ isCurrent || plan.highlight ? { ...styles.card, ...styles.cardCurrent } : styles.card,
297
323
  },
298
324
  isCurrent && React.createElement("span", { style: styles.badge }, "Current"),
325
+ !isCurrent &&
326
+ plan.badge &&
327
+ React.createElement("span", { style: styles.badge }, plan.badge),
299
328
  React.createElement("h3", { style: styles.name }, plan.name || plan.id),
300
329
  plan.description &&
301
330
  React.createElement(
@@ -319,6 +348,12 @@ function PricingTable({
319
348
  annual != null ? "billed annually" : "/ month",
320
349
  ),
321
350
  ),
351
+ plan.trial_days > 0 &&
352
+ React.createElement(
353
+ "div",
354
+ { style: styles.trial },
355
+ `${plan.trial_days}-day free trial`,
356
+ ),
322
357
  Array.isArray(plan.features) &&
323
358
  plan.features.length > 0 &&
324
359
  React.createElement(
@@ -329,19 +364,28 @@ function PricingTable({
329
364
  ),
330
365
  ),
331
366
  plan.usage && React.createElement(PlanUsage, { usage: plan.usage }),
332
- React.createElement(
333
- "button",
334
- {
335
- type: "button",
336
- style: isCurrent ? { ...styles.cta, ...styles.ctaCurrent } : styles.cta,
337
- disabled: isCurrent,
338
- onClick: () => (onSelect ? onSelect(plan, billingInterval) : undefined),
339
- "aria-label": isCurrent
340
- ? `Currently on ${plan.name || plan.id}`
341
- : `Choose ${plan.name || plan.id}`,
342
- },
343
- isCurrent ? "Current plan" : "Choose plan",
344
- ),
367
+ link
368
+ ? React.createElement(
369
+ "a",
370
+ {
371
+ href: link.url,
372
+ style: { ...styles.cta, textAlign: "center", textDecoration: "none" },
373
+ },
374
+ link.label,
375
+ )
376
+ : React.createElement(
377
+ "button",
378
+ {
379
+ type: "button",
380
+ style: isCurrent ? { ...styles.cta, ...styles.ctaCurrent } : styles.cta,
381
+ disabled: isCurrent,
382
+ onClick: () => (onSelect ? onSelect(plan, billingInterval) : undefined),
383
+ "aria-label": isCurrent
384
+ ? `Currently on ${plan.name || plan.id}`
385
+ : `Choose ${plan.name || plan.id}`,
386
+ },
387
+ isCurrent ? "Current plan" : "Choose plan",
388
+ ),
345
389
  );
346
390
  }),
347
391
  ),
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,