Initial commit

Next.js + Express event management app for Hope Family Church.
This commit is contained in:
2026-07-23 15:26:47 +02:00
commit 3d381944d2
246 changed files with 57565 additions and 0 deletions
@@ -0,0 +1,87 @@
"use client";
import React, { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
export default function DonatePage() {
const { token } = useAuth();
const [events, setEvents] = useState<any[]>([]);
const [eventId, setEventId] = useState<string>("");
const [amount, setAmount] = useState<string>("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [info, setInfo] = useState<string | null>(null);
useEffect(() => {
(async () => {
try {
const evs = await apiFetch<any[]>("/api/events");
setEvents(evs);
if (evs.length > 0) setEventId(evs[0].id);
} catch (e: any) {
setError(e?.message || "Failed to load events");
}
})();
}, []);
const submit = async () => {
if (!token) { setError("Please login"); return; }
const amt = parseFloat(amount);
if (!(amt > 0)) { setError("Enter a valid amount"); return; }
if (amt < 15) { setError("Minimum donation is R15"); return; }
if (!eventId) { setError("Select an event"); return; }
try {
setError(null);
setInfo(null);
setLoading(true);
const res = await apiFetch<{ redirectUrl: string }>("/api/payments/yoco-checkout", {
method: "POST",
body: {
eventId,
amount: amt,
successUrl: window.location.origin + "/payment/success",
cancelUrl: window.location.origin + "/payment/cancel",
failureUrl: window.location.origin + "/payment/failure",
},
authToken: token,
});
setInfo("Redirecting to payment...");
window.location.href = res.redirectUrl;
} catch (e: any) {
setError(e?.message || "Failed to start donation checkout");
} finally {
setLoading(false);
}
};
return (
<div className="max-w-xl mx-auto w-full p-6">
<h1 className="text-2xl font-semibold mb-4">Make a donation</h1>
{error && <p className="text-red-600 text-sm mb-3">{error}</p>}
{info && <p className="text-green-700 text-sm mb-3">{info}</p>}
<label className="block text-sm font-medium mb-1">Event</label>
<select className="w-full border rounded px-3 py-2 mb-3" value={eventId} onChange={(e)=>setEventId(e.target.value)}>
{events.map(ev => <option key={ev.id} value={ev.id}>{ev.title}</option>)}
</select>
<label className="block text-sm font-medium mb-1">Amount (R)</label>
<input
type="number"
min="15"
step="1"
placeholder="Enter amount (min R15)"
value={amount}
onChange={(e)=>setAmount(e.target.value)}
className="w-full border rounded px-3 py-2 mb-1"
/>
<p className="text-xs text-gray-600 mb-3">Minimum donation is R15.</p>
<button
disabled={loading}
onClick={submit}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-60"
>{loading?"Starting checkout...":"Donate"}</button>
</div>
);
}
@@ -0,0 +1,235 @@
"use client";
import React, { Suspense, useEffect, useMemo, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
// Types for form fields
type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'; label: string; isRequired?: boolean; helpText?: string|null };
function FormsContent() {
const search = useSearchParams();
const router = useRouter();
const { token } = useAuth();
const registrationId = search.get("registrationId");
const [registration, setRegistration] = useState<any | null>(null);
const [eventForm, setEventForm] = useState<{ isRequired: boolean; fields: FormField[] } | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [info, setInfo] = useState<string | null>(null);
// Local entry state for new responses
const [formsData, setFormsData] = useState<Record<number, Record<string, string>>>({});
useEffect(() => {
(async () => {
if (!token || !registrationId) return;
setLoading(true);
setError(null);
setInfo(null);
try {
const reg = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
setRegistration(reg);
const ev = await apiFetch<any>(`/api/events/${encodeURIComponent(reg.eventId)}`);
if (ev?.form) setEventForm(ev.form);
// Load any saved draft
try {
const draft = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token });
if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data);
} catch {}
} catch (e: any) {
setError(e?.message || 'Failed to load registration');
} finally {
setLoading(false);
}
})();
}, [token, registrationId]);
const submittedCount = useMemo(() => {
return (registration?.formResponses || []).length;
}, [registration]);
const requiredCount = useMemo(() => {
if (!registration) return 0;
try {
return (registration.registrationOptions || [])
.filter((ro: any) => ro.eventOption?.isMainTicket)
.reduce((s: number, ro: any) => s + (ro.quantity || 0), 0);
} catch {
return 0;
}
}, [registration]);
const remaining = Math.max(0, requiredCount - submittedCount);
// Determine if all required fields are filled for each attendee form to be submitted
const canSubmit = useMemo(() => {
if (!eventForm || remaining <= 0) return false;
const reqFields = (eventForm.fields || [])
.filter(f => !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph')
.map(f => f.id);
for (let i = 0; i < remaining; i++) {
const data = formsData[i] || {};
for (const fid of reqFields) {
const v = data[fid];
if (v === undefined || v === null || String(v).trim() === '') {
return false;
}
}
}
return true;
}, [eventForm, formsData, remaining]);
const submit = async () => {
if (!token || !registrationId) return;
try {
setError(null); setInfo(null);
const payload: any[] = [];
for (let i = 0; i < remaining; i++) {
payload.push({ answers: formsData[i] || {} });
}
if (payload.length === 0) {
setInfo('No remaining attendee forms to submit.');
return;
}
await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, {
method: 'POST',
authToken: token,
body: { responses: payload }
});
setInfo('Attendee forms submitted successfully.');
// reload registration to reflect new responses
const reg = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
setRegistration(reg);
setFormsData({});
// On success, redirect to the user dashbaord
router.push('/dashboard/user');
} catch (e: any) {
setError(e?.message || 'Failed to submit forms');
}
};
const saveDraft = async () => {
if (!token || !registrationId) return;
try {
setError(null); setInfo(null);
await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, {
method: 'PUT',
authToken: token,
body: { data: formsData }
});
setInfo('Draft saved. You can return later to finish.');
} catch (e: any) {
setError(e?.message || 'Failed to save draft');
}
};
if (!registrationId) return <div className="p-6">Missing registrationId.</div>;
return (
<div className="max-w-2xl mx-auto w-full p-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-semibold">Attendee forms</h1>
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200" onClick={() => router.push('/dashboard/user')}>Back</button>
</div>
{loading && <div className="text-sm text-gray-600 mb-2">Loading</div>}
{error && <div className="text-sm text-red-600 mb-2">{error}</div>}
{info && <div className="text-sm text-emerald-700 mb-2">{info}</div>}
{registration && (
<div className="border rounded p-3 mb-4 bg-white">
<div className="font-medium">{registration.event?.title || registration.eventId}</div>
<div className="text-xs text-gray-600">Registration #{registration.id.slice(0,8)}</div>
<div className="text-sm mt-1">Forms submitted: {submittedCount} / {requiredCount}</div>
</div>
)}
{/* Existing responses (read-only list) */}
{registration && (registration.formResponses || []).length > 0 && (
<div className="border rounded p-3 mb-4 bg-gray-50">
<div className="text-sm font-medium mb-2">Submitted responses</div>
<ul className="space-y-2">
{(registration.formResponses || []).map((resp: any, idx: number) => (
<li key={resp.id} className="bg-white border rounded p-2">
<div className="font-medium text-sm mb-1">Attendee {idx + 1}</div>
{(resp.answers || []).length === 0 ? (
<div className="text-xs text-gray-600">No answers recorded.</div>
) : (
<ul className="text-xs list-disc pl-5 space-y-0.5">
{resp.answers.map((a: any) => (
<li key={a.id}>
<span className="text-gray-600">{eventForm?.fields.find(f => f.id === a.fieldId)?.label || (`Field ${a.fieldId}`)}</span>: {a.value}
</li>
))}
</ul>
)}
</li>
))}
</ul>
</div>
)}
{/* Remaining forms to fill */}
{eventForm && remaining > 0 && (
<div className="border rounded p-3 bg-gray-50">
<div className="text-sm font-medium mb-2">Fill remaining attendee details ({remaining})</div>
<div className="space-y-4">
{Array.from({ length: remaining }, (_, idx) => (
<div key={idx} className="bg-white border rounded p-3">
<div className="font-medium mb-2">Attendee {submittedCount + idx + 1}</div>
{eventForm.fields.map((f) => (
<div key={f.id} className="mb-2">
{f.type === 'statement' ? (
<div className="text-sm text-gray-700 whitespace-pre-line">{f.label}</div>
) : f.type === 'paragraph' ? (
<div className="text-sm text-gray-700">
{f.label && <div className="font-medium mb-1 whitespace-pre-line">{f.label}</div>}
{f.helpText && <div className="whitespace-pre-line">{f.helpText}</div>}
</div>
) : (
<>
<label className="block text-xs text-gray-600 mb-1">{f.label}{f.isRequired ? ' *' : ''}</label>
{f.type === 'yes_no' ? (
<select className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))}>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
) : f.type === 'date' ? (
<input type="date" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} />
) : f.type === 'numeric' ? (
<input type="number" className="border rounded px-2 py-1 text-sm" value={formsData[idx]?.[f.id] || ''} onChange={e => setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} />
) : (
<input type="text" className="border rounded px-2 py-1 text-sm w-full" value={formsData[idx]?.[f.id] || ''} onChange={e => setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} />
)}
{f.helpText && <div className="text-xs text-gray-500 mt-1">{f.helpText}</div>}
</>
)}
</div>
))}
</div>
))}
</div>
<div className="mt-3 flex gap-2">
<button className="px-3 py-1.5 text-sm rounded bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50" disabled={!canSubmit} onClick={submit}>Submit</button>
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200" onClick={saveDraft}>Save for later</button>
</div>
</div>
)}
{eventForm && remaining === 0 && (
<div className="text-sm text-emerald-700">All required attendee forms are completed for this registration.</div>
)}
</div>
);
}
export default function FormsPage() {
return (
<Suspense fallback={<div className="p-6">Loading</div>}>
<FormsContent />
</Suspense>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,207 @@
"use client";
import React, { Suspense, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
function MakePaymentContent() {
const searchParams = useSearchParams();
const registrationId = searchParams.get("registrationId");
const { token } = useAuth();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [info, setInfo] = useState<string | null>(null);
const [registration, setRegistration] = useState<any | null>(null);
const [payments, setPayments] = useState<any[]>([]);
const [amount, setAmount] = useState<string>("");
const [priceUpdated, setPriceUpdated] = useState<{ newTotal: number; message: string } | null>(null);
// Compute effective unit price for a registration option.
// Uses priceSnapshot when available (authoritative backend price, variant-aware).
// Falls back to deadline-only early-bird calculation for legacy rows without a snapshot.
const optionUnitPrice = (opt: any, referenceTime: any, atTime: Date): number => {
if (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) {
return Number(opt.priceSnapshot);
}
const eo = opt.eventOption;
const variantId: string | null = opt.variantId || null;
const base = (opt.variant?.price !== null && opt.variant?.price !== undefined)
? Number(opt.variant.price)
: Number(eo?.price || 0);
const allTiers = Array.isArray(eo?.earlyBirdTiers) ? eo.earlyBirdTiers.slice() : [];
const tiers = variantId
? allTiers.filter((t: any) => t.variantId === variantId)
: allTiers.filter((t: any) => !t.variantId);
if (tiers.length === 0) return base;
const t = atTime ? new Date(atTime) : new Date();
const ref = referenceTime ? new Date(referenceTime) : t;
const applicable = tiers
.map((x: any) => ({ ...x, deadline: new Date(x.deadline) }))
.filter((x: any) => (ref < x.deadline) && (t < x.deadline))
.sort((a: any, b: any) => a.deadline.getTime() - b.deadline.getTime() || (a.order||0) - (b.order||0) || a.price - b.price);
if (applicable.length === 0) return base;
const price = Number(applicable[0].price);
return (price >= 0) ? price : base;
};
const totals = useMemo(() => {
if (!registration) return { totalDue: 0, totalPaid: 0, outstanding: 0 };
const now = new Date();
// totalDue uses priceSnapshot — not time-dependent, consistent with what the backend charges
const totalDue = (registration.registrationOptions || []).reduce((s: number, opt: any) => s + optionUnitPrice(opt, null, now) * (opt.quantity || 0), 0);
const totalPaid = payments.reduce((s: number, p: any) => s + (p.amount || 0), 0);
const outstanding = Math.max(0, totalDue - totalPaid);
return { totalDue, totalPaid, outstanding };
}, [registration, payments]);
const minAllowed = useMemo(() => {
if (totals.outstanding <= 0) return 0;
return totals.outstanding >= 15 ? 15 : totals.outstanding;
}, [totals.outstanding]);
useEffect(() => {
(async () => {
if (!token || !registrationId) return;
try {
setError(null);
setLoading(true);
const reg = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
setRegistration(reg);
const pays = await apiFetch<any[]>(`/api/payments/registration/${encodeURIComponent(registrationId)}`, { authToken: token });
setPayments(pays);
} catch (e: any) {
setError(e?.message || "Failed to load registration");
} finally {
setLoading(false);
}
})();
}, [token, registrationId]);
useEffect(() => {
if (totals.outstanding <= 0) {
setAmount("");
}
}, [totals.outstanding]);
const submit = async () => {
if (!token || !registrationId) return;
const amt = parseFloat(amount);
if (!(amt > 0)) { setError("Enter a valid amount"); return; }
if (amt > totals.outstanding) { setError(`Amount cannot exceed outstanding (R ${totals.outstanding.toFixed(2)})`); return; }
if (amt < minAllowed) {
if (totals.outstanding >= 15) {
setError("Minimum payment is R15");
} else {
setError(`Please pay the remaining outstanding amount (R ${totals.outstanding.toFixed(2)})`);
}
return;
}
try {
setError(null);
setInfo(null);
setPriceUpdated(null);
setLoading(true);
const res = await apiFetch<{ redirectUrl?: string; priceUpdated?: boolean; newTotal?: number; message?: string }>("/api/payments/yoco-checkout", {
method: "POST",
body: {
registrationId,
amount: amt,
successUrl: window.location.origin + "/payment/success",
cancelUrl: window.location.origin + "/payment/cancel",
failureUrl: window.location.origin + "/payment/failure",
},
authToken: token,
});
if (res.priceUpdated) {
// Early-bird price changed — show warning and reload registration data
setPriceUpdated({ newTotal: res.newTotal ?? 0, message: res.message ?? 'Prices have changed.' });
// Reload registration so totals reflect updated priceSnapshot
try {
const reg = await apiFetch<any>(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token });
setRegistration(reg);
const pays = await apiFetch<any[]>(`/api/payments/registration/${encodeURIComponent(registrationId)}`, { authToken: token });
setPayments(pays);
} catch {}
setAmount("");
return;
}
setInfo("Redirecting to payment...");
window.location.href = res.redirectUrl!;
} catch (e: any) {
setError(e?.message || "Failed to create checkout");
} finally {
setLoading(false);
}
};
if (!registrationId) return <div className="p-6">Missing registrationId.</div>;
return (
<div className="max-w-xl mx-auto w-full p-6">
<h1 className="text-2xl font-semibold mb-4">Make a payment</h1>
{error && <p className="text-red-600 text-sm mb-3">{error}</p>}
{info && <p className="text-green-700 text-sm mb-3">{info}</p>}
{priceUpdated && (
<div className="mb-4 p-3 border border-amber-300 bg-amber-50 rounded text-sm text-amber-800">
<strong>Pricing has changed.</strong> {priceUpdated.message}
<div className="mt-1">New outstanding: <strong>R {priceUpdated.newTotal.toFixed(2)}</strong></div>
<button
className="mt-2 text-xs underline text-amber-700 hover:text-amber-900"
onClick={() => setPriceUpdated(null)}
>OK, I understand continue with new price</button>
</div>
)}
{registration ? (
<div className="border rounded p-3 mb-4">
<div className="font-medium">{registration.event?.title || registration.eventId}</div>
<div className="text-sm text-gray-600">Registration #{registration.id.slice(0,8)}</div>
<div className="mt-2 text-sm">
<div>Total: R {totals.totalDue.toFixed(2)}</div>
<div>Paid: R {totals.totalPaid.toFixed(2)}</div>
<div>Outstanding: <span className={totals.outstanding>0?"text-red-600":"text-green-700"}>R {totals.outstanding.toFixed(2)}</span></div>
</div>
{(() => {
const tiers = (registration.registrationOptions || []).flatMap((ro: any) => Array.isArray(ro.eventOption?.earlyBirdTiers) ? ro.eventOption.earlyBirdTiers : []);
const upcoming = tiers.map((t: any) => ({ ...t, deadline: new Date(t.deadline) })).filter((t: any) => new Date() < t.deadline).sort((a: any, b: any) => a.deadline.getTime() - b.deadline.getTime());
if (upcoming.length === 0) return null;
const d = upcoming[0].deadline as Date;
const dateStr = d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: '2-digit' });
return <div className="mt-2 text-xs text-amber-700">Early bird pricing applies if paid before {dateStr}.</div>;
})()}
</div>
) : (
<p className="text-sm text-gray-600 mb-4">Loading registration...</p>
)}
<label className="block text-sm font-medium mb-1">Amount (R)</label>
<input
type="number"
min={minAllowed.toFixed(2)}
max={totals.outstanding > 0 ? totals.outstanding.toFixed(2) : "0"}
step="1"
placeholder={totals.outstanding >= 15 ? "Enter amount (min R15)" : `Enter amount (max R ${totals.outstanding.toFixed(2)})`}
value={amount}
onChange={(e) => setAmount(e.target.value)}
disabled={totals.outstanding <= 0}
className="w-full border rounded px-3 py-2 mb-1 disabled:opacity-60"
/>
{totals.outstanding > 0 && (
<p className="text-xs text-gray-600 mb-3">Minimum payment {totals.outstanding >= 15 ? "is R15" : `is the remaining outstanding amount (R ${totals.outstanding.toFixed(2)})`}.</p>
)}
<button
disabled={loading || totals.outstanding <= 0}
onClick={submit}
className="bg-green-600 text-white px-4 py-2 rounded disabled:opacity-60"
>{loading?"Creating checkout...": totals.outstanding <= 0 ? "No outstanding amount" : "Pay now"}</button>
</div>
);
}
export default function MakePaymentPage() {
return (
<Suspense fallback={<div className="p-6">Loading...</div>}>
<MakePaymentContent />
</Suspense>
);
}
@@ -0,0 +1,365 @@
"use client";
import React, { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { isValidZAPhone } from "@/lib/phone";
export default function UserProfilePage() {
const { user, token, logout, updateToken } = useAuth();
const router = useRouter();
useEffect(() => {
if (!user && !token) router.replace("/login");
}, [user, token, router]);
// ── Profile form ─────────────────────────────────────────────────────────
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [notifPref, setNotifPref] = useState<"email" | "whatsapp" | "both">("email");
const [profileMsg, setProfileMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [savingProfile, setSavingProfile] = useState(false);
const hasValidPhone = isValidZAPhone(phone);
useEffect(() => {
if (user) {
setName(user.name || "");
setEmail(user.email || "");
setPhone(user.phoneNumber || "");
setNotifPref(user.notificationPreference || "email");
}
}, [user]);
const saveProfile = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setSavingProfile(true);
setProfileMsg(null);
try {
const res = await apiFetch<any>("/api/users/profile", {
method: "PUT",
authToken: token,
body: {
name,
email,
phoneNumber: phone || null,
notificationPreference: hasValidPhone ? notifPref : "email",
},
});
// Backend returns a refreshed token — save it so the session stays valid
if (res?.token) updateToken(res.token);
setProfileMsg({ type: "ok", text: "Profile updated." });
} catch (e: any) {
setProfileMsg({ type: "err", text: e?.message || "Failed to update profile." });
} finally {
setSavingProfile(false);
}
};
// ── Password change ───────────────────────────────────────────────────────
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [pwMsg, setPwMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [savingPw, setSavingPw] = useState(false);
const changePassword = async (e: React.FormEvent) => {
e.preventDefault();
if (newPassword !== confirmPassword) {
setPwMsg({ type: "err", text: "Passwords do not match." });
return;
}
if (newPassword.length < 8) {
setPwMsg({ type: "err", text: "Password must be at least 8 characters." });
return;
}
if (!token) return;
setSavingPw(true);
setPwMsg(null);
try {
const res = await apiFetch<any>("/api/users/profile", {
method: "PUT",
authToken: token,
body: { currentPassword, password: newPassword },
});
if (res?.token) updateToken(res.token);
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setPwMsg({ type: "ok", text: "Password changed." });
} catch (e: any) {
setPwMsg({ type: "err", text: e?.message || "Failed to change password." });
} finally {
setSavingPw(false);
}
};
// ── Revoke sessions ───────────────────────────────────────────────────────
const [revokeMsg, setRevokeMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [revoking, setRevoking] = useState(false);
const revokeSessions = async () => {
if (!confirm("This will sign you out of all other devices. You will need to log in again everywhere except here. Continue?")) return;
if (!token) return;
setRevoking(true);
setRevokeMsg(null);
try {
const res = await apiFetch<any>("/api/users/revoke-sessions", {
method: "POST",
authToken: token,
});
// Revoking sessions invalidates the token this device was using too —
// save the freshly issued one so this device stays signed in.
if (res?.token) updateToken(res.token);
setRevokeMsg({ type: "ok", text: res?.message || "All other sessions signed out." });
} catch (e: any) {
setRevokeMsg({ type: "err", text: e?.message || "Failed to revoke sessions." });
} finally {
setRevoking(false);
}
};
// ── Account closure ───────────────────────────────────────────────────────
const [closeStep, setCloseStep] = useState<"idle" | "confirm">("idle");
const [deleteData, setDeleteData] = useState(false);
const [closePassword, setClosePassword] = useState("");
const [closeMsg, setCloseMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [closing, setClosing] = useState(false);
const submitAccountClosure = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setClosing(true);
setCloseMsg(null);
try {
const res = await apiFetch<any>("/api/users/close-account", {
method: "POST",
authToken: token,
body: { password: closePassword, deleteData },
});
setCloseMsg({ type: "ok", text: res?.message || "Account closed." });
// Slight delay so the user can read the message, then log out
setTimeout(() => logout(), 2500);
} catch (e: any) {
setCloseMsg({ type: "err", text: e?.message || "Failed to close account." });
} finally {
setClosing(false);
}
};
// ── Shared helpers ────────────────────────────────────────────────────────
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
<div className={`mt-3 p-3 rounded text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
return (
<div className="max-w-2xl mx-auto w-full p-6 space-y-8">
<h1 className="text-2xl font-semibold">Profile &amp; Security</h1>
{/* ── Profile info ─────────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-lg font-semibold mb-4">Personal information</h2>
<form onSubmit={saveProfile} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Full name</label>
<input
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={name}
onChange={e => setName(e.target.value)}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Email address</label>
<input
type="email"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={email}
onChange={e => setEmail(e.target.value)}
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Phone number</label>
<input
type="tel"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={phone}
onChange={e => setPhone(e.target.value)}
placeholder="e.g. 082 123 4567"
/>
</div>
{hasValidPhone && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Notification preference</label>
<select
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={notifPref}
onChange={e => setNotifPref(e.target.value as "email" | "whatsapp" | "both")}
>
<option value="email">Email only</option>
<option value="whatsapp">WhatsApp only</option>
<option value="both">Email &amp; WhatsApp</option>
</select>
<p className="mt-1 text-xs text-gray-500">Security alerts (password reset, login notifications) are always sent via email regardless of this setting.</p>
</div>
)}
<button
type="submit"
disabled={savingProfile}
className="px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 disabled:opacity-50"
>
{savingProfile ? "Saving…" : "Save changes"}
</button>
{profileMsg && <Alert msg={profileMsg} />}
</form>
</section>
{/* ── Password ─────────────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-lg font-semibold mb-4">Change password</h2>
<form onSubmit={changePassword} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Current password</label>
<input
type="password"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
required
autoComplete="current-password"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">New password</label>
<input
type="password"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
required
minLength={8}
autoComplete="new-password"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Confirm new password</label>
<input
type="password"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
required
autoComplete="new-password"
/>
</div>
<button
type="submit"
disabled={savingPw}
className="px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 disabled:opacity-50"
>
{savingPw ? "Changing…" : "Change password"}
</button>
{pwMsg && <Alert msg={pwMsg} />}
</form>
</section>
{/* ── Security ─────────────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-lg font-semibold mb-1">Security</h2>
<p className="text-sm text-gray-500 mb-4">
If you suspect someone else has access to your account, you can sign out of all other devices immediately.
You will remain logged in on this device.
</p>
<button
onClick={revokeSessions}
disabled={revoking}
className="px-4 py-2 rounded-lg bg-amber-500 text-white text-sm font-medium hover:bg-amber-600 disabled:opacity-50"
>
{revoking ? "Signing out…" : "Sign out all other devices"}
</button>
{revokeMsg && <Alert msg={revokeMsg} />}
</section>
{/* ── Danger zone ──────────────────────────────────────────────────── */}
<section className="border border-red-200 rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-lg font-semibold text-red-700 mb-1">Close account</h2>
<p className="text-sm text-gray-500 mb-4">
Closing your account will deactivate it immediately. You can also request that your personal
information (name, email, phone number) be permanently deleted. Tickets and payment records
will remain for accounting purposes but will show as &quot;Deleted User&quot;.
</p>
{closeStep === "idle" && (
<button
onClick={() => setCloseStep("confirm")}
className="px-4 py-2 rounded-lg border border-red-600 text-red-600 text-sm font-medium hover:bg-red-50"
>
Close my account
</button>
)}
{closeStep === "confirm" && (
<form onSubmit={submitAccountClosure} className="space-y-4">
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-800">
<strong>This action cannot be undone.</strong> Please read carefully before continuing.
</div>
<label className="flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
className="mt-0.5"
checked={deleteData}
onChange={e => setDeleteData(e.target.checked)}
/>
<span className="text-sm text-gray-700">
<span className="font-medium">Also delete my personal data</span> your name, email address,
and phone number will be permanently removed and cannot be recovered.
</span>
</label>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Confirm with your password
</label>
<input
type="password"
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-red-500"
value={closePassword}
onChange={e => setClosePassword(e.target.value)}
required
placeholder="Enter your password to confirm"
autoComplete="current-password"
/>
</div>
<div className="flex gap-3">
<button
type="button"
onClick={() => { setCloseStep("idle"); setClosePassword(""); setDeleteData(false); setCloseMsg(null); }}
className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200"
>
Cancel
</button>
<button
type="submit"
disabled={closing || !closePassword}
className="px-4 py-2 rounded-lg bg-red-600 text-white text-sm font-medium hover:bg-red-700 disabled:opacity-50"
>
{closing ? "Processing…" : deleteData ? "Delete my data & close account" : "Close my account"}
</button>
</div>
{closeMsg && <Alert msg={closeMsg} />}
</form>
)}
</section>
</div>
);
}
@@ -0,0 +1,110 @@
"use client";
import React, { useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { useRouter } from "next/navigation";
export default function ResetPasswordPage() {
const { token } = useAuth();
const router = useRouter();
const [current, setCurrent] = useState("");
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
const [status, setStatus] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const canSubmit = useMemo(() => current.length > 0 && password.length >= 8 && password === confirm, [current, password, confirm]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setStatus(null);
setError(null);
if (!token) {
setError("You must be logged in to change your password.");
return;
}
if (!canSubmit) return;
try {
setLoading(true);
await apiFetch("/api/users/profile", { method: "PUT", authToken: token, body: { password, currentPassword: current } });
setStatus("Your password has been updated successfully.");
setCurrent("");
setPassword("");
setConfirm("");
setTimeout(() => router.push("/dashboard/user"), 1200);
} catch (err: any) {
setError(err?.message || "Failed to update password");
} finally {
setLoading(false);
}
};
return (
<div className="max-w-2xl mx-auto w-full p-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-semibold">Reset password</h1>
<button
className="px-2.5 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200 text-gray-800 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1"
onClick={() => router.push("/dashboard/user")}
>Back to dashboard</button>
</div>
{error && <p className="text-red-600 text-sm mb-3">{error}</p>}
{status && <p className="text-green-700 text-sm mb-3">{status}</p>}
<div className="border rounded-xl p-5 bg-white shadow-sm">
<form onSubmit={submit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Current password</label>
<input
type="password"
value={current}
onChange={e => setCurrent(e.target.value)}
required
className="w-full border rounded px-3 py-2"
placeholder="Enter your current password"
/>
<p className="text-xs text-gray-500 mt-1">For your security, please confirm your current password.</p>
</div>
<div>
<label className="block text-sm font-medium mb-1">New password</label>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
required
className="w-full border rounded px-3 py-2"
placeholder="At least 8 characters"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Confirm new password</label>
<input
type="password"
value={confirm}
onChange={e => setConfirm(e.target.value)}
required
className="w-full border rounded px-3 py-2"
/>
{password && confirm && password !== confirm && (
<p className="text-xs text-red-600 mt-1">Passwords do not match.</p>
)}
</div>
<div className="flex items-center gap-2">
<button
type="submit"
disabled={!canSubmit || loading}
className="px-4 py-2 rounded bg-blue-600 text-white disabled:opacity-60"
>{loading ? "Saving…" : "Update password"}</button>
<button
type="button"
className="px-3 py-2 rounded bg-gray-100 hover:bg-gray-200 text-gray-800"
onClick={() => router.push("/dashboard/user")}
>Cancel</button>
</div>
</form>
</div>
</div>
);
}