WIP 1.51.8: frontend on v2 for event detail, options, sections, attachments, costs, uploads
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import type { Event } from "@/types";
|
||||
|
||||
export const revalidate = 60;
|
||||
@@ -20,7 +19,8 @@ export default async function EventRedirectPage({ params }: { params: Promise<{
|
||||
|
||||
if (VALID_ALIAS.test(redirectUrl)) {
|
||||
try {
|
||||
event = await apiFetch<Event & { message?: string }>(`/api/events/by-alias/${redirectUrl}`);
|
||||
const { apiV2 } = await import("@/lib/apiV2");
|
||||
event = (await apiV2("get", "/events/by-alias/{alias}", { params: { alias: redirectUrl } })).data as unknown as Event;
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch event:", error);
|
||||
}
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { apiFetch, fetchEvent } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import type { EventCost, EventCostType, EventFinancials, CashupMethod, CashupWriteOffCategory, ReconciledByMethod, Event } from "@/types";
|
||||
import { Wallet, DollarSign, ClipboardCheck, FileBarChart } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { createCost, updateCost, deleteCost } from "@/lib/eventSetup";
|
||||
|
||||
const METHOD_LABELS: Record<CashupMethod, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
|
||||
const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"];
|
||||
@@ -42,7 +43,7 @@ export default function EventCashupPage() {
|
||||
try {
|
||||
const [financials, event] = await Promise.all([
|
||||
apiFetch<EventFinancials>(`/api/cashups/event/${eventId}`, { authToken: token }),
|
||||
apiFetch<Event>(`/api/events/${eventId}`, { authToken: token })
|
||||
fetchEvent<Event>(eventId, { authToken: token })
|
||||
]);
|
||||
setData(financials);
|
||||
setEventOptions((event.eventOptions || []).map((o) => ({ id: o.id, name: o.name })));
|
||||
@@ -142,11 +143,11 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
|
||||
setSaving(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const body = { label: label.trim(), costType, amount: parseFloat(amount), eventOptionId: costType === "per_item" ? eventOptionId : null, paidFromMethod: paidFromMethod || null, notes: notes || null };
|
||||
const body = { label: label.trim(), costType, amount: parseFloat(amount), eventOptionId: costType === "per_item" ? eventOptionId : null, paidFromMethod: (paidFromMethod || null) as "cash" | "card" | "eft" | "other" | null, notes: notes || null };
|
||||
if (editingId === "new") {
|
||||
await apiFetch(`/api/events/${eventId}/costs`, { method: "POST", authToken: token, body });
|
||||
await createCost(token, eventId, body);
|
||||
} else {
|
||||
await apiFetch(`/api/costs/${editingId}`, { method: "PUT", authToken: token, body });
|
||||
await updateCost(token, editingId!, body);
|
||||
}
|
||||
setEditingId(null);
|
||||
onChanged();
|
||||
@@ -160,7 +161,7 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
|
||||
const remove = async (id: string) => {
|
||||
if (!confirm("Delete this cost?")) return;
|
||||
try {
|
||||
await apiFetch(`/api/costs/${id}`, { method: "DELETE", authToken: token });
|
||||
await deleteCost(token, id);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || "Failed to delete cost");
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { Suspense, useCallback, useEffect, useRef, useState } from "react
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { apiFetch, ApiError, API_BASE, resolveToApiOrigin } from "@/lib/api";
|
||||
import { apiFetch, ApiError, resolveToApiOrigin } from "@/lib/api";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook } from "lucide-react";
|
||||
@@ -20,6 +20,7 @@ import { extractDominantColors } from "@/lib/extractColors";
|
||||
import { mapsSearchUrl } from "@/lib/maps";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence";
|
||||
|
||||
@@ -232,16 +233,11 @@ function SiteSettingsPageInner() {
|
||||
});
|
||||
|
||||
const uploadBrandingAsset = async (file: File, kind: "logo" | "favicon"): Promise<string> => {
|
||||
const fd = new FormData();
|
||||
fd.append("image", file);
|
||||
const res = await fetch(`${API_BASE}/api/uploads/${kind}`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: fd,
|
||||
});
|
||||
if (!res.ok) throw new Error(`${kind === "logo" ? "Logo" : "Favicon"} upload failed`);
|
||||
const data = await res.json();
|
||||
return data.url || "";
|
||||
try {
|
||||
return await uploadImage(token, kind, file);
|
||||
} catch {
|
||||
throw new Error(`${kind === "logo" ? "Logo" : "Favicon"} upload failed`);
|
||||
}
|
||||
};
|
||||
|
||||
const saveBranding = async () => {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { EventPicker } from "@/components/shared/EventPicker";
|
||||
import { activeSessions, currentSessionLabel, formatSessionWhen, sessionLabel } from "@/lib/sessions";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { apiV2 } from "@/lib/apiV2";
|
||||
import { listSections } from "@/lib/eventSetup";
|
||||
|
||||
// What the confirm step needs, from GET /api/v2/checkin/{qrCode}. Offline scans build the
|
||||
// same shape from the downloaded ticket list.
|
||||
@@ -120,7 +121,7 @@ export default function TicketScanningPage() {
|
||||
}
|
||||
try {
|
||||
setLoadingSections(true);
|
||||
const list = await apiFetch<Section[]>(`/api/sections?eventId=${selectedEventId}`, { authToken: token });
|
||||
const list = await listSections<Section>(token, selectedEventId);
|
||||
setSections(Array.isArray(list) ? list : []);
|
||||
setSelectedSectionId("all");
|
||||
} catch {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, fetchManagedEvents } from "@/lib/api";
|
||||
import { apiFetch, fetchManagedEvents, fetchEvent } from "@/lib/api";
|
||||
import { scoreUser } from "@/lib/fuzzyMatch";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||||
@@ -162,7 +162,7 @@ export default function AtTheDoorPage() {
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const ev = await apiFetch<Event>(`/api/events/${eventId}`, {
|
||||
const ev = await fetchEvent<Event>(eventId, {
|
||||
authToken: token
|
||||
});
|
||||
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { apiFetch, fetchManagedEvents } from "@/lib/api";
|
||||
import { fetchManagedEvents } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Ticket } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import type { Event, EventOption } from "@/types";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { EventPicker } from "@/components/shared/EventPicker";
|
||||
import { createTicketOption, updateTicketOption, deleteTicketOption } from "@/lib/eventSetup";
|
||||
|
||||
// Format a Date (or date-like input) to the value expected by <input type="datetime-local">
|
||||
// This returns local time (browser timezone) as YYYY-MM-DDTHH:mm
|
||||
@@ -160,11 +161,7 @@ function EventOptionsContent() {
|
||||
if (!newOpt.name) { setError("Option name is required"); return; }
|
||||
const priceNum = parseFloat(newOpt.price || "0");
|
||||
try {
|
||||
await apiFetch(`/api/events/${encodeURIComponent(selectedEventId)}/options`, {
|
||||
method: "POST",
|
||||
authToken: token,
|
||||
body: { name: newOpt.name, price: priceNum || 0, isMainTicket: !!newOpt.isMainTicket }
|
||||
});
|
||||
await createTicketOption(token, selectedEventId, { name: newOpt.name, price: priceNum || 0, isMainTicket: !!newOpt.isMainTicket });
|
||||
setNewOpt({ name: "", price: "", isMainTicket: false });
|
||||
setInfo("Option created");
|
||||
await loadEvents();
|
||||
@@ -177,11 +174,7 @@ function EventOptionsContent() {
|
||||
if (!token) return;
|
||||
setError(null); setInfo(null);
|
||||
try {
|
||||
await apiFetch(`/api/events/options/${encodeURIComponent(opt.id)}`, {
|
||||
method: "PUT",
|
||||
authToken: token,
|
||||
body: patch
|
||||
});
|
||||
await updateTicketOption(token, opt.id, patch);
|
||||
setInfo("Option updated");
|
||||
await loadEvents();
|
||||
} catch (e) {
|
||||
@@ -193,10 +186,7 @@ function EventOptionsContent() {
|
||||
if (!token) return;
|
||||
setError(null); setInfo(null);
|
||||
try {
|
||||
await apiFetch(`/api/events/options/${encodeURIComponent(opt.id)}`, {
|
||||
method: "DELETE",
|
||||
authToken: token,
|
||||
});
|
||||
await deleteTicketOption(token, opt.id);
|
||||
setInfo("Option deleted");
|
||||
await loadEvents();
|
||||
} catch (e) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta
|
||||
import { createPortal } from "react-dom";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, API_BASE, fetchManagedEvents } from "@/lib/api";
|
||||
import { apiFetch, API_BASE, fetchManagedEvents, fetchEvent } from "@/lib/api";
|
||||
import { ApiImage } from "@/components/shared/ApiImage";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { toSessionDraft, scheduleSummary } from "@/lib/sessions";
|
||||
import { fetchApiFile, openBlob } from "@/lib/export";
|
||||
import { apiV2 } from "@/lib/apiV2";
|
||||
import { createTicketOption, updateTicketOption, listSections, createSection, updateSection, deleteSection, listAttachments, uploadAttachment, deleteAttachment, uploadImage } from "@/lib/eventSetup";
|
||||
|
||||
// ─── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -61,7 +62,7 @@ type FormFieldType = "yes_no" | "text" | "date" | "numeric" | "statement" | "par
|
||||
type EventFormDef = { isRequired: boolean; fields: { id?: string; type: FormFieldType; label: string; isRequired?: boolean; order?: number; helpText?: string | null; options?: unknown }[] };
|
||||
type FieldDef = EventFormDef["fields"][number];
|
||||
|
||||
// What PUT /api/events/options/:id takes as earlyBirdTiers (variantId null = option-level).
|
||||
// What PATCH /api/v2/ticket-options/{id} takes as earlyBirdTiers (variantId null = option-level).
|
||||
type TierPayload = { id?: string; deadline: string; price: number; stockLimit: number; order: number; variantId: string | null };
|
||||
|
||||
// GET /api/feedback/event/:id — the event's post-event feedback form, if it has one.
|
||||
@@ -120,10 +121,7 @@ function UploadImageButton({ onUploaded, label = "Upload image" }: { onUploaded:
|
||||
if (!file || !token) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("image", file);
|
||||
const res = await apiFetch<{ url?: string; path?: string }>("/api/uploads/event-image", { method: "POST", body: fd, authToken: token });
|
||||
const uploaded = res?.url || res?.path;
|
||||
const uploaded = await uploadImage(token, "event-image", file);
|
||||
if (uploaded) onUploaded(uploaded);
|
||||
} finally { setUploading(false); if (ref.current) ref.current.value = ""; }
|
||||
}} />
|
||||
@@ -506,8 +504,8 @@ function SectionsManager({ eventId }: { eventId: string }) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [secList, evFull] = await Promise.all([
|
||||
apiFetch<Section[]>("/api/sections", { authToken: token || undefined }),
|
||||
apiFetch<Event>(`/api/events/${eventId}`)
|
||||
listSections<Section>(token),
|
||||
fetchEvent<Event>(eventId)
|
||||
]);
|
||||
setSections((secList || []).filter(s => s.eventId === eventId));
|
||||
setEventOptions(evFull?.eventOptions || []);
|
||||
@@ -517,17 +515,17 @@ function SectionsManager({ eventId }: { eventId: string }) {
|
||||
|
||||
const create = async () => {
|
||||
if (!newName.trim() || !token) return;
|
||||
await apiFetch("/api/sections", { method: "POST", authToken: token, body: { eventId, name: newName.trim(), allowedOptionIds: newOptionIds } });
|
||||
await createSection(token, { eventId, name: newName.trim(), allowedOptionIds: newOptionIds });
|
||||
setNewName(""); setNewOptionIds([]); load();
|
||||
};
|
||||
const del = async (id: string) => {
|
||||
if (!token) return;
|
||||
await apiFetch(`/api/sections/${id}`, { method: "DELETE", authToken: token });
|
||||
await deleteSection(token, id);
|
||||
load();
|
||||
};
|
||||
const update = async (id: string, name: string, optionIds: string[]) => {
|
||||
if (!token) return;
|
||||
await apiFetch(`/api/sections/${id}`, { method: "PUT", authToken: token, body: { name, allowedOptionIds: optionIds } });
|
||||
await updateSection(token, id, { name, allowedOptionIds: optionIds });
|
||||
load();
|
||||
};
|
||||
|
||||
@@ -595,8 +593,7 @@ function AttachmentsManager({ eventId }: { eventId: string }) {
|
||||
const ref = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const res = await apiFetch<EventAttachment[]>(`/api/events/${eventId}/attachments`);
|
||||
setItems(Array.isArray(res) ? res : []);
|
||||
setItems(await listAttachments(eventId));
|
||||
}, [eventId]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
@@ -605,16 +602,14 @@ function AttachmentsManager({ eventId }: { eventId: string }) {
|
||||
if (!file || !token) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
await apiFetch(`/api/events/${eventId}/attachments`, { method: "POST", body: fd, authToken: token });
|
||||
await uploadAttachment(token, eventId, file);
|
||||
await load();
|
||||
} finally { setUploading(false); if (ref.current) ref.current.value = ""; }
|
||||
};
|
||||
|
||||
const del = async (id: string) => {
|
||||
if (!token || !confirm("Delete this attachment?")) return;
|
||||
await apiFetch(`/api/events/${eventId}/attachments/${id}`, { method: "DELETE", authToken: token });
|
||||
await deleteAttachment(token, eventId, id);
|
||||
await load();
|
||||
};
|
||||
|
||||
@@ -1040,7 +1035,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
// left out (the kids or volunteer ticket) is dropped rather than widened to "all options".
|
||||
useEffect(() => {
|
||||
if (!cloned || !source?.id || !token) return;
|
||||
apiFetch<Section[]>(`/api/sections?eventId=${source.id}`, { authToken: token }).then(list => {
|
||||
listSections<Section>(token, source.id).then(list => {
|
||||
const drafts: SectionDraft[] = [];
|
||||
for (const sec of list || []) {
|
||||
const ids = (sec.allowedOptions || []).map(o => o.eventOptionId);
|
||||
@@ -1065,7 +1060,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
const formLoadedRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (mode !== "edit" || !ev?.id || formLoadedRef.current) return;
|
||||
apiFetch<Event>(`/api/events/${ev.id}`).then(full => {
|
||||
fetchEvent<Event>(ev.id).then(full => {
|
||||
const f = full?.form;
|
||||
if (f) setFormDef({ isRequired: !!f.isRequired, fields: toFieldDefs(f.fields) });
|
||||
}).catch(() => {}).finally(() => { formLoadedRef.current = true; });
|
||||
@@ -1205,10 +1200,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
|
||||
if (opt.id) {
|
||||
// Update option + variants first to get/confirm variant IDs
|
||||
const updated = await apiFetch<EventOption>(`/api/events/options/${opt.id}`, {
|
||||
method: "PUT", authToken: token || undefined,
|
||||
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all", variants: variantsPayload }
|
||||
});
|
||||
const updated = await updateTicketOption(token, opt.id, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all", variants: variantsPayload });
|
||||
|
||||
// Build variant tiers with confirmed IDs from response
|
||||
const serverVariants = updated?.variants || [];
|
||||
@@ -1224,10 +1216,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
}
|
||||
|
||||
if (allTiers.length > 0 || opt.earlyBirdTiers.length > 0 || opt.variants.some(v => v.earlyBirdTiers.length > 0)) {
|
||||
await apiFetch(`/api/events/options/${opt.id}`, {
|
||||
method: "PUT", authToken: token || undefined,
|
||||
body: { earlyBirdTiers: allTiers }
|
||||
});
|
||||
await updateTicketOption(token, opt.id, { earlyBirdTiers: allTiers });
|
||||
}
|
||||
|
||||
// Handle form save (edit only)
|
||||
@@ -1237,15 +1226,9 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
});
|
||||
} else {
|
||||
// New option added during edit
|
||||
const created = await apiFetch<EventOption>(`/api/events/${eventId}/options`, {
|
||||
method: "POST", authToken: token || undefined,
|
||||
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
|
||||
});
|
||||
const created = await createTicketOption(token, eventId, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
|
||||
if (created?.id) {
|
||||
const updated = await apiFetch<EventOption>(`/api/events/options/${created.id}`, {
|
||||
method: "PUT", authToken: token || undefined,
|
||||
body: { variants: variantsPayload }
|
||||
});
|
||||
const updated = await updateTicketOption(token, created.id, { variants: variantsPayload });
|
||||
const serverVariants = updated?.variants || [];
|
||||
for (let vi = 0; vi < opt.variants.length; vi++) {
|
||||
const v = opt.variants[vi];
|
||||
@@ -1258,9 +1241,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
}
|
||||
}
|
||||
if (allTiers.length > 0) {
|
||||
await apiFetch(`/api/events/options/${created.id}`, {
|
||||
method: "PUT", authToken: token || undefined, body: { earlyBirdTiers: allTiers }
|
||||
});
|
||||
await updateTicketOption(token, created.id, { earlyBirdTiers: allTiers });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1268,7 +1249,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
} else {
|
||||
// Create mode — backend auto-creates a "Main Ticket" option; replace/create from draft
|
||||
let createdEvent: Event | null = null;
|
||||
try { createdEvent = await apiFetch<Event>(`/api/events/${eventId}`); } catch {}
|
||||
try { createdEvent = await fetchEvent<Event>(eventId); } catch {}
|
||||
const existingMain = (createdEvent?.eventOptions || []).find((o) => !!o.isMainTicket);
|
||||
const uiMainIdx = options.findIndex(o => o.isMainTicket);
|
||||
|
||||
@@ -1284,16 +1265,10 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
|
||||
if (i === uiMainIdx && existingMain) {
|
||||
// Update the auto-created main ticket
|
||||
await apiFetch(`/api/events/options/${existingMain.id}`, {
|
||||
method: "PUT", authToken: token || undefined,
|
||||
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: true, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
|
||||
});
|
||||
await updateTicketOption(token, existingMain.id, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: true, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
|
||||
optId = existingMain.id;
|
||||
} else {
|
||||
const created = await apiFetch<EventOption>(`/api/events/${eventId}/options`, {
|
||||
method: "POST", authToken: token || undefined,
|
||||
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
|
||||
});
|
||||
const created = await createTicketOption(token, eventId, { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" });
|
||||
optId = created?.id;
|
||||
}
|
||||
|
||||
@@ -1305,9 +1280,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
.map((t, ti) => ({ deadline: new Date(t.deadline).toISOString(), price: parseFloat(t.price), stockLimit: parseInt(t.stockLimit || "0"), order: ti, variantId: null }));
|
||||
|
||||
if (variantsPayload.length > 0 || opt.variants.some(v => v.earlyBirdTiers.length > 0)) {
|
||||
const updated = await apiFetch<EventOption>(`/api/events/options/${optId}`, {
|
||||
method: "PUT", authToken: token || undefined, body: { variants: variantsPayload }
|
||||
});
|
||||
const updated = await updateTicketOption(token, optId, { variants: variantsPayload });
|
||||
const serverVariants = updated?.variants || [];
|
||||
for (let vi = 0; vi < opt.variants.length; vi++) {
|
||||
const v = opt.variants[vi];
|
||||
@@ -1322,9 +1295,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
}
|
||||
|
||||
if (allTiers.length > 0) {
|
||||
await apiFetch(`/api/events/options/${optId}`, {
|
||||
method: "PUT", authToken: token || undefined, body: { earlyBirdTiers: allTiers }
|
||||
});
|
||||
await updateTicketOption(token, optId, { earlyBirdTiers: allTiers });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1337,10 +1308,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
.map(idx => createdOptions[idx]?.id)
|
||||
.filter(Boolean);
|
||||
try {
|
||||
await apiFetch("/api/sections", {
|
||||
method: "POST", authToken: token || undefined,
|
||||
body: { eventId, name: sec.name.trim(), allowedOptionIds: optionIds }
|
||||
});
|
||||
await createSection(token, { eventId, name: sec.name.trim(), allowedOptionIds: optionIds as string[] });
|
||||
} catch {}
|
||||
}
|
||||
};
|
||||
@@ -1430,14 +1398,12 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP
|
||||
await apiV2("post", "/events/{id}/copy-from", { params: { id: created.id }, authToken: token, body: { fromEventId: source!.id } });
|
||||
}
|
||||
// Fetch event to get final option IDs for sections
|
||||
const fullEvent = await apiFetch<Event>(`/api/events/${created.id}`).catch(() => null);
|
||||
const fullEvent = await fetchEvent<Event>(created.id).catch(() => null);
|
||||
const createdOptions = fullEvent?.eventOptions || [];
|
||||
if (sectionDrafts.length > 0) await saveStagedSections(created.id, createdOptions);
|
||||
// Upload staged attachments
|
||||
for (const file of stagedFiles) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
await apiFetch(`/api/events/${created.id}/attachments`, { method: "POST", body: fd, authToken: token || undefined });
|
||||
await uploadAttachment(token, created.id, file);
|
||||
}
|
||||
// Save staged notify recipients
|
||||
if (notifyRecipientDrafts.length > 0) {
|
||||
@@ -2090,7 +2056,7 @@ export default function ManageEventsPage() {
|
||||
const openCreate = () => { setEditingEvent(null); setModalMode("create"); };
|
||||
const openEdit = async (ev: Event) => {
|
||||
try {
|
||||
const full = await apiFetch<Event>(`/api/events/${ev.id}`, { authToken: token || undefined });
|
||||
const full = await fetchEvent<Event>(ev.id, { authToken: token || undefined });
|
||||
setEditingEvent(full);
|
||||
} catch { setEditingEvent(ev); }
|
||||
setModalMode("edit");
|
||||
@@ -2099,7 +2065,7 @@ export default function ManageEventsPage() {
|
||||
const [copyFrom, setCopyFrom] = useState<Event | null>(null);
|
||||
const openCopy = async (ev: Event) => {
|
||||
try {
|
||||
const full = await apiFetch<Event>(`/api/events/${ev.id}`, { authToken: token || undefined });
|
||||
const full = await fetchEvent<Event>(ev.id, { authToken: token || undefined });
|
||||
setEditingEvent(null);
|
||||
setCopyFrom(full);
|
||||
setModalMode("create");
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ExtraFieldInput, isExtraFieldType, ChoicesEditor } from "@/components/s
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, fetchAllUsers, fetchManagedEvents } from "@/lib/api";
|
||||
import { apiFetch, fetchAllUsers, fetchManagedEvents, fetchEvent } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { FileText } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
@@ -308,7 +308,7 @@ export default function FormsBrowserPage() {
|
||||
if (!eventId) return;
|
||||
try {
|
||||
setFormLoading(true);
|
||||
const evFull = await apiFetch<Event>(`/api/events/${encodeURIComponent(eventId)}`);
|
||||
const evFull = await fetchEvent<Event>(eventId);
|
||||
setFormDef(toFormDef(evFull?.form));
|
||||
setFormLoadedFor(eventId);
|
||||
} catch (e) {
|
||||
@@ -377,7 +377,7 @@ export default function FormsBrowserPage() {
|
||||
const reg = await apiFetch<Registration>(`/api/registrations/${encodeURIComponent(fillRegistrationId)}`, { authToken: token! });
|
||||
setFillRegistration(reg);
|
||||
if (reg?.event?.id) {
|
||||
const evFull = await apiFetch<Event>(`/api/events/${encodeURIComponent(reg.event.id)}`);
|
||||
const evFull = await fetchEvent<Event>(reg.event.id);
|
||||
setFillForm(toFormDef(evFull?.form));
|
||||
}
|
||||
const resList = await apiFetch<{ items?: FormResponse[] } | FormResponse[]>(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! });
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { apiFetch, fetchEvent } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { UserPlus } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
@@ -51,7 +51,7 @@ export default function ManualRegistrationPage() {
|
||||
setCreatedReg(res);
|
||||
// Load form definition for this event (if any)
|
||||
try {
|
||||
const ev = await apiFetch<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(`/api/events/${encodeURIComponent(eventId)}`);
|
||||
const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(eventId);
|
||||
if (ev?.form) setForm(ev.form);
|
||||
} catch {}
|
||||
alert("Manual registration created");
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, fetchAllUsers, fetchManagedEvents } from "@/lib/api";
|
||||
import { apiFetch, fetchAllUsers, fetchManagedEvents, fetchEvent } from "@/lib/api";
|
||||
import { scoreUser } from "@/lib/fuzzyMatch";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||||
@@ -277,7 +277,7 @@ export default function ManualRegistrationPage() {
|
||||
useEffect(() => {
|
||||
if (!selectedEventId) { setBundles([]); setFullEvent(null); return; }
|
||||
let cancelled = false;
|
||||
apiFetch<Event>(`/api/events/${selectedEventId}`, { authToken: token || undefined })
|
||||
fetchEvent<Event>(selectedEventId, { authToken: token || undefined })
|
||||
.then(ev => { if (!cancelled) { setBundles(ev?.bundles || []); setFullEvent(ev || null); } })
|
||||
.catch(() => { if (!cancelled) { setBundles([]); setFullEvent(null); } });
|
||||
return () => { cancelled = true; };
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField
|
||||
import React, { Suspense, useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { apiFetch, fetchEvent } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { FileText } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
@@ -37,7 +37,7 @@ function FormsContent() {
|
||||
try {
|
||||
const reg = await apiFetch<Registration>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
|
||||
setRegistration(reg);
|
||||
const ev = await apiFetch<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(`/api/events/${encodeURIComponent(reg.eventId)}`);
|
||||
const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(reg.eventId);
|
||||
if (ev?.form) setEventForm(ev.form);
|
||||
// Load any saved draft
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch, createFullPaymentCheckout } from "@/lib/api";
|
||||
import { apiFetch, createFullPaymentCheckout, fetchEvent } from "@/lib/api";
|
||||
import { apiV2 } from "@/lib/apiV2";
|
||||
import { useOnlinePayments } from "@/lib/onlinePayments";
|
||||
import { useRouter } from "next/navigation";
|
||||
@@ -383,7 +383,7 @@ export default function UserDashboardPage() {
|
||||
}
|
||||
(async () => {
|
||||
try {
|
||||
const ev = await apiFetch<Event>(`/api/events/${encodeURIComponent(ar.eventId)}`);
|
||||
const ev = await fetchEvent<Event>(ar.eventId);
|
||||
const has = !!(ev?.form && Array.isArray(ev.form.fields) && ev.form.fields.length > 0);
|
||||
setActiveEventHasForm(has);
|
||||
} catch {
|
||||
@@ -509,7 +509,7 @@ export default function UserDashboardPage() {
|
||||
setEditLoading(true);
|
||||
try {
|
||||
// Load event options (with variants) for this event
|
||||
const eventData = await apiFetch<Event>(`/api/events/${encodeURIComponent(activeReg.eventId)}`);
|
||||
const eventData = await fetchEvent<Event>(activeReg.eventId);
|
||||
const eventOptions = (eventData?.eventOptions || []).filter((eo) => !isPickOption(eventData, eo));
|
||||
|
||||
const regOptById = new Map<string, RegistrationOption>((activeReg.registrationOptions || []).map((o) => [o.id, o]));
|
||||
|
||||
@@ -53,7 +53,7 @@ export default function ClientActions({ event }: Props) {
|
||||
Save QR
|
||||
</button>
|
||||
<a
|
||||
href={`${API_BASE}/api/events/${event.id}/ics`}
|
||||
href={`${API_BASE}/api/v2/events/${event.id}/calendar.ics`}
|
||||
download
|
||||
className="flex items-center gap-2 px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors text-sm font-medium"
|
||||
>
|
||||
|
||||
@@ -59,7 +59,7 @@ type Event = {
|
||||
nextInSeries?: NextInSeries | null;
|
||||
};
|
||||
|
||||
import { apiFetch, ApiError, resolveToApiOrigin } from "@/lib/api";
|
||||
import { ApiError, resolveToApiOrigin, fetchEvent } from "@/lib/api";
|
||||
import { ApiImage } from "@/components/shared/ApiImage";
|
||||
import { formatDateTimeRange } from "@/lib/date";
|
||||
import { BundleOffers } from "@/components/shared/BundleDeals";
|
||||
@@ -142,7 +142,7 @@ function RegisterCta({ event }: { event: Event }) {
|
||||
// request, so calling this again from the page component below is free.
|
||||
async function loadEvent(id: string): Promise<Event | null> {
|
||||
try {
|
||||
return await apiFetch<Event>(`/api/events/${id}`, { nextOptions: { next: { revalidate } } });
|
||||
return await fetchEvent<Event>(id, { nextOptions: { next: { revalidate } } });
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 404) return null;
|
||||
throw e;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormField
|
||||
import React, { Suspense, useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { apiFetch, fetchEvent } from "@/lib/api";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { FileText } from "lucide-react";
|
||||
@@ -42,7 +42,7 @@ function FormsContent() {
|
||||
// authToken optional — guests access via registrationId alone
|
||||
const reg = await apiFetch<Registration>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token || undefined });
|
||||
setRegistration(reg);
|
||||
const ev = await apiFetch<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(`/api/events/${encodeURIComponent(reg.eventId)}`);
|
||||
const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(reg.eventId);
|
||||
if (ev?.form) setEventForm(ev.form);
|
||||
// Load any saved draft to prefill fields
|
||||
try {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { ApiError, fetchEvent } from "@/lib/api";
|
||||
import RegisterForm, { type RegisterEvent } from "./RegisterForm";
|
||||
import { FunnelTracker } from "@/components/events/FunnelTracker";
|
||||
|
||||
@@ -13,7 +13,7 @@ export default async function RegisterPage({ params }: { params: Promise<{ event
|
||||
try {
|
||||
// Fetched server-side (same pattern as /events/[id]) so the form's content is part of
|
||||
// the initial HTML instead of showing a loading skeleton after a client-side fetch.
|
||||
event = await apiFetch<RegisterEvent>(`/api/events/${eventId}`, { nextOptions: { next: { revalidate } } });
|
||||
event = await fetchEvent<RegisterEvent>(eventId, { nextOptions: { next: { revalidate } } });
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 404) notFound();
|
||||
throw e;
|
||||
|
||||
@@ -43,7 +43,7 @@ function RegistrationSuccessContent() {
|
||||
const r = token ? await (await import('@/lib/api')).apiFetch<Registration>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token }) : null;
|
||||
if (r) {
|
||||
setReg(r);
|
||||
const ev = await (await import('@/lib/api')).apiFetch<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(`/api/events/${encodeURIComponent(r.eventId)}`);
|
||||
const ev = await (await import('@/lib/api')).fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(r.eventId);
|
||||
if (ev?.form) setForm(ev.form);
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormFieldExtras";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { apiFetch, fetchManagedEvents } from "@/lib/api";
|
||||
import { apiFetch, fetchManagedEvents, fetchEvent } from "@/lib/api";
|
||||
import { AuthResponse, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
|
||||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||||
import { BundleBuilder, BundleOffers, BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
|
||||
@@ -218,7 +218,7 @@ export default function SelfServicePage() {
|
||||
useEffect(() => {
|
||||
if (!selectedEventId) { setKioskBundles([]); setKioskFull(null); return; }
|
||||
let cancelled = false;
|
||||
apiFetch<Event>(`/api/events/${selectedEventId}`, { authToken: supervisorToken || undefined })
|
||||
fetchEvent<Event>(selectedEventId, { authToken: supervisorToken || undefined })
|
||||
.then(ev => { if (!cancelled) { setKioskBundles(ev?.bundles || []); setKioskFull(ev || null); } })
|
||||
.catch(() => { if (!cancelled) { setKioskBundles([]); setKioskFull(null); } });
|
||||
return () => { cancelled = true; };
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch, API_BASE } from "@/lib/api";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { ColorPickerField } from "@/components/admin/ColorPickerField";
|
||||
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
|
||||
import { extractDominantColors } from "@/lib/extractColors";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { ConnectForm } from "@/components/admin/LicenceTab";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
|
||||
type Step = 1 | 2 | 3 | 4 | 5 | 6;
|
||||
|
||||
@@ -196,36 +197,12 @@ export default function SetupPage() {
|
||||
// setupToken from /api/setup/register covers that.
|
||||
let logoUrl = "";
|
||||
if (logoFile) {
|
||||
const fd = new FormData();
|
||||
fd.append("image", logoFile);
|
||||
const uploadRes = await fetch(`${API_BASE}/api/uploads/logo`, {
|
||||
method: "POST",
|
||||
headers: setupToken ? { Authorization: `Bearer ${setupToken}` } : undefined,
|
||||
body: fd,
|
||||
});
|
||||
if (uploadRes.ok) {
|
||||
const up = await uploadRes.json();
|
||||
logoUrl = up.url || "";
|
||||
} else {
|
||||
throw new Error("Logo upload failed. Please try again.");
|
||||
}
|
||||
logoUrl = await uploadImage(setupToken, "logo", logoFile).catch(() => { throw new Error("Logo upload failed. Please try again."); });
|
||||
}
|
||||
|
||||
let faviconUrl = "";
|
||||
if (faviconFile) {
|
||||
const fd = new FormData();
|
||||
fd.append("image", faviconFile);
|
||||
const uploadRes = await fetch(`${API_BASE}/api/uploads/favicon`, {
|
||||
method: "POST",
|
||||
headers: setupToken ? { Authorization: `Bearer ${setupToken}` } : undefined,
|
||||
body: fd,
|
||||
});
|
||||
if (uploadRes.ok) {
|
||||
const up = await uploadRes.json();
|
||||
faviconUrl = up.url || "";
|
||||
} else {
|
||||
throw new Error("Favicon upload failed. Please try again.");
|
||||
}
|
||||
faviconUrl = await uploadImage(setupToken, "favicon", faviconFile).catch(() => { throw new Error("Favicon upload failed. Please try again."); });
|
||||
}
|
||||
|
||||
const settings: Record<string, string> = {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import React, { useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
|
||||
export function FileUploader({ onUploaded }: { onUploaded: (url: string) => void }) {
|
||||
const { token } = useAuth();
|
||||
@@ -16,14 +16,7 @@ export function FileUploader({ onUploaded }: { onUploaded: (url: string) => void
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("image", file);
|
||||
const data = await apiFetch<{ url: string }>(`/api/uploads/event-image`, {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
authToken: token,
|
||||
});
|
||||
onUploaded(data.url);
|
||||
onUploaded(await uploadImage(token, "event-image", file));
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Upload failed");
|
||||
} finally {
|
||||
|
||||
@@ -216,6 +216,17 @@ export async function fetchManagedEvents<T = Event>(token: string | null | undef
|
||||
return data as unknown as T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export function fetchAllUsers(token: string, params: Record<string, string> = {}): Promise<User[]> {
|
||||
return fetchAllPages<User>("/api/users", token, params);
|
||||
}
|
||||
|
||||
@@ -27,18 +27,21 @@ type Body<O> = O extends { requestBody: { content: { "application/json": infer B
|
||||
|
||||
type IfAny<T, Then> = [T] extends [never] ? object : Then;
|
||||
export type V2Options<P extends keyof paths, M extends Method> =
|
||||
{ authToken?: string | null }
|
||||
{ authToken?: string | null; nextOptions?: RequestInit }
|
||||
& 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 };
|
||||
const opts = (options || {}) as { authToken?: string | null; nextOptions?: RequestInit; 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 });
|
||||
return apiFetch<V2Result<P, M>>(`/api/v2${url}`, { method: method.toUpperCase(), authToken: opts.authToken, body: opts.body, nextOptions: opts.nextOptions });
|
||||
}
|
||||
|
||||
/** The JSON body a v2 endpoint takes. */
|
||||
export type V2Body<P extends keyof paths, M extends Method> = Body<Op<P, M>>;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { apiV2, type V2Body } from "@/lib/apiV2";
|
||||
import type { EventAttachment, EventOption } from "@/types";
|
||||
|
||||
/**
|
||||
* Event set-up calls on API v2 (1.51.8): ticket options and variants, scanning sections,
|
||||
* attachments, planned costs and image uploads. Each returns what the screens already work with.
|
||||
*/
|
||||
|
||||
type Token = string | null | undefined;
|
||||
|
||||
// ─── Ticket options ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function createTicketOption(token: Token, eventId: string, body: V2Body<"/events/{id}/ticket-options", "post">): Promise<EventOption> {
|
||||
const { data } = await apiV2("post", "/events/{id}/ticket-options", { params: { id: eventId }, authToken: token, body });
|
||||
return data as unknown as EventOption;
|
||||
}
|
||||
|
||||
/** Only what's sent changes; `earlyBirdTiers` and `variants`, when sent, are the full lists. */
|
||||
export async function updateTicketOption(token: Token, optionId: string, body: V2Body<"/ticket-options/{id}", "patch">): Promise<EventOption> {
|
||||
const { data } = await apiV2("patch", "/ticket-options/{id}", { params: { id: optionId }, authToken: token, body });
|
||||
return data as unknown as EventOption;
|
||||
}
|
||||
|
||||
export async function deleteTicketOption(token: Token, optionId: string): Promise<void> {
|
||||
await apiV2("delete", "/ticket-options/{id}", { params: { id: optionId }, authToken: token });
|
||||
}
|
||||
|
||||
// ─── Scanning sections ───────────────────────────────────────────────────────
|
||||
|
||||
export type SectionRecord = { id: string; eventId: string; name: string; allowedOptions?: { eventOptionId: string; eventOption?: { id: string; name: string } }[] };
|
||||
|
||||
export async function listSections<T = SectionRecord>(token: Token, eventId?: string): Promise<T[]> {
|
||||
const { data } = await apiV2("get", "/sections", { authToken: token, query: eventId ? { eventId } : {} });
|
||||
return data as unknown as T[];
|
||||
}
|
||||
|
||||
export async function createSection(token: Token, body: V2Body<"/sections", "post">): Promise<SectionRecord> {
|
||||
const { data } = await apiV2("post", "/sections", { authToken: token, body });
|
||||
return data as unknown as SectionRecord;
|
||||
}
|
||||
|
||||
export async function updateSection(token: Token, sectionId: string, body: V2Body<"/sections/{id}", "patch">): Promise<SectionRecord> {
|
||||
const { data } = await apiV2("patch", "/sections/{id}", { params: { id: sectionId }, authToken: token, body });
|
||||
return data as unknown as SectionRecord;
|
||||
}
|
||||
|
||||
export async function deleteSection(token: Token, sectionId: string): Promise<void> {
|
||||
await apiV2("delete", "/sections/{id}", { params: { id: sectionId }, authToken: token });
|
||||
}
|
||||
|
||||
// ─── Attachments ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listAttachments(eventId: string): Promise<EventAttachment[]> {
|
||||
const { data } = await apiV2("get", "/events/{id}/attachments", { params: { id: eventId } });
|
||||
return data as unknown as EventAttachment[];
|
||||
}
|
||||
|
||||
/** Uploads a file (PDF, Office, text, CSV or ZIP, up to 20 MB) to an event. */
|
||||
export async function uploadAttachment(token: Token, eventId: string, file: File): Promise<EventAttachment> {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const { apiFetch } = await import("@/lib/api");
|
||||
const { data } = await apiFetch<{ data: EventAttachment }>(`/api/v2/events/${encodeURIComponent(eventId)}/attachments`, { method: "POST", body: fd, authToken: token });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteAttachment(token: Token, eventId: string, attachmentId: string): Promise<void> {
|
||||
await apiV2("delete", "/events/{id}/attachments/{attachmentId}", { params: { id: eventId, attachmentId }, authToken: token });
|
||||
}
|
||||
|
||||
// ─── Planned costs ───────────────────────────────────────────────────────────
|
||||
|
||||
export async function createCost(token: Token, eventId: string, body: V2Body<"/events/{id}/costs", "post">): Promise<void> {
|
||||
await apiV2("post", "/events/{id}/costs", { params: { id: eventId }, authToken: token, body });
|
||||
}
|
||||
|
||||
export async function updateCost(token: Token, costId: string, body: V2Body<"/costs/{id}", "patch">): Promise<void> {
|
||||
await apiV2("patch", "/costs/{id}", { params: { id: costId }, authToken: token, body });
|
||||
}
|
||||
|
||||
export async function deleteCost(token: Token, costId: string): Promise<void> {
|
||||
await apiV2("delete", "/costs/{id}", { params: { id: costId }, authToken: token });
|
||||
}
|
||||
|
||||
// ─── Image uploads ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Uploads an image (field "image") and returns the path to save (`/uploads/…`). `logo` and
|
||||
* `favicon` work without a token during first-time setup.
|
||||
*/
|
||||
export async function uploadImage(token: Token, kind: "event-image" | "logo" | "favicon", file: File | Blob): Promise<string> {
|
||||
const fd = new FormData();
|
||||
fd.append("image", file);
|
||||
const { apiFetch } = await import("@/lib/api");
|
||||
const { data } = await apiFetch<{ data: { path: string; url: string } }>(`/api/v2/uploads/${kind}`, { method: "POST", body: fd, authToken: token });
|
||||
return data.path;
|
||||
}
|
||||
Reference in New Issue
Block a user