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
@@ -0,0 +1,340 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var report_block_tools_exports = {};
28
+ __export(report_block_tools_exports, {
29
+ createReportBlockTools: () => createReportBlockTools
30
+ });
31
+ module.exports = __toCommonJS(report_block_tools_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_constants = require("../shared/constants");
34
+ var import_acl_guard = require("./acl-guard");
35
+ var import_ElasticReportService = require("./services/ElasticReportService");
36
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
37
+ function fail(ctx, status, key) {
38
+ var _a;
39
+ throw Object.assign(new Error(((_a = ctx.t) == null ? void 0 : _a.call(ctx, key, { ns: import_constants.PLUGIN_NAME })) ?? key), { status });
40
+ }
41
+ const defaults = { reportId: null, showToolbar: true, compact: false, subscribeDashboardFilters: true, syncGroup: "" };
42
+ const propertySchemas = {
43
+ reportId: { type: ["number", "string"] },
44
+ showToolbar: { type: "boolean" },
45
+ compact: { type: "boolean" },
46
+ subscribeDashboardFilters: { type: "boolean" },
47
+ syncGroup: { type: "string" }
48
+ };
49
+ function isReportId(value) {
50
+ return typeof value === "string" && !!value.trim() || typeof value === "number" && Number.isSafeInteger(value);
51
+ }
52
+ function validField(key, value, expected) {
53
+ if (key === "reportId") {
54
+ return expected && value === null || isReportId(value);
55
+ }
56
+ if (key === "syncGroup") return typeof value === "string";
57
+ return Object.hasOwn(defaults, key) && typeof value === "boolean";
58
+ }
59
+ function sameSetting(key, left, right) {
60
+ if (key === "reportId" && left != null && right != null) return String(left) === String(right);
61
+ return left === right;
62
+ }
63
+ function readPatch(ctx, { changes, expected }) {
64
+ if (!isObject(changes) || !isObject(expected)) fail(ctx, 400, "Invalid block changes");
65
+ const keys = Object.keys(changes);
66
+ if (!keys.length || keys.length !== Object.keys(expected).length) fail(ctx, 400, "Invalid block changes");
67
+ for (const key of keys) {
68
+ if (!Object.hasOwn(expected, key) || !validField(key, changes[key], false) || !validField(key, expected[key], true)) {
69
+ fail(ctx, 400, "Invalid block changes");
70
+ }
71
+ }
72
+ return { changes, expected };
73
+ }
74
+ async function selectedContext(app, ctx, type) {
75
+ var _a, _b;
76
+ const values = (_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values;
77
+ let items;
78
+ if (Array.isArray(values == null ? void 0 : values.messages)) {
79
+ const userMessage = values.messages.find((item) => isObject(item) && item.role === "user");
80
+ items = userMessage == null ? void 0 : userMessage.workContext;
81
+ } else if (typeof (values == null ? void 0 : values.sessionId) === "string") {
82
+ const sessionId = values.sessionId;
83
+ const owned = await app.db.getRepository("aiConversations").count({
84
+ filter: { sessionId, userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx) }
85
+ });
86
+ if (owned) {
87
+ const message = await app.db.getRepository("aiMessages").findOne({
88
+ filter: { sessionId, role: "user", ...values.messageId ? { messageId: { $lte: values.messageId } } : {} },
89
+ fields: ["workContext"],
90
+ sort: ["-messageId"]
91
+ });
92
+ items = message == null ? void 0 : message.get("workContext");
93
+ }
94
+ }
95
+ const selected = Array.isArray(items) ? items.filter((item) => isObject(item) && item.type === type) : [];
96
+ return selected.length === 1 ? selected[0] : void 0;
97
+ }
98
+ async function resolvePage(app, ctx, uid, write, transaction) {
99
+ const paths = await app.db.getRepository("flowModelTreePath").find({
100
+ filter: { descendant: uid },
101
+ sort: ["depth"],
102
+ fields: ["ancestor"],
103
+ transaction
104
+ });
105
+ const ancestors = [.../* @__PURE__ */ new Set([uid, ...paths.map((path) => path.get("ancestor"))])];
106
+ const routes = app.db.getRepository("desktopRoutes");
107
+ const anchors = await routes.find({
108
+ filter: { schemaUid: { $in: ancestors }, type: { $in: ["flowPage", "tabs"] } },
109
+ transaction
110
+ });
111
+ const anchor = ancestors.map((id) => anchors.find((route) => route.get("schemaUid") === id)).find(Boolean);
112
+ const page = (anchor == null ? void 0 : anchor.get("type")) === "tabs" ? await routes.findOne({ filter: { id: anchor.get("parentId"), type: "flowPage" }, transaction }) : anchor;
113
+ if (!page || !anchor) fail(ctx, 403, "Block page unavailable");
114
+ const roles = (0, import_acl_guard.getEffectiveRoles)(ctx);
115
+ const routeIds = new Set([page.get("id"), anchor.get("id")].map(String));
116
+ if (app.db.hasCollection("uiLayouts")) {
117
+ let parentId = page.get("parentId");
118
+ while (parentId != null && !roles.includes("root")) {
119
+ if (routeIds.has(String(parentId))) fail(ctx, 403, "Block page unavailable");
120
+ routeIds.add(String(parentId));
121
+ const parent = await routes.findOne({ filterByTk: parentId, fields: ["parentId"], transaction });
122
+ if (!parent) fail(ctx, 403, "Block page unavailable");
123
+ parentId = parent.get("parentId");
124
+ }
125
+ const enabled = await app.db.getRepository("uiLayouts").find({ filter: { enabled: true }, fields: ["uid"], transaction });
126
+ const assignments = await app.db.getRepository("desktopRoutesUiLayouts").find({
127
+ filter: {
128
+ desktopRouteId: { $in: [...routeIds] },
129
+ uiLayoutUid: { $in: enabled.map((layout) => layout.get("uid")) }
130
+ },
131
+ transaction
132
+ });
133
+ const inCommonLayout = enabled.some(
134
+ (layout) => assignments.filter((link) => link.get("uiLayoutUid") === layout.get("uid")).length === routeIds.size
135
+ );
136
+ if (!inCommonLayout) fail(ctx, 403, "Block page unavailable");
137
+ }
138
+ if (!roles.includes("root")) {
139
+ const grants = await app.db.getRepository("rolesDesktopRoutes").find({
140
+ filter: { roleName: { $in: roles }, desktopRouteId: { $in: [...routeIds] } },
141
+ transaction
142
+ });
143
+ for (const grant of grants) routeIds.delete(String(grant.get("desktopRouteId")));
144
+ if (routeIds.size) fail(ctx, 403, "Block page unavailable");
145
+ }
146
+ const acl = app.acl.can({ roles, resource: "flowModels", action: "save" });
147
+ const canSave = !!acl && !Object.keys(acl.params ?? {}).length;
148
+ const shared = app.db.hasCollection("flowModelTemplates") && await app.db.getRepository("flowModelTemplates").count({
149
+ filter: { targetUid: { $in: ancestors } },
150
+ transaction
151
+ });
152
+ const canConfigure = canSave && !shared;
153
+ if (write && !canConfigure) fail(ctx, 403, "Block editing unavailable");
154
+ return { pageUid: String(page.get("schemaUid")), canConfigure };
155
+ }
156
+ function createReportBlockTools(app, reports) {
157
+ async function requirePublishedReport(id, ctx, transaction) {
158
+ const report = await reports.findReport(id, transaction);
159
+ if (!(report == null ? void 0 : report.published) || !report.dataView || !(0, import_acl_guard.canAccessReport)(app, ctx, report, report.dataView))
160
+ fail(ctx, 403, "Report unavailable for this block");
161
+ return report;
162
+ }
163
+ async function addBlock({ pageUid, tabUid, reportId }, ctx) {
164
+ (0, import_acl_guard.assertAuthenticated)(ctx);
165
+ const attachment = await selectedContext(app, ctx, import_constants.REPORT_DESTINATION_CONTEXT);
166
+ const selected = attachment == null ? void 0 : attachment.content;
167
+ if (!isObject(selected) || typeof pageUid !== "string" || !pageUid || typeof tabUid !== "string" || !tabUid || attachment.uid !== tabUid || !isReportId(reportId) || selected.pageUid !== pageUid || selected.tabUid !== tabUid || !sameSetting("reportId", selected.reportId, reportId)) {
168
+ fail(ctx, 400, "Select report block destination");
169
+ }
170
+ const options = app.db.sequelize.getDialect() === "sqlite" ? { type: import_database.Transaction.TYPES.IMMEDIATE } : { isolationLevel: import_database.Transaction.ISOLATION_LEVELS.READ_COMMITTED };
171
+ return app.db.sequelize.transaction(options, async (transaction) => {
172
+ var _a, _b;
173
+ const route = await app.db.getRepository("desktopRoutes").model.findOne({
174
+ where: { schemaUid: tabUid, type: "tabs" },
175
+ transaction,
176
+ lock: true
177
+ });
178
+ if (!route) fail(ctx, 403, "Block page unavailable");
179
+ const page = await resolvePage(app, ctx, tabUid, true, transaction);
180
+ if (page.pageUid !== pageUid) fail(ctx, 403, "Block page unavailable");
181
+ const report = await requirePublishedReport(reportId, ctx, transaction);
182
+ const repo = app.db.getRepository("flowModels");
183
+ const anchor = await repo.model.findByPk(tabUid, { transaction, lock: true });
184
+ if (!anchor) await repo.upsertModel({ uid: tabUid, use: "RootPageTabModel" }, { transaction });
185
+ const gridUid = await repo.ensureRouteContent(
186
+ { parentId: tabUid, subKey: "grid", use: "BlockGridModel" },
187
+ { transaction }
188
+ );
189
+ const grid = await repo.findModelById(gridUid, { transaction });
190
+ if ((grid == null ? void 0 : grid.use) !== "BlockGridModel") fail(ctx, 403, "Block page unavailable");
191
+ await resolvePage(app, ctx, gridUid, true, transaction);
192
+ const existing = (_b = (_a = grid.subModels) == null ? void 0 : _a.items) == null ? void 0 : _b.find(
193
+ (item) => {
194
+ var _a2, _b2, _c, _d;
195
+ return item.use === "ElasticReportBlockModel" && sameSetting(
196
+ "reportId",
197
+ ((_c = (_b2 = (_a2 = item.stepParams) == null ? void 0 : _a2.elasticReportBlockSettings) == null ? void 0 : _b2.editReport) == null ? void 0 : _c.reportId) ?? ((_d = item.props) == null ? void 0 : _d.reportId),
198
+ report.id
199
+ );
200
+ }
201
+ );
202
+ const target2 = { pageUid, tabUid, gridUid, reportId: report.id };
203
+ if (existing) return { ...target2, blockUid: existing.uid, created: false };
204
+ const blockUid = await repo.upsertModel(
205
+ {
206
+ parentId: gridUid,
207
+ subKey: "items",
208
+ subType: "array",
209
+ use: "ElasticReportBlockModel",
210
+ stepParams: { elasticReportBlockSettings: { editReport: { reportId: report.id } } }
211
+ },
212
+ { transaction }
213
+ );
214
+ transaction.afterCommit(() => {
215
+ app.emit("ws:sendToUser", {
216
+ userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx),
217
+ message: { type: import_constants.BLOCK_ADDED_EVENT, payload: { gridUid, blockUid } }
218
+ });
219
+ });
220
+ return { ...target2, blockUid, created: true };
221
+ });
222
+ }
223
+ async function run(args, ctx, write) {
224
+ var _a;
225
+ (0, import_acl_guard.assertAuthenticated)(ctx);
226
+ const uid = args.blockUid;
227
+ if (typeof uid !== "string" || !uid.trim()) fail(ctx, 400, "Pick one Elastic Report block");
228
+ if (((_a = await selectedContext(app, ctx, "flow-model")) == null ? void 0 : _a.uid) !== uid) fail(ctx, 400, "Pick one Elastic Report block");
229
+ const patch = write ? readPatch(ctx, args) : void 0;
230
+ const transactionOptions = write && app.db.sequelize.getDialect() === "sqlite" ? { type: import_database.Transaction.TYPES.IMMEDIATE } : {};
231
+ return app.db.sequelize.transaction(transactionOptions, async (transaction) => {
232
+ const repo = app.db.getRepository("flowModels");
233
+ const row = await repo.model.findByPk(uid, { transaction, lock: write });
234
+ const raw = row == null ? void 0 : row.get("options");
235
+ const options = typeof raw === "string" ? JSON.parse(raw) : raw;
236
+ if (!isObject(options) || options.use !== "ElasticReportBlockModel") fail(ctx, 404, "Block page unavailable");
237
+ const page = await resolvePage(app, ctx, uid, write, transaction);
238
+ if ((write || args.pageUid !== void 0) && args.pageUid !== page.pageUid)
239
+ fail(ctx, 403, "Block page unavailable");
240
+ const steps = isObject(options.stepParams) ? options.stepParams : {};
241
+ const flow = isObject(steps.elasticReportBlockSettings) ? steps.elasticReportBlockSettings : {};
242
+ const edit = isObject(flow.editReport) ? flow.editReport : {};
243
+ const stored = { ...isObject(options.props) ? options.props : {}, ...edit };
244
+ const settings = {};
245
+ for (const [key, fallback] of Object.entries(defaults)) settings[key] = stored[key] ?? fallback;
246
+ if (patch) {
247
+ const { changes, expected } = patch;
248
+ if (typeof changes.reportId === "number" || typeof changes.reportId === "string") {
249
+ await requirePublishedReport(changes.reportId, ctx, transaction);
250
+ }
251
+ const pending = Object.keys(changes).filter((key) => !sameSetting(key, settings[key], changes[key]));
252
+ if (pending.some((key) => !sameSetting(key, settings[key], expected[key])))
253
+ fail(ctx, 409, "Block settings changed");
254
+ if (pending.length) {
255
+ const legacyProps = Object.fromEntries(
256
+ Object.keys(defaults).filter((key) => stored[key] != null && !Object.hasOwn(edit, key)).map((key) => [key, stored[key]])
257
+ );
258
+ await repo.patch(
259
+ {
260
+ uid,
261
+ stepParams: {
262
+ ...steps,
263
+ elasticReportBlockSettings: { ...flow, editReport: { ...legacyProps, ...edit, ...changes } }
264
+ }
265
+ },
266
+ { transaction }
267
+ );
268
+ }
269
+ transaction.afterCommit(() => {
270
+ app.emit("ws:sendToUser", {
271
+ userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx),
272
+ message: { type: import_constants.BLOCK_SETTINGS_EVENT, payload: { blockUid: uid, changes } }
273
+ });
274
+ });
275
+ return { blockUid: uid, ...page, changes };
276
+ }
277
+ let reportTitle;
278
+ if (typeof settings.reportId === "number" || typeof settings.reportId === "string") {
279
+ const report = await reports.findReport(settings.reportId, transaction);
280
+ if ((report == null ? void 0 : report.dataView) && (0, import_acl_guard.canAccessReport)(app, ctx, report, report.dataView)) reportTitle = report.title;
281
+ if (reportTitle === void 0) settings.reportId = null;
282
+ }
283
+ return { blockUid: uid, ...page, settings, reportTitle };
284
+ });
285
+ }
286
+ const target = { blockUid: { type: "string" }, pageUid: { type: "string" } };
287
+ return [
288
+ {
289
+ name: "es_add_report_block",
290
+ title: import_constants.PLUGIN_NAME + ":Add report block",
291
+ description: "Append the published report selected in Report block destination to the selected page and tab. Reuse an existing block for that report in the same grid. Supply the exact IDs from the attached destination.",
292
+ defaultPermission: "ASK",
293
+ inputSchema: {
294
+ type: "object",
295
+ required: ["pageUid", "tabUid", "reportId"],
296
+ additionalProperties: false,
297
+ properties: {
298
+ pageUid: { type: "string" },
299
+ tabUid: { type: "string" },
300
+ reportId: propertySchemas.reportId
301
+ }
302
+ },
303
+ execute: (args, ctx = {}) => addBlock(args, ctx)
304
+ },
305
+ {
306
+ name: "es_describe_block",
307
+ title: import_constants.PLUGIN_NAME + ":Inspect selected Elastic Report block",
308
+ description: "Read display settings and the page UID of the Elastic Report block attached with Pick block.",
309
+ defaultPermission: "ALLOW",
310
+ inputSchema: { type: "object", required: ["blockUid"], properties: target, additionalProperties: false },
311
+ execute: (args, ctx = {}) => run(args, ctx, false)
312
+ },
313
+ {
314
+ name: "es_configure_block",
315
+ title: import_constants.PLUGIN_NAME + ":Configure selected Elastic Report block",
316
+ description: "Update only the picked instance. Supply the page UID and previous values from es_describe_block. Use null as the previous reportId for an unbound block.",
317
+ defaultPermission: "ASK",
318
+ inputSchema: {
319
+ type: "object",
320
+ required: ["blockUid", "pageUid", "expected", "changes"],
321
+ additionalProperties: false,
322
+ properties: {
323
+ ...target,
324
+ changes: { type: "object", minProperties: 1, additionalProperties: false, properties: propertySchemas },
325
+ expected: {
326
+ type: "object",
327
+ minProperties: 1,
328
+ additionalProperties: false,
329
+ properties: { ...propertySchemas, reportId: { type: ["number", "string", "null"] } }
330
+ }
331
+ }
332
+ },
333
+ execute: (args, ctx = {}) => run(args, ctx, true)
334
+ }
335
+ ];
336
+ }
337
+ // Annotate the CommonJS export names for ESM import in node:
338
+ 0 && (module.exports = {
339
+ createReportBlockTools
340
+ });
@@ -197,16 +197,21 @@ class ElasticReportService {
197
197
  });
198
198
  return rows.map(serializeReport);
199
199
  }
200
- async getReport(reportId) {
200
+ async findReport(reportId, transaction) {
201
201
  const repo = this.app.db.getRepository(import_constants.REPORTS_COLLECTION);
202
202
  const row = await repo.findOne({
203
203
  filterByTk: reportId,
204
- appends: ["dataView"]
204
+ appends: ["dataView"],
205
+ transaction
205
206
  });
206
- if (!row) {
207
+ return row ? serializeReport(row) : null;
208
+ }
209
+ async getReport(reportId) {
210
+ const report = await this.findReport(reportId);
211
+ if (!report) {
207
212
  throw new Error(`Report "${String(reportId)}" was not found`);
208
213
  }
209
- return serializeReport(row);
214
+ return report;
210
215
  }
211
216
  async saveReport(input, userId) {
212
217
  var _a;
@@ -222,11 +227,11 @@ class ElasticReportService {
222
227
  const repo = this.app.db.getRepository(import_constants.REPORTS_COLLECTION);
223
228
  const values = {
224
229
  title,
225
- description: input.description ?? null,
230
+ ...input.description !== void 0 ? { description: input.description } : {},
226
231
  dataViewId: dataView.id,
227
232
  visualization: spec.visualization,
228
233
  spec,
229
- published: input.published !== false,
234
+ ...input.published !== void 0 ? { published: input.published } : {},
230
235
  ...input.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(input.allowedRoles) } : {},
231
236
  ...userId !== void 0 ? { updatedById: userId } : {}
232
237
  };
@@ -237,6 +242,7 @@ class ElasticReportService {
237
242
  });
238
243
  return this.getReport(input.id);
239
244
  }
245
+ values.published ??= true;
240
246
  if (values.allowedRoles === void 0) {
241
247
  values.allowedRoles = [];
242
248
  }
@@ -27,6 +27,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var constants_exports = {};
28
28
  __export(constants_exports, {
29
29
  ACL_SNIPPET: () => ACL_SNIPPET,
30
+ BLOCK_ADDED_EVENT: () => BLOCK_ADDED_EVENT,
31
+ BLOCK_SETTINGS_EVENT: () => BLOCK_SETTINGS_EVENT,
30
32
  DATA_VIEWS_COLLECTION: () => DATA_VIEWS_COLLECTION,
31
33
  DEFAULT_MAX_EXPORT_ROWS: () => DEFAULT_MAX_EXPORT_ROWS,
32
34
  DEFAULT_PAGE_SIZE: () => DEFAULT_PAGE_SIZE,
@@ -43,6 +45,7 @@ __export(constants_exports, {
43
45
  MCP_SERVER_NAME: () => MCP_SERVER_NAME,
44
46
  PLUGIN_NAME: () => PLUGIN_NAME,
45
47
  REPORTS_COLLECTION: () => REPORTS_COLLECTION,
48
+ REPORT_DESTINATION_CONTEXT: () => REPORT_DESTINATION_CONTEXT,
46
49
  SERVICE_RESOURCE: () => SERVICE_RESOURCE,
47
50
  SETTINGS_MENU_KEY: () => SETTINGS_MENU_KEY,
48
51
  WORKFLOW_GROUP_KEY: () => WORKFLOW_GROUP_KEY,
@@ -51,6 +54,9 @@ __export(constants_exports, {
51
54
  module.exports = __toCommonJS(constants_exports);
52
55
  const PLUGIN_NAME = "plugin-elastic-report";
53
56
  const SETTINGS_MENU_KEY = "elastic-report";
57
+ const BLOCK_SETTINGS_EVENT = "elastic-report:block-settings";
58
+ const BLOCK_ADDED_EVENT = "elastic-report:block-added";
59
+ const REPORT_DESTINATION_CONTEXT = "elastic-report-destination";
54
60
  const ACL_SNIPPET = "pm.elastic-report";
55
61
  const DATA_VIEWS_COLLECTION = "esReportDataViews";
56
62
  const REPORTS_COLLECTION = "esReports";
@@ -73,6 +79,8 @@ const WORKFLOW_INSTRUCTION_TYPE = "elastic-report-query";
73
79
  // Annotate the CommonJS export names for ESM import in node:
74
80
  0 && (module.exports = {
75
81
  ACL_SNIPPET,
82
+ BLOCK_ADDED_EVENT,
83
+ BLOCK_SETTINGS_EVENT,
76
84
  DATA_VIEWS_COLLECTION,
77
85
  DEFAULT_MAX_EXPORT_ROWS,
78
86
  DEFAULT_PAGE_SIZE,
@@ -89,6 +97,7 @@ const WORKFLOW_INSTRUCTION_TYPE = "elastic-report-query";
89
97
  MCP_SERVER_NAME,
90
98
  PLUGIN_NAME,
91
99
  REPORTS_COLLECTION,
100
+ REPORT_DESTINATION_CONTEXT,
92
101
  SERVICE_RESOURCE,
93
102
  SETTINGS_MENU_KEY,
94
103
  WORKFLOW_GROUP_KEY,
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "description": "Kibana-style Elasticsearch Discover & Visualization reports with reusable blocks and a dedicated MCP server for AI Employees.",
7
7
  "description.vi-VN": "Tạo báo cáo bảng và biểu đồ từ dữ liệu Elasticsearch theo phong cách Kibana, gắn dưới dạng Block và cung cấp MCP riêng cho AI Employee.",
8
8
  "description.zh-CN": "连接 Elasticsearch 构建类 Kibana 的检索、筛选、排序与基础图表报表区块,并提供专属 MCP 服务供 AI 员工调用。",
9
- "version": "0.7.0",
9
+ "version": "0.9.0",
10
10
  "license": "Apache-2.0",
11
11
  "main": "dist/server/index.js",
12
12
  "keywords": [
@@ -20,7 +20,6 @@
20
20
  ],
21
21
  "files": [
22
22
  "dist",
23
- "ai",
24
23
  "src",
25
24
  "client.js",
26
25
  "client.d.ts",
@@ -56,7 +55,7 @@
56
55
  "url": "git+https://github.com/OrgGem/nocobase-beta.git",
57
56
  "directory": "packages/plugins/plugin-elastic-report"
58
57
  },
59
- "gitHead": "3680e22db0068952760bb3b869a054cef57a6d77",
58
+ "gitHead": "04dbff450450c00a7c4d8eb70ee3e53d2ec41154",
60
59
  "publishConfig": {
61
60
  "access": "public",
62
61
  "registry": "https://registry.npmjs.org/"
package/server.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './dist/server';
2
- export { default } from './dist/server';
1
+ export * from './dist/server';
2
+ export { default } from './dist/server';
package/server.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/server/index.js');
1
+ module.exports = require('./dist/server/index.js');
@@ -0,0 +1,52 @@
1
+ ---
2
+ name: elastic-report-builder
3
+ scope: CUSTOM
4
+ introduction:
5
+ title: Elastic Report Builder
6
+ title: Elasticsearch Kibana Report Builder
7
+ description: Discover Elasticsearch data views, inspect field capabilities, preview KQL/filter/sort/aggregation queries, and create Saved Elasticsearch Reports for NocoBase blocks.
8
+ tools:
9
+ - elastic-report-es_list_connections
10
+ - elastic-report-es_list_data_views
11
+ - elastic-report-es_upsert_data_view
12
+ - elastic-report-es_inspect_fields
13
+ - elastic-report-es_preview_report
14
+ - elastic-report-es_save_report
15
+ - elastic-report-es_list_reports
16
+ - elastic-report-es_analyze_report
17
+ - elastic-report-es_create_dashboard_bundle
18
+ - elastic-report-es_describe_block
19
+ - elastic-report-es_configure_block
20
+ - elastic-report-es_add_report_block
21
+ ---
22
+
23
+ # Elasticsearch Report Builder Guide
24
+
25
+ Use these tools (or their `mcp-elastic-report-*` equivalents) whenever a user asks to explore Elasticsearch logs/metrics/documents or build a Kibana-style Table or Chart report in NocoBase.
26
+
27
+ ## Reports in Settings
28
+
29
+ Save drafts with `published: false`. For edits, fetch the existing report by ID and preserve its full spec, including locked filters and role restrictions. Return the saved report ID and actual publication status.
30
+
31
+ 1. **Locate or Create a Data View**:
32
+ - Call `es_list_data_views` first.
33
+ - If no matching Data View exists yet, call `es_list_connections` to check available Elasticsearch connections and index names, then call `es_upsert_data_view` with `dataSourceKey` and `indexPattern` (for example `logs-*`).
34
+ 2. **Inspect Field Capabilities (`_field_caps`)**:
35
+ - Always call `es_inspect_fields` for the chosen `dataViewId` before writing filters, sorts, or chart buckets.
36
+ - Never guess field names. When sorting or grouping (`terms` bucket) on a `text` field, prefer its `keywordSubfield` (for example `service.keyword`) or a field marked `aggregatable: true`.
37
+ 3. **Preview Before Saving**:
38
+ - Call `es_preview_report` with your proposed `spec` (`visualization`: `'table' | 'bar' | 'line' | 'area' | 'pie' | 'metric'`, `query` in KQL, `filters`, `sort`, `timeRange`, `columns` or `chart`).
39
+ - Verify `total` hits and sample rows/series look accurate; adjust filters or field names if `total` is unexpectedly 0 or an error occurs.
40
+ 4. **Save Single Reports, Dashboard Bundles, or Analyze Existing Reports**:
41
+ - Call `es_save_report` for a single report, or `es_create_dashboard_bundle` to generate a coordinated multi-panel dashboard (KPI with `comparePreviousPeriod`, `p95`/`p99` line chart, stacked `splitSeriesField` breakdown, and Discover table) with optional `allowedRoles` and `lockedFilters` (supports server tokens `{{$user.id}}`, `{{$user.username}}`, `{{$role}}`).
42
+ - When a user asks to analyze or explain data from an already published report, call `es_analyze_report` (respects the caller's role and `lockedFilters`).
43
+
44
+ ## Edit the selected block
45
+
46
+ Use Pick block to attach exactly one Elastic Report block to the request. Call the native `es_describe_block` with its UID. To change that instance, call `es_configure_block` with the returned page UID, block UID, requested fields and their current values in `expected`. A display-only change requires no report save. If a value conflicts, describe again and show the user what changed before retrying.
47
+
48
+ For a combined create-and-bind request, describe the block and check `canConfigure` first. Preview and save the report once, then bind its published ID. If binding fails, return that ID and retry only the block change.
49
+
50
+ ## Add a report block to a tab
51
+
52
+ On a page without a report block, ask the user to attach **Work context → Report block destination**. They select the page/tab and a published report, then send the request. Call `elastic-report-es_add_report_block` with the exact `pageUid`, `tabUid` and `reportId` from that attachment. The user approves the tool in chat. Report the returned block UID and whether it was added or already present. The block appears at the end of the tab. If needed, reopen the tab or reload it. To use a draft, have the user publish it and select it first.
@@ -1,34 +1,34 @@
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 { Plugin } from '@nocobase/client';
11
- import { ElasticFilterBarBlockModel } from '../client-v2/models/ElasticFilterBarBlockModel';
12
- import { ElasticReportBlockModel } from '../client-v2/models/ElasticReportBlockModel';
13
- import type { WorkflowClientRegistry } from '../client-v2/workflow/instructions';
14
-
15
- export class PluginElasticReportLegacyClient extends Plugin {
16
- async load() {
17
- this.flowEngine?.registerModels?.({
18
- ElasticReportBlockModel,
19
- ElasticFilterBarBlockModel,
20
- });
21
-
22
- const workflow = (
23
- this.app as unknown as {
24
- pm?: { get?: (name: string) => WorkflowClientRegistry | undefined };
25
- }
26
- ).pm?.get?.('workflow');
27
- if (workflow && typeof workflow.registerInstruction === 'function') {
28
- const { registerLegacyWorkflowInstructions } = await import('./workflow-instructions');
29
- registerLegacyWorkflowInstructions(workflow);
30
- }
31
- }
32
- }
33
-
34
- export default PluginElasticReportLegacyClient;
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 { Plugin } from '@nocobase/client';
11
+ import { ElasticFilterBarBlockModel } from '../client-v2/models/ElasticFilterBarBlockModel';
12
+ import { ElasticReportBlockModel } from '../client-v2/models/ElasticReportBlockModel';
13
+ import type { WorkflowClientRegistry } from '../client-v2/workflow/instructions';
14
+
15
+ export class PluginElasticReportLegacyClient extends Plugin {
16
+ async load() {
17
+ this.flowEngine?.registerModels?.({
18
+ ElasticReportBlockModel,
19
+ ElasticFilterBarBlockModel,
20
+ });
21
+
22
+ const workflow = (
23
+ this.app as unknown as {
24
+ pm?: { get?: (name: string) => WorkflowClientRegistry | undefined };
25
+ }
26
+ ).pm?.get?.('workflow');
27
+ if (workflow && typeof workflow.registerInstruction === 'function') {
28
+ const { registerLegacyWorkflowInstructions } = await import('./workflow-instructions');
29
+ registerLegacyWorkflowInstructions(workflow);
30
+ }
31
+ }
32
+ }
33
+
34
+ export default PluginElasticReportLegacyClient;