mirror of
https://github.com/temetro/temetro.git
synced 2026-07-26 11:58:14 +00:00
frontend: messages search, care-team employee dialog, PCP picker + transfer, activity detail, analytics grid
- Messages: search the inbox and the compose member picker. - Care Team: clickable member rows open an employee dialog showing role + permissions, with change-role (updateMemberRole) and remove. - Patients: Primary Care is now a provider dropdown (defaults to self for a doctor); add a Transfer action + dialog wired to the transfer API. - Activity: entries are clickable, opening a detail dialog. - Analytics: Section takes a columns prop so each row fills evenly (no orphan card in Appointments). - Add lib/staff.ts (listProviders), transferPatient client, rolePermissionSummary helper, and i18n keys for all new strings. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,17 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
type ActivityEntityType,
|
||||
type ActivityEntry,
|
||||
@@ -56,6 +67,14 @@ function formatTime(iso: string): string {
|
||||
return `${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, ${time}`;
|
||||
}
|
||||
|
||||
// Full, unambiguous timestamp for the detail dialog.
|
||||
function formatFullTime(iso: string): string {
|
||||
return new Date(iso).toLocaleString("en-US", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
}
|
||||
|
||||
function Kpi({
|
||||
label,
|
||||
value,
|
||||
@@ -80,9 +99,19 @@ function Kpi({
|
||||
);
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="shrink-0 text-muted-foreground text-xs">{label}</span>
|
||||
<span className="text-right text-foreground text-sm">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ActivityView() {
|
||||
const { t } = useTranslation();
|
||||
const [entries, setEntries] = useState<ActivityEntry[]>([]);
|
||||
const [selected, setSelected] = useState<ActivityEntry | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -166,7 +195,14 @@ export function ActivityView() {
|
||||
{!isLast && <div className="mt-1 w-px flex-1 bg-border" />}
|
||||
</div>
|
||||
|
||||
<div className={cn("flex-1", isLast ? "pb-0" : "pb-6")}>
|
||||
<button
|
||||
className={cn(
|
||||
"-mx-2 flex-1 rounded-lg px-2 py-1 text-left transition-colors hover:bg-accent/40",
|
||||
isLast ? "pb-1" : "mb-5",
|
||||
)}
|
||||
onClick={() => setSelected(entry)}
|
||||
type="button"
|
||||
>
|
||||
<span className="font-medium text-foreground text-sm">
|
||||
{entry.action}
|
||||
</span>
|
||||
@@ -185,12 +221,63 @@ export function ActivityView() {
|
||||
<div className="mt-2 text-muted-foreground text-xs">
|
||||
{formatTime(entry.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
onOpenChange={(o) => !o && setSelected(null)}
|
||||
open={selected !== null}
|
||||
>
|
||||
<DialogPopup className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("activity.detail.title")}</DialogTitle>
|
||||
<DialogDescription>{selected?.action}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-2.5">
|
||||
<DetailRow
|
||||
label={t("activity.detail.person")}
|
||||
value={selected?.actorName ?? ""}
|
||||
/>
|
||||
<DetailRow
|
||||
label={t("activity.detail.record")}
|
||||
value={
|
||||
selected
|
||||
? t(`activity.detail.entityTypes.${selected.entityType}`)
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
{selected?.patientName && (
|
||||
<DetailRow
|
||||
label={t("activity.detail.patient")}
|
||||
value={`${selected.patientName}${
|
||||
selected.patientFileNumber
|
||||
? ` (#${selected.patientFileNumber})`
|
||||
: ""
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
{selected?.entityId && !selected?.patientFileNumber && (
|
||||
<DetailRow
|
||||
label={t("activity.detail.reference")}
|
||||
value={selected.entityId}
|
||||
/>
|
||||
)}
|
||||
<DetailRow
|
||||
label={t("activity.detail.time")}
|
||||
value={selected ? formatFullTime(selected.createdAt) : ""}
|
||||
/>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("activity.detail.close")}
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,13 +24,24 @@ function StatCard({ label, value }: Metric) {
|
||||
);
|
||||
}
|
||||
|
||||
// Each section's grid fills its row evenly: the column count matches the number
|
||||
// of cards so there's never an orphan card on its own row. Static class strings
|
||||
// (no interpolation) so Tailwind can see them.
|
||||
const GRID_BY_COLUMNS: Record<2 | 3 | 4, string> = {
|
||||
2: "grid grid-cols-1 gap-4 sm:grid-cols-2",
|
||||
3: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",
|
||||
4: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",
|
||||
};
|
||||
|
||||
function Section({
|
||||
title,
|
||||
description,
|
||||
columns,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
columns: 2 | 3 | 4;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
@@ -39,9 +50,7 @@ function Section({
|
||||
<h2 className="font-semibold text-lg tracking-tight">{title}</h2>
|
||||
<p className="text-muted-foreground text-sm">{description}</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{children}
|
||||
</div>
|
||||
<div className={GRID_BY_COLUMNS[columns]}>{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -77,6 +86,7 @@ export function AnalysisView() {
|
||||
</div>
|
||||
|
||||
<Section
|
||||
columns={3}
|
||||
description={t("analysis.patientVolume.description")}
|
||||
title={t("analysis.patientVolume.title")}
|
||||
>
|
||||
@@ -122,6 +132,7 @@ export function AnalysisView() {
|
||||
</section>
|
||||
|
||||
<Section
|
||||
columns={4}
|
||||
description={t("analysis.appointments.description")}
|
||||
title={t("analysis.appointments.title")}
|
||||
>
|
||||
@@ -144,6 +155,7 @@ export function AnalysisView() {
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
columns={2}
|
||||
description={t("analysis.prescriptions.description")}
|
||||
title={t("analysis.prescriptions.title")}
|
||||
>
|
||||
@@ -158,6 +170,7 @@ export function AnalysisView() {
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
columns={2}
|
||||
description={t("analysis.tasks.description")}
|
||||
title={t("analysis.tasks.title")}
|
||||
>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { CalendarIcon, Plus, RefreshCw, X } from "lucide-react";
|
||||
import { type FormEvent, type ReactNode, useState } from "react";
|
||||
import { type FormEvent, type ReactNode, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ROLE_LABELS } from "@/lib/access";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
type AllergySeverity,
|
||||
@@ -32,6 +34,7 @@ import {
|
||||
updatePatient,
|
||||
} from "@/lib/patients";
|
||||
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||
import { listProviders, type Provider } from "@/lib/staff";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
type PatientFormDialogProps = {
|
||||
@@ -209,6 +212,8 @@ export function PatientFormDialog({
|
||||
// while the role is still loading to avoid a flash for clinical users.
|
||||
const role = useActiveRole();
|
||||
const showClinical = role == null || hasClinicalAccess(role);
|
||||
const { data: session } = authClient.useSession();
|
||||
const myId = session?.user?.id;
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -222,7 +227,10 @@ export function PatientFormDialog({
|
||||
const [status, setStatus] = useState<Patient["status"]>(
|
||||
patient?.status ?? "active"
|
||||
);
|
||||
const [pcp, setPcp] = useState(patient?.pcp ?? "");
|
||||
// Primary care provider is picked from the clinic's clinicians (drives
|
||||
// per-doctor visibility), not free text. `providerId` is the selected user id.
|
||||
const [providers, setProviders] = useState<Provider[]>([]);
|
||||
const [providerId, setProviderId] = useState(patient?.primaryProviderId ?? "");
|
||||
const [bp, setBp] = useState(patient?.vitals.bp ?? "");
|
||||
const [hr, setHr] = useState(patient?.vitals.hr ?? "");
|
||||
const [temp, setTemp] = useState(patient?.vitals.temp ?? "");
|
||||
@@ -249,18 +257,45 @@ export function PatientFormDialog({
|
||||
})) ?? []
|
||||
);
|
||||
|
||||
// Load the clinic's clinicians for the PCP picker. When creating, default the
|
||||
// PCP to the current user if they're a provider (a doctor registering their
|
||||
// own patient).
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
listProviders()
|
||||
.then((list) => {
|
||||
if (!active) return;
|
||||
setProviders(list);
|
||||
if (!isEdit && myId && list.some((p) => p.userId === myId)) {
|
||||
setProviderId((cur) => cur || myId);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* leave the picker empty; PCP just stays unassigned */
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [isEdit, myId]);
|
||||
|
||||
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!name.trim() || submitting) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedProvider = providers.find((p) => p.userId === providerId);
|
||||
// Display name follows the selected provider; preserve any existing label
|
||||
// when nothing is selected so legacy free-text PCPs aren't wiped on edit.
|
||||
const pcpName = selectedProvider?.name ?? (patient?.pcp || "—");
|
||||
|
||||
const built: Patient = {
|
||||
fileNumber,
|
||||
name: name.trim(),
|
||||
age: Number(age) || 0,
|
||||
sex,
|
||||
pcp: pcp.trim() || "—",
|
||||
pcp: pcpName,
|
||||
primaryProviderId: providerId || null,
|
||||
status,
|
||||
initials: initialsFromName(name),
|
||||
allergies: allergies.filter((a) => a.substance.trim()),
|
||||
@@ -415,11 +450,20 @@ export function PatientFormDialog({
|
||||
</div>
|
||||
|
||||
<Field label={t("patientForm.primaryCare")}>
|
||||
<Input
|
||||
onChange={(event) => setPcp(event.target.value)}
|
||||
placeholder={t("patientForm.primaryCarePlaceholder")}
|
||||
value={pcp}
|
||||
/>
|
||||
<select
|
||||
className={controlClass}
|
||||
onChange={(event) => setProviderId(event.target.value)}
|
||||
value={providerId}
|
||||
>
|
||||
<option value="">
|
||||
{t("patientForm.primaryCareUnassigned")}
|
||||
</option>
|
||||
{providers.map((p) => (
|
||||
<option key={p.userId} value={p.userId}>
|
||||
{p.name} · {ROLE_LABELS[p.role as keyof typeof ROLE_LABELS] ?? p.role}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
|
||||
{showClinical && (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Mail, Plus, SendHorizonal } from "lucide-react";
|
||||
import { Mail, Plus, Search, SendHorizonal } from "lucide-react";
|
||||
import {
|
||||
type FormEvent,
|
||||
useEffect,
|
||||
@@ -68,9 +68,11 @@ export function MessagesView() {
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [messages, setMessages] = useState<ConversationMessage[]>([]);
|
||||
const [showUnreadOnly, setShowUnreadOnly] = useState(false);
|
||||
const [inboxQuery, setInboxQuery] = useState("");
|
||||
const [draft, setDraft] = useState("");
|
||||
const [composeOpen, setComposeOpen] = useState(false);
|
||||
const [members, setMembers] = useState<Participant[]>([]);
|
||||
const [memberQuery, setMemberQuery] = useState("");
|
||||
|
||||
// Refs so the socket handler (registered once) reads current values.
|
||||
const selectedIdRef = useRef<string | null>(null);
|
||||
@@ -135,11 +137,22 @@ export function MessagesView() {
|
||||
const unreadCount = conversations.filter((c) => c.unread).length;
|
||||
const selected = conversations.find((c) => c.id === selectedId) ?? null;
|
||||
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
showUnreadOnly ? conversations.filter((c) => c.unread) : conversations,
|
||||
[conversations, showUnreadOnly],
|
||||
const visible = useMemo(() => {
|
||||
const q = inboxQuery.trim().toLowerCase();
|
||||
return conversations.filter((c) => {
|
||||
if (showUnreadOnly && !c.unread) return false;
|
||||
if (!q) return true;
|
||||
return (
|
||||
c.name.toLowerCase().includes(q) ||
|
||||
(c.lastMessage?.body.toLowerCase().includes(q) ?? false)
|
||||
);
|
||||
});
|
||||
}, [conversations, showUnreadOnly, inboxQuery]);
|
||||
|
||||
const visibleMembers = useMemo(() => {
|
||||
const q = memberQuery.trim().toLowerCase();
|
||||
return q ? members.filter((m) => m.name.toLowerCase().includes(q)) : members;
|
||||
}, [members, memberQuery]);
|
||||
|
||||
const open = (id: string) => {
|
||||
setSelectedId(id);
|
||||
@@ -170,6 +183,7 @@ export function MessagesView() {
|
||||
|
||||
const openCompose = () => {
|
||||
setComposeOpen(true);
|
||||
setMemberQuery("");
|
||||
listClinicMembers()
|
||||
.then(setMembers)
|
||||
.catch(() => setMembers([]));
|
||||
@@ -220,10 +234,25 @@ export function MessagesView() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border border-b px-3 py-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("messages.searchPlaceholder")}
|
||||
className="pl-9"
|
||||
onChange={(e) => setInboxQuery(e.target.value)}
|
||||
placeholder={t("messages.searchPlaceholder")}
|
||||
size="sm"
|
||||
value={inboxQuery}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2">
|
||||
{visible.length === 0 ? (
|
||||
<p className="px-2 py-1.5 text-muted-foreground text-sm">
|
||||
{showUnreadOnly
|
||||
{inboxQuery.trim()
|
||||
? t("messages.noMatches")
|
||||
: showUnreadOnly
|
||||
? t("messages.noUnread")
|
||||
: t("messages.noConversations")}
|
||||
</p>
|
||||
@@ -379,13 +408,29 @@ export function MessagesView() {
|
||||
{t("messages.compose.description")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-1">
|
||||
<DialogPanel className="flex flex-col gap-2">
|
||||
<div className="relative">
|
||||
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label={t("messages.compose.searchPlaceholder")}
|
||||
className="pl-9"
|
||||
onChange={(e) => setMemberQuery(e.target.value)}
|
||||
placeholder={t("messages.compose.searchPlaceholder")}
|
||||
size="sm"
|
||||
value={memberQuery}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex max-h-72 flex-col gap-1 overflow-y-auto">
|
||||
{members.length === 0 ? (
|
||||
<p className="px-1 py-4 text-center text-muted-foreground text-sm">
|
||||
{t("messages.compose.noMembers")}
|
||||
</p>
|
||||
) : visibleMembers.length === 0 ? (
|
||||
<p className="px-1 py-4 text-center text-muted-foreground text-sm">
|
||||
{t("messages.compose.noMatches")}
|
||||
</p>
|
||||
) : (
|
||||
members.map((m) => (
|
||||
visibleMembers.map((m) => (
|
||||
<button
|
||||
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
||||
key={m.id}
|
||||
@@ -401,6 +446,7 @@ export function MessagesView() {
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</DialogPanel>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PatientFormDialog } from "@/components/chat/patient-form-dialog";
|
||||
import { PatientDetail } from "@/components/patients/patient-detail";
|
||||
import { TransferPatientDialog } from "@/components/patients/transfer-patient-dialog";
|
||||
import {
|
||||
Sheet,
|
||||
SheetHeader,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from "@/components/ui/sheet";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { getPatient, type Patient } from "@/lib/patients";
|
||||
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||
|
||||
type Status = "loading" | "ready" | "not-found";
|
||||
|
||||
@@ -54,9 +56,13 @@ export function PatientDetailSheet({
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const role = useActiveRole();
|
||||
// Clinical roles can reassign a chart; show optimistically while role loads.
|
||||
const canTransfer = role == null || hasClinicalAccess(role);
|
||||
const [patient, setPatient] = useState<Patient | null>(null);
|
||||
const [status, setStatus] = useState<Status>("loading");
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [transferOpen, setTransferOpen] = useState(false);
|
||||
// Bumped on open so the editor remounts with the latest patient data.
|
||||
const [editKey, setEditKey] = useState(0);
|
||||
|
||||
@@ -106,6 +112,9 @@ export function PatientDetailSheet({
|
||||
setEditKey((k) => k + 1);
|
||||
setEditOpen(true);
|
||||
}}
|
||||
onTransfer={
|
||||
canTransfer ? () => setTransferOpen(true) : undefined
|
||||
}
|
||||
patient={patient}
|
||||
/>
|
||||
)}
|
||||
@@ -123,6 +132,15 @@ export function PatientDetailSheet({
|
||||
patient={patient}
|
||||
/>
|
||||
)}
|
||||
|
||||
{patient && (
|
||||
<TransferPatientDialog
|
||||
onOpenChange={setTransferOpen}
|
||||
onTransferred={(updated) => setPatient(updated)}
|
||||
open={transferOpen}
|
||||
patient={patient}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Pencil } from "lucide-react";
|
||||
import { ArrowLeftRight, Pencil } from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -81,9 +81,11 @@ function TrendBlock({ trend }: { trend: Trend }) {
|
||||
export function PatientDetail({
|
||||
patient,
|
||||
onEdit,
|
||||
onTransfer,
|
||||
}: {
|
||||
patient: Patient;
|
||||
onEdit?: () => void;
|
||||
onTransfer?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const sex = t(`patientCard.sex.${patient.sex}`);
|
||||
@@ -115,6 +117,18 @@ export function PatientDetail({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{onTransfer && (
|
||||
<Button
|
||||
onClick={onTransfer}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<ArrowLeftRight className="size-4" />
|
||||
{t("patients.transfer.action")}
|
||||
</Button>
|
||||
)}
|
||||
{onEdit && (
|
||||
<Button onClick={onEdit} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" />
|
||||
@@ -122,6 +136,7 @@ export function PatientDetail({
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Section title={t("patientCard.overview")}>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, 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 { ROLE_LABELS } from "@/lib/access";
|
||||
import { type Patient, transferPatient } from "@/lib/patients";
|
||||
import { listProviders, type Provider } from "@/lib/staff";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
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 = {
|
||||
patient: Patient;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onTransferred: (patient: Patient) => void;
|
||||
};
|
||||
|
||||
// Reassign a patient to another clinician. The new provider becomes the
|
||||
// patient's primary provider (and PCP label), which moves the chart into their
|
||||
// panel under per-doctor visibility.
|
||||
export function TransferPatientDialog({
|
||||
patient,
|
||||
open,
|
||||
onOpenChange,
|
||||
onTransferred,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [providers, setProviders] = useState<Provider[]>([]);
|
||||
const [providerId, setProviderId] = useState(patient.primaryProviderId ?? "");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setProviderId(patient.primaryProviderId ?? "");
|
||||
setError(null);
|
||||
let active = true;
|
||||
listProviders()
|
||||
.then((list) => active && setProviders(list))
|
||||
.catch(() => active && setProviders([]));
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [open, patient.primaryProviderId]);
|
||||
|
||||
const submit = async () => {
|
||||
if (!providerId || submitting) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await transferPatient(patient.fileNumber, providerId);
|
||||
onTransferred(updated);
|
||||
notify.success(
|
||||
t("patients.transfer.successTitle"),
|
||||
t("patients.transfer.successBody", {
|
||||
name: updated.name,
|
||||
provider: updated.pcp,
|
||||
}),
|
||||
);
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : t("patients.transfer.error");
|
||||
setError(message);
|
||||
notify.error(t("patients.transfer.errorTitle"), message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogPopup className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("patients.transfer.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("patients.transfer.description", { name: patient.name })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="flex flex-col gap-3">
|
||||
{error && (
|
||||
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("patients.transfer.providerLabel")}
|
||||
</span>
|
||||
<select
|
||||
className={selectClass}
|
||||
onChange={(e) => setProviderId(e.target.value)}
|
||||
value={providerId}
|
||||
>
|
||||
<option value="">{t("patients.transfer.choose")}</option>
|
||||
{providers.map((p) => (
|
||||
<option key={p.userId} value={p.userId}>
|
||||
{p.name} ·{" "}
|
||||
{ROLE_LABELS[p.role as keyof typeof ROLE_LABELS] ?? p.role}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("patients.transfer.cancel")}
|
||||
</DialogClose>
|
||||
<Button
|
||||
disabled={
|
||||
submitting ||
|
||||
!providerId ||
|
||||
providerId === patient.primaryProviderId
|
||||
}
|
||||
onClick={submit}
|
||||
type="button"
|
||||
>
|
||||
{submitting
|
||||
? t("patients.transfer.transferring")
|
||||
: t("patients.transfer.confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ROLE_LABELS } from "@/lib/access";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { PROVISIONABLE_ROLES, rolePermissionSummary } from "@/lib/roles";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
// One row of /api/staff — shared with the Care Team panel.
|
||||
export type StaffMember = {
|
||||
id: string;
|
||||
userId: string;
|
||||
role: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
username: string | null;
|
||||
};
|
||||
|
||||
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";
|
||||
|
||||
function roleLabel(role?: string | null): string {
|
||||
if (!role) return ROLE_LABELS.member;
|
||||
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
|
||||
}
|
||||
|
||||
function initials(name?: string | null, email?: string | null): string {
|
||||
const source = name?.trim() || email?.trim() || "?";
|
||||
return (
|
||||
source
|
||||
.split(/\s+/)
|
||||
.map((w) => w[0])
|
||||
.filter(Boolean)
|
||||
.join("")
|
||||
.slice(0, 2)
|
||||
.toUpperCase() || "?"
|
||||
);
|
||||
}
|
||||
|
||||
type Props = {
|
||||
member: StaffMember | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
// True when the viewer may change/remove this member (admin, not self, not an
|
||||
// owner). When false the dialog is read-only.
|
||||
editable: boolean;
|
||||
onChanged: () => void;
|
||||
onRemove: (member: StaffMember) => void;
|
||||
};
|
||||
|
||||
// Admin-facing detail view for a single clinic member: shows who they are, what
|
||||
// their role lets them do, and (when editable) lets an admin change the role —
|
||||
// which swaps the whole permission bundle — or remove them.
|
||||
export function EmployeeDetailDialog({
|
||||
member,
|
||||
open,
|
||||
onOpenChange,
|
||||
editable,
|
||||
onChanged,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [role, setRole] = useState<string>(member?.role ?? "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setRole(member?.role ?? "");
|
||||
}, [member?.id, member?.role]);
|
||||
|
||||
const summary = rolePermissionSummary(member?.role);
|
||||
const secondary = member?.username ? `@${member.username}` : member?.email;
|
||||
// Keep the member's current role selectable even if it isn't admin-assignable
|
||||
// (e.g. the "member"/Clinician role).
|
||||
const roleOptions = Array.from(
|
||||
new Set([member?.role, ...PROVISIONABLE_ROLES].filter(Boolean) as string[]),
|
||||
);
|
||||
|
||||
const changeRole = async () => {
|
||||
if (!member || saving || role === member.role) return;
|
||||
setSaving(true);
|
||||
const { error } = await authClient.organization.updateMemberRole({
|
||||
memberId: member.id,
|
||||
role,
|
||||
});
|
||||
setSaving(false);
|
||||
if (error) {
|
||||
notify.error(
|
||||
t("settings.careTeam.employee.roleFailedTitle"),
|
||||
error.message ?? t("settings.careTeam.employee.roleFailedBody"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
notify.success(
|
||||
t("settings.careTeam.employee.roleUpdatedTitle"),
|
||||
t("settings.careTeam.employee.roleUpdatedBody", {
|
||||
name: member.name ?? member.email ?? "",
|
||||
role: roleLabel(role),
|
||||
}),
|
||||
);
|
||||
onChanged();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogPopup className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("settings.careTeam.employee.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("settings.careTeam.employee.description")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogPanel className="flex flex-col gap-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="size-10">
|
||||
<AvatarFallback>
|
||||
{initials(member?.name, member?.email)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">
|
||||
{member?.name || member?.email || member?.userId}
|
||||
</p>
|
||||
{secondary && (
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{secondary}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Badge className="capitalize" variant="secondary">
|
||||
{roleLabel(member?.role)}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
{t("settings.careTeam.employee.permissions")}
|
||||
</span>
|
||||
<div className="flex flex-col gap-1.5 rounded-2xl border bg-card/30 px-3 py-2.5">
|
||||
{summary.map(({ resource, actions }) => (
|
||||
<div
|
||||
className="flex items-center justify-between gap-3"
|
||||
key={resource}
|
||||
>
|
||||
<span className="text-sm text-foreground">
|
||||
{t(`settings.careTeam.employee.resources.${resource}`)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{actions.length === 0
|
||||
? t("settings.careTeam.employee.noAccess")
|
||||
: actions
|
||||
.map((a) =>
|
||||
t(`settings.careTeam.employee.actions.${a}`),
|
||||
)
|
||||
.join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editable && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
{t("settings.careTeam.employee.changeRole")}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
aria-label={t("settings.careTeam.employee.changeRole")}
|
||||
className={selectClass}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
value={role}
|
||||
>
|
||||
{roleOptions.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{roleLabel(r)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
disabled={saving || role === member?.role}
|
||||
onClick={changeRole}
|
||||
type="button"
|
||||
>
|
||||
{saving
|
||||
? t("settings.careTeam.employee.saving")
|
||||
: t("settings.careTeam.employee.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter>
|
||||
{editable && member && (
|
||||
<Button
|
||||
className="sm:mr-auto"
|
||||
onClick={() => onRemove(member)}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
{t("settings.careTeam.employee.remove")}
|
||||
</Button>
|
||||
)}
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("settings.careTeam.employee.close")}
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { UserPlus, X } from "lucide-react";
|
||||
import { UserPlus } from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { AddStaffDialog } from "@/components/settings/add-staff-dialog";
|
||||
import {
|
||||
EmployeeDetailDialog,
|
||||
type StaffMember,
|
||||
} from "@/components/settings/employee-detail-dialog";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsSection,
|
||||
@@ -26,17 +30,6 @@ import { apiFetch } from "@/lib/api-client";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
// 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;
|
||||
userId: string;
|
||||
role: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
username: string | null;
|
||||
};
|
||||
|
||||
function roleLabel(role?: string | null): string {
|
||||
if (!role) return ROLE_LABELS.member;
|
||||
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
|
||||
@@ -62,6 +55,7 @@ export function CareTeamPanel() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [selected, setSelected] = useState<StaffMember | null>(null);
|
||||
const [pendingRemove, setPendingRemove] = useState<StaffMember | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
|
||||
@@ -142,14 +136,14 @@ export function CareTeamPanel() {
|
||||
// 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}>
|
||||
const body = (
|
||||
<>
|
||||
<Avatar className="size-8">
|
||||
<AvatarFallback>
|
||||
{initials(m.name, m.email)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="min-w-0 flex-1 text-left">
|
||||
<p className="truncate text-sm font-medium">
|
||||
{m.name || m.email || m.userId}
|
||||
{isSelf && (
|
||||
@@ -167,17 +161,22 @@ export function CareTeamPanel() {
|
||||
<Badge className="capitalize" variant="secondary">
|
||||
{roleLabel(m.role)}
|
||||
</Badge>
|
||||
{canManage && !isSelf && m.role !== "owner" && (
|
||||
<Button
|
||||
aria-label={t("settings.careTeam.removeMember")}
|
||||
onClick={() => setPendingRemove(m)}
|
||||
size="icon-sm"
|
||||
</>
|
||||
);
|
||||
// Admins click a row to open the employee detail dialog (view
|
||||
// permissions, change role, remove). Non-managers see a static row.
|
||||
return canManage ? (
|
||||
<button
|
||||
className="flex w-full items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50"
|
||||
key={m.id}
|
||||
onClick={() => setSelected(m)}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 px-4 py-3" key={m.id}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
@@ -192,6 +191,23 @@ export function CareTeamPanel() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Click a member to view details, change role, or remove. */}
|
||||
<EmployeeDetailDialog
|
||||
editable={
|
||||
canManage &&
|
||||
selected?.userId !== session?.user?.id &&
|
||||
selected?.role !== "owner"
|
||||
}
|
||||
member={selected}
|
||||
onChanged={() => void load()}
|
||||
onOpenChange={(o) => !o && setSelected(null)}
|
||||
onRemove={(m) => {
|
||||
setSelected(null);
|
||||
setPendingRemove(m);
|
||||
}}
|
||||
open={selected !== null}
|
||||
/>
|
||||
|
||||
{/* Confirm before removing a member — destructive and not reversible. */}
|
||||
<Dialog
|
||||
onOpenChange={(o) => !o && setPendingRemove(null)}
|
||||
|
||||
@@ -187,6 +187,20 @@
|
||||
"notFound": "Patient not found",
|
||||
"loading": "Loading patient…",
|
||||
"noPatientForFile": "No patient found for file #{{number}}."
|
||||
},
|
||||
"transfer": {
|
||||
"action": "Transfer",
|
||||
"title": "Transfer patient",
|
||||
"description": "Reassign {{name}} to another clinician. They become this patient's primary provider.",
|
||||
"providerLabel": "New primary provider",
|
||||
"choose": "Choose a provider…",
|
||||
"cancel": "Cancel",
|
||||
"confirm": "Transfer patient",
|
||||
"transferring": "Transferring…",
|
||||
"successTitle": "Patient transferred",
|
||||
"successBody": "{{name}} is now with {{provider}}.",
|
||||
"errorTitle": "Couldn't transfer patient",
|
||||
"error": "Please try again."
|
||||
}
|
||||
},
|
||||
"appointments": {
|
||||
@@ -366,6 +380,8 @@
|
||||
"inbox": "Inbox",
|
||||
"unread": "Unread · {{count}}",
|
||||
"newMessage": "New message",
|
||||
"searchPlaceholder": "Search conversations",
|
||||
"noMatches": "No conversations match your search.",
|
||||
"noUnread": "No unread messages.",
|
||||
"noConversations": "No conversations yet.",
|
||||
"you": "You: ",
|
||||
@@ -378,6 +394,8 @@
|
||||
"compose": {
|
||||
"title": "New message",
|
||||
"description": "Start a conversation with a member of your clinic.",
|
||||
"searchPlaceholder": "Search people",
|
||||
"noMatches": "No people match your search.",
|
||||
"noMembers": "No other clinic members yet. Invite colleagues from Settings → Care team."
|
||||
},
|
||||
"startFailedTitle": "Couldn't start conversation",
|
||||
@@ -430,7 +448,23 @@
|
||||
"changesToday": "Changes today",
|
||||
"thisWeek": "This week",
|
||||
"totalRecorded": "Total recorded",
|
||||
"empty": "No activity yet. Changes to patients, notes, appointments, prescriptions and tasks will appear here."
|
||||
"empty": "No activity yet. Changes to patients, notes, appointments, prescriptions and tasks will appear here.",
|
||||
"detail": {
|
||||
"title": "Activity detail",
|
||||
"person": "Performed by",
|
||||
"record": "Record type",
|
||||
"patient": "Patient",
|
||||
"reference": "Reference",
|
||||
"time": "Time",
|
||||
"close": "Close",
|
||||
"entityTypes": {
|
||||
"patient": "Patient",
|
||||
"note": "Note",
|
||||
"appointment": "Appointment",
|
||||
"prescription": "Prescription",
|
||||
"task": "Task"
|
||||
}
|
||||
}
|
||||
},
|
||||
"notes": {
|
||||
"title": "Notes",
|
||||
@@ -603,6 +637,7 @@
|
||||
"status": "Status",
|
||||
"primaryCare": "Primary care",
|
||||
"primaryCarePlaceholder": "e.g. Dr. Lena Ortiz",
|
||||
"primaryCareUnassigned": "Unassigned",
|
||||
"currentVitals": "Current vitals",
|
||||
"bp": "Blood pressure",
|
||||
"hr": "Heart rate",
|
||||
@@ -725,6 +760,32 @@
|
||||
"you": "(you)",
|
||||
"addMember": "Add team member",
|
||||
"removeMember": "Remove member",
|
||||
"employee": {
|
||||
"title": "Team member",
|
||||
"description": "View this member's access, change their role, or remove them.",
|
||||
"permissions": "Permissions",
|
||||
"noAccess": "No access",
|
||||
"changeRole": "Change role",
|
||||
"save": "Save",
|
||||
"saving": "Saving…",
|
||||
"remove": "Remove employee",
|
||||
"close": "Close",
|
||||
"roleUpdatedTitle": "Role updated",
|
||||
"roleUpdatedBody": "{{name}} is now {{role}}.",
|
||||
"roleFailedTitle": "Couldn't update role",
|
||||
"roleFailedBody": "Please try again.",
|
||||
"resources": {
|
||||
"patient": "Patients",
|
||||
"appointment": "Appointments",
|
||||
"prescription": "Prescriptions",
|
||||
"task": "Tasks"
|
||||
},
|
||||
"actions": {
|
||||
"read": "View",
|
||||
"write": "Edit",
|
||||
"delete": "Delete"
|
||||
}
|
||||
},
|
||||
"remove": {
|
||||
"title": "Remove team member?",
|
||||
"description": "{{name}} will lose access to this clinic. This can't be undone.",
|
||||
|
||||
@@ -62,7 +62,8 @@ export type Patient = {
|
||||
name: string;
|
||||
age: number;
|
||||
sex: "M" | "F";
|
||||
pcp: string; // primary care provider
|
||||
pcp: string; // primary care provider (display name)
|
||||
primaryProviderId?: string | null; // user id of the responsible clinician
|
||||
status: "active" | "inpatient" | "discharged";
|
||||
initials: string; // for AvatarFallback
|
||||
allergies: Allergy[];
|
||||
@@ -112,6 +113,20 @@ export async function updatePatient(patient: Patient): Promise<Patient> {
|
||||
);
|
||||
}
|
||||
|
||||
// Reassign a patient to another clinician (sets their primary provider + PCP).
|
||||
export async function transferPatient(
|
||||
fileNumber: string,
|
||||
providerId: string,
|
||||
): Promise<Patient> {
|
||||
return apiFetch<Patient>(
|
||||
`/api/patients/${encodeURIComponent(fileNumber)}/transfer`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ providerId }),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Suggest a unique-ish 5-digit file number for new charts. The server is the
|
||||
// source of truth and rejects collisions with a 409.
|
||||
export function generateFileNumber(): string {
|
||||
|
||||
@@ -45,6 +45,42 @@ export function useActiveRole(): string | null {
|
||||
return role;
|
||||
}
|
||||
|
||||
// The clinical resources + actions we surface in the Care Team permissions
|
||||
// summary. Mirrors the statements in lib/access.ts.
|
||||
export const CLINICAL_RESOURCES = [
|
||||
"patient",
|
||||
"appointment",
|
||||
"prescription",
|
||||
"task",
|
||||
] as const;
|
||||
const RESOURCE_ACTIONS = ["read", "write", "delete"] as const;
|
||||
|
||||
type PermissionArg = Parameters<
|
||||
typeof authClient.organization.checkRolePermission
|
||||
>[0]["permissions"];
|
||||
|
||||
// For a given role, the allowed actions on each clinical resource — computed
|
||||
// from Better Auth so it stays in lock-step with lib/access.ts. Used by the
|
||||
// Care Team employee dialog to show what a role can do.
|
||||
export function rolePermissionSummary(
|
||||
role: string | null | undefined,
|
||||
): { resource: (typeof CLINICAL_RESOURCES)[number]; actions: string[] }[] {
|
||||
if (!role) return [];
|
||||
return CLINICAL_RESOURCES.map((resource) => {
|
||||
const actions = RESOURCE_ACTIONS.filter((action) => {
|
||||
try {
|
||||
return authClient.organization.checkRolePermission({
|
||||
role: role as RoleKey,
|
||||
permissions: { [resource]: [action] } as PermissionArg,
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return { resource, actions };
|
||||
});
|
||||
}
|
||||
|
||||
// Whether a role may see clinical records (AI lookup, prescriptions, notes,
|
||||
// analysis). Driven by Better Auth permissions so it stays in lock-step with
|
||||
// lib/access.ts: the `reception` role has no `prescription` statement, so this
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { apiFetch } from "@/lib/api-client";
|
||||
|
||||
// A clinician who can be assigned as a patient's primary provider. Returned by
|
||||
// the backend's GET /api/staff/providers (clinical roles only — excludes
|
||||
// reception/viewer). Readable by any clinic member.
|
||||
export type Provider = {
|
||||
userId: string;
|
||||
name: string;
|
||||
role: string;
|
||||
};
|
||||
|
||||
export function listProviders(): Promise<Provider[]> {
|
||||
return apiFetch<Provider[]>("/api/staff/providers");
|
||||
}
|
||||
Reference in New Issue
Block a user