Type caught errors as unknown in the frontend
Replace `catch (e: any)` with `catch (e)` and read the message through a new errorMessage() helper. ApiError.data gets a real type, and useDismissingState's setter keeps one identity across renders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@ import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -18,12 +19,12 @@ export default function ForgotPasswordPage() {
|
||||
setStatus(null);
|
||||
const res: any = await apiFetch("/api/users/forgot", { method: "POST", body: { email } });
|
||||
setStatus(res?.message || "If that email exists, a password reset link has been sent.");
|
||||
} catch (err: any) {
|
||||
} catch (err) {
|
||||
try {
|
||||
const parsed = JSON.parse(err?.message || "");
|
||||
const parsed = JSON.parse(errorMessage(err) || "");
|
||||
setStatus(parsed?.message || "Something went wrong");
|
||||
} catch {
|
||||
setStatus(err?.message || "Something went wrong");
|
||||
setStatus(errorMessage(err) || "Something went wrong");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { saveToken } from "@/lib/auth";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { ShieldCheck } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
function ActivateAccountContent() {
|
||||
const search = useSearchParams();
|
||||
@@ -30,8 +31,8 @@ function ActivateAccountContent() {
|
||||
if (data?.token) saveToken(data.token);
|
||||
setStatus("Your account is now active. Redirecting…");
|
||||
setTimeout(() => { window.location.href = "/dashboard"; }, 1500);
|
||||
} catch (err: any) {
|
||||
setStatus(err?.message || "Activation failed. The link may have expired.");
|
||||
} catch (err) {
|
||||
setStatus(errorMessage(err) || "Activation failed. The link may have expired.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { History } from "lucide-react";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
const ACTIONS = [
|
||||
"refund_created",
|
||||
@@ -174,8 +175,8 @@ export default function AdminAuditLogPage() {
|
||||
setEntries(res?.rows || []);
|
||||
setTotal(res?.total ?? 0);
|
||||
setPage(p);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load audit log");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load audit log");
|
||||
} finally {
|
||||
setFetching(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import type { EventCost, EventCostType, EventFinancials, CashupMethod } from "@/types";
|
||||
import { Wallet, DollarSign, ClipboardCheck, FileBarChart } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
const METHOD_LABELS: Record<CashupMethod, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
|
||||
const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"];
|
||||
@@ -47,8 +48,8 @@ export default function EventCashupPage() {
|
||||
]);
|
||||
setData(financials);
|
||||
setEventOptions((event.eventOptions || []).map((o: any) => ({ id: o.id, name: o.name })));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load cashup data");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load cashup data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -151,8 +152,8 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
|
||||
}
|
||||
setEditingId(null);
|
||||
onChanged();
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || "Failed to save cost");
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || "Failed to save cost");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -163,8 +164,8 @@ function CostsTab({ eventId, token, costs, eventOptions, isClosed, onChanged }:
|
||||
try {
|
||||
await apiFetch(`/api/costs/${id}`, { method: "DELETE", authToken: token });
|
||||
onChanged();
|
||||
} catch (e: any) {
|
||||
alert(e?.message || "Failed to delete cost");
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || "Failed to delete cost");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -461,8 +462,8 @@ function PersonCashCountEditor({ eventId, token, userId, initialDenominations, i
|
||||
method: "PUT", authToken: token, body: { denominations: lines, notes: notes || null }
|
||||
});
|
||||
onSaved();
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || "Failed to save count");
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || "Failed to save count");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -659,8 +660,8 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
|
||||
try {
|
||||
await apiFetch(`/api/cashups/event/${eventId}/draft`, { method: "PUT", authToken: token, body: { lines: buildLinesPayload() } });
|
||||
onChanged();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to save draft");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to save draft");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -673,8 +674,8 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
|
||||
await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { lines: buildLinesPayload(), notes: closeNotes || null } });
|
||||
onChanged();
|
||||
onClosed();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to close event");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to close event");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -687,8 +688,8 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
|
||||
await apiFetch(`/api/cashups/event/${eventId}/close`, { method: "POST", authToken: token, body: { notes: closeNotes || null } });
|
||||
onChanged();
|
||||
onClosed();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to close event");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to close event");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -700,8 +701,8 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh
|
||||
try {
|
||||
await apiFetch(`/api/cashups/event/${eventId}/reopen`, { method: "POST", authToken: token, body: { notes: reopenNotes || null } });
|
||||
onChanged();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to reopen event");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to reopen event");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Wallet } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export default function CashupLandingPage() {
|
||||
const { token } = useAuth();
|
||||
@@ -27,8 +28,8 @@ export default function CashupLandingPage() {
|
||||
try {
|
||||
const evs = await apiFetch<any[]>("/api/events/all?includePast=true&includeInactive=true", { authToken: token });
|
||||
setEvents(Array.isArray(evs) ? evs : []);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { ClipboardList } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const;
|
||||
|
||||
@@ -57,8 +58,8 @@ export default function AdminRegistrationsPage() {
|
||||
return (a.user?.name || a.userId).localeCompare(b.user?.name || b.userId);
|
||||
}) : [];
|
||||
setRegistrations(list);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load registrations");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load registrations");
|
||||
} finally {
|
||||
setLoadingRegs(false);
|
||||
}
|
||||
@@ -117,8 +118,8 @@ export default function AdminRegistrationsPage() {
|
||||
await apiFetch(`/api/registrations/${encodeURIComponent(reg.id)}`, { method: "DELETE", authToken: token });
|
||||
setInfo("Registration cancelled");
|
||||
await loadRegistrations();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to cancel registration");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to cancel registration");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -129,8 +130,8 @@ export default function AdminRegistrationsPage() {
|
||||
await apiFetch(`/api/registrations/${encodeURIComponent(reg.id)}`, { method: "PUT", authToken: token, body: { status } });
|
||||
setInfo("Status updated");
|
||||
await loadRegistrations();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to update status");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to update status");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import React, { Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { apiFetch, API_BASE, resolveToApiOrigin } from "@/lib/api";
|
||||
import { apiFetch, ApiError, API_BASE, resolveToApiOrigin } from "@/lib/api";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, type LucideIcon } from "lucide-react";
|
||||
@@ -13,6 +13,7 @@ import { BackupsTab } from "@/components/admin/BackupsTab";
|
||||
import { YocoTab } from "@/components/admin/YocoTab";
|
||||
import { extractDominantColors } from "@/lib/extractColors";
|
||||
import { mapsSearchUrl } from "@/lib/maps";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type TabId = "organisation" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "yoco" | "backups";
|
||||
|
||||
@@ -194,8 +195,8 @@ function SiteSettingsPageInner() {
|
||||
await apiFetch("/api/settings", { method: "PUT", authToken: token, body: updates });
|
||||
setResult({ ok: true, message: "Saved." });
|
||||
reloadSettings();
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, message: e?.message || "Failed to save" });
|
||||
} catch (e) {
|
||||
setResult({ ok: false, message: errorMessage(e) || "Failed to save" });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -253,8 +254,8 @@ function SiteSettingsPageInner() {
|
||||
setSuggestedColors([]);
|
||||
setResult({ ok: true, message: "Saved." });
|
||||
reloadSettings();
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, message: e?.message || "Failed to save" });
|
||||
} catch (e) {
|
||||
setResult({ ok: false, message: errorMessage(e) || "Failed to save" });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -278,8 +279,8 @@ function SiteSettingsPageInner() {
|
||||
setSuggestedColors([]);
|
||||
setResult({ ok: true, message: "Reset to defaults." });
|
||||
reloadSettings();
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, message: e?.message || "Failed to reset" });
|
||||
} catch (e) {
|
||||
setResult({ ok: false, message: errorMessage(e) || "Failed to reset" });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -312,8 +313,8 @@ function SiteSettingsPageInner() {
|
||||
if (smtpPass.trim() !== "") { setSmtpPassSet(true); setSmtpPass(""); }
|
||||
setResult({ ok: true, message: "Saved." });
|
||||
reloadSettings();
|
||||
} catch (e: any) {
|
||||
setResult({ ok: false, message: e?.message || "Failed to save" });
|
||||
} catch (e) {
|
||||
setResult({ ok: false, message: errorMessage(e) || "Failed to save" });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -347,8 +348,9 @@ function SiteSettingsPageInner() {
|
||||
},
|
||||
});
|
||||
setSmtpTestResult({ ok: true, message: "Connection successful — check your inbox for a test email." });
|
||||
} catch (e: any) {
|
||||
setSmtpTestResult({ ok: false, message: e?.message || "SMTP test failed", raw: e?.data?.raw });
|
||||
} catch (e) {
|
||||
const raw = e instanceof ApiError && typeof e.data?.raw === "string" ? e.data.raw : undefined;
|
||||
setSmtpTestResult({ ok: false, message: errorMessage(e) || "SMTP test failed", raw });
|
||||
} finally {
|
||||
setSmtpTesting(false);
|
||||
}
|
||||
@@ -923,8 +925,8 @@ function WhatsAppTab({ active }: { active: boolean }) {
|
||||
setActionMsg({ type: "ok", text: res?.message || `${action} successful.` });
|
||||
await fetchStatus();
|
||||
await fetchConfig();
|
||||
} catch (e: any) {
|
||||
let msg = e?.message || `${action} failed.`;
|
||||
} catch (e) {
|
||||
let msg = errorMessage(e) || `${action} failed.`;
|
||||
try { msg = JSON.parse(msg)?.message || msg; } catch {}
|
||||
await fetchConfig();
|
||||
if (!msg.includes("SESSION_NOT_FOUND")) {
|
||||
@@ -947,8 +949,8 @@ function WhatsAppTab({ active }: { active: boolean }) {
|
||||
await apiFetch("/api/whatsapp/config", { method: "POST", authToken: token!, body: { token: inputToken.trim(), instanceId: "" } });
|
||||
setInputToken("");
|
||||
await fetchConfig();
|
||||
} catch (e: any) {
|
||||
setActionMsg({ type: "err", text: e?.message || "Failed to save token." });
|
||||
} catch (e) {
|
||||
setActionMsg({ type: "err", text: errorMessage(e) || "Failed to save token." });
|
||||
} finally {
|
||||
setSavingToken(false);
|
||||
}
|
||||
@@ -965,8 +967,8 @@ function WhatsAppTab({ active }: { active: boolean }) {
|
||||
await apiFetch("/api/whatsapp/config", { method: "POST", authToken: token!, body: { token: "", instanceId: inputInstanceId.trim() } });
|
||||
setInputInstanceId("");
|
||||
await fetchConfig();
|
||||
} catch (e: any) {
|
||||
setActionMsg({ type: "err", text: e?.message || "Failed to save Instance ID." });
|
||||
} catch (e) {
|
||||
setActionMsg({ type: "err", text: errorMessage(e) || "Failed to save Instance ID." });
|
||||
} finally {
|
||||
setSavingInstance(false);
|
||||
}
|
||||
@@ -979,8 +981,8 @@ function WhatsAppTab({ active }: { active: boolean }) {
|
||||
const res = await apiFetch<any>("/api/whatsapp/create-instance", { method: "POST", authToken: token! });
|
||||
setActionMsg({ type: "ok", text: res?.message || "Instance created." });
|
||||
await fetchConfig();
|
||||
} catch (e: any) {
|
||||
setActionMsg({ type: "err", text: e?.message || "Failed to create instance." });
|
||||
} catch (e) {
|
||||
setActionMsg({ type: "err", text: errorMessage(e) || "Failed to create instance." });
|
||||
} finally {
|
||||
setSavingInstance(false);
|
||||
}
|
||||
@@ -1224,8 +1226,8 @@ function WhatsAppTab({ active }: { active: boolean }) {
|
||||
setInputToken("");
|
||||
setInputInstanceId("");
|
||||
await fetchConfig();
|
||||
} catch (e: any) {
|
||||
setActionMsg({ type: "err", text: e?.message || "Failed to update." });
|
||||
} catch (e) {
|
||||
setActionMsg({ type: "err", text: errorMessage(e) || "Failed to update." });
|
||||
} finally {
|
||||
setSavingToken(false);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { beginImpersonation } from "@/lib/impersonation";
|
||||
import { Users as UsersIcon } from "lucide-react";
|
||||
import { RoleBadge, type Role as RoleBadgeRole } from "@/components/shared/RoleBadge";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
interface UserItem {
|
||||
id: string;
|
||||
@@ -94,8 +95,8 @@ export default function AdminUsersPage() {
|
||||
setTotal(res?.total ?? 0);
|
||||
setTotalPages(res?.pages ?? 1);
|
||||
setPage(p);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load users");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load users");
|
||||
} finally {
|
||||
setFetching(false);
|
||||
}
|
||||
@@ -132,8 +133,8 @@ export default function AdminUsersPage() {
|
||||
resetCreateForm();
|
||||
setCreateOpen(false);
|
||||
await loadUsers(page);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create user");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create user");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
@@ -163,8 +164,8 @@ export default function AdminUsersPage() {
|
||||
setEditingId(null);
|
||||
setEditData({});
|
||||
await loadUsers(page);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to save user");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to save user");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -174,8 +175,8 @@ export default function AdminUsersPage() {
|
||||
if (!confirm(`Revoke all active sessions for ${name}? They will be signed out on all devices.`)) return;
|
||||
try {
|
||||
await apiFetch(`/api/users/${encodeURIComponent(id)}/revoke-sessions`, { method: "POST", authToken: token! });
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to revoke sessions");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to revoke sessions");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -190,8 +191,8 @@ export default function AdminUsersPage() {
|
||||
try {
|
||||
const res = await apiFetch<any>(`/api/admin/impersonate/${encodeURIComponent(impTarget.id)}`, { method: "POST", authToken: token, body: { reason: impReason } });
|
||||
beginImpersonation(res);
|
||||
} catch (e: any) {
|
||||
setImpError(e?.message || "Couldn't start impersonation");
|
||||
} catch (e) {
|
||||
setImpError(errorMessage(e) || "Couldn't start impersonation");
|
||||
setImpBusy(false);
|
||||
}
|
||||
};
|
||||
@@ -206,8 +207,8 @@ export default function AdminUsersPage() {
|
||||
try {
|
||||
await apiFetch(`/api/users/${encodeURIComponent(id)}`, { method: "PUT", authToken: token!, body: { twoFactorEnabled: false } });
|
||||
await loadUsers(page);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to reset two-factor authentication");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to reset two-factor authentication");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -216,8 +217,8 @@ export default function AdminUsersPage() {
|
||||
try {
|
||||
await apiFetch(`/api/users/${encodeURIComponent(id)}`, { method: "DELETE", authToken: token! });
|
||||
await loadUsers(page);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to deactivate user");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to deactivate user");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -226,8 +227,8 @@ export default function AdminUsersPage() {
|
||||
try {
|
||||
await apiFetch(`/api/users/${encodeURIComponent(id)}/anonymize`, { method: "POST", authToken: token! });
|
||||
await loadUsers(page);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to delete user data");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to delete user data");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { QrImage } from "@/components/shared/QrImage";
|
||||
import { Ticket } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
function EventTicketsContent() {
|
||||
const { token, user } = useAuth();
|
||||
@@ -55,8 +56,8 @@ function EventTicketsContent() {
|
||||
}`
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
}
|
||||
})();
|
||||
}, [token]);
|
||||
@@ -80,8 +81,8 @@ function EventTicketsContent() {
|
||||
{ authToken: token }
|
||||
);
|
||||
setTickets(list);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load tickets");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load tickets");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { QrCode } from "lucide-react";
|
||||
import { useOfflineScanning } from "@/components/scanner/useOfflineScanning";
|
||||
import { OfflineScanPanel } from "@/components/scanner/OfflineScanPanel";
|
||||
import type { SnapshotTicket } from "@/lib/offlineScan";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export default function TicketScanningPage() {
|
||||
const router = useRouter();
|
||||
@@ -158,8 +159,8 @@ export default function TicketScanningPage() {
|
||||
let preview: any;
|
||||
try {
|
||||
preview = await apiFetch<any>(`/api/tickets/scan-preview/${encodeURIComponent(text)}`, { authToken: token });
|
||||
} catch (pe: any) {
|
||||
setErrorModal(pe?.message || 'Failed to validate ticket');
|
||||
} catch (pe) {
|
||||
setErrorModal(errorMessage(pe) || 'Failed to validate ticket');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -202,8 +203,8 @@ export default function TicketScanningPage() {
|
||||
setConfirmQty(remaining);
|
||||
setConfirmQtyRaw(String(remaining));
|
||||
setConfirmModal({ qrCode: text, ticket: preview, remaining });
|
||||
} catch (e: any) {
|
||||
setErrorModal(e?.message || "Failed to scan ticket");
|
||||
} catch (e) {
|
||||
setErrorModal(errorMessage(e) || "Failed to scan ticket");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,9 +238,9 @@ export default function TicketScanningPage() {
|
||||
if (offlineTicket) {
|
||||
try {
|
||||
await offline.scanLocally(offlineTicket, qty);
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setSuccessModal(null);
|
||||
setErrorModal(e?.message || "Couldn't save the scan on this device");
|
||||
setErrorModal(errorMessage(e) || "Couldn't save the scan on this device");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -260,10 +261,10 @@ export default function TicketScanningPage() {
|
||||
},
|
||||
});
|
||||
refreshStatsAndRecent();
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setSuccessModal(null);
|
||||
setScanInfo(null);
|
||||
const raw = e?.message || "Failed to scan ticket";
|
||||
const raw = errorMessage(e) || "Failed to scan ticket";
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
const msg: string | undefined = parsed?.message;
|
||||
|
||||
@@ -8,6 +8,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { BedDouble, Plus, Wand2, Printer, Trash2, Pencil, Eraser } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null };
|
||||
type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] };
|
||||
@@ -96,8 +97,8 @@ export default function AllocationsPage() {
|
||||
const b = await apiFetch<Board>(`/api/allocations/event/${encodeURIComponent(eventId)}`, { authToken: token });
|
||||
setBoard(b);
|
||||
setSetId(id => (b.sets.some(s => s.id === id) ? id : b.sets[0]?.id || ""));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load allocations");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load allocations");
|
||||
}
|
||||
}, [token, eventId, setError]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
@@ -126,8 +127,8 @@ export default function AllocationsPage() {
|
||||
}));
|
||||
try {
|
||||
await call(`/api/allocations/sets/${current.id}/assignments`, "PUT", { attendeeId, groupId });
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Couldn't move them");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Couldn't move them");
|
||||
load();
|
||||
}
|
||||
};
|
||||
@@ -138,8 +139,8 @@ export default function AllocationsPage() {
|
||||
const msg = await fn();
|
||||
if (msg) setInfo(msg);
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Something went wrong");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Something went wrong");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -182,8 +183,8 @@ export default function AllocationsPage() {
|
||||
section{page-break-after:always} section:last-child{page-break-after:auto}
|
||||
</style></head><body>${body}<script>window.onload=function(){window.print()}</script></body></html>`);
|
||||
w.document.close();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Couldn't load the lists");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Couldn't load the lists");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi
|
||||
import { TransferTicketModal, canOfferTransfer } from "@/components/shared/TransferTicketModal";
|
||||
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Mode = "registration" | "payment" | "checkin" | "tickets" | "refund";
|
||||
|
||||
@@ -259,8 +260,8 @@ export default function AtTheDoorPage() {
|
||||
body: { code: doorCoupon.code },
|
||||
});
|
||||
message = `Registration updated — code ${doorCoupon.code} applied`;
|
||||
} catch (ce: any) {
|
||||
message = `Registration updated, but the code wasn't applied: ${ce?.message || "unknown error"}`;
|
||||
} catch (ce) {
|
||||
message = `Registration updated, but the code wasn't applied: ${errorMessage(ce) || "unknown error"}`;
|
||||
}
|
||||
}
|
||||
setShowOptionsModal(false);
|
||||
@@ -291,8 +292,8 @@ export default function AtTheDoorPage() {
|
||||
if (res?.couponError) setError(`Registered, but the code wasn't applied: ${res.couponError}`);
|
||||
handleRegistrationCreated(res);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed");
|
||||
} finally {
|
||||
setConfirming(false);
|
||||
}
|
||||
@@ -336,8 +337,8 @@ export default function AtTheDoorPage() {
|
||||
let freshReg = reg;
|
||||
try {
|
||||
freshReg = await apiFetch<any>(`/api/registrations/${reg.id}`, { authToken: token });
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load latest registration data");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load latest registration data");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -725,8 +726,8 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) {
|
||||
onSuccess(updated, true); // 🎯 partial payment flow
|
||||
}
|
||||
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Payment failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Payment failed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -1137,8 +1138,8 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: a
|
||||
res?.remaining > 0 ? ` — ${res.remaining} remaining` : " — fully checked in"
|
||||
}. Confirmation sent.`);
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Check-in failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Check-in failed");
|
||||
} finally {
|
||||
setSubmittingId(null);
|
||||
}
|
||||
@@ -1421,8 +1422,8 @@ function DonationModal({ open, onClose, user, token, eventId, onSuccess, setErro
|
||||
setAmount("");
|
||||
onClose();
|
||||
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Donation failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Donation failed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -1523,8 +1524,8 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf
|
||||
});
|
||||
setLocalInfo("Tickets sent successfully.");
|
||||
setTimeout(() => { setLocalInfo(""); onClose(); }, 7000);
|
||||
} catch (e: any) {
|
||||
setLocalError(e?.message || "Failed to send tickets");
|
||||
} catch (e) {
|
||||
setLocalError(errorMessage(e) || "Failed to send tickets");
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
@@ -1645,8 +1646,8 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded
|
||||
// Re-fetch registration to get updated status & payments
|
||||
const updated = await apiFetch<any>(`/api/registrations/${registration.id}`, { authToken: token });
|
||||
onRefunded(updated);
|
||||
} catch (e: any) {
|
||||
setLocalError(e?.message || "Refund failed.");
|
||||
} catch (e) {
|
||||
setLocalError(errorMessage(e) || "Refund failed.");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { formatDate } from "@/lib/date";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { ShieldCheck, Send, RefreshCw, HeartPulse, Printer } from "lucide-react";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type ConsentRow = {
|
||||
attendeeId: string;
|
||||
@@ -76,8 +77,8 @@ export default function ConsentTrackerPage() {
|
||||
setBusy(true);
|
||||
try {
|
||||
setData(await apiFetch(`/api/consent/events/${encodeURIComponent(eventId)}`, { authToken: token }));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load consent status");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load consent status");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -100,8 +101,8 @@ export default function ConsentTrackerPage() {
|
||||
const res = await fn();
|
||||
setInfo(res.message);
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Something went wrong");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Something went wrong");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -139,8 +140,8 @@ export default function ConsentTrackerPage() {
|
||||
<tbody>${rowsHtml || '<tr><td colspan="5">No consent given yet.</td></tr>'}</tbody></table>
|
||||
<script>window.onload=()=>window.print()</script></body></html>`);
|
||||
w.document.close();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load the medical list");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load the medical list");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { TicketPercent, Plus, X, Search } from "lucide-react";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type CouponType = "percent" | "fixed" | "comp";
|
||||
type Role = "user" | "staff" | "supervisor" | "admin";
|
||||
@@ -164,8 +165,8 @@ export default function CouponsPage() {
|
||||
]);
|
||||
setCoupons(c || []);
|
||||
setEvents(ev || []);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load coupons");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load coupons");
|
||||
} finally {
|
||||
setFetching(false);
|
||||
}
|
||||
@@ -183,8 +184,8 @@ export default function CouponsPage() {
|
||||
await apiFetch(`/api/coupons/${c.id}`, { method: "PUT", authToken: token!, body: { active: !c.active } });
|
||||
setInfo(`${c.code} turned ${c.active ? "off" : "on"}.`);
|
||||
load();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to update coupon");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to update coupon");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -192,8 +193,8 @@ export default function CouponsPage() {
|
||||
try {
|
||||
const full = await apiFetch<Coupon & { redemptions: Redemption[] }>(`/api/coupons/${c.id}`, { authToken: token! });
|
||||
setViewing({ coupon: c, redemptions: full.redemptions || [] });
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load uses");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load uses");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -406,8 +407,8 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: {
|
||||
await apiFetch(`/api/coupons`, { method: "POST", authToken: token, body });
|
||||
onSaved(`${body.code.toUpperCase()} created.`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to save");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Failed to save");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch, fetchAllUsers } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Mail, Users, Zap, Clock } from "lucide-react";
|
||||
import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Attendee = { id: string; name: string; email: string; pref: string };
|
||||
|
||||
@@ -198,8 +199,8 @@ function EmailAttendeesPageInner() {
|
||||
const evs = await apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token || undefined });
|
||||
const sorted = (evs || []).sort((a: any, b: any) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
|
||||
setAllEvents(sorted);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
} finally {
|
||||
setLoadingEvents(false);
|
||||
}
|
||||
@@ -431,8 +432,8 @@ function EmailAttendeesPageInner() {
|
||||
setPreviewCount(res?.matched ?? 0);
|
||||
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
|
||||
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to preview recipients');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to preview recipients');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -471,8 +472,8 @@ function EmailAttendeesPageInner() {
|
||||
setInfo(`Queued ${queued} recipient(s) for sending.`);
|
||||
// Reset form to default state
|
||||
resetAttendeesForm();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to send emails');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to send emails');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Ticket } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// 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
|
||||
@@ -161,8 +162,8 @@ function EventOptionsContent() {
|
||||
setNewOpt({ name: "", price: "", isMainTicket: false });
|
||||
setInfo("Option created");
|
||||
await loadEvents();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create option");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create option");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -177,8 +178,8 @@ function EventOptionsContent() {
|
||||
});
|
||||
setInfo("Option updated");
|
||||
await loadEvents();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to update option");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to update option");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -192,8 +193,8 @@ function EventOptionsContent() {
|
||||
});
|
||||
setInfo("Option deleted");
|
||||
await loadEvents();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to delete option");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to delete option");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { Calendar } from "lucide-react";
|
||||
import { ChoicesEditor } from "@/components/shared/FormFieldExtras";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// ─── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -731,8 +732,8 @@ function NotifyRecipientsManager({ eventId, creator, initialRecipients }: { even
|
||||
try {
|
||||
const res = await apiFetch<any>(`/api/events/${eventId}/notify-recipients`, { authToken: token || undefined });
|
||||
if (!cancelled) setSelected(Array.isArray(res) ? res : []);
|
||||
} catch (e: any) {
|
||||
if (!cancelled) setError(e?.message || "Failed to load notification recipients");
|
||||
} catch (e) {
|
||||
if (!cancelled) setError(errorMessage(e) || "Failed to load notification recipients");
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
@@ -751,9 +752,9 @@ function NotifyRecipientsManager({ eventId, creator, initialRecipients }: { even
|
||||
method: "PUT", authToken: token || undefined,
|
||||
body: { userIds: next.map(u => u.id) },
|
||||
});
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setSelected(prev);
|
||||
setError(e?.message || "Failed to save notification recipients");
|
||||
setError(errorMessage(e) || "Failed to save notification recipients");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -1219,8 +1220,8 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
|
||||
}
|
||||
|
||||
onSuccess(); onClose();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to save event");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to save event");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -1720,8 +1721,8 @@ export default function ManageEventsPage() {
|
||||
try {
|
||||
const evs = await apiFetch<any[]>("/api/events/all?includePast=true&includeInactive=true", { authToken: token });
|
||||
setEvents(Array.isArray(evs) ? evs.sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()) : []);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
} finally {
|
||||
setLoadingEvents(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";
|
||||
import { apiFetch, fetchAllUsers } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { FileText } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type FormFieldType = 'yes_no' | 'text' | 'date' | 'numeric' | 'statement' | 'paragraph' | 'rating' | 'multiple_choice';
|
||||
|
||||
@@ -211,8 +212,8 @@ export default function FormsBrowserPage() {
|
||||
const newItems = Array.isArray(res?.items) ? res!.items : [];
|
||||
setItems(prev => append ? [...prev, ...newItems] : newItems);
|
||||
setNextCursor(res?.nextCursor || null);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load form responses");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load form responses");
|
||||
} finally {
|
||||
setLoadingList(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { UserPlus } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
|
||||
|
||||
@@ -52,8 +53,8 @@ export default function ManualRegistrationPage() {
|
||||
if (ev?.form) setForm(ev.form);
|
||||
} catch {}
|
||||
alert("Manual registration created");
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create manual registration");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create manual registration");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -150,8 +151,8 @@ function AttendeeFormsSection({ registration, form, formsData, setFormsData }: {
|
||||
method: 'POST', authToken: token, body: { responses: payload }
|
||||
});
|
||||
setInfo('Attendee forms submitted successfully.');
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to submit forms');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to submit forms');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||||
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { UserPlus, CreditCard } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// ─── Pricing helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -199,8 +200,8 @@ export default function ManualRegistrationPage() {
|
||||
const regs = await apiFetch<any[]>("/api/registrations", { authToken: token });
|
||||
setAllRegistrations(Array.isArray(regs) ? regs : []);
|
||||
} catch {}
|
||||
} catch (e: any) {
|
||||
setPayError(e?.message || "Failed to record payment");
|
||||
} catch (e) {
|
||||
setPayError(errorMessage(e) || "Failed to record payment");
|
||||
} finally {
|
||||
setPaySubmitting(false);
|
||||
}
|
||||
@@ -356,8 +357,8 @@ export default function ManualRegistrationPage() {
|
||||
setAttendeeEntries({});
|
||||
setDelivery("payer");
|
||||
setQuantities(prev => Object.fromEntries(Object.keys(prev).map(k => [k, 0])));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create manual registration");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create manual registration");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { WifiOff, Unlock, CheckCircle2 } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null };
|
||||
type Report = {
|
||||
@@ -57,8 +58,8 @@ export default function OfflineScansPage() {
|
||||
]);
|
||||
setLocks(l);
|
||||
setReports(r.filter(x => !onlyOpen || x.conflicts.length > 0 || x.afterForceRelease));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load offline scanning");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load offline scanning");
|
||||
}
|
||||
}, [token, eventId, onlyOpen, setError]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
@@ -68,13 +69,13 @@ export default function OfflineScansPage() {
|
||||
const res = await apiFetch<{ message: string }>(`/api/scan-locks/${l.id}/force-release`, { method: "POST", authToken: token! });
|
||||
setInfo(res.message);
|
||||
load();
|
||||
} catch (e: any) { setError(e?.message || "Failed"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed"); }
|
||||
};
|
||||
const review = async (r: Report) => {
|
||||
try {
|
||||
await apiFetch(`/api/scan-locks/reports/${r.id}/review`, { method: "POST", authToken: token! });
|
||||
load();
|
||||
} catch (e: any) { setError(e?.message || "Failed"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed"); }
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch, fetchAllUsers, fetchAllPayments } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { scoreUser } from "@/lib/fuzzyMatch";
|
||||
import { Wallet, RotateCcw, HandHeart, ScanLine, Link2 } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// A donation is never mutated once created — assigning it to a registration creates a separate
|
||||
// "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead.
|
||||
@@ -150,8 +151,8 @@ function PaymentsContent() {
|
||||
setLoadingList(true);
|
||||
const list = await fetchAllPayments(token);
|
||||
setPayments(list.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load payments");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load payments");
|
||||
} finally {
|
||||
setLoadingList(false);
|
||||
}
|
||||
@@ -327,8 +328,8 @@ function PaymentsContent() {
|
||||
if (!res.redirectUrl) { setError("Failed to generate link"); return; }
|
||||
setLinkResult({ redirectUrl: res.redirectUrl, amount: res.amount ?? amt, registrationId: linkRegistrationId });
|
||||
setInfo("Payment link generated");
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to generate payment link");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to generate payment link");
|
||||
} finally {
|
||||
setLinkGenerating(false);
|
||||
}
|
||||
@@ -356,8 +357,8 @@ function PaymentsContent() {
|
||||
body: { registrationId: linkResult.registrationId, redirectUrl: linkResult.redirectUrl, channel },
|
||||
});
|
||||
setInfo(`Payment link sent via ${channel === "email" ? "email" : "WhatsApp"}`);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || `Failed to send link via ${channel}`);
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || `Failed to send link via ${channel}`);
|
||||
} finally {
|
||||
setLinkSending(null);
|
||||
}
|
||||
@@ -433,8 +434,8 @@ function PaymentsContent() {
|
||||
setInfo(`Payment created (R ${amt.toFixed(2)})`);
|
||||
setAmount(""); setRegistrationId(""); setIsDonation(false); setEventId(""); setPaidAtLocal("");
|
||||
await Promise.all([loadPayments(), loadRegistrations()]);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create payment");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create payment");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -515,8 +516,8 @@ function PaymentsContent() {
|
||||
}
|
||||
setReconcileForm({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false });
|
||||
await Promise.all([loadYocoUnreconciled(), loadPayments(), loadRegistrations()]);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to reconcile');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to reconcile');
|
||||
} finally {
|
||||
setReconcileForm(prev => ({ ...prev, submitting: false }));
|
||||
}
|
||||
@@ -944,8 +945,8 @@ function RefundSection({ payments, allUsers, regsForUser, regOutstanding, onDone
|
||||
});
|
||||
setUserId(""); setPaymentId(""); setRegistrationId(""); setAmount(""); setReason(""); setMethod("");
|
||||
await onDone();
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || 'Failed to create refund');
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || 'Failed to create refund');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -1083,8 +1084,8 @@ function AssignedDonationsList({ payments, onDone }: AssignedDonationsListProps)
|
||||
body: { legId: leg.id }
|
||||
});
|
||||
await onDone();
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || 'Failed to unassign donation');
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || 'Failed to unassign donation');
|
||||
} finally {
|
||||
setUnassigningId(null);
|
||||
}
|
||||
@@ -1267,8 +1268,8 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi
|
||||
});
|
||||
setUserId(""); setRegistrationId(""); setPaymentId(""); setAmountStr("");
|
||||
await onDone();
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || 'Failed to assign donation');
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || 'Failed to assign donation');
|
||||
} finally {
|
||||
setAssigning(false);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { formatDate } from "@/lib/date";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { ListChecks, ArrowUp, ArrowDown } from "lucide-react";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Entry = {
|
||||
id: string;
|
||||
@@ -67,8 +68,8 @@ export default function WaitlistPage() {
|
||||
setBusy(true);
|
||||
try {
|
||||
setEntries(await apiFetch<Entry[]>(`/api/waitlist/events/${encodeURIComponent(eventId)}`, { authToken: token }));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load the waitlist");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load the waitlist");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -81,8 +82,8 @@ export default function WaitlistPage() {
|
||||
const res = await apiFetch<{ message?: string }>(path, { method: "POST", authToken: token!, body });
|
||||
if (res?.message) setInfo(res.message);
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Something went wrong");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Something went wrong");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch, fetchAllUsers } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { MessageCircle, Users, Zap, Send, Clock, type LucideIcon } from "lucide-react";
|
||||
import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// Attendee with preference info
|
||||
type Attendee = { id: string; name: string; phone: string; pref: string };
|
||||
@@ -248,8 +249,8 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: any[];
|
||||
scheduled++;
|
||||
}
|
||||
onInfo(`Scheduled ${scheduled} WhatsApp automation(s).`);
|
||||
} catch (e: any) {
|
||||
onError(e?.message || "Failed to schedule automations");
|
||||
} catch (e) {
|
||||
onError(errorMessage(e) || "Failed to schedule automations");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -387,8 +388,8 @@ function WhatsAppAttendeesPageInner() {
|
||||
setLoadingEvents(true);
|
||||
const evs = await apiFetch<any[]>("/api/events/all?includePast=true", { authToken: token || undefined });
|
||||
setAllEvents((evs || []).sort((a: any, b: any) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()));
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
} finally {
|
||||
setLoadingEvents(false);
|
||||
}
|
||||
@@ -469,7 +470,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
setPreviewCount(res?.matched ?? 0);
|
||||
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
|
||||
setInfo(`Matched ${res?.matched ?? 0} recipient(s) with a phone number.`);
|
||||
} catch (e: any) { setError(e?.message || "Failed to preview"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to preview"); }
|
||||
};
|
||||
|
||||
const resetAttendeesForm = () => {
|
||||
@@ -488,7 +489,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload() });
|
||||
setInfo(`Queued ${res?.queued ?? res?.matched ?? 0} recipient(s) for sending.`);
|
||||
resetAttendeesForm();
|
||||
} catch (e: any) { setError(e?.message || "Failed to send"); } finally { setSending(false); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to send"); } finally { setSending(false); }
|
||||
};
|
||||
|
||||
const onScheduleSend = async () => {
|
||||
@@ -507,7 +508,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
const res = await apiFetch(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload });
|
||||
setInfo(res?.job?.id ? "WhatsApp scheduled. It will be sent around the specified time." : "Scheduled.");
|
||||
resetAttendeesForm();
|
||||
} catch (e: any) { setError(e?.message || "Failed to schedule"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to schedule"); }
|
||||
};
|
||||
|
||||
// ── Broadcasts tab ─────────────────────────────────────────────────────────
|
||||
@@ -575,7 +576,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
setInfo("Scheduled message updated.");
|
||||
setEditing(null);
|
||||
loadScheduled();
|
||||
} catch (e: any) { setError(e?.message || "Failed to update"); } finally { setSavingEdit(false); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to update"); } finally { setSavingEdit(false); }
|
||||
};
|
||||
|
||||
const removeJob = async (job: ScheduledJob) => {
|
||||
@@ -584,7 +585,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
await apiFetch(`/api/scheduled-emails/${encodeURIComponent(job.id)}`, { method: "DELETE", authToken: token });
|
||||
setInfo("Scheduled message removed.");
|
||||
loadScheduled();
|
||||
} catch (e: any) { setError(e?.message || "Failed to remove"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to remove"); }
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
@@ -841,7 +842,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
setBroadcastPreviewCount(res?.matched ?? 0);
|
||||
setBroadcastPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
|
||||
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
|
||||
} catch (e: any) { setError(e?.message || "Failed to preview"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to preview"); }
|
||||
}}>Preview recipients</button>
|
||||
|
||||
<button type="button" className="px-3 py-1.5 text-sm rounded bg-green-600 text-white hover:bg-green-700 disabled:opacity-50" onClick={async () => {
|
||||
@@ -852,7 +853,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
const res = await apiFetch(`/api/whatsapp-broadcasts/send`, { method: "POST", authToken: token, body: { message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
|
||||
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).`);
|
||||
resetBroadcastForm();
|
||||
} catch (e: any) { setError(e?.message || "Failed to send"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to send"); }
|
||||
}}>Send now</button>
|
||||
|
||||
<button type="button" disabled={!broadcastScheduledAtLocal} className="px-3 py-1.5 text-sm rounded bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50" onClick={async () => {
|
||||
@@ -864,7 +865,7 @@ function WhatsAppAttendeesPageInner() {
|
||||
const res = await apiFetch(`/api/whatsapp-broadcasts/schedule`, { method: "POST", authToken: token, body: { scheduledAt: whenIso, message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
|
||||
if (res?.job?.id) setInfo("WhatsApp broadcast scheduled."); else setInfo("Scheduled.");
|
||||
resetBroadcastForm();
|
||||
} catch (e: any) { setError(e?.message || "Failed to schedule broadcast"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Failed to schedule broadcast"); }
|
||||
}}>Schedule send</button>
|
||||
|
||||
{broadcastPreviewCount != null && <span className="text-xs text-gray-600">Preview: {broadcastPreviewCount} recipient(s)</span>}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { HandHeart } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export default function DonatePage() {
|
||||
const { token } = useAuth();
|
||||
@@ -20,8 +21,8 @@ export default function DonatePage() {
|
||||
const evs = await apiFetch<any[]>("/api/events");
|
||||
setEvents(evs);
|
||||
if (evs.length > 0) setEventId(evs[0].id);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
@@ -49,8 +50,8 @@ export default function DonatePage() {
|
||||
});
|
||||
setInfo("Redirecting to payment...");
|
||||
window.location.href = res.redirectUrl;
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to start donation checkout");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to start donation checkout");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { FileText } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// Types for form fields
|
||||
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
|
||||
@@ -41,8 +42,8 @@ function FormsContent() {
|
||||
const draft = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token });
|
||||
if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data);
|
||||
} catch {}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to load registration');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to load registration');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -108,8 +109,8 @@ function FormsContent() {
|
||||
setFormsData({});
|
||||
// On success, redirect to the user dashbaord
|
||||
router.push('/dashboard/user');
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to submit forms');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to submit forms');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -123,8 +124,8 @@ function FormsContent() {
|
||||
body: { data: formsData }
|
||||
});
|
||||
setInfo('Draft saved. You can return later to finish.');
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to save draft');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to save draft');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AttendeesPanel } from "@/components/shared/AttendeesPanel";
|
||||
import { MyWaitlists } from "@/components/shared/MyWaitlists";
|
||||
import { TransferTicketModal, canOfferTransfer } from "@/components/shared/TransferTicketModal";
|
||||
import { ClipboardList, Calendar, Ticket, ChevronRight } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// Helper formatters
|
||||
const formatRand = (n: number) => `R ${n.toFixed(2)}`;
|
||||
@@ -178,8 +179,8 @@ export default function UserDashboardPage() {
|
||||
}
|
||||
})
|
||||
);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load data");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -252,9 +253,9 @@ export default function UserDashboardPage() {
|
||||
});
|
||||
const msg = (res && res.message) ? res.message : `${ticketIds.length} ticket(s) emailed successfully.`;
|
||||
setDialog({ open: true, message: msg, loading: false });
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setDialog({ open: false, message: "", loading: false });
|
||||
setError(e?.message || "Failed to email tickets");
|
||||
setError(errorMessage(e) || "Failed to email tickets");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -272,9 +273,9 @@ export default function UserDashboardPage() {
|
||||
});
|
||||
const msg = (res && res.message) ? res.message : `${ticketIds.length} ticket(s) sent to WhatsApp.`;
|
||||
setDialog({ open: true, message: msg, loading: false });
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setDialog({ open: false, message: "", loading: false });
|
||||
setError(e?.message || "Failed to send tickets to WhatsApp");
|
||||
setError(errorMessage(e) || "Failed to send tickets to WhatsApp");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -294,9 +295,9 @@ export default function UserDashboardPage() {
|
||||
authToken: token,
|
||||
});
|
||||
setDialog({ open: true, loading: false, title: "Invoice sent", message: (res && res.message) || "Invoice sent." });
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setDialog({ open: false, message: "", loading: false });
|
||||
setError(e?.message || "Failed to send invoice");
|
||||
setError(errorMessage(e) || "Failed to send invoice");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -316,9 +317,9 @@ export default function UserDashboardPage() {
|
||||
authToken: token,
|
||||
});
|
||||
setDialog({ open: true, loading: false, title: "Receipt sent", message: (res && res.message) || "Receipt sent." });
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setDialog({ open: false, message: "", loading: false });
|
||||
setError(e?.message || "Failed to send receipt");
|
||||
setError(errorMessage(e) || "Failed to send receipt");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -361,9 +362,9 @@ export default function UserDashboardPage() {
|
||||
return;
|
||||
}
|
||||
window.location.href = res.redirectUrl;
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setDialog({ open: false, message: "", loading: false });
|
||||
setError(e?.message || "Failed to create checkout");
|
||||
setError(errorMessage(e) || "Failed to create checkout");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -518,8 +519,8 @@ export default function UserDashboardPage() {
|
||||
} catch {}
|
||||
setCodeInput("");
|
||||
setInfo(res?.message || 'Code applied.');
|
||||
} catch (e: any) {
|
||||
setCodeError(e?.message || "Couldn't apply that code");
|
||||
} catch (e) {
|
||||
setCodeError(errorMessage(e) || "Couldn't apply that code");
|
||||
} finally {
|
||||
setCodeBusy(false);
|
||||
}
|
||||
@@ -555,8 +556,8 @@ export default function UserDashboardPage() {
|
||||
setActiveRegId(null);
|
||||
setShowCancelConfirm(false);
|
||||
setInfo('Registration cancelled.');
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to cancel registration');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to cancel registration');
|
||||
setShowCancelConfirm(false);
|
||||
} finally {
|
||||
setCancelLoading(false);
|
||||
@@ -718,8 +719,8 @@ export default function UserDashboardPage() {
|
||||
} catch {}
|
||||
setInfo('Registration updated successfully');
|
||||
setEditMode(false);
|
||||
} catch (e: any) {
|
||||
setEditError(e?.message || 'Failed to update registration');
|
||||
} catch (e) {
|
||||
setEditError(errorMessage(e) || 'Failed to update registration');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -1009,7 +1010,7 @@ export default function UserDashboardPage() {
|
||||
const r: any = await apiFetch(`/api/tickets/${t.id}/transfer`, { method: "DELETE", authToken: token! });
|
||||
setInfo(r?.message || "Transfer cancelled");
|
||||
reloadAfterAttendees();
|
||||
} catch (e: any) { setError(e?.message || "Couldn't cancel"); }
|
||||
} catch (e) { setError(errorMessage(e) || "Couldn't cancel"); }
|
||||
}}>Cancel</button>
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { formatDateTime } from "@/lib/date";
|
||||
import { formatPaymentMethod } from "@/lib/paymentMethod";
|
||||
import { Receipt } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
interface PaymentItem {
|
||||
id: string;
|
||||
@@ -55,8 +56,8 @@ export default function UserPaymentsPage() {
|
||||
authToken: token,
|
||||
});
|
||||
setInfo((res && res.message) || "Receipt sent.");
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to send receipt");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to send receipt");
|
||||
} finally {
|
||||
setSendingReceipt(false);
|
||||
}
|
||||
@@ -87,8 +88,8 @@ export default function UserPaymentsPage() {
|
||||
setTotal(res?.total ?? 0);
|
||||
setTotalPages(res?.pages ?? 1);
|
||||
setPage(p);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load payments");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load payments");
|
||||
} finally {
|
||||
setFetching(false);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { isValidZAPhone } from "@/lib/phone";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { TwoFactorChallenge, TwoFactorMethod } from "@/lib/auth";
|
||||
import { User, Lock, ShieldAlert, ShieldCheck, ShieldOff, Trash2, Clock, LogIn, KeyRound, RotateCcw } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
|
||||
|
||||
@@ -67,8 +68,8 @@ export default function UserProfilePage() {
|
||||
// Backend returns a refreshed token — save it so the session stays valid
|
||||
if (res?.token) updateToken(res.token);
|
||||
setProfileMsg({ type: "ok", text: "Profile updated." });
|
||||
} catch (e: any) {
|
||||
setProfileMsg({ type: "err", text: e?.message || "Failed to update profile." });
|
||||
} catch (e) {
|
||||
setProfileMsg({ type: "err", text: errorMessage(e) || "Failed to update profile." });
|
||||
} finally {
|
||||
setSavingProfile(false);
|
||||
}
|
||||
@@ -106,8 +107,8 @@ export default function UserProfilePage() {
|
||||
setConfirmPassword("");
|
||||
setPwMsg({ type: "ok", text: "Password changed." });
|
||||
loadActivity();
|
||||
} catch (e: any) {
|
||||
setPwMsg({ type: "err", text: e?.message || "Failed to change password." });
|
||||
} catch (e) {
|
||||
setPwMsg({ type: "err", text: errorMessage(e) || "Failed to change password." });
|
||||
} finally {
|
||||
setSavingPw(false);
|
||||
}
|
||||
@@ -131,8 +132,8 @@ export default function UserProfilePage() {
|
||||
// save the freshly issued one so this device stays signed in.
|
||||
if (res?.token) updateToken(res.token);
|
||||
setRevokeMsg({ type: "ok", text: res?.message || "All other sessions signed out." });
|
||||
} catch (e: any) {
|
||||
setRevokeMsg({ type: "err", text: e?.message || "Failed to revoke sessions." });
|
||||
} catch (e) {
|
||||
setRevokeMsg({ type: "err", text: errorMessage(e) || "Failed to revoke sessions." });
|
||||
} finally {
|
||||
setRevoking(false);
|
||||
}
|
||||
@@ -203,8 +204,8 @@ export default function UserProfilePage() {
|
||||
setTfCode("");
|
||||
setTfPassword("");
|
||||
setTfStep("code");
|
||||
} catch (e: any) {
|
||||
setTfMsg({ type: "err", text: e?.message || "Failed to send a verification code." });
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to send a verification code." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
@@ -227,8 +228,8 @@ export default function UserProfilePage() {
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Codes will now be sent by ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
loadActivity();
|
||||
} catch (e: any) {
|
||||
setTfMsg({ type: "err", text: e?.message || "Failed to verify the code." });
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
@@ -249,8 +250,8 @@ export default function UserProfilePage() {
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
||||
loadActivity();
|
||||
} catch (e: any) {
|
||||
setTfMsg({ type: "err", text: e?.message || "Failed to turn off two-factor authentication." });
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to turn off two-factor authentication." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
@@ -277,8 +278,8 @@ export default function UserProfilePage() {
|
||||
setCloseMsg({ type: "ok", text: res?.message || "Account closed." });
|
||||
// Slight delay so the user can read the message, then log out
|
||||
setTimeout(() => logout(), 2500);
|
||||
} catch (e: any) {
|
||||
setCloseMsg({ type: "err", text: e?.message || "Failed to close account." });
|
||||
} catch (e) {
|
||||
setCloseMsg({ type: "err", text: errorMessage(e) || "Failed to close account." });
|
||||
} finally {
|
||||
setClosing(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const { token } = useAuth();
|
||||
@@ -35,8 +36,8 @@ export default function ResetPasswordPage() {
|
||||
setPassword("");
|
||||
setConfirm("");
|
||||
setTimeout(() => router.push("/dashboard/user"), 1200);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to update password");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Failed to update password");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { MessageSquareHeart, CheckCircle2 } from "lucide-react";
|
||||
import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormFieldExtras";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Field = { id: string; type: string; label: string; isRequired: boolean; helpText: string | null; options: unknown };
|
||||
type FeedbackInfo = {
|
||||
@@ -46,8 +47,8 @@ export default function FeedbackPage() {
|
||||
try {
|
||||
await apiFetch(`/api/feedback/public/${encodeURIComponent(token!)}`, { method: "POST", body: { answers } });
|
||||
setDone(true);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Couldn't send your feedback");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Couldn't send your feedback");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { FileText } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// Types for form fields
|
||||
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
|
||||
@@ -45,8 +46,8 @@ function FormsContent() {
|
||||
const draft = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token || undefined });
|
||||
if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data);
|
||||
} catch {}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to load registration');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to load registration');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -128,8 +129,8 @@ function FormsContent() {
|
||||
// On success, redirect to the success page
|
||||
const totalDue = (registration?.registrationOptions || []).reduce((s: number, ro: any) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0);
|
||||
router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}`);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to submit forms');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to submit forms');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -148,11 +149,11 @@ function FormsContent() {
|
||||
// Redirect to the success page
|
||||
const totalDue = (registration?.registrationOptions || []).reduce((s: number, ro: any) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0);
|
||||
router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}`);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failded to go to next step');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failded to go to next step');
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to save draft');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to save draft');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -162,8 +163,8 @@ function FormsContent() {
|
||||
// Redirect to the success page
|
||||
const totalDue = (registration?.registrationOptions || []).reduce((s: number, ro: any) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0);
|
||||
router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}`);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failded to skip');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failded to skip');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi
|
||||
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
|
||||
import { analyticsSessionId } from "@/lib/analytics";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// Tiered low-stock threshold — mirrors events/[id]/page.tsx
|
||||
function lowStockThreshold(stockLimit: number): number {
|
||||
@@ -395,8 +396,8 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
|
||||
body: { eventId, options: items, waitlistToken, analyticsSessionId: analyticsSessionId(), ...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}) },
|
||||
});
|
||||
if (res?.id) window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent((res.totalDueComputed ?? payable).toFixed(2))}`;
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Registration failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Registration failed");
|
||||
} finally {
|
||||
setCreatingRegistration(false);
|
||||
}
|
||||
@@ -439,8 +440,8 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
|
||||
}
|
||||
window.location.href = next;
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Registration failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Registration failed");
|
||||
} finally {
|
||||
setCreatingRegistration(false);
|
||||
}
|
||||
@@ -475,8 +476,8 @@ export default function RegisterForm({ event: baseEvent }: { event: Event }) {
|
||||
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`;
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Registration failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Registration failed");
|
||||
} finally {
|
||||
setCreatingRegistration(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Footer } from "@/components/layout/Footer";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { CheckCircle2 } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown };
|
||||
|
||||
@@ -36,8 +37,8 @@ function RegistrationSuccessContent() {
|
||||
const ev = await (await import('@/lib/api')).apiFetch(`/api/events/${encodeURIComponent(r.eventId)}`);
|
||||
if (ev?.form) setForm(ev.form);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to load details');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to load details');
|
||||
}
|
||||
})();
|
||||
}, [registrationId, token]);
|
||||
@@ -92,8 +93,8 @@ function RegistrationSuccessContent() {
|
||||
}
|
||||
if (!res.redirectUrl) { setError('Failed to create checkout'); return; }
|
||||
window.location.href = res.redirectUrl;
|
||||
} catch (e: any) {
|
||||
setError(e?.message || 'Failed to create checkout');
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || 'Failed to create checkout');
|
||||
} finally {
|
||||
setPayLoading(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Footer } from "@/components/layout/Footer";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
function ResetPasswordContent() {
|
||||
const search = useSearchParams();
|
||||
@@ -26,8 +27,8 @@ function ResetPasswordContent() {
|
||||
await apiFetch("/api/users/reset", { method: "POST", body: { token, password } });
|
||||
setStatus("Your password has been reset. You can now log in.");
|
||||
setTimeout(() => router.push("/login"), 1500);
|
||||
} catch (err: any) {
|
||||
setStatus(err?.message || "Reset failed");
|
||||
} catch (err) {
|
||||
setStatus(errorMessage(err) || "Reset failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { apiFetch } from "@/lib/api";
|
||||
import { TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
|
||||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||||
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
|
||||
@@ -318,8 +319,8 @@ export default function SelfServicePage() {
|
||||
setSetupCode("");
|
||||
setSupervisorToken(data.token);
|
||||
await loadEvents(data.token);
|
||||
} catch (err: any) {
|
||||
setSetupError(err?.message || "Login failed. Please check your credentials.");
|
||||
} catch (err) {
|
||||
setSetupError(errorMessage(err) || "Login failed. Please check your credentials.");
|
||||
} finally {
|
||||
setSetupLoading(false);
|
||||
}
|
||||
@@ -361,8 +362,8 @@ export default function SelfServicePage() {
|
||||
setScreen("setup");
|
||||
setSelectedEventId("");
|
||||
resetForm();
|
||||
} catch (err: any) {
|
||||
setChangeError(err?.message || "Incorrect password.");
|
||||
} catch (err) {
|
||||
setChangeError(errorMessage(err) || "Incorrect password.");
|
||||
} finally {
|
||||
setChangeLoading(false);
|
||||
}
|
||||
@@ -455,8 +456,8 @@ export default function SelfServicePage() {
|
||||
setScreen("confirmation");
|
||||
startCountdown();
|
||||
}
|
||||
} catch (err: any) {
|
||||
setFormError(err?.message || "Registration failed. Please try again.");
|
||||
} catch (err) {
|
||||
setFormError(errorMessage(err) || "Registration failed. Please try again.");
|
||||
} finally {
|
||||
setFormLoading(false);
|
||||
}
|
||||
@@ -503,8 +504,8 @@ export default function SelfServicePage() {
|
||||
|
||||
setScreen("confirmation");
|
||||
startCountdown();
|
||||
} catch (err: any) {
|
||||
setFormSubmitError(err?.message || "Form submission failed. Please try again.");
|
||||
} catch (err) {
|
||||
setFormSubmitError(errorMessage(err) || "Form submission failed. Please try again.");
|
||||
} finally {
|
||||
setFormSubmitLoading(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { Megaphone } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type BannerType = "info" | "warning" | "success" | "danger";
|
||||
|
||||
@@ -75,8 +76,8 @@ export default function SetBannerPage() {
|
||||
},
|
||||
});
|
||||
setStatus("Banner saved.");
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to save banner.");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to save banner.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -98,8 +99,8 @@ export default function SetBannerPage() {
|
||||
setLiveFrom("");
|
||||
setLiveTill("");
|
||||
setStatus("Banner cleared.");
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to clear banner.");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to clear banner.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { apiFetch, API_BASE } 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";
|
||||
|
||||
type Step = 1 | 2 | 3 | 4 | 5 | 6;
|
||||
|
||||
@@ -144,8 +145,8 @@ export default function SetupPage() {
|
||||
});
|
||||
setSetupToken(res.token);
|
||||
next();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to create admin account. Please try again.");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to create admin account. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -173,8 +174,8 @@ export default function SetupPage() {
|
||||
},
|
||||
});
|
||||
setSmtpTestResult({ ok: true, message: res.message || "Connection successful." });
|
||||
} catch (e: any) {
|
||||
setSmtpTestResult({ ok: false, message: e?.message || "Connection failed." });
|
||||
} catch (e) {
|
||||
setSmtpTestResult({ ok: false, message: errorMessage(e) || "Connection failed." });
|
||||
} finally {
|
||||
setSmtpTesting(false);
|
||||
}
|
||||
@@ -260,8 +261,8 @@ export default function SetupPage() {
|
||||
});
|
||||
|
||||
next(); // → step 6 (done)
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Setup failed. Please try again.");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Setup failed. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Footer } from "@/components/layout/Footer";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { Ticket, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Offer = {
|
||||
status: "pending" | "accepted" | "declined" | "cancelled" | "expired";
|
||||
@@ -46,8 +47,8 @@ export default function TransferOfferPage() {
|
||||
try {
|
||||
const r = await apiFetch<{ message: string }>(`/api/tickets/transfer-offer/${encodeURIComponent(token!)}/${action}`, { method: "POST" });
|
||||
setDone({ ok: action === "accept", message: r.message });
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Something went wrong");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Something went wrong");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch, API_BASE } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { DatabaseBackup, Download } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
interface BackupEntry {
|
||||
filename: string;
|
||||
@@ -38,8 +39,8 @@ export function BackupsTab({ active }: { active: boolean }) {
|
||||
]);
|
||||
setBackups(list || []);
|
||||
setRetainCount(allSettings?.backup_retain_count || "14");
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Failed to load backups" });
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Failed to load backups" });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -51,8 +52,8 @@ export function BackupsTab({ active }: { active: boolean }) {
|
||||
try {
|
||||
await apiFetch("/api/settings", { method: "PUT", authToken: token, body: { backup_retain_count: retainCount } });
|
||||
setMessage({ type: "ok", text: "Retention setting saved." });
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Failed to save retention setting" });
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Failed to save retention setting" });
|
||||
} finally {
|
||||
setSavingRetain(false);
|
||||
}
|
||||
@@ -68,8 +69,8 @@ export function BackupsTab({ active }: { active: boolean }) {
|
||||
const res = await apiFetch<{ filename: string }>("/api/backups/run", { method: "POST", authToken: token });
|
||||
setMessage({ type: "ok", text: `Backup created: ${res.filename}` });
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Backup failed" });
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Backup failed" });
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Copy, CreditCard, KeyRound, Trash2, Webhook } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Source = "db" | "env" | "none";
|
||||
|
||||
@@ -99,9 +100,9 @@ export function YocoTab({ active }: { active: boolean }) {
|
||||
const res = await apiFetch<{ webhooks: YocoWebhook[] }>("/api/yoco/webhooks", { authToken: token });
|
||||
setHooks(res.webhooks || []);
|
||||
setHooksError(null);
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
setHooks([]);
|
||||
setHooksError(e?.message || "Could not load webhooks from Yoco");
|
||||
setHooksError(errorMessage(e) || "Could not load webhooks from Yoco");
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
@@ -114,8 +115,8 @@ export function YocoTab({ active }: { active: boolean }) {
|
||||
setHookUrl((prev) => prev || c.webhookUrl);
|
||||
if (c.secretKeySource !== "none") await loadHooks();
|
||||
else { setHooks([]); setHooksError(null); }
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Failed to load Yoco settings" });
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Failed to load Yoco settings" });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -130,8 +131,8 @@ export function YocoTab({ active }: { active: boolean }) {
|
||||
const text = await fn();
|
||||
setMessage({ type: "ok", text });
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Something went wrong" });
|
||||
} catch (e) {
|
||||
setMessage({ type: "err", text: errorMessage(e) || "Something went wrong" });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ export function LoginForm() {
|
||||
return;
|
||||
}
|
||||
goToDashboard(result);
|
||||
} catch (err: any) {
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err) || "Login failed. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -92,7 +92,7 @@ export function LoginForm() {
|
||||
|
||||
try {
|
||||
goToDashboard(await verifyTwoFactor(challenge.challengeId, code, rememberDevice));
|
||||
} catch (err: any) {
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err) || "Verification failed. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -108,7 +108,7 @@ export function LoginForm() {
|
||||
setChallenge({ ...next, enrolling: challenge.enrolling });
|
||||
setCode("");
|
||||
setResendIn(RESEND_COOLDOWN_SECONDS);
|
||||
} catch (err: any) {
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err) || "Couldn't send a new code. Please try again.");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -62,7 +62,7 @@ export function RegisterForm() {
|
||||
notificationPreference: hasValidPhone ? notificationPreference : "email",
|
||||
});
|
||||
window.location.href = redirectTo;
|
||||
} catch (err: any) {
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err) || "Registration failed. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
@@ -4,6 +4,7 @@ import React, { useEffect, useState } from "react";
|
||||
import { HeartHandshake, X } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Sponsorship = { enabled: boolean; open?: boolean; spotPrice?: number | null; showProgress?: boolean; goalSpots?: number | null; spotsFunded?: number | null; sponsors?: number | null };
|
||||
|
||||
@@ -63,8 +64,8 @@ export function SponsorSpot({ eventId, eventTitle }: { eventId: string; eventTit
|
||||
},
|
||||
});
|
||||
window.location.href = res.redirectUrl;
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Couldn't start the payment");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Couldn't start the payment");
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import React, { useRef, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export function FileUploader({ onUploaded }: { onUploaded: (url: string) => void }) {
|
||||
const { token } = useAuth();
|
||||
@@ -23,8 +24,8 @@ export function FileUploader({ onUploaded }: { onUploaded: (url: string) => void
|
||||
authToken: token,
|
||||
});
|
||||
onUploaded(data.url);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Upload failed");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Upload failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
import Webcam from "react-webcam";
|
||||
import { useQRScanner } from "@/hooks/useQRScanner";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export type QRScannerProps = {
|
||||
onResult?: (text: string) => void;
|
||||
@@ -126,8 +127,9 @@ export const QRScanner = React.forwardRef<QRScannerHandle, QRScannerProps>(
|
||||
try { warmup.getTracks().forEach(t => t.stop()); } catch {}
|
||||
setShowCam(true);
|
||||
if (!active) toggle();
|
||||
} catch (e: any) {
|
||||
const name = e?.name || e?.message;
|
||||
} catch (e) {
|
||||
// getUserMedia rejects with a DOMException whose `name` says why (NotAllowedError, ...).
|
||||
const name = (e as { name?: string } | null)?.name || errorMessage(e);
|
||||
if (name === "NotAllowedError") {
|
||||
setLocalError("Camera permission denied. Please enable camera access in your browser settings.");
|
||||
} else if (name === "NotFoundError" || name === "OverconstrainedError") {
|
||||
|
||||
@@ -12,6 +12,7 @@ import ReportViewerModal, { ReportActionButton } from "./ReportViewerModal";
|
||||
import { StatTile, StatTileRow } from "./StatTile";
|
||||
import { HorizontalBarChart } from "./charts/HorizontalBarChart";
|
||||
import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
const METHOD_KEYS = ["cash", "card", "eft", "other"] as const;
|
||||
const METHOD_LABEL: Record<string, string> = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" };
|
||||
@@ -124,8 +125,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
setLoadingEvents(true);
|
||||
const evs = await apiFetch<any[]>("/api/events/all?includePast=true&includeInactive=true", { authToken: token || undefined });
|
||||
setEvents(Array.isArray(evs) ? evs : []);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Failed to load events");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to load events");
|
||||
} finally {
|
||||
setLoadingEvents(false);
|
||||
}
|
||||
@@ -1297,8 +1298,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const payload = buildReportPayload();
|
||||
if (!payload) return;
|
||||
await downloadReportExcel(API_BASE, token, payload);
|
||||
} catch (e: any) {
|
||||
alert(e?.message || 'Failed to generate Excel file');
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || 'Failed to generate Excel file');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1327,8 +1328,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const payload = buildReportPayload();
|
||||
if (!payload) return;
|
||||
await viewReportPdf(API_BASE, token, payload);
|
||||
} catch (e: any) {
|
||||
alert(e?.message || 'Failed to generate PDF');
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || 'Failed to generate PDF');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1339,8 +1340,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
if (!payload) return;
|
||||
await emailReportPdf(API_BASE, token, { ...payload, subject: REPORT_LABEL[report], body: "Report generated on " + new Date().toLocaleString() });
|
||||
alert('Email sent with PDF attachment');
|
||||
} catch (e: any) {
|
||||
alert(e?.message || 'Failed to email PDF');
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || 'Failed to email PDF');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1351,8 +1352,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
if (!payload) return;
|
||||
await whatsappReportPdf(API_BASE, token, { ...payload, caption: REPORT_LABEL[report] });
|
||||
alert('Report sent to your WhatsApp');
|
||||
} catch (e: any) {
|
||||
alert(e?.message || 'Failed to send via WhatsApp');
|
||||
} catch (e) {
|
||||
alert(errorMessage(e) || 'Failed to send via WhatsApp');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import React, { useEffect, useState } from "react";
|
||||
import { Wifi, WifiOff, CloudUpload, Lock } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import type { OtherLock } from "./useOfflineScanning";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Offline = ReturnType<typeof import("./useOfflineScanning").useOfflineScanning>;
|
||||
|
||||
@@ -38,8 +39,8 @@ export function OfflineScanPanel({ offline, token, eventId, eventTitle, sectionI
|
||||
try {
|
||||
const n = await offline.enable(eventId, eventTitle, sectionId, sectionName);
|
||||
onInfo(`Offline mode on — ${n} ticket(s) downloaded. You can keep scanning without a connection.`);
|
||||
} catch (e: any) {
|
||||
onError(e?.message || "Couldn't turn on offline mode");
|
||||
} catch (e) {
|
||||
onError(errorMessage(e) || "Couldn't turn on offline mode");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -49,8 +50,8 @@ export function OfflineScanPanel({ offline, token, eventId, eventTitle, sectionI
|
||||
try {
|
||||
await offline.release();
|
||||
onInfo("Offline mode ended and the section is unlocked.");
|
||||
} catch (e: any) {
|
||||
onError(e?.message || "Couldn't end offline mode");
|
||||
} catch (e) {
|
||||
onError(errorMessage(e) || "Couldn't end offline mode");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -59,8 +60,8 @@ export function OfflineScanPanel({ offline, token, eventId, eventTitle, sectionI
|
||||
try {
|
||||
const r = await offline.sync();
|
||||
if (r) onInfo(`Synced ${r.accepted} scan(s)${r.conflicts ? ` — ${r.conflicts} need a supervisor to review` : ""}.`);
|
||||
} catch (e: any) {
|
||||
onError(e?.message || "Sync failed — scans are kept on this device and will retry.");
|
||||
} catch (e) {
|
||||
onError(errorMessage(e) || "Sync failed — scans are kept on this device and will retry.");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import React, { useMemo, useState } from "react";
|
||||
import { Users, Send } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { isMinorOn } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
const CONSENT_LABEL: Record<string, { text: string; cls: string }> = {
|
||||
pending: { text: "consent pending", cls: "text-amber-700" },
|
||||
@@ -100,8 +101,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
setEditing(false);
|
||||
onMessage("Attendees saved.");
|
||||
onSaved();
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Couldn't save attendees");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Couldn't save attendees");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -111,8 +112,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
try {
|
||||
const res = await apiFetch<{ message: string }>(`/api/registrations/${encodeURIComponent(registration.id)}/attendees/${encodeURIComponent(a.id)}/send-form-link`, { method: "POST", authToken: token });
|
||||
onMessage(res.message);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Couldn't send the form link");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Couldn't send the form link");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -122,8 +123,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
try {
|
||||
const res = await apiFetch<{ message: string }>(`/api/consent/requests/${encodeURIComponent(requestId)}/resend`, { method: "POST", authToken: token });
|
||||
onMessage(res.message);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Couldn't re-send the consent request");
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Couldn't re-send the consent request");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { ListChecks } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Entry = {
|
||||
id: string;
|
||||
@@ -30,8 +31,8 @@ export function MyWaitlists({ token, onMessage }: { token: string; onMessage: (m
|
||||
const res = await apiFetch<{ message: string }>(`/api/waitlist/${encodeURIComponent(id)}`, { method: "DELETE", authToken: token });
|
||||
onMessage(res.message);
|
||||
load();
|
||||
} catch (e: any) {
|
||||
onMessage(e?.message || "Couldn't leave the waitlist");
|
||||
} catch (e) {
|
||||
onMessage(errorMessage(e) || "Couldn't leave the waitlist");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import React, { useState } from "react";
|
||||
import { ArrowRightLeft } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { isMinorOn } from "@/components/shared/AttendeeNamesEditor";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
/** Whether to offer "Transfer" on a ticket (the server checks the rules again). */
|
||||
export function canOfferTransfer(ticket: any, event: any, isSupervisor = false): boolean {
|
||||
@@ -42,8 +43,8 @@ export function TransferTicketModal({ ticket, event, token, onClose, onDone }: {
|
||||
if (youth) Object.assign(body, { dateOfBirth: f.dateOfBirth, parentName: f.parentName, parentEmail: f.parentEmail, parentPhone: f.parentPhone });
|
||||
const res = await apiFetch<{ message: string }>(`/api/tickets/${ticket.id}/transfer`, { method: "POST", authToken: token, body });
|
||||
onDone(res.message);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Couldn't transfer the ticket");
|
||||
} catch (err) {
|
||||
setError(errorMessage(err) || "Couldn't transfer the ticket");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
@@ -9,14 +9,17 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
export function useDismissingState<T>(initial: T, ms = 7000) {
|
||||
const [value, setValue] = useState<T>(initial);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// Held in a ref so the setter keeps one identity across renders (like useState's),
|
||||
// even when the caller passes a fresh object/array literal as `initial`.
|
||||
const initialRef = useRef(initial);
|
||||
|
||||
const set = useCallback((next: T) => {
|
||||
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
||||
setValue(next);
|
||||
if (next) {
|
||||
timeoutRef.current = setTimeout(() => setValue(initial), ms);
|
||||
timeoutRef.current = setTimeout(() => setValue(initialRef.current), ms);
|
||||
}
|
||||
}, [ms, initial]);
|
||||
}, [ms]);
|
||||
|
||||
useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
|
||||
|
||||
|
||||
@@ -57,10 +57,12 @@ export function useQRScanner(videoEl: HTMLVideoElement | null, opts: UseQRScanne
|
||||
cancelRef.current = () => {
|
||||
cancelled = true;
|
||||
};
|
||||
} catch (err: any) {
|
||||
if (err?.name === "NotAllowedError") {
|
||||
} catch (err) {
|
||||
// getUserMedia rejects with a DOMException whose `name` says why.
|
||||
const name = (err as { name?: string } | null)?.name;
|
||||
if (name === "NotAllowedError") {
|
||||
setPermissionError("Camera permission denied. Please enable camera access.");
|
||||
} else if (err?.name === "NotFoundError") {
|
||||
} else if (name === "NotFoundError") {
|
||||
setPermissionError("No suitable camera found. Try a device with a back camera.");
|
||||
} else {
|
||||
setPermissionError("Unable to access camera.");
|
||||
|
||||
@@ -72,8 +72,12 @@ export function resolveToApiOrigin(urlOrPath: string | null | undefined): string
|
||||
return API_BASE ? `${API_BASE}${raw}` : raw;
|
||||
}
|
||||
|
||||
// The parsed JSON body of a failed request — the backend always sends `message`, and
|
||||
// some routes add a machine-readable `code` or extra detail fields.
|
||||
export type ApiErrorData = { message?: string; code?: string; [key: string]: unknown };
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public readonly status: number, message: string, public readonly data?: any) {
|
||||
constructor(public readonly status: number, message: string, public readonly data?: ApiErrorData) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
}
|
||||
@@ -110,7 +114,7 @@ export async function apiFetch<T = any>(path: string, options: ApiOptions = {}):
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
let message = text || `Request failed with status ${res.status}`;
|
||||
let data: any;
|
||||
let data: ApiErrorData | undefined;
|
||||
// Backend returns { message: "..." } — extract it so callers get a plain string
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
|
||||
@@ -25,3 +25,11 @@ export function truncateText(text: string, maxLength: number): string {
|
||||
if (text.length <= maxLength) return text
|
||||
return `${text.slice(0, maxLength)}...`
|
||||
}
|
||||
|
||||
// Message from a caught value (an Error, an ApiError, or anything thrown), or undefined when
|
||||
// it has none — so callers can write `errorMessage(e) || "Fallback text"`.
|
||||
export function errorMessage(e: unknown): string | undefined {
|
||||
if (e instanceof Error) return e.message || undefined
|
||||
if (typeof e === "object" && e !== null && "message" in e && typeof e.message === "string") return e.message || undefined
|
||||
return undefined
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user