Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
+252
View File
@@ -0,0 +1,252 @@
import { useMemo, useState } from "react";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { DataTable, type Column } from "../../components/ui/DataTable";
import { Select } from "../../components/ui/Field";
import { Modal } from "../../components/ui/Modal";
import { PageHeader } from "../../components/ui/PageHeader";
import { EmptyState, ErrorState, Skeleton } from "../../components/ui/States";
import { useToast } from "../../components/ui/Toast";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { errorMessage, formatDate, humanize } from "../../lib/format";
import { Link } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { CsvRow, CsvTable, FormApproval } from "../../types";
import { APPROVAL_FORMS, APPROVAL_POLL_MS } from "./approval";
import { RowEditor } from "./RowEditor";
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
const DATES = new Set(["report_date", "date_of_visit"]);
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const sameMonth = (a: unknown, b: string) => String(a ?? "").trim().toLowerCase() === b.trim().toLowerCase();
/** The number shown for a row: its place in that MR's own form. */
const numberOf = (r: CsvRow) => String(r.serial_no ?? r.source_row_number);
export function FormsPage({ table: routeTable }: { table?: string }) {
const user = useUser();
const toast = useToast();
const tables = useAsync(api.csvTables, [], { poll: LIVE });
const profile = useAsync(() => api.profile().catch(() => null), []);
const list = tables.data ?? [];
const table: CsvTable | undefined = list.find((t) => t.name === routeTable) ?? list[0];
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
const isManager = user.role === "AM" || user.role === "ADMIN";
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
const owners = useAsync(() => (isManager && needsApproval ? api.formOwners() : Promise.resolve([])), [isManager, needsApproval], { poll: LIVE });
const [ownerChoice, setOwnerChoice] = useState("");
const [monthChoice, setMonthChoice] = useState<Record<string, string>>({});
const pendingFor = (tableName: string, ownerId: string) => approvals.data?.some((a) => a.table_name === tableName && a.owner_user_id === ownerId && a.status === "pending") ?? false;
const ownerList = owners.data ?? [];
const viewOwner = useMemo(() => {
if (!isManager || !needsApproval || !table) return undefined;
const chosen = ownerList.find((o) => o.id === ownerChoice);
if (chosen) return chosen;
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, user.role, approvals.data]);
const waitingForOwners = isManager && needsApproval && !owners.data;
const rows = useAsync<CsvRow[]>(
() => (table && !waitingForOwners ? api.csvRows(table.name, viewOwner?.id) : Promise.resolve([])),
[table?.name, viewOwner?.id, waitingForOwners], { poll: LIVE },
);
const [acting, setActing] = useState(false);
const [editing, setEditing] = useState<{ row: CsvRow | null } | null>(null);
const [deleting, setDeleting] = useState<CsvRow | null>(null);
const canEdit = user.role === "MR" || user.role === "ADMIN";
// An admin adds rows on behalf of one chosen MR.
const canAdd = canEdit && (!needsApproval || user.role === "MR" || !!viewOwner);
const subjectId = user.role === "MR" ? user.id : viewOwner?.id;
const approval = table && subjectId ? approvals.data?.find((a) => a.table_name === table.name && a.owner_user_id === subjectId) : undefined;
const hasRows = (rows.data?.length ?? 0) > 0;
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
// Only the controls that make sense right now: nothing to approve means nothing to show.
const canSend = needsApproval && user.role === "MR" && status === "draft" && hasRows;
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
const showStatus = needsApproval && (status === "pending" || status === "approved");
// Forms with a month can be downloaded one month at a time.
const hasMonth = !!table?.columns.includes("month");
const months = useMemo(() => {
if (!hasMonth) return [] as string[];
const seen = new Map<string, string>();
for (const r of rows.data ?? []) { const m = String(r.month ?? "").trim(); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
const rank = (m: string) => { const i = MONTHS.findIndex((x) => sameMonth(x, m)); return i < 0 ? 99 : i; };
return [...seen.values()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
}, [hasMonth, rows.data]);
const thisMonth = MONTHS[new Date().getMonth()]!;
const chosenMonth = table ? monthChoice[table.name] : undefined;
// Starts on the current month when the form has rows for it, otherwise on everything.
const month = chosenMonth !== undefined ? (chosenMonth === "" || months.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : months.find((m) => sameMonth(m, thisMonth)) ?? "";
const shownRows = month ? (rows.data ?? []).filter((r) => sameMonth(r.month, month)) : rows.data ?? [];
const showToolbar = hasMonth ? months.length > 0 : isManager && needsApproval;
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
async function act(kind: "request" | "approve") {
if (!table || acting) return;
const name = table.name;
const before = approvals.data ?? [];
const ownerId = user.role === "MR" ? user.id : viewOwner?.id;
if (!ownerId) return;
const base = { table_name: name, owner_user_id: ownerId, owner_name: viewOwner?.name ?? user.full_name, headquarters_name: viewOwner?.headquarters_name ?? null, updated_at: null };
const next: FormApproval = kind === "request"
? { ...base, status: "pending", approved_by_name: null }
: { ...base, status: "approved", approved_by_name: user.full_name };
const same = (a: FormApproval) => a.table_name === name && a.owner_user_id === ownerId;
const merge = (list: FormApproval[], item: FormApproval) => (list.some(same) ? list.map((a) => (same(a) ? item : a)) : [...list, item]);
setActing(true);
approvals.setData(merge(before, next));
try {
const saved = await (kind === "request" ? api.requestFormApproval(name) : api.approveForm(name, ownerId));
approvals.setData(merge(before, saved));
toast.success(kind === "request" ? "Sent to the Area Manager for approval" : "Form approved");
} catch (e) {
approvals.setData(before);
toast.error(errorMessage(e, kind === "request" ? "Could not send the form for approval" : "Could not approve the form"));
void approvals.reload();
} finally {
setActing(false);
}
}
const run = (task: Promise<unknown>) => task.catch((e) => toast.error(errorMessage(e, "Download failed")));
async function confirmDelete() {
if (!table || !deleting) return;
try {
await api.deleteCsvRow(table.name, deleting.id);
toast.success("Row deleted");
setDeleting(null);
await Promise.all([rows.reload(), approvals.reload()]);
} catch (e) { toast.error(errorMessage(e, "Could not delete the row")); }
}
const columns: Column<CsvRow>[] = table ? [
{ key: "_no", header: "No.", render: numberOf, width: "64px" },
...table.columns
.filter((c) => !SERIAL.has(c) && !(user.role !== "ADMIN" && IDENTITY.has(c)))
.map<Column<CsvRow>>((c) => ({
key: c,
header: humanize(c),
nowrap: true,
render: (r) => {
const value = String(r[c] ?? "");
return value ? (DATES.has(c) ? formatDate(value) : value) : <span className="muted">—</span>;
},
})),
{
key: "_actions", header: "", align: "right", nowrap: true, sticky: true,
render: (r) => (
<span className="row-actions">
{canEdit && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
<Button size="sm" variant="ghost" icon="download" onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
{canEdit && <Button size="sm" variant="ghost" icon="trash" onClick={() => setDeleting(r)} aria-label="Delete row" />}
</span>
),
},
] : [];
if (tables.error) return <ErrorState message={tables.error} onRetry={() => void tables.reload()} />;
return (
<>
<PageHeader title="Company forms" description="Fill in the company’s standard forms and print them as ready-to-sign PDFs." />
<div className="forms-layout">
<nav className="form-nav" aria-label="Forms">
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
<Link key={t.name} to={`/forms/${t.name}`} className={`form-nav-item${t.name === table?.name ? " active" : ""}`} aria-current={t.name === table?.name ? "page" : undefined}>
{t.label}
{user.role === "AM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
</Link>
))}
</nav>
<Card>
{!table ? <CardBody><EmptyState icon="table" title="No forms available" /></CardBody> : (
<>
<CardHeader
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Manager"}` : "Pending AM approval"}</Badge>}</span>}
description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`}
actions={
<>
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
<Button icon="download" disabled={!hasRows} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</Button>
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
</>
}
/>
{showToolbar && (
<div className="toolbar">
{isManager && needsApproval && (
<label className="filter">
<span>Medical representative</span>
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
{user.role === "ADMIN" && <option value="">All medical representatives</option>}
{ownerList.map((o) => <option key={o.id} value={o.id}>{o.name}{o.headquarters_name ? ` · ${o.headquarters_name}` : ""}{pendingFor(table.name, o.id) ? " — needs approval" : ""}</option>)}
</Select>
</label>
)}
{hasMonth && months.length > 0 && (
<label className="filter">
<span>Month</span>
<Select value={month} onChange={(e) => setMonthChoice((m) => ({ ...m, [table.name]: e.target.value }))} aria-label="Month">
<option value="">All months</option>
{months.map((m) => <option key={m} value={m}>{m}</option>)}
</Select>
</label>
)}
</div>
)}
{rows.error ? <ErrorState message={rows.error} onRetry={() => void rows.reload()} /> : (
<DataTable
columns={columns}
rows={shownRows}
rowKey={(r) => r.id}
loading={rows.loading || waitingForOwners}
minWidth={Math.max(640, columns.length * 115)}
empty={month
? <EmptyState icon="table" title={`No rows for ${month}`} description="Choose another month, or All months." />
: isManager && needsApproval && ownerList.length === 0
? <EmptyState icon="users" title="No medical representatives" description={user.role === "AM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
: <EmptyState icon="table" title="No rows yet" description={canAdd ? "Add a row to start filling in this form." : isManager && needsApproval ? "This medical representative has not filled in this form." : undefined} action={canAdd ? <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button> : undefined} />}
/>
)}
</>
)}
</Card>
</div>
{table && editing && (
<RowEditor
open
table={table}
row={editing.row}
rows={rows.data ?? []}
user={user}
profile={profile.data}
owner={viewOwner}
onClose={() => setEditing(null)}
onSaved={(message) => { setEditing(null); toast.success(message); void rows.reload(); void approvals.reload(); }}
/>
)}
<Modal
open={!!deleting}
title="Delete this row?"
description="This cannot be undone."
onClose={() => setDeleting(null)}
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>Delete row</Button></>}
>
<p className="prose">Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.</p>
</Modal>
</>
);
}