All files / src/components/crm KanbanBoard.tsx

96.59% Statements 85/88
84.31% Branches 43/51
100% Functions 17/17
100% Lines 80/80

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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341                                                                                                                                                                  124x 124x 124x 124x 124x     124x 71x     124x 5x 5x 5x 1x   4x   5x         124x 93x 93x 368x   93x 236x 236x   93x       124x 93x 93x 236x   93x     124x 71x 71x 280x   71x     124x   124x                           8x               8x 8x 8x 3x     3x       8x     1x 1x       8x           124x   13x 13x 13x   11x 11x     11x 8x           8x     3x         124x 5x           5x 5x 2x 2x   5x 2x 2x     5x         5x 5x 5x 5x                 124x 1x 1x 1x 1x     124x 1x                 123x 9x                                               114x                                       456x                         5x                                                
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Contact } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { crmApi } from "../../lib/api";
import type { KanbanData, KanbanLead } from "../../lib/api/pro/crm";
import { parseCurrencyInput } from "../../lib/currency-utils";
import { queryKeys } from "../../lib/query-keys";
import { EmptyState } from "../ui/empty-state";
import { KanbanColumn } from "./KanbanColumn";
import { isTerminalStage } from "./lead-status";
import { LeadsTable } from "./LeadsTable";
import { MobileLeadList } from "./MobileLeadList";
import { StageChangeDialogs, type PendingDrop } from "./StageChangeDialogs";
 
/**
 * The pipeline board — and, behind the ☰ switch, the same leads as rows.
 *
 * `.context/mockups/leads-board.html` prints the board as a fixed number of
 * equal columns that SCROLL SIDEWAYS rather than wrap, "because a stage must
 * never fall below another stage". That is why this is a `grid-flow-col` with
 * an `auto-cols` track and not one of the design system's `grid-2`/`grid-3`
 * helpers — the mockup carries the same page-local rule, under a comment
 * saying "layout only: no new colour, no new radius, no new type size".
 *
 * This component owns ONE thing beyond layout: the stage-change mutation and
 * its Won/Lost dialogs, because dropping a card is how a stage changes. The
 * quick-note and quick-reminder dialogs are the page's, since the overdue band
 * above the board opens the same note dialog and two owners would mean two
 * dialogs.
 *
 * STAFF CANNOT MOVE A LEAD, so `canChangeStage` is threaded all the way to the
 * card: no `draggable`, no drop target, no stage dialog. See
 * `lead-write-scope.ts` for why, and for the allowlist it mirrors.
 */
 
// ─── Types ───────────────────────────────────────────────────────────────────
 
export type LeadsView = "board" | "table";
 
type KanbanBoardProps = {
	proId: string;
	/** The full payload — stages and their counts come from here. */
	data: KanbanData;
	/**
	 * The leads to show, already filtered and sorted by the page. Defaults to
	 * every lead in `data`, so the board is usable without a filter bar.
	 */
	leads?: readonly KanbanLead[];
	/** Board (default) or the same leads as ruled rows. */
	view?: LeadsView;
	/** One reading of the clock for the whole page. Defaults to this render's. */
	now?: number;
	/** False for staff. Hides every control the API would refuse. */
	canChangeStage?: boolean;
	/**
	 * The lead the page is currently ABOUT — the one whose dialog is open. The
	 * table gives it the page's one 3px index-red inset bar, which is the whole
	 * of the Index Red Rule: it marks the current item and nothing else. Never
	 * a state; a lead is not "current" because it is overdue.
	 */
	currentLeadId?: number | null;
	/** Absent when the member may not create a lead. */
	onAddLead?: () => void;
	onQuickNote?: (leadId: number) => void;
	onQuickReminder?: (leadId: number) => void;
};
 
// ─── Component ───────────────────────────────────────────────────────────────
 
export function KanbanBoard({
	proId,
	data,
	leads = data.leads,
	view = "board",
	now = Date.now(),
	canChangeStage = true,
	currentLeadId = null,
	onAddLead,
	onQuickNote,
	onQuickReminder,
}: KanbanBoardProps) {
	const queryClient = useQueryClient();
	const [pendingDrop, setPendingDrop] = useState<PendingDrop | null>(null);
	const [lossReasonCategory, setLossReasonCategory] = useState("");
	const [lossReason, setLossReason] = useState("");
	const [orderValue, setOrderValue] = useState("");
 
	// Terminal columns default to expanded (users can still collapse manually)
	const [collapsedColumns, setCollapsedColumns] = useState<Set<number>>(
		() => new Set<number>(),
	);
 
	const toggleCollapse = useCallback((stageId: number) => {
		setCollapsedColumns((prev) => {
			const next = new Set(prev);
			if (next.has(stageId)) {
				next.delete(stageId);
			} else {
				next.add(stageId);
			}
			return next;
		});
	}, []);
 
	// Group the visible leads by stage
	const leadsByStage = useMemo(() => {
		const map = new Map<number, KanbanLead[]>();
		for (const stage of data.stages) {
			map.set(stage.id, []);
		}
		for (const lead of leads) {
			const arr = map.get(lead.currentStageId);
			Eif (arr) arr.push(lead);
		}
		return map;
	}, [data.stages, leads]);
 
	// Lead lookup for O(1) access in handleDrop
	const leadMap = useMemo(() => {
		const map = new Map<number, KanbanLead>();
		for (const lead of leads) {
			map.set(lead.id, lead);
		}
		return map;
	}, [leads]);
 
	const stageMap = useMemo(() => {
		const map = new Map<number, (typeof data.stages)[number]>();
		for (const stage of data.stages) {
			map.set(stage.id, stage);
		}
		return map;
	}, [data.stages]);
 
	const kanbanQueryKey = queryKeys.crm.kanban(proId);
 
	const changeStageMutation = useMutation({
		mutationFn: async ({
			leadId,
			stageId,
			orderValuePaise,
			lossReason: reason,
			lossReasonCategory: category,
		}: {
			leadId: number;
			stageId: number;
			orderValuePaise?: number;
			lossReason?: string;
			lossReasonCategory?: string;
		}) => {
			return crmApi.changeStage(proId, leadId, {
				stageId,
				orderValuePaise,
				lossReason: reason,
				lossReasonCategory: category,
			});
		},
		onMutate: async ({ leadId, stageId }) => {
			await queryClient.cancelQueries({ queryKey: kanbanQueryKey });
			const previous = queryClient.getQueryData<KanbanData>(kanbanQueryKey);
			if (previous) {
				queryClient.setQueryData<KanbanData>(kanbanQueryKey, {
					...previous,
					leads: previous.leads.map((l) =>
						l.id === leadId ? { ...l, currentStageId: stageId } : l,
					),
				});
			}
			return { previous };
		},
		onError: (_err, _vars, context) => {
			Eif (context?.previous) {
				queryClient.setQueryData(kanbanQueryKey, context.previous);
			}
		},
		onSettled: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.all,
			});
		},
	});
 
	const handleDrop = useCallback(
		(leadId: number, stageId: number) => {
			Iif (!canChangeStage) return;
			const lead = leadMap.get(leadId);
			if (!lead || lead.currentStageId === stageId) return;
 
			const targetStage = stageMap.get(stageId);
			Iif (!targetStage) return;
 
			// Won/Lost require confirmation
			if (isTerminalStage(targetStage.stageType)) {
				setPendingDrop({
					leadId,
					stageId,
					stageName: targetStage.name,
					stageType: targetStage.stageType,
				});
				return;
			}
 
			changeStageMutation.mutate({ leadId, stageId });
		},
		[canChangeStage, leadMap, stageMap, changeStageMutation],
	);
 
	const confirmDrop = useCallback(() => {
		Iif (!pendingDrop) return;
 
		const extras: {
			orderValuePaise?: number;
			lossReason?: string;
			lossReasonCategory?: string;
		} = {};
		if (pendingDrop.stageType === "system_terminal_won" && orderValue) {
			const parsed = parseCurrencyInput(orderValue);
			Eif (parsed && parsed > 0) extras.orderValuePaise = parsed;
		}
		if (pendingDrop.stageType === "system_terminal_lost") {
			if (lossReasonCategory) extras.lossReasonCategory = lossReasonCategory;
			if (lossReason) extras.lossReason = lossReason;
		}
 
		changeStageMutation.mutate({
			leadId: pendingDrop.leadId,
			stageId: pendingDrop.stageId,
			...extras,
		});
		setPendingDrop(null);
		setLossReasonCategory("");
		setLossReason("");
		setOrderValue("");
	}, [
		pendingDrop,
		orderValue,
		lossReasonCategory,
		lossReason,
		changeStageMutation,
	]);
 
	const cancelDrop = useCallback(() => {
		setPendingDrop(null);
		setLossReasonCategory("");
		setLossReason("");
		setOrderValue("");
	}, []);
 
	if (data.stages.length === 0) {
		return (
			<EmptyState
				icon={Contact}
				title="Setting up your pipeline"
				description="Your pipeline is being set up. Refresh the page in a moment."
			/>
		);
	}
 
	if (view === "table") {
		return (
			<>
				<LeadsTable
					leads={leads}
					stages={data.stages}
					now={now}
					currentLeadId={currentLeadId}
				/>
				<StageChangeDialogs
					pendingDrop={pendingDrop}
					orderValue={orderValue}
					onOrderValueChange={setOrderValue}
					lossReasonCategory={lossReasonCategory}
					onLossReasonCategoryChange={setLossReasonCategory}
					lossReason={lossReason}
					onLossReasonChange={setLossReason}
					onConfirm={confirmDrop}
					onCancel={cancelDrop}
					isPending={changeStageMutation.isPending}
				/>
			</>
		);
	}
 
	return (
		<>
			{/* Mobile: the same stages as collapsible sections of rows. */}
			<div className="md:hidden">
				<MobileLeadList
					stages={data.stages}
					leads={leads}
					now={now}
					onAddLead={onAddLead}
					onQuickNote={onQuickNote}
					onQuickReminder={onQuickReminder}
				/>
			</div>
 
			{/*
			 * Desktop: equal columns that scroll sideways, never wrap. The
			 * `auto-cols` track is the mockup's own page-local `.board` rule.
			 */}
			<div className="hidden h-[calc(100vh-22rem)] grid-flow-col auto-cols-[minmax(14rem,1fr)] gap-4 overflow-x-auto pb-2 md:grid">
				{data.stages.map((stage) => (
					<KanbanColumn
						key={stage.id}
						stage={stage}
						leads={leadsByStage.get(stage.id) || []}
						now={now}
						canChangeStage={canChangeStage}
						onDrop={handleDrop}
						onAddLead={
							stage.stageType === "system_entry" ? onAddLead : undefined
						}
						isCollapsed={collapsedColumns.has(stage.id)}
						onToggleCollapse={
							isTerminalStage(stage.stageType)
								? () => toggleCollapse(stage.id)
								: undefined
						}
						onQuickNote={onQuickNote}
						onQuickReminder={onQuickReminder}
					/>
				))}
			</div>
 
			<StageChangeDialogs
				pendingDrop={pendingDrop}
				orderValue={orderValue}
				onOrderValueChange={setOrderValue}
				lossReasonCategory={lossReasonCategory}
				onLossReasonCategoryChange={setLossReasonCategory}
				lossReason={lossReason}
				onLossReasonChange={setLossReason}
				onConfirm={confirmDrop}
				onCancel={cancelDrop}
				isPending={changeStageMutation.isPending}
			/>
		</>
	);
}