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,486 +1,494 @@
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 type { Context } from '@nocobase/actions';
11
- import type { Application } from '@nocobase/server';
12
- import {
13
- DATA_VIEWS_COLLECTION,
14
- MAX_MCP_PREVIEW_SIZE,
15
- MAX_UI_PAGE_SIZE,
16
- REPORTS_COLLECTION,
17
- } from '../../shared/constants';
18
- import type {
19
- EsConnectionHealthResult,
20
- EsConnectionSummary,
21
- EsDataViewRecord,
22
- EsFieldCapability,
23
- EsReportRecord,
24
- FieldTopValuesResult,
25
- ID,
26
- ReportExecutionResult,
27
- ReportRuntimeOverrides,
28
- RoleSummary,
29
- } from '../../shared/types';
30
- import { getEffectiveRoles, normalizeRoleList } from '../acl-guard';
31
- import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
32
- import {
33
- type ServerUserTokenContext,
34
- buildFieldCapabilityMap,
35
- compileKqlToQueryDsl,
36
- compileSearchRequest,
37
- normalizeReportSpec,
38
- parseSearchResponse,
39
- resolveAggregatableField,
40
- } from './ReportQueryCompiler';
41
-
42
- function isRecord(value: unknown): value is Record<string, unknown> {
43
- return typeof value === 'object' && value !== null && !Array.isArray(value);
44
- }
45
-
46
- function toPlainObject(modelOrRow: unknown): Record<string, unknown> {
47
- if (isRecord(modelOrRow) && typeof modelOrRow.toJSON === 'function') {
48
- const json = modelOrRow.toJSON();
49
- return isRecord(json) ? json : {};
50
- }
51
- return isRecord(modelOrRow) ? modelOrRow : {};
52
- }
53
-
54
- function serializeDataView(row: unknown): EsDataViewRecord {
55
- const plain = toPlainObject(row);
56
- return {
57
- id: (plain.id as ID) ?? '',
58
- title: typeof plain.title === 'string' ? plain.title : '',
59
- dataSourceKey: typeof plain.dataSourceKey === 'string' ? plain.dataSourceKey : '',
60
- indexPattern: typeof plain.indexPattern === 'string' ? plain.indexPattern : '',
61
- timeField: typeof plain.timeField === 'string' && plain.timeField.trim() ? plain.timeField.trim() : null,
62
- description: typeof plain.description === 'string' ? plain.description : null,
63
- allowedRoles: normalizeRoleList(plain.allowedRoles),
64
- cachedFields: Array.isArray(plain.cachedFields) ? (plain.cachedFields as EsFieldCapability[]) : null,
65
- ...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
66
- ...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
67
- };
68
- }
69
-
70
- function serializeReport(row: unknown): EsReportRecord {
71
- const plain = toPlainObject(row);
72
- const spec = normalizeReportSpec(plain.spec, plain.visualization);
73
- return {
74
- id: (plain.id as ID) ?? '',
75
- title: typeof plain.title === 'string' ? plain.title : '',
76
- description: typeof plain.description === 'string' ? plain.description : null,
77
- dataViewId: (plain.dataViewId as ID) ?? '',
78
- dataView: isRecord(plain.dataView) ? serializeDataView(plain.dataView) : null,
79
- visualization: spec.visualization,
80
- spec,
81
- published: plain.published !== false,
82
- allowedRoles: normalizeRoleList(plain.allowedRoles),
83
- ...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
84
- ...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
85
- };
86
- }
87
-
88
- export interface UpsertDataViewInput {
89
- id?: ID;
90
- title: string;
91
- dataSourceKey: string;
92
- indexPattern: string;
93
- timeField?: string | null;
94
- description?: string | null;
95
- allowedRoles?: string[];
96
- refreshFields?: boolean;
97
- }
98
-
99
- export interface SaveReportInput {
100
- id?: ID;
101
- title: string;
102
- description?: string | null;
103
- dataViewId: ID;
104
- spec: unknown;
105
- published?: boolean;
106
- allowedRoles?: string[];
107
- }
108
-
109
- export class ElasticReportService {
110
- constructor(
111
- private readonly app: Application,
112
- private readonly connections: ElasticsearchConnectionService,
113
- ) {}
114
-
115
- async listConnections(): Promise<EsConnectionSummary[]> {
116
- return this.connections.listConnections();
117
- }
118
-
119
- async testConnection(dataSourceKey: string, indexPattern = '*'): Promise<EsConnectionHealthResult> {
120
- const client = await this.connections.getClient(dataSourceKey);
121
- return client.testConnection(indexPattern);
122
- }
123
-
124
- async listAvailableRoles(): Promise<RoleSummary[]> {
125
- if (!this.app.db.hasCollection('roles')) {
126
- return [];
127
- }
128
- const rows = await this.app.db.getRepository('roles').find({
129
- sort: ['name'],
130
- });
131
- return rows
132
- .map((row) => {
133
- const plain = toPlainObject(row);
134
- const name = typeof plain.name === 'string' ? plain.name.trim() : '';
135
- const rawTitle = typeof plain.title === 'string' && plain.title.trim() ? plain.title.trim() : name;
136
- const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, '$1');
137
- return { name, title };
138
- })
139
- .filter((r) => Boolean(r.name) && r.name !== 'anonymous');
140
- }
141
-
142
- async listIndices(dataSourceKey: string, indexPattern = '*'): Promise<string[]> {
143
- const client = await this.connections.getClient(dataSourceKey);
144
- return client.readIndices(indexPattern);
145
- }
146
-
147
- async listDataViews(): Promise<EsDataViewRecord[]> {
148
- const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
149
- const rows = await repo.find({ sort: ['-id'] });
150
- return rows.map(serializeDataView);
151
- }
152
-
153
- async getDataView(dataViewId: ID): Promise<EsDataViewRecord> {
154
- const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
155
- const row = await repo.findOne({ filterByTk: dataViewId });
156
- if (!row) {
157
- throw new Error(`Data view "${String(dataViewId)}" was not found`);
158
- }
159
- return serializeDataView(row);
160
- }
161
-
162
- async inspectFieldsBySource(dataSourceKey: string, indexPattern: string): Promise<EsFieldCapability[]> {
163
- const client = await this.connections.getClient(dataSourceKey);
164
- return client.inspectFields(indexPattern);
165
- }
166
-
167
- async inspectDataViewFields(
168
- dataViewId: ID,
169
- refresh = false,
170
- ): Promise<{
171
- dataView: EsDataViewRecord;
172
- fields: EsFieldCapability[];
173
- }> {
174
- const dataView = await this.getDataView(dataViewId);
175
- if (!refresh && Array.isArray(dataView.cachedFields) && dataView.cachedFields.length > 0) {
176
- return { dataView, fields: dataView.cachedFields };
177
- }
178
-
179
- const fields = await this.inspectFieldsBySource(dataView.dataSourceKey, dataView.indexPattern);
180
- const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
181
- await repo.update({
182
- filterByTk: dataView.id,
183
- values: { cachedFields: fields },
184
- });
185
-
186
- return {
187
- dataView: { ...dataView, cachedFields: fields },
188
- fields,
189
- };
190
- }
191
-
192
- async upsertDataView(input: UpsertDataViewInput, userId?: ID): Promise<EsDataViewRecord> {
193
- const title = input.title?.trim();
194
- const dataSourceKey = input.dataSourceKey?.trim();
195
- const indexPattern = input.indexPattern?.trim();
196
- if (!title) throw new Error('Data view title is required');
197
- if (!dataSourceKey) throw new Error('Elasticsearch dataSourceKey is required');
198
- if (!indexPattern) throw new Error('Index pattern is required');
199
-
200
- const fields = await this.inspectFieldsBySource(dataSourceKey, indexPattern);
201
- let timeField = input.timeField?.trim() || null;
202
- if (!timeField) {
203
- const autoDate =
204
- fields.find((f) => f.name === '@timestamp' && (f.type === 'date' || f.type === 'date_nanos')) ??
205
- fields.find((f) => f.type === 'date' || f.type === 'date_nanos');
206
- timeField = autoDate?.name ?? null;
207
- }
208
-
209
- const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
210
- const values: Record<string, unknown> = {
211
- title,
212
- dataSourceKey,
213
- indexPattern,
214
- timeField,
215
- description: input.description ?? null,
216
- cachedFields: fields,
217
- ...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
218
- };
219
-
220
- if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
221
- await repo.update({
222
- filterByTk: input.id,
223
- values,
224
- });
225
- return this.getDataView(input.id);
226
- }
227
-
228
- if (values.allowedRoles === undefined) {
229
- values.allowedRoles = [];
230
- }
231
- if (userId !== undefined) {
232
- values.createdById = userId;
233
- }
234
- const created = await repo.create({ values });
235
- return serializeDataView(created);
236
- }
237
-
238
- async listReports(options?: { publishedOnly?: boolean; search?: string }): Promise<EsReportRecord[]> {
239
- const repo = this.app.db.getRepository(REPORTS_COLLECTION);
240
- const filter: Record<string, unknown> = {};
241
- if (options?.publishedOnly) {
242
- filter.published = true;
243
- }
244
- if (options?.search?.trim()) {
245
- filter.title = { $includes: options.search.trim() };
246
- }
247
- const rows = await repo.find({
248
- filter,
249
- appends: ['dataView'],
250
- sort: ['-updatedAt', '-id'],
251
- });
252
- return rows.map(serializeReport);
253
- }
254
-
255
- async getReport(reportId: ID): Promise<EsReportRecord> {
256
- const repo = this.app.db.getRepository(REPORTS_COLLECTION);
257
- const row = await repo.findOne({
258
- filterByTk: reportId,
259
- appends: ['dataView'],
260
- });
261
- if (!row) {
262
- throw new Error(`Report "${String(reportId)}" was not found`);
263
- }
264
- return serializeReport(row);
265
- }
266
-
267
- async saveReport(input: SaveReportInput, userId?: ID): Promise<EsReportRecord> {
268
- const title = input.title?.trim();
269
- if (!title) {
270
- throw new Error('Report title is required');
271
- }
272
- const dataView = await this.getDataView(input.dataViewId);
273
- const spec = normalizeReportSpec(input.spec);
274
- if (spec.queryMode !== 'simple' && spec.query && spec.query.trim()) {
275
- compileKqlToQueryDsl(spec.query);
276
- }
277
- const repo = this.app.db.getRepository(REPORTS_COLLECTION);
278
-
279
- const values: Record<string, unknown> = {
280
- title,
281
- description: input.description ?? null,
282
- dataViewId: dataView.id,
283
- visualization: spec.visualization,
284
- spec,
285
- published: input.published !== false,
286
- ...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
287
- ...(userId !== undefined ? { updatedById: userId } : {}),
288
- };
289
-
290
- if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
291
- await repo.update({
292
- filterByTk: input.id,
293
- values,
294
- });
295
- return this.getReport(input.id);
296
- }
297
-
298
- if (values.allowedRoles === undefined) {
299
- values.allowedRoles = [];
300
- }
301
- if (userId !== undefined) {
302
- values.createdById = userId;
303
- }
304
- const created = await repo.create({ values });
305
- const plain = toPlainObject(created);
306
- return this.getReport(plain.id as ID);
307
- }
308
-
309
- async previewReport(params: {
310
- dataViewId: ID;
311
- spec: unknown;
312
- overrides?: ReportRuntimeOverrides;
313
- forMcp?: boolean;
314
- userContext?: ServerUserTokenContext;
315
- }): Promise<{
316
- dataView: EsDataViewRecord;
317
- result: ReportExecutionResult;
318
- }> {
319
- const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
320
- const normalizedSpec = normalizeReportSpec(params.spec);
321
- const client = await this.connections.getClient(dataView.dataSourceKey);
322
-
323
- let activePitId = params.overrides?.pitId;
324
- const needsDeepCursor =
325
- normalizedSpec.visualization === 'table' &&
326
- !activePitId &&
327
- ((params.overrides?.page ?? 1) * (params.overrides?.pageSize ?? normalizedSpec.pageSize ?? 20) > 10000 ||
328
- Boolean(params.overrides?.searchAfter));
329
-
330
- if (needsDeepCursor && !params.overrides?.searchAfter) {
331
- activePitId = (await client.openPit(dataView.indexPattern, '1m')) ?? undefined;
332
- }
333
-
334
- const { body, effectiveSpec } = compileSearchRequest({
335
- spec: normalizedSpec,
336
- overrides: params.overrides,
337
- timeField: dataView.timeField,
338
- fields,
339
- maxRowsCap: params.forMcp ? MAX_MCP_PREVIEW_SIZE : MAX_UI_PAGE_SIZE,
340
- userContext: params.userContext,
341
- usePit: Boolean(activePitId),
342
- });
343
-
344
- const rawSearch = await client.search(
345
- dataView.indexPattern,
346
- body,
347
- activePitId ? { pitId: activePitId } : undefined,
348
- );
349
- const result = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
350
- if (activePitId && !result.pitId) {
351
- result.pitId = activePitId;
352
- }
353
- return { dataView, result };
354
- }
355
-
356
- async runSavedReport(params: {
357
- reportId: ID;
358
- overrides?: ReportRuntimeOverrides;
359
- requirePublished?: boolean;
360
- forMcp?: boolean;
361
- userContext?: ServerUserTokenContext;
362
- }): Promise<{
363
- report: EsReportRecord;
364
- dataView: EsDataViewRecord;
365
- result: ReportExecutionResult;
366
- }> {
367
- const report = await this.getReport(params.reportId);
368
- if (params.requirePublished && !report.published) {
369
- throw new Error(`Report "${report.title}" is not published`);
370
- }
371
-
372
- const runtimeOverrides: ReportRuntimeOverrides | undefined =
373
- report.spec.allowInteractiveControls === false
374
- ? {
375
- contextFilters: params.overrides?.contextFilters,
376
- sharedFilters: params.overrides?.sharedFilters,
377
- timeZone: params.overrides?.timeZone,
378
- page: params.overrides?.page,
379
- pageSize: params.overrides?.pageSize,
380
- searchAfter: params.overrides?.searchAfter,
381
- pitId: params.overrides?.pitId,
382
- }
383
- : params.overrides;
384
-
385
- const { dataView, result } = await this.previewReport({
386
- dataViewId: report.dataViewId,
387
- spec: report.spec,
388
- overrides: runtimeOverrides,
389
- forMcp: params.forMcp,
390
- userContext: params.userContext,
391
- });
392
-
393
- return { report, dataView, result };
394
- }
395
-
396
- async inspectFieldTopValues(params: {
397
- dataViewId: ID;
398
- reportId?: ID;
399
- field: string;
400
- size?: number;
401
- overrides?: ReportRuntimeOverrides;
402
- userContext?: ServerUserTokenContext;
403
- }): Promise<FieldTopValuesResult> {
404
- const rawField = params.field.trim();
405
- if (!rawField) {
406
- throw new Error('field is required');
407
- }
408
-
409
- let baseSpec = normalizeReportSpec({ visualization: 'bar' });
410
- let targetDataViewId = params.dataViewId;
411
- if (params.reportId !== undefined && params.reportId !== null && String(params.reportId).trim() !== '') {
412
- const report = await this.getReport(params.reportId);
413
- targetDataViewId = report.dataViewId;
414
- baseSpec = report.spec;
415
- }
416
-
417
- const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
418
- const fieldMap = buildFieldCapabilityMap(fields);
419
- const resolvedField = resolveAggregatableField(rawField, fieldMap);
420
- const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
421
-
422
- const probeSpec = normalizeReportSpec({
423
- ...baseSpec,
424
- visualization: 'bar',
425
- chart: {
426
- bucketType: 'terms',
427
- bucketField: resolvedField,
428
- topN: topSize,
429
- metricType: 'count',
430
- },
431
- });
432
-
433
- const { body, effectiveSpec } = compileSearchRequest({
434
- spec: probeSpec,
435
- overrides: params.overrides,
436
- timeField: dataView.timeField,
437
- fields,
438
- userContext: params.userContext,
439
- });
440
-
441
- const client = await this.connections.getClient(dataView.dataSourceKey);
442
- const rawSearch = await client.search(dataView.indexPattern, body);
443
- const parsed = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
444
- const totalDocs = parsed.total;
445
-
446
- return {
447
- field: rawField,
448
- resolvedField,
449
- totalDocs,
450
- buckets: parsed.series.map((pt) => ({
451
- value: pt.label,
452
- count: pt.count,
453
- percentage: totalDocs > 0 ? Number(((pt.count / totalDocs) * 100).toFixed(1)) : 0,
454
- })),
455
- };
456
- }
457
- }
458
-
459
- export function extractCurrentUserId(ctx?: Partial<Context>): ID | undefined {
460
- const stateUser = (ctx?.state as { currentUser?: { id?: ID } } | undefined)?.currentUser?.id;
461
- if (stateUser !== undefined && stateUser !== null) return stateUser;
462
- const authUser = (ctx?.auth as { user?: { id?: ID } } | undefined)?.user?.id;
463
- if (authUser !== undefined && authUser !== null) return authUser;
464
- return undefined;
465
- }
466
-
467
- export function extractServerUserContext(ctx?: Partial<Context>): ServerUserTokenContext {
468
- const stateUser = (
469
- ctx?.state as
470
- | {
471
- currentUser?: {
472
- id?: ID;
473
- username?: string;
474
- email?: string;
475
- };
476
- }
477
- | undefined
478
- )?.currentUser;
479
- const effectiveRole = getEffectiveRoles(ctx)[0];
480
- return {
481
- userId: extractCurrentUserId(ctx),
482
- ...(typeof stateUser?.username === 'string' ? { username: stateUser.username } : {}),
483
- ...(typeof stateUser?.email === 'string' ? { email: stateUser.email } : {}),
484
- ...(effectiveRole ? { role: effectiveRole } : {}),
485
- };
486
- }
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 type { Context } from '@nocobase/actions';
11
+ import type { Transaction } from '@nocobase/database';
12
+ import type { Application } from '@nocobase/server';
13
+ import {
14
+ DATA_VIEWS_COLLECTION,
15
+ MAX_MCP_PREVIEW_SIZE,
16
+ MAX_UI_PAGE_SIZE,
17
+ REPORTS_COLLECTION,
18
+ } from '../../shared/constants';
19
+ import type {
20
+ EsConnectionHealthResult,
21
+ EsConnectionSummary,
22
+ EsDataViewRecord,
23
+ EsFieldCapability,
24
+ EsReportRecord,
25
+ FieldTopValuesResult,
26
+ ID,
27
+ ReportExecutionResult,
28
+ ReportRuntimeOverrides,
29
+ RoleSummary,
30
+ } from '../../shared/types';
31
+ import { getEffectiveRoles, normalizeRoleList } from '../acl-guard';
32
+ import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
33
+ import {
34
+ type ServerUserTokenContext,
35
+ buildFieldCapabilityMap,
36
+ compileKqlToQueryDsl,
37
+ compileSearchRequest,
38
+ normalizeReportSpec,
39
+ parseSearchResponse,
40
+ resolveAggregatableField,
41
+ } from './ReportQueryCompiler';
42
+
43
+ function isRecord(value: unknown): value is Record<string, unknown> {
44
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
45
+ }
46
+
47
+ function toPlainObject(modelOrRow: unknown): Record<string, unknown> {
48
+ if (isRecord(modelOrRow) && typeof modelOrRow.toJSON === 'function') {
49
+ const json = modelOrRow.toJSON();
50
+ return isRecord(json) ? json : {};
51
+ }
52
+ return isRecord(modelOrRow) ? modelOrRow : {};
53
+ }
54
+
55
+ function serializeDataView(row: unknown): EsDataViewRecord {
56
+ const plain = toPlainObject(row);
57
+ return {
58
+ id: (plain.id as ID) ?? '',
59
+ title: typeof plain.title === 'string' ? plain.title : '',
60
+ dataSourceKey: typeof plain.dataSourceKey === 'string' ? plain.dataSourceKey : '',
61
+ indexPattern: typeof plain.indexPattern === 'string' ? plain.indexPattern : '',
62
+ timeField: typeof plain.timeField === 'string' && plain.timeField.trim() ? plain.timeField.trim() : null,
63
+ description: typeof plain.description === 'string' ? plain.description : null,
64
+ allowedRoles: normalizeRoleList(plain.allowedRoles),
65
+ cachedFields: Array.isArray(plain.cachedFields) ? (plain.cachedFields as EsFieldCapability[]) : null,
66
+ ...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
67
+ ...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
68
+ };
69
+ }
70
+
71
+ function serializeReport(row: unknown): EsReportRecord {
72
+ const plain = toPlainObject(row);
73
+ const spec = normalizeReportSpec(plain.spec, plain.visualization);
74
+ return {
75
+ id: (plain.id as ID) ?? '',
76
+ title: typeof plain.title === 'string' ? plain.title : '',
77
+ description: typeof plain.description === 'string' ? plain.description : null,
78
+ dataViewId: (plain.dataViewId as ID) ?? '',
79
+ dataView: isRecord(plain.dataView) ? serializeDataView(plain.dataView) : null,
80
+ visualization: spec.visualization,
81
+ spec,
82
+ published: plain.published !== false,
83
+ allowedRoles: normalizeRoleList(plain.allowedRoles),
84
+ ...(typeof plain.createdAt === 'string' ? { createdAt: plain.createdAt } : {}),
85
+ ...(typeof plain.updatedAt === 'string' ? { updatedAt: plain.updatedAt } : {}),
86
+ };
87
+ }
88
+
89
+ export interface UpsertDataViewInput {
90
+ id?: ID;
91
+ title: string;
92
+ dataSourceKey: string;
93
+ indexPattern: string;
94
+ timeField?: string | null;
95
+ description?: string | null;
96
+ allowedRoles?: string[];
97
+ refreshFields?: boolean;
98
+ }
99
+
100
+ export interface SaveReportInput {
101
+ id?: ID;
102
+ title: string;
103
+ description?: string | null;
104
+ dataViewId: ID;
105
+ spec: unknown;
106
+ published?: boolean;
107
+ allowedRoles?: string[];
108
+ }
109
+
110
+ export class ElasticReportService {
111
+ constructor(
112
+ private readonly app: Application,
113
+ private readonly connections: ElasticsearchConnectionService,
114
+ ) {}
115
+
116
+ async listConnections(): Promise<EsConnectionSummary[]> {
117
+ return this.connections.listConnections();
118
+ }
119
+
120
+ async testConnection(dataSourceKey: string, indexPattern = '*'): Promise<EsConnectionHealthResult> {
121
+ const client = await this.connections.getClient(dataSourceKey);
122
+ return client.testConnection(indexPattern);
123
+ }
124
+
125
+ async listAvailableRoles(): Promise<RoleSummary[]> {
126
+ if (!this.app.db.hasCollection('roles')) {
127
+ return [];
128
+ }
129
+ const rows = await this.app.db.getRepository('roles').find({
130
+ sort: ['name'],
131
+ });
132
+ return rows
133
+ .map((row) => {
134
+ const plain = toPlainObject(row);
135
+ const name = typeof plain.name === 'string' ? plain.name.trim() : '';
136
+ const rawTitle = typeof plain.title === 'string' && plain.title.trim() ? plain.title.trim() : name;
137
+ const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, '$1');
138
+ return { name, title };
139
+ })
140
+ .filter((r) => Boolean(r.name) && r.name !== 'anonymous');
141
+ }
142
+
143
+ async listIndices(dataSourceKey: string, indexPattern = '*'): Promise<string[]> {
144
+ const client = await this.connections.getClient(dataSourceKey);
145
+ return client.readIndices(indexPattern);
146
+ }
147
+
148
+ async listDataViews(): Promise<EsDataViewRecord[]> {
149
+ const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
150
+ const rows = await repo.find({ sort: ['-id'] });
151
+ return rows.map(serializeDataView);
152
+ }
153
+
154
+ async getDataView(dataViewId: ID): Promise<EsDataViewRecord> {
155
+ const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
156
+ const row = await repo.findOne({ filterByTk: dataViewId });
157
+ if (!row) {
158
+ throw new Error(`Data view "${String(dataViewId)}" was not found`);
159
+ }
160
+ return serializeDataView(row);
161
+ }
162
+
163
+ async inspectFieldsBySource(dataSourceKey: string, indexPattern: string): Promise<EsFieldCapability[]> {
164
+ const client = await this.connections.getClient(dataSourceKey);
165
+ return client.inspectFields(indexPattern);
166
+ }
167
+
168
+ async inspectDataViewFields(
169
+ dataViewId: ID,
170
+ refresh = false,
171
+ ): Promise<{
172
+ dataView: EsDataViewRecord;
173
+ fields: EsFieldCapability[];
174
+ }> {
175
+ const dataView = await this.getDataView(dataViewId);
176
+ if (!refresh && Array.isArray(dataView.cachedFields) && dataView.cachedFields.length > 0) {
177
+ return { dataView, fields: dataView.cachedFields };
178
+ }
179
+
180
+ const fields = await this.inspectFieldsBySource(dataView.dataSourceKey, dataView.indexPattern);
181
+ const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
182
+ await repo.update({
183
+ filterByTk: dataView.id,
184
+ values: { cachedFields: fields },
185
+ });
186
+
187
+ return {
188
+ dataView: { ...dataView, cachedFields: fields },
189
+ fields,
190
+ };
191
+ }
192
+
193
+ async upsertDataView(input: UpsertDataViewInput, userId?: ID): Promise<EsDataViewRecord> {
194
+ const title = input.title?.trim();
195
+ const dataSourceKey = input.dataSourceKey?.trim();
196
+ const indexPattern = input.indexPattern?.trim();
197
+ if (!title) throw new Error('Data view title is required');
198
+ if (!dataSourceKey) throw new Error('Elasticsearch dataSourceKey is required');
199
+ if (!indexPattern) throw new Error('Index pattern is required');
200
+
201
+ const fields = await this.inspectFieldsBySource(dataSourceKey, indexPattern);
202
+ let timeField = input.timeField?.trim() || null;
203
+ if (!timeField) {
204
+ const autoDate =
205
+ fields.find((f) => f.name === '@timestamp' && (f.type === 'date' || f.type === 'date_nanos')) ??
206
+ fields.find((f) => f.type === 'date' || f.type === 'date_nanos');
207
+ timeField = autoDate?.name ?? null;
208
+ }
209
+
210
+ const repo = this.app.db.getRepository(DATA_VIEWS_COLLECTION);
211
+ const values: Record<string, unknown> = {
212
+ title,
213
+ dataSourceKey,
214
+ indexPattern,
215
+ timeField,
216
+ description: input.description ?? null,
217
+ cachedFields: fields,
218
+ ...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
219
+ };
220
+
221
+ if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
222
+ await repo.update({
223
+ filterByTk: input.id,
224
+ values,
225
+ });
226
+ return this.getDataView(input.id);
227
+ }
228
+
229
+ if (values.allowedRoles === undefined) {
230
+ values.allowedRoles = [];
231
+ }
232
+ if (userId !== undefined) {
233
+ values.createdById = userId;
234
+ }
235
+ const created = await repo.create({ values });
236
+ return serializeDataView(created);
237
+ }
238
+
239
+ async listReports(options?: { publishedOnly?: boolean; search?: string }): Promise<EsReportRecord[]> {
240
+ const repo = this.app.db.getRepository(REPORTS_COLLECTION);
241
+ const filter: Record<string, unknown> = {};
242
+ if (options?.publishedOnly) {
243
+ filter.published = true;
244
+ }
245
+ if (options?.search?.trim()) {
246
+ filter.title = { $includes: options.search.trim() };
247
+ }
248
+ const rows = await repo.find({
249
+ filter,
250
+ appends: ['dataView'],
251
+ sort: ['-updatedAt', '-id'],
252
+ });
253
+ return rows.map(serializeReport);
254
+ }
255
+
256
+ async findReport(reportId: ID, transaction?: Transaction): Promise<EsReportRecord | null> {
257
+ const repo = this.app.db.getRepository(REPORTS_COLLECTION);
258
+ const row = await repo.findOne({
259
+ filterByTk: reportId,
260
+ appends: ['dataView'],
261
+ transaction,
262
+ });
263
+ return row ? serializeReport(row) : null;
264
+ }
265
+
266
+ async getReport(reportId: ID): Promise<EsReportRecord> {
267
+ const report = await this.findReport(reportId);
268
+ if (!report) {
269
+ throw new Error(`Report "${String(reportId)}" was not found`);
270
+ }
271
+ return report;
272
+ }
273
+
274
+ async saveReport(input: SaveReportInput, userId?: ID): Promise<EsReportRecord> {
275
+ const title = input.title?.trim();
276
+ if (!title) {
277
+ throw new Error('Report title is required');
278
+ }
279
+ const dataView = await this.getDataView(input.dataViewId);
280
+ const spec = normalizeReportSpec(input.spec);
281
+ if (spec.queryMode !== 'simple' && spec.query && spec.query.trim()) {
282
+ compileKqlToQueryDsl(spec.query);
283
+ }
284
+ const repo = this.app.db.getRepository(REPORTS_COLLECTION);
285
+
286
+ const values: Record<string, unknown> = {
287
+ title,
288
+ ...(input.description !== undefined ? { description: input.description } : {}),
289
+ dataViewId: dataView.id,
290
+ visualization: spec.visualization,
291
+ spec,
292
+ ...(input.published !== undefined ? { published: input.published } : {}),
293
+ ...(input.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(input.allowedRoles) } : {}),
294
+ ...(userId !== undefined ? { updatedById: userId } : {}),
295
+ };
296
+
297
+ if (input.id !== undefined && input.id !== null && String(input.id).trim() !== '') {
298
+ await repo.update({
299
+ filterByTk: input.id,
300
+ values,
301
+ });
302
+ return this.getReport(input.id);
303
+ }
304
+
305
+ values.published ??= true;
306
+ if (values.allowedRoles === undefined) {
307
+ values.allowedRoles = [];
308
+ }
309
+ if (userId !== undefined) {
310
+ values.createdById = userId;
311
+ }
312
+ const created = await repo.create({ values });
313
+ const plain = toPlainObject(created);
314
+ return this.getReport(plain.id as ID);
315
+ }
316
+
317
+ async previewReport(params: {
318
+ dataViewId: ID;
319
+ spec: unknown;
320
+ overrides?: ReportRuntimeOverrides;
321
+ forMcp?: boolean;
322
+ userContext?: ServerUserTokenContext;
323
+ }): Promise<{
324
+ dataView: EsDataViewRecord;
325
+ result: ReportExecutionResult;
326
+ }> {
327
+ const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
328
+ const normalizedSpec = normalizeReportSpec(params.spec);
329
+ const client = await this.connections.getClient(dataView.dataSourceKey);
330
+
331
+ let activePitId = params.overrides?.pitId;
332
+ const needsDeepCursor =
333
+ normalizedSpec.visualization === 'table' &&
334
+ !activePitId &&
335
+ ((params.overrides?.page ?? 1) * (params.overrides?.pageSize ?? normalizedSpec.pageSize ?? 20) > 10000 ||
336
+ Boolean(params.overrides?.searchAfter));
337
+
338
+ if (needsDeepCursor && !params.overrides?.searchAfter) {
339
+ activePitId = (await client.openPit(dataView.indexPattern, '1m')) ?? undefined;
340
+ }
341
+
342
+ const { body, effectiveSpec } = compileSearchRequest({
343
+ spec: normalizedSpec,
344
+ overrides: params.overrides,
345
+ timeField: dataView.timeField,
346
+ fields,
347
+ maxRowsCap: params.forMcp ? MAX_MCP_PREVIEW_SIZE : MAX_UI_PAGE_SIZE,
348
+ userContext: params.userContext,
349
+ usePit: Boolean(activePitId),
350
+ });
351
+
352
+ const rawSearch = await client.search(
353
+ dataView.indexPattern,
354
+ body,
355
+ activePitId ? { pitId: activePitId } : undefined,
356
+ );
357
+ const result = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
358
+ if (activePitId && !result.pitId) {
359
+ result.pitId = activePitId;
360
+ }
361
+ return { dataView, result };
362
+ }
363
+
364
+ async runSavedReport(params: {
365
+ reportId: ID;
366
+ overrides?: ReportRuntimeOverrides;
367
+ requirePublished?: boolean;
368
+ forMcp?: boolean;
369
+ userContext?: ServerUserTokenContext;
370
+ }): Promise<{
371
+ report: EsReportRecord;
372
+ dataView: EsDataViewRecord;
373
+ result: ReportExecutionResult;
374
+ }> {
375
+ const report = await this.getReport(params.reportId);
376
+ if (params.requirePublished && !report.published) {
377
+ throw new Error(`Report "${report.title}" is not published`);
378
+ }
379
+
380
+ const runtimeOverrides: ReportRuntimeOverrides | undefined =
381
+ report.spec.allowInteractiveControls === false
382
+ ? {
383
+ contextFilters: params.overrides?.contextFilters,
384
+ sharedFilters: params.overrides?.sharedFilters,
385
+ timeZone: params.overrides?.timeZone,
386
+ page: params.overrides?.page,
387
+ pageSize: params.overrides?.pageSize,
388
+ searchAfter: params.overrides?.searchAfter,
389
+ pitId: params.overrides?.pitId,
390
+ }
391
+ : params.overrides;
392
+
393
+ const { dataView, result } = await this.previewReport({
394
+ dataViewId: report.dataViewId,
395
+ spec: report.spec,
396
+ overrides: runtimeOverrides,
397
+ forMcp: params.forMcp,
398
+ userContext: params.userContext,
399
+ });
400
+
401
+ return { report, dataView, result };
402
+ }
403
+
404
+ async inspectFieldTopValues(params: {
405
+ dataViewId: ID;
406
+ reportId?: ID;
407
+ field: string;
408
+ size?: number;
409
+ overrides?: ReportRuntimeOverrides;
410
+ userContext?: ServerUserTokenContext;
411
+ }): Promise<FieldTopValuesResult> {
412
+ const rawField = params.field.trim();
413
+ if (!rawField) {
414
+ throw new Error('field is required');
415
+ }
416
+
417
+ let baseSpec = normalizeReportSpec({ visualization: 'bar' });
418
+ let targetDataViewId = params.dataViewId;
419
+ if (params.reportId !== undefined && params.reportId !== null && String(params.reportId).trim() !== '') {
420
+ const report = await this.getReport(params.reportId);
421
+ targetDataViewId = report.dataViewId;
422
+ baseSpec = report.spec;
423
+ }
424
+
425
+ const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
426
+ const fieldMap = buildFieldCapabilityMap(fields);
427
+ const resolvedField = resolveAggregatableField(rawField, fieldMap);
428
+ const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
429
+
430
+ const probeSpec = normalizeReportSpec({
431
+ ...baseSpec,
432
+ visualization: 'bar',
433
+ chart: {
434
+ bucketType: 'terms',
435
+ bucketField: resolvedField,
436
+ topN: topSize,
437
+ metricType: 'count',
438
+ },
439
+ });
440
+
441
+ const { body, effectiveSpec } = compileSearchRequest({
442
+ spec: probeSpec,
443
+ overrides: params.overrides,
444
+ timeField: dataView.timeField,
445
+ fields,
446
+ userContext: params.userContext,
447
+ });
448
+
449
+ const client = await this.connections.getClient(dataView.dataSourceKey);
450
+ const rawSearch = await client.search(dataView.indexPattern, body);
451
+ const parsed = parseSearchResponse(rawSearch, body, effectiveSpec, dataView.timeField);
452
+ const totalDocs = parsed.total;
453
+
454
+ return {
455
+ field: rawField,
456
+ resolvedField,
457
+ totalDocs,
458
+ buckets: parsed.series.map((pt) => ({
459
+ value: pt.label,
460
+ count: pt.count,
461
+ percentage: totalDocs > 0 ? Number(((pt.count / totalDocs) * 100).toFixed(1)) : 0,
462
+ })),
463
+ };
464
+ }
465
+ }
466
+
467
+ export function extractCurrentUserId(ctx?: Partial<Context>): ID | undefined {
468
+ const stateUser = (ctx?.state as { currentUser?: { id?: ID } } | undefined)?.currentUser?.id;
469
+ if (stateUser !== undefined && stateUser !== null) return stateUser;
470
+ const authUser = (ctx?.auth as { user?: { id?: ID } } | undefined)?.user?.id;
471
+ if (authUser !== undefined && authUser !== null) return authUser;
472
+ return undefined;
473
+ }
474
+
475
+ export function extractServerUserContext(ctx?: Partial<Context>): ServerUserTokenContext {
476
+ const stateUser = (
477
+ ctx?.state as
478
+ | {
479
+ currentUser?: {
480
+ id?: ID;
481
+ username?: string;
482
+ email?: string;
483
+ };
484
+ }
485
+ | undefined
486
+ )?.currentUser;
487
+ const effectiveRole = getEffectiveRoles(ctx)[0];
488
+ return {
489
+ userId: extractCurrentUserId(ctx),
490
+ ...(typeof stateUser?.username === 'string' ? { username: stateUser.username } : {}),
491
+ ...(typeof stateUser?.email === 'string' ? { email: stateUser.email } : {}),
492
+ ...(effectiveRole ? { role: effectiveRole } : {}),
493
+ };
494
+ }