Files
crosscode-platform/apps/events/frontend/src/lib/api.ts
T
joshuaandClaude Opus 5.5 abd2c36e97 WIP 2.0.0: React Compiler lint rules back to errors; docs
- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:45:25 +02:00

264 lines
12 KiB
TypeScript

import type { Event, Paginated, Payment, Registration, User } from "@/types";
import { hardNavigate } from "@/lib/navigation";
export type ApiOptions = {
method?: string;
headers?: Record<string, string>;
body?: unknown;
authToken?: string | null;
nextOptions?: RequestInit;
};
// Compute a robust API base that works locally, across devices, and in prod.
// Priority: NEXT_PUBLIC_API_URL -> API_URL -> (browser) smart dev fallbacks -> (browser) window.origin -> ""
function computeApiBase(): string {
const envBase = process.env.NEXT_PUBLIC_API_URL || process.env.API_URL || "";
// If running in the browser, try to adapt localhost to current hostname for LAN/mobile testing
if (typeof window !== "undefined") {
try {
if (envBase) {
const u = new URL(envBase);
const isLocalHost = ["localhost", "127.0.0.1", "::1"].includes(u.hostname);
if (isLocalHost) {
// Replace localhost with the actual device hostname so other devices can reach the dev machine
const protocol = u.protocol || window.location.protocol;
const hostname = window.location.hostname; // e.g., 192.168.x.x or your.dev.domain
const port = u.port ? `:${u.port}` : "";
return `${protocol}//${hostname}${port}`;
}
return u.origin;
}
// No env base provided — provide a sensible dev fallback
// If Next dev server is on 3000, assume backend on the same host port 5000
if (window.location.port === "3000") {
const protocol = window.location.protocol;
const hostname = window.location.hostname;
return `${protocol}//${hostname}:5000`;
}
// Otherwise, assume same origin will proxy /api (works if reverse proxy is configured)
return window.location.origin;
} catch {
// Fallbacks below
}
}
// On the server (or if window not available), use envBase if present; otherwise empty string.
return envBase || "";
}
export const API_BASE = computeApiBase();
// Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE.
// If it's an absolute URL but points to localhost/127.0.0.1/::1, rewrite its origin to API_BASE.
export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null {
const raw = (urlOrPath || "").trim();
if (!raw) return null;
try {
if (raw.startsWith("http")) {
const u = new URL(raw);
const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname);
if (isLocal && API_BASE) {
const api = new URL(API_BASE);
u.protocol = api.protocol;
u.hostname = api.hostname;
u.port = api.port;
return u.toString();
}
return raw; // already absolute and not localhost
}
} catch {
// fall through to relative handling
}
return API_BASE ? `${API_BASE}${raw}` : raw;
}
// The parsed JSON body of a failed request — v1 sends `message` (some routes add a
// machine-readable `code` or extra detail fields); for v2 it is the `error` object
// (`code`, `message`, and `fields` on validation errors).
export type ApiErrorData = { message?: string; code?: string; [key: string]: unknown };
export class ApiError extends Error {
constructor(public readonly status: number, message: string, public readonly data?: ApiErrorData) {
super(message);
this.name = "ApiError";
}
}
export async function apiFetch<T = unknown>(path: string, options: ApiOptions = {}): Promise<T> {
const { method = "GET", headers = {}, body, authToken, nextOptions } = options;
const url = path.startsWith("http") ? path : `${API_BASE}${path}`;
// On the server a relative URL has no origin to resolve against, and Next's
// patched fetch never settles on one during prerender (the build then times out
// every page). Fail fast instead so callers can degrade.
if (typeof window === "undefined" && !url.startsWith("http")) {
throw new Error(`API base URL is not configured (set NEXT_PUBLIC_API_URL or API_URL); cannot fetch ${path}`);
}
const mergedHeaders: Record<string, string> = { ...headers };
if (!(body instanceof FormData)) {
mergedHeaders["Content-Type"] = "application/json";
}
if (authToken) {
mergedHeaders["Authorization"] = `Bearer ${authToken}`;
}
const res = await fetch(url, {
method,
headers: mergedHeaders as HeadersInit,
body: body instanceof FormData ? body : body != null ? JSON.stringify(body) : undefined,
...nextOptions,
} as RequestInit);
if (!res.ok) {
const text = await res.text().catch(() => "");
let message = text || `Request failed with status ${res.status}`;
let data: ApiErrorData | undefined;
// Backend returns { message: "..." } — extract it so callers get a plain string
try {
const json = JSON.parse(text);
if (json?.message && typeof json.message === "string") message = json.message;
data = json;
// /api/v2 errors: { error: { code, message, fields?, reason? } }. `code` is the specific
// reason when there is one (TWO_FACTOR_REQUIRED, OTHER_CAMPUS…), like v1; v2Code is v2's own.
if (json?.error && typeof json.error === "object" && typeof json.error.message === "string") {
message = json.error.message;
data = { ...json.error, code: json.error.reason || json.error.code, v2Code: json.error.code };
}
} catch { /* not JSON — use raw text */ }
// An admin/supervisor session from before 2FA was required for their role:
// end it and send them to log in, where they enrol.
// The admin's "view as" session ended or expired: put their own session back.
if (res.status === 401 && data?.code === "IMPERSONATION_ENDED" && typeof window !== "undefined") {
const { restoreAdmin } = await import("@/lib/impersonation");
restoreAdmin();
}
if (res.status === 401 && data?.code === "TWO_FACTOR_REQUIRED" && typeof window !== "undefined") {
localStorage.removeItem("hope_events_token");
localStorage.removeItem("hope_events_user_cache");
if (!window.location.pathname.startsWith("/login")) {
const back = window.location.pathname + window.location.search;
hardNavigate(`/login?reason=2fa&redirect=${encodeURIComponent(back)}`);
}
}
throw new ApiError(res.status, message, data);
}
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return res.json();
}
// Non-JSON responses come back as text; callers that expect that pass T = string.
return (await res.text()) as T;
}
// For server components that prerender a public list: during `next build` the
// backend is often not running (or no API URL is set), so fall back to an empty
// list rather than failing the build — the page fills in on its first revalidate.
// At runtime the error still propagates, so ISR keeps serving the last good page
// instead of caching an empty one.
export async function apiFetchListForPrerender<T>(path: string, options: ApiOptions = {}): Promise<T[]> {
try {
// v2 answers { data: [...] }; v1 answered the bare list.
const res = await apiFetch<T[] | { data?: T[] }>(path, options);
return (Array.isArray(res) ? res : res?.data) || [];
} catch (err) {
if (process.env.NEXT_PHASE === "phase-production-build") return [];
throw err;
}
}
/**
* Every event staff can see (API v2 GET /events/manage): upcoming by default; `past`,
* `inactive` widen it, `closed: false` leaves out cashed-up events. Full records — ticket options,
* form, sessions, campus, series — for the event pickers and set-up screens.
*/
export async function fetchManagedEvents<T = Event>(token: string | null | undefined, opts: { past?: boolean; inactive?: boolean; closed?: boolean; campus?: string } = {}): Promise<T[]> {
const { apiV2 } = await import("@/lib/apiV2");
const { data } = await apiV2("get", "/events/manage", {
authToken: token,
query: {
past: opts.past ? "true" : "false",
inactive: opts.inactive ? "true" : "false",
closed: opts.closed === false ? "false" : "true",
...(opts.campus ? { campus: opts.campus } : {}),
},
});
return data as unknown as T[];
}
/**
* Every registration staff may see (API v2 GET /registrations, all pages), newest first, in full.
* `unpaid`: only ones still owing; `userId`: one person's.
*/
export async function fetchAllRegistrations<T = Registration>(token: string | null | undefined, filter: { unpaid?: boolean; userId?: string } = {}): Promise<T[]> {
const { apiV2 } = await import("@/lib/apiV2");
const out: T[] = [];
for (let page = 1; ; page++) {
const res = await apiV2("get", "/registrations", {
authToken: token,
query: { page, limit: 200, unpaid: filter.unpaid ? "true" : "false", ...(filter.userId ? { userId: filter.userId } : {}) },
});
out.push(...(res.data as unknown as T[]));
if (page >= res.meta.pages) return out;
}
}
/**
* One event in full (API v2 GET /events/{id}/full): ticket options with what's left, sessions,
* form, attachments, bundles. Staff signed in (`authToken`) also see inactive and not-yet-live
* events; `nextOptions` passes Next.js caching (e.g. revalidate) through for server pages.
*/
export async function fetchEvent<T = Event>(id: string, options: { authToken?: string | null; nextOptions?: RequestInit } = {}): Promise<T> {
const { apiV2 } = await import("@/lib/apiV2");
const { data } = await apiV2("get", "/events/{id}/full", { params: { id }, authToken: options.authToken, nextOptions: options.nextOptions });
return data as unknown as T;
}
/** Every account (API v2 GET /users, all pages at once). */
export async function fetchAllUsers(token: string, params: Record<string, string> = {}): Promise<User[]> {
const { apiV2Data } = await import("@/lib/apiV2");
const page = (n: number) => apiV2Data("get", "/users", { query: { ...params, limit: "200", page: String(n) }, authToken: token }) as Promise<Paginated<User>>;
const first = await page(1);
const items: User[] = Array.isArray(first?.data) ? [...first.data] : [];
const rest = await Promise.all(Array.from({ length: Math.max(0, (first?.pages || 1) - 1) }, (_, i) => page(i + 2)));
for (const res of rest) if (Array.isArray(res?.data)) items.push(...res.data);
return items;
}
/** Every payment staff may see (API v2 GET /payments, all pages at once). */
export async function fetchAllPayments(token: string, params: Record<string, string> = {}): Promise<Payment[]> {
const { apiV2Data } = await import("@/lib/apiV2");
const page = (n: number) => apiV2Data("get", "/payments", { query: { ...params, limit: "200", page: String(n) }, authToken: token }) as Promise<Paginated<Payment>>;
const first = await page(1);
const items: Payment[] = Array.isArray(first?.data) ? [...first.data] : [];
const rest = await Promise.all(Array.from({ length: Math.max(0, (first?.pages || 1) - 1) }, (_, i) => page(i + 2)));
for (const res of rest) if (Array.isArray(res?.data)) items.push(...res.data);
return items;
}
// Starts an online payment for everything still owed on one of my registrations (API v2), with
// an optional donation on top. Partial amounts are only taken from the supervisor payments page.
export type CheckoutResponse = { redirectUrl?: string; priceUpdated?: boolean; newTotal?: number; message?: string };
export async function createFullPaymentCheckout(token: string, registrationId: string, donationAmount?: number): Promise<CheckoutResponse> {
const { apiV2 } = await import("@/lib/apiV2");
const { data } = await apiV2("post", "/registrations/{id}/checkout", {
params: { id: registrationId },
authToken: token,
body: {
...(donationAmount && donationAmount > 0 ? { donationAmount } : {}),
successUrl: window.location.origin + "/payment/success",
cancelUrl: window.location.origin + "/payment/cancel",
failureUrl: window.location.origin + "/payment/failure",
},
});
// The price changed since registering: nothing was started — show the new amount owing.
if (data.priceUpdated) return { priceUpdated: true, newTotal: data.newBalance, message: data.message };
return { redirectUrl: data.redirectUrl };
}