All files / components/records RecordsTable.tsx

68.84% Statements 95/138
54.76% Branches 69/126
72.09% Functions 31/43
70% Lines 84/120

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                                                      3x 28x     38x 25x 25x 25x 2x 2x 2x             3x                                                                                                                                                                                                                                                                                                                 53x 53x 38x     53x                 53x   2x 2x 2x   2x 2x           53x 1x 1x     53x 123x       53x 103x                 53x 301x     301x 21x       280x                   280x 100x               180x               180x             180x         180x 19x       161x 1x               160x       53x   53x     53x 53x     155x   155x   53x     53x     53x 155x 155x 155x 155x   155x                                                     301x           53x 53x   53x                 53x 35x         2x                   70x     3x 3x   3x   3x             53x       103x     53x         103x       1x               2x               2x                 53x             53x             53x                                           159x 159x         2x   2x                                     53x               103x                                    
/**
 * Records table component
 * Dynamic table that renders columns based on collection schema
 */
 
import { useCallback, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
	DropdownMenu,
	DropdownMenuCheckboxItem,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Calculator, Columns3, Eye, Pencil, Pin, PinOff, Trash2 } from 'lucide-react';
import type { FieldDefinition } from '@/services/collections.service';
import type { RecordData, RecordListItem } from '@/types/records.types';
import { shouldMaskField, maskPiiValue } from '@/lib/form-helpers';
import { DataTable, type Column, type DispatchPagination, type DispatchSorting } from '@/components/common/DataTable';
import { useAuthStore } from '@/stores/auth.store';
import { cn } from '@/lib/utils';
 
const COLUMN_VISIBILITY_KEY = (collectionName: string) =>
	`column_visibility_${collectionName}`;
 
function loadHiddenColumns(collectionName?: string): Set<string> {
	if (!collectionName || typeof localStorage === 'undefined') return new Set();
	try {
		const raw = localStorage.getItem(COLUMN_VISIBILITY_KEY(collectionName));
		if (!raw) return new Set();
		const parsed = JSON.parse(raw) as unknown;
		Iif (!Array.isArray(parsed)) return new Set();
		return new Set(parsed.filter((x): x is string => typeof x === 'string'));
	} catch {
		return new Set();
	}
}
 
function persistHiddenColumns(collectionName: string, hidden: Set<string>) {
	localStorage.setItem(
		COLUMN_VISIBILITY_KEY(collectionName),
		JSON.stringify([...hidden]),
	);
}
 
interface RecordsTableProps {
	records: RecordListItem[];
	schema: FieldDefinition[];
	sortBy: string;
	sortOrder: 'asc' | 'desc';
	onSort: (column: string) => void;
	onView: (record: RecordListItem) => void;
	onEdit: (record: RecordListItem) => void;
	onDelete: (record: RecordListItem) => void;
	hasPiiAccess?: boolean;
	referenceRecords?: Record<string, RecordData[]>;
	/** Used for per-collection column visibility localStorage. */
	collectionName?: string;
 
	// Multi-select
	selectedIds?: Set<string>;
	onSelectionChange?: (ids: Set<string>) => void;
 
	// Pagination props
	totalItems: number;
	page: number;
	pageSize: number;
	onPageChange: (page: number) => void;
	onPageSizeChange: (pageSize: number) => void;
 
	// Cursor pagination props
	paginationMode?: 'page' | 'scroll';
	onPaginationModeChange?: (mode: 'page' | 'scroll') => void;
	hasMore?: boolean;
	onLoadMore?: () => void;
	isLoadingMore?: boolean;
	autoLoad?: boolean;
	onAutoLoadChange?: (enabled: boolean) => void;
	maxTableHeight?: string;
}
 
/** Returns the best display value for a referenced record. */
function getRefDisplayValue(record: RecordData): string {
	if (typeof record['name'] === 'string' && record['name']) return record['name'];
	const systemKeys = ['id', 'account_id', 'created_at', 'updated_at', 'created_by', 'updated_by'];
	const key = Object.keys(record).find(
		(k) => !systemKeys.includes(k) && typeof record[k] === 'string' && record[k],
	);
	if (key) return String(record[key]);
	return String(record.id ?? '').slice(0, 8) + '…';
}
 
/** Non-system fields of a record, up to `limit`. */
function getUserFields(record: RecordData, limit = 4): [string, unknown][] {
	const systemKeys = ['id', 'account_id', 'created_at', 'updated_at', 'created_by', 'updated_by'];
	return Object.entries(record)
		.filter(([key]) => !systemKeys.includes(key))
		.slice(0, limit);
}
 
// ---------------------------------------------------------------------------
// ReferenceCell — renders a single reference field cell
// ---------------------------------------------------------------------------
 
interface ReferenceCellProps {
	id: string;
	refRecord: RecordData | null;
}
 
function ReferenceCell({ id, refRecord }: ReferenceCellProps) {
	const [open, setOpen] = useState(false);
 
	if (!refRecord) {
		return (
			<div className="flex items-center gap-1">
				<span className="text-muted-foreground font-mono text-xs">{id.slice(0, 8)}…</span>
				<Badge variant="secondary" className="text-xs">Deleted</Badge>
			</div>
		);
	}
 
	const displayValue = getRefDisplayValue(refRecord);
 
	return (
		<Popover open={open} onOpenChange={setOpen}>
			<PopoverTrigger asChild>
				<button
					className="text-sm text-primary underline-offset-2 hover:underline cursor-pointer truncate max-w-[160px] text-left"
					title={displayValue}
				>
					{displayValue}
				</button>
			</PopoverTrigger>
			<PopoverContent className="w-64" align="start">
				<div className="space-y-2">
					<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
						Referenced Record
					</p>
					<p className="font-mono text-xs text-muted-foreground break-all">{refRecord.id as string}</p>
					<div className="space-y-1 pt-1 border-t">
						{getUserFields(refRecord).map(([key, val]) => (
							<div key={key} className="flex justify-between gap-2 text-sm">
								<span className="text-muted-foreground shrink-0">{key}:</span>
								<span className="font-medium truncate max-w-[130px]">
									{val === null || val === undefined ? (
										<span className="italic text-muted-foreground">null</span>
									) : (
										String(val)
									)}
								</span>
							</div>
						))}
					</div>
				</div>
			</PopoverContent>
		</Popover>
	);
}
 
// ---------------------------------------------------------------------------
// RecordsTable
// ---------------------------------------------------------------------------
 
export default function RecordsTable({
	records,
	schema,
	sortBy,
	sortOrder,
	onSort,
	onView,
	onEdit,
	onDelete,
	hasPiiAccess = false,
	referenceRecords = {},
	collectionName,
	selectedIds,
	onSelectionChange,
	totalItems,
	page,
	pageSize,
	onPageChange,
	onPageSizeChange,
	paginationMode = 'page',
	onPaginationModeChange,
	hasMore = false,
	onLoadMore,
	isLoadingMore = false,
	autoLoad = false,
	onAutoLoadChange,
	maxTableHeight = 'calc(100vh - 280px)',
}: RecordsTableProps) {
 
	const [pinnedColumns, setPinnedColumns] = useState<Set<string>>(new Set());
	const [hiddenColumns, setHiddenColumns] = useState<Set<string>>(() =>
		loadHiddenColumns(collectionName),
	);
 
	const togglePin = (fieldName: string) => {
		setPinnedColumns(prev => {
			const next = new Set(prev);
			if (next.has(fieldName)) next.delete(fieldName);
			else next.add(fieldName);
			return next;
		});
	};
 
	const setFieldHidden = useCallback(
		(fieldName: string, hidden: boolean) => {
			setHiddenColumns((prev) => {
				const next = new Set(prev);
				if (hidden) next.add(fieldName);
				else Enext.delete(fieldName);
				Eif (collectionName) persistHiddenColumns(collectionName, next);
				return next;
			});
		},
		[collectionName],
	);
 
	const showAllColumns = useCallback(() => {
		setHiddenColumns(new Set());
		Eif (collectionName) persistHiddenColumns(collectionName, new Set());
	}, [collectionName]);
 
	const visibleSchema = useMemo(
		() => schema.filter((f) => !hiddenColumns.has(f.name)),
		[schema, hiddenColumns],
	);
 
	const formatDate = (dateString: string) => {
		return new Date(dateString).toLocaleString('en-US', {
			year: 'numeric',
			month: 'short',
			day: 'numeric',
			hour: '2-digit',
			minute: '2-digit',
		});
	};
 
	const renderCellValue = (record: RecordListItem, field: FieldDefinition) => {
		const value = record[field.name];
 
		// Handle null/undefined
		if (value === null || value === undefined) {
			return <span className="text-muted-foreground italic">null</span>;
		}
 
		// Handle PII masking
		Iif (shouldMaskField(field, hasPiiAccess)) {
			const maskedValue = maskPiiValue(String(value), field.mask_type || 'full');
			return (
				<span className="text-muted-foreground" title="PII masked">
					{maskedValue}
				</span>
			);
		}
 
		// Handle boolean
		if (field.type === 'boolean') {
			return value ? (
				<Badge variant="default">Yes</Badge>
			) : (
				<Badge variant="secondary">No</Badge>
			);
		}
 
		// Handle reference fields — show display value from cache
		Iif (field.type === 'reference') {
			const id = String(value);
			const collectionCache = referenceRecords[field.collection || ''] ?? [];
			const refRecord = collectionCache.find((r) => r.id === id) ?? null;
			return <ReferenceCell id={id} refRecord={refRecord} />;
		}
 
		// Handle JSON
		Iif (field.type === 'json') {
			const jsonStr = typeof value === 'string' ? value : JSON.stringify(value);
			const truncated = jsonStr.length > 50 ? jsonStr.slice(0, 50) + '...' : jsonStr;
			return <span className="font-mono text-xs">{truncated}</span>;
		}
 
		// Handle datetime
		Iif (field.type === 'datetime') {
			return <span className="text-sm">{formatDate(value as string)}</span>;
		}
 
		// Handle number
		if (field.type === 'number') {
			return <span className="font-mono">{value as React.ReactNode}</span>;
		}
 
		// Handle long text
		if (field.type === 'text' && String(value).length > 50) {
			return (
				<span className="text-sm" title={String(value)}>
					{String(value).slice(0, 50)}...
				</span>
			);
		}
 
		// Default text rendering
		return <span className="text-sm">{String(value)}</span>;
	};
 
	// Fixed width (px) for pinned columns — required for predictable sticky offsets
	const PINNED_COL_WIDTH = 160;
	// Width of the checkbox column when multi-select is active
	const CHECKBOX_COL_WIDTH = 44;
 
	// Multi-select derived state
	const isAllSelected = records.length > 0 && selectedIds !== undefined && selectedIds.size === records.length;
	const isIndeterminate = (selectedIds?.size ?? 0) > 0 && !isAllSelected;
 
	// Pinned fields in original schema order (visible only)
	const pinnedFields = visibleSchema.filter(f => pinnedColumns.has(f.name));
	// Unpinned fields in original schema order (visible only)
	const unpinnedFields = visibleSchema.filter(f => !pinnedColumns.has(f.name));
	// Render order: pinned first (original order), then unpinned
	const orderedFields = [...pinnedFields, ...unpinnedFields];
 
	// Extra left offset for pinned schema columns when the checkbox column is present
	const checkboxOffset = onSelectionChange ? CHECKBOX_COL_WIDTH : 0;
 
	// Build dynamic columns — all schema fields visible, pinned ones frozen left
	const columns: Column<RecordListItem>[] = orderedFields.map((field) => {
		const isPinned = pinnedColumns.has(field.name);
		const pinnedIndex = pinnedFields.findIndex(f => f.name === field.name);
		const isLastPinned = isPinned && pinnedIndex === pinnedFields.length - 1;
		const isComputed = field.type === 'computed';
 
		return {
			header: isComputed
				? <span className="flex items-center gap-1">{field.name} <Calculator className="h-3 w-3 text-blue-400" /></span>
				: field.name,
			accessorKey: field.name as keyof RecordListItem,
			sortable: true,
			frozen: isPinned ? 'left' : undefined,
			frozenOffset: isPinned ? checkboxOffset + pinnedIndex * PINNED_COL_WIDTH : undefined,
			frozenBorderRight: isLastPinned,
			className: isComputed ? 'bg-blue-50/40 dark:bg-blue-950/20' : undefined,
			style: isPinned
				? { minWidth: PINNED_COL_WIDTH, maxWidth: PINNED_COL_WIDTH }
				: { minWidth: 140 },
			headerSuffix: (
				<button
					onClick={(e) => { e.stopPropagation(); togglePin(field.name); }}
					className={cn(
						'ml-1 rounded p-0.5 transition-opacity',
						isPinned
							? 'text-primary opacity-100'
							: 'text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-foreground'
					)}
					title={isPinned ? 'Unpin column' : 'Pin column'}
				>
					{isPinned ? <PinOff className="h-3 w-3" /> : <Pin className="h-3 w-3" />}
				</button>
			),
			render: (record: RecordListItem) => isComputed
				? <span className="text-sm text-muted-foreground italic">{renderCellValue(record, field)}</span>
				: renderCellValue(record, field),
		};
	});
 
	const { account } = useAuthStore();
	const isSuperadmin = account?.id === '00000000-0000-0000-0000-000000000000';
 
	Iif (isSuperadmin) {
		columns.unshift({
			header: 'Account',
			accessorKey: 'account_name',
			render: (record) => <span className="text-sm font-medium">{record.account_name || 'System'}</span>,
		});
	}
 
	// Multi-select checkbox column — prepended as the very first column
	if (onSelectionChange) {
		columns.unshift({
			header: (
				<Checkbox
					checked={isIndeterminate ? 'indeterminate' : isAllSelected}
					onCheckedChange={(checked) => {
						onSelectionChange(checked ? new Set(records.map(r => r.id)) : new Set());
					}}
					aria-label="Select all"
				/>
			),
			frozen: 'left',
			frozenOffset: 0,
			frozenBorderRight: false,
			style: { minWidth: CHECKBOX_COL_WIDTH, maxWidth: CHECKBOX_COL_WIDTH, padding: '0 8px' },
			render: (record) => (
				<Checkbox
					checked={selectedIds?.has(record.id) ?? false}
					onCheckedChange={(checked) => {
						const next = new Set(selectedIds);
						if (checked) next.add(record.id);
						else Enext.delete(record.id);
						onSelectionChange(next);
					}}
					onClick={(e) => e.stopPropagation()}
					aria-label={`Select record ${record.id}`}
				/>
			),
		});
	}
 
	columns.push({
		header: 'Created',
		accessorKey: 'created_at',
		sortable: true,
		render: (record) => <span className="text-sm text-muted-foreground">{formatDate(record.created_at)}</span>,
	});
 
	columns.push({
		header: 'Actions',
		className: 'text-right',
		frozen: 'right',
		render: (record) => (
			<div className="flex justify-end gap-2">
				<Button
					variant="ghost"
					size="sm"
					onClick={() => onView(record)}
					title="View record"
				>
					<Eye className="h-4 w-4" />
				</Button>
				<Button
					variant="ghost"
					size="sm"
					onClick={() => onEdit(record)}
					title="Edit record"
				>
					<Pencil className="h-4 w-4" />
				</Button>
				<Button
					variant="ghost"
					size="sm"
					onClick={() => onDelete(record)}
					title="Delete record"
				>
					<Trash2 className="h-4 w-4 text-destructive" />
				</Button>
			</div>
		),
	});
 
	const pagination: DispatchPagination = {
		page,
		pageSize,
		onPageChange,
		onPageSizeChange,
	};
 
	const sorting: DispatchSorting = {
		sortBy,
		sortOrder,
		onSort,
	};
 
	const columnVisibilityMenu =
		schema.length > 0 ? (
			<DropdownMenu>
				<DropdownMenuTrigger asChild>
					<Button
						variant="outline"
						size="sm"
						className="gap-1.5"
						data-testid="column-visibility-trigger"
					>
						<Columns3 className="h-4 w-4" />
						Columns
						{hiddenColumns.size > 0 && (
							<Badge variant="secondary" className="ml-0.5 text-xs">
								{schema.length - hiddenColumns.size}/{schema.length}
							</Badge>
						)}
					</Button>
				</DropdownMenuTrigger>
				<DropdownMenuContent align="end" className="w-56" data-testid="column-visibility-menu">
					<DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
					<DropdownMenuSeparator />
					{schema.map((field) => {
						const isVisible = !hiddenColumns.has(field.name);
						return (
							<DropdownMenuCheckboxItem
								key={field.name}
								checked={isVisible}
								onCheckedChange={(checked) =>
									setFieldHidden(field.name, !checked)
								}
								onSelect={(e) => e.preventDefault()}
								data-testid={`column-toggle-${field.name}`}
							>
								<span className="font-mono text-sm">{field.name}</span>
							</DropdownMenuCheckboxItem>
						);
					})}
					{hiddenColumns.size > 0 && (
						<>
							<DropdownMenuSeparator />
							<DropdownMenuItem onClick={showAllColumns} data-testid="column-show-all">
								Show all
							</DropdownMenuItem>
						</>
					)}
				</DropdownMenuContent>
			</DropdownMenu>
		) : null;
 
	return (
		<div className="space-y-3">
			{columnVisibilityMenu && (
				<div className="flex justify-end">{columnVisibilityMenu}</div>
			)}
			<DataTable
				data={records}
				columns={columns}
				keyExtractor={(item) => item.id}
				pagination={pagination}
				sorting={sorting}
				totalItems={totalItems}
				noDataMessage="No records found. Create your first record to get started."
				paginationMode={paginationMode}
				onPaginationModeChange={onPaginationModeChange}
				hasMore={hasMore}
				onLoadMore={onLoadMore}
				isLoadingMore={isLoadingMore}
				autoLoad={autoLoad}
				onAutoLoadChange={onAutoLoadChange}
				showModeToggle={true}
				maxTableHeight={maxTableHeight}
			/>
		</div>
	);
}