fix: clinic creation gating, analysis line charts, username + task assignee, delete confirm

- Hide "Create clinic" (sidebar footer) for non-admins; only owner/admin can
  spin up additional clinics. Onboarding for brand-new users is unaffected.
- Analysis: drop the bar charts; show line charts (Sparkline) inside KPI cards
  that open a detail dialog with the full chart + per-point breakdown.
- Add Team Member: validate the username client-side (no spaces; letters,
  numbers, dots, underscores) with a clear warning + field hint.
- Tasks: New Task now has an Assignee selector (Myself / Other → department).
  Tasks are visible to the department they're assigned to (or the creator), and
  show who created them. Backend adds assignee_role + created_by_name with
  visibility filtering in listTasks; owners/admins see all.
- Care team: removing a member now asks for confirmation first (dialog) and
  surfaces success/failure + refreshes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-08 19:52:12 +03:00
parent 8ab0552cf8
commit 4f8793c765
19 changed files with 2878 additions and 144 deletions
+27 -40
View File
@@ -3,7 +3,7 @@
import { type ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { BarChart } from "@/components/analysis/bar-chart";
import { TrendCard } from "@/components/analysis/trend-card";
import { Card } from "@/components/ui/card";
import { type Analytics, getAnalytics } from "@/lib/analytics";
@@ -46,26 +46,6 @@ function Section({
);
}
// A full-width section that frames a single chart in a card.
function ChartSection({
title,
description,
children,
}: {
title: string;
description: string;
children: ReactNode;
}) {
return (
<section className="flex flex-col gap-3">
<div>
<h2 className="font-semibold text-lg tracking-tight">{title}</h2>
<p className="text-muted-foreground text-sm">{description}</p>
</div>
<Card className="p-5">{children}</Card>
</section>
);
}
export function AnalysisView() {
const { t } = useTranslation();
@@ -114,15 +94,32 @@ export function AnalysisView() {
/>
</Section>
<ChartSection
description={t("analysis.charts.patientGrowthDescription")}
title={t("analysis.charts.patientGrowthTitle")}
>
<BarChart
data={data?.trends.patientsByMonth ?? []}
emptyLabel={t("analysis.charts.empty")}
/>
</ChartSection>
<section className="flex flex-col gap-3">
<div>
<h2 className="font-semibold text-lg tracking-tight">
{t("analysis.charts.title")}
</h2>
<p className="text-muted-foreground text-sm">
{t("analysis.charts.subtitle")}
</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<TrendCard
description={t("analysis.charts.patientGrowthDescription")}
detailsLabel={t("analysis.charts.viewDetails")}
emptyLabel={t("analysis.charts.empty")}
points={data?.trends.patientsByMonth ?? []}
title={t("analysis.charts.patientGrowthTitle")}
/>
<TrendCard
description={t("analysis.charts.weeklyAppointmentsDescription")}
detailsLabel={t("analysis.charts.viewDetails")}
emptyLabel={t("analysis.charts.empty")}
points={data?.trends.appointmentsByWeekday ?? []}
title={t("analysis.charts.weeklyAppointmentsTitle")}
/>
</div>
</section>
<Section
description={t("analysis.appointments.description")}
@@ -146,16 +143,6 @@ export function AnalysisView() {
/>
</Section>
<ChartSection
description={t("analysis.charts.weeklyAppointmentsDescription")}
title={t("analysis.charts.weeklyAppointmentsTitle")}
>
<BarChart
data={data?.trends.appointmentsByWeekday ?? []}
emptyLabel={t("analysis.charts.empty")}
/>
</ChartSection>
<Section
description={t("analysis.prescriptions.description")}
title={t("analysis.prescriptions.title")}
@@ -1,59 +0,0 @@
"use client";
import type { TrendPoint } from "@/lib/analytics";
import { cn } from "@/lib/utils";
// A small dependency-free vertical bar chart (matches the spirit of
// components/chat/sparkline.tsx). Bars scale to the series max; each shows its
// value above and its label below. Themed with semantic tokens.
export function BarChart({
data,
className,
emptyLabel,
}: {
data: TrendPoint[];
className?: string;
emptyLabel: string;
}) {
const max = Math.max(1, ...data.map((d) => d.count));
const hasData = data.some((d) => d.count > 0);
if (data.length === 0 || !hasData) {
return (
<div
className={cn(
"flex h-44 items-center justify-center text-muted-foreground text-sm",
className,
)}
>
{emptyLabel}
</div>
);
}
return (
<div className={cn("flex h-44 items-end gap-2 sm:gap-3", className)}>
{data.map((d, i) => {
const pct = (d.count / max) * 100;
return (
<div
className="flex h-full flex-1 flex-col items-center gap-1.5"
key={`${d.label}-${i}`}
>
<span className="font-medium text-foreground text-xs tabular-nums">
{d.count}
</span>
<div className="flex w-full flex-1 items-end">
<div
className="w-full rounded-t-md bg-primary/80 transition-colors hover:bg-primary"
style={{ height: `${Math.max(pct, d.count > 0 ? 4 : 0)}%` }}
title={`${d.label}: ${d.count}`}
/>
</div>
<span className="text-muted-foreground text-xs">{d.label}</span>
</div>
);
})}
</div>
);
}
@@ -0,0 +1,91 @@
"use client";
import { useState } from "react";
import { Sparkline } from "@/components/chat/sparkline";
import { Card } from "@/components/ui/card";
import {
Dialog,
DialogDescription,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "@/components/ui/dialog";
import type { TrendPoint } from "@/lib/analytics";
// A KPI card with an inline line chart (Sparkline). Clicking it opens a dialog
// with the full line chart and a per-point breakdown. Used on the Analysis page.
export function TrendCard({
title,
description,
points,
emptyLabel,
detailsLabel,
}: {
title: string;
description: string;
points: TrendPoint[];
emptyLabel: string;
detailsLabel: string;
}) {
const [open, setOpen] = useState(false);
const values = points.map((p) => p.count);
const total = values.reduce((a, b) => a + b, 0);
const hasData = points.length > 0;
return (
<>
<button
className="w-full text-left"
disabled={!hasData}
onClick={() => setOpen(true)}
type="button"
>
<Card className="gap-3 p-4 transition-colors hover:border-ring/40 hover:bg-accent/30">
<div className="flex items-baseline justify-between gap-2">
<span className="text-muted-foreground text-sm">{title}</span>
<span className="font-semibold text-foreground text-xl tabular-nums">
{total}
</span>
</div>
{hasData ? (
<Sparkline className="h-12" points={values} />
) : (
<p className="py-4 text-center text-muted-foreground text-xs">
{emptyLabel}
</p>
)}
{hasData && (
<span className="text-muted-foreground text-xs">{detailsLabel}</span>
)}
</Card>
</button>
<Dialog onOpenChange={setOpen} open={open}>
<DialogPopup className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogPanel className="flex flex-col gap-5">
<Sparkline className="h-36" points={values} />
<dl className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm sm:grid-cols-3">
{points.map((p) => (
<div
className="flex items-center justify-between border-border/60 border-b py-1"
key={p.label}
>
<dt className="text-muted-foreground">{p.label}</dt>
<dd className="font-medium text-foreground tabular-nums">
{p.count}
</dd>
</div>
))}
</dl>
</DialogPanel>
</DialogPopup>
</Dialog>
</>
);
}
@@ -23,6 +23,9 @@ import { notify } from "@/lib/toast";
const MIN_PASSWORD = 12;
const MIN_USERNAME = 3;
// Mirrors the backend rule (backend/src/routes/staff.ts): letters, numbers,
// dots and underscores only — notably no spaces.
const USERNAME_RE = /^[a-zA-Z0-9_.]+$/;
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";
@@ -77,10 +80,15 @@ export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
}
// Step 2 → create the account.
if (username.trim().length < MIN_USERNAME) {
const trimmedUsername = username.trim();
if (trimmedUsername.length < MIN_USERNAME) {
setError(t("settings.careTeam.add.usernameTooShort", { count: MIN_USERNAME }));
return;
}
if (!USERNAME_RE.test(trimmedUsername)) {
setError(t("settings.careTeam.add.usernameInvalid"));
return;
}
if (password.length < MIN_PASSWORD) {
setError(t("settings.careTeam.add.passwordTooShort", { count: MIN_PASSWORD }));
return;
@@ -93,7 +101,7 @@ export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
body: JSON.stringify({
name: name.trim(),
role,
username: username.trim(),
username: trimmedUsername,
password,
}),
});
@@ -101,7 +109,7 @@ export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
t("settings.careTeam.add.createdTitle"),
t("settings.careTeam.add.createdBody", {
name: name.trim(),
username: username.trim().toLowerCase(),
username: trimmedUsername.toLowerCase(),
}),
);
onCreated?.();
@@ -183,6 +191,9 @@ export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
required
value={username}
/>
<FieldDescription>
{t("settings.careTeam.add.usernameHint")}
</FieldDescription>
</Field>
<Field className="w-full">
<FieldLabel htmlFor="staff-password">
@@ -12,9 +12,19 @@ import {
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,
DialogPopup,
DialogTitle,
} from "@/components/ui/dialog";
import { ROLE_LABELS } from "@/lib/access";
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).
@@ -52,6 +62,8 @@ export function CareTeamPanel() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [pendingRemove, setPendingRemove] = useState<StaffMember | null>(null);
const [removing, setRemoving] = useState(false);
const load = useCallback(async () => {
try {
@@ -75,8 +87,27 @@ export function CareTeamPanel() {
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
const canManage = myRole === "owner" || myRole === "admin";
const removeMember = async (memberId: string) => {
await authClient.organization.removeMember({ memberIdOrEmail: memberId });
const confirmRemove = async () => {
if (!pendingRemove || removing) return;
setRemoving(true);
const { error: err } = await authClient.organization.removeMember({
memberIdOrEmail: pendingRemove.id,
});
setRemoving(false);
if (err) {
notify.error(
t("settings.careTeam.remove.failedTitle"),
err.message ?? t("settings.careTeam.remove.failedBody"),
);
return;
}
notify.success(
t("settings.careTeam.remove.removedTitle"),
t("settings.careTeam.remove.removedBody", {
name: pendingRemove.name ?? pendingRemove.email ?? "",
}),
);
setPendingRemove(null);
void load();
};
@@ -139,7 +170,7 @@ export function CareTeamPanel() {
{canManage && !isSelf && m.role !== "owner" && (
<Button
aria-label={t("settings.careTeam.removeMember")}
onClick={() => removeMember(m.id)}
onClick={() => setPendingRemove(m)}
size="icon-sm"
type="button"
variant="ghost"
@@ -160,6 +191,41 @@ export function CareTeamPanel() {
open={adding}
/>
)}
{/* Confirm before removing a member — destructive and not reversible. */}
<Dialog
onOpenChange={(o) => !o && setPendingRemove(null)}
open={pendingRemove !== null}
>
<DialogPopup className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>{t("settings.careTeam.remove.title")}</DialogTitle>
<DialogDescription>
{t("settings.careTeam.remove.description", {
name:
pendingRemove?.name ??
pendingRemove?.email ??
t("settings.careTeam.remove.thisMember"),
})}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" />}>
{t("settings.careTeam.remove.cancel")}
</DialogClose>
<Button
disabled={removing}
onClick={confirmRemove}
type="button"
variant="destructive"
>
{removing
? t("settings.careTeam.remove.removing")
: t("settings.careTeam.remove.confirm")}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
</SettingsSection>
);
}
+17 -5
View File
@@ -49,6 +49,7 @@ import {
useSidebar,
} from "@/components/ui/sidebar";
import { authClient } from "@/lib/auth-client";
import { useActiveRole } from "@/lib/roles";
import { notify } from "@/lib/toast";
// Open-source repo (placeholder).
@@ -91,6 +92,10 @@ export function NavUser() {
const { open: openCommand } = useCommandPalette();
const { data: orgs } = authClient.useListOrganizations();
const { data: activeOrg } = authClient.useActiveOrganization();
const role = useActiveRole();
// Only clinic owners/admins may spin up additional clinics. New users with no
// clinic still onboard via /onboarding (a separate flow).
const canCreateClinic = role === "owner" || role === "admin";
const [createOpen, setCreateOpen] = useState(false);
@@ -231,11 +236,18 @@ export function NavUser() {
</MenuItem>
))}
</MenuGroup>
<MenuSeparator />
<MenuItem className="gap-2" onClick={() => setCreateOpen(true)}>
<Plus />
{t("userMenu.createClinic")}
</MenuItem>
{canCreateClinic && (
<>
<MenuSeparator />
<MenuItem
className="gap-2"
onClick={() => setCreateOpen(true)}
>
<Plus />
{t("userMenu.createClinic")}
</MenuItem>
</>
)}
</MenuSubPopup>
</MenuSub>
@@ -11,6 +11,7 @@ import {
SheetPopup,
SheetTitle,
} from "@/components/ui/sheet";
import { ROLE_LABELS } from "@/lib/access";
import { cn } from "@/lib/utils";
import type { Priority, Task } from "@/components/tasks/tasks-view";
@@ -21,6 +22,10 @@ const priorityVariant: Record<Priority, "destructive" | "secondary" | "outline">
low: "outline",
};
function deptLabel(role: string): string {
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
}
// Right-side Sheet showing a single task's full detail, opened from the Tasks
// list (mirrors the Patients table → PatientDetailSheet pattern). The task is
// passed in directly from the page.
@@ -67,9 +72,19 @@ export function TaskDetailSheet({
: t("tasks.detail.open")}
</dd>
<dt className="text-muted-foreground">
{t("tasks.detail.assignee")}
{t("tasks.detail.assignedTo")}
</dt>
<dd className="text-foreground">{task.assignee}</dd>
<dd className="text-foreground">
{task.assigneeRole
? t("tasks.detail.deptTeam", {
dept: deptLabel(task.assigneeRole),
})
: t("tasks.detail.personal")}
</dd>
<dt className="text-muted-foreground">
{t("tasks.detail.createdBy")}
</dt>
<dd className="text-foreground">{task.createdByName ?? "—"}</dd>
<dt className="text-muted-foreground">
{t("tasks.detail.due")}
</dt>
+73 -22
View File
@@ -25,6 +25,8 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ROLE_LABELS } from "@/lib/access";
import { DEPARTMENTS } from "@/lib/roles";
import {
type Priority,
type Task,
@@ -36,6 +38,12 @@ import {
import { notify } from "@/lib/toast";
import { cn } from "@/lib/utils";
type AssigneeMode = "self" | "other";
function deptLabel(role: string): string {
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
}
export type { Priority, Task } from "@/lib/tasks";
type Filter = "all" | "open" | "done";
@@ -98,14 +106,16 @@ function AddTaskDialog({
const { t } = useTranslation();
const [title, setTitle] = useState("");
const [notes, setNotes] = useState("");
const [assignee, setAssignee] = useState("");
const [assigneeMode, setAssigneeMode] = useState<AssigneeMode>("self");
const [department, setDepartment] = useState<string>("reception");
const [due, setDue] = useState("");
const [priority, setPriority] = useState<Priority>("medium");
const reset = () => {
setTitle("");
setNotes("");
setAssignee("");
setAssigneeMode("self");
setDepartment("reception");
setDue("");
setPriority("medium");
};
@@ -122,7 +132,8 @@ function AddTaskDialog({
onAdd({
title: title.trim(),
notes: notes.trim() || undefined,
assignee: assignee.trim() || "Unassigned",
// "Myself" → personal task (no department); "Other" → a department.
assigneeRole: assigneeMode === "self" ? null : department,
due: due.trim() || "No due date",
priority,
});
@@ -163,14 +174,47 @@ function AddTaskDialog({
value={notes}
/>
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label={t("tasks.dialog.assignee")}>
<Input
onChange={(e) => setAssignee(e.target.value)}
placeholder={t("tasks.dialog.assigneePlaceholder")}
value={assignee}
/>
<div className="flex flex-col gap-1.5">
<span className="text-muted-foreground text-xs">
{t("tasks.dialog.assignee")}
</span>
<div className="flex gap-2">
<Button
className="flex-1"
onClick={() => setAssigneeMode("self")}
size="sm"
type="button"
variant={assigneeMode === "self" ? "secondary" : "outline"}
>
{t("tasks.dialog.assigneeSelf")}
</Button>
<Button
className="flex-1"
onClick={() => setAssigneeMode("other")}
size="sm"
type="button"
variant={assigneeMode === "other" ? "secondary" : "outline"}
>
{t("tasks.dialog.assigneeOther")}
</Button>
</div>
</div>
{assigneeMode === "other" && (
<Field label={t("tasks.dialog.department")}>
<select
className={controlClass}
onChange={(e) => setDepartment(e.target.value)}
value={department}
>
{DEPARTMENTS.map((d) => (
<option key={d} value={d}>
{ROLE_LABELS[d]}
</option>
))}
</select>
</Field>
)}
<div className="grid grid-cols-2 gap-3">
<Field label={t("tasks.dialog.due")}>
<Input
onChange={(e) => setDue(e.target.value)}
@@ -178,18 +222,18 @@ function AddTaskDialog({
value={due}
/>
</Field>
<Field label={t("tasks.dialog.priorityLabel")}>
<select
className={controlClass}
onChange={(e) => setPriority(e.target.value as Priority)}
value={priority}
>
<option value="high">{t("tasks.priority.high")}</option>
<option value="medium">{t("tasks.priority.medium")}</option>
<option value="low">{t("tasks.priority.low")}</option>
</select>
</Field>
</div>
<Field label={t("tasks.dialog.priorityLabel")}>
<select
className={controlClass}
onChange={(e) => setPriority(e.target.value as Priority)}
value={priority}
>
<option value="high">{t("tasks.priority.high")}</option>
<option value="medium">{t("tasks.priority.medium")}</option>
<option value="low">{t("tasks.priority.low")}</option>
</select>
</Field>
</DialogPanel>
<DialogFooter>
@@ -337,7 +381,14 @@ export function TasksView() {
{task.title}
</span>
<span className="truncate text-muted-foreground text-xs">
{task.assignee} · {task.due}
{task.assigneeRole
? t("tasks.list.forDept", {
dept: deptLabel(task.assigneeRole),
})
: t("tasks.list.personal")}
{task.createdByName
? ` · ${t("tasks.list.byCreator", { name: task.createdByName })}`
: ""}
</span>
</button>
<Badge