feat: admin-provisioned staff, username login & role-based access

Replace the email-invitation flow with admin-provisioned staff accounts and
add role-based access that changes what each member sees.

Backend:
- Enable Better Auth `username` plugin (staff sign in by username); regenerate
  auth schema (+ username/displayUsername on user) and migration 0007.
- Add `doctor` and `reception` roles to the access-control RBAC. `reception` is
  scoped to scheduling + registration (no `prescription` statement).
- New `/api/staff` route: POST creates a user (auth.api.signUpEmail) and adds
  them to the active clinic (auth.api.addMember); GET lists members + usernames.
  Gated by requirePermission({ member: ["create"] }).
- Redact clinical PHI for the reception role in the patients service (read,
  create and update) so demographics-only is enforced server-side.

Frontend:
- usernameClient + Email|Username tabs on the login form.
- lib/roles.ts: useActiveRole + Better-Auth-permission-driven nav visibility,
  default landing, and a route guard (reception -> /appointments, blocked from
  clinical routes). Applied to the sidebar, command palette and auth guard.
- Care team page now provisions staff via a two-step Add-team-member dialog
  (details -> username/password) hitting /api/staff; removes the email-invite
  and pending-invitation UI. New members are contactable from Messages
  automatically (they become org members).
- Hide clinical sections of the patient form and the admin-only settings tabs
  for non-clinical/non-admin roles.

All permission management stays in Better Auth (per the better-auth skills now
referenced in backend/CLAUDE.md).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-08 19:12:07 +03:00
parent ab2f10bffc
commit 6213da9477
24 changed files with 3338 additions and 180 deletions
@@ -0,0 +1,235 @@
"use client";
import { type FormEvent, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "@/components/ui/dialog";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { ROLE_LABELS } from "@/lib/access";
import { apiFetch } from "@/lib/api-client";
import { PROVISIONABLE_ROLES } from "@/lib/roles";
import { notify } from "@/lib/toast";
const MIN_PASSWORD = 12;
const MIN_USERNAME = 3;
const selectClass =
"h-9 w-full rounded-3xl border border-transparent bg-input/50 px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30";
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
onCreated?: () => void;
};
// Admin provisions a staff account in two steps: first the "invitation" (who +
// what role), then the credentials (username + password) the employee uses to
// sign in. Posts to /api/staff, which creates the account and adds them to the
// active clinic via Better Auth.
export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
const { t } = useTranslation();
const [step, setStep] = useState<1 | 2>(1);
const [name, setName] = useState("");
const [role, setRole] = useState<string>("reception");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const reset = () => {
setStep(1);
setName("");
setRole("reception");
setUsername("");
setPassword("");
setError(null);
setSubmitting(false);
};
const handleOpenChange = (next: boolean) => {
if (!next) reset();
onOpenChange(next);
};
const submit = async (event: FormEvent) => {
event.preventDefault();
setError(null);
// Step 1 → advance to credentials.
if (step === 1) {
if (!name.trim()) {
setError(t("settings.careTeam.add.nameRequired"));
return;
}
setStep(2);
return;
}
// Step 2 → create the account.
if (username.trim().length < MIN_USERNAME) {
setError(t("settings.careTeam.add.usernameTooShort", { count: MIN_USERNAME }));
return;
}
if (password.length < MIN_PASSWORD) {
setError(t("settings.careTeam.add.passwordTooShort", { count: MIN_PASSWORD }));
return;
}
setSubmitting(true);
try {
await apiFetch("/api/staff", {
method: "POST",
body: JSON.stringify({
name: name.trim(),
role,
username: username.trim(),
password,
}),
});
notify.success(
t("settings.careTeam.add.createdTitle"),
t("settings.careTeam.add.createdBody", {
name: name.trim(),
username: username.trim().toLowerCase(),
}),
);
onCreated?.();
handleOpenChange(false);
} catch (err) {
const message =
err instanceof Error ? err.message : t("settings.careTeam.add.error");
setError(message);
notify.error(t("settings.careTeam.add.errorTitle"), message);
setSubmitting(false);
}
};
return (
<Dialog onOpenChange={handleOpenChange} open={open}>
<DialogPopup className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t("settings.careTeam.add.title")}</DialogTitle>
<DialogDescription>
{step === 1
? t("settings.careTeam.add.step1Description")
: t("settings.careTeam.add.step2Description")}
</DialogDescription>
</DialogHeader>
<form className="contents" onSubmit={submit}>
<DialogPanel className="flex flex-col gap-4">
{error && (
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
{step === 1 ? (
<>
<Field className="w-full">
<FieldLabel htmlFor="staff-name">
{t("settings.careTeam.add.nameLabel")}
</FieldLabel>
<Input
autoFocus
id="staff-name"
onChange={(e) => setName(e.target.value)}
placeholder={t("settings.careTeam.add.namePlaceholder")}
required
value={name}
/>
</Field>
<Field className="w-full">
<FieldLabel htmlFor="staff-role">
{t("settings.careTeam.add.roleLabel")}
</FieldLabel>
<select
className={selectClass}
id="staff-role"
onChange={(e) => setRole(e.target.value)}
value={role}
>
{PROVISIONABLE_ROLES.map((r) => (
<option key={r} value={r}>
{ROLE_LABELS[r]}
</option>
))}
</select>
</Field>
</>
) : (
<>
<Field className="w-full">
<FieldLabel htmlFor="staff-username">
{t("settings.careTeam.add.usernameLabel")}
</FieldLabel>
<Input
autoComplete="off"
autoFocus
id="staff-username"
onChange={(e) => setUsername(e.target.value)}
placeholder={t("settings.careTeam.add.usernamePlaceholder")}
required
value={username}
/>
</Field>
<Field className="w-full">
<FieldLabel htmlFor="staff-password">
{t("settings.careTeam.add.passwordLabel")}
</FieldLabel>
<Input
autoComplete="new-password"
id="staff-password"
onChange={(e) => setPassword(e.target.value)}
required
type="password"
value={password}
/>
<FieldDescription>
{t("settings.careTeam.add.passwordHint", { count: MIN_PASSWORD })}
</FieldDescription>
</Field>
</>
)}
</DialogPanel>
<DialogFooter>
{step === 2 && (
<Button
onClick={() => {
setStep(1);
setError(null);
}}
type="button"
variant="outline"
>
{t("settings.careTeam.add.back")}
</Button>
)}
<DialogClose render={<Button type="button" variant="ghost" />}>
{t("settings.careTeam.add.cancel")}
</DialogClose>
<Button disabled={submitting} type="submit">
{step === 1
? t("settings.careTeam.add.next")
: submitting
? t("settings.careTeam.add.creating")
: t("settings.careTeam.add.create")}
</Button>
</DialogFooter>
</form>
</DialogPopup>
</Dialog>
);
}
@@ -1,9 +1,10 @@
"use client";
import { X } from "lucide-react";
import { type FormEvent, useCallback, useEffect, useState } from "react";
import { UserPlus, X } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { AddStaffDialog } from "@/components/settings/add-staff-dialog";
import {
SettingsCard,
SettingsSection,
@@ -11,27 +12,23 @@ import {
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ROLE_LABELS } from "@/lib/access";
import { apiFetch } from "@/lib/api-client";
import { authClient } from "@/lib/auth-client";
type Member = {
// One row of /api/staff — clinic members joined to their user record (incl. the
// username admin-provisioned staff sign in with).
type StaffMember = {
id: string;
role: string;
userId: string;
user?: { name?: string | null; email?: string | null };
role: string;
name: string | null;
email: string | null;
username: string | null;
};
type Invite = {
id: string;
email: string;
role?: string | null;
status: string;
};
const INVITE_ROLES = ["member", "admin", "viewer"] as const;
function roleLabel(role?: string | null): string {
if (!role) return "Member";
if (!role) return ROLE_LABELS.member;
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
}
@@ -51,32 +48,24 @@ function initials(name?: string | null, email?: string | null): string {
export function CareTeamPanel() {
const { t } = useTranslation();
const { data: session } = authClient.useSession();
const [members, setMembers] = useState<Member[]>([]);
const [invites, setInvites] = useState<Invite[]>([]);
const [members, setMembers] = useState<StaffMember[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [email, setEmail] = useState("");
const [role, setRole] = useState<(typeof INVITE_ROLES)[number]>("member");
const [inviting, setInviting] = useState(false);
const [adding, setAdding] = useState(false);
const load = useCallback(async () => {
const { data, error: err } =
await authClient.organization.getFullOrganization();
if (err || !data) {
setError(err?.message ?? t("settings.careTeam.loadError"));
try {
const data = await apiFetch<StaffMember[]>("/api/staff");
setMembers(data);
setError(null);
} catch (err) {
setError(
err instanceof Error ? err.message : t("settings.careTeam.loadError"),
);
} finally {
setLoading(false);
return;
}
setMembers((data.members ?? []) as Member[]);
setInvites(
((data.invitations ?? []) as Invite[]).filter(
(i) => i.status === "pending"
)
);
setError(null);
setLoading(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
@@ -86,36 +75,11 @@ export function CareTeamPanel() {
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
const canManage = myRole === "owner" || myRole === "admin";
const invite = async (event: FormEvent) => {
event.preventDefault();
if (!email.trim() || inviting) return;
setInviting(true);
setNotice(null);
setError(null);
const { error: err } = await authClient.organization.inviteMember({
email: email.trim(),
role,
});
setInviting(false);
if (err) {
setError(err.message ?? t("settings.careTeam.inviteError"));
return;
}
setEmail("");
setNotice(t("settings.careTeam.inviteSent", { email: email.trim() }));
void load();
};
const removeMember = async (memberId: string) => {
await authClient.organization.removeMember({ memberIdOrEmail: memberId });
void load();
};
const cancelInvite = async (invitationId: string) => {
await authClient.organization.cancelInvitation({ invitationId });
void load();
};
return (
<SettingsSection
description={t("settings.careTeam.description")}
@@ -126,46 +90,14 @@ export function CareTeamPanel() {
{error}
</p>
)}
{notice && (
<p className="rounded-2xl bg-primary/10 px-3 py-2 text-sm text-primary">
{notice}
</p>
)}
{canManage && (
<SettingsCard className="p-4">
<form
className="flex flex-col gap-2 sm:flex-row sm:items-center"
onSubmit={invite}
>
<Input
className="flex-1"
onChange={(e) => setEmail(e.target.value)}
placeholder={t("settings.careTeam.invitePlaceholder")}
required
type="email"
value={email}
/>
<select
className="h-9 rounded-3xl border border-transparent bg-input/50 px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30"
onChange={(e) =>
setRole(e.target.value as (typeof INVITE_ROLES)[number])
}
value={role}
>
{INVITE_ROLES.map((r) => (
<option key={r} value={r}>
{roleLabel(r)}
</option>
))}
</select>
<Button disabled={inviting} type="submit">
{inviting
? t("settings.careTeam.inviting")
: t("settings.careTeam.invite")}
</Button>
</form>
</SettingsCard>
<div className="flex justify-end">
<Button onClick={() => setAdding(true)} type="button">
<UserPlus className="size-4" />
{t("settings.careTeam.addMember")}
</Button>
</div>
)}
<SettingsCard className="divide-y divide-border">
@@ -176,25 +108,28 @@ export function CareTeamPanel() {
) : (
members.map((m) => {
const isSelf = m.userId === session?.user?.id;
// Prefer the login username; fall back to email for owners who
// signed up by email.
const secondary = m.username ? `@${m.username}` : m.email;
return (
<div className="flex items-center gap-3 px-4 py-3" key={m.id}>
<Avatar className="size-8">
<AvatarFallback>
{initials(m.user?.name, m.user?.email)}
{initials(m.name, m.email)}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{m.user?.name || m.user?.email || m.userId}
{m.name || m.email || m.userId}
{isSelf && (
<span className="ml-1 text-xs text-muted-foreground">
{t("settings.careTeam.you")}
</span>
)}
</p>
{m.user?.email && (
{secondary && (
<p className="truncate text-xs text-muted-foreground">
{m.user.email}
{secondary}
</p>
)}
</div>
@@ -218,33 +153,12 @@ export function CareTeamPanel() {
)}
</SettingsCard>
{invites.length > 0 && (
<SettingsCard className="divide-y divide-border">
<p className="px-4 py-2.5 text-xs font-medium tracking-wide text-muted-foreground uppercase">
{t("settings.careTeam.pendingInvitations")}
</p>
{invites.map((inv) => (
<div className="flex items-center gap-3 px-4 py-3" key={inv.id}>
<div className="min-w-0 flex-1">
<p className="truncate text-sm">{inv.email}</p>
</div>
<Badge className="capitalize" variant="outline">
{roleLabel(inv.role)}
</Badge>
{canManage && (
<Button
aria-label={t("settings.careTeam.cancelInvitation")}
onClick={() => cancelInvite(inv.id)}
size="icon-sm"
type="button"
variant="ghost"
>
<X className="size-4" />
</Button>
)}
</div>
))}
</SettingsCard>
{canManage && (
<AddStaffDialog
onCreated={() => void load()}
onOpenChange={setAdding}
open={adding}
/>
)}
</SettingsSection>
);
+16 -8
View File
@@ -11,6 +11,7 @@ import {
import { SigningPanel } from "@/components/settings/settings-billing";
import { CareTeamPanel } from "@/components/settings/settings-care-team";
import { ProfilePanel } from "@/components/settings/settings-preferences";
import { useActiveRole } from "@/lib/roles";
const TABS = [
{ id: "profile", labelKey: "settings.tabs.profile" },
@@ -41,20 +42,27 @@ function PlaceholderPanel({
export function SettingsView() {
const { t } = useTranslation();
const role = useActiveRole();
const [tab, setTab] = useState<Tab>("profile");
// Only clinic owners/admins manage clinic-wide settings (care team, records,
// signing, developers). Everyone else gets their own profile only.
const isAdmin = role === "owner" || role === "admin";
const visibleTabs = isAdmin ? TABS : TABS.filter((item) => item.id === "profile");
const activeTab = visibleTabs.some((item) => item.id === tab) ? tab : "profile";
return (
<div className="mx-auto w-full max-w-3xl px-6 py-10">
<div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
<h1 className="text-2xl font-semibold tracking-tight">
{t(`settings.tabs.${tab}`)}
{t(`settings.tabs.${activeTab}`)}
</h1>
<nav className="flex flex-wrap items-center gap-1">
{TABS.map((item) => (
{visibleTabs.map((item) => (
<button
className={cn(
"rounded-lg px-3 py-1.5 text-sm transition-colors",
tab === item.id
activeTab === item.id
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground"
)}
@@ -69,16 +77,16 @@ export function SettingsView() {
</div>
<div className="mt-10 space-y-12">
{tab === "profile" && <ProfilePanel />}
{tab === "records" && (
{activeTab === "profile" && <ProfilePanel />}
{activeTab === "records" && (
<PlaceholderPanel
description={t("settings.records.description")}
title={t("settings.tabs.records")}
/>
)}
{tab === "signing" && <SigningPanel />}
{tab === "careTeam" && <CareTeamPanel />}
{tab === "developers" && (
{activeTab === "signing" && <SigningPanel />}
{activeTab === "careTeam" && <CareTeamPanel />}
{activeTab === "developers" && (
<PlaceholderPanel
description={t("settings.developers.description")}
title={t("settings.tabs.developers")}