Files
celtic-life-science/web/src/components/admin/MasterRequests.tsx
T
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

115 lines
5.9 KiB
TypeScript

import { useState } from "react";
import { Badge } from "../ui/Badge";
import { Button } from "../ui/Button";
import { Card, CardBody, CardHeader } from "../ui/Card";
import { DataTable, type Column } from "../ui/DataTable";
import { Field, Textarea } from "../ui/Field";
import { Modal } from "../ui/Modal";
import { ErrorState } from "../ui/States";
import { useToast } from "../ui/Toast";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { errorMessage, formatDate } from "../../lib/format";
import { useUser } from "../../lib/session";
import type { Chemist, Doctor } from "../../types";
type Request = { kind: "doctor" | "chemist"; item: Doctor | Chemist };
const address = (r: Request) => (r.kind === "doctor" ? (r.item as Doctor).clinic_address : (r.item as Chemist).shop_address);
/**
* Doctors and chemists an MR added that wait for the Area Manager.
* `mine`: the MR's own requests, with any rejection and its reason.
* `review`: what waits for this Area Manager (or the admin) to approve or reject; the GM only looks.
* Shows nothing when there is nothing to show.
*/
export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review"; onReviewed?: () => void }) {
const user = useUser();
const toast = useToast();
const canAct = mode === "review" && (user.role === "AM" || user.role === "ADMIN");
const data = useAsync(async () => {
const [doctors, chemists] = await Promise.all([api.doctorRequests(), api.chemistRequests()]);
return [...doctors.map((item) => ({ kind: "doctor" as const, item })), ...chemists.map((item) => ({ kind: "chemist" as const, item }))]
.sort((a, b) => b.item.created_at.localeCompare(a.item.created_at));
}, [], { poll: LIVE });
const [acting, setActing] = useState<string | null>(null);
const [rejecting, setRejecting] = useState<Request | null>(null);
const [reason, setReason] = useState("");
const [reasonError, setReasonError] = useState<string | null>(null);
const rows = data.data ?? [];
async function decide(r: Request, approve: boolean, why?: string) {
setActing(r.item.id);
try {
await api.reviewMaster(r.kind, r.item.id, approve, why);
toast.success(approve ? `${r.item.name} approved and added to the list` : `${r.item.name} rejected`);
setRejecting(null);
await data.reload();
onReviewed?.();
} catch (e) {
toast.error(errorMessage(e, approve ? "Could not approve" : "Could not reject"));
} finally {
setActing(null);
}
}
if (data.error) return <Card><ErrorState message={data.error} onRetry={() => void data.reload()} /></Card>;
if (rows.length === 0) return null;
const columns: Column<Request>[] = [
{ key: "kind", header: "Type", render: (r) => <Badge tone="brand">{r.kind === "doctor" ? "Doctor" : "Chemist"}</Badge>, nowrap: true },
{ key: "name", header: "Name", render: (r) => <strong>{r.item.name}</strong> },
{ key: "address", header: "Address", render: address },
...(mode === "review" ? [{ key: "by", header: "Added by", render: (r: Request) => r.item.requested_by_name ?? "—", nowrap: true }] : []),
{ key: "on", header: "Added on", render: (r) => formatDate(r.item.created_at), nowrap: true },
mode === "mine"
? {
key: "status", header: "Status",
render: (r) => r.item.approval_status === "REJECTED"
? <span><Badge tone="danger" dot>Rejected</Badge>{r.item.rejection_reason && <span className="muted"> — {r.item.rejection_reason}</span>}</span>
: <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
}
: {
key: "_actions", header: "", align: "right", nowrap: true,
render: (r) => canAct ? (
<span className="row-actions">
<Button size="sm" variant="primary" icon="check" loading={acting === r.item.id} onClick={() => void decide(r, true)}>Approve</Button>
<Button size="sm" variant="ghost" disabled={acting === r.item.id} onClick={() => { setRejecting(r); setReason(""); setReasonError(null); }}>Reject</Button>
</span>
) : <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
},
];
const pending = rows.filter((r) => r.item.approval_status === "PENDING").length;
return (
<>
<Card>
<CardHeader
title={mode === "mine" ? "Your requests" : "Waiting for approval"}
description={mode === "mine"
? "Doctors and chemists you added. Each joins your list once your Area Manager approves it. To re-send a rejected one, add it again with the corrected details."
: `${pending} new doctor${pending === 1 ? "" : "s"} or chemist${pending === 1 ? "" : "s"} added by MRs. Once approved, each joins the list and is assigned to the MR who added it.`}
/>
<CardBody flush>
<DataTable columns={columns} rows={rows} rowKey={(r) => `${r.kind}-${r.item.id}`} loading={data.loading} minWidth={720} />
</CardBody>
</Card>
<Modal
open={!!rejecting}
title={`Reject ${rejecting?.item.name ?? ""}?`}
description="The MR sees your reason and can add it again with corrected details."
onClose={() => setRejecting(null)}
footer={<><Button onClick={() => setRejecting(null)}>Cancel</Button><Button variant="danger" loading={!!rejecting && acting === rejecting.item.id} onClick={() => {
const why = reason.trim();
if (why.length < 3) { setReasonError("Give a reason (at least 3 characters)"); return; }
if (rejecting) void decide(rejecting, false, why);
}}>Reject</Button></>}
>
<Field label="Reason" required error={reasonError ?? undefined} hint={`${reason.length}/500`}>
<Textarea value={reason} maxLength={500} rows={3} onChange={(e) => { setReason(e.target.value); setReasonError(null); }} placeholder="e.g. Wrong clinic address, or this doctor is already in the list" />
</Field>
</Modal>
</>
);
}