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>({}); 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( () => (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(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 { 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 = { 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 = 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(); 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(); 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(); 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(); 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) => 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 = { 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[] = table ? [ { key: "_no", header: "No.", render: numberOf, width: "64px" }, ...screenColumns(table, user.role) .filter((c) => !SERIAL.has(c) && !(!seesAll && IDENTITY.has(c))) .map>((c) => ({ key: c, header: columnLabel(c), nowrap: true, render: (r) => { const value = String(r[c] ?? ""); if (c === "month" && month && isProductList) return value || —; if (canEdit && inline?.has(c)) return saveCell(r, c, v)} />; return value ? (c === "date_of_visit" ? dayOfMonth(value) : DATES.has(c) ? formatDate(value) : value) : —; }, })), { key: "_actions", header: "", align: "right", nowrap: true, sticky: true, render: (r) => ( {showEdit && !isNewRow(r) && } {canDelete && ( )} ), }, ] : []; if (tables.error) return void tables.reload()} />; return ( <>
{!table ? : ( <> {table.label}{showStatus && {status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Manager"}` : "Pending AM approval"}}} description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`} actions={ <> {canSend && } {canApprove && } {canAdd && } } /> {showToolbar && (
{user.role === "AM" && needsApproval && ( )} {hasMonth && ( )} {peopleFilter && ( <> )}
)} {rows.error ? void rows.reload()} /> : ( r.id} footer={footer} loading={rows.loading || waitingForOwners} minWidth={Math.max(640, columns.length * 115)} empty={month ? : isManager && needsApproval && ownerList.length === 0 ? : setEditing({ row: null })}>New row : undefined} />} /> )} )}
{table && editing && ( setEditing(null)} onSaved={(message) => { setEditing(null); toast.success(message); void rows.reload(); void approvals.reload(); }} /> )} setDeleting(null)} footer={<>} >

{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." : ""}}

); }