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
@@ -9,9 +9,22 @@
9
9
 
10
10
  import type { Context } from '@nocobase/actions';
11
11
  import type { Application } from '@nocobase/server';
12
- import type { ID } from '../../shared/types';
13
- import { assertAuthenticated, assertCanManageReports, canManageReports } from '../acl-guard';
14
- import { extractCurrentUserId, type ElasticReportService } from '../services/ElasticReportService';
12
+ import type { ID, ReportRuntimeOverrides } from '../../shared/types';
13
+ import {
14
+ assertAuthenticated,
15
+ assertCanAccessDataView,
16
+ assertCanAccessReport,
17
+ assertCanManageReports,
18
+ canAccessDataView,
19
+ canAccessReport,
20
+ canManageReports,
21
+ normalizeRoleList,
22
+ } from '../acl-guard';
23
+ import {
24
+ extractCurrentUserId,
25
+ extractServerUserContext,
26
+ type ElasticReportService,
27
+ } from '../services/ElasticReportService';
15
28
 
16
29
  export interface ElasticReportToolDefinition {
17
30
  name: string;
@@ -82,7 +95,9 @@ export function createElasticReportToolCatalog(
82
95
  async execute(_args, ctx) {
83
96
  assertAuthenticated(ctx);
84
97
  const dataViews = await reportService.listDataViews();
85
- return { dataViews };
98
+ return {
99
+ dataViews: dataViews.filter((dv) => canAccessDataView(app, ctx, dv)),
100
+ };
86
101
  },
87
102
  },
88
103
  {
@@ -119,6 +134,12 @@ export function createElasticReportToolCatalog(
119
134
  type: 'string',
120
135
  description: 'Optional description of the dataset.',
121
136
  },
137
+ allowedRoles: {
138
+ type: 'array',
139
+ items: { type: 'string' },
140
+ description:
141
+ 'Optional role names allowed to access this Data View (empty means all authenticated viewers).',
142
+ },
122
143
  },
123
144
  },
124
145
  async execute(args, ctx) {
@@ -131,6 +152,7 @@ export function createElasticReportToolCatalog(
131
152
  indexPattern: typeof args.indexPattern === 'string' ? args.indexPattern : '',
132
153
  timeField: typeof args.timeField === 'string' ? args.timeField : null,
133
154
  description: typeof args.description === 'string' ? args.description : null,
155
+ ...(args.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(args.allowedRoles) } : {}),
134
156
  },
135
157
  extractCurrentUserId(ctx),
136
158
  );
@@ -166,6 +188,9 @@ export function createElasticReportToolCatalog(
166
188
  const refresh = args.refresh === true;
167
189
  if (refresh) {
168
190
  assertCanManageReports(app, ctx);
191
+ } else {
192
+ const dv = await reportService.getDataView(dataViewId);
193
+ assertCanAccessDataView(app, ctx, dv);
169
194
  }
170
195
  const { dataView, fields } = await reportService.inspectDataViewFields(dataViewId, refresh);
171
196
  return {
@@ -240,6 +265,37 @@ export function createElasticReportToolCatalog(
240
265
  },
241
266
  },
242
267
  },
268
+ lockedFilters: {
269
+ type: 'array',
270
+ description:
271
+ 'Mandatory server-enforced filters (e.g. tenant or department isolation) that viewer interactive overrides can never remove or replace.',
272
+ items: {
273
+ type: 'object',
274
+ required: ['field', 'operator'],
275
+ properties: {
276
+ field: { type: 'string' },
277
+ operator: {
278
+ type: 'string',
279
+ enum: [
280
+ 'eq',
281
+ 'ne',
282
+ 'in',
283
+ 'not_in',
284
+ 'gt',
285
+ 'gte',
286
+ 'lt',
287
+ 'lte',
288
+ 'between',
289
+ 'contains',
290
+ 'exists',
291
+ 'not_exists',
292
+ ],
293
+ },
294
+ value: {},
295
+ valueTo: {},
296
+ },
297
+ },
298
+ },
243
299
  sort: {
244
300
  type: 'array',
245
301
  items: {
@@ -281,14 +337,24 @@ export function createElasticReportToolCatalog(
281
337
  topN: { type: 'number' },
282
338
  metricType: {
283
339
  type: 'string',
284
- enum: ['count', 'sum', 'avg', 'min', 'max', 'cardinality'],
340
+ enum: ['count', 'sum', 'avg', 'min', 'max', 'cardinality', 'p50', 'p95', 'p99'],
285
341
  },
286
342
  metricField: { type: 'string' },
287
343
  metricLabel: { type: 'string' },
288
344
  showHistogram: { type: 'boolean' },
345
+ splitSeriesField: { type: 'string' },
346
+ splitSeriesTopN: { type: 'number' },
347
+ stackMode: { type: 'string', enum: ['none', 'stacked', 'percent'] },
348
+ comparePreviousPeriod: { type: 'boolean' },
289
349
  },
290
350
  },
351
+ fieldFormats: {
352
+ type: 'object',
353
+ description:
354
+ 'Optional map of fieldName -> format ("duration_ms" | "bytes" | "percent" | "number" | "status_badge" | "url").',
355
+ },
291
356
  allowInteractiveControls: { type: 'boolean' },
357
+ allowExport: { type: 'boolean' },
292
358
  },
293
359
  },
294
360
  },
@@ -300,6 +366,7 @@ export function createElasticReportToolCatalog(
300
366
  dataViewId,
301
367
  spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
302
368
  forMcp: true,
369
+ userContext: extractServerUserContext(ctx),
303
370
  });
304
371
  return {
305
372
  dataView: {
@@ -310,12 +377,18 @@ export function createElasticReportToolCatalog(
310
377
  total: result.total,
311
378
  totalRelation: result.totalRelation,
312
379
  tookMs: result.tookMs,
380
+ ...(result.timedOut ? { timedOut: true } : {}),
381
+ ...(result.shards ? { shards: result.shards } : {}),
382
+ ...(result.warnings && result.warnings.length > 0 ? { warnings: result.warnings } : {}),
313
383
  visualization: result.visualization,
314
384
  columns: result.columns,
315
385
  sampleRows: result.rows.slice(0, 10),
316
386
  series: result.series,
387
+ ...(result.seriesKeys ? { seriesKeys: result.seriesKeys } : {}),
317
388
  histogram: result.histogram,
318
389
  metricValue: result.metricValue,
390
+ ...(result.previousMetricValue !== undefined ? { previousMetricValue: result.previousMetricValue } : {}),
391
+ ...(result.deltaPercent !== undefined ? { deltaPercent: result.deltaPercent } : {}),
319
392
  metricLabel: result.metricLabel,
320
393
  compiledDsl: result.compiledDsl,
321
394
  };
@@ -351,6 +424,11 @@ export function createElasticReportToolCatalog(
351
424
  type: 'boolean',
352
425
  description: 'Whether the report is published for selection in page blocks (default true).',
353
426
  },
427
+ allowedRoles: {
428
+ type: 'array',
429
+ items: { type: 'string' },
430
+ description: 'Optional role names allowed to view/run this report (empty means all authenticated viewers).',
431
+ },
354
432
  spec: {
355
433
  type: 'object',
356
434
  description: 'Validated ReportSpec object (same schema as es_preview_report.spec).',
@@ -366,6 +444,7 @@ export function createElasticReportToolCatalog(
366
444
  description: typeof args.description === 'string' ? args.description : null,
367
445
  dataViewId: requireId(args.dataViewId, 'dataViewId'),
368
446
  published: args.published !== false,
447
+ ...(args.allowedRoles !== undefined ? { allowedRoles: normalizeRoleList(args.allowedRoles) } : {}),
369
448
  spec: isRecord(args.spec) ? args.spec : { visualization: 'table' },
370
449
  },
371
450
  extractCurrentUserId(ctx),
@@ -401,16 +480,183 @@ export function createElasticReportToolCatalog(
401
480
  const isManager = canManageReports(app, ctx);
402
481
  if (args.reportId !== undefined && args.reportId !== null && String(args.reportId).trim() !== '') {
403
482
  const report = await reportService.getReport(requireId(args.reportId, 'reportId'));
404
- if (!isManager && !report.published) {
405
- throw new Error('Report not found');
406
- }
483
+ const dataView = report.dataView ?? (await reportService.getDataView(report.dataViewId));
484
+ assertCanAccessReport(app, ctx, report, dataView);
407
485
  return { report };
408
486
  }
409
487
  const reports = await reportService.listReports({
410
488
  publishedOnly: !isManager,
411
489
  search: typeof args.search === 'string' ? args.search : undefined,
412
490
  });
413
- return { reports };
491
+ return {
492
+ reports: reports.filter((r) => canAccessReport(app, ctx, r, r.dataView)),
493
+ };
494
+ },
495
+ },
496
+ {
497
+ name: 'es_analyze_report',
498
+ title: 'Execute & Analyze Saved Elasticsearch Report (Viewer-Safe)',
499
+ description:
500
+ "Execute a published Saved Elasticsearch Report under the caller's effective NocoBase role and mandatory server lockedFilters, optionally narrowing with KQL or timeRange overrides, to summarize anomalies, top buckets, KPI deltas, or sample logs.",
501
+ defaultPermission: 'ALLOW',
502
+ inputSchema: {
503
+ type: 'object',
504
+ required: ['reportId'],
505
+ properties: {
506
+ reportId: {
507
+ type: ['number', 'string'],
508
+ description: 'ID of the Saved Report from es_list_reports.',
509
+ },
510
+ query: {
511
+ type: 'string',
512
+ description: 'Optional KQL override when the report allows interactive controls.',
513
+ },
514
+ timePreset: {
515
+ type: 'string',
516
+ enum: ['last_15m', 'last_1h', 'last_24h', 'last_7d', 'last_30d', 'last_90d', 'all'],
517
+ description: 'Optional time preset override.',
518
+ },
519
+ },
520
+ },
521
+ async execute(args, ctx) {
522
+ assertAuthenticated(ctx);
523
+ const reportId = requireId(args.reportId, 'reportId');
524
+ const report = await reportService.getReport(reportId);
525
+ const dataView = report.dataView ?? (await reportService.getDataView(report.dataViewId));
526
+ assertCanAccessReport(app, ctx, report, dataView);
527
+
528
+ const overrides: ReportRuntimeOverrides = {};
529
+ if (typeof args.query === 'string') {
530
+ overrides.query = args.query;
531
+ }
532
+ if (typeof args.timePreset === 'string' && args.timePreset.trim()) {
533
+ overrides.timeRange = {
534
+ preset: args.timePreset as NonNullable<ReportRuntimeOverrides['timeRange']>['preset'],
535
+ };
536
+ }
537
+
538
+ const { result } = await reportService.runSavedReport({
539
+ reportId,
540
+ overrides: Object.keys(overrides).length > 0 ? overrides : undefined,
541
+ requirePublished: false,
542
+ forMcp: true,
543
+ userContext: extractServerUserContext(ctx),
544
+ });
545
+
546
+ return {
547
+ report: {
548
+ id: report.id,
549
+ title: report.title,
550
+ visualization: report.visualization,
551
+ dataViewTitle: dataView.title,
552
+ indexPattern: dataView.indexPattern,
553
+ },
554
+ total: result.total,
555
+ totalRelation: result.totalRelation,
556
+ tookMs: result.tookMs,
557
+ ...(result.warnings ? { warnings: result.warnings } : {}),
558
+ metricLabel: result.metricLabel,
559
+ metricValue: result.metricValue,
560
+ ...(result.previousMetricValue !== undefined ? { previousMetricValue: result.previousMetricValue } : {}),
561
+ ...(result.deltaPercent !== undefined ? { deltaPercent: result.deltaPercent } : {}),
562
+ series: result.series.slice(0, 15),
563
+ ...(result.seriesKeys ? { seriesKeys: result.seriesKeys } : {}),
564
+ histogram: result.histogram.slice(0, 24),
565
+ sampleRows: result.rows.slice(0, 15).map((r) => r.source),
566
+ };
567
+ },
568
+ },
569
+ {
570
+ name: 'es_create_dashboard_bundle',
571
+ title: 'Create Multi-Panel Elasticsearch Dashboard Bundle',
572
+ description:
573
+ 'Create a coordinated set of Saved Elasticsearch Reports (e.g. KPI with previous-period delta, trend line/area chart, stacked/grouped breakdown bar chart, and Discover table) sharing common Data View, lockedFilters, and allowedRoles, ready to combine with an Elastic Filter Bar on a NocoBase page.',
574
+ defaultPermission: 'ALLOW',
575
+ inputSchema: {
576
+ type: 'object',
577
+ required: ['dataViewId', 'panels'],
578
+ properties: {
579
+ dataViewId: {
580
+ type: ['number', 'string'],
581
+ description: 'Target Data View ID.',
582
+ },
583
+ allowedRoles: {
584
+ type: 'array',
585
+ items: { type: 'string' },
586
+ description: 'Optional role names applied to every report in the bundle.',
587
+ },
588
+ lockedFilters: {
589
+ type: 'array',
590
+ description: 'Optional mandatory server-enforced filters applied to every report in the bundle.',
591
+ items: {
592
+ type: 'object',
593
+ required: ['field', 'operator'],
594
+ properties: {
595
+ field: { type: 'string' },
596
+ operator: { type: 'string' },
597
+ value: {},
598
+ valueTo: {},
599
+ },
600
+ },
601
+ },
602
+ panels: {
603
+ type: 'array',
604
+ minItems: 1,
605
+ maxItems: 8,
606
+ items: {
607
+ type: 'object',
608
+ required: ['title', 'spec'],
609
+ properties: {
610
+ title: { type: 'string' },
611
+ description: { type: 'string' },
612
+ spec: { type: 'object' },
613
+ },
614
+ },
615
+ },
616
+ },
617
+ },
618
+ async execute(args, ctx) {
619
+ assertCanManageReports(app, ctx);
620
+ const dataViewId = requireId(args.dataViewId, 'dataViewId');
621
+ const panels = Array.isArray(args.panels) ? args.panels : [];
622
+ if (panels.length === 0 || panels.length > 8) {
623
+ throw new Error('"panels" must contain between 1 and 8 report definitions');
624
+ }
625
+ const sharedRoles = args.allowedRoles !== undefined ? normalizeRoleList(args.allowedRoles) : undefined;
626
+ const sharedLockedFilters = Array.isArray(args.lockedFilters) ? args.lockedFilters : undefined;
627
+ const userId = extractCurrentUserId(ctx);
628
+
629
+ const createdReports = [];
630
+ for (const panel of panels) {
631
+ if (!isRecord(panel)) continue;
632
+ const rawSpec = isRecord(panel.spec) ? { ...panel.spec } : { visualization: 'table' };
633
+ if (sharedLockedFilters && !Array.isArray(rawSpec.lockedFilters)) {
634
+ rawSpec.lockedFilters = sharedLockedFilters;
635
+ }
636
+ const saved = await reportService.saveReport(
637
+ {
638
+ title: typeof panel.title === 'string' ? panel.title : 'Dashboard Panel',
639
+ description: typeof panel.description === 'string' ? panel.description : null,
640
+ dataViewId,
641
+ published: true,
642
+ ...(sharedRoles !== undefined ? { allowedRoles: sharedRoles } : {}),
643
+ spec: rawSpec,
644
+ },
645
+ userId,
646
+ );
647
+ createdReports.push({
648
+ id: saved.id,
649
+ title: saved.title,
650
+ visualization: saved.visualization,
651
+ });
652
+ }
653
+
654
+ return {
655
+ createdCount: createdReports.length,
656
+ reports: createdReports,
657
+ usageHint:
658
+ 'Add an "Elastic Filter Bar" block at the top of a NocoBase /v/ page, then add an "Elastic Report" block for each created report so all panels cross-filter together.',
659
+ };
414
660
  },
415
661
  },
416
662
  ];