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,791 +1,879 @@
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 { act, cleanup, render, screen, waitFor } from '@testing-library/react';
11
- import userEvent from '@testing-library/user-event';
12
- import { ConfigProvider } from 'antd';
13
- import React from 'react';
14
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
15
- import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
16
-
17
- const mocks = vi.hoisted(() => {
18
- const request = vi.fn();
19
- const apiClient = { request };
20
- const registerModelLoaders = vi.fn();
21
- const registerComponents = vi.fn();
22
- const addMenuItem = vi.fn();
23
- const addPageTabItem = vi.fn();
24
- const setPluginSettingsLink = vi.fn();
25
-
26
- class MockBlockModel {
27
- props: Record<string, unknown> = {};
28
- static definedMeta: Record<string, unknown> | undefined;
29
- static definedMetas: Record<string, unknown>[] = [];
30
- static registeredFlows: Record<string, unknown>[] = [];
31
-
32
- static define(meta: Record<string, unknown>) {
33
- this.definedMeta = meta;
34
- this.definedMetas.push(meta);
35
- }
36
-
37
- static registerFlow(flow: Record<string, unknown>) {
38
- this.registeredFlows.push(flow);
39
- }
40
-
41
- setProps(next: Record<string, unknown>) {
42
- this.props = { ...this.props, ...next };
43
- }
44
- }
45
-
46
- class MockPlugin {
47
- options: Record<string, unknown>;
48
- app: Record<string, unknown>;
49
- flowEngine = { registerModelLoaders, flowSettings: { registerComponents } };
50
- pluginSettingsManager = {
51
- addMenuItem,
52
- addPageTabItem,
53
- setPluginSettingsLink,
54
- };
55
-
56
- constructor(options: Record<string, unknown> = {}, app: Record<string, unknown> = {}) {
57
- this.options = options;
58
- this.app = app;
59
- }
60
-
61
- t(key: string) {
62
- return key;
63
- }
64
- }
65
-
66
- return {
67
- request,
68
- apiClient,
69
- registerModelLoaders,
70
- registerComponents,
71
- addMenuItem,
72
- addPageTabItem,
73
- setPluginSettingsLink,
74
- MockBlockModel,
75
- MockPlugin,
76
- };
77
- });
78
-
79
- vi.mock('@nocobase/client-v2', () => ({
80
- BlockModel: mocks.MockBlockModel,
81
- Plugin: mocks.MockPlugin,
82
- Application: class {},
83
- useApp: () => ({
84
- apiClient: mocks.apiClient,
85
- }),
86
- }));
87
-
88
- vi.mock('@nocobase/flow-engine', () => ({
89
- tExpr: (key: string) => key,
90
- useFlowEngine: () => ({
91
- context: {
92
- t: (key: string) => key,
93
- },
94
- }),
95
- }));
96
-
97
- vi.mock('@nocobase/plugin-workflow/client-v2', () => ({
98
- Instruction: class {},
99
- NodeDefaultView: () => null,
100
- }));
101
-
102
- import { clearDashboardScope } from '../bus/DashboardFilterBus';
103
- import { ElasticBasicChart } from '../components/ElasticBasicCharts';
104
- import { ElasticFilterBar } from '../components/ElasticFilterBar';
105
- import { ElasticReportBlock } from '../components/ElasticReportBlock';
106
- import { HighlightText } from '../components/HighlightText';
107
- import { ElasticFilterBarBlockModel } from '../models/ElasticFilterBarBlockModel';
108
- import { ElasticReportBlockModel } from '../models/ElasticReportBlockModel';
109
- import { PluginElasticReportClient } from '../plugin';
110
-
111
- function renderWithoutMotion(ui: React.ReactElement) {
112
- return render(<ConfigProvider theme={{ token: { motion: false }, hashed: false }}>{ui}</ConfigProvider>);
113
- }
114
-
115
- describe('plugin-elastic-report client-v2', () => {
116
- beforeEach(() => {
117
- mocks.request.mockReset();
118
- mocks.registerModelLoaders.mockClear();
119
- mocks.addMenuItem.mockClear();
120
- mocks.addPageTabItem.mockClear();
121
- mocks.setPluginSettingsLink.mockClear();
122
- });
123
-
124
- afterEach(async () => {
125
- await act(async () => {
126
- await new Promise((resolve) => setTimeout(resolve, 0));
127
- });
128
- cleanup();
129
- });
130
-
131
- it('registers Report + FilterBar block loaders, settings page, and workflow instruction on load()', async () => {
132
- const registerInstructionGroup = vi.fn();
133
- const registerInstruction = vi.fn();
134
- const mockApp = {
135
- pm: {
136
- get: (name: string) => (name === 'workflow' ? { registerInstructionGroup, registerInstruction } : undefined),
137
- },
138
- };
139
- const plugin = new PluginElasticReportClient({ name: 'plugin-elastic-report' } as never, mockApp as never);
140
- await plugin.load();
141
-
142
- expect(mocks.registerComponents).toHaveBeenCalledWith({
143
- ElasticReportSelect: expect.any(Function),
144
- });
145
- expect(mocks.registerModelLoaders).toHaveBeenCalledWith(
146
- expect.objectContaining({
147
- ElasticReportBlockModel: expect.objectContaining({
148
- extends: 'BlockModel',
149
- }),
150
- ElasticFilterBarBlockModel: expect.objectContaining({
151
- extends: 'BlockModel',
152
- }),
153
- }),
154
- );
155
- expect(mocks.addMenuItem).toHaveBeenCalledWith(
156
- expect.objectContaining({
157
- key: 'elastic-report',
158
- aclSnippet: 'pm.elastic-report',
159
- }),
160
- );
161
- expect(mocks.addPageTabItem).toHaveBeenCalledTimes(1);
162
- expect(registerInstructionGroup).toHaveBeenCalledWith(
163
- 'elastic-report',
164
- expect.objectContaining({ key: 'elastic-report' }),
165
- );
166
- expect(registerInstruction).toHaveBeenCalledWith('elastic-report-query', expect.any(Function));
167
- expect(ElasticReportBlockModel).toBeDefined();
168
- expect(ElasticFilterBarBlockModel).toBeDefined();
169
- expect(mocks.MockBlockModel.definedMetas).toEqual(
170
- expect.arrayContaining([
171
- expect.objectContaining({
172
- label: 'Elastic Report',
173
- createModelOptions: { use: 'ElasticReportBlockModel' },
174
- }),
175
- expect.objectContaining({
176
- label: 'Elastic Filter Bar',
177
- createModelOptions: { use: 'ElasticFilterBarBlockModel' },
178
- }),
179
- ]),
180
- );
181
- });
182
-
183
- it('renders Elasticsearch highlights safely with <mark> without injecting raw HTML', () => {
184
- const text = ` Normal <img src=x onerror=alert(1)> ${HIGHLIGHT_PRE_TAG}matched term${HIGHLIGHT_POST_TAG} tail`;
185
- const { container } = renderWithoutMotion(<HighlightText text={text} />);
186
-
187
- const mark = container.querySelector('mark');
188
- expect(mark?.textContent).toBe('matched term');
189
- expect(container.querySelector('img')).toBeNull();
190
- expect(container.textContent).toContain('<img src=x onerror=alert(1)>');
191
- });
192
-
193
- it('renders accessible SVG bar chart, switches to data table, and indicates >= on truncated KPI counts', async () => {
194
- const user = userEvent.setup();
195
- renderWithoutMotion(
196
- <div>
197
- <ElasticBasicChart
198
- title="Requests by Service"
199
- visualization="bar"
200
- metricLabel="Requests"
201
- metricValue={null}
202
- totalHits={42}
203
- series={[
204
- { key: 'checkout', label: 'checkout', value: 30, count: 30 },
205
- { key: 'catalog', label: 'catalog', value: 12, count: 12 },
206
- ]}
207
- />
208
- <ElasticBasicChart
209
- title="Total Errors KPI"
210
- visualization="metric"
211
- metricType="count"
212
- metricLabel="Error Count"
213
- metricValue={10000}
214
- totalHits={10000}
215
- totalRelation="gte"
216
- series={[]}
217
- />
218
- </div>,
219
- );
220
-
221
- expect(screen.getByRole('img', { name: /Requests by Service/i })).toBeTruthy();
222
- expect(screen.getByText('≥')).toBeTruthy();
223
- expect(screen.getByText(/Hits: 10,000\+/)).toBeTruthy();
224
-
225
- await act(async () => {
226
- await user.click(screen.getByRole('button', { name: 'Show data table' }));
227
- });
228
- expect(await screen.findByText('checkout')).toBeTruthy();
229
- expect(screen.getByText('catalog')).toBeTruthy();
230
- });
231
-
232
- it('preserves KQL, custom timeRange bounds on Refresh, lockedFilters, shard warnings, and edited filter pills', async () => {
233
- const user = userEvent.setup();
234
- const savedSpec = {
235
- visualization: 'table' as const,
236
- query: 'status >= 400',
237
- lockedFilters: [
238
- { id: 'lock-1', field: 'region', operator: 'eq' as const, value: 'ap-southeast-1', enabled: true },
239
- ],
240
- filters: [{ id: 'f1', field: 'service', operator: 'eq' as const, value: 'checkout-api', enabled: true }],
241
- timeRange: {
242
- preset: 'custom' as const,
243
- from: '2026-11-29T00:00:00Z',
244
- to: '2026-11-30T00:00:00Z',
245
- },
246
- columns: ['@timestamp', 'service', 'status'],
247
- pageSize: 20,
248
- allowInteractiveControls: true,
249
- };
250
-
251
- mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
252
- if (cfg.url === 'esReportService:getReportMeta') {
253
- return {
254
- data: {
255
- data: {
256
- report: {
257
- id: 10,
258
- title: 'Gateway Error Logs (Discover Table)',
259
- dataViewId: 1,
260
- visualization: 'table',
261
- published: true,
262
- spec: { ...savedSpec },
263
- },
264
- dataView: {
265
- id: 1,
266
- title: 'Logs',
267
- dataSourceKey: 'es_main',
268
- indexPattern: 'logs-*',
269
- timeField: '@timestamp',
270
- },
271
- fields: [
272
- { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
273
- { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
274
- { name: 'status', type: 'integer', searchable: true, aggregatable: true },
275
- { name: 'region', type: 'keyword', searchable: true, aggregatable: true },
276
- ],
277
- },
278
- },
279
- };
280
- }
281
-
282
- if (cfg.url === 'esReportService:runReport') {
283
- return {
284
- data: {
285
- data: {
286
- report: {
287
- id: 10,
288
- title: 'Gateway Error Logs (Discover Table)',
289
- dataViewId: 1,
290
- visualization: 'table',
291
- published: true,
292
- spec: {
293
- ...savedSpec,
294
- filters: savedSpec.filters.map((f) => ({ ...f })),
295
- lockedFilters: savedSpec.lockedFilters.map((f) => ({ ...f })),
296
- },
297
- },
298
- dataView: {
299
- id: 1,
300
- title: 'Logs',
301
- dataSourceKey: 'es_main',
302
- indexPattern: 'logs-*',
303
- timeField: '@timestamp',
304
- },
305
- result: {
306
- total: 1,
307
- totalRelation: 'eq',
308
- tookMs: 4,
309
- timedOut: true,
310
- shards: { total: 5, successful: 4, skipped: 0, failed: 1 },
311
- visualization: 'table',
312
- columns: ['@timestamp', 'service', 'status'],
313
- rows: [
314
- {
315
- _id: 'doc-1',
316
- _index: 'logs-2026',
317
- source: {
318
- '@timestamp': '2026-11-30T01:00:00Z',
319
- service: 'gateway',
320
- status: 503,
321
- },
322
- },
323
- ],
324
- series: [],
325
- histogram: [],
326
- metricValue: null,
327
- metricLabel: 'Count',
328
- compiledDsl: { query: { match_all: {} } },
329
- },
330
- },
331
- },
332
- };
333
- }
334
- return { data: { data: [] } };
335
- });
336
-
337
- await act(async () => {
338
- renderWithoutMotion(<ElasticReportBlock reportId={10} showToolbar={true} />);
339
- });
340
-
341
- await waitFor(() => {
342
- expect(screen.getByText('gateway')).toBeTruthy();
343
- });
344
-
345
- // Locked filter badge and partial shard/timeout warning alert are both rendered
346
- expect(screen.getByText(/region eq ap-southeast-1/)).toBeTruthy();
347
- expect(screen.getByText('Partial results warning')).toBeTruthy();
348
- expect(screen.getByText(/Failed shards: 1 \/ 5/)).toBeTruthy();
349
-
350
- // Clicking Refresh preserves custom timeRange { preset: 'custom', from, to }
351
- await act(async () => {
352
- await user.click(screen.getByRole('button', { name: 'Refresh' }));
353
- });
354
- await waitFor(() => {
355
- expect(mocks.request).toHaveBeenCalledWith(
356
- expect.objectContaining({
357
- url: 'esReportService:runReport',
358
- data: expect.objectContaining({
359
- reportId: 10,
360
- overrides: expect.objectContaining({
361
- timeRange: {
362
- preset: 'custom',
363
- from: '2026-11-29T00:00:00Z',
364
- to: '2026-11-30T00:00:00Z',
365
- },
366
- }),
367
- }),
368
- }),
369
- );
370
- });
371
-
372
- const searchInput = screen.getByRole('combobox', { name: 'KQL / Search Query' }) as HTMLInputElement;
373
- expect(searchInput.value).toBe('status >= 400');
374
-
375
- await act(async () => {
376
- await user.clear(searchInput);
377
- await user.type(searchInput, 'status >= 500');
378
- await user.click(screen.getByRole('button', { name: /Search/i }));
379
- });
380
-
381
- await waitFor(() => {
382
- expect(mocks.request).toHaveBeenCalledWith(
383
- expect.objectContaining({
384
- url: 'esReportService:runReport',
385
- data: expect.objectContaining({
386
- reportId: 10,
387
- overrides: expect.objectContaining({
388
- query: 'status >= 500',
389
- }),
390
- }),
391
- }),
392
- );
393
- });
394
- expect(searchInput.value).toBe('status >= 500');
395
-
396
- // Click existing filter pill to edit its value in place
397
- await act(async () => {
398
- await user.click(screen.getByRole('button', { name: 'Edit Filter: service' }));
399
- });
400
- const valueInput = await screen.findByDisplayValue('checkout-api');
401
- await act(async () => {
402
- await user.clear(valueInput);
403
- await user.type(valueInput, 'auth-service');
404
- await user.click(screen.getByRole('button', { name: 'Apply' }));
405
- });
406
-
407
- await waitFor(() => {
408
- expect(mocks.request).toHaveBeenCalledWith(
409
- expect.objectContaining({
410
- url: 'esReportService:runReport',
411
- data: expect.objectContaining({
412
- reportId: 10,
413
- overrides: expect.objectContaining({
414
- query: 'status >= 500',
415
- filters: [expect.objectContaining({ field: 'service', operator: 'eq', value: 'auth-service' })],
416
- }),
417
- }),
418
- }),
419
- );
420
- });
421
- expect(screen.getByText(/service eq auth-service/)).toBeTruthy();
422
- });
423
-
424
- it('supports stacked multi-series charts, KPI delta badges, DashboardFilterBus cross-filtering, cell + filter, and fieldFormats', async () => {
425
- const user = userEvent.setup();
426
- const scopeKey = 'page-root-test:ops';
427
- clearDashboardScope(scopeKey);
428
-
429
- mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
430
- if (cfg.url === 'esReportService:getReportMeta') {
431
- return {
432
- data: {
433
- data: {
434
- report: {
435
- id: 21,
436
- title: 'Service Latency Table',
437
- dataViewId: 1,
438
- visualization: 'table',
439
- published: true,
440
- spec: {
441
- visualization: 'table',
442
- columns: ['@timestamp', 'service', 'status', 'latency_ms'],
443
- fieldFormats: {
444
- status: 'status_badge',
445
- latency_ms: 'duration_ms',
446
- },
447
- contextBindings: [{ esField: 'customer_id', recordFieldPath: 'account.code' }],
448
- allowInteractiveControls: true,
449
- allowExport: true,
450
- },
451
- },
452
- dataView: {
453
- id: 1,
454
- title: 'Logs',
455
- dataSourceKey: 'es_main',
456
- indexPattern: 'logs-*',
457
- timeField: '@timestamp',
458
- },
459
- fields: [
460
- { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
461
- { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
462
- { name: 'status', type: 'integer', searchable: true, aggregatable: true },
463
- { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
464
- ],
465
- },
466
- },
467
- };
468
- }
469
-
470
- if (cfg.url === 'esReportService:runReport') {
471
- return {
472
- data: {
473
- data: {
474
- report: {
475
- id: 21,
476
- title: 'Service Latency Table',
477
- dataViewId: 1,
478
- visualization: 'table',
479
- published: true,
480
- spec: {
481
- visualization: 'table',
482
- columns: ['@timestamp', 'service', 'status', 'latency_ms'],
483
- fieldFormats: {
484
- status: 'status_badge',
485
- latency_ms: 'duration_ms',
486
- },
487
- contextBindings: [{ esField: 'customer_id', recordFieldPath: 'account.code' }],
488
- allowInteractiveControls: true,
489
- allowExport: true,
490
- },
491
- },
492
- dataView: {
493
- id: 1,
494
- title: 'Logs',
495
- dataSourceKey: 'es_main',
496
- indexPattern: 'logs-*',
497
- timeField: '@timestamp',
498
- },
499
- result: {
500
- total: 1,
501
- totalRelation: 'eq',
502
- tookMs: 3,
503
- visualization: 'table',
504
- columns: ['@timestamp', 'service', 'status', 'latency_ms'],
505
- rows: [
506
- {
507
- _id: 'doc-21',
508
- _index: 'logs-2026',
509
- source: {
510
- '@timestamp': '2026-11-30T02:00:00Z',
511
- service: 'payments',
512
- status: 502,
513
- latency_ms: 1500,
514
- },
515
- },
516
- ],
517
- series: [],
518
- histogram: [],
519
- metricValue: null,
520
- metricLabel: 'Count',
521
- compiledDsl: { query: { match_all: {} } },
522
- },
523
- },
524
- },
525
- };
526
- }
527
- return { data: { data: { buckets: [] } } };
528
- });
529
-
530
- await act(async () => {
531
- renderWithoutMotion(
532
- <div>
533
- <ElasticBasicChart
534
- title="Stacked Latency by Service"
535
- visualization="bar"
536
- stackMode="stacked"
537
- seriesKeys={['checkout', 'payments']}
538
- metricLabel="P95 Latency"
539
- metricValue={null}
540
- totalHits={25}
541
- series={[
542
- {
543
- key: '10:00',
544
- label: '10:00',
545
- value: 600,
546
- count: 25,
547
- breakdown: [
548
- { seriesKey: 'checkout', value: 250, count: 15 },
549
- { seriesKey: 'payments', value: 350, count: 10 },
550
- ],
551
- },
552
- ]}
553
- />
554
- <ElasticBasicChart
555
- title="P95 Latency KPI"
556
- visualization="metric"
557
- metricType="p95"
558
- metricLabel="P95 Latency"
559
- metricValue={250}
560
- previousMetricValue={200}
561
- deltaPercent={25}
562
- totalHits={100}
563
- series={[]}
564
- />
565
- <ElasticFilterBar scopeKey={scopeKey} showGlobalKql={true} showGlobalTimeRange={true} />
566
- <ElasticReportBlock
567
- reportId={21}
568
- scopeKey={scopeKey}
569
- subscribeDashboardFilters={true}
570
- contextRecord={{ account: { code: 'ACME-01' } }}
571
- />
572
- </div>,
573
- );
574
- });
575
-
576
- // Formatted duration_ms (1500 -> "1.50 s") and KPI previous-period delta (+25%) are rendered
577
- await waitFor(() => {
578
- expect(screen.getByText('1.50 s')).toBeTruthy();
579
- });
580
- expect(screen.getByText(/\+25%/)).toBeTruthy();
581
-
582
- // Context binding filter (customer_id = ACME-01) is sent automatically
583
- await waitFor(() => {
584
- expect(mocks.request).toHaveBeenCalledWith(
585
- expect.objectContaining({
586
- url: 'esReportService:runReport',
587
- data: expect.objectContaining({
588
- reportId: 21,
589
- overrides: expect.objectContaining({
590
- contextFilters: [expect.objectContaining({ field: 'customer_id', operator: 'eq', value: 'ACME-01' })],
591
- }),
592
- }),
593
- }),
594
- );
595
- });
596
-
597
- // Global KQL from ElasticFilterBar propagates via DashboardFilterBus to ElasticReportBlock
598
- const kqlInputs = screen.getAllByRole('combobox', { name: 'KQL / Search Query' });
599
- await act(async () => {
600
- await user.type(kqlInputs[0], 'status >= 500');
601
- await user.click(screen.getByRole('button', { name: 'Apply' }));
602
- });
603
-
604
- await waitFor(() => {
605
- expect(mocks.request).toHaveBeenCalledWith(
606
- expect.objectContaining({
607
- url: 'esReportService:runReport',
608
- data: expect.objectContaining({
609
- reportId: 21,
610
- overrides: expect.objectContaining({
611
- query: 'status >= 500',
612
- }),
613
- }),
614
- }),
615
- );
616
- });
617
-
618
- // Clicking Discover cell "+" button pushes shared cross-filter pill to ElasticFilterBar and re-queries
619
- await act(async () => {
620
- await user.click(screen.getByRole('button', { name: 'Filter for value: service=payments' }));
621
- });
622
-
623
- await waitFor(() => {
624
- expect(mocks.request).toHaveBeenCalledWith(
625
- expect.objectContaining({
626
- url: 'esReportService:runReport',
627
- data: expect.objectContaining({
628
- reportId: 21,
629
- overrides: expect.objectContaining({
630
- sharedFilters: [expect.objectContaining({ field: 'service', operator: 'eq', value: 'payments' })],
631
- }),
632
- }),
633
- }),
634
- );
635
- });
636
- expect(screen.getByText(/service eq payments/)).toBeTruthy();
637
- });
638
-
639
- it('provides guided KQL autocomplete for fields, operators, live Elasticsearch top values, and Enter-to-submit', async () => {
640
- const user = userEvent.setup();
641
-
642
- mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
643
- if (cfg.url === 'esReportService:getReportMeta') {
644
- return {
645
- data: {
646
- data: {
647
- report: {
648
- id: 30,
649
- title: 'Guided Search Report',
650
- dataViewId: 1,
651
- visualization: 'table',
652
- published: true,
653
- spec: {
654
- visualization: 'table',
655
- columns: ['@timestamp', 'service', 'status'],
656
- allowInteractiveControls: true,
657
- },
658
- },
659
- dataView: {
660
- id: 1,
661
- title: 'Logs',
662
- dataSourceKey: 'es_main',
663
- indexPattern: 'logs-*',
664
- timeField: '@timestamp',
665
- },
666
- fields: [
667
- { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
668
- { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
669
- { name: 'status', type: 'integer', searchable: true, aggregatable: true },
670
- ],
671
- },
672
- },
673
- };
674
- }
675
- if (cfg.url === 'esReportService:inspectTopValues') {
676
- return {
677
- data: {
678
- data: {
679
- field: cfg.data?.field,
680
- resolvedField: cfg.data?.field,
681
- totalDocs: 50,
682
- buckets:
683
- cfg.data?.field === 'service'
684
- ? [
685
- { value: 'gateway', count: 32, percentage: 64 },
686
- { value: 'billing-api', count: 18, percentage: 36 },
687
- ]
688
- : [{ value: '500', count: 20, percentage: 40 }],
689
- },
690
- },
691
- };
692
- }
693
- if (cfg.url === 'esReportService:runReport') {
694
- return {
695
- data: {
696
- data: {
697
- report: {
698
- id: 30,
699
- title: 'Guided Search Report',
700
- dataViewId: 1,
701
- visualization: 'table',
702
- published: true,
703
- spec: {
704
- visualization: 'table',
705
- columns: ['@timestamp', 'service', 'status'],
706
- allowInteractiveControls: true,
707
- },
708
- },
709
- dataView: {
710
- id: 1,
711
- title: 'Logs',
712
- dataSourceKey: 'es_main',
713
- indexPattern: 'logs-*',
714
- timeField: '@timestamp',
715
- },
716
- result: {
717
- total: 1,
718
- totalRelation: 'eq',
719
- tookMs: 2,
720
- visualization: 'table',
721
- columns: ['@timestamp', 'service', 'status'],
722
- rows: [],
723
- series: [],
724
- histogram: [],
725
- metricValue: null,
726
- metricLabel: 'Count',
727
- compiledDsl: { query: { match_all: {} } },
728
- },
729
- },
730
- },
731
- };
732
- }
733
- return { data: { data: [] } };
734
- });
735
-
736
- await act(async () => {
737
- renderWithoutMotion(<ElasticReportBlock reportId={30} showToolbar={true} />);
738
- });
739
-
740
- const kqlCombo = await screen.findByRole('combobox', { name: 'KQL / Search Query' });
741
-
742
- // 1. Focus empty search input -> field suggestions appear
743
- await act(async () => {
744
- await user.click(kqlCombo);
745
- });
746
- const serviceFieldOpt = await screen.findByRole('option', { name: /service/i });
747
-
748
- // 2. Click `service` -> inserts `service: ` and automatically loads live top values from Elasticsearch
749
- await act(async () => {
750
- await user.click(serviceFieldOpt);
751
- });
752
- expect((kqlCombo as HTMLInputElement).value).toBe('service: ');
753
-
754
- const gatewayValOpt = await screen.findByRole('option', { name: /"gateway"/i });
755
- expect(mocks.request).toHaveBeenCalledWith(
756
- expect.objectContaining({
757
- url: 'esReportService:inspectTopValues',
758
- data: expect.objectContaining({
759
- reportId: 30,
760
- field: 'service',
761
- overrides: expect.objectContaining({
762
- query: '',
763
- }),
764
- }),
765
- }),
766
- );
767
- await act(async () => {
768
- await user.click(gatewayValOpt);
769
- });
770
- expect((kqlCombo as HTMLInputElement).value).toBe('service: "gateway" ');
771
-
772
- // 3. Press Enter directly without highlighting another option -> executes the search immediately
773
- await act(async () => {
774
- await user.keyboard('{Enter}');
775
- });
776
-
777
- await waitFor(() => {
778
- expect(mocks.request).toHaveBeenCalledWith(
779
- expect.objectContaining({
780
- url: 'esReportService:runReport',
781
- data: expect.objectContaining({
782
- reportId: 30,
783
- overrides: expect.objectContaining({
784
- query: 'service: "gateway"',
785
- }),
786
- }),
787
- }),
788
- );
789
- });
790
- });
791
- });
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 { act, cleanup, render, screen, waitFor } from '@testing-library/react';
11
+ import userEvent from '@testing-library/user-event';
12
+ import { ConfigProvider } from 'antd';
13
+ import React from 'react';
14
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
15
+ import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
16
+
17
+ const mocks = vi.hoisted(() => {
18
+ const request = vi.fn();
19
+ const apiClient = { request };
20
+ const registerModelLoaders = vi.fn();
21
+ const registerComponents = vi.fn();
22
+ const addMenuItem = vi.fn();
23
+ const addPageTabItem = vi.fn();
24
+ const setPluginSettingsLink = vi.fn();
25
+
26
+ class MockBlockModel {
27
+ props: Record<string, unknown> = {};
28
+ static definedMeta: Record<string, unknown> | undefined;
29
+ static definedMetas: Record<string, unknown>[] = [];
30
+ static registeredFlows: Record<string, unknown>[] = [];
31
+
32
+ static define(meta: Record<string, unknown>) {
33
+ this.definedMeta = meta;
34
+ this.definedMetas.push(meta);
35
+ }
36
+
37
+ static registerFlow(flow: Record<string, unknown>) {
38
+ this.registeredFlows.push(flow);
39
+ }
40
+
41
+ setProps(next: Record<string, unknown>) {
42
+ this.props = { ...this.props, ...next };
43
+ }
44
+ }
45
+
46
+ class MockPlugin {
47
+ options: Record<string, unknown>;
48
+ app: Record<string, unknown>;
49
+ flowEngine = { registerModelLoaders, getModel: vi.fn(), flowSettings: { registerComponents } };
50
+ pluginSettingsManager = {
51
+ addMenuItem,
52
+ addPageTabItem,
53
+ setPluginSettingsLink,
54
+ };
55
+
56
+ constructor(options: Record<string, unknown> = {}, app: Record<string, unknown> = {}) {
57
+ this.options = options;
58
+ this.app = app;
59
+ }
60
+
61
+ t(key: string) {
62
+ return key;
63
+ }
64
+ }
65
+
66
+ return {
67
+ request,
68
+ apiClient,
69
+ registerModelLoaders,
70
+ registerComponents,
71
+ addMenuItem,
72
+ addPageTabItem,
73
+ setPluginSettingsLink,
74
+ MockBlockModel,
75
+ MockPlugin,
76
+ };
77
+ });
78
+
79
+ vi.mock('@nocobase/client-v2', () => ({
80
+ BlockModel: mocks.MockBlockModel,
81
+ Plugin: mocks.MockPlugin,
82
+ Application: class {},
83
+ useApp: () => ({
84
+ apiClient: mocks.apiClient,
85
+ }),
86
+ }));
87
+
88
+ vi.mock('@nocobase/flow-engine', () => ({
89
+ tExpr: (key: string) => key,
90
+ useFlowEngine: () => ({
91
+ context: {
92
+ t: (key: string) => key,
93
+ },
94
+ }),
95
+ }));
96
+
97
+ vi.mock('@nocobase/plugin-workflow/client-v2', () => ({
98
+ Instruction: class {},
99
+ NodeDefaultView: () => null,
100
+ }));
101
+
102
+ import { clearDashboardScope } from '../bus/DashboardFilterBus';
103
+ import { ElasticBasicChart } from '../components/ElasticBasicCharts';
104
+ import { ElasticFilterBar } from '../components/ElasticFilterBar';
105
+ import { ElasticReportBlock } from '../components/ElasticReportBlock';
106
+ import { HighlightText } from '../components/HighlightText';
107
+ import { ElasticFilterBarBlockModel } from '../models/ElasticFilterBarBlockModel';
108
+ import { ElasticReportBlockModel } from '../models/ElasticReportBlockModel';
109
+ import { PluginElasticReportClient } from '../plugin';
110
+ import { reportDestinationContext } from '../report-destination';
111
+
112
+ function renderWithoutMotion(ui: React.ReactElement) {
113
+ return render(<ConfigProvider theme={{ token: { motion: false }, hashed: false }}>{ui}</ConfigProvider>);
114
+ }
115
+
116
+ describe('plugin-elastic-report client-v2', () => {
117
+ beforeEach(() => {
118
+ mocks.request.mockReset();
119
+ mocks.registerModelLoaders.mockClear();
120
+ mocks.addMenuItem.mockClear();
121
+ mocks.addPageTabItem.mockClear();
122
+ mocks.setPluginSettingsLink.mockClear();
123
+ });
124
+
125
+ afterEach(async () => {
126
+ await act(async () => {
127
+ await new Promise((resolve) => setTimeout(resolve, 0));
128
+ });
129
+ cleanup();
130
+ });
131
+
132
+ it('registers Report + FilterBar block loaders, settings page, and workflow instruction on load()', async () => {
133
+ const registerInstructionGroup = vi.fn();
134
+ const registerInstruction = vi.fn();
135
+ const mockApp = {
136
+ pm: {
137
+ get: (name: string) => (name === 'workflow' ? { registerInstructionGroup, registerInstruction } : undefined),
138
+ },
139
+ };
140
+ const plugin = new PluginElasticReportClient({ name: 'plugin-elastic-report' } as never, mockApp as never);
141
+ await plugin.load();
142
+
143
+ expect(mocks.registerComponents).toHaveBeenCalledWith({
144
+ ElasticReportSelect: expect.any(Function),
145
+ });
146
+ expect(mocks.registerModelLoaders).toHaveBeenCalledWith(
147
+ expect.objectContaining({
148
+ ElasticReportBlockModel: expect.objectContaining({
149
+ extends: 'BlockModel',
150
+ }),
151
+ ElasticFilterBarBlockModel: expect.objectContaining({
152
+ extends: 'BlockModel',
153
+ }),
154
+ }),
155
+ );
156
+ expect(mocks.addMenuItem).toHaveBeenCalledWith(
157
+ expect.objectContaining({
158
+ key: 'elastic-report',
159
+ aclSnippet: 'pm.elastic-report',
160
+ }),
161
+ );
162
+ expect(mocks.addPageTabItem).toHaveBeenCalledTimes(1);
163
+ expect(registerInstructionGroup).toHaveBeenCalledWith(
164
+ 'elastic-report',
165
+ expect.objectContaining({ key: 'elastic-report' }),
166
+ );
167
+ expect(registerInstruction).toHaveBeenCalledWith('elastic-report-query', expect.any(Function));
168
+ expect(ElasticReportBlockModel).toBeDefined();
169
+ expect(ElasticFilterBarBlockModel).toBeDefined();
170
+ expect(mocks.MockBlockModel.definedMetas).toEqual(
171
+ expect.arrayContaining([
172
+ expect.objectContaining({
173
+ label: 'Elastic Report',
174
+ createModelOptions: { use: 'ElasticReportBlockModel' },
175
+ }),
176
+ expect.objectContaining({
177
+ label: 'Elastic Filter Bar',
178
+ createModelOptions: { use: 'ElasticFilterBarBlockModel' },
179
+ }),
180
+ ]),
181
+ );
182
+ });
183
+
184
+ it('attaches the chosen tab and published report from an empty page to the user message', async () => {
185
+ const onAdd = vi.fn();
186
+ const onRemove = vi.fn();
187
+ const close = vi.fn();
188
+ const routes = [
189
+ {
190
+ type: 'group',
191
+ title: 'QA',
192
+ children: [
193
+ {
194
+ type: 'flowPage',
195
+ title: 'Overview',
196
+ schemaUid: 'single-page',
197
+ enableTabs: false,
198
+ children: [{ type: 'tabs', hidden: true, schemaUid: 'implicit-tab' }],
199
+ },
200
+ {
201
+ type: 'flowPage',
202
+ title: 'Sales',
203
+ schemaUid: 'page',
204
+ enableTabs: true,
205
+ children: [
206
+ { type: 'tabs', title: 'First', schemaUid: 'first' },
207
+ { type: 'tabs', title: 'Second', schemaUid: 'second' },
208
+ ],
209
+ },
210
+ ],
211
+ },
212
+ ];
213
+ mocks.request.mockResolvedValue({ data: { data: [{ id: 12, title: 'Revenue', visualization: 'metric' }] } });
214
+ const dialog = vi.fn();
215
+ reportDestinationContext.menu.onClick({
216
+ ctx: { t: (key: string) => key, routeRepository: { listAccessible: () => routes }, viewer: { dialog } } as never,
217
+ contextItems: [{ type: 'elastic-report-destination', uid: 'first' }],
218
+ onAdd,
219
+ onRemove,
220
+ });
221
+ await act(async () => {
222
+ renderWithoutMotion(dialog.mock.calls[0][0].content({ close }));
223
+ });
224
+ const user = userEvent.setup();
225
+ const attach = screen.getByRole('button', { name: 'Attach destination' });
226
+ expect(attach).toBeDisabled();
227
+ await act(async () => {
228
+ await user.click(screen.getByRole('combobox', { name: 'Page and tab' }));
229
+ });
230
+ expect(screen.getByText('QA / Overview')).toBeTruthy();
231
+ await act(async () => {
232
+ await user.click(screen.getByText('QA / Sales / Second'));
233
+ });
234
+ await act(async () => {
235
+ await user.click(screen.getByRole('combobox', { name: 'Report' }));
236
+ });
237
+ await act(async () => {
238
+ await user.click(screen.getByText('Revenue'));
239
+ });
240
+ await act(async () => {
241
+ await user.click(attach);
242
+ });
243
+ await waitFor(() =>
244
+ expect(onAdd).toHaveBeenCalledWith(
245
+ expect.objectContaining({
246
+ uid: 'second',
247
+ content: { pageUid: 'page', tabUid: 'second', reportId: 12 },
248
+ }),
249
+ ),
250
+ );
251
+ expect(onRemove).toHaveBeenCalledWith('first');
252
+ expect(close).toHaveBeenCalledOnce();
253
+ });
254
+
255
+ it('updates the mounted report block settings on notification', async () => {
256
+ const eventBus = new EventTarget();
257
+ const plugin = new PluginElasticReportClient({} as never, { eventBus } as never);
258
+ const target = { use: 'ElasticReportBlockModel', setStepParams: vi.fn(), setProps: vi.fn() };
259
+ vi.mocked(plugin.flowEngine.getModel).mockReturnValue(target as never);
260
+ await plugin.load();
261
+ eventBus.dispatchEvent(
262
+ new CustomEvent('ws:message:elastic-report:block-settings', {
263
+ detail: { blockUid: 'selected', changes: { compact: true } },
264
+ }),
265
+ );
266
+ expect(plugin.flowEngine.getModel).toHaveBeenCalledWith('selected', true);
267
+ expect(target.setStepParams).toHaveBeenCalledWith('elasticReportBlockSettings', 'editReport', { compact: true });
268
+ expect(target.setProps).toHaveBeenCalledWith({ compact: true });
269
+ });
270
+
271
+ it('renders Elasticsearch highlights safely with <mark> without injecting raw HTML', () => {
272
+ const text = ` Normal <img src=x onerror=alert(1)> ${HIGHLIGHT_PRE_TAG}matched term${HIGHLIGHT_POST_TAG} tail`;
273
+ const { container } = renderWithoutMotion(<HighlightText text={text} />);
274
+
275
+ const mark = container.querySelector('mark');
276
+ expect(mark?.textContent).toBe('matched term');
277
+ expect(container.querySelector('img')).toBeNull();
278
+ expect(container.textContent).toContain('<img src=x onerror=alert(1)>');
279
+ });
280
+
281
+ it('renders accessible SVG bar chart, switches to data table, and indicates >= on truncated KPI counts', async () => {
282
+ const user = userEvent.setup();
283
+ renderWithoutMotion(
284
+ <div>
285
+ <ElasticBasicChart
286
+ title="Requests by Service"
287
+ visualization="bar"
288
+ metricLabel="Requests"
289
+ metricValue={null}
290
+ totalHits={42}
291
+ series={[
292
+ { key: 'checkout', label: 'checkout', value: 30, count: 30 },
293
+ { key: 'catalog', label: 'catalog', value: 12, count: 12 },
294
+ ]}
295
+ />
296
+ <ElasticBasicChart
297
+ title="Total Errors KPI"
298
+ visualization="metric"
299
+ metricType="count"
300
+ metricLabel="Error Count"
301
+ metricValue={10000}
302
+ totalHits={10000}
303
+ totalRelation="gte"
304
+ series={[]}
305
+ />
306
+ </div>,
307
+ );
308
+
309
+ expect(screen.getByRole('img', { name: /Requests by Service/i })).toBeTruthy();
310
+ expect(screen.getByText('≥')).toBeTruthy();
311
+ expect(screen.getByText(/Hits: 10,000\+/)).toBeTruthy();
312
+
313
+ await act(async () => {
314
+ await user.click(screen.getByRole('button', { name: 'Show data table' }));
315
+ });
316
+ expect(await screen.findByText('checkout')).toBeTruthy();
317
+ expect(screen.getByText('catalog')).toBeTruthy();
318
+ });
319
+
320
+ it('preserves KQL, custom timeRange bounds on Refresh, lockedFilters, shard warnings, and edited filter pills', async () => {
321
+ const user = userEvent.setup();
322
+ const savedSpec = {
323
+ visualization: 'table' as const,
324
+ query: 'status >= 400',
325
+ lockedFilters: [
326
+ { id: 'lock-1', field: 'region', operator: 'eq' as const, value: 'ap-southeast-1', enabled: true },
327
+ ],
328
+ filters: [{ id: 'f1', field: 'service', operator: 'eq' as const, value: 'checkout-api', enabled: true }],
329
+ timeRange: {
330
+ preset: 'custom' as const,
331
+ from: '2026-11-29T00:00:00Z',
332
+ to: '2026-11-30T00:00:00Z',
333
+ },
334
+ columns: ['@timestamp', 'service', 'status'],
335
+ pageSize: 20,
336
+ allowInteractiveControls: true,
337
+ };
338
+
339
+ mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
340
+ if (cfg.url === 'esReportService:getReportMeta') {
341
+ return {
342
+ data: {
343
+ data: {
344
+ report: {
345
+ id: 10,
346
+ title: 'Gateway Error Logs (Discover Table)',
347
+ dataViewId: 1,
348
+ visualization: 'table',
349
+ published: true,
350
+ spec: { ...savedSpec },
351
+ },
352
+ dataView: {
353
+ id: 1,
354
+ title: 'Logs',
355
+ dataSourceKey: 'es_main',
356
+ indexPattern: 'logs-*',
357
+ timeField: '@timestamp',
358
+ },
359
+ fields: [
360
+ { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
361
+ { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
362
+ { name: 'status', type: 'integer', searchable: true, aggregatable: true },
363
+ { name: 'region', type: 'keyword', searchable: true, aggregatable: true },
364
+ ],
365
+ },
366
+ },
367
+ };
368
+ }
369
+
370
+ if (cfg.url === 'esReportService:runReport') {
371
+ return {
372
+ data: {
373
+ data: {
374
+ report: {
375
+ id: 10,
376
+ title: 'Gateway Error Logs (Discover Table)',
377
+ dataViewId: 1,
378
+ visualization: 'table',
379
+ published: true,
380
+ spec: {
381
+ ...savedSpec,
382
+ filters: savedSpec.filters.map((f) => ({ ...f })),
383
+ lockedFilters: savedSpec.lockedFilters.map((f) => ({ ...f })),
384
+ },
385
+ },
386
+ dataView: {
387
+ id: 1,
388
+ title: 'Logs',
389
+ dataSourceKey: 'es_main',
390
+ indexPattern: 'logs-*',
391
+ timeField: '@timestamp',
392
+ },
393
+ result: {
394
+ total: 1,
395
+ totalRelation: 'eq',
396
+ tookMs: 4,
397
+ timedOut: true,
398
+ shards: { total: 5, successful: 4, skipped: 0, failed: 1 },
399
+ visualization: 'table',
400
+ columns: ['@timestamp', 'service', 'status'],
401
+ rows: [
402
+ {
403
+ _id: 'doc-1',
404
+ _index: 'logs-2026',
405
+ source: {
406
+ '@timestamp': '2026-11-30T01:00:00Z',
407
+ service: 'gateway',
408
+ status: 503,
409
+ },
410
+ },
411
+ ],
412
+ series: [],
413
+ histogram: [],
414
+ metricValue: null,
415
+ metricLabel: 'Count',
416
+ compiledDsl: { query: { match_all: {} } },
417
+ },
418
+ },
419
+ },
420
+ };
421
+ }
422
+ return { data: { data: [] } };
423
+ });
424
+
425
+ await act(async () => {
426
+ renderWithoutMotion(<ElasticReportBlock reportId={10} showToolbar={true} />);
427
+ });
428
+
429
+ await waitFor(() => {
430
+ expect(screen.getByText('gateway')).toBeTruthy();
431
+ });
432
+
433
+ // Locked filter badge and partial shard/timeout warning alert are both rendered
434
+ expect(screen.getByText(/region eq ap-southeast-1/)).toBeTruthy();
435
+ expect(screen.getByText('Partial results warning')).toBeTruthy();
436
+ expect(screen.getByText(/Failed shards: 1 \/ 5/)).toBeTruthy();
437
+
438
+ // Clicking Refresh preserves custom timeRange { preset: 'custom', from, to }
439
+ await act(async () => {
440
+ await user.click(screen.getByRole('button', { name: 'Refresh' }));
441
+ });
442
+ await waitFor(() => {
443
+ expect(mocks.request).toHaveBeenCalledWith(
444
+ expect.objectContaining({
445
+ url: 'esReportService:runReport',
446
+ data: expect.objectContaining({
447
+ reportId: 10,
448
+ overrides: expect.objectContaining({
449
+ timeRange: {
450
+ preset: 'custom',
451
+ from: '2026-11-29T00:00:00Z',
452
+ to: '2026-11-30T00:00:00Z',
453
+ },
454
+ }),
455
+ }),
456
+ }),
457
+ );
458
+ });
459
+
460
+ const searchInput = screen.getByRole('combobox', { name: 'KQL / Search Query' }) as HTMLInputElement;
461
+ expect(searchInput.value).toBe('status >= 400');
462
+
463
+ await act(async () => {
464
+ await user.clear(searchInput);
465
+ await user.type(searchInput, 'status >= 500');
466
+ await user.click(screen.getByRole('button', { name: /Search/i }));
467
+ });
468
+
469
+ await waitFor(() => {
470
+ expect(mocks.request).toHaveBeenCalledWith(
471
+ expect.objectContaining({
472
+ url: 'esReportService:runReport',
473
+ data: expect.objectContaining({
474
+ reportId: 10,
475
+ overrides: expect.objectContaining({
476
+ query: 'status >= 500',
477
+ }),
478
+ }),
479
+ }),
480
+ );
481
+ });
482
+ expect(searchInput.value).toBe('status >= 500');
483
+
484
+ // Click existing filter pill to edit its value in place
485
+ await act(async () => {
486
+ await user.click(screen.getByRole('button', { name: 'Edit Filter: service' }));
487
+ });
488
+ const valueInput = await screen.findByDisplayValue('checkout-api');
489
+ await act(async () => {
490
+ await user.clear(valueInput);
491
+ await user.type(valueInput, 'auth-service');
492
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
493
+ });
494
+
495
+ await waitFor(() => {
496
+ expect(mocks.request).toHaveBeenCalledWith(
497
+ expect.objectContaining({
498
+ url: 'esReportService:runReport',
499
+ data: expect.objectContaining({
500
+ reportId: 10,
501
+ overrides: expect.objectContaining({
502
+ query: 'status >= 500',
503
+ filters: [expect.objectContaining({ field: 'service', operator: 'eq', value: 'auth-service' })],
504
+ }),
505
+ }),
506
+ }),
507
+ );
508
+ });
509
+ expect(screen.getByText(/service eq auth-service/)).toBeTruthy();
510
+ });
511
+
512
+ it('supports stacked multi-series charts, KPI delta badges, DashboardFilterBus cross-filtering, cell + filter, and fieldFormats', async () => {
513
+ const user = userEvent.setup();
514
+ const scopeKey = 'page-root-test:ops';
515
+ clearDashboardScope(scopeKey);
516
+
517
+ mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
518
+ if (cfg.url === 'esReportService:getReportMeta') {
519
+ return {
520
+ data: {
521
+ data: {
522
+ report: {
523
+ id: 21,
524
+ title: 'Service Latency Table',
525
+ dataViewId: 1,
526
+ visualization: 'table',
527
+ published: true,
528
+ spec: {
529
+ visualization: 'table',
530
+ columns: ['@timestamp', 'service', 'status', 'latency_ms'],
531
+ fieldFormats: {
532
+ status: 'status_badge',
533
+ latency_ms: 'duration_ms',
534
+ },
535
+ contextBindings: [{ esField: 'customer_id', recordFieldPath: 'account.code' }],
536
+ allowInteractiveControls: true,
537
+ allowExport: true,
538
+ },
539
+ },
540
+ dataView: {
541
+ id: 1,
542
+ title: 'Logs',
543
+ dataSourceKey: 'es_main',
544
+ indexPattern: 'logs-*',
545
+ timeField: '@timestamp',
546
+ },
547
+ fields: [
548
+ { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
549
+ { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
550
+ { name: 'status', type: 'integer', searchable: true, aggregatable: true },
551
+ { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
552
+ ],
553
+ },
554
+ },
555
+ };
556
+ }
557
+
558
+ if (cfg.url === 'esReportService:runReport') {
559
+ return {
560
+ data: {
561
+ data: {
562
+ report: {
563
+ id: 21,
564
+ title: 'Service Latency Table',
565
+ dataViewId: 1,
566
+ visualization: 'table',
567
+ published: true,
568
+ spec: {
569
+ visualization: 'table',
570
+ columns: ['@timestamp', 'service', 'status', 'latency_ms'],
571
+ fieldFormats: {
572
+ status: 'status_badge',
573
+ latency_ms: 'duration_ms',
574
+ },
575
+ contextBindings: [{ esField: 'customer_id', recordFieldPath: 'account.code' }],
576
+ allowInteractiveControls: true,
577
+ allowExport: true,
578
+ },
579
+ },
580
+ dataView: {
581
+ id: 1,
582
+ title: 'Logs',
583
+ dataSourceKey: 'es_main',
584
+ indexPattern: 'logs-*',
585
+ timeField: '@timestamp',
586
+ },
587
+ result: {
588
+ total: 1,
589
+ totalRelation: 'eq',
590
+ tookMs: 3,
591
+ visualization: 'table',
592
+ columns: ['@timestamp', 'service', 'status', 'latency_ms'],
593
+ rows: [
594
+ {
595
+ _id: 'doc-21',
596
+ _index: 'logs-2026',
597
+ source: {
598
+ '@timestamp': '2026-11-30T02:00:00Z',
599
+ service: 'payments',
600
+ status: 502,
601
+ latency_ms: 1500,
602
+ },
603
+ },
604
+ ],
605
+ series: [],
606
+ histogram: [],
607
+ metricValue: null,
608
+ metricLabel: 'Count',
609
+ compiledDsl: { query: { match_all: {} } },
610
+ },
611
+ },
612
+ },
613
+ };
614
+ }
615
+ return { data: { data: { buckets: [] } } };
616
+ });
617
+
618
+ await act(async () => {
619
+ renderWithoutMotion(
620
+ <div>
621
+ <ElasticBasicChart
622
+ title="Stacked Latency by Service"
623
+ visualization="bar"
624
+ stackMode="stacked"
625
+ seriesKeys={['checkout', 'payments']}
626
+ metricLabel="P95 Latency"
627
+ metricValue={null}
628
+ totalHits={25}
629
+ series={[
630
+ {
631
+ key: '10:00',
632
+ label: '10:00',
633
+ value: 600,
634
+ count: 25,
635
+ breakdown: [
636
+ { seriesKey: 'checkout', value: 250, count: 15 },
637
+ { seriesKey: 'payments', value: 350, count: 10 },
638
+ ],
639
+ },
640
+ ]}
641
+ />
642
+ <ElasticBasicChart
643
+ title="P95 Latency KPI"
644
+ visualization="metric"
645
+ metricType="p95"
646
+ metricLabel="P95 Latency"
647
+ metricValue={250}
648
+ previousMetricValue={200}
649
+ deltaPercent={25}
650
+ totalHits={100}
651
+ series={[]}
652
+ />
653
+ <ElasticFilterBar scopeKey={scopeKey} showGlobalKql={true} showGlobalTimeRange={true} />
654
+ <ElasticReportBlock
655
+ reportId={21}
656
+ scopeKey={scopeKey}
657
+ subscribeDashboardFilters={true}
658
+ contextRecord={{ account: { code: 'ACME-01' } }}
659
+ />
660
+ </div>,
661
+ );
662
+ });
663
+
664
+ // Formatted duration_ms (1500 -> "1.50 s") and KPI previous-period delta (+25%) are rendered
665
+ await waitFor(() => {
666
+ expect(screen.getByText('1.50 s')).toBeTruthy();
667
+ });
668
+ expect(screen.getByText(/\+25%/)).toBeTruthy();
669
+
670
+ // Context binding filter (customer_id = ACME-01) is sent automatically
671
+ await waitFor(() => {
672
+ expect(mocks.request).toHaveBeenCalledWith(
673
+ expect.objectContaining({
674
+ url: 'esReportService:runReport',
675
+ data: expect.objectContaining({
676
+ reportId: 21,
677
+ overrides: expect.objectContaining({
678
+ contextFilters: [expect.objectContaining({ field: 'customer_id', operator: 'eq', value: 'ACME-01' })],
679
+ }),
680
+ }),
681
+ }),
682
+ );
683
+ });
684
+
685
+ // Global KQL from ElasticFilterBar propagates via DashboardFilterBus to ElasticReportBlock
686
+ const kqlInputs = screen.getAllByRole('combobox', { name: 'KQL / Search Query' });
687
+ await act(async () => {
688
+ await user.type(kqlInputs[0], 'status >= 500');
689
+ await user.click(screen.getByRole('button', { name: 'Apply' }));
690
+ });
691
+
692
+ await waitFor(() => {
693
+ expect(mocks.request).toHaveBeenCalledWith(
694
+ expect.objectContaining({
695
+ url: 'esReportService:runReport',
696
+ data: expect.objectContaining({
697
+ reportId: 21,
698
+ overrides: expect.objectContaining({
699
+ query: 'status >= 500',
700
+ }),
701
+ }),
702
+ }),
703
+ );
704
+ });
705
+
706
+ // Clicking Discover cell "+" button pushes shared cross-filter pill to ElasticFilterBar and re-queries
707
+ await act(async () => {
708
+ await user.click(screen.getByRole('button', { name: 'Filter for value: service=payments' }));
709
+ });
710
+
711
+ await waitFor(() => {
712
+ expect(mocks.request).toHaveBeenCalledWith(
713
+ expect.objectContaining({
714
+ url: 'esReportService:runReport',
715
+ data: expect.objectContaining({
716
+ reportId: 21,
717
+ overrides: expect.objectContaining({
718
+ sharedFilters: [expect.objectContaining({ field: 'service', operator: 'eq', value: 'payments' })],
719
+ }),
720
+ }),
721
+ }),
722
+ );
723
+ });
724
+ expect(screen.getByText(/service eq payments/)).toBeTruthy();
725
+ });
726
+
727
+ it('provides guided KQL autocomplete for fields, operators, live Elasticsearch top values, and Enter-to-submit', async () => {
728
+ const user = userEvent.setup();
729
+
730
+ mocks.request.mockImplementation(async (cfg: { url: string; data?: Record<string, unknown> }) => {
731
+ if (cfg.url === 'esReportService:getReportMeta') {
732
+ return {
733
+ data: {
734
+ data: {
735
+ report: {
736
+ id: 30,
737
+ title: 'Guided Search Report',
738
+ dataViewId: 1,
739
+ visualization: 'table',
740
+ published: true,
741
+ spec: {
742
+ visualization: 'table',
743
+ columns: ['@timestamp', 'service', 'status'],
744
+ allowInteractiveControls: true,
745
+ },
746
+ },
747
+ dataView: {
748
+ id: 1,
749
+ title: 'Logs',
750
+ dataSourceKey: 'es_main',
751
+ indexPattern: 'logs-*',
752
+ timeField: '@timestamp',
753
+ },
754
+ fields: [
755
+ { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
756
+ { name: 'service', type: 'keyword', searchable: true, aggregatable: true },
757
+ { name: 'status', type: 'integer', searchable: true, aggregatable: true },
758
+ ],
759
+ },
760
+ },
761
+ };
762
+ }
763
+ if (cfg.url === 'esReportService:inspectTopValues') {
764
+ return {
765
+ data: {
766
+ data: {
767
+ field: cfg.data?.field,
768
+ resolvedField: cfg.data?.field,
769
+ totalDocs: 50,
770
+ buckets:
771
+ cfg.data?.field === 'service'
772
+ ? [
773
+ { value: 'gateway', count: 32, percentage: 64 },
774
+ { value: 'billing-api', count: 18, percentage: 36 },
775
+ ]
776
+ : [{ value: '500', count: 20, percentage: 40 }],
777
+ },
778
+ },
779
+ };
780
+ }
781
+ if (cfg.url === 'esReportService:runReport') {
782
+ return {
783
+ data: {
784
+ data: {
785
+ report: {
786
+ id: 30,
787
+ title: 'Guided Search Report',
788
+ dataViewId: 1,
789
+ visualization: 'table',
790
+ published: true,
791
+ spec: {
792
+ visualization: 'table',
793
+ columns: ['@timestamp', 'service', 'status'],
794
+ allowInteractiveControls: true,
795
+ },
796
+ },
797
+ dataView: {
798
+ id: 1,
799
+ title: 'Logs',
800
+ dataSourceKey: 'es_main',
801
+ indexPattern: 'logs-*',
802
+ timeField: '@timestamp',
803
+ },
804
+ result: {
805
+ total: 1,
806
+ totalRelation: 'eq',
807
+ tookMs: 2,
808
+ visualization: 'table',
809
+ columns: ['@timestamp', 'service', 'status'],
810
+ rows: [],
811
+ series: [],
812
+ histogram: [],
813
+ metricValue: null,
814
+ metricLabel: 'Count',
815
+ compiledDsl: { query: { match_all: {} } },
816
+ },
817
+ },
818
+ },
819
+ };
820
+ }
821
+ return { data: { data: [] } };
822
+ });
823
+
824
+ await act(async () => {
825
+ renderWithoutMotion(<ElasticReportBlock reportId={30} showToolbar={true} />);
826
+ });
827
+
828
+ const kqlCombo = await screen.findByRole('combobox', { name: 'KQL / Search Query' });
829
+
830
+ // 1. Focus empty search input -> field suggestions appear
831
+ await act(async () => {
832
+ await user.click(kqlCombo);
833
+ });
834
+ const serviceFieldOpt = await screen.findByRole('option', { name: /service/i });
835
+
836
+ // 2. Click `service` -> inserts `service: ` and automatically loads live top values from Elasticsearch
837
+ await act(async () => {
838
+ await user.click(serviceFieldOpt);
839
+ });
840
+ expect((kqlCombo as HTMLInputElement).value).toBe('service: ');
841
+
842
+ const gatewayValOpt = await screen.findByRole('option', { name: /"gateway"/i });
843
+ expect(mocks.request).toHaveBeenCalledWith(
844
+ expect.objectContaining({
845
+ url: 'esReportService:inspectTopValues',
846
+ data: expect.objectContaining({
847
+ reportId: 30,
848
+ field: 'service',
849
+ overrides: expect.objectContaining({
850
+ query: '',
851
+ }),
852
+ }),
853
+ }),
854
+ );
855
+ await act(async () => {
856
+ await user.click(gatewayValOpt);
857
+ });
858
+ expect((kqlCombo as HTMLInputElement).value).toBe('service: "gateway" ');
859
+
860
+ // 3. Press Enter directly without highlighting another option -> executes the search immediately
861
+ await act(async () => {
862
+ await user.keyboard('{Enter}');
863
+ });
864
+
865
+ await waitFor(() => {
866
+ expect(mocks.request).toHaveBeenCalledWith(
867
+ expect.objectContaining({
868
+ url: 'esReportService:runReport',
869
+ data: expect.objectContaining({
870
+ reportId: 30,
871
+ overrides: expect.objectContaining({
872
+ query: 'service: "gateway"',
873
+ }),
874
+ }),
875
+ }),
876
+ );
877
+ });
878
+ });
879
+ });