API v2 registrations and payments (1.51.1)

- v2: register, get, cancel and checkout a registration (owner/admin only).
- Registration create/cancel moved to src/services/registrations.ts and online checkout to
  src/services/payments.ts; v1 controllers call the same services (ServiceError carries status).
- Typed frontend calls: npm run api:types writes openapi.json and schema.d.ts; apiV2() helper.
  Register page, Pay now and My Events cancel use v2; apiFetch reads v2 errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
2026-10-29 09:09:09 +02:00
co-authored by Claude Opus 5.5
parent 966fa256b6
commit 310684a563
29 changed files with 4117 additions and 741 deletions
@@ -2,6 +2,7 @@
import React, { useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, createFullPaymentCheckout } from "@/lib/api";
import { apiV2 } from "@/lib/apiV2";
import { useOnlinePayments } from "@/lib/onlinePayments";
import { useRouter } from "next/navigation";
import { formatDate } from "@/lib/date";
@@ -454,10 +455,7 @@ export default function UserDashboardPage() {
if (!token || !activeRegId) return;
setCancelLoading(true);
try {
await apiFetch(`/api/registrations/${encodeURIComponent(activeRegId)}`, {
method: 'DELETE',
authToken: token,
});
await apiV2("post", "/registrations/{id}/cancel", { params: { id: activeRegId }, authToken: token });
const myRegs = await apiFetch<Registration[]>(`/api/registrations/myregistrations?showPast=${showPast ? '1' : '0'}`, { authToken: token });
setRegistrations(myRegs);
setActiveRegId(null);
@@ -3,6 +3,7 @@
import React, { useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { apiV2 } from "@/lib/apiV2";
import { useOnlinePayments } from "@/lib/onlinePayments";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { BundleBuilder, BundleOffers, BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
@@ -552,6 +553,15 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
setError(`The minimum donation is R${MIN_DONATION}. Choose None to skip it.`);
return;
}
// Registers through API v2; returns the new registration (balance = what's owed now).
const register = async (extra: { couponCode?: string; waitlistToken?: string; guest?: { name: string; email: string; phone?: string } }, authToken?: string | null) => {
const named = namedAttendees();
const { data } = await apiV2("post", "/registrations", {
body: { eventId, options: items, analyticsSessionId: analyticsSessionId(), ...(named.length > 0 ? { attendees: named, ticketDelivery: delivery } : {}), ...extra },
authToken,
});
return data;
};
const donationParam = donation > 0 ? `&donation=${encodeURIComponent(donation.toFixed(2))}` : "";
// Claim link without logging in: the link identifies the person.
@@ -559,11 +569,8 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
try {
setError(null);
setCreatingRegistration(true);
const res = await apiFetch<{ id: string; totalDueComputed?: number }>("/api/registrations", {
method: "POST",
body: { eventId, options: items, waitlistToken, analyticsSessionId: analyticsSessionId(), ...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}) },
});
if (res?.id) window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent((res.totalDueComputed ?? payable).toFixed(2))}`;
const res = await register({ waitlistToken });
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent(Math.max(0, res.balance).toFixed(2))}`;
} catch (e) {
setError(errorMessage(e) || "Registration failed");
} finally {
@@ -581,21 +588,10 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
try {
setError(null);
setCreatingRegistration(true);
const res = await apiFetch<{ id: string; totalDueComputed?: number; couponError?: string }>("/api/registrations", {
method: "POST",
body: {
eventId,
options: items,
...(coupon ? { couponCode: coupon.code } : {}),
analyticsSessionId: analyticsSessionId(),
...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}),
...(waitlistToken ? { waitlistToken } : {}),
},
authToken: token,
});
if (res?.id) {
const res = await register({ ...(coupon ? { couponCode: coupon.code } : {}), ...(waitlistToken ? { waitlistToken } : {}) }, token);
{
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
const due = res.totalDueComputed ?? payable;
const due = Math.max(0, res.balance);
const next = hasForm
? `/forms?registrationId=${encodeURIComponent(res.id)}${donationParam}`
: `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent((due || 0).toFixed(2))}${donationParam}`;
@@ -628,15 +624,8 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
try {
setError(null);
setCreatingRegistration(true);
const res = await apiFetch<{ id: string }>("/api/registrations", {
method: "POST",
body: {
eventId, options: items, guestName: guestName.trim(), guestEmail: guestEmail.trim(), guestPhone: guestPhone.trim() || undefined,
analyticsSessionId: analyticsSessionId(),
...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}),
},
});
if (res?.id) {
const res = await register({ guest: { name: guestName.trim(), email: guestEmail.trim(), ...(guestPhone.trim() ? { phone: guestPhone.trim() } : {}) } });
{
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
if (hasForm) {
window.location.href = `/forms?registrationId=${encodeURIComponent(res.id)}`;
File diff suppressed because it is too large Load Diff
+838
View File
@@ -0,0 +1,838 @@
/**
* This file was auto-generated by openapi-typescript.
* Do not make direct changes to the file.
*/
export interface paths {
"/events": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Upcoming public events
* @description Events anyone can see (active, not hidden, live) that have not ended, soonest first.
*
* **Who:** Anyone.
*/
get: operations["getEvents"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/events/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* One public event
* @description With its ticket options (internal kids check-in and volunteer tickets left out) and sessions. Hidden events can be fetched by id (they are unlisted, not private).
*
* **Who:** Anyone.
*/
get: operations["getEventsId"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/registrations": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Register for an event
* @description Signed in, or as a guest for a free event that allows it (`guest` then required), or with a waitlist link (`waitlistToken`).
*
* Registering again for the same event adds to the existing registration. When nothing is owed it is marked paid and tickets are issued; otherwise pay with `POST /registrations/{id}/checkout`.
*
* A coupon that was valid when checked but used up a moment later is reported in `couponError`; the registration is still made.
*
* **Who:** Anyone; signed-in staff may see more.
*/
post: operations["postRegistrations"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/registrations/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* One of my registrations
* @description **Who:** Any signed-in person.
*/
get: operations["getRegistrationsId"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/registrations/{id}/cancel": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Cancel my registration
* @description Not after the event has ended, and not once anything has been paid (the church can do that). Its places go to the waitlist.
*
* **Who:** Any signed-in person.
*/
post: operations["postRegistrationsIdCancel"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/registrations/{id}/checkout": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Pay what I owe online
* @description Starts a payment with the church's provider (Yoco or PayFast) and returns where to send the person (`redirectUrl`).
*
* If an early-bird price ran out since the registration was made, nothing is started: `priceUpdated` is true with the new amount owing — show it, then call again.
*
* **Who:** Any signed-in person.
*/
post: operations["postRegistrationsIdCheckout"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/me": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The signed-in person
* @description **Who:** Any signed-in person.
*/
get: operations["getMe"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/me/registrations": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* My registrations
* @description Newest first. By default only ones for events that have not ended, and not cancelled; `past=true` lists everything.
*
* **Who:** Any signed-in person.
*/
get: operations["getMeRegistrations"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
schemas: {
Error: {
error: {
/** @enum {string} */
code: "VALIDATION_FAILED" | "UNAUTHENTICATED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "RATE_LIMITED" | "READ_ONLY" | "INTERNAL";
message: string;
/** @description Per-field problems (VALIDATION_FAILED only) */
fields?: {
[key: string]: string;
};
};
};
};
responses: never;
parameters: never;
requestBodies: never;
headers: never;
pathItems: never;
}
export type $defs = Record<string, never>;
export interface operations {
getEvents: {
parameters: {
query?: {
/** @description Page number, from 1 */
page?: number;
/** @description Items per page (at most 100) */
limit?: number;
/** @description Search the title */
q?: string;
/** @description A campus id or slug (its events plus church-wide ones), or 'all' for church-wide events only */
campus?: string;
/** @description A series slug */
series?: string;
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
location: string | null;
/** @description The headline price in rand (0 = free) */
price: number;
pictureUrl: string | null;
requiresRegistration: boolean;
/** @enum {string} */
scheduleType: "single" | "sessions";
/** @description null = for all campuses (or campuses are off) */
campus: {
id: string;
name: string;
slug: string;
} | null;
series: {
id: string;
name: string;
slug: string;
} | null;
}[];
meta: {
page: number;
limit: number;
/** @description Items across all pages */
total: number;
/** @description Number of pages (at least 1) */
pages: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getEventsId: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
location: string | null;
/** @description The headline price in rand (0 = free) */
price: number;
pictureUrl: string | null;
requiresRegistration: boolean;
/** @enum {string} */
scheduleType: "single" | "sessions";
/** @description null = for all campuses (or campuses are off) */
campus: {
id: string;
name: string;
slug: string;
} | null;
series: {
id: string;
name: string;
slug: string;
} | null;
description: string | null;
registrationDeadline: string | null;
ticketOptions: {
id: string;
name: string;
/** @description The normal price in rand */
price: number;
/** @description What it costs now (an early-bird price while one runs) */
currentPrice: number;
isMainTicket: boolean;
/**
* @description "pick" = the buyer chooses sessions
* @enum {string}
*/
sessionMode: "all" | "pick";
}[];
/** @description Multi-day events only; empty otherwise */
sessions: {
id: string;
label: string | null;
/** Format: date-time */
startsAt: string;
/** Format: date-time */
endsAt: string;
location: string | null;
cancelled: boolean;
}[];
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postRegistrations: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
eventId: string;
options: {
eventOptionId: string;
quantity: number;
variantId?: string | null;
/** @description "Pick sessions" tickets: the sessions chosen */
sessionIds?: string[];
}[];
guest?: {
name: string;
/** Format: email */
email: string;
phone?: string;
};
couponCode?: string;
/** @description Names for the places (events that collect them) */
attendees?: {
eventOptionId: string;
variantId?: string | null;
name: string;
email?: string | null;
phone?: string | null;
/** @description YYYY-MM-DD (youth events) */
dateOfBirth?: string | null;
gender?: string | null;
parentName?: string | null;
parentEmail?: string | null;
parentPhone?: string | null;
}[];
/**
* @description With attendees: tickets to the payer, or to each attendee
* @enum {string}
*/
ticketDelivery?: "payer" | "each";
waitlistToken?: string;
analyticsSessionId?: string;
};
};
};
responses: {
/** @description OK */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
/** @enum {string} */
status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled";
/** Format: date-time */
createdAt: string;
event: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
};
items: {
ticket: string;
variant: string | null;
quantity: number;
unitPrice: number;
}[];
/** @description In rand, after discounts */
totalDue: number;
/** @description In rand (refunds subtracted) */
amountPaid: number;
/** @description totalDue − amountPaid; 0 or less = nothing owing */
balance: number;
/** @description false = added to an existing registration */
isNew: boolean;
couponError: string | null;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getRegistrationsId: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
/** @enum {string} */
status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled";
/** Format: date-time */
createdAt: string;
event: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
};
items: {
ticket: string;
variant: string | null;
quantity: number;
unitPrice: number;
}[];
/** @description In rand, after discounts */
totalDue: number;
/** @description In rand (refunds subtracted) */
amountPaid: number;
/** @description totalDue − amountPaid; 0 or less = nothing owing */
balance: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postRegistrationsIdCancel: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
/** @enum {string} */
status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled";
/** Format: date-time */
createdAt: string;
event: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
};
items: {
ticket: string;
variant: string | null;
quantity: number;
unitPrice: number;
}[];
/** @description In rand, after discounts */
totalDue: number;
/** @description In rand (refunds subtracted) */
amountPaid: number;
/** @description totalDue − amountPaid; 0 or less = nothing owing */
balance: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postRegistrationsIdCheckout: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description An optional donation added on top, in rand */
donationAmount?: number;
/** @description yoco or payfast (default: the first one switched on) */
provider?: string;
/** Format: uri */
successUrl?: string;
/** Format: uri */
cancelUrl?: string;
/** Format: uri */
failureUrl?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
priceUpdated: true;
newBalance: number;
message: string;
} | {
/** @constant */
priceUpdated: false;
checkoutId: string;
redirectUrl: string;
provider: string;
/** @description Charged now, in rand (with any donation) */
amount: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getMe: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
name: string;
email: string;
phone: string | null;
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
twoFactorEnabled: boolean;
/** Format: date-time */
createdAt: string;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getMeRegistrations: {
parameters: {
query?: {
/** @description Page number, from 1 */
page?: number;
/** @description Items per page (at most 100) */
limit?: number;
/** @description Include past and cancelled registrations */
past?: "true" | "false";
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
/** @enum {string} */
status: "pending" | "confirmed" | "partial_paid" | "paid" | "cancelled";
/** Format: date-time */
createdAt: string;
event: {
id: string;
title: string;
/** Format: date-time */
startDate: string;
/** Format: date-time */
endDate: string;
};
items: {
ticket: string;
variant: string | null;
quantity: number;
unitPrice: number;
}[];
/** @description In rand, after discounts */
totalDue: number;
/** @description In rand (refunds subtracted) */
amountPaid: number;
/** @description totalDue − amountPaid; 0 or less = nothing owing */
balance: number;
}[];
meta: {
page: number;
limit: number;
/** @description Items across all pages */
total: number;
/** @description Number of pages (at least 1) */
pages: number;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}
+17 -9
View File
@@ -74,8 +74,9 @@ export function resolveToApiOrigin(urlOrPath: string | null | undefined): string
return API_BASE ? `${API_BASE}${raw}` : raw;
}
// The parsed JSON body of a failed request — the backend always sends `message`, and
// some routes add a machine-readable `code` or extra detail fields.
// 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 {
@@ -122,6 +123,11 @@ export async function apiFetch<T = unknown>(path: string, options: ApiOptions =
const json = JSON.parse(text);
if (json?.message && typeof json.message === "string") message = json.message;
data = json;
// /api/v2 errors: { error: { code, message, fields? } }
if (json?.error && typeof json.error === "object" && typeof json.error.message === "string") {
message = json.error.message;
data = { ...json.error };
}
} 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.
@@ -198,21 +204,23 @@ export function fetchAllPayments(token: string, params: Record<string, string> =
return fetchAllPages<Payment>("/api/payments", token, params);
}
// Creates an online checkout (default payment provider) for a registration's full remaining balance.
// Omitting `amount` makes the backend charge the full remainder rather than a partial amount —
// partial-amount checkouts are only ever created from the supervisor payments dashboard.
// 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 function createFullPaymentCheckout(token: string, registrationId: string, donationAmount?: number): Promise<CheckoutResponse> {
return apiFetch<CheckoutResponse>("/api/payments/checkout", {
method: "POST",
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: {
registrationId,
...(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 };
}
+44
View File
@@ -0,0 +1,44 @@
import { apiFetch } from "@/lib/api";
import type { paths } from "@/lib/api-v2/schema";
/**
* Typed calls to /api/v2. The types come from the backend's OpenAPI document
* (`npm run api:types` in the repo root regenerates src/lib/api-v2/), so a path, its parameters,
* its body and its answer are all checked by TypeScript:
*
* const { data, meta } = await apiV2("get", "/events", { query: { q: "camp", limit: 10 } });
* const { data } = await apiV2("post", "/registrations/{id}/cancel", { params: { id }, authToken });
*
* Errors throw ApiError (from apiFetch) with the v2 `code` and `fields` in `.data`.
*/
type Method = "get" | "post" | "put" | "patch" | "delete";
type PathsWith<M extends Method> = { [P in keyof paths]: paths[P][M] extends { responses: unknown } ? P : never }[keyof paths];
type Op<P extends keyof paths, M extends Method> = NonNullable<paths[P][M]>;
type Json<T> = T extends { content: { "application/json": infer J } } ? J : never;
type Responses<O> = O extends { responses: infer R } ? R : never;
/** The 2xx answer's JSON. */
export type V2Result<P extends keyof paths, M extends Method> = Json<Responses<Op<P, M>>[Extract<keyof Responses<Op<P, M>>, 200 | 201>]>;
type PathParams<O> = O extends { parameters: { path: infer X } } ? (X extends Record<string, unknown> ? X : never) : never;
type QueryParams<O> = O extends { parameters: { query?: infer X } } ? X : never;
type Body<O> = O extends { requestBody: { content: { "application/json": infer B } } } ? B : never;
type IfAny<T, Then> = [T] extends [never] ? object : Then;
export type V2Options<P extends keyof paths, M extends Method> =
{ authToken?: string | null }
& IfAny<PathParams<Op<P, M>>, { params: PathParams<Op<P, M>> }>
& IfAny<QueryParams<Op<P, M>>, { query?: QueryParams<Op<P, M>> }>
& IfAny<Body<Op<P, M>>, { body: Body<Op<P, M>> }>;
export function apiV2<M extends Method, P extends PathsWith<M>>(method: M, path: P, ...[options]: object extends V2Options<P, M> ? [V2Options<P, M>?] : [V2Options<P, M>]): Promise<V2Result<P, M>> {
const opts = (options || {}) as { authToken?: string | null; params?: Record<string, string>; query?: Record<string, unknown>; body?: unknown };
let url = String(path).replace(/\{(\w+)\}/g, (_, name: string) => encodeURIComponent(String(opts.params?.[name] ?? "")));
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(opts.query || {})) {
if (v !== undefined && v !== null && v !== "") qs.set(k, String(v));
}
if (qs.toString()) url += `?${qs.toString()}`;
return apiFetch<V2Result<P, M>>(`/api/v2${url}`, { method: method.toUpperCase(), authToken: opts.authToken, body: opts.body });
}