Files
celtic-life-science/web/src/pages/forms/FormsPage.tsx
T
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

430 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { columnLabel, errorMessage, formatDate, isField } 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 { INLINE_COLUMNS, screenColumns } from "./layout";
import { InlineCell } from "./InlineCell";
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"]);
/** "2026-10-13" -> "13": the Core Doctor Call Conversion form shows only the day of the month. */
const dayOfMonth = (iso: string) => (/^\d{4}-\d{2}-\d{2}/.test(iso) ? String(Number(iso.slice(8, 10))) : iso);
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 month a row belongs to: its own Month column, else the month of its date. */
const rowMonth = (r: CsvRow): string => {
const m = String(r.month ?? "").trim();
if (m) return m;
const d = String(r.report_date ?? "").trim();
if (!d) return "";
const iso = /^(\d{4})-(\d{2})/.exec(d);
if (iso) return MONTHS[Number(iso[2]) - 1] ?? "";
const dmy = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{2,4})/.exec(d);
if (dmy) return MONTHS[Number(dmy[2]) - 1] ?? "";
const t = new Date(d);
return Number.isNaN(t.getTime()) ? "" : MONTHS[t.getMonth()]!;
};
/** Tables whose stored Sl. No. restarts at 1 for each month (see MONTH_NUMBERED_TABLES in
* app/csv_data/router.py) — so it only means something within one chosen month. Viewed across
* "All months" it would repeat 1, 1, 1…, so that view counts fresh over what's actually shown. */
const MONTH_NUMBERED_TABLES = new Set(["sales_projection", "sales_and_stock_statement"]);
/** Forms that are the company's product list: picking a month always shows every product, with
* that month's figures filled in where there are some and blank boxes where there are none. */
const PRODUCT_LIST_TABLES = new Set(["sales_projection", "sales_and_stock_statement"]);
const PRODUCT_COLUMNS = ["pts", "value_in_pts"];
const NEW_ROW = "new:";
const isNewRow = (r: CsvRow) => String(r.id).startsWith(NEW_ROW);
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" || user.role === "GM";
// Admin and the General Manager look across every medical representative; the GM only reads.
const seesAll = user.role === "ADMIN" || user.role === "GM";
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
// Sales Projection isn't an approval form but managers still pick a headquarters / MR to look at.
const hasPeopleFilter = isManager && (needsApproval || seesAll);
const owners = useAsync(() => (hasPeopleFilter ? api.formOwners() : Promise.resolve([])), [hasPeopleFilter], { poll: LIVE });
const [hqChoice, setHqChoice] = useState("");
const [mrChoice, setMrChoice] = useState("");
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 === (seesAll ? mrChoice : 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, mrChoice, seesAll, user.role, approvals.data]);
const waitingForOwners = isManager && needsApproval && !owners.data;
const rows = useAsync<CsvRow[]>(
() => (table && !waitingForOwners ? api.csvRows(table.name, viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined)) : Promise.resolve([])),
[table?.name, viewOwner?.id, mrChoice, 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 = isField(user.role) || user.role === "ADMIN";
// Forms whose figures are typed straight into the table: those cells are boxes, and an MR
// has no Edit drawer (the admin keeps it, to change the product list itself).
const inline = table ? INLINE_COLUMNS[table.name] : undefined;
const showEdit = canEdit && !(inline && isField(user.role));
async function saveCell(row: CsvRow, column: string, value: string): Promise<boolean> {
if (!table) return false;
try {
if (isNewRow(row)) {
// A product with nothing yet in this month: the first figure typed creates its row.
const seed: Record<string, string> = { product_name: String(row.product_name ?? ""), month: String(row.month ?? ""), [column]: value };
for (const c of PRODUCT_COLUMNS) if (table.columns.includes(c) && row[c] !== undefined && c !== column) seed[c] = String(row[c]);
await api.createCsvRow(table.name, seed);
await rows.reload();
return true;
}
// A product's blank row picked up in a month belongs to that month from now on.
const claims: Record<string, string> = month && column !== "month" && !String(row.month ?? "").trim() ? { month } : {};
const saved = await api.updateCsvRow(table.name, row.id, { [column]: value, ...claims });
rows.setData((rows.data ?? []).map((r) => (r.id === row.id ? { ...r, ...saved } : r)));
return true;
} catch (e) {
toast.error(errorMessage(e, "Could not save the value"));
return false;
}
}
// Anyone who fills a form in can remove a row entered by mistake (an MR only their own; the
// server checks). On a shared product list an MR removes an extra copy of a product whole, but
// a product's only row stays for everyone — there they clear their figures instead.
const canDelete = canEdit;
const productKey = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
const copies = useMemo(() => {
const count = new Map<string, number>();
for (const r of rows.data ?? []) count.set(productKey(r), (count.get(productKey(r)) ?? 0) + 1);
return count;
}, [rows.data]);
const clearsInstead = (r: CsvRow) => !!inline && isField(user.role) && (copies.get(productKey(r)) ?? 0) < 2;
const hasFigures = (r: CsvRow) => [...(inline ?? [])].some((c) => String(r[c] ?? "").trim());
// An admin adds rows on behalf of one chosen MR.
const canAdd = canEdit && (!needsApproval || isField(user.role) || !!viewOwner);
const subjectId = isField(user.role) ? 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 && isField(user.role) && 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. Every month is always offered —
// not just ones with rows already in them — so choosing next month before anyone has filled
// it in is a normal, working choice, not something hidden until data happens to exist.
const hasMonthColumn = !!table?.columns.includes("month");
const hasMonth = hasMonthColumn || !!table?.columns.includes("report_date");
const monthsWithRows = useMemo(() => {
if (!hasMonth) return [] as string[];
const seen = new Map<string, string>();
for (const r of rows.data ?? []) { const m = rowMonth(r); 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 already has rows for it, otherwise on everything.
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
// The General Manager and Admin can narrow every form by headquarters and medical representative.
const peopleFilter = seesAll;
// Forms kept per MR on the server are narrowed there; the rest by the name and headquarters written on each row.
const narrowedByServer = !!mrChoice && !!table && (needsApproval || PRODUCT_LIST_TABLES.has(table.name));
const hqOptions = useMemo(() => [...new Set(ownerList.map((o) => o.headquarters_name).filter((h): h is string => !!h))].sort(), [ownerList]);
const mrOptions = ownerList.filter((o) => !hqChoice || sameMonth(o.headquarters_name, hqChoice));
const mrName = mrOptions.find((o) => o.id === mrChoice)?.name;
const isProductList = !!table && PRODUCT_LIST_TABLES.has(table.name);
const shownRows = useMemo(() => {
const base = (rows.data ?? []).filter((r) => !peopleFilter || narrowedByServer || (isProductList && !String(r.name ?? "").trim() && !String(r.headquarter ?? "").trim()) || ((!hqChoice || sameMonth(r.headquarter, hqChoice)) && (!mrName || sameMonth(r.name ?? r.employee_name, mrName))));
// "All MRs": the rows MRs have entered; for a month, every product of the list is there too, blank where nobody has entered it.
const listAcrossMrs = isProductList && peopleFilter && !mrChoice;
if (listAcrossMrs && user.role === "GM" && !month) return base.filter((r) => String(r.month ?? "").trim());
if (!month) return base;
if (listAcrossMrs) {
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
const order: string[] = [];
const entered = new Map<string, CsvRow[]>();
for (const r of base) {
if (!key(r)) continue;
if (!order.includes(key(r))) order.push(key(r));
if (sameMonth(r.month, month)) entered.set(key(r), [...(entered.get(key(r)) ?? []), r]);
}
// What MRs have entered comes first; the products nobody has filled in yet follow.
const blank = order.filter((k) => !entered.has(k)).map((k) => ({ id: NEW_ROW + k, source_row_number: 0, product_name: base.find((r) => key(r) === k)!.product_name, month, name: "", headquarter: "" } as CsvRow));
return [...order.flatMap((k) => entered.get(k) ?? []), ...blank];
}
// "All MRs": the rows that were actually entered. One MR picked: their whole product list for the month, blank lines included.
if (!isProductList || (peopleFilter && !mrChoice)) return base.filter((r) => sameMonth(rowMonth(r), month));
// Every product, once: its row for this month, else its still-unused blank row, else an empty
// placeholder that becomes a real row when a figure is typed into it.
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
const products = new Map<string, CsvRow[]>();
for (const r of base) if (key(r)) products.set(key(r), [...(products.get(key(r)) ?? []), r]);
return [...products.entries()].map(([k, copies]) => {
const mine = copies.find((r) => sameMonth(r.month, month)) ?? copies.find((r) => !String(r.month ?? "").trim());
if (mine) return mine;
const first = copies[0]!;
const seed: CsvRow = { id: NEW_ROW + k, source_row_number: 0, product_name: first.product_name, month };
for (const c of PRODUCT_COLUMNS) if (first[c] !== undefined) seed[c] = first[c];
return seed;
});
}, [rows.data, month, isProductList, peopleFilter, narrowedByServer, mrChoice, hqChoice, mrName]);
const showToolbar = hasMonth || peopleFilter || (isManager && needsApproval);
// Across "All months" a month-numbered table's own Sl. No. would repeat per month, so number
// by position in the list actually on screen instead; a single chosen month already has its
// own correct running numbers from the server, so those are kept as stored.
const continuousNumbering = !!table && MONTH_NUMBERED_TABLES.has(table.name) && (!month || isProductList);
// A form with no Sl. No. column of its own would otherwise show the table-wide row id, which has
// gaps wherever another month or MR has rows in between — so it counts what is on screen instead.
const positional = continuousNumbering || (!!table && !table.columns.includes("serial_no"));
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
const numberOf = (r: CsvRow) => String(positional ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
/** 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 = isField(user.role) ? 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;
const clearing = clearsInstead(deleting);
try {
if (clearing) {
await api.updateCsvRow(table.name, deleting.id, Object.fromEntries([...(inline ?? [])].map((c) => [c, ""])));
toast.success("Figures cleared");
} else {
await api.deleteCsvRow(table.name, deleting.id);
toast.success("Row removed");
}
setDeleting(null);
await Promise.all([rows.reload(), approvals.reload()]);
} catch (e) { toast.error(errorMessage(e, clearing ? "Could not clear the row" : "Could not remove the row")); }
}
// Sales Projection: a Total row combining every row on screen (the chosen month, and for
// managers every medical representative shown).
const footer = useMemo(() => {
if (table?.name === "field_activity_report") {
// Average calls per working day: total calls ÷ the number of distinct dates worked.
const days = new Set(shownRows.filter((r) => String(r.report_date ?? "").trim()).map((r) => String(r.report_date).slice(0, 10))).size;
const avg = (c: string) => {
const total = shownRows.reduce((t, r) => { const n = Number(String(r[c] ?? "").replace(/,/g, "").trim()); return Number.isFinite(n) ? t + n : t; }, 0);
return days ? String(Math.round((total / days) * 100) / 100) : "";
};
return { station_worked: `AVERAGE per working day (${days} day${days === 1 ? "" : "s"})`, no_of_doctors_called: avg("no_of_doctors_called"), no_of_chemists_pds_called: avg("no_of_chemists_pds_called") };
}
if (table?.name !== "sales_projection") return undefined;
const sum = (c: string) => shownRows.reduce((t, r) => { const n = Number(String(r[c] ?? "").replace(/,/g, "").trim()); return Number.isFinite(n) ? t + n : t; }, 0);
const out: Record<string, string> = { product_name: "TOTAL" };
for (const c of ["closing_qty", "closing_value", "projection_qty", "projection_value"]) out[c] = sum(c).toLocaleString("en-IN", { maximumFractionDigits: 2 });
return out;
}, [table?.name, shownRows]);
const columns: Column<CsvRow>[] = table ? [
{ key: "_no", header: "No.", render: numberOf, width: "64px" },
...screenColumns(table, user.role)
.filter((c) => !SERIAL.has(c) && !(!seesAll && IDENTITY.has(c)))
.map<Column<CsvRow>>((c) => ({
key: c,
header: columnLabel(c),
nowrap: true,
render: (r) => {
const value = String(r[c] ?? "");
if (c === "month" && month && isProductList) return value || <span className="muted">—</span>;
if (canEdit && inline?.has(c)) return <InlineCell value={value} column={c} onSave={(v) => saveCell(r, c, v)} />;
return value ? (c === "date_of_visit" ? dayOfMonth(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">
{showEdit && !isNewRow(r) && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
<Button size="sm" variant="ghost" icon="download" disabled={isNewRow(r)} onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
{canDelete && (
<Button size="sm" variant="ghost" icon="trash" disabled={isNewRow(r) || (clearsInstead(r) && !hasFigures(r))} title={clearsInstead(r) ? (hasFigures(r) ? "This is the product's only row, so only its figures are cleared" : "Nothing entered in this row yet") : undefined} onClick={() => setDeleting(r)}>
{clearsInstead(r) ? "Clear" : "Remove"}
</Button>
)}
</span>
),
},
] : [];
if (tables.error) return <ErrorState message={tables.error} onRetry={() => void tables.reload()} />;
return (
<>
<PageHeader title="Company forms" description={user.role === "GM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "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={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>{month && hasMonthColumn ? `Download ${month} PDF` : "Download PDF"}</Button>
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
</>
}
/>
{showToolbar && (
<div className="toolbar">
{user.role === "AM" && needsApproval && (
<label className="filter">
<span>Medical representative</span>
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
{seesAll && <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 && (
<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}{monthsWithRows.some((x) => sameMonth(x, m)) ? "" : " (no rows yet)"}</option>)}
</Select>
</label>
)}
{peopleFilter && (
<>
<label className="filter">
<span>Headquarter</span>
<Select value={hqChoice} onChange={(e) => { setHqChoice(e.target.value); setMrChoice(""); }} aria-label="Headquarter">
<option value="">All headquarters</option>
{hqOptions.map((h) => <option key={h} value={h}>{h}</option>)}
</Select>
</label>
<label className="filter">
<span>MR</span>
<Select value={mrChoice} onChange={(e) => setMrChoice(e.target.value)} aria-label="Medical representative">
<option value="">All MRs</option>
{mrOptions.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
</Select>
</label>
</>
)}
</div>
)}
{rows.error ? <ErrorState message={rows.error} onRetry={() => void rows.reload()} /> : (
<DataTable
columns={columns}
rows={shownRows}
rowKey={(r) => r.id}
footer={footer}
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={deleting && clearsInstead(deleting) ? "Clear this row?" : "Remove this row?"}
description="This cannot be undone."
onClose={() => setDeleting(null)}
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>{deleting && clearsInstead(deleting) ? "Clear figures" : "Remove row"}</Button></>}
>
<p className="prose">{deleting && clearsInstead(deleting)
? <>Everything entered for {String(deleting?.product_name ?? "this product")} (month and figures) will be emptied. The product stays in the list.</>
: <>Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.{needsApproval && isField(user.role) ? " If this form was sent for approval, it goes back to draft." : ""}</>}</p>
</Modal>
</>
);
}