Production
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user