/* ============================================================ 前后台共用层(唯一来源) ------------------------------------------------------------ 硬规则:工作台(workbench.html) 与后台(admin.html) 的 4 个标签**功能必须完全一致**;而数据流与数据库各自独立(session.db / history.db), 差异只允许体现在「API 地址 + 库名」,不允许体现在「渲染逻辑 / 列 / 口径」。 因此下列东西**只允许在这里写一份**,两侧都引用: ① 基础工具 esc / num / ell / fmtAttr ② 4 个标签的定义与顺序(TABS) ③ 列定义 COLS(bill / lme) ④ 清单分组行、组标题行、定额子行的 HTML ⑤ 工料机行的 HTML ⑥ 原数据标签(目录树 + 四张卡)的全部渲染 ⑦ 定额展开交互 / 列宽拖动 ⑧ 地区三级联动(regFill / dictFillRegion:上级限定下级,只列真实存在的组合) ⑨ 下载 / 另存为 + 页面内提示条 ⑩ 数据源字典下拉(dictLoad / dictFillSel / dictQuickAdd) 禁止在任一页面里再写一份 —— 那是当初两侧分叉的根因。 改这个文件 = 两侧同时生效。一致性由 app/tools/check_parity.py 守护。 ⚠️ 2026-10-06 重建说明:本文件曾因磁盘写入事故被整段损坏(无备份), 这份是按「后端字段契约 + common.css 的类名契约 + 老副本 wb5.js」重建的, 功能范围与损坏前一致;细节请以实机复核为准。 ============================================================ */ /* ---------------- ① 基础工具 ---------------- */ function esc(s) { return (s ?? '').toString().replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); } /* 单元格截断(2026-10-06,**前后台统一入口**):table-layout:fixed 下,没有空格的长串 (期次「2026-07~2026-09」、文件名「RATION_202510200934.txt」)**不换行、只会撑破格子**, 必须 nowrap + ellipsis 才收得住。title 带全名,`.ell{cursor:help}` 提示可悬停查看。 ⚠️ 要用块级 span 兜:`td` 上直接写 text-overflow 在部分浏览器不生效。 */ function ell(s, dash) { const v = (s == null || s === '') ? (dash || '') : String(s); return `${esc(v)}`; } // 统一口径:zh-CN 千分位 + 固定小数位(此前工作台用 zh-CN,后台用 undefined locale,显示不一致) function num(v, d) { if (v == null || v === '') return '—'; const n = Number(v); if (isNaN(n)) return esc(v); const k = d ?? 2; return n.toLocaleString('zh-CN', { minimumFractionDigits: k, maximumFractionDigits: k }); } const rm = v => num(v, 2); const r3 = v => num(v, 3); // 项目特征:按序号拆成多行((1) / 1、 / 1. 三种写法;排除 2.5 这类小数被误拆) // ⚠️ 2026-10-02 修复:1、/1. 两种写法必须加 (? `
` + `${t.name}${t.p === 'p3' ? '' : '0'}
`).join(''); } /* 标签点击 → 转交各页自己的切换函数。 工作台:window.onWBTab = tab; 后台:window.onWBTab = loadTab; 这样「标签长什么样、几条、什么顺序」由公共层定,「切到哪个面板」由各页定。 */ function WB_TAB(p) { if (typeof onWBTab === 'function') onWBTab(p); } /* ---------------- ③ 列定义 ---------------- 格式:[列名, 宽度px, 对齐, 标记] 对齐:c=居中 l=左 r=右 标记:'attr'=项目特征(可换行) 'tg'=展开把手 */ const COLS = { // 类似清单 / 组价不一致清单 共用(12 列) // ⚠️ 与后端 BILLROW() 数组下标一一对应: // 0=id 1=编码 2=名称 3=项目特征 4=单位 5=工程量 6=单价 7=合价 8=序号 9=单位工程名称 bill: [['', 30, 'c', 'tg'], ['序号', 52, 'c'], ['编码', 120, 'c'], ['类别', 52, 'c'], ['单位工程名称', 150, 'l'], ['名称', 210, 'l'], ['项目特征', 260, 'l', 'attr'], ['单位', 56, 'c'], ['工程量', 90, 'r'], ['单价', 100, 'r'], ['合价', 110, 'r'], ['备注', 150, 'l']], // 项目工料机(显示 10 列,2026-10-08 主人定:类型列不再显示,数据下标 9=类型 保持不变) // 标记 'F' = 固定宽列;无标记 = 伸缩列(名称/规格型号/备注),平分容器剩余宽度 // —— 表宽始终贴合容器撑满屏幕,见 flexFit() / flexRedistribute()。 lme: [['序号', 52, 'c', 'F'], ['编码', 120, 'c', 'F'], ['名称', 220, 'l'], ['规格型号', 200, 'l'], ['单位', 56, 'c', 'F'], ['数量', 90, 'r', 'F'], ['除税编制价', 110, 'r', 'F'], ['税率', 70, 'r', 'F'], ['含税编制价', 110, 'r', 'F'], ['备注', 160, 'l']] }; function colsObjs(arr) { return arr.map(c => { const o = { t: c[0], a: c[2], w: c[1] }; if (c[3] === 'attr') o.attr = 1; if (c[2] === 'r') o.num = 1; return o; }); } // 表头 / colgroup:两侧共用。列定义两种写法都支持: // 数组式 [名称,宽,对齐](COLS.*) 对象式 {t,w,a}(后台价格明细列) function headHTML(cols) { // 每个表头右侧挂一条 7px 的拖动手柄(.rs)→ 4 个标签的列宽都能左右自由拖动(主人 2026-10-01) return '' + cols.map(c => { const t = Array.isArray(c) ? c[0] : c.t; const a = Array.isArray(c) ? c[2] : c.a; return `${t}`; }).join('') + ''; } function colgHTML(cols) { return cols.map(c => ``).join(''); } /* ---- 可排序表:前后台唯一实现(2026-10-09 收编,原工作台页内版升入共用层) ---- sortHeadHTML(cols, st, fn):全部居中的表头,点列名排序(fn(列下标)),当前列带 ▲/▼; 点拖动手柄 .rs 上不触发排序(列宽拖动优先)。 列定义第 5 位写 'ns'(no-sort)= 纯展示列:输出普通 th,无排序点击(2026-10-09)。 sortRows(rows, k, dir, numSet):返回排序后的副本(不动原数组顺序)。 数字列(numSet 里的下标)按数值比,文本按中文 locale 比,空值恒排最后(与方向无关); k<0 = 不排序,按原序原样返回。 排序状态 {k,dir} 由各页自己管:换数据/换批次时复位 {k:-1,dir:1}。 */ function sortHeadHTML(cols, st, fn) { return '' + cols.map((c, i) => { const mark = (st.k === i) ? (st.dir > 0 ? ' ▲' : ' ▼') : ''; if (c[4] === 'ns') return `${esc(c[0])}`; // 纯展示列,不参与排序 return `${esc(c[0])}${mark}`; }).join('') + ''; } function sortRows(rows, k, dir, numSet) { const view = (rows || []).slice(); if (k >= 0) { const num = numSet.has(k); view.sort((a, b) => { const x = a[k], y = b[k]; const ex = (x == null || x === ''), ey = (y == null || y === ''); if (ex && ey) return 0; if (ex) return 1; if (ey) return -1; const c = num ? (Number(x) - Number(y)) : String(x).localeCompare(String(y), 'zh'); return c * dir; }); } return view; } /* ---- 组表表头排序(2026-10-10 主人定:类似清单点表头 = 在**展开的组内**排序)---- 只排每组内部的清单行,组的先后不动;未展开的组等展开时按同一排序渲染(grpRowsHTML)。 BILL_SORT.k 记「显示列下标」,经 BILL_SORT_DS 映射到 r[] 数据下标(与 COLS.bill 对齐); ± 把手列 / 类别(恒为清单)/ 备注(恒为空)三列不可排序。 定额子行(tr.sub)跟着父清单行整体搬家,展开状态不丢;重排只动 DOM 顺序,GRP_DATA 不变。 排序状态由各页在换数据时复位 {k:-1,dir:1}(工作台 loadGroups / 后台 loadTab)。 */ let BILL_SORT = { k: -1, dir: 1 }; const BILL_ATTR_IDX = COLS.bill.findIndex(c => c[3] === 'attr'); // 项目特征列(显示下标) const BILL_SORT_DS = { 1: 8, 2: 1, 4: 9, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6, 10: 7 }; const BILL_SORT_NUM = new Set([8, 5, 6, 7]); // 序号/工程量/单价/合价 按数值比 function billHeadHTML() { return '' + COLS.bill.map((c, i) => { const can = BILL_SORT_DS[i] != null; const mark = (can && BILL_SORT.k === i) ? (BILL_SORT.dir > 0 ? ' ▲' : ' ▼') : ''; const click = can ? ' onclick="if(event.target.closest(\'.rs\'))return;billSort(this,' + i + ')"' + ' style="cursor:pointer" title="点击在组内按本列排序"' : ''; return `${esc(c[0])}${mark}`; }).join('') + ''; } function billSort(th, i) { if (BILL_SORT.k === i) BILL_SORT.dir = -BILL_SORT.dir; else { BILL_SORT.k = i; BILL_SORT.dir = 1; } const tb = th.closest('table'); billSortDOM(tb); th.closest('thead').innerHTML = billHeadHTML(); // 重画 ▲/▼(colgroup 不动,列宽保持) } /* 组 key('bg3'/'bx0'/'ag2')→ 数据组。原先内联在 tgGrp 里,组内排序也要用,收编成一份。 */ function _grpByKey(key) { if (!GRP_DATA) return null; const gi = /^([ab])g(\d+)$/.exec(key); if (gi) return (GRP_DATA.d.groups || [])[+gi[2]]; const xi = /^([ab])x(\d+)$/.exec(key); if (xi) return (GRP_DATA.d.extra || [])[+xi[2]]; return null; } function billSortDOM(tb) { if (!tb || BILL_SORT.k < 0) return; const rk = BILL_SORT_DS[BILL_SORT.k]; const tbody = tb && tb.tBodies[0]; if (rk == null || !tbody) return; tbody.querySelectorAll('tr.grp[data-grp],tr.grp2[data-grp]').forEach(hdr => { const g = _grpByKey(hdr.dataset.grp); if (!g) return; const units = []; let cur = null; // 清单行 + 其后跟的定额子行 = 一个搬动单元 let n = hdr.nextElementSibling; while (n && n.dataset.grp === hdr.dataset.grp) { if (n.classList.contains('sub')) { if (cur) cur.subs.push(n); } else { cur = { tr: n, subs: [] }; units.push(cur); } n = n.nextElementSibling; } if (units.length < 2) return; const order = new Map(sortRows(g.rows || [], rk, BILL_SORT.dir, BILL_SORT_NUM) .map((r, i) => [String(r[0]), i])); units.sort((a, b) => (order.has(a.tr.dataset.bid) ? order.get(a.tr.dataset.bid) : 1e9) - (order.has(b.tr.dataset.bid) ? order.get(b.tr.dataset.bid) : 1e9)); let anchor = hdr; units.forEach(u => { anchor.after(u.tr); anchor = u.tr; u.subs.forEach(s => { anchor.after(s); anchor = s; }); }); }); } /* ---- 列宽拖动:委托到 .rs(2026-10-01)---- 拖一列的手柄 → 改 colgroup 里对应 的宽度;table-layout:fixed 下整列跟着变, 不用逐行改宽度。委托在 document 上:4 个标签 + 原数据里新画的表格都能直接拖, 重画表格后不必重新绑定。 2026-10-07 起**全项目统一**「拖列只动被拖列」:带 data-sumw 的表,表宽 = 列宽之和 (sumw() 在每次重建 colgroup 后设置),拖动器同步总宽 —— 其余列一毫米不动。 */ (function () { let cur = null, col = null, cg = null, x0 = 0, w0 = 0; document.addEventListener('mousedown', function (e) { const h = e.target.closest && e.target.closest('.rs'); if (!h) return; // 点在别处:不动 const th = h.parentNode, tb = th.closest && th.closest('table'); if (!tb) return; cg = tb.querySelector('colgroup'); if (!cg) return; const idx = Array.prototype.indexOf.call(th.parentNode.children, th); col = cg.children[idx]; if (!col) return; cur = h; x0 = e.clientX; w0 = parseFloat(col.style.width) || th.offsetWidth || 80; document.body.style.cursor = 'col-resize'; e.preventDefault(); }); document.addEventListener('mousemove', function (e) { if (!cur || !col) return; col.style.width = Math.max(30, Math.round(w0 + (e.clientX - x0))) + 'px'; const tb = col.closest && col.closest('table'); if (tb && tb.dataset.sumw) sumw(tb); // 表宽跟着加差值,其他列不动 }); document.addEventListener('mouseup', function () { if (!cur) return; const tb = col && col.closest('table'); const idx = (col && cg) ? Array.prototype.indexOf.call(cg.children, col) : -1; cur = null; col = null; cg = null; document.body.style.cursor = ''; if (!tb) return; // 固定+伸缩列表(data-flex):拖动=从其它伸缩列等量挪,总宽贴合容器,不做记忆; // 其余表照旧记入 localStorage(2026-10-07) if (tb.dataset.flex === '1') { if (typeof flexRedistribute === 'function') flexRedistribute(tb, idx); } else colwSave(tb); // 补宽列表(attrFillBind)拖完立刻重贴伸缩列:拖宽其他列时余量跟着走,不挤出横向滚动条 if (tb._attrCol != null) attrRefill(tb); }); })(); /* ---- 列宽持久化(2026-10-07,主人批准)---- 此前拖完列宽,切个标签/重画就还原(列定义重建),是高频操作里的真实摩擦。 按**表头文字指纹**为每张表存一份列宽到 localStorage,重建后自动套用。 指纹跨重画稳定:同一套列即使表元素是新建的也得到同一个键; 排序标记 ▲▼ 不参与指纹(同一张表排序前后是同一个键)。 */ function _colk(tb) { const ths = tb.querySelectorAll('thead th'); let s = ''; ths.forEach(t => { s += (t.textContent || '').trim().replace(/[▲▼]\s*$/, '') + '|'; }); let h = 0; for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) & 0x7fffffff; return 'h' + h.toString(36); } function _colwKey(tb) { return 'colw|' + location.pathname + '|' + _colk(tb); } function colwSave(tb) { const cg = tb.querySelector('colgroup'); if (!cg || !cg.children.length) return; const w = Array.prototype.map.call(cg.children, c => parseFloat(c.style.width) || 0); // 补宽列(项目特征):显示宽是动态算的,不入库,只存基础宽 —— 否则列宽记忆会越滚越大 if (tb._attrCol != null && tb._attrBase != null) w[tb._attrCol] = tb._attrBase; if (!w.every(x => x > 0)) return; // 含自动宽列的表不记 try { localStorage.setItem(_colwKey(tb), JSON.stringify(w)); } catch (e) {} } function colwApply(tb, deferred) { if (!tb) return; const doApply = () => { const cg = tb.querySelector('colgroup'); if (!cg || !cg.children.length) return; let saved = null; try { saved = JSON.parse(localStorage.getItem(_colwKey(tb)) || 'null'); } catch (e) {} if (!saved || saved.length !== cg.children.length) return; Array.prototype.forEach.call(cg.children, (c, i) => { if (saved[i]) c.style.width = saved[i] + 'px'; }); if (tb.dataset.sumw) sumw(tb); // 表宽=列宽和的表:套用后总宽重算 if (tb._attrCol != null) attrRefill(tb); // 补宽列:套用记忆(只存基础宽)后重新贴合 }; // 键依赖表头文字,而表头常在 colgroup 之后才填、切换视图时还会短暂留着**上一个 // 视图**的旧表头 —— 所以立即套一次 + 下一帧再套一次(幂等,两种时序都盖住)。 if (deferred) { doApply(); return; } doApply(); requestAnimationFrame(() => colwApply(tb, true)); } function colwClear(tb) { try { localStorage.removeItem(_colwKey(tb)); } catch (e) {} } /* ---- 固定+伸缩列(2026-10-08 主人定:项目工料机全部字段撑满屏幕)---- sumw 是 2026-10-07 定的全项目口径(表宽=列宽和);项目工料机是**例外**: 固定列(标 'F')锁宽,伸缩列(名称/规格型号/备注)平分容器剩余宽度, 表宽始终贴合容器。渲染(flexFit)、拖动(flexRedistribute)、窗口缩放(下方 resize) 三个入口都会重新贴合;伸缩表不做列宽记忆(拖动器的 mouseup 分支已跳过 colwSave)。 */ function flexFit(tb, cols) { if (!tb) return; const cg = tb.querySelector('colgroup'); if (!cg || cg.children.length !== cols.length) return; tb._cols = cols; // 拖动器/重算据此区分固定列与伸缩列 tb.dataset.flex = '1'; // 拖动器改走 flexRedistribute、不做列宽记忆 tb.dataset.flexfit = '1'; // 专属标记:resize 重算只认这个,不碰后台 #tb delete tb.dataset.sumw; // 与「表宽=列宽和」两态互斥(后台 #dtb 三视图共用一张表) if (!tb.parentNode.clientWidth) { // 容器还藏着(面板未切换/抽屉未开):量不出可用宽 const n = +(tb.dataset.fftry || 0); // 有界重试 30 帧(≈半秒);切标签/抽屉处另有兜底重贴 if (n < 30) { tb.dataset.fftry = n + 1; requestAnimationFrame(() => flexFit(tb, cols)); } return; } delete tb.dataset.fftry; const fixedSum = cols.reduce((s, c) => s + (c[3] === 'F' ? c[1] : 0), 0); const flexIdx = cols.map((c, i) => c[3] === 'F' ? -1 : i).filter(i => i >= 0); if (!flexIdx.length) return; const avail = Math.max(360, tb.parentNode.clientWidth - 23); const wsum = flexIdx.reduce((s, i) => s + cols[i][1], 0); const rest = avail - fixedSum; const w = {}; flexIdx.forEach(i => { w[i] = Math.max(90, Math.round(rest * cols[i][1] / wsum)); }); // 精确贴合:min 钳位/取整的差额补到最大伸缩列,不挤出横向滚动条 const diff = avail - fixedSum - flexIdx.reduce((s, i) => s + w[i], 0); if (diff !== 0) { const big = flexIdx.reduce((a, b) => w[a] >= w[b] ? a : b); w[big] += diff; } cols.forEach((c, i) => { cg.children[i].style.width = (c[3] === 'F' ? c[1] : w[i]) + 'px'; }); tb.style.width = '100%'; } /* 拖一列 = 该列保持新宽,其余伸缩列平分剩余空间(固定列锁宽不可拖)。 原先是 admin.html 的页内实现(#tb 用),2026-10-08 收编为公共层唯一实现, 项目工料机(工作台 #t0 / 后台 #dtb)同走这一份。 */ function flexRedistribute(tb, idx) { const cols = tb._cols || [], cg = tb.querySelector('colgroup'); if (!cols.length || !cg || !cols[idx] || cols[idx][3] === 'F') return; // 固定列不可拖 const flexIdx = cols.map((c, i) => c[3] === 'F' ? -1 : i).filter(i => i >= 0); const others = flexIdx.filter(i => i !== idx); const fixedSum = cols.reduce((s, c, i) => s + (c[3] === 'F' ? c[1] : 0), 0); const avail = Math.max(360, tb.parentNode.clientWidth - 6); const cur = Math.max(90, parseFloat(cg.children[idx].style.width) || 90); cg.children[idx].style.width = cur + 'px'; const rest = Math.max(90 * others.length, avail - fixedSum - cur); const each = Math.floor(rest / Math.max(1, others.length)); others.forEach(i => cg.children[i].style.width = each + 'px'); } // 窗口尺寸变化:撑满屏幕的表重新贴合(防抖 200ms;只认 data-flexfit, // 不碰后台 #tb 那套内容定宽伸缩逻辑) let _ffT = null; window.addEventListener('resize', () => { clearTimeout(_ffT); _ffT = setTimeout(() => { document.querySelectorAll('table[data-flexfit="1"]').forEach(tb => { if (tb._cols) flexFit(tb, tb._cols); }); document.querySelectorAll('table[data-attrfill="1"]').forEach(tb => attrRefill(tb)); }, 200); }); /* ---- 项目特征自适应补宽(2026-10-10 主人定:备注右缘没贴到屏幕右边 → 项目特征自动加宽到贴满)---- 适用类似清单/组价不一致清单(data-sumw 表,表宽=列宽和,宽屏右侧留一条空白): 项目特征列做伸缩列,显示宽 = max(基础宽, 容器可用宽 − 其余列宽和),只加不缩、其余列不动, 随后 sumw() 重贴表宽。贴满时逐px回退(cut 0~3),保证不挤出横向滚动条。 ResizeObserver 盯滚动容器:窗口缩放、左树拖宽、组展开/收起(竖滚动条出现/消失)都会重贴; colwApply 套用记忆列宽后也补一次(列宽记忆里项目特征只存基础宽,见 colwSave)。 #dtb 一张表轮画三种视图:补宽前先校验 colgroup 列数没变,换了视图就自动不碰。 */ function attrFillBind(tb, idx, base) { if (!tb) return; const cg = tb.querySelector('colgroup'); if (!cg) return; tb._attrCol = idx; tb._attrBase = base; tb._attrCols = cg.children.length; tb.dataset.attrfill = '1'; // resize 兜底通道按这个标记找表 attrRefill(tb); if (!tb._attrRO && typeof ResizeObserver === 'function') { tb._attrRO = new ResizeObserver(() => attrRefill(tb)); tb._attrRO.observe(tb.parentNode); // 容器宽度变了 = 该重新贴合 } } function attrRefill(tb) { if (!tb || tb._attrCol == null) return; const cg = tb.querySelector('colgroup'); if (!cg || cg.children.length !== tb._attrCols) return; const host = tb.parentNode; if (!host || !host.clientWidth) return; // 面板还藏着:量不准,等 RO 下次触发 let otherSum = 0; Array.prototype.forEach.call(cg.children, (c, i) => { if (i !== tb._attrCol) otherSum += parseFloat(c.style.width) || 0; }); for (let cut = 0; cut <= 3; cut++) { const want = Math.max(tb._attrBase || 60, host.clientWidth - cut - otherSum); cg.children[tb._attrCol].style.width = want + 'px'; sumw(tb); if (tb.offsetWidth <= host.clientWidth) break; // 贴满且没挤出横向滚动条 } } /* 表宽 = 列宽之和(2026-10-07,主人定:全项目凡是有列的表都按此执行)。 每次重建 colgroup 后调一次 sumw(tb):按当前列宽和重设表宽,并打上 data-sumw 标记 (拖动器据此在拖动时同步总宽)。含自动宽列(style.width 不是 px)的表不适用 —— 那种表本来就有弹性列吸收差值,拖列天然只动被拖列。 */ function sumw(tb) { if (!tb) return; const cg = tb.querySelector('colgroup'); if (!cg) return; const cols = Array.prototype.slice.call(cg.children); if (!cols.length || !cols.every(c => /px\s*$/.test((c.style.width || '').trim()))) return; // 与「固定+伸缩」两态互斥:后台 #dtb 一张表轮着画 价格明细/项目工料机/类似清单, // 回到定宽视图时必须摘掉 flex 状态,否则拖列会拿着上一视图的列定义分摊 delete tb.dataset.flex; delete tb.dataset.flexfit; tb._cols = null; tb.dataset.sumw = '1'; tb.style.width = cols.reduce((s, c) => s + (parseFloat(c.style.width) || 0), 0) + 'px'; } /* ---------------- ④ 清单分组渲染 ---------------- 行数组 r = [id, 编码, 名称, 项目特征, 单位, 工程量, 单价, 合价, 序号, 单位工程名称] opts.rowClick:行点击回调名(工作台='pick',后台='' 表示不绑) opts.normApi:展开定额的接口前缀(会话 /api/session/bill/,批次 /api/admin/bill/) */ const CB_LAST = COLS.bill.length - 1, CB_TOTAL = COLS.bill.length - 2; // 组标题 colspan 随列数推导,去魔数 function grpTitle(tag, g) { let t = tag + ' · ' + (g.n != null ? g.n : (g.rows ? g.rows.length : 0)) + ' 条清单'; if (g.pmin != null && g.pmax != null) t += ' · 单价 ' + num(g.pmin) + ' ~ ' + num(g.pmax) + (g.spread != null ? '(差 ' + g.spread + '%)' : ''); return t; } function billTR(r, grp, hide, opts) { opts = opts || (typeof WB_OPTS !== 'undefined' ? WB_OPTS : {}) || {}; const st = hide ? ' style="display:none"' : ''; const clk = opts.rowClick ? ' onclick="' + opts.rowClick + "('bill'," + r[0] + ',this)"' : ''; const pr = (r[6] == null ? '' : r[6]); // data-bid:组内排序按它对回 GRP_DATA 里的数据行(billSortDOM) return '' + '+' + '' + ((r[8] == null || r[8] === '') ? '—' : esc(r[8])) + '' + '' + ell(r[1], '—') + '' + '清单' + '' + ell(r[9], '—') + '' + '' + ell(r[2], '—') + '' + '' + ell(fmtAttr(r[3])) + '' + '' + esc(r[4] || '—') + '' + '' + num(r[5], 3) + '' + '' + num(r[6]) + '' + '' + num(r[7]) + '' + ''; } function grpTR(cls, key, title, sum, open) { return '' + '' + (open ? '−' : '+') + '' + '' + '' + title + '' + '' + num(sum) + '' + ''; } function tgGrp(key, tr) { const tg = document.getElementById('gt_' + key); if (!tg) return; // 懒渲染:该组的行还没进 DOM(组头后面不是自己的行)就先现场建,再走正常收/展 const nxt = tr.nextElementSibling; if (!nxt || nxt.dataset.grp !== key) { const g = _grpByKey(key); if (g) tr.insertAdjacentHTML('afterend', grpRowsHTML(g, key, GRP_DATA.opts)); } const open = tg.dataset.open === '1'; tg.dataset.open = open ? '0' : '1'; tg.textContent = open ? '+' : '−'; tg.classList.toggle('g', !open); // 只收/展**明细行**,组标题行自己留着(它也是 tr[data-grp])。 // 展开着的定额子行同样带 data-grp → 跟着一起收,不会散落在表格里。 tr.parentNode.querySelectorAll('tr[data-grp="' + key + '"]').forEach(r => { if (r !== tr) r.style.display = open ? 'none' : ''; }); } /* 组列表 → HTML。kind: 'similar' | 'inconsistent' d.groups 为后端返回;d.extra 为未命中任何组的「其他」批(仅 similar 有) 组 key 必须带标签前缀:两个标签的 tbody 可能同时留在 DOM 里(只是整个 panel 不显示而已), 不前缀的话 p1 / p2 会出现同 id 的组行,$('gt_…') 只会取到前一个,点第二张表的 ± 就失灵。 */ /* 组表数据留底 + 组行懒渲染(2026-10-08 主人报「后台明细卡」): renderGroups 只画**组头**和当前展开组的行,其余组首次展开时才由 tgGrp 现场建行 —— 万行大表首屏从几千行降到百来行。GRP_DATA 供 tgGrp 取数(每页只有一张组表在显示)。 */ let GRP_DATA = null; function grpRowsHTML(g, key, opts) { let rows = g.rows || []; // 组内排序激活时,懒展开的组也按同一排序出(2026-10-10 主人定) if (BILL_SORT.k >= 0) { const rk = BILL_SORT_DS[BILL_SORT.k]; if (rk != null) rows = sortRows(rows, rk, BILL_SORT.dir, BILL_SORT_NUM); } return rows.map(r => billTR(r, key, false, opts)).join(''); } function renderGroups(d, kind, opts) { opts = opts || (typeof WB_OPTS !== 'undefined' ? WB_OPTS : {}) || {}; const pfx = (kind === 'inconsistent') ? 'a' : 'b'; GRP_DATA = { d: d, kind: kind, opts: opts }; let html = ''; const groups = (d && d.groups) || []; groups.forEach((g, i) => { const key = pfx + 'g' + i, open = (i === 0); // 默认只展开第 1 组(全开会没法看) // 价差 ≥20% 的组标红(两侧同一口径,样式在 common.css 的 .grp.bad) const bad = (g.spread != null && Number(g.spread) >= 20) ? ' bad' : ''; // 过滤显示单组时(主人 10-08:点二级只显示该组),labels 带来树上的原始组号 const lbl = (d.labels && d.labels[i]) || ('第 ' + (i + 1) + ' 组'); html += grpTR('grp' + bad, key, grpTitle(lbl, g), g.tsum, open); if (open) html += grpRowsHTML(g, key, opts); // 懒渲染:未展开的组不建行 }); // 落单组(决策 32:单个「其他」批)跟着组序连续编为第 N+1 组,与左树同号(决策 33 对齐口径) if (kind === 'similar' && d && d.extra && d.extra.length) { html += '以下清单符合筛选条件,但未形成相似组'; d.extra.forEach((g, i) => { const key = pfx + 'x' + i; const bad = (g.spread != null && Number(g.spread) >= 20) ? ' bad' : ''; html += grpTR('grp2' + bad, key, grpTitle('第 ' + (groups.length + i + 1) + ' 组', g), g.tsum, false); }); } return html || '没有数据'; } /* ---- 类似清单左目录树(2026-10-08 主人定:工作台/后台的类似清单都有;2026-10-10 决策 30 改格式)---- 根 = 类似清单(组数含末尾落单组,与节点编号一致);二级 = 关键词组在前("第 seq 组 · 组名(条数)"),系统聚类组随后连续编号; 末尾落单组不再叫「其他」,跟排为第 N+1 组 · 条数(2026-10-11 主人定;按类别分桶已废,决策 30)。 pick(key):key='all'(根,显示全部)或 'bg3'/'bx0'(只显示该组)—— 过滤行为由页面 各自实现(表格 id/取数不同),树只管画节点和**选中底色**(.rn.on,主人 10-08 定)。 */ function grpTreeRender(box, d, pick) { if (!box) return; const groups = (d && d.groups) || [], extra = (d && d.extra) || []; let h = '
−' + '类似清单(' + (groups.length + extra.length) + ' 组)
'; groups.forEach((g, i) => { const n = (g.rows || []).length; // 组号跟主表对齐(2026-10-10 主人定「按现有目录排序」):一律按显示位置连续编第 1~N 组, // 不再用规则 seq —— 那套号与主表错位,还和系统组撞号(第19/20/24组在树里各出现两次)。 // 关键词组名保留(主表组标题没有组名,左树是唯一能看到组名的地方)。 const nm = g.cat ? '第 ' + (i + 1) + ' 组 · ' + esc(g.cat) + '(' + n + ' 条)' : '第 ' + (i + 1) + ' 组 · ' + n + ' 条'; h += '
' + nm + '
'; }); extra.forEach((g, i) => { h += '
' + '第 ' + (groups.length + i + 1) + ' 组 · ' + ((g.rows || []).length) + ' 条
'; }); h += '
'; box.innerHTML = h; const sel = pk => box.querySelectorAll('.rn').forEach(n => n.classList.toggle('on', n.dataset.pk === pk)); const root = box.querySelector('.lv0'), kids = box.querySelector('.rkids'); root.querySelector('.arw').onclick = e => { // ± 只管收展,不触发过滤 e.stopPropagation(); const off = kids.style.display === 'none'; kids.style.display = off ? '' : 'none'; root.querySelector('.arw').textContent = off ? '−' : '+'; }; root.onclick = () => { sel('all'); pick('all'); }; box.querySelectorAll('.rn[data-pk]:not(.lv0)').forEach(n => { n.onclick = () => { sel(n.dataset.pk); pick(n.dataset.pk); }; }); } /* 类似清单目录树的**点选行为**(两侧唯一实现,2026-10-08 收编): 点根=显示全部;点组/类=只显示该组。原先 workbench / admin 各写一份逐字相同的回调, 且交互还在调的阶段 —— 收进公共层,改一处两侧同步。 grpTreeBind(树容器, 清单表 tbody 的 id, /similar 接口返回); opts 不用传 —— renderGroups 自己会取页面全局 WB_OPTS。 */ function grpTreeBind(box, tbId, d) { grpTreeRender(box, d, key => { const tb = document.getElementById(tbId); if (!tb) return; if (key === 'all') { tb.innerHTML = renderGroups(d, 'similar'); return; } const i = +key.slice(2); const g = key.charAt(1) === 'g' ? (d.groups || [])[i] : (d.extra || [])[i]; if (!g) return; const lbl = key.charAt(1) === 'g' ? ('第 ' + (i + 1) + ' 组') : ('第 ' + ((d.groups || []).length + i + 1) + ' 组'); tb.innerHTML = renderGroups({ groups: [g], labels: [lbl] }, 'similar'); }); } /* ---------------- ⑤ 工料机行 ---------------- ⚠️ 与后端 _lme_rows() 的 10 列一一对应(第 11 列「备注」:会话侧 = 采纳备注 r[10],批次侧无 → 空): 0=id 1=编码 2=名称 3=规格型号 4=单位 5=数量 6=除税编制价 7=税率 8=含税编制价 9=类型 10=备注 2026-10-08 主人定:**类型列不显示**(r[9] 照常拿到但不渲染格);备注列显示采纳写入的审核备注 (工作台 /api/session/rows 返回 r[10]=x_remark;后台批次行没有这列,留空 —— 两侧同一份渲染)。 2026-10-09:opts.lmeExtra(r,i) 可选钩子 —— 在「备注」格**前**插一格(工作台的「取消采纳」列; 后台不传 = 不显示)。会话侧行渲染 11 格、批次侧仍 10 格,列序由各页自己的 cols 数组决定。 */ function renderLme(rows, opts) { opts = opts || (typeof WB_OPTS !== 'undefined' ? WB_OPTS : {}) || {}; const click = opts.rowClick ? (id => ' onclick="' + opts.rowClick + "('lme'," + id + ',this)"') : (() => ''); return (rows || []).map((r, i) => '' + '' + (i + 1) + '' + '' + ell(r[1], '—') + '' + '' + ell(r[2], '—') + '' + '' + ell(r[3], '—') + '' + '' + esc(r[4] || '—') + '' + '' + num(r[5], 3) + '' + '' + num(r[6]) + '' + '' + num(r[7], 2) + '' + '' + num(r[8]) + '' + (opts.lmeExtra ? opts.lmeExtra(r, i) : '') + '' + esc(r[10] || '') + '').join(''); } /* ---------------- ⑦ 定额展开交互 ---------------- 清单首列「+」→ 展开其下的定额。两侧同一份实现,只是查的库不同 (工作台 /api/session/bill/… 会话库,后台 /api/admin/bill/… 历史库), 差异**只允许**体现在 WB_OPTS.normApi 这个前缀上。 ⚠️ 子行必须 12 个 td,和 COLS.bill 对齐 —— 早年后台写过 4 列的子行版本, 跟工作台对不齐(也对不上列头),已废弃。 */ function tgNorm(el, billId) { const opts = (typeof WB_OPTS !== 'undefined' ? WB_OPTS : {}) || {}; const base = opts.normApi || '/api/session/bill/'; const tr = el.closest('tr'); // 先清掉这一行已经挂着的所有子行(重复点同一个 + 时不要越堆越多) let nx = tr.nextElementSibling; while (nx && nx.classList.contains('sub')) { const n2 = nx.nextElementSibling; nx.remove(); nx = n2; } if (el.dataset.open === '1') { el.textContent = '+'; el.dataset.open = '0'; el.classList.remove('g'); return; } el.dataset.open = '1'; el.textContent = '−'; el.classList.add('g'); fetch(base + billId + '/norms').then(r => r.json()).then(d => { const frag = document.createElement('tbody'); // 子行带上所属组 key —— 收起整组时,展开着的定额子行也得一起藏起来 const gp = tr.dataset.grp || ''; const rows = (d && d.rows) || []; if (!rows.length) { frag.innerHTML = '' + '(该清单下没有定额)'; } else { // 定额 0=编码 1=名称 2=单位 3=工程量 4=单价 5=合价,其余列按清单的对应位置排空 frag.innerHTML = rows.map(r => '' + '—' + ell(r[0], '—') + '' + '定额' + '—' + '    ' + ell(r[1], '—') + '' + '—' + '' + esc(r[2] || '—') + '' + '' + num(r[3], 3) + '' + '' + num(r[4]) + '' + '' + num(r[5]) + '' + '').join(''); } let n2 = tr.nextElementSibling; while (n2 && n2.classList.contains('sub')) n2 = n2.nextElementSibling; while (frag.firstChild) tr.parentNode.insertBefore(frag.firstChild, n2); }).catch(() => { el.textContent = '+'; el.dataset.open = '0'; el.classList.remove('g'); }); } /* ---------------- ⑥ 原数据标签(目录树 + 四张卡)---------------- 只读还原原文件结构:项目 → 单项工程 → 单位工程 → 清单 → 定额 → 工料机。 **不做任何计算**(金额重算交给原软件),跟「项目工料机」的跨工程合并视图分工。 标签卡按主人定的规则:项目级 4 个 / 单项工程级**不挂** / 单位工程级 4 个。 ⚠️ 渲染集中在这里,两侧只声明「去哪个接口取数」(RawView 的配置), —— 数据流独立(会话库 / 批次库),渲染逻辑共用,改这里 = 两侧同时生效。 */ // 2026-10-08 主人定:隐藏「基本信息」「项目特征信息」两张项目级标签卡(只藏 UI,不动 x_info/x_feat 数据列)。 // 数据照常入库/可取,只是原数据视图不再显示这两张卡。前后台共用本 RawView,改这里=两侧同时隐藏。 const RAW_PT = [['sum', '汇总分析'], ['lme', '工料机汇总']]; const RAW_UT = [['item', '分部分项'], ['prelim', '措施项目'], ['lme', '工料机汇总'], ['cost', '汇总分析']]; /* 原数据「工料机汇总」表里要不要显示「类别」列(1人工 / 2材料 / 3机械)。 0=不显示(主人 2026-10-06 定:数据照取照算,只是不占一列)。 ⚠️ 关掉时必须**真的不输出**这一列的 col/th/td —— 用 display:none 会让它退出列模型, 后面的列整体左移一列错位(曾经就因为这个把「单位」显示到「消耗量」底下)。 */ const RAW_LME_KIND = 0; // 模块级状态:每页只有一个原数据视图(工作台 / 后台各一个),够用。 let RVO = null, RVT = null, RVSEL = { k: 'proj', id: 0 }, RVTAB = 'sum', RVLV = 2; /* 树的「展开」与「选中」必须分开记(2026-10-07 修交互): 此前单项工程节点"被选中才展开",于是 ① 默认全是收起的(主人要的默认打开没有); ② 点开单位工程后,父级单项工程整个收起、刚选中的节点直接消失(看着就是"点了没反应/树乱跳"); ③ 展开过的节点没有任何办法再收起(再点一次还是走选中→重画→仍展开)。 RVOPEN = 展开着的单项工程 id 集合;null = 尚未初始化(drawRawTree 里按"默认全展开"初始化)。 RVROOT = 根节点(项目)是否展开。 */ let RVOPEN = null, RVROOT = true; /* 原数据的平表:cols 里写 0 表示「这一列不输出」(见上 RAW_LME_KIND 的坑)。 head 项可以是字符串,也可以是 [文字, 对齐];cols[i] 是宽度(数字=px,''=自动宽)。 2026-10-07:列全为 px 的表一律**表宽=列宽之和**(data-sumw)—— 全项目「拖列只动 被拖列」的统一口径;含自动宽列的表不标记(弹性列天然吸收差值)。 sort={cur,dir,fn}(可选):各列头可点击排序(fn(原列下标)),当前排序列带 ▲/▼; 点击落在拖动手柄 .rs 上时不触发排序。 */ function rawTbl(cols, head, body, al, sort) { const keep = cols.map((w, i) => i).filter(i => cols[i] !== 0); const cg = keep.map(i => '').join(''); const th = keep.map((i) => { const h = head[i]; const t = Array.isArray(h) ? h[0] : h; const a = Array.isArray(h) ? h[1] : ((al && al[i]) || ''); let click = '', mark = ''; if (sort && sort.fn) { if (sort.cur === i) mark = sort.dir > 0 ? ' ▲' : ' ▼'; click = ' onclick="if(event.target.closest(\'.rs\'))return;' + sort.fn + '(' + i + ')"' + ' style="cursor:pointer" title="点击按本列排序"'; } return '' + t + mark + ''; }).join(''); let attr = ''; if (keep.every(i => typeof cols[i] === 'number')) { attr = ' data-sumw="1" style="width:' + keep.reduce((s, i) => s + cols[i], 0) + 'px"'; } return '' + cg + '' + th + '' + body + ''; } function rawKV(rows, tip) { if (!rows || !rows.length) return '
没有数据
'; return (tip ? '
' + esc(tip) + '
' : '') + '' + '' + rows.map(r => '').join('') + '
字段值
' + esc(r[0]) + '' + esc(r[1] == null || r[1] === '' ? '—' : r[1]) + '
'; } /* 工料机汇总表:后端 _raw_proj(lme) 与 _raw_uw(lme) 的行序一致 0=编码 1=名称 2=规格 3=单位 4=类别 5=消耗量 6=除税编制价 7=含税编制价 RAW_LME_KIND=0 时把「类别」整列拿掉 —— 数据仍然取,只是不显示。 */ /* 工料机汇总表的列排序(2026-10-07 主人要求): 点列名按该列排序、再点反向;空值恒排最后(与方向无关);消耗量/两列价格按数值比, 其余按中文比。排序状态跨重画保留(切单位工程后维持同一排序),换工程/重开明细复位。 */ let RV_LME_SORT = { k: -1, dir: 1 }; let RV_LME_ROWS = null, RV_LME_TIP = ''; const RV_LME_NUM = new Set([5, 6, 7]); // 消耗量 / 除税价 / 含税价 function rawLmeSort(k) { if (RV_LME_SORT.k === k) RV_LME_SORT.dir = -RV_LME_SORT.dir; else { RV_LME_SORT.k = k; RV_LME_SORT.dir = 1; } const b = document.getElementById(RVO.bodyEl); if (b && RV_LME_ROWS) { b.innerHTML = rawLmeTbl(RV_LME_ROWS, RV_LME_TIP); rvCachePut(); } } function rawLmeTbl(rows, tip) { rows = rows || []; RV_LME_ROWS = rows; RV_LME_TIP = tip || ''; const view = sortRows(rows, RV_LME_SORT.k, RV_LME_SORT.dir, RV_LME_NUM); // 共用比较器(2026-10-09 收编) const body = view.map(r => { const kind = RAW_LME_KIND ? '' + esc(r[4] == null ? '—' : ({ 1: '人工', 2: '材料', 3: '机械', 4: '主材', 5: '设备' }[Number(r[4])] || r[4])) + '' : ''; return '' + ell(r[0], '—') + '' + ell(r[1], '—') + '' + '' + ell(r[2], '—') + '' + kind + '' + esc(r[3] || '—') + '' + r3(r[5]) + '' + '' + rm(r[6]) + '' + rm(r[7]) + ''; }).join(''); // 2026-10-08 主人定:名称/规格两列都给弹性宽('')—— fixed 布局下自动列均摊剩余空间, // 两列严格等宽、随容器自适应;其余列宽不变。表头统一居中见 common.css。 const cols = RAW_LME_KIND ? [110, '', '', 60, 52, 90, 100, 100] : [110, '', '', 0, 52, 90, 100, 100]; const head = [['编码', 'c'], ['名称', 'l'], ['规格', 'l'], ['类别', 'c'], ['单位', 'c'], ['消耗量', 'r'], ['除税价', 'r'], ['含税价', 'r']]; return (tip ? '
' + esc(tip) + '
' : '') + rawTbl(cols, head, body || '没有工料机数据', null, { cur: RV_LME_SORT.k, dir: RV_LME_SORT.dir, fn: 'rawLmeSort' }); } /* 标签卡(含右边的「分部 / 清单 / 定额」层级按钮 + 「默认列宽」)。 单项工程级不挂标签卡(st 整个藏起来),直接显示本组汇总。 */ function rawTabs() { const st = document.getElementById(RVO.tabsEl); if (!st) return; if (RVSEL.k === 'sec') { st.style.display = 'none'; st.innerHTML = ''; return; } st.style.display = 'flex'; const T = RVSEL.k === 'proj' ? RAW_PT : RAW_UT; let h = T.map(t => '
' + t[1] + '
').join(''); if (RVSEL.k === 'uw' && (RVTAB === 'item' || RVTAB === 'prelim')) { // 层级按钮:一键把所有节点重置到该档默认(分部=只到分部 / 清单=只到清单 / 定额=全展开); // 「默认列宽」是动作按钮,不做选中态 h += '
' + ['1_分部', '2_清单', '3_定额'].map(x => { const v = Number(x[0]), nm = x.slice(2); return '
' + nm + '
'; }).join('') + '
默认列宽
'; } st.innerHTML = h; } function rawTab(t) { RVTAB = t; rawTabs(); rawDraw(); } function rawLv(v) { RVLV = v; RV_TREE = { root: true, divs: {}, bills: {} }; // 新档:树状态交给 rawTreeHTML 重建 RV_CACHE[_rvCacheKey()] = null; // 该视图换档了,旧缓存作废 delete RV_CACHE[_rvCacheKey()]; rawTabs(); rawDraw(); } function rawRst() { const b = document.getElementById(RVO.bodyEl); if (b) { const t = b.querySelector('table'); if (t) colwClear(t); b.innerHTML = ''; } rawDraw(); // 重画后回默认列宽 } async function rawPick(k, id, el) { RVSEL = { k: k, id: id }; RVTAB = k === 'uw' ? 'item' : 'sum'; RVLV = 2; // 默认「只展开到清单」(主人 2026-10-07 定) // 点名字 = 选中**并**展开自己所在的分支(收起只走 ± 把手,两条线分开) if (RVOPEN === null) RVOPEN = new Set(((RVT && RVT.sections) || []).map(s => s.id)); if (k === 'sec') RVOPEN.add(id); if (k === 'uw') ((RVT && RVT.sections) || []).forEach(s => { if ((s.uws || []).some(u => u.id === id)) RVOPEN.add(s.id); }); const tree = document.getElementById(RVO.treeEl); if (tree) tree.querySelectorAll('.rn').forEach(x => x.classList.remove('on')); if (el) el.classList.add('on'); rawPanelClose(); drawRawTree(); rawTabs(); await rawDraw(); } /* ± 把手:只折叠/展开,不改变右侧选中(否则看个目录就把右边的表切走了) */ function rawFoldSec(ev, id) { ev.stopPropagation(); if (RVOPEN === null) RVOPEN = new Set(((RVT && RVT.sections) || []).map(s => s.id)); if (RVOPEN.has(id)) RVOPEN.delete(id); else RVOPEN.add(id); drawRawTree(); } function rawFoldRoot(ev) { ev.stopPropagation(); RVROOT = !RVROOT; drawRawTree(); } function drawRawTree() { const t = RVT, box = document.getElementById(RVO.treeEl); if (!box || !t) return; const keep = box.scrollTop; // 重画后留住滚动位置(点深层节点不再跳回顶上) const secs = t.sections || []; if (RVOPEN === null) RVOPEN = new Set(secs.map(s => s.id)); // 默认全展开(结构树默认打开) // 2026-10-08 主人定:目录树里单位工程只显示名称,编号不再拼在前面(无名称时退回编号兜底) const uwHTML = u => '
' + '' + esc(u.Name || u.Number || '(未命名)') + '
'; let h = '
' + '' + (RVROOT ? '−' : '+') + '' + '' + esc(t.proj && t.proj.name || '(未命名)') + '
' + ''; box.scrollTop = keep; } /* query 是**拼好的**查询串("uw_id=1&tab=item"),别再整体 encodeURIComponent: 那样会把 & 变成 %26,后端收到的 uw_id 就成了 "1&tab=item" —— 接口不报错, 只是查不到任何分部/清单(界面上是「0 个分部 · 0 条清单」,极难往这里想)。 */ async function rawFetch(path, query) { const base = (typeof RVO.api === 'function') ? RVO.api() : RVO.api; const r = await fetch(base + path + (query ? '?' + query : '')); return r.json(); } const _qid = (k, v) => encodeURIComponent(k) + '=' + encodeURIComponent(v); /* ---- 原数据取数缓存 + 无感加载(2026-10-07 主人要求「加载尽量无感、弹框不要跳动」)---- ① 每个视图(工程/单项/单位工程 × 标签)的数据**内存缓存**:来回切标签、关开明细 原位直出零等待;键里带工程 id,不会串数据;页面刷新即清(数据只在重新解析/重开时变)。 ② 未命中时不**清空**旧内容(那一下跳动最扎眼):旧内容压暗 + 右上角小角标, 数据到了原位替换。配合索引优化,未命中加载本地也只有几十毫秒。 */ let RV_CACHE = {}; let RV_NORM_CACHE = {}; // 子目工料机面板:定额 id → 面板体 HTML(换工程清空) function _rvCacheKey() { const oid = (typeof RVO.getId === 'function') ? RVO.getId() : RVO.getId; return oid + '|' + RVSEL.k + ':' + (RVSEL.id || 0) + '|' + RVTAB; } function rvCachePut() { // DOM 变化(排序/树折叠)后把最新状态写回缓存 const b = document.getElementById(RVO.bodyEl); const k = _rvCacheKey(); if (b && RV_CACHE[k]) RV_CACHE[k] = { html: b.innerHTML, scroll: b.scrollTop }; } async function rawDraw() { const b = document.getElementById(RVO.bodyEl); if (!b) return; const key = _rvCacheKey(); const hit = RV_CACHE[key]; if (hit) { // 命中缓存:原位直出,零等待 b.innerHTML = hit.html; colwApply(b.querySelector('table')); b.scrollTop = hit.scroll || 0; return; } if (b.innerHTML.trim()) b.classList.add('rawloading'); // 压暗旧内容,不清空不跳动 const oid = (typeof RVO.getId === 'function') ? RVO.getId() : RVO.getId; try { let html = ''; if (RVSEL.k === 'proj') { const d = await rawFetch('/proj', _qid(RVO.idParam, oid) + '&tab=' + encodeURIComponent(RVTAB)); if (RVTAB === 'sum') html = rawProj('sum', d.rows); else if (RVTAB === 'lme') html = rawLmeTbl(d.rows, '项目级 · 工料机汇总(读原文件 Project.xml 的项目级汇总;点列名可排序)'); else if (RVTAB === 'info') html = rawKV(Object.entries(d.rows || {}), '项目级 · 基本信息(Project.xml 根节点属性)'); else html = rawKV((d.rows || []).map(f => [f.n, f.v]), '项目级 · 项目特征信息(Project.xml 的 AttrInfo / AddiInfo 条目,最多 60 条)'); } else if (RVSEL.k === 'sec') { html = rawSec(await rawFetch('/sec', 'sec_id=' + encodeURIComponent(RVSEL.id))); } else { const d = await rawFetch('/uw', 'uw_id=' + encodeURIComponent(RVSEL.id) + '&tab=' + encodeURIComponent(RVTAB)); if (RVTAB === 'item' || RVTAB === 'prelim') html = rawTreeHTML(d); else if (RVTAB === 'lme') html = rawLmeTbl(d.rows, '单位工程级 · 工料机汇总(按本单位工程的清单→定额→消耗量归集;点列名可排序)'); else html = rawUw('cost', d.rows); } b.innerHTML = html; colwApply(b.querySelector('table')); if (RVSEL.k === 'uw' && (RVTAB === 'item' || RVTAB === 'prelim')) rawTreeSync(); b.scrollTop = 0; RV_CACHE[key] = { html: b.innerHTML, scroll: 0 }; } catch (e) { b.innerHTML = '
读取失败
'; } finally { b.classList.remove('rawloading'); } } /* ---- 分部分项 / 措施项目 的树形展开状态(2026-10-07 重做)---- 把手 ± 必须始终反映**真实可见性**(子级看得见=−、看不见=+): 此前 ± 是画行时写死的,点层级按钮「分部」后子级行被藏了、把手却还停在 −(主人指出的错)。 模型:RV_TREE = {root, divs:{d{id}:bool}, bills:{b{id}:bool}}; 行的可见 = 它 data-vis 里列出的**祖先容器**全部展开(自己折叠只藏自己的子级,不藏自己)。 层级按钮 = 一键把所有节点重置到该档默认:分部=只到分部 / 清单=只到清单 / 定额=全展开。 默认档 RVLV=2「只展开到清单」(主人 2026-10-07 定)。 */ let RV_TREE = { root: true, divs: {}, bills: {} }; function _rvExp(key) { if (key === 'uw') return RV_TREE.root; if (key === 'loose') return true; // 无分部清单的虚拟容器,恒展开 const c = key.charAt(0); if (c === 'd') return RV_TREE.divs[key] !== false; if (c === 'b') return RV_TREE.bills[key] !== false; return true; } function _rvVisible(vis) { if (!vis) return true; return vis.split('/').every(_rvExp); } /* ± 点击 / 层级按钮之后:按状态重算每行可见性与每个把手文字(不重新取数) */ function rawTreeSync() { const b = document.getElementById(RVO.bodyEl); if (!b) return; b.querySelectorAll('tr[data-vis]').forEach(tr => { tr.style.display = _rvVisible(tr.dataset.vis) ? '' : 'none'; }); b.querySelectorAll('.tgi[data-node]').forEach(el => { el.textContent = _rvExp(el.dataset.node) ? '−' : '+'; }); rvCachePut(); // 折叠状态写回缓存(切标签回来不丢) } function rawTog(key, el) { if (key === 'uw') RV_TREE.root = !RV_TREE.root; else { const m = (key.charAt(0) === 'd') ? RV_TREE.divs : RV_TREE.bills; m[key] = !m[key]; } rawTreeSync(); } function rawTreeHTML(d) { const uw = d.uw || {}, divs = d.tree || [], loose = d.loose || []; const ind = dp => 'padding-left:' + (4 + dp * 14) + 'px'; // 2026-10-08 主人定:①「项目特征」列弹性宽('',尽量宽、吸收容器剩余),其余列收窄到最小所需宽; // ②「类型」列 52→88px,让根目录「单位工程」徽章不再溢出(4 字 ~62px + 内边距); // 两处均不再标 data-sumw,表退回 width:100% 填满弹框/屏幕;表头统一居中见 common.css。 const head = ['', '序号', ['编码', 'c'], ['类型', 'c'], ['名称', 'l'], ['项目特征', 'l'], ['单位', 'c'], ['工程量', 'r'], ['单价', 'r'], ['合价', 'r'], ['备注', 'l']]; // 把手列(第一列):单位工程最左、分部统一 16px、清单统一 32px —— 三档错开、各成一条直线 const TGI_UW = 0, TGI_DIV = 16, TGI_BILL = 32; // 2026-10-08 主人定(修「± 把手外溢」):把手列宽不再写死 40。table-layout:fixed 的列 // 不会按内容撑开,而清单行把手 = 4px 内边距 + 32px 缩进 + 20px 把手盒 = 56px, // 早超出 40px 列宽,溢进「序号」列。列宽从缩进常量推导(左右内边距 8 + 最深缩进 + 把手 20), // 以后调整进/把手尺寸列宽自动跟上,结构上不可能再外溢。 // 2026-10-08 主人定:源文件备注显示在备注栏 —— 列宽 56→220 放得下备注文字(悬停有全文提示), // 「项目特征」仍是伸缩列('')吸收剩余宽度。 const cols = [8 + TGI_BILL + 20, 40, 100, 88, 160, '', 64, 76, 74, 86, 220]; let n = 0, rows = ''; // 展开状态按当前层级档重建(切层级按钮 / 换单位工程都会走到这里) // RVLV=1 只到分部(分部全收) RVLV=2 只到清单(清单全收) RVLV=3 全展开 RV_TREE = { root: true, divs: {}, bills: {} }; const initState = nodes => nodes.forEach(nd => { RV_TREE.divs['d' + nd.id] = (RVLV >= 2); (nd.bills || []).forEach(b => { RV_TREE.bills['b' + b.id] = (RVLV >= 3); }); initState(nd.children || []); }); initState(divs); loose.forEach(b => { RV_TREE.bills['b' + b.id] = (RVLV >= 3); }); const tgi = (key, off) => { const open = _rvExp(key); return '' + (open ? '−' : '+') + ''; }; // 固定根行:单位工程(CSS 的 tr.uwrow —— 最重的一档,代表「这是这个表的根」) rows += '' + tgi('uw', TGI_UW) + '—' // 编码列:单位工程编号已按主人 2026-10-08 要求全软件不显示,根行留「—」占位 + '—单位工程' + '' + ell(uw.Name, '—') + '——' + '' + rm(uw.Total) + ''; const billRow = (b, path, dp) => { n++; const hasNorms = (b.norms || []).length > 0; // data-vis = 祖先容器链(不含自己):自己的 ± 只管自己的定额,不影响本行可见 const vis = 'uw/' + path; rows += '' + (hasNorms ? tgi('b' + b.id, TGI_BILL) : '') // 序号 = 单位工程内行号(2026-10-10 主人定:每个单位工程的清单从 1 起排,不跨工程连号) + '' + n + '' + ell(b.Number, '—') + '' + '清单' + '' + ell(b.Name, '—') + '' + '' + ell(fmtAttr(b.Attr)) + '' + '' + esc(b.Unit || '—') + '' + r3(b.Quantity) + '' + '' + rm(b.Price) + '' + rm(b.Total) + '' // 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏);空则留白,不显示「—」 + '' + ell(b.Remark, '') + ''; (b.norms || []).forEach(x => { // 定额行可点 → 下方「子目工料机」面板(x[0] = 定额 id);可见性含父清单 rows += '' + '—' + ell(x[1], '—') + '' + '定额' + '' + ell(x[2], '—') + '' + '—' + esc(x[3] || '—') + '' + '' + r3(x[4]) + '' + rm(x[5]) + '' + '' + rm(x[6]) + ''; }); }; const walk = (nodes, parentPath, dp) => { nodes.forEach(nd => { const key = 'd' + nd.id, path = parentPath ? parentPath + '/' + key : key; const has = (nd.children && nd.children.length) || (nd.bills && nd.bills.length); rows += '' + (has ? tgi(key, TGI_DIV) : '') + '—' + ell(nd.Number, '—') + '' + '分部' + '' + ell(nd.Name, '—') + '' + '——' + '' + rm(nd.Total) + ''; (nd.bills || []).forEach(b => billRow(b, path, dp + 1)); walk(nd.children || [], path, dp + 1); }); }; walk(divs, '', 0); loose.forEach(b => billRow(b, 'loose', 0)); const tip = (d.n_div || 0) + ' 个分部 · ' + (d.n_bill || 0) + ' 条清单(原文件全量,未做任何过滤)'; return '
' + esc(tip) + '
' + rawTbl(cols, head, rows, null, 'auto'); } function rawProj(tab, rows) { if (!rows || !rows.length) return '
没有数据
'; const tot = rows.reduce((a, r) => a + (r.Total || 0), 0) || 1; // 2026-10-08 主人定:汇总分析的**结构与排序以左侧目录树为准** —— 单项工程做分组 // 标题行(=树的单项工程层)。后端已按树序排好(单项工程按入库顺序、组内编号 // 自然序、未挂单项工程的排最后),这里按 sec_name 相邻归组即可。 const groups = []; rows.forEach(r => { const key = r.sec_name || '(未挂单项工程)'; const last = groups[groups.length - 1]; if (last && last.key === key) last.rows.push(r); else groups.push({ key: key, rows: [r] }); }); const body = groups.map(g => { const sum = g.rows.reduce((a, r) => a + (r.Total || 0), 0); return '' + esc(g.key) + ' · ' + g.rows.length + ' 个单位工程 · 合计 ' + rm(sum) + '' + g.rows.map(r => '' + ell(r.Name, '—') + '' + '' + rm(r.DivisionalAndElementalWorks) + '' + '' + rm(r.Preliminaries) + '' + rm(r.Tax) + '' + '' + rm(r.Total) + '' + '' + ((r.Total || 0) / tot * 100).toFixed(3) + '').join(''); }).join(''); return '
项目级 · 汇总分析 —— 与左侧目录同结构同序(合计 ' + rm(tot) + ',与项目总造价的差额=税金/其他项目/安全生产费)
' // 单位工程名称列弹性宽('')填满容器,其余列固定宽(2026-10-08 口径不变) + rawTbl(['', 100, 100, 90, 110, 60], [['单位工程名称', 'l'], ['分部分项', 'r'], ['措施项目', 'r'], ['税金', 'r'], ['总造价', 'r'], ['占总价%', 'r']], body); } function rawSec(d) { const s = d.sec || {}, rows = d.rows || []; if (!rows.length) return '
该单项工程下没有单位工程
'; const tot = rows.reduce((a, r) => a + (r.Total || 0), 0) || 1; return '
单项工程级 —— 按你的要求不挂标签卡,直接显示本组汇总
' // 2026-10-08 主人定:「编号」列整列不输出(与 rawProj 同口径)。 + rawTbl([150, 220, 110, 110, 120, 64], [['单项工程', 'l'], ['单位工程名称', 'l'], ['分部分项', 'r'], ['措施项目', 'r'], ['总造价', 'r'], ['占本组%', 'r']], rows.map(r => '' + ell(s.Name, '—') + '' + '' + ell(r.Name, '—') + '' + rm(r.DivisionalAndElementalWorks) + '' + '' + rm(r.Preliminaries) + '' + rm(r.Total) + '' + '' + ((r.Total || 0) / tot * 100).toFixed(3) + '').join('')); } function rawUw(tab, rows) { const r = rows || {}; const K = [['Total', '总造价'], ['Construction', '建筑安装工程费'], ['DivisionalAndElementalWorks', '分部分项工程费'], ['Preliminaries', '措施项目费'], ['CostForHSE', '绿色施工安全防护费'], ['SundryCosts', '其他项目费'], ['Tax', '税金']]; return rawKV(K.map(x => [x[1], r[x[0]] == null ? '—' : rm(r[x[0]])]), '单位工程级 · 汇总分析(造价构成,来自原文件)'); } /* ---- 点定额行 → 下方「子目工料机」面板 ---- 数据源 opt.normApi(nid):会话库 /api/session/norm/{id}/res,批次库 /api/admin/norm/{id}/res。 面板挂在 body 元素的父节点上(= .rawmain),跟着一起 flex 布局,不占表格的滚动区。 面板与表格之间有一条**上下分隔条**:按住拖 = 调面板高度;正中间的小把手点一下 = 收起/展开整块面板(rawVSplitInit)。 */ function rawNorm(nid, name, tr) { const box = document.getElementById(RVO.bodyEl); if (!box || !box.parentNode) return; box.querySelectorAll('tr.sub.on').forEach(x => x.classList.remove('on')); if (tr) tr.classList.add('on'); let np = document.getElementById('rawnp'); if (!np) { np = document.createElement('div'); np.className = 'rawnorm'; np.id = 'rawnp'; box.parentNode.appendChild(np); rawVSplitInit(np); } // 2026-10-07:定额的工料机取数缓存 —— 同一条定额反复点不再闪「正在读取…」 if (RV_NORM_CACHE[nid]) { np.querySelector('.npname').textContent = name || ''; np.querySelector('.npbody').innerHTML = RV_NORM_CACHE[nid]; bindNormRes(np); return; } np.innerHTML = '
子目工料机' + esc(name || '') + '' + '关闭
' + '
正在读取…
'; const base = (typeof RVO.normApi === 'function') ? RVO.normApi(nid) : (RVO.normApi + nid + '/res'); fetch(base).then(r => r.json()).then(d => { const rows = (d && d.rows) || []; // 列序(后端 _norm_res):0编码 1名称 2规格 3单位 4类别 5含量 6除税价 7含税价 8有下一级 // 2026-10-07 改版:① ± 把手**单独一列放最左**(与全软件的展开把手同款); // ② 「类别」列整个不输出(主人定;同 rawLmeTbl 的 RAW_LME_KIND=0 口径)。 const body = rows.map(x => { const has = x[8] === 1 || x[8] === '1'; return '' + (has ? '+' : '') + '' + '' + ell(x[0], '—') + '' + '' + ell(x[1], '—') + '' + '' + ell(x[2], '—') + '' + '' + esc(x[3] || '—') + '' + '' + r3(x[5]) + '' + '' + rm(x[6]) + '' + '' + rm(x[7]) + ''; }).join(''); np.querySelector('.npbody').innerHTML = rows.length ? rawTbl([34, 130, 220, 150, 56, 90, 100, 100], [['', 'c'], ['编码', 'c'], ['名称', 'l'], ['规格', 'l'], ['单位', 'c'], ['含量', 'r'], ['除税价', 'r'], ['含税价', 'r']], body) : '
这条定额下没有工料机
'; RV_NORM_CACHE[nid] = np.querySelector('.npbody').innerHTML; bindNormRes(np); }).catch(() => { np.querySelector('.npbody').innerHTML = '
读取失败
'; }); } function bindNormRes(np) { np.querySelectorAll('.tgi').forEach(s => { s.style.cursor = 'pointer'; s.onclick = function (e) { e.stopPropagation(); rawRes(x_code(s), s.closest('tr')); }; }); } function x_code(s) { return s.closest('tr').children[1].textContent.trim(); } /* 台班 / 配合比的**下一级组成**(tr.resk):值与 _norm_res 同仰面料序,单独一行「组成」色 + 缩进。 列与子目工料机主表同构(把手/编码/名称/规格/单位/含量/除税/含税),把手列只占位不挂 ±。 */ function rawRes(code, tr) { if (!code) return; if (tr.dataset.open === '1') { let nx = tr.nextElementSibling; while (nx && nx.classList.contains('resk')) { const n2 = nx.nextElementSibling; nx.remove(); nx = n2; } tr.dataset.open = '0'; const m = tr.querySelector('.tgi'); if (m) m.textContent = '+'; return; } const base = (typeof RVO.lmeApi === 'function') ? RVO.lmeApi() : RVO.lmeApi; fetch(base + '&code=' + encodeURIComponent(code)).then(r => r.json()).then(d => { const rows = (d && d.rows) || []; tr.dataset.open = '1'; const m = tr.querySelector('.tgi'); if (m) m.textContent = '−'; const frag = document.createElement('tbody'); frag.innerHTML = rows.length ? rows.map(x => '' + ell(x[0], '—') + '' + '' + ell(x[1], '—') + '' + '' + ell(x[2], '—') + '' + esc(x[3] || '—') + '' + '' + r3(x[5]) + '' + rm(x[6]) + '' + '' + rm(x[7]) + '').join('') : '(没有下一级组成)'; let nx = tr.nextElementSibling; while (nx && nx.classList.contains('resk')) nx = nx.nextElementSibling; while (frag.firstChild) tr.parentNode.insertBefore(frag.firstChild, nx); }); } function rawPanelClose() { const np = document.getElementById('rawnp'); if (np) np.remove(); const sp = document.getElementById('rawvsplit'); if (sp) sp.remove(); const box = document.getElementById(RVO.bodyEl); if (box) box.querySelectorAll('tr.sub.on').forEach(x => x.classList.remove('on')); } /* ---- 子目工料机面板的上下分隔条(2026-10-07,主人要求)---- ① 按住分隔条上下拖 = 调面板高度(120px ~ 容器的 75%); ② 分隔条正中间的小把手,点一下 = 收起/展开整块面板(收起后把手仍在,随时点回来)。 面板被「关闭」(rawPanelClose)时分隔条一并移除,不留死把手。 */ function rawVSplitInit(np) { const main = np.parentNode; // .rawmain const sp = document.createElement('div'); sp.className = 'rawvsplit'; sp.id = 'rawvsplit'; sp.innerHTML = '▼'; main.insertBefore(sp, np); const btn = sp.querySelector('.vsplitbtn'); let drag = null; // {y0, h0} 拖动起点与起始面板高 sp.addEventListener('mousedown', e => { if (e.target === btn) return; // 把手只管收展,不参与拖动 drag = { y0: e.clientY, h0: np.getBoundingClientRect().height }; document.body.classList.add('rawrow-dragging'); e.preventDefault(); }); document.addEventListener('mousemove', e => { if (!drag) return; const max = Math.max(200, main.getBoundingClientRect().height * 0.75); const h = Math.round(Math.min(max, Math.max(120, drag.h0 - (e.clientY - drag.y0)))); np.style.maxHeight = 'none'; // 松开 CSS 的 40% 封顶,改听内联高度 np.style.height = h + 'px'; }); document.addEventListener('mouseup', () => { if (!drag) return; drag = null; document.body.classList.remove('rawrow-dragging'); }); btn.addEventListener('click', () => { const off = np.style.display === 'none'; np.style.display = off ? '' : 'none'; btn.textContent = off ? '▼' : '▲'; btn.title = off ? '收起子目工料机' : '展开子目工料机'; }); } /* ---- 树 / 内容 分隔条(2026-10-07,主人要求)---- ① 按住分隔条左右拖 = 改左树宽度(150 ~ 560px,页面本次会话内记住); ② 分隔条正中间一个小把手,点一下 = 收起/展开整棵树(树收起后把手仍在,随时点回来)。 两页的容器都是 .rawbox(工作台 #pan3 / 后台明细弹框各一个),一份代码两边生效。 */ function rawSplitInit() { document.querySelectorAll('.rawbox').forEach(box => { if (box.dataset.splitReady) return; // 重复调用不重复挂 box.dataset.splitReady = '1'; const tree = box.querySelector('.rawtree'); if (!tree) return; const sp = document.createElement('div'); sp.className = 'rawsplit'; sp.innerHTML = '◀'; box.insertBefore(sp, tree.nextSibling); // 紧跟在树后面(= rawmain 之前) const btn = sp.querySelector('.splitbtn'); let drag = null; // {x0, w0} 拖动起点与起始树宽 sp.addEventListener('mousedown', e => { if (e.target === btn) return; // 把手只管收展,不参与拖动 drag = { x0: e.clientX, w0: tree.getBoundingClientRect().width }; document.body.classList.add('rawcol-dragging'); e.preventDefault(); }); document.addEventListener('mousemove', e => { if (!drag) return; const w = Math.round(drag.w0 + e.clientX - drag.x0); tree.style.width = Math.min(560, Math.max(150, w)) + 'px'; }); document.addEventListener('mouseup', () => { if (!drag) return; drag = null; document.body.classList.remove('rawcol-dragging'); }); btn.addEventListener('click', () => { const closed = box.classList.toggle('treeclosed'); btn.textContent = closed ? '▶' : '◀'; btn.title = closed ? '展开目录树' : '收起目录树'; }); }); } rawSplitInit(); // 两页都在 body 末尾引入本文件,DOM 已就绪 /* 页面侧的入口:只声明接口,不写渲染。 opt = { api, idParam, getId, normApi, lmeApi, treeEl, tabsEl, bodyEl } */ function RawView(opt) { RVO = opt || {}; return { load: async function () { const tree = document.getElementById(RVO.treeEl), tabs = document.getElementById(RVO.tabsEl); const body = document.getElementById(RVO.bodyEl); const oid = (typeof RVO.getId === 'function') ? RVO.getId() : RVO.getId; if (!oid) { if (tree) tree.innerHTML = '
未打开工程
'; if (tabs) tabs.innerHTML = ''; if (body) body.innerHTML = ''; return; } // 目录树也走缓存:关掉明细再开、来回切页签时原位直出(数据只在重新解析/重开工程时变) const tkey = 'tree|' + oid; if (RV_CACHE[tkey]) { RVT = RV_CACHE[tkey]; } else { if (tree) tree.innerHTML = '
正在读取…
'; try { RVT = await rawFetch('/tree', _qid(RVO.idParam, oid)); } catch (e) { if (tree) tree.innerHTML = '
读取失败:服务没连上(软件可能没启动)
'; return; } RV_CACHE[tkey] = RVT; } RVSEL = { k: 'proj', id: 0 }; RVTAB = 'sum'; RVLV = 2; RVOPEN = null; RVROOT = true; // 换工程 / 重开明细:展开状态回到「默认全开」 RV_LME_SORT = { k: -1, dir: 1 }; // 排序状态同步复位 RV_NORM_CACHE = {}; // 换工程:定额面板缓存清空(不同工程定额 id 空间不同) rawPanelClose(); drawRawTree(); rawTabs(); await rawDraw(); } }; } /* ---------------- ⑦.4 弹框自由拖动(2026-10-08 主人定:全部弹框均可移动)---------------- 按住弹框标题栏(.dh)拖动整个弹框;位置记住,关闭再打开保持原位; 标题栏上的按钮(× 等)不参与拖动。防止拖出屏幕:至少留 60px 宽、40px 高可见。 2026-10-08 追加「开框钉位」(主人:弹框加载数据时左上角不能动,闪一下太难受): 弹框显示的那一刻按当帧尺寸居中一次并转固定定位 —— 之后异步加载、内容长高只向下伸展, 顶边不再随 flex 垂直居中每帧重算而上跳。拖过的弹框(dataset.dragged)以手放的 位置为准,钉位与 resize 重居中都永久退出。 */ function dlgPin(dlg){ if (dlg.dataset.dragged) return; const r = dlg.getBoundingClientRect(); if (r.width < 40 || r.height < 40) return; // 不可见/异常尺寸不钉 dlg.style.position = 'fixed'; dlg.style.margin = '0'; dlg.style.left = Math.max(0, Math.round((window.innerWidth - r.width) / 2)) + 'px'; dlg.style.top = Math.max(0, Math.round((window.innerHeight - r.height) / 2)) + 'px'; } function dialogsDraggable(){ document.querySelectorAll('.mask').forEach(mask => { const dlg = mask.querySelector('.dlg'); if (!dlg) return; if (!dlg._dragReady) { dlg._dragReady = true; const dh = dlg.querySelector('.dh'); if (dh) { dh.style.cursor = 'move'; dh.addEventListener('mousedown', e => { if (e.target.closest('a,button,input,select,.close')) return; // 控件不拖 const r = dlg.getBoundingClientRect(); const ox = e.clientX - r.left, oy = e.clientY - r.top; let moved = false; const move = ev => { if (!moved) { moved = true; dlg.dataset.dragged = '1'; } // 真拖动了才锁钉位 let L = ev.clientX - ox, T = ev.clientY - oy; L = Math.max(60 - r.width, Math.min(L, window.innerWidth - 60)); T = Math.max(0, Math.min(T, window.innerHeight - 40)); dlg.style.position = 'fixed'; dlg.style.margin = '0'; dlg.style.left = L + 'px'; dlg.style.top = T + 'px'; }; const up = () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); }; document.addEventListener('mousemove', move); document.addEventListener('mouseup', up); e.preventDefault(); }); } } if (!mask._pinReady) { mask._pinReady = true; let wasOn = mask.classList.contains('on'); // 只在「开框」沿(off→on)触发一次钉位;.on 内部的其他 class 变化不理会。 // 不用 rAF:后台标签页 Chromium 不派发动画帧,钉位会永远不执行; // getBoundingClientRect 自带强制同步排版,观察器回调里当场读、当场钉。 new MutationObserver(() => { const on = mask.classList.contains('on'); if (on && !wasOn) dlgPin(dlg); wasOn = on; }).observe(mask, { attributes: true, attributeFilter: ['class'] }); } }); } dialogsDraggable(); /* 窗口尺寸变化:没拖过的弹框重新居中一次(对齐旧 flex 居中在 resize 时的行为);拖过的不动 */ window.addEventListener('resize', () => { document.querySelectorAll('.mask.on .dlg').forEach(dlg => dlgPin(dlg)); }); /* ---------------- ⑦.5 可搜索下拉(combobox,2026-10-07 主人定)---------------- 把既有 (缺级传 null) * @param rows [[p,c,d], ...] * @param cur [p,c,d] 初值(编辑回填) * @param opt {ph:['省','市','区/县/镇'], onChange: 任何一级变化后的回调} */ function regFill(els, rows, cur, opt) { opt = opt || {}; const ph = opt.ph || ['省', '市', '区/县/镇']; const R = (rows || []).map(r => [(r[0] || '').trim(), (r[1] || '').trim(), (r[2] || '').trim()]) .filter(r => r.join('') !== ''); const V = (i, f) => [...new Set(R.filter(f).map(r => r[i]).filter(Boolean))] .sort((a, b) => a.localeCompare(b, 'zh')); const pv0 = (cur || [])[0] || '', cv0 = (cur || [])[1] || ''; _regOpts(els[0], V(0, () => true), ph[0], pv0); _regOpts(els[1], V(1, r => !pv0 || r[0] === pv0), ph[1], cv0); const pv = (els[0] && els[0].value) || '', cv = (els[1] && els[1].value) || ''; _regOpts(els[2], V(2, r => (!pv || r[0] === pv) && (!cv || r[1] === cv)), ph[2], (cur || [])[2] || ''); // 上级变化 → 重算下级(原下级值若已不属于新集合会被清掉,不会留下无效组合) const sync = from => { const p = (els[0] && els[0].value) || ''; if (from <= 1 && els[1]) _regOpts(els[1], V(1, r => !p || r[0] === p), ph[1], els[1].value); const c = (els[1] && els[1].value) || ''; if (from <= 2 && els[2]) _regOpts(els[2], V(2, r => (!p || r[0] === p) && (!c || r[1] === c)), ph[2], els[2].value); }; const after = () => { if (opt.onChange) opt.onChange(); }; if (els[0]) els[0].onchange = () => { sync(1); after(); }; if (els[1]) els[1].onchange = () => { sync(2); after(); }; if (els[2]) els[2].onchange = () => { after(); }; return { sync: sync, rows: R }; } /* ---------------- ⑨ 数据源字典(2026-10-06)---------------- 后台「设置」面板维护,后台(导入/编辑)与工作台(打开工程)**共用同一份**, 杜绝同一个单位在不同页面写成两个名字。 分工(重要): · 录入类下拉 → 只取字典 dictLoad()(本文件提供) · 过滤类下拉 → 取「字典 ∪ 库里实际值」/api/admin/filters(服务端 _union_distinct) 过滤要能筛到历史数据,所以只增不减;录入才严格收口。 */ let DICT = { regions: [], publishers: [], builders: [] }; async function dictLoad() { try { const d = await (await fetch('/api/dict')).json(); if (d && d.ok) DICT = d; } catch (e) {} return DICT; } /** 某级的地区值(去重排序)。level: province | city | district */ function dictRegions(level) { const s = new Set(); (DICT.regions || []).forEach(r => { if (r[level]) s.add(r[level]); }); return [...s].sort((a, b) => a.localeCompare(b, 'zh')); } /** 单位名列表。cat: publisher | builder */ function dictOrgs(cat) { return (cat === 'publisher' ? DICT.publishers : DICT.builders || []).map(o => o.name); } /** 字典口径的地区三联动(导入 / 编辑 / 打开工程这类**录入**下拉都走这里)。 签名沿用旧 dictFillRegion(els, cur),新增第三参 opt 透传给 regFill。 */ function dictFillRegion(els, cur, opt) { return regFill(els, regRows(DICT.regions), cur, Object.assign({ ph: ['省', '市', '区/县/镇'] }, opt || {})); } /** * 把 元素 * @param opts 字符串数组 * @param cur 当前值;不在 opts 里也会补进选项(编辑老数据时不丢值) * @param cat 'publisher' | 'builder';不传 = 纯下拉,不允许新增 * @param onAdd 值变化 / 新增成功后的回调(newValue) */ function dictFillSel(el, opts, cur, cat, onAdd) { if (!el) return; const list = (opts || []).slice(); if (cur && !list.includes(cur)) list.unshift(cur); // 首个必须是空选项:既当占位提示,也保证「必填校验」在字典为空时不会把「+新增…」当成已选值 el.innerHTML = '' + list.map(v => '').join('') + (cat ? '' : ''); el.value = cur || ''; el.onchange = async () => { if (el.value !== '__add') { if (onAdd) onAdd(el.value); return; } const nm = await dictQuickAdd(cat); if (nm) { await dictLoad(); dictFillSel(el, dictOrgs(cat), nm, cat, onAdd); if (onAdd) onAdd(nm); } else { el.value = cur || ''; if (onAdd) onAdd(el.value); } }; } /** 极小的新增弹窗(动态创建,两个页面共用,不占各页 markup)。返回新名字或 null */ function dictQuickAdd(cat) { const TITLE = { publisher: '新增发布单位', builder: '新增建设单位' }; return new Promise(resolve => { let box = document.getElementById('__dictq'); if (!box) { box = document.createElement('div'); box.id = '__dictq'; box.className = 'mask'; box.innerHTML = '
' + '
×
' + '
' + '
' + '名称' + '
' + '
' + '
' + '' + '' + '
' + '
' + '
'; document.body.appendChild(box); } const inp = document.getElementById('__dqi'), msg = document.getElementById('__dqm'); document.getElementById('__dqt').textContent = TITLE[cat] || '新增'; inp.value = ''; msg.textContent = ''; msg.className = 'tip'; box.classList.add('on'); inp.focus(); let done = false; const close = v => { done = true; box.classList.remove('on'); resolve(v); }; const ok = async () => { const nm = (inp.value || '').trim(); if (!nm) { msg.textContent = '名称不能为空'; return; } try { const r = await (await fetch('/api/dict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cat: cat, act: 'add', name: nm }) })).json(); if (r && r.ok) { close(nm); return; } msg.textContent = (r && r.msg) || '保存失败'; } catch (e) { msg.textContent = '保存失败:' + e; } }; document.getElementById('__dqb1').onclick = () => close(null); document.getElementById('__dqc').onclick = () => close(null); document.getElementById('__dqb2').onclick = ok; inp.onkeydown = e => { if (e.key === 'Enter') ok(); }; box.onclick = e => { if (e.target === box && !done) close(null); }; }); } /* ---------------- ⑩ 下载 / 另存为 + 页面内提示条(2026-10-06)---------------- 替代 alert:不打断操作、说得清去了哪儿。 ⚠️ showSaveFilePicker 必须在**点击手势里的第一个 await** 才能弹出: 先 fetch 再弹框,transient activation 就被耗光了(浏览器会静默忽略,文件直接落地或不落地)。 所以顺序是「先弹框拿句柄 → 再 fetch 内容 → 写句柄」。不支持的时候退回 , 再不行才用 location.href(一定会落到默认下载目录,但至少能下载)。 */ /* ---------------- ⑩ 下载 / 另存为 + 页面内提示条(2026-10-06)---------------- 替代 alert:不打断操作、说得清去了哪儿。 ⚠️ showSaveFilePicker 必须在**点击手势里的第一个 await** 才能弹出: 先 fetch 再弹框,transient activation 就被耗光了(浏览器会静默忽略,文件直接落地或不落地)。 所以顺序是「先弹框拿句柄 → 再 fetch 内容 → 写句柄」。不支持的时候退回 , 再不行才用 location.href(一定会落到默认下载目录,但至少能下载)。 */ /* ---- 上传大小预检(2026-10-07 补回)---- admin.html 三处上传(导入带附件 / 附件原件 / 询价附件)都调用 overMaxMsg(f), 此前这个函数丢失 → onchange 一进来就 ReferenceError,上传**静默失败** (主人报「询价附件上传不成功」的根因;导入主文件走的 pickFile 没调它所以一直正常)。 上限 = 后台「设置 → 上传设置」的 upload_max_mb,进程内缓存(本文件加载即取一次, admin 的 upLoad/upSave 更新设置后同步刷新)。同步返回:''=可以传,否则是错误文案。 */ let _UP_LIMIT = 0; function uploadLimit() { if (_UP_LIMIT) return _UP_LIMIT; fetch('/api/admin/settings').then(r => r.json()).then(d => { if (d && d.ok && Number(d.upload_max_mb) > 0) _UP_LIMIT = Number(d.upload_max_mb); }).catch(() => {}); return 0; } uploadLimit(); // 页面加载即预热缓存(选文件前早就绪) function overMaxMsg(f) { if (!f) return ''; const mb = uploadLimit(); if (!mb || f.size <= mb * 1048576) return ''; // 上限未知时放行,交给服务端把守 return '文件 ' + (f.size / 1048576).toFixed(1) + ' MB,超过上限 ' + mb + ' MB(可在后台「设置 → 上传设置」里调大)'; } /* ---- 文件上传:二进制直传(2026-10-07)---- 后端 /api/admin/upload、/attach、/inq 自 10-06 起都支持 octet-stream (body=文件字节,文件名走 X-File-Name);此前前端仍走 readAsDataURL → base64 塞 JSON,200MB 文件要膨胀成 267MB 字符串再解码。统一入口,调用方一行。 */ async function uploadFile(url, f) { const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'X-File-Name': encodeURIComponent(f.name || 'file') }, body: f // File/Blob 直接作 body,浏览器流式发送 }); return r.json(); } async function saveAs(url, name) { const nm = name || '下载文件'; try { if (window.showSaveFilePicker) { const fh = await window.showSaveFilePicker({ suggestedName: nm }); const r = await fetch(url); const buf = await r.arrayBuffer(); const w = await fh.createWritable(); await w.write(buf); await w.close(); dlMsg('已保存:' + nm, 'ok'); return false; } } catch (e) { if (e && e.name === 'AbortError') { dlMsg('已取消保存', 'warn'); return false; } } try { const a = document.createElement('a'); a.href = url; a.download = nm; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => a.remove(), 0); dlMsg('已开始下载:' + nm, 'ok'); } catch (e) { location.href = url; dlMsg('已开始下载:' + nm, 'ok'); } return false; } /** 询价附件的另存为(自己的链接里 onclick="return dlInq(id,name)") */ function dlInq(id, name) { return saveAs('/api/admin/inq/file/' + id, name || ('询价附件' + id)); } /** 页面内提示条:优先写 #dlmsg(查询栏里那一条),没有它就用右下角浮层 */ function dlMsg(msg, kind) { const el = document.getElementById('dlmsg'); if (el) { el.className = 'dlmsg' + (kind === 'warn' ? ' warn' : kind === 'err' ? ' err' : ''); el.textContent = msg || ''; el.style.opacity = '1'; clearTimeout(el._t); el._t = setTimeout(() => { el.style.opacity = '0'; }, 3000); return; } toast(msg, kind); } function toast(msg, kind) { let box = document.getElementById('toastBox'); if (!box) { box = document.createElement('div'); box.id = 'toastBox'; document.body.appendChild(box); } const d = document.createElement('div'); d.className = 'toast' + (kind === 'warn' ? ' warn' : kind === 'err' ? ' err' : ''); d.textContent = msg || ''; box.appendChild(d); requestAnimationFrame(() => d.classList.add('on')); setTimeout(() => { d.classList.remove('on'); setTimeout(() => d.remove(), 300); }, 3000); } /* ================= 统一设置窗口 + 授权到期预警(2026-10-10 决策 31)================= 两页各挂一行:workbench licMount('.tabright') / admin licMount('.tabs')。 - licDlg() 统一「设置」弹框(本版先放「授权」一节:状态卡/立即刷新/重新激活; 后续新设置项往这里加,不再各自开窗) - licBannerTick 授权剩余 ≤14 天时顶栏出红字 chip,点击开设置弹框(10 分钟一查) 接口三口在门禁层永放行:GET /api/license/status、POST /api/license/refresh、 POST /api/license/activate —— 未激活状态下弹框也能用(但未激活时整页已是授权页)。 样式作用域全部收在 #licMask / .lic-* 下,不碰页面既有 .dlg 样式。 */ let _licPoll = null; function licEnsureStyle() { if (document.getElementById('licStyle')) return; const st = document.createElement('style'); st.id = 'licStyle'; st.textContent = '' + '#licMask .dlg.lic{width:540px;max-width:94vw;background:#fff;border-radius:10px;\n' + ' box-shadow:0 10px 40px rgba(16,35,61,.18)}\n' + '#licMask .dh{display:flex;justify-content:space-between;align-items:center;\n' + ' background:#1f4e79;color:#fff;padding:12px 18px;font-size:15px;font-weight:600;\n' + ' border-radius:10px 10px 0 0;user-select:none}\n' + '#licMask .dh .close{color:#fff;cursor:pointer;font-size:20px;line-height:1;padding:0 4px}\n' + '.lic-bd{padding:16px 18px 18px;font-size:13px;color:#1c2733}\n' + '.lic-st{border:1px solid #e3e8ef;background:#fafbfd;border-radius:8px;\n' + ' padding:10px 14px;line-height:2.05}\n' + '.lic-st b.ok{color:#1c7c44}.lic-st b.bad{color:#b02a2a}\n' + '.lic-btns{display:flex;gap:10px;margin-top:12px}\n' + '.lic-row{margin-top:10px}\n' + '.lic-row label{display:block;color:#51606f;margin-bottom:4px;font-size:12.5px}\n' + '.lic-row input{width:100%;padding:8px 10px;border:1px solid #c8d2dd;border-radius:6px;\n' + ' font-size:13px;box-sizing:border-box;font-family:inherit}\n' + '.lic-tip{margin-top:12px;color:#8a97a5;font-size:12px;line-height:1.7}\n' + '.btn.lic-warn{color:#b02a2a;border-color:#e4b6b6;background:#fdf3f3;font-weight:600}'; document.head.appendChild(st); } function licMount(sel) { const host = document.querySelector(sel); if (!host || document.getElementById('licWarn')) return; licEnsureStyle(); const warn = document.createElement('button'); warn.id = 'licWarn'; warn.className = 'btn lic-warn'; warn.style.display = 'none'; warn.onclick = licDlg; warn.title = '点击查看授权详情'; const btn = document.createElement('button'); btn.className = 'btn'; btn.textContent = '⚙ 设置'; btn.title = '授权状态 / 激活 / 续费提示(后续设置项统一收这里)'; btn.onclick = licDlg; host.appendChild(warn); host.appendChild(btn); licBannerTick(); setInterval(licBannerTick, 10 * 60 * 1000); } function licBannerTick() { const warn = document.getElementById('licWarn'); if (!warn) return; fetch('/api/license/status').then(r => r.json()).then(j => { const d = j.data || {}; let show = false, txt = ''; if (d.enforce && d.can_run) { if (d.days_left != null && d.days_left <= 14) { show = true; txt = d.days_left <= 0 ? '⚠ 授权即将到期,请立即续费' : '⚠ 授权剩 ' + d.days_left + ' 天,请及时续费'; } else if (d.lease_state && d.lease_state !== 'active') { show = true; txt = '⚠ 授权状态异常(' + esc(d.lease_state) + ')'; } } warn.textContent = txt; warn.style.display = show ? '' : 'none'; }).catch(() => {}); } function licDlg() { licEnsureStyle(); let mask = document.getElementById('licMask'); if (!mask) { mask = document.createElement('div'); mask.id = 'licMask'; mask.className = 'mask'; mask.innerHTML = '
' + '
' + '
加载中…
' + '
' + '' + '
' + '' + '
续费由软件提供方在授权平台操作,在线状态下一分钟内自动生效,无需重装;' + '「立即刷新授权」可手动联网续租。激活密钥只保存在本机(Windows 加密存储),不会上传到别处。
' + '
'; document.body.appendChild(mask); mask.addEventListener('click', e => { if (e.target === mask) licClose(); }); } dialogsDraggable(); // 新插入的弹框补挂拖动/钉位(幂等) mask.classList.add('on'); const f = document.getElementById('licForm'); // 重开时表单复位收起(上轮未关的残留) if (f) f.style.display = 'none'; licLoad(); clearInterval(_licPoll); _licPoll = setInterval(licLoad, 15000); } function licClose() { const m = document.getElementById('licMask'); if (m) m.classList.remove('on'); clearInterval(_licPoll); } function licLoad() { fetch('/api/license/status').then(r => r.json()) .then(j => licRender(j.data || {})).catch(() => licRender(null)); } function licRender(d) { const el = document.getElementById('licSt'); if (!el) return; if (!d) { el.innerHTML = '无法读取授权状态(本机服务异常?)'; return; } let h = ''; if (!d.enforce) h += '模式:开发模式(enforce=false,不强制校验)
'; h += '状态:' + (d.can_run ? '已授权,运行中' : '' + esc(d.reason || '不可用') + '') + '
'; if (d.instance_id) h += '实例:' + esc(d.instance_id) + '
'; if (d.product_id != null) h += '产品 ID:' + esc(d.product_id) + '
'; if (d.entitlement_expires_at) { h += '授权到期:' + esc(d.entitlement_expires_at); if (d.days_left != null) h += '(剩 ' + d.days_left + ' 天)'; h += '
'; } if (d.lease_expires_at) h += '租约到期:' + esc(d.lease_expires_at) + '
'; if (d.last_heartbeat_at) { h += '最后心跳:' + esc(d.last_heartbeat_at); if (d.heartbeat_running === false) h += ' (自动心跳未运行,可点「立即刷新授权」恢复)'; h += '
'; } if (!d.keyring_ready) h += '⚠ 信任根未配置(pinned_keys 为空),激活/续租都会失败——请联系软件提供方。
'; if (d.last_error) h += '最近错误:' + esc(d.last_error); el.innerHTML = h; } function licRefresh() { const b = document.getElementById('licRf'); b.disabled = true; fetch('/api/license/refresh', { method: 'POST' }).then(r => r.json()).then(j => { b.disabled = false; const res = (j.data || {}).result || {}; toast(res.ok ? '授权已刷新' : ('刷新失败:' + (res.message || '未知错误')), res.ok ? '' : 'err'); licLoad(); }).catch(() => { b.disabled = false; toast('网络错误:无法连接本机服务', 'err'); }); } function licToggleForm() { const f = document.getElementById('licForm'); f.style.display = f.style.display === 'none' ? '' : 'none'; } function licActivate() { const b = { instance_id: document.getElementById('licIid').value.trim(), license_key: document.getElementById('licLk').value.trim(), secret: document.getElementById('licSec').value }; if (!b.instance_id || !b.license_key || !b.secret) { toast('三项都要填写(见交付单)', 'warn'); return; } const go = document.getElementById('licGo'); go.disabled = true; fetch('/api/license/activate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b) }) .then(r => r.json()).then(j => { go.disabled = false; const d = j.data || {}, res = d.result || {}; if (res.ok) { document.getElementById('licSec').value = ''; document.getElementById('licForm').style.display = 'none'; toast('激活成功', ''); } else { toast(res.message || '激活失败,请核对凭据', 'err'); } licLoad(); }).catch(() => { go.disabled = false; toast('网络错误:无法连接本机服务', 'err'); }); }