Files
co-lite/solvway-customer-portal/app/settings/profile/page.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

439 lines
20 KiB
TypeScript

"use client";
import { useState, useEffect, useRef, useId } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { Save, Loader2 } from "lucide-react";
import { useTheme } from "@/app/lib/ThemeContext";
import { useMember } from "@/app/lib/MemberContext";
import { useToast } from "@/app/lib/ToastContext";
import { apiGet, apiPut, ApiError } from "@/app/lib/clientApi";
import { isAtLeast18, toApiGender } from "@/app/lib/profileMappers";
import { geoName } from "@/app/lib/geoName";
import MemberAvatar from "@/app/components/ui/MemberAvatar";
import DobPicker from "@/app/components/ui/DobPicker";
import type { MemberProfile, GeoLocationNode } from "@/app/lib/types";
const GENDERS = ["Male", "Female"];
interface NationalityOpt { code: string; name: string }
interface Place { id: number; label: string; postCode: string | null }
const fadeUp = {
hidden: { opacity: 0, y: 12 },
visible: { opacity: 1, y: 0, transition: { type: "spring" as const, stiffness: 340, damping: 28 } },
};
// Defined at module scope so their identity is stable across re-renders; if these
// lived inside ProfilePage they'd be re-created on every keystroke, remounting the
// inputs they wrap and dropping focus. Theme colors are passed in as props.
const Label = ({ children, required, color }: { children: React.ReactNode; required?: boolean; color: string }) => (
<p className="text-xs font-semibold mb-1.5" style={{ color }}>
{children}
{required && <span className="ml-0.5 text-red-500">*</span>}
</p>
);
const Row = ({ children, first, divider }: { children: React.ReactNode; first?: boolean; divider: string }) => (
<div className="px-4 py-4" style={first ? undefined : { borderTop: `1px solid ${divider}` }}>{children}</div>
);
export default function ProfilePage() {
const { isDark } = useTheme();
const { member } = useMember();
const { showToast } = useToast();
const router = useRouter();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [fieldErrors, setFieldErrors] = useState<Partial<Record<"firstName" | "surname" | "email", string>>>({});
const [profile, setProfile] = useState<MemberProfile | null>(null);
const [nationalities, setNationalities] = useState<NationalityOpt[]>([]);
const [countries, setCountries] = useState<GeoLocationNode[]>([]);
const [countryId, setCountryId] = useState("");
const [places, setPlaces] = useState<Place[]>([]);
const [picked, setPicked] = useState<Place | null>(null);
const [query, setQuery] = useState("");
const [listOpen, setListOpen] = useState(false);
const [placesState, setPlacesState] = useState<"loading" | "ready" | "error">("loading");
const [placesReload, setPlacesReload] = useState(0);
const listId = useId();
const [savedCountry, setSavedCountry] = useState("");
const [street, setStreet] = useState("");
const [editing, setEditing] = useState(false);
const fieldRefs = useRef<Record<string, HTMLInputElement | null>>({});
const [form, setForm] = useState({
firstName: "",
surname: "",
email: "",
nationality: "",
dob: "",
gender: "Male",
postcode: "",
});
const set = (key: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
setForm((f) => ({ ...f, [key]: e.target.value }));
setFieldErrors((fe) => ({ ...fe, [key]: undefined }));
};
const fieldError = (key: keyof typeof fieldErrors) =>
fieldErrors[key] && <p className="text-xs text-red-500 font-medium mt-1">{fieldErrors[key]}</p>;
useEffect(() => {
(async () => {
try {
const [p, init, firstLevel] = await Promise.all([
apiGet<MemberProfile>("/api/member/profile"),
apiGet<Record<string, unknown>>("/api/member/profile-init"),
apiGet<GeoLocationNode[]>("/api/geo/first-level"),
]);
setProfile(p);
setForm({
firstName: p.name || "",
surname: p.surname || "",
email: p.email || "",
nationality: p.nationality?.code || "",
dob: p.dob || "",
gender: p.gender === "F" ? "Female" : "Male",
postcode: p.postCode || "",
});
const natList = (init["nationalityList"] as NationalityOpt[] | undefined) ?? [];
setNationalities(natList);
setCountries(firstLevel);
const saved = init["geoLocationLevel1"];
const malaysia = firstLevel.find((c) => geoName(c.name) === "Malaysia");
const savedId = firstLevel.some((c) => String(c.id) === String(saved)) ? String(saved) : "";
const initial = savedId || String(malaysia?.id ?? "");
setSavedCountry(initial);
setCountryId(initial);
setStreet(p.addressDetails || "");
setEditing(!p.addressLocation);
} catch (err) {
if (!(err instanceof ApiError && err.status === 401)) {
setError("Couldn't load your profile. Please try again.");
}
} finally {
setLoading(false);
}
})();
}, []);
// Load the selected country's places for the area search (editor only).
useEffect(() => {
if (!editing || !countryId) return;
let cancelled = false;
apiGet<Place[]>(`/api/geo/search-index?country=${countryId}`)
.then((list) => { if (!cancelled) { setPlaces(list); setPlacesState("ready"); } })
.catch(() => { if (!cancelled) { setPlaces([]); setPlacesState("error"); } });
return () => { cancelled = true; };
}, [editing, countryId, placesReload]);
const onCountryChange = (id: string) => {
setCountryId(id);
setPlaces([]);
setPlacesState("loading");
setPicked(null);
setQuery("");
};
// Picking a place closes the panel and fills the place's postcode, replacing any
// previous value (members typed postcodes that did not match the picked area).
// The field stays editable; a place without a postcode leaves it as is.
const onPick = (place: Place) => {
setPicked(place);
setQuery("");
setListOpen(false);
const postcode = place.postCode?.trim();
if (postcode) setForm((f) => ({ ...f, postcode }));
};
const q = query.trim().toLowerCase();
const ownName = (pl: Place) => pl.label.split(", ")[0].toLowerCase();
const BROWSE_CAP = 300;
const suggestions =
!q
? [...places].sort((x, y) => x.label.localeCompare(y.label)).slice(0, BROWSE_CAP)
: places
.filter((pl) => pl.label.toLowerCase().includes(q) || pl.postCode === q)
.sort(
(x, y) =>
Number(ownName(y).includes(q)) - Number(ownName(x).includes(q)) ||
y.label.split(", ").length - x.label.split(", ").length,
)
.slice(0, 20);
// Malaysia requires a valid 5-digit postcode (the backend rejects anything else);
// mirror that on the client so a miss/typo is caught with a clear message rather than
// the backend's raw "Param 'postCode' is invalid".
const isMalaysia = geoName(countries.find((c) => String(c.id) === countryId)?.name) === "Malaysia";
const addressLine = (profile?.fullAddress || "").split(", ").filter((x) => x.trim()).join(", ");
const handleSave = async () => {
setError(null);
const missing: typeof fieldErrors = {};
if (!form.firstName.trim()) missing.firstName = "First name is required.";
if (!form.surname.trim()) missing.surname = "Surname is required.";
if (!form.email.trim()) missing.email = "Email is required.";
setFieldErrors(missing);
const firstMissing = (Object.keys(missing) as (keyof typeof missing)[])[0];
if (firstMissing) {
fieldRefs.current[firstMissing]?.focus();
return;
}
if (!form.dob) {
setError("Please complete your date of birth.");
return;
}
const dob = form.dob;
if (!isAtLeast18(dob)) {
setError("You must be at least 18 years old.");
return;
}
const gender = toApiGender(form.gender);
if (!gender) {
setError("Please select a valid gender.");
return;
}
if (
editing &&
profile?.addressLocation && countryId !== savedCountry && !picked
) {
setError("Please pick your area from the list.");
return;
}
const addressLocation = (picked ? String(picked.id) : "") || profile?.addressLocation || "";
if (!addressLocation) {
setError("Please select your address location.");
return;
}
if (isMalaysia && !/^\d{5}$/.test(form.postcode.trim())) {
setError("Please enter a valid 5-digit postcode.");
return;
}
setSaving(true);
try {
const firstCompletion = profile?.emrmProfileUpdate !== "Y";
const balance = firstCompletion
? await apiGet<{ balance: number }>("/api/points/balance").then((r) => r.balance, () => null)
: null;
await apiPut("/api/member/profile", {
name: form.firstName,
surname: form.surname,
email: form.email,
dob,
gender,
postCode: form.postcode,
addressLocation,
addressDetails: street.trim(),
});
if (balance !== null) {
// Complete Profile reward lands asynchronously after save; Home diffs against this baseline.
// No baseline when the read failed: 0 would make Home claim the whole balance.
try {
sessionStorage.setItem("profileRewardBaseline", JSON.stringify({ balance, at: Date.now() }));
} catch {}
}
showToast("Profile updated");
router.push("/");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't save changes. Please try again.");
} finally {
setSaving(false);
}
};
const t = {
text: isDark ? "#FFFFFF" : "#1a1a1a",
textSec: isDark ? "rgba(255,255,255,0.8)" : "#5C5C5C",
textMuted: isDark ? "rgba(255,255,255,0.6)" : "#6B6B6B",
card: isDark ? "rgba(255,255,255,0.06)" : "#FFFFFF",
border: isDark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)",
shadow: isDark
? "0 4px 24px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.06)"
: "0 2px 16px rgba(0,0,0,0.07), 0 1px 3px rgba(0,0,0,0.04)",
inputBg: isDark ? "rgba(255,255,255,0.04)" : "#FAFAFA",
inputBorder: isDark ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.1)",
divider: isDark ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.06)",
};
const inputCls = "w-full text-sm outline-none rounded-xl px-3 py-2.5 transition-colors";
const inputStyle = { background: t.inputBg, border: `1px solid ${t.inputBorder}`, color: t.text };
const selectStyle = { ...inputStyle, cursor: "pointer" };
if (loading) {
return (
<div className="min-h-full flex items-center justify-center pb-28" style={{ background: "var(--bg-primary)" }}>
<motion.div animate={{ rotate: 360 }} transition={{ repeat: Infinity, duration: 0.8, ease: "linear" }}>
<Loader2 strokeWidth={2} className="w-8 h-8 stroke-tastefullyOrange" />
</motion.div>
</div>
);
}
return (
<div className="min-h-full pb-28" style={{ background: "var(--bg-primary)" }}>
{/* Avatar hero */}
<motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} transition={{ type: "spring", stiffness: 320, damping: 26 }} className="flex flex-col items-center gap-3 pt-6 pb-5">
<MemberAvatar className="w-20 h-20 rounded-3xl" style={{ boxShadow: "0 8px 28px rgba(255,107,0,0.3)" }} />
<div className="text-center">
<p className="font-bold text-base uppercase" style={{ color: t.text }}>{form.firstName} {form.surname}</p>
<p className="text-xs font-mono mt-0.5" style={{ color: t.textMuted }}>{profile?.memberCode ?? ""}</p>
</div>
</motion.div>
<div className="px-4">
<motion.p variants={fadeUp} initial="hidden" animate="visible" className="text-lg font-extrabold mb-4" style={{ color: t.text }}>
Personal Info
</motion.p>
<motion.div variants={fadeUp} initial="hidden" animate="visible" className="rounded-2xl overflow-hidden" style={{ background: t.card, border: `1px solid ${t.border}`, boxShadow: t.shadow }}>
{/* Mobile (read-only) */}
<Row first divider={t.divider}>
<Label color={t.textSec}>Mobile</Label>
<input type="tel" value={profile?.phoneNoCombined || member?.phone || ""} disabled className={inputCls} style={{ ...inputStyle, opacity: 0.7 }} />
</Row>
<Row divider={t.divider}>
<Label required color={t.textSec}>First Name</Label>
<input type="text" ref={(el) => { fieldRefs.current.firstName = el; }} aria-invalid={!!fieldErrors.firstName} value={form.firstName} onChange={set("firstName")} placeholder="Your first name" className={inputCls} style={inputStyle} />
{fieldError("firstName")}
</Row>
<Row divider={t.divider}>
<Label required color={t.textSec}>Surname</Label>
<input type="text" ref={(el) => { fieldRefs.current.surname = el; }} aria-invalid={!!fieldErrors.surname} value={form.surname} onChange={set("surname")} placeholder="Your surname" className={inputCls} style={inputStyle} />
{fieldError("surname")}
</Row>
<Row divider={t.divider}>
<Label required color={t.textSec}>Email</Label>
<input type="email" ref={(el) => { fieldRefs.current.email = el; }} aria-invalid={!!fieldErrors.email} value={form.email} onChange={set("email")} placeholder="you@email.com" className={inputCls} style={inputStyle} />
{fieldError("email")}
</Row>
<Row divider={t.divider}>
<Label color={t.textSec}>Nationality</Label>
<select value={form.nationality} onChange={set("nationality")} className={inputCls} style={selectStyle} disabled={nationalities.length === 0}>
<option value="">Select nationality</option>
{nationalities.map((n) => <option key={n.code} value={n.code}>{n.name}</option>)}
</select>
</Row>
<Row divider={t.divider}>
<Label required color={t.textSec}>Date Of Birth</Label>
<DobPicker value={form.dob} onChange={(dob) => setForm((f) => ({ ...f, dob }))} />
</Row>
<Row divider={t.divider}>
<Label required color={t.textSec}>Gender</Label>
<select value={form.gender} onChange={set("gender")} className={inputCls} style={selectStyle}>
{GENDERS.map((g) => <option key={g} value={g}>{g}</option>)}
</select>
</Row>
{/* Address — saved line, or street + area search */}
<Row divider={t.divider}>
<Label required color={t.textSec}>Address Location</Label>
{!editing ? (
<div className="flex items-start justify-between gap-3">
<p data-testid="profile-address-line" className="text-sm" style={{ color: t.text }}>{addressLine}</p>
<button type="button" onClick={() => setEditing(true)} className="text-xs font-semibold text-tastefullyOrangeText">Change</button>
</div>
) : (
<div className="space-y-2">
<select aria-label="Country" value={countryId} onChange={(e) => onCountryChange(e.target.value)} className={inputCls} style={selectStyle}>
{countries.map((c) => <option key={c.id} value={String(c.id)}>{geoName(c.name)}</option>)}
</select>
<input type="text" maxLength={250} value={street} onChange={(e) => setStreet(e.target.value)} placeholder="Unit, building, street" className={inputCls} style={inputStyle} />
<div className="relative">
<div className="relative">
<button
type="button"
data-testid="area-picker"
aria-haspopup="listbox"
aria-expanded={listOpen}
aria-controls={listId}
onClick={() => { setListOpen((o) => !o); setQuery(""); }}
className={`${inputCls} pr-10 text-left`}
style={{ ...inputStyle, color: picked ? t.text : t.textMuted }}
>
{picked?.label ?? "Select your area"}
</button>
<span aria-hidden className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs" style={{ color: t.textSec }}>▼</span>
</div>
{listOpen && (
<div className="mt-1 rounded-xl p-2 space-y-2" style={{ background: t.card, border: `1px solid ${t.inputBorder}`, boxShadow: t.shadow }}>
<input
type="text"
aria-label="Search town or postcode"
aria-controls={listId}
autoFocus
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search town or postcode"
className={inputCls}
style={inputStyle}
/>
<ul id={listId} role="listbox" className="max-h-56 overflow-auto text-sm">
{suggestions.map((pl) => (
<li key={pl.id} role="option" aria-selected={picked?.id === pl.id} onMouseDown={(e) => { e.preventDefault(); onPick(pl); }} className="px-3 py-2 cursor-pointer" style={{ color: t.text }}>{pl.label}</li>
))}
{!q && places.length > BROWSE_CAP && (
<li className="px-3 py-2 text-xs" style={{ color: t.textMuted }}>Type to narrow the list.</li>
)}
</ul>
<p className="text-xs px-1" style={{ color: t.textMuted }}>Can&apos;t find your taman? Pick the nearest town and add your taman in the street line.</p>
</div>
)}
{countryId && placesState === "loading" && <p className="text-xs mt-1" style={{ color: t.textMuted }}>Loading places…</p>}
{placesState === "error" && (
<p className="text-xs mt-1 text-red-500">
Couldn&apos;t load places.{" "}
<button type="button" onClick={() => { setPlacesState("loading"); setPlacesReload((n) => n + 1); }} className="font-semibold underline">Try again</button>
</p>
)}
</div>
</div>
)}
</Row>
<Row divider={t.divider}>
<Label required={isMalaysia} color={t.textSec}>Postcode</Label>
<input type="text" inputMode="numeric" value={form.postcode} onChange={set("postcode")} placeholder="Enter Postcode" className={inputCls} style={inputStyle} />
</Row>
</motion.div>
{error && (
<motion.p initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} className="text-xs text-red-500 font-medium mt-3">
{error}
</motion.p>
)}
<motion.button
onClick={handleSave}
disabled={saving}
whileTap={{ scale: 0.96 }}
transition={{ type: "spring", stiffness: 420, damping: 26 }}
className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl font-bold text-sm mt-5 text-white"
style={{
background: "linear-gradient(135deg, #C94D00 0%, #A83F00 100%)",
boxShadow: "0 8px 24px rgba(255,107,0,0.35)",
opacity: saving ? 0.85 : 1,
}}
>
{saving ? (
<motion.div animate={{ rotate: 360 }} transition={{ repeat: Infinity, duration: 0.8, ease: "linear" }}>
<Loader2 strokeWidth={2} className="w-4 h-4" />
</motion.div>
) : (
<><Save strokeWidth={2} className="w-4 h-4" /> Save Changes</>
)}
</motion.button>
</div>
</div>
);
}