@meterbox/react 0.1.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.
package/src/Paywall.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * <Paywall feature="vision" customerId="..." customerToken="..." baseUrl="...">
3
+ * <YourFeature />
4
+ * </Paywall>
5
+ *
6
+ * Gates `children` on whether the customer's resolved entitlement includes
7
+ * `feature`. On deny, renders the configured `fallback` (or a default upgrade
8
+ * prompt). Self-fetches from `GET /v1/customer-portal/:id/entitlements`.
9
+ *
10
+ * Modes:
11
+ * • **Self-fetching** (default) — provide `baseUrl`, `customerId`,
12
+ * `customerToken`. Fetches the entitlements once on mount and again
13
+ * whenever the customer or token changes.
14
+ * • **Presentational** — pass `features` (array of feature ids the customer
15
+ * has) directly. No fetch.
16
+ *
17
+ * Fail-open: when the fetch errors (network down, missing endpoint), the
18
+ * default behavior is to ALLOW (`failOpen: true`). Set `failOpen={false}`
19
+ * to deny on error. Mirrors the entitlement-sidecar's stale-while-error
20
+ * semantics — you'd rather show a feature briefly than block paying
21
+ * customers when Meterbox blips.
22
+ */
23
+
24
+ const React = require("react");
25
+
26
+ const defaultStyles = {
27
+ fallback: {
28
+ padding: "16px 20px",
29
+ borderRadius: 10,
30
+ border: "1px solid #e5e7eb",
31
+ background: "#fafafa",
32
+ fontFamily: "system-ui, -apple-system, sans-serif",
33
+ color: "#111",
34
+ display: "flex",
35
+ flexDirection: "column",
36
+ gap: 8,
37
+ },
38
+ title: { fontSize: 15, fontWeight: 600, margin: 0 },
39
+ hint: { fontSize: 13, opacity: 0.7, margin: 0 },
40
+ cta: {
41
+ marginTop: 4,
42
+ padding: "8px 14px",
43
+ border: "none",
44
+ borderRadius: 8,
45
+ background: "#5045e8",
46
+ color: "#fff",
47
+ fontWeight: 600,
48
+ cursor: "pointer",
49
+ alignSelf: "flex-start",
50
+ },
51
+ };
52
+
53
+ async function fetchEntitlements({ baseUrl, customerId, customerToken, fetchImpl }) {
54
+ const url = `${baseUrl.replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
55
+ customerId,
56
+ )}/entitlements`;
57
+ const res = await fetchImpl(url, {
58
+ method: "GET",
59
+ headers: { Authorization: `Bearer ${customerToken}` },
60
+ });
61
+ if (!res.ok) throw new Error(`paywall: ${res.status}`);
62
+ return res.json();
63
+ }
64
+
65
+ function Paywall({
66
+ feature,
67
+ features,
68
+ children,
69
+ fallback,
70
+ onUpgradeClick,
71
+ baseUrl,
72
+ customerId,
73
+ customerToken,
74
+ fetch: fetchImpl,
75
+ failOpen = true,
76
+ }) {
77
+ const selfFetch = !features && baseUrl && customerId && customerToken;
78
+ const [fetched, setFetched] = React.useState(null);
79
+ const [error, setError] = React.useState(null);
80
+
81
+ React.useEffect(() => {
82
+ if (!selfFetch) return undefined;
83
+ let alive = true;
84
+ fetchEntitlements({
85
+ baseUrl,
86
+ customerId,
87
+ customerToken,
88
+ fetchImpl: fetchImpl || globalThis.fetch,
89
+ })
90
+ .then((d) => {
91
+ if (alive) setFetched(d);
92
+ })
93
+ .catch((err) => {
94
+ if (alive) setError(err);
95
+ });
96
+ return () => {
97
+ alive = false;
98
+ };
99
+ }, [selfFetch, baseUrl, customerId, customerToken, fetchImpl]);
100
+
101
+ // Determine the list of features the customer has.
102
+ let resolvedFeatures = features;
103
+ if (selfFetch && fetched) {
104
+ // Entitlement check returns a flat `features[]` list; surface either
105
+ // shape so the same component works with our admin + portal endpoints.
106
+ resolvedFeatures = Array.isArray(fetched.features)
107
+ ? fetched.features
108
+ : fetched.features
109
+ ? Object.keys(fetched.features)
110
+ : [];
111
+ }
112
+
113
+ // Fail-open on error: act as if the customer HAS the feature.
114
+ const hasFeature = error
115
+ ? failOpen
116
+ : Array.isArray(resolvedFeatures)
117
+ ? resolvedFeatures.includes(feature)
118
+ : null;
119
+
120
+ if (hasFeature === null) return null; // loading
121
+ if (hasFeature) return children || null;
122
+
123
+ if (fallback) return fallback;
124
+ return React.createElement(
125
+ "div",
126
+ { className: "meterbox-paywall", style: defaultStyles.fallback, role: "alert" },
127
+ React.createElement("p", { style: defaultStyles.title }, `Upgrade to unlock ${feature}`),
128
+ React.createElement(
129
+ "p",
130
+ { style: defaultStyles.hint },
131
+ `Your current plan doesn't include ${feature}.`,
132
+ ),
133
+ onUpgradeClick &&
134
+ React.createElement(
135
+ "button",
136
+ {
137
+ type: "button",
138
+ style: defaultStyles.cta,
139
+ onClick: () => onUpgradeClick(feature),
140
+ },
141
+ "See plans",
142
+ ),
143
+ );
144
+ }
145
+
146
+ module.exports = Paywall;
@@ -0,0 +1,270 @@
1
+ /**
2
+ * <PlanChangeCard ... />
3
+ *
4
+ * Composes `<SubscriptionPreview>` with the two actions that were missing
5
+ * from the customer-portal surface: actually applying or scheduling the
6
+ * change. Previewing a plan change was already possible; there was no way
7
+ * for a customer to confirm one without the host app building its own
8
+ * checkout flow (a NEW Stripe Checkout session — the wrong primitive for
9
+ * modifying an existing subscription in place).
10
+ *
11
+ * Two modes, same split as `<SubscriptionPreview>`:
12
+ *
13
+ * 1. **Presentational** — host supplies `preview` (already fetched) and
14
+ * `onConfirm(effective)` / `onCancelScheduled()` callbacks that return
15
+ * promises. The panel owns only the busy/result UI state around
16
+ * calling them; the host owns how the request actually gets made
17
+ * (e.g. Meterbox's own Settings page proxies through its control
18
+ * plane, session-authenticated, holding no customer JWT at all).
19
+ *
20
+ * 2. **Self-fetching** — `baseUrl` + `customerId` + `customerToken` +
21
+ * `planId`, no `onConfirm`/`onCancelScheduled` supplied. The panel
22
+ * fetches its own preview AND posts the confirm/cancel actions
23
+ * directly to `/v1/customer-portal/:id/subscription/change` and
24
+ * `/v1/customer-portal/:id/subscription/scheduled`.
25
+ *
26
+ * `scheduledChange` (if the customer already has one pending — from
27
+ * `GET /v1/customer-portal/:id/me`'s `scheduled_change` field, or the
28
+ * host's own equivalent) renders a banner with its own Cancel action ahead
29
+ * of the preview.
30
+ *
31
+ * `allowSchedule` (default true) hides "Schedule for end of period" when
32
+ * the host has nothing watching for the scheduled change to actually land
33
+ * later — e.g. Meterbox's own Settings usage mirrors an "apply now" result
34
+ * into a local field synchronously, but has no sweeper reconciling a
35
+ * schedule applied later on the dogfood org's own side, so it only offers
36
+ * "Change now".
37
+ */
38
+
39
+ const React = require("react");
40
+ const SubscriptionPreview = require("./SubscriptionPreview");
41
+
42
+ const styles = {
43
+ wrap: {
44
+ fontFamily: "system-ui, -apple-system, sans-serif",
45
+ display: "grid",
46
+ gap: 12,
47
+ maxWidth: 480,
48
+ },
49
+ banner: {
50
+ padding: "10px 12px",
51
+ borderRadius: 8,
52
+ fontSize: 13,
53
+ background: "rgba(245,158,11,0.12)",
54
+ color: "#b45309",
55
+ display: "flex",
56
+ justifyContent: "space-between",
57
+ alignItems: "center",
58
+ gap: 12,
59
+ },
60
+ actions: { display: "flex", gap: 8 },
61
+ btn: {
62
+ padding: "10px 16px",
63
+ border: "1px solid #d1d5db",
64
+ borderRadius: 8,
65
+ background: "#fff",
66
+ color: "#111",
67
+ fontWeight: 600,
68
+ cursor: "pointer",
69
+ fontFamily: "system-ui, -apple-system, sans-serif",
70
+ fontSize: 14,
71
+ },
72
+ btnPrimary: {
73
+ border: "none",
74
+ background: "#5045e8",
75
+ color: "#fff",
76
+ },
77
+ disabled: { opacity: 0.6, cursor: "default" },
78
+ message: { fontSize: 13 },
79
+ success: { color: "#16a34a" },
80
+ error: { color: "#dc2626" },
81
+ };
82
+
83
+ function fmtDate(iso) {
84
+ return iso ? String(iso).slice(0, 10) : "—";
85
+ }
86
+
87
+ function btnStyle(disabled, primary) {
88
+ const base = primary ? { ...styles.btn, ...styles.btnPrimary } : styles.btn;
89
+ return disabled ? { ...base, ...styles.disabled } : base;
90
+ }
91
+
92
+ async function postChange({ baseUrl, customerId, customerToken, planId, effective, fetchImpl }) {
93
+ const url = `${String(baseUrl).replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
94
+ customerId,
95
+ )}/subscription/change`;
96
+ const res = await fetchImpl(url, {
97
+ method: "POST",
98
+ headers: {
99
+ "Content-Type": "application/json",
100
+ Authorization: `Bearer ${customerToken}`,
101
+ },
102
+ body: JSON.stringify({ plan_id: planId, effective }),
103
+ });
104
+ const body = await res.json().catch(() => ({}));
105
+ if (!res.ok) {
106
+ const err = new Error(body.error || `HTTP ${res.status}`);
107
+ err.status = res.status;
108
+ throw err;
109
+ }
110
+ return body;
111
+ }
112
+
113
+ async function deleteScheduled({ baseUrl, customerId, customerToken, fetchImpl }) {
114
+ const url = `${String(baseUrl).replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
115
+ customerId,
116
+ )}/subscription/scheduled`;
117
+ const res = await fetchImpl(url, {
118
+ method: "DELETE",
119
+ headers: { Authorization: `Bearer ${customerToken}` },
120
+ });
121
+ const body = await res.json().catch(() => ({}));
122
+ if (!res.ok) {
123
+ const err = new Error(body.error || `HTTP ${res.status}`);
124
+ err.status = res.status;
125
+ throw err;
126
+ }
127
+ return body;
128
+ }
129
+
130
+ function PlanChangeCard({
131
+ preview,
132
+ scheduledChange,
133
+ allowSchedule = true,
134
+ baseUrl,
135
+ customerId,
136
+ customerToken,
137
+ planId,
138
+ planVersion,
139
+ fetch: fetchImpl,
140
+ onConfirm,
141
+ onCancelScheduled,
142
+ onChanged,
143
+ }) {
144
+ const fetcher = fetchImpl || globalThis.fetch;
145
+ const canSelfFetch = Boolean(baseUrl && customerId && customerToken);
146
+ const [busy, setBusy] = React.useState(false);
147
+ const [err, setErr] = React.useState(null);
148
+ const [message, setMessage] = React.useState(null);
149
+ const [scheduled, setScheduled] = React.useState(scheduledChange || null);
150
+
151
+ React.useEffect(() => {
152
+ setScheduled(scheduledChange || null);
153
+ }, [scheduledChange]);
154
+
155
+ async function confirm(effective) {
156
+ if (!planId) return;
157
+ setErr(null);
158
+ setMessage(null);
159
+ setBusy(true);
160
+ try {
161
+ const result = onConfirm
162
+ ? await onConfirm(effective)
163
+ : canSelfFetch
164
+ ? await postChange({ baseUrl, customerId, customerToken, planId, effective, fetchImpl: fetcher })
165
+ : null;
166
+ if (result?.scheduled) {
167
+ setScheduled(result.scheduled_change);
168
+ setMessage(`Scheduled: applies on ${fmtDate(result.scheduled_change.apply_at)}.`);
169
+ } else {
170
+ setMessage(`Plan changed${result?.new_plan ? ` to ${result.new_plan}` : ""}.`);
171
+ }
172
+ if (typeof onChanged === "function") onChanged(result);
173
+ } catch (e) {
174
+ setErr(e.message || "Plan change failed.");
175
+ } finally {
176
+ setBusy(false);
177
+ }
178
+ }
179
+
180
+ async function cancelScheduled() {
181
+ setErr(null);
182
+ setMessage(null);
183
+ setBusy(true);
184
+ try {
185
+ if (onCancelScheduled) {
186
+ await onCancelScheduled();
187
+ } else if (canSelfFetch) {
188
+ await deleteScheduled({ baseUrl, customerId, customerToken, fetchImpl: fetcher });
189
+ }
190
+ setScheduled(null);
191
+ setMessage("Scheduled change cancelled.");
192
+ if (typeof onChanged === "function") onChanged({ cancelled: true });
193
+ } catch (e) {
194
+ setErr(e.message || "Cancel failed.");
195
+ } finally {
196
+ setBusy(false);
197
+ }
198
+ }
199
+
200
+ const ready = Boolean(planId) && (Boolean(onConfirm) || canSelfFetch);
201
+
202
+ return React.createElement(
203
+ "div",
204
+ { className: "meterbox-plan-change-panel", style: styles.wrap },
205
+ scheduled &&
206
+ React.createElement(
207
+ "div",
208
+ { role: "status", style: styles.banner },
209
+ React.createElement(
210
+ "span",
211
+ null,
212
+ `Scheduled change to ${scheduled.target_plan_id} on ${fmtDate(scheduled.apply_at)}.`,
213
+ ),
214
+ React.createElement(
215
+ "button",
216
+ {
217
+ type: "button",
218
+ style: busy ? { ...styles.btn, ...styles.disabled } : styles.btn,
219
+ disabled: busy,
220
+ onClick: cancelScheduled,
221
+ },
222
+ "Cancel",
223
+ ),
224
+ ),
225
+ React.createElement(SubscriptionPreview, {
226
+ preview,
227
+ baseUrl,
228
+ customerId,
229
+ customerToken,
230
+ planId,
231
+ planVersion,
232
+ fetch: fetchImpl,
233
+ }),
234
+ React.createElement(
235
+ "div",
236
+ { style: styles.actions },
237
+ React.createElement(
238
+ "button",
239
+ {
240
+ type: "button",
241
+ style: btnStyle(!ready || busy, true),
242
+ disabled: !ready || busy,
243
+ onClick: () => confirm("now"),
244
+ },
245
+ busy ? "Working…" : "Change now",
246
+ ),
247
+ allowSchedule &&
248
+ React.createElement(
249
+ "button",
250
+ {
251
+ type: "button",
252
+ style: btnStyle(!ready || busy, false),
253
+ disabled: !ready || busy,
254
+ onClick: () => confirm("period_end"),
255
+ },
256
+ "Schedule for end of period",
257
+ ),
258
+ ),
259
+ err && React.createElement("div", { style: { ...styles.message, ...styles.error } }, err),
260
+ message &&
261
+ !err &&
262
+ React.createElement(
263
+ "div",
264
+ { role: "status", style: { ...styles.message, ...styles.success } },
265
+ message,
266
+ ),
267
+ );
268
+ }
269
+
270
+ module.exports = PlanChangeCard;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * <PlanComparison from={...} to={...} onSwitch? />
3
+ *
4
+ * Side-by-side comparison of two plan records (`from` and `to`). Highlights
5
+ * the feature deltas (added / removed / shared) and lets the embedding app
6
+ * route the customer onward via `onSwitch`.
7
+ *
8
+ * Both `from` and `to` are plan records as returned by `GET /v1/plans`.
9
+ * For the prorated-cost preview, render a `<SubscriptionPreview>`
10
+ * alongside this — that's the separate `subscription/preview` call.
11
+ */
12
+
13
+ const React = require("react");
14
+
15
+ const styles = {
16
+ grid: {
17
+ display: "grid",
18
+ gridTemplateColumns: "1fr 1fr",
19
+ gap: 24,
20
+ fontFamily: "system-ui, -apple-system, sans-serif",
21
+ color: "#111",
22
+ },
23
+ col: {
24
+ border: "1px solid #e5e7eb",
25
+ borderRadius: 12,
26
+ padding: 16,
27
+ background: "#fff",
28
+ display: "grid",
29
+ gap: 10,
30
+ },
31
+ colTo: { borderColor: "#5045e8" },
32
+ heading: { fontSize: 14, fontWeight: 600, opacity: 0.7, margin: 0 },
33
+ planName: { fontSize: 20, fontWeight: 700, margin: 0 },
34
+ features: { margin: 0, padding: 0, listStyle: "none", fontSize: 13, display: "grid", gap: 4 },
35
+ added: { color: "#16a34a", fontWeight: 600 },
36
+ removed: { color: "#dc2626", textDecoration: "line-through" },
37
+ switchBtn: {
38
+ marginTop: 8,
39
+ padding: "10px 14px",
40
+ border: "none",
41
+ borderRadius: 8,
42
+ background: "#5045e8",
43
+ color: "#fff",
44
+ fontWeight: 600,
45
+ cursor: "pointer",
46
+ },
47
+ };
48
+
49
+ function PlanComparison({ from, to, onSwitch }) {
50
+ if (!from || !to) {
51
+ return React.createElement(
52
+ "div",
53
+ { style: { opacity: 0.6, fontFamily: styles.grid.fontFamily } },
54
+ "Pick a plan to compare.",
55
+ );
56
+ }
57
+ const fromFeatures = new Set(Array.isArray(from.features) ? from.features : []);
58
+ const toFeatures = new Set(Array.isArray(to.features) ? to.features : []);
59
+ const added = [...toFeatures].filter((f) => !fromFeatures.has(f));
60
+ const removed = [...fromFeatures].filter((f) => !toFeatures.has(f));
61
+
62
+ function FeatureList(features, extras) {
63
+ return React.createElement(
64
+ "ul",
65
+ { style: styles.features },
66
+ features.map((f) =>
67
+ React.createElement(
68
+ "li",
69
+ { key: f, style: extras?.removed?.has(f) ? styles.removed : null },
70
+ `• ${f.replace(/_/g, " ")}`,
71
+ ),
72
+ ),
73
+ added.length > 0 &&
74
+ extras?.showAdded &&
75
+ added.map((f) =>
76
+ React.createElement(
77
+ "li",
78
+ { key: `added-${f}`, style: styles.added },
79
+ `+ ${f.replace(/_/g, " ")}`,
80
+ ),
81
+ ),
82
+ );
83
+ }
84
+
85
+ return React.createElement(
86
+ "div",
87
+ { className: "meterbox-plan-comparison", style: styles.grid },
88
+ React.createElement(
89
+ "div",
90
+ { style: styles.col },
91
+ React.createElement("h4", { style: styles.heading }, "Current"),
92
+ React.createElement("h3", { style: styles.planName }, from.name || from.id),
93
+ FeatureList(Array.from(fromFeatures), { removed: new Set(removed) }),
94
+ ),
95
+ React.createElement(
96
+ "div",
97
+ { style: { ...styles.col, ...styles.colTo } },
98
+ React.createElement("h4", { style: styles.heading }, "Switching to"),
99
+ React.createElement("h3", { style: styles.planName }, to.name || to.id),
100
+ FeatureList(
101
+ Array.from(toFeatures).filter((f) => !added.includes(f)),
102
+ { showAdded: true },
103
+ ),
104
+ onSwitch &&
105
+ React.createElement(
106
+ "button",
107
+ {
108
+ type: "button",
109
+ style: styles.switchBtn,
110
+ onClick: () => onSwitch(to),
111
+ },
112
+ `Switch to ${to.name || to.id}`,
113
+ ),
114
+ ),
115
+ );
116
+ }
117
+
118
+ module.exports = PlanComparison;