dsh-data-dashboard 0.0.0-stage → 0.1.4

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/README.md +35 -2
  2. package/assets/theater-board.svg +1 -0
  3. package/backend/incremental/flow.mjs +492 -0
  4. package/backend/incremental/jobs.mjs +58 -0
  5. package/backend/incremental/xlsx-rows.mjs +145 -0
  6. package/backend/job-worker.mjs +22 -0
  7. package/backend/modules/banquet/index.mjs +46 -0
  8. package/backend/modules/inventory/index.mjs +45 -0
  9. package/backend/modules/inventory/legacy-fields.mjs +83 -0
  10. package/backend/modules/invoice/index.mjs +72 -0
  11. package/backend/modules/movement/index.mjs +68 -0
  12. package/backend/modules/opening/index.mjs +48 -0
  13. package/backend/modules/target/index.mjs +45 -0
  14. package/backend/modules/terminal/index.mjs +114 -0
  15. package/backend/modules.mjs +12 -0
  16. package/backend/public/admin.css +192 -0
  17. package/backend/public/admin.js +713 -0
  18. package/backend/public/board.css +43 -0
  19. package/backend/public/board.html +47 -0
  20. package/backend/public/board.js +96 -0
  21. package/backend/public/index.html +110 -0
  22. package/backend/public/review.css +5 -0
  23. package/backend/public/review.js +452 -0
  24. package/backend/real-data/generate-dashboard.mjs +135 -0
  25. package/backend/real-data/inventory-history.mjs +316 -0
  26. package/backend/real-data/organization-mapping.mjs +102 -0
  27. package/backend/real-data/source-payload.mjs +459 -0
  28. package/backend/real-data/terminal-components.mjs +280 -0
  29. package/backend/real-data/terminal-structure.css +105 -0
  30. package/backend/real-data/terminal-structure.mjs +276 -0
  31. package/backend/real-data/v10-components.mjs +112 -0
  32. package/backend/real-data/v10-details.css +18 -0
  33. package/backend/real-data/v10-details.mjs +251 -0
  34. package/backend/real-data/v10-layout.css +27 -0
  35. package/backend/real-data/v10-model.mjs +521 -0
  36. package/backend/real-data/v10-overview-data.mjs +248 -0
  37. package/backend/real-data/v10-overview.css +264 -0
  38. package/backend/real-data/v10-overview.mjs +263 -0
  39. package/backend/real-data/v10-presentation.mjs +342 -0
  40. package/backend/real-data/v10-shell.html +1097 -0
  41. package/backend/real-data/v10-template.mjs +351 -0
  42. package/backend/recognition/fingerprint.mjs +32 -0
  43. package/backend/recognition/headers.mjs +2 -0
  44. package/backend/recognition/module-definition.mjs +4 -0
  45. package/backend/recognition/result.mjs +29 -0
  46. package/backend/recognition/upload-limits.mjs +14 -0
  47. package/backend/review-engine.mjs +364 -0
  48. package/backend/review-service.mjs +182 -0
  49. package/backend/server.mjs +545 -0
  50. package/backend/store.mjs +68 -0
  51. package/backend/target-template.mjs +47 -0
  52. package/backend/validate-workbook.mjs +251 -0
  53. package/backend/web-sync/README.md +37 -0
  54. package/backend/web-sync/client.mjs +63 -0
  55. package/backend/web-sync/exporter.mjs +260 -0
  56. package/backend/web-sync/local.html +34 -0
  57. package/backend/web-sync/server.mjs +147 -0
  58. package/build-manifest.json +79 -0
  59. package/client.js +24 -0
  60. package/cordis.patch.yml +3 -0
  61. package/index.js +117 -0
  62. package/lib/dist-manifest.mjs +19 -0
  63. package/lib/market-index.mjs +56 -0
  64. package/lib/package-audit.mjs +34 -0
  65. package/lib/settings.mjs +71 -0
  66. package/lib/tool-definitions.mjs +56 -0
  67. package/lib/tools.mjs +255 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +71 -4
package/index.js ADDED
@@ -0,0 +1,117 @@
1
+ // Host face of the DSH plugin: start the existing local backend on a plugin
2
+ // port while the row is enabled, and close it when the row is disposed.
3
+ import http from 'node:http';
4
+ import { existsSync } from 'node:fs';
5
+ import { dirname, resolve } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { DEFAULT_PORT, frameOriginsFor, problemPage, resolveSettings, startupProblem } from './lib/settings.mjs';
8
+ import { createBoardQueries } from './lib/tools.mjs';
9
+ import { toolDefinitions } from './lib/tool-definitions.mjs';
10
+
11
+ export const name = 'dsh-data-dashboard';
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url));
14
+ // DSH packages resolve from the running host (declared as optional peers).
15
+ let Schema, dshTools, dshLlm;
16
+ try { Schema = (await import('@deepseek-ai/schemastery')).default; } catch {}
17
+ try { dshTools = await import('@deepseek-ai/dsh-tools'); } catch {}
18
+ try { dshLlm = await import('@deepseek-ai/dsh-llm'); } catch {}
19
+
20
+ export const Config = Schema && Schema.object({
21
+ port: Schema.natural().min(1024).max(65535).default(DEFAULT_PORT).volatile()
22
+ .description('插件后台端口(只监听 127.0.0.1)。默认 4181,避开源码版的 4180。'),
23
+ dataDir: Schema.string().default('')
24
+ .description('数据目录(绝对路径)。留空使用用户数据目录下的 TheaterCommandBoard-DSH/data;可指向项目的「本机后台数据」以沿用现有数据,但同一目录同时只能有一个后台在用。'),
25
+ extraFrameAncestors: Schema.array(Schema.string()).default([])
26
+ .description('额外允许嵌入看板的本机页面来源(如 http://127.0.0.1:3080),一般不需要填写。'),
27
+ });
28
+
29
+ /** Backend location: bundled copy first (distribution), then the source checkout. */
30
+ export function backendEntry() {
31
+ for (const candidate of [resolve(here, 'backend/server.mjs'), resolve(here, '../战区看板原型/backend/server.mjs')]) if (existsSync(candidate)) return candidate;
32
+ throw new Error('找不到战区看板后台源码(backend/server.mjs)。');
33
+ }
34
+
35
+ /** Start the backend, or a static explanation page on the same port when it cannot start. */
36
+ const embedOrigin = origin => typeof origin === 'string' && (/^https?:\/\/(127\.0\.0\.1|localhost)(:\d{1,5})?$/.test(origin) || origin === 'dsh-app://app');
37
+
38
+ /** Volatile config fields arrive as refs with get(); plain values pass through. */
39
+ const plain = config => Object.fromEntries(Object.entries(config || {}).map(([key, value]) => [key, typeof value?.get === 'function' ? value.get() : value]));
40
+
41
+ export async function startBoard(config = {}, { frameOrigins = () => [], log = console } = {}) {
42
+ const settings = resolveSettings(plain(config));
43
+ const ancestors = () => [...new Set([...frameOrigins(), ...settings.extraFrameAncestors].filter(embedOrigin))];
44
+ try {
45
+ const { createAdminServer } = await import(pathToFileURL(backendEntry()).href);
46
+ const backend = await createAdminServer({ port: settings.port, dataDir: settings.dataDir, frameAncestors: ancestors });
47
+ log.info?.(`[dsh-data-dashboard] 看板后台已启动 ${backend.url}(数据目录 ${settings.dataDir})`);
48
+ return { ok: true, url: backend.url, settings, close: () => backend.close() };
49
+ } catch (error) {
50
+ const problem = startupProblem(error, settings);
51
+ log.warn?.(`[dsh-data-dashboard] ${problem.message}`);
52
+ if (problem.code === 'port_in_use') return { ok: false, problem, settings, close: async () => {} };
53
+ const page = problemPage(problem);
54
+ const server = http.createServer((request, response) => {
55
+ const hosts = [`127.0.0.1:${settings.port}`, `localhost:${settings.port}`];
56
+ if (!hosts.includes(request.headers.host)) { response.writeHead(403); response.end(); return; }
57
+ if (request.url.startsWith('/api/health')) {
58
+ response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
59
+ response.end(JSON.stringify({ ready: false, problem }));
60
+ return;
61
+ }
62
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'self' ${ancestors().join(' ')}`.trim() });
63
+ response.end(page);
64
+ });
65
+ try {
66
+ await new Promise((ok, fail) => { server.once('error', fail); server.listen(settings.port, '127.0.0.1', ok); });
67
+ } catch (listenError) {
68
+ return { ok: false, problem: startupProblem(listenError, settings), settings, close: async () => {} };
69
+ }
70
+ return { ok: false, problem, settings, close: () => new Promise(ok => { server.close(() => ok()); server.closeAllConnections?.(); }) };
71
+ }
72
+ }
73
+
74
+ export function apply(ctx, config = {}) {
75
+ let web = null;
76
+ let current = null;
77
+ ctx.inject?.(['webServer'], webCtx => {
78
+ web = webCtx.webServer;
79
+ webCtx.effect(() => () => { web = null; });
80
+ });
81
+ // Always admit the desktop window (dsh-app://app); add the DSH Web origin once known.
82
+ const frameOrigins = () => {
83
+ let origin = null;
84
+ try { origin = web ? web.getOrigin() : null; } catch {}
85
+ return frameOriginsFor(origin);
86
+ };
87
+ // ctx.effect owns the backend: its disposer runs when the row is disabled,
88
+ // uninstalled or hot-replaced, and waits for uploads/generation to settle.
89
+ ctx.effect(() => {
90
+ let disposed = false;
91
+ const running = startBoard(config, { frameOrigins }).then(board => {
92
+ if (disposed) return board.close().then(() => null);
93
+ current = board;
94
+ return board;
95
+ }, error => { console.warn(`[dsh-data-dashboard] ${error.message}`); return null; });
96
+ return async () => {
97
+ disposed = true;
98
+ current = null;
99
+ const board = await running;
100
+ if (board) { await board.close(); console.info('[dsh-data-dashboard] 看板后台已关闭'); }
101
+ };
102
+ });
103
+
104
+ // Read-only AI tools (docs/DSH插件.md §5). Registered only when the host
105
+ // offers a tool registry; failures here never affect the board itself.
106
+ if (dshTools?.defineTool && ctx.inject) {
107
+ let settings;
108
+ try { settings = resolveSettings(plain(config)); } catch { return; }
109
+ const queries = createBoardQueries({
110
+ dataDir: settings.dataDir, backendDir: dirname(backendEntry()), port: settings.port,
111
+ problem: () => (current && !current.ok ? current.problem : current ? null : { message: '战区看板后台尚未启动或已停用。' }),
112
+ });
113
+ ctx.inject(['tools'], toolCtx => {
114
+ for (const definition of toolDefinitions(queries, { HarnessError: dshLlm?.HarnessError })) toolCtx.tools.register(dshTools.defineTool(definition));
115
+ });
116
+ }
117
+ }
@@ -0,0 +1,19 @@
1
+ // package.json of the published package (dist/package). The source manifest keeps
2
+ // "private": true so `npm publish` from dsh-plugin/ is refused; only the built copy
3
+ // is publishable, and always to the official registry (a mirror cannot accept it).
4
+ export const NPM_REGISTRY = 'https://registry.npmjs.org/';
5
+ export const RUNTIME_DEPENDENCIES = ['exceljs', 'saxes', 'yauzl'];
6
+ export const PACKAGE_FILES = ['index.js', 'client.js', 'cordis.patch.yml', 'README.md', 'lib/', 'locale/*.json', 'assets/', 'backend/', 'package-lock.json', 'build-manifest.json'];
7
+
8
+ export function distManifest(pluginManifest, appManifest) {
9
+ const { private: _private, ...rest } = pluginManifest;
10
+ const missing = RUNTIME_DEPENDENCIES.filter(name => !appManifest.dependencies?.[name]);
11
+ if (missing.length) throw new Error(`应用 package.json 缺少运行依赖:${missing.join('、')}`);
12
+ if (!rest.repository?.url || !rest.homepage) throw new Error('插件 package.json 缺少 repository 或 homepage。');
13
+ return {
14
+ ...rest,
15
+ files: PACKAGE_FILES,
16
+ dependencies: Object.fromEntries(RUNTIME_DEPENDENCIES.map(name => [name, appManifest.dependencies[name]])),
17
+ publishConfig: { registry: NPM_REGISTRY, access: 'public' },
18
+ };
19
+ }
@@ -0,0 +1,56 @@
1
+ // Build the DSH custom plugin index (format 1) for a Git distribution.
2
+ // Rules follow DSH docs/user/guide/plugin-market: https Git URL without
3
+ // credentials or fragment, 40-hex commit, exact SemVer, Unix-second timestamp.
4
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
5
+
6
+ /** npm source; DSH installs `name@version`, asking `registry` first when given. */
7
+ export function npmSource({ registry } = {}) {
8
+ if (registry === undefined || registry === null || registry === '') return { type: 'npm' };
9
+ let url;
10
+ try { url = new URL(registry); } catch { throw new Error(`注册表地址无效:${registry}`); }
11
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.hash) throw new Error('注册表地址须为不含用户名、密码或 # 片段的 http(s) 地址。');
12
+ return { type: 'npm', registry: url.href };
13
+ }
14
+
15
+ export function gitSource({ repo, commit, path }) {
16
+ let url;
17
+ try { url = new URL(repo); } catch { throw new Error(`仓库地址无效:${repo}`); }
18
+ if (url.protocol !== 'https:') throw new Error('Git 仓库地址必须是 https。');
19
+ if (url.username || url.password) throw new Error('仓库地址不能包含用户名或密码;私有仓库的访问凭据由使用者本机的 Git 保存。');
20
+ if (url.hash || url.search) throw new Error('仓库地址不能包含 # 片段或查询参数。');
21
+ if (!/^[0-9a-f]{40}$/.test(commit || '')) throw new Error('commit 必须是 40 位小写十六进制完整提交号。');
22
+ const clean = repo.replace(/\.git$/, '').replace(/\/$/, '');
23
+ const dir = typeof path === 'string' ? path.replace(/^\/+|\/+$/g, '') : '';
24
+ if (dir && (dir.split('/').includes('..') || /\\/.test(dir))) throw new Error(`包目录无效:${path}`);
25
+ return { type: 'git', url: clean, commit, ...(dir ? { path: dir } : {}) };
26
+ }
27
+
28
+ /**
29
+ * @param manifest - the built package.json (name, version, description, engines).
30
+ * @param source - git source from gitSource().
31
+ * @param previous - an existing index to extend (keeps earlier versions).
32
+ */
33
+ const repositoryUrl = (manifest, source) => source.type === 'git' ? source.url
34
+ : typeof manifest.repository?.url === 'string' ? manifest.repository.url.replace(/^git\+/, '').replace(/\.git$/, '') : null;
35
+
36
+ export function buildIndex({ manifest, source, publishTimestamp = Math.floor(Date.now() / 1000), previous = null, icon = 'icons/theater-board.svg', homepage = manifest.homepage }) {
37
+ if (!SEMVER.test(manifest.version)) throw new Error(`版本号不是 SemVer:${manifest.version}`);
38
+ if (icon.startsWith('data:') && Buffer.byteLength(icon) > 32 * 1024) throw new Error('内嵌图标超过 32 KiB。');
39
+ const version = { version: manifest.version, publishTimestamp, source, ...(manifest.engines?.dsh ? { engines: { dsh: manifest.engines.dsh } } : {}) };
40
+ const base = previous ?? { format: 1, title: { en: 'DSH Data Dashboard plugins', zh: '战区看板插件' }, plugins: [] };
41
+ if (base.format !== 1 || !Array.isArray(base.plugins)) throw new Error('已有索引格式无效。');
42
+ const existing = base.plugins.find(plugin => plugin.name === manifest.name);
43
+ const versions = [...(existing?.versions || []).filter(item => item.version !== manifest.version), version]
44
+ .sort((a, b) => b.publishTimestamp - a.publishTimestamp);
45
+ const plugin = {
46
+ name: manifest.name,
47
+ title: { en: 'DSH Data Dashboard', zh: '战区看板' },
48
+ description: { en: 'Local theater sales dashboard inside DeepSeek Harness, with read-only board query tools.', zh: '在 DeepSeek Harness 中打开本机战区经营看板(看板 / 更新数据 / 历史版本),并提供只读看板查询工具。' },
49
+ icon,
50
+ author: '战区看板项目',
51
+ ...(homepage ? { homepage } : {}),
52
+ ...(repositoryUrl(manifest, source) ? { repository: { url: repositoryUrl(manifest, source), ...(source.path ? { directory: source.path } : {}) } } : {}),
53
+ versions,
54
+ };
55
+ return { ...base, plugins: [...base.plugins.filter(item => item.name !== manifest.name), plugin] };
56
+ }
@@ -0,0 +1,34 @@
1
+ // Distribution safety check for the packed plugin (docs/DSH插件.md §7). The
2
+ // package must never carry business workbooks, data directories, generated
3
+ // dashboards, credentials or machine configuration.
4
+ const ALLOWED_ROOT = new Set(['package.json', 'package-lock.json', 'build-manifest.json', 'README.md', 'index.js', 'client.js', 'cordis.patch.yml']);
5
+ const ALLOWED_HTML = [/^backend\/public\/[^/]+\.html$/, /^backend\/web-sync\/local\.html$/, /^backend\/real-data\/v10-shell\.html$/];
6
+ const FORBIDDEN = [
7
+ [/\.(xlsx|xlsm|xls|csv|tsv|zip|tgz|7z|rar|db|sqlite|log)$/i, '业务数据或压缩包'],
8
+ [/(^|\/)(本机后台数据|销售看板数据|业务资料|看板归档|历史版本|网站版|node_modules|generations|uploads)(\/|$)/, '数据或依赖目录'],
9
+ [/(^|\/)(\.env[^/]*|\.npmrc|\.git|\.claude|\.openai|credentials[^/]*|id_rsa[^/]*|[^/]*\.pem|[^/]*\.key)$/i, '凭据或机器配置'],
10
+ [/(^|\/)(state|generation-decisions|review-settings)\.json$/i, '本机状态文件'],
11
+ ];
12
+
13
+ /**
14
+ * @param {{path: string, text?: string}[]} entries - package-relative POSIX paths, text for text files.
15
+ * @returns {string[]} problems; empty when the package is clean.
16
+ */
17
+ export function auditPackage(entries) {
18
+ const problems = [];
19
+ for (const { path, text } of entries) {
20
+ for (const [pattern, reason] of FORBIDDEN) if (pattern.test(path)) problems.push(`${path}:${reason}`);
21
+ const top = path.split('/')[0];
22
+ if (!path.includes('/') && !ALLOWED_ROOT.has(path)) problems.push(`${path}:未登记的根目录文件`);
23
+ if (path.includes('/') && !['lib', 'backend', 'assets', 'locale'].includes(top)) problems.push(`${path}:未登记的目录`);
24
+ if (path.endsWith('.html') && !ALLOWED_HTML.some(pattern => pattern.test(path))) problems.push(`${path}:只允许后台静态页面与去业务化的 v10 外壳`);
25
+ if (path.startsWith('backend/') && !/\.(mjs|js|css|html|md)$/.test(path)) problems.push(`${path}:后台出现未审核文件类型`);
26
+ if (path.startsWith('locale/') && !/^locale\/[a-z]{2}(-[A-Z]{2})?\.json$/.test(path)) problems.push(`${path}:语言文件只允许 locale/<语言>.json`);
27
+ if (typeof text === 'string') {
28
+ if (/\/Users\/|[A-Z]:\\Users\\/.test(text)) problems.push(`${path}:包含本机用户目录路径`);
29
+ // Generated dashboards embed a payload; shipped HTML must be static pages only.
30
+ if (path.endsWith('.html') && /const ZQ_RD = |V10_PAYLOAD=/.test(text)) problems.push(`${path}:疑似包含看板业务快照`);
31
+ }
32
+ }
33
+ return problems;
34
+ }
@@ -0,0 +1,71 @@
1
+ // Pure helpers for the DSH plugin host face; kept free of DSH imports so they
2
+ // can be tested with plain node:test.
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, join, resolve } from 'node:path';
5
+
6
+ export const DEFAULT_PORT = 4181;
7
+ export const FORMAL_PORT = 4180;
8
+ export const DATA_FOLDER = 'TheaterCommandBoard-DSH';
9
+ /** The DSH desktop window origin (custom standard+secure scheme). Allowed exactly, nothing broader. */
10
+ export const DSH_DESKTOP_ORIGIN = 'dsh-app://app';
11
+
12
+ /** Per-user application data directory (outside the plugin install directory). */
13
+ export function defaultDataDir({ platform = process.platform, env = process.env, home = homedir() } = {}) {
14
+ let base;
15
+ if (platform === 'win32') base = env.APPDATA || join(home, 'AppData', 'Roaming');
16
+ else if (platform === 'darwin') base = join(home, 'Library', 'Application Support');
17
+ else base = env.XDG_DATA_HOME || join(home, '.local', 'share');
18
+ return join(base, DATA_FOLDER, 'data');
19
+ }
20
+
21
+ /** Normalize the row config: port in range, data dir absolute. */
22
+ export function resolveSettings(config = {}, options) {
23
+ const port = config.port ?? DEFAULT_PORT;
24
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error(`端口必须是 1024–65535 之间的整数:${port}`);
25
+ if (port === FORMAL_PORT) throw new Error('端口 4180 留给源码版本机后台,请为插件选择其他端口。');
26
+ const raw = typeof config.dataDir === 'string' ? config.dataDir.trim() : '';
27
+ if (raw && !isAbsolute(raw)) throw new Error(`数据目录必须是绝对路径:${raw}`);
28
+ const extra = Array.isArray(config.extraFrameAncestors) ? config.extraFrameAncestors : [];
29
+ return { port, dataDir: raw ? resolve(raw) : defaultDataDir(options), extraFrameAncestors: extra };
30
+ }
31
+
32
+ /** Embedding origins in plugin mode: the DSH desktop window plus the loopback forms of the DSH Web origin. */
33
+ export function frameOriginsFor(webOrigin) {
34
+ return [DSH_DESKTOP_ORIGIN, ...dshOrigins(webOrigin)];
35
+ }
36
+
37
+ /** Loopback forms of the DSH page origin, so 127.0.0.1 and localhost both embed. */
38
+ export function dshOrigins(origin) {
39
+ if (!origin) return [];
40
+ let url;
41
+ try { url = new URL(origin); } catch { return []; }
42
+ if (!['http:', 'https:'].includes(url.protocol)) return [];
43
+ // Chrome rejects IPv6 literals in frame-ancestors, so only these two forms.
44
+ const loopback = ['127.0.0.1', 'localhost'];
45
+ if (![...loopback, '[::1]'].includes(url.hostname)) return [];
46
+ const port = url.port ? `:${url.port}` : '';
47
+ return loopback.map(host => `${url.protocol}//${host}${port}`);
48
+ }
49
+
50
+ /** Classify a startup failure into a message the panel shows instead of the board. */
51
+ export function startupProblem(error, { port, dataDir }) {
52
+ const message = String(error?.message || error);
53
+ if (error?.code === 'EADDRINUSE') return { code: 'port_in_use', message: `端口 ${port} 已被其他程序占用。请在插件配置中换一个端口后重新启用插件。` };
54
+ if (/已有后台进程在使用|startup\.lock|另一个后台正在启动/.test(message)) {
55
+ return { code: 'data_dir_locked', message: `数据目录正被另一个战区看板后台使用(例如源码版 http://127.0.0.1:${FORMAL_PORT}/ 或桌面版)。插件不会强行接管:请先关闭那个后台后重新启用插件,或在插件配置中改用其他数据目录。`, detail: `数据目录:${dataDir}` };
56
+ }
57
+ return { code: 'startup_failed', message: `战区看板后台启动失败:${message}`, detail: `数据目录:${dataDir}` };
58
+ }
59
+
60
+ const escape = text => String(text).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
61
+
62
+ /** Static explanation page served on the plugin port when the backend cannot start. */
63
+ export function problemPage(problem) {
64
+ return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>战区看板未启动</title>
65
+ <body style="margin:0;font:14px/1.7 -apple-system,BlinkMacSystemFont,'PingFang SC','Microsoft YaHei',sans-serif;color:#1f2328;background:#f6f7f9">
66
+ <main style="max-width:560px;margin:72px auto;padding:24px 28px;background:#fff;border:1px solid #e5e7eb;border-radius:12px">
67
+ <h1 style="font-size:16px;margin:0 0 8px">战区看板暂未启动</h1>
68
+ <p style="margin:0 0 8px">${escape(problem.message)}</p>
69
+ ${problem.detail ? `<p style="margin:0;color:#6b7280;font-size:12px">${escape(problem.detail)}</p>` : ''}
70
+ </main></body></html>`;
71
+ }
@@ -0,0 +1,56 @@
1
+ // DSH tool definitions for the read-only board queries (docs/DSH插件.md §5).
2
+ // Kept apart from DSH imports: defineTool / HarnessError are passed in.
3
+ import { BoardToolError } from './tools.mjs';
4
+
5
+ const json = { type: 'json' };
6
+ const render = (_args, value) => [{ type: 'text', text: JSON.stringify(value) }];
7
+
8
+ export function toolDefinitions(queries, { HarnessError } = {}) {
9
+ const fail = error => {
10
+ if (!(error instanceof BoardToolError)) throw error;
11
+ const message = Object.keys(error.detail || {}).length ? `${error.message}\n${JSON.stringify(error.detail)}` : error.message;
12
+ if (HarnessError) throw new HarnessError(message, error.code.toUpperCase());
13
+ throw Object.assign(new Error(message), { code: error.code });
14
+ };
15
+ const run = fn => async args => { try { return await fn(args || {}); } catch (error) { return fail(error); } };
16
+ const shared = '只读:不上传、不修改数据、不生成看板。数据来自最近一次成功生成的战区看板;指标 state 为 available 时 value 才是数值,pending/unavailable/missing 时须照 reason 说明,不能当作 0 或自行估算。';
17
+ return [
18
+ {
19
+ name: 'theater_board_status',
20
+ description: `战区经营看板:查看七类资料(发票、动销、开瓶、签约、库存、宴席、经营目标)的当前文件、上传时间、数据起止日、是否超期待更新,以及最近一次生成的看板时间和打开链接。${shared}`,
21
+ parameters: {},
22
+ output: { schema: json, render },
23
+ isConcurrencySafe: () => true,
24
+ timeoutMs: 60_000,
25
+ execute: run(() => queries.status()),
26
+ },
27
+ {
28
+ name: 'theater_board_summary',
29
+ description: `战区经营看板:按月份或日期区间、大区/办事处/主任单元,返回发票销售、终端动销、消费者开瓶的主指标、当年累计和经营目标达成率(与看板同一口径)。三个板块分别统计,不要自行计算它们之间的比例。组织名称请先用 theater_board_organizations 确认。${shared}`,
30
+ parameters: {
31
+ month: { type: 'string', description: '月份 YYYY-MM;与 start/end 二选一;都不填为看板默认最近月份' },
32
+ start: { type: 'string', description: '区间开始 YYYY-MM-DD(需与 end 同时给出)' },
33
+ end: { type: 'string', description: '区间结束 YYYY-MM-DD' },
34
+ region: { type: 'string', description: '大区显示名称(看板下拉中的名称)' },
35
+ office: { type: 'string', description: '办事处显示名称' },
36
+ unit: { type: 'string', description: '主任单元显示名称' },
37
+ },
38
+ output: { schema: json, render },
39
+ isConcurrencySafe: () => true,
40
+ timeoutMs: 120_000,
41
+ execute: run(args => queries.summary(args)),
42
+ },
43
+ {
44
+ name: 'theater_board_organizations',
45
+ description: `战区经营看板:列出可查询的组织名称(不填参数列大区;给 region 列其办事处;再给 office 列主任单元),含完整组织路径和出现于哪些板块。同名组织按完整路径区分,不要合并。${shared}`,
46
+ parameters: {
47
+ region: { type: 'string', description: '大区显示名称' },
48
+ office: { type: 'string', description: '办事处显示名称' },
49
+ },
50
+ output: { schema: json, render },
51
+ isConcurrencySafe: () => true,
52
+ timeoutMs: 120_000,
53
+ execute: run(args => queries.organizations(args)),
54
+ },
55
+ ];
56
+ }
package/lib/tools.mjs ADDED
@@ -0,0 +1,255 @@
1
+ // Read-only board queries behind the DSH AI tools (contract: docs/DSH插件.md §5).
2
+ // Everything is computed from the latest completed generation's embedded payload
3
+ // with the same createV10Model the dashboard runs, so numbers match the board.
4
+ // Nothing here writes to the data directory or calls backend write endpoints.
5
+ import { createHash } from 'node:crypto';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { resolve } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ export class BoardToolError extends Error {
11
+ constructor(code, message, detail = {}) { super(message); this.code = code; this.detail = detail; }
12
+ }
13
+
14
+ const FLOW = ['invoice', 'movement', 'opening'];
15
+ const MONTH = /^\d{4}-\d{2}$/;
16
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
17
+ const finite = value => typeof value === 'number' && Number.isFinite(value);
18
+ const text = value => String(value ?? '').trim();
19
+
20
+ /** Payload literal boundaries inside a rendered dashboard (see v10-template.mjs renderShell). */
21
+ export function extractPayload(html, unpackSource) {
22
+ const prefix = `const V10_PAYLOAD=(${unpackSource})(`;
23
+ const start = html.indexOf(prefix);
24
+ if (start < 0) return null;
25
+ const from = start + prefix.length;
26
+ const end = html.indexOf(');\nconst V10_PRESENTATION=', from);
27
+ if (end < 0) return null;
28
+ return JSON.parse(html.slice(from, end));
29
+ }
30
+
31
+ export function createBoardQueries({ dataDir, backendDir, port, problem = () => null }) {
32
+ let modulesPromise;
33
+ const code = () => modulesPromise ??= Promise.all([
34
+ import(pathToFileURL(resolve(backendDir, 'real-data/v10-template.mjs')).href),
35
+ import(pathToFileURL(resolve(backendDir, 'real-data/v10-model.mjs')).href),
36
+ import(pathToFileURL(resolve(backendDir, 'real-data/terminal-structure.mjs')).href),
37
+ import(pathToFileURL(resolve(backendDir, 'modules.mjs')).href),
38
+ import(pathToFileURL(resolve(backendDir, 'server.mjs')).href),
39
+ ]).then(([template, model, terminal, modules, server]) => ({
40
+ unpack: template.unpackV10Payload, createV10Model: model.createV10Model, buildTerminalStructure: terminal.buildTerminalStructure,
41
+ definitions: modules.moduleDefinitions, cycles: server.DEFAULT_CYCLES,
42
+ }));
43
+
44
+ const readState = async () => {
45
+ try { return JSON.parse(await readFile(resolve(dataDir, 'state.json'), 'utf8')); }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT') return { uploads: [], active: {}, candidates: {}, generations: [] };
48
+ throw new BoardToolError('state_unreadable', '无法读取插件数据目录中的 state.json,请在看板“更新数据”中检查后台状态。');
49
+ }
50
+ };
51
+ const selectedId = (state, id) => state.candidates?.[id] || state.active?.[id] || null;
52
+ const byTime = (a, b) => String(b.finishedAt || b.createdAt || '').localeCompare(String(a.finishedAt || a.createdAt || ''));
53
+ const latestCompleted = state => [...(state.generations || [])].filter(job => job.status === 'completed').sort(byTime)[0] || null;
54
+ const boardUrl = id => `http://127.0.0.1:${port}/api/generations/${id}/view`;
55
+ const newerUploads = (state, job, titles) => {
56
+ const ids = new Set([...Object.keys(state.active || {}), ...Object.keys(state.candidates || {})]);
57
+ return [...ids].filter(id => selectedId(state, id) && selectedId(state, id) !== job.sourceVersions?.[id]?.uploadId)
58
+ .map(id => ({ moduleId: id, title: titles[id] || id }));
59
+ };
60
+
61
+ let cached = null;
62
+ /** Load (and cache by generation id) the latest board's model. */
63
+ async function board() {
64
+ const [state, lib] = await Promise.all([readState(), code()]);
65
+ const titles = Object.fromEntries(lib.definitions.map(item => [item.id, item.title]));
66
+ const job = latestCompleted(state);
67
+ if (!job) throw new BoardToolError('no_board', '还没有成功生成过看板。请在战区看板的“更新数据”中上传资料并生成看板后再查询。');
68
+ if (cached?.id !== job.id) {
69
+ let html;
70
+ try { html = await readFile(resolve(dataDir, 'generations', job.id, 'dashboard.html'), 'utf8'); }
71
+ catch { throw new BoardToolError('no_board', '最近一次生成的看板文件无法读取,请重新生成看板。'); }
72
+ let payload;
73
+ try { payload = extractPayload(html, lib.unpack.toString()); } catch { payload = null; }
74
+ if (!payload) throw new BoardToolError('no_board', '最近一次生成的看板格式较旧,无法读取其中的数据;请在界面中重新生成看板后再查询。');
75
+ const unpacked = lib.unpack(payload);
76
+ const modelMatchesBoard = html.includes(`const V10=(${lib.createV10Model.toString()})(V10_PAYLOAD);`)
77
+ && html.includes(`const buildTerminalStructure=(${lib.buildTerminalStructure.toString()});`);
78
+ cached = { id: job.id, model: lib.createV10Model(unpacked), modelMatchesBoard, coverage: unpacked.coverage || {} };
79
+ }
80
+ const basis = {
81
+ generationId: job.id, generatedAt: job.finishedAt || job.createdAt, payloadSha256: job.payloadSha256 || null,
82
+ modelMatchesBoard: cached.modelMatchesBoard, newerUploads: newerUploads(state, job, titles),
83
+ dataEnd: Object.fromEntries(FLOW.map(id => [id, cached.coverage[id]?.end || null])),
84
+ ...(cached.modelMatchesBoard ? {} : { warning: '看板生成后计算代码已更新,数字可能与看板略有不同,建议重新生成。' }),
85
+ };
86
+ return { model: cached.model, basis, state, titles };
87
+ }
88
+
89
+ // ---- status ----
90
+ async function coverageOf(upload) {
91
+ if (upload.coverage?.start || upload.coverage?.end) return upload.coverage;
92
+ for (const file of ['coverage.json', 'aggregate.json']) {
93
+ try {
94
+ const data = JSON.parse(await readFile(resolve(dataDir, 'uploads', upload.id, file), 'utf8'));
95
+ if (data.sha256 !== upload.sha256) continue;
96
+ const range = file === 'coverage.json' ? data : data.aggregate;
97
+ if (range?.start || range?.end) return { start: range.start || null, end: range.end || null };
98
+ } catch {}
99
+ }
100
+ return null;
101
+ }
102
+ const localDay = value => { const date = new Date(value); return Number.isNaN(date.valueOf()) ? null : new Date(date.getFullYear(), date.getMonth(), date.getDate()); };
103
+ const cycleDays = { daily: 1, weekly: 7, monthly: 31, irregular: Infinity };
104
+
105
+ async function status({ now = Date.now() } = {}) {
106
+ const [state, lib] = await Promise.all([readState(), code()]);
107
+ const issue = problem();
108
+ const cycles = { ...lib.cycles, ...(state.settings?.cycles || {}) };
109
+ const sources = [];
110
+ for (const definition of lib.definitions) {
111
+ const id = definition.id, uploadId = selectedId(state, id);
112
+ const upload = (state.uploads || []).find(item => item.id === uploadId && item.moduleId === id);
113
+ const cycle = cycles[id] || 'irregular';
114
+ if (!upload) { sources.push({ moduleId: id, title: definition.title, state: 'none', filename: null, uploadedAt: null, dataStart: null, dataEnd: null, reviewStatus: null, cycle, overdue: null }); continue; }
115
+ const range = await coverageOf(upload);
116
+ const day = localDay(upload.uploadedAt || upload.createdAt);
117
+ const age = day ? Math.round((localDay(now) - day) / 86400000) : null;
118
+ sources.push({
119
+ moduleId: id, title: definition.title, state: 'active', filename: upload.originalName || upload.filename || null,
120
+ uploadedAt: upload.uploadedAt || upload.createdAt || null, dataStart: range?.start || null, dataEnd: range?.end || null,
121
+ ...(range ? {} : { dataRangeNote: '数据起止日尚未计算;打开插件后台后会自动补算。' }),
122
+ reviewStatus: upload.reviewStatus ?? 'unchecked', cycle, overdue: age === null ? null : age >= (cycleDays[cycle] ?? Infinity),
123
+ });
124
+ }
125
+ const titles = Object.fromEntries(lib.definitions.map(item => [item.id, item.title]));
126
+ const job = latestCompleted(state);
127
+ const failed = [...(state.generations || [])].sort(byTime)[0];
128
+ return {
129
+ backend: issue ? { state: 'problem', message: issue.message } : { state: 'running', url: `http://127.0.0.1:${port}/` },
130
+ sources,
131
+ latestBoard: job ? { generationId: job.id, generatedAt: job.finishedAt || job.createdAt, filename: job.filename || null, needsReview: Boolean(job.needsReview), url: boardUrl(job.id), newerUploads: newerUploads(state, job, titles) } : null,
132
+ lastAttempt: failed && failed.status === 'failed' ? { at: failed.finishedAt || failed.createdAt, error: failed.error || '生成未完成' } : null,
133
+ };
134
+ }
135
+
136
+ // ---- organizations ----
137
+ const partsOf = key => { try { const parts = JSON.parse(key); return Array.isArray(parts) ? parts.map(text) : []; } catch { return []; } };
138
+ const fullPath = key => partsOf(key).map(value => value || '未提供').join(' / ');
139
+ function levelItems(model, level, parentFilter) {
140
+ const keys = new Map();
141
+ for (const org of model.organizations) {
142
+ if (parentFilter && !parentFilter(org)) continue;
143
+ const key = org[level];
144
+ if (!keys.has(key)) keys.set(key, { key, name: partsOf(key).at(-1) || '未提供', fullPath: fullPath(key), label: model.label(key) });
145
+ }
146
+ return [...keys.values()];
147
+ }
148
+ function sourcesOf(model, level, key) {
149
+ return model.ids.filter(id => model.payload.modules[id].records.some(row => {
150
+ const parts = row.orgPath || [];
151
+ const depth = { region: 4, office: 5, unit: 6 }[level];
152
+ return JSON.stringify(parts.slice(0, depth).map(value => value || '')) === JSON.stringify(partsOf(key).map(value => value || ''));
153
+ })).map(id => model.titles[id]);
154
+ }
155
+ function resolveOrg(model, { region, office, unit }) {
156
+ const filters = { region: 'all', office: 'all', unit: 'all' };
157
+ const pick = (level, name, parent) => {
158
+ const all = levelItems(model, level, parent);
159
+ // Board dropdown label first (unique by construction), then full path, then bare name.
160
+ let items = all.filter(item => item.label === name);
161
+ if (!items.length) items = all.filter(item => item.fullPath === name);
162
+ if (!items.length) items = all.filter(item => item.name === name);
163
+ const names = { region: '大区', office: '办事处', unit: '主任单元' };
164
+ if (!items.length) {
165
+ const options = all.map(item => item.label);
166
+ const near = options.filter(option => option.includes(name) || name.includes(option)).slice(0, 10);
167
+ throw new BoardToolError('org_not_found', `看板中没有名为“${name}”的${names[level]}。`, { level, suggestions: near.length ? near : options.slice(0, 20) });
168
+ }
169
+ if (items.length > 1) throw new BoardToolError('org_ambiguous', `“${name}”对应多个${names[level]},请改用看板中的显示名称或完整路径。`, { level, candidates: items.map(item => ({ name: item.label, fullPath: item.fullPath })) });
170
+ return items[0].key;
171
+ };
172
+ if (text(region)) filters.region = pick('region', text(region));
173
+ if (text(office)) filters.office = pick('office', text(office), filters.region === 'all' ? null : org => org.region === filters.region);
174
+ if (text(unit)) filters.unit = pick('unit', text(unit), org => (filters.region === 'all' || org.region === filters.region) && (filters.office === 'all' || org.office === filters.office));
175
+ // Fill parents from the chosen child so the selection is a consistent path.
176
+ const chosen = model.organizations.find(org => (filters.unit === 'all' || org.unit === filters.unit) && (filters.office === 'all' || org.office === filters.office) && (filters.region === 'all' || org.region === filters.region));
177
+ if (chosen && filters.unit !== 'all') { filters.office = chosen.office; filters.region = chosen.region; }
178
+ else if (chosen && filters.office !== 'all') filters.region = chosen.region;
179
+ return filters;
180
+ }
181
+
182
+ async function organizations({ region, office } = {}) {
183
+ const { model, basis } = await board();
184
+ const parentFilters = resolveOrg(model, { region, office });
185
+ const level = parentFilters.office !== 'all' ? 'unit' : parentFilters.region !== 'all' ? 'office' : 'region';
186
+ const items = levelItems(model, level, org => (parentFilters.region === 'all' || org.region === parentFilters.region) && (parentFilters.office === 'all' || org.office === parentFilters.office))
187
+ .map(item => ({ name: item.label, fullPath: item.fullPath, sources: sourcesOf(model, level, item.key) }))
188
+ // Only organizations the summary can answer for (invoice / movement / opening).
189
+ .filter(item => item.sources.some(title => FLOW.some(id => model.titles[id] === title)));
190
+ return { basis: { generationId: basis.generationId, generatedAt: basis.generatedAt }, level, items };
191
+ }
192
+
193
+ // ---- summary ----
194
+ function shape(item, model) {
195
+ if (!item) return { label: null, unit: null, value: null, display: null, state: 'missing', reason: '没有该指标' };
196
+ const available = item.state === 'available' && finite(item.value);
197
+ let display = null;
198
+ if (available) display = item.unit === '元' ? `${model.format(item.value / 10000, 2)} 万元` : item.unit === '%' ? `${model.format(item.value, 1)}%` : `${model.format(item.value, item.precision ?? 0)} ${item.unit}`;
199
+ return { label: item.label, unit: item.unit, value: available ? item.value : null, display, state: available ? 'available' : (item.state === 'available' ? 'pending' : item.state || 'pending'), reason: available ? null : item.reason || null, ...(item.note ? { note: item.note } : {}) };
200
+ }
201
+
202
+ function periodFilters(model, { month, start, end }) {
203
+ const hasMonth = month !== undefined && month !== null && month !== '';
204
+ const hasRange = Boolean(start || end);
205
+ if (hasMonth && hasRange) throw new BoardToolError('bad_period', 'month 与 start/end 只能二选一。');
206
+ const months = model.months.filter(value => MONTH.test(value));
207
+ if (hasMonth) {
208
+ if (!MONTH.test(month)) throw new BoardToolError('bad_period', `月份格式应为 YYYY-MM:${month}`);
209
+ if (!months.includes(month)) throw new BoardToolError('bad_period', `看板中没有 ${month} 的来源记录。`, { months: months.length ? { first: months[0], last: months.at(-1) } : null });
210
+ return { month, period: 'month', start: null, end: null };
211
+ }
212
+ if (hasRange) {
213
+ if (!DATE.test(start || '') || !DATE.test(end || '') || start > end) throw new BoardToolError('bad_period', '区间需同时给出 start 与 end(YYYY-MM-DD),且开始不晚于结束。');
214
+ const bounds = model.dateBounds;
215
+ if (!bounds || start < bounds.min || end > bounds.max) throw new BoardToolError('bad_period', bounds ? `区间超出来源范围 ${bounds.min} 至 ${bounds.max}。` : '来源没有可用的日期范围。', { bounds });
216
+ return { month: end.slice(0, 7), period: 'range', start, end };
217
+ }
218
+ return { month: model.defaults.month, period: 'month', start: null, end: null };
219
+ }
220
+
221
+ async function summary(args = {}) {
222
+ const { model, basis } = await board();
223
+ const org = resolveOrg(model, args);
224
+ const filters = { ...model.defaults, ...periodFilters(model, args), ...org, product: 'all' };
225
+ const result = model.select(filters);
226
+ const p = result.period;
227
+ const modules = {};
228
+ for (const id of FLOW) {
229
+ const m = result.modules[id];
230
+ const t = m.targets || {};
231
+ modules[id] = {
232
+ title: m.title, state: m.state, main: shape(m.main, model),
233
+ ...(id === 'opening' ? {} : { ytd: shape(m.extra.find(item => item.label === '当年截至所选月来源金额'), model) }),
234
+ targets: { attainment: shape(t.attainment, model), ytdAttainment: shape(t.ytdAttainment, model), target: shape(t.month, model), ytdTarget: shape(t.ytd, model) },
235
+ records: m.recordCount, notes: [...m.pending],
236
+ };
237
+ }
238
+ const scopeKey = org.unit !== 'all' ? org.unit : org.office !== 'all' ? org.office : org.region !== 'all' ? org.region : null;
239
+ return {
240
+ basis,
241
+ scope: { label: model.scope(org), fullPath: scopeKey ? fullPath(scopeKey) : '全战区' },
242
+ period: { mode: p.mode, start: p.start, end: p.end, label: p.label },
243
+ modules,
244
+ };
245
+ }
246
+
247
+ return { status, summary, organizations, board };
248
+ }
249
+
250
+ /** Stable digest of the data directory files the tools may read (for read-only tests). */
251
+ export async function digestFiles(paths) {
252
+ const hash = createHash('sha256');
253
+ for (const path of paths) { try { hash.update(path); hash.update(await readFile(path)); } catch { hash.update(`${path}:missing`); } }
254
+ return hash.digest('hex');
255
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "DSH Data Dashboard",
4
+ "description": "Opens the local theater sales dashboard in DeepSeek Harness and adds read-only dashboard query tools."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "战区看板",
4
+ "description": "在 DeepSeek Harness 左侧栏打开本机战区经营看板(看板 / 更新数据 / 历史版本),并提供只读看板查询工具。"
5
+ }
6
+ }