Files
temetro/frontend/components/settings/settings-care-team.tsx
T
Khalid Abdi 4f8793c765 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>
2026-06-08 19:52:12 +03:00

232 lines
7.2 KiB
TypeScript

"use client";
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,
} from "@/components/settings/settings-parts";
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).
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;
}
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() || "?"
);
}
export function CareTeamPanel() {
const { t } = useTranslation();
const { data: session } = authClient.useSession();
const [members, setMembers] = useState<StaffMember[]>([]);
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 {
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);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
void load();
}, [load]);
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
const canManage = myRole === "owner" || myRole === "admin";
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();
};
return (
<SettingsSection
description={t("settings.careTeam.description")}
title={t("settings.careTeam.title")}
>
{error && (
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
{canManage && (
<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">
{loading ? (
<p className="p-6 text-center text-sm text-muted-foreground">
{t("settings.careTeam.loading")}
</p>
) : (
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.name, m.email)}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{m.name || m.email || m.userId}
{isSelf && (
<span className="ml-1 text-xs text-muted-foreground">
{t("settings.careTeam.you")}
</span>
)}
</p>
{secondary && (
<p className="truncate text-xs text-muted-foreground">
{secondary}
</p>
)}
</div>
<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"
type="button"
variant="ghost"
>
<X className="size-4" />
</Button>
)}
</div>
);
})
)}
</SettingsCard>
{canManage && (
<AddStaffDialog
onCreated={() => void load()}
onOpenChange={setAdding}
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>
);
}