This commit is contained in:
Shubhankar45
2026-10-27 12:03:31 +00:00
parent 2ed3945b5d
commit 4e5e95775d
104 changed files with 5210 additions and 606 deletions
+19 -6
View File
@@ -10,6 +10,7 @@ import { NotFoundPage } from "./pages/NotFoundPage";
import { ProductsPage } from "./pages/ProductsPage";
import { ProfilePage } from "./pages/ProfilePage";
import { AdminPage } from "./pages/admin/AdminPage";
import { UserDetailPage } from "./pages/admin/UserDetailPage";
import { UsersPage } from "./pages/admin/UsersPage";
import { FormsPage } from "./pages/forms/FormsPage";
import { NewReportPage } from "./pages/reports/NewReportPage";
@@ -20,16 +21,28 @@ import type { Role } from "./types";
/** Which roles may open which screens; anything else renders "not found". */
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
{ pattern: "/", render: () => <DashboardPage /> },
{ pattern: "/reports", roles: ["MR", "AM", "GM"], render: () => <ReportsPage /> },
{ pattern: "/reports/new", roles: ["MR"], render: () => <NewReportPage /> },
{ pattern: "/reports/:id", roles: ["MR", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
// Daily Call Report (Plan) and (Done) each have their own list, new-report form and report pages.
{ pattern: "/reports", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/plan", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/done", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="ACTUAL" key="ACTUAL" /> },
{ pattern: "/reports/plan/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/done/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="ACTUAL" key="ACTUAL" /> },
{ pattern: "/reports/plan/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/reports/done/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/reports/self", roles: ["AM", "GM"], render: () => <ReportsPage type="SELF" key="SELF" /> },
{ pattern: "/reports/self/new", roles: ["AM"], render: () => <NewReportPage type="SELF" key="SELF" /> },
{ pattern: "/reports/self/:id", roles: ["AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
// Links from before the split.
{ pattern: "/reports/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/directory", render: () => <DirectoryPage /> },
{ pattern: "/products", render: () => <ProductsPage /> },
{ pattern: "/forms", roles: ["MR", "AM", "ADMIN"], render: () => <FormsPage /> },
{ pattern: "/forms/:table", roles: ["MR", "AM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
{ pattern: "/forms", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: () => <FormsPage /> },
{ pattern: "/forms/:table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
{ pattern: "/profile", render: () => <ProfilePage /> },
{ pattern: "/admin", roles: ["ADMIN"], render: () => <AdminPage /> },
{ pattern: "/admin", roles: ["ADMIN", "MR", "SFE"], render: () => <AdminPage /> },
{ pattern: "/users", roles: ["ADMIN", "GM"], render: () => <UsersPage /> },
{ pattern: "/users/:id", roles: ["ADMIN", "GM"], render: (p) => <UserDetailPage id={p.id!} key={p.id} /> },
];
function Routes({ role }: { role: Role }) {
+14 -3
View File
@@ -1,6 +1,6 @@
import type {
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
FormApproval, Product, Profile, StatusCounts, StockInventory, User,
FormApproval, Product, Profile, UserOverview, ReportType, StatusCounts, StockInventory, User,
} from "../types";
import { API_BASE, auth, download, json, request } from "./client";
@@ -24,14 +24,19 @@ export const api = {
profile: () => request<Profile>("/users/me/profile"),
// daily call reports
reports: () => request<DcrListItem[]>("/dcr?limit=200"),
counts: () => request<StatusCounts>("/dcr/counts"),
/** `type` limits the list to Daily Call Report (Plan) or (Done); omitted, both. */
/** `headquartersId` narrows a manager's list to one of their headquarters. */
reports: (type?: ReportType, headquartersId?: string) => request<DcrListItem[]>(`/dcr${query({ limit: "200", type, headquarters_id: headquartersId })}`),
counts: (headquartersId?: string) => request<StatusCounts>(`/dcr/counts${query({ headquarters_id: headquartersId })}`),
report: (id: string) => request<Dcr>(`/dcr/${id}`),
createReport: (payload: Payload) => request<Dcr>("/dcr", json("POST", payload)),
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
/** End-of-day report: why a planned doctor/chemist (`target` holds doctor_id or chemist_id) was not visited. */
setMissedReason: (id: string, target: Payload, reason: string) => request<Dcr>(`/dcr/${id}/missed`, json("PUT", { ...target, reason })),
clearMissedReason: (id: string, missedId: string) => request<Dcr>(`/dcr/${id}/missed/${missedId}`, json("DELETE")),
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
returnReport: (id: string, reason: string) => request<Dcr>(`/dcr/${id}/return`, json("POST", { reason })),
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
@@ -41,8 +46,14 @@ export const api = {
// masters and organisation
doctors: () => request<Doctor[]>("/doctors"),
chemists: () => request<Chemist[]>("/chemists"),
/** Doctors / chemists added by an MR that wait for (or were refused by) the Area Manager. */
doctorRequests: () => request<Doctor[]>("/doctors/requests"),
chemistRequests: () => request<Chemist[]>("/chemists/requests"),
reviewMaster: (kind: "doctor" | "chemist", id: string, approve: boolean, reason?: string) =>
request<Doctor | Chemist>(`/${kind}s/${id}/${approve ? "approve" : "reject"}`, json("POST", approve ? undefined : { reason })),
headquarters: () => request<Headquarters[]>("/headquarters"),
users: () => request<User[]>("/users"),
userOverview: (id: string) => request<UserOverview>(`/users/${id}/overview`),
areaManagerMappings: () => request<AreaManagerMapping[]>("/headquarters/area-managers"),
setAreaManagerHeadquarters: (areaManagerId: string, headquarters_ids: string[]) =>
request<AreaManagerMapping[]>(`/headquarters/area-managers/${areaManagerId}`, json("PUT", { headquarters_ids })),
@@ -1,6 +1,6 @@
import type { Headquarters } from "../../types";
/** Pick any number of headquarters. `owners` shows who manages each one today. */
/** Pick any number of headquarters. `owners` shows who else manages each one today (a headquarters may have several). */
export function HeadquartersChecklist({ headquarters, selected, onChange, owners = {}, disabled = false }: {
headquarters: Headquarters[];
selected: ReadonlySet<string>;
@@ -21,7 +21,7 @@ export function HeadquartersChecklist({ headquarters, selected, onChange, owners
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
<span className="hq-check-text">
<strong>{h.code}</strong> · {h.name}
{owners[h.id] && <small>Managed by {owners[h.id]}</small>}
{owners[h.id] && <small>Area Manager: {owners[h.id]}</small>}
</span>
</label>
))}
+114
View File
@@ -0,0 +1,114 @@
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>
</>
);
}
+9
View File
@@ -1,4 +1,6 @@
import { Icon } from "../ui/Icon";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { Link } from "../../lib/router";
import { navigationFor } from "../../lib/navigation";
import type { Role } from "../../types";
@@ -9,6 +11,12 @@ export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed,
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
onToggleCollapsed: () => void; onNavigate: () => void;
}) {
// An Area Manager is told how many new doctors / chemists wait for their approval.
const waiting = useAsync(
async () => (role === "AM" ? (await Promise.all([api.doctorRequests(), api.chemistRequests()])).reduce((n, list) => n + list.length, 0) : 0),
[role], { poll: LIVE },
);
const flags: Record<string, number> = { "/directory": waiting.data ?? 0 };
return (
<aside className={`sidebar${collapsed ? " collapsed" : ""}${mobileOpen ? " open" : ""}`} aria-label="Primary">
<Link to="/" className="sidebar-brand" onClick={onNavigate} aria-label="Celtic Life Science — home">
@@ -29,6 +37,7 @@ export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed,
>
<Icon name={item.icon} />
<span>{item.label}</span>
{!collapsed && (flags[item.to] ?? 0) > 0 && <span className="nav-flag" title="Waiting for your approval">{flags[item.to]}</span>}
</Link>
))}
</div>
+55 -31
View File
@@ -1,16 +1,20 @@
import { type FormEvent, useState } from "react";
import { type FormEvent, useEffect, useRef, useState } from "react";
import { Alert } from "../ui/Alert";
import { Button } from "../ui/Button";
import { Field, Input, Select, Textarea } from "../ui/Field";
import { useToast } from "../ui/Toast";
import { ProductPicker } from "./ProductPicker";
import { api } from "../../api";
import { useAsync } from "../../hooks/useAsync";
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
import { amount, maxLength, required, useValidation } from "../../lib/validation";
import type { Chemist, Dcr, Doctor } from "../../types";
export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void;
/** Pre-selects a doctor/chemist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
export interface VisitPreset { kind: "doctor" | "chemist"; targetId: string; key: number }
export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
}) {
const toast = useToast();
const products = useAsync(api.stockInventory, []);
@@ -20,27 +24,43 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
const [time, setTime] = useState(nowHHMM);
const [outcome, setOutcome] = useState("MET");
const [conversion, setConversion] = useState("NOT_STARTED");
const [promote, setPromote] = useState("");
const [sample, setSample] = useState("");
const [promote, setPromote] = useState<string[]>([]);
const [sample, setSample] = useState<string[]>([]);
const [pob, setPob] = useState("");
const [gift, setGift] = useState("");
const [remarks, setRemarks] = useState("");
const [busy, setBusy] = useState(false);
const formRef = useRef<HTMLFormElement>(null);
// A day plan records who and when only; outcomes, products and POB come at the end of the day.
const isPlan = dcr.report_type === "PLAN";
// An Area Manager's own report lists the headquarters' doctors and chemists, not assigned ones.
const isSelf = dcr.report_type === "SELF";
const productNames = (products.data ?? []).map((p) => p.product_name);
useEffect(() => {
if (!preset) return;
setKind(preset.kind);
setTargetId(preset.targetId);
setTime(nowHHMM());
v.clear();
formRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
}, [preset?.key]);
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
const options = kind === "doctor" ? doctors : chemists;
// Visit times are local; today's report cannot hold a visit later than now.
const isToday = dcr.report_date === todayISO();
const isToday = !isPlan && dcr.report_date === todayISO();
const timeLabel = isPlan ? "Planned time" : "Visit time";
const label = kind === "doctor" ? "Doctor" : "Chemist";
const v = useValidation({
target: [required(label)],
time: [required("Visit time"), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
promote: [maxLength(200, "Product promoted")],
sample: [maxLength(200, "Product sample")],
time: [required(timeLabel), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
pob: [maxLength(100, "POB"), amount("POB")],
gift: [maxLength(200, "Gift")],
remarks: [maxLength(2000, "Remarks")],
});
const values = () => ({ target: targetId, time, promote, sample, pob, remarks });
const values = () => ({ target: targetId, time, pob, gift, remarks });
const on = (name: string, set: (value: string) => void) => (e: { target: { value: string } }) => { set(e.target.value); v.retouch(name, e.target.value); };
const blur = (name: string) => (e: { target: { value: string } }) => v.touch(name, e.target.value);
@@ -50,16 +70,20 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
setBusy(true);
setError(null);
try {
const updated = kind === "doctor"
const updated = isPlan
? kind === "doctor"
? await api.addDoctorCall(dcr.id, { doctor_id: targetId, visit_time: time, remarks: remarks.trim() || null })
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, remarks: remarks.trim() || null })
: kind === "doctor"
? await api.addDoctorCall(dcr.id, {
doctor_id: targetId, visit_time: time, call_outcome: outcome,
conversion_status: selectedDoctor?.is_core_doctor ? conversion : null,
product_promote: promote.trim() || null, product_sample: sample.trim() || null, remarks: remarks.trim() || null,
product_promote: promote, product_sample: sample, gift: gift.trim() || null, remarks: remarks.trim() || null,
})
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, pob: pob.trim() || null, remarks: remarks.trim() || null });
onChange(updated);
toast.success(`${label} visit added`);
setTargetId(""); setPromote(""); setSample(""); setPob(""); setRemarks("");
toast.success(isPlan ? `${label} added to the plan` : `${label} visit added`);
setTargetId(""); setPromote([]); setSample([]); setPob(""); setGift(""); setRemarks("");
v.clear();
} catch (err) {
setError(errorMessage(err, "Could not add the visit")); // shown right here, where the MR is looking
@@ -69,7 +93,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
}
return (
<form className="form-grid" onSubmit={submit} noValidate>
<form ref={formRef} className="form-grid" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Visit type">
<Select value={kind} onChange={(e) => { setKind(e.target.value as "doctor" | "chemist"); setTargetId(""); v.clear(); }}>
@@ -77,18 +101,18 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
<option value="chemist">Chemist</option>
</Select>
</Field>
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? `No ${kind}s are assigned to you yet — ask your administrator to assign some.` : undefined}>
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : `No ${kind}s are assigned to you yet — ask your administrator to assign some.`) : undefined}>
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
<option value="">Choose an assigned {kind}</option>
<option value="">{isSelf ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
{options.map((o) => (
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
))}
</Select>
</Field>
<Field label="Visit time" required error={v.errors.time}>
<Field label={timeLabel} required error={v.errors.time}>
<Input type="time" value={time} max={isToday ? nowHHMM() : undefined} onChange={on("time", setTime)} onBlur={blur("time")} />
</Field>
{kind === "doctor" && (
{!isPlan && kind === "doctor" && (
<Field label="Outcome">
<Select value={outcome} onChange={(e) => setOutcome(e.target.value)}>
<option value="MET">Met</option>
@@ -97,7 +121,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
</Select>
</Field>
)}
{selectedDoctor?.is_core_doctor && (
{!isPlan && selectedDoctor?.is_core_doctor && (
<Field label="Core doctor status">
<Select value={conversion} onChange={(e) => setConversion(e.target.value)}>
<option value="NOT_STARTED">Not started</option>
@@ -107,28 +131,28 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
</Select>
</Field>
)}
{kind === "doctor" ? (
{isPlan ? null : kind === "doctor" ? (
<>
<Field label="Product promoted" error={v.errors.promote}>
<Input list="product-suggestions" value={promote} onChange={on("promote", setPromote)} onBlur={blur("promote")} placeholder="Pick or type a product" />
<Field label="Products promoted" hint={`${promote.length} chosen`}>
<ProductPicker value={promote} onChange={setPromote} suggestions={productNames} listId="promote-suggestions" placeholder="Pick or type a product" />
</Field>
<Field label="Product sample" error={v.errors.sample}>
<Input list="product-suggestions" value={sample} onChange={on("sample", setSample)} onBlur={blur("sample")} placeholder="Sample given, if any" />
<Field label="Product samples" hint={`${sample.length} chosen`}>
<ProductPicker value={sample} onChange={setSample} suggestions={productNames} listId="sample-suggestions" placeholder="Samples given, if any" />
</Field>
<Field label="Gift" error={v.errors.gift} hint="Optional — any gift given to the doctor on this visit">
<Input value={gift} onChange={on("gift", setGift)} onBlur={blur("gift")} placeholder="e.g. Diary, pen" />
</Field>
<datalist id="product-suggestions">
{(products.data ?? []).map((p) => <option key={p.id} value={p.product_name} />)}
</datalist>
</>
) : (
<Field label="POB (order booked)" error={v.errors.pob} hint="Amount, e.g. 12500 or 12,500.50">
<Input inputMode="decimal" value={pob} onChange={on("pob", setPob)} onBlur={blur("pob")} placeholder="0" />
</Field>
)}
<Field label="Remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} />
<Field label={isPlan ? "Purpose / note" : "Remarks"} span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} placeholder={isPlan ? "Optional, e.g. follow up on samples" : undefined} />
</Field>
<div className="form-actions">
<Button type="submit" variant="primary" icon="plus" loading={busy}>Add {kind} visit</Button>
<Button type="submit" variant="primary" icon="plus" loading={busy}>{isPlan ? `Add ${kind} to plan` : `Add ${kind} visit`}</Button>
</div>
</form>
);
@@ -0,0 +1,86 @@
import { useState } from "react";
import { Badge } from "../ui/Badge";
import { Button } from "../ui/Button";
import { Field, Textarea } from "../ui/Field";
import { EmptyState } from "../ui/States";
import type { Dcr, PlannedVisit } from "../../types";
const STATUS: Record<PlannedVisit["status"], { label: string; tone: "success" | "warning" | "danger" }> = {
VISITED: { label: "Visited", tone: "success" },
MISSED: { label: "Missed", tone: "warning" },
PENDING: { label: "Not recorded", tone: "danger" },
};
/**
* The approved day plan, line by line, on the end-of-day report. Every line must end up
* visited (a visit recorded below) or missed (with a short note) before the report can be submitted.
*/
export function PlannedVisitList({ dcr, editable, onRecord, onSaveReason, onClearReason }: {
dcr: Dcr;
editable: boolean;
onRecord: (line: PlannedVisit) => void;
onSaveReason: (line: PlannedVisit, reason: string) => Promise<boolean>;
onClearReason: (line: PlannedVisit) => void;
}) {
const [editing, setEditing] = useState<string | null>(null);
const [reason, setReason] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
if (dcr.planned_visits.length === 0) {
return <EmptyState icon="file" title="Nothing was planned" description="The approved Daily Call Report (Plan) has no visits on it." />;
}
const startEdit = (line: PlannedVisit) => { setEditing(line.target_id); setReason(line.missed_reason ?? ""); setError(null); };
const save = async (line: PlannedVisit) => {
if (reason.trim().length < 3) { setError("Say briefly why the visit was missed (3+ characters)."); return; }
if (reason.trim().length > 500) { setError("Keep the note to 500 characters or fewer."); return; }
setSaving(true);
if (await onSaveReason(line, reason.trim())) setEditing(null);
setSaving(false);
};
return (
<ul className="visit-list">
{dcr.planned_visits.map((line) => {
const status = STATUS[line.status];
const isEditing = editable && editing === line.target_id;
return (
<li key={line.target_id} style={isEditing ? { flexWrap: "wrap" } : undefined}>
<span className="visit-time">{line.planned_time.slice(0, 5)}</span>
<div className="visit-main">
<p>
<strong>{line.name}</strong> <Badge tone={line.kind === "DOCTOR" ? "brand" : "neutral"}>{line.kind === "DOCTOR" ? "Doctor" : "Chemist"}</Badge>
{line.is_core_doctor && <> <Badge tone="warning">Core</Badge></>} <Badge tone={status.tone} dot>{status.label}</Badge>
</p>
{line.status === "MISSED" && !isEditing && <p className="visit-detail">Why missed: {line.missed_reason}</p>}
</div>
{editable && !isEditing && line.status === "PENDING" && (
<span className="row-actions">
<Button size="sm" icon="check" onClick={() => onRecord(line)}>Record visit</Button>
<Button size="sm" variant="ghost" icon="edit" onClick={() => startEdit(line)}>Missed</Button>
</span>
)}
{editable && !isEditing && line.status === "MISSED" && (
<span className="row-actions">
<Button size="sm" variant="ghost" icon="edit" onClick={() => startEdit(line)}>Edit note</Button>
<Button size="sm" variant="ghost" icon="x" onClick={() => onClearReason(line)} aria-label={`Clear the missed note for ${line.name}`}>Clear</Button>
</span>
)}
{isEditing && (
<div style={{ flexBasis: "100%" }}>
<Field label={`Why was ${line.name} not visited?`} required error={error ?? undefined} hint={`${reason.length}/500`}>
<Textarea value={reason} onChange={(e) => { setReason(e.target.value); setError(null); }} rows={2} maxLength={500} placeholder="e.g. Doctor on leave, clinic closed, rescheduled to tomorrow" autoFocus />
</Field>
<div className="button-row">
<Button size="sm" onClick={() => setEditing(null)}>Cancel</Button>
<Button size="sm" variant="primary" icon="check" loading={saving} onClick={() => void save(line)}>Save note</Button>
</div>
</div>
)}
</li>
);
})}
</ul>
);
}
@@ -0,0 +1,62 @@
import { type ChangeEvent, type KeyboardEvent, useState } from "react";
import { Button } from "../ui/Button";
import { Icon } from "../ui/Icon";
import { Input } from "../ui/Field";
/** Matches the server's limit per visit. */
export const MAX_PRODUCTS = 10;
/**
* Several products for one visit. Picking a suggestion adds it at once; a name typed by hand is
* added with Enter, the Add button, or on leaving the box (so it is never silently dropped).
* Chosen products show as chips that can be removed.
*/
export function ProductPicker({ value, onChange, suggestions, listId, placeholder }: {
value: string[]; onChange: (next: string[]) => void; suggestions: string[]; listId: string; placeholder: string;
}) {
const [draft, setDraft] = useState("");
const full = value.length >= MAX_PRODUCTS;
const chosen = new Set(value.map((v) => v.toLowerCase()));
const add = (name: string) => {
const clean = name.trim();
if (clean && !full && !chosen.has(clean.toLowerCase())) onChange([...value, clean]);
setDraft("");
};
const typed = (e: ChangeEvent<HTMLInputElement>) => {
const next = e.target.value;
// A datalist pick is not a keystroke. Typing "Zinc" on the way to "Zinc Plus" must not add "Zinc".
const native = e.nativeEvent as Event & { inputType?: string };
const picked = native.inputType === undefined || native.inputType === "insertReplacementText";
if (picked && suggestions.includes(next)) add(next);
else setDraft(next);
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") { e.preventDefault(); add(draft); }
};
return (
<div className="product-picker">
<span className="input-row">
<Input list={listId} value={draft} onChange={typed} onKeyDown={onKey} onBlur={() => add(draft)} disabled={full}
placeholder={full ? `Up to ${MAX_PRODUCTS} products` : placeholder} />
<Button size="sm" icon="plus" onClick={() => add(draft)} disabled={full || !draft.trim()}>Add</Button>
</span>
<datalist id={listId}>
{suggestions.filter((s) => !chosen.has(s.toLowerCase())).map((s) => <option key={s} value={s} />)}
</datalist>
{value.length > 0 && (
<div className="chips">
{value.map((name) => (
<span key={name} className="badge badge-brand chip">
{name}
<button type="button" className="chip-remove" aria-label={`Remove ${name}`} onClick={() => onChange(value.filter((v) => v !== name))}>
<Icon name="x" size={12} />
</button>
</span>
))}
</div>
)}
</div>
);
}
+11 -8
View File
@@ -1,26 +1,29 @@
import { Badge } from "../ui/Badge";
import { DataTable, type Column } from "../ui/DataTable";
import { EmptyState } from "../ui/States";
import { StatusBadge } from "./StatusBadge";
import { formatDate } from "../../lib/format";
import { formatDate, REPORT_TYPE_SHORT } from "../../lib/format";
import { reportPath } from "../../lib/navigation";
import { navigate } from "../../lib/router";
import type { DcrListItem } from "../../types";
const COLUMNS: Column<DcrListItem>[] = [
const columns = (ownerHeader: string): Column<DcrListItem>[] => [
{ key: "date", header: "Report date", render: (r) => <strong>{formatDate(r.report_date)}</strong>, nowrap: true },
{ key: "mr", header: "Medical Representative", render: (r) => r.mr_name },
{ key: "type", header: "Report", render: (r) => <Badge tone={r.report_type === "ACTUAL" ? "brand" : "neutral"}>{REPORT_TYPE_SHORT[r.report_type]}</Badge>, nowrap: true },
{ key: "mr", header: ownerHeader, render: (r) => r.mr_name },
{ key: "hq", header: "Headquarters", render: (r) => r.headquarters_name },
{ key: "calls", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists`, nowrap: true },
{ key: "status", header: "Status", render: (r) => <StatusBadge status={r.status} /> },
{ key: "calls", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists${r.report_type === "PLAN" ? " planned" : ""}`, nowrap: true },
{ key: "status", header: "Status", render: (r) => <StatusBadge status={r.status} type={r.report_type} /> },
];
export function ReportTable({ rows, loading, emptyText = "No reports yet" }: { rows: DcrListItem[]; loading?: boolean; emptyText?: string }) {
export function ReportTable({ rows, loading, emptyText = "No reports yet", ownerHeader = "Medical Representative" }: { rows: DcrListItem[]; loading?: boolean; emptyText?: string; ownerHeader?: string }) {
return (
<DataTable
columns={COLUMNS}
columns={columns(ownerHeader)}
rows={rows}
loading={loading}
rowKey={(r) => r.id}
onRowClick={(r) => navigate(`/reports/${r.id}`)}
onRowClick={(r) => navigate(reportPath(r))}
minWidth={720}
empty={<EmptyState icon="file" title={emptyText} />}
/>
+4 -4
View File
@@ -1,6 +1,6 @@
import { Badge, type Tone } from "../ui/Badge";
import { STATUS_LABEL } from "../../lib/format";
import type { DcrStatus } from "../../types";
import { statusLabel } from "../../lib/format";
import type { DcrStatus, ReportType } from "../../types";
const TONE: Record<DcrStatus, Tone> = {
DRAFT: "neutral",
@@ -9,6 +9,6 @@ const TONE: Record<DcrStatus, Tone> = {
APPROVED: "success",
};
export function StatusBadge({ status }: { status: DcrStatus }) {
return <Badge tone={TONE[status]} dot>{STATUS_LABEL[status]}</Badge>;
export function StatusBadge({ status, type }: { status: DcrStatus; type?: ReportType }) {
return <Badge tone={TONE[status]} dot>{statusLabel(status, type)}</Badge>;
}
+9 -2
View File
@@ -10,7 +10,7 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
const visits: Visit[] = [
...dcr.doctor_calls.map((c) => ({
id: c.id, kind: "Doctor" as const, name: c.doctor_name, time: c.visit_time, core: c.is_core_doctor,
detail: [humanize(c.call_outcome.toLowerCase()), c.conversion_status && humanize(c.conversion_status.toLowerCase()), c.product_promote && `Promote: ${c.product_promote}`, c.product_sample && `Sample: ${c.product_sample}`, c.remarks].filter(Boolean).join(" · "),
detail: [c.call_outcome && humanize(c.call_outcome.toLowerCase()), c.conversion_status && humanize(c.conversion_status.toLowerCase()), c.product_promote.length > 0 && `Promote: ${c.product_promote.join(", ")}`, c.product_sample.length > 0 && `Sample: ${c.product_sample.join(", ")}`, c.gift && `Gift: ${c.gift}`, c.remarks].filter(Boolean).join(" · "),
})),
...dcr.chemist_calls.map((c) => ({
id: c.id, kind: "Chemist" as const, name: c.chemist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
@@ -18,7 +18,14 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
].sort((a, b) => a.time.localeCompare(b.time));
if (visits.length === 0) {
return <EmptyState icon="stethoscope" title="No visits recorded" description={editable ? "Add doctor and chemist visits above." : undefined} />;
const plan = dcr.report_type === "PLAN";
return (
<EmptyState
icon="stethoscope"
title={plan ? "No visits planned" : "No visits recorded"}
description={editable ? (plan ? "Add the doctors and chemists you plan to visit above." : "Add doctor and chemist visits above.") : undefined}
/>
);
}
return (
<ul className="visit-list">
@@ -1,15 +1,18 @@
import { Icon } from "../ui/Icon";
import type { DcrStatus } from "../../types";
import type { DcrStatus, ReportType } from "../../types";
const STEPS = ["Draft", "Area Manager", "Approved"] as const;
const STEPS = ["Draft", "Area Manager", "Approved"];
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_AM: 1, APPROVED: 2 };
/** An Area Manager's own report goes straight from draft to final. */
const SELF_STEPS = ["Draft", "Submitted"];
/** Where a report is in DRAFT → AM → APPROVED. A returned report sits back at step one. */
export function WorkflowTracker({ status }: { status: DcrStatus }) {
const current = INDEX[status];
export function WorkflowTracker({ status, type }: { status: DcrStatus; type?: ReportType }) {
const steps = type === "SELF" ? SELF_STEPS : STEPS;
const current = Math.min(INDEX[status], steps.length - 1);
return (
<ol className="steps" aria-label="Approval progress">
{STEPS.map((label, i) => {
{steps.map((label, i) => {
const state = status === "APPROVED" || i < current ? "done" : i === current ? (status === "RETURNED" ? "returned" : "current") : "todo";
return (
<li key={label} className={`step step-${state}`} aria-current={state === "current" ? "step" : undefined}>
+12 -1
View File
@@ -11,9 +11,11 @@ export interface Column<T> {
sticky?: boolean;
}
export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, onRowClick, minWidth }: {
export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, onRowClick, minWidth, footer }: {
columns: Column<T>[]; rows: T[]; rowKey: (row: T) => string; loading?: boolean;
empty?: ReactNode; onRowClick?: (row: T) => void; minWidth?: number;
/** A summary row pinned under the data (e.g. totals), keyed by column key. */
footer?: Record<string, ReactNode>;
}) {
return (
<div className="table-scroll">
@@ -44,6 +46,15 @@ export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, on
</tr>
))}
</tbody>
{footer && !loading && rows.length > 0 && (
<tfoot>
<tr>
{columns.map((c) => (
<td key={c.key} style={{ textAlign: c.align }} className={[c.nowrap && "nowrap", c.sticky && "col-sticky"].filter(Boolean).join(" ") || undefined}>{footer[c.key]}</td>
))}
</tr>
</tfoot>
)}
</table>
{!loading && rows.length === 0 && empty}
</div>
+25 -6
View File
@@ -1,4 +1,4 @@
import type { DcrStatus, Role } from "../types";
import type { DcrStatus, ReportType, Role } from "../types";
export const STATUS_LABEL: Record<DcrStatus, string> = {
DRAFT: "Draft",
@@ -7,16 +7,28 @@ export const STATUS_LABEL: Record<DcrStatus, string> = {
APPROVED: "Approved",
};
export const REPORT_TYPE_LABEL: Record<ReportType, string> = { PLAN: "Daily Call Report (Plan)", ACTUAL: "Daily Call Report (Done)", SELF: "Daily Call Report (Self)" };
/** Short form for badges and tight spaces. */
export const REPORT_TYPE_SHORT: Record<ReportType, string> = { PLAN: "Plan", ACTUAL: "Done", SELF: "Self" };
/** An Area Manager's own report has no approval: once submitted it is final. */
export const statusLabel = (status: DcrStatus, type?: ReportType) => (type === "SELF" && status === "APPROVED" ? "Submitted" : STATUS_LABEL[status]);
/** The roles that do field work and file reports: an SFE does an MR's work. */
export const isField = (role: string): boolean => role === "MR" || role === "SFE";
export const ROLE_LABEL: Record<Role, string> = {
MR: "Medical Representative",
SFE: "Senior Field Executive",
AM: "Area Manager",
GM: "General Manager",
ADMIN: "Administrator",
};
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
export const todayISO = () => {
/** Today's local date as YYYY-MM-DD, or `days` from today. */
export const todayISO = (days = 0) => {
const d = new Date();
d.setDate(d.getDate() + days);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
@@ -52,10 +64,17 @@ export const humanize = (key: string) =>
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
.join(" ");
/** Column labels that read wrong once spelled out from their key. The stored column is still
* "aug_sales" (the printed form's own field, matching the database and the PDF) — this is only
* what the app displays, since "Aug Sales" is misleading once the row can be any month. */
const COLUMN_LABEL_OVERRIDES: Record<string, string> = { aug_sales: "Month Sales" };
/** Column labels that read wrong once spelled out from their key; the stored column keeps its name. */
const COLUMN_LABEL_OVERRIDES: Record<string, string> = {
kilometers_km: "Kilometers KM (One Way)",
fare: "Fare (Rs)",
da_hq: "Daily allowance – H.Q. (Rs)",
da_ex: "Daily allowance – EX (Rs)",
da_out: "Daily allowance – OUT (Rs)",
postage: "Postage (Rs)",
other_expense: "Other expense (Rs)",
total: "Total (Rs)",
};
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
+17 -2
View File
@@ -1,11 +1,26 @@
import { isField } from "./format";
import type { AreaManagerMapping, Headquarters, User } from "../types";
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
const ids = user.role === "MR"
? (user.headquarters_id ? [user.headquarters_id] : [])
const ids = isField(user.role)
? [...(user.headquarters_id ? [user.headquarters_id] : []), ...(user.extra_headquarter_ids ?? [])]
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
const wanted = new Set(ids);
return { all: false, items: hqs.filter((h) => wanted.has(h.id)) };
}
/**
* The Area Managers of each headquarters, by name ("Asha Rao, Ravi Das"). A headquarters may
* have several. `except` leaves one Area Manager out, e.g. the one whose headquarters are being edited.
*/
export function areaManagersOf(mappings: AreaManagerMapping[], users: User[], except?: string): Record<string, string> {
const name = new Map(users.map((u) => [u.id, u.full_name]));
const byHq = new Map<string, string[]>();
for (const m of mappings) {
if (m.area_manager_user_id === except) continue;
byHq.set(m.headquarters_id, [...(byHq.get(m.headquarters_id) ?? []), name.get(m.area_manager_user_id) ?? "an Area Manager"]);
}
return Object.fromEntries([...byHq].map(([hq, names]) => [hq, names.sort().join(", ")]));
}
+14 -7
View File
@@ -1,5 +1,5 @@
import type { IconName } from "../components/ui/Icon";
import type { Role } from "../types";
import type { ReportType, Role } from "../types";
export interface NavItem {
to: string;
@@ -13,13 +13,20 @@ export interface NavSection {
items: NavItem[];
}
/** Each report type has its own list, so the sidebar highlights the right one on a report's page. */
const REPORTS_PATH: Record<ReportType, string> = { PLAN: "/reports/plan", ACTUAL: "/reports/done", SELF: "/reports/self" };
export const reportsPath = (type: ReportType) => REPORTS_PATH[type];
export const reportPath = (report: { id: string; report_type: ReportType }) => `${reportsPath(report.report_type)}/${report.id}`;
/** Sidebar structure. `roles` limits an item to those roles; omitted means everyone. */
export const NAVIGATION: NavSection[] = [
{
title: "Workspace",
items: [
{ to: "/", label: "Dashboard", icon: "dashboard" },
{ to: "/reports", label: "Daily Call Reports", icon: "file", roles: ["MR", "AM", "GM"] },
{ to: "/reports/plan", label: "Daily Call Report (Plan)", icon: "file", roles: ["MR", "SFE", "AM", "GM"] },
{ to: "/reports/done", label: "Daily Call Report (Done)", icon: "checkCircle", roles: ["MR", "SFE", "AM", "GM"] },
{ to: "/reports/self", label: "Daily Call Report (Self)", icon: "file", roles: ["AM", "GM"] },
],
},
{
@@ -27,13 +34,13 @@ export const NAVIGATION: NavSection[] = [
items: [
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
{ to: "/products", label: "Products", icon: "box" },
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "AM", "ADMIN"] },
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"] },
],
},
{
title: "Administration",
items: [
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN"] },
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN", "MR", "SFE"] },
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
],
},
@@ -49,9 +56,9 @@ export function navigationFor(role: Role): NavSection[] {
/** Title shown in the top bar for the current path. */
export function titleFor(path: string): string {
if (path === "/") return "Dashboard";
if (path === "/reports/new") return "New report";
if (path.startsWith("/reports/")) return "Report";
if (path.startsWith("/reports")) return "Daily Call Reports";
if (path.startsWith("/reports/done")) return "Daily Call Report (Done)";
if (path.startsWith("/reports/self")) return "Daily Call Report (Self)";
if (path.startsWith("/reports")) return "Daily Call Report (Plan)";
if (path.startsWith("/forms")) return "Company forms";
if (path.startsWith("/directory")) return "Doctors & Chemists";
if (path.startsWith("/products")) return "Products";
+119 -20
View File
@@ -3,6 +3,7 @@ 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 { EmptyState, ErrorState } from "../components/ui/States";
import { PageHeader } from "../components/ui/PageHeader";
import { Stat } from "../components/ui/Misc";
@@ -11,7 +12,7 @@ import { LIVE, useAsync } from "../hooks/useAsync";
import { api } from "../api";
import { Link, navigate } from "../lib/router";
import { useUser } from "../lib/session";
import { ROLE_LABEL } from "../lib/format";
import { ROLE_LABEL, isField } from "../lib/format";
import { headquartersOf } from "../lib/headquarters";
import type { DcrListItem, Headquarters, Role, User } from "../types";
@@ -26,12 +27,29 @@ export function DashboardPage() {
return <ReportDashboard role={user.role} name={user.full_name.split(" ")[0]!} />;
}
/**
* Narrows the dashboard to one headquarters. It lists only the headquarters the server lets
* this user see; "" means all of them.
*/
function HeadquartersFilter({ value, onChange }: { value: string; onChange: (id: string) => void }) {
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
return (
<Select className="hq-filter" value={value} onChange={(e) => onChange(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
<option value="">All headquarters</option>
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
);
}
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
const counts = useAsync(api.counts, [], { poll: LIVE });
const reports = useAsync(api.reports, [], { poll: LIVE });
const isMR = role === "MR";
// The General Manager looks across every headquarters, so they can narrow it to one.
const [hq, setHq] = useState("");
const hqId = role === "GM" ? hq || undefined : undefined;
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
const isMR = isField(role);
// A General Manager has no approval step — they get a read-only overview.
const config = role === "GM" ? null : WAITING[role];
const config = role === "GM" ? null : WAITING[isField(role) ? "MR" : (role as "AM")];
const all = reports.data ?? [];
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
@@ -41,10 +59,20 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
title={isMR ? `Good to see you, ${name}` : role === "GM" ? "Reports overview" : "Your review queue"}
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "GM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
actions={isMR
? <Button variant="primary" icon="plus" onClick={() => navigate("/reports/new")}>New report</Button>
: <Button icon="file" onClick={() => navigate("/reports")}>View all reports</Button>}
? <>
<Button icon="plus" onClick={() => navigate("/reports/done/new")}>New report (Done)</Button>
<Button variant="primary" icon="plus" onClick={() => navigate("/reports/plan/new")}>Plan my day</Button>
</>
: <>
{role === "GM" && <HeadquartersFilter value={hq} onChange={setHq} />}
<Button icon="file" onClick={() => navigate("/reports/plan")}>View all reports</Button>
</>}
/>
{role === "SFE" && <MyHeadquarters />}
{role === "GM" && <OrganisationOverview canManage={false} hqId={hqId} />}
<div className="stats">
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
<Stat label="With Area Manager" value={counts.data?.PENDING_AM ?? "–"} tone="warning" />
@@ -66,29 +94,95 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
)}
<Card>
<CardHeader title="Recent reports" description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
<CardHeader title={role === "GM" ? "Recent MR reports" : "Recent reports"} description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
<CardBody flush>
{reports.error ? null : <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
</CardBody>
</Card>
{role === "GM" && <AreaManagerReports hqId={hqId} />}
</>
);
}
/** For a Senior Field Executive: every headquarters (district) they cover, the main one first. */
function MyHeadquarters() {
const user = useUser();
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
const mine = (hqs.data ?? []).filter((h) => h.id === user.headquarters_id || (user.extra_headquarter_ids ?? []).includes(h.id))
.sort((a, b) => Number(b.id === user.headquarters_id) - Number(a.id === user.headquarters_id));
return (
<Card>
<CardHeader title="Your headquarters" description={hqs.data ? `You cover ${mine.length} headquarters. Reports go to the Area Manager of ${mine.find((h) => h.id === user.headquarters_id)?.name ?? "your main headquarters"}.` : "Loading…"} />
<CardBody>
<div className="chip-row">
{mine.map((h) => <Badge key={h.id} tone={h.id === user.headquarters_id ? "brand" : "neutral"}>{h.code} · {h.name}{h.id === user.headquarters_id ? " (main)" : ""}</Badge>)}
</div>
</CardBody>
</Card>
);
}
/** For a General Manager: what the Area Managers did themselves (their Daily Call Report (Self)). */
function AreaManagerReports({ hqId }: { hqId?: string }) {
const reports = useAsync(() => api.reports("SELF", hqId), [hqId], { poll: LIVE });
const all = reports.data ?? [];
const submitted = all.filter((r) => r.status === "APPROVED").length;
return (
<Card>
<CardHeader
title="Area Managers' own reports"
description={reports.data ? `${submitted} submitted · ${all.length - submitted} in draft. Their Daily Call Report (Self), across every headquarters.` : "Their Daily Call Report (Self), across every headquarters."}
actions={<Link to="/reports/self" className="text-link">See all →</Link>}
/>
<CardBody flush>
{reports.error
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
: !reports.loading && all.length === 0
? <EmptyState icon="file" title="No Area Manager reports yet" />
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} ownerHeader="Area Manager" />}
</CardBody>
</Card>
);
}
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
function AdminDashboard() {
const [hq, setHq] = useState("");
return (
<>
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button></>} />
<OrganisationOverview canManage hqId={hq || undefined} />
</>
);
}
/**
* Headquarters and people across the whole company, with a details table per tile.
* The admin manages them; a General Manager (`canManage` false) only looks — every
* headquarters, every MR, AM and GM — and is sent to the People page, never to Setup.
*/
function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?: string }) {
const users = useAsync(api.users, [], { poll: LIVE });
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
const mappings = useAsync(api.areaManagerMappings, [], { poll: LIVE });
const [view, setView] = useState<AdminView | null>(null);
const panel = useRef<HTMLDivElement>(null);
const list = users.data ?? [];
const activeUsers = useMemo(() => list.filter((u) => u.is_active), [list]);
const byRole = (role: Role) => activeUsers.filter((u) => u.role === role);
// With one headquarters chosen: that headquarters, its MRs, the Area Managers who manage it,
// and the General Managers and admins (who cover every headquarters).
const shownHqs = useMemo(() => (hqs.data ?? []).filter((h) => !hqId || h.id === hqId), [hqs.data, hqId]);
const worksIn = (u: User) => {
if (!hqId) return true;
const place = headquartersOf(u, hqs.data ?? [], mappings.data ?? []);
return place.all || place.items.some((h) => h.id === hqId);
};
const activeUsers = useMemo(() => list.filter((u) => u.is_active && worksIn(u)), [list, hqId, hqs.data, mappings.data]);
const byRole = (role: Role) => activeUsers.filter((u) => (role === "MR" ? isField(u.role) : u.role === role));
useEffect(() => {
if (view) panel.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
}, [view]);
@@ -115,26 +209,30 @@ function AdminDashboard() {
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
];
// Setup is the admin's; a GM may open the People page but not Setup.
const manageLink = (to: string) => (canManage || to !== "/admin" ? to : null);
const setupHint = (text: string) => (canManage ? text : undefined);
const detail: Record<AdminView, { title: string; description: string; manage: string; error: string | null; loading: boolean; table: ReactNode }> = {
hq: {
title: "Headquarters", description: "Every headquarters set up for the company.", manage: "/admin",
error: hqs.error, loading: hqs.loading,
table: <DataTable columns={hqColumns} rows={hqs.data ?? []} rowKey={(h) => h.id} loading={hqs.loading} minWidth={560} empty={<EmptyState icon="settings" title="No headquarters yet" description="Create one under Setup → Organisation." />} />,
table: <DataTable columns={hqColumns} rows={shownHqs} rowKey={(h) => h.id} loading={hqs.loading} minWidth={560} empty={<EmptyState icon="settings" title="No headquarters yet" description={setupHint("Create one under Setup → Organisation.")} />} />,
},
mr: {
title: "Medical Representatives", description: "Active MRs and the headquarters they work in.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description="Add one under Setup → People." />} />,
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description={setupHint("Add one under Setup → People.")} />} />,
},
am: {
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description="Add one under Setup → People." />} />,
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description={setupHint("Add one under Setup → People.")} />} />,
},
gm: {
title: "General Managers", description: "Active General Managers. They have a read-only view across every headquarters.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description="Add one under Setup → People." />} />,
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description={setupHint("Add one under Setup → People.")} />} />,
},
users: {
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
@@ -143,12 +241,12 @@ function AdminDashboard() {
},
};
const current = view ? detail[view] : null;
const currentManage = current ? manageLink(current.manage) : null;
return (
<>
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button>} />
<div className="stats stats-5">
<Stat label="Headquarters" value={hqs.data?.length ?? "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
<Stat label="Headquarters" value={hqs.data ? shownHqs.length : "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
<Stat label="Medical Representatives" value={users.data ? byRole("MR").length : "–"} hint="View details" onClick={() => pick("mr")} selected={view === "mr"} />
<Stat label="Area Managers" value={users.data ? byRole("AM").length : "–"} hint="View details" onClick={() => pick("am")} selected={view === "am"} />
<Stat label="General Managers" value={users.data ? byRole("GM").length : "–"} hint="View details" onClick={() => pick("gm")} selected={view === "gm"} />
@@ -160,7 +258,7 @@ function AdminDashboard() {
<CardHeader
title={current.title}
description={current.description}
actions={<><Link to={current.manage} className="text-link">Manage →</Link><Button size="sm" variant="ghost" onClick={() => setView(null)}>Close</Button></>}
actions={<>{currentManage && <Link to={currentManage} className="text-link">{canManage ? "Manage →" : "Open →"}</Link>}<Button size="sm" variant="ghost" onClick={() => setView(null)}>Close</Button></>}
/>
<CardBody flush>
{current.error ? <ErrorState message={current.error} onRetry={() => { void users.reload(); void hqs.reload(); }} /> : current.table}
@@ -168,7 +266,8 @@ function AdminDashboard() {
</Card>
</div>
)}
<Card>
{/* Setup steps are the admin's to follow; the GM's dashboard leaves them out. */}
{canManage && <Card>
<CardHeader title="Recommended order" description="Create organisation data in this order." />
<CardBody>
<ol className="checklist">
@@ -179,7 +278,7 @@ function AdminDashboard() {
<li>Assign doctors and chemists to Medical Representatives</li>
</ol>
</CardBody>
</Card>
</Card>}
</>
);
}
+18 -6
View File
@@ -4,16 +4,17 @@ 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 } from "../components/ui/Field";
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 } from "../lib/format";
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";
@@ -46,9 +47,13 @@ export function DirectoryPage() {
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) => !q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [doctors.data, hqLabel, q]);
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => !q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [chemists.data, hqLabel, q]);
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;
@@ -88,15 +93,22 @@ export function DirectoryPage() {
return (
<>
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); }} />}
<Card>
<div className="toolbar">
<Tabs
label="Directory"
value={tab}
onChange={setTab}
items={[{ key: "doctors", label: "Doctors", count: doctors.data?.length }, { key: "chemists", label: "Chemists", count: chemists.data?.length }]}
items={[{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined }, { key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined }]}
/>
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
<div className="toolbar-group">
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
<option value="">All headquarters</option>
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
</div>
</div>
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
+103 -43
View File
@@ -9,11 +9,14 @@ import { useToast } from "../../components/ui/Toast";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
import { areaManagersOf } from "../../lib/headquarters";
import { MasterRequests } from "../../components/admin/MasterRequests";
import { DataTable, type Column } from "../../components/ui/DataTable";
import { Badge } from "../../components/ui/Badge";
import type { AreaManagerMapping, Headquarters, User } from "../../types";
import { errorMessage } from "../../lib/format";
import { code as codeRule, email as emailRule, focusFirstError, maxLength, minLength, password as passwordRule, phone as phoneRule, required, validateValues, type Errors, type Rule } from "../../lib/validation";
import { errorMessage, todayISO, isField } from "../../lib/format";
import { useUser } from "../../lib/session";
import { code as codeRule, email as emailRule, focusFirstError, isoDate, maxLength, notAfter, minLength, password as passwordRule, phone as phoneRule, required, validateValues, type Errors, type Rule } from "../../lib/validation";
/** Turns a form's FormData into plain strings for the validators. */
const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
@@ -24,8 +27,8 @@ const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([..
* that depend on other fields. Errors show under the matching <Field name="…"> as you leave a
* field, and all of them on submit.
*/
function AdminForm({ title, description, submitLabel, onSubmit, rules, children }: {
title: string; description?: string; submitLabel: string;
function AdminForm({ title, description, submitLabel, onSubmit, rules, successMessage, children }: {
title: string; description?: string; submitLabel: string; successMessage?: string;
onSubmit: (data: FormData) => Promise<unknown>; children: ReactNode;
rules?: Record<string, Rule[]> | ((values: Record<string, string>) => Record<string, Rule[]>);
}) {
@@ -64,7 +67,7 @@ function AdminForm({ title, description, submitLabel, onSubmit, rules, children
await onSubmit(new FormData(form));
form.reset();
setErrors({});
toast.success(`${title} — saved`);
toast.success(successMessage ?? `${title} — saved`);
} catch (err) {
setError(errorMessage(err, "Could not save"));
} finally {
@@ -96,17 +99,88 @@ const optional = (f: FormData, key: string) => text(f, key) || null;
type Section = "organisation" | "people" | "masters" | "assignments";
/** Setup for the signed-in role: an MR gets only the doctor and chemist forms. */
export function AdminPage() {
return isField(useUser().role) ? <MasterDataSetup /> : <FullSetup />;
}
type Refresh = (task: Promise<unknown>) => Promise<unknown>;
/** With a single headquarters in scope (an MR's own), it is preselected. */
function HeadquartersSelect({ hqs }: { hqs: Headquarters[] }) {
return (
<Field label="Headquarters" name="headquarters_id" required>
<Select name="headquarters_id" defaultValue={hqs.length === 1 ? hqs[0].id : ""} key={hqs.map((h) => h.id).join()}>
<option value="">Choose headquarters</option>
{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
</Field>
);
}
/** What an MR sees after adding a doctor or chemist: it is not in their list yet. */
const sentForApproval = (role: string, what: string) => isField(role) ? `${what} sent to your Area Manager for approval` : undefined;
function DoctorForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
const role = useUser().role;
return (
<AdminForm title="Create doctor" submitLabel={isField(role) ? "Send for approval" : "Create doctor"} successMessage={sentForApproval(role, "Doctor")}
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Clinic address"), speciality: [maxLength(100, "Speciality")], phone: [phoneRule], date_of_birth: [isoDate("Date of birth"), notAfter(todayISO(), "Date of birth")] }}
onSubmit={(f) => refresh(api.createDoctor({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), clinic_address: text(f, "address"), speciality: optional(f, "speciality"), qualification: null, contact_number: optional(f, "phone"), date_of_birth: optional(f, "date_of_birth"), is_core_doctor: f.get("core") === "on" }))}>
<HeadquartersSelect hqs={hqs} />
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Clinic address" name="address" required span><Input name="address" /></Field>
<Field label="Speciality" name="speciality"><Input name="speciality" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
<Field label="Date of birth" name="date_of_birth"><Input type="date" name="date_of_birth" max={todayISO()} /></Field>
<Checkbox name="core" label="Core doctor" />
</AdminForm>
);
}
function ChemistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
const role = useUser().role;
return (
<AdminForm title="Create chemist" submitLabel={isField(role) ? "Send for approval" : "Create chemist"} successMessage={sentForApproval(role, "Chemist")}
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Shop address"), phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createChemist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), shop_address: text(f, "address"), contact_number: optional(f, "phone") }))}>
<HeadquartersSelect hqs={hqs} />
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Shop address" name="address" required span><Input name="address" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
</AdminForm>
);
}
/** An MR adds doctors and chemists to their own headquarters; each is assigned to them. */
function MasterDataSetup() {
const hqs = useAsync(() => api.headquarters(), []);
// A new request shows in "Your requests" straight away, not only on the next poll.
const [sent, setSent] = useState(0);
const refresh: Refresh = async (task) => { const result = await task; setSent((n) => n + 1); return result; };
return (
<>
<PageHeader title="Setup" description="Add a doctor or chemist in your headquarters. Your Area Manager approves it, and then it joins your Doctors & Chemists list." />
<Alert tone="danger">{hqs.error}</Alert>
<div className="grid-2">
<DoctorForm hqs={hqs.data ?? []} refresh={refresh} />
<ChemistForm hqs={hqs.data ?? []} refresh={refresh} />
</div>
<MasterRequests key={sent} mode="mine" />
</>
);
}
function FullSetup() {
const [section, setSection] = useState<Section>("organisation");
const data = useAsync(async () => {
const [hqs, users, doctors, chemists, mappings] = await Promise.all([api.headquarters(), api.users(), api.doctors(), api.chemists(), api.areaManagerMappings()]);
return { hqs, users, doctors, chemists, mappings };
}, [], { poll: LIVE });
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
const mrs = users.filter((u) => u.role === "MR");
const mrs = users.filter((u) => isField(u.role));
const ams = users.filter((u) => u.role === "AM");
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
const hqOptions = hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>);
return (
<>
@@ -143,24 +217,8 @@ export function AdminPage() {
{section === "masters" && (
<div className="grid-2">
<AdminForm title="Create doctor" submitLabel="Create doctor"
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Clinic address"), speciality: [maxLength(100, "Speciality")], phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createDoctor({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), clinic_address: text(f, "address"), speciality: optional(f, "speciality"), qualification: null, contact_number: optional(f, "phone"), is_core_doctor: f.get("core") === "on" }))}>
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Clinic address" name="address" required span><Input name="address" /></Field>
<Field label="Speciality" name="speciality"><Input name="speciality" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
<Checkbox name="core" label="Core doctor" />
</AdminForm>
<AdminForm title="Create chemist" submitLabel="Create chemist"
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Shop address"), phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createChemist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), shop_address: text(f, "address"), contact_number: optional(f, "phone") }))}>
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Shop address" name="address" required span><Input name="address" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
</AdminForm>
<DoctorForm hqs={hqs} refresh={refresh} />
<ChemistForm hqs={hqs} refresh={refresh} />
<AdminForm title="Create product" submitLabel="Create product"
rules={{ name: nameRule("Product name"), pack: [maxLength(100, "Pack")], unit: [maxLength(50, "Unit")] }}
onSubmit={(f) => refresh(api.createProduct({ name: text(f, "name"), pack: optional(f, "pack"), unit: optional(f, "unit") }))}>
@@ -191,17 +249,12 @@ export function AdminPage() {
);
}
/** Owner name per headquarters, from the current Area Manager mappings. */
function ownersOf(mappings: AreaManagerMapping[], users: User[]): Record<string, string> {
const name = new Map(users.map((u) => [u.id, u.full_name]));
return Object.fromEntries(mappings.map((m) => [m.headquarters_id, name.get(m.area_manager_user_id) ?? "an Area Manager"]));
}
/** Choose an Area Manager, then tick every headquarters they should manage. */
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
const [amId, setAmId] = useState("");
const [picked, setPicked] = useState<Set<string>>(new Set());
const owners = ownersOf(mappings, users);
// The other Area Managers of each headquarters: ticking one adds this AM beside them.
const owners = areaManagersOf(mappings, users, amId || undefined);
function choose(id: string) {
setAmId(id);
@@ -210,7 +263,7 @@ function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[];
return (
<AdminForm
title="Assign headquarters to an Area Manager"
description="An Area Manager can manage any number of headquarters. A headquarters has one Area Manager, so ticking one that is managed by someone else moves it."
description="An Area Manager can manage any number of headquarters, and a headquarters can have several Area Managers. Ticking one already managed by someone else adds this Area Manager beside them."
submitLabel="Save assignments"
rules={{ area_manager_user_id: [required("Area Manager")] }}
onSubmit={async () => {
@@ -234,13 +287,13 @@ function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[];
/** Every headquarters and who manages it — visible at a glance. */
function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquarters[]; users: User[]; mappings: AreaManagerMapping[]; loading: boolean }) {
const owners = ownersOf(mappings, users);
const mrCount = (id: string) => users.filter((u) => u.role === "MR" && u.is_active && u.headquarters_id === id).length;
const owners = areaManagersOf(mappings, users);
const mrCount = (id: string) => users.filter((u) => isField(u.role) && u.is_active && u.headquarters_id === id).length;
const columns: Column<Headquarters>[] = [
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
{ key: "name", header: "Headquarters", render: (h) => h.name },
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
{ key: "am", header: "Area Manager", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
{ key: "am", header: "Area Managers", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
{ key: "mrs", header: "MRs", render: (h) => mrCount(h.id), align: "right", nowrap: true },
];
return (
@@ -254,7 +307,7 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
}
const ROLES = [
{ value: "MR", label: "Medical Representative" }, { value: "AM", label: "Area Manager" },
{ value: "MR", label: "Medical Representative" }, { value: "SFE", label: "Senior Field Executive" }, { value: "AM", label: "Area Manager" },
{ value: "GM", label: "General Manager" }, { value: "ADMIN", label: "Administrator" },
] as const;
@@ -262,6 +315,7 @@ const ROLES = [
function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task: Promise<T>) => Promise<T> }) {
const [role, setRole] = useState<string>("MR");
const [picked, setPicked] = useState<Set<string>>(new Set());
const [extras, setExtras] = useState<Set<string>>(new Set());
return (
<AdminForm
title="Create user" submitLabel="Create user"
@@ -271,16 +325,17 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
email: [required("Email"), emailRule],
password: [required("Password"), passwordRule],
phone: [phoneRule],
...(role === "MR" ? { headquarters_id: [required("Headquarters")] } : {}),
...(isField(role) ? { headquarters_id: [required("Headquarters")] } : {}),
}}
onSubmit={async (f) => {
const created = await api.createUser({
email: text(f, "email"), password: text(f, "password"), full_name: text(f, "full_name"),
employee_code: text(f, "employee_code"), phone: optional(f, "phone"), role,
headquarters_id: role === "MR" ? text(f, "headquarters_id") : null,
headquarters_id: isField(role) ? text(f, "headquarters_id") : null,
...(role === "SFE" ? { extra_headquarter_ids: [...extras].filter((id) => id !== text(f, "headquarters_id")) } : {}),
});
if (role === "AM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
setRole("MR"); setPicked(new Set());
setRole("MR"); setPicked(new Set()); setExtras(new Set());
await refresh(Promise.resolve(created));
}}
>
@@ -288,13 +343,18 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
<Field label="Employee code" name="employee_code" required><Input name="employee_code" /></Field>
<Field label="Email" name="email" required><Input type="email" name="email" autoComplete="off" /></Field>
<Field label="Password" name="password" required hint="At least 8 characters, with a letter and a number."><Input type="password" name="password" autoComplete="new-password" /></Field>
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); setExtras(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
{role === "MR" && (
<Field label="Headquarters" name="headquarters_id" required hint="The headquarters this Medical Representative works in.">
{isField(role) && (
<Field label="Headquarters" name="headquarters_id" required hint={role === "SFE" ? "Their main headquarters: reports go to its Area Manager." : "The headquarters this Medical Representative works in."}>
<Select name="headquarters_id"><option value="">Choose headquarters</option>{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}</Select>
</Field>
)}
{role === "SFE" && (
<Field label="Other districts they cover" span group hint={`Optional. ${extras.size} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
<HeadquartersChecklist headquarters={hqs} selected={extras} onChange={setExtras} />
</Field>
)}
{role === "AM" && (
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
+168
View File
@@ -0,0 +1,168 @@
import type { ReactNode } 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 { PageHeader } from "../../components/ui/PageHeader";
import { StatusBadge } from "../../components/reports/StatusBadge";
import { EmptyState, ErrorState, Skeleton } from "../../components/ui/States";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { ROLE_LABEL, REPORT_TYPE_LABEL, STATUS_LABEL, formatDate, isField } from "../../lib/format";
import { Link } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { DcrListItem, DcrStatus, ReportType, UserOverview } from "../../types";
const STATUSES: DcrStatus[] = ["DRAFT", "PENDING_AM", "RETURNED", "APPROVED"];
const APPROVAL_TONE = { draft: "neutral", pending: "warning", approved: "success" } as const;
const APPROVAL_LABEL = { draft: "Draft", pending: "With Area Manager", approved: "Approved" } as const;
/** One person's whole picture, for the General Manager and Admin: where they work, who they report to, their people, reports and forms. */
export function UserDetailPage({ id }: { id: string }) {
const viewer = useUser();
const data = useAsync(() => api.userOverview(id), [id], { poll: LIVE });
const o = data.data;
if (data.error) return <ErrorState message={data.error} onRetry={() => void data.reload()} />;
if (!o) return <Skeleton lines={8} />;
const { user } = o;
const field = isField(user.role);
return (
<>
<PageHeader
back={{ to: "/users", label: "All users" }}
title={<>{user.full_name} <Badge tone="brand">{user.is_superadmin ? "Super Admin" : ROLE_LABEL[user.role]}</Badge> <Badge tone={user.is_active ? "success" : "neutral"} dot>{user.is_active ? "Active" : "Inactive"}</Badge></>}
description={`${user.email} · Code ${user.employee_code}${user.phone ? ` · ${user.phone}` : ""}`}
/>
<div className="detail-grid">
<Card>
<CardHeader title={user.role === "AM" ? "Headquarters they manage" : field ? "Headquarters" : "Headquarters"} description={user.role === "AM" ? `${o.headquarters.length} headquarters` : field ? "The main headquarters is where their reports are sent." : undefined} />
<CardBody>
{o.headquarters.length === 0
? <span className="muted">{field || user.role === "AM" ? "None assigned" : "This role sees every headquarters."}</span>
: <div className="chip-row">{o.headquarters.map((h) => (
<Badge key={h.id} tone={h.main ? "brand" : "neutral"}>{h.code} · {h.name}{h.main && field && o.headquarters.length > 1 ? " (main)" : ""}{h.field_staff !== undefined ? ` · ${h.field_staff} field staff` : ""}</Badge>
))}</div>}
</CardBody>
</Card>
{field && (
<Card>
<CardHeader title="Reports to" description="Area Manager(s) of the main headquarters" />
<CardBody>
{o.reporting_managers.length === 0 ? <span className="muted">No Area Manager assigned</span>
: <div className="chip-row">{o.reporting_managers.map((m) => <Link key={m.id} to={`/users/${m.id}`}><Badge tone="brand">{m.full_name}</Badge></Link>)}</div>}
</CardBody>
</Card>
)}
</div>
{field && <PeopleCards o={o} />}
{user.role === "AM" && <Team o={o} />}
{(field || user.role === "AM") && <ReportsSection o={o} viewerRole={viewer.role} title={user.role === "AM" ? "Reports in their headquarters" : "Daily call reports"} />}
{user.role === "AM" && o.own_reports && o.own_reports.length > 0 && (
<ReportList title="Their own reports (Daily Call Report (Self))" rows={o.own_reports} link={viewer.role === "GM"} />
)}
{field && <Forms o={o} />}
{!field && user.role !== "AM" && <Card><CardBody><EmptyState icon="users" title="Nothing field-related to show" description="This role sets things up or looks across the company; it has no doctors, reports or forms of its own." /></CardBody></Card>}
</>
);
}
function PeopleCards({ o }: { o: UserOverview }) {
const doctorCols: Column<UserOverview["doctors"][number]>[] = [
{ key: "n", header: "Doctor", render: (d) => <strong>{d.name}{d.is_core_doctor ? " ★" : ""}</strong> },
{ key: "s", header: "Speciality", render: (d) => d.speciality ?? "—" },
{ key: "h", header: "Headquarters", render: (d) => d.headquarters_name, nowrap: true },
{ key: "a", header: "Clinic", render: (d) => d.clinic_address },
];
const chemistCols: Column<UserOverview["chemists"][number]>[] = [
{ key: "n", header: "Chemist", render: (c) => <strong>{c.name}</strong> },
{ key: "h", header: "Headquarters", render: (c) => c.headquarters_name, nowrap: true },
{ key: "a", header: "Shop", render: (c) => c.shop_address },
];
return (
<>
<Card>
<CardHeader title="Assigned doctors" description={`${o.doctors.length} doctor${o.doctors.length === 1 ? "" : "s"} · ★ core doctor`} />
<CardBody flush><DataTable columns={doctorCols} rows={o.doctors} rowKey={(d) => d.id} minWidth={560} empty={<EmptyState icon="users" title="No doctors assigned" />} /></CardBody>
</Card>
<Card>
<CardHeader title="Assigned chemists" description={`${o.chemists.length} chemist${o.chemists.length === 1 ? "" : "s"}`} />
<CardBody flush><DataTable columns={chemistCols} rows={o.chemists} rowKey={(c) => c.id} minWidth={520} empty={<EmptyState icon="users" title="No chemists assigned" />} /></CardBody>
</Card>
</>
);
}
function Team({ o }: { o: UserOverview }) {
const cols: Column<UserOverview["team"][number]>[] = [
{ key: "n", header: "Name", render: (p) => <Link to={`/users/${p.id}`} className="text-link"><strong>{p.full_name}</strong></Link> },
{ key: "r", header: "Role", render: (p) => <Badge tone="brand">{ROLE_LABEL[p.role]}</Badge>, nowrap: true },
{ key: "h", header: "Main headquarters", render: (p) => p.headquarters ?? "—", nowrap: true },
{ key: "s", header: "Status", render: (p) => <Badge tone={p.is_active ? "success" : "neutral"} dot>{p.is_active ? "Active" : "Inactive"}</Badge> },
];
return (
<Card>
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Manager" />
<CardBody flush><DataTable columns={cols} rows={o.team} rowKey={(p) => p.id} minWidth={520} empty={<EmptyState icon="users" title="Nobody reports to them yet" />} /></CardBody>
</Card>
);
}
function ReportsSection({ o, viewerRole, title }: { o: UserOverview; viewerRole: string; title: string }) {
const types: ReportType[] = ["PLAN", "ACTUAL"];
return (
<>
<Card>
<CardHeader title={title} description="How many reports are in each state" />
<CardBody>
<div className="summary-grid">
{types.map((t) => (
<div key={t} className="summary-block">
<strong>{REPORT_TYPE_LABEL[t]}</strong>
<div className="chip-row">
{STATUSES.map((s) => <Badge key={s} tone={s === "APPROVED" ? "success" : s === "RETURNED" ? "danger" : s === "PENDING_AM" ? "warning" : "neutral"}>{STATUS_LABEL[s]}: {o.reports.counts[t]?.[s] ?? 0}</Badge>)}
</div>
</div>
))}
</div>
</CardBody>
</Card>
<ReportList title="Latest reports" rows={o.reports.recent} link={viewerRole === "GM"} />
</>
);
}
function ReportList({ title, rows, link }: { title: string; rows: DcrListItem[]; link: boolean }) {
const cols: Column<DcrListItem>[] = [
{ key: "d", header: "Report date", render: (r) => link ? <Link to={`/reports/${r.id}`} className="text-link">{formatDate(r.report_date)}</Link> : formatDate(r.report_date), nowrap: true },
{ key: "t", header: "Report", render: (r) => <Badge>{r.report_type === "PLAN" ? "Plan" : r.report_type === "ACTUAL" ? "Done" : "Self"}</Badge> },
{ key: "p", header: "By", render: (r) => r.mr_name },
{ key: "h", header: "Headquarters", render: (r) => r.headquarters_name },
{ key: "v", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists`, nowrap: true },
{ key: "s", header: "Status", render: (r) => <StatusBadge status={r.status} type={r.report_type} /> },
];
return (
<Card>
<CardHeader title={title} />
<CardBody flush><DataTable columns={cols} rows={rows} rowKey={(r) => r.id} minWidth={640} empty={<EmptyState icon="file" title="No reports yet" />} /></CardBody>
</Card>
);
}
function Forms({ o }: { o: UserOverview }) {
const cols: Column<UserOverview["forms"][number]>[] = [
{ key: "l", header: "Company form", render: (f) => <Link to={`/forms/${f.table}`} className="text-link"><strong>{f.label}</strong></Link> },
{ key: "r", header: "Rows", render: (f) => f.rows, nowrap: true },
{ key: "m", header: "Months filled", render: (f) => (f.months.length ? f.months.join(", ") : <span className="muted">—</span>) },
{ key: "a", header: "Approval", render: (f): ReactNode => (f.approval_status ? <Badge tone={APPROVAL_TONE[f.approval_status]} dot>{APPROVAL_LABEL[f.approval_status]}</Badge> : <span className="muted">—</span>), nowrap: true },
];
return (
<Card>
<CardHeader title="Company forms" description="What they have filled in. Open a form to pick them under the MR filter." actions={<Link to="/forms"><Button size="sm">All forms</Button></Link>} />
<CardBody flush><DataTable columns={cols} rows={o.forms} rowKey={(f) => f.table} minWidth={560} /></CardBody>
</Card>
);
}
+67 -16
View File
@@ -1,6 +1,6 @@
import { type FormEvent, useMemo, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Field, Input } from "../../components/ui/Field";
import { Field, Input, Select } from "../../components/ui/Field";
import { Modal } from "../../components/ui/Modal";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
@@ -14,11 +14,12 @@ import { useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { LIVE } from "../../hooks/useAsync";
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
import { headquartersOf } from "../../lib/headquarters";
import { areaManagersOf, headquartersOf } from "../../lib/headquarters";
import { code as codeRule, email as emailRule, maxLength, minLength, password as passwordRule, phone as phoneRule, required, useValidation } from "../../lib/validation";
import { ROLE_LABEL, errorMessage } from "../../lib/format";
import { ROLE_LABEL, errorMessage, isField } from "../../lib/format";
import { Link } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { AreaManagerMapping, Headquarters, User } from "../../types";
import type { AreaManagerMapping, Headquarters, Role, User } from "../../types";
export function UsersPage() {
const me = useUser();
@@ -31,6 +32,7 @@ export function UsersPage() {
const hqs = org.data?.hqs ?? [];
const mappings = org.data?.mappings ?? [];
const [query, setQuery] = useState("");
const [hqFilter, setHqFilter] = useState("");
const canManage = me.role === "ADMIN";
const [editing, setEditing] = useState<User | null>(null);
@@ -43,13 +45,15 @@ export function UsersPage() {
}
const columns: Column<User>[] = [
{ key: "name", header: "Name", render: (u) => <strong>{u.full_name}</strong> },
{ key: "name", header: "Name", render: (u) => <Link to={`/users/${u.id}`} className="text-link"><strong>{u.full_name}</strong></Link> },
{ key: "email", header: "Email", render: (u) => u.email },
{ key: "code", header: "Code", render: (u) => u.employee_code, nowrap: true },
{ key: "role", header: "Role", render: (u) => <Badge tone="brand">{ROLE_LABEL[u.role]}</Badge>, nowrap: true },
{ key: "role", header: "Role", render: (u) => <Badge tone="brand">{u.is_superadmin ? "Super Admin" : ROLE_LABEL[u.role]}</Badge>, nowrap: true },
{ key: "hq", header: "Headquarters", render: (u) => <HqChips user={u} hqs={hqs} mappings={mappings} /> },
{ key: "status", header: "Status", render: (u) => <Badge tone={u.is_active ? "success" : "neutral"} dot>{u.is_active ? "Active" : "Inactive"}</Badge> },
...(canManage ? [{ key: "action", header: "", align: "right" as const, nowrap: true, render: (u: User) => (
...(canManage ? [{ key: "action", header: "", align: "right" as const, nowrap: true, render: (u: User) => u.is_superadmin ? (
<Badge tone="neutral">Protected</Badge>
) : (
<span className="row-actions">
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(u)}>Edit</Button>
<Button size="sm" onClick={() => void toggle(u)} disabled={u.id === me.id}>{u.is_active ? "Deactivate" : "Activate"}</Button>
@@ -59,18 +63,28 @@ export function UsersPage() {
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return (users.data ?? []).filter((u) => {
if (!q) return true;
const place = headquartersOf(u, hqs, mappings);
// One headquarters chosen: only the people who work in it (GM and Admin cover all, so they drop out).
if (hqFilter && !place.items.some((h) => h.id === hqFilter)) return false;
if (!q) return true;
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
return `${u.full_name} ${u.email} ${u.employee_code} ${u.role} ${where}`.toLowerCase().includes(q);
});
}, [users.data, hqs, mappings, query]);
}, [users.data, hqs, mappings, query, hqFilter]);
return (
<>
<PageHeader title="Users" description={canManage ? "Manage who can sign in and what they can do." : "View active and inactive users."} />
<Card>
<div className="toolbar toolbar-end"><SearchInput value={query} onChange={setQuery} placeholder="Search users" /></div>
<div className="toolbar toolbar-end">
<div className="toolbar-group">
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters">
<option value="">All headquarters</option>
{[...hqs].sort((a, b) => a.name.localeCompare(b.name)).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
<SearchInput value={query} onChange={setQuery} placeholder="Search users" />
</div>
</div>
{users.error
? <ErrorState message={users.error} onRetry={() => void users.reload()} />
: <DataTable columns={columns} rows={rows} rowKey={(u) => u.id} loading={users.loading} minWidth={860} empty={<EmptyState icon="users" title="No users found" />} />}
@@ -96,12 +110,16 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
const [phone, setPhone] = useState(user.phone ?? "");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const isAm = user.role === "AM";
const [role, setRole] = useState<Role>(user.role);
const [hqId, setHqId] = useState(user.headquarters_id ?? "");
const roleChanged = role !== user.role;
const isAm = role === "AM";
const hqChanged = !roleChanged && isField(user.role) && isField(role) && hqId !== (user.headquarters_id ?? "");
const editingSelf = user.id === me.id;
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
const [extras, setExtras] = useState<Set<string>>(() => new Set(user.extra_headquarter_ids ?? []));
const [picked, setPicked] = useState<Set<string>>(() => new Set(mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id)));
const names = new Map(users.map((u) => [u.id, u.full_name]));
const owners = Object.fromEntries(mappings.filter((m) => m.area_manager_user_id !== user.id).map((m) => [m.headquarters_id, names.get(m.area_manager_user_id) ?? "another Area Manager"]));
const owners = areaManagersOf(mappings, users, user.id);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -111,6 +129,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
code: [required("Employee code"), maxLength(50, "Employee code"), codeRule("Employee code")],
phone: [phoneRule],
password: [passwordRule],
hq: [(value) => (isField(role) && !value ? "Headquarters is required" : null)],
});
const bind = (key: string, set: (value: string) => void) => ({
onChange: (e: { target: { value: string } }) => { set(e.target.value); v.retouch(key, e.target.value); },
@@ -119,7 +138,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ name, email, code, phone, password }, e.currentTarget)) return;
if (!v.check({ name, email, code, phone, password, hq: hqId }, e.currentTarget)) return;
setBusy(true);
setError(null);
try {
@@ -128,6 +147,10 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
if (code.trim() !== user.employee_code) payload.employee_code = code.trim();
if (phone.trim() !== (user.phone ?? "")) payload.phone = phone.trim() || null;
if (password) payload.password = password;
if (roleChanged) payload.role = role;
if (isField(role) && (roleChanged || hqId !== user.headquarters_id)) payload.headquarters_id = hqId;
else if (roleChanged) payload.headquarters_id = null;
if (role === "SFE") payload.extra_headquarter_ids = [...extras].filter((id) => id !== hqId);
await api.updateUser(user.id, payload);
if (isAm) await api.setAreaManagerHeadquarters(user.id, [...picked]);
onSaved();
@@ -151,6 +174,14 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
<Field label="Full name" required error={v.errors.name}><Input value={name} {...bind("name", setName)} /></Field>
<Field label="Email (sign-in)" required error={v.errors.email}><Input type="email" value={email} autoComplete="off" {...bind("email", setEmail)} /></Field>
<Field label="Employee code" required error={v.errors.code}><Input value={code} {...bind("code", setCode)} /></Field>
{isField(role) && (
<Field label="Headquarters" required error={v.errors.hq} hint="The headquarters this Medical Representative works in. You can change it any time.">
<Select value={hqId} onChange={(e) => { setHqId(e.target.value); v.retouch("hq", e.target.value); }}>
<option value="">Choose headquarters</option>
{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
</Field>
)}
<Field label="Phone" error={v.errors.phone}><Input value={phone} inputMode="tel" {...bind("phone", setPhone)} /></Field>
<Field label="New password" error={v.errors.password} hint="Leave empty to keep the current password. At least 8 characters, with a letter and a number.">
<span className="input-row">
@@ -159,15 +190,35 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
<Button size="sm" onClick={() => { setPassword(generatePassword()); setShowPassword(true); }}>Generate</Button>
</span>
</Field>
<Field label="Role" hint={editingSelf ? "You cannot change your own role." : undefined}>
<Select value={role} disabled={editingSelf} onChange={(e) => setRole(e.target.value as Role)}>
{(Object.keys(ROLE_LABEL) as Role[]).map((r) => <option key={r} value={r}>{ROLE_LABEL[r]}</option>)}
</Select>
</Field>
{roleChanged && (
<Alert tone="warning">
{user.full_name} will be signed out and must sign in again as {ROLE_LABEL[role]}.
{isField(user.role) && " Their doctor and chemist assignments end, so reassign them in Setup → Assignments."}
{user.role === "AM" && " The headquarters they manage are released; any that have no other Area Manager need a new one."}
</Alert>
)}
{hqChanged && (
<Alert tone="warning">{user.full_name} moves to the new headquarters. Their current doctor and chemist assignments end, so reassign them in Setup → Assignments. Their forms then show the new headquarters.</Alert>
)}
{credentialsChanged && (
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
)}
{role === "SFE" && (
<Field label="Other districts they cover" group hint={`${[...extras].filter((id) => id !== hqId).length} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
<HeadquartersChecklist headquarters={hqs.filter((h) => h.id !== hqId)} selected={extras} onChange={setExtras} />
</Field>
)}
{isAm && (
<Field label="Headquarters they manage" group hint={`${picked.size} selected. Ticking one managed by someone else moves it here.`}>
<Field label="Headquarters they manage" group hint={`${picked.size} selected. A headquarters can have several Area Managers; the others keep theirs.`}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
</Field>
)}
{(user.role === "GM" || user.role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
{(role === "GM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
</form>
</Modal>
);
+200 -37
View File
@@ -10,22 +10,45 @@ 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 } from "../../lib/format";
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"]);
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();
@@ -37,53 +60,96 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
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";
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.
const owners = useAsync(() => (isManager && needsApproval ? api.formOwners() : Promise.resolve([])), [isManager, needsApproval], { poll: LIVE });
// 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 === ownerChoice);
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, user.role, approvals.data]);
}, [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) : Promise.resolve([])),
[table?.name, viewOwner?.id, waitingForOwners], { poll: LIVE },
() => (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 = user.role === "MR" || user.role === "ADMIN";
// Only an admin may delete a row — an MR can edit their own forms but not remove rows from them.
const canDelete = user.role === "ADMIN";
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 || user.role === "MR" || !!viewOwner);
const subjectId = user.role === "MR" ? user.id : viewOwner?.id;
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 && user.role === "MR" && status === "draft" && hasRows;
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 hasMonth = !!table?.columns.includes("month");
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 = String(r.month ?? "").trim(); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
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]);
@@ -92,22 +158,67 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
// 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)) ?? "";
const shownRows = month ? (rows.data ?? []).filter((r) => sameMonth(r.month, month)) : rows.data ?? [];
const showToolbar = hasMonth || (isManager && needsApproval);
// 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;
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(continuousNumbering ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
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 = user.role === "MR" ? user.id : viewOwner?.id;
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"
@@ -134,34 +245,65 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
async function confirmDelete() {
if (!table || !deleting) return;
const clearing = clearsInstead(deleting);
try {
await api.deleteCsvRow(table.name, deleting.id);
toast.success("Row deleted");
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, "Could not delete the row")); }
} 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" },
...table.columns
.filter((c) => !SERIAL.has(c) && !(user.role !== "ADMIN" && IDENTITY.has(c)))
...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] ?? "");
return value ? (DATES.has(c) ? formatDate(value) : value) : <span className="muted">—</span>;
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">
{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>
{canDelete && <Button size="sm" variant="ghost" icon="trash" onClick={() => setDeleting(r)} aria-label="Delete row" />}
{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>
),
},
@@ -171,7 +313,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
return (
<>
<PageHeader title="Company forms" description="Fill in the company’s standard forms and print them as ready-to-sign PDFs." />
<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) => (
@@ -192,18 +334,18 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
<>
{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, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</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">
{isManager && needsApproval && (
{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">
{user.role === "ADMIN" && <option value="">All medical representatives</option>}
{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>
@@ -217,6 +359,24 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
</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()} /> : (
@@ -224,6 +384,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
columns={columns}
rows={shownRows}
rowKey={(r) => r.id}
footer={footer}
loading={rows.loading || waitingForOwners}
minWidth={Math.max(640, columns.length * 115)}
empty={month
@@ -254,12 +415,14 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
<Modal
open={!!deleting}
title="Delete this row?"
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()}>Delete row</Button></>}
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>{deleting && clearsInstead(deleting) ? "Clear figures" : "Remove row"}</Button></>}
>
<p className="prose">Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.</p>
<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>
</>
);
+85
View File
@@ -0,0 +1,85 @@
import { useEffect, useState } from "react";
import { Input, Select } from "../../components/ui/Field";
import { columnLabel } from "../../lib/format";
const NUMBER = /^-?\d[\d,]*(\.\d+)?$/;
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/**
* A small box in the table that is typed into directly. Saves when the user leaves it (or
* presses Enter) and only if the value changed; Escape puts the saved value back. A refresh
* of the list never overwrites what is being typed.
*/
export function InlineCell({ value, column, onSave }: {
value: string; column: string; onSave: (value: string) => Promise<boolean>;
}) {
if (column === "month") return <MonthCell value={value} onSave={onSave} />;
return <NumberCell value={value} column={column} onSave={onSave} />;
}
/** The month, picked from the list; saved as soon as it is chosen. */
function MonthCell({ value, onSave }: { value: string; onSave: (value: string) => Promise<boolean> }) {
const [draft, setDraft] = useState(value);
const [saving, setSaving] = useState(false);
useEffect(() => { if (!saving) setDraft(value); }, [value, saving]);
async function choose(next: string) {
if (next === value) return;
setDraft(next);
setSaving(true);
const ok = await onSave(next);
setSaving(false);
if (!ok) setDraft(value);
}
return (
<Select className="cell-input cell-select" value={draft} disabled={saving} aria-label={columnLabel("month")} onChange={(e) => void choose(e.target.value)}>
<option value="">—</option>
{/* A month typed some other way in an imported row keeps showing as it was. */}
{draft && !MONTHS.includes(draft) && <option value={draft}>{draft}</option>}
{MONTHS.map((m) => <option key={m} value={m}>{m}</option>)}
</Select>
);
}
function NumberCell({ value, column, onSave }: {
value: string; column: string; onSave: (value: string) => Promise<boolean>;
}) {
const [draft, setDraft] = useState(value);
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const [invalid, setInvalid] = useState(false);
useEffect(() => { if (!editing && !saving) setDraft(value); }, [value, editing, saving]);
async function commit() {
setEditing(false);
const next = draft.trim();
if (next === value.trim()) { setInvalid(false); return; }
if (next && !NUMBER.test(next)) { setInvalid(true); return; }
setInvalid(false);
setSaving(true);
const ok = await onSave(next);
setSaving(false);
if (!ok) setDraft(value);
}
return (
<Input
className={`cell-input${invalid ? " invalid" : ""}`}
value={draft}
inputMode="decimal"
disabled={saving}
aria-label={columnLabel(column)}
aria-invalid={invalid || undefined}
title={invalid ? "Numbers only" : undefined}
onFocus={() => setEditing(true)}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => void commit()}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
if (e.key === "Escape") { setDraft(value); setInvalid(false); e.currentTarget.blur(); }
}}
/>
);
}
+25 -6
View File
@@ -8,16 +8,24 @@ import { useAsync } from "../../hooks/useAsync";
import { columnLabel, errorMessage } from "../../lib/format";
import { isoDate, maxLength, numeric, required, useValidation, type Rule } from "../../lib/validation";
import type { CsvRow, CsvTable, FormOwner, Profile, User } from "../../types";
import { screenColumns } from "./layout";
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
const DATES = new Set(["date", "report_date", "date_of_visit"]);
/** Columns that hold quantities or money — must be numbers (commas and decimals allowed). */
const NUMERIC = new Set([
"pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2", "opening", "receipt", "sale", "value_in_pts",
"pts", "closing_qty", "closing_value", "projection_qty", "projection_value", "closing", "opening", "receipt", "sale", "value_in_pts",
"kilometers_km", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "no_of_doctors_called", "no_of_chemists_pds_called",
"pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "doctor_call_avg", "chemist_call_avg", "pob",
"fare", "da_hq", "da_ex", "da_out", "postage", "other_expense", "total", "business_achieved",
]);
/** Expense Statement: TOTAL is always the sum of these, worked out here and again on the server. */
const EXPENSE_AMOUNTS = ["fare", "da_hq", "da_ex", "da_out", "postage", "other_expense"];
const expenseTotal = (d: Record<string, string>) => {
const amounts = EXPENSE_AMOUNTS.map((c) => (d[c] ?? "").replace(/,/g, "").trim()).filter(Boolean).map(Number);
return amounts.length && amounts.every(Number.isFinite) ? amounts.reduce((a, b) => a + b, 0).toFixed(2) : "";
};
const LONG_TEXT = new Set(["remarks", "area_to_cover", "product_offer_scheme_booked", "product_offer_scheme_objective"]);
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
@@ -28,10 +36,11 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
owner?: FormOwner;
onClose: () => void; onSaved: (message: string) => void;
}) {
const columns = useMemo(() => table.columns.filter((c) => !SERIAL.has(c)), [table]);
const columns = useMemo(() => screenColumns(table, user.role).filter((c) => !SERIAL.has(c)), [table, user.role]);
const isAdmin = user.role === "ADMIN";
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin);
const isExpense = table.name === "expense_statement";
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (isExpense && c === "total");
// NAME / HEADQUARTER are the MR's: the signed-in MR, or the one an admin is filling the form in for.
const account = (c: string) => {
if (isAdmin && owner) return c === "headquarter" ? owner.headquarters_name ?? "" : owner.name;
@@ -66,13 +75,22 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
if (!open) return;
setError(null);
v.clear();
setDraft(Object.fromEntries(columns.map((c) => [c, IDENTITY.has(c) ? (row ? String(row[c] ?? "") : account(c)) : String(row?.[c] ?? "")])));
const initial = Object.fromEntries(columns.map((c) => [c, IDENTITY.has(c) ? (row ? String(row[c] ?? "") : account(c)) : String(row?.[c] ?? "")]));
// A new day on the expense statement starts with the designation used on the earlier days.
if (isExpense && !row) initial.designation = String([...rows].reverse().find((r) => r.designation)?.designation ?? "Medical Representative");
setDraft(initial);
// Keyed on the row's id and primitives — not object identity — so a background refresh
// of the list can never wipe what the user is typing.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, row?.id, table.name, profile?.full_name, profile?.headquarters_name, owner?.id]);
const set = (column: string, value: string) => { setDraft((d) => ({ ...d, [column]: value })); v.retouch(column, value); };
const set = (column: string, value: string) => {
setDraft((d) => {
const next = { ...d, [column]: value };
return isExpense && EXPENSE_AMOUNTS.includes(column) ? { ...next, total: expenseTotal(next) } : next;
});
v.retouch(column, value);
};
const blur = (column: string) => (e: { target: { value: string } }) => v.touch(column, e.target.value);
async function submit(e: FormEvent<HTMLFormElement>) {
@@ -148,7 +166,8 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
error={v.errors[c]}
required={table.name === "sales_projection" && c === "product_name"}
hint={
generated(c) ? "Filled in automatically"
isExpense && c === "total" ? "Fare + daily allowance + postage + other expense"
: generated(c) ? "Filled in automatically"
: needsDoctors && c === "doctor_name" && !doctors.loading && coreDoctorNames.length === 0 ? "No core doctors are assigned yet — ask your administrator to assign some."
: NUMERIC.has(c) ? "Numbers only"
: undefined
+1 -1
View File
@@ -1,5 +1,5 @@
/** Forms that carry an Area Manager approval signature on their PDF. */
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart"]);
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"]);
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
export const APPROVAL_POLL_MS = 3_000;
+36
View File
@@ -0,0 +1,36 @@
import type { CsvTable, Role } from "../../types";
/** Columns shown in a different order than they are stored, to match the printed form (app/pdf/forms.py). */
const SCREEN_ORDER: Record<string, string[]> = {
sales_and_stock_statement: ["product_name", "value_in_pts"],
};
/** Columns nobody sees or fills in on that form, whatever their role. */
const HIDDEN: Record<string, Set<string>> = {
sales_and_stock_statement: new Set(["report_date"]),
sales_projection: new Set(["report_date"]),
};
/** Columns worked out by the system, never typed (Field Activity Report averages — shown as the Average row). */
const COMPUTED: Record<string, Set<string>> = {
field_activity_report: new Set(["doctor_call_avg", "chemist_call_avg"]),
area_covered: new Set(["sale_status"]),
};
/** The form's columns as this role sees them: in printed order, without the ones hidden from them. */
export function screenColumns(table: CsvTable, role: Role): string[] {
const hidden = HIDDEN[table.name];
const columns = table.columns.filter((c) => !hidden?.has(c) && !COMPUTED[table.name]?.has(c));
const order = SCREEN_ORDER[table.name];
if (!order) return columns;
// The listed columns sit together, in that order, where the first of them was.
const rest = columns.filter((c) => !order.includes(c));
const at = columns.findIndex((c) => order.includes(c));
return at < 0 ? columns : [...rest.slice(0, at), ...order.filter((c) => columns.includes(c)), ...rest.slice(at)];
}
/** Columns typed straight into the table, in a small box per cell, instead of through the Edit drawer. */
export const INLINE_COLUMNS: Record<string, Set<string>> = {
sales_and_stock_statement: new Set(["month", "value_in_pts", "opening", "receipt", "sale", "closing"]),
sales_projection: new Set(["month", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
};
+56 -12
View File
@@ -2,31 +2,67 @@ import { type FormEvent, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { Field, Input, Textarea } from "../../components/ui/Field";
import { Field, Input, Select, Textarea } from "../../components/ui/Field";
import { PageHeader } from "../../components/ui/PageHeader";
import { api } from "../../api";
import { useAsync } from "../../hooks/useAsync";
import { errorMessage, todayISO } from "../../lib/format";
import { REPORT_TYPE_LABEL } from "../../lib/format";
import { reportPath, reportsPath } from "../../lib/navigation";
import { navigate } from "../../lib/router";
import { isoDate, maxLength, notAfter, required, useValidation } from "../../lib/validation";
import type { ReportType } from "../../types";
export function NewReportPage() {
const COPY: Record<ReportType, { title: string; description: string; remarks: string; create: string }> = {
SELF: {
title: "New Daily Call Report (Self)",
description: "Record the doctors and chemists you visited yourself. No approval is needed: once you submit it, the report is final.",
remarks: "Optional summary of the day",
create: "Start report",
},
PLAN: {
title: "New Daily Call Report (Plan)",
description: "List the doctors and chemists you intend to visit today and when, then send the plan to your Area Manager.",
remarks: "Optional note for your Area Manager, e.g. the area you will cover",
create: "Start plan",
},
ACTUAL: {
title: "New Daily Call Report (Done)",
description: "Once your plan is approved, record the visits you made. Planned visits you could not make need a short note.",
remarks: "Optional summary of the day",
create: "Start report",
},
};
/** A plan may be made this many days ahead (PLAN_AHEAD_DAYS on the server); Done and Self never. */
const PLAN_AHEAD_DAYS = 2;
export function NewReportPage({ type }: { type: ReportType }) {
const copy = COPY[type];
const latest = todayISO(type === "PLAN" ? PLAN_AHEAD_DAYS : 0);
const isSelf = type === "SELF";
// An Area Manager's own report is for one of the headquarters they manage.
const hqs = useAsync(() => (isSelf ? api.headquarters() : Promise.resolve([])), [isSelf]);
const [hqChoice, setHqChoice] = useState("");
const hqId = hqChoice || (hqs.data?.length === 1 ? hqs.data[0].id : "");
const [date, setDate] = useState(todayISO());
const [remarks, setRemarks] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const v = useValidation({
date: [required("Report date"), isoDate("Report date"), notAfter(todayISO(), "Report date", "today")],
date: [required("Report date"), isoDate("Report date"), notAfter(latest, "Report date", type === "PLAN" ? `${PLAN_AHEAD_DAYS} days from today` : "today")],
hq: isSelf ? [required("Headquarters")] : [],
remarks: [maxLength(2000, "Remarks")],
});
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ date, remarks }, e.currentTarget)) return;
if (!v.check({ date, hq: hqId, remarks }, e.currentTarget)) return;
setBusy(true);
setError(null);
try {
const created = await api.createReport({ report_date: date, mr_remarks: remarks || null });
navigate(`/reports/${created.id}`);
const created = await api.createReport({ report_date: date, report_type: type, mr_remarks: remarks || null, ...(isSelf && { headquarters_id: hqId }) });
navigate(reportPath(created));
} catch (err) {
setError(errorMessage(err, "Could not create the report"));
setBusy(false);
@@ -35,21 +71,29 @@ export function NewReportPage() {
return (
<div className="narrow">
<PageHeader back={{ to: "/reports", label: "Daily Call Reports" }} title="New Daily Call Report" description="Start a draft, then add your doctor and chemist visits before submitting." />
<PageHeader back={{ to: reportsPath(type), label: REPORT_TYPE_LABEL[type] }} title={copy.title} description={copy.description} />
<Card>
<CardHeader title="Report details" />
<CardBody>
<form className="form-grid" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Report date" required error={v.errors.date} hint="One report per day; you can file up to the configured backdating window.">
<Input type="date" value={date} max={todayISO()} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
<Field label="Report date" required error={v.errors.date} hint={type === "PLAN" ? `One plan per day. You can plan today or up to ${PLAN_AHEAD_DAYS} days ahead.` : isSelf ? "One report per day." : "Your Daily Call Report (Plan) for this date must already be approved by your Area Manager."}>
<Input type="date" value={date} max={latest} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
</Field>
{isSelf && (
<Field label="Headquarters" required error={v.errors.hq ?? hqs.error ?? undefined} hint={hqs.data?.length === 0 ? "You do not manage a headquarters yet — ask your administrator." : "Its doctors and chemists can be added to the report."}>
<Select value={hqId} onChange={(e) => { setHqChoice(e.target.value); v.retouch("hq", e.target.value); }}>
<option value="">Choose headquarters</option>
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
</Field>
)}
<Field label="Daily remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={(e) => { setRemarks(e.target.value); v.retouch("remarks", e.target.value); }} onBlur={(e) => v.touch("remarks", e.target.value)} rows={4} placeholder="Optional summary of the day" />
<Textarea value={remarks} onChange={(e) => { setRemarks(e.target.value); v.retouch("remarks", e.target.value); }} onBlur={(e) => v.touch("remarks", e.target.value)} rows={4} placeholder={copy.remarks} />
</Field>
<div className="form-actions">
<Button onClick={() => navigate("/reports")}>Cancel</Button>
<Button type="submit" variant="primary" loading={busy}>Create draft</Button>
<Button onClick={() => navigate(reportsPath(type))}>Cancel</Button>
<Button type="submit" variant="primary" loading={busy}>{copy.create}</Button>
</div>
</form>
</CardBody>
+133 -32
View File
@@ -7,18 +7,21 @@ import { KeyValue } from "../../components/ui/Misc";
import { PageHeader } from "../../components/ui/PageHeader";
import { ErrorState, Skeleton } from "../../components/ui/States";
import { useToast } from "../../components/ui/Toast";
import { AddVisitForm } from "../../components/reports/AddVisitForm";
import { AddVisitForm, type VisitPreset } from "../../components/reports/AddVisitForm";
import { ApprovalTimeline } from "../../components/reports/ApprovalTimeline";
import { PlannedVisitList } from "../../components/reports/PlannedVisitList";
import { ReviewPanel, type ReviewAction } from "../../components/reports/ReviewPanel";
import { StatusBadge } from "../../components/reports/StatusBadge";
import { VisitList } from "../../components/reports/VisitList";
import { WorkflowTracker } from "../../components/reports/WorkflowTracker";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { errorMessage, formatDate, formatDateTime } from "../../lib/format";
import { errorMessage, formatDate, formatDateTime, REPORT_TYPE_LABEL, isField } from "../../lib/format";
import { reportPath, reportsPath } from "../../lib/navigation";
import { navigate } from "../../lib/router";
import { useUser } from "../../lib/session";
import { maxLength, useValidation } from "../../lib/validation";
import type { Approval, Chemist, Dcr, Doctor } from "../../types";
import type { Approval, Chemist, Dcr, Doctor, PlannedVisit } from "../../types";
export function ReportDetailPage({ id }: { id: string }) {
const user = useUser();
@@ -43,6 +46,7 @@ export function ReportDetailPage({ id }: { id: string }) {
const [remarks, setRemarks] = useState("");
const [stockist, setStockist] = useState("");
const [order, setOrder] = useState("");
const [preset, setPreset] = useState<VisitPreset | null>(null);
const dirty = useRef(false); // the MR has typed something not yet saved
const details = useValidation({ remarks: [maxLength(2000, "Remarks")], stockist: [maxLength(200, "Stockist visit")], order: [maxLength(100, "Order")] });
@@ -55,7 +59,8 @@ export function ReportDetailPage({ id }: { id: string }) {
}
}, [report.data]);
const editable = user.role === "MR" && !!dcr && !dcr.is_locked && ["DRAFT", "RETURNED"].includes(dcr.status);
// Only the report's owner edits it: the MR for a plan or done report, the AM for their own.
const editable = !!dcr && dcr.mr_user_id === user.id && !dcr.is_locked && ["DRAFT", "RETURNED"].includes(dcr.status);
editableRef.current = editable;
const masters = useAsync(
() => (editable ? Promise.all([api.doctors(), api.chemists()]).then(([doctors, chemists]) => ({ doctors, chemists })) : Promise.resolve({ doctors: [] as Doctor[], chemists: [] as Chemist[] })),
@@ -118,6 +123,44 @@ export function ReportDetailPage({ id }: { id: string }) {
setError(errorMessage(e, "Could not remove the visit"));
}
};
// --- day plan / end-of-day ---------------------------------------------------------------
const isPlan = dcr.report_type === "PLAN";
const isSelf = dcr.report_type === "SELF";
// An Area Manager sees every headquarters they manage; their own report covers just one.
const inReportHq = <T extends { headquarters_id: string; is_active: boolean }>(items: T[]) =>
isSelf ? items.filter((i) => i.is_active && i.headquarters_id === dcr.headquarters_id) : items;
const planned = dcr.planned_visits;
const pending = planned.filter((p) => p.status === "PENDING").length;
const visitedPlanned = planned.filter((p) => p.status === "VISITED").length;
const target = (line: PlannedVisit) => (line.kind === "DOCTOR" ? { doctor_id: line.target_id } : { chemist_id: line.target_id });
const recordPlanned = (line: PlannedVisit) => setPreset({ kind: line.kind === "DOCTOR" ? "doctor" : "chemist", targetId: line.target_id, key: Date.now() });
const saveReason = async (line: PlannedVisit, reason: string): Promise<boolean> => {
setError(null);
try {
apply(await api.setMissedReason(dcr.id, target(line), reason));
toast.success("Missed-visit note saved");
reconcile();
return true;
} catch (e) {
setError(errorMessage(e, "Could not save the note"));
return false;
}
};
const clearReason = (line: PlannedVisit) => {
if (line.missed_visit_id) void run(() => api.clearMissedReason(dcr.id, line.missed_visit_id!), "Missed-visit note cleared");
};
const startEndOfDay = async () => {
setBusy(true);
setError(null);
try {
const created = await api.createReport({ report_date: dcr.report_date, report_type: "ACTUAL" });
navigate(reportPath(created));
} catch (e) {
setError(errorMessage(e, "Could not start the Daily Call Report (Done)"));
setBusy(false);
}
};
const typed = (set: (value: string) => void, name: string) => (e: { target: { value: string } }) => {
dirty.current = true;
set(e.target.value);
@@ -127,19 +170,23 @@ export function ReportDetailPage({ id }: { id: string }) {
return (
<>
<PageHeader
back={{ to: "/reports", label: "Daily Call Reports" }}
title={<>{formatDate(dcr.report_date)} <StatusBadge status={dcr.status} /></>}
description={`${dcr.mr_name} · ${dcr.headquarters_name}`}
actions={dcr.status === "APPROVED" && (
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
)}
back={{ to: reportsPath(dcr.report_type), label: REPORT_TYPE_LABEL[dcr.report_type] }}
title={<>{formatDate(dcr.report_date)} <StatusBadge status={dcr.status} type={dcr.report_type} /></>}
description={`${REPORT_TYPE_LABEL[dcr.report_type]} · ${dcr.mr_name} · ${dcr.headquarters_name}`}
actions={<>
{dcr.plan_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.plan_id!, report_type: "PLAN" }))}>View plan</Button>}
{dcr.actual_report_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.actual_report_id!, report_type: "ACTUAL" }))}>View done report</Button>}
{dcr.status === "APPROVED" && (
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
)}
</>}
/>
<Alert>{error}</Alert>
{dcr.return_reason && (
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ?? "reviewer"}`}>{dcr.return_reason}</Alert>
)}
<Card><CardBody><WorkflowTracker status={dcr.status} /></CardBody></Card>
<Card><CardBody><WorkflowTracker status={dcr.status} type={dcr.report_type} /></CardBody></Card>
<div className="split">
<div className="stack">
@@ -147,48 +194,93 @@ export function ReportDetailPage({ id }: { id: string }) {
<CardHeader title="Summary" />
<CardBody>
<KeyValue items={[
{ label: "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
{ label: isSelf ? "Area Manager" : "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
{ label: "Headquarters", value: dcr.headquarters_name },
{ label: "Doctor visits", value: dcr.doctor_calls.length },
{ label: "Chemist visits", value: dcr.chemist_calls.length },
{ label: isPlan ? "Doctors planned" : "Doctor visits", value: dcr.doctor_calls.length },
{ label: isPlan ? "Chemists planned" : "Chemist visits", value: dcr.chemist_calls.length },
...(dcr.plan_id ? [{ label: "Planned visits made", value: `${visitedPlanned} of ${planned.length}` }] : []),
{ label: "Submitted", value: formatDateTime(dcr.submitted_at) },
{ label: "Approved", value: formatDateTime(dcr.approved_at) },
...(isSelf ? [] : [{ label: "Approved", value: formatDateTime(dcr.approved_at) }]),
]} />
<div className="divider" />
{editable ? (
<div className="form-grid">
<Field label="Stockist visit" error={details.errors.stockist}>
<Input value={stockist} onChange={typed(setStockist, "stockist")} onBlur={() => void saveDetails()} placeholder="Stockist visited, if any" />
</Field>
<Field label="Order" error={details.errors.order}>
<Input value={order} onChange={typed(setOrder, "order")} onBlur={() => void saveDetails()} placeholder="Order value or details" />
</Field>
<Field label="Daily remarks" span error={details.errors.remarks} hint={`${remarks.length}/2000 — saved when you leave the box`}>
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder="Optional summary of the day" />
{!isPlan && <>
<Field label="Stockist visit" error={details.errors.stockist}>
<Input value={stockist} onChange={typed(setStockist, "stockist")} onBlur={() => void saveDetails()} placeholder="Stockist visited, if any" />
</Field>
<Field label="Order" error={details.errors.order}>
<Input value={order} onChange={typed(setOrder, "order")} onBlur={() => void saveDetails()} placeholder="Order value or details" />
</Field>
</>}
<Field label={isPlan ? "Plan note" : "Daily remarks"} span error={details.errors.remarks} hint={`${remarks.length}/2000 — saved when you leave the box`}>
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder={isPlan ? "Optional note for your Area Manager" : "Optional summary of the day"} />
</Field>
</div>
) : (
<>
<p className="field-label">Stockist visit / Order</p>
<p className="prose">{[dcr.stockist_visit, dcr.order_value && `Order: ${dcr.order_value}`].filter(Boolean).join(" · ") || "None recorded."}</p>
<p className="field-label">Daily remarks</p>
{!isPlan && <>
<p className="field-label">Stockist visit / Order</p>
<p className="prose">{[dcr.stockist_visit, dcr.order_value && `Order: ${dcr.order_value}`].filter(Boolean).join(" · ") || "None recorded."}</p>
</>}
<p className="field-label">{isPlan ? "Plan note" : "Daily remarks"}</p>
<p className="prose">{dcr.mr_remarks || "No remarks recorded."}</p>
</>
)}
</CardBody>
</Card>
{isPlan && isField(user.role) && dcr.status === "PENDING_AM" && (
<Alert tone="info">Once your Area Manager approves this plan, you can fill the Daily Call Report (Done) for {formatDate(dcr.report_date)}.</Alert>
)}
{isPlan && dcr.status === "APPROVED" && isField((user.role) || dcr.actual_report_id) && (
<Card>
<CardHeader title={REPORT_TYPE_LABEL.ACTUAL} description={dcr.actual_report_id ? "Filed against this plan." : "Your plan is approved. At the end of the day, record the visits you made and why any planned visit was missed."} />
<CardBody>
{dcr.actual_report_id
? <Button icon="arrowRight" onClick={() => navigate(reportPath({ id: dcr.actual_report_id!, report_type: "ACTUAL" }))}>Open Daily Call Report (Done)</Button>
: <Button variant="primary" icon="plus" loading={busy} onClick={() => void startEndOfDay()}>Start Daily Call Report (Done)</Button>}
</CardBody>
</Card>
)}
{dcr.plan_id && (
<Card>
<CardHeader
title="Plan check"
description={pending > 0
? `${pending} planned visit${pending === 1 ? "" : "s"} still need${pending === 1 ? "s" : ""} a recorded visit or a note saying why it was missed.`
: "Every planned visit is accounted for."}
/>
<CardBody flush>
<PlannedVisitList dcr={dcr} editable={editable} onRecord={recordPlanned} onSaveReason={saveReason} onClearReason={clearReason} />
</CardBody>
</Card>
)}
{editable && (
<Card>
<CardHeader title="Add a visit" description="Only doctors and chemists assigned to you are listed." />
<CardHeader
title={isPlan ? "Add to your plan" : "Add a visit"}
description={isPlan
? "Who you intend to visit today, and when. Only doctors and chemists assigned to you are listed."
: isSelf
? `Doctors and chemists of ${dcr.headquarters_name} are listed.`
: "Only doctors and chemists assigned to you are listed. Unplanned visits can be added too."}
/>
<CardBody>
<AddVisitForm dcr={dcr} doctors={masters.data?.doctors ?? []} chemists={masters.data?.chemists ?? []} onChange={(next) => { apply(next); reconcile(); }} />
<AddVisitForm dcr={dcr} doctors={inReportHq(masters.data?.doctors ?? [])} chemists={inReportHq(masters.data?.chemists ?? [])} preset={preset} onChange={(next) => { apply(next); reconcile(); }} />
</CardBody>
</Card>
)}
<Card>
<CardHeader title="Visits" description={`${dcr.doctor_calls.length + dcr.chemist_calls.length} recorded, in visit order.`} />
<CardHeader
title={isPlan ? "Planned visits" : "Visits"}
description={isPlan
? `${dcr.doctor_calls.length + dcr.chemist_calls.length} planned, in time order.`
: `${dcr.doctor_calls.length + dcr.chemist_calls.length} recorded, in visit order.`}
/>
<CardBody flush>
<VisitList dcr={dcr} editable={editable} onRemove={(callId) => void removeVisit(callId)} />
</CardBody>
@@ -196,9 +288,18 @@ export function ReportDetailPage({ id }: { id: string }) {
{editable && (
<Card>
<CardHeader title="Ready to send?" description="Submitted reports cannot be edited unless they are returned for correction." />
<CardHeader
title={isPlan ? "Ready to send your plan?" : isSelf ? "Ready to submit?" : "Ready to send?"}
description={pending > 0
? "Account for every planned visit above before submitting."
: isSelf
? "No approval is needed. Once submitted, the report is final and cannot be edited."
: "Submitted reports cannot be edited unless they are returned for correction."}
/>
<CardBody>
<Button variant="primary" icon="send" loading={busy} onClick={() => void run(() => api.submit(dcr.id), "Submitted to the Area Manager")}>Submit to Area Manager</Button>
<Button variant="primary" icon="send" loading={busy} disabled={pending > 0} onClick={() => void run(() => api.submit(dcr.id), isPlan ? "Plan sent to the Area Manager" : isSelf ? "Report submitted" : "Submitted to the Area Manager")}>
{isPlan ? "Send plan to Area Manager" : isSelf ? "Submit report" : "Submit to Area Manager"}
</Button>
</CardBody>
</Card>
)}
@@ -207,7 +308,7 @@ export function ReportDetailPage({ id }: { id: string }) {
</div>
<Card className="sticky">
<CardHeader title="Approval history" />
<CardHeader title={isSelf ? "History" : "Approval history"} />
<CardBody><ApprovalTimeline items={history} /></CardBody>
</Card>
</div>
+39 -11
View File
@@ -8,9 +8,11 @@ import { Tabs, type TabItem } from "../../components/ui/Tabs";
import { ReportTable } from "../../components/reports/ReportTable";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { REPORT_TYPE_LABEL, isField } from "../../lib/format";
import { reportsPath } from "../../lib/navigation";
import { navigate } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { DcrListItem } from "../../types";
import type { DcrListItem, ReportType } from "../../types";
type Filter = "ALL" | "DRAFT" | "PENDING" | "RETURNED" | "APPROVED";
const MATCH: Record<Filter, (r: DcrListItem) => boolean> = {
@@ -21,17 +23,39 @@ const MATCH: Record<Filter, (r: DcrListItem) => boolean> = {
APPROVED: (r) => r.status === "APPROVED",
};
export function ReportsPage() {
const DESCRIPTION: Record<ReportType, { mr: string; manager: string; gm?: string }> = {
SELF: {
mr: "",
manager: "Your own visits to doctors and chemists, one report a day. No approval is needed: submitting a report makes it final.",
gm: "Area Managers' own visits to doctors and chemists, across every headquarters. A submitted report is final.",
},
PLAN: {
mr: "Plan the doctors and chemists you will visit each day, and send the plan to your Area Manager.",
manager: "Day plans from your scope. Approving a plan lets the MR file its Daily Call Report (Done).",
},
ACTUAL: {
mr: "At the end of the day, record the visits you made against your approved plan.",
manager: "Visits made against approved plans, with a note for every planned visit that was missed.",
},
};
/** The list behind one sidebar entry: Daily Call Report (Plan), (Done) or an Area Manager's (Self). */
export function ReportsPage({ type }: { type: ReportType }) {
const user = useUser();
const reports = useAsync(api.reports, [], { poll: LIVE });
const isSelf = type === "SELF";
// The role that files this type of report, and so gets the "new report" button.
const author = isSelf ? "AM" : "MR";
const reports = useAsync(() => api.reports(type), [type], { poll: LIVE });
const [filter, setFilter] = useState<Filter>("ALL");
const [query, setQuery] = useState("");
const all = reports.data ?? [];
const tabs: TabItem<Filter>[] = [
{ key: "ALL", label: "All" }, { key: "DRAFT", label: "Draft" }, { key: "PENDING", label: "In review" },
{ key: "RETURNED", label: "Returned" }, { key: "APPROVED", label: "Approved" },
].map((t) => ({ ...t, key: t.key as Filter, count: all.filter(MATCH[t.key as Filter]).length }));
const tabs: TabItem<Filter>[] = (isSelf
? [{ key: "ALL", label: "All" }, { key: "DRAFT", label: "Draft" }, { key: "APPROVED", label: "Submitted" }]
: [
{ key: "ALL", label: "All" }, { key: "DRAFT", label: "Draft" }, { key: "PENDING", label: "In review" },
{ key: "RETURNED", label: "Returned" }, { key: "APPROVED", label: "Approved" },
]).map((t) => ({ ...t, key: t.key as Filter, count: all.filter(MATCH[t.key as Filter]).length }));
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -41,9 +65,13 @@ export function ReportsPage() {
return (
<>
<PageHeader
title="Daily Call Reports"
description={user.role === "MR" ? "Create, submit and track your field work." : "Only reports within your permitted scope are shown."}
actions={user.role === "MR" && <Button variant="primary" icon="plus" onClick={() => navigate("/reports/new")}>New report</Button>}
title={REPORT_TYPE_LABEL[type]}
description={isField(user.role) ? DESCRIPTION[type].mr : (user.role === "GM" && DESCRIPTION[type].gm) || DESCRIPTION[type].manager}
actions={user.role === author && (
<Button variant="primary" icon="plus" onClick={() => navigate(`${reportsPath(type)}/new`)}>
{type === "PLAN" ? "Plan my day" : `New report (${isSelf ? "Self" : "Done"})`}
</Button>
)}
/>
<Card>
<div className="toolbar">
@@ -52,7 +80,7 @@ export function ReportsPage() {
</div>
{reports.error
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
: <ReportTable rows={rows} loading={reports.loading} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
: <ReportTable rows={rows} loading={reports.loading} ownerHeader={isSelf ? "Area Manager" : undefined} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
</Card>
</>
);
+20
View File
@@ -77,8 +77,14 @@
@keyframes shimmer { to { background-position: -200% 0; } }
/* ---- Toolbar, tabs, search ------------------------------------------------------- */
.chip-row { display: flex; flex-wrap: wrap; gap: 8px; }
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 12px 16px; border-bottom: 1px solid var(--border); }
.toolbar-end { justify-content: flex-end; }
/* Controls kept together at one end of a toolbar, e.g. a filter beside the search box. */
.toolbar-group { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; max-width: 100%; }
/* A headquarters filter beside a search box or in a page header. */
.select.hq-filter { width: auto; min-width: 200px; max-width: 100%; }
.toolbar-group .hq-filter { height: 36px; }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; }
.tab { display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px; border: 0; border-radius: var(--radius); background: none; color: var(--text-3); font-weight: 500; }
.tab:hover { background: var(--surface-hover); color: var(--text); }
@@ -102,6 +108,7 @@
.table th { padding: 10px 16px; text-align: left; font-size: 12px; font-weight: 600; color: var(--text-3); background: var(--surface-2); border-bottom: 1px solid var(--border); white-space: nowrap; }
.table td { padding: 13px 16px; border-bottom: 1px solid var(--border); color: var(--text-2); vertical-align: middle; }
.table tbody tr:last-child td { border-bottom: 0; }
.table tfoot td { position: sticky; bottom: 0; z-index: 1; font-weight: 600; color: var(--text); background: var(--surface-2); border-top: 1px solid var(--border); }
.table td strong { color: var(--text); font-weight: 600; }
.table tr.clickable { cursor: pointer; }
.table tr.clickable:hover td { background: var(--surface-hover); }
@@ -128,6 +135,11 @@
.input::placeholder { color: var(--text-4); }
.input:focus { outline: none; border-color: var(--brand-600); box-shadow: var(--ring); }
.input[readonly] { background: var(--surface-2); color: var(--text-3); }
/* A small box typed into straight from a table cell. */
.input.cell-input { width: 88px; height: 32px; padding: 0 8px; text-align: right; font-variant-numeric: tabular-nums; }
.input.cell-input.invalid { border-color: var(--danger); }
.input.cell-input:disabled { opacity: .6; }
.select.cell-input.cell-select { width: 132px; height: 32px; padding: 0 28px 0 8px; text-align: left; background-position: right 6px center; }
.select { appearance: none; padding-right: 34px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23667085' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; }
.textarea { height: auto; min-height: 76px; padding: 10px 12px; resize: vertical; line-height: 1.5; }
.checkbox { display: flex; align-items: center; gap: 8px; height: 38px; align-self: end; font-weight: 500; color: var(--text-2); }
@@ -228,6 +240,10 @@
.hq-check-text small { color: var(--text-4); font-size: 12px; }
.hq-empty { color: var(--text-3); font-size: 13px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.product-picker { display: grid; gap: 8px; min-width: 0; }
.chip { height: auto; min-height: 24px; padding-right: 4px; white-space: normal; overflow-wrap: anywhere; }
.chip-remove { display: inline-grid; place-items: center; width: 18px; height: 18px; padding: 0; border: 0; border-radius: 50%; background: transparent; color: inherit; cursor: pointer; }
.chip-remove:hover { background: var(--brand-100); }
@media (max-width: 640px) {
.form-grid { grid-template-columns: 1fr; }
.hq-check-list { grid-template-columns: 1fr; }
@@ -246,6 +262,7 @@
}
.form-nav-item { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.nav-item .nav-flag { margin-left: auto; }
.nav-flag { flex: none; padding: 2px 8px; border-radius: 999px; background: var(--warning-bg); border: 1px solid var(--warning-border); color: var(--warning); font-size: 11px; font-weight: 600; }
.update-bar { position: sticky; top: 0; z-index: 70; display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: wrap; padding: 8px 16px; background: var(--brand-700); color: #fff; font-size: 14px; }
@@ -254,3 +271,6 @@
.toolbar .filter { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; color: var(--text-muted); }
.toolbar .filter .select { width: auto; min-width: 180px; max-width: 100%; }
@media (max-width: 640px) { .toolbar .filter { width: 100%; flex-wrap: wrap; } .toolbar .filter .select { flex: 1; } }
.detail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }
.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }
.summary-block { display: flex; flex-direction: column; gap: 8px; }
+28 -7
View File
@@ -1,16 +1,23 @@
export type Role = "ADMIN" | "GM" | "AM" | "MR";
export type Role = "ADMIN" | "GM" | "AM" | "MR" | "SFE";
export type DcrStatus = "DRAFT" | "PENDING_AM" | "RETURNED" | "APPROVED";
export interface User { id: string; full_name: string; email: string; employee_code: string; phone?: string | null; role: Role; headquarters_id: string | null; is_active: boolean }
/** PLAN = the morning day plan; ACTUAL = the end-of-day report filed against it. */
export type ReportType = "PLAN" | "ACTUAL" | "SELF";
export interface User { id: string; full_name: string; email: string; employee_code: string; phone?: string | null; role: Role; headquarters_id: string | null; is_active: boolean; is_superadmin?: boolean; extra_headquarter_ids?: string[] }
export interface Headquarters { id: string; code: string; name: string; district: string | null; state: string | null; is_active: boolean }
export interface AreaManagerMapping { id: string; area_manager_user_id: string; headquarters_id: string; effective_from: string; effective_to: string | null }
export interface Doctor { id: string; headquarters_id: string; name: string; speciality: string | null; clinic_address: string; is_core_doctor: boolean; is_active: boolean }
export interface Chemist { id: string; headquarters_id: string; name: string; shop_address: string; is_active: boolean }
/** A doctor or chemist an MR adds is PENDING until their Area Manager approves it; only APPROVED ones are listed. */
export type MasterApproval = "PENDING" | "APPROVED" | "REJECTED";
interface MasterApprovalFields { approval_status: MasterApproval; rejection_reason: string | null; requested_by_name: string | null; created_at: string }
export interface Doctor extends MasterApprovalFields { id: string; headquarters_id: string; name: string; speciality: string | null; clinic_address: string; date_of_birth: string | null; is_core_doctor: boolean; is_active: boolean }
export interface Chemist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; shop_address: string; is_active: boolean }
export interface Product { id: string; company_id: string; name: string; pack: string | null; unit: string | null; is_active: boolean }
export interface StockInventory { id: number; serial_no: number; product_name: string; pack: string | null; quantity: string | null; unit: string | null }
export interface DoctorCall { id: string; doctor_id: string; doctor_name: string; doctor_speciality: string | null; is_core_doctor: boolean; visit_time: string; call_outcome: string; conversion_status: string | null; product_promote: string | null; product_sample: string | null; remarks: string | null }
export interface DoctorCall { id: string; doctor_id: string; doctor_name: string; doctor_speciality: string | null; is_core_doctor: boolean; visit_time: string; call_outcome: string | null; conversion_status: string | null; product_promote: string[]; product_sample: string[]; gift: string | null; remarks: string | null }
export interface ChemistCall { id: string; chemist_id: string; chemist_name: string; visit_time: string; pob: string | null; remarks: string | null }
export interface DcrListItem { id: string; report_date: string; status: DcrStatus; mr_name: string; headquarters_name: string; doctor_call_count: number; chemist_call_count: number; submitted_at: string | null; approved_at: string | null; returned_by_role: Role | null }
export interface Dcr extends DcrListItem { mr_user_id: string; employee_code: string; headquarters_id: string; is_locked: boolean; mr_remarks: string | null; stockist_visit: string | null; order_value: string | null; return_reason: string | null; doctor_calls: DoctorCall[]; chemist_calls: ChemistCall[] }
export interface DcrListItem { id: string; report_date: string; report_type: ReportType; status: DcrStatus; mr_name: string; headquarters_name: string; doctor_call_count: number; chemist_call_count: number; submitted_at: string | null; approved_at: string | null; returned_by_role: Role | null }
export interface Dcr extends DcrListItem { mr_user_id: string; employee_code: string; headquarters_id: string; is_locked: boolean; mr_remarks: string | null; stockist_visit: string | null; order_value: string | null; return_reason: string | null; doctor_calls: DoctorCall[]; chemist_calls: ChemistCall[]; plan_id: string | null; actual_report_id: string | null; planned_visits: PlannedVisit[] }
/** One line of the approved plan, checked against the end-of-day report. */
export interface PlannedVisit { kind: "DOCTOR" | "CHEMIST"; target_id: string; name: string; is_core_doctor: boolean; planned_time: string; status: "VISITED" | "MISSED" | "PENDING"; missed_visit_id: string | null; missed_reason: string | null }
export interface Profile extends User { phone: string | null; headquarters_code: string | null; headquarters_name: string | null; reporting_manager_name: string | null }
export interface Approval { action: string; actor_name: string; actor_role: string; comment: string | null; at: string }
export interface CsvTable { name: string; label: string; columns: string[] }
@@ -24,3 +31,17 @@ export type FormApproval = {
};
/** A medical representative whose company forms the signed-in user may open. */
export type FormOwner = { id: string; name: string; employee_code: string; headquarters_name: string | null };
export interface UserOverviewHq { id: string; code: string; name: string; district: string | null; state: string | null; main: boolean; field_staff?: number }
export interface UserOverviewPerson { id: string; full_name: string; email: string; role: Role; is_active: boolean; headquarters?: string | null }
export interface UserOverview {
user: { id: string; full_name: string; email: string; employee_code: string; phone: string | null; role: Role; is_active: boolean; is_superadmin: boolean };
headquarters: UserOverviewHq[];
reporting_managers: UserOverviewPerson[];
doctors: { id: string; name: string; speciality: string | null; clinic_address: string; headquarters_name: string; is_core_doctor: boolean; is_active: boolean }[];
chemists: { id: string; name: string; shop_address: string; headquarters_name: string; is_active: boolean }[];
reports: { counts: Partial<Record<ReportType, Partial<Record<DcrStatus, number>>>>; recent: DcrListItem[] };
own_reports: DcrListItem[] | null;
forms: { table: string; label: string; rows: number; months: string[]; approval_status: "draft" | "pending" | "approved" | null }[];
team: UserOverviewPerson[];
}