hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { For, Show, createSignal } from "solid-js"; |
| 2 | import { cn } from "@/lib/cn"; |
| 3 | import { patchMe } from "@/api/users"; |
| 4 | import type { Gender, ProfileUpdate, User } from "@/api/client"; |
| 5 | import { formatApiError } from "@/api/client"; |
| 6 | import { Alert } from "@/components/ui/alert"; |
| 7 | import { Button } from "@/components/ui/button"; |
| 8 | import { DatePicker } from "@/components/ui/date-picker"; |
| 9 | import { Input } from "@/components/ui/input"; |
| 10 | import { Label } from "@/components/ui/label"; |
| 11 | import { Select } from "@/components/ui/select"; |
| 12 | import { Textarea } from "@/components/ui/textarea"; |
| 13 | import { createFlash } from "@/lib/flash"; |
| 14 | import { GENDER_LABEL_KEYS } from "@/lib/gender"; |
| 15 | import { hasMinRole } from "@/lib/roles"; |
| 16 | import { useT } from "@/stores/preferences-context"; |
| 17 | |
| 18 | const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 19 | const PHONE_RE = /^\+?[\d\s().-]{7,20}$/; |
| 20 | const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; |
| 21 | // The closed gender vocabulary the backend accepts (limits.user.genders). |
| 22 | const GENDERS: Gender[] = ["female", "male", "other", "undisclosed"]; |
| 23 | |
| 24 | function isFutureDate(iso: string) { |
| 25 | const d = new Date(`${iso}T00:00:00Z`); |
| 26 | if (Number.isNaN(d.getTime())) return true; |
| 27 | const tomorrow = new Date(); |
| 28 | tomorrow.setUTCDate(tomorrow.getUTCDate() + 1); |
| 29 | tomorrow.setUTCHours(0, 0, 0, 0); |
| 30 | return d.getTime() > tomorrow.getTime(); |
| 31 | } |
| 32 | |
| 33 | function dateInputFromIso(iso: string | null | undefined): string { |
| 34 | if (!iso) return ""; |
| 35 | const match = iso.match(/^(\d{4})-(\d{2})-(\d{2})$/); |
| 36 | if (!match) return ""; |
| 37 | const [, year, month, day] = match; |
| 38 | return `${day}/${month}/${year}`; |
| 39 | } |
| 40 | |
| 41 | function isoFromDateInput(value: string): string { |
| 42 | const match = value.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/); |
| 43 | if (!match) return value.trim(); |
| 44 | const [, day, month, year] = match; |
| 45 | return `${year}-${month}-${day}`; |
| 46 | } |
| 47 | |
| 48 | export function ProfileForm(props: { |
| 49 | user: User; |
| 50 | /** |
| 51 | * `display_name` and `bio` ride the same PATCH but do not live on `User` — |
| 52 | * GET /auth/me never returns them, only GET /users/{id}/profile does. Pass |
| 53 | * them where a profile is in hand; omit them and the fields stay hidden |
| 54 | * rather than silently offering to clear values they cannot see. |
| 55 | */ |
| 56 | profile?: { display_name: string | null; bio: string | null; branch?: string | null }; |
| 57 | /** The school's branş vocabulary (settings.branches); the picker hides when empty. */ |
| 58 | branches?: string[]; |
| 59 | maxDisplayNameLen?: number; |
| 60 | maxBioLen?: number; |
| 61 | /** |
| 62 | * Extra classes for the sticky save bar, so a host whose scroll area has |
| 63 | * other padding can pull the bar flush to its edges (the settings dialog). |
| 64 | */ |
| 65 | footerClass?: string; |
| 66 | /** Cap for the address field, from limits.user.max_address_len. */ |
| 67 | maxAddressLen?: number; |
| 68 | /** |
| 69 | * Offer the school-issued student number. It is the office's field, not the |
| 70 | * account holder's, so only the admin surface passes this; it stays hidden |
| 71 | * for anyone editing their own profile. Ignored for a non-student role, |
| 72 | * which the server refuses a number for anyway. |
| 73 | */ |
| 74 | editStudentNumber?: boolean; |
| 75 | maxStudentNumberLen?: number; |
| 76 | onSaved: () => void; |
| 77 | onSave?: (body: ProfileUpdate) => Promise<User>; |
| 78 | }) { |
| 79 | const t = useT(); |
| 80 | const [name, setName] = createSignal(props.user.name ?? ""); |
| 81 | const [surname, setSurname] = createSignal(props.user.surname ?? ""); |
| 82 | const [email, setEmail] = createSignal(props.user.email ?? ""); |
| 83 | const [phone, setPhone] = createSignal(props.user.phone ?? ""); |
| 84 | const [birthDate, setBirthDate] = createSignal(dateInputFromIso(props.user.birth_date)); |
| 85 | const [gender, setGender] = createSignal(props.user.gender ?? ""); |
| 86 | const [address, setAddress] = createSignal(props.user.address ?? ""); |
| 87 | const [emergencyName, setEmergencyName] = createSignal(props.user.emergency_contact_name ?? ""); |
| 88 | const [emergencyPhone, setEmergencyPhone] = createSignal(props.user.emergency_contact_phone ?? ""); |
| 89 | const [displayName, setDisplayName] = createSignal(props.profile?.display_name ?? ""); |
| 90 | const [bio, setBio] = createSignal(props.profile?.bio ?? ""); |
| 91 | const [branch, setBranch] = createSignal(props.profile?.branch ?? ""); |
| 92 | const [studentNumber, setStudentNumber] = createSignal(props.user.student_number ?? ""); |
| 93 | const showStudentNumber = () => !!props.editStudentNumber && props.user.role === "student"; |
| 94 | // Branş is a teacher's field; a stored value outside the list still shows so |
| 95 | // saving the form never silently drops it. |
| 96 | const branchOptions = () => { |
| 97 | const list = props.branches ?? []; |
| 98 | const stored = props.profile?.branch; |
| 99 | return stored && !list.includes(stored) ? [stored, ...list] : list; |
| 100 | }; |
| 101 | const showBranch = () => !!props.profile && hasMinRole(props.user.role, "teacher") && branchOptions().length > 0; |
| 102 | const [error, setError] = createSignal(""); |
| 103 | const [flash, setFlash] = createFlash(); |
| 104 | const [pending, setPending] = createSignal(false); |
| 105 | |
| 106 | const validate = (): string | null => { |
| 107 | const e = email().trim(); |
| 108 | const p = phone().trim(); |
| 109 | const b = isoFromDateInput(birthDate()); |
| 110 | const ep = emergencyPhone().trim(); |
| 111 | if (e && !EMAIL_RE.test(e)) return t("profile.emailInvalid"); |
| 112 | if (p && !PHONE_RE.test(p)) return t("profile.phoneInvalid"); |
| 113 | if (ep && !PHONE_RE.test(ep)) return t("profile.phoneInvalid"); |
| 114 | if (b && (!DATE_RE.test(b) || isFutureDate(b))) return t("profile.dateInvalid"); |
| 115 | return null; |
| 116 | }; |
| 117 | |
| 118 | const buildBody = (): ProfileUpdate => { |
| 119 | const b: ProfileUpdate = {}; |
| 120 | const n = name().trim(); |
| 121 | const s = surname().trim(); |
| 122 | const e = email().trim(); |
| 123 | const p = phone().trim(); |
| 124 | const d = isoFromDateInput(birthDate()); |
| 125 | if (n !== (props.user.name ?? "")) b.name = n; |
| 126 | if (s !== (props.user.surname ?? "")) b.surname = s; |
| 127 | if (e !== (props.user.email ?? "")) b.email = e; |
| 128 | if (p !== (props.user.phone ?? "")) b.phone = p; |
| 129 | if (d !== (props.user.birth_date ?? "")) b.birth_date = d; |
| 130 | // Same omitted=keep / ""=clear / value=set merge the backend applies. An |
| 131 | // empty gender select sends an explicit null (clear); a pick sends the enum. |
| 132 | const g = gender(); |
| 133 | if (g !== (props.user.gender ?? "")) b.gender = g === "" ? null : (g as Gender); |
| 134 | const a = address().trim(); |
| 135 | if (a !== (props.user.address ?? "")) b.address = a; |
| 136 | const em = emergencyName().trim(); |
| 137 | if (em !== (props.user.emergency_contact_name ?? "")) b.emergency_contact_name = em; |
| 138 | const ep = emergencyPhone().trim(); |
| 139 | if (ep !== (props.user.emergency_contact_phone ?? "")) b.emergency_contact_phone = ep; |
| 140 | // Blank clears it server-side, which is how the office un-numbers a student. |
| 141 | if (showStudentNumber() && studentNumber().trim() !== (props.user.student_number ?? "")) { |
| 142 | b.student_number = studentNumber().trim(); |
| 143 | } |
| 144 | if (props.profile) { |
| 145 | // An empty string clears the field server-side; an omitted key keeps it. |
| 146 | const dn = displayName().trim(); |
| 147 | const bi = bio().trim(); |
| 148 | if (dn !== (props.profile.display_name ?? "")) b.display_name = dn; |
| 149 | if (bi !== (props.profile.bio ?? "")) b.bio = bi; |
| 150 | if (showBranch() && branch() !== (props.profile.branch ?? "")) b.branch = branch(); |
| 151 | } |
| 152 | return b; |
| 153 | }; |
| 154 | |
| 155 | const submit = async (e: Event) => { |
| 156 | e.preventDefault(); |
| 157 | setError(""); |
| 158 | const msg = validate(); |
| 159 | if (msg) { setError(msg); return; } |
| 160 | const body = buildBody(); |
| 161 | if (Object.keys(body).length === 0) { props.onSaved(); return; } |
| 162 | setPending(true); |
| 163 | try { |
| 164 | await (props.onSave ?? patchMe)(body); |
| 165 | props.onSaved(); |
| 166 | setFlash(t("common.saved")); |
| 167 | } catch (err) { |
| 168 | setError(formatApiError(err)); |
| 169 | } finally { |
| 170 | setPending(false); |
| 171 | } |
| 172 | }; |
| 173 | |
| 174 | return ( |
| 175 | <form onSubmit={submit} class="flex min-h-full flex-col space-y-4"> |
| 176 | <Show when={flash()}> |
| 177 | <Alert variant="success">{flash()}</Alert> |
| 178 | </Show> |
| 179 | <div class="grid gap-3 sm:grid-cols-2"> |
| 180 | <div class="space-y-1.5"> |
| 181 | <Label for="pf-name">{t("profile.name")}</Label> |
| 182 | <Input id="pf-name" class="h-10" value={name()} onInput={(e) => setName(e.currentTarget.value)} /> |
| 183 | </div> |
| 184 | <div class="space-y-1.5"> |
| 185 | <Label for="pf-surname">{t("profile.surname")}</Label> |
| 186 | <Input id="pf-surname" class="h-10" value={surname()} onInput={(e) => setSurname(e.currentTarget.value)} /> |
| 187 | </div> |
| 188 | </div> |
| 189 | <Show when={props.profile}> |
| 190 | <div class="space-y-1.5"> |
| 191 | <Label for="pf-display-name">{t("profile.displayName")}</Label> |
| 192 | <Input |
| 193 | id="pf-display-name" |
| 194 | class="h-10" |
| 195 | maxlength={props.maxDisplayNameLen} |
| 196 | value={displayName()} |
| 197 | onInput={(e) => setDisplayName(e.currentTarget.value)} |
| 198 | /> |
| 199 | <p class="text-xs text-muted-foreground">{t("profile.displayNameHint")}</p> |
| 200 | </div> |
| 201 | <div class="space-y-1.5"> |
| 202 | <Label for="pf-bio">{t("profile.bio")}</Label> |
| 203 | <Textarea |
| 204 | id="pf-bio" |
| 205 | rows={3} |
| 206 | maxlength={props.maxBioLen} |
| 207 | value={bio()} |
| 208 | onInput={(e) => setBio(e.currentTarget.value)} |
| 209 | /> |
| 210 | <p class="text-xs text-muted-foreground"> |
| 211 | {t("profile.bioHint")} |
| 212 | <Show when={props.maxBioLen}> |
| 213 | {(max) => <span class="ml-1 tabular-nums">{bio().length} / {max()}</span>} |
| 214 | </Show> |
| 215 | </p> |
| 216 | </div> |
| 217 | </Show> |
| 218 | <Show when={showBranch()}> |
| 219 | <div class="space-y-1.5"> |
| 220 | <Label for="pf-branch">{t("profile.branch")}</Label> |
| 221 | <Select id="pf-branch" class="h-10" value={branch()} onChange={(e) => setBranch(e.currentTarget.value)}> |
| 222 | <option value="">{t("profile.branchNone")}</option> |
| 223 | <For each={branchOptions()}>{(name) => <option value={name}>{name}</option>}</For> |
| 224 | </Select> |
| 225 | </div> |
| 226 | </Show> |
| 227 | <Show when={showStudentNumber()}> |
| 228 | <div class="space-y-1.5"> |
| 229 | <Label for="pf-student-number">{t("roster.studentNumber")}</Label> |
| 230 | <Input |
| 231 | id="pf-student-number" |
| 232 | class="h-10" |
| 233 | maxlength={props.maxStudentNumberLen} |
| 234 | value={studentNumber()} |
| 235 | onInput={(e) => setStudentNumber(e.currentTarget.value)} |
| 236 | /> |
| 237 | <p class="text-xs text-muted-foreground">{t("admin.studentNumberHint")}</p> |
| 238 | </div> |
| 239 | </Show> |
| 240 | <div class="space-y-1.5"> |
| 241 | <Label for="pf-email">{t("profile.email")}</Label> |
| 242 | <Input id="pf-email" class="h-10" type="email" value={email()} onInput={(e) => setEmail(e.currentTarget.value)} /> |
| 243 | </div> |
| 244 | <div class="space-y-1.5"> |
| 245 | <Label for="pf-phone">{t("profile.phone")}</Label> |
| 246 | <Input id="pf-phone" class="h-10" type="tel" value={phone()} onInput={(e) => setPhone(e.currentTarget.value)} /> |
| 247 | </div> |
| 248 | <div class="space-y-1.5"> |
| 249 | <Label for="pf-birth">{t("profile.birthDate")}</Label> |
| 250 | <DatePicker id="pf-birth" class="h-10" placeholder={t("form.datePlaceholder")} value={birthDate()} onChange={setBirthDate} /> |
| 251 | </div> |
| 252 | <div class="space-y-1.5"> |
| 253 | <Label for="pf-gender">{t("profile.gender")}</Label> |
| 254 | <Select id="pf-gender" class="h-10" value={gender()} onChange={(e) => setGender(e.currentTarget.value)}> |
| 255 | <option value="">{t("profile.genderNone")}</option> |
| 256 | <For each={GENDERS}>{(g) => <option value={g}>{t(GENDER_LABEL_KEYS[g])}</option>}</For> |
| 257 | </Select> |
| 258 | </div> |
| 259 | <div class="space-y-1.5"> |
| 260 | <Label for="pf-address">{t("profile.address")}</Label> |
| 261 | <Textarea |
| 262 | id="pf-address" |
| 263 | rows={2} |
| 264 | maxlength={props.maxAddressLen} |
| 265 | value={address()} |
| 266 | onInput={(e) => setAddress(e.currentTarget.value)} |
| 267 | /> |
| 268 | <Show when={props.maxAddressLen}> |
| 269 | {(max) => <p class="text-xs text-muted-foreground">{address().length} / {max()}</p>} |
| 270 | </Show> |
| 271 | </div> |
| 272 | <div class="grid gap-3 sm:grid-cols-2"> |
| 273 | <div class="space-y-1.5"> |
| 274 | <Label for="pf-emergency-name">{t("profile.emergencyContactName")}</Label> |
| 275 | <Input id="pf-emergency-name" class="h-10" value={emergencyName()} onInput={(e) => setEmergencyName(e.currentTarget.value)} /> |
| 276 | </div> |
| 277 | <div class="space-y-1.5"> |
| 278 | <Label for="pf-emergency-phone">{t("profile.emergencyContactPhone")}</Label> |
| 279 | <Input id="pf-emergency-phone" class="h-10" type="tel" value={emergencyPhone()} onInput={(e) => setEmergencyPhone(e.currentTarget.value)} /> |
| 280 | </div> |
| 281 | </div> |
| 282 | {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive-text">{error()}</p>} |
| 283 | <div class={cn("!mt-auto sticky bottom-0 -mx-5 flex justify-end border-t border-border-hairline bg-surface-base px-5 pb-1 pt-4", props.footerClass)}> |
| 284 | <Button type="submit" class="h-10 w-full sm:w-auto" disabled={pending()}>{t("common.save")}</Button> |
| 285 | </div> |
| 286 | </form> |
| 287 | ); |
| 288 | } |