186 lines
11 KiB
TypeScript
186 lines
11 KiB
TypeScript
import { type FormEvent, useMemo, useState } from "react";
|
|
import { Alert } from "../components/ui/Alert";
|
|
import { Badge } from "../components/ui/Badge";
|
|
import { Button } from "../components/ui/Button";
|
|
import { Card } from "../components/ui/Card";
|
|
import { DataTable, type Column } from "../components/ui/DataTable";
|
|
import { Checkbox, Field, Input, Select } from "../components/ui/Field";
|
|
import { Modal } from "../components/ui/Modal";
|
|
import { SearchInput } from "../components/ui/Misc";
|
|
import { PageHeader } from "../components/ui/PageHeader";
|
|
import { EmptyState, ErrorState } from "../components/ui/States";
|
|
import { Tabs } from "../components/ui/Tabs";
|
|
import { useToast } from "../components/ui/Toast";
|
|
import { MasterRequests } from "../components/admin/MasterRequests";
|
|
import { LIVE, useAsync } from "../hooks/useAsync";
|
|
import { api } from "../api";
|
|
import { errorMessage, isField } from "../lib/format";
|
|
import { useUser } from "../lib/session";
|
|
import { maxLength, minLength, required, useValidation } from "../lib/validation";
|
|
import type { Chemist, Doctor } from "../types";
|
|
|
|
const DOCTOR_COLUMNS: Column<Doctor>[] = [
|
|
{ key: "name", header: "Doctor", render: (d) => <strong>{d.name}</strong> },
|
|
{ key: "speciality", header: "Speciality", render: (d) => d.speciality || "—" },
|
|
{ key: "address", header: "Clinic address", render: (d) => d.clinic_address },
|
|
{ key: "core", header: "Type", render: (d) => (d.is_core_doctor ? <Badge tone="warning">Core doctor</Badge> : <Badge>Regular</Badge>), nowrap: true },
|
|
{ key: "status", header: "Status", render: (d) => <Badge tone={d.is_active ? "success" : "neutral"} dot>{d.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
|
|
];
|
|
const CHEMIST_COLUMNS: Column<Chemist>[] = [
|
|
{ key: "name", header: "Chemist", render: (c) => <strong>{c.name}</strong> },
|
|
{ key: "address", header: "Shop address", render: (c) => c.shop_address },
|
|
{ key: "status", header: "Status", render: (c) => <Badge tone={c.is_active ? "success" : "neutral"} dot>{c.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
|
|
];
|
|
|
|
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist };
|
|
|
|
export function DirectoryPage() {
|
|
const user = useUser();
|
|
const toast = useToast();
|
|
const isAdmin = user.role === "ADMIN";
|
|
const [editing, setEditing] = useState<Editing | null>(null);
|
|
const [toggling, setToggling] = useState<string | null>(null);
|
|
const doctors = useAsync(api.doctors, [], { poll: LIVE });
|
|
const chemists = useAsync(api.chemists, [], { poll: LIVE });
|
|
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
|
const hqLabel = useMemo(() => new Map((hqs.data ?? []).map((h) => [h.id, `${h.code} · ${h.name}`])), [hqs.data]);
|
|
const [tab, setTab] = useState<"doctors" | "chemists">("doctors");
|
|
const [query, setQuery] = useState("");
|
|
const q = query.trim().toLowerCase();
|
|
// Headquarters filter: the list holds only the headquarters this user may see (every one for
|
|
// the admin and GM, an Area Manager's own), so it offers exactly those. "" = all of them.
|
|
const [hqFilter, setHqFilter] = useState("");
|
|
const inHq = (id: string) => !hqFilter || id === hqFilter;
|
|
|
|
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => inHq(d.headquarters_id) && (!q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [doctors.data, hqLabel, q, hqFilter]);
|
|
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => inHq(c.headquarters_id) && (!q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [chemists.data, hqLabel, q, hqFilter]);
|
|
const active = tab === "doctors" ? doctors : chemists;
|
|
async function toggleActive(target: Editing) {
|
|
const next = !target.item.is_active;
|
|
setToggling(target.item.id);
|
|
try {
|
|
if (target.kind === "doctor") await api.updateDoctor(target.item.id, { is_active: next });
|
|
else await api.updateChemist(target.item.id, { is_active: next });
|
|
toast.success(`${target.kind === "doctor" ? "Doctor" : "Chemist"} ${next ? "activated" : "deactivated"}`);
|
|
await (target.kind === "doctor" ? doctors : chemists).reload();
|
|
} catch (err) {
|
|
toast.error(errorMessage(err, "Could not change the status"));
|
|
} finally {
|
|
setToggling(null);
|
|
}
|
|
}
|
|
const editButton = (target: Editing) => (
|
|
<>
|
|
<Button size="sm" variant="ghost" loading={toggling === target.item.id} onClick={() => void toggleActive(target)}>{target.item.is_active ? "Deactivate" : "Activate"}</Button>
|
|
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(target)}>Edit</Button>
|
|
</>
|
|
);
|
|
/** The headquarters each doctor / chemist is assigned to. */
|
|
const hqCell = (id: string) => (hqLabel.has(id) ? <Badge tone="brand">{hqLabel.get(id)}</Badge> : <span className="muted">—</span>);
|
|
const doctorColumns: Column<Doctor>[] = [
|
|
...DOCTOR_COLUMNS.slice(0, 1),
|
|
{ key: "hq", header: "Headquarters", render: (d) => hqCell(d.headquarters_id), nowrap: true },
|
|
...DOCTOR_COLUMNS.slice(1),
|
|
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (d: Doctor) => editButton({ kind: "doctor", item: d }) }] : []),
|
|
];
|
|
const chemistColumns: Column<Chemist>[] = [
|
|
...CHEMIST_COLUMNS.slice(0, 1),
|
|
{ key: "hq", header: "Headquarters", render: (c) => hqCell(c.headquarters_id), nowrap: true },
|
|
...CHEMIST_COLUMNS.slice(1),
|
|
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (c: Chemist) => editButton({ kind: "chemist", item: c }) }] : []),
|
|
];
|
|
|
|
return (
|
|
<>
|
|
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
|
|
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); }} />}
|
|
<Card>
|
|
<div className="toolbar">
|
|
<Tabs
|
|
label="Directory"
|
|
value={tab}
|
|
onChange={setTab}
|
|
items={[{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined }, { key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined }]}
|
|
/>
|
|
<div className="toolbar-group">
|
|
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
|
|
<option value="">All headquarters</option>
|
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
|
</Select>
|
|
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
|
|
</div>
|
|
</div>
|
|
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
|
|
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
|
|
) : (
|
|
<DataTable columns={chemistColumns} rows={chemistRows} rowKey={(c) => c.id} loading={chemists.loading} minWidth={640} empty={<EmptyState icon="stethoscope" title="No chemists found" />} />
|
|
)}
|
|
</Card>
|
|
{editing && (
|
|
<DirectoryEditor
|
|
editing={editing}
|
|
onClose={() => setEditing(null)}
|
|
onSaved={() => {
|
|
setEditing(null);
|
|
toast.success(`${editing.kind === "doctor" ? "Doctor" : "Chemist"} updated`);
|
|
void (editing.kind === "doctor" ? doctors : chemists).reload();
|
|
}}
|
|
/>
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onClose: () => void; onSaved: () => void }) {
|
|
const isDoctor = editing.kind === "doctor";
|
|
const [name, setName] = useState(editing.item.name);
|
|
const [address, setAddress] = useState(isDoctor ? (editing.item as Doctor).clinic_address : (editing.item as Chemist).shop_address);
|
|
const [speciality, setSpeciality] = useState(isDoctor ? (editing.item as Doctor).speciality ?? "" : "");
|
|
const [core, setCore] = useState(isDoctor ? (editing.item as Doctor).is_core_doctor : false);
|
|
const [active, setActive] = useState(editing.item.is_active);
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const v = useValidation({
|
|
name: [required("Name"), minLength(2, "Name"), maxLength(200, "Name")],
|
|
address: [required(isDoctor ? "Clinic address" : "Shop address"), minLength(2, "Address"), maxLength(500, "Address")],
|
|
speciality: [maxLength(100, "Speciality")],
|
|
});
|
|
|
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
|
e.preventDefault();
|
|
if (!v.check({ name, address, speciality }, e.currentTarget)) return;
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
if (isDoctor) {
|
|
await api.updateDoctor(editing.item.id, { name: name.trim(), clinic_address: address.trim(), speciality: speciality.trim() || null, is_core_doctor: core, is_active: active });
|
|
} else {
|
|
await api.updateChemist(editing.item.id, { name: name.trim(), shop_address: address.trim(), is_active: active });
|
|
}
|
|
onSaved();
|
|
} catch (err) {
|
|
setError(errorMessage(err, "Could not save the changes"));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Modal
|
|
open
|
|
title={isDoctor ? "Edit doctor" : "Edit chemist"}
|
|
onClose={onClose}
|
|
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("directory-editor-form") as HTMLFormElement | null)?.requestSubmit()}>Save changes</Button></>}
|
|
>
|
|
<form id="directory-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
|
|
<Alert>{error}</Alert>
|
|
<Field label="Name" required error={v.errors.name}><Input value={name} onChange={(e) => { setName(e.target.value); v.retouch("name", e.target.value); }} onBlur={(e) => v.touch("name", e.target.value)} /></Field>
|
|
<Field label={isDoctor ? "Clinic address" : "Shop address"} required error={v.errors.address}><Input value={address} onChange={(e) => { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /></Field>
|
|
{isDoctor && <Field label="Speciality" error={v.errors.speciality}><Input value={speciality} onChange={(e) => { setSpeciality(e.target.value); v.retouch("speciality", e.target.value); }} onBlur={(e) => v.touch("speciality", e.target.value)} /></Field>}
|
|
{isDoctor && <Checkbox label="Core doctor" checked={core} onChange={(e) => setCore(e.target.checked)} />}
|
|
<Checkbox label="Active" checked={active} onChange={(e) => setActive(e.target.checked)} />
|
|
</form>
|
|
</Modal>
|
|
);
|
|
}
|