Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
import { AppShell } from "./components/layout/AppShell";
import { ToastProvider } from "./components/ui/Toast";
import { Skeleton } from "./components/ui/States";
import { matchPath, useLocation } from "./lib/router";
import { SessionProvider, useSession } from "./lib/session";
import { DashboardPage } from "./pages/DashboardPage";
import { DirectoryPage } from "./pages/DirectoryPage";
import { LoginPage } from "./pages/LoginPage";
import { NotFoundPage } from "./pages/NotFoundPage";
import { ProductsPage } from "./pages/ProductsPage";
import { ProfilePage } from "./pages/ProfilePage";
import { AdminPage } from "./pages/admin/AdminPage";
import { UsersPage } from "./pages/admin/UsersPage";
import { FormsPage } from "./pages/forms/FormsPage";
import { NewReportPage } from "./pages/reports/NewReportPage";
import { ReportDetailPage } from "./pages/reports/ReportDetailPage";
import { ReportsPage } from "./pages/reports/ReportsPage";
import type { Role } from "./types";
/** Which roles may open which screens; anything else renders "not found". */
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
{ pattern: "/", render: () => <DashboardPage /> },
{ pattern: "/reports", roles: ["MR", "AM", "GM"], render: () => <ReportsPage /> },
{ pattern: "/reports/new", roles: ["MR"], render: () => <NewReportPage /> },
{ pattern: "/reports/:id", roles: ["MR", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
{ pattern: "/directory", render: () => <DirectoryPage /> },
{ pattern: "/products", render: () => <ProductsPage /> },
{ pattern: "/forms", roles: ["MR", "AM", "ADMIN"], render: () => <FormsPage /> },
{ pattern: "/forms/:table", roles: ["MR", "AM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
{ pattern: "/profile", render: () => <ProfilePage /> },
{ pattern: "/admin", roles: ["ADMIN"], render: () => <AdminPage /> },
{ pattern: "/users", roles: ["ADMIN", "GM"], render: () => <UsersPage /> },
];
function Routes({ role }: { role: Role }) {
const path = useLocation();
for (const route of ROUTES) {
const params = matchPath(route.pattern, path);
if (params && (!route.roles || route.roles.includes(role))) return route.render(params);
}
return <NotFoundPage />;
}
function Gate() {
const { user, loading } = useSession();
if (loading) return <main className="auth auth-center"><Skeleton lines={2} /></main>;
if (!user) return <LoginPage />;
return <AppShell><Routes role={user.role} /></AppShell>;
}
export default function App() {
return (
<SessionProvider>
<ToastProvider>
<Gate />
</ToastProvider>
</SessionProvider>
);
}
+109
View File
@@ -0,0 +1,109 @@
/** Low-level HTTP client: base URL, bearer token, silent refresh, file downloads. */
export const API_BASE = "/api/v1";
interface TokenPair {
access_token: string;
refresh_token: string;
}
let accessToken = localStorage.getItem("access_token");
let refreshToken = localStorage.getItem("refresh_token");
let onSignedOut: (() => void) | null = null;
export const auth = {
get token() {
return accessToken;
},
save(tokens: TokenPair) {
accessToken = tokens.access_token;
refreshToken = tokens.refresh_token;
localStorage.setItem("access_token", accessToken);
localStorage.setItem("refresh_token", refreshToken);
},
clear() {
accessToken = refreshToken = null;
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
},
/** Called when the session can no longer be refreshed, so the UI can return to sign-in. */
onSignedOut(handler: () => void) {
onSignedOut = handler;
},
};
export class ApiError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
}
}
async function refreshSession(): Promise<void> {
const tokens = await request<TokenPair>(
"/auth/refresh",
{ method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) },
false,
);
auth.save(tokens);
}
async function send<T>(path: string, init: RequestInit = {}, retry = true): Promise<T> {
const headers = new Headers(init.headers);
if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
if (init.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
const response = await fetch(`${API_BASE}${path}`, { ...init, headers });
if (response.status === 401 && retry && refreshToken) {
try {
await refreshSession();
return send<T>(path, init, false);
} catch {
auth.clear();
onSignedOut?.();
}
}
if (!response.ok) {
const body = await response.json().catch(() => null);
throw new ApiError(body?.error?.message || `Request failed (${response.status})`, response.status);
}
return response.status === 204 ? (undefined as T) : ((await response.json()) as T);
}
const inFlight = new Map<string, Promise<unknown>>();
/**
* Every API call goes through here. A change (POST/PATCH/PUT/DELETE) identical to one that is
* still on its way — a double click, a second tab of the same click — shares that one request
* instead of sending a duplicate, so it can never be applied twice.
*/
export function request<T>(path: string, init: RequestInit = {}, retry = true): Promise<T> {
const method = (init.method ?? "GET").toUpperCase();
if (method === "GET" || !retry) return send<T>(path, init, retry);
const key = `${method} ${path} ${typeof init.body === "string" ? init.body : ""}`;
const pending = inFlight.get(key);
if (pending) return pending as Promise<T>;
const call = send<T>(path, init, retry).finally(() => inFlight.delete(key));
inFlight.set(key, call);
return call;
}
export const json = (method: string, body?: unknown): RequestInit => ({
method,
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
/** Fetch a protected file and hand it to the browser as a download. */
export async function download(url: string, filename: string): Promise<void> {
const response = await fetch(url, { headers: { 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);
}
+90
View File
@@ -0,0 +1,90 @@
import type {
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
FormApproval, Product, Profile, StatusCounts, StockInventory, User,
} from "../types";
import { API_BASE, auth, download, json, request } from "./client";
export { ApiError, auth } from "./client";
type Payload = Record<string, unknown>;
/** `?a=1&b=2` from the values that are set, or nothing. */
const query = (params: Record<string, string | undefined>) => {
const q = new URLSearchParams(Object.entries(params).filter((e): e is [string, string] => !!e[1]));
return q.size ? `?${q}` : "";
};
export const api = {
// session
async login(email: string, password: string) {
auth.save(await request("/auth/login", json("POST", { email, password })));
return request<User>("/auth/me");
},
me: () => request<User>("/auth/me"),
profile: () => request<Profile>("/users/me/profile"),
// daily call reports
reports: () => request<DcrListItem[]>("/dcr?limit=200"),
counts: () => request<StatusCounts>("/dcr/counts"),
report: (id: string) => request<Dcr>(`/dcr/${id}`),
createReport: (payload: Payload) => request<Dcr>("/dcr", json("POST", payload)),
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
returnReport: (id: string, reason: string) => request<Dcr>(`/dcr/${id}/return`, json("POST", { reason })),
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
approvalHistory: (id: string) => request<Approval[]>(`/audit/dcr/${id}/approval-history`),
downloadReportPdf: (id: string) => download(`${API_BASE}/dcr/${id}/pdf`, `DCR-${id}.pdf`),
// masters and organisation
doctors: () => request<Doctor[]>("/doctors"),
chemists: () => request<Chemist[]>("/chemists"),
headquarters: () => request<Headquarters[]>("/headquarters"),
users: () => request<User[]>("/users"),
areaManagerMappings: () => request<AreaManagerMapping[]>("/headquarters/area-managers"),
setAreaManagerHeadquarters: (areaManagerId: string, headquarters_ids: string[]) =>
request<AreaManagerMapping[]>(`/headquarters/area-managers/${areaManagerId}`, json("PUT", { headquarters_ids })),
products: () => request<Product[]>("/products"),
stockInventory: () => request<StockInventory[]>("/products/stock-inventory"),
createStockItem: (payload: Payload) => request<StockInventory>("/products/stock-inventory", json("POST", payload)),
updateStockItem: (id: number, payload: Payload) => request<StockInventory>(`/products/stock-inventory/${id}`, json("PATCH", payload)),
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)),
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)),
assignAreaManager: (headquartersId: string, area_manager_user_id: string) =>
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)),
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 })),
// 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. */
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)),
updateCsvRow: (table: string, id: string, payload: Record<string, string>) =>
request<CsvRow>(`/csv-data/${table}/rows/${id}`, json("PATCH", payload)),
deleteCsvRow: (table: string, id: string) => request<void>(`/csv-data/${table}/rows/${id}`, json("DELETE")),
formApprovals: () => request<FormApproval[]>("/csv-data/approvals"),
requestFormApproval: (table: string) => request<FormApproval>(`/csv-data/${table}/approval/request`, json("POST")),
approveForm: (table: string, ownerId: string) =>
request<FormApproval>(`/csv-data/${table}/approval/approve${query({ owner_id: ownerId })}`, json("POST")),
formOwners: () => request<FormOwner[]>("/csv-data/owners"),
/** The approval signature on the PDF is decided by the server, not sent from here. */
downloadCsvPdf(table: string, opts: { rowId?: string; ownerId?: string; month?: string } = {}) {
const { rowId, ownerId, month } = opts;
if (rowId) return download(`${API_BASE}/csv-data/${table}/rows/${rowId}/pdf`, `${table}-${rowId}.pdf`);
const suffix = month ? `-${month.toLowerCase()}` : "";
return download(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`, `${table}${suffix}.pdf`);
},
};
@@ -0,0 +1,30 @@
import type { Headquarters } from "../../types";
/** Pick any number of headquarters. `owners` shows who manages each one today. */
export function HeadquartersChecklist({ headquarters, selected, onChange, owners = {}, disabled = false }: {
headquarters: Headquarters[];
selected: ReadonlySet<string>;
onChange: (next: Set<string>) => void;
owners?: Record<string, string>;
disabled?: boolean;
}) {
if (headquarters.length === 0) return <p className="hq-empty">No headquarters yet — create one under Organisation first.</p>;
const toggle = (id: string) => {
const next = new Set(selected);
if (next.has(id)) next.delete(id); else next.add(id);
onChange(next);
};
return (
<div className="hq-check-list" role="group" aria-label="Headquarters">
{headquarters.map((h) => (
<label key={h.id} className={`hq-check${selected.has(h.id) ? " on" : ""}`}>
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
<span className="hq-check-text">
<strong>{h.code}</strong> · {h.name}
{owners[h.id] && <small>Managed by {owners[h.id]}</small>}
</span>
</label>
))}
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { type ReactNode, useEffect, useState } from "react";
import { Sidebar } from "./Sidebar";
import { Topbar } from "./Topbar";
import { titleFor } from "../../lib/navigation";
import { useSession, useUser } from "../../lib/session";
import { useLocation } from "../../lib/router";
import { useAppUpdate } from "../../hooks/useAppUpdate";
const COLLAPSE_KEY = "sidebar-collapsed";
function readCollapsed(): boolean {
try { return localStorage.getItem(COLLAPSE_KEY) === "1"; } catch { return false; }
}
export function AppShell({ children }: { children: ReactNode }) {
const user = useUser();
const { signOut } = useSession();
const path = useLocation();
const [collapsed, setCollapsed] = useState(readCollapsed);
const [mobileOpen, setMobileOpen] = useState(false);
const update = useAppUpdate();
useEffect(() => {
try { localStorage.setItem(COLLAPSE_KEY, collapsed ? "1" : "0"); } catch { /* storage unavailable */ }
}, [collapsed]);
useEffect(() => { document.title = `${titleFor(path)} · Celtic Life Science`; }, [path]);
useEffect(() => { window.scrollTo(0, 0); }, [path]);
return (
<div className={`shell${collapsed ? " shell-collapsed" : ""}`}>
<Sidebar
role={user.role}
path={path}
collapsed={collapsed}
mobileOpen={mobileOpen}
onToggleCollapsed={() => setCollapsed((v) => !v)}
onNavigate={() => setMobileOpen(false)}
/>
{mobileOpen && <div className="scrim" onClick={() => setMobileOpen(false)} />}
<div className="shell-main">
{update.stale && (
<div className="update-bar" role="status">
<span>A new version of the app is available.</span>
<button type="button" onClick={update.reload}>Reload now</button>
</div>
)}
<Topbar user={user} title={titleFor(path)} onMenu={() => setMobileOpen(true)} onSignOut={signOut} />
<main className="content" id="main">{children}</main>
</div>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { Icon } from "../ui/Icon";
import { Link } from "../../lib/router";
import { navigationFor } from "../../lib/navigation";
import type { Role } from "../../types";
const isActive = (to: string, path: string) => (to === "/" ? path === "/" : path === to || path.startsWith(`${to}/`));
export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed, onNavigate }: {
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
onToggleCollapsed: () => void; onNavigate: () => void;
}) {
return (
<aside className={`sidebar${collapsed ? " collapsed" : ""}${mobileOpen ? " open" : ""}`} aria-label="Primary">
<Link to="/" className="sidebar-brand" onClick={onNavigate} aria-label="Celtic Life Science — home">
<img src="/celtic-logo.svg" alt="Celtic Life Science" />
</Link>
<nav className="sidebar-nav">
{navigationFor(role).map((section) => (
<div key={section.title} className="nav-section">
<p className="nav-title">{section.title}</p>
{section.items.map((item) => (
<Link
key={item.to}
to={item.to}
className={`nav-item${isActive(item.to, path) ? " active" : ""}`}
aria-current={isActive(item.to, path) ? "page" : undefined}
title={collapsed ? item.label : undefined}
onClick={onNavigate}
>
<Icon name={item.icon} />
<span>{item.label}</span>
</Link>
))}
</div>
))}
</nav>
<button type="button" className="nav-item collapse-toggle" onClick={onToggleCollapsed} title={collapsed ? "Expand menu" : undefined}>
<Icon name="panel" />
<span>{collapsed ? "Expand menu" : "Collapse menu"}</span>
</button>
</aside>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { useEffect, useRef, useState } from "react";
import { Avatar } from "../ui/Misc";
import { Badge } from "../ui/Badge";
import { Icon } from "../ui/Icon";
import { ROLE_LABEL } from "../../lib/format";
import { Link } from "../../lib/router";
import type { User } from "../../types";
export function Topbar({ user, title, onMenu, onSignOut }: { user: User; title: string; onMenu: () => void; onSignOut: () => void }) {
const [open, setOpen] = useState(false);
const menu = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const close = (e: MouseEvent | KeyboardEvent) => {
if (e instanceof KeyboardEvent ? e.key === "Escape" : !menu.current?.contains(e.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", close);
document.addEventListener("keydown", close);
return () => {
document.removeEventListener("mousedown", close);
document.removeEventListener("keydown", close);
};
}, [open]);
return (
<header className="topbar">
<button type="button" className="icon-btn menu-btn" onClick={onMenu} aria-label="Open navigation"><Icon name="menu" size={20} /></button>
<h1 className="topbar-title">{title}</h1>
<div className="topbar-right">
<Badge tone="brand">{ROLE_LABEL[user.role]}</Badge>
<div className="user-menu" ref={menu}>
<button type="button" className="user-trigger" aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen((v) => !v)}>
<Avatar name={user.full_name} size={28} />
<span className="user-name">{user.full_name}</span>
<Icon name="chevronDown" size={16} />
</button>
{open && (
<div className="menu" role="menu">
<div className="menu-head">
<strong>{user.full_name}</strong>
<span>{user.email}</span>
</div>
<Link to="/profile" role="menuitem" className="menu-item" onClick={() => setOpen(false)}><Icon name="user" size={16} />Profile</Link>
<button type="button" role="menuitem" className="menu-item" onClick={onSignOut}><Icon name="logout" size={16} />Sign out</button>
</div>
)}
</div>
</div>
</header>
);
}
+135
View File
@@ -0,0 +1,135 @@
import { type FormEvent, useState } from "react";
import { Alert } from "../ui/Alert";
import { Button } from "../ui/Button";
import { Field, Input, Select, Textarea } from "../ui/Field";
import { useToast } from "../ui/Toast";
import { api } from "../../api";
import { useAsync } from "../../hooks/useAsync";
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
import { amount, maxLength, required, useValidation } from "../../lib/validation";
import type { Chemist, Dcr, Doctor } from "../../types";
export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void;
}) {
const toast = useToast();
const products = useAsync(api.stockInventory, []);
const [error, setError] = useState<string | null>(null);
const [kind, setKind] = useState<"doctor" | "chemist">("doctor");
const [targetId, setTargetId] = useState("");
const [time, setTime] = useState(nowHHMM);
const [outcome, setOutcome] = useState("MET");
const [conversion, setConversion] = useState("NOT_STARTED");
const [promote, setPromote] = useState("");
const [sample, setSample] = useState("");
const [pob, setPob] = useState("");
const [remarks, setRemarks] = useState("");
const [busy, setBusy] = useState(false);
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
const options = kind === "doctor" ? doctors : chemists;
// Visit times are local; today's report cannot hold a visit later than now.
const isToday = dcr.report_date === todayISO();
const label = kind === "doctor" ? "Doctor" : "Chemist";
const v = useValidation({
target: [required(label)],
time: [required("Visit time"), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
promote: [maxLength(200, "Product promoted")],
sample: [maxLength(200, "Product sample")],
pob: [maxLength(100, "POB"), amount("POB")],
remarks: [maxLength(2000, "Remarks")],
});
const values = () => ({ target: targetId, time, promote, sample, pob, remarks });
const on = (name: string, set: (value: string) => void) => (e: { target: { value: string } }) => { set(e.target.value); v.retouch(name, e.target.value); };
const blur = (name: string) => (e: { target: { value: string } }) => v.touch(name, e.target.value);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check(values(), e.currentTarget)) return;
setBusy(true);
setError(null);
try {
const updated = kind === "doctor"
? await api.addDoctorCall(dcr.id, {
doctor_id: targetId, visit_time: time, call_outcome: outcome,
conversion_status: selectedDoctor?.is_core_doctor ? conversion : null,
product_promote: promote.trim() || null, product_sample: sample.trim() || null, remarks: remarks.trim() || null,
})
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, pob: pob.trim() || null, remarks: remarks.trim() || null });
onChange(updated);
toast.success(`${label} visit added`);
setTargetId(""); setPromote(""); setSample(""); setPob(""); setRemarks("");
v.clear();
} catch (err) {
setError(errorMessage(err, "Could not add the visit")); // shown right here, where the MR is looking
} finally {
setBusy(false);
}
}
return (
<form 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(); }}>
<option value="doctor">Doctor</option>
<option value="chemist">Chemist</option>
</Select>
</Field>
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? `No ${kind}s are assigned to you yet — ask your administrator to assign some.` : undefined}>
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
<option value="">Choose an assigned {kind}</option>
{options.map((o) => (
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
))}
</Select>
</Field>
<Field label="Visit time" required error={v.errors.time}>
<Input type="time" value={time} max={isToday ? nowHHMM() : undefined} onChange={on("time", setTime)} onBlur={blur("time")} />
</Field>
{kind === "doctor" && (
<Field label="Outcome">
<Select value={outcome} onChange={(e) => setOutcome(e.target.value)}>
<option value="MET">Met</option>
<option value="NOT_AVAILABLE">Not available</option>
<option value="RESCHEDULED">Rescheduled</option>
</Select>
</Field>
)}
{selectedDoctor?.is_core_doctor && (
<Field label="Core doctor status">
<Select value={conversion} onChange={(e) => setConversion(e.target.value)}>
<option value="NOT_STARTED">Not started</option>
<option value="IN_PROGRESS">In progress</option>
<option value="CONVERTED">Converted</option>
<option value="LOST">Lost</option>
</Select>
</Field>
)}
{kind === "doctor" ? (
<>
<Field label="Product promoted" error={v.errors.promote}>
<Input list="product-suggestions" value={promote} onChange={on("promote", setPromote)} onBlur={blur("promote")} placeholder="Pick or type a product" />
</Field>
<Field label="Product sample" error={v.errors.sample}>
<Input list="product-suggestions" value={sample} onChange={on("sample", setSample)} onBlur={blur("sample")} placeholder="Sample given, if any" />
</Field>
<datalist id="product-suggestions">
{(products.data ?? []).map((p) => <option key={p.id} value={p.product_name} />)}
</datalist>
</>
) : (
<Field label="POB (order booked)" error={v.errors.pob} hint="Amount, e.g. 12500 or 12,500.50">
<Input inputMode="decimal" value={pob} onChange={on("pob", setPob)} onBlur={blur("pob")} placeholder="0" />
</Field>
)}
<Field label="Remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} />
</Field>
<div className="form-actions">
<Button type="submit" variant="primary" icon="plus" loading={busy}>Add {kind} visit</Button>
</div>
</form>
);
}
@@ -0,0 +1,22 @@
import { EmptyState } from "../ui/States";
import { formatDateTime } from "../../lib/format";
import type { Approval } from "../../types";
export function ApprovalTimeline({ items }: { items: Approval[] }) {
if (items.length === 0) return <EmptyState icon="clock" title="No activity yet" description="Workflow actions will appear here." />;
return (
<ol className="timeline">
{items.map((item, i) => (
<li key={`${item.at}-${i}`}>
<span className="timeline-dot" />
<div>
<p className="timeline-action">{item.action.replaceAll("_", " ")}</p>
<p className="timeline-meta">{item.actor_name} · {item.actor_role}</p>
<time className="timeline-meta">{formatDateTime(item.at)}</time>
{item.comment && <p className="timeline-note">{item.comment}</p>}
</div>
</li>
))}
</ol>
);
}
@@ -0,0 +1,28 @@
import { DataTable, type Column } from "../ui/DataTable";
import { EmptyState } from "../ui/States";
import { StatusBadge } from "./StatusBadge";
import { formatDate } from "../../lib/format";
import { navigate } from "../../lib/router";
import type { DcrListItem } from "../../types";
const COLUMNS: Column<DcrListItem>[] = [
{ key: "date", header: "Report date", render: (r) => <strong>{formatDate(r.report_date)}</strong>, nowrap: true },
{ key: "mr", header: "Medical Representative", render: (r) => r.mr_name },
{ key: "hq", header: "Headquarters", render: (r) => r.headquarters_name },
{ key: "calls", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists`, nowrap: true },
{ key: "status", header: "Status", render: (r) => <StatusBadge status={r.status} /> },
];
export function ReportTable({ rows, loading, emptyText = "No reports yet" }: { rows: DcrListItem[]; loading?: boolean; emptyText?: string }) {
return (
<DataTable
columns={COLUMNS}
rows={rows}
loading={loading}
rowKey={(r) => r.id}
onRowClick={(r) => navigate(`/reports/${r.id}`)}
minWidth={720}
empty={<EmptyState icon="file" title={emptyText} />}
/>
);
}
@@ -0,0 +1,44 @@
import { useState } from "react";
import { Button } from "../ui/Button";
import { Card, CardBody, CardHeader } from "../ui/Card";
import { Field, Textarea } from "../ui/Field";
import { maxLength, minLength, required } from "../../lib/validation";
import type { Dcr, Role } from "../../types";
export type ReviewAction = "return" | "approve";
/** Decision box for the manager whose turn it is. Renders nothing for anyone else. */
export function ReviewPanel({ dcr, role, busy, onDecide }: {
dcr: Dcr; role: Role; busy: boolean; onDecide: (action: ReviewAction, comment: string) => Promise<boolean>;
}) {
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";
if (!canDecide) return null;
const check = (action: ReviewAction, text: string): string | null =>
maxLength(2000, "Comment")(text)
?? (action === "return" ? required("A reason")(text) ?? minLength(10, "The reason")(text) : null);
const decide = async (action: ReviewAction) => {
const message = check(action, comment);
setProblem(message);
if (message) return;
if (await onDecide(action, comment.trim())) setComment("");
};
return (
<Card>
<CardHeader title="Review decision" description="Your note is saved to the approval history." />
<CardBody>
<Field label="Comment" error={problem} hint="Required (10+ characters) when returning a report.">
<Textarea value={comment} onChange={(e) => { setComment(e.target.value); if (problem) setProblem(null); }} rows={3} placeholder="Add a clear review note" />
</Field>
<div className="button-row">
<Button variant="danger" disabled={busy} onClick={() => void decide("return")}>Return for correction</Button>
<Button variant="primary" icon="check" loading={busy} onClick={() => void decide("approve")}>Approve and lock</Button>
</div>
</CardBody>
</Card>
);
}
@@ -0,0 +1,14 @@
import { Badge, type Tone } from "../ui/Badge";
import { STATUS_LABEL } from "../../lib/format";
import type { DcrStatus } from "../../types";
const TONE: Record<DcrStatus, Tone> = {
DRAFT: "neutral",
PENDING_AM: "warning",
RETURNED: "danger",
APPROVED: "success",
};
export function StatusBadge({ status }: { status: DcrStatus }) {
return <Badge tone={TONE[status]} dot>{STATUS_LABEL[status]}</Badge>;
}
+37
View File
@@ -0,0 +1,37 @@
import { Badge } from "../ui/Badge";
import { Button } from "../ui/Button";
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 }
export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boolean; onRemove: (callId: string) => void }) {
const visits: Visit[] = [
...dcr.doctor_calls.map((c) => ({
id: c.id, kind: "Doctor" as const, name: c.doctor_name, time: c.visit_time, core: c.is_core_doctor,
detail: [humanize(c.call_outcome.toLowerCase()), c.conversion_status && humanize(c.conversion_status.toLowerCase()), c.product_promote && `Promote: ${c.product_promote}`, c.product_sample && `Sample: ${c.product_sample}`, c.remarks].filter(Boolean).join(" · "),
})),
...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(" · "),
})),
].sort((a, b) => a.time.localeCompare(b.time));
if (visits.length === 0) {
return <EmptyState icon="stethoscope" title="No visits recorded" description={editable ? "Add doctor and chemist visits above." : undefined} />;
}
return (
<ul className="visit-list">
{visits.map((v) => (
<li key={v.id}>
<span className="visit-time">{v.time.slice(0, 5)}</span>
<div className="visit-main">
<p><strong>{v.name}</strong> <Badge tone={v.kind === "Doctor" ? "brand" : "neutral"}>{v.kind}</Badge>{v.core && <> <Badge tone="warning">Core</Badge></>}</p>
{v.detail && <p className="visit-detail">{v.detail}</p>}
</div>
{editable && <Button size="sm" variant="ghost" icon="trash" onClick={() => onRemove(v.id)} aria-label={`Remove visit with ${v.name}`}>Remove</Button>}
</li>
))}
</ul>
);
}
@@ -0,0 +1,23 @@
import { Icon } from "../ui/Icon";
import type { DcrStatus } from "../../types";
const STEPS = ["Draft", "Area Manager", "Approved"] as const;
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_AM: 1, APPROVED: 2 };
/** Where a report is in DRAFT → AM → APPROVED. A returned report sits back at step one. */
export function WorkflowTracker({ status }: { status: DcrStatus }) {
const current = INDEX[status];
return (
<ol className="steps" aria-label="Approval progress">
{STEPS.map((label, i) => {
const state = status === "APPROVED" || i < current ? "done" : i === current ? (status === "RETURNED" ? "returned" : "current") : "todo";
return (
<li key={label} className={`step step-${state}`} aria-current={state === "current" ? "step" : undefined}>
<span className="step-dot">{state === "done" ? <Icon name="check" size={13} /> : i + 1}</span>
<span className="step-label">{label}</span>
</li>
);
})}
</ol>
);
}
+15
View File
@@ -0,0 +1,15 @@
import type { ReactNode } from "react";
import { Icon } from "./Icon";
export function Alert({ tone = "danger", title, children }: { tone?: "danger" | "success" | "warning" | "info"; title?: string; children?: ReactNode }) {
if (!children && !title) return null;
return (
<div className={`alert alert-${tone}`} role={tone === "danger" ? "alert" : "status"}>
<Icon name={tone === "success" ? "checkCircle" : tone === "info" ? "info" : "alert"} size={18} />
<div>
{title && <strong>{title}</strong>}
{children && <p>{children}</p>}
</div>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import type { ReactNode } from "react";
export type Tone = "neutral" | "brand" | "success" | "warning" | "danger";
export function Badge({ tone = "neutral", dot = false, children }: { tone?: Tone; dot?: boolean; children: ReactNode }) {
return (
<span className={`badge badge-${tone}`}>
{dot && <i className="badge-dot" />}
{children}
</span>
);
}
+27
View File
@@ -0,0 +1,27 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { Icon, type IconName } from "./Icon";
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "primary" | "secondary" | "ghost" | "danger";
size?: "sm" | "md";
icon?: IconName;
loading?: boolean;
children?: ReactNode;
}
export function Button({
variant = "secondary", size = "md", icon, loading = false, children, className = "", disabled, type = "button", ...rest
}: ButtonProps) {
return (
<button
type={type}
className={`btn btn-${variant} btn-${size} ${className}`.trim()}
disabled={disabled || loading}
aria-busy={loading || undefined}
{...rest}
>
{loading ? <span className="spinner" aria-hidden="true" /> : icon && <Icon name={icon} size={16} />}
{children}
</button>
);
}
+21
View File
@@ -0,0 +1,21 @@
import type { ReactNode } from "react";
export function Card({ children, className = "" }: { children: ReactNode; className?: string }) {
return <section className={`card ${className}`.trim()}>{children}</section>;
}
export function CardHeader({ title, description, actions }: { title: ReactNode; description?: ReactNode; actions?: ReactNode }) {
return (
<header className="card-header">
<div>
<h2 className="card-title">{title}</h2>
{description && <p className="card-desc">{description}</p>}
</div>
{actions && <div className="card-actions">{actions}</div>}
</header>
);
}
export function CardBody({ children, flush = false, className = "" }: { children: ReactNode; flush?: boolean; className?: string }) {
return <div className={`card-body${flush ? " flush" : ""} ${className}`.trim()}>{children}</div>;
}
+51
View File
@@ -0,0 +1,51 @@
import type { ReactNode } from "react";
export interface Column<T> {
key: string;
header: string;
render: (row: T) => ReactNode;
align?: "left" | "right" | "center";
width?: string;
nowrap?: boolean;
/** Pin the column to the right edge while the table scrolls horizontally. */
sticky?: boolean;
}
export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, onRowClick, minWidth }: {
columns: Column<T>[]; rows: T[]; rowKey: (row: T) => string; loading?: boolean;
empty?: ReactNode; onRowClick?: (row: T) => void; minWidth?: number;
}) {
return (
<div className="table-scroll">
<table className="table" style={minWidth ? { minWidth } : undefined}>
<thead>
<tr>
{columns.map((c) => (
<th key={c.key} style={{ width: c.width, textAlign: c.align }} className={c.sticky ? "col-sticky" : undefined}>{c.header}</th>
))}
</tr>
</thead>
<tbody>
{loading
? Array.from({ length: 4 }, (_, i) => (
<tr key={i} aria-hidden="true">
{columns.map((c) => <td key={c.key}><span className="skeleton" /></td>)}
</tr>
))
: rows.map((row) => (
<tr
key={rowKey(row)}
className={onRowClick ? "clickable" : undefined}
onClick={onRowClick ? () => onRowClick(row) : undefined}
>
{columns.map((c) => (
<td key={c.key} style={{ textAlign: c.align }} className={[c.nowrap && "nowrap", c.sticky && "col-sticky"].filter(Boolean).join(" ") || undefined}>{c.render(row)}</td>
))}
</tr>
))}
</tbody>
</table>
{!loading && rows.length === 0 && empty}
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
import { createContext, forwardRef, useContext, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes, type TextareaHTMLAttributes } from "react";
/** Errors for the fields of an uncontrolled form, keyed by input `name` (see AdminForm). */
export const FormErrors = createContext<Record<string, string>>({});
export function Field({ label, hint, error, name, required = false, span, group = false, children }: {
label: string; hint?: string; error?: string | null; name?: string; required?: boolean; span?: boolean; group?: boolean; children: ReactNode;
}) {
const fromForm = useContext(FormErrors);
const message = error ?? (name ? fromForm[name] : undefined);
const className = `field${span ? " field-span" : ""}${message ? " field-invalid" : ""}`;
const body = (
<>
<span className="field-label">{label}{required && <span className="field-req" aria-hidden="true"> *</span>}</span>
{children}
{message
? <span className="field-error" role="alert">{message}</span>
: hint && <span className="field-hint">{hint}</span>}
</>
);
// A group of controls (checklist) must not sit inside a <label>, or clicks go to the first control.
return group ? <div className={className} role="group" aria-label={label}>{body}</div> : <label className={className}>{body}</label>;
}
export const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(function Input(
{ className = "", ...rest }, ref,
) {
return <input ref={ref} className={`input ${className}`.trim()} {...rest} />;
});
export const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElement>>(function Select(
{ className = "", ...rest }, ref,
) {
return <select ref={ref} className={`input select ${className}`.trim()} {...rest} />;
});
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>(function Textarea(
{ className = "", ...rest }, ref,
) {
return <textarea ref={ref} className={`input textarea ${className}`.trim()} {...rest} />;
});
export function Checkbox({ label, ...rest }: { label: string } & InputHTMLAttributes<HTMLInputElement>) {
return (
<label className="checkbox">
<input type="checkbox" {...rest} />
<span>{label}</span>
</label>
);
}
+56
View File
@@ -0,0 +1,56 @@
import type { SVGProps } from "react";
const PATHS = {
dashboard: "M3 3h7v9H3z M14 3h7v5h-7z M14 12h7v9h-7z M3 16h7v5H3z",
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",
table: "M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M3 10h18 M3 15h18 M9 3v18",
users: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2 M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M22 21v-2a4 4 0 0 0-3-3.87 M16 3.13a4 4 0 0 1 0 7.75",
user: "M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2 M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z",
settings: "M4 21v-7 M4 10V3 M12 21v-9 M12 8V3 M20 21v-5 M20 12V3 M1 14h6 M9 8h6 M17 16h6",
logout: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4 M16 17l5-5-5-5 M21 12H9",
chevronDown: "M6 9l6 6 6-6",
chevronRight: "M9 6l6 6-6 6",
chevronLeft: "M15 18l-6-6 6-6",
plus: "M12 5v14 M5 12h14",
download: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4 M7 10l5 5 5-5 M12 15V3",
search: "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z M21 21l-4.3-4.3",
menu: "M3 6h18 M3 12h18 M3 18h18",
x: "M18 6L6 18 M6 6l12 12",
check: "M20 6L9 17l-5-5",
checkCircle: "M22 11.08V12a10 10 0 1 1-5.93-9.14 M22 4L12 14.01l-3-3",
alert: "M10.3 3.9L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z M12 9v4 M12 17h.01",
info: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 16v-4 M12 8h.01",
refresh: "M21 12a9 9 0 1 1-3-6.7L21 8 M21 3v5h-5",
panel: "M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z M9 3v18",
arrowRight: "M5 12h14 M12 5l7 7-7 7",
arrowLeft: "M19 12H5 M12 19l-7-7 7-7",
edit: "M12 20h9 M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z",
trash: "M3 6h18 M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2 M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6",
clock: "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z M12 6v6l4 2",
send: "M22 2L11 13 M22 2l-7 20-4-9-9-4z",
inbox: "M22 12h-6l-2 3h-4l-2-3H2 M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",
} as const;
export type IconName = keyof typeof PATHS;
export function Icon({ name, size = 18, ...rest }: { name: IconName; size?: number } & SVGProps<SVGSVGElement>) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={1.75}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
{...rest}
>
<path d={PATHS[name]} />
</svg>
);
}
+41
View File
@@ -0,0 +1,41 @@
import type { ReactNode } from "react";
import { initials } from "../../lib/format";
import { Icon } from "./Icon";
export function Avatar({ name, size = 30 }: { name: string; size?: number }) {
return <span className="avatar" style={{ width: size, height: size, fontSize: size * 0.38 }}>{initials(name)}</span>;
}
export function SearchInput({ value, onChange, placeholder = "Search" }: { value: string; onChange: (v: string) => void; placeholder?: string }) {
return (
<label className="search">
<Icon name="search" size={16} />
<input type="search" value={value} placeholder={placeholder} aria-label={placeholder} onChange={(e) => onChange(e.target.value)} />
</label>
);
}
export function Stat({ label, value, tone = "neutral", hint, onClick, selected = false }: { label: string; value: ReactNode; tone?: "neutral" | "warning" | "danger" | "success"; hint?: string; onClick?: () => void; selected?: boolean }) {
const body = (
<>
<span className="stat-label"><i className={`stat-dot stat-${tone}`} />{label}</span>
<strong className="stat-value">{value}</strong>
{hint && <span className="stat-hint">{hint}</span>}
</>
);
if (!onClick) return <div className="stat">{body}</div>;
return <button type="button" className={`stat stat-button${selected ? " selected" : ""}`} aria-pressed={selected} onClick={onClick}>{body}</button>;
}
export function KeyValue({ items }: { items: { label: string; value: ReactNode }[] }) {
return (
<dl className="kv">
{items.map((item) => (
<div key={item.label}>
<dt>{item.label}</dt>
<dd>{item.value || "—"}</dd>
</div>
))}
</dl>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { type ReactNode, useEffect, useRef } from "react";
import { Icon } from "./Icon";
/** Accessible dialog. `variant="drawer"` slides in from the right for longer forms. */
export function Modal({ open, title, description, onClose, children, footer, variant = "dialog" }: {
open: boolean; title: string; description?: string; onClose: () => void;
children: ReactNode; footer?: ReactNode; variant?: "dialog" | "drawer";
}) {
const panel = useRef<HTMLDivElement>(null);
// A fresh onClose on every parent render must not re-run the effect below, or focus
// would jump back to the first field while the user is typing.
const closeRef = useRef(onClose);
closeRef.current = onClose;
useEffect(() => {
if (!open) return;
const previous = document.activeElement as HTMLElement | null;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && closeRef.current();
document.addEventListener("keydown", onKey);
document.body.style.overflow = "hidden";
panel.current?.querySelector<HTMLElement>("input:not([readonly]), select, textarea, button:not(.modal-close)")?.focus();
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = "";
previous?.focus();
};
}, [open]);
if (!open) return null;
return (
<div className={`overlay overlay-${variant}`} onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className={`modal modal-${variant}`} role="dialog" aria-modal="true" aria-label={title} ref={panel}>
<header className="modal-header">
<div>
<h2>{title}</h2>
{description && <p>{description}</p>}
</div>
<button type="button" className="icon-btn modal-close" onClick={onClose} aria-label="Close"><Icon name="x" /></button>
</header>
<div className="modal-body">{children}</div>
{footer && <footer className="modal-footer">{footer}</footer>}
</div>
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import type { ReactNode } from "react";
import { Icon } from "./Icon";
import { Link } from "../../lib/router";
export function PageHeader({ title, description, actions, back }: {
title: ReactNode; description?: ReactNode; actions?: ReactNode; back?: { to: string; label: string };
}) {
return (
<div className="page-header">
<div>
{back && (
<Link to={back.to} className="back-link"><Icon name="arrowLeft" size={15} />{back.label}</Link>
)}
<h1>{title}</h1>
{description && <p className="page-desc">{description}</p>}
</div>
{actions && <div className="page-actions">{actions}</div>}
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { ReactNode } from "react";
import { Button } from "./Button";
import { Icon, type IconName } from "./Icon";
export function EmptyState({ icon = "inbox", title, description, action }: { icon?: IconName; title: string; description?: string; action?: ReactNode }) {
return (
<div className="state">
<span className="state-icon"><Icon name={icon} size={22} /></span>
<h3>{title}</h3>
{description && <p>{description}</p>}
{action}
</div>
);
}
export function ErrorState({ message, onRetry }: { message: string; onRetry?: () => void }) {
return (
<div className="state">
<span className="state-icon state-icon-danger"><Icon name="alert" size={22} /></span>
<h3>This didn’t load</h3>
<p>{message}</p>
{onRetry && <Button icon="refresh" onClick={onRetry}>Try again</Button>}
</div>
);
}
export function Skeleton({ lines = 3 }: { lines?: number }) {
return (
<div className="skeleton-block" aria-busy="true" aria-label="Loading">
{Array.from({ length: lines }, (_, i) => <span key={i} className="skeleton" style={{ width: `${92 - i * 14}%` }} />)}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
export interface TabItem<K extends string> { key: K; label: string; count?: number }
export function Tabs<K extends string>({ items, value, onChange, label }: {
items: TabItem<K>[]; value: K; onChange: (key: K) => void; label: string;
}) {
return (
<div className="tabs" role="tablist" aria-label={label}>
{items.map((item) => (
<button
key={item.key}
role="tab"
type="button"
aria-selected={item.key === value}
className={`tab${item.key === value ? " active" : ""}`}
onClick={() => onChange(item.key)}
>
{item.label}
{item.count !== undefined && <span className="tab-count">{item.count}</span>}
</button>
))}
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from "react";
import { Icon } from "./Icon";
type ToastTone = "success" | "danger";
interface ToastItem { id: number; tone: ToastTone; message: string }
interface ToastApi { success: (message: string) => void; error: (message: string) => void }
const ToastContext = createContext<ToastApi | null>(null);
let counter = 0;
export function ToastProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<ToastItem[]>([]);
const push = useCallback((tone: ToastTone, message: string) => {
const id = ++counter;
setItems((prev) => [...prev, { id, tone, message }]);
setTimeout(() => setItems((prev) => prev.filter((t) => t.id !== id)), tone === "danger" ? 7000 : 4000);
}, []);
const api = useMemo<ToastApi>(() => ({ success: (m) => push("success", m), error: (m) => push("danger", m) }), [push]);
return (
<ToastContext.Provider value={api}>
{children}
<div className="toasts" aria-live="polite">
{items.map((t) => (
<div key={t.id} className={`toast toast-${t.tone}`}>
<Icon name={t.tone === "success" ? "checkCircle" : "alert"} size={18} />
<span>{t.message}</span>
<button type="button" className="icon-btn" aria-label="Dismiss" onClick={() => setItems((p) => p.filter((x) => x.id !== t.id))}>
<Icon name="x" size={14} />
</button>
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast(): ToastApi {
const ctx = useContext(ToastContext);
if (!ctx) throw new Error("useToast must be used inside ToastProvider");
return ctx;
}
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useState } from "react";
const CHECK_EVERY_MS = 60_000;
/** The build file this page was loaded with, e.g. "/assets/index-Cv0GnyPV.js". */
const runningBuild = () => document.querySelector<HTMLScriptElement>('script[type="module"][src*="/assets/"]')?.getAttribute("src") ?? "";
async function publishedBuild(): Promise<string> {
const response = await fetch("/", { cache: "no-store" });
if (!response.ok) return "";
return /<script[^>]+src="([^"]*\/assets\/[^"]+\.js)"/.exec(await response.text())?.[1] ?? "";
}
/**
* Notices when a newer version of the app has been deployed while this tab stayed open, so nobody
* keeps running old code (an old tab would, for example, ignore server-side features).
* `stale` turns true; the next page change reloads by itself, which is a safe moment.
*/
export function useAppUpdate(): { stale: boolean; reload: () => void } {
const [stale, setStale] = useState(false);
useEffect(() => {
const running = runningBuild();
if (!running) return; // dev server or unexpected markup: nothing to compare
let cancelled = false;
const check = async () => {
try {
const latest = await publishedBuild();
if (!cancelled && latest && latest !== running) setStale(true);
} catch { /* offline or mid-deploy: try again next time */ }
};
const onVisible = () => { if (document.visibilityState === "visible") void check(); };
const timer = window.setInterval(() => void check(), CHECK_EVERY_MS);
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("focus", onVisible);
void check();
return () => {
cancelled = true;
window.clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("focus", onVisible);
};
}, []);
useEffect(() => {
if (!stale) return;
// Moving to another screen is a natural break: nothing half-typed is lost.
const onNavigate = () => window.location.reload();
window.addEventListener("hashchange", onNavigate);
return () => window.removeEventListener("hashchange", onNavigate);
}, [stale]);
return { stale, reload: () => window.location.reload() };
}
+97
View File
@@ -0,0 +1,97 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { errorMessage } from "../lib/format";
export interface AsyncState<T> {
data: T | null;
error: string | null;
/** True only while there is nothing to show yet (first load, or the inputs changed). */
loading: boolean;
/** Fetch again now. Keeps the current data on screen and swaps it in place. */
reload: () => Promise<void>;
setData: (value: T) => void;
}
export interface AsyncOptions {
/** Re-fetch every N ms while the tab is visible (0 or omitted: off). May be a function, read on each tick. */
poll?: number | (() => number);
}
/** Default live-update cadence for lists other people can change. */
export const LIVE = 5_000;
/**
* Run an async loader on mount and whenever `deps` change; ignores stale responses.
*
* Refreshes (`reload`, polling, returning to the tab) are silent: the screen keeps its data,
* gets no skeleton flash, and is only re-rendered when the server's answer actually differs.
*/
export function useAsync<T>(loader: () => Promise<T>, deps: unknown[] = [], options: AsyncOptions = {}): AsyncState<T> {
const [data, setDataState] = useState<T | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const ticket = useRef(0);
const current = useRef<T | null>(null);
const loaderRef = useRef(loader);
const pollRef = useRef(options.poll);
loaderRef.current = loader;
pollRef.current = options.poll;
const commit = useCallback((value: T | null) => {
// Same answer as before: keep the old object so nothing downstream re-renders or resets.
if (value !== null && current.current !== null && JSON.stringify(value) === JSON.stringify(current.current)) return;
current.current = value;
setDataState(value);
}, []);
const run = useCallback(async (silent: boolean) => {
const mine = ++ticket.current;
if (!silent) {
setLoading(true);
setError(null);
}
try {
const result = await loaderRef.current();
if (mine !== ticket.current) return;
commit(result);
setError(null);
} catch (e) {
// A failed background refresh must not wipe a screen the user is looking at.
if (mine === ticket.current && (!silent || current.current === null)) setError(errorMessage(e, "Could not load data"));
} finally {
if (mine === ticket.current) setLoading(false);
}
}, [commit]);
useEffect(() => {
commit(null); // inputs changed: never show the previous inputs' data
void run(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
useEffect(() => {
const revalidate = () => { if (document.visibilityState === "visible") void run(true); };
document.addEventListener("visibilitychange", revalidate);
window.addEventListener("focus", revalidate);
window.addEventListener("online", revalidate);
let timer: number | undefined;
const schedule = () => {
const every = typeof pollRef.current === "function" ? pollRef.current() : pollRef.current ?? 0;
timer = window.setTimeout(() => {
if (every > 0 && document.visibilityState === "visible") void run(true);
schedule();
}, every > 0 ? every : 5_000);
};
schedule();
return () => {
document.removeEventListener("visibilitychange", revalidate);
window.removeEventListener("focus", revalidate);
window.removeEventListener("online", revalidate);
window.clearTimeout(timer);
};
}, [run]);
const reload = useCallback(() => run(true), [run]);
// An answer we already know is newer than any request still on its way — drop those.
const setData = useCallback((value: T) => { ticket.current++; commit(value); }, [commit]);
return { data, error, loading, reload, setData };
}
+56
View File
@@ -0,0 +1,56 @@
import type { DcrStatus, Role } from "../types";
export const STATUS_LABEL: Record<DcrStatus, string> = {
DRAFT: "Draft",
PENDING_AM: "With Area Manager",
RETURNED: "Returned",
APPROVED: "Approved",
};
export const ROLE_LABEL: Record<Role, string> = {
MR: "Medical Representative",
AM: "Area Manager",
GM: "General Manager",
ADMIN: "Administrator",
};
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
export const todayISO = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
/** The current local time as HH:MM, for time inputs. */
export const nowHHMM = () => {
const d = new Date();
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
};
export function formatDate(value: string | null | undefined): string {
if (!value) return "—";
const date = new Date(value.length === 10 ? `${value}T00:00:00` : value);
return Number.isNaN(date.getTime())
? value
: date.toLocaleDateString(undefined, { day: "2-digit", month: "short", year: "numeric" });
}
export function formatDateTime(value: string | null | undefined): string {
if (!value) return "—";
const date = new Date(value);
return Number.isNaN(date.getTime())
? value
: date.toLocaleString(undefined, { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
}
export const initials = (name: string) =>
name.split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part[0]!.toUpperCase()).join("") || "?";
const ACRONYMS = new Set(["pob", "pts", "km", "kms", "pds", "id"]);
export const humanize = (key: string) =>
key
.split("_")
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
.join(" ");
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
error instanceof Error ? error.message : fallback;
+11
View File
@@ -0,0 +1,11 @@
import type { AreaManagerMapping, Headquarters, User } from "../types";
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
const ids = user.role === "MR"
? (user.headquarters_id ? [user.headquarters_id] : [])
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
const wanted = new Set(ids);
return { all: false, items: hqs.filter((h) => wanted.has(h.id)) };
}
+62
View File
@@ -0,0 +1,62 @@
import type { IconName } from "../components/ui/Icon";
import type { Role } from "../types";
export interface NavItem {
to: string;
label: string;
icon: IconName;
roles?: Role[];
}
export interface NavSection {
title: string;
items: NavItem[];
}
/** Sidebar structure. `roles` limits an item to those roles; omitted means everyone. */
export const NAVIGATION: NavSection[] = [
{
title: "Workspace",
items: [
{ to: "/", label: "Dashboard", icon: "dashboard" },
{ to: "/reports", label: "Daily Call Reports", icon: "file", roles: ["MR", "AM", "GM"] },
],
},
{
title: "Field data",
items: [
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
{ to: "/products", label: "Products", icon: "box" },
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "AM", "ADMIN"] },
],
},
{
title: "Administration",
items: [
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN"] },
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
],
},
];
export function navigationFor(role: Role): NavSection[] {
return NAVIGATION.map((section) => ({
...section,
items: section.items.filter((item) => !item.roles || item.roles.includes(role)),
})).filter((section) => section.items.length > 0);
}
/** Title shown in the top bar for the current path. */
export function titleFor(path: string): string {
if (path === "/") return "Dashboard";
if (path === "/reports/new") return "New report";
if (path.startsWith("/reports/")) return "Report";
if (path.startsWith("/reports")) return "Daily Call Reports";
if (path.startsWith("/forms")) return "Company forms";
if (path.startsWith("/directory")) return "Doctors & Chemists";
if (path.startsWith("/products")) return "Products";
if (path.startsWith("/admin")) return "Setup";
if (path.startsWith("/users")) return "Users";
if (path.startsWith("/profile")) return "Profile";
return "Not found";
}
+38
View File
@@ -0,0 +1,38 @@
import { type AnchorHTMLAttributes, useEffect, useState } from "react";
/**
* Minimal hash router. Hash URLs work behind any static file server (no server-side
* fallback needed), give every screen a shareable address and keep the back button working.
*/
const read = () => (window.location.hash.replace(/^#/, "").split("?")[0] || "/").replace(/\/+$/, "") || "/";
export function useLocation(): string {
const [path, setPath] = useState(read);
useEffect(() => {
const update = () => setPath(read());
window.addEventListener("hashchange", update);
return () => window.removeEventListener("hashchange", update);
}, []);
return path;
}
export function navigate(to: string): void {
if (read() !== to) window.location.hash = to;
}
/** Match "/reports/:id" against "/reports/42" → { id: "42" }, or null. */
export function matchPath(pattern: string, path: string): Record<string, string> | null {
const want = pattern.split("/").filter(Boolean);
const have = path.split("/").filter(Boolean);
if (want.length !== have.length) return null;
const params: Record<string, string> = {};
for (let i = 0; i < want.length; i++) {
if (want[i].startsWith(":")) params[want[i].slice(1)] = decodeURIComponent(have[i]);
else if (want[i] !== have[i]) return null;
}
return params;
}
export function Link({ to, ...rest }: { to: string } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">) {
return <a href={`#${to}`} {...rest} />;
}
+54
View File
@@ -0,0 +1,54 @@
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { api, auth } from "../api";
import type { User } from "../types";
interface Session {
user: User | null;
loading: boolean;
signIn: (email: string, password: string) => Promise<void>;
signOut: () => void;
}
const SessionContext = createContext<Session | null>(null);
export function SessionProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(Boolean(auth.token));
const signOut = useCallback(() => {
auth.clear();
setUser(null);
window.location.hash = "/";
}, []);
useEffect(() => {
auth.onSignedOut(() => setUser(null));
if (!auth.token) return;
api
.me()
.then(setUser)
.catch(() => auth.clear())
.finally(() => setLoading(false));
}, []);
const signIn = useCallback(async (email: string, password: string) => {
setUser(await api.login(email, password));
window.location.hash = "/";
}, []);
const value = useMemo(() => ({ user, loading, signIn, signOut }), [user, loading, signIn, signOut]);
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}
export function useSession(): Session {
const ctx = useContext(SessionContext);
if (!ctx) throw new Error("useSession must be used inside SessionProvider");
return ctx;
}
/** The signed-in user; only call below the authentication gate. */
export function useUser(): User {
const { user } = useSession();
if (!user) throw new Error("No signed-in user");
return user;
}
+96
View File
@@ -0,0 +1,96 @@
/** Small, dependency-free form validation shared by every form. Each rule returns an error message or null. */
import { useState } from "react";
export type Rule = (value: string) => string | null;
export type Errors = Record<string, string>;
const blank = (v: string) => v.trim() === "";
export const required = (label: string): Rule => (v) => (blank(v) ? `${label} is required` : null);
export const minLength = (n: number, label: string): Rule => (v) => (!blank(v) && v.trim().length < n ? `${label} must be at least ${n} characters` : null);
export const maxLength = (n: number, label: string): Rule => (v) => (v.trim().length > n ? `${label} must be ${n} characters or fewer` : null);
export const pattern = (re: RegExp, message: string): Rule => (v) => (blank(v) || re.test(v.trim()) ? null : message);
export const email: Rule = pattern(/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/, "Enter a valid email address, like name@company.com");
/** 7–15 digits, optionally with a leading + and spaces, dashes or brackets. */
export const phone: Rule = (v) => {
if (blank(v)) return null;
const digits = v.replace(/\D/g, "").length;
return /^\+?[0-9\s()-]+$/.test(v.trim()) && digits >= 7 && digits <= 15 ? null : "Enter a valid phone number (7–15 digits)";
};
export const code = (label: string): Rule => pattern(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/, `${label} may only contain letters, numbers and . _ / -`);
export const password: Rule = (v) => {
if (v === "") return null;
if (v.length < 8) return "Password must be at least 8 characters";
if (v.length > 128) return "Password must be 128 characters or fewer";
return /[A-Za-z]/.test(v) && /\d/.test(v) ? null : "Password needs at least one letter and one number";
};
/** Whole or decimal number, thousands commas allowed ("12,500.50"). */
export const numeric = (label: string): Rule => pattern(/^-?\d[\d,]*(\.\d+)?$/, `${label} must be a number`);
/** An amount of money: optional ₹ / Rs prefix, digits with commas, up to 2 decimals. */
export const amount = (label: string): Rule => pattern(/^(₹|rs\.?)?\s?\d[\d,]*(\.\d{1,2})?$/i, `${label} must be an amount, like 12500 or 12,500.50`);
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
export const isoDate = (label: string): Rule => (v) => {
if (blank(v)) return null;
const valid = ISO_DATE.test(v) && !Number.isNaN(Date.parse(v));
return valid ? null : `${label} must be a valid date`;
};
export const notAfter = (limit: string, label: string, what = "today"): Rule => (v) => (!blank(v) && v > limit ? `${label} cannot be after ${what}` : null);
/** The first failing rule's message, or null. */
export function firstError(value: string, rules: Rule[] = []): string | null {
for (const rule of rules) {
const message = rule(value);
if (message) return message;
}
return null;
}
export function validateValues(values: Record<string, string>, spec: Record<string, Rule[]>): Errors {
const errors: Errors = {};
for (const [name, rules] of Object.entries(spec)) {
const message = firstError(values[name] ?? "", rules);
if (message) errors[name] = message;
}
return errors;
}
/** Move the cursor to the first invalid control once the errors have rendered. */
export function focusFirstError(root: ParentNode | null): void {
requestAnimationFrame(() => {
root?.querySelector<HTMLElement>(".field-invalid input, .field-invalid select, .field-invalid textarea")?.focus();
});
}
/**
* Validation state for a controlled form. `check` validates everything (on submit);
* `touch` validates one field (on blur, and on change once it has shown an error).
*/
export function useValidation(spec: Record<string, Rule[]>) {
const [errors, setErrors] = useState<Errors>({});
return {
errors,
check(values: Record<string, string>, form?: ParentNode | null): boolean {
const found = validateValues(values, spec);
setErrors(found);
const ok = Object.keys(found).length === 0;
if (!ok) focusFirstError(form ?? document);
return ok;
},
touch(name: string, value: string) {
const message = firstError(value, spec[name]);
setErrors((prev) => {
if ((prev[name] ?? null) === message) return prev;
const next = { ...prev };
if (message) next[name] = message; else delete next[name];
return next;
});
},
/** Live re-check while typing, but only for a field that is already showing an error. */
retouch(name: string, value: string) {
if (errors[name]) this.touch(name, value);
},
clear: () => setErrors({}),
};
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles/index.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
+185
View File
@@ -0,0 +1,185 @@
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { Badge } from "../components/ui/Badge";
import { Button } from "../components/ui/Button";
import { Card, CardBody, CardHeader } from "../components/ui/Card";
import { DataTable, type Column } from "../components/ui/DataTable";
import { EmptyState, ErrorState } from "../components/ui/States";
import { PageHeader } from "../components/ui/PageHeader";
import { Stat } from "../components/ui/Misc";
import { ReportTable } from "../components/reports/ReportTable";
import { LIVE, useAsync } from "../hooks/useAsync";
import { api } from "../api";
import { Link, navigate } from "../lib/router";
import { useUser } from "../lib/session";
import { ROLE_LABEL } from "../lib/format";
import { headquartersOf } from "../lib/headquarters";
import type { DcrListItem, Headquarters, Role, User } from "../types";
const WAITING: Record<"MR" | "AM", { 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." },
};
export function DashboardPage() {
const user = useUser();
if (user.role === "ADMIN") return <AdminDashboard />;
return <ReportDashboard role={user.role} name={user.full_name.split(" ")[0]!} />;
}
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
const counts = useAsync(api.counts, [], { poll: LIVE });
const reports = useAsync(api.reports, [], { poll: LIVE });
const isMR = role === "MR";
// A General Manager has no approval step — they get a read-only overview.
const config = role === "GM" ? null : WAITING[role];
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."}
actions={isMR
? <Button variant="primary" icon="plus" onClick={() => navigate("/reports/new")}>New report</Button>
: <Button icon="file" onClick={() => navigate("/reports")}>View all reports</Button>}
/>
<div className="stats">
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
<Stat label="With Area Manager" value={counts.data?.PENDING_AM ?? "–"} tone="warning" />
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
</div>
{config && (
<Card>
<CardHeader title={config.title} description={waiting.length ? `${waiting.length} report${waiting.length === 1 ? "" : "s"} need your attention.` : "Nothing needs your attention right now."} />
<CardBody flush>
{reports.error
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
: waiting.length === 0 && !reports.loading
? <EmptyState icon="checkCircle" title="Queue is clear" description={config.empty} />
: <ReportTable rows={waiting} loading={reports.loading} />}
</CardBody>
</Card>
)}
<Card>
<CardHeader title="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>
</>
);
}
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
function AdminDashboard() {
const users = useAsync(api.users, [], { poll: LIVE });
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
const mappings = useAsync(api.areaManagerMappings, [], { poll: LIVE });
const [view, setView] = useState<AdminView | null>(null);
const panel = useRef<HTMLDivElement>(null);
const list = users.data ?? [];
const activeUsers = useMemo(() => list.filter((u) => u.is_active), [list]);
const byRole = (role: Role) => activeUsers.filter((u) => u.role === role);
useEffect(() => {
if (view) panel.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
}, [view]);
const pick = (next: AdminView) => setView((cur) => (cur === next ? null : next));
const hqColumns: Column<Headquarters>[] = [
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
{ key: "name", header: "Headquarters", render: (h) => h.name },
{ key: "district", header: "District", render: (h) => h.district || "—" },
{ key: "state", header: "State", render: (h) => h.state || "—" },
{ key: "status", header: "Status", render: (h) => statusBadge(h.is_active), nowrap: true },
];
const userColumns = (withRole: boolean, withHq: boolean): Column<User>[] => [
{ key: "name", header: "Name", render: (u) => <strong>{u.full_name}</strong> },
{ key: "code", header: "Code", render: (u) => u.employee_code, nowrap: true },
{ key: "email", header: "Email", render: (u) => u.email },
...(withRole ? [{ key: "role", header: "Role", render: (u: User) => <Badge tone="brand">{ROLE_LABEL[u.role]}</Badge>, nowrap: true }] : []),
...(withHq ? [{ key: "hq", header: "Headquarters", render: (u: User) => {
const place = headquartersOf(u, hqs.data ?? [], mappings.data ?? []);
if (place.all) return <Badge tone="neutral">All headquarters</Badge>;
return place.items.length ? <span className="chips">{place.items.map((h) => <Badge key={h.id} tone="brand">{h.code} · {h.name}</Badge>)}</span> : "—";
} }] : []),
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
];
const detail: Record<AdminView, { title: string; description: string; manage: string; error: string | null; loading: boolean; table: ReactNode }> = {
hq: {
title: "Headquarters", description: "Every headquarters set up for the company.", manage: "/admin",
error: hqs.error, loading: hqs.loading,
table: <DataTable columns={hqColumns} rows={hqs.data ?? []} rowKey={(h) => h.id} loading={hqs.loading} minWidth={560} empty={<EmptyState icon="settings" title="No headquarters yet" description="Create one under Setup → Organisation." />} />,
},
mr: {
title: "Medical Representatives", description: "Active MRs and the headquarters they work in.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description="Add one under Setup → People." />} />,
},
am: {
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description="Add one under Setup → People." />} />,
},
gm: {
title: "General Managers", description: "Active General Managers. They have a read-only view across every headquarters.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description="Add one under Setup → People." />} />,
},
users: {
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
error: users.error, loading: users.loading,
table: <DataTable columns={userColumns(true, false)} rows={activeUsers} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active users" />} />,
},
};
const current = view ? detail[view] : null;
return (
<>
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button>} />
<div className="stats stats-5">
<Stat label="Headquarters" value={hqs.data?.length ?? "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
<Stat label="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="Active users" value={users.data ? activeUsers.length : "–"} tone="success" hint="View details" onClick={() => pick("users")} selected={view === "users"} />
</div>
{current && (
<div ref={panel}>
<Card>
<CardHeader
title={current.title}
description={current.description}
actions={<><Link to={current.manage} className="text-link">Manage →</Link><Button size="sm" variant="ghost" onClick={() => setView(null)}>Close</Button></>}
/>
<CardBody flush>
{current.error ? <ErrorState message={current.error} onRetry={() => { void users.reload(); void hqs.reload(); }} /> : current.table}
</CardBody>
</Card>
</div>
)}
<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 doctors, chemists and products</li>
<li>Assign doctors and chemists to Medical Representatives</li>
</ol>
</CardBody>
</Card>
</>
);
}
+173
View File
@@ -0,0 +1,173 @@
import { type FormEvent, useMemo, useState } from "react";
import { Alert } from "../components/ui/Alert";
import { Badge } from "../components/ui/Badge";
import { Button } from "../components/ui/Button";
import { Card } from "../components/ui/Card";
import { DataTable, type Column } from "../components/ui/DataTable";
import { Checkbox, Field, Input } from "../components/ui/Field";
import { Modal } from "../components/ui/Modal";
import { SearchInput } from "../components/ui/Misc";
import { PageHeader } from "../components/ui/PageHeader";
import { EmptyState, ErrorState } from "../components/ui/States";
import { Tabs } from "../components/ui/Tabs";
import { useToast } from "../components/ui/Toast";
import { LIVE, useAsync } from "../hooks/useAsync";
import { api } from "../api";
import { errorMessage } from "../lib/format";
import { useUser } from "../lib/session";
import { maxLength, minLength, required, useValidation } from "../lib/validation";
import type { Chemist, Doctor } from "../types";
const DOCTOR_COLUMNS: Column<Doctor>[] = [
{ key: "name", header: "Doctor", render: (d) => <strong>{d.name}</strong> },
{ key: "speciality", header: "Speciality", render: (d) => d.speciality || "—" },
{ key: "address", header: "Clinic address", render: (d) => d.clinic_address },
{ key: "core", header: "Type", render: (d) => (d.is_core_doctor ? <Badge tone="warning">Core doctor</Badge> : <Badge>Regular</Badge>), nowrap: true },
{ key: "status", header: "Status", render: (d) => <Badge tone={d.is_active ? "success" : "neutral"} dot>{d.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
];
const CHEMIST_COLUMNS: Column<Chemist>[] = [
{ key: "name", header: "Chemist", render: (c) => <strong>{c.name}</strong> },
{ 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 },
];
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist };
export function DirectoryPage() {
const user = useUser();
const toast = useToast();
const isAdmin = user.role === "ADMIN";
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 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 [query, setQuery] = useState("");
const q = query.trim().toLowerCase();
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => !q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [doctors.data, hqLabel, q]);
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => !q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [chemists.data, hqLabel, q]);
const active = tab === "doctors" ? doctors : chemists;
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();
} catch (err) {
toast.error(errorMessage(err, "Could not change the status"));
} finally {
setToggling(null);
}
}
const editButton = (target: Editing) => (
<>
<Button size="sm" variant="ghost" loading={toggling === target.item.id} onClick={() => void toggleActive(target)}>{target.item.is_active ? "Deactivate" : "Activate"}</Button>
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(target)}>Edit</Button>
</>
);
/** The headquarters each doctor / chemist is assigned to. */
const hqCell = (id: string) => (hqLabel.has(id) ? <Badge tone="brand">{hqLabel.get(id)}</Badge> : <span className="muted">—</span>);
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),
...(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),
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (c: Chemist) => editButton({ kind: "chemist", item: c }) }] : []),
];
return (
<>
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
<Card>
<div className="toolbar">
<Tabs
label="Directory"
value={tab}
onChange={setTab}
items={[{ key: "doctors", label: "Doctors", count: doctors.data?.length }, { key: "chemists", label: "Chemists", count: chemists.data?.length }]}
/>
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
</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" />} />
) : (
<DataTable columns={chemistColumns} rows={chemistRows} rowKey={(c) => c.id} loading={chemists.loading} minWidth={640} empty={<EmptyState icon="stethoscope" title="No chemists found" />} />
)}
</Card>
{editing && (
<DirectoryEditor
editing={editing}
onClose={() => setEditing(null)}
onSaved={() => {
setEditing(null);
toast.success(`${editing.kind === "doctor" ? "Doctor" : "Chemist"} updated`);
void (editing.kind === "doctor" ? doctors : chemists).reload();
}}
/>
)}
</>
);
}
function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onClose: () => void; onSaved: () => void }) {
const isDoctor = editing.kind === "doctor";
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 [active, setActive] = useState(editing.item.is_active);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
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")],
speciality: [maxLength(100, "Speciality")],
});
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ name, address, speciality }, e.currentTarget)) return;
setBusy(true);
setError(null);
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 });
} else {
await api.updateChemist(editing.item.id, { name: name.trim(), shop_address: address.trim(), is_active: active });
}
onSaved();
} catch (err) {
setError(errorMessage(err, "Could not save the changes"));
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={isDoctor ? "Edit doctor" : "Edit chemist"}
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>
{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 && <Checkbox label="Core doctor" checked={core} onChange={(e) => setCore(e.target.checked)} />}
<Checkbox label="Active" checked={active} onChange={(e) => setActive(e.target.checked)} />
</form>
</Modal>
);
}
+73
View File
@@ -0,0 +1,73 @@
import { type FormEvent, useState } from "react";
import { Alert } from "../components/ui/Alert";
import { Button } from "../components/ui/Button";
import { Field, Input } from "../components/ui/Field";
import { errorMessage } from "../lib/format";
import { useSession } from "../lib/session";
import { email as emailRule, required, useValidation } from "../lib/validation";
export function LoginPage() {
const { signIn } = useSession();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [reveal, setReveal] = useState(false);
const v = useValidation({ email: [required("Email"), emailRule], password: [required("Password")] });
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ email, password }, e.currentTarget)) return;
setBusy(true);
setError(null);
try {
await signIn(email.trim(), password);
} catch (err) {
setError(errorMessage(err, "Sign-in failed"));
setBusy(false);
}
}
return (
<main className="auth">
<section className="auth-panel">
<div className="auth-card">
<img className="auth-logo" src="/celtic-logo.svg" alt="Celtic Life Science" />
<h1>Welcome back</h1>
<p className="page-desc">Sign in to continue to Celtic field-force reporting.</p>
<form className="auth-form" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Email" required error={v.errors.email}>
<Input type="email" value={email} onChange={(e) => { setEmail(e.target.value); v.retouch("email", e.target.value); }} onBlur={(e) => v.touch("email", e.target.value)} autoComplete="username" autoFocus placeholder="you@company.com" />
</Field>
<Field label="Password" required error={v.errors.password}>
<span className="input-affix">
<Input type={reveal ? "text" : "password"} value={password} onChange={(e) => { setPassword(e.target.value); v.retouch("password", e.target.value); }} onBlur={(e) => v.touch("password", e.target.value)} autoComplete="current-password" placeholder="Enter your password" />
<button type="button" className="affix-btn" onClick={() => setReveal((r) => !r)} aria-pressed={reveal} aria-label={reveal ? "Hide password" : "Show password"}>{reveal ? "Hide" : "Show"}</button>
</span>
</Field>
<Button type="submit" variant="primary" loading={busy} className="btn-block">Sign in</Button>
</form>
<p className="auth-help">Trouble signing in? Contact your administrator.</p>
</div>
<p className="auth-copy">© {new Date().getFullYear()} Celtic Life Science Pvt Ltd</p>
</section>
<aside className="auth-aside">
<div className="auth-about">
<h2>Celtic Life Science Pvt. Ltd</h2>
<p>
Celtic Life Science is a growing pharmaceutical company committed to improving global healthcare by delivering high-quality, safe,
and affordable medicinal products. Driven by science, innovation, and ethical practices, we aim to enhance patient well-being and
support healthcare professionals with reliable therapeutic solutions.
</p>
<p>
With a strong focus on quality and compliance, Celtic Life Science offers a diverse portfolio of pharmaceutical formulations across
multiple dosage forms including tablets, capsules, syrups, injectables, nutraceuticals, and speciality medicines. Our products are
developed and manufactured in accordance with international quality standards to ensure consistency, safety, and efficacy.
</p>
</div>
</aside>
</main>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { Button } from "../components/ui/Button";
import { EmptyState } from "../components/ui/States";
import { navigate } from "../lib/router";
export function NotFoundPage() {
return (
<EmptyState
icon="search"
title="Page not found"
description="The page you are looking for does not exist, or you do not have access to it."
action={<Button variant="primary" onClick={() => navigate("/")}>Back to dashboard</Button>}
/>
);
}
+152
View File
@@ -0,0 +1,152 @@
import { type FormEvent, useMemo, useState } from "react";
import { Alert } from "../components/ui/Alert";
import { Button } from "../components/ui/Button";
import { Card } from "../components/ui/Card";
import { DataTable, type Column } from "../components/ui/DataTable";
import { Field, Input } from "../components/ui/Field";
import { Modal } from "../components/ui/Modal";
import { SearchInput } from "../components/ui/Misc";
import { PageHeader } from "../components/ui/PageHeader";
import { EmptyState, ErrorState } from "../components/ui/States";
import { useToast } from "../components/ui/Toast";
import { LIVE, useAsync } from "../hooks/useAsync";
import { api } from "../api";
import { errorMessage } from "../lib/format";
import { useUser } from "../lib/session";
import { maxLength, minLength, required, useValidation } from "../lib/validation";
import type { StockInventory } from "../types";
type Draft = { product_name: string; pack: string; quantity: string; unit: string };
const EMPTY: Draft = { product_name: "", pack: "", quantity: "", unit: "" };
export function ProductsPage() {
const user = useUser();
const toast = useToast();
const isAdmin = user.role === "ADMIN";
const products = useAsync(api.stockInventory, [], { poll: LIVE });
const [query, setQuery] = useState("");
const [editing, setEditing] = useState<{ item: StockInventory | null } | null>(null);
const [deleting, setDeleting] = useState<StockInventory | null>(null);
const columns: Column<StockInventory>[] = [
{ key: "no", header: "No.", render: (p) => p.serial_no, width: "72px" },
{ key: "name", header: "Product", render: (p) => <strong>{p.product_name}</strong> },
{ key: "pack", header: "Pack", render: (p) => p.pack || "—" },
{ key: "qty", header: "Quantity", render: (p) => p.quantity || "—", align: "right" },
{ key: "unit", header: "Unit", render: (p) => p.unit || "—" },
...(isAdmin ? [{
key: "actions", header: "", align: "right" as const, nowrap: true,
render: (p: StockInventory) => (
<span className="row-actions">
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ item: p })}>Edit</Button>
<Button size="sm" variant="ghost" icon="trash" aria-label={`Delete ${p.product_name}`} onClick={() => setDeleting(p)} />
</span>
),
}] : []),
];
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return (products.data ?? []).filter((p) => !q || `${p.product_name} ${p.pack}`.toLowerCase().includes(q));
}, [products.data, query]);
async function confirmDelete() {
if (!deleting) return;
try {
await api.deleteStockItem(deleting.id);
toast.success(`${deleting.product_name} deleted`);
setDeleting(null);
await products.reload();
} catch (e) { toast.error(errorMessage(e, "Could not delete the product")); }
}
return (
<>
<PageHeader
title="Products"
description="Products and stock details from the inventory list."
actions={isAdmin && <Button variant="primary" icon="plus" onClick={() => setEditing({ item: null })}>Add product</Button>}
/>
<Card>
<div className="toolbar toolbar-end">
<SearchInput value={query} onChange={setQuery} placeholder="Search products" />
</div>
{products.error
? <ErrorState message={products.error} onRetry={() => void products.reload()} />
: <DataTable columns={columns} rows={rows} rowKey={(p) => String(p.id)} loading={products.loading} minWidth={isAdmin ? 680 : 560} empty={<EmptyState icon="box" title="No products found" />} />}
</Card>
{editing && (
<ProductEditor
item={editing.item}
onClose={() => setEditing(null)}
onSaved={(message) => { setEditing(null); toast.success(message); void products.reload(); }}
/>
)}
<Modal
open={!!deleting}
title="Delete this product?"
description={deleting ? `${deleting.product_name} will be removed from the inventory list.` : undefined}
onClose={() => setDeleting(null)}
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>Delete product</Button></>}
>
<p className="muted">This cannot be undone.</p>
</Modal>
</>
);
}
function ProductEditor({ item, onClose, onSaved }: { item: StockInventory | null; onClose: () => void; onSaved: (message: string) => void }) {
const [draft, setDraft] = useState<Draft>(item ? {
product_name: item.product_name, pack: item.pack ?? "", quantity: item.quantity ?? "", unit: item.unit ?? "",
} : EMPTY);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const v = useValidation({
product_name: [required("Product name"), minLength(2, "Product name"), maxLength(200, "Product name")],
pack: [maxLength(100, "Pack")], quantity: [maxLength(50, "Quantity")], unit: [maxLength(50, "Unit")],
});
const set = (key: keyof Draft) => (e: { target: { value: string } }) => { setDraft((d) => ({ ...d, [key]: e.target.value })); v.retouch(key, e.target.value); };
const blur = (key: keyof Draft) => (e: { target: { value: string } }) => v.touch(key, e.target.value);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check(draft, e.currentTarget)) return;
setBusy(true);
setError(null);
const payload = {
product_name: draft.product_name.trim(),
pack: draft.pack.trim() || null,
quantity: draft.quantity.trim() || null,
unit: draft.unit.trim() || null,
};
try {
if (item) await api.updateStockItem(item.id, payload);
else await api.createStockItem(payload);
onSaved(item ? "Product updated" : "Product added");
} catch (err) {
setError(errorMessage(err, "Could not save the product"));
} finally {
setBusy(false);
}
}
return (
<Modal
open
title={item ? "Edit product" : "Add product"}
description="Product, pack and stock quantity"
onClose={onClose}
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("product-editor-form") as HTMLFormElement | null)?.requestSubmit()}>{item ? "Save changes" : "Add product"}</Button></>}
>
<form id="product-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Product name" required error={v.errors.product_name}><Input value={draft.product_name} onChange={set("product_name")} onBlur={blur("product_name")} /></Field>
<Field label="Pack" error={v.errors.pack} hint="e.g. 10X10 TAB"><Input value={draft.pack} onChange={set("pack")} onBlur={blur("pack")} /></Field>
<Field label="Quantity" error={v.errors.quantity} hint="e.g. 10+1"><Input value={draft.quantity} onChange={set("quantity")} onBlur={blur("quantity")} /></Field>
<Field label="Unit" error={v.errors.unit}><Input value={draft.unit} onChange={set("unit")} onBlur={blur("unit")} /></Field>
</form>
</Modal>
);
}
+36
View File
@@ -0,0 +1,36 @@
import { Badge } from "../components/ui/Badge";
import { Card, CardBody, CardHeader } from "../components/ui/Card";
import { Avatar, KeyValue } from "../components/ui/Misc";
import { PageHeader } from "../components/ui/PageHeader";
import { ErrorState, Skeleton } from "../components/ui/States";
import { useAsync } from "../hooks/useAsync";
import { api } from "../api";
import { ROLE_LABEL } from "../lib/format";
export function ProfilePage() {
const profile = useAsync(api.profile, []);
const p = profile.data;
return (
<div className="narrow">
<PageHeader title="My profile" description="Your account and territory." />
{profile.error ? <ErrorState message={profile.error} onRetry={() => void profile.reload()} /> : !p ? (
<Card><CardBody><Skeleton lines={5} /></CardBody></Card>
) : (
<Card>
<CardHeader
title={<span className="identity"><Avatar name={p.full_name} size={44} /><span>{p.full_name}<small>{p.email}</small></span></span>}
actions={<Badge tone="brand">{ROLE_LABEL[p.role]}</Badge>}
/>
<CardBody>
<KeyValue items={[
{ 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" },
]} />
</CardBody>
</Card>
)}
</div>
);
}
+308
View File
@@ -0,0 +1,308 @@
import { type FormEvent, type ReactNode, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { Checkbox, Field, FormErrors, Input, Select } from "../../components/ui/Field";
import { PageHeader } from "../../components/ui/PageHeader";
import { Tabs } from "../../components/ui/Tabs";
import { useToast } from "../../components/ui/Toast";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
import { DataTable, type Column } from "../../components/ui/DataTable";
import { Badge } from "../../components/ui/Badge";
import type { AreaManagerMapping, Headquarters, User } from "../../types";
import { errorMessage } from "../../lib/format";
import { code as codeRule, email as emailRule, focusFirstError, maxLength, minLength, password as passwordRule, phone as phoneRule, required, validateValues, type Errors, type Rule } from "../../lib/validation";
/** Turns a form's FormData into plain strings for the validators. */
const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
/**
* A titled card with a form; handles validation, busy state, error text, success toast and reset.
* `rules` maps an input `name` to its rules — or is a function of the current values, for rules
* that depend on other fields. Errors show under the matching <Field name="…"> as you leave a
* field, and all of them on submit.
*/
function AdminForm({ title, description, submitLabel, onSubmit, rules, children }: {
title: string; description?: string; submitLabel: string;
onSubmit: (data: FormData) => Promise<unknown>; children: ReactNode;
rules?: Record<string, Rule[]> | ((values: Record<string, string>) => Record<string, Rule[]>);
}) {
const toast = useToast();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [errors, setErrors] = useState<Errors>({});
const validate = (form: HTMLFormElement): Errors => {
if (!rules) return {};
const values = valuesOf(new FormData(form));
return validateValues(values, typeof rules === "function" ? rules(values) : rules);
};
// Re-check just the field being edited, so one bad field never lights up the others early.
const recheck = (form: HTMLFormElement, target: EventTarget) => {
const name = (target as HTMLInputElement).name;
if (!name) return;
const found = validate(form);
setErrors((prev) => {
if ((prev[name] ?? null) === (found[name] ?? null)) return prev;
const next = { ...prev };
if (found[name]) next[name] = found[name]; else delete next[name];
return next;
});
};
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = e.currentTarget;
const found = validate(form);
setErrors(found);
if (Object.keys(found).length > 0) { focusFirstError(form); return; }
setBusy(true);
setError(null);
try {
await onSubmit(new FormData(form));
form.reset();
setErrors({});
toast.success(`${title} — saved`);
} catch (err) {
setError(errorMessage(err, "Could not save"));
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader title={title} description={description} />
<CardBody>
<form className="form-grid" onSubmit={submit} noValidate
onBlur={(e) => recheck(e.currentTarget, e.target)}
onChange={(e) => { if (errors[(e.target as HTMLInputElement).name]) recheck(e.currentTarget, e.target); }}>
<Alert>{error}</Alert>
<FormErrors.Provider value={errors}>{children}</FormErrors.Provider>
<div className="form-actions"><Button type="submit" variant="primary" loading={busy}>{submitLabel}</Button></div>
</form>
</CardBody>
</Card>
);
}
// Field rules, shared so the same rule is worded the same everywhere.
const nameRule = (label: string) => [required(label), minLength(2, label), maxLength(200, label)];
const addressRule = (label: string) => [required(label), minLength(2, label), maxLength(500, label)];
const text = (f: FormData, key: string) => String(f.get(key) ?? "");
const optional = (f: FormData, key: string) => text(f, key) || null;
type Section = "organisation" | "people" | "masters" | "assignments";
export function AdminPage() {
const [section, setSection] = useState<Section>("organisation");
const data = useAsync(async () => {
const [hqs, users, doctors, chemists, mappings] = await Promise.all([api.headquarters(), api.users(), api.doctors(), api.chemists(), api.areaManagerMappings()]);
return { hqs, users, doctors, chemists, mappings };
}, [], { poll: LIVE });
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
const mrs = users.filter((u) => u.role === "MR");
const ams = users.filter((u) => u.role === "AM");
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
const hqOptions = hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>);
return (
<>
<PageHeader title="Setup" description="Create organisation data in this order: headquarters, users, Area Manager mapping, master data, then assignments." />
<Alert tone="danger">{data.error}</Alert>
<Tabs
label="Setup sections"
value={section}
onChange={setSection}
items={[
{ key: "organisation", label: "1 · Organisation" }, { key: "people", label: "2 · People" },
{ key: "masters", label: "3 · Master data" }, { key: "assignments", label: "4 · Assignments" },
]}
/>
{section === "organisation" && (
<div className="grid-2">
<AdminForm title="Create headquarters" submitLabel="Create headquarters"
rules={{ code: [required("Code"), maxLength(20, "Code"), codeRule("Code")], name: nameRule("Name"), district: [maxLength(100, "District")], state: [maxLength(100, "State")] }}
onSubmit={(f) => refresh(api.createHeadquarters({ code: text(f, "code"), name: text(f, "name"), district: optional(f, "district"), state: optional(f, "state") }))}>
<Field label="Code" name="code" required hint="Short and unique, e.g. BBSR"><Input name="code" placeholder="BBSR" /></Field>
<Field label="Name" name="name" required><Input name="name" placeholder="Bhubaneswar" /></Field>
<Field label="District" name="district"><Input name="district" /></Field>
<Field label="State" name="state"><Input name="state" /></Field>
</AdminForm>
<AreaManagerForm ams={ams} hqs={hqs} mappings={mappings} users={users} onSaved={() => data.reload()} />
</div>
)}
{section === "organisation" && <HeadquartersOverview hqs={hqs} users={users} mappings={mappings} loading={data.loading} />}
{section === "people" && (
<PeopleForm hqs={hqs} refresh={refresh} />
)}
{section === "masters" && (
<div className="grid-2">
<AdminForm title="Create doctor" submitLabel="Create doctor"
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Clinic address"), speciality: [maxLength(100, "Speciality")], phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createDoctor({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), clinic_address: text(f, "address"), speciality: optional(f, "speciality"), qualification: null, contact_number: optional(f, "phone"), is_core_doctor: f.get("core") === "on" }))}>
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Clinic address" name="address" required span><Input name="address" /></Field>
<Field label="Speciality" name="speciality"><Input name="speciality" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
<Checkbox name="core" label="Core doctor" />
</AdminForm>
<AdminForm title="Create chemist" submitLabel="Create chemist"
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Shop address"), phone: [phoneRule] }}
onSubmit={(f) => refresh(api.createChemist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), shop_address: text(f, "address"), contact_number: optional(f, "phone") }))}>
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
<Field label="Name" name="name" required><Input name="name" /></Field>
<Field label="Shop address" name="address" required span><Input name="address" /></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
</AdminForm>
<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") }))}>
<Field label="Product name" name="name" required span><Input name="name" /></Field>
<Field label="Pack" name="pack"><Input name="pack" placeholder="e.g. 10x10 tablets" /></Field>
<Field label="Unit" name="unit"><Input name="unit" placeholder="e.g. Strip" /></Field>
</AdminForm>
</div>
)}
{section === "assignments" && (
<div className="grid-2">
<AdminForm title="Assign doctor to MR" submitLabel="Assign doctor"
rules={{ doctor_id: [required("Doctor")], mr_user_id: [required("Medical Representative")] }}
onSubmit={(f) => refresh(api.assignDoctor(text(f, "doctor_id"), text(f, "mr_user_id")))}>
<Field label="Doctor" name="doctor_id" required><Select name="doctor_id"><option value="">Choose doctor</option>{doctors.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}</Select></Field>
<Field label="Medical Representative" name="mr_user_id" required><Select name="mr_user_id"><option value="">Choose MR</option>{mrs.map((u) => <option key={u.id} value={u.id}>{u.full_name}</option>)}</Select></Field>
</AdminForm>
<AdminForm title="Assign chemist to MR" submitLabel="Assign chemist"
rules={{ chemist_id: [required("Chemist")], mr_user_id: [required("Medical Representative")] }}
onSubmit={(f) => refresh(api.assignChemist(text(f, "chemist_id"), text(f, "mr_user_id")))}>
<Field label="Chemist" name="chemist_id" required><Select name="chemist_id"><option value="">Choose chemist</option>{chemists.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}</Select></Field>
<Field label="Medical Representative" name="mr_user_id" required><Select name="mr_user_id"><option value="">Choose MR</option>{mrs.map((u) => <option key={u.id} value={u.id}>{u.full_name}</option>)}</Select></Field>
</AdminForm>
</div>
)}
</>
);
}
/** Owner name per headquarters, from the current Area Manager mappings. */
function ownersOf(mappings: AreaManagerMapping[], users: User[]): Record<string, string> {
const name = new Map(users.map((u) => [u.id, u.full_name]));
return Object.fromEntries(mappings.map((m) => [m.headquarters_id, name.get(m.area_manager_user_id) ?? "an Area Manager"]));
}
/** Choose an Area Manager, then tick every headquarters they should manage. */
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
const [amId, setAmId] = useState("");
const [picked, setPicked] = useState<Set<string>>(new Set());
const owners = ownersOf(mappings, users);
function choose(id: string) {
setAmId(id);
setPicked(new Set(mappings.filter((m) => m.area_manager_user_id === id).map((m) => m.headquarters_id)));
}
return (
<AdminForm
title="Assign headquarters to an Area Manager"
description="An Area Manager can manage any number of headquarters. A headquarters has one Area Manager, so ticking one that is managed by someone else moves it."
submitLabel="Save assignments"
rules={{ area_manager_user_id: [required("Area 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>
<Select name="area_manager_user_id" value={amId} onChange={(e) => choose(e.target.value)}>
<option value="">Choose Area 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."}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} disabled={!amId} />
</Field>
</AdminForm>
);
}
/** Every headquarters and who manages it — visible at a glance. */
function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquarters[]; users: User[]; mappings: AreaManagerMapping[]; loading: boolean }) {
const owners = ownersOf(mappings, users);
const mrCount = (id: string) => users.filter((u) => u.role === "MR" && u.is_active && u.headquarters_id === id).length;
const columns: Column<Headquarters>[] = [
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
{ key: "name", header: "Headquarters", render: (h) => h.name },
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
{ key: "am", header: "Area Manager", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
{ key: "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." />
<CardBody flush>
<DataTable columns={columns} rows={hqs} rowKey={(h) => h.id} loading={loading} minWidth={560} />
</CardBody>
</Card>
);
}
const ROLES = [
{ value: "MR", label: "Medical Representative" }, { value: "AM", label: "Area Manager" },
{ value: "GM", label: "General Manager" }, { 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. */
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());
return (
<AdminForm
title="Create user" submitLabel="Create user"
rules={{
full_name: nameRule("Full name"),
employee_code: [required("Employee code"), maxLength(50, "Employee code"), codeRule("Employee code")],
email: [required("Email"), emailRule],
password: [required("Password"), passwordRule],
phone: [phoneRule],
...(role === "MR" ? { headquarters_id: [required("Headquarters")] } : {}),
}}
onSubmit={async (f) => {
const created = await api.createUser({
email: text(f, "email"), password: text(f, "password"), full_name: text(f, "full_name"),
employee_code: text(f, "employee_code"), phone: optional(f, "phone"), role,
headquarters_id: role === "MR" ? text(f, "headquarters_id") : null,
});
if (role === "AM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
setRole("MR"); setPicked(new Set());
await refresh(Promise.resolve(created));
}}
>
<Field label="Full name" name="full_name" required><Input name="full_name" /></Field>
<Field label="Employee code" name="employee_code" required><Input name="employee_code" /></Field>
<Field label="Email" name="email" required><Input type="email" name="email" autoComplete="off" /></Field>
<Field label="Password" name="password" required hint="At least 8 characters, with a letter and a number."><Input type="password" name="password" autoComplete="new-password" /></Field>
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
{role === "MR" && (
<Field label="Headquarters" name="headquarters_id" required hint="The headquarters this Medical Representative works in.">
<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 === "AM" && (
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
</Field>
)}
{(role === "GM" || role === "ADMIN") && (
<p className="field-hint field-span">General Managers and Administrators see every headquarters, so none is assigned.</p>
)}
</AdminForm>
);
}
+181
View File
@@ -0,0 +1,181 @@
import { type FormEvent, useMemo, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Field, Input } from "../../components/ui/Field";
import { Modal } from "../../components/ui/Modal";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
import { Card } from "../../components/ui/Card";
import { DataTable, type Column } from "../../components/ui/DataTable";
import { SearchInput } from "../../components/ui/Misc";
import { PageHeader } from "../../components/ui/PageHeader";
import { EmptyState, ErrorState } from "../../components/ui/States";
import { useToast } from "../../components/ui/Toast";
import { useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { LIVE } from "../../hooks/useAsync";
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
import { headquartersOf } from "../../lib/headquarters";
import { code as codeRule, email as emailRule, maxLength, minLength, password as passwordRule, phone as phoneRule, required, useValidation } from "../../lib/validation";
import { ROLE_LABEL, errorMessage } from "../../lib/format";
import { useUser } from "../../lib/session";
import type { AreaManagerMapping, Headquarters, User } from "../../types";
export function UsersPage() {
const me = useUser();
const toast = useToast();
const org = useAsync(async () => {
const [users, hqs, mappings] = await Promise.all([api.users(), api.headquarters(), api.areaManagerMappings()]);
return { users, hqs, mappings };
}, [], { poll: LIVE });
const users = { ...org, data: org.data?.users };
const hqs = org.data?.hqs ?? [];
const mappings = org.data?.mappings ?? [];
const [query, setQuery] = useState("");
const canManage = me.role === "ADMIN";
const [editing, setEditing] = useState<User | null>(null);
async function toggle(u: User) {
try {
await api.updateUser(u.id, { is_active: !u.is_active });
toast.success(`${u.full_name} is now ${u.is_active ? "inactive" : "active"}`);
await users.reload();
} catch (e) { toast.error(errorMessage(e, "Could not update the user")); }
}
const columns: Column<User>[] = [
{ key: "name", header: "Name", render: (u) => <strong>{u.full_name}</strong> },
{ key: "email", header: "Email", render: (u) => u.email },
{ key: "code", header: "Code", render: (u) => u.employee_code, nowrap: true },
{ key: "role", header: "Role", render: (u) => <Badge tone="brand">{ROLE_LABEL[u.role]}</Badge>, nowrap: true },
{ key: "hq", header: "Headquarters", render: (u) => <HqChips user={u} hqs={hqs} mappings={mappings} /> },
{ key: "status", header: "Status", render: (u) => <Badge tone={u.is_active ? "success" : "neutral"} dot>{u.is_active ? "Active" : "Inactive"}</Badge> },
...(canManage ? [{ key: "action", header: "", align: "right" as const, nowrap: true, render: (u: User) => (
<span className="row-actions">
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(u)}>Edit</Button>
<Button size="sm" onClick={() => void toggle(u)} disabled={u.id === me.id}>{u.is_active ? "Deactivate" : "Activate"}</Button>
</span>
) }] : []),
];
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return (users.data ?? []).filter((u) => {
if (!q) return true;
const place = headquartersOf(u, hqs, mappings);
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
return `${u.full_name} ${u.email} ${u.employee_code} ${u.role} ${where}`.toLowerCase().includes(q);
});
}, [users.data, hqs, mappings, query]);
return (
<>
<PageHeader title="Users" description={canManage ? "Manage who can sign in and what they can do." : "View active and inactive users."} />
<Card>
<div className="toolbar toolbar-end"><SearchInput value={query} onChange={setQuery} placeholder="Search users" /></div>
{users.error
? <ErrorState message={users.error} onRetry={() => void users.reload()} />
: <DataTable columns={columns} rows={rows} rowKey={(u) => u.id} loading={users.loading} minWidth={860} empty={<EmptyState icon="users" title="No users found" />} />}
</Card>
{editing && <UserEditor user={editing} hqs={hqs} mappings={mappings} users={users.data ?? []} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); toast.success("User updated"); void users.reload(); }} />}
</>
);
}
/** Headquarters of one person: chips for an MR or AM, "All headquarters" for GM 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>;
return <span className="chips">{place.items.map((h) => <Badge key={h.id} tone="brand">{h.code}</Badge>)}</span>;
}
function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: User; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onClose: () => void; onSaved: () => void }) {
const me = useUser();
const [name, setName] = useState(user.full_name);
const [email, setEmail] = useState(user.email);
const [code, setCode] = useState(user.employee_code);
const [phone, setPhone] = useState(user.phone ?? "");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const isAm = user.role === "AM";
const editingSelf = user.id === me.id;
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
const [picked, setPicked] = useState<Set<string>>(() => new Set(mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id)));
const names = new Map(users.map((u) => [u.id, u.full_name]));
const owners = Object.fromEntries(mappings.filter((m) => m.area_manager_user_id !== user.id).map((m) => [m.headquarters_id, names.get(m.area_manager_user_id) ?? "another Area Manager"]));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const v = useValidation({
name: [required("Full name"), minLength(2, "Full name"), maxLength(200, "Full name")],
email: [required("Email"), emailRule],
code: [required("Employee code"), maxLength(50, "Employee code"), codeRule("Employee code")],
phone: [phoneRule],
password: [passwordRule],
});
const bind = (key: string, set: (value: string) => void) => ({
onChange: (e: { target: { value: string } }) => { set(e.target.value); v.retouch(key, e.target.value); },
onBlur: (e: { target: { value: string } }) => v.touch(key, e.target.value),
});
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ name, email, code, phone, password }, e.currentTarget)) return;
setBusy(true);
setError(null);
try {
const payload: Record<string, unknown> = { full_name: name.trim() };
if (email.trim().toLowerCase() !== user.email) payload.email = email.trim();
if (code.trim() !== user.employee_code) payload.employee_code = code.trim();
if (phone.trim() !== (user.phone ?? "")) payload.phone = phone.trim() || null;
if (password) payload.password = password;
await api.updateUser(user.id, payload);
if (isAm) await api.setAreaManagerHeadquarters(user.id, [...picked]);
onSaved();
} catch (err) {
setError(errorMessage(err, "Could not update the user"));
} finally {
setBusy(false);
}
}
return (
<Modal
open
title="Edit user"
description={user.email}
onClose={onClose}
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("user-editor-form") as HTMLFormElement | null)?.requestSubmit()}>Save changes</Button></>}
>
<form id="user-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Full name" required error={v.errors.name}><Input value={name} {...bind("name", setName)} /></Field>
<Field label="Email (sign-in)" required error={v.errors.email}><Input type="email" value={email} autoComplete="off" {...bind("email", setEmail)} /></Field>
<Field label="Employee code" required error={v.errors.code}><Input value={code} {...bind("code", setCode)} /></Field>
<Field label="Phone" error={v.errors.phone}><Input value={phone} inputMode="tel" {...bind("phone", setPhone)} /></Field>
<Field label="New password" error={v.errors.password} hint="Leave empty to keep the current password. At least 8 characters, with a letter and a number.">
<span className="input-row">
<Input type={showPassword ? "text" : "password"} value={password} autoComplete="new-password" placeholder="Unchanged" {...bind("password", setPassword)} />
<Button size="sm" onClick={() => setShowPassword((v) => !v)}>{showPassword ? "Hide" : "Show"}</Button>
<Button size="sm" onClick={() => { setPassword(generatePassword()); setShowPassword(true); }}>Generate</Button>
</span>
</Field>
{credentialsChanged && (
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
)}
{isAm && (
<Field label="Headquarters they manage" group hint={`${picked.size} selected. Ticking one managed by someone else moves it here.`}>
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
</Field>
)}
{(user.role === "GM" || user.role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
</form>
</Modal>
);
}
/** A random 14-character password: letters and digits (no look-alikes) plus a symbol and digit so it always passes. */
function generatePassword(): string {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
const bytes = crypto.getRandomValues(new Uint32Array(12));
return Array.from(bytes, (n) => chars[n % chars.length]).join("") + "!7";
}
+252
View File
@@ -0,0 +1,252 @@
import { useMemo, useState } from "react";
import { Badge } from "../../components/ui/Badge";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { DataTable, type Column } from "../../components/ui/DataTable";
import { Select } from "../../components/ui/Field";
import { Modal } from "../../components/ui/Modal";
import { PageHeader } from "../../components/ui/PageHeader";
import { EmptyState, ErrorState, Skeleton } from "../../components/ui/States";
import { useToast } from "../../components/ui/Toast";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { errorMessage, formatDate, humanize } from "../../lib/format";
import { Link } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { CsvRow, CsvTable, FormApproval } from "../../types";
import { APPROVAL_FORMS, APPROVAL_POLL_MS } from "./approval";
import { RowEditor } from "./RowEditor";
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
const DATES = new Set(["report_date", "date_of_visit"]);
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const sameMonth = (a: unknown, b: string) => String(a ?? "").trim().toLowerCase() === b.trim().toLowerCase();
/** The number shown for a row: its place in that MR's own form. */
const numberOf = (r: CsvRow) => String(r.serial_no ?? r.source_row_number);
export function FormsPage({ table: routeTable }: { table?: string }) {
const user = useUser();
const toast = useToast();
const tables = useAsync(api.csvTables, [], { poll: LIVE });
const profile = useAsync(() => api.profile().catch(() => null), []);
const list = tables.data ?? [];
const table: CsvTable | undefined = list.find((t) => t.name === routeTable) ?? list[0];
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
const isManager = user.role === "AM" || user.role === "ADMIN";
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
const owners = useAsync(() => (isManager && needsApproval ? api.formOwners() : Promise.resolve([])), [isManager, needsApproval], { poll: LIVE });
const [ownerChoice, setOwnerChoice] = useState("");
const [monthChoice, setMonthChoice] = useState<Record<string, string>>({});
const pendingFor = (tableName: string, ownerId: string) => approvals.data?.some((a) => a.table_name === tableName && a.owner_user_id === ownerId && a.status === "pending") ?? false;
const ownerList = owners.data ?? [];
const viewOwner = useMemo(() => {
if (!isManager || !needsApproval || !table) return undefined;
const chosen = ownerList.find((o) => o.id === ownerChoice);
if (chosen) return chosen;
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, user.role, approvals.data]);
const waitingForOwners = isManager && needsApproval && !owners.data;
const rows = useAsync<CsvRow[]>(
() => (table && !waitingForOwners ? api.csvRows(table.name, viewOwner?.id) : Promise.resolve([])),
[table?.name, viewOwner?.id, waitingForOwners], { poll: LIVE },
);
const [acting, setActing] = useState(false);
const [editing, setEditing] = useState<{ row: CsvRow | null } | null>(null);
const [deleting, setDeleting] = useState<CsvRow | null>(null);
const canEdit = user.role === "MR" || user.role === "ADMIN";
// An admin adds rows on behalf of one chosen MR.
const canAdd = canEdit && (!needsApproval || user.role === "MR" || !!viewOwner);
const subjectId = user.role === "MR" ? user.id : viewOwner?.id;
const approval = table && subjectId ? approvals.data?.find((a) => a.table_name === table.name && a.owner_user_id === subjectId) : undefined;
const hasRows = (rows.data?.length ?? 0) > 0;
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
// Only the controls that make sense right now: nothing to approve means nothing to show.
const canSend = needsApproval && user.role === "MR" && status === "draft" && hasRows;
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
const showStatus = needsApproval && (status === "pending" || status === "approved");
// Forms with a month can be downloaded one month at a time.
const hasMonth = !!table?.columns.includes("month");
const months = useMemo(() => {
if (!hasMonth) return [] as string[];
const seen = new Map<string, string>();
for (const r of rows.data ?? []) { const m = String(r.month ?? "").trim(); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
const rank = (m: string) => { const i = MONTHS.findIndex((x) => sameMonth(x, m)); return i < 0 ? 99 : i; };
return [...seen.values()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
}, [hasMonth, rows.data]);
const thisMonth = MONTHS[new Date().getMonth()]!;
const chosenMonth = table ? monthChoice[table.name] : undefined;
// Starts on the current month when the form has rows for it, otherwise on everything.
const month = chosenMonth !== undefined ? (chosenMonth === "" || months.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : months.find((m) => sameMonth(m, thisMonth)) ?? "";
const shownRows = month ? (rows.data ?? []).filter((r) => sameMonth(r.month, month)) : rows.data ?? [];
const showToolbar = hasMonth ? months.length > 0 : isManager && needsApproval;
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
async function act(kind: "request" | "approve") {
if (!table || acting) return;
const name = table.name;
const before = approvals.data ?? [];
const ownerId = user.role === "MR" ? user.id : viewOwner?.id;
if (!ownerId) return;
const base = { table_name: name, owner_user_id: ownerId, owner_name: viewOwner?.name ?? user.full_name, headquarters_name: viewOwner?.headquarters_name ?? null, updated_at: null };
const next: FormApproval = kind === "request"
? { ...base, status: "pending", approved_by_name: null }
: { ...base, status: "approved", approved_by_name: user.full_name };
const same = (a: FormApproval) => a.table_name === name && a.owner_user_id === ownerId;
const merge = (list: FormApproval[], item: FormApproval) => (list.some(same) ? list.map((a) => (same(a) ? item : a)) : [...list, item]);
setActing(true);
approvals.setData(merge(before, next));
try {
const saved = await (kind === "request" ? api.requestFormApproval(name) : api.approveForm(name, ownerId));
approvals.setData(merge(before, saved));
toast.success(kind === "request" ? "Sent to the Area Manager for approval" : "Form approved");
} catch (e) {
approvals.setData(before);
toast.error(errorMessage(e, kind === "request" ? "Could not send the form for approval" : "Could not approve the form"));
void approvals.reload();
} finally {
setActing(false);
}
}
const run = (task: Promise<unknown>) => task.catch((e) => toast.error(errorMessage(e, "Download failed")));
async function confirmDelete() {
if (!table || !deleting) return;
try {
await api.deleteCsvRow(table.name, deleting.id);
toast.success("Row deleted");
setDeleting(null);
await Promise.all([rows.reload(), approvals.reload()]);
} catch (e) { toast.error(errorMessage(e, "Could not delete the row")); }
}
const columns: Column<CsvRow>[] = table ? [
{ key: "_no", header: "No.", render: numberOf, width: "64px" },
...table.columns
.filter((c) => !SERIAL.has(c) && !(user.role !== "ADMIN" && IDENTITY.has(c)))
.map<Column<CsvRow>>((c) => ({
key: c,
header: humanize(c),
nowrap: true,
render: (r) => {
const value = String(r[c] ?? "");
return value ? (DATES.has(c) ? formatDate(value) : value) : <span className="muted">—</span>;
},
})),
{
key: "_actions", header: "", align: "right", nowrap: true, sticky: true,
render: (r) => (
<span className="row-actions">
{canEdit && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
<Button size="sm" variant="ghost" icon="download" onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
{canEdit && <Button size="sm" variant="ghost" icon="trash" onClick={() => setDeleting(r)} aria-label="Delete row" />}
</span>
),
},
] : [];
if (tables.error) return <ErrorState message={tables.error} onRetry={() => void tables.reload()} />;
return (
<>
<PageHeader title="Company forms" description="Fill in the company’s standard forms and print them as ready-to-sign PDFs." />
<div className="forms-layout">
<nav className="form-nav" aria-label="Forms">
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
<Link key={t.name} to={`/forms/${t.name}`} className={`form-nav-item${t.name === table?.name ? " active" : ""}`} aria-current={t.name === table?.name ? "page" : undefined}>
{t.label}
{user.role === "AM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
</Link>
))}
</nav>
<Card>
{!table ? <CardBody><EmptyState icon="table" title="No forms available" /></CardBody> : (
<>
<CardHeader
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Manager"}` : "Pending AM approval"}</Badge>}</span>}
description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`}
actions={
<>
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
<Button icon="download" disabled={!hasRows} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</Button>
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
</>
}
/>
{showToolbar && (
<div className="toolbar">
{isManager && needsApproval && (
<label className="filter">
<span>Medical representative</span>
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
{user.role === "ADMIN" && <option value="">All medical representatives</option>}
{ownerList.map((o) => <option key={o.id} value={o.id}>{o.name}{o.headquarters_name ? ` · ${o.headquarters_name}` : ""}{pendingFor(table.name, o.id) ? " — needs approval" : ""}</option>)}
</Select>
</label>
)}
{hasMonth && months.length > 0 && (
<label className="filter">
<span>Month</span>
<Select value={month} onChange={(e) => setMonthChoice((m) => ({ ...m, [table.name]: e.target.value }))} aria-label="Month">
<option value="">All months</option>
{months.map((m) => <option key={m} value={m}>{m}</option>)}
</Select>
</label>
)}
</div>
)}
{rows.error ? <ErrorState message={rows.error} onRetry={() => void rows.reload()} /> : (
<DataTable
columns={columns}
rows={shownRows}
rowKey={(r) => r.id}
loading={rows.loading || waitingForOwners}
minWidth={Math.max(640, columns.length * 115)}
empty={month
? <EmptyState icon="table" title={`No rows for ${month}`} description="Choose another month, or All months." />
: isManager && needsApproval && ownerList.length === 0
? <EmptyState icon="users" title="No medical representatives" description={user.role === "AM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
: <EmptyState icon="table" title="No rows yet" description={canAdd ? "Add a row to start filling in this form." : isManager && needsApproval ? "This medical representative has not filled in this form." : undefined} action={canAdd ? <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button> : undefined} />}
/>
)}
</>
)}
</Card>
</div>
{table && editing && (
<RowEditor
open
table={table}
row={editing.row}
rows={rows.data ?? []}
user={user}
profile={profile.data}
owner={viewOwner}
onClose={() => setEditing(null)}
onSaved={(message) => { setEditing(null); toast.success(message); void rows.reload(); void approvals.reload(); }}
/>
)}
<Modal
open={!!deleting}
title="Delete this row?"
description="This cannot be undone."
onClose={() => setDeleting(null)}
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>Delete row</Button></>}
>
<p className="prose">Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.</p>
</Modal>
</>
);
}
+131
View File
@@ -0,0 +1,131 @@
import { type FormEvent, useEffect, useMemo, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Button } from "../../components/ui/Button";
import { Field, Input, Select } from "../../components/ui/Field";
import { Modal } from "../../components/ui/Modal";
import { api } from "../../api";
import { errorMessage, humanize } from "../../lib/format";
import { isoDate, maxLength, numeric, required, useValidation, type Rule } from "../../lib/validation";
import type { CsvRow, CsvTable, FormOwner, Profile, User } from "../../types";
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
const DATES = new Set(["date", "report_date", "date_of_visit"]);
/** Columns that hold quantities or money — must be numbers (commas and decimals allowed). */
const NUMERIC = new Set([
"pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2", "opening", "receipt", "sale", "value_in_pts",
"kilometers_km", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "no_of_doctors_called", "no_of_chemists_pds_called",
"pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "doctor_call_avg", "chemist_call_avg", "pob",
]);
const LONG_TEXT = new Set(["remarks", "area_to_cover", "product_offer_scheme_booked", "product_offer_scheme_objective"]);
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
export function RowEditor({ open, table, row, rows, user, profile, owner, onClose, onSaved }: {
open: boolean; table: CsvTable; row: CsvRow | null; rows: CsvRow[]; user: User; profile: Profile | null;
/** The MR an admin is filling the form in for. */
owner?: FormOwner;
onClose: () => void; onSaved: (message: string) => void;
}) {
const columns = useMemo(() => table.columns.filter((c) => !SERIAL.has(c)), [table]);
const isAdmin = user.role === "ADMIN";
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin);
// 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;
return c === "headquarter" ? profile?.headquarters_name ?? "" : profile?.full_name ?? user.full_name;
};
const products = useMemo(
() => (table.name === "sales_projection" ? rows.map((r) => ({ name: String(r.product_name || ""), pts: String(r.pts || "") })).filter((p) => p.name) : []),
[table.name, rows],
);
const [draft, setDraft] = useState<Record<string, string>>({});
const rulesFor = (c: string): Rule[] => {
const label = humanize(c);
if (table.name === "sales_projection" && c === "product_name") return [required("Product name"), maxLength(200, label)];
if (DATES.has(c)) return [isoDate(label)];
if (NUMERIC.has(c)) return [maxLength(30, label), numeric(label)];
return [maxLength(LONG_TEXT.has(c) ? 500 : 200, label)];
};
const v = useValidation(Object.fromEntries(columns.filter((c) => !generated(c)).map((c) => [c, rulesFor(c)])));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setError(null);
v.clear();
setDraft(Object.fromEntries(columns.map((c) => [c, IDENTITY.has(c) ? (row ? String(row[c] ?? "") : account(c)) : String(row?.[c] ?? "")])));
// Keyed on the row's id and primitives — not object identity — so a background refresh
// of the list can never wipe what the user is typing.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, row?.id, table.name, profile?.full_name, profile?.headquarters_name, owner?.id]);
const set = (column: string, value: string) => { setDraft((d) => ({ ...d, [column]: value })); v.retouch(column, value); };
const blur = (column: string) => (e: { target: { value: string } }) => v.touch(column, e.target.value);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check(draft, e.currentTarget)) return;
if (!columns.some((c) => !generated(c) && !IDENTITY.has(c) && (draft[c] ?? "").trim())) {
setError("Fill in at least one value before saving the row.");
return;
}
setBusy(true);
setError(null);
try {
if (row) await api.updateCsvRow(table.name, row.id, draft);
else await api.createCsvRow(table.name, draft, isAdmin ? owner?.id : undefined);
onSaved(row ? "Row updated" : "Row added");
} catch (err) {
setError(errorMessage(err, "Could not save the row"));
} finally {
setBusy(false);
}
}
const control = (column: string) => {
const value = draft[column] ?? "";
if (table.name === "sales_projection" && column === "product_name" && isAdmin) {
return <Input value={value} placeholder="Product name" onChange={(e) => set("product_name", e.target.value)} onBlur={blur("product_name")} />;
}
if (table.name === "sales_projection" && column === "product_name") {
return (
<Select value={value} onChange={(e) => { set("product_name", e.target.value); set("pts", products.find((p) => p.name === e.target.value)?.pts ?? ""); }} onBlur={blur("product_name")}>
<option value="">Choose product</option>
{products.map((p) => <option key={p.name} value={p.name}>{p.name}</option>)}
</Select>
);
}
if (column === "month") {
return (
<Select value={value} onChange={(e) => set(column, e.target.value)}>
<option value="">Choose month</option>
{value && !MONTHS.includes(value) && <option value={value}>{value}</option>}
{MONTHS.map((m) => <option key={m} value={m}>{m}</option>)}
</Select>
);
}
return <Input type={DATES.has(column) ? "date" : "text"} inputMode={NUMERIC.has(column) ? "decimal" : undefined} value={value} readOnly={generated(column)} onChange={(e) => set(column, e.target.value)} onBlur={blur(column)} />;
};
return (
<Modal
open={open}
variant="drawer"
title={row ? "Edit row" : "New row"}
description={table.label}
onClose={onClose}
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("row-editor-form") as HTMLFormElement | null)?.requestSubmit()}>{row ? "Save changes" : "Add row"}</Button></>}
>
<form id="row-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
{columns.map((c) => (
<Field key={c} label={humanize(c)} error={v.errors[c]} required={table.name === "sales_projection" && c === "product_name"} hint={generated(c) ? "Filled in automatically" : NUMERIC.has(c) ? "Numbers only" : undefined}>{control(c)}</Field>
))}
</form>
</Modal>
);
}
+5
View File
@@ -0,0 +1,5 @@
/** Forms that carry an Area Manager approval signature on their PDF. */
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart"]);
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
export const APPROVAL_POLL_MS = 3_000;
+59
View File
@@ -0,0 +1,59 @@
import { type FormEvent, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { Field, Input, Textarea } from "../../components/ui/Field";
import { PageHeader } from "../../components/ui/PageHeader";
import { api } from "../../api";
import { errorMessage, todayISO } from "../../lib/format";
import { navigate } from "../../lib/router";
import { isoDate, maxLength, notAfter, required, useValidation } from "../../lib/validation";
export function NewReportPage() {
const [date, setDate] = useState(todayISO());
const [remarks, setRemarks] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const v = useValidation({
date: [required("Report date"), isoDate("Report date"), notAfter(todayISO(), "Report date", "today")],
remarks: [maxLength(2000, "Remarks")],
});
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!v.check({ date, remarks }, e.currentTarget)) return;
setBusy(true);
setError(null);
try {
const created = await api.createReport({ report_date: date, mr_remarks: remarks || null });
navigate(`/reports/${created.id}`);
} catch (err) {
setError(errorMessage(err, "Could not create the report"));
setBusy(false);
}
}
return (
<div className="narrow">
<PageHeader back={{ to: "/reports", label: "Daily Call Reports" }} title="New Daily Call Report" description="Start a draft, then add your doctor and chemist visits before submitting." />
<Card>
<CardHeader title="Report details" />
<CardBody>
<form className="form-grid" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Report date" required error={v.errors.date} hint="One report per day; you can file up to the configured backdating window.">
<Input type="date" value={date} max={todayISO()} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
</Field>
<Field label="Daily remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={(e) => { setRemarks(e.target.value); v.retouch("remarks", e.target.value); }} onBlur={(e) => v.touch("remarks", e.target.value)} rows={4} placeholder="Optional summary of the day" />
</Field>
<div className="form-actions">
<Button onClick={() => navigate("/reports")}>Cancel</Button>
<Button type="submit" variant="primary" loading={busy}>Create draft</Button>
</div>
</form>
</CardBody>
</Card>
</div>
);
}
+216
View File
@@ -0,0 +1,216 @@
import { useEffect, useRef, useState } from "react";
import { Alert } from "../../components/ui/Alert";
import { Button } from "../../components/ui/Button";
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
import { Field, Input, Textarea } from "../../components/ui/Field";
import { KeyValue } from "../../components/ui/Misc";
import { PageHeader } from "../../components/ui/PageHeader";
import { ErrorState, Skeleton } from "../../components/ui/States";
import { useToast } from "../../components/ui/Toast";
import { AddVisitForm } from "../../components/reports/AddVisitForm";
import { ApprovalTimeline } from "../../components/reports/ApprovalTimeline";
import { ReviewPanel, type ReviewAction } from "../../components/reports/ReviewPanel";
import { StatusBadge } from "../../components/reports/StatusBadge";
import { VisitList } from "../../components/reports/VisitList";
import { WorkflowTracker } from "../../components/reports/WorkflowTracker";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { errorMessage, formatDate, formatDateTime } from "../../lib/format";
import { useUser } from "../../lib/session";
import { maxLength, useValidation } from "../../lib/validation";
import type { Approval, Chemist, Dcr, Doctor } from "../../types";
export function ReportDetailPage({ id }: { id: string }) {
const user = useUser();
const toast = useToast();
// A report someone else is deciding on updates by itself; one being edited is left alone.
const editableRef = useRef(false);
const report = useAsync(async () => {
const [dcr, history] = await Promise.all([api.report(id), api.approvalHistory(id)]);
return { dcr, history };
}, [id], { poll: () => (editableRef.current ? 0 : LIVE) });
// The report lives in one place (the loader's data). Every change writes its result straight
// back there, so the screen updates the instant the server answers.
const latest = useRef(report.data);
latest.current = report.data;
const dcr: Dcr | null = report.data?.dcr ?? null;
const history: Approval[] = report.data?.history ?? [];
const apply = (next: Dcr) => report.setData({ dcr: next, history: latest.current?.history ?? [] });
// Quietly confirm with the server a moment after a change, in case anything else moved.
const reconcile = () => { window.setTimeout(() => void report.reload(), 250); };
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [remarks, setRemarks] = useState("");
const [stockist, setStockist] = useState("");
const [order, setOrder] = useState("");
const dirty = useRef(false); // the MR has typed something not yet saved
const details = useValidation({ remarks: [maxLength(2000, "Remarks")], stockist: [maxLength(200, "Stockist visit")], order: [maxLength(100, "Order")] });
useEffect(() => {
if (!report.data) return;
if (!dirty.current) {
setRemarks(report.data.dcr.mr_remarks ?? "");
setStockist(report.data.dcr.stockist_visit ?? "");
setOrder(report.data.dcr.order_value ?? "");
}
}, [report.data]);
const editable = user.role === "MR" && !!dcr && !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], { poll: LIVE },
);
if (report.error) return <ErrorState message={report.error} onRetry={() => void report.reload()} />;
if (!dcr) return <Card><CardBody><Skeleton lines={5} /></CardBody></Card>;
const refreshHistory = () => api.approvalHistory(id).then((h) => { if (latest.current) report.setData({ dcr: latest.current.dcr, history: h }); }).catch(() => undefined);
const run = async (task: () => Promise<Dcr>, success: string): Promise<boolean> => {
setBusy(true);
setError(null);
try {
apply(await task());
void refreshHistory(); // the timeline catches up without holding the screen back
toast.success(success);
reconcile();
return true;
} catch (e) {
setError(errorMessage(e, "That action failed"));
return false;
} finally {
setBusy(false);
}
};
const decide = (action: ReviewAction, comment: string) => {
if (action === "return") return run(() => api.returnReport(dcr.id, comment), "Report returned for correction");
return run(() => api.approve(dcr.id, comment), "Report approved and locked");
};
const saveDetails = async () => {
if (!dcr) return;
const values = { remarks, stockist, order };
if (!details.check(values)) return;
const changes: Record<string, string | null> = {};
if (remarks !== (dcr.mr_remarks ?? "")) changes.mr_remarks = remarks.trim() || null;
if (stockist !== (dcr.stockist_visit ?? "")) changes.stockist_visit = stockist.trim() || null;
if (order !== (dcr.order_value ?? "")) changes.order_value = order.trim() || null;
if (Object.keys(changes).length === 0) { dirty.current = false; return; }
try {
apply(await api.updateReport(dcr.id, changes));
dirty.current = false;
toast.success("Report details saved");
reconcile();
} catch (e) { setError(errorMessage(e, "Could not save the report details")); }
};
// 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) });
setError(null);
try {
apply(await api.deleteCall(dcr.id, callId));
toast.success("Visit removed");
reconcile();
} catch (e) {
apply(before);
setError(errorMessage(e, "Could not remove the visit"));
}
};
const typed = (set: (value: string) => void, name: string) => (e: { target: { value: string } }) => {
dirty.current = true;
set(e.target.value);
details.retouch(name, e.target.value);
};
return (
<>
<PageHeader
back={{ to: "/reports", label: "Daily Call Reports" }}
title={<>{formatDate(dcr.report_date)} <StatusBadge status={dcr.status} /></>}
description={`${dcr.mr_name} · ${dcr.headquarters_name}`}
actions={dcr.status === "APPROVED" && (
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
)}
/>
<Alert>{error}</Alert>
{dcr.return_reason && (
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ?? "reviewer"}`}>{dcr.return_reason}</Alert>
)}
<Card><CardBody><WorkflowTracker status={dcr.status} /></CardBody></Card>
<div className="split">
<div className="stack">
<Card>
<CardHeader title="Summary" />
<CardBody>
<KeyValue items={[
{ label: "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
{ label: "Headquarters", value: dcr.headquarters_name },
{ label: "Doctor visits", value: dcr.doctor_calls.length },
{ label: "Chemist visits", value: dcr.chemist_calls.length },
{ label: "Submitted", value: formatDateTime(dcr.submitted_at) },
{ label: "Approved", value: formatDateTime(dcr.approved_at) },
]} />
<div className="divider" />
{editable ? (
<div className="form-grid">
<Field label="Stockist visit" error={details.errors.stockist}>
<Input value={stockist} onChange={typed(setStockist, "stockist")} onBlur={() => void saveDetails()} placeholder="Stockist visited, if any" />
</Field>
<Field label="Order" error={details.errors.order}>
<Input value={order} onChange={typed(setOrder, "order")} onBlur={() => void saveDetails()} placeholder="Order value or details" />
</Field>
<Field label="Daily remarks" span error={details.errors.remarks} hint={`${remarks.length}/2000 — saved when you leave the box`}>
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder="Optional summary of the day" />
</Field>
</div>
) : (
<>
<p className="field-label">Stockist visit / Order</p>
<p className="prose">{[dcr.stockist_visit, dcr.order_value && `Order: ${dcr.order_value}`].filter(Boolean).join(" · ") || "None recorded."}</p>
<p className="field-label">Daily remarks</p>
<p className="prose">{dcr.mr_remarks || "No remarks recorded."}</p>
</>
)}
</CardBody>
</Card>
{editable && (
<Card>
<CardHeader title="Add a visit" description="Only doctors and chemists assigned to you are listed." />
<CardBody>
<AddVisitForm dcr={dcr} doctors={masters.data?.doctors ?? []} chemists={masters.data?.chemists ?? []} onChange={(next) => { apply(next); reconcile(); }} />
</CardBody>
</Card>
)}
<Card>
<CardHeader title="Visits" description={`${dcr.doctor_calls.length + dcr.chemist_calls.length} recorded, in visit order.`} />
<CardBody flush>
<VisitList dcr={dcr} editable={editable} onRemove={(callId) => void removeVisit(callId)} />
</CardBody>
</Card>
{editable && (
<Card>
<CardHeader title="Ready to send?" description="Submitted reports cannot be edited unless they are returned for correction." />
<CardBody>
<Button variant="primary" icon="send" loading={busy} onClick={() => void run(() => api.submit(dcr.id), "Submitted to the Area Manager")}>Submit to Area Manager</Button>
</CardBody>
</Card>
)}
<ReviewPanel dcr={dcr} role={user.role} busy={busy} onDecide={decide} />
</div>
<Card className="sticky">
<CardHeader title="Approval history" />
<CardBody><ApprovalTimeline items={history} /></CardBody>
</Card>
</div>
</>
);
}
+59
View File
@@ -0,0 +1,59 @@
import { useMemo, useState } from "react";
import { Button } from "../../components/ui/Button";
import { Card } from "../../components/ui/Card";
import { PageHeader } from "../../components/ui/PageHeader";
import { SearchInput } from "../../components/ui/Misc";
import { ErrorState } from "../../components/ui/States";
import { Tabs, type TabItem } from "../../components/ui/Tabs";
import { ReportTable } from "../../components/reports/ReportTable";
import { LIVE, useAsync } from "../../hooks/useAsync";
import { api } from "../../api";
import { navigate } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { DcrListItem } from "../../types";
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",
RETURNED: (r) => r.status === "RETURNED",
APPROVED: (r) => r.status === "APPROVED",
};
export function ReportsPage() {
const user = useUser();
const reports = useAsync(api.reports, [], { poll: LIVE });
const [filter, setFilter] = useState<Filter>("ALL");
const [query, setQuery] = useState("");
const all = reports.data ?? [];
const tabs: TabItem<Filter>[] = [
{ key: "ALL", label: "All" }, { key: "DRAFT", label: "Draft" }, { key: "PENDING", label: "In review" },
{ key: "RETURNED", label: "Returned" }, { key: "APPROVED", label: "Approved" },
].map((t) => ({ ...t, key: t.key as Filter, count: all.filter(MATCH[t.key as Filter]).length }));
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return all.filter(MATCH[filter]).filter((r) => !q || `${r.mr_name} ${r.headquarters_name} ${r.report_date}`.toLowerCase().includes(q));
}, [all, filter, query]);
return (
<>
<PageHeader
title="Daily Call Reports"
description={user.role === "MR" ? "Create, submit and track your field work." : "Only reports within your permitted scope are shown."}
actions={user.role === "MR" && <Button variant="primary" icon="plus" onClick={() => navigate("/reports/new")}>New report</Button>}
/>
<Card>
<div className="toolbar">
<Tabs label="Filter by status" items={tabs} value={filter} onChange={setFilter} />
<SearchInput value={query} onChange={setQuery} placeholder="Search by name, headquarters or date" />
</div>
{reports.error
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
: <ReportTable rows={rows} loading={reports.loading} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
</Card>
</>
);
}
+22
View File
@@ -0,0 +1,22 @@
*, *::before, *::after { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0; min-width: 320px;
font: 14px/1.5 var(--font); color: var(--text); background: var(--bg);
-webkit-font-smoothing: antialiased;
}
h1, h2, h3, p, ul, ol, dl, dd { margin: 0; }
h1, h2, h3 { line-height: 1.25; letter-spacing: -0.01em; }
ul, ol { padding: 0; list-style: none; }
a { color: var(--brand-600); text-decoration: none; }
button, input, select, textarea { font: inherit; color: inherit; }
button { cursor: pointer; }
img, svg { display: block; max-width: 100%; }
:focus-visible { outline: 2px solid var(--brand-600); outline-offset: 2px; }
::selection { background: var(--brand-100); }
.muted { color: var(--text-4); }
.prose { color: var(--text-2); white-space: pre-wrap; }
.nowrap { white-space: nowrap; }
.text-link { font-weight: 500; font-size: 13px; }
.text-link:hover { text-decoration: underline; }
@media (prefers-reduced-motion: reduce) { * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } }
+256
View File
@@ -0,0 +1,256 @@
/* ---- Buttons -------------------------------------------------------------- */
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 38px; padding: 0 14px;
border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface); color: var(--text-2);
font-weight: 500; font-size: 14px; white-space: nowrap; box-shadow: var(--shadow-xs);
transition: background .15s, border-color .15s, box-shadow .15s;
}
.btn:hover:not(:disabled) { background: var(--surface-hover); }
.btn:disabled { opacity: .55; cursor: not-allowed; }
.btn-sm { height: 30px; padding: 0 10px; font-size: 13px; gap: 6px; }
.btn-primary { background: var(--brand-600); border-color: var(--brand-600); color: #fff; }
.btn-primary:hover:not(:disabled) { background: var(--brand-700); border-color: var(--brand-700); }
.btn-danger { background: var(--surface); border-color: var(--danger-border); color: var(--danger); }
.btn-danger:hover:not(:disabled) { background: var(--danger-bg); }
.btn-ghost { border-color: transparent; background: transparent; box-shadow: none; color: var(--text-3); }
.btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); }
.btn-block { width: 100%; height: 42px; }
.spinner { width: 14px; height: 14px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin .7s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.icon-btn { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; border: 0; border-radius: var(--radius); background: none; color: var(--text-3); }
.icon-btn:hover { background: var(--surface-hover); color: var(--text); }
.button-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
.row-actions { display: inline-flex; gap: 2px; }
/* ---- Card ------------------------------------------------------------------ */
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-xs); min-width: 0; }
.card-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; flex-wrap: wrap; padding: 18px 20px; border-bottom: 1px solid var(--border); }
.card-title { font-size: 15px; font-weight: 600; }
.card-desc { color: var(--text-3); margin-top: 2px; font-size: 13px; }
.card-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.card-body { padding: 20px; }
.card-body.flush { padding: 0; }
.card > .table-scroll:first-child, .card > .state:first-child { border-radius: var(--radius-lg); }
.title-row { display: inline-flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.identity { display: inline-flex; align-items: center; gap: 12px; }
.identity small { display: block; color: var(--text-3); font-weight: 400; font-size: 13px; }
.divider { height: 1px; background: var(--border); margin: 18px 0; }
/* ---- Stats ----------------------------------------------------------------- */
.stat { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); padding: 16px 18px; box-shadow: var(--shadow-xs); display: grid; gap: 6px; }
.stat-label { display: inline-flex; align-items: center; gap: 8px; color: var(--text-3); font-size: 13px; font-weight: 500; }
.stat-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-4); }
.stat-warning { background: #f79009; } .stat-danger { background: #f04438; } .stat-success { background: #12b76a; }
.stat-value { font-size: 28px; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; }
.stat-hint { color: var(--text-4); font-size: 12px; }
.stat-button { width: 100%; text-align: left; font: inherit; color: inherit; cursor: pointer; transition: border-color .15s, box-shadow .15s, transform .05s; }
.stat-button:hover { border-color: var(--brand-600, #2456a6); box-shadow: var(--shadow-sm, var(--shadow-xs)); }
.stat-button:active { transform: translateY(1px); }
.stat-button:focus-visible { outline: 2px solid var(--brand-600, #2456a6); outline-offset: 2px; }
.stat-button.selected { border-color: var(--brand-600, #2456a6); box-shadow: 0 0 0 1px var(--brand-600, #2456a6); background: var(--brand-50, var(--surface)); }
/* ---- Badge ------------------------------------------------------------------- */
.badge { display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 9px; border: 1px solid transparent; border-radius: 999px; font-size: 12px; font-weight: 500; white-space: nowrap; vertical-align: middle; }
.badge-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.badge-neutral { background: #f2f4f7; color: var(--text-2); border-color: var(--border); }
.badge-brand { background: var(--brand-50); color: var(--brand-700); border-color: var(--brand-100); }
.badge-success { background: var(--success-bg); color: var(--success); border-color: var(--success-border); }
.badge-warning { background: var(--warning-bg); color: var(--warning); border-color: var(--warning-border); }
.badge-danger { background: var(--danger-bg); color: var(--danger); border-color: var(--danger-border); }
.avatar { display: inline-grid; place-items: center; border-radius: 50%; background: var(--brand-100); color: var(--brand-700); font-weight: 600; flex: none; }
/* ---- Alerts and states --------------------------------------------------------- */
.alert { display: flex; gap: 12px; align-items: flex-start; padding: 12px 14px; border: 1px solid; border-radius: var(--radius); }
.alert p { margin-top: 2px; }
.alert svg { flex: none; margin-top: 2px; }
.alert-danger { background: var(--danger-bg); border-color: var(--danger-border); color: var(--danger); }
.alert-warning { background: var(--warning-bg); border-color: var(--warning-border); color: var(--warning); }
.alert-success { background: var(--success-bg); border-color: var(--success-border); color: var(--success); }
.alert-info { background: var(--brand-50); border-color: var(--brand-100); color: var(--brand-700); }
.state { display: grid; justify-items: center; gap: 6px; padding: 44px 20px; text-align: center; }
.state h3 { font-size: 15px; font-weight: 600; margin-top: 6px; }
.state p { color: var(--text-3); max-width: 420px; margin-bottom: 8px; }
.state-icon { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 12px; background: var(--surface-hover); border: 1px solid var(--border); color: var(--text-3); }
.state-icon-danger { background: var(--danger-bg); border-color: var(--danger-border); color: var(--danger); }
.skeleton { display: block; height: 12px; border-radius: 6px; background: linear-gradient(90deg, #eef0f4 25%, #f6f7f9 50%, #eef0f4 75%); background-size: 200% 100%; animation: shimmer 1.3s infinite linear; }
.skeleton-block { display: grid; gap: 12px; padding: 4px 0; }
@keyframes shimmer { to { background-position: -200% 0; } }
/* ---- Toolbar, tabs, search ------------------------------------------------------- */
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 12px 16px; border-bottom: 1px solid var(--border); }
.toolbar-end { justify-content: flex-end; }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; }
.tab { display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px; border: 0; border-radius: var(--radius); background: none; color: var(--text-3); font-weight: 500; }
.tab:hover { background: var(--surface-hover); color: var(--text); }
.tab.active { background: var(--brand-50); color: var(--brand-700); }
.tab-count { min-width: 20px; padding: 0 6px; border-radius: 999px; background: #eaecf0; color: var(--text-2); font-size: 12px; text-align: center; }
.tab.active .tab-count { background: var(--brand-100); color: var(--brand-700); }
.content > .tabs { padding-bottom: 4px; }
.search { position: relative; display: block; width: 300px; max-width: 100%; }
.search svg { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--text-4); }
.search input { width: 100%; height: 36px; padding: 0 12px 0 34px; border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface); }
.search input:focus { outline: none; border-color: var(--brand-600); box-shadow: var(--ring); }
/* ---- Table -------------------------------------------------------------------------- */
/* Scroll both ways inside the card, with the header pinned, so a long or wide table never hides its scrollbar off-screen. */
.table-scroll { overflow: auto; max-height: min(70vh, 720px); overscroll-behavior: contain; scrollbar-gutter: stable; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
.table-scroll::-webkit-scrollbar { width: 10px; height: 10px; }
.table-scroll::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid var(--surface); }
.table-scroll::-webkit-scrollbar-track { background: var(--surface-2); }
.table thead th { position: sticky; top: 0; z-index: 2; }
.table { width: 100%; border-collapse: collapse; font-size: 14px; }
.table th { padding: 10px 16px; text-align: left; font-size: 12px; font-weight: 600; color: var(--text-3); background: var(--surface-2); border-bottom: 1px solid var(--border); white-space: nowrap; }
.table td { padding: 13px 16px; border-bottom: 1px solid var(--border); color: var(--text-2); vertical-align: middle; }
.table tbody tr:last-child td { border-bottom: 0; }
.table td strong { color: var(--text); font-weight: 600; }
.table tr.clickable { cursor: pointer; }
.table tr.clickable:hover td { background: var(--surface-hover); }
.table td .skeleton { width: 70%; }
.table .col-sticky { position: sticky; right: 0; background: var(--surface); box-shadow: -1px 0 0 var(--border); }
.table th.col-sticky { background: var(--surface-2); z-index: 3; }
.table tr.clickable:hover td.col-sticky { background: var(--surface-hover); }
/* ---- Forms ------------------------------------------------------------------------------ */
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; }
.form-grid > .alert, .form-grid > .form-actions { grid-column: 1 / -1; }
.form-single { grid-template-columns: 1fr; }
.form-actions { display: flex; justify-content: flex-end; gap: 10px; }
.field { display: grid; gap: 6px; align-content: start; }
.field-span { grid-column: 1 / -1; }
.field-label { font-size: 13px; font-weight: 500; color: var(--text-2); }
.field-hint { font-size: 12px; color: var(--text-4); }
.field-req { color: var(--danger); }
.field-error { font-size: 12px; color: var(--danger); font-weight: 500; }
.field-invalid .input { border-color: var(--danger); }
.field-invalid .input:focus { border-color: var(--danger); box-shadow: 0 0 0 3px rgb(240 68 56 / .18); }
.field-invalid .hq-check-list { outline: 1px solid var(--danger); border-radius: var(--radius); }
.input { width: 100%; height: 38px; padding: 0 12px; border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow-xs); }
.input::placeholder { color: var(--text-4); }
.input:focus { outline: none; border-color: var(--brand-600); box-shadow: var(--ring); }
.input[readonly] { background: var(--surface-2); color: var(--text-3); }
.select { appearance: none; padding-right: 34px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23667085' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; }
.textarea { height: auto; min-height: 76px; padding: 10px 12px; resize: vertical; line-height: 1.5; }
.checkbox { display: flex; align-items: center; gap: 8px; height: 38px; align-self: end; font-weight: 500; color: var(--text-2); }
.checkbox input { width: 16px; height: 16px; accent-color: var(--brand-600); }
/* ---- Key/value, checklist, timeline, steps, visits ----------------------------------------- */
.kv { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 24px; }
.kv dt { font-size: 12px; color: var(--text-3); font-weight: 500; margin-bottom: 2px; }
.kv dd { font-weight: 500; color: var(--text); }
.checklist { counter-reset: n; display: grid; gap: 10px; }
.checklist li { counter-increment: n; display: flex; align-items: center; gap: 12px; color: var(--text-2); }
.checklist li::before { content: counter(n); display: grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--brand-50); color: var(--brand-700); font-size: 12px; font-weight: 600; }
.steps { display: flex; align-items: center; }
.step { position: relative; flex: 1; display: flex; align-items: center; gap: 10px; color: var(--text-4); font-weight: 500; }
.step:not(:last-child)::after { content: ""; flex: 1; height: 2px; margin: 0 14px; background: var(--border); border-radius: 2px; }
.step-dot { display: grid; place-items: center; flex: none; width: 26px; height: 26px; border-radius: 50%; background: var(--surface); border: 2px solid var(--border-strong); font-size: 12px; font-weight: 600; }
.step-done { color: var(--text-2); }
.step-done .step-dot { background: var(--brand-600); border-color: var(--brand-600); color: #fff; }
.step-done:not(:last-child)::after { background: var(--brand-600); }
.step-current { color: var(--brand-700); }
.step-current .step-dot { border-color: var(--brand-600); color: var(--brand-600); box-shadow: var(--ring); }
.step-returned { color: var(--danger); }
.step-returned .step-dot { border-color: var(--danger); color: var(--danger); }
@media (max-width: 640px) { .step-label { display: none; } .step-current .step-label, .step-returned .step-label { display: inline; } }
.timeline { display: grid; gap: 0; }
.timeline li { position: relative; display: flex; gap: 12px; padding-bottom: 20px; }
.timeline li:last-child { padding-bottom: 0; }
.timeline li:not(:last-child)::before { content: ""; position: absolute; left: 4px; top: 14px; bottom: 0; width: 2px; background: var(--border); }
.timeline-dot { flex: none; width: 10px; height: 10px; margin-top: 5px; border-radius: 50%; background: var(--brand-600); box-shadow: 0 0 0 3px var(--brand-100); }
.timeline-action { font-weight: 600; text-transform: capitalize; }
.timeline-meta { color: var(--text-3); font-size: 12px; display: block; }
.timeline-note { margin-top: 6px; padding: 8px 10px; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text-2); }
.visit-list li { display: flex; align-items: center; gap: 16px; padding: 14px 20px; border-bottom: 1px solid var(--border); }
.visit-list li:last-child { border-bottom: 0; }
.visit-time { flex: none; width: 48px; font-variant-numeric: tabular-nums; color: var(--text-3); font-weight: 600; }
.visit-main { flex: 1; min-width: 0; }
.visit-detail { color: var(--text-3); font-size: 13px; margin-top: 2px; }
/* ---- Overlay, modal, drawer, toasts ------------------------------------------------------------- */
.overlay { position: fixed; inset: 0; z-index: 60; display: grid; overflow-y: auto; background: rgb(16 24 40 / .45); animation: fade .15s ease; }
.overlay-dialog { place-items: center; padding: 16px; }
.overlay-drawer { justify-items: end; }
.modal { display: flex; flex-direction: column; background: var(--surface); box-shadow: var(--shadow-lg); max-height: calc(100vh - 32px); max-height: calc(100dvh - 32px); min-height: 0; }
.modal-dialog { width: min(440px, 100%); border-radius: var(--radius-lg); }
.modal-drawer { width: min(480px, 100%); height: 100vh; height: 100dvh; max-height: none; animation: slide .2s ease; }
.modal-header { display: flex; justify-content: space-between; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--border); }
.modal-header h2 { font-size: 16px; font-weight: 600; }
.modal-header p { color: var(--text-3); font-size: 13px; }
.modal-body { padding: 20px; overflow-y: auto; flex: 1; min-height: 0; overscroll-behavior: contain; }
.modal-footer, .modal-header { flex: none; }
.modal-footer { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 20px; border-top: 1px solid var(--border); background: var(--surface-2); }
@keyframes fade { from { opacity: 0; } }
@keyframes slide { from { transform: translateX(24px); opacity: 0; } }
.toasts { position: fixed; right: 20px; bottom: 20px; z-index: 80; display: grid; gap: 10px; width: min(380px, calc(100vw - 32px)); }
.toast { display: flex; align-items: center; gap: 10px; padding: 12px 12px 12px 14px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-lg); animation: slide .2s ease; }
.toast span { flex: 1; }
.toast-success svg:first-child { color: var(--success); }
.toast-danger svg:first-child { color: var(--danger); }
/* ---- Sign-in ------------------------------------------------------------------------------------------------ */
.auth { min-height: 100vh; display: grid; grid-template-columns: minmax(400px, 5fr) 6fr; background: var(--surface); }
.auth-center { place-items: center; grid-template-columns: 240px; }
.auth-panel { position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 48px clamp(24px, 5vw, 72px) 72px; }
.auth-card { width: 100%; max-width: 400px; display: flex; flex-direction: column; gap: 6px; }
.auth-logo { height: 44px; width: auto; margin-bottom: 40px; align-self: flex-start; }
.auth-panel h1 { font-size: 28px; font-weight: 650; letter-spacing: -0.02em; }
.auth-form { display: grid; gap: 18px; margin-top: 26px; }
.auth-form .input { height: 44px; }
.auth-form .btn-block { height: 44px; font-size: 15px; margin-top: 4px; }
.auth-help { margin-top: 22px; color: var(--text-4); font-size: 13px; }
.auth-copy { position: absolute; left: 0; right: 0; bottom: 24px; text-align: center; color: var(--text-4); font-size: 12px; }
.input-affix { position: relative; display: block; }
.input-affix .input { padding-right: 64px; }
.affix-btn { position: absolute; right: 6px; top: 50%; transform: translateY(-50%); height: 30px; padding: 0 10px; border: 0; border-radius: 6px; background: transparent; color: var(--brand-600); font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; }
.affix-btn:hover { background: var(--brand-50); }
.affix-btn:focus-visible { outline: 2px solid var(--brand-600); outline-offset: 1px; }
/* Company panel: flat brand colour, plain type, content centred and capped. */
.auth-aside { display: flex; align-items: center; justify-content: center; padding: 56px clamp(32px, 6vw, 96px); background: var(--brand-700); color: #fff; }
.auth-about { width: 100%; max-width: 540px; }
.auth-about h2 { font-size: 30px; font-weight: 600; line-height: 1.25; letter-spacing: -0.01em; padding-bottom: 18px; margin-bottom: 22px; border-bottom: 3px solid var(--accent); width: fit-content; }
.auth-about p { font-size: 16px; line-height: 1.75; color: rgb(255 255 255 / .9); }
.auth-about p + p { margin-top: 18px; }
@media (max-height: 640px) { .auth-about p { font-size: 15px; line-height: 1.6; } }
@media (max-width: 860px) { .auth { grid-template-columns: 1fr; } .auth-panel { justify-content: flex-start; padding-top: 48px; padding-bottom: 32px; } .auth-copy { position: static; margin-top: 40px; } .auth-aside { padding: 36px 24px; justify-content: flex-start; } .auth-about h2 { font-size: 22px; } .auth-about p { font-size: 15px; line-height: 1.65; } }
/* ---- Headquarters checklist and chips --------------------------------------------------- */
.hq-check-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; max-height: 260px; overflow: auto; padding: 2px; }
.hq-check { display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); cursor: pointer; min-width: 0; }
.hq-check:hover { background: var(--surface-hover); }
.hq-check.on { border-color: var(--brand-600); background: var(--brand-50); }
.hq-check input { width: 16px; height: 16px; margin-top: 2px; accent-color: var(--brand-600); flex: none; }
.hq-check-text { display: grid; gap: 2px; min-width: 0; overflow-wrap: anywhere; }
.hq-check-text small { color: var(--text-4); font-size: 12px; }
.hq-empty { color: var(--text-3); font-size: 13px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
@media (max-width: 640px) {
.form-grid { grid-template-columns: 1fr; }
.hq-check-list { grid-template-columns: 1fr; }
}
.input-row { display: flex; gap: 8px; align-items: center; }
.input-row .input { flex: 1; min-width: 0; }
.input-row .btn { flex: none; }
/* Long forms and wide tables must scroll on small screens instead of being cut off. */
.form-grid, .auth-form { min-width: 0; }
.forms-layout > .card, .forms-layout > div { min-width: 0; }
@media (max-width: 640px) {
.overlay-dialog { padding: 8px; align-items: end; }
.modal-dialog { width: 100%; max-height: calc(100dvh - 16px); }
.table-scroll { max-height: 65vh; }
}
.form-nav-item { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.nav-flag { flex: none; padding: 2px 8px; border-radius: 999px; background: var(--warning-bg); border: 1px solid var(--warning-border); color: var(--warning); font-size: 11px; font-weight: 600; }
.update-bar { position: sticky; top: 0; z-index: 70; display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: wrap; padding: 8px 16px; background: var(--brand-700); color: #fff; font-size: 14px; }
.update-bar button { padding: 4px 12px; border: 1px solid rgb(255 255 255 / .6); border-radius: 6px; background: transparent; color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
.update-bar button:hover { background: rgb(255 255 255 / .15); }
.toolbar .filter { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; color: var(--text-muted); }
.toolbar .filter .select { width: auto; min-width: 180px; max-width: 100%; }
@media (max-width: 640px) { .toolbar .filter { width: 100%; flex-wrap: wrap; } .toolbar .filter .select { flex: 1; } }
+4
View File
@@ -0,0 +1,4 @@
@import "./tokens.css";
@import "./base.css";
@import "./layout.css";
@import "./components.css";
+107
View File
@@ -0,0 +1,107 @@
/* ---- Shell ---------------------------------------------------------------- */
.shell { min-height: 100vh; }
.shell-main { margin-left: var(--sidebar-w); min-height: 100vh; display: flex; flex-direction: column; transition: margin-left .2s ease; }
.shell-collapsed .shell-main { margin-left: var(--sidebar-w-collapsed); }
.sidebar {
position: fixed; inset: 0 auto 0 0; width: var(--sidebar-w); z-index: 40;
display: flex; flex-direction: column; background: var(--surface);
border-right: 1px solid var(--border); transition: width .2s ease, transform .2s ease;
}
.sidebar.collapsed { width: var(--sidebar-w-collapsed); }
.sidebar-brand { display: flex; align-items: center; height: var(--topbar-h); padding: 0 20px; border-bottom: 1px solid var(--border); }
.sidebar-brand img { height: 34px; width: auto; }
.sidebar.collapsed .sidebar-brand { padding: 0; justify-content: center; overflow: hidden; }
.sidebar.collapsed .sidebar-brand img { height: 30px; width: 44px; object-fit: cover; object-position: left center; }
.sidebar-nav { flex: 1; overflow-y: auto; padding: 8px 12px 16px; }
.nav-section { margin-top: 18px; }
.nav-title { padding: 0 10px 6px; font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--text-4); }
.sidebar.collapsed .nav-title { visibility: hidden; height: 6px; padding: 0; }
.nav-item {
display: flex; align-items: center; gap: 12px; width: 100%; height: 38px; padding: 0 10px; margin-bottom: 2px;
border: 0; border-radius: var(--radius); background: none; color: var(--text-2); font-weight: 500; font-size: 14px; text-align: left; white-space: nowrap;
}
.nav-item:hover { background: var(--surface-hover); color: var(--text); }
.nav-item.active { background: var(--brand-50); color: var(--brand-700); }
.nav-item svg { flex: none; color: var(--text-3); }
.nav-item.active svg { color: var(--brand-600); }
.sidebar.collapsed .nav-item { justify-content: center; padding: 0; }
.sidebar.collapsed .nav-item span { display: none; }
.collapse-toggle { margin: 0; border-radius: 0; height: 48px; padding: 0 22px; border-top: 1px solid var(--border); }
.sidebar.collapsed .collapse-toggle { padding: 0; }
.topbar {
position: sticky; top: 0; z-index: 30; height: var(--topbar-h); padding: 0 32px;
display: flex; align-items: center; gap: 12px; background: rgb(255 255 255 / .92);
backdrop-filter: saturate(1.4) blur(8px); border-bottom: 1px solid var(--border);
}
.topbar-title { font-size: 15px; font-weight: 600; }
.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 12px; }
.icon-btn.menu-btn { display: none; }
.user-menu { position: relative; }
.user-trigger { display: flex; align-items: center; gap: 8px; height: 38px; padding: 0 8px 0 5px; background: var(--surface); border: 1px solid var(--border); border-radius: 999px; color: var(--text-2); font-weight: 500; }
.user-trigger:hover { background: var(--surface-hover); }
.menu { position: absolute; right: 0; top: calc(100% + 8px); min-width: 230px; padding: 6px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); }
.menu-head { padding: 8px 10px 10px; border-bottom: 1px solid var(--border); margin-bottom: 6px; display: grid; }
.menu-head span { color: var(--text-3); font-size: 12px; overflow: hidden; text-overflow: ellipsis; }
.menu-item { display: flex; align-items: center; gap: 10px; width: 100%; height: 36px; padding: 0 10px; border: 0; border-radius: var(--radius); background: none; color: var(--text-2); font-weight: 500; text-align: left; }
.menu-item:hover { background: var(--surface-hover); }
.content { flex: 1; width: 100%; max-width: 1240px; margin: 0 auto; padding: 32px 32px 64px; display: grid; gap: 20px; align-content: start; }
.narrow { max-width: 760px; display: grid; gap: 20px; }
.scrim { position: fixed; inset: 0; background: rgb(16 24 40 / .4); z-index: 35; }
/* ---- Page furniture ----------------------------------------------------------- */
.page-header { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
.page-header h1 { font-size: 24px; font-weight: 600; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.page-desc { color: var(--text-3); margin-top: 4px; }
.page-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.back-link { display: inline-flex; align-items: center; gap: 6px; margin-bottom: 8px; color: var(--text-3); font-weight: 500; font-size: 13px; }
.back-link:hover { color: var(--brand-700); }
.split { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 20px; align-items: start; }
.stack { display: grid; gap: 20px; min-width: 0; }
.sticky { position: sticky; top: calc(var(--topbar-h) + 20px); }
.grid-2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; align-items: start; }
.stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
.stats.stats-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
.forms-layout { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 20px; align-items: start; }
.form-nav { display: grid; gap: 2px; position: sticky; top: calc(var(--topbar-h) + 20px); }
.form-nav-item { padding: 8px 12px; border-radius: var(--radius); color: var(--text-2); font-weight: 500; }
.form-nav-item:hover { background: var(--surface-hover); }
.form-nav-item.active { background: var(--brand-50); color: var(--brand-700); }
@media (max-width: 1100px) {
.stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.stats.stats-5 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.split { grid-template-columns: 1fr; }
.sticky { position: static; }
}
@media (max-width: 900px) {
.forms-layout { grid-template-columns: 1fr; }
.form-nav { position: static; display: flex; overflow-x: auto; gap: 6px; padding-bottom: 4px; }
.form-nav-item { white-space: nowrap; border: 1px solid var(--border); background: var(--surface); }
.grid-2 { grid-template-columns: 1fr; }
}
@media (max-width: 860px) {
.shell-main, .shell-collapsed .shell-main { margin-left: 0; }
.sidebar, .sidebar.collapsed { width: var(--sidebar-w); transform: translateX(-100%); box-shadow: var(--shadow-lg); }
.sidebar.open { transform: none; }
.sidebar.collapsed .nav-item { justify-content: flex-start; padding: 0 10px; }
.sidebar.collapsed .nav-item span { display: inline; }
.sidebar.collapsed .nav-title { visibility: visible; height: auto; padding: 0 10px 6px; }
.sidebar.collapsed .sidebar-brand { padding: 0 20px; justify-content: flex-start; }
.sidebar.collapsed .sidebar-brand img { width: auto; height: 34px; }
.collapse-toggle { display: none; }
.icon-btn.menu-btn { display: inline-flex; }
.topbar { padding: 0 16px; }
.content { padding: 20px 16px 48px; }
.user-name { display: none; }
}
@media (max-width: 520px) {
.stats, .stats.stats-5 { grid-template-columns: 1fr 1fr; gap: 10px; }
.topbar-right .badge { display: none; }
}
+43
View File
@@ -0,0 +1,43 @@
/* Design tokens — Celtic brand: logo blue (#285AA8), orange accent (#E95C00), neutral grey. */
:root {
--font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--bg: #f6f7f9;
--surface: #ffffff;
--surface-2: #fafbfc;
--surface-hover: #f5f7fa;
--border: #e4e7ec;
--border-strong: #d0d5dd;
--text: #101828;
--text-2: #344054;
--text-3: #667085;
--text-4: #98a2b3;
--brand-50: #eff4fb;
--brand-100: #dde8f7;
--brand-200: #bcd1ee;
--brand-500: #2a61b0;
--brand-600: #285aa8;
--brand-700: #23509a;
--brand-800: #1c407c;
--accent: #e95c00;
--accent-50: #fff3ea;
--success: #067647; --success-bg: #ecfdf3; --success-border: #abefc6;
--warning: #b54708; --warning-bg: #fffaeb; --warning-border: #fedf89;
--danger: #b42318; --danger-bg: #fef3f2; --danger-border: #fecdca;
--radius-sm: 6px;
--radius: 8px;
--radius-lg: 12px;
--shadow-xs: 0 1px 2px rgb(16 24 40 / 0.05);
--shadow-sm: 0 1px 3px rgb(16 24 40 / 0.08), 0 1px 2px rgb(16 24 40 / 0.04);
--shadow-lg: 0 12px 32px rgb(16 24 40 / 0.14), 0 4px 8px rgb(16 24 40 / 0.06);
--ring: 0 0 0 3px rgb(40 90 168 / 0.18);
--sidebar-w: 256px;
--sidebar-w-collapsed: 68px;
--topbar-h: 60px;
}
+26
View File
@@ -0,0 +1,26 @@
export type Role = "ADMIN" | "GM" | "AM" | "MR";
export type DcrStatus = "DRAFT" | "PENDING_AM" | "RETURNED" | "APPROVED";
export interface User { id: string; full_name: string; email: string; employee_code: string; phone?: string | null; role: Role; headquarters_id: string | null; is_active: boolean }
export interface Headquarters { id: string; code: string; name: string; district: string | null; state: string | null; is_active: boolean }
export interface AreaManagerMapping { id: string; area_manager_user_id: string; headquarters_id: string; effective_from: string; effective_to: string | null }
export interface Doctor { id: string; headquarters_id: string; name: string; speciality: string | null; clinic_address: string; is_core_doctor: boolean; is_active: boolean }
export interface Chemist { id: string; headquarters_id: string; name: string; shop_address: string; is_active: boolean }
export interface Product { id: string; company_id: string; name: string; pack: string | null; unit: string | null; is_active: boolean }
export interface StockInventory { id: number; serial_no: number; product_name: string; pack: string | null; quantity: string | null; unit: string | null }
export interface DoctorCall { id: string; doctor_id: string; doctor_name: string; doctor_speciality: string | null; is_core_doctor: boolean; visit_time: string; call_outcome: string; conversion_status: string | null; product_promote: string | null; product_sample: string | null; remarks: string | null }
export interface ChemistCall { id: string; chemist_id: string; chemist_name: string; visit_time: string; pob: string | null; remarks: string | null }
export interface DcrListItem { id: string; report_date: string; status: DcrStatus; mr_name: string; headquarters_name: string; doctor_call_count: number; chemist_call_count: number; submitted_at: string | null; approved_at: string | null; returned_by_role: Role | null }
export interface Dcr extends DcrListItem { mr_user_id: string; employee_code: string; headquarters_id: string; is_locked: boolean; mr_remarks: string | null; stockist_visit: string | null; order_value: string | null; return_reason: string | null; doctor_calls: DoctorCall[]; chemist_calls: ChemistCall[] }
export interface 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 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;
};
/** A medical representative whose company forms the signed-in user may open. */
export type FormOwner = { id: string; name: string; employee_code: string; headquarters_name: string | null };