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