Fixed Form Vlidation

This commit is contained in:
Shubhankar45
2026-09-22 10:36:55 +00:00
parent 8fdd20b29f
commit 2ed3945b5d
2435 changed files with 892940 additions and 32 deletions
+20 -6
View File
@@ -41,13 +41,27 @@ export class ApiError extends Error {
}
}
// Refresh tokens are single-use on the server (rotated on each call). If two requests hit a
// 401 at the same moment — e.g. a page's several polling calls right as the access token
// expires — they must not each race the server with the same refresh token: only the first
// would succeed, and the rest would see it already burned and wrongly sign the user out. So
// concurrent callers share one in-flight refresh instead of each starting their own.
let refreshInFlight: Promise<void> | null = null;
async function refreshSession(): Promise<void> {
const tokens = await request<TokenPair>(
"/auth/refresh",
{ method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) },
false,
);
auth.save(tokens);
if (!refreshInFlight) {
refreshInFlight = (async () => {
const tokens = await request<TokenPair>(
"/auth/refresh",
{ method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) },
false,
);
auth.save(tokens);
})().finally(() => {
refreshInFlight = null;
});
}
return refreshInFlight;
}
async function send<T>(path: string, init: RequestInit = {}, retry = true): Promise<T> {
+6
View File
@@ -52,5 +52,11 @@ export const humanize = (key: string) =>
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
.join(" ");
/** Column labels that read wrong once spelled out from their key. The stored column is still
* "aug_sales" (the printed form's own field, matching the database and the PDF) — this is only
* what the app displays, since "Aug Sales" is misleading once the row can be any month. */
const COLUMN_LABEL_OVERRIDES: Record<string, string> = { aug_sales: "Month Sales" };
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
error instanceof Error ? error.message : fallback;
+27 -13
View File
@@ -10,7 +10,7 @@ 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 { columnLabel, errorMessage, formatDate } from "../../lib/format";
import { Link } from "../../lib/router";
import { useUser } from "../../lib/session";
import type { CsvRow, CsvTable, FormApproval } from "../../types";
@@ -22,8 +22,10 @@ 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);
/** Tables whose stored Sl. No. restarts at 1 for each month (see MONTH_NUMBERED_TABLES in
* app/csv_data/router.py) — so it only means something within one chosen month. Viewed across
* "All months" it would repeat 1, 1, 1…, so that view counts fresh over what's actually shown. */
const MONTH_NUMBERED_TABLES = new Set(["sales_projection"]);
export function FormsPage({ table: routeTable }: { table?: string }) {
const user = useUser();
@@ -61,6 +63,8 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
const [deleting, setDeleting] = useState<CsvRow | null>(null);
const canEdit = user.role === "MR" || user.role === "ADMIN";
// Only an admin may delete a row — an MR can edit their own forms but not remove rows from them.
const canDelete = user.role === "ADMIN";
// 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;
@@ -72,9 +76,11 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
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.
// Forms with a month can be downloaded one month at a time. Every month is always offered —
// not just ones with rows already in them — so choosing next month before anyone has filled
// it in is a normal, working choice, not something hidden until data happens to exist.
const hasMonth = !!table?.columns.includes("month");
const months = useMemo(() => {
const monthsWithRows = useMemo(() => {
if (!hasMonth) return [] as string[];
const seen = new Map<string, string>();
for (const r of rows.data ?? []) { const m = String(r.month ?? "").trim(); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
@@ -83,10 +89,18 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
}, [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)) ?? "";
// Starts on the current month when the form already has rows for it, otherwise on everything.
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
const shownRows = month ? (rows.data ?? []).filter((r) => sameMonth(r.month, month)) : rows.data ?? [];
const showToolbar = hasMonth ? months.length > 0 : isManager && needsApproval;
const showToolbar = hasMonth || (isManager && needsApproval);
// Across "All months" a month-numbered table's own Sl. No. would repeat per month, so number
// by position in the list actually on screen instead; a single chosen month already has its
// own correct running numbers from the server, so those are kept as stored.
const continuousNumbering = !!table && MONTH_NUMBERED_TABLES.has(table.name) && !month;
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
const numberOf = (r: CsvRow) => String(continuousNumbering ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
/** 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") {
@@ -134,7 +148,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
.filter((c) => !SERIAL.has(c) && !(user.role !== "ADMIN" && IDENTITY.has(c)))
.map<Column<CsvRow>>((c) => ({
key: c,
header: humanize(c),
header: columnLabel(c),
nowrap: true,
render: (r) => {
const value = String(r[c] ?? "");
@@ -147,7 +161,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
<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" />}
{canDelete && <Button size="sm" variant="ghost" icon="trash" onClick={() => setDeleting(r)} aria-label="Delete row" />}
</span>
),
},
@@ -178,7 +192,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
<>
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
<Button icon="download" disabled={!hasRows} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</Button>
<Button icon="download" disabled={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</Button>
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
</>
}
@@ -194,12 +208,12 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
</Select>
</label>
)}
{hasMonth && months.length > 0 && (
{hasMonth && (
<label className="filter">
<span>Month</span>
<Select value={month} onChange={(e) => setMonthChoice((m) => ({ ...m, [table.name]: e.target.value }))} aria-label="Month">
<option value="">All months</option>
{months.map((m) => <option key={m} value={m}>{m}</option>)}
{MONTHS.map((m) => <option key={m} value={m}>{m}{monthsWithRows.some((x) => sameMonth(x, m)) ? "" : " (no rows yet)"}</option>)}
</Select>
</label>
)}
+33 -3
View File
@@ -4,7 +4,8 @@ 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 { useAsync } from "../../hooks/useAsync";
import { columnLabel, errorMessage } from "../../lib/format";
import { isoDate, maxLength, numeric, required, useValidation, type Rule } from "../../lib/validation";
import type { CsvRow, CsvTable, FormOwner, Profile, User } from "../../types";
@@ -40,10 +41,18 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
() => (table.name === "sales_projection" ? rows.map((r) => ({ name: String(r.product_name || ""), pts: String(r.pts || "") })).filter((p) => p.name) : []),
[table.name, rows],
);
// "Core Dr. Call & Conversion" tracks core doctors only — the field is only ever one of
// the doctors assigned to whoever the row is for, never free text.
const needsDoctors = table.name === "core_dr_call_conversion";
const doctors = useAsync(() => (needsDoctors ? api.doctors() : Promise.resolve([])), [needsDoctors]);
const coreDoctorNames = useMemo(
() => (doctors.data ?? []).filter((d) => d.is_core_doctor).map((d) => d.name),
[doctors.data],
);
const [draft, setDraft] = useState<Record<string, string>>({});
const rulesFor = (c: string): Rule[] => {
const label = humanize(c);
const label = columnLabel(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)];
@@ -108,6 +117,16 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
</Select>
);
}
if (needsDoctors && column === "doctor_name") {
return (
<Select value={value} onChange={(e) => set(column, e.target.value)} onBlur={blur(column)} disabled={doctors.loading}>
<option value="">{doctors.loading ? "Loading doctors…" : "Choose doctor"}</option>
{/* A row imported before this doctor's assignment changed keeps showing its own value. */}
{value && !coreDoctorNames.includes(value) && <option value={value}>{value}</option>}
{coreDoctorNames.map((n) => <option key={n} value={n}>{n}</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)} />;
};
@@ -123,7 +142,18 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
<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>
<Field
key={c}
label={columnLabel(c)}
error={v.errors[c]}
required={table.name === "sales_projection" && c === "product_name"}
hint={
generated(c) ? "Filled in automatically"
: needsDoctors && c === "doctor_name" && !doctors.loading && coreDoctorNames.length === 0 ? "No core doctors are assigned yet — ask your administrator to assign some."
: NUMERIC.has(c) ? "Numbers only"
: undefined
}
>{control(c)}</Field>
))}
</form>
</Modal>