Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord

Migration 076 adds a member role below viewer (the site and its own
profile, never the admin: /api/admin now needs viewer), invites, person
claims, a Discord link on accounts and people.hide_* switches. Public reads
of people go through v_people_public, which nulls hidden fields, and the
views that read people are rebuilt over it.

Admins invite an email from Data -> Profile accounts (link shown once,
emailed on request). The invitee sets a password or signs in with any
Google account under that email, asks to claim their People record, and
once approved edits it and chooses what shows at /account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aidan Dona 2026-10-16 18:14:30 -05:00
parent 0cc2a3f721
commit e4c7e165d1
34 changed files with 2483 additions and 74 deletions

416
src/pages/Account.tsx Normal file
View file

@ -0,0 +1,416 @@
/* ═══════════════════════════════════════════════════════════════
YOUR PROFILE: /account, a profile account's page (076)
Your account who's signed in, sign out (and the admin, for
an admin account)
Your profile before a record is theirs: ask to claim one (an
admin approves it); after: edit its text and
photo, and choose what of it shows on the site
Discord link it (or unlink), for the gamification to come
Signed out, it's the sign-in page's job. Everything is saved
through routes/account.js, which only ever writes the account's
own person.
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from 'react'
import { Link, Navigate, useSearchParams } from 'react-router-dom'
import { ArrowSquareOut, SignOut } from '@phosphor-icons/react'
import PageShell from '../components/PageShell.tsx'
import { useAuth } from '../lib/auth.tsx'
import { ApiError, del, get, patch, post, upload } from '../lib/api.ts'
import { ACCENTS, BRAND } from '../lib/color.ts'
import { mediaUrl } from '../lib/media.ts'
import { personHref } from '../lib/hrefs.ts'
import { ROLE_LABELS, isStaff, type Role } from '../lib/roles.ts'
import { HIDE_FIELDS, useMyAccount, type MyAccount, type MyPerson } from '../lib/useAccount.ts'
import { fieldClass, primaryButton } from './SignIn.tsx'
const quietButton =
'btn border border-brand px-5 py-2.5 text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:opacity-60'
/* What ?discord= says after the trip to Discord (routes/account.js). */
const DISCORD_RESULTS: Record<string, string> = {
linked: 'Your Discord account is linked.',
canceled: 'Linking Discord was canceled.',
expired: 'That took too long. Try again.',
taken: 'That Discord account is already linked to another profile.',
failed: "Discord didn't link. Try again in a moment.",
}
const message = (err: unknown) =>
err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."
function Alert({ children, tone = 'danger' }: { children: React.ReactNode; tone?: 'danger' | 'ok' }) {
return (
<p
role={tone === 'danger' ? 'alert' : 'status'}
className={`mt-4 px-4 py-3 text-sm ${
tone === 'danger' ? 'border border-danger/30 bg-danger-tint text-danger' : 'border border-brand/30 bg-tint text-body'
}`}
>
{children}
</p>
)
}
export default function Account() {
const { user, loading, logout } = useAuth()
const { data, error, reload } = useMyAccount(Boolean(user))
if (loading) return null
if (!user) return <Navigate to="/sign-in" replace />
const content = (part: React.ReactNode) => <div className="mx-auto max-w-3xl px-6">{part}</div>
return (
<PageShell
title="Your profile"
intro="Your account on the site, the profile that's yours, and what of it shows."
sections={[
{
id: 'account',
title: 'Your account',
accent: BRAND,
content: content(
<div className="flex flex-wrap items-center justify-between gap-4 bg-raised p-6 shadow-md">
<div>
<p className="font-semibold text-ink">{user.name || user.email}</p>
<p className="text-sm text-muted">
{user.email} · {ROLE_LABELS[user.role as Role] ?? user.role}
</p>
</div>
<div className="flex flex-wrap gap-3">
{isStaff(user) && (
<Link to="/admin/home" className={quietButton}>
Admin
</Link>
)}
<button type="button" onClick={logout} className={`${quietButton} inline-flex items-center gap-2`}>
<SignOut size={18} weight="bold" aria-hidden="true" />
Sign out
</button>
</div>
</div>,
),
},
{
id: 'profile',
title: 'Your profile',
blurb: 'Your page on the site, eg. on a team or an event. Ask for yours, then edit it here.',
accent: ACCENTS.green,
content: content(
error ? (
<p className="text-danger">Couldn't load your profile. {error}</p>
) : !data ? (
<div className="skeleton !min-h-40" aria-label="Loading your profile" />
) : data.person ? (
<ProfileEditor key={data.person.id} person={data.person} onSaved={reload} />
) : (
<Claim account={data} onChange={reload} />
),
),
},
{
id: 'discord',
title: 'Discord',
blurb: 'Link your Discord account so what you do there can count here.',
accent: ACCENTS.amber,
content: content(data ? <Discord account={data} onChange={reload} /> : null),
},
]}
/>
)
}
/* ── Claiming a record ───────────────────────────────────────── */
function Claim({ account, onChange }: { account: MyAccount; onChange: () => void }) {
const [people, setPeople] = useState<{ id: string; name: string }[] | null>(null)
const [personId, setPersonId] = useState('')
const [note, setNote] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const pending = account.claim?.status === 'pending' ? account.claim : null
useEffect(() => {
if (pending) return
get('/account/people', { ttl: 0 })
.then((data) => setPeople(data.people))
.catch((err) => setError(message(err)))
}, [pending])
async function run(action: () => Promise<unknown>) {
setBusy(true)
setError(null)
try {
await action()
onChange()
} catch (err) {
setError(message(err))
} finally {
setBusy(false)
}
}
if (pending) {
return (
<div className="notice p-5">
<p className="text-body">
You asked to be <strong>{pending.display_name}</strong>. An admin will look at it soon.
</p>
<button type="button" disabled={busy} onClick={() => run(() => del('/account/claim'))} className={`mt-4 ${quietButton}`}>
Take back the request
</button>
{error && <Alert>{error}</Alert>}
</div>
)
}
return (
<form
onSubmit={(e) => {
e.preventDefault()
run(() => post('/account/claim', { person_id: personId, message: note }))
}}
className="bg-raised p-6 shadow-md"
>
{account.claim?.status === 'declined' && (
<p className="mb-4 text-sm text-muted">
Your request to be {account.claim.display_name} wasn't approved. Pick again, or say more in the note.
</p>
)}
<label htmlFor="claim-person" className="block text-sm font-medium text-body">
Which person on the site is you?
</label>
<select
id="claim-person"
value={personId}
onChange={(e) => setPersonId(e.target.value)}
className={`mt-2 ${fieldClass}`}
disabled={!people}
>
<option value="">{people ? 'Choose your name' : 'Loading…'}</option>
{people?.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
<p className="mt-1 text-xs text-muted">Not listed? Ask us through the Request page to add you.</p>
<label htmlFor="claim-note" className="mt-5 block text-sm font-medium text-body">
A note for the admin <span className="font-normal text-muted">(optional)</span>
</label>
<textarea
id="claim-note"
rows={3}
maxLength={1000}
value={note}
onChange={(e) => setNote(e.target.value)}
className={`mt-2 ${fieldClass}`}
/>
{error && <Alert>{error}</Alert>}
<button type="submit" disabled={busy || !personId} className={`mt-6 ${primaryButton}`}>
{busy ? 'Sending…' : 'Ask for this profile'}
</button>
</form>
)
}
/* ── Editing it ──────────────────────────────────────────────── */
const TEXT_FIELDS: { key: keyof MyPerson; label: string; help?: string; long?: boolean; type?: string }[] = [
{ key: 'pronouns', label: 'Pronouns', help: 'eg. she/her' },
{ key: 'tagline', label: 'Tagline', help: 'A line under your name when you have no title, eg. Musician and youth leader' },
{ key: 'location_label', label: 'Location', help: 'eg. Kansas City, MO' },
{ key: 'public_email', label: 'Public email', type: 'email', help: 'Shown on your page. Leave it blank for none.' },
{ key: 'public_phone', label: 'Public phone', type: 'tel' },
{ key: 'bio', label: 'Bio', long: true, help: 'A blank line starts a new paragraph.' },
]
function ProfileEditor({ person, onSaved }: { person: MyPerson; onSaved: () => void }) {
const [values, setValues] = useState(() =>
Object.fromEntries(TEXT_FIELDS.map(({ key }) => [key, (person[key] as string | null) ?? ''])),
)
const [hidden, setHidden] = useState(person.hidden)
const [photo, setPhoto] = useState(person.photo)
const [fields, setFields] = useState<Record<string, string>>({})
const [error, setError] = useState<string | null>(null)
const [saved, setSaved] = useState(false)
const [busy, setBusy] = useState(false)
async function save(event: React.FormEvent) {
event.preventDefault()
setBusy(true)
setError(null)
setFields({})
setSaved(false)
try {
await patch('/account/profile', { ...values, hidden })
setSaved(true)
onSaved()
} catch (err) {
setError(message(err))
if (err instanceof ApiError && err.fields) setFields(err.fields)
} finally {
setBusy(false)
}
}
async function sendPhoto(file: File | undefined) {
if (!file) return
setBusy(true)
setError(null)
try {
const form = new FormData()
form.append('file', file)
const data = await upload('/account/photo', form)
setPhoto(data.person.photo)
} catch (err) {
setError(message(err))
} finally {
setBusy(false)
}
}
return (
<form onSubmit={save} noValidate className="bg-raised p-6 shadow-md sm:p-8">
<div className="flex flex-wrap items-center gap-5">
{photo ? (
<img src={mediaUrl(photo) ?? undefined} alt="" className="h-24 w-24 object-cover" />
) : (
<div className="flex h-24 w-24 items-center justify-center bg-tint text-sm text-muted">No photo</div>
)}
<div>
<p className="text-xl font-bold text-ink">{person.display_name}</p>
{person.is_published ? (
<Link to={personHref(person.id)} className="inline-flex items-center gap-1 text-sm text-link underline">
Your page on the site
<ArrowSquareOut size={14} weight="bold" aria-hidden="true" />
</Link>
) : (
<p className="text-sm text-muted">Your page isn't on the site yet.</p>
)}
<label className={`mt-3 inline-block cursor-pointer ${quietButton}`}>
{photo ? 'Change photo' : 'Add a photo'}
<input
type="file"
accept="image/jpeg,image/png,image/webp"
className="sr-only"
disabled={busy}
onChange={(e) => sendPhoto(e.target.files?.[0])}
/>
</label>
</div>
</div>
<p className="mt-3 text-xs text-muted">Your name is changed by an admin: ask through the Request page.</p>
<div className="mt-8 grid gap-5 sm:grid-cols-2">
{TEXT_FIELDS.map(({ key, label, help, long, type }) => (
<div key={key} className={long ? 'sm:col-span-2' : ''}>
<label htmlFor={`profile-${key}`} className="block text-sm font-medium text-body">
{label}
</label>
{long ? (
<textarea
id={`profile-${key}`}
rows={6}
value={values[key]}
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
aria-describedby={help ? `profile-${key}-help` : undefined}
className={`mt-2 ${fieldClass}`}
/>
) : (
<input
id={`profile-${key}`}
type={type ?? 'text'}
value={values[key]}
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
aria-describedby={help ? `profile-${key}-help` : undefined}
aria-invalid={Boolean(fields[key])}
className={`mt-2 ${fieldClass}`}
/>
)}
{fields[key] && <p className="mt-1 text-sm text-danger">{fields[key]}</p>}
{help && (
<p id={`profile-${key}-help`} className="mt-1 text-xs text-muted">
{help}
</p>
)}
</div>
))}
</div>
<fieldset className="mt-8">
<legend className="text-base font-semibold text-body">Hide on the site</legend>
<p className="mt-1 text-sm text-muted">
Ticked parts stay saved but don't show anywhere on the site: your page, team and event lists, people tiles.
</p>
<div className="mt-3 grid gap-2 sm:grid-cols-2">
{HIDE_FIELDS.map(([key, label]) => (
<label key={key} className="flex items-center gap-3 text-body">
<input
type="checkbox"
checked={hidden[key]}
onChange={(e) => setHidden({ ...hidden, [key]: e.target.checked })}
className="h-4 w-4 accent-[var(--color-action)]"
/>
Hide {label.toLowerCase()}
</label>
))}
</div>
</fieldset>
{error && <Alert>{error}</Alert>}
{saved && !error && <Alert tone="ok">Saved. It's on the site now.</Alert>}
<button type="submit" disabled={busy} className={`mt-6 ${primaryButton}`}>
{busy ? 'Saving…' : 'Save profile'}
</button>
</form>
)
}
/* ── Discord ─────────────────────────────────────────────────── */
function Discord({ account, onChange }: { account: MyAccount; onChange: () => void }) {
const [searchParams] = useSearchParams()
const result = searchParams.get('discord')
const [error, setError] = useState<string | null>(null)
const { discord } = account
async function unlink() {
setError(null)
try {
await del('/account/discord')
onChange()
} catch (err) {
setError(message(err))
}
}
return (
<div className="bg-raised p-6 shadow-md">
{discord.id ? (
<div className="flex flex-wrap items-center justify-between gap-4">
<p className="text-body">
Linked to <strong>{discord.name ?? discord.id}</strong>.
</p>
<button type="button" onClick={unlink} className={quietButton}>
Unlink
</button>
</div>
) : discord.enabled ? (
<a href="/api/account/discord" className={`inline-block ${primaryButton}`}>
Link Discord
</a>
) : (
<p className="text-muted">Linking Discord isn't switched on yet. An admin can link it for you.</p>
)}
{result && DISCORD_RESULTS[result] && (
<Alert tone={result === 'linked' ? 'ok' : 'danger'}>{DISCORD_RESULTS[result]}</Alert>
)}
{error && <Alert>{error}</Alert>}
</div>
)
}