-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathReportViewer.tsx
More file actions
423 lines (388 loc) · 16.6 KB
/
Copy pathReportViewer.tsx
File metadata and controls
423 lines (388 loc) · 16.6 KB
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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, Button, Badge, Skeleton } from '@object-ui/components';
import { SchemaRenderer } from '@object-ui/react';
import type { ReportViewerSchema, ReportSection, ReportExportFormat, ReportField, ReportGroupBy } from '@object-ui/types';
import { Download, Printer, RefreshCw } from 'lucide-react';
import { exportReport } from './ReportExportEngine';
import { formatValue } from './formatValue';
import { getCellRenderer, resolveCellRendererType } from '@object-ui/fields';
// ---------------------------------------------------------------------------
// Client-side grouping utility
// ---------------------------------------------------------------------------
interface GroupedData {
key: string;
label: string;
rows: Record<string, any>[];
}
function groupData(data: any[], groupBy: ReportGroupBy[]): GroupedData[] | null {
if (!groupBy || groupBy.length === 0 || !data || data.length === 0) return null;
const firstGroup = groupBy[0];
const field = firstGroup.field;
const groups: Map<string, Record<string, any>[]> = new Map();
for (const row of data) {
const key = String(row[field] ?? '(empty)');
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(row);
}
const result: GroupedData[] = [];
for (const [key, rows] of groups) {
result.push({ key, label: `${firstGroup.label || field}: ${key}`, rows });
}
// Sort groups
const dir = firstGroup.sort === 'desc' ? -1 : 1;
result.sort((a, b) => a.key.localeCompare(b.key) * dir);
return result;
}
/**
* Compute one summary value for a report column. Covers every
* `ReportAggregationType` member (`@object-ui/types/reports.ts`) — `distinct`
* used to fall into `default: return ''` and render a blank cell while the
* type accepted it (#2942). Exported for the coverage guard, whose sample
* table is `Record<ReportAggregationType, …>` so a new member fails
* type-check until it computes here.
*/
export function computeReportAggregation(
data: Record<string, any>[] | undefined,
fieldName: string,
aggregation?: string,
): string | number {
if (!data) return 0;
const values = data.map((item: Record<string, any>) => Number(item[fieldName]) || 0);
switch (aggregation) {
case 'count': return data.length;
case 'sum': return values.reduce((sum: number, v: number) => sum + v, 0);
case 'avg': return values.length > 0
? (values.reduce((sum: number, v: number) => sum + v, 0) / values.length).toFixed(2)
: 0;
case 'min': return values.length > 0 ? Math.min(...values) : 0;
case 'max': return values.length > 0 ? Math.max(...values) : 0;
// Distinct values of the RAW field (numeric coercion would fold distinct
// strings together).
case 'distinct':
return new Set(data.map((item: Record<string, any>) => item[fieldName])).size;
default: return '';
}
}
export interface ReportViewerProps {
schema: ReportViewerSchema;
/** Callback to refresh data */
onRefresh?: () => void;
}
/**
* ReportViewer - Display a generated report with optional toolbar
* Supports rendering report sections, charts, tables, and export functionality
*/
export const ReportViewer: React.FC<ReportViewerProps> = ({ schema, onRefresh }) => {
const {
report,
data,
showToolbar = true,
allowExport = true,
allowPrint = true,
loading = false
} = schema;
const handleExport = (format: string) => {
if (!report) {
console.warn('ReportViewer: Cannot export, no report defined');
return;
}
exportReport(format as ReportExportFormat, report, data || [],
report.exportConfigs?.[format as ReportExportFormat]
);
};
const handlePrint = () => {
window.print();
};
const handleRefresh = () => {
onRefresh?.();
};
const computeAggregation = (fieldName: string, aggregation?: string): string | number =>
computeReportAggregation(data, fieldName, aggregation);
// Evaluate conditional formatting rules for a cell
const getCellStyle = (fieldName: string, value: any): React.CSSProperties | undefined => {
const rules = report?.conditionalFormatting;
if (!rules || !Array.isArray(rules)) return undefined;
for (const rule of rules) {
if (rule.field !== fieldName) continue;
const strValue = String(value ?? '');
const ruleValue = String(rule.value ?? '');
let match = false;
switch (rule.operator) {
case 'equals': match = strValue === ruleValue; break;
case 'not_equals': match = strValue !== ruleValue; break;
case 'contains': match = strValue.includes(ruleValue); break;
case 'greater_than': match = Number(value) > Number(rule.value); break;
case 'less_than': match = Number(value) < Number(rule.value); break;
}
if (match) {
const style: React.CSSProperties = {};
if (rule.backgroundColor) style.backgroundColor = rule.backgroundColor;
if (rule.textColor) style.color = rule.textColor;
return style;
}
}
return undefined;
};
const renderCellValue = (value: any, field: ReportField): React.ReactNode => {
if (value == null || value === '') return '';
// Legacy badge rendering — explicit opt-in via renderAs='badge'.
// Kept for backwards compatibility; new code should set type:'select'/'status'
// which auto-renders as a badge.
if (field.renderAs === 'badge' && (!field.type || field.type === 'string' || field.type === 'text')) {
const colorClass = field.colorMap?.[String(value)] || '';
return <Badge className={colorClass}>{String(value)}</Badge>;
}
// Aggregation results are always raw numbers — keep simple numeric formatting
// and skip type-aware rendering (lookup/badge/etc don't make sense for sums).
if (field.aggregation) {
return formatValue(value, field);
}
// Type-aware rendering via the shared field cell-renderer registry.
// This handles select (badge), lookup (link), boolean (✓/✗), email/url/phone
// (mailto:/external/tel: links), image (thumbnail), richtext (sanitized),
// datetime, currency, percent, etc. Falls back to text for unknown types.
if (field.type) {
// colorMap on the report column should override per-option colors —
// splice it into a synthetic options list when present.
const fieldMeta: any = { ...field };
if (field.colorMap && !fieldMeta.options) {
fieldMeta.options = Object.entries(field.colorMap).map(([v, color]) => ({
value: v,
label: v,
color,
}));
}
const Renderer = getCellRenderer(resolveCellRendererType(fieldMeta));
return <Renderer value={value} field={fieldMeta} />;
}
return formatValue(value, field);
};
if (!report) {
return (
<Card>
<CardContent className="p-8 text-center text-muted-foreground">
No report to display
</CardContent>
</Card>
);
}
return (
<div className="space-y-4">
{/* Toolbar */}
{showToolbar && (
<div className="flex items-center justify-between gap-2 p-4 bg-card rounded-lg border">
<div>
<h2 className="text-lg font-semibold">{report.title}</h2>
{report.description && (
<p className="text-sm text-muted-foreground">{report.description}</p>
)}
</div>
<div className="flex items-center gap-2">
{report.refreshInterval && (
<Button variant="outline" size="sm" onClick={handleRefresh}>
<RefreshCw className="h-4 w-4 mr-2" />
Refresh
</Button>
)}
{allowPrint && (
<Button variant="outline" size="sm" onClick={handlePrint}>
<Printer className="h-4 w-4 mr-2" />
Print
</Button>
)}
{allowExport && report.showExportButtons && (
<div className="flex items-center gap-1">
<Button
variant="outline"
size="sm"
onClick={() => handleExport('pdf')}
>
<Download className="h-4 w-4 mr-2" />
PDF
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleExport('excel')}
>
<Download className="h-4 w-4 mr-2" />
Excel
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleExport('csv')}
>
<Download className="h-4 w-4 mr-2" />
CSV
</Button>
</div>
)}
</div>
</div>
)}
{/* Report Content */}
<Card>
<CardHeader>
{!showToolbar && report.title && <CardTitle>{report.title}</CardTitle>}
{!showToolbar && report.description && <CardDescription>{report.description}</CardDescription>}
</CardHeader>
<CardContent className="space-y-6">
{loading && (
<div className="space-y-6">
{/* Skeleton summary cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{[1, 2, 3].map((i) => (
<Card key={i}>
<CardContent className="p-4 space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-8 w-28" />
</CardContent>
</Card>
))}
</div>
{/* Skeleton table */}
<div className="space-y-2">
<Skeleton className="h-10 w-full" />
{[1, 2, 3, 4, 5].map((i) => (
<Skeleton key={i} className="h-8 w-full" />
))}
</div>
</div>
)}
{!loading && report.sections?.map((section: ReportSection, index: number) => {
// Check visibility condition
if (section.visible === false) {
return null;
}
return (
<div key={index} className="space-y-2">
{/* Section Title - skip for header type since it renders its own title */}
{section.title && section.type !== 'header' && (
<h3 className="text-lg font-semibold border-b pb-2">{section.title}</h3>
)}
{/* Section Content */}
{section.type === 'header' && section.title && (
<div className="text-2xl font-bold py-4">{section.title}</div>
)}
{section.type === 'summary' && (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{report.fields
?.filter((f: ReportField) => f.showInSummary)
.map((field: ReportField, idx: number) => (
<Card key={idx}>
<CardContent className="p-4">
<div className="text-sm text-muted-foreground">{field.label || field.name}</div>
<div className="text-2xl font-bold">
{formatValue(computeAggregation(field.name, field.aggregation), field)}
</div>
</CardContent>
</Card>
))}
</div>
)}
{section.type === 'table' && (
<div className="border rounded-lg overflow-x-auto">
<table className="w-full text-sm min-w-[600px]">
<thead className="bg-muted">
<tr>
{section.columns?.map((col: ReportField, idx: number) => (
<th key={idx} className={`px-4 py-2 font-medium ${col.type === 'number' ? 'text-right' : 'text-left'}`}>
{col.label || col.name}
</th>
))}
</tr>
</thead>
<tbody>
{(() => {
const groups = groupData(data || [], report.groupBy || []);
if (groups) {
return groups.map((group) => (
<React.Fragment key={group.key}>
<tr className="bg-muted/60">
<td
colSpan={section.columns?.length || 1}
className="px-4 py-2 font-semibold text-sm"
>
{group.label} ({group.rows.length})
</td>
</tr>
{group.rows.map((row: Record<string, any>, rowIdx: number) => (
<tr key={rowIdx} className="border-t hover:bg-muted/50 even:bg-muted/20">
{section.columns?.map((col: ReportField, colIdx: number) => (
<td key={colIdx} className={`px-4 py-2 ${col.type === 'number' ? 'text-right tabular-nums' : ''}`} style={getCellStyle(col.name, row[col.name])}>
{renderCellValue(row[col.name], col)}
</td>
))}
</tr>
))}
</React.Fragment>
));
}
return data?.map((row: Record<string, any>, rowIdx: number) => (
<tr key={rowIdx} className="border-t hover:bg-muted/50 even:bg-muted/20">
{section.columns?.map((col: ReportField, colIdx: number) => (
<td key={colIdx} className={`px-4 py-2 ${col.type === 'number' ? 'text-right tabular-nums' : ''}`} style={getCellStyle(col.name, row[col.name])}>
{renderCellValue(row[col.name], col)}
</td>
))}
</tr>
));
})()}
</tbody>
</table>
</div>
)}
{section.type === 'text' && section.text && (
<div className="prose max-w-none">
<p>{section.text}</p>
</div>
)}
{section.type === 'page-break' && (
<div className="border-t-2 border-dashed my-8 print:page-break-after-always" />
)}
{section.content && (
<SchemaRenderer schema={section.content} />
)}
</div>
);
})}
{/* Fallback: Show data if no sections defined */}
{!report.sections && data && data.length > 0 && (
<div className="border rounded-lg overflow-x-auto">
<table className="w-full text-sm min-w-[600px]">
<thead className="bg-muted">
<tr>
{report.fields?.map((field: ReportField, idx: number) => (
<th key={idx} className={`px-4 py-2 font-medium ${field.type === 'number' ? 'text-right' : 'text-left'}`}>
{field.label || field.name}
</th>
))}
</tr>
</thead>
<tbody>
{data.map((row: Record<string, any>, rowIdx: number) => (
<tr key={rowIdx} className="border-t hover:bg-muted/50 even:bg-muted/20">
{report.fields?.map((field: ReportField, colIdx: number) => (
<td key={colIdx} className={`px-4 py-2 ${field.type === 'number' ? 'text-right tabular-nums' : ''}`} style={getCellStyle(field.name, row[field.name])}>
{renderCellValue(row[field.name], field)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
);
};