Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic

Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
This commit is contained in:
Shubhankar45
2026-11-07 05:43:12 +00:00
parent b001e2d03c
commit 0d30c58bf0
98 changed files with 1878 additions and 573 deletions
+13 -13
View File
@@ -22,27 +22,27 @@ import type { Role } from "./types";
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
{ pattern: "/", render: () => <DashboardPage /> },
// 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", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/plan", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
{ pattern: "/reports/done", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], 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} /> },
{ pattern: "/reports/plan/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/reports/done/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/reports/self", roles: ["ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="SELF" key="SELF" /> },
{ pattern: "/reports/self/new", roles: ["ABM"], render: () => <NewReportPage type="SELF" key="SELF" /> },
{ pattern: "/reports/self/:id", roles: ["ABM", "AGM", "ADMIN"], 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: "/reports/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/directory", render: () => <DirectoryPage /> },
{ pattern: "/products", render: () => <ProductsPage /> },
{ 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: "/forms", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <FormsPage /> },
{ pattern: "/forms/:table", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
{ pattern: "/profile", render: () => <ProfilePage /> },
{ 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} /> },
{ pattern: "/users", roles: ["ADMIN", "AGM"], render: () => <UsersPage /> },
{ pattern: "/users/:id", roles: ["ADMIN", "AGM"], render: (p) => <UserDetailPage id={p.id!} key={p.id} /> },
];
function Routes({ role }: { role: Role }) {
+30
View File
@@ -121,3 +121,33 @@ export async function download(url: string, filename: string): Promise<void> {
link.click();
URL.revokeObjectURL(href);
}
/** Fetch a protected PDF and show it in a new browser tab (no download). */
export async function view(url: string, init: RequestInit = {}): Promise<void> {
// Opened before the fetch so the browser treats it as part of the click, not a pop-up.
const tab = window.open("", "_blank");
try {
const headers = { ...(init.headers as Record<string, string> | undefined), Authorization: `Bearer ${accessToken}` };
const response = await fetch(url, { ...init, headers });
if (!response.ok) throw new ApiError("The PDF could not be opened", response.status);
const href = URL.createObjectURL(new Blob([await response.blob()], { type: "application/pdf" }));
if (tab) tab.location.href = href;
else window.open(href, "_blank");
setTimeout(() => URL.revokeObjectURL(href), 60_000);
} catch (err) {
tab?.close();
throw err;
}
}
/** POST a JSON body and download the PDF the server returns. */
export async function downloadPost(url: string, body: unknown, filename: string): Promise<void> {
const response = await fetch(url, { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` } });
if (!response.ok) throw new ApiError("The PDF could not be downloaded", response.status);
const href = URL.createObjectURL(await response.blob());
const link = document.createElement("a");
link.href = href;
link.download = filename;
link.click();
URL.revokeObjectURL(href);
}
+27 -7
View File
@@ -1,8 +1,8 @@
import type {
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
FormApproval, Product, Profile, UserOverview, ReportType, StatusCounts, StockInventory, User,
FormApproval, Product, Profile, Stockist, UserOverview, ReportType, StatusCounts, StockInventory, User,
} from "../types";
import { API_BASE, auth, download, json, request } from "./client";
import { API_BASE, auth, download, downloadPost, json, request, view } from "./client";
export { ApiError, auth } from "./client";
@@ -33,8 +33,9 @@ export const api = {
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)),
addStockistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/stockist`, 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. */
/** End-of-day report: why a planned doctor/chemist/stockist (`target` holds doctor_id, chemist_id or stockist_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")),
@@ -42,15 +43,18 @@ export const api = {
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
approvalHistory: (id: string) => request<Approval[]>(`/audit/dcr/${id}/approval-history`),
downloadReportPdf: (id: string) => download(`${API_BASE}/dcr/${id}/pdf`, `DCR-${id}.pdf`),
viewReportPdf: (id: string) => view(`${API_BASE}/dcr/${id}/pdf`),
// 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. */
stockists: () => request<Stockist[]>("/stockists"),
/** Doctors / chemists / stockists added by an MR that wait for (or were refused by) the Area Business 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 })),
stockistRequests: () => request<Stockist[]>("/stockists/requests"),
reviewMaster: (kind: "doctor" | "chemist" | "stockist", id: string, approve: boolean, reason?: string) =>
request<Doctor | Chemist | Stockist>(`/${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`),
@@ -64,6 +68,7 @@ export const api = {
deleteStockItem: (id: number) => request<void>(`/products/stock-inventory/${id}`, json("DELETE")),
updateDoctor: (id: string, payload: Payload) => request<Doctor>(`/doctors/${id}`, json("PATCH", payload)),
updateChemist: (id: string, payload: Payload) => request<Chemist>(`/chemists/${id}`, json("PATCH", payload)),
updateStockist: (id: string, payload: Payload) => request<Stockist>(`/stockists/${id}`, json("PATCH", payload)),
createHeadquarters: (payload: Payload) => request<Headquarters>("/headquarters", json("POST", payload)),
createUser: (payload: Payload) => request<User>("/users", json("POST", payload)),
updateUser: (id: string, payload: Payload) => request<User>(`/users/${id}`, json("PATCH", payload)),
@@ -71,15 +76,18 @@ export const api = {
request<unknown>(`/headquarters/${headquartersId}/area-manager`, json("POST", { area_manager_user_id })),
createDoctor: (payload: Payload) => request<Doctor>("/doctors", json("POST", payload)),
createChemist: (payload: Payload) => request<Chemist>("/chemists", json("POST", payload)),
createStockist: (payload: Payload) => request<Stockist>("/stockists", json("POST", payload)),
createProduct: (payload: Payload) => request<Product>("/products", json("POST", payload)),
assignDoctor: (doctorId: string, mr_user_id: string) =>
request<unknown>(`/doctors/${doctorId}/assign`, json("POST", { mr_user_id })),
assignChemist: (chemistId: string, mr_user_id: string) =>
request<unknown>(`/chemists/${chemistId}/assign`, json("POST", { mr_user_id })),
/** Administrator only: leave a doctor / chemist with no MR. */
unassignMaster: (kind: "doctor" | "chemist", id: string) => request<void>(`/${kind}s/${id}/assign`, json("DELETE")),
// company forms (CSV tables)
csvTables: () => request<CsvTable[]>("/csv-data/tables"),
/** `ownerId` picks one MR's copy of a form (Area Manager and admin); an MR always gets their own. */
/** `ownerId` picks one MR's copy of a form (Area Business Manager and admin); an MR always gets their own. */
csvRows: (table: string, ownerId?: string) => request<CsvRow[]>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`),
createCsvRow: (table: string, payload: Record<string, string>, ownerId?: string) =>
request<CsvRow>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`, json("POST", payload)),
@@ -98,4 +106,16 @@ export const api = {
const suffix = month ? `-${month.toLowerCase()}` : "";
return download(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`, `${table}${suffix}.pdf`);
},
/** Same PDF as downloadCsvPdf, shown in a new tab instead of saved. */
viewCsvPdf(table: string, opts: { rowId?: string; ownerId?: string; month?: string } = {}) {
const { rowId, ownerId, month } = opts;
if (rowId) return view(`${API_BASE}/csv-data/${table}/rows/${rowId}/pdf`);
return view(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`);
},
/** A printable list of the doctors / chemists / stockists exactly as shown on screen. */
directoryPdf(payload: { title: string; columns: string[]; rows: Record<string, string>[] }, mode: "view" | "download") {
const url = `${API_BASE}/directory/pdf`;
if (mode === "view") return view(url, { method: "POST", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
return downloadPost(url, payload, `${payload.title.toLowerCase().replace(/\s+/g, "-")}.pdf`);
},
};
@@ -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>Area Manager: {owners[h.id]}</small>}
{owners[h.id] && <small>Area Business Manager: {owners[h.id]}</small>}
</span>
</label>
))}
+20 -14
View File
@@ -11,25 +11,31 @@ 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";
import type { Chemist, Doctor, Stockist } from "../../types";
type Request = { kind: "doctor" | "chemist"; item: Doctor | Chemist };
type Request = { kind: "doctor" | "chemist" | "stockist"; item: Doctor | Chemist | Stockist };
const address = (r: Request) => (r.kind === "doctor" ? (r.item as Doctor).clinic_address : (r.item as Chemist).shop_address);
const address = (r: Request) =>
r.kind === "doctor" ? (r.item as Doctor).clinic_address : r.kind === "chemist" ? (r.item as Chemist).shop_address : (r.item as Stockist).address;
const KIND_LABEL = { doctor: "Doctor", chemist: "Chemist", stockist: "Stockist" } as const;
/**
* Doctors and chemists an MR added that wait for the Area Manager.
* Doctors, chemists and stockists an MR added that wait for the Area Business 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.
* `review`: what waits for this Area Business Manager (or the admin) to approve or reject; the AGM 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 canAct = mode === "review" && (user.role === "ABM" || 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 }))]
const [doctors, chemists, stockists] = await Promise.all([api.doctorRequests(), api.chemistRequests(), api.stockistRequests()]);
return [
...doctors.map((item) => ({ kind: "doctor" as const, item })),
...chemists.map((item) => ({ kind: "chemist" as const, item })),
...stockists.map((item) => ({ kind: "stockist" as const, item })),
]
.sort((a, b) => b.item.created_at.localeCompare(a.item.created_at));
}, [], { poll: LIVE });
const [acting, setActing] = useState<string | null>(null);
@@ -57,7 +63,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
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: "kind", header: "Type", render: (r) => <Badge tone="brand">{KIND_LABEL[r.kind]}</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 }] : []),
@@ -67,7 +73,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
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>,
: <Badge tone="warning" dot>Waiting for Area Business Manager</Badge>,
}
: {
key: "_actions", header: "", align: "right", nowrap: true,
@@ -76,7 +82,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
<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>,
) : <Badge tone="warning" dot>Waiting for Area Business Manager</Badge>,
},
];
@@ -87,8 +93,8 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
<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.`}
? "Doctors, chemists and stockists you added. Each joins your list once your Area Business Manager approves it. To re-send a rejected one, add it again with the corrected details."
: `${pending} new doctor${pending === 1 ? "" : "s"}, chemist${pending === 1 ? "" : "s"} or stockist${pending === 1 ? "" : "s"} added by MRs. Once approved, each joins the list (doctors and chemists are assigned to the MR who added them).`}
/>
<CardBody flush>
<DataTable columns={columns} rows={rows} rowKey={(r) => `${r.kind}-${r.item.id}`} loading={data.loading} minWidth={720} />
@@ -106,7 +112,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
}}>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" />
<Textarea value={reason} maxLength={500} rows={3} onChange={(e) => { setReason(e.target.value); setReasonError(null); }} placeholder="e.g. Wrong address, or this one is already in the list" />
</Field>
</Modal>
</>
+2 -2
View File
@@ -11,9 +11,9 @@ 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.
// An Area Business 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),
async () => (role === "ABM" ? (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 };
+20 -13
View File
@@ -8,18 +8,22 @@ 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";
import type { Chemist, Dcr, Doctor, Stockist } from "../../types";
/** 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 type VisitKind = "doctor" | "chemist" | "stockist";
export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
/** Pre-selects a doctor/chemist/stockist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
export interface VisitPreset { kind: VisitKind; targetId: string; key: number }
const KIND_LABEL: Record<VisitKind, string> = { doctor: "Doctor", chemist: "Chemist", stockist: "Stockist" };
export function AddVisitForm({ dcr, doctors, chemists, stockists, onChange, preset }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; stockists: Stockist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
}) {
const toast = useToast();
const products = useAsync(api.stockInventory, []);
const [error, setError] = useState<string | null>(null);
const [kind, setKind] = useState<"doctor" | "chemist">("doctor");
const [kind, setKind] = useState<VisitKind>("doctor");
const [targetId, setTargetId] = useState("");
const [time, setTime] = useState(nowHHMM);
const [outcome, setOutcome] = useState("MET");
@@ -33,7 +37,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
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.
// An Area Business 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);
@@ -47,11 +51,11 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
}, [preset?.key]);
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
const options = kind === "doctor" ? doctors : chemists;
const options = kind === "doctor" ? doctors : kind === "chemist" ? chemists : stockists;
// Visit times are local; today's report cannot hold a visit later than now.
const isToday = !isPlan && dcr.report_date === todayISO();
const timeLabel = isPlan ? "Planned time" : "Visit time";
const label = kind === "doctor" ? "Doctor" : "Chemist";
const label = KIND_LABEL[kind];
const v = useValidation({
target: [required(label)],
@@ -70,7 +74,9 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
setBusy(true);
setError(null);
try {
const updated = isPlan
const updated = kind === "stockist"
? await api.addStockistCall(dcr.id, { stockist_id: targetId, visit_time: time, pob: isPlan ? null : pob.trim() || null, remarks: remarks.trim() || null })
: 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 })
@@ -96,14 +102,15 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
<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(); }}>
<Select value={kind} onChange={(e) => { setKind(e.target.value as VisitKind); setTargetId(""); v.clear(); }}>
<option value="doctor">Doctor</option>
<option value="chemist">Chemist</option>
<option value="stockist">Stockist</option>
</Select>
</Field>
<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}>
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : kind === "stockist" ? "Your headquarters has no stockists yet — ask your administrator to add some." : `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="">{isSelf ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
<option value="">{isSelf || kind === "stockist" ? `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>
))}
@@ -1,5 +1,5 @@
import { EmptyState } from "../ui/States";
import { formatDateTime } from "../../lib/format";
import { formatDateTime, roleLabel } from "../../lib/format";
import type { Approval } from "../../types";
export function ApprovalTimeline({ items }: { items: Approval[] }) {
@@ -11,7 +11,7 @@ export function ApprovalTimeline({ items }: { items: Approval[] }) {
<span className="timeline-dot" />
<div>
<p className="timeline-action">{item.action.replaceAll("_", " ")}</p>
<p className="timeline-meta">{item.actor_name} · {item.actor_role}</p>
<p className="timeline-meta">{item.actor_name} · {roleLabel(item.actor_role)}</p>
<time className="timeline-meta">{formatDateTime(item.at)}</time>
{item.comment && <p className="timeline-note">{item.comment}</p>}
</div>
@@ -5,6 +5,8 @@ import { Field, Textarea } from "../ui/Field";
import { EmptyState } from "../ui/States";
import type { Dcr, PlannedVisit } from "../../types";
const KIND_LABEL: Record<PlannedVisit["kind"], string> = { DOCTOR: "Doctor", CHEMIST: "Chemist", STOCKIST: "Stockist" };
const STATUS: Record<PlannedVisit["status"], { label: string; tone: "success" | "warning" | "danger" }> = {
VISITED: { label: "Visited", tone: "success" },
MISSED: { label: "Missed", tone: "warning" },
@@ -50,7 +52,7 @@ export function PlannedVisitList({ dcr, editable, onRecord, onSaveReason, onClea
<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>
<strong>{line.name}</strong> <Badge tone={line.kind === "DOCTOR" ? "brand" : "neutral"}>{KIND_LABEL[line.kind]}</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>}
+2 -2
View File
@@ -13,8 +13,8 @@ export function ReviewPanel({ dcr, role, busy, onDecide }: {
}) {
const [comment, setComment] = useState("");
const [problem, setProblem] = useState<string | null>(null);
// The Area Manager is the final approver: approve and lock, or return for correction.
const canDecide = role === "AM" && dcr.status === "PENDING_AM";
// The Area Business Manager is the final approver: approve and lock, or return for correction.
const canDecide = role === "ABM" && dcr.status === "PENDING_ABM";
if (!canDecide) return null;
const check = (action: ReviewAction, text: string): string | null =>
+1 -1
View File
@@ -4,7 +4,7 @@ import type { DcrStatus, ReportType } from "../../types";
const TONE: Record<DcrStatus, Tone> = {
DRAFT: "neutral",
PENDING_AM: "warning",
PENDING_ABM: "warning",
RETURNED: "danger",
APPROVED: "success",
};
+5 -2
View File
@@ -4,7 +4,7 @@ import { EmptyState } from "../ui/States";
import { humanize } from "../../lib/format";
import type { Dcr } from "../../types";
interface Visit { id: string; kind: "Doctor" | "Chemist"; name: string; time: string; detail: string; core: boolean }
interface Visit { id: string; kind: "Doctor" | "Chemist" | "Stockist"; name: string; time: string; detail: string; core: boolean }
export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boolean; onRemove: (callId: string) => void }) {
const visits: Visit[] = [
@@ -15,6 +15,9 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
...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(" · "),
})),
...(dcr.stockist_calls ?? []).map((c) => ({
id: c.id, kind: "Stockist" as const, name: c.stockist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
})),
].sort((a, b) => a.time.localeCompare(b.time));
if (visits.length === 0) {
@@ -23,7 +26,7 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
<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}
description={editable ? (plan ? "Add the doctors, chemists and stockists you plan to visit above." : "Add doctor, chemist and stockist visits above.") : undefined}
/>
);
}
@@ -1,12 +1,12 @@
import { Icon } from "../ui/Icon";
import type { DcrStatus, ReportType } from "../../types";
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 STEPS = ["Draft", "Area Business Manager (ABM)", "Approved"];
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_ABM: 1, APPROVED: 2 };
/** An Area Business 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. */
/** Where a report is in DRAFT → ABM → APPROVED. A returned report sits back at step one. */
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);
+1
View File
@@ -2,6 +2,7 @@ import type { SVGProps } from "react";
const PATHS = {
dashboard: "M3 3h7v9H3z M14 3h7v5h-7z M14 12h7v9h-7z M3 16h7v5H3z",
eye: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6",
file: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z M14 3v5h5 M9 13h6 M9 17h6",
stethoscope: "M6 3v6a4 4 0 0 0 8 0V3 M4 3h4 M12 3h4 M10 13v2a5 5 0 0 0 10 0v-2 M20 8a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",
box: "M21 8l-9-5-9 5v8l9 5 9-5z M3 8l9 5 9-5 M12 13v9",
+8 -4
View File
@@ -2,7 +2,7 @@ import type { DcrStatus, ReportType, Role } from "../types";
export const STATUS_LABEL: Record<DcrStatus, string> = {
DRAFT: "Draft",
PENDING_AM: "With Area Manager",
PENDING_ABM: "With Area Business Manager (ABM)",
RETURNED: "Returned",
APPROVED: "Approved",
};
@@ -10,7 +10,7 @@ export const STATUS_LABEL: Record<DcrStatus, string> = {
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. */
/** An Area Business 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. */
@@ -19,11 +19,14 @@ 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",
ABM: "Area Business Manager (ABM)",
AGM: "Assistant General Manager (AGM)",
ADMIN: "Administrator",
};
const ROLE_LABELS: ReadonlyMap<string, string> = new Map(Object.entries(ROLE_LABEL));
export const roleLabel = (role: string) => ROLE_LABELS.get(role) ?? role;
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
/** Today's local date as YYYY-MM-DD, or `days` from today. */
export const todayISO = (days = 0) => {
@@ -74,6 +77,7 @@ const COLUMN_LABEL_OVERRIDES: Record<string, string> = {
postage: "Postage (Rs)",
other_expense: "Other expense (Rs)",
total: "Total (Rs)",
stockiest_visit: "Stockist Visit",
};
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
+5 -5
View File
@@ -1,9 +1,9 @@
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. */
/** Headquarters a person works in: an MR has one, an ABM has any number, AGM 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: [] };
if (user.role === "AGM" || user.role === "ADMIN") return { all: true, items: [] };
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);
@@ -12,15 +12,15 @@ export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaMa
}
/**
* 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.
* The Area Business Managers of each headquarters, by name ("Asha Rao, Ravi Das"). A headquarters may
* have several. `except` leaves one Area Business 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"]);
byHq.set(m.headquarters_id, [...(byHq.get(m.headquarters_id) ?? []), name.get(m.area_manager_user_id) ?? "an Area Business Manager"]);
}
return Object.fromEntries([...byHq].map(([hq, names]) => [hq, names.sort().join(", ")]));
}
+5 -5
View File
@@ -24,9 +24,9 @@ export const NAVIGATION: NavSection[] = [
title: "Workspace",
items: [
{ to: "/", label: "Dashboard", icon: "dashboard" },
{ 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"] },
{ to: "/reports/plan", label: "Daily Call Report (Plan)", icon: "file", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
{ to: "/reports/done", label: "Daily Call Report (Done)", icon: "checkCircle", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
{ to: "/reports/self", label: "Daily Call Report (Self)", icon: "file", roles: ["ABM", "AGM", "ADMIN"] },
],
},
{
@@ -34,14 +34,14 @@ 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", "SFE", "AM", "GM", "ADMIN"] },
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
],
},
{
title: "Administration",
items: [
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN", "MR", "SFE"] },
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "AGM"] },
],
},
];
+69 -35
View File
@@ -16,9 +16,9 @@ import { ROLE_LABEL, isField } from "../lib/format";
import { headquartersOf } from "../lib/headquarters";
import type { DcrListItem, Headquarters, Role, User } from "../types";
const WAITING: Record<"MR" | "AM", { statuses: DcrListItem["status"][]; title: string; empty: string }> = {
const WAITING: Record<"MR" | "ABM", { statuses: DcrListItem["status"][]; title: string; empty: string }> = {
MR: { statuses: ["RETURNED", "DRAFT"], title: "Waiting on you", empty: "No drafts or reports sent back for correction." },
AM: { statuses: ["PENDING_AM"], title: "Waiting on you", empty: "No reports are waiting for your review." },
ABM: { statuses: ["PENDING_ABM"], title: "Waiting on you", empty: "No reports are waiting for your review." },
};
export function DashboardPage() {
@@ -42,40 +42,40 @@ function HeadquartersFilter({ value, onChange }: { value: string; onChange: (id:
}
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
// The General Manager looks across every headquarters, so they can narrow it to one.
// The Assistant 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 hqId = role === "AGM" ? 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[isField(role) ? "MR" : (role as "AM")];
// An Assistant General Manager has no approval step — they get a read-only overview.
const config = role === "AGM" ? null : WAITING[isField(role) ? "MR" : (role as "ABM")];
const all = reports.data ?? [];
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
return (
<>
<PageHeader
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."}
title={isMR ? `Good to see you, ${name}` : role === "AGM" ? "Reports overview" : "Your review queue"}
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "AGM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
actions={isMR
? <>
<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} />}
{role === "AGM" && <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} />}
{role === "AGM" && <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" />
<Stat label="With Area Business Manager" value={counts.data?.PENDING_ABM ?? "–"} tone="warning" />
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
</div>
@@ -94,13 +94,13 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
)}
<Card>
<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>} />
<CardHeader title={role === "AGM" ? "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} />}
{role === "AGM" && <AreaManagerReports hqId={hqId} />}
</>
);
}
@@ -113,7 +113,7 @@ function MyHeadquarters() {
.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…"} />
<CardHeader title="Your headquarters" description={hqs.data ? `You cover ${mine.length} headquarters. Reports go to the Area Business 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>)}
@@ -123,7 +123,7 @@ function MyHeadquarters() {
);
}
/** For a General Manager: what the Area Managers did themselves (their Daily Call Report (Self)). */
/** For an Assistant General Manager: what the Area Business 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 ?? [];
@@ -131,7 +131,7 @@ function AreaManagerReports({ hqId }: { hqId?: string }) {
return (
<Card>
<CardHeader
title="Area Managers' own reports"
title="Area Business 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>}
/>
@@ -139,14 +139,14 @@ function AreaManagerReports({ hqId }: { hqId?: string }) {
{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" />}
? <EmptyState icon="file" title="No Area Business Manager reports yet" />
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} ownerHeader="Area Business Manager" />}
</CardBody>
</Card>
);
}
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
type AdminView = "hq" | "mr" | "abm" | "agm" | "users";
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
@@ -156,14 +156,48 @@ function AdminDashboard() {
<>
<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} />
<AdminReportMonitor />
</>
);
}
function AdminReportMonitor() {
const [hq, setHq] = useState("");
const hqId = hq || undefined;
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
const all = reports.data ?? [];
const error = reports.error ?? counts.error;
return (
<Card>
<CardHeader
title="Daily Call Report monitoring"
description="Read-only view of reports across the company."
actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Link to="/reports/plan" className="text-link">View all →</Link></>}
/>
<CardBody>
{error
? <ErrorState message={error} onRetry={() => { void reports.reload(); void counts.reload(); }} />
: <div className="stats">
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
<Stat label="With Area Business Manager" value={counts.data?.PENDING_ABM ?? "–"} tone="warning" />
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
</div>}
</CardBody>
<CardBody flush>
{error
? null
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
</CardBody>
</Card>
);
}
/**
* 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.
* The admin manages them; an Assistant General Manager (`canManage` false) only looks — every
* headquarters, every MR, ABM and AGM — 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 });
@@ -172,8 +206,8 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
const [view, setView] = useState<AdminView | null>(null);
const panel = useRef<HTMLDivElement>(null);
const list = users.data ?? [];
// With one headquarters chosen: that headquarters, its MRs, the Area Managers who manage it,
// and the General Managers and admins (who cover every headquarters).
// With one headquarters chosen: that headquarters, its MRs, the Area Business Managers who manage it,
// and the Assistant 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;
@@ -209,7 +243,7 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
{ 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.
// Setup is the admin's; a AGM may open the People page but not Setup.
const manageLink = (to: string) => (canManage || to !== "/admin" ? to : null);
const setupHint = (text: string) => (canManage ? text : undefined);
@@ -224,15 +258,15 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
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={setupHint("Add one under Setup → People.")} />} />,
},
am: {
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
abm: {
title: "Area Business Managers (ABMs)", description: "Active Area Business Managers (ABMs) 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={setupHint("Add one under Setup → People.")} />} />,
table: <DataTable columns={userColumns(false, true)} rows={byRole("ABM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Business 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",
agm: {
title: "Assistant General Managers (AGMs)", description: "Active Assistant General Managers (AGMs). 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={setupHint("Add one under Setup → People.")} />} />,
table: <DataTable columns={userColumns(false, true)} rows={byRole("AGM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Assistant General Managers" description={setupHint("Add one under Setup → People.")} />} />,
},
users: {
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
@@ -248,8 +282,8 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
<div className="stats stats-5">
<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"} />
<Stat label="Area Business Managers (ABMs)" value={users.data ? byRole("ABM").length : "–"} hint="View details" onClick={() => pick("abm")} selected={view === "abm"} />
<Stat label="Assistant General Managers (AGMs)" value={users.data ? byRole("AGM").length : "–"} hint="View details" onClick={() => pick("agm")} selected={view === "agm"} />
<Stat label="Active users" value={users.data ? activeUsers.length : "–"} tone="success" hint="View details" onClick={() => pick("users")} selected={view === "users"} />
</div>
{current && (
@@ -266,14 +300,14 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
</Card>
</div>
)}
{/* Setup steps are the admin's to follow; the GM's dashboard leaves them out. */}
{/* Setup steps are the admin's to follow; the AGM's dashboard leaves them out. */}
{canManage && <Card>
<CardHeader title="Recommended order" description="Create organisation data in this order." />
<CardBody>
<ol className="checklist">
<li>Create headquarters</li>
<li>Create users (MR, AM, GM)</li>
<li>Assign an Area Manager to each headquarters</li>
<li>Create users (MR, ABM, AGM)</li>
<li>Assign an Area Business Manager to each headquarters</li>
<li>Create doctors, chemists and products</li>
<li>Assign doctors and chemists to Medical Representatives</li>
</ol>
+171 -27
View File
@@ -17,7 +17,7 @@ import { api } from "../api";
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";
import type { Chemist, Doctor, Stockist } from "../types";
const DOCTOR_COLUMNS: Column<Doctor>[] = [
{ key: "name", header: "Doctor", render: (d) => <strong>{d.name}</strong> },
@@ -31,38 +31,94 @@ const CHEMIST_COLUMNS: Column<Chemist>[] = [
{ key: "address", header: "Shop address", render: (c) => c.shop_address },
{ key: "status", header: "Status", render: (c) => <Badge tone={c.is_active ? "success" : "neutral"} dot>{c.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
];
const STOCKIST_COLUMNS: Column<Stockist>[] = [
{ key: "name", header: "Stockist", render: (s) => <strong>{s.name}</strong> },
{ key: "address", header: "Stockist address", render: (s) => s.address },
{ key: "status", header: "Status", render: (s) => <Badge tone={s.is_active ? "success" : "neutral"} dot>{s.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
];
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist };
const UNASSIGNED = "__unassigned__";
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist } | { kind: "stockist"; item: Stockist };
export function DirectoryPage() {
const user = useUser();
const toast = useToast();
const isAdmin = user.role === "ADMIN";
const canSeeAssignedMr = user.role === "ADMIN" || user.role === "AGM";
/** Chemists and stockists show the Assigned MR column to the admin, AGM and Area Business Manager. */
const canSeeMasterMr = canSeeAssignedMr || user.role === "ABM";
const [editing, setEditing] = useState<Editing | null>(null);
const [toggling, setToggling] = useState<string | null>(null);
const doctors = useAsync(api.doctors, [], { poll: LIVE });
const chemists = useAsync(api.chemists, [], { poll: LIVE });
const stockists = useAsync(api.stockists, [], { poll: LIVE });
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
const hqLabel = useMemo(() => new Map((hqs.data ?? []).map((h) => [h.id, `${h.code} · ${h.name}`])), [hqs.data]);
const [tab, setTab] = useState<"doctors" | "chemists">("doctors");
const [tab, setTab] = useState<"doctors" | "chemists" | "stockists">("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.
// the admin and AGM, an Area Business Manager's own), so it offers exactly those. "" = all of them.
const [hqFilter, setHqFilter] = useState("");
const inHq = (id: string) => !hqFilter || id === hqFilter;
// MR filter (admin, AGM, Area Business Manager): "" = every MR, UNASSIGNED = no MR.
// A stockist belongs to every MR working its headquarters, so it matches any of them.
const canFilterMr = canSeeAssignedMr || user.role === "ABM";
const [mrFilter, setMrFilter] = useState("");
const mrNames = (names: string | null | undefined) => (names ?? "").split(",").map((n) => n.trim()).filter(Boolean);
const ofMr = (names: string | null | undefined) => {
if (!mrFilter) return true;
const list = mrNames(names);
return mrFilter === UNASSIGNED ? list.length === 0 : list.includes(mrFilter);
};
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;
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => inHq(d.headquarters_id) && ofMr(d.assigned_mr_name) && (!q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [doctors.data, hqLabel, q, hqFilter, mrFilter]);
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => inHq(c.headquarters_id) && ofMr(c.assigned_mr_name) && (!q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [chemists.data, hqLabel, q, hqFilter, mrFilter]);
const stockistRows = useMemo(() => (stockists.data ?? []).filter((s) => inHq(s.headquarters_id) && ofMr(s.assigned_mr_name) && (!q || `${s.name} ${s.address} ${hqLabel.get(s.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [stockists.data, hqLabel, q, hqFilter, mrFilter]);
const active = tab === "doctors" ? doctors : tab === "chemists" ? chemists : stockists;
/** The MRs in this tab's list (within the chosen headquarters), for the MR filter. */
const mrOptions = useMemo(() => {
const items: { headquarters_id: string; assigned_mr_name?: string | null }[] = active.data ?? [];
const names = new Set(items.filter((i) => inHq(i.headquarters_id)).flatMap((i) => mrNames(i.assigned_mr_name)));
if (mrFilter && mrFilter !== UNASSIGNED) names.add(mrFilter);
return [...names].sort((a, b) => a.localeCompare(b));
}, [active.data, hqFilter, mrFilter]);
const [printing, setPrinting] = useState<"view" | "download" | null>(null);
const shownCount = tab === "doctors" ? doctorRows.length : tab === "chemists" ? chemistRows.length : stockistRows.length;
/** The list on screen (current tab, headquarters filter and search) as a PDF. */
async function printList(mode: "view" | "download") {
const hq = (id: string) => hqLabel.get(id) ?? "";
const yesNo = (v: boolean) => (v ? "Active" : "Inactive");
const payload =
tab === "doctors"
? {
title: "Doctors",
columns: ["doctor", "headquarters", "speciality", "clinic_address", "type", ...(canSeeAssignedMr ? ["assigned_mr"] : []), "status"],
rows: doctorRows.map((d) => ({ doctor: d.name, headquarters: hq(d.headquarters_id), speciality: d.speciality || "", clinic_address: d.clinic_address, type: d.is_core_doctor ? "Core doctor" : "Regular", assigned_mr: d.assigned_mr_name || "Unassigned", status: yesNo(d.is_active) })),
}
: tab === "chemists"
? { title: "Chemists", columns: ["chemist", "headquarters", "shop_address", ...(canSeeMasterMr ? ["assigned_mr"] : []), "status"], rows: chemistRows.map((c) => ({ chemist: c.name, headquarters: hq(c.headquarters_id), shop_address: c.shop_address, assigned_mr: c.assigned_mr_name || "Unassigned", status: yesNo(c.is_active) })) }
: { title: "Stockists", columns: ["stockist", "headquarters", "stockist_address", ...(canSeeMasterMr ? ["assigned_mr"] : []), "status"], rows: stockistRows.map((s) => ({ stockist: s.name, headquarters: hq(s.headquarters_id), stockist_address: s.address, assigned_mr: s.assigned_mr_name || "Unassigned", status: yesNo(s.is_active) })) };
setPrinting(mode);
try {
await api.directoryPdf(payload, mode);
} catch (err) {
toast.error(errorMessage(err, mode === "view" ? "Could not open the PDF" : "Download failed"));
} finally {
setPrinting(null);
}
}
async function toggleActive(target: Editing) {
const next = !target.item.is_active;
setToggling(target.item.id);
try {
if (target.kind === "doctor") await api.updateDoctor(target.item.id, { is_active: next });
else await api.updateChemist(target.item.id, { is_active: next });
toast.success(`${target.kind === "doctor" ? "Doctor" : "Chemist"} ${next ? "activated" : "deactivated"}`);
await (target.kind === "doctor" ? doctors : chemists).reload();
else if (target.kind === "chemist") await api.updateChemist(target.item.id, { is_active: next });
else await api.updateStockist(target.item.id, { is_active: next });
const label = target.kind === "doctor" ? "Doctor" : target.kind === "chemist" ? "Chemist" : "Stockist";
toast.success(`${label} ${next ? "activated" : "deactivated"}`);
await (target.kind === "doctor" ? doctors : target.kind === "chemist" ? chemists : stockists).reload();
} catch (err) {
toast.error(errorMessage(err, "Could not change the status"));
} finally {
@@ -80,40 +136,67 @@ export function DirectoryPage() {
const doctorColumns: Column<Doctor>[] = [
...DOCTOR_COLUMNS.slice(0, 1),
{ key: "hq", header: "Headquarters", render: (d) => hqCell(d.headquarters_id), nowrap: true },
...DOCTOR_COLUMNS.slice(1),
...DOCTOR_COLUMNS.slice(1, 4),
...(canSeeAssignedMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (d: Doctor) => d.assigned_mr_name || "Unassigned" }] : []),
...DOCTOR_COLUMNS.slice(4),
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (d: Doctor) => editButton({ kind: "doctor", item: d }) }] : []),
];
const chemistColumns: Column<Chemist>[] = [
...CHEMIST_COLUMNS.slice(0, 1),
{ key: "hq", header: "Headquarters", render: (c) => hqCell(c.headquarters_id), nowrap: true },
...CHEMIST_COLUMNS.slice(1),
...CHEMIST_COLUMNS.slice(1, 2),
...(canSeeMasterMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (c: Chemist) => c.assigned_mr_name || "Unassigned" }] : []),
...CHEMIST_COLUMNS.slice(2),
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (c: Chemist) => editButton({ kind: "chemist", item: c }) }] : []),
];
const stockistColumns: Column<Stockist>[] = [
...STOCKIST_COLUMNS.slice(0, 1),
{ key: "hq", header: "Headquarters", render: (s) => hqCell(s.headquarters_id), nowrap: true },
...STOCKIST_COLUMNS.slice(1, 2),
...(canSeeMasterMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (s: Stockist) => s.assigned_mr_name || "Unassigned" }] : []),
...STOCKIST_COLUMNS.slice(2),
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (s: Stockist) => editButton({ kind: "stockist", item: s }) }] : []),
];
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(); }} />}
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); void stockists.reload(); }} />}
<Card>
<div className="toolbar">
<Tabs
label="Directory"
value={tab}
onChange={setTab}
items={[{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined }, { key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined }]}
items={[
{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined },
{ key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined },
{ key: "stockists", label: "Stockists", count: stockists.data ? stockistRows.length : undefined },
]}
/>
<div className="toolbar-group">
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
<Select className="hq-filter" value={hqFilter} onChange={(e) => { setHqFilter(e.target.value); setMrFilter(""); }} 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>
{canFilterMr && (
<Select className="hq-filter" value={mrFilter} onChange={(e) => setMrFilter(e.target.value)} aria-label="Filter by MR" disabled={!active.data}>
<option value="">All MRs</option>
{mrOptions.map((name) => <option key={name} value={name}>{name}</option>)}
<option value={UNASSIGNED}>Unassigned</option>
</Select>
)}
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
<Button icon="eye" disabled={shownCount === 0} loading={printing === "view"} onClick={() => void printList("view")}>View</Button>
<Button icon="download" disabled={shownCount === 0} loading={printing === "download"} onClick={() => void printList("download")}>Download PDF</Button>
</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" />} />
) : (
) : tab === "chemists" ? (
<DataTable columns={chemistColumns} rows={chemistRows} rowKey={(c) => c.id} loading={chemists.loading} minWidth={640} empty={<EmptyState icon="stethoscope" title="No chemists found" />} />
) : (
<DataTable columns={stockistColumns} rows={stockistRows} rowKey={(s) => s.id} loading={stockists.loading} minWidth={640} empty={<EmptyState icon="box" title="No stockists found" />} />
)}
</Card>
{editing && (
@@ -121,9 +204,10 @@ export function DirectoryPage() {
editing={editing}
onClose={() => setEditing(null)}
onSaved={() => {
const label = editing.kind === "doctor" ? "Doctor" : editing.kind === "chemist" ? "Chemist" : "Stockist";
setEditing(null);
toast.success(`${editing.kind === "doctor" ? "Doctor" : "Chemist"} updated`);
void (editing.kind === "doctor" ? doctors : chemists).reload();
toast.success(`${label} updated`);
void (editing.kind === "doctor" ? doctors : editing.kind === "chemist" ? chemists : stockists).reload();
}}
/>
)}
@@ -133,29 +217,68 @@ export function DirectoryPage() {
function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onClose: () => void; onSaved: () => void }) {
const isDoctor = editing.kind === "doctor";
const isChemist = editing.kind === "chemist";
const hasMr = editing.kind !== "stockist";
const doctor = isDoctor ? (editing.item as Doctor) : null;
const chemist = isChemist ? (editing.item as Chemist) : null;
const originalMr = (doctor?.assigned_mr_id ?? chemist?.assigned_mr_id) || "";
const [name, setName] = useState(editing.item.name);
const [address, setAddress] = useState(isDoctor ? (editing.item as Doctor).clinic_address : (editing.item as Chemist).shop_address);
const [speciality, setSpeciality] = useState(isDoctor ? (editing.item as Doctor).speciality ?? "" : "");
const [core, setCore] = useState(isDoctor ? (editing.item as Doctor).is_core_doctor : false);
const [hqId, setHqId] = useState(editing.item.headquarters_id);
const [address, setAddress] = useState(doctor ? doctor.clinic_address : chemist ? chemist.shop_address : (editing.item as Stockist).address);
const [contact, setContact] = useState((doctor?.contact_number ?? chemist?.contact_number ?? (editing.item as Stockist).contact_number) || "");
const [speciality, setSpeciality] = useState(doctor?.speciality ?? "");
const [qualification, setQualification] = useState(doctor?.qualification ?? "");
const [dob, setDob] = useState(doctor?.date_of_birth ?? "");
const [core, setCore] = useState(doctor?.is_core_doctor ?? false);
const [mrId, setMrId] = useState(originalMr);
const [active, setActive] = useState(editing.item.is_active);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const hqs = useAsync(api.headquarters, []);
const users = useAsync(api.users, []);
/** Active MRs / SFEs who work a headquarters (their own one or an extra one). */
const mrsOf = (hq: string) => (users.data ?? [])
.filter((u) => u.is_active && (u.role === "MR" || u.role === "SFE") && (u.headquarters_id === hq || (u.extra_headquarter_ids ?? []).includes(hq)))
.sort((a, b) => a.full_name.localeCompare(b.full_name));
const mrOptions = mrsOf(hqId);
const stockistMrs = !hasMr ? mrOptions.map((u) => u.full_name).join(", ") : "";
const addressLabel = isDoctor ? "Clinic address" : isChemist ? "Shop address" : "Stockist address";
const v = useValidation({
name: [required("Name"), minLength(2, "Name"), maxLength(200, "Name")],
address: [required(isDoctor ? "Clinic address" : "Shop address"), minLength(2, "Address"), maxLength(500, "Address")],
address: [required(addressLabel), minLength(2, "Address"), maxLength(500, "Address")],
speciality: [maxLength(100, "Speciality")],
qualification: [maxLength(100, "Qualification")],
contact: [maxLength(20, "Contact number")],
});
function changeHq(next: string) {
setHqId(next);
// An MR can only hold masters of a headquarters they work, as the server also enforces.
if (mrId && !mrsOf(next).some((u) => u.id === mrId)) setMrId("");
}
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ name, address, speciality }, e.currentTarget)) return;
if (!v.check({ name, address, speciality, qualification, contact }, e.currentTarget)) return;
setBusy(true);
setError(null);
const common = {
name: name.trim(),
contact_number: contact.trim() || null,
is_active: active,
...(hqId !== editing.item.headquarters_id ? { headquarters_id: hqId } : {}),
};
try {
if (isDoctor) {
await api.updateDoctor(editing.item.id, { name: name.trim(), clinic_address: address.trim(), speciality: speciality.trim() || null, is_core_doctor: core, is_active: active });
await api.updateDoctor(editing.item.id, { ...common, clinic_address: address.trim(), speciality: speciality.trim() || null, qualification: qualification.trim() || null, date_of_birth: dob || null, is_core_doctor: core });
} else if (isChemist) {
await api.updateChemist(editing.item.id, { ...common, shop_address: address.trim() });
} else {
await api.updateChemist(editing.item.id, { name: name.trim(), shop_address: address.trim(), is_active: active });
await api.updateStockist(editing.item.id, { ...common, address: address.trim() });
}
if (hasMr && mrId !== originalMr) {
if (mrId) await (isDoctor ? api.assignDoctor(editing.item.id, mrId) : api.assignChemist(editing.item.id, mrId));
else await api.unassignMaster(isDoctor ? "doctor" : "chemist", editing.item.id);
}
onSaved();
} catch (err) {
@@ -168,15 +291,36 @@ function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onCl
return (
<Modal
open
title={isDoctor ? "Edit doctor" : "Edit chemist"}
title={isDoctor ? "Edit doctor" : isChemist ? "Edit chemist" : "Edit stockist"}
onClose={onClose}
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("directory-editor-form") as HTMLFormElement | null)?.requestSubmit()}>Save changes</Button></>}
>
<form id="directory-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Name" required error={v.errors.name}><Input value={name} onChange={(e) => { setName(e.target.value); v.retouch("name", e.target.value); }} onBlur={(e) => v.touch("name", e.target.value)} /></Field>
<Field label={isDoctor ? "Clinic address" : "Shop address"} required error={v.errors.address}><Input value={address} onChange={(e) => { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /></Field>
<Field label="Headquarters" required>
<Select value={hqId} onChange={(e) => changeHq(e.target.value)} disabled={!hqs.data}>
{!hqs.data && <option value={hqId}>Loading…</option>}
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
</Select>
</Field>
{hasMr ? (
<Field label="Assigned MR" hint={mrOptions.length === 0 && users.data ? "No active MR works this headquarters yet." : undefined}>
<Select value={mrId} onChange={(e) => setMrId(e.target.value)} disabled={!users.data}>
<option value="">Unassigned</option>
{mrOptions.map((u) => <option key={u.id} value={u.id}>{u.full_name} ({u.employee_code})</option>)}
</Select>
</Field>
) : (
<Field label="Assigned MR" hint="A stockist serves every MR of its headquarters; change the headquarters to change them.">
<Input value={users.data ? stockistMrs || "No active MR in this headquarters" : "Loading…"} readOnly disabled />
</Field>
)}
<Field label={addressLabel} required error={v.errors.address}><Input value={address} onChange={(e) => { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /></Field>
{isDoctor && <Field label="Speciality" error={v.errors.speciality}><Input value={speciality} onChange={(e) => { setSpeciality(e.target.value); v.retouch("speciality", e.target.value); }} onBlur={(e) => v.touch("speciality", e.target.value)} /></Field>}
{isDoctor && <Field label="Qualification" error={v.errors.qualification}><Input value={qualification} onChange={(e) => { setQualification(e.target.value); v.retouch("qualification", e.target.value); }} onBlur={(e) => v.touch("qualification", e.target.value)} /></Field>}
<Field label="Contact number" error={v.errors.contact}><Input type="tel" value={contact} onChange={(e) => { setContact(e.target.value); v.retouch("contact", e.target.value); }} onBlur={(e) => v.touch("contact", e.target.value)} /></Field>
{isDoctor && <Field label="Date of birth"><Input type="date" value={dob} max={new Date().toISOString().slice(0, 10)} onChange={(e) => setDob(e.target.value)} /></Field>}
{isDoctor && <Checkbox label="Core doctor" checked={core} onChange={(e) => setCore(e.target.checked)} />}
<Checkbox label="Active" checked={active} onChange={(e) => setActive(e.target.checked)} />
</form>
+1 -1
View File
@@ -26,7 +26,7 @@ export function ProfilePage() {
{ label: "Employee code", value: p.employee_code },
{ label: "Phone", value: p.phone },
{ label: "Headquarters", value: p.headquarters_name ? `${p.headquarters_name}${p.headquarters_code ? ` (${p.headquarters_code})` : ""}` : "Not assigned" },
{ label: "Reporting Area Manager", value: p.reporting_manager_name || "Not assigned" },
{ label: "Reporting Area Business Manager", value: p.reporting_manager_name || "Not assigned" },
]} />
</CardBody>
</Card>
+42 -26
View File
@@ -99,7 +99,7 @@ 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. */
/** Setup for the signed-in role: an MR gets only the doctor, chemist and stockist forms. */
export function AdminPage() {
return isField(useUser().role) ? <MasterDataSetup /> : <FullSetup />;
}
@@ -118,8 +118,8 @@ function HeadquartersSelect({ hqs }: { hqs: Headquarters[] }) {
);
}
/** 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;
/** What an MR sees after adding a doctor, chemist or stockist: it is not in their list yet. */
const sentForApproval = (role: string, what: string) => isField(role) ? `${what} sent to your Area Business Manager for approval` : undefined;
function DoctorForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
const role = useUser().role;
@@ -152,7 +152,21 @@ function ChemistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }
);
}
/** An MR adds doctors and chemists to their own headquarters; each is assigned to them. */
function StockistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
const role = useUser().role;
return (
<AdminForm title="Create stockist" submitLabel={isField(role) ? "Send for approval" : "Create stockist"} successMessage={sentForApproval(role, "Stockist")}
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Stockist address"), phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createStockist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), address: text(f, "address"), contact_number: optional(f, "phone") }))}>
<HeadquartersSelect hqs={hqs} />
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Stockist 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, chemists and stockists to their own headquarters; each waits for approval. */
function MasterDataSetup() {
const hqs = useAsync(() => api.headquarters(), []);
// A new request shows in "Your requests" straight away, not only on the next poll.
@@ -160,11 +174,12 @@ function MasterDataSetup() {
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." />
<PageHeader title="Setup" description="Add a doctor, chemist or stockist in your headquarters. Your Area Business 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} />
<StockistForm hqs={hqs.data ?? []} refresh={refresh} />
</div>
<MasterRequests key={sent} mode="mine" />
</>
@@ -179,12 +194,12 @@ function FullSetup() {
}, [], { poll: LIVE });
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
const mrs = users.filter((u) => isField(u.role));
const ams = users.filter((u) => u.role === "AM");
const ams = users.filter((u) => u.role === "ABM");
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
return (
<>
<PageHeader title="Setup" description="Create organisation data in this order: headquarters, users, Area Manager mapping, master data, then assignments." />
<PageHeader title="Setup" description="Create organisation data in this order: headquarters, users, Area Business Manager mapping, master data, then assignments." />
<Alert tone="danger">{data.error}</Alert>
<Tabs
label="Setup sections"
@@ -219,6 +234,7 @@ function FullSetup() {
<div className="grid-2">
<DoctorForm hqs={hqs} refresh={refresh} />
<ChemistForm hqs={hqs} refresh={refresh} />
<StockistForm 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") }))}>
@@ -249,11 +265,11 @@ function FullSetup() {
);
}
/** Choose an Area Manager, then tick every headquarters they should manage. */
/** Choose an Area Business 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());
// The other Area Managers of each headquarters: ticking one adds this AM beside them.
// The other Area Business Managers of each headquarters: ticking one adds this ABM beside them.
const owners = areaManagersOf(mappings, users, amId || undefined);
function choose(id: string) {
@@ -262,23 +278,23 @@ 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, and a headquarters can have several Area Managers. Ticking one already managed by someone else adds this Area Manager beside them."
title="Assign headquarters to an Area Business Manager"
description="An Area Business Manager can manage any number of headquarters, and a headquarters can have several Area Business Managers. Ticking one already managed by someone else adds this Area Business Manager beside them."
submitLabel="Save assignments"
rules={{ area_manager_user_id: [required("Area Manager")] }}
rules={{ area_manager_user_id: [required("Area Business Manager")] }}
onSubmit={async () => {
await api.setAreaManagerHeadquarters(amId, [...picked]);
setAmId(""); setPicked(new Set());
await onSaved();
}}
>
<Field label="Area Manager" name="area_manager_user_id" required span>
<Field label="Area Business Manager" name="area_manager_user_id" required span>
<Select name="area_manager_user_id" value={amId} onChange={(e) => choose(e.target.value)}>
<option value="">Choose Area Manager</option>
<option value="">Choose Area Business Manager</option>
{ams.map((u) => <option key={u.id} value={u.id}>{u.full_name}</option>)}
</Select>
</Field>
<Field label="Headquarters they manage" span group hint={amId ? `${picked.size} selected` : "Choose an Area Manager first."}>
<Field label="Headquarters they manage" span group hint={amId ? `${picked.size} selected` : "Choose an Area Business Manager first."}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} disabled={!amId} />
</Field>
</AdminForm>
@@ -293,12 +309,12 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
{ 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 Managers", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
{ key: "am", header: "Area Business 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 (
<Card>
<CardHeader title="Headquarters overview" description="Every headquarters, its Area Manager and how many active MRs work there." />
<CardHeader title="Headquarters overview" description="Every headquarters, its Area Business Manager and how many active MRs work there." />
<CardBody flush>
<DataTable columns={columns} rows={hqs} rowKey={(h) => h.id} loading={loading} minWidth={560} />
</CardBody>
@@ -307,11 +323,11 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
}
const ROLES = [
{ 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" },
{ value: "MR", label: "Medical Representative" }, { value: "SFE", label: "Senior Field Executive" }, { value: "ABM", label: "Area Business Manager (ABM)" },
{ value: "AGM", label: "Assistant General Manager (AGM)" }, { value: "ADMIN", label: "Administrator" },
] as const;
/** Create-user form. Headquarters depends on the role: one for an MR, several for an AM, none for GM/Admin. */
/** Create-user form. Headquarters depends on the role: one for an MR, several for an ABM, none for AGM/Admin. */
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());
@@ -334,7 +350,7 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
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]);
if (role === "ABM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
setRole("MR"); setPicked(new Set()); setExtras(new Set());
await refresh(Promise.resolve(created));
}}
@@ -346,22 +362,22 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
<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>
{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."}>
<Field label="Headquarters" name="headquarters_id" required hint={role === "SFE" ? "Their main headquarters: reports go to its Area Business 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.`}>
<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 Business Manager.`}>
<HeadquartersChecklist headquarters={hqs} selected={extras} onChange={setExtras} />
</Field>
)}
{role === "AM" && (
{role === "ABM" && (
<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} />
</Field>
)}
{(role === "GM" || role === "ADMIN") && (
<p className="field-hint field-span">General Managers and Administrators see every headquarters, so none is assigned.</p>
{(role === "AGM" || role === "ADMIN") && (
<p className="field-hint field-span">Assistant General Managers and Administrators see every headquarters, so none is assigned.</p>
)}
</AdminForm>
);
+15 -15
View File
@@ -13,11 +13,11 @@ 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 STATUSES: DcrStatus[] = ["DRAFT", "PENDING_ABM", "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;
const APPROVAL_LABEL = { draft: "Draft", pending: "With Area Business 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. */
/** One person's whole picture, for the Assistant 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 });
@@ -38,10 +38,10 @@ export function UserDetailPage({ id }: { id: string }) {
<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} />
<CardHeader title={user.role === "ABM" ? "Headquarters they manage" : field ? "Headquarters" : "Headquarters"} description={user.role === "ABM" ? `${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>
? <span className="muted">{field || user.role === "ABM" ? "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>}
@@ -49,9 +49,9 @@ export function UserDetailPage({ id }: { id: string }) {
</Card>
{field && (
<Card>
<CardHeader title="Reports to" description="Area Manager(s) of the main headquarters" />
<CardHeader title="Reports to" description="Area Business Manager(s) of the main headquarters" />
<CardBody>
{o.reporting_managers.length === 0 ? <span className="muted">No Area Manager assigned</span>
{o.reporting_managers.length === 0 ? <span className="muted">No Area Business 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>
@@ -59,13 +59,13 @@ export function UserDetailPage({ id }: { id: string }) {
</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"} />
{user.role === "ABM" && <Team o={o} />}
{(field || user.role === "ABM") && <ReportsSection o={o} viewerRole={viewer.role} title={user.role === "ABM" ? "Reports in their headquarters" : "Daily call reports"} />}
{user.role === "ABM" && o.own_reports && o.own_reports.length > 0 && (
<ReportList title="Their own reports (Daily Call Report (Self))" rows={o.own_reports} link={viewer.role === "AGM"} />
)}
{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>}
{!field && user.role !== "ABM" && <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>}
</>
);
}
@@ -105,7 +105,7 @@ function Team({ o }: { o: UserOverview }) {
];
return (
<Card>
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Manager" />
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Business 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>
);
@@ -123,14 +123,14 @@ function ReportsSection({ o, viewerRole, title }: { o: UserOverview; viewerRole:
<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>)}
{STATUSES.map((s) => <Badge key={s} tone={s === "APPROVED" ? "success" : s === "RETURNED" ? "danger" : s === "PENDING_ABM" ? "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"} />
<ReportList title="Latest reports" rows={o.reports.recent} link={viewerRole === "AGM"} />
</>
);
}
+8 -8
View File
@@ -64,7 +64,7 @@ export function UsersPage() {
const q = query.trim().toLowerCase();
return (users.data ?? []).filter((u) => {
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).
// One headquarters chosen: only the people who work in it (AGM 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(" ");
@@ -94,11 +94,11 @@ export function UsersPage() {
);
}
/** Headquarters of one person: chips for an MR or AM, "All headquarters" for GM and Admin. */
/** Headquarters of one person: chips for an MR or ABM, "All headquarters" for AGM and Admin. */
function HqChips({ user, hqs, mappings }: { user: User; hqs: Headquarters[]; mappings: AreaManagerMapping[] }) {
const place = headquartersOf(user, hqs, mappings);
if (place.all) return <Badge tone="neutral">All headquarters</Badge>;
if (place.items.length === 0) return <span className="muted">{user.role === "AM" ? "None assigned" : "—"}</span>;
if (place.items.length === 0) return <span className="muted">{user.role === "ABM" ? "None assigned" : "—"}</span>;
return <span className="chips">{place.items.map((h) => <Badge key={h.id} tone="brand">{h.code}</Badge>)}</span>;
}
@@ -113,7 +113,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
const [role, setRole] = useState<Role>(user.role);
const [hqId, setHqId] = useState(user.headquarters_id ?? "");
const roleChanged = role !== user.role;
const isAm = role === "AM";
const isAm = role === "ABM";
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 !== "";
@@ -199,7 +199,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
<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."}
{user.role === "ABM" && " The headquarters they manage are released; any that have no other Area Business Manager need a new one."}
</Alert>
)}
{hqChanged && (
@@ -209,16 +209,16 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
<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.`}>
<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 Business 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. A headquarters can have several Area Managers; the others keep theirs.`}>
<Field label="Headquarters they manage" group hint={`${picked.size} selected. A headquarters can have several Area Business Managers; the others keep theirs.`}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
</Field>
)}
{(role === "GM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
{(role === "AGM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
</form>
</Modal>
);
+19 -17
View File
@@ -60,10 +60,10 @@ 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" || 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 isManager = user.role === "ABM" || user.role === "ADMIN" || user.role === "AGM";
// Admin and the Assistant General Manager look across every medical representative; the AGM only reads.
const seesAll = user.role === "ADMIN" || user.role === "AGM";
// Each MR has their own copy of these forms. An Area Business Manager (or admin) opens one MR's copy at a time.
// Sales Projection isn't an approval form but managers still pick a headquarters / MR to look at.
const hasPeopleFilter = isManager && (needsApproval || seesAll);
const owners = useAsync(() => (hasPeopleFilter ? api.formOwners() : Promise.resolve([])), [hasPeopleFilter], { poll: LIVE });
@@ -77,8 +77,8 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
if (!isManager || !needsApproval || !table) return undefined;
const chosen = ownerList.find((o) => o.id === (seesAll ? mrChoice : ownerChoice));
if (chosen) return chosen;
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
// An Area Business Manager lands on the MR who is waiting for them; an admin starts with everyone.
return user.role === "ABM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, mrChoice, seesAll, user.role, approvals.data]);
const waitingForOwners = isManager && needsApproval && !owners.data;
@@ -138,7 +138,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
// Only the controls that make sense right now: nothing to approve means nothing to show.
const canSend = needsApproval && isField(user.role) && status === "draft" && hasRows;
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
const canApprove = needsApproval && user.role === "ABM" && 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 —
@@ -158,7 +158,7 @@ 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)) ?? "";
// The General Manager and Admin can narrow every form by headquarters and medical representative.
// The Assistant 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));
@@ -170,7 +170,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
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 (listAcrossMrs && user.role === "AGM" && !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();
@@ -213,7 +213,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
const numberOf = (r: CsvRow) => String(positional ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
/** Send (MR) or approve (ABM). 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;
@@ -231,7 +231,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
try {
const saved = await (kind === "request" ? api.requestFormApproval(name) : api.approveForm(name, ownerId));
approvals.setData(merge(before, saved));
toast.success(kind === "request" ? "Sent to the Area Manager for approval" : "Form approved");
toast.success(kind === "request" ? "Sent to the Area Business Manager for approval" : "Form approved");
} catch (e) {
approvals.setData(before);
toast.error(errorMessage(e, kind === "request" ? "Could not send the form for approval" : "Could not approve the form"));
@@ -298,6 +298,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
render: (r) => (
<span className="row-actions">
{showEdit && !isNewRow(r) && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
<Button size="sm" variant="ghost" icon="eye" disabled={isNewRow(r)} onClick={() => void run(api.viewCsvPdf(table.name, { rowId: r.id }))}>View</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)}>
@@ -313,13 +314,13 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
return (
<>
<PageHeader title="Company forms" description={user.role === "GM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "Fill in the company’s standard forms and print them as ready-to-sign PDFs."} />
<PageHeader title="Company forms" description={user.role === "AGM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "Fill in the company’s standard forms and print them as ready-to-sign PDFs."} />
<div className="forms-layout">
<nav className="form-nav" aria-label="Forms">
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
<Link key={t.name} to={`/forms/${t.name}`} className={`form-nav-item${t.name === table?.name ? " active" : ""}`} aria-current={t.name === table?.name ? "page" : undefined}>
{t.label}
{user.role === "AM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
{user.role === "ABM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
</Link>
))}
</nav>
@@ -328,12 +329,13 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
{!table ? <CardBody><EmptyState icon="table" title="No forms available" /></CardBody> : (
<>
<CardHeader
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Manager"}` : "Pending AM approval"}</Badge>}</span>}
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Business Manager"}` : "Pending ABM approval"}</Badge>}</span>}
description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`}
actions={
<>
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as ABM</Button>}
<Button icon="eye" disabled={shownRows.length === 0} onClick={() => void run(api.viewCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>View</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>}
</>
@@ -341,7 +343,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
/>
{showToolbar && (
<div className="toolbar">
{user.role === "AM" && needsApproval && (
{user.role === "ABM" && needsApproval && (
<label className="filter">
<span>Medical representative</span>
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
@@ -390,7 +392,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
empty={month
? <EmptyState icon="table" title={`No rows for ${month}`} description="Choose another month, or All months." />
: isManager && needsApproval && ownerList.length === 0
? <EmptyState icon="users" title="No medical representatives" description={user.role === "AM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
? <EmptyState icon="users" title="No medical representatives" description={user.role === "ABM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
: <EmptyState icon="table" title="No rows yet" description={canAdd ? "Add a row to start filling in this form." : isManager && needsApproval ? "This medical representative has not filled in this form." : undefined} action={canAdd ? <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button> : undefined} />}
/>
)}
+2 -1
View File
@@ -39,8 +39,9 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
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.
// Sales and Stock Statement's VALUE IN PTS always follows the product's Sales Projection PTS.
const isExpense = table.name === "expense_statement";
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (isExpense && c === "total");
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (table.name === "sales_and_stock_statement" && c === "value_in_pts") || (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;
+1 -1
View File
@@ -1,4 +1,4 @@
/** Forms that carry an Area Manager approval signature on their PDF. */
/** Forms that carry an Area Business Manager approval signature on their PDF. */
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. */
+1 -1
View File
@@ -31,6 +31,6 @@ export function screenColumns(table: CsvTable, role: Role): string[] {
/** 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_and_stock_statement: new Set(["month", "opening", "receipt", "sale", "closing"]),
sales_projection: new Set(["month", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
};
+4 -4
View File
@@ -22,8 +22,8 @@ const COPY: Record<ReportType, { title: string; description: string; remarks: st
},
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",
description: "List the doctors and chemists you intend to visit today and when, then send the plan to your Area Business Manager.",
remarks: "Optional note for your Area Business Manager, e.g. the area you will cover",
create: "Start plan",
},
ACTUAL: {
@@ -41,7 +41,7 @@ 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.
// An Area Business 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 : "");
@@ -77,7 +77,7 @@ export function NewReportPage({ type }: { type: ReportType }) {
<CardBody>
<form className="form-grid" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<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."}>
<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 Business 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 && (
+27 -21
View File
@@ -16,12 +16,12 @@ 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, REPORT_TYPE_LABEL, isField } from "../../lib/format";
import { errorMessage, formatDate, formatDateTime, REPORT_TYPE_LABEL, isField, roleLabel } 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, PlannedVisit } from "../../types";
import type { Approval, Chemist, Dcr, Doctor, PlannedVisit, Stockist } from "../../types";
export function ReportDetailPage({ id }: { id: string }) {
const user = useUser();
@@ -59,11 +59,13 @@ export function ReportDetailPage({ id }: { id: string }) {
}
}, [report.data]);
// Only the report's owner edits it: the MR for a plan or done report, the AM for their own.
// Only the report's owner edits it: the MR for a plan or done report, the ABM 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[] })),
() => (editable
? Promise.all([api.doctors(), api.chemists(), api.stockists()]).then(([doctors, chemists, stockists]) => ({ doctors, chemists, stockists }))
: Promise.resolve({ doctors: [] as Doctor[], chemists: [] as Chemist[], stockists: [] as Stockist[] })),
[editable], { poll: LIVE },
);
@@ -112,7 +114,7 @@ export function ReportDetailPage({ id }: { id: string }) {
// Removing a visit vanishes from the list immediately; if the server refuses, it comes back.
const removeVisit = async (callId: string) => {
const before = dcr;
apply({ ...dcr, doctor_calls: dcr.doctor_calls.filter((c) => c.id !== callId), chemist_calls: dcr.chemist_calls.filter((c) => c.id !== callId) });
apply({ ...dcr, doctor_calls: dcr.doctor_calls.filter((c) => c.id !== callId), chemist_calls: dcr.chemist_calls.filter((c) => c.id !== callId), stockist_calls: dcr.stockist_calls.filter((c) => c.id !== callId) });
setError(null);
try {
apply(await api.deleteCall(dcr.id, callId));
@@ -126,14 +128,14 @@ export function ReportDetailPage({ id }: { id: string }) {
// --- 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.
// An Area Business 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 target = (line: PlannedVisit) => (line.kind === "DOCTOR" ? { doctor_id: line.target_id } : line.kind === "STOCKIST" ? { stockist_id: line.target_id } : { chemist_id: line.target_id });
const recordPlanned = (line: PlannedVisit) => setPreset({ kind: line.kind === "DOCTOR" ? "doctor" : line.kind === "STOCKIST" ? "stockist" : "chemist", targetId: line.target_id, key: Date.now() });
const saveReason = async (line: PlannedVisit, reason: string): Promise<boolean> => {
setError(null);
try {
@@ -176,6 +178,9 @@ export function ReportDetailPage({ id }: { id: string }) {
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 icon="eye" onClick={() => api.viewReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>View</Button>
)}
{dcr.status === "APPROVED" && (
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
)}
@@ -183,7 +188,7 @@ export function ReportDetailPage({ id }: { id: string }) {
/>
<Alert>{error}</Alert>
{dcr.return_reason && (
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ?? "reviewer"}`}>{dcr.return_reason}</Alert>
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ? roleLabel(dcr.returned_by_role) : "reviewer"}`}>{dcr.return_reason}</Alert>
)}
<Card><CardBody><WorkflowTracker status={dcr.status} type={dcr.report_type} /></CardBody></Card>
@@ -194,10 +199,11 @@ export function ReportDetailPage({ id }: { id: string }) {
<CardHeader title="Summary" />
<CardBody>
<KeyValue items={[
{ label: isSelf ? "Area Manager" : "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
{ label: isSelf ? "Area Business Manager" : "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
{ label: "Headquarters", value: dcr.headquarters_name },
{ label: isPlan ? "Doctors planned" : "Doctor visits", value: dcr.doctor_calls.length },
{ label: isPlan ? "Chemists planned" : "Chemist visits", value: dcr.chemist_calls.length },
...(dcr.stockist_calls.length ? [{ label: isPlan ? "Stockists planned" : "Stockist visits", value: dcr.stockist_calls.length }] : []),
...(dcr.plan_id ? [{ label: "Planned visits made", value: `${visitedPlanned} of ${planned.length}` }] : []),
{ label: "Submitted", value: formatDateTime(dcr.submitted_at) },
...(isSelf ? [] : [{ label: "Approved", value: formatDateTime(dcr.approved_at) }]),
@@ -214,7 +220,7 @@ export function ReportDetailPage({ id }: { id: string }) {
</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"} />
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder={isPlan ? "Optional note for your Area Business Manager" : "Optional summary of the day"} />
</Field>
</div>
) : (
@@ -230,8 +236,8 @@ export function ReportDetailPage({ id }: { id: string }) {
</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 && isField(user.role) && dcr.status === "PENDING_ABM" && (
<Alert tone="info">Once your Area Business 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>
@@ -263,13 +269,13 @@ export function ReportDetailPage({ id }: { id: string }) {
<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."
? "Who you intend to visit today, and when. Only doctors and chemists assigned to you, and stockists of your headquarters, 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."}
? `Doctors, chemists and stockists of ${dcr.headquarters_name} are listed.`
: "Only doctors and chemists assigned to you, and stockists of your headquarters, are listed. Unplanned visits can be added too."}
/>
<CardBody>
<AddVisitForm dcr={dcr} doctors={inReportHq(masters.data?.doctors ?? [])} chemists={inReportHq(masters.data?.chemists ?? [])} preset={preset} onChange={(next) => { apply(next); reconcile(); }} />
<AddVisitForm dcr={dcr} doctors={inReportHq(masters.data?.doctors ?? [])} chemists={inReportHq(masters.data?.chemists ?? [])} stockists={inReportHq(masters.data?.stockists ?? []).filter((s) => s.is_active)} preset={preset} onChange={(next) => { apply(next); reconcile(); }} />
</CardBody>
</Card>
)}
@@ -278,8 +284,8 @@ export function ReportDetailPage({ id }: { id: string }) {
<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.`}
? `${dcr.doctor_calls.length + dcr.chemist_calls.length + dcr.stockist_calls.length} planned, in time order.`
: `${dcr.doctor_calls.length + dcr.chemist_calls.length + dcr.stockist_calls.length} recorded, in visit order.`}
/>
<CardBody flush>
<VisitList dcr={dcr} editable={editable} onRemove={(callId) => void removeVisit(callId)} />
@@ -297,8 +303,8 @@ export function ReportDetailPage({ id }: { id: string }) {
: "Submitted reports cannot be edited unless they are returned for correction."}
/>
<CardBody>
<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 variant="primary" icon="send" loading={busy} disabled={pending > 0} onClick={() => void run(() => api.submit(dcr.id), isPlan ? "Plan sent to the Area Business Manager" : isSelf ? "Report submitted" : "Submitted to the Area Business Manager")}>
{isPlan ? "Send plan to Area Business Manager" : isSelf ? "Submit report" : "Submit to Area Business Manager"}
</Button>
</CardBody>
</Card>
+7 -7
View File
@@ -18,7 +18,7 @@ type Filter = "ALL" | "DRAFT" | "PENDING" | "RETURNED" | "APPROVED";
const MATCH: Record<Filter, (r: DcrListItem) => boolean> = {
ALL: () => true,
DRAFT: (r) => r.status === "DRAFT",
PENDING: (r) => r.status === "PENDING_AM",
PENDING: (r) => r.status === "PENDING_ABM",
RETURNED: (r) => r.status === "RETURNED",
APPROVED: (r) => r.status === "APPROVED",
};
@@ -27,10 +27,10 @@ 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.",
gm: "Area Business 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.",
mr: "Plan the doctors and chemists you will visit each day, and send the plan to your Area Business Manager.",
manager: "Day plans from your scope. Approving a plan lets the MR file its Daily Call Report (Done).",
},
ACTUAL: {
@@ -39,12 +39,12 @@ const DESCRIPTION: Record<ReportType, { mr: string; manager: string; gm?: string
},
};
/** The list behind one sidebar entry: Daily Call Report (Plan), (Done) or an Area Manager's (Self). */
/** The list behind one sidebar entry: Daily Call Report (Plan), (Done) or an Area Business Manager's (Self). */
export function ReportsPage({ type }: { type: ReportType }) {
const user = useUser();
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 author = isSelf ? "ABM" : "MR";
const reports = useAsync(() => api.reports(type), [type], { poll: LIVE });
const [filter, setFilter] = useState<Filter>("ALL");
const [query, setQuery] = useState("");
@@ -66,7 +66,7 @@ export function ReportsPage({ type }: { type: ReportType }) {
<>
<PageHeader
title={REPORT_TYPE_LABEL[type]}
description={isField(user.role) ? DESCRIPTION[type].mr : (user.role === "GM" && DESCRIPTION[type].gm) || DESCRIPTION[type].manager}
description={isField(user.role) ? DESCRIPTION[type].mr : (user.role === "AGM" && 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"})`}
@@ -80,7 +80,7 @@ export function ReportsPage({ type }: { type: ReportType }) {
</div>
{reports.error
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
: <ReportTable rows={rows} loading={reports.loading} ownerHeader={isSelf ? "Area Manager" : undefined} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
: <ReportTable rows={rows} loading={reports.loading} ownerHeader={isSelf ? "Area Business Manager (ABM)" : undefined} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
</Card>
</>
);
+11 -9
View File
@@ -1,30 +1,32 @@
export type Role = "ADMIN" | "GM" | "AM" | "MR" | "SFE";
export type DcrStatus = "DRAFT" | "PENDING_AM" | "RETURNED" | "APPROVED";
export type Role = "ADMIN" | "AGM" | "ABM" | "MR" | "SFE";
export type DcrStatus = "DRAFT" | "PENDING_ABM" | "RETURNED" | "APPROVED";
/** 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 }
/** A doctor or chemist an MR adds is PENDING until their Area Manager approves it; only APPROVED ones are listed. */
/** A doctor or chemist an MR adds is PENDING until their Area Business 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 Doctor extends MasterApprovalFields { id: string; headquarters_id: string; name: string; speciality: string | null; qualification?: string | null; contact_number?: string | null; clinic_address: string; date_of_birth: string | null; is_core_doctor: boolean; is_active: boolean; assigned_mr_name: string | null; assigned_mr_id?: string | null }
export interface Chemist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; shop_address: string; contact_number?: string | null; is_active: boolean; assigned_mr_name?: string | null; assigned_mr_id?: string | null }
export interface Stockist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; address: string; contact_number?: string | null; is_active: boolean; assigned_mr_name?: string | null }
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 | 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 StockistCall { id: string; stockist_id: string; stockist_name: string; visit_time: string; pob: string | null; remarks: string | null }
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[] }
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[]; stockist_calls: StockistCall[]; 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 PlannedVisit { kind: "DOCTOR" | "CHEMIST" | "STOCKIST"; 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[] }
export interface CsvRow { id: string; source_row_number: number;[key: string]: string | number }
export interface StatusCounts { DRAFT: number; PENDING_AM: number; RETURNED: number; APPROVED: number }
/** Server-side approval state of a company form. draft = not sent, pending = with the Area Manager. */
export interface StatusCounts { DRAFT: number; PENDING_ABM: number; RETURNED: number; APPROVED: number }
/** Server-side approval state of a company form. draft = not sent, pending = with the Area Business Manager. */
export type FormApproval = {
table_name: string; owner_user_id: string; owner_name: string; headquarters_name: string | null;
status: "draft" | "pending" | "approved"; approved_by_name: string | null; updated_at: string | null;