Fix frontend lint: links, unused code, quotes, img elements

- Internal links use next/link instead of <a> (no full page reload).
- Remove dead code: RegisterForm's unreachable Yoco checkout branch, the
  unused AttendeeForms on the registration success page, unused Geist
  fonts, and assorted unused variables and catch bindings.
- Escape quotes in JSX text; replace @ts-ignore in apiFetch with a cast.
- Keep the intentional raw <img> elements (data URLs, runtime API host)
  with a documented lint exception; the event editor uses ApiImage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 11:10:00 +02:00
co-authored by Claude Opus 5.5
parent 700b220906
commit 9e8244bb71
33 changed files with 73 additions and 266 deletions
@@ -41,7 +41,7 @@ export default function ForgotPasswordPage() {
</div>
<h1 className="text-xl font-semibold text-gray-900">Forgot your password?</h1>
</div>
<p className="text-gray-600 text-sm mb-6">Enter your account email and we'll send you a link to reset your password.</p>
<p className="text-gray-600 text-sm mb-6">Enter your account email and we&apos;ll send you a link to reset your password.</p>
<form onSubmit={submit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Email</label>
@@ -1,3 +1,4 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { apiFetch } from "@/lib/api";
@@ -32,9 +33,9 @@ export default async function EventRedirectPage({ params }: { params: Promise<{
<p className="text-gray-500 mb-6">
The page you&apos;re looking for doesn&apos;t exist.
</p>
<a href="/" className="text-brand-600 hover:underline transition-all duration-200">
<Link href="/" className="text-brand-600 hover:underline transition-all duration-200">
Back to Home &rarr;
</a>
</Link>
</main>
);
}
@@ -47,9 +48,9 @@ export default async function EventRedirectPage({ params }: { params: Promise<{
<main className="flex flex-col items-center justify-center min-h-screen text-center">
<h1 className="text-3xl font-bold mb-2">This event has ended</h1>
<p className="text-gray-600">Thanks for joining us! Stay tuned for the next one.</p>
<a href="/" className="mt-4 text-brand-600 hover:underline">
<Link href="/" className="mt-4 text-brand-600 hover:underline">
Back to Home &rarr;
</a>
</Link>
</main>
);
}
@@ -179,7 +179,7 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
)}
</div>
{isClosed && <div className="text-xs text-gray-500">This event is closed — costs can't be changed until it's reopened.</div>}
{isClosed && <div className="text-xs text-gray-500">This event is closed — costs can&apos;t be changed until it&apos;s reopened.</div>}
<div className="overflow-auto">
<table className="w-full text-sm min-w-[600px]">
@@ -261,7 +261,7 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
<option value="">Not from event takings</option>
{METHODS.map(m => <option key={m} value={m}>{METHOD_LABELS[m]}</option>)}
</select>
<p className="text-[10px] text-gray-400 mt-0.5">If this was paid out of the door takings (e.g. cash to a vendor), tag it so the Cashup report deducts it from that method's expected amount.</p>
<p className="text-[10px] text-gray-400 mt-0.5">If this was paid out of the door takings (e.g. cash to a vendor), tag it so the Cashup report deducts it from that method&apos;s expected amount.</p>
</div>
<div className="col-span-2">
<label className="block text-xs text-gray-600 mb-1">Notes (optional)</label>
@@ -761,7 +761,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
</tbody>
</table>
{!isClosed && (
<div className="text-xs text-gray-500">Cash actual is the live sum of per-staff-member counts entered below — there's no separate event-wide entry.</div>
<div className="text-xs text-gray-500">Cash actual is the live sum of per-staff-member counts entered below — there&apos;s no separate event-wide entry.</div>
)}
</div>
@@ -84,7 +84,7 @@ export default function AdminDashboardPage() {
]);
setPaymentStats(dash.paymentStats);
setOverview(overviewData);
} catch (e) {
} catch {
// ignore errors for dashboard summaries
} finally {
hasLoadedOnce.current = true;
@@ -875,7 +875,7 @@ function WhatsAppTab({ active }: { active: boolean }) {
const res = await apiFetch<StatusResponse>("/api/whatsapp/status", { authToken: token });
setStatus(res.status ?? null);
setStatusMsg(res.message ?? null);
} catch (e: any) {
} catch {
await fetchConfig();
setStatus("FAILED");
setStatusMsg(null);
@@ -27,15 +27,6 @@ type Role = typeof roleOptions[number];
const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const;
// Simple fuzzy: tolerate one missing/swapped char by checking if query chars appear in order
function fuzzyMatch(query: string, target: string): boolean {
const q = query.toLowerCase();
const t = target.toLowerCase();
if (t.includes(q)) return true;
// token-based: all tokens must appear somewhere
const tokens = q.split(/\s+/).filter(Boolean);
return tokens.every(tok => t.includes(tok));
}
export default function AdminUsersPage() {
const { user, loading, token } = useAuth();
@@ -48,7 +48,7 @@ export default function StaffDashboardPage() {
const data = await apiFetch<any>("/api/stats/staff", { authToken: token });
setStats(data.scanStats);
setRecentScans(Array.isArray(data.recentScans) ? data.recentScans : []);
} catch (e) {
} catch {
// ignore
} finally {
hasLoadedOnce.current = true;
@@ -14,7 +14,6 @@ import type { SnapshotTicket } from "@/lib/offlineScan";
export default function TicketScanningPage() {
const router = useRouter();
const scannerRef = useRef<QRScannerHandle>(null);
const [lastResult, setLastResult] = useState<string | null>(null);
const [scanInfo, setScanInfo] = useDismissingState<string | null>(null);
const [error, setError] = useDismissingState<string | null>(null);
const [alreadyUsedModal, setAlreadyUsedModal] = useState<{ message: string; ticket?: any } | null>(null);
@@ -64,7 +63,7 @@ export default function TicketScanningPage() {
const evs = await apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token });
const sorted = (evs || []).sort((a, b) => new Date(a.endDate).getTime() - new Date(b.endDate).getTime());
setAllEvents(sorted);
} catch (e: any) {
} catch {
// non-fatal
} finally {
setLoadingEvents(false);
@@ -120,7 +119,6 @@ export default function TicketScanningPage() {
}, [selectedEventId, selectedSectionId]);
async function handleResult(text: string) {
setLastResult(text);
setError(null);
setScanInfo(null);
try {
@@ -180,8 +180,6 @@ function EmailAttendeesPageInner() {
// Tabs: attendees (current), automations (coming soon), broadcasts
const [tab, setTab] = useState<'attendees'|'automations'|'broadcasts'|'scheduled'>('attendees');
const isAdmin = user?.role === "admin";
const [allEvents, setAllEvents] = useState<any[]>([]);
const [evIncludePast, setEvIncludePast] = useState(false);
@@ -221,7 +219,7 @@ function EmailAttendeesPageInner() {
.map((u: any) => ({ id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' }))
.sort((a: any, b: any) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }));
setUsers(mapped);
} catch (e) {
} catch {
// ignore for now
} finally {
setLoadingUsers(false);
@@ -277,7 +275,7 @@ function EmailAttendeesPageInner() {
setLoadingScheduled(true);
const res = await apiFetch<{jobs: ScheduledJob[]}>(`/api/scheduled-emails?channel=email`, { authToken: token });
setScheduled(Array.isArray(res?.jobs) ? res.jobs : []);
} catch (e) {
} catch {
// ignore here; surfaces via UI when tab open
} finally {
setLoadingScheduled(false);
@@ -402,7 +400,7 @@ function EmailAttendeesPageInner() {
// Default: select those with email/both preference; fall back to all
const matching = list.filter(a => a.pref === 'email' || a.pref === 'both').map(a => a.id);
setSelectedAttendeeIds(matching.length > 0 ? matching : list.map(a => a.id));
} catch (e) {
} catch {
// ignore
} finally {
setLoadingAttendees(false);
@@ -584,7 +582,7 @@ function EmailAttendeesPageInner() {
<li><code>{'{{event.title}}'}</code> — the event title.</li>
<li><code>{'{{event.start}}'}</code> — the event start date/time (local).</li>
<li><code>{'{{balance}}'}</code> — outstanding amount across the attendee’s registrations for the selected event.</li>
<li><code>{'{{payment.link}}'}</code> — a direct Yoco payment link for the attendee's outstanding balance (generated per recipient when sending).</li>
<li><code>{'{{payment.link}}'}</code> — a direct Yoco payment link for the attendee&apos;s outstanding balance (generated per recipient when sending).</li>
</ul>
<p className="mb-2">Example: Hi <code>{'{{name}}'}</code>, your balance is <code>{'{{balance}}'}</code>. Pay here: <code>{'{{payment.link}}'}</code></p>
<p className="text-[11px] text-gray-500">To add new placeholders, extend <span className="font-mono">backend/src/utils/placeholders.js</span> and update this help.</p>
@@ -113,20 +113,16 @@ function EventOptionsContent() {
const [events, setEvents] = useState<any[]>([]);
const [selectedEventId, setSelectedEventId] = useState<string>("");
const [options, setOptions] = useState<any[]>([]);
const [loadingEv, setLoadingEv] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
const loadEvents = async () => {
if (!token) return;
try {
setLoadingEv(true);
const evs = await apiFetch<any[]>("/api/events/all", { authToken: token });
setEvents(evs || []);
} catch (e) {
} catch {
// ignore
} finally {
setLoadingEv(false);
}
};
@@ -4,7 +4,8 @@ import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from "re
import { createPortal } from "react-dom";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch, resolveToApiOrigin } from "@/lib/api";
import { apiFetch } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { Calendar } from "lucide-react";
@@ -819,8 +820,7 @@ interface EventModalProps {
}
function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
const { token, user } = useAuth();
const isAdmin = user?.role === "admin";
const { token } = useAuth();
const { settings } = useSiteSettings();
const [step, setStep] = useState<StepIdx>(0);
const [pricingSubstep, setPricingSubstep] = useState<PricingSubstep>(0);
@@ -1306,7 +1306,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
<div className="p-5 space-y-4 max-h-[65vh] overflow-y-auto">
{isClosed && (
<div className="p-3 border rounded bg-rose-50 text-rose-800 text-sm">
This event is closed — it can't be edited until it's reopened from the cashup page (admin only).
This event is closed — it can&apos;t be edited until it&apos;s reopened from the cashup page (admin only).
</div>
)}
{error && <div className="p-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
@@ -1342,7 +1342,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
onChange={e => upd({ requiresRegistration: !e.target.checked, price: e.target.checked ? "0" : draft.price })}
/>
<label htmlFor="contact-only-toggle" className="text-xs text-gray-700">
<span className="font-medium">This is a contact-only event</span> (e.g. baptism) — no online registration or payment. Shows a "Contact us" button on the public site instead of "Register".
<span className="font-medium">This is a contact-only event</span> (e.g. baptism) — no online registration or payment. Shows a &quot;Contact us&quot; button on the public site instead of &quot;Register&quot;.
</label>
</div>
{draft.requiresRegistration ? (
@@ -1369,7 +1369,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
)}
<div>
<label className="block text-xs text-gray-600 mb-1">Picture</label>
{draft.picture && <img src={resolveToApiOrigin(draft.picture) || undefined} alt="" className="h-20 w-20 object-cover rounded border mb-2" />}
<ApiImage src={draft.picture} className="h-20 w-20 object-cover rounded border mb-2" />
<div className="flex items-center gap-2">
<input className="flex-1 border rounded px-3 py-2 text-sm" placeholder="/uploads/... or https://" value={draft.picture} onChange={e => upd({ picture: e.target.value })} />
<UploadImageButton onUploaded={url => upd({ picture: url })} label="Upload" />
@@ -1405,7 +1405,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
{/* ── Step 2: Sections ── */}
{step === 2 && (
<div>
<p className="text-xs text-gray-500 mb-3">Group ticket options into named sections shown on the registration page (e.g. "Tickets", "Add-ons", "Accommodation").</p>
<p className="text-xs text-gray-500 mb-3">Group ticket options into named sections shown on the registration page (e.g. &quot;Tickets&quot;, &quot;Add-ons&quot;, &quot;Accommodation&quot;).</p>
{mode === "edit" && ev?.id
? <SectionsManager eventId={ev.id} />
: <SectionsDraftEditor sections={sectionDrafts} options={options} onChange={setSectionDrafts} />
@@ -261,7 +261,7 @@ export default function ManualRegistrationPage() {
});
active.sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
setEvents(active);
} catch (e: any) {
} catch {
// ignore
}
})();
@@ -86,7 +86,7 @@ export default function SupervisorDashboardPage() {
setPaymentStats(data.paymentStats);
setRecentScans(Array.isArray(data.recentScans) ? data.recentScans : []);
setOverview(overviewData);
} catch (e) {
} catch {
// ignore
} finally {
hasLoadedOnce.current = true;
@@ -209,7 +209,7 @@ function PaymentsContent() {
// Sort by createdAt desc
const sorted = list.sort((a,b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
setRegistrations(sorted);
} catch (e) {
} catch {
// ignore
} finally {
setLoadingRegs(false);
@@ -226,7 +226,7 @@ function PaymentsContent() {
setLoadingUsers(true);
const users = await fetchAllUsers(token);
setAllUsers(users);
} catch (e) {
} catch {
// ignore; fallback to derived users from registrations
} finally {
setLoadingUsers(false);
@@ -417,7 +417,7 @@ function PaymentsContent() {
}
try {
setSubmitting(true);
const res = await apiFetch<any>("/api/payments", {
await apiFetch("/api/payments", {
method: "POST",
authToken: token,
body: {
@@ -462,7 +462,7 @@ function PaymentsContent() {
const res = await apiFetch<any>("/api/yoco-transactions/unreconciled", { authToken: token });
const items = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : []);
setYocoTxs(items);
} catch (e) {
} catch {
// ignore silently, shown on demand via error state if needed
} finally {
setYocoLoading(false);
@@ -753,7 +753,6 @@ function PaymentsContent() {
<RefundSection
payments={payments}
allUsers={allUsers}
usersList={usersList}
regsForUser={(uid:string)=> registrations.filter((r:any)=> String(r.user?.id||r.userId)===String(uid))}
regOutstanding={regOutstanding}
onDone={async()=>{ await Promise.all([loadPayments(), loadRegistrations()]); setInfo('Refund recorded'); }}
@@ -877,13 +876,12 @@ function PaymentsContent() {
type RefundSectionProps = {
payments: any[];
allUsers: any[];
usersList: { id: string; name: string }[];
regsForUser: (userId: string) => any[];
regOutstanding: Record<string, { totalDue: number; totalPaid: number; outstanding: number }>;
onDone: () => void | Promise<void>;
};
function RefundSection({ payments, allUsers, usersList, regsForUser, regOutstanding, onDone }: RefundSectionProps) {
function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone }: RefundSectionProps) {
const { token } = useAuth();
const [userId, setUserId] = useState<string>("");
const [target, setTarget] = useState<'payment'|'registration'>('payment');
@@ -1003,7 +1001,7 @@ function RefundSection({ payments, allUsers, usersList, regsForUser, regOutstand
<option value="eft-refund">EFT refund</option>
<option value="voucher-refund">Voucher refund</option>
</select>
<div className="text-[10px] text-gray-500 mt-1">Mirrors the method being refunded — this is what nets against that method's total in reports.</div>
<div className="text-[10px] text-gray-500 mt-1">Mirrors the method being refunded — this is what nets against that method&apos;s total in reports.</div>
</div>
</div>
<label className="block text-xs text-gray-600 mt-2">Reason (optional)</label>
@@ -693,7 +693,7 @@ function WhatsAppAttendeesPageInner() {
<li><code>{"{{event.title}}"}</code> — the event title.</li>
<li><code>{"{{event.start}}"}</code> — the event start date/time.</li>
<li><code>{"{{balance}}"}</code> — outstanding balance for the event.</li>
<li><code>{"{{payment.link}}"}</code> — a direct Yoco payment link for the attendee's outstanding balance (generated per recipient when sending).</li>
<li><code>{"{{payment.link}}"}</code> — a direct Yoco payment link for the attendee&apos;s outstanding balance (generated per recipient when sending).</li>
</ul>
<p className="text-[11px] text-gray-500 mt-2">
Preference indicators: <span className="text-green-700 bg-green-50 px-1 rounded">WA</span> = WhatsApp only,{" "}
@@ -218,7 +218,7 @@ export default function UserDashboardPage() {
requiredCount,
complete,
};
} catch (e) {
} catch {
// On any error, do not show forms status to avoid noisy UI
next[r.id] = { hasForm: false };
}
@@ -456,16 +456,6 @@ export default function UserDashboardPage() {
return Array.from(map.values()).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
}, [registrations]);
// Tickets by grouping
const ticketsByEvent = useMemo(() => {
const m: Record<string, any[]> = {};
for (const t of tickets) {
const eid = t.eventId;
if (!m[eid]) m[eid] = [];
m[eid].push(t);
}
return m;
}, [tickets]);
// Registration click -> open modal
const activeReg = useMemo(() => registrations.find(r => r.id === activeRegId) || null, [registrations, activeRegId]);
@@ -148,7 +148,7 @@ export default function UserProfilePage() {
try {
const res = await apiFetch<ActivityEvent[]>("/api/users/activity", { authToken: token });
setActivity(Array.isArray(res) ? res : []);
} catch (e) {
} catch {
// Non-critical — just leave the list empty rather than showing an error banner.
} finally {
setLoadingActivity(false);
-11
View File
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/contexts/AuthContext";
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext";
@@ -14,16 +13,6 @@ import { API_BASE, resolveToApiOrigin } from "@/lib/api";
import { buildThemeCssVars } from "@/lib/colorScale";
import { appUrl } from "@/lib/siteConfig";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
const appName = process.env.NEXT_PUBLIC_APP_NAME || 'Cross Code';
/**
+7 -6
View File
@@ -1,3 +1,4 @@
import Link from "next/link";
import { EventCard } from "@/components/events/EventCard";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
@@ -71,10 +72,10 @@ export default async function HomePage() {
<h1 className="text-4xl sm:text-5xl font-bold mb-4 text-gray-900">Welcome to {displayName}</h1>
<p className="text-gray-600 text-lg mb-8">Experience unforgettable moments. Powered by purpose.</p>
<div className="flex flex-wrap items-center justify-center gap-3">
<a href="/events" className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-600 text-white rounded-xl hover:bg-brand-700 shadow-sm font-medium transition-colors">
<Link href="/events" className="inline-flex items-center gap-2 px-6 py-2.5 bg-brand-600 text-white rounded-xl hover:bg-brand-700 shadow-sm font-medium transition-colors">
<Calendar className="w-4 h-4" />
View Events
</a>
</Link>
<JoinUsButton />
</div>
</div>
@@ -83,10 +84,10 @@ export default async function HomePage() {
<section className="py-12 px-4 max-w-7xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h2 className="text-2xl font-semibold text-gray-900">Upcoming Events</h2>
<a href="/events" className="hidden sm:inline-flex items-center gap-1 text-sm font-medium text-brand-600 hover:underline">
<Link href="/events" className="hidden sm:inline-flex items-center gap-1 text-sm font-medium text-brand-600 hover:underline">
View all events
<ArrowRight className="w-3.5 h-3.5" />
</a>
</Link>
</div>
{sorted.length === 0 ? (
<div className="text-center py-12 border rounded-xl bg-gray-50">
@@ -101,10 +102,10 @@ export default async function HomePage() {
</div>
)}
<div className="text-center mt-8 sm:hidden">
<a href="/events" className="inline-flex items-center gap-1 text-brand-600 hover:underline text-sm font-medium">
<Link href="/events" className="inline-flex items-center gap-1 text-brand-600 hover:underline text-sm font-medium">
View all events
<ArrowRight className="w-3.5 h-3.5" />
</a>
</Link>
</div>
</section>
@@ -300,8 +300,6 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
return initial;
});
const [error, setError] = useState<string | null>(null);
const [registrationId, setRegistrationId] = useState<string | null>(null);
const [creatingCheckout, setCreatingCheckout] = useState(false);
const [creatingRegistration, setCreatingRegistration] = useState(false);
const [coupon, setCoupon] = useState<AppliedCoupon | null>(null);
const [namingOthers, setNamingOthers] = useState(false);
@@ -484,27 +482,6 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
}
};
const createYocoCheckout = async () => {
if (!token || !registrationId) return;
try {
setCreatingCheckout(true);
const res = await apiFetch<{ redirectUrl: string }>("/api/payments/yoco-checkout", {
method: "POST",
body: {
registrationId,
successUrl: window.location.origin + "/payment/success",
cancelUrl: window.location.origin + "/payment/cancel",
failureUrl: window.location.origin + "/payment/failure",
},
authToken: token,
});
window.open(res.redirectUrl, "_blank");
} catch (e: any) {
setError(e?.message || "Failed to create checkout");
} finally {
setCreatingCheckout(false);
}
};
return (
<>
@@ -628,12 +605,11 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
)}
<div className="text-lg font-semibold">Total: R{payable.toFixed(2)}</div>
</div>
{!registrationId ? (
eventSoldOut ? (
<button disabled className="bg-red-50 text-red-700 border border-red-200 px-4 py-2 rounded cursor-not-allowed">
Sold Out
</button>
) : (
{eventSoldOut ? (
<button disabled className="bg-red-50 text-red-700 border border-red-200 px-4 py-2 rounded cursor-not-allowed">
Sold Out
</button>
) : (
<button
onClick={submitRegistration}
disabled={creatingRegistration || (!isLoggedIn && !isGuestEligible && !waitlistToken)}
@@ -641,15 +617,6 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
>
{creatingRegistration ? "Registering..." : "Register"}
</button>
)
) : (
<button
onClick={createYocoCheckout}
disabled={creatingCheckout}
className="bg-green-600 text-white px-4 py-2 rounded disabled:opacity-60"
>
{creatingCheckout ? "Creating checkout..." : "Pay with Yoco"}
</button>
)}
</div>
@@ -1,5 +1,4 @@
"use client";
import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormFieldExtras";
import React, { Suspense } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
@@ -22,35 +21,23 @@ function RegistrationSuccessContent() {
const [reg, setReg] = React.useState<any | null>(null);
const [form, setForm] = React.useState<{ isRequired: boolean; fields: FormField[] } | null>(null);
const [formsData, setFormsData] = React.useState<Record<number, Record<string, string>>>({});
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const [info, setInfo] = React.useState<string | null>(null);
const [payLoading, setPayLoading] = React.useState(false);
React.useEffect(() => {
(async () => {
setError(null);
setInfo(null);
if (!registrationId) return;
try {
setLoading(true);
// Try to fetch registration and event form
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(`/api/events/${encodeURIComponent(r.eventId)}`);
if (ev?.form) setForm(ev.form);
// Load any saved draft
try {
const d = await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token || undefined });
if (d && d.data && typeof d.data === 'object') setFormsData(d.data);
} catch {}
}
} catch (e: any) {
setError(e?.message || 'Failed to load details');
} finally {
setLoading(false);
}
})();
}, [registrationId, token]);
@@ -161,119 +148,6 @@ function RegistrationSuccessContent() {
);
}
function AttendeeForms({ reg, form, formsData, setFormsData, setError, setInfo }: { reg: any; form: { isRequired: boolean; fields: FormField[] }; formsData: Record<number, Record<string,string>>; setFormsData: any; setError: any; setInfo: any; }) {
const { token } = useAuth();
const registrationId = reg?.id;
const mainTickets = (reg?.registrationOptions || []).filter((o: any) => o?.eventOption?.isMainTicket).reduce((s: number, o: any) => s + (o.quantity || 0), 0);
const count = Math.max(0, mainTickets);
const canSubmit = React.useMemo(() => {
if (!form || count <= 0) return false;
const reqFields = (form.fields || [])
.filter(f => !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph')
.map(f => f.id);
for (let i = 0; i < count; i++) {
const data = formsData[i] || {};
for (const fid of reqFields) {
const v = data[fid];
if (v === undefined || v === null || String(v).trim() === '') {
return false;
}
}
}
return true;
}, [form, formsData, count]);
const update = (idx: number, fieldId: string, value: string) => {
setFormsData((prev: any) => ({ ...prev, [idx]: { ...(prev[idx]||{}), [fieldId]: value } }));
};
const submit = async () => {
try {
setError(null); setInfo(null);
if (!token) { setError('Please login to submit forms.'); return; }
const payload = [] as any[];
for (let i = 0; i < count; i++) {
payload.push({ answers: formsData[i] || {} });
}
await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, {
method: 'POST',
authToken: token,
body: { responses: payload }
});
setInfo('Attendee forms submitted. You will receive tickets once payment is confirmed.');
} catch (e: any) {
setError(e?.message || 'Failed to submit forms');
}
};
const saveDraft = async () => {
try {
setError(null); setInfo(null);
if (!token) { setError('Please login to save drafts.'); return; }
await (await import('@/lib/api')).apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, {
method: 'PUT',
authToken: token,
body: { data: formsData }
});
setInfo('Draft saved. You can finish later from your dashboard.');
} catch (e: any) {
setError(e?.message || 'Failed to save draft');
}
};
if (!form || !Array.isArray(form.fields) || count === 0) return null;
return (
<div className="border rounded p-3 bg-gray-50 mb-4">
<div className="text-sm font-medium mb-2">Attendee details</div>
<div className="space-y-4">
{Array.from({ length: count }, (_, idx) => (
<div key={idx} className="bg-white border rounded p-3">
<div className="font-medium mb-2">Attendee {idx + 1}</div>
{form.fields.map((f) => (
<div key={f.id} className="mb-2">
{f.type === 'statement' ? (
<div className="text-sm text-gray-700 whitespace-pre-line">{f.label}</div>
) : f.type === 'paragraph' ? (
<div className="text-sm text-gray-700">
{f.label && <div className="font-medium mb-1 whitespace-pre-line">{f.label}</div>}
{f.helpText && <div className="whitespace-pre-line">{f.helpText}</div>}
</div>
) : (
<>
<label className="block text-xs text-gray-600 mb-1">{f.label}{f.isRequired ? ' *' : ''}</label>
{isExtraFieldType(f.type) ? (
<ExtraFieldInput field={f} idPrefix={`a${idx}`} value={formsData[idx]?.[f.id] || ''} onChange={v => update(idx, f.id, v)} />
) : f.type === 'yes_no' ? (
<select className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)}>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
) : f.type === 'date' ? (
<input type="date" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
) : f.type === 'numeric' ? (
<input type="number" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
) : (
<input type="text" className="border rounded px-2 py-1 text-sm w-full" value={formsData[idx]?.[f.id] || ''} onChange={e => update(idx, f.id, e.target.value)} />
)}
{f.helpText && <div className="text-xs text-gray-500 mt-1">{f.helpText}</div>}
</>
)}
</div>
))}
</div>
))}
</div>
<div className="mt-3 flex gap-2">
<button className="px-3 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50" disabled={!canSubmit} onClick={submit}>Submit attendee forms</button>
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200" onClick={saveDraft}>Save for later</button>
</div>
</div>
);
}
export default function RegistrationSuccessPage() {
return (
<Suspense fallback={<div className="p-6">Loading...</div>}>
@@ -187,7 +187,6 @@ export default function SelfServicePage() {
// ── Event form (attendee form) state ────────────────────────────
const [currentRegistrationId, setCurrentRegistrationId] = useState<string | null>(null);
const [currentUserId, setCurrentUserId] = useState<string | null>(null);
const [currentTicketIndex, setCurrentTicketIndex] = useState(0);
const [allFormAnswers, setAllFormAnswers] = useState<Record<string, string>[]>([]);
const [currentTicketAnswers, setCurrentTicketAnswers] = useState<Record<string, string>>({});
@@ -442,7 +441,6 @@ export default function SelfServicePage() {
});
setCurrentRegistrationId(result?.id || null);
setCurrentUserId(result?.userId || null);
setRegistrationIsFree(result?.status === "paid" || (result?.totalDueComputed ?? total) === 0);
setConfirmationName(visitorName.trim());
@@ -562,7 +560,6 @@ export default function SelfServicePage() {
setLookupMessage(null);
setFormError(null);
setCurrentRegistrationId(null);
setCurrentUserId(null);
setCurrentTicketIndex(0);
setAllFormAnswers([]);
setCurrentTicketAnswers({});
@@ -386,6 +386,8 @@ export default function SetupPage() {
<Field label="Logo image (optional)" hint="PNG, JPG, SVG or WebP, max 2 MB. If skipped, a default logo is used.">
<input type="file" accept="image/*" onChange={handleLogoChange} className="text-sm" />
{logoPreview && (
// Local file preview (data: URL) — nothing for next/image to optimize.
// eslint-disable-next-line @next/next/no-img-element
<img src={logoPreview} alt="Preview" className="mt-2 h-16 object-contain rounded border" />
)}
{suggestedColors.length > 0 && (