plugin-elastic-report 0.1.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,1047 +1,1453 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import {
11
- CopyOutlined,
12
- DeleteOutlined,
13
- EditOutlined,
14
- EyeOutlined,
15
- PlayCircleOutlined,
16
- PlusOutlined,
17
- ReloadOutlined,
18
- } from '@ant-design/icons';
19
- import { useApp } from '@nocobase/client-v2';
20
- import {
21
- Alert,
22
- App,
23
- Button,
24
- Card,
25
- Col,
26
- Descriptions,
27
- Divider,
28
- Drawer,
29
- Form,
30
- Input,
31
- InputNumber,
32
- Modal,
33
- Popconfirm,
34
- Row,
35
- Select,
36
- Space,
37
- Switch,
38
- Table,
39
- Tabs,
40
- Tag,
41
- Typography,
42
- } from 'antd';
43
- import type { TableColumnsType } from 'antd';
44
- import React, { useCallback, useEffect, useMemo, useState } from 'react';
45
- import type {
46
- BucketAggType,
47
- CalendarIntervalOption,
48
- EsConnectionSummary,
49
- EsDataViewRecord,
50
- EsFieldCapability,
51
- EsReportRecord,
52
- FilterOperator,
53
- ID,
54
- MetricAggType,
55
- ReportExecutionResult,
56
- ReportFilterItem,
57
- ReportRuntimeOverrides,
58
- ReportSortItem,
59
- ReportSpec,
60
- ReportVisualizationType,
61
- TimeRangePreset,
62
- } from '../../shared/types';
63
- import {
64
- executeReportPreview,
65
- fetchAllReports,
66
- fetchDataViewFields,
67
- fetchDataViews,
68
- fetchEsConnections,
69
- fetchEsIndices,
70
- fetchMcpInfo,
71
- persistReport,
72
- removeDataView,
73
- removeReport,
74
- saveDataView,
75
- type ApiClientLike,
76
- type McpInfoPayload,
77
- } from '../api';
78
- import { ElasticReportRenderer } from '../components/ElasticReportRenderer';
79
- import { useT } from '../locale';
80
-
81
- const { Paragraph, Text } = Typography;
82
-
83
- interface ReportEditorFormValues {
84
- title: string;
85
- description?: string;
86
- dataViewId: ID;
87
- published: boolean;
88
- visualization: ReportVisualizationType;
89
- query?: string;
90
- timePreset: TimeRangePreset;
91
- filters?: Array<{
92
- field: string;
93
- operator: FilterOperator;
94
- value?: string;
95
- valueTo?: string;
96
- }>;
97
- sort?: Array<{
98
- field: string;
99
- order: 'asc' | 'desc';
100
- }>;
101
- columns?: string[];
102
- pageSize: number;
103
- showHistogram: boolean;
104
- allowInteractiveControls: boolean;
105
- bucketType: BucketAggType;
106
- bucketField?: string;
107
- calendarInterval: CalendarIntervalOption;
108
- topN: number;
109
- metricType: MetricAggType;
110
- metricField?: string;
111
- metricLabel?: string;
112
- }
113
-
114
- interface DataViewFormValues {
115
- title: string;
116
- dataSourceKey: string;
117
- indexPattern: string;
118
- timeField?: string;
119
- description?: string;
120
- }
121
-
122
- const FILTER_OPERATOR_ITEMS: Array<{ label: string; value: FilterOperator }> = [
123
- { label: 'is (=)', value: 'eq' },
124
- { label: 'is not (!=)', value: 'ne' },
125
- { label: 'contains', value: 'contains' },
126
- { label: 'in (comma-separated)', value: 'in' },
127
- { label: 'not in', value: 'not_in' },
128
- { label: '>', value: 'gt' },
129
- { label: '>=', value: 'gte' },
130
- { label: '<', value: 'lt' },
131
- { label: '<=', value: 'lte' },
132
- { label: 'between', value: 'between' },
133
- { label: 'exists', value: 'exists' },
134
- { label: 'does not exist', value: 'not_exists' },
135
- ];
136
-
137
- function formValuesToSpec(values: ReportEditorFormValues): ReportSpec {
138
- const filters: ReportFilterItem[] = (values.filters ?? [])
139
- .filter((f) => Boolean(f?.field))
140
- .map((f, idx) => ({
141
- id: `flt-${idx}`,
142
- field: f.field,
143
- operator: f.operator || 'eq',
144
- ...(f.value !== undefined && f.value !== '' ? { value: f.value } : {}),
145
- ...(f.valueTo !== undefined && f.valueTo !== '' ? { valueTo: f.valueTo } : {}),
146
- enabled: true,
147
- }));
148
-
149
- const sort: ReportSortItem[] = (values.sort ?? [])
150
- .filter((s) => Boolean(s?.field))
151
- .map((s) => ({
152
- field: s.field,
153
- order: s.order === 'asc' ? 'asc' : 'desc',
154
- }));
155
-
156
- return {
157
- visualization: values.visualization || 'table',
158
- query: values.query?.trim() ?? '',
159
- queryMode: 'kql',
160
- filters,
161
- sort,
162
- timeRange: { preset: values.timePreset || 'last_24h' },
163
- columns: values.columns ?? [],
164
- pageSize: values.pageSize || 20,
165
- allowInteractiveControls: values.allowInteractiveControls !== false,
166
- chart: {
167
- bucketType: values.bucketType || 'date_histogram',
168
- ...(values.bucketField ? { bucketField: values.bucketField } : {}),
169
- calendarInterval: values.calendarInterval || 'auto',
170
- topN: values.topN || 10,
171
- metricType: values.metricType || 'count',
172
- ...(values.metricField ? { metricField: values.metricField } : {}),
173
- ...(values.metricLabel ? { metricLabel: values.metricLabel } : {}),
174
- showHistogram: values.showHistogram !== false,
175
- },
176
- };
177
- }
178
-
179
- export const ElasticReportManager: React.FC = () => {
180
- const t = useT();
181
- const app = useApp();
182
- const api = app.apiClient as unknown as ApiClientLike;
183
- const { message } = App.useApp();
184
-
185
- const [connections, setConnections] = useState<EsConnectionSummary[]>([]);
186
- const [dataViews, setDataViews] = useState<EsDataViewRecord[]>([]);
187
- const [reports, setReports] = useState<EsReportRecord[]>([]);
188
- const [mcpInfo, setMcpInfo] = useState<McpInfoPayload | null>(null);
189
- const [loadingList, setLoadingList] = useState(false);
190
-
191
- // Data View modal state
192
- const [dvModalOpen, setDvModalOpen] = useState(false);
193
- const [editingDataView, setEditingDataView] = useState<EsDataViewRecord | null>(null);
194
- const [dvSaving, setDvSaving] = useState(false);
195
- const [matchedIndices, setMatchedIndices] = useState<string[]>([]);
196
- const [loadingIndices, setLoadingIndices] = useState(false);
197
- const [dvForm] = Form.useForm<DataViewFormValues>();
198
-
199
- // Report Studio drawer state
200
- const [studioOpen, setStudioOpen] = useState(false);
201
- const [editingReport, setEditingReport] = useState<EsReportRecord | null>(null);
202
- const [studioFields, setStudioFields] = useState<EsFieldCapability[]>([]);
203
- const [studioPreviewSpec, setStudioPreviewSpec] = useState<ReportSpec>({ visualization: 'table' });
204
- const [previewResult, setPreviewResult] = useState<ReportExecutionResult | null>(null);
205
- const [previewLoading, setPreviewLoading] = useState(false);
206
- const [previewError, setPreviewError] = useState<string | null>(null);
207
- const [savingReport, setSavingReport] = useState(false);
208
- const [reportForm] = Form.useForm<ReportEditorFormValues>();
209
-
210
- const watchedVisualization = Form.useWatch('visualization', reportForm) ?? 'table';
211
- const watchedDataViewId = Form.useWatch('dataViewId', reportForm);
212
- const watchedBucketType = Form.useWatch('bucketType', reportForm) ?? 'date_histogram';
213
- const watchedMetricType = Form.useWatch('metricType', reportForm) ?? 'count';
214
-
215
- const loadAll = useCallback(async () => {
216
- setLoadingList(true);
217
- try {
218
- const [connList, dvList, reportList, mcpData] = await Promise.all([
219
- fetchEsConnections(api).catch(() => []),
220
- fetchDataViews(api).catch(() => []),
221
- fetchAllReports(api).catch(() => []),
222
- fetchMcpInfo(api).catch(() => null),
223
- ]);
224
- setConnections(connList);
225
- setDataViews(dvList);
226
- setReports(reportList);
227
- setMcpInfo(mcpData);
228
- } finally {
229
- setLoadingList(false);
230
- }
231
- }, [api]);
232
-
233
- useEffect(() => {
234
- loadAll();
235
- }, [loadAll]);
236
-
237
- useEffect(() => {
238
- if (!studioOpen || watchedDataViewId === undefined || watchedDataViewId === null) {
239
- setStudioFields([]);
240
- return;
241
- }
242
- let cancelled = false;
243
- fetchDataViewFields(api, watchedDataViewId, false)
244
- .then((res) => {
245
- if (!cancelled) setStudioFields(res.fields ?? []);
246
- })
247
- .catch(() => {
248
- if (!cancelled) setStudioFields([]);
249
- });
250
- return () => {
251
- cancelled = true;
252
- };
253
- }, [api, studioOpen, watchedDataViewId]);
254
-
255
- const selectedDataView = useMemo(
256
- () => dataViews.find((dv) => String(dv.id) === String(watchedDataViewId)) ?? null,
257
- [dataViews, watchedDataViewId],
258
- );
259
-
260
- const aggregatableStudioFields = useMemo(
261
- () => studioFields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
262
- [studioFields],
263
- );
264
-
265
- const numericStudioFields = useMemo(
266
- () =>
267
- studioFields.filter((f) =>
268
- ['long', 'integer', 'short', 'byte', 'double', 'float', 'half_float', 'scaled_float'].includes(f.type),
269
- ),
270
- [studioFields],
271
- );
272
-
273
- const openNewDataViewModal = () => {
274
- setEditingDataView(null);
275
- setMatchedIndices([]);
276
- dvForm.resetFields();
277
- dvForm.setFieldsValue({
278
- dataSourceKey: connections[0]?.key,
279
- indexPattern: '*',
280
- timeField: '@timestamp',
281
- });
282
- setDvModalOpen(true);
283
- };
284
-
285
- const openEditDataViewModal = (record: EsDataViewRecord) => {
286
- setEditingDataView(record);
287
- setMatchedIndices([]);
288
- dvForm.setFieldsValue({
289
- title: record.title,
290
- dataSourceKey: record.dataSourceKey,
291
- indexPattern: record.indexPattern,
292
- timeField: record.timeField ?? '',
293
- description: record.description ?? '',
294
- });
295
- setDvModalOpen(true);
296
- };
297
-
298
- const handleBrowseIndices = async () => {
299
- const dsKey = dvForm.getFieldValue('dataSourceKey');
300
- const pattern = dvForm.getFieldValue('indexPattern') || '*';
301
- if (!dsKey) return;
302
- setLoadingIndices(true);
303
- try {
304
- const list = await fetchEsIndices(api, dsKey, pattern);
305
- setMatchedIndices(list);
306
- } catch (err) {
307
- message.error(err instanceof Error ? err.message : String(err));
308
- } finally {
309
- setLoadingIndices(false);
310
- }
311
- };
312
-
313
- const handleSaveDataView = async () => {
314
- try {
315
- const values = await dvForm.validateFields();
316
- setDvSaving(true);
317
- await saveDataView(api, {
318
- ...(editingDataView ? { id: editingDataView.id } : {}),
319
- title: values.title,
320
- dataSourceKey: values.dataSourceKey,
321
- indexPattern: values.indexPattern,
322
- timeField: values.timeField || null,
323
- description: values.description || null,
324
- });
325
- message.success(t('Saved successfully'));
326
- setDvModalOpen(false);
327
- await loadAll();
328
- } catch (err) {
329
- if (err instanceof Error && 'message' in err) {
330
- message.error(err.message);
331
- }
332
- } finally {
333
- setDvSaving(false);
334
- }
335
- };
336
-
337
- const openNewReportStudio = () => {
338
- setEditingReport(null);
339
- setPreviewResult(null);
340
- setPreviewError(null);
341
- reportForm.resetFields();
342
- reportForm.setFieldsValue({
343
- title: '',
344
- dataViewId: dataViews[0]?.id,
345
- published: true,
346
- visualization: 'table',
347
- query: '',
348
- timePreset: 'last_24h',
349
- filters: [],
350
- sort: [],
351
- columns: [],
352
- pageSize: 20,
353
- showHistogram: true,
354
- allowInteractiveControls: true,
355
- bucketType: 'date_histogram',
356
- calendarInterval: 'auto',
357
- topN: 10,
358
- metricType: 'count',
359
- });
360
- setStudioPreviewSpec({
361
- visualization: 'table',
362
- query: '',
363
- queryMode: 'kql',
364
- filters: [],
365
- sort: [],
366
- timeRange: { preset: 'last_24h' },
367
- columns: [],
368
- pageSize: 20,
369
- allowInteractiveControls: true,
370
- chart: {
371
- bucketType: 'date_histogram',
372
- calendarInterval: 'auto',
373
- topN: 10,
374
- metricType: 'count',
375
- showHistogram: true,
376
- },
377
- });
378
- setStudioOpen(true);
379
- };
380
-
381
- const openEditReportStudio = (record: EsReportRecord) => {
382
- setEditingReport(record);
383
- setPreviewResult(null);
384
- setPreviewError(null);
385
- const spec = record.spec;
386
- setStudioPreviewSpec(spec);
387
- reportForm.setFieldsValue({
388
- title: record.title,
389
- description: record.description ?? '',
390
- dataViewId: record.dataViewId,
391
- published: record.published !== false,
392
- visualization: spec.visualization ?? 'table',
393
- query: spec.query ?? '',
394
- timePreset: spec.timeRange?.preset ?? 'last_24h',
395
- filters: (spec.filters ?? []).map((f) => ({
396
- field: f.field,
397
- operator: f.operator,
398
- value: Array.isArray(f.value) ? f.value.join(', ') : f.value !== undefined ? String(f.value) : '',
399
- valueTo: f.valueTo !== undefined ? String(f.valueTo) : '',
400
- })),
401
- sort: spec.sort ?? [],
402
- columns: spec.columns ?? [],
403
- pageSize: spec.pageSize ?? 20,
404
- showHistogram: spec.chart?.showHistogram !== false,
405
- allowInteractiveControls: spec.allowInteractiveControls !== false,
406
- bucketType: spec.chart?.bucketType ?? 'date_histogram',
407
- bucketField: spec.chart?.bucketField,
408
- calendarInterval: spec.chart?.calendarInterval ?? 'auto',
409
- topN: spec.chart?.topN ?? 10,
410
- metricType: spec.chart?.metricType ?? 'count',
411
- metricField: spec.chart?.metricField,
412
- metricLabel: spec.chart?.metricLabel,
413
- });
414
- setStudioOpen(true);
415
- };
416
-
417
- const handleRunStudioPreview = async (overrides?: ReportRuntimeOverrides) => {
418
- const values = reportForm.getFieldsValue(true) as ReportEditorFormValues;
419
- if (values.dataViewId === undefined || values.dataViewId === null) {
420
- return;
421
- }
422
- setPreviewLoading(true);
423
- setPreviewError(null);
424
- try {
425
- const spec = formValuesToSpec(values);
426
- if (!overrides) {
427
- setStudioPreviewSpec(spec);
428
- }
429
- const res = await executeReportPreview(api, values.dataViewId, spec, overrides);
430
- setPreviewResult(res.result);
431
- } catch (err) {
432
- setPreviewError(err instanceof Error ? err.message : String(err));
433
- } finally {
434
- setPreviewLoading(false);
435
- }
436
- };
437
-
438
- const handleSaveReport = async () => {
439
- try {
440
- const values = await reportForm.validateFields();
441
- setSavingReport(true);
442
- const spec = formValuesToSpec(values);
443
- await persistReport(api, {
444
- ...(editingReport ? { id: editingReport.id } : {}),
445
- title: values.title,
446
- description: values.description || null,
447
- dataViewId: values.dataViewId,
448
- published: values.published !== false,
449
- spec,
450
- });
451
- message.success(t('Saved successfully'));
452
- setStudioOpen(false);
453
- await loadAll();
454
- } catch (err) {
455
- if (err instanceof Error && 'message' in err) {
456
- message.error(err.message);
457
- }
458
- } finally {
459
- setSavingReport(false);
460
- }
461
- };
462
-
463
- const reportColumns: TableColumnsType<EsReportRecord> = [
464
- {
465
- title: t('Title'),
466
- dataIndex: 'title',
467
- key: 'title',
468
- render: (val: string, row) => (
469
- <Space direction="vertical" size={0}>
470
- <Text strong>{val}</Text>
471
- {row.description && (
472
- <Text type="secondary" style={{ fontSize: 12 }}>
473
- {row.description}
474
- </Text>
475
- )}
476
- </Space>
477
- ),
478
- },
479
- {
480
- title: t('Visualization'),
481
- dataIndex: 'visualization',
482
- key: 'visualization',
483
- width: 140,
484
- render: (val: string) => <Tag color="blue">{String(val).toUpperCase()}</Tag>,
485
- },
486
- {
487
- title: t('Data View'),
488
- key: 'dataView',
489
- render: (_: unknown, row) =>
490
- row.dataView ? `${row.dataView.title} (${row.dataView.indexPattern})` : String(row.dataViewId),
491
- },
492
- {
493
- title: t('Published'),
494
- dataIndex: 'published',
495
- key: 'published',
496
- width: 120,
497
- render: (pub: boolean) => <Tag color={pub ? 'success' : 'default'}>{pub ? t('Published') : t('Draft')}</Tag>,
498
- },
499
- {
500
- title: '',
501
- key: 'actions',
502
- width: 180,
503
- render: (_: unknown, row) => (
504
- <Space>
505
- <Button size="small" icon={<EditOutlined />} onClick={() => openEditReportStudio(row)}>
506
- {t('Edit')}
507
- </Button>
508
- <Popconfirm
509
- title={t('Confirm delete?')}
510
- onConfirm={async () => {
511
- await removeReport(api, row.id);
512
- message.success(t('Deleted successfully'));
513
- await loadAll();
514
- }}
515
- >
516
- <Button size="small" danger icon={<DeleteOutlined />}>
517
- {t('Delete')}
518
- </Button>
519
- </Popconfirm>
520
- </Space>
521
- ),
522
- },
523
- ];
524
-
525
- const dataViewColumns: TableColumnsType<EsDataViewRecord> = [
526
- { title: t('Title'), dataIndex: 'title', key: 'title' },
527
- { title: t('Data Source (Elasticsearch)'), dataIndex: 'dataSourceKey', key: 'dataSourceKey' },
528
- {
529
- title: t('Index Pattern'),
530
- dataIndex: 'indexPattern',
531
- key: 'indexPattern',
532
- render: (val: string) => <Tag>{val}</Tag>,
533
- },
534
- { title: t('Time Field'), dataIndex: 'timeField', key: 'timeField', render: (v?: string | null) => v || '—' },
535
- {
536
- title: t('Fields'),
537
- key: 'fieldCount',
538
- width: 110,
539
- render: (_: unknown, row) => row.cachedFields?.length ?? 0,
540
- },
541
- {
542
- title: '',
543
- key: 'actions',
544
- width: 260,
545
- render: (_: unknown, row) => (
546
- <Space>
547
- <Button
548
- size="small"
549
- icon={<ReloadOutlined />}
550
- onClick={async () => {
551
- await fetchDataViewFields(api, row.id, true);
552
- message.success(t('Saved successfully'));
553
- await loadAll();
554
- }}
555
- >
556
- {t('Refresh Fields')}
557
- </Button>
558
- <Button size="small" icon={<EditOutlined />} onClick={() => openEditDataViewModal(row)}>
559
- {t('Edit')}
560
- </Button>
561
- <Popconfirm
562
- title={t('Confirm delete?')}
563
- onConfirm={async () => {
564
- await removeDataView(api, row.id);
565
- message.success(t('Deleted successfully'));
566
- await loadAll();
567
- }}
568
- >
569
- <Button size="small" danger icon={<DeleteOutlined />} aria-label={t('Delete')} />
570
- </Popconfirm>
571
- </Space>
572
- ),
573
- },
574
- ];
575
-
576
- return (
577
- <Card bordered={false}>
578
- <Tabs
579
- items={[
580
- {
581
- key: 'reports',
582
- label: t('Reports'),
583
- children: (
584
- <div>
585
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
586
- <Space>
587
- <Button type="primary" icon={<PlusOutlined />} onClick={openNewReportStudio}>
588
- {t('New Report')}
589
- </Button>
590
- <Button icon={<ReloadOutlined />} onClick={loadAll}>
591
- {t('Refresh')}
592
- </Button>
593
- </Space>
594
- </div>
595
- <Table<EsReportRecord> rowKey="id" loading={loadingList} columns={reportColumns} dataSource={reports} />
596
- </div>
597
- ),
598
- },
599
- {
600
- key: 'dataViews',
601
- label: t('Data Views'),
602
- children: (
603
- <div>
604
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
605
- <Space>
606
- <Button type="primary" icon={<PlusOutlined />} onClick={openNewDataViewModal}>
607
- {t('New Data View')}
608
- </Button>
609
- <Button icon={<ReloadOutlined />} onClick={loadAll}>
610
- {t('Refresh')}
611
- </Button>
612
- </Space>
613
- </div>
614
- <Table<EsDataViewRecord>
615
- rowKey="id"
616
- loading={loadingList}
617
- columns={dataViewColumns}
618
- dataSource={dataViews}
619
- />
620
- </div>
621
- ),
622
- },
623
- {
624
- key: 'mcp',
625
- label: t('MCP & AI Employee'),
626
- children: (
627
- <Space direction="vertical" size={16} style={{ width: '100%' }}>
628
- <Alert
629
- type="info"
630
- showIcon
631
- message={t('AI Employee Usage')}
632
- description={t(
633
- 'This plugin automatically registers the elastic-report MCP server (with user context) and AI Employee tools so AI agents can inspect fields, preview Elasticsearch queries, and publish Saved Reports ready to select in blocks.',
634
- )}
635
- />
636
- {mcpInfo && (
637
- <Descriptions bordered column={1} size="small">
638
- <Descriptions.Item label={t('MCP Server Name')}>
639
- <Tag color="purple">{mcpInfo.serverName}</Tag>
640
- </Descriptions.Item>
641
- <Descriptions.Item label={t('Dedicated MCP Endpoint')}>
642
- <Space>
643
- <code>{mcpInfo.endpointPath}</code>
644
- <Button
645
- size="small"
646
- icon={<CopyOutlined />}
647
- onClick={() => {
648
- navigator.clipboard?.writeText(window.location.origin + mcpInfo.endpointPath);
649
- message.success(t('Copied to clipboard'));
650
- }}
651
- >
652
- {t('Copy')}
653
- </Button>
654
- </Space>
655
- </Descriptions.Item>
656
- </Descriptions>
657
- )}
658
- <Card size="small" title={t('Exposed MCP Tools')}>
659
- <Table
660
- size="small"
661
- rowKey="name"
662
- pagination={false}
663
- dataSource={mcpInfo?.tools ?? []}
664
- columns={[
665
- {
666
- title: 'Tool',
667
- dataIndex: 'name',
668
- key: 'name',
669
- width: 220,
670
- render: (v: string) => <code>{v}</code>,
671
- },
672
- { title: t('Description'), dataIndex: 'description', key: 'description' },
673
- ]}
674
- />
675
- </Card>
676
- </Space>
677
- ),
678
- },
679
- ]}
680
- />
681
-
682
- {/* Data View Modal */}
683
- <Modal
684
- title={editingDataView ? t('Edit Data View') : t('New Data View')}
685
- open={dvModalOpen}
686
- confirmLoading={dvSaving}
687
- onCancel={() => setDvModalOpen(false)}
688
- onOk={handleSaveDataView}
689
- width={600}
690
- >
691
- <Form form={dvForm} layout="vertical">
692
- <Form.Item name="title" label={t('Title')} rules={[{ required: true }]}>
693
- <Input placeholder="Application Logs" />
694
- </Form.Item>
695
- <Form.Item name="dataSourceKey" label={t('Data Source (Elasticsearch)')} rules={[{ required: true }]}>
696
- <Select
697
- options={connections.map((c) => ({
698
- label: `${c.displayName} (${c.key})`,
699
- value: c.key,
700
- }))}
701
- />
702
- </Form.Item>
703
- <Form.Item name="indexPattern" label={t('Index Pattern')} rules={[{ required: true }]}>
704
- <Space.Compact style={{ width: '100%' }}>
705
- <Input placeholder="logs-*" />
706
- <Button loading={loadingIndices} icon={<EyeOutlined />} onClick={handleBrowseIndices}>
707
- {t('Browse Indices')}
708
- </Button>
709
- </Space.Compact>
710
- </Form.Item>
711
- {matchedIndices.length > 0 && (
712
- <Paragraph style={{ fontSize: 12 }}>
713
- <Text strong>{t('Matching Indices')}: </Text>
714
- {matchedIndices.slice(0, 20).map((idx) => (
715
- <Tag key={idx} style={{ marginBottom: 4 }}>
716
- {idx}
717
- </Tag>
718
- ))}
719
- </Paragraph>
720
- )}
721
- <Form.Item name="timeField" label={t('Time Field')}>
722
- <Input placeholder="@timestamp" />
723
- </Form.Item>
724
- <Form.Item name="description" label={t('Description')}>
725
- <Input.TextArea rows={2} />
726
- </Form.Item>
727
- </Form>
728
- </Modal>
729
-
730
- {/* Report Studio Drawer */}
731
- <Drawer
732
- title={editingReport ? t('Edit Report') : t('New Report')}
733
- open={studioOpen}
734
- onClose={() => setStudioOpen(false)}
735
- width={1080}
736
- extra={
737
- <Space>
738
- <Button icon={<PlayCircleOutlined />} loading={previewLoading} onClick={() => handleRunStudioPreview()}>
739
- {t('Run Preview')}
740
- </Button>
741
- <Button type="primary" loading={savingReport} onClick={handleSaveReport}>
742
- {t('Save')}
743
- </Button>
744
- </Space>
745
- }
746
- >
747
- <Form form={reportForm} layout="vertical">
748
- <Row gutter={16}>
749
- <Col xs={24} md={10}>
750
- <Form.Item name="title" label={t('Title')} rules={[{ required: true }]}>
751
- <Input placeholder="HTTP 5xx Error Logs" />
752
- </Form.Item>
753
- </Col>
754
- <Col xs={24} md={7}>
755
- <Form.Item name="dataViewId" label={t('Data View')} rules={[{ required: true }]}>
756
- <Select
757
- options={dataViews.map((dv) => ({
758
- label: `${dv.title} (${dv.indexPattern})`,
759
- value: dv.id,
760
- }))}
761
- />
762
- </Form.Item>
763
- </Col>
764
- <Col xs={24} md={7}>
765
- <Form.Item name="visualization" label={t('Visualization')} rules={[{ required: true }]}>
766
- <Select
767
- options={[
768
- { label: t('Table (Discover)'), value: 'table' },
769
- { label: t('Bar Chart'), value: 'bar' },
770
- { label: t('Line Chart'), value: 'line' },
771
- { label: t('Area Chart'), value: 'area' },
772
- { label: t('Pie Chart'), value: 'pie' },
773
- { label: t('Metric KPI'), value: 'metric' },
774
- ]}
775
- />
776
- </Form.Item>
777
- </Col>
778
- </Row>
779
-
780
- <Row gutter={16}>
781
- <Col xs={24} md={14}>
782
- <Form.Item name="query" label={t('KQL / Search Query')}>
783
- <Input placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')} />
784
- </Form.Item>
785
- </Col>
786
- <Col xs={12} md={5}>
787
- <Form.Item name="timePreset" label={t('Time Field')}>
788
- <Select
789
- options={[
790
- { label: t('Last 15 minutes'), value: 'last_15m' },
791
- { label: t('Last 1 hour'), value: 'last_1h' },
792
- { label: t('Last 24 hours'), value: 'last_24h' },
793
- { label: t('Last 7 days'), value: 'last_7d' },
794
- { label: t('Last 30 days'), value: 'last_30d' },
795
- { label: t('Last 90 days'), value: 'last_90d' },
796
- { label: t('All time'), value: 'all' },
797
- ]}
798
- />
799
- </Form.Item>
800
- </Col>
801
- <Col xs={12} md={5}>
802
- <Form.Item name="published" label={t('Published')} valuePropName="checked">
803
- <Switch />
804
- </Form.Item>
805
- </Col>
806
- </Row>
807
-
808
- {/* Structured Filters Builder */}
809
- <Card size="small" title={t('Add Filter')} style={{ marginBottom: 12 }}>
810
- <Form.List name="filters">
811
- {(fieldsList, { add, remove }) => (
812
- <Space direction="vertical" style={{ width: '100%' }}>
813
- {fieldsList.map(({ key, name }) => (
814
- <Space key={key} wrap align="baseline">
815
- <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 190 }}>
816
- <Select
817
- showSearch
818
- placeholder={t('Field')}
819
- options={studioFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
820
- />
821
- </Form.Item>
822
- <Form.Item name={[name, 'operator']} style={{ marginBottom: 0, minWidth: 160 }}>
823
- <Select options={FILTER_OPERATOR_ITEMS} />
824
- </Form.Item>
825
- <Form.Item name={[name, 'value']} style={{ marginBottom: 0 }}>
826
- <Input placeholder={t('Value')} />
827
- </Form.Item>
828
- <Form.Item name={[name, 'valueTo']} style={{ marginBottom: 0 }}>
829
- <Input placeholder={t('To Value')} style={{ width: 120 }} />
830
- </Form.Item>
831
- <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
832
- </Space>
833
- ))}
834
- <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={() => add({ operator: 'eq' })}>
835
- {t('Add Filter')}
836
- </Button>
837
- </Space>
838
- )}
839
- </Form.List>
840
- </Card>
841
-
842
- {watchedVisualization === 'table' ? (
843
- <Row gutter={16}>
844
- <Col xs={24} md={12}>
845
- <Form.Item name="columns" label={t('Columns')}>
846
- <Select
847
- mode="multiple"
848
- allowClear
849
- placeholder={t('Auto-detect columns from documents')}
850
- options={studioFields.filter((f) => !f.isSubfield).map((f) => ({ label: f.name, value: f.name }))}
851
- />
852
- </Form.Item>
853
- <Card size="small" title={t('Sort')} style={{ marginBottom: 12 }}>
854
- <Form.List name="sort">
855
- {(sortList, { add, remove }) => (
856
- <Space direction="vertical" style={{ width: '100%' }}>
857
- {sortList.map(({ key, name }) => (
858
- <Space key={key} align="baseline">
859
- <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 200 }}>
860
- <Select
861
- showSearch
862
- placeholder={t('Field')}
863
- options={aggregatableStudioFields.map((f) => ({
864
- label: f.keywordSubfield ? `${f.name} (${f.keywordSubfield})` : f.name,
865
- value: f.keywordSubfield || f.name,
866
- }))}
867
- />
868
- </Form.Item>
869
- <Form.Item name={[name, 'order']} style={{ marginBottom: 0, minWidth: 130 }}>
870
- <Select
871
- options={[
872
- { label: t('Descending'), value: 'desc' },
873
- { label: t('Ascending'), value: 'asc' },
874
- ]}
875
- />
876
- </Form.Item>
877
- <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
878
- </Space>
879
- ))}
880
- <Button
881
- size="small"
882
- type="dashed"
883
- icon={<PlusOutlined />}
884
- onClick={() => add({ order: 'desc' })}
885
- >
886
- {t('Add Sort')}
887
- </Button>
888
- </Space>
889
- )}
890
- </Form.List>
891
- </Card>
892
- </Col>
893
- <Col xs={24} md={12}>
894
- <Row gutter={12}>
895
- <Col span={8}>
896
- <Form.Item name="pageSize" label={t('Page Size')}>
897
- <InputNumber min={5} max={200} style={{ width: '100%' }} />
898
- </Form.Item>
899
- </Col>
900
- <Col span={8}>
901
- <Form.Item
902
- name="showHistogram"
903
- label={t('Show time histogram above table')}
904
- valuePropName="checked"
905
- >
906
- <Switch />
907
- </Form.Item>
908
- </Col>
909
- <Col span={8}>
910
- <Form.Item
911
- name="allowInteractiveControls"
912
- label={t('Allow interactive search/filter on block')}
913
- valuePropName="checked"
914
- >
915
- <Switch />
916
- </Form.Item>
917
- </Col>
918
- </Row>
919
- <Form.Item name="description" label={t('Description')}>
920
- <Input.TextArea rows={2} />
921
- </Form.Item>
922
- </Col>
923
- </Row>
924
- ) : (
925
- <Card size="small" style={{ marginBottom: 12 }}>
926
- <Row gutter={16}>
927
- {watchedVisualization !== 'metric' && (
928
- <>
929
- <Col xs={12} md={6}>
930
- <Form.Item name="bucketType" label={t('Bucket Type')}>
931
- <Select
932
- options={[
933
- { label: t('Date Histogram'), value: 'date_histogram' },
934
- { label: t('Top Terms'), value: 'terms' },
935
- ]}
936
- />
937
- </Form.Item>
938
- </Col>
939
- <Col xs={12} md={6}>
940
- <Form.Item name="bucketField" label={t('Bucket Field')}>
941
- <Select
942
- showSearch
943
- allowClear
944
- options={aggregatableStudioFields.map((f) => ({
945
- label: f.keywordSubfield ? `${f.name} → ${f.keywordSubfield}` : f.name,
946
- value: f.keywordSubfield || f.name,
947
- }))}
948
- />
949
- </Form.Item>
950
- </Col>
951
- {watchedBucketType === 'date_histogram' ? (
952
- <Col xs={12} md={4}>
953
- <Form.Item name="calendarInterval" label={t('Interval')}>
954
- <Select
955
- options={[
956
- { label: 'Auto', value: 'auto' },
957
- { label: '1m', value: '1m' },
958
- { label: '5m', value: '5m' },
959
- { label: '15m', value: '15m' },
960
- { label: '1h', value: '1h' },
961
- { label: '1d', value: '1d' },
962
- { label: '1w', value: '1w' },
963
- { label: '1M', value: '1M' },
964
- ]}
965
- />
966
- </Form.Item>
967
- </Col>
968
- ) : (
969
- <Col xs={12} md={4}>
970
- <Form.Item name="topN" label={t('Top N')}>
971
- <InputNumber min={1} max={50} style={{ width: '100%' }} />
972
- </Form.Item>
973
- </Col>
974
- )}
975
- </>
976
- )}
977
- <Col xs={12} md={4}>
978
- <Form.Item name="metricType" label={t('Metric')}>
979
- <Select
980
- options={[
981
- { label: 'Count', value: 'count' },
982
- { label: 'Sum', value: 'sum' },
983
- { label: 'Average', value: 'avg' },
984
- { label: 'Min', value: 'min' },
985
- { label: 'Max', value: 'max' },
986
- { label: 'Unique (Cardinality)', value: 'cardinality' },
987
- ]}
988
- />
989
- </Form.Item>
990
- </Col>
991
- {watchedMetricType !== 'count' && (
992
- <Col xs={12} md={4}>
993
- <Form.Item name="metricField" label={t('Metric Field')}>
994
- <Select
995
- showSearch
996
- options={(watchedMetricType === 'cardinality'
997
- ? aggregatableStudioFields
998
- : numericStudioFields.length > 0
999
- ? numericStudioFields
1000
- : aggregatableStudioFields
1001
- ).map((f) => ({
1002
- label: f.name,
1003
- value: f.keywordSubfield || f.name,
1004
- }))}
1005
- />
1006
- </Form.Item>
1007
- </Col>
1008
- )}
1009
- <Col xs={12} md={6}>
1010
- <Form.Item name="metricLabel" label={t('Metric Label')}>
1011
- <Input placeholder="Requests / Latency (ms)" />
1012
- </Form.Item>
1013
- </Col>
1014
- <Col xs={12} md={6}>
1015
- <Form.Item
1016
- name="allowInteractiveControls"
1017
- label={t('Allow interactive search/filter on block')}
1018
- valuePropName="checked"
1019
- >
1020
- <Switch />
1021
- </Form.Item>
1022
- </Col>
1023
- </Row>
1024
- </Card>
1025
- )}
1026
- </Form>
1027
-
1028
- <Divider orientation="left">{t('Preview')}</Divider>
1029
- <ElasticReportRenderer
1030
- title={reportForm.getFieldValue('title') || t('Preview')}
1031
- spec={studioPreviewSpec}
1032
- dataView={selectedDataView}
1033
- fields={studioFields}
1034
- result={previewResult}
1035
- loading={previewLoading}
1036
- error={previewError}
1037
- showToolbar={true}
1038
- onExecute={(overrides) => {
1039
- handleRunStudioPreview(overrides);
1040
- }}
1041
- />
1042
- </Drawer>
1043
- </Card>
1044
- );
1045
- };
1046
-
1047
- export default ElasticReportManager;
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import {
11
+ CopyOutlined,
12
+ DeleteOutlined,
13
+ EditOutlined,
14
+ EyeOutlined,
15
+ PlayCircleOutlined,
16
+ PlusOutlined,
17
+ ReloadOutlined,
18
+ } from '@ant-design/icons';
19
+ import { useApp } from '@nocobase/client-v2';
20
+ import {
21
+ Alert,
22
+ App,
23
+ Button,
24
+ Card,
25
+ Col,
26
+ Descriptions,
27
+ Divider,
28
+ Drawer,
29
+ Form,
30
+ Input,
31
+ InputNumber,
32
+ Modal,
33
+ Popconfirm,
34
+ Row,
35
+ Select,
36
+ Space,
37
+ Switch,
38
+ Table,
39
+ Tabs,
40
+ Tag,
41
+ Typography,
42
+ } from 'antd';
43
+ import type { TableColumnsType } from 'antd';
44
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
45
+ import type {
46
+ BucketAggType,
47
+ CalendarIntervalOption,
48
+ ChartStackMode,
49
+ EsConnectionHealthResult,
50
+ EsConnectionSummary,
51
+ EsDataViewRecord,
52
+ EsFieldCapability,
53
+ EsReportRecord,
54
+ FieldFormatType,
55
+ FilterOperator,
56
+ ID,
57
+ MetricAggType,
58
+ RecordContextBinding,
59
+ ReportExecutionResult,
60
+ ReportFilterItem,
61
+ ReportRuntimeOverrides,
62
+ ReportSortItem,
63
+ ReportSpec,
64
+ ReportVisualizationType,
65
+ RoleSummary,
66
+ TimeRangePreset,
67
+ } from '../../shared/types';
68
+ import {
69
+ executeReportPreview,
70
+ fetchAllReports,
71
+ fetchAvailableRoles,
72
+ fetchDataViewFields,
73
+ fetchDataViews,
74
+ fetchEsConnections,
75
+ fetchEsIndices,
76
+ fetchFieldTopValues,
77
+ fetchMcpInfo,
78
+ persistReport,
79
+ removeDataView,
80
+ removeReport,
81
+ saveDataView,
82
+ testEsConnection,
83
+ type ApiClientLike,
84
+ type McpInfoPayload,
85
+ } from '../api';
86
+ import { ElasticKqlInput } from '../components/ElasticKqlInput';
87
+ import { ElasticReportRenderer } from '../components/ElasticReportRenderer';
88
+ import { useT } from '../locale';
89
+
90
+ const { Paragraph, Text } = Typography;
91
+
92
+ interface FilterFormRow {
93
+ field: string;
94
+ operator: FilterOperator;
95
+ value?: string;
96
+ valueTo?: string;
97
+ }
98
+
99
+ interface ReportEditorFormValues {
100
+ title: string;
101
+ description?: string;
102
+ dataViewId: ID;
103
+ published: boolean;
104
+ allowedRoles?: string[];
105
+ visualization: ReportVisualizationType;
106
+ query?: string;
107
+ timePreset: TimeRangePreset;
108
+ timeFrom?: string;
109
+ timeTo?: string;
110
+ filters?: FilterFormRow[];
111
+ lockedFilters?: FilterFormRow[];
112
+ sort?: Array<{
113
+ field: string;
114
+ order: 'asc' | 'desc';
115
+ }>;
116
+ columns?: string[];
117
+ fieldFormats?: Array<{
118
+ field: string;
119
+ format: FieldFormatType;
120
+ }>;
121
+ contextBindings?: RecordContextBinding[];
122
+ pageSize: number;
123
+ showHistogram: boolean;
124
+ allowInteractiveControls: boolean;
125
+ allowExport: boolean;
126
+ bucketType: BucketAggType;
127
+ bucketField?: string;
128
+ calendarInterval: CalendarIntervalOption;
129
+ topN: number;
130
+ metricType: MetricAggType;
131
+ metricField?: string;
132
+ metricLabel?: string;
133
+ splitSeriesField?: string;
134
+ stackMode?: ChartStackMode;
135
+ comparePreviousPeriod?: boolean;
136
+ }
137
+
138
+ interface DataViewFormValues {
139
+ title: string;
140
+ dataSourceKey: string;
141
+ indexPattern: string;
142
+ timeField?: string;
143
+ description?: string;
144
+ allowedRoles?: string[];
145
+ }
146
+
147
+ const FILTER_OPERATOR_ITEMS: Array<{ label: string; value: FilterOperator }> = [
148
+ { label: 'is (=)', value: 'eq' },
149
+ { label: 'is not (!=)', value: 'ne' },
150
+ { label: 'contains', value: 'contains' },
151
+ { label: 'in (comma-separated)', value: 'in' },
152
+ { label: 'not in', value: 'not_in' },
153
+ { label: '>', value: 'gt' },
154
+ { label: '>=', value: 'gte' },
155
+ { label: '<', value: 'lt' },
156
+ { label: '<=', value: 'lte' },
157
+ { label: 'between', value: 'between' },
158
+ { label: 'exists', value: 'exists' },
159
+ { label: 'does not exist', value: 'not_exists' },
160
+ ];
161
+
162
+ function mapFilterRows(rows: FilterFormRow[] | undefined, prefix: string): ReportFilterItem[] {
163
+ return (rows ?? [])
164
+ .filter((f) => Boolean(f?.field))
165
+ .map((f, idx) => ({
166
+ id: `${prefix}-${idx}`,
167
+ field: f.field,
168
+ operator: f.operator || 'eq',
169
+ ...(f.value !== undefined && f.value !== '' ? { value: f.value } : {}),
170
+ ...(f.valueTo !== undefined && f.valueTo !== '' ? { valueTo: f.valueTo } : {}),
171
+ enabled: true,
172
+ }));
173
+ }
174
+
175
+ function formValuesToSpec(values: ReportEditorFormValues): ReportSpec {
176
+ const filters = mapFilterRows(values.filters, 'flt');
177
+ const lockedFilters = mapFilterRows(values.lockedFilters, 'locked');
178
+
179
+ const sort: ReportSortItem[] = (values.sort ?? [])
180
+ .filter((s) => Boolean(s?.field))
181
+ .map((s) => ({
182
+ field: s.field,
183
+ order: s.order === 'asc' ? 'asc' : 'desc',
184
+ }));
185
+
186
+ const preset = values.timePreset || 'last_24h';
187
+ const timeRange =
188
+ preset === 'custom'
189
+ ? {
190
+ preset: 'custom' as const,
191
+ ...(values.timeFrom?.trim() ? { from: values.timeFrom.trim() } : {}),
192
+ ...(values.timeTo?.trim() ? { to: values.timeTo.trim() } : {}),
193
+ }
194
+ : { preset };
195
+
196
+ const fieldFormatsMap: Record<string, FieldFormatType> = {};
197
+ for (const row of values.fieldFormats ?? []) {
198
+ if (row?.field && row.format && row.format !== 'auto') {
199
+ fieldFormatsMap[row.field] = row.format;
200
+ }
201
+ }
202
+ const contextBindings = (values.contextBindings ?? []).filter(
203
+ (b) => Boolean(b?.esField?.trim()) && Boolean(b?.recordFieldPath?.trim()),
204
+ );
205
+
206
+ return {
207
+ visualization: values.visualization || 'table',
208
+ query: values.query?.trim() ?? '',
209
+ queryMode: 'kql',
210
+ filters,
211
+ lockedFilters,
212
+ sort,
213
+ timeRange,
214
+ columns: values.columns ?? [],
215
+ ...(Object.keys(fieldFormatsMap).length > 0 ? { fieldFormats: fieldFormatsMap } : {}),
216
+ ...(contextBindings.length > 0 ? { contextBindings } : {}),
217
+ pageSize: values.pageSize || 20,
218
+ allowInteractiveControls: values.allowInteractiveControls !== false,
219
+ allowExport: values.allowExport !== false,
220
+ chart: {
221
+ bucketType: values.bucketType || 'date_histogram',
222
+ ...(values.bucketField ? { bucketField: values.bucketField } : {}),
223
+ calendarInterval: values.calendarInterval || 'auto',
224
+ topN: values.topN || 10,
225
+ metricType: values.metricType || 'count',
226
+ ...(values.metricField ? { metricField: values.metricField } : {}),
227
+ ...(values.metricLabel ? { metricLabel: values.metricLabel } : {}),
228
+ showHistogram: values.showHistogram !== false,
229
+ ...(values.splitSeriesField ? { splitSeriesField: values.splitSeriesField } : {}),
230
+ ...(values.stackMode && values.stackMode !== 'none' ? { stackMode: values.stackMode } : {}),
231
+ ...(values.comparePreviousPeriod === true ? { comparePreviousPeriod: true } : {}),
232
+ },
233
+ };
234
+ }
235
+
236
+ export const ElasticReportManager: React.FC = () => {
237
+ const t = useT();
238
+ const app = useApp();
239
+ const api = app.apiClient as unknown as ApiClientLike;
240
+ const { message } = App.useApp();
241
+
242
+ const [connections, setConnections] = useState<EsConnectionSummary[]>([]);
243
+ const [roles, setRoles] = useState<RoleSummary[]>([]);
244
+ const [dataViews, setDataViews] = useState<EsDataViewRecord[]>([]);
245
+ const [reports, setReports] = useState<EsReportRecord[]>([]);
246
+ const [mcpInfo, setMcpInfo] = useState<McpInfoPayload | null>(null);
247
+ const [loadingList, setLoadingList] = useState(false);
248
+
249
+ // Data View modal state
250
+ const [dvModalOpen, setDvModalOpen] = useState(false);
251
+ const [editingDataView, setEditingDataView] = useState<EsDataViewRecord | null>(null);
252
+ const [dvSaving, setDvSaving] = useState(false);
253
+ const [matchedIndices, setMatchedIndices] = useState<string[]>([]);
254
+ const [loadingIndices, setLoadingIndices] = useState(false);
255
+ const [testingConn, setTestingConn] = useState(false);
256
+ const [connHealth, setConnHealth] = useState<EsConnectionHealthResult | null>(null);
257
+ const [dvForm] = Form.useForm<DataViewFormValues>();
258
+
259
+ // Report Studio drawer state
260
+ const [studioOpen, setStudioOpen] = useState(false);
261
+ const [editingReport, setEditingReport] = useState<EsReportRecord | null>(null);
262
+ const [studioFields, setStudioFields] = useState<EsFieldCapability[]>([]);
263
+ const [studioPreviewSpec, setStudioPreviewSpec] = useState<ReportSpec>({ visualization: 'table' });
264
+ const [previewResult, setPreviewResult] = useState<ReportExecutionResult | null>(null);
265
+ const [previewLoading, setPreviewLoading] = useState(false);
266
+ const [previewError, setPreviewError] = useState<string | null>(null);
267
+ const [savingReport, setSavingReport] = useState(false);
268
+ const [reportForm] = Form.useForm<ReportEditorFormValues>();
269
+
270
+ const watchedVisualization = Form.useWatch('visualization', reportForm) ?? 'table';
271
+ const watchedDataViewId = Form.useWatch('dataViewId', reportForm);
272
+ const watchedTimePreset = Form.useWatch('timePreset', reportForm) ?? 'last_24h';
273
+ const watchedBucketType = Form.useWatch('bucketType', reportForm) ?? 'date_histogram';
274
+ const watchedMetricType = Form.useWatch('metricType', reportForm) ?? 'count';
275
+
276
+ const roleOptions = useMemo(
277
+ () =>
278
+ roles.map((r) => ({
279
+ label: r.title && r.title !== r.name ? `${r.title} (${r.name})` : r.name,
280
+ value: r.name,
281
+ })),
282
+ [roles],
283
+ );
284
+
285
+ const loadAll = useCallback(async () => {
286
+ setLoadingList(true);
287
+ try {
288
+ const [connList, roleList, dvList, reportList, mcpData] = await Promise.all([
289
+ fetchEsConnections(api).catch(() => []),
290
+ fetchAvailableRoles(api).catch(() => []),
291
+ fetchDataViews(api).catch(() => []),
292
+ fetchAllReports(api).catch(() => []),
293
+ fetchMcpInfo(api).catch(() => null),
294
+ ]);
295
+ setConnections(connList);
296
+ setRoles(roleList);
297
+ setDataViews(dvList);
298
+ setReports(reportList);
299
+ setMcpInfo(mcpData);
300
+ } finally {
301
+ setLoadingList(false);
302
+ }
303
+ }, [api]);
304
+
305
+ useEffect(() => {
306
+ loadAll();
307
+ }, [loadAll]);
308
+
309
+ useEffect(() => {
310
+ if (!studioOpen || watchedDataViewId === undefined || watchedDataViewId === null) {
311
+ setStudioFields([]);
312
+ return;
313
+ }
314
+ let cancelled = false;
315
+ fetchDataViewFields(api, watchedDataViewId, false)
316
+ .then((res) => {
317
+ if (!cancelled) setStudioFields(res.fields ?? []);
318
+ })
319
+ .catch(() => {
320
+ if (!cancelled) setStudioFields([]);
321
+ });
322
+ return () => {
323
+ cancelled = true;
324
+ };
325
+ }, [api, studioOpen, watchedDataViewId]);
326
+
327
+ const selectedDataView = useMemo(
328
+ () => dataViews.find((dv) => String(dv.id) === String(watchedDataViewId)) ?? null,
329
+ [dataViews, watchedDataViewId],
330
+ );
331
+
332
+ const aggregatableStudioFields = useMemo(
333
+ () => studioFields.filter((f) => f.aggregatable || Boolean(f.keywordSubfield)),
334
+ [studioFields],
335
+ );
336
+
337
+ const numericStudioFields = useMemo(
338
+ () =>
339
+ studioFields.filter((f) =>
340
+ ['long', 'integer', 'short', 'byte', 'double', 'float', 'half_float', 'scaled_float'].includes(f.type),
341
+ ),
342
+ [studioFields],
343
+ );
344
+
345
+ const openNewDataViewModal = () => {
346
+ setEditingDataView(null);
347
+ setMatchedIndices([]);
348
+ setConnHealth(null);
349
+ dvForm.resetFields();
350
+ dvForm.setFieldsValue({
351
+ dataSourceKey: connections[0]?.key,
352
+ indexPattern: '*',
353
+ timeField: '@timestamp',
354
+ allowedRoles: [],
355
+ });
356
+ setDvModalOpen(true);
357
+ };
358
+
359
+ const openEditDataViewModal = (record: EsDataViewRecord) => {
360
+ setEditingDataView(record);
361
+ setMatchedIndices([]);
362
+ setConnHealth(null);
363
+ dvForm.setFieldsValue({
364
+ title: record.title,
365
+ dataSourceKey: record.dataSourceKey,
366
+ indexPattern: record.indexPattern,
367
+ timeField: record.timeField ?? '',
368
+ description: record.description ?? '',
369
+ allowedRoles: record.allowedRoles ?? [],
370
+ });
371
+ setDvModalOpen(true);
372
+ };
373
+
374
+ const handleBrowseIndices = async () => {
375
+ const dsKey = dvForm.getFieldValue('dataSourceKey');
376
+ const pattern = dvForm.getFieldValue('indexPattern') || '*';
377
+ if (!dsKey) return;
378
+ setLoadingIndices(true);
379
+ try {
380
+ const list = await fetchEsIndices(api, dsKey, pattern);
381
+ setMatchedIndices(list);
382
+ } catch (err) {
383
+ message.error(err instanceof Error ? err.message : String(err));
384
+ } finally {
385
+ setLoadingIndices(false);
386
+ }
387
+ };
388
+
389
+ const handleTestDvConnection = async () => {
390
+ const dsKey = dvForm.getFieldValue('dataSourceKey');
391
+ const pattern = dvForm.getFieldValue('indexPattern') || '*';
392
+ if (!dsKey) return;
393
+ setTestingConn(true);
394
+ setConnHealth(null);
395
+ try {
396
+ const res = await testEsConnection(api, dsKey, pattern);
397
+ setConnHealth(res);
398
+ message.success(t('Connection verified'));
399
+ } catch (err) {
400
+ message.error(err instanceof Error ? err.message : String(err));
401
+ } finally {
402
+ setTestingConn(false);
403
+ }
404
+ };
405
+
406
+ const handleSaveDataView = async () => {
407
+ try {
408
+ const values = await dvForm.validateFields();
409
+ setDvSaving(true);
410
+ await saveDataView(api, {
411
+ ...(editingDataView ? { id: editingDataView.id } : {}),
412
+ title: values.title,
413
+ dataSourceKey: values.dataSourceKey,
414
+ indexPattern: values.indexPattern,
415
+ timeField: values.timeField || null,
416
+ description: values.description || null,
417
+ allowedRoles: values.allowedRoles ?? [],
418
+ });
419
+ message.success(t('Saved successfully'));
420
+ setDvModalOpen(false);
421
+ await loadAll();
422
+ } catch (err) {
423
+ if (err instanceof Error && 'message' in err) {
424
+ message.error(err.message);
425
+ }
426
+ } finally {
427
+ setDvSaving(false);
428
+ }
429
+ };
430
+
431
+ const openNewReportStudio = () => {
432
+ setEditingReport(null);
433
+ setPreviewResult(null);
434
+ setPreviewError(null);
435
+ reportForm.resetFields();
436
+ reportForm.setFieldsValue({
437
+ title: '',
438
+ dataViewId: dataViews[0]?.id,
439
+ published: true,
440
+ allowedRoles: [],
441
+ visualization: 'table',
442
+ query: '',
443
+ timePreset: 'last_24h',
444
+ timeFrom: '',
445
+ timeTo: '',
446
+ filters: [],
447
+ lockedFilters: [],
448
+ sort: [],
449
+ columns: [],
450
+ fieldFormats: [],
451
+ contextBindings: [],
452
+ pageSize: 20,
453
+ showHistogram: true,
454
+ allowInteractiveControls: true,
455
+ allowExport: true,
456
+ bucketType: 'date_histogram',
457
+ calendarInterval: 'auto',
458
+ topN: 10,
459
+ metricType: 'count',
460
+ stackMode: 'none',
461
+ comparePreviousPeriod: false,
462
+ });
463
+ setStudioPreviewSpec({
464
+ visualization: 'table',
465
+ query: '',
466
+ queryMode: 'kql',
467
+ filters: [],
468
+ lockedFilters: [],
469
+ sort: [],
470
+ timeRange: { preset: 'last_24h' },
471
+ columns: [],
472
+ pageSize: 20,
473
+ allowInteractiveControls: true,
474
+ allowExport: true,
475
+ chart: {
476
+ bucketType: 'date_histogram',
477
+ calendarInterval: 'auto',
478
+ topN: 10,
479
+ metricType: 'count',
480
+ showHistogram: true,
481
+ },
482
+ });
483
+ setStudioOpen(true);
484
+ };
485
+
486
+ const openEditReportStudio = (record: EsReportRecord) => {
487
+ setEditingReport(record);
488
+ setPreviewResult(null);
489
+ setPreviewError(null);
490
+ const spec = record.spec;
491
+ setStudioPreviewSpec(spec);
492
+ reportForm.setFieldsValue({
493
+ title: record.title,
494
+ description: record.description ?? '',
495
+ dataViewId: record.dataViewId,
496
+ published: record.published !== false,
497
+ allowedRoles: record.allowedRoles ?? [],
498
+ visualization: spec.visualization ?? 'table',
499
+ query: spec.query ?? '',
500
+ timePreset: spec.timeRange?.preset ?? 'last_24h',
501
+ timeFrom: spec.timeRange?.from ?? '',
502
+ timeTo: spec.timeRange?.to ?? '',
503
+ filters: (spec.filters ?? []).map((f) => ({
504
+ field: f.field,
505
+ operator: f.operator,
506
+ value: Array.isArray(f.value) ? f.value.join(', ') : f.value !== undefined ? String(f.value) : '',
507
+ valueTo: f.valueTo !== undefined ? String(f.valueTo) : '',
508
+ })),
509
+ lockedFilters: (spec.lockedFilters ?? []).map((f) => ({
510
+ field: f.field,
511
+ operator: f.operator,
512
+ value: Array.isArray(f.value) ? f.value.join(', ') : f.value !== undefined ? String(f.value) : '',
513
+ valueTo: f.valueTo !== undefined ? String(f.valueTo) : '',
514
+ })),
515
+ sort: spec.sort ?? [],
516
+ columns: spec.columns ?? [],
517
+ fieldFormats: Object.entries(spec.fieldFormats ?? {}).map(([field, format]) => ({ field, format })),
518
+ contextBindings: spec.contextBindings ?? [],
519
+ pageSize: spec.pageSize ?? 20,
520
+ showHistogram: spec.chart?.showHistogram !== false,
521
+ allowInteractiveControls: spec.allowInteractiveControls !== false,
522
+ allowExport: spec.allowExport !== false,
523
+ bucketType: spec.chart?.bucketType ?? 'date_histogram',
524
+ bucketField: spec.chart?.bucketField,
525
+ calendarInterval: spec.chart?.calendarInterval ?? 'auto',
526
+ topN: spec.chart?.topN ?? 10,
527
+ metricType: spec.chart?.metricType ?? 'count',
528
+ metricField: spec.chart?.metricField,
529
+ metricLabel: spec.chart?.metricLabel,
530
+ splitSeriesField: spec.chart?.splitSeriesField,
531
+ stackMode: spec.chart?.stackMode ?? 'none',
532
+ comparePreviousPeriod: spec.chart?.comparePreviousPeriod === true,
533
+ });
534
+ setStudioOpen(true);
535
+ };
536
+
537
+ const handleRunStudioPreview = async (overrides?: ReportRuntimeOverrides) => {
538
+ const values = reportForm.getFieldsValue(true) as ReportEditorFormValues;
539
+ if (values.dataViewId === undefined || values.dataViewId === null) {
540
+ return;
541
+ }
542
+ setPreviewLoading(true);
543
+ setPreviewError(null);
544
+ try {
545
+ const spec = formValuesToSpec(values);
546
+ if (!overrides) {
547
+ setStudioPreviewSpec(spec);
548
+ }
549
+ const res = await executeReportPreview(api, values.dataViewId, spec, overrides);
550
+ setPreviewResult(res.result);
551
+ } catch (err) {
552
+ setPreviewError(err instanceof Error ? err.message : String(err));
553
+ } finally {
554
+ setPreviewLoading(false);
555
+ }
556
+ };
557
+
558
+ const handleSaveReport = async () => {
559
+ try {
560
+ const values = await reportForm.validateFields();
561
+ setSavingReport(true);
562
+ const spec = formValuesToSpec(values);
563
+ await persistReport(api, {
564
+ ...(editingReport ? { id: editingReport.id } : {}),
565
+ title: values.title,
566
+ description: values.description || null,
567
+ dataViewId: values.dataViewId,
568
+ published: values.published !== false,
569
+ allowedRoles: values.allowedRoles ?? [],
570
+ spec,
571
+ });
572
+ message.success(t('Saved successfully'));
573
+ setStudioOpen(false);
574
+ await loadAll();
575
+ } catch (err) {
576
+ if (err instanceof Error && 'message' in err) {
577
+ message.error(err.message);
578
+ }
579
+ } finally {
580
+ setSavingReport(false);
581
+ }
582
+ };
583
+
584
+ const reportColumns: TableColumnsType<EsReportRecord> = [
585
+ {
586
+ title: t('Title'),
587
+ dataIndex: 'title',
588
+ key: 'title',
589
+ render: (val: string, row) => (
590
+ <Space direction="vertical" size={0}>
591
+ <Text strong>{val}</Text>
592
+ {row.description && (
593
+ <Text type="secondary" style={{ fontSize: 12 }}>
594
+ {row.description}
595
+ </Text>
596
+ )}
597
+ </Space>
598
+ ),
599
+ },
600
+ {
601
+ title: t('Visualization'),
602
+ dataIndex: 'visualization',
603
+ key: 'visualization',
604
+ width: 140,
605
+ render: (val: string) => <Tag color="blue">{String(val).toUpperCase()}</Tag>,
606
+ },
607
+ {
608
+ title: t('Data View'),
609
+ key: 'dataView',
610
+ render: (_: unknown, row) =>
611
+ row.dataView ? `${row.dataView.title} (${row.dataView.indexPattern})` : String(row.dataViewId),
612
+ },
613
+ {
614
+ title: t('Allowed Roles'),
615
+ key: 'allowedRoles',
616
+ width: 180,
617
+ render: (_: unknown, row) =>
618
+ row.allowedRoles && row.allowedRoles.length > 0 ? (
619
+ <Space wrap size={[4, 4]}>
620
+ {row.allowedRoles.map((r) => (
621
+ <Tag key={r}>{r}</Tag>
622
+ ))}
623
+ </Space>
624
+ ) : (
625
+ <Text type="secondary">{t('All roles')}</Text>
626
+ ),
627
+ },
628
+ {
629
+ title: t('Published'),
630
+ dataIndex: 'published',
631
+ key: 'published',
632
+ width: 120,
633
+ render: (pub: boolean) => <Tag color={pub ? 'success' : 'default'}>{pub ? t('Published') : t('Draft')}</Tag>,
634
+ },
635
+ {
636
+ title: '',
637
+ key: 'actions',
638
+ width: 180,
639
+ render: (_: unknown, row) => (
640
+ <Space>
641
+ <Button size="small" icon={<EditOutlined />} onClick={() => openEditReportStudio(row)}>
642
+ {t('Edit')}
643
+ </Button>
644
+ <Popconfirm
645
+ title={t('Confirm delete?')}
646
+ onConfirm={async () => {
647
+ await removeReport(api, row.id);
648
+ message.success(t('Deleted successfully'));
649
+ await loadAll();
650
+ }}
651
+ >
652
+ <Button size="small" danger icon={<DeleteOutlined />}>
653
+ {t('Delete')}
654
+ </Button>
655
+ </Popconfirm>
656
+ </Space>
657
+ ),
658
+ },
659
+ ];
660
+
661
+ const dataViewColumns: TableColumnsType<EsDataViewRecord> = [
662
+ { title: t('Title'), dataIndex: 'title', key: 'title' },
663
+ { title: t('Data Source (Elasticsearch)'), dataIndex: 'dataSourceKey', key: 'dataSourceKey' },
664
+ {
665
+ title: t('Index Pattern'),
666
+ dataIndex: 'indexPattern',
667
+ key: 'indexPattern',
668
+ render: (val: string) => <Tag>{val}</Tag>,
669
+ },
670
+ { title: t('Time Field'), dataIndex: 'timeField', key: 'timeField', render: (v?: string | null) => v || '—' },
671
+ {
672
+ title: t('Allowed Roles'),
673
+ key: 'allowedRoles',
674
+ width: 180,
675
+ render: (_: unknown, row) =>
676
+ row.allowedRoles && row.allowedRoles.length > 0 ? (
677
+ <Space wrap size={[4, 4]}>
678
+ {row.allowedRoles.map((r) => (
679
+ <Tag key={r}>{r}</Tag>
680
+ ))}
681
+ </Space>
682
+ ) : (
683
+ <Text type="secondary">{t('All roles')}</Text>
684
+ ),
685
+ },
686
+ {
687
+ title: t('Fields'),
688
+ key: 'fieldCount',
689
+ width: 110,
690
+ render: (_: unknown, row) => row.cachedFields?.length ?? 0,
691
+ },
692
+ {
693
+ title: '',
694
+ key: 'actions',
695
+ width: 260,
696
+ render: (_: unknown, row) => (
697
+ <Space>
698
+ <Button
699
+ size="small"
700
+ icon={<ReloadOutlined />}
701
+ onClick={async () => {
702
+ await fetchDataViewFields(api, row.id, true);
703
+ message.success(t('Saved successfully'));
704
+ await loadAll();
705
+ }}
706
+ >
707
+ {t('Refresh Fields')}
708
+ </Button>
709
+ <Button size="small" icon={<EditOutlined />} onClick={() => openEditDataViewModal(row)}>
710
+ {t('Edit')}
711
+ </Button>
712
+ <Popconfirm
713
+ title={t('Confirm delete?')}
714
+ onConfirm={async () => {
715
+ await removeDataView(api, row.id);
716
+ message.success(t('Deleted successfully'));
717
+ await loadAll();
718
+ }}
719
+ >
720
+ <Button size="small" danger icon={<DeleteOutlined />} aria-label={t('Delete')} />
721
+ </Popconfirm>
722
+ </Space>
723
+ ),
724
+ },
725
+ ];
726
+
727
+ return (
728
+ <Card variant="borderless">
729
+ <Tabs
730
+ items={[
731
+ {
732
+ key: 'reports',
733
+ label: t('Reports'),
734
+ children: (
735
+ <div>
736
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
737
+ <Space>
738
+ <Button type="primary" icon={<PlusOutlined />} onClick={openNewReportStudio}>
739
+ {t('New Report')}
740
+ </Button>
741
+ <Button icon={<ReloadOutlined />} onClick={loadAll}>
742
+ {t('Refresh')}
743
+ </Button>
744
+ </Space>
745
+ </div>
746
+ <Table<EsReportRecord>
747
+ rowKey="id"
748
+ scroll={{ x: 'max-content' }}
749
+ loading={loadingList}
750
+ columns={reportColumns}
751
+ dataSource={reports}
752
+ />
753
+ </div>
754
+ ),
755
+ },
756
+ {
757
+ key: 'dataViews',
758
+ label: t('Data Views'),
759
+ children: (
760
+ <div>
761
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
762
+ <Space>
763
+ <Button type="primary" icon={<PlusOutlined />} onClick={openNewDataViewModal}>
764
+ {t('New Data View')}
765
+ </Button>
766
+ <Button icon={<ReloadOutlined />} onClick={loadAll}>
767
+ {t('Refresh')}
768
+ </Button>
769
+ </Space>
770
+ </div>
771
+ <Table<EsDataViewRecord>
772
+ rowKey="id"
773
+ scroll={{ x: 'max-content' }}
774
+ loading={loadingList}
775
+ columns={dataViewColumns}
776
+ dataSource={dataViews}
777
+ />
778
+ </div>
779
+ ),
780
+ },
781
+ {
782
+ key: 'mcp',
783
+ label: t('MCP & AI Employee'),
784
+ children: (
785
+ <Space direction="vertical" size={16} style={{ width: '100%' }}>
786
+ <Alert
787
+ type="info"
788
+ showIcon
789
+ message={t('AI Employee Usage')}
790
+ description={t(
791
+ 'This plugin automatically registers the elastic-report MCP server (with user context) and AI Employee tools so AI agents can inspect fields, preview Elasticsearch queries, and publish Saved Reports ready to select in blocks.',
792
+ )}
793
+ />
794
+ {mcpInfo && (
795
+ <Descriptions bordered column={1} size="small">
796
+ <Descriptions.Item label={t('MCP Server Name')}>
797
+ <Tag color="purple">{mcpInfo.serverName}</Tag>
798
+ </Descriptions.Item>
799
+ <Descriptions.Item label={t('Dedicated MCP Endpoint')}>
800
+ <Space>
801
+ <code>{mcpInfo.endpointPath}</code>
802
+ <Button
803
+ size="small"
804
+ icon={<CopyOutlined />}
805
+ onClick={() => {
806
+ navigator.clipboard?.writeText(window.location.origin + mcpInfo.endpointPath);
807
+ message.success(t('Copied to clipboard'));
808
+ }}
809
+ >
810
+ {t('Copy')}
811
+ </Button>
812
+ </Space>
813
+ </Descriptions.Item>
814
+ </Descriptions>
815
+ )}
816
+ <Card size="small" title={t('Exposed MCP Tools')}>
817
+ <Table
818
+ size="small"
819
+ rowKey="name"
820
+ pagination={false}
821
+ dataSource={mcpInfo?.tools ?? []}
822
+ columns={[
823
+ {
824
+ title: 'Tool',
825
+ dataIndex: 'name',
826
+ key: 'name',
827
+ width: 220,
828
+ render: (v: string) => <code>{v}</code>,
829
+ },
830
+ { title: t('Description'), dataIndex: 'description', key: 'description' },
831
+ ]}
832
+ />
833
+ </Card>
834
+ </Space>
835
+ ),
836
+ },
837
+ ]}
838
+ />
839
+
840
+ {/* Data View Modal */}
841
+ <Modal
842
+ title={editingDataView ? t('Edit Data View') : t('New Data View')}
843
+ open={dvModalOpen}
844
+ confirmLoading={dvSaving}
845
+ onCancel={() => setDvModalOpen(false)}
846
+ onOk={handleSaveDataView}
847
+ width={600}
848
+ style={{ maxWidth: 'calc(100vw - 32px)' }}
849
+ centered
850
+ >
851
+ <Form form={dvForm} layout="vertical">
852
+ <Form.Item name="title" label={t('Title')} rules={[{ required: true }]}>
853
+ <Input placeholder="Application Logs" />
854
+ </Form.Item>
855
+ <Form.Item
856
+ name="dataSourceKey"
857
+ label={t('Data Source (Elasticsearch)')}
858
+ rules={[{ required: true }]}
859
+ extra={t(
860
+ 'Configure Elasticsearch 8.x TLS, CA Fingerprint, API Key, or Bearer Token in Data Source Manager',
861
+ )}
862
+ >
863
+ <Select
864
+ onChange={() => setConnHealth(null)}
865
+ options={connections.map((c) => {
866
+ const badgeParts = [
867
+ c.endpointMode === 'cloud' ? 'Cloud' : 'Nodes',
868
+ c.authMode && c.authMode !== 'none' ? c.authMode : undefined,
869
+ c.tlsMode === 'caFingerprint'
870
+ ? 'CA-FP'
871
+ : c.tlsMode === 'caCert'
872
+ ? 'CA-PEM'
873
+ : c.tlsMode === 'skip'
874
+ ? 'No-TLS-Verify'
875
+ : undefined,
876
+ ].filter(Boolean);
877
+ return {
878
+ label: `${c.displayName} (${c.key})${badgeParts.length ? ` · [${badgeParts.join(' / ')}]` : ''}`,
879
+ value: c.key,
880
+ };
881
+ })}
882
+ />
883
+ </Form.Item>
884
+ <div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
885
+ <Button size="small" loading={testingConn} onClick={handleTestDvConnection}>
886
+ {t('Test Connection')}
887
+ </Button>
888
+ {connHealth?.ok && (
889
+ <Tag color="success">
890
+ {t('Connection verified')}
891
+ {connHealth.clusterName ? `: ${connHealth.clusterName}` : ''}
892
+ {connHealth.version ? ` (v${connHealth.version})` : ''}
893
+ {connHealth.limitedPrivileges ? ` · ${t('Index-scoped role')}` : ''}
894
+ </Tag>
895
+ )}
896
+ </div>
897
+ <Form.Item name="indexPattern" label={t('Index Pattern')} rules={[{ required: true }]}>
898
+ <Space.Compact style={{ width: '100%' }}>
899
+ <Input placeholder="logs-*" />
900
+ <Button loading={loadingIndices} icon={<EyeOutlined />} onClick={handleBrowseIndices}>
901
+ {t('Browse Indices')}
902
+ </Button>
903
+ </Space.Compact>
904
+ </Form.Item>
905
+ {matchedIndices.length > 0 && (
906
+ <Paragraph style={{ fontSize: 12 }}>
907
+ <Text strong>{t('Matching Indices')}: </Text>
908
+ {matchedIndices.slice(0, 20).map((idx) => (
909
+ <Tag key={idx} style={{ marginBottom: 4 }}>
910
+ {idx}
911
+ </Tag>
912
+ ))}
913
+ </Paragraph>
914
+ )}
915
+ <Form.Item name="timeField" label={t('Time Field')}>
916
+ <Input placeholder="@timestamp" />
917
+ </Form.Item>
918
+ <Form.Item name="allowedRoles" label={t('Allowed Roles')}>
919
+ <Select
920
+ mode="tags"
921
+ allowClear
922
+ placeholder={t('Leave empty to allow all authenticated users')}
923
+ options={roleOptions}
924
+ />
925
+ </Form.Item>
926
+ <Form.Item name="description" label={t('Description')}>
927
+ <Input.TextArea rows={2} />
928
+ </Form.Item>
929
+ </Form>
930
+ </Modal>
931
+
932
+ {/* Report Studio Drawer */}
933
+ <Drawer
934
+ title={editingReport ? t('Edit Report') : t('New Report')}
935
+ open={studioOpen}
936
+ onClose={() => setStudioOpen(false)}
937
+ width="min(1080px, 96vw)"
938
+ extra={
939
+ <Space>
940
+ <Button icon={<PlayCircleOutlined />} loading={previewLoading} onClick={() => handleRunStudioPreview()}>
941
+ {t('Run Preview')}
942
+ </Button>
943
+ <Button type="primary" loading={savingReport} onClick={handleSaveReport}>
944
+ {t('Save')}
945
+ </Button>
946
+ </Space>
947
+ }
948
+ >
949
+ <Form form={reportForm} layout="vertical">
950
+ <Row gutter={16}>
951
+ <Col xs={24} md={10}>
952
+ <Form.Item name="title" label={t('Title')} rules={[{ required: true }]}>
953
+ <Input placeholder="HTTP 5xx Error Logs" />
954
+ </Form.Item>
955
+ </Col>
956
+ <Col xs={24} md={7}>
957
+ <Form.Item name="dataViewId" label={t('Data View')} rules={[{ required: true }]}>
958
+ <Select
959
+ options={dataViews.map((dv) => ({
960
+ label: `${dv.title} (${dv.indexPattern})`,
961
+ value: dv.id,
962
+ }))}
963
+ />
964
+ </Form.Item>
965
+ </Col>
966
+ <Col xs={24} md={7}>
967
+ <Form.Item name="visualization" label={t('Visualization')} rules={[{ required: true }]}>
968
+ <Select
969
+ options={[
970
+ { label: t('Table (Discover)'), value: 'table' },
971
+ { label: t('Bar Chart'), value: 'bar' },
972
+ { label: t('Line Chart'), value: 'line' },
973
+ { label: t('Area Chart'), value: 'area' },
974
+ { label: t('Pie Chart'), value: 'pie' },
975
+ { label: t('Metric KPI'), value: 'metric' },
976
+ ]}
977
+ />
978
+ </Form.Item>
979
+ </Col>
980
+ </Row>
981
+
982
+ <Row gutter={16}>
983
+ <Col xs={24} md={10}>
984
+ <Form.Item name="query" label={t('KQL / Search Query')}>
985
+ <ElasticKqlInput
986
+ placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
987
+ fields={studioFields}
988
+ sampleRows={previewResult?.rows}
989
+ style={{ width: '100%' }}
990
+ onInspectTopValues={
991
+ watchedDataViewId !== undefined && watchedDataViewId !== null
992
+ ? (field) =>
993
+ fetchFieldTopValues(api, {
994
+ dataViewId: watchedDataViewId,
995
+ field,
996
+ size: 12,
997
+ })
998
+ : undefined
999
+ }
1000
+ onSubmit={() => {
1001
+ handleRunStudioPreview();
1002
+ }}
1003
+ />
1004
+ </Form.Item>
1005
+ </Col>
1006
+ <Col xs={12} md={5}>
1007
+ <Form.Item name="timePreset" label={t('Time Field')}>
1008
+ <Select
1009
+ options={[
1010
+ { label: t('Last 15 minutes'), value: 'last_15m' },
1011
+ { label: t('Last 1 hour'), value: 'last_1h' },
1012
+ { label: t('Last 24 hours'), value: 'last_24h' },
1013
+ { label: t('Last 7 days'), value: 'last_7d' },
1014
+ { label: t('Last 30 days'), value: 'last_30d' },
1015
+ { label: t('Last 90 days'), value: 'last_90d' },
1016
+ { label: t('All time'), value: 'all' },
1017
+ { label: t('Custom range'), value: 'custom' },
1018
+ ]}
1019
+ />
1020
+ </Form.Item>
1021
+ </Col>
1022
+ <Col xs={12} md={6}>
1023
+ <Form.Item name="allowedRoles" label={t('Allowed Roles')}>
1024
+ <Select
1025
+ mode="tags"
1026
+ allowClear
1027
+ placeholder={t('Leave empty to allow all authenticated users')}
1028
+ options={roleOptions}
1029
+ />
1030
+ </Form.Item>
1031
+ </Col>
1032
+ <Col xs={12} md={3}>
1033
+ <Form.Item name="published" label={t('Published')} valuePropName="checked">
1034
+ <Switch />
1035
+ </Form.Item>
1036
+ </Col>
1037
+ </Row>
1038
+
1039
+ {watchedTimePreset === 'custom' && (
1040
+ <Row gutter={16}>
1041
+ <Col xs={12} md={6}>
1042
+ <Form.Item name="timeFrom" label={t('From')}>
1043
+ <Input placeholder="2026-11-29T00:00:00Z / now-24h" />
1044
+ </Form.Item>
1045
+ </Col>
1046
+ <Col xs={12} md={6}>
1047
+ <Form.Item name="timeTo" label={t('To')}>
1048
+ <Input placeholder="2026-11-30T00:00:00Z / now" />
1049
+ </Form.Item>
1050
+ </Col>
1051
+ </Row>
1052
+ )}
1053
+
1054
+ {/* Mandatory Server-Enforced Locked Filters Builder */}
1055
+ <Card size="small" title={t('Locked Security Filters (Server-enforced)')} style={{ marginBottom: 12 }}>
1056
+ <Form.List name="lockedFilters">
1057
+ {(lockedList, { add, remove }) => (
1058
+ <Space direction="vertical" style={{ width: '100%' }}>
1059
+ {lockedList.map(({ key, name }) => (
1060
+ <Space key={key} wrap align="baseline">
1061
+ <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 190 }}>
1062
+ <Select
1063
+ showSearch
1064
+ placeholder={t('Field')}
1065
+ options={studioFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
1066
+ />
1067
+ </Form.Item>
1068
+ <Form.Item name={[name, 'operator']} style={{ marginBottom: 0, minWidth: 160 }}>
1069
+ <Select options={FILTER_OPERATOR_ITEMS} />
1070
+ </Form.Item>
1071
+ <Form.Item name={[name, 'value']} style={{ marginBottom: 0 }}>
1072
+ <Input placeholder={t('Value')} />
1073
+ </Form.Item>
1074
+ <Form.Item name={[name, 'valueTo']} style={{ marginBottom: 0 }}>
1075
+ <Input placeholder={t('To Value')} style={{ width: 120 }} />
1076
+ </Form.Item>
1077
+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
1078
+ </Space>
1079
+ ))}
1080
+ <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={() => add({ operator: 'eq' })}>
1081
+ {t('Add Locked Filter')}
1082
+ </Button>
1083
+ </Space>
1084
+ )}
1085
+ </Form.List>
1086
+ </Card>
1087
+
1088
+ {/* Structured Filters Builder */}
1089
+ <Card size="small" title={t('Add Filter')} style={{ marginBottom: 12 }}>
1090
+ <Form.List name="filters">
1091
+ {(fieldsList, { add, remove }) => (
1092
+ <Space direction="vertical" style={{ width: '100%' }}>
1093
+ {fieldsList.map(({ key, name }) => (
1094
+ <Space key={key} wrap align="baseline">
1095
+ <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 190 }}>
1096
+ <Select
1097
+ showSearch
1098
+ placeholder={t('Field')}
1099
+ options={studioFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
1100
+ />
1101
+ </Form.Item>
1102
+ <Form.Item name={[name, 'operator']} style={{ marginBottom: 0, minWidth: 160 }}>
1103
+ <Select options={FILTER_OPERATOR_ITEMS} />
1104
+ </Form.Item>
1105
+ <Form.Item name={[name, 'value']} style={{ marginBottom: 0 }}>
1106
+ <Input placeholder={t('Value')} />
1107
+ </Form.Item>
1108
+ <Form.Item name={[name, 'valueTo']} style={{ marginBottom: 0 }}>
1109
+ <Input placeholder={t('To Value')} style={{ width: 120 }} />
1110
+ </Form.Item>
1111
+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
1112
+ </Space>
1113
+ ))}
1114
+ <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={() => add({ operator: 'eq' })}>
1115
+ {t('Add Filter')}
1116
+ </Button>
1117
+ </Space>
1118
+ )}
1119
+ </Form.List>
1120
+ </Card>
1121
+
1122
+ {watchedVisualization === 'table' ? (
1123
+ <Row gutter={16}>
1124
+ <Col xs={24} md={12}>
1125
+ <Form.Item name="columns" label={t('Columns')}>
1126
+ <Select
1127
+ mode="multiple"
1128
+ allowClear
1129
+ placeholder={t('Auto-detect columns from documents')}
1130
+ options={studioFields.filter((f) => !f.isSubfield).map((f) => ({ label: f.name, value: f.name }))}
1131
+ />
1132
+ </Form.Item>
1133
+ <Card size="small" title={t('Sort')} style={{ marginBottom: 12 }}>
1134
+ <Form.List name="sort">
1135
+ {(sortList, { add, remove }) => (
1136
+ <Space direction="vertical" style={{ width: '100%' }}>
1137
+ {sortList.map(({ key, name }) => (
1138
+ <Space key={key} align="baseline">
1139
+ <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 200 }}>
1140
+ <Select
1141
+ showSearch
1142
+ placeholder={t('Field')}
1143
+ options={aggregatableStudioFields.map((f) => ({
1144
+ label: f.keywordSubfield ? `${f.name} (${f.keywordSubfield})` : f.name,
1145
+ value: f.keywordSubfield || f.name,
1146
+ }))}
1147
+ />
1148
+ </Form.Item>
1149
+ <Form.Item name={[name, 'order']} style={{ marginBottom: 0, minWidth: 130 }}>
1150
+ <Select
1151
+ options={[
1152
+ { label: t('Descending'), value: 'desc' },
1153
+ { label: t('Ascending'), value: 'asc' },
1154
+ ]}
1155
+ />
1156
+ </Form.Item>
1157
+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
1158
+ </Space>
1159
+ ))}
1160
+ <Button
1161
+ size="small"
1162
+ type="dashed"
1163
+ icon={<PlusOutlined />}
1164
+ onClick={() => add({ order: 'desc' })}
1165
+ >
1166
+ {t('Add Sort')}
1167
+ </Button>
1168
+ </Space>
1169
+ )}
1170
+ </Form.List>
1171
+ </Card>
1172
+ </Col>
1173
+ <Col xs={24} md={12}>
1174
+ <Row gutter={12}>
1175
+ <Col span={6}>
1176
+ <Form.Item name="pageSize" label={t('Page Size')}>
1177
+ <InputNumber min={5} max={200} style={{ width: '100%' }} />
1178
+ </Form.Item>
1179
+ </Col>
1180
+ <Col span={6}>
1181
+ <Form.Item
1182
+ name="showHistogram"
1183
+ label={t('Show time histogram above table')}
1184
+ valuePropName="checked"
1185
+ >
1186
+ <Switch />
1187
+ </Form.Item>
1188
+ </Col>
1189
+ <Col span={6}>
1190
+ <Form.Item
1191
+ name="allowInteractiveControls"
1192
+ label={t('Allow interactive search/filter on block')}
1193
+ valuePropName="checked"
1194
+ >
1195
+ <Switch />
1196
+ </Form.Item>
1197
+ </Col>
1198
+ <Col span={6}>
1199
+ <Form.Item name="allowExport" label={t('Allow data export on block')} valuePropName="checked">
1200
+ <Switch />
1201
+ </Form.Item>
1202
+ </Col>
1203
+ </Row>
1204
+ <Card size="small" title={t('Field Formats')} style={{ marginBottom: 12 }}>
1205
+ <Form.List name="fieldFormats">
1206
+ {(fmtList, { add, remove }) => (
1207
+ <Space direction="vertical" style={{ width: '100%' }}>
1208
+ {fmtList.map(({ key, name }) => (
1209
+ <Space key={key} align="baseline">
1210
+ <Form.Item name={[name, 'field']} style={{ marginBottom: 0, minWidth: 170 }}>
1211
+ <Select
1212
+ showSearch
1213
+ placeholder={t('Field')}
1214
+ options={studioFields
1215
+ .filter((f) => !f.isSubfield)
1216
+ .map((f) => ({ label: f.name, value: f.name }))}
1217
+ />
1218
+ </Form.Item>
1219
+ <Form.Item name={[name, 'format']} style={{ marginBottom: 0, minWidth: 160 }}>
1220
+ <Select
1221
+ options={[
1222
+ { label: t('Duration (ms)'), value: 'duration_ms' },
1223
+ { label: t('Bytes'), value: 'bytes' },
1224
+ { label: t('Percent (%)'), value: 'percent' },
1225
+ { label: t('Number'), value: 'number' },
1226
+ { label: t('Status Badge'), value: 'status_badge' },
1227
+ { label: t('URL Link'), value: 'url' },
1228
+ ]}
1229
+ />
1230
+ </Form.Item>
1231
+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
1232
+ </Space>
1233
+ ))}
1234
+ <Button
1235
+ size="small"
1236
+ type="dashed"
1237
+ icon={<PlusOutlined />}
1238
+ onClick={() => add({ format: 'status_badge' })}
1239
+ >
1240
+ {t('Add Field Format')}
1241
+ </Button>
1242
+ </Space>
1243
+ )}
1244
+ </Form.List>
1245
+ </Card>
1246
+ <Form.Item name="description" label={t('Description')}>
1247
+ <Input.TextArea rows={2} />
1248
+ </Form.Item>
1249
+ </Col>
1250
+ </Row>
1251
+ ) : (
1252
+ <Card size="small" style={{ marginBottom: 12 }}>
1253
+ <Row gutter={16}>
1254
+ {watchedVisualization !== 'metric' && (
1255
+ <>
1256
+ <Col xs={12} md={6}>
1257
+ <Form.Item name="bucketType" label={t('Bucket Type')}>
1258
+ <Select
1259
+ options={[
1260
+ { label: t('Date Histogram'), value: 'date_histogram' },
1261
+ { label: t('Top Terms'), value: 'terms' },
1262
+ ]}
1263
+ />
1264
+ </Form.Item>
1265
+ </Col>
1266
+ <Col xs={12} md={6}>
1267
+ <Form.Item name="bucketField" label={t('Bucket Field')}>
1268
+ <Select
1269
+ showSearch
1270
+ allowClear
1271
+ options={aggregatableStudioFields.map((f) => ({
1272
+ label: f.keywordSubfield ? `${f.name} → ${f.keywordSubfield}` : f.name,
1273
+ value: f.keywordSubfield || f.name,
1274
+ }))}
1275
+ />
1276
+ </Form.Item>
1277
+ </Col>
1278
+ {watchedBucketType === 'date_histogram' ? (
1279
+ <Col xs={12} md={4}>
1280
+ <Form.Item name="calendarInterval" label={t('Interval')}>
1281
+ <Select
1282
+ options={[
1283
+ { label: 'Auto', value: 'auto' },
1284
+ { label: '1m', value: '1m' },
1285
+ { label: '5m', value: '5m' },
1286
+ { label: '15m', value: '15m' },
1287
+ { label: '1h', value: '1h' },
1288
+ { label: '1d', value: '1d' },
1289
+ { label: '1w', value: '1w' },
1290
+ { label: '1M', value: '1M' },
1291
+ ]}
1292
+ />
1293
+ </Form.Item>
1294
+ </Col>
1295
+ ) : (
1296
+ <Col xs={12} md={4}>
1297
+ <Form.Item name="topN" label={t('Top N')}>
1298
+ <InputNumber min={1} max={50} style={{ width: '100%' }} />
1299
+ </Form.Item>
1300
+ </Col>
1301
+ )}
1302
+ {watchedVisualization !== 'pie' && (
1303
+ <>
1304
+ <Col xs={12} md={4}>
1305
+ <Form.Item name="splitSeriesField" label={t('Split Series Field')}>
1306
+ <Select
1307
+ showSearch
1308
+ allowClear
1309
+ options={aggregatableStudioFields.map((f) => ({
1310
+ label: f.keywordSubfield ? `${f.name} → ${f.keywordSubfield}` : f.name,
1311
+ value: f.keywordSubfield || f.name,
1312
+ }))}
1313
+ />
1314
+ </Form.Item>
1315
+ </Col>
1316
+ <Col xs={12} md={4}>
1317
+ <Form.Item name="stackMode" label={t('Stack Mode')}>
1318
+ <Select
1319
+ options={[
1320
+ { label: t('Grouped'), value: 'none' },
1321
+ { label: t('Stacked'), value: 'stacked' },
1322
+ { label: t('100% Stacked'), value: 'percent' },
1323
+ ]}
1324
+ />
1325
+ </Form.Item>
1326
+ </Col>
1327
+ </>
1328
+ )}
1329
+ </>
1330
+ )}
1331
+ <Col xs={12} md={4}>
1332
+ <Form.Item name="metricType" label={t('Metric')}>
1333
+ <Select
1334
+ options={[
1335
+ { label: 'Count', value: 'count' },
1336
+ { label: 'Sum', value: 'sum' },
1337
+ { label: 'Average', value: 'avg' },
1338
+ { label: 'Min', value: 'min' },
1339
+ { label: 'Max', value: 'max' },
1340
+ { label: 'P50 (Median)', value: 'p50' },
1341
+ { label: 'P95', value: 'p95' },
1342
+ { label: 'P99', value: 'p99' },
1343
+ { label: 'Unique (Cardinality)', value: 'cardinality' },
1344
+ ]}
1345
+ />
1346
+ </Form.Item>
1347
+ </Col>
1348
+ {watchedMetricType !== 'count' && (
1349
+ <Col xs={12} md={4}>
1350
+ <Form.Item name="metricField" label={t('Metric Field')}>
1351
+ <Select
1352
+ showSearch
1353
+ options={(watchedMetricType === 'cardinality'
1354
+ ? aggregatableStudioFields
1355
+ : numericStudioFields.length > 0
1356
+ ? numericStudioFields
1357
+ : aggregatableStudioFields
1358
+ ).map((f) => ({
1359
+ label: f.name,
1360
+ value: f.keywordSubfield || f.name,
1361
+ }))}
1362
+ />
1363
+ </Form.Item>
1364
+ </Col>
1365
+ )}
1366
+ <Col xs={12} md={6}>
1367
+ <Form.Item name="metricLabel" label={t('Metric Label')}>
1368
+ <Input placeholder="Requests / Latency (ms)" />
1369
+ </Form.Item>
1370
+ </Col>
1371
+ {watchedVisualization === 'metric' && (
1372
+ <Col xs={12} md={5}>
1373
+ <Form.Item
1374
+ name="comparePreviousPeriod"
1375
+ label={t('Compare previous period')}
1376
+ valuePropName="checked"
1377
+ >
1378
+ <Switch />
1379
+ </Form.Item>
1380
+ </Col>
1381
+ )}
1382
+ <Col xs={12} md={5}>
1383
+ <Form.Item
1384
+ name="allowInteractiveControls"
1385
+ label={t('Allow interactive search/filter on block')}
1386
+ valuePropName="checked"
1387
+ >
1388
+ <Switch />
1389
+ </Form.Item>
1390
+ </Col>
1391
+ </Row>
1392
+ </Card>
1393
+ )}
1394
+
1395
+ <Card size="small" title={t('Record Context Bindings')} style={{ marginBottom: 12 }}>
1396
+ <Form.List name="contextBindings">
1397
+ {(ctxList, { add, remove }) => (
1398
+ <Space direction="vertical" style={{ width: '100%' }}>
1399
+ {ctxList.map(({ key, name }) => (
1400
+ <Space key={key} wrap align="baseline">
1401
+ <Form.Item name={[name, 'esField']} style={{ marginBottom: 0, minWidth: 200 }}>
1402
+ <Select
1403
+ showSearch
1404
+ placeholder={t('Field')}
1405
+ options={studioFields.map((f) => ({ label: `${f.name} (${f.type})`, value: f.name }))}
1406
+ />
1407
+ </Form.Item>
1408
+ <Form.Item name={[name, 'recordFieldPath']} style={{ marginBottom: 0, minWidth: 220 }}>
1409
+ <Input placeholder={t('Record Field Path')} />
1410
+ </Form.Item>
1411
+ <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
1412
+ </Space>
1413
+ ))}
1414
+ <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={() => add()}>
1415
+ {t('Add Context Binding')}
1416
+ </Button>
1417
+ </Space>
1418
+ )}
1419
+ </Form.List>
1420
+ </Card>
1421
+ </Form>
1422
+
1423
+ <Divider orientation="left">{t('Preview')}</Divider>
1424
+ <ElasticReportRenderer
1425
+ title={reportForm.getFieldValue('title') || t('Preview')}
1426
+ spec={studioPreviewSpec}
1427
+ dataView={selectedDataView}
1428
+ fields={studioFields}
1429
+ result={previewResult}
1430
+ loading={previewLoading}
1431
+ error={previewError}
1432
+ showToolbar={true}
1433
+ onExecute={(overrides) => {
1434
+ handleRunStudioPreview(overrides);
1435
+ }}
1436
+ onInspectTopValues={
1437
+ watchedDataViewId !== undefined && watchedDataViewId !== null
1438
+ ? (field, overrides) =>
1439
+ fetchFieldTopValues(api, {
1440
+ dataViewId: watchedDataViewId,
1441
+ field,
1442
+ size: 8,
1443
+ overrides,
1444
+ })
1445
+ : undefined
1446
+ }
1447
+ />
1448
+ </Drawer>
1449
+ </Card>
1450
+ );
1451
+ };
1452
+
1453
+ export default ElasticReportManager;