diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a7b25f..64fe61a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.3.2] - 2026-08-03 + +### Added + +- Self-service kiosk: all password fields (supervisor sign-in, change event, and the visitor "Choose a password" field) now have a show/hide toggle button, so staff can verify what they've typed on the touchscreen instead of typing blind. + +### Fixed + +- Self-service kiosk: removed the separate "Look up existing account" search field — for privacy, staff no longer type a visitor's email/phone into a dedicated search box. Instead, entering an email or phone number in the registration form itself (Email and Cell Number are now the first two fields, followed by Name) automatically checks for a matching account once that field is left. +- Self-service kiosk: matched accounts are no longer updated silently. If the operator's typed Name, Email, Cell Number, or "Send tickets via" preference differs from what's on file, a confirmation dialog now lists exactly what will change (old value → new value) and requires the operator to confirm before the account is updated. +- Self-service kiosk / manual registration: an existing account's name is now actually updated when confirmed changed (previously silently discarded), and email/phone corrections are applied even when the account already had a real value on file (previously only blank phone numbers or guest-placeholder emails could be replaced). +- Self-service kiosk: fixed a bug where changing the phone number to one belonging to a different account would silently replace the Name/Email fields with that other account's details, and re-editing the email back to the original value afterward would not re-check it — together this could result in a registration being (or looking like it would be) saved under the wrong account. Email and phone matches are now tracked independently; if they resolve to two different existing accounts, the kiosk shows a clear warning naming both accounts and blocks registration until the operator corrects one of the fields, instead of silently merging or overwriting details. +- Manual registration API: added a server-side check, independent of the kiosk UI, that rejects (`409`) a registration whose submitted email and phone number belong to two different existing accounts — a defense-in-depth safeguard against one account's contact details being overwritten with, or hijacked by, another's. +- Manual registration API: an existing account's notification preference is now validated against its final email/phone after any confirmed update (e.g. falls back off "WhatsApp"/"Both" if no valid phone remains, or onto "WhatsApp" if the email was cleared in favor of a real phone), instead of persisting a preference that no longer matches the account's actual contact info. +- Self-service kiosk: tapping anywhere else on the page (e.g. a ticket quantity +/− button) while Email or Cell Number was focused blurred that field and silently re-ran its account lookup; even though the match hadn't changed, this reset Name/Email/Phone/preference back to the matched account's original values, discarding any edits the operator had just made. The autofill now only applies once per distinct matched account instead of on every re-check. + ## [1.3.1] - 2026-07-28 ### Fixed diff --git a/backend/package.json b/backend/package.json index 2fbdaaf..bd50500 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "event-management-backend", - "version": "1.3.1", + "version": "1.3.2", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { diff --git a/backend/src/controllers/registrationController.js b/backend/src/controllers/registrationController.js index a8fc6a9..f1d9741 100644 --- a/backend/src/controllers/registrationController.js +++ b/backend/src/controllers/registrationController.js @@ -764,32 +764,66 @@ const createManualRegistration = async (req, res) => { ? prefFromBody : (hasValidEmail && phone ? 'both' : phone ? 'whatsapp' : 'email'); - // Always search by email AND/OR phone regardless of guestOnly - // Also try the alternate format (27xxx ↔ 0xxx) so both representations match + // Always search by email AND/OR phone regardless of guestOnly. + // Resolve each channel independently (rather than a single findFirst with an OR + // across both) so that an email belonging to one account and a phone number + // belonging to a *different* account can never be silently collapsed into + // whichever record happens to match first — that would let a registration + // hijack or corrupt someone else's account. Also try the alternate phone + // format (27xxx ↔ 0xxx) so both representations match. const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null); - const searchClauses = [ - ...(hasValidEmail ? [{ email: user.email }] : []), - ...(phone ? [{ phoneNumber: phone }] : []), - ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : []), - ]; - const existingUser = searchClauses.length > 0 - ? await prisma.user.findFirst({ where: { OR: searchClauses } }) + const emailUser = hasValidEmail + ? await prisma.user.findUnique({ where: { email: user.email } }) : null; + const phoneUser = phone + ? await prisma.user.findFirst({ where: { OR: [{ phoneNumber: phone }, ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : [])] } }) + : null; + + if (emailUser && phoneUser && emailUser.id !== phoneUser.id) { + res.status(409); + throw new Error( + `This email and phone number belong to two different existing accounts (${emailUser.name} vs ${phoneUser.name}). Please verify the visitor's details before registering.` + ); + } + + const existingUser = emailUser || phoneUser || null; if (existingUser) { userId = existingUser.id; const updateData = {}; - // Update preference only when the caller explicitly specified one - if (prefFromBody && validPrefs.includes(prefFromBody)) { - updateData.notificationPreference = prefFromBody; + // The kiosk shows the operator a diff of name/email/phone against the matched + // account and requires explicit confirmation before submitting, so any + // difference reaching this point is an already-confirmed correction — apply + // it as a full overwrite rather than only filling in blanks. + if (user.name && user.name.trim() && user.name.trim() !== existingUser.name) { + updateData.name = user.name.trim(); } - // Fill in a missing contact channel with the newly supplied value, without overwriting an existing one - if (phone && !existingUser.phoneNumber) { + if (phone && phone !== existingUser.phoneNumber) { updateData.phoneNumber = phone; } - if (hasValidEmail && existingUser.email !== user.email && existingUser.email.endsWith('@guest.local')) { + if (hasValidEmail && existingUser.email !== user.email) { updateData.email = user.email; } + + // Update preference only when the caller explicitly specified one, but validate it + // against the contact info that will actually be on the account after this update — + // a stale "whatsapp"/"both" preference must not survive a phone number being + // removed, nor "email" survive an email being cleared in favor of a real phone. + if (prefFromBody && validPrefs.includes(prefFromBody)) { + const { isValidZAPhone } = require('../utils/whatsapp'); + const finalPhone = updateData.phoneNumber !== undefined ? updateData.phoneNumber : existingUser.phoneNumber; + const finalEmail = updateData.email !== undefined ? updateData.email : existingUser.email; + const finalEmailValid = !!(finalEmail && !finalEmail.endsWith('@guest.local')); + let candidatePref = prefFromBody; + if ((candidatePref === 'whatsapp' || candidatePref === 'both') && !isValidZAPhone(finalPhone)) { + candidatePref = finalEmailValid ? 'email' : candidatePref; + } + if (candidatePref === 'email' && !finalEmailValid && isValidZAPhone(finalPhone)) { + candidatePref = 'whatsapp'; + } + updateData.notificationPreference = candidatePref; + } + if (Object.keys(updateData).length > 0) { await prisma.user.update({ where: { id: userId }, data: updateData }).catch(() => {}); } diff --git a/backend/src/controllers/userController.js b/backend/src/controllers/userController.js index 9e96e7d..e046eb0 100644 --- a/backend/src/controllers/userController.js +++ b/backend/src/controllers/userController.js @@ -482,7 +482,7 @@ const checkUserExists = async (req, res) => { const existingUser = await prisma.user.findFirst({ where: { OR: searchClauses }, - select: { name: true, email: true, phoneNumber: true, notificationPreference: true }, + select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true }, }); const hasEmail = !!existingUser?.email && !existingUser.email.endsWith('@guest.local'); @@ -494,7 +494,11 @@ const checkUserExists = async (req, res) => { hasPhone, // Safe-to-display fields only, for autofilling a lookup form — never the password. // Guest placeholder emails are withheld the same way hasEmail already treats them. + // `id` lets the kiosk tell two different matched accounts apart (e.g. when the + // typed email and phone number resolve to different people) — it's never shown, + // only compared client-side, and this endpoint is already Private/Supervisor. user: existingUser ? { + id: existingUser.id, name: existingUser.name, email: hasEmail ? existingUser.email : null, phoneNumber: hasPhone ? existingUser.phoneNumber : null, diff --git a/frontend/package.json b/frontend/package.json index 07024ea..d6aecb1 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "hope-events-frontend", - "version": "1.3.1", + "version": "1.3.2", "private": true, "scripts": { "dev": "next dev --turbopack", diff --git a/frontend/src/app/self-service/page.tsx b/frontend/src/app/self-service/page.tsx index db16625..b4575a0 100644 --- a/frontend/src/app/self-service/page.tsx +++ b/frontend/src/app/self-service/page.tsx @@ -85,6 +85,10 @@ function fmtCurrency(val: number) { return val === 0 ? "Free" : `R${val.toFixed(2)}`; } +function prefLabel(pref: "email" | "whatsapp" | "both") { + return pref === "whatsapp" ? "WhatsApp" : pref === "both" ? "Email & WhatsApp" : "Email"; +} + // Loose "does this look like a mobile number" check — covers 0821234567 (10, leading 0), // 821234567 (9, no leading 0), and 27821234567 / +27821234567 (11 digits, country code). function looksLikePhone(s: string): boolean { @@ -92,6 +96,32 @@ function looksLikePhone(s: string): boolean { return digits.length >= 9 && digits.length <= 11; } +// Show/hide toggle rendered inside a password input — absolutely positioned on its +// right edge, so callers must wrap the input in a `relative` container and add +// enough right padding (`pr-12`) for it not to overlap the typed text. +function PasswordToggleButton({ shown, onToggle }: { shown: boolean; onToggle: () => void }) { + return ( + + ); +} + // ─── Kiosk Page ─────────────────────────────────────────────────────────────── export default function SelfServicePage() { const [screen, setScreen] = useState("setup"); @@ -99,6 +129,7 @@ export default function SelfServicePage() { // ── Setup state ───────────────────────────────────────────────── const [setupEmail, setSetupEmail] = useState(""); const [setupPassword, setSetupPassword] = useState(""); + const [showSetupPassword, setShowSetupPassword] = useState(false); const [setupLoading, setSetupLoading] = useState(false); const [setupError, setSetupError] = useState(null); const [supervisorToken, setSupervisorToken] = useState(null); @@ -109,6 +140,7 @@ export default function SelfServicePage() { // ── Change-event modal ─────────────────────────────────────────── const [showChangeModal, setShowChangeModal] = useState(false); const [changePassword, setChangePassword] = useState(""); + const [showChangePassword, setShowChangePassword] = useState(false); const [changeError, setChangeError] = useState(null); const [changeLoading, setChangeLoading] = useState(false); @@ -119,13 +151,23 @@ export default function SelfServicePage() { const [notificationPref, setNotificationPref] = useState<"email" | "whatsapp" | "both">("email"); const [createAccount, setCreateAccount] = useState(false); const [visitorPassword, setVisitorPassword] = useState(""); - const [accountExists, setAccountExists] = useState(false); + const [showVisitorPassword, setShowVisitorPassword] = useState(false); const [quantities, setQuantities] = useState>({}); - // ── Account lookup (search-by-email/phone) state ────────────────── - const [lookupQuery, setLookupQuery] = useState(""); + // ── Account lookup (automatic, triggered when email/phone is entered) ── + // Email and phone are resolved to an existing account independently. If they + // resolve to the SAME account, that account is "matched". If they resolve to + // two DIFFERENT accounts, that's a conflict — surfaced to the operator instead + // of silently overwriting one field's details with the other's account. + type MatchedAccount = { id: string; name: string; email: string | null; phoneNumber: string | null; notificationPreference: "email" | "whatsapp" | "both" }; + const [emailMatch, setEmailMatch] = useState(null); + const [phoneMatch, setPhoneMatch] = useState(null); + const accountConflict = !!(emailMatch && phoneMatch && emailMatch.id !== phoneMatch.id); + const matchedAccount = accountConflict ? null : (emailMatch || phoneMatch); + const accountExists = !!matchedAccount; const [lookupLoading, setLookupLoading] = useState(false); const [lookupMessage, setLookupMessage] = useState(null); + const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); const [formLoading, setFormLoading] = useState(false); const [formError, setFormError] = useState(null); @@ -186,6 +228,33 @@ export default function SelfServicePage() { }, 0); }, [selectedEvent, quantities]); + // Differences between what's on file for the matched account and what's currently + // typed in the form — shown to the operator for confirmation before anything is saved. + const pendingChanges = useMemo(() => { + if (!matchedAccount) return []; + const changes: { field: string; from: string; to: string }[] = []; + const name = visitorName.trim(); + const email = visitorEmail.trim(); + const phone = visitorPhone.trim(); + if (name && name !== matchedAccount.name) { + changes.push({ field: "Name", from: matchedAccount.name, to: name }); + } + if (email && email !== (matchedAccount.email || "")) { + changes.push({ field: "Email", from: matchedAccount.email || "(none on file)", to: email }); + } + if (phone && phone !== (matchedAccount.phoneNumber || "")) { + changes.push({ field: "Phone", from: matchedAccount.phoneNumber || "(none on file)", to: phone }); + } + if (notificationPref !== matchedAccount.notificationPreference) { + changes.push({ + field: "Send tickets via", + from: prefLabel(matchedAccount.notificationPreference), + to: prefLabel(notificationPref), + }); + } + return changes; + }, [matchedAccount, visitorName, visitorEmail, visitorPhone, notificationPref]); + // ─── Load events after supervisor login ───────────────────────── const loadEvents = useCallback(async (token: string) => { setEventsLoading(true); @@ -273,7 +342,9 @@ export default function SelfServicePage() { } // ─── Visitor registration ──────────────────────────────────────── - async function handleRegister(e: React.FormEvent) { + // Validates the form and, if the typed name/email/phone differ from the matched + // account's details, shows a confirmation modal before anything is saved. + function handleRegisterSubmit(e: React.FormEvent) { e.preventDefault(); setFormError(null); if (!visitorName.trim() || (!visitorEmail.trim() && !visitorPhone.trim())) { @@ -288,7 +359,18 @@ export default function SelfServicePage() { setFormError("No event selected."); return; } + if (accountConflict) { + setFormError("The email and phone number entered belong to two different existing accounts. Please check and correct one of them before continuing."); + return; + } + if (pendingChanges.length > 0) { + setShowUpdateConfirm(true); + return; + } + handleRegister(); + } + async function handleRegister() { setFormLoading(true); try { const payload: any = { @@ -426,8 +508,11 @@ export default function SelfServicePage() { setNotificationPref("email"); setCreateAccount(false); setVisitorPassword(""); - setAccountExists(false); - setLookupQuery(""); + setShowVisitorPassword(false); + setEmailMatch(null); + setPhoneMatch(null); + appliedMatchIdRef.current = null; + setShowUpdateConfirm(false); setLookupMessage(null); setFormError(null); setCurrentRegistrationId(null); @@ -444,52 +529,35 @@ export default function SelfServicePage() { }; }, []); - // ─── Explicit account lookup — only runs when the operator submits the search - // (Enter or the Search button), never on keystroke. Matches exactly against a - // single email or phone value and only ever returns that one matched account - // (or nothing) — never a broader/fuzzy match. ── - async function handleLookup() { - const q = lookupQuery.trim(); - if (!q || !supervisorToken) return; + // ─── Automatic account lookup — runs once the operator finishes entering the + // email or phone field (on blur), never on keystroke. Matches exactly against + // that one value and only ever returns that one matched account (or nothing) — + // never a broader/fuzzy match. Email and phone are tracked as two independent + // matches (emailMatch/phoneMatch, above) rather than being merged into a single + // "last found account" — that's what previously let changing the phone number + // silently pull in and overwrite the form with an unrelated account's details. ── + async function performLookup(kind: "email" | "phone", rawValue: string) { + const value = rawValue.trim(); + const setMatch = kind === "email" ? setEmailMatch : setPhoneMatch; + if (!value || !supervisorToken) { setMatch(null); return; } + if (kind === "email" ? !value.includes("@") : !looksLikePhone(value)) { setMatch(null); return; } + setLookupLoading(true); setLookupMessage(null); try { - // Classify the query as email- or phone-shaped and send it as only that param — - // sending the same raw string as both could let digits embedded in an email - // (e.g. a numeric local-part) get misread as an unrelated phone number. - const isEmailLike = q.includes("@"); const params = new URLSearchParams(); - if (isEmailLike) params.set("email", q); - else params.set("phone", q); + if (kind === "email") params.set("email", value); + else params.set("phone", value); const data = await apiFetch<{ exists: boolean; - user?: { name: string; email: string | null; phoneNumber: string | null; notificationPreference: "email" | "whatsapp" | "both" } | null; + user?: MatchedAccount | null; }>(`/api/users/check-exists?${params.toString()}`, { authToken: supervisorToken }); if (data?.exists && data.user) { - const found = data.user; - setVisitorName(found.name); - setVisitorEmail(found.email || ""); - setVisitorPhone(found.phoneNumber || ""); - setNotificationPref(found.notificationPreference); - setAccountExists(true); + setMatch(data.user); setLookupMessage("Account found — details filled in below."); } else { - // No match — still save the retype: carry the query into whichever field it - // resembles, and leave everything else blank for a fresh entry. - setAccountExists(false); - setVisitorName(""); - setNotificationPref("email"); - if (isEmailLike) { - setVisitorEmail(q); - setVisitorPhone(""); - } else if (looksLikePhone(q)) { - setVisitorPhone(q); - setVisitorEmail(""); - } else { - setVisitorEmail(""); - setVisitorPhone(""); - } - setLookupMessage("No matching account found."); + setMatch(null); + setLookupMessage(null); } } catch { setLookupMessage("Lookup failed. Please try again."); @@ -498,13 +566,31 @@ export default function SelfServicePage() { } } - function handleLookupKeyDown(e: React.KeyboardEvent) { - if (e.key === "Enter") { - e.preventDefault(); - handleLookup(); - } + function handleEmailBlur() { + performLookup("email", visitorEmail); } + function handlePhoneBlur() { + performLookup("phone", visitorPhone); + } + + // Autofill Name/Email/Phone/preference from the matched account — but only once per + // distinct account id. Re-focusing elsewhere on the page (e.g. tapping a ticket + // quantity button) blurs whatever field was last active and re-runs its lookup; + // that returns the same account as a new object each time, and keying this off + // object identity instead of id made it re-fire and stomp every field — including + // ones the operator had already deliberately edited — back to the account's + // original values on every unrelated tap. + const appliedMatchIdRef = useRef(null); + useEffect(() => { + if (!matchedAccount || appliedMatchIdRef.current === matchedAccount.id) return; + appliedMatchIdRef.current = matchedAccount.id; + setVisitorName(matchedAccount.name); + if (matchedAccount.email) setVisitorEmail(matchedAccount.email); + if (matchedAccount.phoneNumber) setVisitorPhone(matchedAccount.phoneNumber); + setNotificationPref(matchedAccount.notificationPreference); + }, [matchedAccount]); + // Existing accounts are linked automatically — never show the "create account" toggle for them useEffect(() => { if (accountExists && createAccount) { @@ -540,15 +626,18 @@ export default function SelfServicePage() {
- setChangePassword(e.target.value)} - className="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" - placeholder="Your password" - autoFocus - required - /> +
+ setChangePassword(e.target.value)} + className="w-full border border-gray-300 rounded-lg px-4 py-3 pr-12 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" + placeholder="Your password" + autoFocus + required + /> + setShowChangePassword((v) => !v)} /> +
{changeError &&

{changeError}

}
@@ -597,15 +686,18 @@ export default function SelfServicePage() {
- setSetupPassword(e.target.value)} - className="w-full border border-gray-300 rounded-xl px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" - placeholder="••••••••" - required - autoComplete="current-password" - /> +
+ setSetupPassword(e.target.value)} + className="w-full border border-gray-300 rounded-xl px-4 py-3 pr-12 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" + placeholder="••••••••" + required + autoComplete="current-password" + /> + setShowSetupPassword((v) => !v)} /> +
{setupError &&

{setupError}

} - - {lookupMessage && ( -

- {lookupMessage} -

- )} - - - -
- - setVisitorName(e.target.value)} - className="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-lg focus:outline-none focus:ring-2 focus:ring-blue-500" - placeholder="John Smith" - required - /> -
+
+ {lookupLoading && ( +

Checking for an existing account…

+ )} + {!lookupLoading && accountConflict && emailMatch && phoneMatch && ( +
+ This email matches an existing account for {emailMatch.name}, but this phone number + matches a different existing account for {phoneMatch.name}. Please check and correct + one of these fields before continuing. +
+ )} + {!lookupLoading && !accountConflict && lookupMessage && ( +

+ {lookupMessage} +

+ )} + +
+ + setVisitorName(e.target.value)} + className="w-full border border-gray-300 rounded-xl px-4 py-3.5 text-lg focus:outline-none focus:ring-2 focus:ring-blue-500" + placeholder="John Smith" + required + /> +
+ {/* Preference selector — only shown when both channels are available */} {visitorEmail.trim() && visitorPhone.trim() && (
@@ -888,14 +971,17 @@ export default function SelfServicePage() { {createAccount && (
- setVisitorPassword(e.target.value)} - className="w-full border border-gray-300 rounded-xl px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" - placeholder="Min. 6 characters" - autoComplete="new-password" - /> +
+ setVisitorPassword(e.target.value)} + className="w-full border border-gray-300 rounded-xl px-4 py-3 pr-12 text-base focus:outline-none focus:ring-2 focus:ring-blue-500" + placeholder="Min. 6 characters" + autoComplete="new-password" + /> + setShowVisitorPassword((v) => !v)} /> +
)}
@@ -909,7 +995,7 @@ export default function SelfServicePage() { + + + + + )} + {/* ── Event Form Screen ──────────────────────────────────────── */} {screen === "eventform" && selectedEvent?.form && (
diff --git a/package.json b/package.json index dba94a4..e31bcda 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hope-events", - "version": "1.3.1", + "version": "1.3.2", "main": "index.js", "scripts": { "dev:backend": "cd backend && npm run dev",