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 { 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"; 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], ); // "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>({}); const rulesFor = (c: string): Rule[] => { 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)]; 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(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) { 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 set("product_name", e.target.value)} onBlur={blur("product_name")} />; } if (table.name === "sales_projection" && column === "product_name") { return ( ); } if (column === "month") { return ( ); } if (needsDoctors && column === "doctor_name") { return ( ); } return set(column, e.target.value)} onBlur={blur(column)} />; }; return ( } >
{error} {columns.map((c) => ( {control(c)} ))}
); }