All files / src/pages/settings pipeline.tsx

90.59% Statements 106/117
74.73% Branches 71/95
86.27% Functions 44/51
92.66% Lines 101/109

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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608                                                                                                                43x 43x 43x   43x               43x 1x                                                                                                                       122x                                                               1113x   231x   231x   231x   420x         742x         2x                 77x 77x 77x 77x 77x 77x   77x 7x     77x 2x   2x 2x             77x   2x   2x 2x             77x     1x 1x     1x 1x             77x 2x             77x   3x 3x 2x   1x           77x   3x 3x 2x           77x   2x 5x 2x   2x 2x 2x     2x       10x           77x 371x 140x 77x   77x                     371x 371x 371x 371x 371x   371x   371x                     4x   3x 3x           1x                 1x                                                       1x                       1x                               6x 6x                   4x                                               4x                                                       1x 1x                 52x 52x 52x   52x 4x     52x 2x   2x 2x             52x 1x             52x 1x             52x   3x 3x 2x           52x                     156x                                                                   2x                                                           3x                                  
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate } from "@tanstack/react-router";
import {
	ArrowLeft,
	Check,
	ChevronDown,
	ChevronUp,
	Lock,
	Pencil,
	Plus,
	ToggleLeft,
	ToggleRight,
	Trash2,
	X,
} from "lucide-react";
import { useCallback, useState } from "react";
import { leadWriteScope } from "../../components/crm/lead-write-scope";
import { Button } from "../../components/ui/button";
import { ConfirmDialog } from "../../components/ui/confirm-dialog";
import { Input } from "../../components/ui/input";
import { MobileFullPage } from "../../components/ui/mobile-full-page";
import { StatusBadge } from "../../components/ui/status-badge";
import { StickyPageHeader } from "../../components/ui/sticky-page-header";
import {
	useLeadSourcesWithInactive,
	usePipelineStages,
} from "../../hooks/queries/useCrmQueries";
import { crmApi } from "../../lib/api";
import type { PipelineStage } from "../../lib/api/pro/crm";
import { notify } from "../../lib/notify";
import { usePro } from "../../lib/pro-context";
import { queryKeys } from "../../lib/query-keys";
import { cn } from "../../lib/utils";
 
/**
 * `/settings/pipeline` — the stages leads move through, and where they come
 * from.
 *
 * This page was titled "CRM Settings" after the route rename moved it off
 * `/crm/settings`. "CRM" is jargon for a one-person studio; the two things on
 * this page are a pipeline and a list of sources, so that is what it says.
 *
 * In the Job Book idiom both lists are RULED ROWS under a quiet band, not
 * bordered chips in a bordered card: hairlines, not boxes. A system stage
 * carries a printed code (ENTRY / WON / LOST), never a pill.
 *
 * STAFF SEE THIS PAGE READ-ONLY. None of `/crm/stages*` or `/crm/sources*` is
 * on the server's staff write allowlist, so every mutation here would 403.
 * `canConfigurePipeline` is a separate capability from `canChangeStage` — one
 * is "reshape the pipeline", the other is "move one lead" — and the gate is
 * the first.
 */
 
// ─── Page ────────────────────────────────────────────────────────────────────
 
export function PipelineSettingsPage() {
	const { proId, proRole } = usePro();
	const navigate = useNavigate();
	const scope = leadWriteScope(proRole);
 
	Iif (!proId) {
		return (
			<div className="flex h-64 items-center justify-center">
				<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary-600" />
			</div>
		);
	}
 
	return (
		<MobileFullPage title="Pipeline" onBack={() => navigate({ to: "/leads" })}>
			<div className="max-w-3xl space-y-6 p-4 sm:p-0">
				{/* Header — desktop only (MobileFullPage provides the mobile one). */}
				<div className="hidden sm:block">
					<StickyPageHeader>
						<div className="flex items-center gap-3">
							<Link
								to="/leads"
								className="text-foreground-muted transition-colors hover:text-foreground-default"
								title="Back to leads"
							>
								<ArrowLeft className="h-5 w-5" aria-hidden="true" />
								<span className="sr-only">Back to leads</span>
							</Link>
							<h1 className="text-xl font-semibold text-foreground-default">
								Pipeline
							</h1>
						</div>
					</StickyPageHeader>
				</div>
 
				{/* The section rule, with the mockup's 3px index-red inset bar. */}
				<div className="relative border-t border-border-strong">
					<span
						aria-hidden="true"
						className="absolute -top-px left-0 h-0.75 w-10 bg-index"
					/>
				</div>
 
				{!scope.canConfigurePipeline && (
					<p className="text-sm text-foreground-muted">
						You can see how the pipeline is set up. Changing the stages or the
						lead sources needs a manager or owner.
					</p>
				)}
 
				<PipelineConfig proId={proId} canEdit={scope.canConfigurePipeline} />
				<SourceConfig proId={proId} canEdit={scope.canConfigurePipeline} />
			</div>
		</MobileFullPage>
	);
}
 
// ─── A quiet band over a ruled list ──────────────────────────────────────────
 
/**
 * The shared section head. `.band .band-quiet`: a 3px `--border-strong`
 * marker, a `.label` name, a right-aligned tabular count, the strong hairline.
 */
function SectionBand({
	id,
	title,
	count,
	hint,
}: {
	id: string;
	title: string;
	count: number;
	hint: string;
}) {
	return (
		<>
			<div className="flex items-center gap-2 border-b border-border-strong pb-1.5">
				<span
					aria-hidden="true"
					className="h-[1.05em] w-0.75 shrink-0 rounded-[1px] bg-border-strong"
				/>
				<h2
					id={id}
					className="flex-1 text-xs font-semibold uppercase tracking-wider text-foreground-muted"
				>
					{title}
				</h2>
				<span className="text-xs font-semibold tabular-nums text-foreground-muted">
					{count}
				</span>
			</div>
			<p className="mt-1.5 text-sm text-foreground-muted">{hint}</p>
		</>
	);
}
 
/**
 * A system stage's ROLE — entry, won, lost — or null for a stage you created.
 *
 * Printed as `.label` caps rather than through `StatusBadge`, on purpose. A
 * printed status code says what state a thing is IN; a stage's type says what
 * the stage is FOR, which never changes. Running it through the status
 * registry would also mean inventing an "ENTRY" status, and the vocabulary is
 * closed.
 */
function systemStageRole(stageType: PipelineStage["stageType"]): string | null {
	switch (stageType) {
		case "system_entry":
			return "Entry";
		case "system_terminal_won":
			return "Won";
		case "system_terminal_lost":
			return "Lost";
		default:
			return null;
	}
}
 
function isSystemStage(stage: PipelineStage): boolean {
	return systemStageRole(stage.stageType) !== null;
}
 
// ─── Pipeline stages ─────────────────────────────────────────────────────────
 
const MAX_CUSTOM_STAGES = 5;
 
function PipelineConfig({
	proId,
	canEdit,
}: {
	proId: string;
	canEdit: boolean;
}) {
	const queryClient = useQueryClient();
	const { data: stages } = usePipelineStages(proId);
	const [editingId, setEditingId] = useState<number | null>(null);
	const [editName, setEditName] = useState("");
	const [newName, setNewName] = useState("");
	const [deleteTarget, setDeleteTarget] = useState<PipelineStage | null>(null);
 
	const invalidateStages = useCallback(() => {
		queryClient.invalidateQueries({ queryKey: queryKeys.crm.all });
	}, [queryClient]);
 
	const createMutation = useMutation({
		mutationFn: (name: string) => crmApi.createStage(proId, { name }),
		onSuccess: () => {
			invalidateStages();
			setNewName("");
		},
		onError: (err: Error) => {
			notify.error(err.message || "Failed to create stage");
		},
	});
 
	const renameMutation = useMutation({
		mutationFn: ({ stageId, name }: { stageId: number; name: string }) =>
			crmApi.updateStage(proId, stageId, { name }),
		onSuccess: () => {
			invalidateStages();
			setEditingId(null);
		},
		onError: (err: Error) => {
			notify.error(err.message || "Failed to rename stage");
		},
	});
 
	const deleteMutation = useMutation({
		mutationFn: (stageId: number) => {
			// Reassign to the entry stage
			const entry = stages?.find((s) => s.stageType === "system_entry");
			return crmApi.deleteStage(proId, stageId, entry?.id);
		},
		onSuccess: () => {
			invalidateStages();
			setDeleteTarget(null);
		},
		onError: (err: Error) => {
			notify.error(err.message || "Failed to delete stage");
		},
	});
 
	const reorderMutation = useMutation({
		mutationFn: (stageIds: number[]) => crmApi.reorderStages(proId, stageIds),
		onSuccess: invalidateStages,
		onError: (err: Error) => {
			notify.error(err.message || "Failed to reorder stages");
		},
	});
 
	const handleRename = useCallback(
		(stageId: number) => {
			const trimmed = editName.trim();
			if (trimmed) {
				renameMutation.mutate({ stageId, name: trimmed });
			} else {
				setEditingId(null);
			}
		},
		[editName, renameMutation],
	);
 
	const handleAddStage = useCallback(
		(e: React.FormEvent) => {
			e.preventDefault();
			if (newName.trim()) {
				createMutation.mutate(newName.trim());
			}
		},
		[newName, createMutation],
	);
 
	const handleMoveStage = useCallback(
		(stageId: number, direction: "up" | "down") => {
			Iif (!stages) return;
			const currentIndex = stages.findIndex((s) => s.id === stageId);
			Iif (currentIndex < 0) return;
 
			const newStages = [...stages];
			const swapIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1;
			Iif (swapIndex < 0 || swapIndex >= newStages.length) return;
 
			// Swap
			[newStages[currentIndex], newStages[swapIndex]] = [
				newStages[swapIndex],
				newStages[currentIndex],
			];
			reorderMutation.mutate(newStages.map((s) => s.id));
		},
		[stages, reorderMutation],
	);
 
	// Custom (non-system) stages in order, for the move constraints
	const customStageIds = (stages || [])
		.filter((s) => !isSystemStage(s))
		.map((s) => s.id);
	const atStageLimit = customStageIds.length >= MAX_CUSTOM_STAGES;
 
	return (
		<section aria-labelledby="pipeline-stages">
			<SectionBand
				id="pipeline-stages"
				title="Pipeline stages"
				count={(stages || []).length}
				hint="The stages a lead moves through, in order. The entry, Won and Lost stages are fixed."
			/>
 
			<ul className="mt-2.5 overflow-hidden rounded-lg bg-background-elevated shadow-card">
				{(stages || []).map((stage) => {
					const isSystem = isSystemStage(stage);
					const isEditing = editingId === stage.id;
					const role = systemStageRole(stage.stageType);
					const customIdx = customStageIds.indexOf(stage.id);
					const canMoveUp = !isSystem && customIdx > 0;
					const canMoveDown =
						!isSystem && customIdx < customStageIds.length - 1;
 
					return (
						<li
							key={stage.id}
							className="group flex items-center gap-2 border-t border-border-default px-3.5 py-2 transition-colors first:border-t-0 hover:bg-foreground-default/7"
						>
							{isEditing ? (
								<>
									<Input
										type="text"
										aria-label={`Rename ${stage.name}`}
										value={editName}
										onChange={(e) => setEditName(e.target.value)}
										onKeyDown={(e) => {
											if (e.key === "Enter") handleRename(stage.id);
											if (e.key === "Escape") setEditingId(null);
										}}
										className="h-8"
									/>
									<button
										type="button"
										onClick={() => handleRename(stage.id)}
										className="grid size-6 shrink-0 place-items-center rounded-sm text-foreground-muted hover:text-foreground-default pointer-coarse:size-11"
										title="Save"
									>
										<Check className="h-3.5 w-3.5" aria-hidden="true" />
										<span className="sr-only">Save the new name</span>
									</button>
									<button
										type="button"
										onClick={() => setEditingId(null)}
										className="grid size-6 shrink-0 place-items-center rounded-sm text-foreground-subtle hover:text-foreground-default pointer-coarse:size-11"
										title="Cancel"
									>
										<X className="h-3.5 w-3.5" aria-hidden="true" />
										<span className="sr-only">Cancel the rename</span>
									</button>
								</>
							) : (
								<>
									<span className="min-w-0 flex-1 truncate text-sm text-foreground-default">
										{stage.name}
									</span>
									{role && (
										<span className="text-xs font-semibold uppercase tracking-wider text-foreground-subtle">
											{role}
										</span>
									)}
									{isSystem && (
										<Lock
											className="h-3 w-3 shrink-0 text-foreground-subtle"
											aria-hidden="true"
										/>
									)}
									{canEdit && !isSystem && (
										<span className="flex items-center gap-0.5 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 pointer-coarse:opacity-100">
											<button
												type="button"
												onClick={() => handleMoveStage(stage.id, "up")}
												disabled={!canMoveUp || reorderMutation.isPending}
												className="grid size-6 place-items-center rounded-sm text-foreground-subtle hover:text-foreground-default disabled:cursor-not-allowed disabled:opacity-30 pointer-coarse:size-11"
												title="Move up"
											>
												<ChevronUp className="h-3.5 w-3.5" aria-hidden="true" />
												<span className="sr-only">
													Move {stage.name} earlier
												</span>
											</button>
											<button
												type="button"
												onClick={() => handleMoveStage(stage.id, "down")}
												disabled={!canMoveDown || reorderMutation.isPending}
												className="grid size-6 place-items-center rounded-sm text-foreground-subtle hover:text-foreground-default disabled:cursor-not-allowed disabled:opacity-30 pointer-coarse:size-11"
												title="Move down"
											>
												<ChevronDown
													className="h-3.5 w-3.5"
													aria-hidden="true"
												/>
												<span className="sr-only">
													Move {stage.name} later
												</span>
											</button>
											<button
												type="button"
												onClick={() => {
													setEditingId(stage.id);
													setEditName(stage.name);
												}}
												className="grid size-6 place-items-center rounded-sm text-foreground-subtle hover:text-foreground-default pointer-coarse:size-11"
												title="Rename"
											>
												<Pencil className="h-3 w-3" aria-hidden="true" />
												<span className="sr-only">Rename {stage.name}</span>
											</button>
											<button
												type="button"
												onClick={() => setDeleteTarget(stage)}
												className="grid size-6 place-items-center rounded-sm text-foreground-subtle hover:text-error pointer-coarse:size-11"
												title="Delete"
											>
												<Trash2 className="h-3 w-3" aria-hidden="true" />
												<span className="sr-only">Delete {stage.name}</span>
											</button>
										</span>
									)}
								</>
							)}
						</li>
					);
				})}
			</ul>
 
			{canEdit && (
				<>
					<form onSubmit={handleAddStage} className="mt-3 flex items-center gap-2">
						{/* The comfortable tier (40px): a form you fill in, not a toolbar. */}
						<Input
							type="text"
							aria-label="New stage name"
							value={newName}
							onChange={(e) => setNewName(e.target.value)}
							placeholder="New stage name"
							disabled={atStageLimit}
						/>
						<Button
							type="submit"
							className="shrink-0"
							disabled={!newName.trim() || atStageLimit}
							isLoading={createMutation.isPending}
						>
							<Plus aria-hidden="true" />
							Add stage
						</Button>
					</form>
					{atStageLimit && (
						<p className="mt-2 text-sm text-foreground-subtle">
							{`You have the maximum of ${MAX_CUSTOM_STAGES} stages of your own. Delete one to add another.`}
						</p>
					)}
				</>
			)}
 
			<ConfirmDialog
				open={!!deleteTarget}
				title="Delete stage"
				description={`Delete "${deleteTarget?.name}"? Leads in this stage will be moved to the entry stage.`}
				confirmLabel="Delete"
				variant="destructive"
				onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
				onCancel={() => setDeleteTarget(null)}
			/>
		</section>
	);
}
 
// ─── Lead sources ────────────────────────────────────────────────────────────
 
function SourceConfig({ proId, canEdit }: { proId: string; canEdit: boolean }) {
	const queryClient = useQueryClient();
	const { data: sources } = useLeadSourcesWithInactive(proId);
	const [newName, setNewName] = useState("");
 
	const invalidateSources = useCallback(() => {
		queryClient.invalidateQueries({ queryKey: queryKeys.crm.sources(proId) });
	}, [queryClient, proId]);
 
	const createMutation = useMutation({
		mutationFn: (name: string) => crmApi.createSource(proId, { name }),
		onSuccess: () => {
			invalidateSources();
			setNewName("");
		},
		onError: (err: Error) => {
			notify.error(err.message || "Failed to create source");
		},
	});
 
	const deactivateMutation = useMutation({
		mutationFn: (sourceId: number) => crmApi.deactivateSource(proId, sourceId),
		onSuccess: invalidateSources,
		onError: (err: Error) => {
			notify.error(err.message || "Failed to deactivate source");
		},
	});
 
	const reactivateMutation = useMutation({
		mutationFn: (sourceId: number) => crmApi.reactivateSource(proId, sourceId),
		onSuccess: invalidateSources,
		onError: (err: Error) => {
			notify.error(err.message || "Failed to reactivate source");
		},
	});
 
	const handleAdd = useCallback(
		(e: React.FormEvent) => {
			e.preventDefault();
			if (newName.trim()) {
				createMutation.mutate(newName.trim());
			}
		},
		[newName, createMutation],
	);
 
	return (
		<section aria-labelledby="lead-sources">
			<SectionBand
				id="lead-sources"
				title="Lead sources"
				count={(sources || []).length}
				hint="Where your leads come from. Built-in sources cannot be archived."
			/>
 
			<ul className="mt-2.5 overflow-hidden rounded-lg bg-background-elevated shadow-card">
				{(sources || []).map((source) => (
					<li
						key={source.id}
						className="flex items-center gap-3 border-t border-border-default px-3.5 py-2 transition-colors first:border-t-0 hover:bg-foreground-default/7"
					>
						<span
							className={cn(
								"min-w-0 flex-1 truncate text-sm",
								source.isActive
									? "text-foreground-default"
									: "text-foreground-subtle line-through",
							)}
						>
							{source.name}
						</span>
 
						{/*
						  * The registry's word, not a new one: the Job Book's status
						  * families put "archived" in graphite for exactly this — put
						  * away, quiet, not in use. The action verbs below match it.
						  */}
						{!source.isActive && (
							<StatusBadge status="Archived" variant="default" />
						)}
 
						{source.isSystem ? (
							<Lock
								className="h-3 w-3 shrink-0 text-foreground-subtle"
								aria-hidden="true"
							/>
						) : (
							canEdit && (
								<button
									type="button"
									onClick={() =>
										source.isActive
											? deactivateMutation.mutate(source.id)
											: reactivateMutation.mutate(source.id)
									}
									className="grid size-6 shrink-0 place-items-center rounded-sm text-foreground-muted hover:text-foreground-default pointer-coarse:size-11"
									title={source.isActive ? "Archive" : "Restore"}
								>
									{source.isActive ? (
										<ToggleRight className="h-5 w-5" aria-hidden="true" />
									) : (
										<ToggleLeft className="h-5 w-5" aria-hidden="true" />
									)}
									<span className="sr-only">
										{source.isActive
											? `Archive ${source.name}`
											: `Restore ${source.name}`}
									</span>
								</button>
							)
						)}
					</li>
				))}
			</ul>
 
			{canEdit && (
				<form onSubmit={handleAdd} className="mt-3 flex items-center gap-2">
					<Input
						type="text"
						aria-label="New source name"
						value={newName}
						onChange={(e) => setNewName(e.target.value)}
						placeholder="New source name"
					/>
					<Button
						type="submit"
						className="shrink-0"
						disabled={!newName.trim()}
						isLoading={createMutation.isPending}
					>
						<Plus aria-hidden="true" />
						Add source
					</Button>
				</form>
			)}
		</section>
	);
}