All files / src/components/crm NoteForm.tsx

96.73% Statements 89/92
92% Branches 69/75
95.23% Functions 20/21
96.59% Lines 85/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307                            4x                 4x                             155x 155x 155x 155x 155x 155x     155x 84x     155x     155x   155x 155x 155x 155x   155x 11x     11x     11x         155x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     155x   7x   6x 6x     1x       155x   7x   6x 6x 6x       6x 1x   5x 5x       1x       155x   15x 15x   15x 1x 1x   14x 1x 1x       13x 7x 7x 1x 1x 1x     7x 2x 2x   7x 7x       6x 6x 6x 1x 1x   6x 1x     6x         155x   155x                                                 4x                         42x                     12x           602x   447x                               1x                             1x         16x                     1x                                                                    
import { useState, useCallback } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { MessageSquarePlus, AlertCircle } from "lucide-react";
import { crmApi } from "../../lib/api";
import { notify } from "../../lib/notify";
import type { Lead, PipelineStage, AddNoteInput, ChangeStageInput } from "../../lib/api/pro/crm";
import { queryKeys } from "../../lib/query-keys";
import { parseCurrencyInput } from "../../lib/currency-utils";
import { LOSS_REASON_OPTIONS } from "../../lib/crm-constants";
import { Button } from "../ui/button";
import { CharCountTextarea } from "../ui/char-count-textarea";
 
// ─── Constants ───────────────────────────────────────────────────────────────
 
const CONTACT_METHODS = [
	{ value: "call", label: "Call" },
	{ value: "whatsapp", label: "WhatsApp" },
	{ value: "site_visit", label: "Site Visit" },
	{ value: "showroom_visit", label: "Showroom Visit" },
	{ value: "video_call", label: "Video Call" },
	{ value: "other", label: "Other" },
];
 
const MAX_NOTE_LENGTH = 2000;
 
// ─── Component ───────────────────────────────────────────────────────────────
 
type NoteFormProps = {
	lead: Lead;
	proId: string;
	stages: PipelineStage[];
	/** Called after successful submission (for closing modal) */
	onClose?: () => void;
	/** When true, renders without card border/background (for use inside modal) */
	bare?: boolean;
};
 
export function NoteForm({ lead, proId, stages, onClose, bare }: NoteFormProps) {
	const queryClient = useQueryClient();
	const [content, setContent] = useState("");
	const [isContacted, setIsContacted] = useState(false);
	const [contactMethod, setContactMethod] = useState("call");
	const [newStageId, setNewStageId] = useState<number | "">("");
	const [error, setError] = useState<string | null>(null);
 
	// Won/Lost inline prompts
	const selectedStage = newStageId
		? stages.find((s) => s.id === Number(newStageId))
		: null;
	const isTerminalStage =
		selectedStage?.stageType === "system_terminal_won" ||
		selectedStage?.stageType === "system_terminal_lost";
	const showOrderPrompt =
		selectedStage?.stageType === "system_terminal_won";
	const showLossPrompt =
		selectedStage?.stageType === "system_terminal_lost";
	const [orderValue, setOrderValue] = useState("");
	const [lossReason, setLossReason] = useState("");
	const [lossReasonCategory, setLossReasonCategory] = useState("");
 
	const invalidateQueries = useCallback(() => {
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.activities(proId, String(lead.id)),
		});
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.lead(proId, String(lead.id)),
		});
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.kanban(proId),
		});
	}, [queryClient, proId, lead.id]);
 
	const resetForm = useCallback(() => {
		setContent("");
		setIsContacted(false);
		setContactMethod("call");
		setNewStageId("");
		setOrderValue("");
		setLossReason("");
		setLossReasonCategory("");
		setError(null);
		notify.success("Note added successfully");
		onClose?.();
	}, [onClose]);
 
	const addNoteMutation = useMutation({
		mutationFn: async (data: AddNoteInput) =>
			crmApi.addNote(proId, lead.id, data),
		onSuccess: () => {
			invalidateQueries();
			resetForm();
		},
		onError: (err: Error) => {
			setError(err.message || "Failed to add note");
		},
	});
 
	const changeStageMutation = useMutation({
		mutationFn: async (data: ChangeStageInput) =>
			crmApi.changeStage(proId, lead.id, data),
		onSuccess: () => {
			const noteData: AddNoteInput = {};
			if (content.trim()) noteData.content = content.trim();
			Iif (isContacted) {
				noteData.isContacted = true;
				noteData.contactMethod = contactMethod;
			}
			if (Object.keys(noteData).length > 0) {
				addNoteMutation.mutate(noteData);
			} else {
				invalidateQueries();
				resetForm();
			}
		},
		onError: (err: Error) => {
			setError(err.message || "Failed to change stage");
		},
	});
 
	const handleSubmit = useCallback(
		(e: React.FormEvent) => {
			e.preventDefault();
			setError(null);
 
			if (isContacted && !content.trim()) {
				setError("Note is required when marking as contacted");
				return;
			}
			if (!content.trim() && !isContacted && !newStageId) {
				setError("Please enter a note, mark as contacted, or change the stage");
				return;
			}
 
			// Terminal stage -> use changeStage API
			if (isTerminalStage && newStageId) {
				const stageInput: ChangeStageInput = { stageId: Number(newStageId) };
				if (showOrderPrompt && orderValue.trim()) {
					const paise = parseCurrencyInput(orderValue);
					Eif (paise !== null && paise >= 0) {
						stageInput.orderValuePaise = paise;
					}
				}
				if (showLossPrompt) {
					if (lossReason.trim()) stageInput.lossReason = lossReason.trim();
					if (lossReasonCategory) stageInput.lossReasonCategory = lossReasonCategory;
				}
				changeStageMutation.mutate(stageInput);
				return;
			}
 
			// Non-terminal -> use addNote with optional stage change
			const data: AddNoteInput = {};
			Eif (content.trim()) data.content = content.trim();
			if (isContacted) {
				data.isContacted = true;
				data.contactMethod = contactMethod;
			}
			if (newStageId && Number(newStageId) !== lead.currentStageId) {
				data.newStageId = Number(newStageId);
			}
 
			addNoteMutation.mutate(data);
		},
		[content, isContacted, contactMethod, newStageId, lead.currentStageId, addNoteMutation, changeStageMutation, isTerminalStage, showOrderPrompt, showLossPrompt, orderValue, lossReason, lossReasonCategory],
	);
 
	const isPending = addNoteMutation.isPending || changeStageMutation.isPending;
 
	return (
		<div className={bare ? "" : "rounded-lg border border-border-default bg-background-elevated p-4"}>
			{!bare && (
				<h3 className="text-sm font-semibold text-foreground-default mb-3 flex items-center gap-2">
					<MessageSquarePlus className="h-4 w-4 text-foreground-subtle" />
					Add Note
				</h3>
			)}
 
			<form onSubmit={handleSubmit} className="space-y-3">
				<CharCountTextarea
					value={content}
					onChange={setContent}
					maxLength={MAX_NOTE_LENGTH}
					rows={4}
					placeholder="Add a note about this lead..."
					disabled={isPending}
				/>
 
				<div className="space-y-2">
					<div className="flex flex-wrap items-center gap-3">
						<label className="flex items-center gap-2 text-sm cursor-pointer">
							<input
								type="checkbox"
								checked={isContacted}
								onChange={(e) => setIsContacted(e.target.checked)}
								className="rounded border-border-default text-primary-500 focus:ring-primary-500"
							/>
							<span className="text-foreground-default">Contacted</span>
						</label>
 
						{isContacted && (
							<select
								value={contactMethod}
								onChange={(e) => setContactMethod(e.target.value)}
								className="h-8 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
							>
								{CONTACT_METHODS.map((m) => (
									<option key={m.value} value={m.value}>
										{m.label}
									</option>
								))}
							</select>
						)}
					</div>
 
					<select
						value={newStageId}
						onChange={(e) =>
							setNewStageId(e.target.value ? Number(e.target.value) : "")
						}
						className="w-full h-8 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
					>
						<option value="">No stage change</option>
						{stages
							.filter((s) => s.id !== lead.currentStageId)
							.map((s) => (
								<option key={s.id} value={s.id}>
									Move to {s.name}
								</option>
							))}
					</select>
				</div>
 
				{showOrderPrompt && (
					<div className="p-3 rounded-md bg-success/5 border border-success/20">
						<label htmlFor="note-order-value" className="block text-sm font-medium text-foreground-default mb-1">
							Order Value (optional)
						</label>
						<input
							id="note-order-value"
							type="text"
							value={orderValue}
							onChange={(e) => setOrderValue(e.target.value)}
							placeholder="e.g., 4.2L or 420000"
							className="h-8 w-full px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
						/>
					</div>
				)}
 
				{showLossPrompt && (
					<div className="p-3 rounded-md bg-error/5 border border-error/20 space-y-2">
						<label htmlFor="note-loss-category" className="block text-sm font-medium text-foreground-default">
							Loss Reason Category
						</label>
						<select
							id="note-loss-category"
							value={lossReasonCategory}
							onChange={(e) => setLossReasonCategory(e.target.value)}
							className="h-8 w-full px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
						>
							<option value="">Select category</option>
							{LOSS_REASON_OPTIONS.map((opt) => (
								<option key={opt.value} value={opt.value}>
									{opt.label}
								</option>
							))}
						</select>
						<label htmlFor="note-loss-reason" className="block text-sm font-medium text-foreground-default">
							Details (optional)
						</label>
						<textarea
							id="note-loss-reason"
							value={lossReason}
							onChange={(e) => setLossReason(e.target.value)}
							rows={2}
							placeholder="Why was this lead lost?"
							className="w-full px-2 py-1.5 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 resize-none"
						/>
					</div>
				)}
 
				{error && (
					<div className="flex items-center gap-1.5 text-sm text-error">
						<AlertCircle className="h-3.5 w-3.5 flex-shrink-0" />
						{error}
					</div>
				)}
 
				<div className={onClose ? "flex justify-end gap-3 pt-2" : ""}>
					{onClose && (
						<Button type="button" variant="outline" onClick={onClose}>
							Cancel
						</Button>
					)}
					<Button
						type="submit"
						size="sm"
						className={onClose ? "" : "w-full"}
						isLoading={isPending}
					>
						{isTerminalStage ? (showOrderPrompt ? "Mark as Won" : "Mark as Lost") : "Add Note"}
					</Button>
				</div>
			</form>
		</div>
	);
}