@startsimpli/billing 0.4.16 → 0.4.18
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 +2 -2
- package/package.json +1 -1
- package/src/components/PlanGate.test.tsx +24 -0
- package/src/components/PlanGate.tsx +7 -1
- package/src/components/SubscriptionManager.test.tsx +24 -0
- package/src/components/SubscriptionManager.tsx +1 -1
- package/src/hooks/useSubscription.test.tsx +18 -0
- package/src/hooks/useSubscription.ts +6 -3
- package/src/utils/api.test.ts +195 -0
- package/src/utils/api.ts +14 -14
- package/src/utils/error-message.ts +111 -0
package/README.md
CHANGED
|
@@ -207,14 +207,14 @@ BILLING_USAGE_ADAPTERS = {
|
|
|
207
207
|
| `PricingPage` / `PricingSection` / `PricingDetailPage` | Pre-billing display surfaces. | For marketing / landing pages. |
|
|
208
208
|
| `UpgradeModal` | Modal pricing overlay. | For mid-flow upgrade prompts. |
|
|
209
209
|
| `ManageSubscription` | Bare portal redirect button. | Use `SubscriptionManager` instead unless you really just want the button. |
|
|
210
|
-
| `PlanGate` | Feature-gate wrapper. | Show / hide children based on the user's offer features. |
|
|
210
|
+
| `PlanGate` | Feature-gate wrapper. | Show / hide children based on the user's offer features. Pass `productId`, or a paid plan on another product opens the gate. |
|
|
211
211
|
|
|
212
212
|
### Hooks
|
|
213
213
|
|
|
214
214
|
| Hook | Returns | Notes |
|
|
215
215
|
|---|---|---|
|
|
216
216
|
| `useProduct(slug)` | `{ product, loading, error, refetch }` | Fetch product + offers |
|
|
217
|
-
| `useSubscription()` | `{ subscription, loading, error, refetch }` | Current sub incl. `viewerIsOwner` + `ownerEmail
|
|
217
|
+
| `useSubscription(productId)` | `{ subscription, loading, error, refetch }` | Current sub for that product, incl. `viewerIsOwner` + `ownerEmail`. Always pass the product: without it the newest sub for ANY product comes back. |
|
|
218
218
|
| `useUsage(slug)` | `{ usage, loading, error, refetch }` | `{feature_key: {used, limit}}` map; auto-refetches on `visibilitychange` + `billing:usage-changed` event |
|
|
219
219
|
| `useCheckout()` | `{ checkout, subscribeFree, loading, error }` | Stripe session creator + free-subscribe in one |
|
|
220
220
|
| `usePortal()` | `{ openPortal, loading, error }` | Stripe customer portal session |
|
package/package.json
CHANGED
|
@@ -130,4 +130,28 @@ describe("PlanGate", () => {
|
|
|
130
130
|
expect(screen.getAllByText(/paid plan|upgrade/i).length).toBeGreaterThan(0)
|
|
131
131
|
);
|
|
132
132
|
});
|
|
133
|
+
|
|
134
|
+
it("gates on the given product's subscription only (startsim-oyr3a.2)", async () => {
|
|
135
|
+
const fetcher = vi.fn(async () => ({
|
|
136
|
+
ok: false,
|
|
137
|
+
status: 404,
|
|
138
|
+
async json() {
|
|
139
|
+
return {};
|
|
140
|
+
},
|
|
141
|
+
})) as unknown as typeof fetch;
|
|
142
|
+
|
|
143
|
+
render(
|
|
144
|
+
<BillingProvider apiBaseUrl="/api" fetcher={fetcher}>
|
|
145
|
+
<PlanGate productId="crochet-patterns" fallback={<span>upgrade</span>}>
|
|
146
|
+
<span>pro feature</span>
|
|
147
|
+
</PlanGate>
|
|
148
|
+
</BillingProvider>
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
await waitFor(() => expect(screen.getByText("upgrade")).toBeDefined());
|
|
152
|
+
expect(fetcher).toHaveBeenCalledWith(
|
|
153
|
+
"/api/billing/subscription/current/?product=crochet-patterns",
|
|
154
|
+
expect.anything()
|
|
155
|
+
);
|
|
156
|
+
});
|
|
133
157
|
});
|
|
@@ -6,6 +6,11 @@ import { isPaidSubscription } from "../utils/plan";
|
|
|
6
6
|
|
|
7
7
|
export interface PlanGateProps {
|
|
8
8
|
children: React.ReactNode;
|
|
9
|
+
/**
|
|
10
|
+
* The app's product slug. Without it, a paid plan on ANY product opens the
|
|
11
|
+
* gate (startsim-oyr3a.2).
|
|
12
|
+
*/
|
|
13
|
+
productId?: string;
|
|
9
14
|
/**
|
|
10
15
|
* Element rendered in place of children when user is not on a paid plan.
|
|
11
16
|
* Defaults to a minimal upgrade nudge pointing at /pricing.
|
|
@@ -40,8 +45,9 @@ export function PlanGate({
|
|
|
40
45
|
children,
|
|
41
46
|
fallback,
|
|
42
47
|
upgradeHref = "/pricing",
|
|
48
|
+
productId,
|
|
43
49
|
}: PlanGateProps) {
|
|
44
|
-
const { subscription, loading } = useSubscription();
|
|
50
|
+
const { subscription, loading } = useSubscription(productId);
|
|
45
51
|
|
|
46
52
|
if (loading) return <>{children}</>;
|
|
47
53
|
|
|
@@ -1279,4 +1279,28 @@ describe("SubscriptionManager", () => {
|
|
|
1279
1279
|
expect(screen.getByText("No active subscription")).toBeDefined()
|
|
1280
1280
|
);
|
|
1281
1281
|
});
|
|
1282
|
+
|
|
1283
|
+
it("asks only for its own product's subscription (startsim-oyr3a.2)", async () => {
|
|
1284
|
+
const fetcher = mockFetchRouter({
|
|
1285
|
+
"/billing/subscription/current/": null,
|
|
1286
|
+
"/billing/products/": mockProduct,
|
|
1287
|
+
});
|
|
1288
|
+
const Wrapper = createWrapper(fetcher);
|
|
1289
|
+
|
|
1290
|
+
render(
|
|
1291
|
+
<Wrapper>
|
|
1292
|
+
<SubscriptionManager
|
|
1293
|
+
productId="raise-simpli"
|
|
1294
|
+
returnUrl="https://app.test.com/settings"
|
|
1295
|
+
/>
|
|
1296
|
+
</Wrapper>
|
|
1297
|
+
);
|
|
1298
|
+
|
|
1299
|
+
await waitFor(() =>
|
|
1300
|
+
expect(fetcher).toHaveBeenCalledWith(
|
|
1301
|
+
"https://api.test.com/api/v1/billing/subscription/current/?product=raise-simpli",
|
|
1302
|
+
expect.anything()
|
|
1303
|
+
)
|
|
1304
|
+
);
|
|
1305
|
+
});
|
|
1282
1306
|
});
|
|
@@ -172,7 +172,7 @@ export function SubscriptionManager({
|
|
|
172
172
|
onPlanChange,
|
|
173
173
|
statusMessage,
|
|
174
174
|
}: SubscriptionManagerProps) {
|
|
175
|
-
const { subscription, loading: subLoading, error: subError, refetch: refetchSubscription } = useSubscription();
|
|
175
|
+
const { subscription, loading: subLoading, error: subError, refetch: refetchSubscription } = useSubscription(productId);
|
|
176
176
|
const { product, loading: productLoading, error: productError, refetch: refetchProduct } = useProduct(productId);
|
|
177
177
|
const { openPortal, loading: portalLoading } = usePortal();
|
|
178
178
|
const { subscribeFree } = useCheckout();
|
|
@@ -88,6 +88,24 @@ describe("useSubscription", () => {
|
|
|
88
88
|
);
|
|
89
89
|
});
|
|
90
90
|
|
|
91
|
+
it("asks only for the given product's subscription (startsim-oyr3a.2)", async () => {
|
|
92
|
+
const mockFetch = vi.fn().mockResolvedValue({
|
|
93
|
+
ok: true,
|
|
94
|
+
status: 200,
|
|
95
|
+
json: () => Promise.resolve(mockSubscription),
|
|
96
|
+
});
|
|
97
|
+
const wrapper = createWrapper(mockFetch as unknown as typeof fetch);
|
|
98
|
+
|
|
99
|
+
const { result } = renderHook(() => useSubscription("crochet-patterns"), { wrapper });
|
|
100
|
+
|
|
101
|
+
await waitFor(() => expect(result.current.loading).toBe(false));
|
|
102
|
+
|
|
103
|
+
expect(mockFetch).toHaveBeenCalledWith(
|
|
104
|
+
"https://api.test.com/api/v1/billing/subscription/current/?product=crochet-patterns",
|
|
105
|
+
expect.anything()
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
|
|
91
109
|
it("returns null when no subscription exists (404)", async () => {
|
|
92
110
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
93
111
|
ok: false,
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* useSubscription — Fetch current user's active subscription.
|
|
3
|
+
*
|
|
4
|
+
* Pass the app's product slug so another app's plan is never returned
|
|
5
|
+
* (startsim-oyr3a.2).
|
|
3
6
|
*/
|
|
4
7
|
|
|
5
8
|
import { useCallback, useEffect, useState } from "react";
|
|
@@ -13,7 +16,7 @@ interface UseSubscriptionResult {
|
|
|
13
16
|
refetch: () => void;
|
|
14
17
|
}
|
|
15
18
|
|
|
16
|
-
export function useSubscription(): UseSubscriptionResult {
|
|
19
|
+
export function useSubscription(productId?: string): UseSubscriptionResult {
|
|
17
20
|
const { client } = useBillingContext();
|
|
18
21
|
const [subscription, setSubscription] = useState<SubscriptionInfo | null>(null);
|
|
19
22
|
const [loading, setLoading] = useState(true);
|
|
@@ -23,14 +26,14 @@ export function useSubscription(): UseSubscriptionResult {
|
|
|
23
26
|
setLoading(true);
|
|
24
27
|
setError(null);
|
|
25
28
|
try {
|
|
26
|
-
const data = await client.getSubscription();
|
|
29
|
+
const data = await client.getSubscription(productId);
|
|
27
30
|
setSubscription(data);
|
|
28
31
|
} catch (e) {
|
|
29
32
|
setError(e instanceof Error ? e : new Error(String(e)));
|
|
30
33
|
} finally {
|
|
31
34
|
setLoading(false);
|
|
32
35
|
}
|
|
33
|
-
}, [client]);
|
|
36
|
+
}, [client, productId]);
|
|
34
37
|
|
|
35
38
|
useEffect(() => {
|
|
36
39
|
fetchSubscription();
|
package/src/utils/api.test.ts
CHANGED
|
@@ -108,6 +108,201 @@ describe("BillingApiClient", () => {
|
|
|
108
108
|
});
|
|
109
109
|
});
|
|
110
110
|
|
|
111
|
+
// startsim-ol36d.27: a buyer saw "Checkout failed: 400" while Django was
|
|
112
|
+
// returning a specific reason. The app route proxies through
|
|
113
|
+
// proxyBillingRequest, which wraps Django's raw error text in an envelope,
|
|
114
|
+
// so the reason arrives as a JSON *string* under `details`.
|
|
115
|
+
describe("error messages carry the server's reason", () => {
|
|
116
|
+
// Captured verbatim from POST https://crochets.site/api/billing/offer-checkout/
|
|
117
|
+
// (signed in) on 2026-09-17.
|
|
118
|
+
const LIVE = {
|
|
119
|
+
bogusOfferUuid:
|
|
120
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"Invalid or inactive offer\\"]}"}',
|
|
121
|
+
malformedOfferId:
|
|
122
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"Must be a valid UUID.\\"]}"}',
|
|
123
|
+
emptyBody:
|
|
124
|
+
'{"error":"Billing API error","status":400,"details":"{\\"offer_id\\":[\\"This field is required.\\"],\\"success_url\\":[\\"This field is required.\\"],\\"cancel_url\\":[\\"This field is required.\\"]}"}',
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function failWith(status: number, body: unknown) {
|
|
128
|
+
mockFetch.mockResolvedValue({
|
|
129
|
+
ok: false,
|
|
130
|
+
status,
|
|
131
|
+
json: () => Promise.resolve(body),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function checkout() {
|
|
136
|
+
return createClient().createCheckout({
|
|
137
|
+
offerId: "bad",
|
|
138
|
+
successUrl: "x",
|
|
139
|
+
cancelUrl: "y",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
it.each([
|
|
144
|
+
["bogus offer id", LIVE.bogusOfferUuid, "Offer id: Invalid or inactive offer"],
|
|
145
|
+
["malformed offer id", LIVE.malformedOfferId, "Offer id: Must be a valid UUID."],
|
|
146
|
+
["empty body (first field wins)", LIVE.emptyBody, "Offer id: This field is required."],
|
|
147
|
+
])("unwraps the live proxy envelope: %s", async (_name, raw, expected) => {
|
|
148
|
+
failWith(400, JSON.parse(raw));
|
|
149
|
+
await expect(checkout()).rejects.toThrow(new Error(expected));
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("unwraps the proxied non_field_errors that caused the original incident", async () => {
|
|
153
|
+
failWith(400, {
|
|
154
|
+
error: "Billing API error",
|
|
155
|
+
status: 400,
|
|
156
|
+
details: JSON.stringify({
|
|
157
|
+
non_field_errors: [
|
|
158
|
+
"BILLING_ALLOWED_REDIRECT_DOMAINS must be configured in production.",
|
|
159
|
+
],
|
|
160
|
+
}),
|
|
161
|
+
});
|
|
162
|
+
await expect(checkout()).rejects.toThrow(
|
|
163
|
+
new Error("BILLING_ALLOWED_REDIRECT_DOMAINS must be configured in production.")
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("unwraps a camelCased body inside the proxy envelope", async () => {
|
|
168
|
+
failWith(400, {
|
|
169
|
+
error: "Billing API error",
|
|
170
|
+
status: 400,
|
|
171
|
+
details: JSON.stringify({ offerId: ["Invalid or inactive offer"] }),
|
|
172
|
+
});
|
|
173
|
+
await expect(checkout()).rejects.toThrow(
|
|
174
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
175
|
+
);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it.each([
|
|
179
|
+
["non_field_errors", { non_field_errors: ["Offer is not purchasable"] }],
|
|
180
|
+
["nonFieldErrors", { nonFieldErrors: ["Offer is not purchasable"] }],
|
|
181
|
+
])("reads a bare DRF %s array", async (_name, body) => {
|
|
182
|
+
failWith(400, body);
|
|
183
|
+
await expect(checkout()).rejects.toThrow(new Error("Offer is not purchasable"));
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it.each([
|
|
187
|
+
["offer_id", { offer_id: ["Invalid or inactive offer"] }],
|
|
188
|
+
["offerId", { offerId: ["Invalid or inactive offer"] }],
|
|
189
|
+
])("reads a bare DRF field error map keyed %s", async (_name, body) => {
|
|
190
|
+
failWith(400, body);
|
|
191
|
+
await expect(checkout()).rejects.toThrow(
|
|
192
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
193
|
+
);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it("prefers detail over everything else", async () => {
|
|
197
|
+
failWith(400, {
|
|
198
|
+
detail: "Offer not synced",
|
|
199
|
+
non_field_errors: ["other"],
|
|
200
|
+
offer_id: ["other"],
|
|
201
|
+
});
|
|
202
|
+
await expect(checkout()).rejects.toThrow(new Error("Offer not synced"));
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("prefers non_field_errors over field errors", async () => {
|
|
206
|
+
failWith(400, {
|
|
207
|
+
offer_id: ["field message"],
|
|
208
|
+
non_field_errors: ["form message"],
|
|
209
|
+
});
|
|
210
|
+
await expect(checkout()).rejects.toThrow(new Error("form message"));
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it.each([
|
|
214
|
+
[401, { error: "Not authenticated", code: "UNAUTHORIZED" }, "Not authenticated"],
|
|
215
|
+
[503, { error: "Billing service unavailable", code: "INTERNAL_ERROR" }, "Billing service unavailable"],
|
|
216
|
+
])("surfaces an app route's {error, code} body (%i)", async (status, body, expected) => {
|
|
217
|
+
failWith(status, body);
|
|
218
|
+
await expect(checkout()).rejects.toThrow(new Error(expected));
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("never shows the proxy's generic label or an HTML page", async () => {
|
|
222
|
+
failWith(502, {
|
|
223
|
+
error: "Billing API error",
|
|
224
|
+
status: 502,
|
|
225
|
+
details: "<html><body><h1>502 Bad Gateway</h1></body></html>",
|
|
226
|
+
});
|
|
227
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 502"));
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("never shows the proxy's network-failure label", async () => {
|
|
231
|
+
failWith(500, { error: "Internal server error", details: "fetch failed" });
|
|
232
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 500"));
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("falls back to the status when the body is not JSON", async () => {
|
|
236
|
+
mockFetch.mockResolvedValue({
|
|
237
|
+
ok: false,
|
|
238
|
+
status: 400,
|
|
239
|
+
json: () => Promise.reject(new SyntaxError("Unexpected token <")),
|
|
240
|
+
});
|
|
241
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 400"));
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("falls back to the status when the body has no message", async () => {
|
|
245
|
+
failWith(400, {});
|
|
246
|
+
await expect(checkout()).rejects.toThrow(new Error("Checkout failed: 400"));
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("applies to subscribeFree", async () => {
|
|
250
|
+
failWith(400, JSON.parse(LIVE.bogusOfferUuid));
|
|
251
|
+
await expect(createClient().subscribeFree("bad")).rejects.toThrow(
|
|
252
|
+
new Error("Offer id: Invalid or inactive offer")
|
|
253
|
+
);
|
|
254
|
+
failWith(400, {});
|
|
255
|
+
await expect(createClient().subscribeFree("bad")).rejects.toThrow(
|
|
256
|
+
new Error("Free signup failed: 400")
|
|
257
|
+
);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("applies to createPortal", async () => {
|
|
261
|
+
failWith(400, {
|
|
262
|
+
error: "Billing API error",
|
|
263
|
+
status: 400,
|
|
264
|
+
details: JSON.stringify({ return_url: ["Enter a valid URL."] }),
|
|
265
|
+
});
|
|
266
|
+
await expect(createClient().createPortal("nope")).rejects.toThrow(
|
|
267
|
+
new Error("Return url: Enter a valid URL.")
|
|
268
|
+
);
|
|
269
|
+
failWith(400, {});
|
|
270
|
+
await expect(createClient().createPortal("nope")).rejects.toThrow(
|
|
271
|
+
new Error("Portal session failed: 400")
|
|
272
|
+
);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("applies to successSync", async () => {
|
|
276
|
+
failWith(400, {
|
|
277
|
+
error: "Billing API error",
|
|
278
|
+
status: 400,
|
|
279
|
+
details: JSON.stringify({ detail: "No checkout session to sync" }),
|
|
280
|
+
});
|
|
281
|
+
await expect(createClient().successSync()).rejects.toThrow(
|
|
282
|
+
new Error("No checkout session to sync")
|
|
283
|
+
);
|
|
284
|
+
failWith(500, {});
|
|
285
|
+
await expect(createClient().successSync()).rejects.toThrow(
|
|
286
|
+
new Error("Success sync failed: 500")
|
|
287
|
+
);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("applies to getSubscription", async () => {
|
|
291
|
+
failWith(403, {
|
|
292
|
+
error: "Billing API error",
|
|
293
|
+
status: 403,
|
|
294
|
+
details: JSON.stringify({ detail: "You are not a member of this team." }),
|
|
295
|
+
});
|
|
296
|
+
await expect(createClient().getSubscription("p")).rejects.toThrow(
|
|
297
|
+
new Error("You are not a member of this team.")
|
|
298
|
+
);
|
|
299
|
+
failWith(500, {});
|
|
300
|
+
await expect(createClient().getSubscription("p")).rejects.toThrow(
|
|
301
|
+
new Error("Failed to fetch subscription: 500")
|
|
302
|
+
);
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
|
|
111
306
|
describe("createPortal", () => {
|
|
112
307
|
it("sends POST with return_url", async () => {
|
|
113
308
|
mockFetch.mockResolvedValue({
|
package/src/utils/api.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type {
|
|
|
12
12
|
SubscriptionInfo,
|
|
13
13
|
UsageMap,
|
|
14
14
|
} from "../types";
|
|
15
|
+
import { billingErrorMessage } from "./error-message";
|
|
15
16
|
|
|
16
17
|
export class BillingApiClient {
|
|
17
18
|
private config: BillingConfig;
|
|
@@ -60,9 +61,7 @@ export class BillingApiClient {
|
|
|
60
61
|
});
|
|
61
62
|
if (!resp.ok) {
|
|
62
63
|
const data = await resp.json().catch(() => ({}));
|
|
63
|
-
throw new Error(
|
|
64
|
-
data.detail ?? `Checkout failed: ${resp.status}`
|
|
65
|
-
);
|
|
64
|
+
throw new Error(billingErrorMessage(data, `Checkout failed: ${resp.status}`));
|
|
66
65
|
}
|
|
67
66
|
return resp.json();
|
|
68
67
|
}
|
|
@@ -77,7 +76,7 @@ export class BillingApiClient {
|
|
|
77
76
|
});
|
|
78
77
|
if (!resp.ok) {
|
|
79
78
|
const data = await resp.json().catch(() => ({}));
|
|
80
|
-
throw new Error(data
|
|
79
|
+
throw new Error(billingErrorMessage(data, `Free signup failed: ${resp.status}`));
|
|
81
80
|
}
|
|
82
81
|
return resp.json();
|
|
83
82
|
}
|
|
@@ -92,9 +91,7 @@ export class BillingApiClient {
|
|
|
92
91
|
});
|
|
93
92
|
if (!resp.ok) {
|
|
94
93
|
const data = await resp.json().catch(() => ({}));
|
|
95
|
-
throw new Error(
|
|
96
|
-
data.detail ?? `Portal session failed: ${resp.status}`
|
|
97
|
-
);
|
|
94
|
+
throw new Error(billingErrorMessage(data, `Portal session failed: ${resp.status}`));
|
|
98
95
|
}
|
|
99
96
|
return resp.json();
|
|
100
97
|
}
|
|
@@ -114,7 +111,7 @@ export class BillingApiClient {
|
|
|
114
111
|
}
|
|
115
112
|
if (!resp.ok) {
|
|
116
113
|
const data = await resp.json().catch(() => ({}));
|
|
117
|
-
throw new Error(data
|
|
114
|
+
throw new Error(billingErrorMessage(data, `Success sync failed: ${resp.status}`));
|
|
118
115
|
}
|
|
119
116
|
return resp.json();
|
|
120
117
|
}
|
|
@@ -134,9 +131,14 @@ export class BillingApiClient {
|
|
|
134
131
|
return (await resp.json()) as UsageMap;
|
|
135
132
|
}
|
|
136
133
|
|
|
137
|
-
/**
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
/**
|
|
135
|
+
* Get current user's subscription. Pass the app's product slug: a team can
|
|
136
|
+
* hold subscriptions to several products, and without it the backend returns
|
|
137
|
+
* the newest one for ANY product (startsim-oyr3a.2).
|
|
138
|
+
*/
|
|
139
|
+
async getSubscription(productSlug?: string): Promise<SubscriptionInfo | null> {
|
|
140
|
+
const query = productSlug ? `?product=${encodeURIComponent(productSlug)}` : "";
|
|
141
|
+
const url = `${this.config.apiBaseUrl}/billing/subscription/current/${query}`;
|
|
140
142
|
const resp = await this.fetcher(url, {
|
|
141
143
|
headers: this.headers,
|
|
142
144
|
});
|
|
@@ -145,9 +147,7 @@ export class BillingApiClient {
|
|
|
145
147
|
}
|
|
146
148
|
if (!resp.ok) {
|
|
147
149
|
const data = await resp.json().catch(() => ({}));
|
|
148
|
-
throw new Error(
|
|
149
|
-
data.detail ?? `Failed to fetch subscription: ${resp.status}`
|
|
150
|
-
);
|
|
150
|
+
throw new Error(billingErrorMessage(data, `Failed to fetch subscription: ${resp.status}`));
|
|
151
151
|
}
|
|
152
152
|
return this.normalizeSubscription(await resp.json());
|
|
153
153
|
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn a failed billing response body into one human-readable sentence.
|
|
3
|
+
*
|
|
4
|
+
* Shapes handled, in priority order:
|
|
5
|
+
* { detail: "..." } DRF's standard message
|
|
6
|
+
* { error: "Billing API error", details: "<json>" } proxyBillingRequest's envelope:
|
|
7
|
+
* Django's raw error text, as a string
|
|
8
|
+
* { non_field_errors: ["..."] } / { nonFieldErrors } first message
|
|
9
|
+
* { offer_id: ["..."] } / { offerId: [...] } "Offer id: ..." (first field wins)
|
|
10
|
+
* { error: "Not authenticated", code: "..." } app routes' own errors
|
|
11
|
+
* { error: { message: "..." } } (also app routes)
|
|
12
|
+
*
|
|
13
|
+
* Anything else (HTML error pages, the proxy's generic labels, empty bodies)
|
|
14
|
+
* yields `fallback`, so the user never sees raw JSON or markup.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// Labels proxyBillingRequest writes itself. They say that something failed,
|
|
18
|
+
// never why, so they must not be shown in place of the fallback.
|
|
19
|
+
const PROXY_LABELS = new Set(["Billing API error", "Internal server error"]);
|
|
20
|
+
|
|
21
|
+
const NON_FIELD_KEYS = new Set(["non_field_errors", "nonFieldErrors"]);
|
|
22
|
+
|
|
23
|
+
const META_KEYS = new Set([
|
|
24
|
+
"detail",
|
|
25
|
+
"details",
|
|
26
|
+
"error",
|
|
27
|
+
"message",
|
|
28
|
+
"code",
|
|
29
|
+
"status",
|
|
30
|
+
"statusCode",
|
|
31
|
+
"timestamp",
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export function billingErrorMessage(body: unknown, fallback: string): string {
|
|
35
|
+
return messageFrom(body) ?? fallback;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function messageFrom(body: unknown): string | null {
|
|
39
|
+
if (Array.isArray(body)) return firstString(body);
|
|
40
|
+
if (!body || typeof body !== "object") return null;
|
|
41
|
+
const d = body as Record<string, unknown>;
|
|
42
|
+
|
|
43
|
+
const detail = typeof d.detail === "string" ? text(d.detail) : messageFrom(d.detail);
|
|
44
|
+
if (detail) return detail;
|
|
45
|
+
|
|
46
|
+
// The envelope carries Django's body as text. Only JSON is worth reading:
|
|
47
|
+
// plain text here is an HTML error page or a network error string.
|
|
48
|
+
if (typeof d.details === "string") {
|
|
49
|
+
const inner = messageFrom(parseJson(d.details));
|
|
50
|
+
if (inner) return inner;
|
|
51
|
+
} else {
|
|
52
|
+
const inner = messageFrom(d.details);
|
|
53
|
+
if (inner) return inner;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
for (const key of NON_FIELD_KEYS) {
|
|
57
|
+
const s = firstString(d[key]);
|
|
58
|
+
if (s) return s;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const [key, val] of Object.entries(d)) {
|
|
62
|
+
if (META_KEYS.has(key) || NON_FIELD_KEYS.has(key)) continue;
|
|
63
|
+
// DRF field errors are always lists (or nested serializer maps); a scalar
|
|
64
|
+
// here is data, not an error.
|
|
65
|
+
if (!val || typeof val !== "object") continue;
|
|
66
|
+
const s = Array.isArray(val) ? firstString(val) : messageFrom(val);
|
|
67
|
+
if (s) return `${fieldLabel(key)}: ${s}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const key of ["message", "error"]) {
|
|
71
|
+
const val = d[key];
|
|
72
|
+
const s = typeof val === "string" ? text(val) : messageFrom(val);
|
|
73
|
+
if (s && !PROXY_LABELS.has(s)) return s;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function firstString(val: unknown): string | null {
|
|
79
|
+
if (typeof val === "string") return text(val);
|
|
80
|
+
if (!Array.isArray(val)) return null;
|
|
81
|
+
for (const item of val) {
|
|
82
|
+
const s = typeof item === "string" ? text(item) : messageFrom(item);
|
|
83
|
+
if (s) return s;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function text(s: string): string | null {
|
|
89
|
+
const t = s.trim();
|
|
90
|
+
return t ? t : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseJson(s: string): unknown {
|
|
94
|
+
const t = s.trim();
|
|
95
|
+
if (!t.startsWith("{") && !t.startsWith("[")) return null;
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(t);
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** "offer_id" / "offerId" → "Offer id" */
|
|
104
|
+
function fieldLabel(key: string): string {
|
|
105
|
+
const words = key
|
|
106
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
107
|
+
.replace(/_+/g, " ")
|
|
108
|
+
.trim()
|
|
109
|
+
.toLowerCase();
|
|
110
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
111
|
+
}
|