plugin-elastic-report 0.7.0 → 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 (70) 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/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,372 +1,372 @@
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 { ClearOutlined, ClockCircleOutlined, FilterOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
11
- import { useApp } from '@nocobase/client-v2';
12
- import { Button, Card, Input, Select, Space, Tag } from 'antd';
13
- import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
14
- import type { AutoRefreshInterval, EsFieldCapability, ID, ReportTimeRange, TimeRangePreset } from '../../shared/types';
15
- import { fetchFieldTopValues, fetchPublishedReports, fetchReportMeta, type ApiClientLike } from '../api';
16
- import {
17
- clearDashboardScope,
18
- patchDashboardScope,
19
- removeDashboardFilterAt,
20
- removeDashboardFilterByField,
21
- triggerDashboardRefresh,
22
- upsertDashboardFilter,
23
- useDashboardScope,
24
- } from '../bus/DashboardFilterBus';
25
- import { useT } from '../locale';
26
- import { ElasticKqlInput } from './ElasticKqlInput';
27
-
28
- export interface ElasticFilterBarProps {
29
- scopeKey: string;
30
- referenceReportId?: ID;
31
- filterFieldsCsv?: string;
32
- showGlobalKql?: boolean;
33
- showGlobalTimeRange?: boolean;
34
- }
35
-
36
- export const ElasticFilterBar: React.FC<ElasticFilterBarProps> = ({
37
- scopeKey,
38
- referenceReportId,
39
- filterFieldsCsv = '',
40
- showGlobalKql = true,
41
- showGlobalTimeRange = true,
42
- }) => {
43
- const t = useT();
44
- const app = useApp();
45
- const apiRef = useRef<ApiClientLike>(app.apiClient as unknown as ApiClientLike);
46
- apiRef.current = app.apiClient as unknown as ApiClientLike;
47
-
48
- const shared = useDashboardScope(scopeKey);
49
- const [draftKql, setDraftKql] = useState<string>(shared.query ?? '');
50
- const [fieldOptionsMap, setFieldOptionsMap] = useState<Record<string, Array<{ label: string; value: string }>>>({});
51
- const [kqlFields, setKqlFields] = useState<EsFieldCapability[]>([]);
52
- const resolvedReportIdRef = useRef<ID | undefined>(referenceReportId);
53
- const loadingMetaRef = useRef(false);
54
-
55
- useEffect(() => {
56
- resolvedReportIdRef.current = referenceReportId;
57
- setKqlFields([]);
58
- }, [referenceReportId]);
59
-
60
- const ensureFilterBarMetaLoaded = useCallback(async () => {
61
- if (kqlFields.length > 0 || loadingMetaRef.current) {
62
- return;
63
- }
64
- loadingMetaRef.current = true;
65
- try {
66
- let targetId = resolvedReportIdRef.current;
67
- if (targetId === undefined || targetId === null || String(targetId).trim() === '') {
68
- const published = await fetchPublishedReports(apiRef.current);
69
- targetId = published[0]?.id;
70
- resolvedReportIdRef.current = targetId;
71
- }
72
- if (targetId !== undefined && targetId !== null && String(targetId).trim() !== '') {
73
- const meta = await fetchReportMeta(apiRef.current, targetId);
74
- setKqlFields(meta?.fields ?? []);
75
- }
76
- } catch {
77
- // Non-fatal: KQL input still works without schema metadata
78
- } finally {
79
- loadingMetaRef.current = false;
80
- }
81
- }, [kqlFields.length]);
82
-
83
- useEffect(() => {
84
- setDraftKql(shared.query ?? '');
85
- }, [shared.query]);
86
-
87
- const filterFields = useMemo(
88
- () =>
89
- filterFieldsCsv
90
- .split(',')
91
- .map((s) => s.trim())
92
- .filter(Boolean)
93
- .slice(0, 6),
94
- [filterFieldsCsv],
95
- );
96
-
97
- useEffect(() => {
98
- if (filterFields.length === 0) {
99
- return;
100
- }
101
- let cancelled = false;
102
- const loadTopTerms = async () => {
103
- let targetReportId: ID | undefined = referenceReportId;
104
- if (targetReportId === undefined || targetReportId === null || String(targetReportId).trim() === '') {
105
- try {
106
- const published = await fetchPublishedReports(apiRef.current);
107
- targetReportId = published[0]?.id;
108
- } catch {
109
- targetReportId = undefined;
110
- }
111
- }
112
- if (targetReportId === undefined || targetReportId === null) {
113
- return;
114
- }
115
- const entries = await Promise.all(
116
- filterFields.map(async (field) => {
117
- try {
118
- const top = await fetchFieldTopValues(apiRef.current, {
119
- reportId: targetReportId,
120
- field,
121
- size: 15,
122
- });
123
- return [
124
- field,
125
- top.buckets.map((b) => ({
126
- label: `${b.value} (${b.count})`,
127
- value: b.value,
128
- })),
129
- ] as const;
130
- } catch {
131
- return [field, []] as const;
132
- }
133
- }),
134
- );
135
- if (!cancelled) {
136
- setFieldOptionsMap(Object.fromEntries(entries));
137
- }
138
- };
139
- loadTopTerms();
140
- return () => {
141
- cancelled = true;
142
- };
143
- }, [filterFields, referenceReportId]);
144
-
145
- // Global Auto-Refresh timer (pauses automatically when browser tab is hidden)
146
- useEffect(() => {
147
- const intervalSec = shared.autoRefreshSec ?? 0;
148
- if (!intervalSec || intervalSec <= 0) {
149
- return;
150
- }
151
- const timer = setInterval(() => {
152
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
153
- return;
154
- }
155
- triggerDashboardRefresh(scopeKey);
156
- }, intervalSec * 1000);
157
- return () => {
158
- clearInterval(timer);
159
- };
160
- }, [scopeKey, shared.autoRefreshSec]);
161
-
162
- const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
163
- () => [
164
- { label: t('Last 15 minutes'), value: 'last_15m' },
165
- { label: t('Last 1 hour'), value: 'last_1h' },
166
- { label: t('Last 24 hours'), value: 'last_24h' },
167
- { label: t('Last 7 days'), value: 'last_7d' },
168
- { label: t('Last 30 days'), value: 'last_30d' },
169
- { label: t('Last 90 days'), value: 'last_90d' },
170
- { label: t('All time'), value: 'all' },
171
- { label: t('Custom range'), value: 'custom' },
172
- ],
173
- [t],
174
- );
175
-
176
- const autoRefreshOptions: Array<{ label: string; value: AutoRefreshInterval }> = useMemo(
177
- () => [
178
- { label: `${t('Auto refresh')}: ${t('Off')}`, value: 0 },
179
- { label: '10s', value: 10 },
180
- { label: '30s', value: 30 },
181
- { label: '1m', value: 60 },
182
- { label: '5m', value: 300 },
183
- ],
184
- [t],
185
- );
186
-
187
- const activeTimeRange = shared.timeRange;
188
-
189
- return (
190
- <Card
191
- size="small"
192
- style={{ width: '100%', maxWidth: '100%', minWidth: 0, boxSizing: 'border-box', overflow: 'hidden' }}
193
- >
194
- <Space wrap style={{ width: '100%', maxWidth: '100%', justifyContent: 'space-between' }}>
195
- <Space wrap style={{ maxWidth: '100%' }}>
196
- {showGlobalKql && (
197
- <ElasticKqlInput
198
- ariaLabel={t('KQL / Search Query')}
199
- placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
200
- value={draftKql}
201
- fields={kqlFields}
202
- style={{ width: 280, maxWidth: '100%' }}
203
- onFocusEnsureFields={ensureFilterBarMetaLoaded}
204
- onInspectTopValues={async (field) => {
205
- let targetId = resolvedReportIdRef.current;
206
- if (targetId === undefined || targetId === null || String(targetId).trim() === '') {
207
- const published = await fetchPublishedReports(apiRef.current);
208
- targetId = published[0]?.id;
209
- resolvedReportIdRef.current = targetId;
210
- }
211
- if (targetId === undefined || targetId === null) {
212
- return { field, resolvedField: field, totalDocs: 0, buckets: [] };
213
- }
214
- return fetchFieldTopValues(apiRef.current, {
215
- reportId: targetId,
216
- field,
217
- size: 12,
218
- });
219
- }}
220
- onChange={(val) => {
221
- setDraftKql(val);
222
- }}
223
- onClear={() => {
224
- setDraftKql('');
225
- patchDashboardScope(scopeKey, { query: '' });
226
- }}
227
- onSubmit={(submittedVal) => patchDashboardScope(scopeKey, { query: submittedVal })}
228
- />
229
- )}
230
-
231
- {showGlobalTimeRange && (
232
- <>
233
- <Select
234
- allowClear
235
- aria-label={t('Time Field')}
236
- placeholder={t('Time Field')}
237
- value={activeTimeRange?.preset}
238
- options={timeRangeOptions}
239
- style={{ minWidth: 155 }}
240
- onChange={(nextPreset: TimeRangePreset | undefined) => {
241
- if (!nextPreset) {
242
- patchDashboardScope(scopeKey, { timeRange: undefined });
243
- return;
244
- }
245
- const nextRange: ReportTimeRange =
246
- nextPreset === 'custom'
247
- ? {
248
- preset: 'custom',
249
- from: activeTimeRange?.from ?? 'now-24h',
250
- to: activeTimeRange?.to ?? 'now',
251
- }
252
- : { preset: nextPreset };
253
- patchDashboardScope(scopeKey, { timeRange: nextRange });
254
- }}
255
- />
256
- {activeTimeRange?.preset === 'custom' && (
257
- <Space.Compact>
258
- <Input
259
- aria-label={t('From')}
260
- placeholder={t('From')}
261
- value={activeTimeRange.from ?? ''}
262
- style={{ width: 160 }}
263
- onChange={(e) =>
264
- patchDashboardScope(scopeKey, {
265
- timeRange: { ...activeTimeRange, preset: 'custom', from: e.target.value },
266
- })
267
- }
268
- />
269
- <Input
270
- aria-label={t('To')}
271
- placeholder={t('To')}
272
- value={activeTimeRange.to ?? ''}
273
- style={{ width: 160 }}
274
- onChange={(e) =>
275
- patchDashboardScope(scopeKey, {
276
- timeRange: { ...activeTimeRange, preset: 'custom', to: e.target.value },
277
- })
278
- }
279
- />
280
- </Space.Compact>
281
- )}
282
- </>
283
- )}
284
-
285
- {filterFields.map((field) => {
286
- const current = shared.filters.find((f) => f.field === field && f.operator === 'eq');
287
- const currentVal =
288
- current?.value !== undefined && !Array.isArray(current.value) ? String(current.value) : undefined;
289
- return (
290
- <Select
291
- key={field}
292
- allowClear
293
- showSearch
294
- aria-label={`${t('Dashboard filter')}: ${field}`}
295
- placeholder={field}
296
- value={currentVal}
297
- options={fieldOptionsMap[field] ?? []}
298
- style={{ minWidth: 150 }}
299
- onChange={(val: string | undefined) => {
300
- if (!val) {
301
- removeDashboardFilterByField(scopeKey, field);
302
- } else {
303
- upsertDashboardFilter(scopeKey, {
304
- field,
305
- operator: 'eq',
306
- value: val,
307
- });
308
- }
309
- }}
310
- />
311
- );
312
- })}
313
- </Space>
314
-
315
- <Space wrap>
316
- <Select
317
- aria-label={t('Auto refresh')}
318
- suffixIcon={<ClockCircleOutlined />}
319
- value={shared.autoRefreshSec ?? 0}
320
- options={autoRefreshOptions}
321
- style={{ minWidth: 145 }}
322
- onChange={(sec: AutoRefreshInterval) => patchDashboardScope(scopeKey, { autoRefreshSec: sec })}
323
- />
324
- {showGlobalKql && (
325
- <Button
326
- type="primary"
327
- icon={<SearchOutlined aria-hidden="true" />}
328
- onClick={() => patchDashboardScope(scopeKey, { query: draftKql })}
329
- >
330
- {t('Apply')}
331
- </Button>
332
- )}
333
- <Button
334
- icon={<ReloadOutlined aria-hidden="true" />}
335
- aria-label={t('Refresh')}
336
- onClick={() => triggerDashboardRefresh(scopeKey)}
337
- />
338
- {(shared.filters.length > 0 || Boolean(shared.query) || Boolean(shared.timeRange)) && (
339
- <Button
340
- icon={<ClearOutlined aria-hidden="true" />}
341
- onClick={() => {
342
- setDraftKql('');
343
- clearDashboardScope(scopeKey);
344
- }}
345
- >
346
- {t('Clear dashboard filters')}
347
- </Button>
348
- )}
349
- </Space>
350
- </Space>
351
-
352
- {shared.filters.length > 0 && (
353
- <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
354
- {shared.filters.map((flt, idx) => (
355
- <Tag
356
- key={flt.id || `shared-${flt.field}-${idx}`}
357
- closable
358
- icon={<FilterOutlined />}
359
- color="cyan"
360
- onClose={(e) => {
361
- e.preventDefault();
362
- removeDashboardFilterAt(scopeKey, idx);
363
- }}
364
- >
365
- {flt.field} {flt.operator} {Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value ?? '')}
366
- </Tag>
367
- ))}
368
- </div>
369
- )}
370
- </Card>
371
- );
372
- };
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 { ClearOutlined, ClockCircleOutlined, FilterOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
11
+ import { useApp } from '@nocobase/client-v2';
12
+ import { Button, Card, Input, Select, Space, Tag } from 'antd';
13
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
14
+ import type { AutoRefreshInterval, EsFieldCapability, ID, ReportTimeRange, TimeRangePreset } from '../../shared/types';
15
+ import { fetchFieldTopValues, fetchPublishedReports, fetchReportMeta, type ApiClientLike } from '../api';
16
+ import {
17
+ clearDashboardScope,
18
+ patchDashboardScope,
19
+ removeDashboardFilterAt,
20
+ removeDashboardFilterByField,
21
+ triggerDashboardRefresh,
22
+ upsertDashboardFilter,
23
+ useDashboardScope,
24
+ } from '../bus/DashboardFilterBus';
25
+ import { useT } from '../locale';
26
+ import { ElasticKqlInput } from './ElasticKqlInput';
27
+
28
+ export interface ElasticFilterBarProps {
29
+ scopeKey: string;
30
+ referenceReportId?: ID;
31
+ filterFieldsCsv?: string;
32
+ showGlobalKql?: boolean;
33
+ showGlobalTimeRange?: boolean;
34
+ }
35
+
36
+ export const ElasticFilterBar: React.FC<ElasticFilterBarProps> = ({
37
+ scopeKey,
38
+ referenceReportId,
39
+ filterFieldsCsv = '',
40
+ showGlobalKql = true,
41
+ showGlobalTimeRange = true,
42
+ }) => {
43
+ const t = useT();
44
+ const app = useApp();
45
+ const apiRef = useRef<ApiClientLike>(app.apiClient as unknown as ApiClientLike);
46
+ apiRef.current = app.apiClient as unknown as ApiClientLike;
47
+
48
+ const shared = useDashboardScope(scopeKey);
49
+ const [draftKql, setDraftKql] = useState<string>(shared.query ?? '');
50
+ const [fieldOptionsMap, setFieldOptionsMap] = useState<Record<string, Array<{ label: string; value: string }>>>({});
51
+ const [kqlFields, setKqlFields] = useState<EsFieldCapability[]>([]);
52
+ const resolvedReportIdRef = useRef<ID | undefined>(referenceReportId);
53
+ const loadingMetaRef = useRef(false);
54
+
55
+ useEffect(() => {
56
+ resolvedReportIdRef.current = referenceReportId;
57
+ setKqlFields([]);
58
+ }, [referenceReportId]);
59
+
60
+ const ensureFilterBarMetaLoaded = useCallback(async () => {
61
+ if (kqlFields.length > 0 || loadingMetaRef.current) {
62
+ return;
63
+ }
64
+ loadingMetaRef.current = true;
65
+ try {
66
+ let targetId = resolvedReportIdRef.current;
67
+ if (targetId === undefined || targetId === null || String(targetId).trim() === '') {
68
+ const published = await fetchPublishedReports(apiRef.current);
69
+ targetId = published[0]?.id;
70
+ resolvedReportIdRef.current = targetId;
71
+ }
72
+ if (targetId !== undefined && targetId !== null && String(targetId).trim() !== '') {
73
+ const meta = await fetchReportMeta(apiRef.current, targetId);
74
+ setKqlFields(meta?.fields ?? []);
75
+ }
76
+ } catch {
77
+ // Non-fatal: KQL input still works without schema metadata
78
+ } finally {
79
+ loadingMetaRef.current = false;
80
+ }
81
+ }, [kqlFields.length]);
82
+
83
+ useEffect(() => {
84
+ setDraftKql(shared.query ?? '');
85
+ }, [shared.query]);
86
+
87
+ const filterFields = useMemo(
88
+ () =>
89
+ filterFieldsCsv
90
+ .split(',')
91
+ .map((s) => s.trim())
92
+ .filter(Boolean)
93
+ .slice(0, 6),
94
+ [filterFieldsCsv],
95
+ );
96
+
97
+ useEffect(() => {
98
+ if (filterFields.length === 0) {
99
+ return;
100
+ }
101
+ let cancelled = false;
102
+ const loadTopTerms = async () => {
103
+ let targetReportId: ID | undefined = referenceReportId;
104
+ if (targetReportId === undefined || targetReportId === null || String(targetReportId).trim() === '') {
105
+ try {
106
+ const published = await fetchPublishedReports(apiRef.current);
107
+ targetReportId = published[0]?.id;
108
+ } catch {
109
+ targetReportId = undefined;
110
+ }
111
+ }
112
+ if (targetReportId === undefined || targetReportId === null) {
113
+ return;
114
+ }
115
+ const entries = await Promise.all(
116
+ filterFields.map(async (field) => {
117
+ try {
118
+ const top = await fetchFieldTopValues(apiRef.current, {
119
+ reportId: targetReportId,
120
+ field,
121
+ size: 15,
122
+ });
123
+ return [
124
+ field,
125
+ top.buckets.map((b) => ({
126
+ label: `${b.value} (${b.count})`,
127
+ value: b.value,
128
+ })),
129
+ ] as const;
130
+ } catch {
131
+ return [field, []] as const;
132
+ }
133
+ }),
134
+ );
135
+ if (!cancelled) {
136
+ setFieldOptionsMap(Object.fromEntries(entries));
137
+ }
138
+ };
139
+ loadTopTerms();
140
+ return () => {
141
+ cancelled = true;
142
+ };
143
+ }, [filterFields, referenceReportId]);
144
+
145
+ // Global Auto-Refresh timer (pauses automatically when browser tab is hidden)
146
+ useEffect(() => {
147
+ const intervalSec = shared.autoRefreshSec ?? 0;
148
+ if (!intervalSec || intervalSec <= 0) {
149
+ return;
150
+ }
151
+ const timer = setInterval(() => {
152
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
153
+ return;
154
+ }
155
+ triggerDashboardRefresh(scopeKey);
156
+ }, intervalSec * 1000);
157
+ return () => {
158
+ clearInterval(timer);
159
+ };
160
+ }, [scopeKey, shared.autoRefreshSec]);
161
+
162
+ const timeRangeOptions: Array<{ label: string; value: TimeRangePreset }> = useMemo(
163
+ () => [
164
+ { label: t('Last 15 minutes'), value: 'last_15m' },
165
+ { label: t('Last 1 hour'), value: 'last_1h' },
166
+ { label: t('Last 24 hours'), value: 'last_24h' },
167
+ { label: t('Last 7 days'), value: 'last_7d' },
168
+ { label: t('Last 30 days'), value: 'last_30d' },
169
+ { label: t('Last 90 days'), value: 'last_90d' },
170
+ { label: t('All time'), value: 'all' },
171
+ { label: t('Custom range'), value: 'custom' },
172
+ ],
173
+ [t],
174
+ );
175
+
176
+ const autoRefreshOptions: Array<{ label: string; value: AutoRefreshInterval }> = useMemo(
177
+ () => [
178
+ { label: `${t('Auto refresh')}: ${t('Off')}`, value: 0 },
179
+ { label: '10s', value: 10 },
180
+ { label: '30s', value: 30 },
181
+ { label: '1m', value: 60 },
182
+ { label: '5m', value: 300 },
183
+ ],
184
+ [t],
185
+ );
186
+
187
+ const activeTimeRange = shared.timeRange;
188
+
189
+ return (
190
+ <Card
191
+ size="small"
192
+ style={{ width: '100%', maxWidth: '100%', minWidth: 0, boxSizing: 'border-box', overflow: 'hidden' }}
193
+ >
194
+ <Space wrap style={{ width: '100%', maxWidth: '100%', justifyContent: 'space-between' }}>
195
+ <Space wrap style={{ maxWidth: '100%' }}>
196
+ {showGlobalKql && (
197
+ <ElasticKqlInput
198
+ ariaLabel={t('KQL / Search Query')}
199
+ placeholder={t('Search KQL, e.g. status >= 500 AND service: "api"')}
200
+ value={draftKql}
201
+ fields={kqlFields}
202
+ style={{ width: 280, maxWidth: '100%' }}
203
+ onFocusEnsureFields={ensureFilterBarMetaLoaded}
204
+ onInspectTopValues={async (field) => {
205
+ let targetId = resolvedReportIdRef.current;
206
+ if (targetId === undefined || targetId === null || String(targetId).trim() === '') {
207
+ const published = await fetchPublishedReports(apiRef.current);
208
+ targetId = published[0]?.id;
209
+ resolvedReportIdRef.current = targetId;
210
+ }
211
+ if (targetId === undefined || targetId === null) {
212
+ return { field, resolvedField: field, totalDocs: 0, buckets: [] };
213
+ }
214
+ return fetchFieldTopValues(apiRef.current, {
215
+ reportId: targetId,
216
+ field,
217
+ size: 12,
218
+ });
219
+ }}
220
+ onChange={(val) => {
221
+ setDraftKql(val);
222
+ }}
223
+ onClear={() => {
224
+ setDraftKql('');
225
+ patchDashboardScope(scopeKey, { query: '' });
226
+ }}
227
+ onSubmit={(submittedVal) => patchDashboardScope(scopeKey, { query: submittedVal })}
228
+ />
229
+ )}
230
+
231
+ {showGlobalTimeRange && (
232
+ <>
233
+ <Select
234
+ allowClear
235
+ aria-label={t('Time Field')}
236
+ placeholder={t('Time Field')}
237
+ value={activeTimeRange?.preset}
238
+ options={timeRangeOptions}
239
+ style={{ minWidth: 155 }}
240
+ onChange={(nextPreset: TimeRangePreset | undefined) => {
241
+ if (!nextPreset) {
242
+ patchDashboardScope(scopeKey, { timeRange: undefined });
243
+ return;
244
+ }
245
+ const nextRange: ReportTimeRange =
246
+ nextPreset === 'custom'
247
+ ? {
248
+ preset: 'custom',
249
+ from: activeTimeRange?.from ?? 'now-24h',
250
+ to: activeTimeRange?.to ?? 'now',
251
+ }
252
+ : { preset: nextPreset };
253
+ patchDashboardScope(scopeKey, { timeRange: nextRange });
254
+ }}
255
+ />
256
+ {activeTimeRange?.preset === 'custom' && (
257
+ <Space.Compact>
258
+ <Input
259
+ aria-label={t('From')}
260
+ placeholder={t('From')}
261
+ value={activeTimeRange.from ?? ''}
262
+ style={{ width: 160 }}
263
+ onChange={(e) =>
264
+ patchDashboardScope(scopeKey, {
265
+ timeRange: { ...activeTimeRange, preset: 'custom', from: e.target.value },
266
+ })
267
+ }
268
+ />
269
+ <Input
270
+ aria-label={t('To')}
271
+ placeholder={t('To')}
272
+ value={activeTimeRange.to ?? ''}
273
+ style={{ width: 160 }}
274
+ onChange={(e) =>
275
+ patchDashboardScope(scopeKey, {
276
+ timeRange: { ...activeTimeRange, preset: 'custom', to: e.target.value },
277
+ })
278
+ }
279
+ />
280
+ </Space.Compact>
281
+ )}
282
+ </>
283
+ )}
284
+
285
+ {filterFields.map((field) => {
286
+ const current = shared.filters.find((f) => f.field === field && f.operator === 'eq');
287
+ const currentVal =
288
+ current?.value !== undefined && !Array.isArray(current.value) ? String(current.value) : undefined;
289
+ return (
290
+ <Select
291
+ key={field}
292
+ allowClear
293
+ showSearch
294
+ aria-label={`${t('Dashboard filter')}: ${field}`}
295
+ placeholder={field}
296
+ value={currentVal}
297
+ options={fieldOptionsMap[field] ?? []}
298
+ style={{ minWidth: 150 }}
299
+ onChange={(val: string | undefined) => {
300
+ if (!val) {
301
+ removeDashboardFilterByField(scopeKey, field);
302
+ } else {
303
+ upsertDashboardFilter(scopeKey, {
304
+ field,
305
+ operator: 'eq',
306
+ value: val,
307
+ });
308
+ }
309
+ }}
310
+ />
311
+ );
312
+ })}
313
+ </Space>
314
+
315
+ <Space wrap>
316
+ <Select
317
+ aria-label={t('Auto refresh')}
318
+ suffixIcon={<ClockCircleOutlined />}
319
+ value={shared.autoRefreshSec ?? 0}
320
+ options={autoRefreshOptions}
321
+ style={{ minWidth: 145 }}
322
+ onChange={(sec: AutoRefreshInterval) => patchDashboardScope(scopeKey, { autoRefreshSec: sec })}
323
+ />
324
+ {showGlobalKql && (
325
+ <Button
326
+ type="primary"
327
+ icon={<SearchOutlined aria-hidden="true" />}
328
+ onClick={() => patchDashboardScope(scopeKey, { query: draftKql })}
329
+ >
330
+ {t('Apply')}
331
+ </Button>
332
+ )}
333
+ <Button
334
+ icon={<ReloadOutlined aria-hidden="true" />}
335
+ aria-label={t('Refresh')}
336
+ onClick={() => triggerDashboardRefresh(scopeKey)}
337
+ />
338
+ {(shared.filters.length > 0 || Boolean(shared.query) || Boolean(shared.timeRange)) && (
339
+ <Button
340
+ icon={<ClearOutlined aria-hidden="true" />}
341
+ onClick={() => {
342
+ setDraftKql('');
343
+ clearDashboardScope(scopeKey);
344
+ }}
345
+ >
346
+ {t('Clear dashboard filters')}
347
+ </Button>
348
+ )}
349
+ </Space>
350
+ </Space>
351
+
352
+ {shared.filters.length > 0 && (
353
+ <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
354
+ {shared.filters.map((flt, idx) => (
355
+ <Tag
356
+ key={flt.id || `shared-${flt.field}-${idx}`}
357
+ closable
358
+ icon={<FilterOutlined />}
359
+ color="cyan"
360
+ onClose={(e) => {
361
+ e.preventDefault();
362
+ removeDashboardFilterAt(scopeKey, idx);
363
+ }}
364
+ >
365
+ {flt.field} {flt.operator} {Array.isArray(flt.value) ? flt.value.join(', ') : String(flt.value ?? '')}
366
+ </Tag>
367
+ ))}
368
+ </div>
369
+ )}
370
+ </Card>
371
+ );
372
+ };