diff --git a/apps/events/frontend/src/app/[redirectUrl]/page.tsx b/apps/events/frontend/src/app/[redirectUrl]/page.tsx index 1b4148b..1c1239e 100644 --- a/apps/events/frontend/src/app/[redirectUrl]/page.tsx +++ b/apps/events/frontend/src/app/[redirectUrl]/page.tsx @@ -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(`/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); } diff --git a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx index 840406c..673c9cd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx @@ -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 = { 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(`/api/cashups/event/${eventId}`, { authToken: token }), - apiFetch(`/api/events/${eventId}`, { authToken: token }) + fetchEvent(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"); diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index 28e8de7..ffccfda 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -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 => { - 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 () => { diff --git a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx index 362d1a1..98b8f54 100644 --- a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx @@ -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(`/api/sections?eventId=${selectedEventId}`, { authToken: token }); + const list = await listSections
(token, selectedEventId); setSections(Array.isArray(list) ? list : []); setSelectedSectionId("all"); } catch { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx index 6234439..c87b778 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -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(`/api/events/${eventId}`, { + const ev = await fetchEvent(eventId, { authToken: token }); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx index c304769..90ada17 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx @@ -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 // 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) { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx index 40db481..c8446d8 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx @@ -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("/api/sections", { authToken: token || undefined }), - apiFetch(`/api/events/${eventId}`) + listSections
(token), + fetchEvent(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(null); const load = useCallback(async () => { - const res = await apiFetch(`/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(`/api/sections?eventId=${source.id}`, { authToken: token }).then(list => { + listSections
(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(`/api/events/${ev.id}`).then(full => { + fetchEvent(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(`/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(`/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(`/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(`/api/events/${eventId}`); } catch {} + try { createdEvent = await fetchEvent(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(`/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(`/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(`/api/events/${created.id}`).catch(() => null); + const fullEvent = await fetchEvent(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(`/api/events/${ev.id}`, { authToken: token || undefined }); + const full = await fetchEvent(ev.id, { authToken: token || undefined }); setEditingEvent(full); } catch { setEditingEvent(ev); } setModalMode("edit"); @@ -2099,7 +2065,7 @@ export default function ManageEventsPage() { const [copyFrom, setCopyFrom] = useState(null); const openCopy = async (ev: Event) => { try { - const full = await apiFetch(`/api/events/${ev.id}`, { authToken: token || undefined }); + const full = await fetchEvent(ev.id, { authToken: token || undefined }); setEditingEvent(null); setCopyFrom(full); setModalMode("create"); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx index 7767055..c6f0984 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx @@ -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(`/api/events/${encodeURIComponent(eventId)}`); + const evFull = await fetchEvent(eventId); setFormDef(toFormDef(evFull?.form)); setFormLoadedFor(eventId); } catch (e) { @@ -377,7 +377,7 @@ export default function FormsBrowserPage() { const reg = await apiFetch(`/api/registrations/${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); setFillRegistration(reg); if (reg?.event?.id) { - const evFull = await apiFetch(`/api/events/${encodeURIComponent(reg.event.id)}`); + const evFull = await fetchEvent(reg.event.id); setFillForm(toFormDef(evFull?.form)); } const resList = await apiFetch<{ items?: FormResponse[] } | FormResponse[]>(`/api/forms/responses?registrationId=${encodeURIComponent(fillRegistrationId)}`, { authToken: token! }); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx index 13680dd..40c6414 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/manual-registration/page.tsx @@ -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"); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx index 21de981..ea9f7d1 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx @@ -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(`/api/events/${selectedEventId}`, { authToken: token || undefined }) + fetchEvent(selectedEventId, { authToken: token || undefined }) .then(ev => { if (!cancelled) { setBundles(ev?.bundles || []); setFullEvent(ev || null); } }) .catch(() => { if (!cancelled) { setBundles([]); setFullEvent(null); } }); return () => { cancelled = true; }; diff --git a/apps/events/frontend/src/app/dashboard/user/forms/page.tsx b/apps/events/frontend/src/app/dashboard/user/forms/page.tsx index 2a2474d..0605e54 100644 --- a/apps/events/frontend/src/app/dashboard/user/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/forms/page.tsx @@ -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(`/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 { diff --git a/apps/events/frontend/src/app/dashboard/user/page.tsx b/apps/events/frontend/src/app/dashboard/user/page.tsx index 63214ee..e88ebdf 100644 --- a/apps/events/frontend/src/app/dashboard/user/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/page.tsx @@ -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(`/api/events/${encodeURIComponent(ar.eventId)}`); + const ev = await fetchEvent(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(`/api/events/${encodeURIComponent(activeReg.eventId)}`); + const eventData = await fetchEvent(activeReg.eventId); const eventOptions = (eventData?.eventOptions || []).filter((eo) => !isPickOption(eventData, eo)); const regOptById = new Map((activeReg.registrationOptions || []).map((o) => [o.id, o])); diff --git a/apps/events/frontend/src/app/events/[id]/ClientActions.tsx b/apps/events/frontend/src/app/events/[id]/ClientActions.tsx index a701d0b..5a47cbd 100644 --- a/apps/events/frontend/src/app/events/[id]/ClientActions.tsx +++ b/apps/events/frontend/src/app/events/[id]/ClientActions.tsx @@ -53,7 +53,7 @@ export default function ClientActions({ event }: Props) { Save QR diff --git a/apps/events/frontend/src/app/events/[id]/page.tsx b/apps/events/frontend/src/app/events/[id]/page.tsx index 27706b2..1e459e1 100644 --- a/apps/events/frontend/src/app/events/[id]/page.tsx +++ b/apps/events/frontend/src/app/events/[id]/page.tsx @@ -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 { try { - return await apiFetch(`/api/events/${id}`, { nextOptions: { next: { revalidate } } }); + return await fetchEvent(id, { nextOptions: { next: { revalidate } } }); } catch (e) { if (e instanceof ApiError && e.status === 404) return null; throw e; diff --git a/apps/events/frontend/src/app/forms/page.tsx b/apps/events/frontend/src/app/forms/page.tsx index a69d177..dd2e568 100644 --- a/apps/events/frontend/src/app/forms/page.tsx +++ b/apps/events/frontend/src/app/forms/page.tsx @@ -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(`/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 { diff --git a/apps/events/frontend/src/app/register/[eventId]/page.tsx b/apps/events/frontend/src/app/register/[eventId]/page.tsx index 7457e48..1eb9967 100644 --- a/apps/events/frontend/src/app/register/[eventId]/page.tsx +++ b/apps/events/frontend/src/app/register/[eventId]/page.tsx @@ -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(`/api/events/${eventId}`, { nextOptions: { next: { revalidate } } }); + event = await fetchEvent(eventId, { nextOptions: { next: { revalidate } } }); } catch (e) { if (e instanceof ApiError && e.status === 404) notFound(); throw e; diff --git a/apps/events/frontend/src/app/registration/success/page.tsx b/apps/events/frontend/src/app/registration/success/page.tsx index 4c2b2db..e989617 100644 --- a/apps/events/frontend/src/app/registration/success/page.tsx +++ b/apps/events/frontend/src/app/registration/success/page.tsx @@ -43,7 +43,7 @@ function RegistrationSuccessContent() { const r = token ? await (await import('@/lib/api')).apiFetch(`/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) { diff --git a/apps/events/frontend/src/app/self-service/page.tsx b/apps/events/frontend/src/app/self-service/page.tsx index 4f0e7ec..74fe945 100644 --- a/apps/events/frontend/src/app/self-service/page.tsx +++ b/apps/events/frontend/src/app/self-service/page.tsx @@ -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(`/api/events/${selectedEventId}`, { authToken: supervisorToken || undefined }) + fetchEvent(selectedEventId, { authToken: supervisorToken || undefined }) .then(ev => { if (!cancelled) { setKioskBundles(ev?.bundles || []); setKioskFull(ev || null); } }) .catch(() => { if (!cancelled) { setKioskBundles([]); setKioskFull(null); } }); return () => { cancelled = true; }; diff --git a/apps/events/frontend/src/app/setup/page.tsx b/apps/events/frontend/src/app/setup/page.tsx index 026081f..569547e 100644 --- a/apps/events/frontend/src/app/setup/page.tsx +++ b/apps/events/frontend/src/app/setup/page.tsx @@ -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 = { diff --git a/apps/events/frontend/src/components/forms/FileUploader.tsx b/apps/events/frontend/src/components/forms/FileUploader.tsx index dbad63b..db37530 100644 --- a/apps/events/frontend/src/components/forms/FileUploader.tsx +++ b/apps/events/frontend/src/components/forms/FileUploader.tsx @@ -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 { diff --git a/apps/events/frontend/src/lib/api.ts b/apps/events/frontend/src/lib/api.ts index 3b0ab33..17d8818 100644 --- a/apps/events/frontend/src/lib/api.ts +++ b/apps/events/frontend/src/lib/api.ts @@ -216,6 +216,17 @@ export async function fetchManagedEvents(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(id: string, options: { authToken?: string | null; nextOptions?: RequestInit } = {}): Promise { + 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 = {}): Promise { return fetchAllPages("/api/users", token, params); } diff --git a/apps/events/frontend/src/lib/apiV2.ts b/apps/events/frontend/src/lib/apiV2.ts index 44db364..ee51c13 100644 --- a/apps/events/frontend/src/lib/apiV2.ts +++ b/apps/events/frontend/src/lib/apiV2.ts @@ -27,18 +27,21 @@ type Body = O extends { requestBody: { content: { "application/json": infer B type IfAny = [T] extends [never] ? object : Then; export type V2Options

= - { authToken?: string | null } + { authToken?: string | null; nextOptions?: RequestInit } & IfAny>, { params: PathParams> }> & IfAny>, { query?: QueryParams> }> & IfAny>, { body: Body> }>; export function apiV2>(method: M, path: P, ...[options]: object extends V2Options ? [V2Options?] : [V2Options]): Promise> { - const opts = (options || {}) as { authToken?: string | null; params?: Record; query?: Record; body?: unknown }; + const opts = (options || {}) as { authToken?: string | null; nextOptions?: RequestInit; params?: Record; query?: Record; 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>(`/api/v2${url}`, { method: method.toUpperCase(), authToken: opts.authToken, body: opts.body }); + return apiFetch>(`/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

= Body>; diff --git a/apps/events/frontend/src/lib/eventSetup.ts b/apps/events/frontend/src/lib/eventSetup.ts new file mode 100644 index 0000000..d5be032 --- /dev/null +++ b/apps/events/frontend/src/lib/eventSetup.ts @@ -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 { + 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 { + 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 { + 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(token: Token, eventId?: string): Promise { + 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 { + 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 { + 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 { + await apiV2("delete", "/sections/{id}", { params: { id: sectionId }, authToken: token }); +} + +// ─── Attachments ───────────────────────────────────────────────────────────── + +export async function listAttachments(eventId: string): Promise { + 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 { + 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 { + 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 { + 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 { + await apiV2("patch", "/costs/{id}", { params: { id: costId }, authToken: token, body }); +} + +export async function deleteCost(token: Token, costId: string): Promise { + 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 { + 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; +}