dsh-data-dashboard 0.1.4 → 0.1.6

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.
@@ -3,8 +3,9 @@
3
3
  // Merged page: latest dashboard, the update page and generation history in
4
4
  // one place. Dashboards stay independent offline HTML files.
5
5
  const $ = selector => document.querySelector(selector);
6
- const titles = { invoice: '发票', movement: '动销', opening: '开瓶', terminal: '签约', inventory: '库存', banquet: '宴席', target: '目标' };
6
+ const titles = { invoice: '发票', movement: '动销', opening: '开瓶', terminal: '签约', inventory: '库存', banquet: '宴席', target: '目标', zang10: '藏10', tunzhihu: '吞之乎', distributor: '分销商' };
7
7
  let state = null, viewingId = null, known = null, followLatest = true, toastTimer = null;
8
+ const openMapping = new Set();
8
9
  const updateFrame = $('#update-frame');
9
10
 
10
11
  function show(view) {
@@ -35,25 +36,25 @@ function openVersion(job) {
35
36
  if (viewingId !== job.id) { frame.src = job.viewUrl; viewingId = job.id; }
36
37
  frame.hidden = false; $('#board-empty').hidden = true;
37
38
  }
38
- function renderMeta() {
39
+ // The top bar stays quiet for the normal current version; a hint only appears
40
+ // while generating, while viewing a non-current version, or when offline.
41
+ function setMeta(text, warn = false) {
42
+ const meta = $('#meta');
43
+ meta.textContent = text; meta.title = text; meta.hidden = !text; meta.classList.toggle('warn', warn);
44
+ }
45
+ function metaText() {
39
46
  const current = completed().find(job => job.id === viewingId);
40
47
  const latest = latestNormal();
41
- const running = (state.generations || []).find(job => job.status === 'running');
42
- $('#meta').innerHTML = '';
43
48
  const parts = [];
44
- if (running) parts.push(['正在生成新版本', '']);
45
- if (current) parts.push([current.id === latest?.id ? '当前版本' : '正在查看历史版本', `${time(current.finishedAt || current.createdAt)} 生成`], ['数据截至', dataEnd(current)]);
46
- else parts.push(['还没有生成过看板', '']);
47
- parts.forEach(([label, value], index) => {
48
- if (index) $('#meta').append(' · ');
49
- $('#meta').append(label);
50
- if (value) { const b = document.createElement('b'); b.textContent = ` ${value}`; $('#meta').append(b); }
51
- });
49
+ if ((state.generations || []).some(job => job.status === 'running')) parts.push('正在生成新版本…');
50
+ if (current && current.id !== latest?.id) parts.push(`正在查看${current.needsReview ? '待确认' : '历史'}版本 · ${time(current.finishedAt || current.createdAt)} 生成`);
51
+ return parts.join(' · ');
52
52
  }
53
+ function renderMeta() { setMeta(metaText()); }
53
54
  function renderHistory() {
54
55
  const body = $('#history'); body.replaceChildren();
55
56
  const jobs = (state.generations || []).filter(job => ['completed', 'failed', 'running'].includes(job.status));
56
- if (!jobs.length) { const row = body.insertRow(); const cell = row.insertCell(); cell.colSpan = 5; cell.className = 'muted'; cell.textContent = '还没有生成记录'; return; }
57
+ if (!jobs.length) { const row = body.insertRow(); const cell = row.insertCell(); cell.colSpan = 6; cell.className = 'muted'; cell.textContent = '还没有生成记录'; return; }
57
58
  const latest = latestNormal();
58
59
  for (const job of jobs.slice(0, 50)) {
59
60
  const row = body.insertRow(); if (job.id === viewingId) row.className = 'viewing';
@@ -64,6 +65,19 @@ function renderHistory() {
64
65
  const kind = job.status === 'failed' ? ['failed', '生成失败'] : job.status === 'running' ? ['running', '生成中'] : job.needsReview ? ['pending', '待确认版本'] : job.id === latest?.id ? ['cur', '当前'] : ['old', '历史'];
65
66
  pill.className = `pill ${kind[0]}`; pill.textContent = kind[1]; status.append(pill);
66
67
  if (job.status === 'failed' && job.error) status.title = job.error;
68
+ const mappingCell = row.insertCell();
69
+ const mapping = job.status === 'completed' && window.OrgMapping ? window.OrgMapping.view(job) : null;
70
+ if (mapping) {
71
+ const open = mapping.items.length && openMapping.has(job.id);
72
+ const chip = document.createElement(mapping.items.length ? 'button' : 'span');
73
+ chip.className = `chip ${mapping.kind}`; chip.textContent = `${mapping.chip}${mapping.items.length ? (open ? ' ▴' : ' ▾') : ''}`;
74
+ if (mapping.line) chip.title = mapping.line;
75
+ if (mapping.items.length) {
76
+ chip.type = 'button'; chip.setAttribute('aria-expanded', String(Boolean(open)));
77
+ chip.addEventListener('click', () => { if (openMapping.has(job.id)) openMapping.delete(job.id); else openMapping.add(job.id); renderHistory(); });
78
+ }
79
+ mappingCell.append(chip);
80
+ } else mappingCell.textContent = '—';
67
81
  const actions = row.insertCell();
68
82
  if (job.status === 'completed') {
69
83
  const view = document.createElement('button'); view.type = 'button'; view.className = 'link'; view.textContent = '查看';
@@ -71,13 +85,30 @@ function renderHistory() {
71
85
  const download = document.createElement('a'); download.className = 'link'; download.href = job.downloadUrl; download.textContent = '下载'; download.setAttribute('download', '');
72
86
  actions.append(view, ' · ', download);
73
87
  }
88
+ if (mapping && mapping.items.length && openMapping.has(job.id)) mappingDetail(body.insertRow(), mapping);
89
+ }
90
+ }
91
+ function mappingDetail(row, mapping) {
92
+ row.className = 'map-row';
93
+ const cell = row.insertCell(); cell.colSpan = 6;
94
+ const line = document.createElement('p'); line.className = 'map-line'; line.textContent = mapping.line;
95
+ const table = document.createElement('table'); table.className = 'map-list';
96
+ const head = table.createTHead().insertRow();
97
+ for (const label of ['板块', '原路径(大区 / 办事处 / 主任单元)', '行数', '原因']) { const th = document.createElement('th'); th.textContent = label; head.append(th); }
98
+ const tbody = table.createTBody();
99
+ for (const item of mapping.items) {
100
+ const r = tbody.insertRow();
101
+ for (const [text, cls] of [[item.module, 'mod'], [item.path, ''], [item.rows, ''], [item.reason, item.rejected ? 'rej' : 'pend']]) { const c = r.insertCell(); c.textContent = text; if (cls) c.className = cls; }
74
102
  }
103
+ cell.append(line, table);
104
+ if (mapping.more) { const more = document.createElement('p'); more.className = 'map-note'; more.textContent = `另有 ${mapping.more} 条未列出,完整清单见该版本的 diagnostics.json。`; cell.append(more); }
105
+ if (mapping.kind === 'partial') { const note = document.createElement('p'); note.className = 'map-note'; note.textContent = window.OrgMapping.note; cell.append(note); }
75
106
  }
76
107
  async function refresh() {
77
108
  try {
78
109
  const response = await fetch('/api/state', { cache: 'no-store' });
79
110
  state = await response.json();
80
- } catch { $('#meta').textContent = '无法连接本机后台,请确认后台已启动'; return; }
111
+ } catch { setMeta('无法连接本机后台,请确认后台已启动', true); return; }
81
112
  const done = completed();
82
113
  if (known === null) { known = new Set(done.map(job => job.id)); openVersion(latestNormal()); }
83
114
  else {
@@ -94,3 +125,29 @@ async function refresh() {
94
125
  }
95
126
  refresh();
96
127
  setInterval(() => { if (document.visibilityState === 'visible') refresh(); }, 3000);
128
+
129
+ // DSH desktop (DSH插件 4.1): app-region inside a cross-origin iframe is ignored,
130
+ // so the host (client.js) lays a transparent drag layer over this top bar. This
131
+ // page only reports where the bar and its clickable controls are — geometry,
132
+ // never business data — and only when the plugin marked the frame and the
133
+ // parent is the DSH desktop window. Without the marker nothing here runs.
134
+ (function reportDragRegion() {
135
+ if (new URLSearchParams(location.search).get('host') !== 'dsh-desktop' || window.parent === window) return;
136
+ const HOST = 'dsh-app://app';
137
+ const bar = $('header.bar');
138
+ const rect = node => { const r = node.getBoundingClientRect(); return [r.left, r.top, r.width, r.height].map(v => Math.round(v * 10) / 10); };
139
+ let pending = 0;
140
+ const send = () => {
141
+ pending = 0;
142
+ const holes = [...bar.querySelectorAll('button, a[href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])')]
143
+ .filter(node => node.getClientRects().length).slice(0, 32).map(rect);
144
+ window.parent.postMessage({ type: 'theater-board:drag-region', version: 1, bar: rect(bar), holes }, HOST);
145
+ };
146
+ const schedule = () => { if (!pending) pending = requestAnimationFrame(send); };
147
+ new ResizeObserver(schedule).observe(bar);
148
+ window.addEventListener('resize', schedule);
149
+ bar.addEventListener('click', schedule);
150
+ window.addEventListener('pageshow', schedule);
151
+ window.addEventListener('load', schedule);
152
+ schedule();
153
+ })();
@@ -8,6 +8,7 @@
8
8
  <link rel="stylesheet" href="/admin.css" />
9
9
  <link rel="stylesheet" href="/review.css" />
10
10
  <script src="/review.js" defer></script>
11
+ <script src="/org-mapping.js" defer></script>
11
12
  <script src="/admin.js" defer></script>
12
13
  </head>
13
14
  <body>
@@ -98,6 +99,8 @@
98
99
  <div class="generation-action"><button id="generate-button" class="button button-primary" type="button" disabled>生成真实数据看板<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12h15m-6-6 6 6-6 6"/></svg></button><button id="generate-pending-button" class="button button-pending" type="button" disabled>仍有问题,生成待确认版本</button><span id="generation-progress" role="status" aria-live="polite">等待后台就绪</span><a id="latest-output" class="text-link" target="_blank" rel="noopener" hidden>打开最新生成的看板 ↗</a></div>
99
100
  </section>
100
101
 
102
+ <div id="org-mapping-status" class="org-map" role="status" aria-live="polite" hidden></div>
103
+
101
104
  <section id="history" class="section" aria-labelledby="history-title">
102
105
  <div class="section-header"><div class="section-heading"><span class="step-number">05</span><div><h2 id="history-title">生成记录</h2><p>每次生成单独保存,可随时查看或下载已有成品。</p></div></div><span id="history-count" class="section-hint"></span></div>
103
106
  <div id="generation-history" class="history-panel"><div class="empty-state"><strong>还没有生成记录</strong><p>上传资料并通过校验后,点击上方按钮生成真实数据看板。</p></div></div>
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ // Organization-mapping status of one generation record, shared by the update
4
+ // page (admin.js) and the merged page history (board.js). Wording follows
5
+ // 设计预览画布 ⑪ (confirmed 2026-11-26); each page draws it with its own CSS.
6
+ (function () {
7
+ const TITLES = { invoice: '发票', movement: '动销', opening: '开瓶', terminal: '签约', inventory: '库存', banquet: '宴席' };
8
+ const ORDER = ['opening', 'banquet', 'movement', 'invoice', 'terminal', 'inventory'];
9
+ const REASONS = { pending: '待确认:现有映射未覆盖', 'target-missing': '已拒:目标路径在当前数据中不存在', ambiguous: '已拒:有歧义', malformed: '已拒:格式不符' };
10
+ const n = value => Number(value || 0).toLocaleString('zh-CN');
11
+ const pathText = path => !Array.isArray(path) ? '(格式不符,无法显示)' : (path.slice(0, 3).some(Boolean) ? path : path.slice(3)).map(part => part || '(空)').join(' / ');
12
+
13
+ function appliedParts(modules) {
14
+ const parts = [];
15
+ for (const id of ORDER) {
16
+ const m = modules[id];
17
+ if (!m || !m.appliedPaths) continue;
18
+ const aliasOnly = m.aliasPaths === m.appliedPaths;
19
+ parts.push(`${TITLES[id] || id}${aliasOnly ? '别名' : ''} ${n(m.appliedPaths)} 条${parts.length || aliasOnly ? '' : '路径'} / ${n(m.appliedRows)} 行`);
20
+ }
21
+ return parts;
22
+ }
23
+
24
+ /** → { kind, chip, line, items } or kind 'none' when nothing is recorded. */
25
+ function view(job) {
26
+ const summary = job && job.organizationMapping;
27
+ if (!summary || typeof summary !== 'object') {
28
+ const legacy = job && job.legacyOrganizationMappingStatus;
29
+ const chip = legacy === 'stale' ? '未记录 · 旧规则停用' : legacy === 'confirmed' ? '未记录 · 旧规则已应用' : '未记录';
30
+ return { kind: 'none', chip, line: '', items: [] };
31
+ }
32
+ const modules = summary.modules || {};
33
+ const total = key => Object.values(modules).reduce((sum, m) => sum + (Number(m[key]) || 0), 0);
34
+ const rejected = total('rejectedCount'), pendingPaths = total('pendingPathCount'), pendingRows = total('pendingRows');
35
+ const items = (summary.items || []).map(item => ({ module: TITLES[item.moduleId] || item.moduleId, path: pathText(item.path), rows: n(item.rows), reason: REASONS[item.reason] || item.reason, rejected: item.reason !== 'pending' }));
36
+ const more = Math.max(0, (summary.itemCount || items.length) - items.length);
37
+ const applied = appliedParts(modules);
38
+ if (summary.status === 'invalid') return { kind: 'invalid', chip: '无效', line: '映射合同格式不受支持,本次一条映射都没有应用;开瓶、宴席按原路径显示。', items, more };
39
+ if (summary.status === 'partial') {
40
+ const issue = `${n(rejected)} 条被拒 · ${n(pendingPaths)} 个待确认路径(${n(pendingRows)} 行)`;
41
+ const chip = `部分应用 · ${pendingPaths ? `${n(pendingPaths)} 待确认` : `${n(rejected)} 被拒`}`;
42
+ return { kind: 'partial', chip, line: [...applied.map(part => `${part}已应用`), issue].join(' · '), issue, items, more };
43
+ }
44
+ if (summary.status === 'applied') return { kind: 'applied', chip: '已应用', line: applied.join(' · ') || '没有需要映射的路径', items: [], more: 0 };
45
+ return { kind: 'none', chip: '未配置', line: '没有组织映射合同。', items: [], more: 0 };
46
+ }
47
+
48
+ window.OrgMapping = { view, note: '这些行保留原路径单独显示(看板下拉中带“(上级未提供)”),记录数和总值不变。要补上级,需要先列候选映射、由你确认后写入;系统不会自动推定。' };
49
+ })();
@@ -2,6 +2,7 @@ import { readFile, writeFile, readdir, realpath } from 'node:fs/promises';
2
2
  import { resolve, relative, sep } from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { buildSourcePayload } from './source-payload.mjs';
5
+ import { summarizeOrganizationMapping } from './organization-mapping.mjs';
5
6
  import { moduleDefinitions } from '../modules.mjs';
6
7
 
7
8
  const sha = value => createHash('sha256').update(value).digest('hex');
@@ -131,5 +132,6 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
131
132
  processors: Object.fromEntries(ids.map(id => [id, { version: payload.processingVersion, state: payload.modules[id].state }])),
132
133
  moduleSummaries: Object.fromEntries(ids.map(id => [id, { state: payload.modules[id].state, records: payload.modules[id].records.length, metrics: payload.modules[id].metrics, warnings: payload.modules[id].warnings || [], unavailable: payload.modules[id].unavailable || [] }])),
133
134
  pendingDecisions: payload.pendingDecisions,
135
+ organizationMapping: summarizeOrganizationMapping(report.organizationMapping),
134
136
  };
135
137
  }
@@ -4,72 +4,135 @@ const validPath = path => Array.isArray(path) && path.length === 6 && path.every
4
4
  const fullPath = path => validPath(path) && path.every(Boolean);
5
5
  const key = path => JSON.stringify(path);
6
6
  const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
7
- const shaMatches = (payload, moduleId, sha) => typeof sha === 'string' && /^[a-f0-9]{64}$/i.test(sha) && payload.sources[moduleId]?.sha256 === sha.toLowerCase() && payload.modules[moduleId]?.state !== 'unavailable';
7
+ const SHA = /^[a-f0-9]{64}$/i;
8
+ const shaMatches = (payload, moduleId, sha) => typeof sha === 'string' && SHA.test(sha) && payload.sources[moduleId]?.sha256 === sha.toLowerCase() && payload.modules[moduleId]?.state !== 'unavailable';
9
+ // v10 业务确认「组织映射生效条件修订(2026-11-26)」: target paths are verified
10
+ // against the current reference boards; their SHAs are recorded, not gates.
11
+ export const REFERENCE_MODULES = ['invoice', 'movement', 'terminal', 'inventory'];
12
+ const KINDS = ['parent-completion', 'confirmed-alias'];
13
+ const LIST_LIMIT = 500;
14
+ // The shape parent completion addresses: upper three levels missing, lower three present.
15
+ const missingParents = path => validPath(path) && path.slice(0, 3).every(value => !value) && path.slice(3).every(Boolean);
16
+ const shaOrNull = sha => typeof sha === 'string' && SHA.test(sha) ? sha.toLowerCase() : null;
8
17
 
9
- /** Apply only enumerated, source-bound mappings. No suffix rewriting or fuzzy
10
- * organization matching is performed here. All original paths stay available
11
- * internally so a changed grouping can be traced back to the uploaded source.
18
+ function reviewedAgainst(decision) {
19
+ // version 2 stores the reviewed versions explicitly; version 1 kept the same
20
+ // facts in referenceSources / sources.*.sourceSha256 (formerly gates).
21
+ const recorded = decision.version === 2 ? decision.reviewedAgainst : null;
22
+ const references = isObject(recorded?.references) ? recorded.references : isObject(decision.referenceSources) ? decision.referenceSources : {};
23
+ const sources = isObject(recorded?.sources) ? recorded.sources : Object.fromEntries(Object.entries(decision.sources).map(([id, source]) => [id, source?.sourceSha256]));
24
+ const clean = values => Object.fromEntries(Object.entries(values).filter(([id]) => MODULES.includes(id)).map(([id, sha]) => [id, shaOrNull(sha)]));
25
+ return { references: clean(references), sources: clean(sources) };
26
+ }
27
+
28
+ /** Apply reviewed, exact from → to organization paths one by one. A mapping
29
+ * applies only when its from path occurs in the mapped board, its full target
30
+ * path occurs in the current reference boards (invoice, movement, terminal,
31
+ * inventory), parent completion is a unique fill of the missing upper levels,
32
+ * and no other target is listed for the same from. Anything else is rejected
33
+ * on its own and reported; the rest still apply. No suffix rewriting or fuzzy
34
+ * matching. Original paths stay on every row for traceability.
12
35
  */
13
36
  export function applyOrganizationMapping(payload, decision) {
14
- const report = { version: 1, status: 'not-configured', appliedSources: {}, referenceSourceMatches: {}, modules: {}, errors: [] };
15
- const observedTargets = new Set();
16
- for (const id of MODULES) for (const row of payload.modules[id].records) {
17
- row.originalOrgPath ??= [...row.orgPath];
18
- if (fullPath(row.orgPath)) observedTargets.add(key(row.orgPath));
19
- }
20
- if (!decision) return report;
21
- if (decision.version !== 1 || !isObject(decision.sources) || !isObject(decision.referenceSources)) {
22
- report.status = 'invalid'; report.errors.push('组织映射合同格式不受支持。'); return report;
37
+ const report = { version: 2, rules: 'path-verified', status: 'not-configured', contractVersion: null, reviewedAgainst: { references: {}, sources: {} }, actualSources: { references: {}, sources: {} }, appliedSources: {}, modules: {}, errors: [] };
38
+ const referencePaths = new Set();
39
+ for (const id of MODULES) for (const row of payload.modules[id]?.records || []) row.originalOrgPath ??= [...row.orgPath];
40
+ for (const id of REFERENCE_MODULES) {
41
+ if (payload.modules[id]?.state === 'unavailable') continue;
42
+ if (payload.sources[id]?.sha256) report.actualSources.references[id] = payload.sources[id].sha256;
43
+ for (const row of payload.modules[id]?.records || []) if (fullPath(row.originalOrgPath)) referencePaths.add(key(row.originalOrgPath));
23
44
  }
24
- const references = Object.entries(decision.referenceSources);
25
- report.referenceSourceMatches = Object.fromEntries(references.map(([id, sha]) => [id, shaMatches(payload, id, sha)]));
26
- if (!references.length || references.some(([id, sha]) => !MODULES.includes(id) || !shaMatches(payload, id, sha))) {
27
- report.status = 'stale'; report.errors.push('组织映射参考来源 SHA 已变化,未应用旧映射。'); return report;
45
+ const pendingFor = (id, applied) => {
46
+ const counts = new Map();
47
+ for (const row of payload.modules[id]?.records || []) { const from = key(row.originalOrgPath); if (!applied.has(from) && missingParents(row.originalOrgPath)) counts.set(from, (counts.get(from) || 0) + 1); }
48
+ const all = [...counts].map(([path, rows]) => ({ path: JSON.parse(path), rows })).sort((a, b) => b.rows - a.rows);
49
+ return { pendingPathCount: all.length, pendingRows: all.reduce((sum, item) => sum + item.rows, 0), pendingPaths: all.slice(0, LIST_LIMIT) };
50
+ };
51
+ const finish = () => {
52
+ // Paths still missing their parents are never silent, configured or not.
53
+ for (const id of MODULES) if (!report.modules[id]) { const pending = pendingFor(id, new Set()); if (pending.pendingPathCount) report.modules[id] = { configured: false, ...pending, rejected: [], rejectedCount: 0, status: 'partial' }; }
54
+ if (report.status !== 'invalid' && Object.values(report.modules).some(detail => detail.rejectedCount || detail.pendingPathCount)) report.status = 'partial';
55
+ return report;
56
+ };
57
+ if (!decision) return finish();
58
+ if (!isObject(decision) || ![1, 2].includes(decision.version) || !isObject(decision.sources)) {
59
+ report.status = 'invalid'; report.errors.push('组织映射合同格式不受支持。'); return finish();
28
60
  }
29
- report.status = 'confirmed';
61
+ report.contractVersion = decision.version;
62
+ report.reviewedAgainst = reviewedAgainst(decision);
63
+ report.status = 'applied';
64
+ const referenceList = [...referencePaths].map(path => JSON.parse(path));
30
65
  for (const [id, source] of Object.entries(decision.sources)) {
31
- if (!MODULES.includes(id)) { report.status = 'partial'; report.errors.push('组织映射含未知板块,已忽略。'); continue; }
32
- const detail = { sourceShaMatches: isObject(source) && shaMatches(payload, id, source.sourceSha256), appliedRows: 0, appliedPaths: 0, parentCompletionRows: 0, aliasRows: 0, unmatchedIncompletePaths: [], ambiguousPaths: [], rejectedMappings: 0, status: 'confirmed' };
66
+ if (!MODULES.includes(id)) { report.errors.push(`组织映射含未知板块 ${String(id).slice(0, 40)},已忽略。`); continue; }
67
+ if (payload.sources[id]?.sha256) report.actualSources.sources[id] = payload.sources[id].sha256;
68
+ const detail = { configured: true, mappings: 0, appliedPaths: 0, appliedRows: 0, parentCompletionPaths: 0, parentCompletionRows: 0, aliasPaths: 0, aliasRows: 0, notInSourceMappings: 0, rejected: [], rejectedCount: 0, status: 'applied' };
33
69
  report.modules[id] = detail;
34
- if (!MODULES.includes(id) || !isObject(source) || !shaMatches(payload, id, source.sourceSha256) || !Array.isArray(source.mappings)) {
35
- detail.status = 'stale'; report.status = 'partial'; continue;
70
+ const records = payload.modules[id]?.records || [];
71
+ const present = new Map(); for (const row of records) { const from = key(row.originalOrgPath); present.set(from, (present.get(from) || 0) + 1); }
72
+ const rejectedFroms = new Set();
73
+ const reject = (mapping, reason) => {
74
+ const from = validPath(mapping?.from) ? mapping.from : null;
75
+ if (from) rejectedFroms.add(key(from));
76
+ detail.rejectedCount++;
77
+ if (detail.rejected.length < LIST_LIMIT) detail.rejected.push({ from, to: validPath(mapping?.to) ? mapping.to : null, kind: KINDS.includes(mapping?.kind) ? mapping.kind : null, reason, rows: from ? present.get(key(from)) || 0 : 0 });
78
+ };
79
+ const mappings = Array.isArray(source?.mappings) ? source.mappings : null;
80
+ if (!mappings) { reject(null, 'malformed'); }
81
+ // Group by from first: one from with two different targets rejects all of them (d).
82
+ const byFrom = new Map();
83
+ for (const mapping of mappings || []) {
84
+ detail.mappings++;
85
+ if (!validPath(mapping?.from) || !fullPath(mapping?.to) || !KINDS.includes(mapping.kind)
86
+ || (mapping.kind === 'parent-completion' && (mapping.from.slice(3).some((value, i) => value !== mapping.to[i + 3]) || mapping.from.slice(0, 3).some((value, i) => value && value !== mapping.to[i])))) { reject(mapping, 'malformed'); continue; }
87
+ const from = key(mapping.from), group = byFrom.get(from) ?? new Map();
88
+ group.set(key(mapping.to) + mapping.kind, mapping); byFrom.set(from, group);
36
89
  }
37
- const candidates = new Map(), invalidKeys = new Set();
38
- for (const mapping of source.mappings) {
39
- const from = validPath(mapping?.from) ? key(mapping.from) : null;
40
- if (from === null || !fullPath(mapping.to) || !['parent-completion', 'confirmed-alias'].includes(mapping.kind) || !observedTargets.has(key(mapping.to))) {
41
- detail.rejectedMappings++; if (from !== null) invalidKeys.add(from); continue;
90
+ const accepted = new Map();
91
+ for (const [from, group] of byFrom) {
92
+ const list = [...group.values()];
93
+ if (new Set(list.map(mapping => key(mapping.to))).size !== 1 || list.length !== 1) { for (const mapping of list) reject(mapping, 'ambiguous'); continue; }
94
+ const [mapping] = list;
95
+ if (!present.has(from)) { detail.notInSourceMappings++; continue; } // (a) nothing to apply in this version
96
+ if (!referencePaths.has(key(mapping.to))) { reject(mapping, 'target-missing'); continue; } // (b)
97
+ if (mapping.kind === 'parent-completion') { // (c) unique among current reference paths
98
+ let matches = 0;
99
+ for (const candidate of referenceList) if (mapping.from.every((value, index) => !value || value === candidate[index])) matches++;
100
+ if (matches !== 1) { reject(mapping, 'ambiguous'); continue; }
42
101
  }
43
- // Parent completion may fill only missing parents; explicit aliases may
44
- // change names, but only through the exact reviewed from/to pair.
45
- if (mapping.kind === 'parent-completion' && (mapping.from.slice(3).some((value, i) => value !== mapping.to[i + 3]) || mapping.from.slice(0, 3).some((value, i) => value && value !== mapping.to[i]))) {
46
- detail.rejectedMappings++; invalidKeys.add(from); continue;
47
- }
48
- if (mapping.kind === 'parent-completion') {
49
- const matches = [...observedTargets].map(path => JSON.parse(path)).filter(path => mapping.from.every((value, index) => !value || value === path[index]));
50
- if (matches.length !== 1) { detail.rejectedMappings++; invalidKeys.add(from); detail.ambiguousPaths.push(mapping.from); continue; }
51
- }
52
- const targets = candidates.get(from) ?? new Map();
53
- targets.set(key(mapping.to), mapping); candidates.set(from, targets);
102
+ accepted.set(from, mapping);
54
103
  }
55
- for (const [from, targets] of candidates) if (targets.size !== 1) { invalidKeys.add(from); detail.ambiguousPaths.push(JSON.parse(from)); }
56
- detail.ambiguousPaths = [...new Map(detail.ambiguousPaths.map(path => [key(path), path])).values()];
57
- const applied = new Set(), incomplete = new Map();
58
- for (const row of payload.modules[id].records) {
59
- const from = key(row.originalOrgPath), targets = candidates.get(from);
60
- const mapping = !invalidKeys.has(from) && targets?.size === 1 ? [...targets.values()][0] : null;
61
- if (mapping) {
62
- row.orgPath = [...mapping.to]; row.org = Object.fromEntries(ORG_FIELDS.map((field, index) => [field, row.orgPath[index]])); row.orgKey = key(row.orgPath);
63
- row.organizationMapping = { version: 1, kind: mapping.kind, status: 'applied' };
64
- detail.appliedRows++; applied.add(from);
65
- if (mapping.kind === 'parent-completion') detail.parentCompletionRows++; else detail.aliasRows++;
66
- } else if (!fullPath(row.orgPath)) incomplete.set(from, row.orgPath);
104
+ const appliedPaths = new Map();
105
+ for (const row of records) {
106
+ const from = key(row.originalOrgPath), mapping = accepted.get(from);
107
+ if (!mapping) continue;
108
+ row.orgPath = [...mapping.to]; row.org = Object.fromEntries(ORG_FIELDS.map((field, index) => [field, row.orgPath[index]])); row.orgKey = key(row.orgPath);
109
+ row.organizationMapping = { version: 2, kind: mapping.kind, status: 'applied' };
110
+ detail.appliedRows++; appliedPaths.set(from, mapping.kind);
111
+ if (mapping.kind === 'parent-completion') detail.parentCompletionRows++; else detail.aliasRows++;
67
112
  }
68
- detail.appliedPaths = applied.size; detail.unmatchedIncompletePaths = [...incomplete.values()];
69
- if (detail.rejectedMappings || detail.ambiguousPaths.length) { detail.status = 'partial'; report.status = 'partial'; }
70
- report.appliedSources[id] = source.sourceSha256.toLowerCase();
113
+ detail.appliedPaths = appliedPaths.size;
114
+ detail.parentCompletionPaths = [...appliedPaths.values()].filter(kind => kind === 'parent-completion').length;
115
+ detail.aliasPaths = detail.appliedPaths - detail.parentCompletionPaths;
116
+ // Rows of a rejected mapping are listed once, under the rejection.
117
+ Object.assign(detail, pendingFor(id, new Set([...appliedPaths.keys(), ...rejectedFroms])));
118
+ if (detail.rejectedCount || detail.pendingPathCount) detail.status = 'partial';
119
+ if (detail.appliedRows && payload.sources[id]?.sha256) report.appliedSources[id] = payload.sources[id].sha256;
120
+ }
121
+ return finish();
122
+ }
123
+
124
+ const SUMMARY_ITEMS = 100;
125
+ /** Compact copy of the mapping report for the generation record (state.json):
126
+ * counts per board plus the first rejected / pending paths for the 查看 list. */
127
+ export function summarizeOrganizationMapping(report) {
128
+ if (!isObject(report)) return null;
129
+ const modules = {}, items = [];
130
+ for (const [id, detail] of Object.entries(report.modules || {})) {
131
+ modules[id] = Object.fromEntries(['appliedPaths', 'appliedRows', 'parentCompletionPaths', 'parentCompletionRows', 'aliasPaths', 'aliasRows', 'rejectedCount', 'pendingPathCount', 'pendingRows', 'notInSourceMappings'].map(name => [name, Number.isSafeInteger(detail[name]) ? detail[name] : 0]));
132
+ for (const item of detail.rejected || []) items.push({ moduleId: id, path: item.from, rows: item.rows || 0, reason: item.reason });
133
+ for (const item of detail.pendingPaths || []) items.push({ moduleId: id, path: item.path, rows: item.rows, reason: 'pending' });
71
134
  }
72
- return report;
135
+ return { version: 2, status: report.status, contractVersion: report.contractVersion ?? null, errors: (report.errors || []).slice(0, 5), modules, items: items.slice(0, SUMMARY_ITEMS), itemCount: items.length };
73
136
  }
74
137
 
75
138
  const RULES = {
@@ -85,7 +148,8 @@ export function buildDecisionContract(payload, decisions, mappingReport) {
85
148
  version: 1, decisionId: typeof decisions?.decisionId === 'string' ? decisions.decisionId : null,
86
149
  confirmedAt: typeof decisions?.confirmedAt === 'string' ? decisions.confirmedAt : null,
87
150
  timeZone: typeof decisions?.timeZone === 'string' ? decisions.timeZone : null,
88
- organizationMapping: { status: mappingReport.status === 'confirmed' ? 'confirmed' : 'pending', version: 1, appliedSources: mappingReport.appliedSources },
151
+ // version 2: path-verified rules; status is the mapping report's own (applied / partial / invalid / not-configured).
152
+ organizationMapping: { status: ['applied', 'partial', 'invalid', 'not-configured'].includes(mappingReport.status) ? mappingReport.status : 'invalid', version: 2, appliedSources: mappingReport.appliedSources || {} },
89
153
  agreementFulfillment: { status: 'pending' }, banquetReward: { status: 'pending' }, inventoryValuationBasis: { status: 'pending' },
90
154
  };
91
155
  for (const [name, rule] of Object.entries(RULES)) {