plugin-elastic-report 0.1.1 → 0.7.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 (60) hide show
  1. package/ai/skills/elastic-report/SKILLS.md +5 -3
  2. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
  5. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  6. package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +3 -2
  9. package/dist/locale/en-US.json +100 -1
  10. package/dist/locale/vi-VN.json +100 -1
  11. package/dist/locale/zh-CN.json +100 -1
  12. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  13. package/dist/server/acl-guard.js +97 -25
  14. package/dist/server/collections/es-report-data-views.js +6 -0
  15. package/dist/server/collections/es-reports.js +6 -0
  16. package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
  17. package/dist/server/plugin.js +153 -19
  18. package/dist/server/services/ElasticReportService.js +125 -11
  19. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  20. package/dist/server/services/ReportExportService.js +243 -0
  21. package/dist/server/services/ReportQueryCompiler.js +532 -91
  22. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  23. package/dist/shared/constants.js +17 -2
  24. package/package.json +3 -2
  25. package/src/client/index.tsx +16 -1
  26. package/src/client/workflow-instructions.tsx +44 -0
  27. package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
  28. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  29. package/src/client-v2/api.ts +96 -0
  30. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  31. package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
  32. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  33. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  34. package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
  35. package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
  36. package/src/client-v2/components/ReportSelect.tsx +39 -26
  37. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  38. package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
  39. package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
  40. package/src/client-v2/plugin.tsx +20 -0
  41. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  42. package/src/client-v2/workflow/instructions.tsx +149 -0
  43. package/src/locale/en-US.json +100 -1
  44. package/src/locale/vi-VN.json +100 -1
  45. package/src/locale/zh-CN.json +100 -1
  46. package/src/server/__tests__/query-compiler.test.ts +390 -1
  47. package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
  48. package/src/server/acl-guard.ts +119 -28
  49. package/src/server/collections/es-report-data-views.ts +6 -0
  50. package/src/server/collections/es-reports.ts +6 -0
  51. package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
  52. package/src/server/plugin.ts +189 -21
  53. package/src/server/services/ElasticReportService.ts +165 -5
  54. package/src/server/services/ElasticsearchConnectionService.ts +375 -48
  55. package/src/server/services/ReportExportService.ts +282 -0
  56. package/src/server/services/ReportQueryCompiler.ts +629 -94
  57. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  58. package/src/shared/constants.ts +7 -0
  59. package/src/shared/types.ts +98 -1
  60. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
@@ -0,0 +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
+ };