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[] = [ { key: "name", header: "Doctor", render: (d) => {d.name} }, { 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 ? Core doctor : Regular), nowrap: true }, { key: "status", header: "Status", render: (d) => {d.is_active ? "Active" : "Inactive"}, nowrap: true }, ]; const CHEMIST_COLUMNS: Column[] = [ { key: "name", header: "Chemist", render: (c) => {c.name} }, { key: "address", header: "Shop address", render: (c) => c.shop_address }, { key: "status", header: "Status", render: (c) => {c.is_active ? "Active" : "Inactive"}, 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(null); const [toggling, setToggling] = useState(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) => ( <> ); /** The headquarters each doctor / chemist is assigned to. */ const hqCell = (id: string) => (hqLabel.has(id) ? {hqLabel.get(id)} : —); const doctorColumns: Column[] = [ ...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_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 ( <> {!isField(user.role) && { void doctors.reload(); void chemists.reload(); }} />}
{active.error ? void active.reload()} /> : tab === "doctors" ? ( d.id} loading={doctors.loading} minWidth={820} empty={} /> ) : ( c.id} loading={chemists.loading} minWidth={640} empty={} /> )}
{editing && ( 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(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) { 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 ( } >
{error} { setName(e.target.value); v.retouch("name", e.target.value); }} onBlur={(e) => v.touch("name", e.target.value)} /> { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /> {isDoctor && { setSpeciality(e.target.value); v.retouch("speciality", e.target.value); }} onBlur={(e) => v.touch("speciality", e.target.value)} />} {isDoctor && setCore(e.target.checked)} />} setActive(e.target.checked)} />
); }