Files
celtic-life-science/web/src/components/reports/AddVisitForm.tsx
T
Shubhankar45 0d30c58bf0 Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
2026-11-07 05:43:12 +00:00

167 lines
8.9 KiB
TypeScript

import { type FormEvent, useEffect, useRef, 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 { ProductPicker } from "./ProductPicker";
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, Stockist } from "../../types";
export type VisitKind = "doctor" | "chemist" | "stockist";
/** Pre-selects a doctor/chemist/stockist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
export interface VisitPreset { kind: VisitKind; targetId: string; key: number }
const KIND_LABEL: Record<VisitKind, string> = { doctor: "Doctor", chemist: "Chemist", stockist: "Stockist" };
export function AddVisitForm({ dcr, doctors, chemists, stockists, onChange, preset }: {
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; stockists: Stockist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
}) {
const toast = useToast();
const products = useAsync(api.stockInventory, []);
const [error, setError] = useState<string | null>(null);
const [kind, setKind] = useState<VisitKind>("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<string[]>([]);
const [sample, setSample] = useState<string[]>([]);
const [pob, setPob] = useState("");
const [gift, setGift] = useState("");
const [remarks, setRemarks] = useState("");
const [busy, setBusy] = useState(false);
const formRef = useRef<HTMLFormElement>(null);
// A day plan records who and when only; outcomes, products and POB come at the end of the day.
const isPlan = dcr.report_type === "PLAN";
// An Area Business Manager's own report lists the headquarters' doctors and chemists, not assigned ones.
const isSelf = dcr.report_type === "SELF";
const productNames = (products.data ?? []).map((p) => p.product_name);
useEffect(() => {
if (!preset) return;
setKind(preset.kind);
setTargetId(preset.targetId);
setTime(nowHHMM());
v.clear();
formRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
}, [preset?.key]);
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
const options = kind === "doctor" ? doctors : kind === "chemist" ? chemists : stockists;
// Visit times are local; today's report cannot hold a visit later than now.
const isToday = !isPlan && dcr.report_date === todayISO();
const timeLabel = isPlan ? "Planned time" : "Visit time";
const label = KIND_LABEL[kind];
const v = useValidation({
target: [required(label)],
time: [required(timeLabel), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
pob: [maxLength(100, "POB"), amount("POB")],
gift: [maxLength(200, "Gift")],
remarks: [maxLength(2000, "Remarks")],
});
const values = () => ({ target: targetId, time, pob, gift, 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 === "stockist"
? await api.addStockistCall(dcr.id, { stockist_id: targetId, visit_time: time, pob: isPlan ? null : pob.trim() || null, remarks: remarks.trim() || null })
: isPlan
? kind === "doctor"
? await api.addDoctorCall(dcr.id, { doctor_id: targetId, visit_time: time, remarks: remarks.trim() || null })
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, remarks: remarks.trim() || null })
: 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, product_sample: sample, gift: gift.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(isPlan ? `${label} added to the plan` : `${label} visit added`);
setTargetId(""); setPromote([]); setSample([]); setPob(""); setGift(""); 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 ref={formRef} className="form-grid" onSubmit={submit} noValidate>
<Alert>{error}</Alert>
<Field label="Visit type">
<Select value={kind} onChange={(e) => { setKind(e.target.value as VisitKind); setTargetId(""); v.clear(); }}>
<option value="doctor">Doctor</option>
<option value="chemist">Chemist</option>
<option value="stockist">Stockist</option>
</Select>
</Field>
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : kind === "stockist" ? "Your headquarters has no stockists yet — ask your administrator to add some." : `No ${kind}s are assigned to you yet — ask your administrator to assign some.`) : undefined}>
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
<option value="">{isSelf || kind === "stockist" ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
{options.map((o) => (
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
))}
</Select>
</Field>
<Field label={timeLabel} required error={v.errors.time}>
<Input type="time" value={time} max={isToday ? nowHHMM() : undefined} onChange={on("time", setTime)} onBlur={blur("time")} />
</Field>
{!isPlan && 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>
)}
{!isPlan && 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>
)}
{isPlan ? null : kind === "doctor" ? (
<>
<Field label="Products promoted" hint={`${promote.length} chosen`}>
<ProductPicker value={promote} onChange={setPromote} suggestions={productNames} listId="promote-suggestions" placeholder="Pick or type a product" />
</Field>
<Field label="Product samples" hint={`${sample.length} chosen`}>
<ProductPicker value={sample} onChange={setSample} suggestions={productNames} listId="sample-suggestions" placeholder="Samples given, if any" />
</Field>
<Field label="Gift" error={v.errors.gift} hint="Optional — any gift given to the doctor on this visit">
<Input value={gift} onChange={on("gift", setGift)} onBlur={blur("gift")} placeholder="e.g. Diary, pen" />
</Field>
</>
) : (
<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={isPlan ? "Purpose / note" : "Remarks"} span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} placeholder={isPlan ? "Optional, e.g. follow up on samples" : undefined} />
</Field>
<div className="form-actions">
<Button type="submit" variant="primary" icon="plus" loading={busy}>{isPlan ? `Add ${kind} to plan` : `Add ${kind} visit`}</Button>
</div>
</form>
);
}