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 | 7x 7x 7x 12x 12x 12x 12x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 32x 32x 32x 3x 32x 173x 92x 92x 1x 1x 92x 1x 1x 1x 1x 1x 92x 8x 8x 8x 8x 8x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 92x 92x 92x 92x 32x 60x 2x 58x 173x 1x 1x 114x 456x 1x 11x 6x 12x 12x | /**
* Analytics Page
* Group-by query builder with aggregation results table and CSV export.
*/
import { useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router';
import { ArrowLeft, BarChart2, Play, Download, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import FilterBuilderPanel, {
type FilterRow,
compileFilterExpression,
} from '@/components/records/FilterBuilderPanel';
import { getCollectionByName, type Collection } from '@/services/collections.service';
import { aggregateRecords } from '@/services/records.service';
import type { AggregationResult } from '@/types/records.types';
import { handleApiError } from '@/lib/api';
import { useEffect } from 'react';
type AggFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
interface FieldFunction {
fn: AggFn;
field?: string; // undefined for count()
}
function buildFunctionsParam(selected: FieldFunction[]): string {
return selected
.map(({ fn, field }) => (field ? `${fn}(${field})` : `${fn}()`))
.join(',');
}
function resultKey(fn: AggFn, field?: string): string {
Eif (!field) return 'count';
return `${fn}_${field}`;
}
function formatValue(val: unknown): string {
Iif (val === null || val === undefined) return '—';
const n = Number(val);
Eif (!isNaN(n) && typeof val !== 'boolean') {
return n.toLocaleString(undefined, { maximumFractionDigits: 4 });
}
return String(val);
}
function exportCsv(columns: string[], rows: AggregationResult[], filename: string) {
const header = columns.join(',');
const body = rows
.map((row) =>
columns
.map((col) => {
const v = row[col];
const s = v === null || v === undefined ? '' : String(v);
return s.includes(',') || s.includes('"') ? `"${s.replace(/"/g, '""')}"` : s;
})
.join(','),
)
.join('\n');
const blob = new Blob([`${header}\n${body}`], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
interface AnalyticsPageProps {
/** When true, hide standalone page chrome for workspace embed. */
embedded?: boolean;
}
export default function AnalyticsPage({ embedded = false }: AnalyticsPageProps) {
const { collectionName } = useParams<{ collectionName: string }>();
const navigate = useNavigate();
const [collection, setCollection] = useState<Collection | null>(null);
const [loadingCollection, setLoadingCollection] = useState(true);
const [collectionError, setCollectionError] = useState<string | null>(null);
// Filter state
const [filterExpression, setFilterExpression] = useState('');
const [appliedFilterRows, setAppliedFilterRows] = useState<FilterRow[]>([]);
// Group by state
const [groupByFields, setGroupByFields] = useState<string[]>([]);
// Function selection: always include count; optionally per-field fns
const [includeCount, setIncludeCount] = useState(true);
const [numericFns, setNumericFns] = useState<Record<string, Set<AggFn>>>({});
// Having clause
const [having, setHaving] = useState('');
// Results
const [results, setResults] = useState<AggregationResult[] | null>(null);
const [totalGroups, setTotalGroups] = useState(0);
const [resultColumns, setResultColumns] = useState<string[]>([]);
const [running, setRunning] = useState(false);
const [runError, setRunError] = useState<string | null>(null);
useEffect(() => {
Iif (!collectionName) return;
setLoadingCollection(true);
getCollectionByName(collectionName)
.then(setCollection)
.catch((err) => setCollectionError(handleApiError(err)))
.finally(() => setLoadingCollection(false));
}, [collectionName]);
const numericFields =
collection?.schema?.filter((f) => f.type === 'number' || f.type === 'integer') ?? [];
const allFields = collection?.schema ?? [];
const toggleGroupBy = (field: string) => {
setGroupByFields((prev) =>
prev.includes(field) ? prev.filter((f) => f !== field) : [...prev, field],
);
};
const toggleNumericFn = (fieldName: string, fn: AggFn) => {
setNumericFns((prev) => {
const current = new Set(prev[fieldName] ?? []);
Iif (current.has(fn)) {
current.delete(fn);
} else {
current.add(fn);
}
return { ...prev, [fieldName]: current };
});
};
const handleRun = useCallback(async () => {
Iif (!collectionName) return;
const selected: FieldFunction[] = [];
if (includeCount) selected.push({ fn: 'count' });
for (const [field, fns] of Object.entries(numericFns)) {
for (const fn of fns) {
selected.push({ fn, field });
}
}
if (selected.length === 0) {
setRunError('Select at least one aggregation function.');
return;
}
setRunning(true);
setRunError(null);
setResults(null);
try {
const params: Parameters<typeof aggregateRecords>[1] = {
functions: buildFunctionsParam(selected),
};
Iif (groupByFields.length > 0) params.group_by = groupByFields.join(',');
Iif (filterExpression) params.filter = filterExpression;
Iif (having.trim()) params.having = having.trim();
const res = await aggregateRecords(collectionName, params);
setResults(res.results);
setTotalGroups(res.total_groups);
// Derive columns: group-by fields first, then aggregation result keys
const aggKeys = selected.map(({ fn, field }) => resultKey(fn, field));
setResultColumns([...groupByFields, ...aggKeys]);
} catch (err) {
setRunError(handleApiError(err));
} finally {
setRunning(false);
}
}, [collectionName, includeCount, numericFns, groupByFields, filterExpression, having]);
const handleApplyFilters = (expression: string, rows: FilterRow[]) => {
setFilterExpression(expression);
setAppliedFilterRows(rows);
};
const handleClearFilters = () => {
setFilterExpression('');
setAppliedFilterRows([]);
};
const handleRemoveFilterPill = (id: string) => {
if (!collection) return;
const remaining = appliedFilterRows.filter((r) => r.id !== id);
const expression = compileFilterExpression(remaining, collection.schema ?? []);
setAppliedFilterRows(remaining);
setFilterExpression(expression);
};
if (loadingCollection) {
return (
<div className="flex items-center justify-center py-20">
<RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (collectionError || !collection) {
return (
<div className="space-y-4">
{!embedded && (
<Button
variant="ghost"
size="sm"
onClick={() => navigate(`/admin/collections/${collectionName}/data`)}
className="gap-1"
>
<ArrowLeft className="h-4 w-4" /> Data
</Button>
)}
<p className="text-destructive">{collectionError ?? 'Collection not found'}</p>
</div>
);
}
return (
<div className="space-y-6" data-testid="analytics-page">
{/* Standalone header only — workspace shell owns title/tabs when embedded */}
{!embedded && (
<div className="flex items-center justify-between">
<div>
<div className="mb-2 flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() =>
navigate(`/admin/collections/${collectionName}/data`)
}
className="gap-1"
>
<ArrowLeft className="h-4 w-4" />
Data
</Button>
</div>
<h1 className="flex items-center gap-2 text-3xl font-bold">
<BarChart2 className="h-7 w-7 text-primary" />
{collectionName} — Analytics
</h1>
<p className="mt-2 text-muted-foreground">
Group records and compute aggregations
</p>
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left column: Filter + Group By Builder */}
<div className="lg:col-span-1 space-y-4">
{/* Filter Panel */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Filters</CardTitle>
<CardDescription>Apply before aggregation</CardDescription>
</CardHeader>
<CardContent>
<FilterBuilderPanel
schema={collection.schema}
appliedRows={appliedFilterRows}
onApply={handleApplyFilters}
onClear={handleClearFilters}
onRemovePill={handleRemoveFilterPill}
/>
</CardContent>
</Card>
{/* Group By Builder */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Group By</CardTitle>
<CardDescription>Select fields to group results</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
{allFields.length === 0 ? (
<p className="text-sm text-muted-foreground">No fields available</p>
) : (
allFields.map((f) => (
<div key={f.name} className="flex items-center gap-2">
<Checkbox
id={`gb-${f.name}`}
checked={groupByFields.includes(f.name)}
onCheckedChange={() => toggleGroupBy(f.name)}
/>
<Label htmlFor={`gb-${f.name}`} className="cursor-pointer font-mono text-sm">
{f.name}
</Label>
<Badge variant="outline" className="text-xs ml-auto">{f.type}</Badge>
</div>
))
)}
</CardContent>
</Card>
{/* Aggregation Functions */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Aggregation Functions</CardTitle>
<CardDescription>Choose what to compute</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Count */}
<div className="flex items-center gap-2">
<Checkbox
id="fn-count"
checked={includeCount}
onCheckedChange={(v) => setIncludeCount(!!v)}
/>
<Label htmlFor="fn-count" className="cursor-pointer font-mono text-sm">
count()
</Label>
</div>
{/* Per-numeric-field functions */}
{numericFields.map((f) => (
<div key={f.name} className="space-y-1">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{f.name}
</p>
{(['sum', 'avg', 'min', 'max'] as AggFn[]).map((fn) => (
<div key={fn} className="flex items-center gap-2 pl-2">
<Checkbox
id={`fn-${fn}-${f.name}`}
checked={numericFns[f.name]?.has(fn) ?? false}
onCheckedChange={() => toggleNumericFn(f.name, fn)}
/>
<Label
htmlFor={`fn-${fn}-${f.name}`}
className="cursor-pointer font-mono text-sm"
>
{fn}({f.name})
</Label>
</div>
))}
</div>
))}
{numericFields.length === 0 && (
<p className="text-sm text-muted-foreground">
No numeric fields — only count() is available
</p>
)}
</CardContent>
</Card>
{/* Having */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Having</CardTitle>
<CardDescription>Filter aggregated results</CardDescription>
</CardHeader>
<CardContent>
<Input
value={having}
onChange={(e) => setHaving(e.target.value)}
placeholder='e.g. count() > 5'
className="font-mono text-sm"
/>
</CardContent>
</Card>
<Button onClick={handleRun} disabled={running} className="w-full gap-2">
{running ? (
<RefreshCw className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
Run
</Button>
{runError && (
<p className="text-sm text-destructive">{runError}</p>
)}
</div>
{/* Right column: Results */}
<div className="lg:col-span-2">
<Card className="h-full">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">Results</CardTitle>
{results !== null && (
<CardDescription>
{totalGroups} group{totalGroups !== 1 ? 's' : ''}
</CardDescription>
)}
</div>
{results && results.length > 0 && (
<Button
variant="outline"
size="sm"
className="gap-2"
onClick={() =>
exportCsv(
resultColumns,
results,
`${collectionName}-analytics.csv`,
)
}
>
<Download className="h-4 w-4" />
Export CSV
</Button>
)}
</div>
</CardHeader>
<CardContent>
{results === null && !running && (
<div className="flex flex-col items-center justify-center py-20 text-muted-foreground gap-3">
<BarChart2 className="h-12 w-12 opacity-30" />
<p className="text-sm">Configure options and click Run</p>
</div>
)}
{running && (
<div className="flex items-center justify-center py-20">
<RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)}
{results !== null && !running && results.length === 0 && (
<div className="flex flex-col items-center justify-center py-20 text-muted-foreground gap-3">
<p className="text-sm">No results</p>
</div>
)}
{results !== null && !running && results.length > 0 && (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
{resultColumns.map((col) => (
<TableHead key={col} className="font-mono text-xs whitespace-nowrap">
{col}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{results.map((row, i) => (
<TableRow key={i}>
{resultColumns.map((col) => (
<TableCell key={col} className="font-mono text-sm whitespace-nowrap">
{formatValue(row[col])}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
</div>
</div>
</div>
);
}
|