A declined card left the account in a state with no way out. `past_due` grants no minutes, so the metering layer resolved the user to the free plan — which meant /api/me reported status=null, the account page swapped "Manage billing" for "Upgrade" (hiding the only button that fixes a card), and the checkout guard then rejected the upgrade with a 409 that every call site swallowed into a generic "Could not start checkout." Silently free, unwarned, unable to pay. Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges that failed when the (now retired) 3-day trial ended. The trial is gone, but the trap is not — a renewal failure or an abandoned 3DS payment reproduces it. - metering: split `_subscription_row` (raw) from `_active_subscription` (entitling), and expose both on the balance. Entitlement logic is unchanged. - /api/me: report status/interval from a row needing attention when no subscription entitles, plus `has_billing_account` to route the portal button. - checkout: drop `incomplete` from the blocking states. Stripe collects nothing on it and expires it within 24h, so blocking only stopped the user's retry. Give past_due/unpaid a message that names the problem and the fix. - account page: explain the failed payment inline with a link to the portal instead of showing a bare "past_due" chip, and keep the portal reachable for any Stripe relationship, live or broken. - api client: throw a typed ApiError carrying the server's detail so callers stop replacing real, actionable messages with generic copy. Verified against a real DB: past_due stays blocked but visible and fixable, incomplete can retry, canceled is silent and can subscribe again.
66 lines
2.3 KiB
JavaScript
66 lines
2.3 KiB
JavaScript
// Centralized API client for cloud mode.
|
|
// Adds the Authorization: Bearer header from the stored session token, and turns
|
|
// a 402 (quota exceeded) into a typed QuotaError the UI can catch to prompt a top-up.
|
|
import { getApiUrl } from '../config';
|
|
|
|
export const AUTH_TOKEN_KEY = 'openshorts_auth';
|
|
|
|
export const getToken = () => localStorage.getItem(AUTH_TOKEN_KEY) || '';
|
|
export const setToken = (t) => localStorage.setItem(AUTH_TOKEN_KEY, t);
|
|
export const clearToken = () => localStorage.removeItem(AUTH_TOKEN_KEY);
|
|
|
|
export class QuotaError extends Error {
|
|
constructor(detail) {
|
|
super('quota_exceeded');
|
|
this.name = 'QuotaError';
|
|
this.minutesRequired = detail?.minutes_required;
|
|
this.minutesRemaining = detail?.minutes_remaining;
|
|
}
|
|
}
|
|
|
|
// Drop-in fetch wrapper. Always attaches the bearer token when present.
|
|
export async function apiFetch(path, options = {}) {
|
|
const headers = new Headers(options.headers || {});
|
|
const token = getToken();
|
|
if (token) headers.set('Authorization', `Bearer ${token}`);
|
|
|
|
const res = await fetch(getApiUrl(path), { ...options, headers });
|
|
|
|
if (res.status === 402) {
|
|
let detail = {};
|
|
try {
|
|
const body = await res.clone().json();
|
|
detail = body.detail || body;
|
|
} catch (_) { /* ignore */ }
|
|
throw new QuotaError(detail);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// A failed request, carrying the server's own explanation. Callers that show an
|
|
// alert should prefer `detail` — the generic "something went wrong" strings hid
|
|
// real, actionable messages (e.g. a declined card blocking checkout).
|
|
export class ApiError extends Error {
|
|
constructor(status, detail, raw) {
|
|
super(`${status}: ${raw}`); // message kept verbatim for existing callers
|
|
this.name = 'ApiError';
|
|
this.status = status;
|
|
this.detail = detail;
|
|
}
|
|
}
|
|
|
|
// Convenience JSON helper.
|
|
export async function apiJson(path, options = {}) {
|
|
const res = await apiFetch(path, options);
|
|
if (!res.ok) {
|
|
const text = await res.text().catch(() => '');
|
|
let detail = '';
|
|
try {
|
|
const d = JSON.parse(text).detail;
|
|
// FastAPI details are strings here, but validation errors arrive as objects.
|
|
if (typeof d === 'string') detail = d;
|
|
} catch (_) { /* not JSON — leave detail empty and fall back to the caller's copy */ }
|
|
throw new ApiError(res.status, detail, text);
|
|
}
|
|
return res.json();
|
|
}
|