All files / src/pages/insights analytics-panels.tsx

96.96% Statements 32/33
94% Branches 47/50
94.11% Functions 16/17
100% Lines 28/28

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                                                      32x                                                                   32x     128x                                                     30x 58x   30x                             58x   58x   58x           58x                                                                                                               29x   29x                                                                 28x 28x                                                                             29x   29x                                                   29x                 116x                                   28x 54x   28x                                     54x 54x                                                     30x   30x                                                                             33x   30x                           120x                                                            
import {
	TrendingUp,
	Users,
	IndianRupee,
	AlertTriangle,
	Target,
	BarChart3,
	XCircle,
} from "lucide-react";
import { LOSS_REASON_LABELS } from "../../lib/crm-constants";
import type { CrmDashboard } from "../../lib/api/pro/crm";
import { cn } from "../../lib/utils";
import { abbreviatePaise } from "../../lib/currency-utils";
import { StatusBadge } from "../../components/ui/status-badge";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../components/ui/table";
 
// ─── KPI Cards ───────────────────────────────────────────────────────────────
 
export function KpiCards({ data }: { data: CrmDashboard }) {
	const cards = [
		{
			label: "Active Leads",
			value: String(data.pipeline.totalActive),
			icon: Users,
			color: "text-primary-600" as const,
			bgColor: "bg-primary-100" as const,
		},
		{
			label: "Pipeline Value",
			value: abbreviatePaise(data.pipeline.totalPipelineValue),
			icon: IndianRupee,
			color: "text-secondary-600" as const,
			bgColor: "bg-secondary-100" as const,
		},
		{
			label: "Won",
			value: `${data.pipeline.wonInPeriod} (${abbreviatePaise(data.pipeline.wonValueInPeriod)})`,
			icon: TrendingUp,
			color: "text-success" as const,
			bgColor: "bg-success/10" as const,
		},
		{
			label: "Conversion",
			value:
				data.pipeline.totalActive + data.pipeline.wonInPeriod > 0
					? `${Math.round((data.pipeline.wonInPeriod / (data.pipeline.totalActive + data.pipeline.wonInPeriod)) * 100)}%`
					: "—",
			icon: Target,
			color: "text-info" as const,
			bgColor: "bg-info/10" as const,
		},
	];
 
	return (
		<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
			{cards.map((card) => (
				<div
					key={card.label}
					className="rounded-lg border border-border-default bg-background-elevated p-4"
				>
					<div className="flex items-center gap-2 mb-2">
						<div
							className={cn(
								"flex h-7 w-7 items-center justify-center rounded-full",
								card.bgColor,
							)}
						>
							<card.icon className={cn("h-3.5 w-3.5", card.color)} />
						</div>
					</div>
					<div className="text-lg font-bold text-foreground-default">
						{card.value}
					</div>
					<div className="text-xs text-foreground-subtle">{card.label}</div>
				</div>
			))}
		</div>
	);
}
 
// ─── Pipeline Overview ───────────────────────────────────────────────────────
 
export function PipelineOverview({ data }: { data: CrmDashboard }) {
	const stages = data.pipeline.stages;
	const maxCount = Math.max(...stages.map((s) => s.leadCount), 1);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<h2 className="text-sm font-semibold text-foreground-default mb-4 flex items-center gap-2">
				<BarChart3 className="h-4 w-4 text-foreground-subtle" />
				Pipeline Overview
			</h2>
 
			{stages.length === 0 ? (
				<p className="text-sm text-foreground-subtle text-center py-4">
					No pipeline stages configured.
				</p>
			) : (
				<div className="space-y-3">
					{/* Funnel bars */}
					{stages.map((stage) => {
						const pct = (stage.leadCount / maxCount) * 100;
						const isTerminal =
							stage.stageType === "system_terminal_won" ||
							stage.stageType === "system_terminal_lost";
						const barColor = isTerminal
							? stage.stageType === "system_terminal_won"
								? "bg-success"
								: "bg-error"
							: "bg-primary-500";
 
						return (
							<div key={stage.id} className="flex items-center gap-3">
								<div className="w-28 text-xs text-foreground-default truncate flex-shrink-0">
									{stage.name}
								</div>
								<div className="flex-1 h-6 bg-background-muted rounded-sm overflow-hidden">
									<div
										className={cn("h-full rounded-sm transition-all", barColor)}
										style={{ width: `${pct}%` }}
									/>
								</div>
								<div className="w-16 text-right text-xs font-medium text-foreground-default flex-shrink-0">
									{stage.leadCount}{" "}
									<span className="text-foreground-subtle font-normal">
										leads
									</span>
								</div>
								<div className="w-20 text-right text-xs text-foreground-subtle flex-shrink-0">
									{abbreviatePaise(stage.totalValue)}
								</div>
							</div>
						);
					})}
 
					{/* Pipeline summary */}
					<div className="flex items-center justify-between pt-3 border-t border-border-default mt-2">
						<div className="grid grid-cols-3 gap-6 text-center flex-1">
							<div>
								<div className="text-lg font-bold text-foreground-default">
									{data.pipeline.newLeadsInPeriod}
								</div>
								<div className="text-xs text-foreground-subtle">New Leads</div>
							</div>
							<div>
								<div className="text-lg font-bold text-success">
									{data.pipeline.wonInPeriod}
								</div>
								<div className="text-xs text-foreground-subtle">Won</div>
							</div>
							<div>
								<div className="text-lg font-bold text-error">
									{data.pipeline.lostInPeriod}
								</div>
								<div className="text-xs text-foreground-subtle">Lost</div>
							</div>
						</div>
					</div>
				</div>
			)}
		</div>
	);
}
 
// ─── Source Performance ──────────────────────────────────────────────────────
 
export function SourcePerformance({ data }: { data: CrmDashboard }) {
	const sources = [...data.sources].sort((a, b) => b.totalLeads - a.totalLeads);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<h2 className="text-sm font-semibold text-foreground-default mb-4 flex items-center gap-2">
				<Target className="h-4 w-4 text-foreground-subtle" />
				Source Performance
			</h2>
 
			{sources.length === 0 ? (
				<p className="text-sm text-foreground-subtle text-center py-4">
					No source data yet.
				</p>
			) : (
				// The ruled data table, on the `Table` family. This was a
				// hand-rolled HTML table with its own padding and its own header
				// typography; Phase 6 adds a grep test forbidding raw table markup
				// outside `components/ui/`, and the primitive already knows the
				// hairline rules, the hover tint, the `.label` column heads and
				// `numeric` (right-aligned, tabular).
				<Table density="dense">
					<TableCaption>
						Leads, wins, conversion rate and value for each lead source.
					</TableCaption>
					<TableHeader>
						<TableRow>
							<TableHead>Source</TableHead>
							<TableHead numeric>Leads</TableHead>
							<TableHead numeric>Won</TableHead>
							<TableHead numeric>Conv %</TableHead>
							<TableHead numeric>Value</TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{sources.map((source, i) => {
							const isBest = i === 0 && source.totalLeads > 0;
							return (
								// `isCurrent` is the Index Red Rule's one use here: a
								// 3px inset bar marking the row the panel is about.
								// The old code tinted the best row `bg-success/5`,
								// spending a STATE ink on a RANK.
								<TableRow key={source.id} isCurrent={isBest}>
									<TableCell>
										{source.name}
										{isBest && (
											<StatusBadge
												status="Top"
												variant="success"
												className="ml-1.5"
											/>
										)}
									</TableCell>
									<TableCell numeric>{source.totalLeads}</TableCell>
									<TableCell numeric>{source.wonCount}</TableCell>
									<TableCell numeric>
										{source.conversionRate > 0
											? `${Math.round(source.conversionRate)}%`
											: "—"}
									</TableCell>
									<TableCell numeric>
										{abbreviatePaise(source.totalValue)}
									</TableCell>
								</TableRow>
							);
						})}
					</TableBody>
				</Table>
			)}
		</div>
	);
}
 
// ─── Financial Summary ───────────────────────────────────────────────────────
 
export function FinancialSummary({ data }: { data: CrmDashboard }) {
	const { financial } = data;
 
	const metrics = [
		{
			label: "Won Deals",
			value: String(financial.wonDealCount),
			sub: abbreviatePaise(financial.wonTotalValue),
		},
		{
			label: "Avg Deal Size",
			value: abbreviatePaise(financial.avgDealSize),
			sub: null,
		},
		{
			label: "Quote→Order Ratio",
			value:
				financial.quoteToOrderRatio > 0
					? `${Math.round(financial.quoteToOrderRatio)}%`
					: "—",
			sub: null,
		},
		{
			label: "Active Pipeline",
			value: abbreviatePaise(financial.activePipelineValue),
			sub: `${financial.activePipelineCount} leads`,
		},
	];
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<h2 className="text-sm font-semibold text-foreground-default mb-4 flex items-center gap-2">
				<IndianRupee className="h-4 w-4 text-foreground-subtle" />
				Financial Summary
			</h2>
 
			<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
				{metrics.map((metric) => (
					<div key={metric.label} className="space-y-1">
						<div className="text-xs text-foreground-subtle">{metric.label}</div>
						<div className="text-lg font-bold text-foreground-default">
							{metric.value}
						</div>
						{metric.sub && (
							<div className="text-xs text-foreground-subtle">{metric.sub}</div>
						)}
					</div>
				))}
			</div>
		</div>
	);
}
 
// ─── Loss Reason Breakdown ───────────────────────────────────────────────────
 
export function LossReasonBreakdown({ data }: { data: CrmDashboard }) {
	const reasons = [...data.lossReasons].sort((a, b) => b.count - a.count);
	const total = reasons.reduce((sum, r) => sum + r.count, 0);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<h2 className="text-sm font-semibold text-foreground-default mb-4 flex items-center gap-2">
				<XCircle className="h-4 w-4 text-foreground-subtle" />
				Loss Reasons
				{total > 0 && (
					<span className="text-xs font-normal text-foreground-subtle">
						({total} lost)
					</span>
				)}
			</h2>
 
			{reasons.length === 0 || total === 0 ? (
				<p className="text-sm text-foreground-subtle text-center py-4">
					No lost leads in this period.
				</p>
			) : (
				<div className="space-y-2">
					{reasons.map((reason) => {
						const pct = Math.round((reason.count / total) * 100);
						return (
							<div key={reason.category} className="flex items-center gap-3">
								<div className="w-32 text-xs text-foreground-default truncate flex-shrink-0">
									{LOSS_REASON_LABELS[reason.category] ?? reason.category}
								</div>
								<div className="flex-1 h-5 bg-background-muted rounded-sm overflow-hidden">
									<div
										className="h-full bg-error/60 rounded-sm transition-all"
										style={{ width: `${Math.max(pct, 3)}%` }}
									/>
								</div>
								<div className="w-16 text-right text-xs text-foreground-default flex-shrink-0">
									{reason.count}{" "}
									<span className="text-foreground-subtle">({pct}%)</span>
								</div>
							</div>
						);
					})}
				</div>
			)}
		</div>
	);
}
 
// ─── Follow-up Health ────────────────────────────────────────────────────────
 
export function FollowupHealth({ data }: { data: CrmDashboard }) {
	const { followup } = data;
 
	const indicators = [
		{
			label: "Stale Leads",
			value: followup.staleLeads,
			description: "No contact in 7+ days",
			color:
				followup.staleLeads > 0 ? "text-warning" : "text-foreground-subtle",
			bgColor:
				followup.staleLeads > 0 ? "bg-warning/10" : "bg-background-muted",
		},
		{
			label: "Overdue Reminders",
			value: followup.overdueReminders,
			description: "Past due date",
			color:
				followup.overdueReminders > 0 ? "text-error" : "text-foreground-subtle",
			bgColor:
				followup.overdueReminders > 0 ? "bg-error/10" : "bg-background-muted",
		},
		{
			label: "Stuck Leads",
			value: followup.stuckLeads,
			description: "Same stage 14+ days",
			color:
				followup.stuckLeads > 0 ? "text-warning" : "text-foreground-subtle",
			bgColor:
				followup.stuckLeads > 0 ? "bg-warning/10" : "bg-background-muted",
		},
		{
			label: "No Notes",
			value: followup.leadsWithNoNotes,
			description: "Active leads without notes",
			color:
				followup.leadsWithNoNotes > 0 ? "text-info" : "text-foreground-subtle",
			bgColor:
				followup.leadsWithNoNotes > 0 ? "bg-info/10" : "bg-background-muted",
		},
	];
 
	const hasIssues = indicators.some((ind) => ind.value > 0);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<h2 className="text-sm font-semibold text-foreground-default mb-4 flex items-center gap-2">
				<AlertTriangle className="h-4 w-4 text-foreground-subtle" />
				Follow-up Health
				{hasIssues && (
					<span className="text-xs font-normal text-warning">
						Needs attention
					</span>
				)}
			</h2>
 
			<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
				{indicators.map((ind) => (
					<div
						key={ind.label}
						className={cn("rounded-md p-3 text-center", ind.bgColor)}
					>
						<div className={cn("text-2xl font-bold", ind.color)}>
							{ind.value}
						</div>
						<div className="text-xs font-medium text-foreground-default mt-1">
							{ind.label}
						</div>
						{/*
						 * `text-[10px]` was an off-scale type value — the Golden
						 * Rule's exact prohibition. `text-xs` is the smallest step
						 * the token scale has.
						 */}
						<div className="text-xs text-foreground-subtle mt-0.5">
							{ind.description}
						</div>
					</div>
				))}
			</div>
 
			{!hasIssues && (
				<p className="text-sm text-success text-center mt-4">
					All leads are being followed up on time.
				</p>
			)}
		</div>
	);
}