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 = { 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(null); const [kind, setKind] = useState("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([]); const [sample, setSample] = useState([]); const [pob, setPob] = useState(""); const [gift, setGift] = useState(""); const [remarks, setRemarks] = useState(""); const [busy, setBusy] = useState(false); const formRef = useRef(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) { 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 (
{error} {!isPlan && kind === "doctor" && ( )} {!isPlan && selectedDoctor?.is_core_doctor && ( )} {isPlan ? null : kind === "doctor" ? ( <> ) : ( )}