All files / src/components/crm ActivityTimeline.tsx

100% Statements 26/26
100% Branches 22/22
100% Functions 5/5
100% Lines 25/25

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                                                                                                              4x                                                                                                                                                                                         4x                             70x 70x   70x 13x 2x 2x 1x   1x 1x 1x     11x       70x                                   70x 70x   70x 59x             11x     12x                   13x 13x   13x     13x 13x                                                                                                                                        
import { useMemo } from "react";
import {
	Plus,
	StickyNote,
	Phone,
	ArrowRight,
	FileText,
	Trash2,
	IndianRupee,
	Bell,
	BellOff,
	Clock,
	RotateCcw,
	XCircle,
	Archive,
	ArchiveRestore,
	AlertTriangle,
} from "lucide-react";
import type { LeadActivity } from "../../lib/api/pro/crm";
import { formatRelativeDate } from "../../lib/format-date";
import { cn, formatDateTimeLong } from "../../lib/utils";
import { Button } from "../ui/button";
import { DENSE_BUTTON } from "./lead-controls";
 
/**
 * A lead's activity, as a ruled timeline.
 *
 * ONE DATE VOCABULARY. Every relative age is `formatRelativeDate` from
 * `lib/format-date.ts` — the portal's single place for that — and the tooltip
 * is `formatDateTimeLong` from `@interioring/utils/format/date`, the one
 * `en-IN` absolute formatter. This file used to carry its OWN
 * `formatTimestamp`: a third spelling ("just now" / "yesterday", lower case,
 * falling back to a bare "14 Dec" past 30 days) plus its own inline
 * `toLocaleString("en-IN", …)`. That is exactly the drift the shared helpers
 * exist to stop — the same hour printed as "Just now" on Today, "just now"
 * here, and "Just now" again on the leads board.
 *
 * WHY THE ICON MEDALLIONS STAY ROUND
 * The Job Book bans pills for STATUSES, because a status is a printed code.
 * These are not statuses: every row prints its activity as a sentence, and the
 * medallion is a glyph next to it. Nothing here is conveyed by colour alone,
 * so there is no information to recover by flattening them, and the round
 * glyph is what makes the grouped spine readable.
 *
 * Index red appears nowhere in this file. A timeline has no current item.
 */
 
// ─── Activity type → icon/color mapping ──────────────────────────────────────
 
type ActivityStyle = {
	icon: React.ElementType;
	color: string;
	bgColor: string;
};
 
const ACTIVITY_STYLES: Record<string, ActivityStyle> = {
	lead_created_auto: {
		icon: Plus,
		color: "text-primary-600",
		bgColor: "bg-primary-100",
	},
	lead_created_manual: {
		icon: Plus,
		color: "text-primary-600",
		bgColor: "bg-primary-100",
	},
	note_added: {
		icon: StickyNote,
		color: "text-foreground-default",
		bgColor: "bg-background-muted",
	},
	contacted: {
		icon: Phone,
		color: "text-success",
		bgColor: "bg-success/10",
	},
	stage_changed: {
		icon: ArrowRight,
		color: "text-secondary-600",
		bgColor: "bg-secondary-100",
	},
	document_attached: {
		icon: FileText,
		color: "text-info",
		bgColor: "bg-info/10",
	},
	document_deleted: {
		icon: Trash2,
		color: "text-foreground-subtle",
		bgColor: "bg-background-muted",
	},
	quote_value_changed: {
		icon: IndianRupee,
		color: "text-warning",
		bgColor: "bg-warning/10",
	},
	order_value_changed: {
		icon: IndianRupee,
		color: "text-success",
		bgColor: "bg-success/10",
	},
	reminder_set: {
		icon: Bell,
		color: "text-info",
		bgColor: "bg-info/10",
	},
	reminder_completed: {
		icon: Bell,
		color: "text-success",
		bgColor: "bg-success/10",
	},
	reminder_overdue: {
		icon: AlertTriangle,
		color: "text-error",
		bgColor: "bg-error/10",
	},
	reminder_dismissed: {
		icon: BellOff,
		color: "text-foreground-subtle",
		bgColor: "bg-background-muted",
	},
	reminder_snoozed: {
		icon: Clock,
		color: "text-warning",
		bgColor: "bg-warning/10",
	},
	lead_reopened: {
		icon: RotateCcw,
		color: "text-primary-600",
		bgColor: "bg-primary-100",
	},
	loss_reason_recorded: {
		icon: XCircle,
		color: "text-error",
		bgColor: "bg-error/10",
	},
	lead_archived: {
		icon: Archive,
		color: "text-foreground-subtle",
		bgColor: "bg-background-muted",
	},
	lead_unarchived: {
		icon: ArchiveRestore,
		color: "text-foreground-default",
		bgColor: "bg-background-muted",
	},
};
 
const DEFAULT_STYLE: ActivityStyle = {
	icon: StickyNote,
	color: "text-foreground-muted",
	bgColor: "bg-background-muted",
};
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
 
// Group activities by groupId
type ActivityGroup = {
	groupId: string | null;
	activities: LeadActivity[];
};
 
function groupActivities(activities: LeadActivity[]): ActivityGroup[] {
	const groups: ActivityGroup[] = [];
	const groupMap = new Map<string, LeadActivity[]>();
 
	for (const activity of activities) {
		if (activity.groupId) {
			const existing = groupMap.get(activity.groupId);
			if (existing) {
				existing.push(activity);
			} else {
				const arr = [activity];
				groupMap.set(activity.groupId, arr);
				groups.push({ groupId: activity.groupId, activities: arr });
			}
		} else {
			groups.push({ groupId: null, activities: [activity] });
		}
	}
 
	return groups;
}
 
// ─── Component ───────────────────────────────────────────────────────────────
 
type ActivityTimelineProps = {
	activities: LeadActivity[];
	total: number;
	onLoadMore?: () => void;
	isLoadingMore?: boolean;
};
 
export function ActivityTimeline({
	activities,
	total,
	onLoadMore,
	isLoadingMore,
}: ActivityTimelineProps) {
	const groups = useMemo(() => groupActivities(activities), [activities]);
	const hasMore = activities.length < total;
 
	if (activities.length === 0) {
		return (
			<div className="text-center py-8 text-sm text-foreground-subtle">
				No activity yet
			</div>
		);
	}
 
	return (
		<div className="space-y-0">
			{groups.map((group, i) => (
				<div
					key={group.groupId || `single-${group.activities[0].id}`}
					className={cn(
						"relative pl-8",
						group.activities.length > 1 &&
							"border-l-2 border-primary-200 ml-3.5",
					)}
				>
					{group.activities.map((activity) => {
						const style =
							ACTIVITY_STYLES[activity.activityType] || DEFAULT_STYLE;
						const Icon = style.icon;
						// One date vocabulary, from the one place. See the header.
						const relative = formatRelativeDate(activity.dateCreated, {
							granularity: "time",
						});
						const exact = formatDateTimeLong(activity.dateCreated);
						return (
							<div
								key={activity.id}
								className={cn(
									"relative flex gap-3 pb-4",
									// Vertical line connector (for non-grouped items)
									group.activities.length === 1 &&
										i < groups.length - 1 &&
										"before:absolute before:left-[13px] before:top-8 before:w-px before:h-[calc(100%-16px)] before:bg-border-default",
								)}
							>
								{/* Icon */}
								<div
									className={cn(
										"flex h-7 w-7 shrink-0 items-center justify-center rounded-full",
										style.bgColor,
										/*
										 * 19px is COMPUTED GEOMETRY, not a design value: it
										 * centres a 28px medallion on the group spine the
										 * wrapper draws at `ml-3.5` with `border-l-2`. The
										 * Golden Rule governs colour, spacing and type
										 * TOKENS; an offset derived from the medallion's own
										 * size has no token to come from, and rounding it to
										 * the 4px scale would visibly miss the line.
										 */
										group.activities.length > 1 && "-ml-[19px]",
									)}
								>
									<Icon className={cn("h-3.5 w-3.5", style.color)} />
								</div>
 
								{/* Content */}
								<div className="flex-1 min-w-0 pt-0.5">
									<p className="text-sm text-foreground-default">
										{activity.content}
									</p>
									<span
										className="text-xs tabular-nums text-foreground-subtle"
										title={exact}
									>
										{relative}
									</span>
								</div>
							</div>
						);
					})}
				</div>
			))}
 
			{/* Load more */}
			{hasMore && onLoadMore && (
				<div className="pt-2 text-center">
					<Button
						variant="ghost"
						size="sm"
						className={DENSE_BUTTON}
						onClick={onLoadMore}
						disabled={isLoadingMore}
					>
						{isLoadingMore
							? "Loading..."
							: `Load more (${total - activities.length} remaining)`}
					</Button>
				</div>
			)}
		</div>
	);
}