--
This commit is contained in:
@@ -1,16 +1,20 @@
|
||||
import { type FormEvent, useState } from "react";
|
||||
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 } from "../../types";
|
||||
|
||||
export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void;
|
||||
/** Pre-selects a doctor/chemist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
|
||||
export interface VisitPreset { kind: "doctor" | "chemist"; targetId: string; key: number }
|
||||
|
||||
export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
||||
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const products = useAsync(api.stockInventory, []);
|
||||
@@ -20,27 +24,43 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
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 [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 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 : chemists;
|
||||
// Visit times are local; today's report cannot hold a visit later than now.
|
||||
const isToday = dcr.report_date === todayISO();
|
||||
const isToday = !isPlan && dcr.report_date === todayISO();
|
||||
const timeLabel = isPlan ? "Planned time" : "Visit time";
|
||||
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")],
|
||||
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, promote, sample, pob, 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);
|
||||
|
||||
@@ -50,16 +70,20 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = kind === "doctor"
|
||||
const updated = 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.trim() || null, product_sample: sample.trim() || null, remarks: remarks.trim() || 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(`${label} visit added`);
|
||||
setTargetId(""); setPromote(""); setSample(""); setPob(""); setRemarks("");
|
||||
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
|
||||
@@ -69,7 +93,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="form-grid" onSubmit={submit} noValidate>
|
||||
<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 "doctor" | "chemist"); setTargetId(""); v.clear(); }}>
|
||||
@@ -77,18 +101,18 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
<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}>
|
||||
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : `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>
|
||||
<option value="">{isSelf ? `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="Visit time" required error={v.errors.time}>
|
||||
<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>
|
||||
{kind === "doctor" && (
|
||||
{!isPlan && kind === "doctor" && (
|
||||
<Field label="Outcome">
|
||||
<Select value={outcome} onChange={(e) => setOutcome(e.target.value)}>
|
||||
<option value="MET">Met</option>
|
||||
@@ -97,7 +121,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
{selectedDoctor?.is_core_doctor && (
|
||||
{!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>
|
||||
@@ -107,28 +131,28 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
{kind === "doctor" ? (
|
||||
{isPlan ? null : 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 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 sample" error={v.errors.sample}>
|
||||
<Input list="product-suggestions" value={sample} onChange={on("sample", setSample)} onBlur={blur("sample")} placeholder="Sample given, if any" />
|
||||
<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>
|
||||
<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 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}>Add {kind} visit</Button>
|
||||
<Button type="submit" variant="primary" icon="plus" loading={busy}>{isPlan ? `Add ${kind} to plan` : `Add ${kind} visit`}</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user