diff --git a/.zcodeignore b/.zcodeignore new file mode 100644 index 0000000..96447c4 --- /dev/null +++ b/.zcodeignore @@ -0,0 +1,66 @@ +.workbuddy/ +.venv/ +*.db +*.db-shm +*.db-wal +*.sqlite +*.sqlite3 +__pycache__/ +*.pyc +node_modules/ +/release/* +# testdata 测试数据生成器是源码,必须入库(2026-10-09 差点因未跟踪丢失) +!/release/testdata/ +# 运行时配置(存本机数据目录路径),不入库 +/release/testdata/config.json + + +# ===== 数据 / 样本 / 生成物:不入库 ===== +/后台需要导入的项目/ +/造价审核/data/* +# 2026-10-06:history.db / session.db 已 git rm --cached 移出版本控制 +# (库内全是测试数据、无保存价值,两库合计约 130MB,不再入库)。 +# 确有必要提交一次数据库快照时:git add -f 造价审核/data/xxx.db +/输出/ +/2025造价数据标准.docx +/横琴高位水池及加压泵房工程(1).html +/珠海信息价_2026年7月.html +*.pdf +*.docx +*.cos4 +*.COS +*.xml +*.XML + +# 废弃代码只留本地(2026-10-09 主人定:不入新仓库) +造价审核/app/_deprecated/ + +# ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)===== +.git/ +.hg/ +.svn/ +bower_components/ +jspm_packages/ +site-packages/ +venv/ +coverage/ +htmlcov/ +lcov-report/ +cmakefiles/ +cmake-build-*/ +bazel-*/ +pods/ +deriveddata/ +storybook-static/ +playwright-report/ +test-results/ +allure-results/ +allure-report/ +cdk.out/ +*.egg-info/ +*.dist-info/ +eggs/ +pip-wheel-metadata/ +wheels/ +# ----- ↑ 以上为 ZCode 默认排除规则(自定义规则请写在本行下方,不会被同步/恢复改动)----- +# 自定义规则写在下方(本行提示可删除) diff --git a/release/testdata/gen_testdata.py b/release/testdata/gen_testdata.py index c456b97..684d67a 100644 --- a/release/testdata/gen_testdata.py +++ b/release/testdata/gen_testdata.py @@ -572,6 +572,18 @@ def _open_db(path): con.execute("PRAGMA busy_timeout=30000") return con + +def _open_ro(path, timeout=3): + """只读打开,短超时:库被其它进程(造价审核软件 / 生成子进程)占用时快速失败返回 + None,绝不死等。原 stats_of/totals_of 用 15~30s 超时,会导致面板整页卡死。""" + try: + con = sqlite3.connect("file:%s?mode=ro" % path.replace("\\", "/"), + uri=True, timeout=timeout) + con.execute("PRAGMA busy_timeout=%d" % int(timeout * 1000)) + return con + except Exception: + return None + # ---------------- 结构级插入(history 与 session 两库共用一份逻辑数据) ---------------- # 逻辑行里的 owner 索引是本地序号,插入时映射为真实 id。 @@ -1189,7 +1201,10 @@ def stats_of(dd): if not os.path.exists(th): out["note"] = "测试库尚未生成(%s 不存在),真实库从未被本工具写过" % TEST_H return out - hc = _open_db(th) + hc = _open_ro(th) + if hc is None: + out["note"] = "测试库被占用(可能正在生成或造价审核软件打开中),稍后点「刷新统计」重试" + return out q = "FROM batches WHERE is_mock=1 AND Name LIKE '测试%'" for k in ("project", "market", "info"): out["b_%s" % k] = hc.execute("SELECT COUNT(*) " + q + " AND kind=?", (k,)).fetchone()[0] @@ -1214,65 +1229,62 @@ def stats_of(dd): hc.close() sp = ts if os.path.exists(sp): - sc = _open_db(sp) - out["s_sessions"] = sc.execute( - "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] - for t in ("s_bills", "s_norms", "s_lmes"): - try: - if t == "s_norms": # s_norms.bill_id 挂在 s_bills 上,要经两层 - out[t] = sc.execute( - "SELECT COUNT(*) FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills " - "WHERE session_id IN (SELECT id FROM sessions WHERE name LIKE '测试%'))" - ).fetchone()[0] - else: - out[t] = sc.execute( - "SELECT COUNT(*) FROM %s WHERE session_id IN " - "(SELECT id FROM sessions WHERE name LIKE '测试%%')" % t).fetchone()[0] - except Exception: + sc = _open_ro(sp) + if sc is None: + out["s_sessions"] = -1 + for t in ("s_bills", "s_norms", "s_lmes"): out[t] = -1 - sc.close() + else: + out["s_sessions"] = sc.execute( + "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] + for t in ("s_bills", "s_norms", "s_lmes"): + try: + if t == "s_norms": # s_norms.bill_id 挂在 s_bills 上,要经两层 + out[t] = sc.execute( + "SELECT COUNT(*) FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills " + "WHERE session_id IN (SELECT id FROM sessions WHERE name LIKE '测试%'))" + ).fetchone()[0] + else: + out[t] = sc.execute( + "SELECT COUNT(*) FROM %s WHERE session_id IN " + "(SELECT id FROM sessions WHERE name LIKE '测试%%')" % t).fetchone()[0] + except Exception: + out[t] = -1 + sc.close() return out # ---------------- 数据库资产总览(两库全量家底,打开面板即看) ---------------- def totals_of(dd): """参考库与测试库的全量资产计数(不区分 mock,只数行数)。 - 缺文件的库返回 None。全部走只读连接,不碰写入。""" + 缺文件 / 被占用的库返回 None。全部走只读短超时连接,库被造价审核软件或生成子进程 + 占用时快速返回(带 locked 标记),绝不死等——否则 /api/stats 卡 15~30s 会让整页假死。""" rh, th, rs, ts = db_paths(dd) - def h_totals(p): + def one(p, tables): if not os.path.exists(p): - return None - c = sqlite3.connect("file:%s?mode=ro" % p.replace("\\", "/"), uri=True, - timeout=15) - c.execute("PRAGMA busy_timeout=15000") + return None, False + c = _open_ro(p, timeout=3) + if c is None: + return None, True # 被占用 out = {} - for t in ("batches", "bills", "norms", "norm_res", "lmes", "lme_lib", - "prices", "attachments"): + for t in tables: try: out[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] except Exception: out[t] = -1 c.close() - return out + return out, False - def s_totals(p): - if not os.path.exists(p): - return None - c = sqlite3.connect("file:%s?mode=ro" % p.replace("\\", "/"), uri=True, - timeout=15) - c.execute("PRAGMA busy_timeout=15000") - out = {} - for t in ("sessions", "s_bills", "s_norms", "s_lmes"): - try: - out[t] = c.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0] - except Exception: - out[t] = -1 - c.close() - return out - - return {"ref_h": h_totals(rh), "ref_s": s_totals(rs), - "test_h": h_totals(th), "test_s": s_totals(ts)} + H = ("batches", "bills", "norms", "norm_res", "lmes", "lme_lib", + "prices", "attachments") + S = ("sessions", "s_bills", "s_norms", "s_lmes") + rh_d, l1 = one(rh, H); th_d, l2 = one(th, H) + rs_d, l3 = one(rs, S); ts_d, l4 = one(ts, S) + locked = [n for n, f in (("参考history", l1), ("参考session", l3), + ("测试history", l2), ("测试session", l4)) if f] + return {"ref_h": rh_d, "ref_s": rs_d, "test_h": th_d, "test_s": ts_d, + "locked": locked} # ---------------- 分块删除 ---------------- diff --git a/release/testdata/panel_server.py b/release/testdata/panel_server.py index 41c5777..10324be 100644 --- a/release/testdata/panel_server.py +++ b/release/testdata/panel_server.py @@ -11,6 +11,7 @@ import json import os import subprocess import sys +import time import threading import webbrowser from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -247,6 +248,9 @@ height:300px;overflow-y:auto;padding:12px;border-radius:6px;white-space:pre-wrap .chk{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--txt)} .sec-h{font-size:12px;color:var(--sub);margin:10px 0 6px;font-weight:bold} .err{color:var(--warn)} +.banner{display:none;margin:0 0 12px;padding:8px 12px;border-radius:6px;font-size:13px} +.banner.err{background:#fdecea;color:#d83931;border:1px solid #f5c6c0} +.banner.ok{background:#eaf6e8;color:#2ea121;border:1px solid #cde9c8} .dblab{display:inline-block;width:84px;text-align:center;border-radius:4px; padding:2px 0;font-size:12px;color:#fff;flex:none} .dblab.ref{background:#646a73}.dblab.test{background:var(--pri)} @@ -268,6 +272,8 @@ table.assets .grp td{background:#fafbfc;font-weight:600;text-align:left} history-test.db / session-test.db(首次自动从真实库克隆底子),真实库零污染—— 对接软件时把测试库改名换上即可;换到别的母体后点一次「版本对齐」,删除只是兜底手段。 + +

数据库

参考数据库 @@ -362,77 +368,124 @@ function cfg(){ return c;} function linkedChange(){document.getElementById("n_session").disabled= document.getElementById("session_linked").checked;} -async function post(u,b){const r=await fetch(u,{method:"POST", - headers:{"Content-Type":"application/json"},body:JSON.stringify(b||{})}); - return r.json();} -async function doRun(){document.getElementById("bRun").disabled=true; - await post("/api/run",cfg());poll();} -async function doStop(){await post("/api/stop",{});} +function banner(msg, cls){ + const el=document.getElementById("banner"); + if(!el)return; + el.textContent=msg||""; + el.className="banner "+(cls||"ok"); + el.style.display=msg?"block":"none"; +} +async function req(u,b){ + const opt={headers:{"Content-Type":"application/json"}}; + if(b!==undefined){opt.method="POST";opt.body=JSON.stringify(b);}else{opt.method="GET";} + const r=await fetch(u,opt); + const txt=await r.text(); + let j;try{j=JSON.parse(txt);}catch(e){throw new Error("服务返回异常("+r.status+"):"+txt.slice(0,160));} + return j; +} +async function post(u,b){return req(u,b);} +async function doRun(){try{document.getElementById("bRun").disabled=true; + const r=await post("/api/run",cfg()); + banner(r.ok?"已提交生成任务,请观察下方日志。":("开始生成失败:"+(r.msg||"未知错误")),"err"); + poll();}catch(e){document.getElementById("bRun").disabled=false; + banner("开始生成失败(服务可能未启动):"+e.message,"err");}} +async function doStop(){try{const r=await post("/api/stop",{});banner(r.msg||"已发送停止信号","");}catch(e){banner("停止失败:"+e.message,"err");}} async function doDel(){if(!confirm("确认真删除全部「测试」前缀的模拟数据?此操作不可恢复!"))return; - await post("/api/delete",{});poll();} -async function doAlign(){const r=await post("/api/align",{});alert(r.msg||"完成");} + try{await post("/api/delete",{});banner("删除任务已提交,请观察日志。","");poll();}catch(e){banner("删除失败:"+e.message,"err");}} +async function doAlign(){try{const r=await post("/api/align",{});banner(r.msg||"完成","");}catch(e){banner("对齐失败:"+e.message,"err");}} async function doSwitch(){ - if(!confirm("一键换库:测试库换上(history-test.db→history.db),原库留底为 history-y.db / session-y.db。\n\n请先关闭造价审核软件,否则文件占用会失败。继续?"))return; - const r=await post("/api/switch",{});alert(r.msg||"完成");loadStats();} + if(!confirm("一键换库:测试库换上(history-test.db→history.db),原库留底为 history-y.db / session-y.db。\\n\\n请先关闭造价审核软件,否则文件占用会失败。继续?"))return; + try{const r=await post("/api/switch",{});banner(r.msg||"完成","");loadStats();}catch(e){banner("换库失败:"+e.message,"err");}} async function saveDir(which){ - const b={}; - if(which==="ref")b.ref_dir=document.getElementById("refdir").value; - else b.test_dir=document.getElementById("testdir").value; - const r=await post("/api/dir",b); - const m=document.getElementById(which+"msg"); - if(m)m.textContent=r.ok?"已保存":(r.msg||"失败"); - loadStats();} + try{const b={}; + if(which==="ref")b.ref_dir=document.getElementById("refdir").value; + else b.test_dir=document.getElementById("testdir").value; + const r=await post("/api/dir",b); + const m=document.getElementById(which+"msg"); + if(m)m.textContent=r.ok?"已保存":(r.msg||"失败"); + banner(r.ok?"路径已保存":("保存失败:"+(r.msg||"未知错误")), r.ok?"":"err"); + loadStats();}catch(e){banner("保存失败(服务可能未启动):"+e.message,"err");}} function kpi(t,v,cls){return '
'+t+' '+v+'
';} -async function loadStats(){const s=await(await fetch("/api/stats")).json(); - const rf=document.getElementById("refdir"),tf=document.getElementById("testdir"); - if(document.activeElement!==rf)rf.value=s.ref_dir||""; - if(document.activeElement!==tf)tf.value=s.test_dir||s.data_dir||""; - const ro=(s.ref_ok||[]).length?s.ref_ok.every(x=>x):false; - const re=document.getElementById("refok"); - re.textContent=ro?"在":"缺";re.className="badge "+(ro?"ok":"no"); - const to=(s.test_ok||[]).length?s.test_ok.every(x=>x):false; - const te=document.getElementById("testok"); - te.textContent=to?"已生成":"尚未生成";te.className="badge "+(to?"ok":"no"); - let h=""; - h+=kpi("后台项目",s.b_project??0);h+=kpi("市场价",s.b_market??0);h+=kpi("信息价",s.b_info??0); - h+=kpi("清单",s.bills??0);h+=kpi("定额",s.norms??0);h+=kpi("定额消耗",s.norm_res??0); - h+=kpi("工料机",s.lmes??0);h+=kpi("价格明细",s.prices??0); - h+=kpi("询价附件",s.inquiry_files??0);h+=kpi("绑定",s.lme_attach??0); - h+=kpi("价格原件批次",s.price_attach_batches??0); - h+=kpi("工作台会话",s.s_sessions??0); - document.getElementById("kpis").innerHTML=h; - renderAssets(s.totals);} +async function loadStats(){ + try{const s=await req("/api/stats"); + const rf=document.getElementById("refdir"),tf=document.getElementById("testdir"); + if(document.activeElement!==rf)rf.value=s.ref_dir||""; + if(document.activeElement!==tf)tf.value=s.test_dir||s.data_dir||""; + const ro=(s.ref_ok||[]).length?s.ref_ok.every(x=>x):false; + const re=document.getElementById("refok"); + re.textContent=ro?"在":"缺";re.className="badge "+(ro?"ok":"no"); + const to=(s.test_ok||[]).length?s.test_ok.every(x=>x):false; + const te=document.getElementById("testok"); + te.textContent=to?"已生成":"尚未生成";te.className="badge "+(to?"ok":"no"); + let h=""; + h+=kpi("后台项目",s.b_project??0);h+=kpi("市场价",s.b_market??0);h+=kpi("信息价",s.b_info??0); + h+=kpi("清单",s.bills??0);h+=kpi("定额",s.norms??0);h+=kpi("定额消耗",s.norm_res??0); + h+=kpi("工料机",s.lmes??0);h+=kpi("价格明细",s.prices??0); + h+=kpi("询价附件",s.inquiry_files??0);h+=kpi("绑定",s.lme_attach??0); + h+=kpi("价格原件批次",s.price_attach_batches??0); + h+=kpi("工作台会话",s.s_sessions??0); + document.getElementById("kpis").innerHTML=h; + renderAssets(s.totals); + if(s.totals_err)banner("资产清点失败:"+s.totals_err,"err"); + }catch(e){banner("无法连接服务,请确认「启动testdata.bat」已运行、且 8412 端口未被旧实例占用:"+e.message,"err");}} function renderAssets(t){ const el=document.getElementById("assets"); if(!t){el.innerHTML='暂无数据(数据目录未就绪)';return;} + const occ=new Set(t.locked||[]); + const occH=occ.has("参考history"),occTH=occ.has("测试history"); + const occS=occ.has("参考session"),occTS=occ.has("测试session"); + const fmt=(v,occupied)=>occupied?"占用":(v==null?"缺文件":(v<0?"-":v.toLocaleString())); const HH=[["batches","批次"],["bills","清单"],["norms","定额"],["norm_res","定额消耗"], ["lmes","工料机"],["lme_lib","价格库"],["prices","价格明细"],["attachments","附件"]]; const SS=[["sessions","会话"],["s_bills","清单"],["s_norms","定额"],["s_lmes","工料机"]]; - const fmt=v=>v==null?"缺文件":(v<0?"-":v.toLocaleString()); let h='指标参考库 history测试库 history-test参考库 session测试库 session-test'; - HH.forEach(([k,n])=>{h+=''+n+''+fmt((t.ref_h||{})[k]) - +''+fmt((t.test_h||{})[k])+'——';}); - SS.forEach(([k,n])=>{h+=''+n+'——'+fmt((t.ref_s||{})[k]) - +''+fmt((t.test_s||{})[k])+'';}); + HH.forEach(([k,n])=>{h+=''+n+''+fmt((t.ref_h||{})[k],occH) + +''+fmt((t.test_h||{})[k],occTH)+'——';}); + SS.forEach(([k,n])=>{h+=''+n+'——'+fmt((t.ref_s||{})[k],occS) + +''+fmt((t.test_s||{})[k],occTS)+'';}); + if(occ.size)h+='⚠ 以下库被占用(造价审核软件打开中或正在生成),数字暂不可用,稍后点「刷新统计」:'+[...occ].join("、")+''; el.innerHTML=h;} let last=0; -async function poll(){const r=await(await fetch("/api/log")).json(); +async function poll(){try{const r=await req("/api/log"); if(r.lines.length!==last){const el=document.getElementById("log"); - el.textContent=r.lines.join("\\n");el.scrollTop=el.scrollHeight;last=r.lines.length;} + el.textContent=r.lines.join("\\n");el.scrollTop=el.scrollHeight;last=r.lines.length;} loadStats(); const run=r.running; document.getElementById("bRun").disabled=run; - if(run)setTimeout(poll,1200);} + if(run)setTimeout(poll,1200);}catch(e){banner("日志读取失败:"+e.message,"err");}} linkedChange();loadStats();poll(); """ +def _kill_port(port): + """Windows:结束占用本端口的进程(多半是上次没退干净的旧面板), + 保证本次启动的是当前代码。netstat 在中文 Windows 输出为 GBK,必须按 gbk 解码, + 否则 utf-8 解码抛 UnicodeDecodeError 会被静默吞掉、导致清场失效。""" + try: + out = subprocess.run(["netstat", "-ano"], capture_output=True, + encoding="gbk", errors="ignore", timeout=5).stdout + for line in out.splitlines(): + if (":%d" % port in line) and "LISTENING" in line: + pid = line.split()[-1] + try: + subprocess.run(["taskkill", "/f", "/pid", pid], + capture_output=True, timeout=5) + except Exception: + pass + except Exception: + pass + + def main(): + # 启动前先清掉占用 8412 的旧面板。Windows 上 SO_REUSEADDR 允许多个进程同时 + # bind 同一端口(bind 不报错),旧实例会继续应答、导致新代码不生效,因此必须主动清场。 + log("启动前清理 8412 端口上的旧实例…") + _kill_port(PORT) + time.sleep(1) try: srv = ThreadingHTTPServer(("127.0.0.1", PORT), H) except OSError: - # 端口被占(多半已有一个面板在跑)→ 不崩,直接开浏览器指过去 - log("端口 %d 已被占用,可能已有面板在跑,直接打开浏览器。" % PORT) + log("端口 %d 仍被占用(可能无权限结束旧进程),直接打开浏览器指向现有面板。" % PORT) webbrowser.open("http://127.0.0.1:%d" % PORT) return log("testdata 控制台:http://127.0.0.1:%d" % PORT) diff --git a/release/testdata/run_cfg.json b/release/testdata/run_cfg.json index 28d6c18..87f2556 100644 --- a/release/testdata/run_cfg.json +++ b/release/testdata/run_cfg.json @@ -1,6 +1,6 @@ { "n_project": 10, - "bill_lo": 500, + "bill_lo": 300, "bill_hi": 800, "norm_lo": 3, "norm_hi": 5, @@ -16,11 +16,12 @@ "info_lo": 500, "info_hi": 800, "info_attach_rate": 90, - "session_linked": true, + "session_linked": false, "n_session": 5, "sbill_lo": 150, "sbill_hi": 400, - "from_ym": "2026-01", + "from_ym": "2024-01", "to_ym": "2026-10", - "data_dir": "D:\\Pricing review‌\\release\\PricingReview-Windows-x64\\造价审核\\data" + "data_dir": "D:\\Pricing review‌\\造价审核\\data", + "ref_dir": "D:\\Pricing review‌\\造价审核\\data" } \ No newline at end of file diff --git a/release/testdata/启动testdata.bat b/release/testdata/启动testdata.bat index 06d896e..0438315 100644 --- a/release/testdata/启动testdata.bat +++ b/release/testdata/启动testdata.bat @@ -2,13 +2,17 @@ chcp 936 >nul title testdata - ²âÊÔÊý¾ÝÉú³ÉÆ÷ cd /d "%~dp0" -rem ÒÀ´ÎÕÒ: ±¾»úvenv python(ÓëÆô¶¯Ôì¼ÛÉóºËbatͬ¿î) Â̰ü×Դøpython ϵͳpython + +rem ÏȽáÊøռÓà 8412 ¶˿ڵľÉʵÀý£¬ȷ±£Æô¶¯µÄÊǵ±ǰ´úÂë +for /f "tokens=5" %%P in ('netstat -ano 2^>nul ^| findstr /i ":8412" ^| findstr /i "LISTENING"') do taskkill /f /pid %%P >nul 2>&1 +timeout /t 1 >nul 2>&1 + set PY= if exist "C://Users//MZ//.workbuddy//binaries//python//envs//default//Scripts//python.exe" set PY=C://Users//MZ//.workbuddy//binaries//python//envs//default//Scripts//python.exe if "%PY%"=="" for /d %%D in ("%~dp0..\PricingReview*") do if exist "%%~fD\python\python.exe" set PY=%%~fD\python\python.exe if "%PY%"=="" set PY=python echo ʹÓà Python: %PY% echo ¿ØÖÆ̨µØַ: http://127.0.0.1:8412 -rem ¶˿ڱ»ռʱ panel_server »áÌáʾ²¢ֱ½ӿªä¯ÀÀÆ÷ +echo Æô¶¯ÖС­¡­Èôä¯ÀÀÆ÷δ×Զ¯´򿪣¬ÇëÊֶ¯·ÃÎÊÉÏÃæµĵØַ¡£ "%PY%" panel_server.py pause diff --git a/决策台账.md b/决策台账.md index bc3e1fb..a51c8e0 100644 --- a/决策台账.md +++ b/决策台账.md @@ -726,3 +726,153 @@ Defender/360 拦(单机分发头号现实问题),买签名证书要年费 - 主人提出**采纳即复制**构想(被采纳清单的定额+工料机复制到对应清单、联动原数据工料机汇总、 原格式导出),并明确口径:导出=**数据无损替代**进原文件,不重算综合单价(算价交回原软件)。 工作量评估见当轮报告(约 4~6 个工作日,最大风险=格式保真需原软件实测),**未拍板、未动工**。 + +## 决策 26 · 2026-10-10|比对自我排除收紧 + 清单次精确名称护栏 + +### 起因 + +主人报:SX-18(前台 .cos「…项目副本」会话、后台 .cos4 入库)点「400万高空抛物摄像枪」 +找相似清单,出来的竟是另一项目的「LED补光灯」。 + +排查结论(两层叠加): +1. **真命中被自我排除误杀**:历史 batch 28(cos4 同项目)有完全相同的清单(精确档命中), + 但排除「被审工程自己」的旧口径含「源文件名主干前 12 字」启发式——会话文件名与批次 + x_src_hash 文件名前 12 字同为「三溪科创城SX-18用地」→ 整批被静默剔除; +2. **次精确(编码+单位)跨项目误配**:国标编码末 3 位是项目内顺序号,另一项目(三溪科创 + 小镇道路改造)把 LED补光灯 编到同码 030507008001 同单位「台」→ 同一次精确哈希命中; + 排序期距优先,且次精确相似度写死 1.0,误导性强。 + +### 决定(主人批复「1+2 都做」) + +- **自我排除收紧**:只认 ①同一份文件(批次 x_src_hash 与会话源文件名完全相同) + ②项目名与会话名完全相同;删除「文件名主干前 12 字」启发式(match.py 四处同口径: + match_bill / match_lme / hist_search / hist_search_lme)。同项目的另一版本 + (.cos / .cos4、改名副本)不再算"自己",正是要比对的对象。 +- **清单次精确名称护栏**:次精确命中要求名称(匹配归一后)与查询名称的字符 Jaccard + ≥ `SEMI_NAME_MIN = 0.2`,同码不同物(LED补光灯 Jaccard=0)不再出现;精确档哈希含 + 名称、工料机/价格次精确 = 名称+单位,均不受影响。 + +### 连带修掉(同根因暴露的存量 bug) + +模糊档此前不对已收录行去重——真命中回归后同一条历史行会以「精确+模糊」重复出现; +match_bill / match_lme 工程分支模糊档均按行 id 去重(工料机三档 SELECT 补带 l.id)。 + +### 验证 + +- SX-18 摄像枪比对:恰回 1 行精确(batch 28 cos4,期距 7 个月),LED补光灯消失; +- 工料机(酒精)比对:9 项目精确命中含 SX-18 cos4 版,无重影; +- 自我排除单测:同文件剔除 / 同名剔除 / 同项目另一文件保留 / 无 self 参数原样; +- 护栏数值:LED补光灯 0.0 剔除,「高空抛物摄像枪」0.7、「400万高清抛物摄像枪机」0.75 保留; +- session 44(与 batch 20 同文件)仍排除 batch 20;独立检索两接口冒烟正常。 + +## 决策 27 · 2026-10-10|搜索/匹配口径四件套(字集键 + 加权打分 + 检索不按序 + 编码前9位) + +### 起因与拍板 + +主人复核搜索("全软件的核心的核心")并定口径:①匹配范围=名称+项目特征(清单)/名称+规格型号 +(工料机),**名称优先**;②**不按排序匹配**(钢筋混凝土=混凝土钢筋);③**字母数字优于文字**; +④清单**编码只比前 9 位**(后 3 位是项目内顺序码,无对比意义);⑤**项目特征里作排序用的数字/字母 +序号(1、2、(3)、a)①)剥掉不参与匹配**。批复"A+B+C+E 一起做"并补 D 口径与序号规则。 + +### 落地(match.py 为唯一口径实现,导入侧同步) + +- **A 字集键**:bills/lmes 各加 `x_setkey` 列(schema.sql + ensure_attach_schema 补列)。 + bills=sor­t(名称归一)+'|'+单位;lmes=sort(名称+规格**合并**归一)+'|'+单位。 + 比对加 **"字集"档**(排次精确之后、模糊之前,sim=1.0),不按排序的严格等价命中。 +- **B 加权打分**:模糊档 `sim_weighted = 0.7×名称Jaccard + 0.3×特征Jaccard`(两边都没写特征时 + 特征维度按满分);字母数字 token(_TOK:字母数字开头的连续段,含 . / - φ)是身份——查询 + **名称**的 token 在候选(名称+特征)里缺失 → 一票否决;查询**特征**的 token 缺失 → 特征分减半。 + **序号剥离 norm_attr/_ORD**:`1、` `2.` `(3)` `a)` `①` 在"前一字符不是字母/数字/点"时剥掉; + IP67、2.8mm、42.5 等正文数字因负向断言保全。清单模糊打分的特征、工料机规格打分都走 norm_attr。 +- **C 检索不按序**:`_kw_conds` 把每个关键词拆成字母数字段(保持子串)+中文单字(逐字在场), + hist_search / hist_search_lme 同用;workbench renderHist 的结果过滤同步(stripOrd+同款规则)。 +- **D 编码前 9 位**:import_job / session_job 落库口径 + 启动迁移 `migrate_match_keys()` + (探针幂等:bills 31252 行 / s_bills 22792 行重算,bills 34794 + lmes 11734 行字集键回填, + ix_bill_setkey / ix_lme_setkey 索引)。次精确=编码9位+单位+名称护栏(0.2)。 +- **E**:次精确相似度显示真实名称 Jaccard(不再写死 1.0)。 + +### 验收(HTTP 实测) + +- 摄像枪行:精确(cos4 同名)+ 次精确(同 9 位编码的 030507008002 摄像机,sim=0.24 真实值), + LED补光灯仍被护栏挡住;工料机(酒精)9 项目精确含 SX-18 无回归。 +- "混凝土钢筋"⇄"钢筋混凝土" 双向命中;工料机 "泥水" 命中水泥;"42.5水泥" 正常。 +- 字集档实战触发:整串逆序名 → 清单/工料机各出"字集"档 sim=1.0。 +- workbench 浏览器实测加载正常(脚本零报错,下拉显示"精确 + 次精确 + 字集")。 + +### 边界(如实记录) + +- 模糊档**捞候选**仍是"名称前 6 字子串"(顺序敏感);字集完全换序的行由字集档兜住, + 部分换序(前 6 字不同序)可能漏召回——待将来有真实漏例再议。 +- 关键词检索的序号剥离只做了前端结果过滤;后端 LIKE 按原文(用户显式敲的关键词不剥)。 + +## 决策 28 · 2026-10-10|询价附件改会话级 + +### 起因与拍板 + +主人解释先前「询价附件没有清空」:预期是**会话级**——切换会话时展示**该会话**上次收进的附件; +只要会话不删除,附件内容就还在;工作台没打开任何项目,就没有附件。(原全局常驻口径出自 +10-09 决策,现由本条取代。) + +### 落地 + +- `/api/adopt/list` 加 `sid` 参数:只返回 adopt_hits 里 **sid 匹配**的附件(projs 同步只取本 + 会话的事件);**无 sid → 空目录**。死链懒清理仍对**全表**做(不留死角);adopt_files 存储 + 仍按内容全局去重(只是展示按会话过滤),零 schema 变更(adopt_hits 早带 sid)。 +- `api_adopt_record`:无会话(缺 session_id/lme_id)直接拒收——会话级视图下无主事件永远不可 + 见,不如不收。 +- 前端:`loadAdopt()` 带 sid;**切会话即切目录**——recOpen(最近审核打开 + 页面恢复)与 + doOpen(新开工程)在置 SID 后各补一次 loadAdopt;openInq 打开弹框时现取;无项目空态文案 + 与有项目无采纳的空态文案区分;按钮悬浮提示改为"当前会话收进的附件目录(切会话跟着切, + 删会话才清)"。 + +### 验收 + +- HTTP:无 sid=0 条、sid=57=2 条(RATION 市场价原件 + 其他.zip,5 个项目名全是 57 的采纳)、 + sid=44(无采纳历史)=0 条。 +- 浏览器实测:进页面(恢复 sid=56,无附件)徽章="询价附件"无计数;置 SID=57 走 loadAdopt → + 徽章="询价附件(2)"、弹框 2 条;切回 56 → 徽章回"询价附件"。 + +## 决策 29 · 2026-10-10|类似清单分组 v2(7 点顺序管线) + +### 主人 7 点口径(原样实现,顺序不可颠倒) + +① 取值范围=名称+项目特征;② 关键词层以"分组与匹配"的专业配置为准(房屋建筑,后期专业取消); +③ 关键词层先分、产物冻结(不再参与后续聚并;**不按单位拆组**);④ 系统聚类按名称字集 +交集≥min(4, 短方全长)(换序等效:钢混凝土=混凝土钢;短名按全长:土=钢混凝土);⑤ 剩余按特征 +"数字字母签名"(剥换行排序)等值成组;⑥ 其余进其他(按类别归并,一条不漏);⑦ 各块组再打分 +合并——**按块进行绝不跨块**(关键词块→名称块→特征块,前者排前),判据=组代表(最高频名称的 +中文主干字集)Jaccard≥0.85 且合并后累计≤50。 + +### 我的保险装置(实测逼出,主人认可方向) + +- **巨组保险丝**:名称层第4点原样跑会串联成 2099 条巨簇(全量口径 3511)→ 任何层组 >50 条时 + 组内按特征签名星形细分(锚=先到签名,行只跟锚比,无串联)。关键词层大组同款处理。 +- **合并累计上限**:合并后 >50 条就不并(防组级串联再造混合巨组——0.7 跨块版实测 237 条箱柜 + 大杂烩,已随"不跨块"+上限废除)。 +- **组代表用中文主干**:编号字母不掺进合并相似度。 +- 组内按名称原文排序(编号相邻);组列表按差%排(决策 19 不变);响应结构与旧版完全同构, + 前端零改动;后台批次页暂走旧聚类(无会话语境,等主人有感再统一)。 + +### 规则参数(global 设置,缺省即默认) + +grp_big=50、grp_sig_thr=0.6、grp_merge_on=1、grp_merge_thr=0.85、grp_merge_cap=50。 +专业/组名称设置项与全局过滤词:过滤词保留原位;专业配置暂时保留作关键词层来源(后期下架, +设置页只留分组规则参数)。 + +### 北师大会话(4318 条)验收数据 + +详见 输出/分组对比台账_20261010.md。不走第7步 278 组 / 走第7步 245 组(对比现状 677 组、 +其他 1004 条);两种变体组内+其他=4318 守恒 ✓;配电箱两条实测同组;最大组 299(特征签名族, +组内按名称排序浏览)。已知边界:特征签名按字符集,规格数字差异不敏感。 + +### 追记(同日,主人拍板修订第 7 点) + +- **第 7 点从"按块+累计上限 50"改为"池化对等、无上限"**:1~6 步的组看作完全对等的待合并组, + 三层组倒进同一个池,组代表(最高频名称的中文主干字集)Jaccard≥0.85 即合并;条数上限取消。 + 设置键 grp_merge_cap 废除(读数仍兼容但不再使用)。 +- 北师大会话实测(HTTP):**231 组 / 最大 349 / 组内 3993 + 其他 325 = 4318 守恒 ✓**, + 与模拟预测一致。对比:不走第 7 步 278 组、按块+上限 245 组。 +- 分析依据(只分析轮已报):池化 vs 按块组数只差 2~3 个(能过 0.85 的跨块对很少),上限才是 + 组数变量;去掉上限换 245→231,最大组 299→349。已知边界不变:特征签名族(299 条二通阀+ + 雨水斗+钢套管混装)来自第 5 点签名等值,与第 7 点无关。 +- 对比台账文件补记:输出/分组对比台账_20261010.md(按块版数字)+ 本追记(池化版 231/349)。 diff --git a/造价审核/app/core/import_job.py b/造价审核/app/core/import_job.py index f47eeb0..f7387a6 100644 --- a/造价审核/app/core/import_job.py +++ b/造价审核/app/core/import_job.py @@ -8,6 +8,7 @@ M1 原型:把「后台需要导入的项目」里的 15 个真实文件解析 - 只保留需要的字段,其余丢弃 """ import io, os, re, sys, time, json, hashlib, zipfile, sqlite3 +import match # 比对引擎:字集键 bill_setkey/lme_setkey 唯一实现(决策 27,口径不分叉) from xml.etree import ElementTree as ET # 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径) @@ -492,8 +493,10 @@ def save(con, kind, out, fn, sha, mtime, meta=None): seq = {"d": 0, "p": 0} # bills 元组第 8 位 = 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏) for i, (num, name, attr, unit, qty, price, total, srk) in enumerate(out["bills"]): - h = md5(num, name, unit) # 精确键:编码+名称+单位(特征写法太杂,不参与) - hs = md5(num, unit) + # 决策 27(2026-10-10):编码只取前 9 位参与哈希(后 3 位是项目内顺序码,无对比意义) + num9 = norm(num)[:9] + h = md5(num9, name, unit) # 精确键:编码9位+名称+单位(特征写法太杂,不参与) + hs = md5(num9, unit) k = buw[i] if i < len(buw) else -1 uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None kb = bkd[i] if i < len(bkd) else None @@ -505,10 +508,10 @@ def save(con, kind, out, fn, sha, mtime, meta=None): divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None cur.execute("""INSERT INTO bills(batch_id, uw_id, div_id, Number, Name, Attr, Unit, Quantity, Price, Total, Kind, src_remark, - x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq) - VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk, - norm(name), clean_attr(attr), norm(unit), h, hs, xseq)) + norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq)) n_bill += 1 bill_ids.append(cur.lastrowid) seen_bill.add(h) @@ -535,10 +538,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None): try: cur.execute("""INSERT OR IGNORE INTO lmes(batch_id, Number, Name, Specification, Unit, Quantity, NoTaxPrice, TaxRate, TaxPrice, Kind, - x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi) - VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (bid, num, name, spec, unit, qty, ntp, tax, tp, _kind, - norm(name), norm(spec), norm(unit), h, md5(name, unit))) + norm(name), norm(spec), norm(unit), h, md5(name, unit), + match.lme_setkey(name, spec, unit))) n_lme += cur.rowcount except Exception: n_lme_errs += 1 diff --git a/造价审核/app/core/match.py b/造价审核/app/core/match.py index bb40ec1..3a2c0d4 100644 --- a/造价审核/app/core/match.py +++ b/造价审核/app/core/match.py @@ -11,9 +11,14 @@ 4. 结果按「距基准先近后远」排序,同距按档位(精确>次精确>模糊) 5. 信息价/市场价的结果行带**原文件字段**(可打开附件 PDF) """ -import sqlite3, re, os, threading +import sqlite3, re, threading SIM_MIN = 0.60 +# 次精确名称护栏(2026-10-10 主人定):清单次精确 = 编码+单位,而国标编码末 3 位是项目内 +# 顺序号,不同项目把不同设备编到同码同单位很常见(实例:030507008001/台 一边是高空抛物 +# 摄像枪、一边是 LED 补光灯)。名称(匹配归一后)字符 Jaccard 低于该值的次精确命中不算 +# 同一清单项,剔除。精确档哈希含名称、工料机/价格次精确 = 名称+单位,都不受影响。 +SEMI_NAME_MIN = 0.2 def lme_list_where(prefix=""): @@ -108,6 +113,64 @@ def jaccard(a, b): return len(A & B) / len(A | B) +# ---------- 字集键 / 加权相似度(2026-10-10 决策 27 主人定) ---------- + +def set_norm(s): + """字集归一:归一后按字符排序——顺序无关的等价串,「钢筋混凝土」与「混凝土钢筋」同串。""" + return "".join(sorted(norm(s))) + + +def bill_setkey(name, unit): + """清单字集键(存 bills.x_setkey):名称字集 + 单位——名称不按排序等价、单位一致。""" + return set_norm(name) + "|" + norm(unit) + + +def lme_setkey(name, spec, unit): + """工料机字集键(存 lmes.x_setkey):名称+规格**合并成一个池**再排序(主人 2026-10-10 定 + 「名称+规格型号作为一个整体、不按排序匹配」)+ 单位。""" + return set_norm((name or "") + (spec or "")) + "|" + norm(unit) + + +# 特征里的排序序号——只是排版顺序,剥掉不参与匹配(2026-10-10 主人定)。 +# ⚠️ 在 norm() 之后套用(小写、全角括号已转半角、空白已去)。「前面的字符不是字母/数字/点」 +# 负向断言保证 IP67、2.8mm、42.5 这类**正文数字**不被误剥——序号前的邻居是文字或开头。 +_ORD = re.compile(r"[①-⑳]" + r"|([0-9]{1,3})|\([0-9]{1,3}\)" + r"|(?= limit: break - out.append(d); seen.add((d["Name"], d["Attr"])) - # L2 模糊:名称+特征 相似度 + out.append(d); seen.add((d["Name"], d["Attr"])); seen_ids.add(d["id"]) + # L1.5 字集精确(2026-10-10 决策 27):名称字集+单位等价——「钢筋混凝土」=「混凝土钢筋」, + # 不按排序的严格命中;键 = bills.x_setkey(导入落列,老库启动迁移回填)。 + if len(out) < limit: + sqlk = """SELECT '字集' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj, + bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src, + bt.x_province, bt.x_city, bt.x_district + FROM bills b JOIN batches bt ON bt.id=b.batch_id + WHERE b.x_setkey=? AND bt.kind='project' AND %s LIMIT ?""" % w + for x in c.execute(sqlk, [bill_setkey(row["Name"], row["Unit"])] + args + [limit]): + d = dict(x) + if d["id"] in seen_ids: + continue + if len(out) >= limit: + break + out.append(d); seen_ids.add(d["id"]) + # L2 模糊:加权相似度(0.7×名称 + 0.3×特征,字母数字身份规则见 sim_weighted) if len(out) < limit: q = norm_match(row["Name"])[:6] if q: @@ -249,10 +361,13 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro for x in c.execute(sql3, args + ["%" + q + "%"]): if norm(x["Unit"]) != norm(row["Unit"]): continue - sim = jaccard(norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(x["Name"]) + norm_match(x["Attr"])) + if x["id"] in seen_ids: + continue + sim = sim_weighted(qn, norm_match(x["Name"]), + norm_attr(row["Attr"]), norm_attr(x["Attr"])) if sim >= SIM_MIN: - d = dict(x); d["tier"] = "模糊" - out.append(d) + d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim + out.append(d); seen_ids.add(x["id"]) if len(out) >= limit: break res = [] @@ -265,17 +380,14 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro "period": ym(nearest(d["p1"], d["p2"], bf)), "period_m": nearest(d["p1"], d["p2"], bf), "dist": dist(d["p1"], d["p2"], bf, bt), - "sim": 1.0 if d["tier"] != "模糊" else round(jaccard( - norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(d["Name"]) + norm(d["Attr"])), 2), + "sim": (1.0 if d["tier"] in ("精确", "字集") else + round(d["_sim"], 2) if "_sim" in d else + round(jaccard(qn, norm_match(d["Name"])), 2)), # 次精确=真实名称相似度(决策 27 E) "src": "工程", "file": "", "src_hash": d.get("src") or "", }) res = [r for r in res if _in_period(r, pfrom, pto)] - ss = _stem(self_src) # 被审工程源文件名主干(前 12 字) - if ss or self_name: # 排除"被审工程自己" - res = [r for r in res - if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss) - and not (self_name and (r["proj"] or "").strip() == self_name.strip())] - res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[r["tier"]])) + res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目) + res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]])) return res[:limit] @@ -287,27 +399,22 @@ def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=N · dist=0、排序由本函数做好(期次先近后远),前端不再按 dist 重排。 期次条件=区间重叠语义:批次的 [起,止] 与所选 [起,止] 有交集即命中(检索没有"基准期")。 self_name/self_src:被审工程自己(若它也入库了)**排除**(2026-10-08 主人定), - 判定与 match_bill/match_lme 同一套:源文件主干相同(_stem 前 12 字)或项目名相同。 + 判定与 match_bill/match_lme 同一套(_self_filter 口径):同一份文件(x_src_hash 相同) + 或项目名相同。 page:分页(2026-10-08 主人定,每页=limit 条,第 N 页 OFFSET (N-1)×limit)。""" c = hist.cursor() cond, args = _filters(kinds, units, [], prefix="bt") # 批次级条件(拼好的 SQL 串 + 参数) extra = [] - ss = _stem(self_src) if self_src else "" nm = (self_name or "").strip() - if ss or nm: + src = (self_src or "").strip() + if src or nm: self_ids = [r[0] for r in c.execute( "SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall() - if (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)] + if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)] if self_ids: extra.append("bt.id NOT IN (%s)" % ",".join("?" * len(self_ids))) args = args + self_ids - for t in (kw or "").split(): - if not t: - continue - pat = "%" + _kw_fold(t) + "%" # 检索词折叠(同 hist_search_lme,符号变体一视同仁) - extra.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)" - % (_kw_like("b.Name"), _kw_like("b.Attr"), _kw_like("b.Unit"))) - args = args + [pat] * 3 + _kw_conds(["b.Name", "b.Attr", "b.Unit"], kw, extra, args) # 不按排序(决策 27):φ 等折叠在 _kw_conds 内 if pfrom is not None: extra.append("bt.x_period_end_m >= ?") args = args + [pfrom] @@ -363,22 +470,16 @@ def hist_search_lme(hist, orgs=None, area=None, pfrom=None, pto=None, kw="", pmi cond, cargs = _filters(kinds or [], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs) condp, cargsp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs) outer, oargs = [], [] - ss = _stem(self_src) if self_src else "" nm = (self_name or "").strip() - if ss or nm: + src = (self_src or "").strip() + if src or nm: self_ids = [r[0] for r in c.execute( "SELECT id, Name, x_src_hash FROM batches").fetchall() - if (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)] + if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)] if self_ids: outer.append("batch_id NOT IN (%s)" % ",".join("?" * len(self_ids))) oargs += self_ids - for t in (kw or "").split(): - if not t: - continue - pat = "%" + _kw_fold(t) + "%" # 检索词折叠(φ/Φ/ϕ/⌀/Ø 一视同仁) - outer.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)" - % (_kw_like("name"), _kw_like("spec"), _kw_like("unit"))) - oargs += [pat] * 3 + _kw_conds(["name", "spec", "unit"], kw, outer, oargs) # 不按排序(决策 27) if pfrom is not None: outer.append("p2 >= ?"); oargs.append(pfrom) if pto is not None: @@ -467,7 +568,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间 srcs = srcs or ["project", "info", "market"] c = hist.cursor() - out = [] + out, seen_ids = [], set() # ---- 历史工程工料机 ---- w, args = _filters(kinds or [], [], [], self_src=self_src, area=area, orgs=orgs) wpr, apr = _price_range("l.NoTaxPrice", pmin, pmax) @@ -479,7 +580,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N # 带 l. 前缀,见 lme_list_where 的说明。 # ⚠️ **信息价/市场价分支永远不过滤任何单位/类别**(主人 2026-10-09 明示"永远不能 # 屏蔽信息价/市场价的任何单位")—— 别把 lme_list_where 加到下面价格查询上。 - sql = """SELECT '精确' tier, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, + sql = """SELECT '精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, bt.Name proj, bt.BulidUnit bunit, bt.FileKind, bt.x_province, bt.x_city, bt.x_district, bt.x_period_start_m p1, bt.x_period_end_m p2, @@ -488,11 +589,12 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N LEFT JOIN lme_attach la ON la.lme_id=l.id LEFT JOIN inquiry_files f ON f.id=la.file_id WHERE l.x_hash_exact=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l")) - out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])] + for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]): + d = dict(x); out.append(d); seen_ids.add(d["id"]) if len(out) < limit: # 次精确:名称+单位一致、规格不同(2026-10-08 主人定)——同名材料不同规格正是常比对象 seen_semi = {(x["Name"], x["Specification"]) for x in out} - sql2 = """SELECT '次精确' tier, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, + sql2 = """SELECT '次精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, bt.Name proj, bt.BulidUnit bunit, bt.FileKind, bt.x_province, bt.x_city, bt.x_district, bt.x_period_start_m p1, bt.x_period_end_m p2, @@ -507,11 +609,30 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N continue if len(out) >= limit: break - out.append(d); seen_semi.add((d["Name"], d["Specification"])) + out.append(d); seen_semi.add((d["Name"], d["Specification"])); seen_ids.add(d["id"]) + # 字集精确(2026-10-10 决策 27):名称+规格**合并字集**+单位等价——「P.O 42.5 水泥」 + # =「水泥 42.5 P.O」这类不按排序的整体命中;键 = lmes.x_setkey(导入落列,老库迁移回填)。 + if len(out) < limit: + sqlk = """SELECT '字集' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, + bt.Name proj, bt.BulidUnit bunit, bt.FileKind, + bt.x_province, bt.x_city, bt.x_district, + bt.x_period_start_m p1, bt.x_period_end_m p2, + f.id fid, f.original_name fname + FROM lmes l JOIN batches bt ON bt.id=l.batch_id + LEFT JOIN lme_attach la ON la.lme_id=l.id + LEFT JOIN inquiry_files f ON f.id=la.file_id + WHERE l.x_setkey=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l")) + for x in c.execute(sqlk, [lme_setkey(row["Name"], row["Specification"], row["Unit"])] + args + [limit]): + d = dict(x) + if d["id"] in seen_ids: + continue + if len(out) >= limit: + break + out.append(d); seen_ids.add(d["id"]) if len(out) < limit: q = norm_match(row["Name"])[:6] if q: - sql3 = """SELECT l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, + sql3 = """SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, bt.Name proj, bt.BulidUnit bunit, bt.FileKind, bt.x_province, bt.x_city, bt.x_district, bt.x_period_start_m p1, bt.x_period_end_m p2, @@ -523,11 +644,13 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N for x in c.execute(sql3, args + ["%" + q + "%"]): if norm(x["Unit"]) != norm(row["Unit"]): continue - sim = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]), - norm_match(x["Name"]) + norm_match(x["Specification"])) + if x["id"] in seen_ids: + continue + sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]), + norm_attr(row["Specification"]), norm_attr(x["Specification"])) if sim >= SIM_MIN: - d = dict(x); d["tier"] = "模糊" - out.append(d) + d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim + out.append(d); seen_ids.add(x["id"]) if len(out) >= limit: break for d in out: @@ -538,9 +661,9 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N "fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")), "period_m": nearest(d["p1"], d["p2"], bf), "dist": dist(d["p1"], d["p2"], bf, bt), - "sim": 1.0 if d["tier"] != "模糊" else round(jaccard( - norm_match(row["Name"]) + norm_match(row["Specification"]), - norm_match(d["Name"]) + norm_match(d["Specification"])), 2), + "sim": (1.0 if d["tier"] in ("精确", "字集") else + round(d["_sim"], 2) if "_sim" in d else + round(jaccard(norm_match(row["Name"]), norm_match(d["Name"])), 2)), "src": "工程", "file": d.get("fname") or "", "file_url": ("/api/admin/inq/file/%d" % d["fid"]) if d.get("fid") else "", }) @@ -627,8 +750,8 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N key = (x["Name"], x["Specification"], x["Unit"]) if key in seen_p: continue - sim = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]), - norm_match(x["Name"]) + norm_match(x["Specification"])) + sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]), + norm_attr(row["Specification"]), norm_attr(x["Specification"])) if sim < SIM_MIN: continue seen_p.add(key) @@ -654,10 +777,6 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N res = [r for r in res if r.get("file")] elif att == "no": res = [r for r in res if not r.get("file")] - ss = _stem(self_src) # 被审工程源文件名主干(前 12 字) - if ss or self_name: # 排除"被审工程自己" - res = [r for r in res - if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss) - and not (self_name and (r["proj"] or "").strip() == self_name.strip())] - res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[r["tier"]])) + res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目) + res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]])) return res[:limit] diff --git a/造价审核/app/core/session_job.py b/造价审核/app/core/session_job.py index d0c9690..6ed3d3d 100644 --- a/造价审核/app/core/session_job.py +++ b/造价审核/app/core/session_job.py @@ -386,7 +386,9 @@ def open_project(con, files, meta, job, sid=None): VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk, norm(nm), norm(attr), norm(unit), - md5(num, nm, unit), md5(num, unit), xseq)) + md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq)) + # 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义); + # 与 history.db.bills(import_job)同口径,启动迁移重算老数据 bill_ids.append(cur.lastrowid) stat["bill"] += 1 diff --git a/造价审核/app/server/api_server.py b/造价审核/app/server/api_server.py index 78b0d1b..10be292 100644 --- a/造价审核/app/server/api_server.py +++ b/造价审核/app/server/api_server.py @@ -4,6 +4,8 @@ M3-1 后端服务:零依赖(Python 标准库 http.server) 提供后台管理界面需要的接口,并托管前端页面。 """ import io, os, re, json, sqlite3, urllib.parse, mimetypes, hashlib, time, threading, base64 +from itertools import combinations +from collections import Counter from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler # ---- 路径:**一律由本文件位置推导**,不写死绝对路径 ---- @@ -117,6 +119,12 @@ def ensure_attach_schema(): con.execute("ALTER TABLE lmes ADD COLUMN x_hash_semi TEXT") if "x_hash_semi" not in pcols: con.execute("ALTER TABLE prices ADD COLUMN x_hash_semi TEXT") + # 2026-10-10 决策 27:字集键列(回填与索引在 migrate_match_keys,连 bills 一起) + bcols = [r[1] for r in con.execute("PRAGMA table_info(bills)")] + if "x_setkey" not in bcols: + con.execute("ALTER TABLE bills ADD COLUMN x_setkey TEXT") + if "x_setkey" not in lcols: + con.execute("ALTER TABLE lmes ADD COLUMN x_setkey TEXT") # 2026-10-06:价格条数从 x_rows_lme 拆出来,单独一列。 # x_rows_lme 此前被复用(项目=工料机数 / 价格批次=价格数), # 导致「x_rows_lme>0 ⇒ 有工料机」的写法会把信息价批次误判。 @@ -130,6 +138,65 @@ def ensure_attach_schema(): con.commit(); con.close() +def _hash9_current(con, table): + """探针:库存清单哈希是否已是「编码前 9 位」口径(决策 27)。整库任取一行重算比对。""" + row = con.execute("""SELECT Number, Name, Unit, x_hash_exact FROM %s + WHERE Number IS NOT NULL AND Length(Number) >= 9 LIMIT 1""" % table).fetchone() + if not row: + return True # 没有长编码行:两种口径结果相同,视为已迁移 + num, name, unit, h0 = row + return job.md5(job.norm(num)[:9], name, unit) == h0 + + +def _rehash_bills_9(con, table): + """整表按「编码前 9 位」重算精确/次精确哈希(决策 27)。返回改动行数。""" + rows = con.execute("SELECT id, Number, Name, Unit, x_hash_exact, x_hash_semi FROM %s" % table).fetchall() + ups = [] + for rid, num, name, unit, h0, hs0 in rows: + num9 = job.norm(num)[:9] + h, hs = job.md5(num9, name, unit), job.md5(num9, unit) + if h != h0 or hs != hs0: + ups.append((h, hs, rid)) + if ups: + con.executemany("UPDATE %s SET x_hash_exact=?, x_hash_semi=? WHERE id=?" % table, ups) + return len(ups) + + +def migrate_match_keys(): + """决策 27(2026-10-10)一次性迁移,幂等(探针不匹配才动手,平时启动零成本跳过): + ① bills 哈希改「编码前 9 位」口径——history.db.bills 与 session.db.s_bills 全量重算 + x_hash_exact / x_hash_semi(编码后 3 位是项目内顺序码,跨项目没有对比意义); + ② bills / lmes 回填 x_setkey 字集键 + 建索引(老库补列在 ensure_attach_schema,新库 schema.sql 自带)。""" + con = sqlite3.connect(DB) + try: + if not _hash9_current(con, "bills"): + print("迁移:bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(con, "bills")) + nb = con.execute("SELECT COUNT(*) FROM bills WHERE x_setkey IS NULL").fetchone()[0] + if nb: + con.executemany("UPDATE bills SET x_setkey=? WHERE id=?", + [(match.bill_setkey(nm, un), rid) for rid, nm, un in + con.execute("SELECT id, Name, Unit FROM bills WHERE x_setkey IS NULL")]) + print("迁移:bills 字集键回填 %d 行" % nb) + nl = con.execute("SELECT COUNT(*) FROM lmes WHERE x_setkey IS NULL").fetchone()[0] + if nl: + con.executemany("UPDATE lmes SET x_setkey=? WHERE id=?", + [(match.lme_setkey(nm, sp, un), rid) for rid, nm, sp, un in + con.execute("SELECT id, Name, Specification, Unit FROM lmes WHERE x_setkey IS NULL")]) + print("迁移:lmes 字集键回填 %d 行" % nl) + con.execute("CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey)") + con.execute("CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey)") + con.commit() + finally: + con.close() + scon = sess.connect() + try: + if not _hash9_current(scon, "s_bills"): + print("迁移:s_bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(scon, "s_bills")) + scon.commit() + finally: + scon.close() + + # --------------------------------------------------------------------------- # 数据源字典 / 后台设置(2026-10-06) # ⚠️ 2026-10-06 重构:dict_region / dict_org / settings 三张表的建表 SQL 已全部收口到 @@ -764,13 +831,15 @@ def api_adopt_record(body): (sha, kind, ref, name, ext, size, now)) sid = int(body.get("session_id") or 0) lmid = int(body.get("lme_id") or 0) + if not sid or not lmid: + # 决策 28(2026-10-10):目录按会话展示,没有会话的事件永远不可见 → 干脆不收 + return {"ok": False, "msg": "未打开项目(无会话),不收集附件"} proj = (body.get("proj") or "").strip() if sid and lmid: # 该行的旧事件先撤(换绑:再采纳即替换) c.execute("DELETE FROM adopt_hits WHERE sid=? AND lme_id=?", (sid, lmid)) if proj: c.execute("""INSERT INTO adopt_hits(sha256, proj, adopted_at, sid, lme_id) - VALUES(?,?,?,?,?)""", (sha, proj, now, - sid or None, lmid or None)) + VALUES(?,?,?,?,?)""", (sha, proj, now, sid, lmid)) c.commit() n_att = c.execute("SELECT COUNT(*) FROM adopt_files").fetchone()[0] return {"ok": True, "n_att": n_att} @@ -807,9 +876,11 @@ def api_adopt_cancel(body): c.close() -def api_adopt_list(): - """「询价附件」弹框数据:附件目录(按内容去重)+ 每个附件被哪些项目采纳过。 - 顺带懒清理:磁盘原件已随批次删除的条目,这里从注册表摘掉,不留死链接。""" +def api_adopt_list(sid=0): + """「询价附件」弹框数据(2026-10-10 主人定:**会话级**)——只看当前会话收进的附件: + 过滤 adopt_hits 里 sid 匹配的事件;没打开项目(无 sid)→ 空目录。 + 会话不删,事件就在,切回来附件还在;删会话连带撤事件(api_session_delete 已有)。 + 仍顺带懒清理:磁盘原件已随批次删除的条目,从注册表摘掉,不留死链接(对全表做,别留死角)。""" c = conn() try: atts, dead = [], [] @@ -820,13 +891,21 @@ def api_adopt_list(): if not rel or not os.path.exists(os.path.join(DATA_DIR, rel)): dead.append(sha) continue + if sid: + n = c.execute("SELECT COUNT(*) FROM adopt_hits WHERE sha256=? AND sid=?", + (sha, sid)).fetchone()[0] + if not n: + continue # 别的会话收的:本会话目录里不显示(行保留) + projs = [h[0] for h in c.execute( + """SELECT DISTINCT proj FROM adopt_hits WHERE sha256=? AND sid=? + ORDER BY proj""", (sha, sid)).fetchall()] + else: + continue # 没打开项目:不给任何附件(主人 2026-10-10 定) atts.append({"sha": sha, "kind": kind, "ref": ref2, "name": name, "ext": ext, "size": size, "adopted_at": at, "url": ("/api/admin/inq/file/%s" % ref2) if kind == "inq" else ("/api/admin/file/%s" % sha), - "projs": [h[0] for h in c.execute( - """SELECT DISTINCT proj FROM adopt_hits WHERE sha256=? - ORDER BY proj""", (sha,)).fetchall()]}) + "projs": projs}) if dead: c.executemany("DELETE FROM adopt_files WHERE sha256=?", [(s,) for s in dead]) c.executemany("DELETE FROM adopt_hits WHERE sha256=?", [(s,) for s in dead]) @@ -2066,68 +2145,11 @@ def api_session_groups(sid, kind): if kind == "inconsistent": return _inconsistent(rows, BILLROW) - # ---- similar ---- - # 系统内置专业:走固定的「前 4 字 + bigram」自动聚类(与后台同一实现 _group_by_prefix) - if _setting_get("session:%d" % sid, "profession") == SYS_PROF: - gs, rest = _group_by_prefix(rows) - out = [] - for g in gs: - d = _grpstat(g["rows"]); d["sim"] = g["sim"] - d["rows"] = [BILLROW(x) for x in g["rows"]] - out.append(d) - out.sort(key=lambda x: -(x.get("spread") or 0)) - return {"total": len(out), "groups": out, - "extra": _extra_by_cat(rest, BILLROW), "group_mode": True} - - # 优先用「关键字分组」配置;无配置走原「前 6 字」逻辑 - cfg = _load_similar_groups(sid) - if cfg: - groups, other = _group_by_keywords(rows, cfg) - out = [] - for gname, rs in groups: - d = _grpstat(rs); d["cat"] = gname; d["sim"] = 1.0 - d["rows"] = [BILLROW(x) for x in rs] - out.append(d) - out.sort(key=lambda x: -(x.get("spread") or 0)) - extra = [] - if other: - d = _grpstat(other); d["cat"] = "其他"; d["sim"] = 1.0 - d["rows"] = [BILLROW(x) for x in other] - extra = [d] - return {"total": len(groups), "groups": out, "extra": extra, "group_mode": True} - - # 原行为:按名称前 6 字分桶 - g = {} - for r in rows: - key = r["x_name_norm"][:6] - if not key: - continue - g.setdefault(key, []).append(r) - out = [] - for key, rs in g.items(): - names = {x["Name"] for x in rs} - if len(names) < 2: - continue - d = _grpstat(rs) - d["sim"] = 1.0 - d["rows"] = [BILLROW(x) for x in rs] - out.append(d) - # 2026-09-29 决策 19:similar 组按「差距%」从大到小排 - out.sort(key=lambda x: -(x.get("spread") or 0)) - - # 2026-09-29 决策 18:没进任何组的合规清单按类别归并,保证一条不漏 - extra = [] - shown = {r[0] for grp in out for r in grp["rows"]} - rest = [r for r in rows if r["id"] not in shown] - buckets = {} - for r in rest: - buckets.setdefault(cat_of(r["Name"]) or "其他", []).append(r) - for lab, rs in sorted(buckets.items(), key=lambda x: (-len(x[1]), x[0])): - d = _grpstat(rs) - d["cat"] = lab - d["rows"] = [BILLROW(x) for x in rs] - extra.append(d) - return {"total": len(out), "groups": out, "extra": extra} + # ---- similar:v2 七点顺序管线(决策 29,2026-10-10 主人定)---- + # 关键词层仍读本工程专业的配置(后期专业取消后 kw_cfg 恒 None,管线自动只剩名称层+特征层) + prof = _setting_get("session:%d" % sid, "profession") + kw_cfg = _load_similar_groups(sid) if (prof and prof != SYS_PROF) else None + return _group_v2_output(rows, kw_cfg) def api_session_bill_norms(bill_id): @@ -3006,6 +3028,207 @@ def norm_txt(s): return s.lower() +# ---------- 类似清单分组 v2(2026-10-10 决策 29 主人定:7 点顺序管线) ---------- +# 顺序语义(主人定,顺序不可颠倒):逐级实施,**上一级分走的行不再进入下一级**。 +# 第3点 关键词层:本工程专业配置的关键词组(首匹配+排除词);**不按单位拆**——取值范围=名称+特征。 +# 第4点 名称层:名称字集 交集≥min(4, 短方全长) 并查集聚类(字集等效换序无关:钢混凝土=混凝土钢; +# 短名按全长处理:土=钢混凝土)。 +# 第5点 特征层:剩余落单按特征"数字字母签名"(剥换行排序序号后提取字母数字的字符集合)等值成组。 +# 第6点 其他:仍没进组的全部按类别归并展示(一条不漏,决策 18)。 +# 第7点 池化合并(2026-10-10 主人定修订):1~6 步的组**完全对等**——三层组倒进同一个池, +# 组代表(组内最高频名称的中文主干字集)Jaccard≥grp_merge_thr 即合并; +# **不设条数上限、无跨块限制**(初版"按块+累计上限50"已废,主人拍板池化)。 +# 保险丝(防串联巨组,实测 2099/3511 条巨组的解):任何一层产生的组超过 grp_big 条 → 组内按特征签名 +# 星形细分(阈值 grp_sig_thr)。 +# 规则参数读 global 设置(缺省用默认):grp_big=50 / grp_sig_thr=0.6 / grp_merge_on=1 / +# grp_merge_thr=0.85。专业/组名称配置仍作关键词层来源(后期取消)。 + +def _grp_rule(): + def _i(k, d): + try: + return int(float(_setting_get("global", k) or d)) + except Exception: + return d + def _f(k, d): + try: + return float(_setting_get("global", k) or d) + except Exception: + return d + return {"big": _i("grp_big", 50), + "sig_thr": _f("grp_sig_thr", 0.6), + "merge_on": (_setting_get("global", "grp_merge_on") or "1") not in ("0", "false", "off"), + "merge_thr": _f("grp_merge_thr", 0.85)} + + +def _grp_signature(s): + """特征「数字字母签名」:norm_attr 剥排序序号后,全部字母数字段的字符集合(排序串)。""" + s = match.norm_attr(s or "") + return "".join(sorted(set("".join(match._TOK.findall(s))))) + + +def _grp_stem_set(names): + """组代表(第7点合并判据):组内最高频名称的**中文主干**字集——编号字母不掺进相似度。""" + c = Counter((match.norm_attr(n or "")) for n in names) + if not c: + return set() + best = c.most_common(1)[0][0] + s = match._TOK.sub(" ", best) + s = "".join(re.sub(r"[^一-鿿]+", " ", s).split()) + return set(match.set_norm(s)) if s else set() + + +def _grp_fuse(mem_rows, thr): + """巨组保险丝:组内按特征签名**星形**细分——锚=先到的签名,行只跟锚比,杜绝串联。 + 返回子组列表(可能含单行子组,调用方分流到下一层)。""" + reps = [] + for r in sorted(mem_rows, key=lambda x: _col(x, "id")): + s = _grp_signature(_col(r, "Attr")) + placed = False + if s: + for rs, m2 in reps: + u = len(set(s) | set(rs)) + if u and len(set(s) & set(rs)) / u >= thr: + m2.append(r); placed = True; break + if not placed: + reps.append((s, [r])) + return [m2 for rs, m2 in reps] + + +def _grp_block_merge(groups, thr): + """第7点池化合并(2026-10-10 主人定:1~6 步的组看作**完全对等**的待合并组,跨块池化; + **不设条数上限**):组代表(最高频名称的中文主干字集)Jaccard≥thr 即合并。""" + reps = [_grp_stem_set([_col(x, "Name") for x in g]) for g in groups] + par2 = list(range(len(groups))) + def f2(x): + while par2[x] != x: par2[x] = par2[par2[x]]; x = par2[x] + return x + for i in range(len(groups)): + for j in range(len(groups)): + if i == j: + continue + a, b = reps[i], reps[j] + if not a or not b: + continue + ri, rj = f2(i), f2(j) + if ri == rj: + continue + u = len(a | b) + if u and len(a & b) / u >= thr: + par2[ri] = rj + mg = {} + for i in range(len(groups)): mg.setdefault(f2(i), []).extend(groups[i]) + return [v for v in mg.values() if len(v) > 1] + + +def _group_v2(rows, kw_cfg): + """决策 29 七点顺序管线。kw_cfg=本工程专业关键词配置(无/后期取消=跳过关键词层)。 + 返回 (blocks, rest):blocks=[(组名或None, 行列表)] 按块顺序(关键词→名称→特征), + rest=未进组的行(调用方交 _extra_by_cat 归并)。""" + rule = _grp_rule() + used = set() + + # ---- 第3点 关键词层 ---- + kw_blocks = [] + if kw_cfg: + for g in kw_cfg: + kws = [match.norm(k) for k in (g.get("keywords") or []) if k] + if not kws: + continue + mem = [] + for r in rows: + if _col(r, "id") in used: + continue + nm = match.norm("%s %s" % (_col(r, "Name") or "", _col(r, "Attr") or "")) + if any(k in nm for k in kws) and not any( + match.norm(x) in nm for x in (g.get("exclude") or []) if x): + mem.append(r) + if not mem: + continue + subs = _grp_fuse(mem, rule["sig_thr"]) if len(mem) > rule["big"] else [mem] + for m in subs: + if len(m) > 1: # 单行子组不算"已分组",落回名称层 + kw_blocks.append((g.get("name") or "关键词组", m)) + used.update(_col(x, "id") for x in m) + + # ---- 第4点 名称层:字集 交集≥min(4,短方全长) ---- + rest0 = [r for r in rows if _col(r, "id") not in used] + par = list(range(len(rest0))) + def find(x): + while par[x] != x: par[x] = par[par[x]]; x = par[x] + return x + keys = [set(match.set_norm(match.norm_attr(_col(r, "Name") or ""))) for r in rest0] + inv = {} + for i, k in enumerate(keys): + for ch in k: + inv.setdefault(ch, []).append(i) + for ch, lst in inv.items(): + for i, j in combinations(lst, 2): + if len(keys[i] & keys[j]) >= min(4, min(len(keys[i]), len(keys[j]))): + ra, rb = find(i), find(j) + if ra != rb: + par[ra] = rb + clus = {} + for i in range(len(rest0)): + clus.setdefault(find(i), []).append(i) + name_blocks = [] + rest = [] + for root, mem in clus.items(): + mrows = sorted((rest0[i] for i in mem), key=lambda x: _col(x, "id")) + if len(mrows) == 1: + rest.append(mrows[0]); continue + subs = _grp_fuse(mrows, rule["sig_thr"]) if len(mrows) > rule["big"] else [mrows] + for m in subs: + if len(m) > 1: + name_blocks.append((None, m)) + else: + rest.append(m[0]) + + # ---- 第5点 特征层:落单按签名等值(签名不足 4 字符的行不参与,留在 rest——条数守恒)---- + sigb = {} + for r in rest: + s = _grp_signature(_col(r, "Attr")) + if len(s) >= 4: + sigb.setdefault(s, []).append(r) + attr_blocks = [(None, v) for v in sigb.values() if len(v) >= 2] + taken = set() + for v in sigb.values(): + if len(v) >= 2: + taken.update(_col(x, "id") for x in v) + rest = [r for r in rest if _col(r, "id") not in taken] + + # ---- 第7点 池化合并(2026-10-10 主人定修订:1~6 步的组**完全对等**,三层组倒进同一个池, + # 组代表主干字集 J≥merge_thr 即并,**不设条数上限、不跨块限制已随池化取消**)---- + if rule["merge_on"] and len(kw_blocks) + len(name_blocks) + len(attr_blocks) > 1: + pool = kw_blocks + name_blocks + attr_blocks + merged = _grp_block_merge([b[1] for b in pool], rule["merge_thr"]) + lbl_of = {} + for lbl0, g0 in pool: + for x in g0: + lbl_of[id(x)] = lbl0 + kw_blocks, name_blocks, attr_blocks = [], [], [] + for g in merged: + cnt = Counter(lbl_of.get(id(x)) for x in g if lbl_of.get(id(x))) + lbl = max(cnt, key=lambda l: cnt[l]) if cnt else None # 沿用簇内多数的关键词组名 + kw_blocks.append((lbl, g)) + return kw_blocks + name_blocks + attr_blocks, rest + + +def _group_v2_output(rows, kw_cfg): + """v2 管线 → 前端响应(结构与原 similar 完全同构:total/groups/extra/group_mode)。""" + blocks, rest = _group_v2(rows, kw_cfg) + out = [] + for label, rs in blocks: + d = _grpstat(rs) + if label: + d["cat"] = label + d["sim"] = 1.0 + d["rows"] = [BILLROW(x) for x in rs] + out.append(d) + out.sort(key=lambda x: -(x.get("spread") or 0)) # 决策 19:组按差% 从大到小 + return {"total": len(out), "groups": out, + "extra": _extra_by_cat(rest, BILLROW), "group_mode": True} + + # 行适配统一用上面的 BILLROW(两侧唯一实现,原 _billrow 已删 —— 2026-10-08 收编)。 @@ -3351,8 +3574,8 @@ class Handler(SimpleHTTPRequestHandler): return self._json(api_raw_uw(one)) if p == "/api/session/inq": # 工作台:询价附件(只读,来源=后台项目批次) return self._json(api_session_inq(int(one.get("session_id", 0) or 0))) - if p == "/api/adopt/list": # 工作台「询价附件」:采纳收集的附件目录 - return self._json(api_adopt_list()) + if p == "/api/adopt/list": # 工作台「询价附件」:当前会话收进的附件目录(会话级,决策 28) + return self._json(api_adopt_list(int((q.get("sid") or ["0"])[0] or 0))) if p == "/api/session/rows": # 会话数据(工作台三个标签) return self._json(api_session_rows(one)) if p == "/api/session/inconsistent": # 会话内:组价不一致 @@ -3668,7 +3891,8 @@ def run(): pass ensure_adopt_schema() # 采纳收集表形状检查(旧去重版 → 事件模型重建) _ensure_batch_schema() # 唯一建表入口:执行 schema.sql(含 attachments/dict/settings/inquiry 全部表) - ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block) + ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block / x_setkey) + migrate_match_keys() # 决策 27:清单哈希改编码前9位 + 字集键回填(幂等,探针跳过) ensure_dict_schema() # 数据源字典(首次用库里已有值播种) backfill_session_batch() # 老会话补 x_batch_id → 工作台才能看到该项目的询价附件 cleanup_sessions() # 启动时清掉超过保留天数的会话(只碰 session.db) diff --git a/造价审核/app/store/schema.sql b/造价审核/app/store/schema.sql index 6e13987..0a1932a 100644 --- a/造价审核/app/store/schema.sql +++ b/造价审核/app/store/schema.sql @@ -165,13 +165,15 @@ CREATE TABLE IF NOT EXISTS bills( x_name_norm TEXT, x_attr_norm TEXT, x_unit_norm TEXT, - x_hash_exact TEXT, -- md5(编码 + 名称归一 + 单位归一) —— 不含项目特征 Attr(Attr 写法太杂不参与) - x_hash_semi TEXT, -- md5(Number + Unit) + x_hash_exact TEXT, -- md5(编码前9位 + 名称归一 + 单位归一) —— 决策27(2026-10-10):编码只比前9位(后3位是顺序码);不含项目特征 Attr + x_hash_semi TEXT, -- md5(编码前9位 + 单位归一)(决策 27 前=全编码+单位;名称护栏在 match.py) + x_setkey TEXT, -- 字集键(决策27):sort(名称归一)+'|'+单位归一 ——「钢筋混凝土」=「混凝土钢筋」的不按排序等价命中 x_seq INTEGER, x_period_start_m INTEGER, -- 期次起(从批次继承,_ensure_period 回填) x_period_end_m INTEGER -- 期次止 ); CREATE INDEX IF NOT EXISTS ix_bill_exact_pe ON bills(x_hash_exact); +CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey); -- 字集精确档(决策 27) CREATE INDEX IF NOT EXISTS ix_bill_batch ON bills(batch_id); CREATE INDEX IF NOT EXISTS ix_bill_uw ON bills(uw_id); -- 原数据/单位工程归集按 uw 取清单(2026-10-07) @@ -206,12 +208,14 @@ CREATE TABLE IF NOT EXISTS lmes( x_unit_norm TEXT, x_hash_exact TEXT, -- md5(Name归一 + Spec归一 + Unit归一) x_hash_semi TEXT, -- md5(Name归一 + Unit归一) 次精确档(2026-10-08 主人定:同名同单位、规格不同的可比价) + x_setkey TEXT, -- 字集键(决策27):sort(名称+规格归一)+'|'+单位归一 —— 不按排序的整体等价命中 x_period_start_m INTEGER, -- 期次起(从批次继承) x_period_end_m INTEGER, -- 期次止 UNIQUE(batch_id, x_hash_exact) ); CREATE INDEX IF NOT EXISTS ix_lme_exact ON lmes(x_hash_exact); CREATE INDEX IF NOT EXISTS ix_lme_semi ON lmes(x_hash_semi); -- 次精确档(2026-10-08) +CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey); -- 字集精确档(决策 27) CREATE INDEX IF NOT EXISTS ix_lme_batch ON lmes(batch_id); CREATE INDEX IF NOT EXISTS ix_lme_num ON lmes(batch_id, Number); -- 消耗量 join 按编码取工料机(2026-10-07,此前每行全表扫) diff --git a/造价审核/app/ui/workbench.html b/造价审核/app/ui/workbench.html index 644a8a5..724434b 100644 --- a/造价审核/app/ui/workbench.html +++ b/造价审核/app/ui/workbench.html @@ -19,9 +19,6 @@ body{margin:0;font:13px/1.5 -apple-system,"Segoe UI","Microsoft YaHei",sans-seri .tabmid #sinfo{color:var(--muted);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .tabmid #msg{font-size:12px;color:#1e8e3e;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .tabright{display:flex;align-items:center;gap:8px;margin-left:auto} -/* 顶栏右侧纵排:「打开项目」在上,「询价附件」紧贴其正下方(2026-10-09 主人定) */ -.inqstack{display:inline-flex;flex-direction:column;gap:4px;align-items:stretch;margin:4px 0} -.inqstack .btn{margin:0;white-space:nowrap} .tabs .btn{padding:4px 10px;font-size:12px;line-height:1.3} .wrap{flex:1;display:flex;flex-direction:column;min-height:0;overflow:hidden} .panel{flex:1 1 auto;min-height:0;overflow:auto;display:none;background:#fff} @@ -236,18 +233,17 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
- - 最近审核 - 后台管理 + - - - - - + 后台管理 + + + 最近审核 +
@@ -311,7 +307,7 @@ body.grptree-dragging{cursor:col-resize !important;user-select:none}
精确度 @@ -587,18 +583,20 @@ async function doOpen(){ if(!r.ok){ $('omsg').textContent=r.msg; return; } SID=r.session_id; try{ localStorage.setItem('wb_sid', SID); }catch(e){} // 记住上次审核的会话(切页回来恢复用) + loadAdopt(); // 决策 28:徽章随会话切(新会话=空目录) // 保存本工程选中的专业(供类似清单按专业分组) try{ await J('/api/session/setting',{method:'POST',headers:{'Content-Type':'application/json'}, body:JSON.stringify({scope:`session:${SID}`,k:'profession',v:$('oprof').value||''})}); }catch(e){} - $('sinfo').innerHTML=`${esc($('oname').value||f.name)} · 基准 ${esc($('oper').value)} · 清单 ${r.n_bill} · 定额 ${r.n_norm} · 工料机 ${r.n_lme}`; + $('sinfo').innerHTML=`${esc($('oname').value||f.name)}`; // 2026-10-10 主人定:只留名称(基准/条数尾串取消) $('omask').classList.remove('on'); await loadLme(); tab('p3'); // 2026-09-30:打开后先看「原数据」 $('msg').textContent=r.msg; } -/* ---------- 询价附件(2026-10-09 改版 主人定)---------- - 口径:对比框**工料机行**点「采纳」时,该行跟随的附件收进全局目录(按内容 sha 去重, +/* ---------- 询价附件(2026-10-09 改版;2026-10-10 决策 28 改**会话级** 主人定)---------- + 口径:对比框**工料机行**点「采纳」时,该行跟随的附件记到**当前会话**名下(按内容 sha 去重, 一个附件被采纳多次只显示一个);右侧项目名与采纳备注同源。 + 切会话=切目录(该会话上次收的还在);删会话连带撤事件;没打开项目=空目录。 2026-10-09 晚:旧「后台绑定」口径的行标/行高亮(询价小标)整套撤掉—— 工作台不再展示后台绑定关系,绑定是后台的事;目录里只看采纳。 */ @@ -607,7 +605,7 @@ let ADOPT={atts:[],projs:[],sel:'',checked:new Set()}; async function loadAdopt(){ try{ - const d=await J('/api/adopt/list'); + const d=await J('/api/adopt/list'+(SID?('?sid='+SID):'')); // 决策 28:只取当前会话的 if(d&&d.ok){ ADOPT.atts=d.atts||[]; ADOPT.projs=d.projs||[]; if(ADOPT.sel && !ADOPT.atts.some(a=>a.sha===ADOPT.sel)) ADOPT.sel=''; @@ -617,7 +615,8 @@ async function loadAdopt(){ }catch(e){} } -function openInq(){ +async function openInq(){ + await loadAdopt(); // 打开时现取:会话切换/别处采纳都最新 ADOPT.sel=''; // 打开停在根目录:右侧显示全部项目名称 ADOPT.checked=new Set(ADOPT.atts.map(a=>a.sha)); // 每次打开默认全选(主人定) renderInqTree(); renderInqRight(); updInqCnt(); @@ -629,7 +628,10 @@ $('inqmask').onclick=e=>{ if(e.target===$('inqmask')) closeInq(); }; function renderInqTree(){ const el=$('inqTree'); if(!ADOPT.atts.length){ - el.innerHTML='
还没有收进附件。
在对比框点工料机行的「采纳」,该行跟随的附件就会收进这里。
'; + el.innerHTML='
' + +(!SID?'还没打开项目。
打开项目后,在对比框点工料机行的「采纳」,该行跟随的附件就归到这个会话名下。' + :'这个会话还没有收进附件。
在对比框点工料机行的「采纳」,该行跟随的附件就会收进这里。') + +'
'; return; } const allOn=ADOPT.checked.size===ADOPT.atts.length; @@ -769,19 +771,30 @@ function curPrice(){ const v = parseFloat(tr.dataset.price); return isNaN(v)?null:v; } function renderHist(){ - const tiers = $('htier').value==='all' ? ['精确','次精确','模糊'] - : ($('htier').value==='e' ? ['精确'] : ['精确','次精确']); + const tiers = $('htier').value==='all' ? ['精确','次精确','字集','模糊'] + : ($('htier').value==='e' ? ['精确'] : ['精确','次精确','字集']); // 检索模式(B):行没有匹配档位,精确度条件不适用;比对模式照旧按档位过滤 let rows = HINDEP ? HROWS.slice() : HROWS.filter(x=>tiers.includes(x.tier)); // 结果关键字搜索:名称/项目特征(规格)/单位,空格分词 AND;直径符号变体折叠(φ/Φ/ϕ/⌀/Ø 一视同仁, - // 与后端 _kw_fold 同款 —— 2026-10-08 主人报「Φ12mm 搜不出来」:库里大写 Φ 与手输小写 φ 互不命中) + // 与后端 _kw_fold 同款 —— 2026-10-08 主人报「Φ12mm 搜不出来」:库里大写 Φ 与手输小写 φ 互不命中)。 + // 2026-10-10 决策 27:不按排序——中文词拆单字逐字在场(「混凝土钢筋」命中「钢筋混凝土」), + // 字母数字段(C30、400、P.O)保持原样子串;特征里的排序序号(1、 2. (3) a)①)剥掉不参与(与后端 norm_attr 同款)。 const fold=s=>(s||'').toLowerCase().replace(/[ϕ⌀ø]/g,'φ'); + // 序号剥离在 fold 之后(保证 [a-z] 能命中大写字母);与后端 _ORD 同一套规则 + const stripOrd=s=>(s||'').replace(/[①-⑳]/g,'').replace(/[((]\d{1,3}[))]/g,'') + .replace(/(?{ - const hay=fold(((x.name||'')+'\n'+(x.attr||'')+'\n'+(x.spec||'')+'\n'+(x.unit||''))); - return toks.every(t=>hay.includes(t)); + const hay=fold(x.name||'')+'\n'+stripOrd(fold((x.attr||'')+'\n'+(x.spec||'')))+'\n'+fold(x.unit||''); + return toks.every(t=>{ + for(const r of (t.match(/[a-z0-9φ][a-z0-9φ./*\-]*/g)||[])) if(!hay.includes(r)) return false; + for(const ch of new Set(t.replace(/[a-z0-9φ./*\-]/g,''))) if(!hay.includes(ch)) return false; + return true; + }); }); } const s=$('hsort').value; @@ -812,7 +825,7 @@ function renderHist(){ const tg=(!isLme && x.bill_id) ? `+` : ''; - const tdbadge=`${x.tier}`; + const tdbadge=`${x.tier}`; const body = isLme ? `${seq0+i+1}` + `${esc(x.src||'—')}` @@ -837,7 +850,7 @@ function renderHist(){ + `${ell(x.region,'—')}` + `${ell(x.period)}${num(x.sim,2)}` + `${op.join(' · ')}`; - return `${isLme?'':`${tg}`}${body}`; + return `${isLme?'':`${tg}`}${body}`; }).join('')||`${HINDEP?(isLme?'没有符合 条件+关键词 的入库工料机/价格':'没有符合 条件+关键词 的入库清单'):'没有命中的历史项'}`; // 统计(命中数角标已按主人 10-08 要求删除) const vs=rows.map(x=>x.price).filter(v=>v!=null).sort((a,b)=>a-b); @@ -911,16 +924,19 @@ async function tgHist(el,bid){ let htipT=0, tipTd=null; const htip=document.createElement('div'); htip.id='htip'; document.body.appendChild(htip); function hideHistTip(){ clearTimeout(htipT); tipTd=null; htip.style.display='none'; } -function showHistTip(x, td){ +function showHistTip(x, td, lmeOnly){ + // lmeOnly(项目工料机结果行,2026-10-10 主人定):只显示完整名称,不弹项目特征/定额 htip.innerHTML = '
'+esc(x.name||'')+'
' - + '
' + (x.attr ? esc(fmtAttr(x.attr)) : '(无项目特征)') + '
' - + '
定额(编码 / 名称)
读取中…
'; + + (lmeOnly ? '' : + '
' + (x.attr ? esc(fmtAttr(x.attr)) : '(无项目特征)') + '
' + + '
定额(编码 / 名称)
读取中…
'); const r=td.getBoundingClientRect(); htip.style.visibility='hidden'; htip.style.display='block'; const L=Math.min(window.innerWidth-htip.offsetWidth-10, Math.max(6, r.left)); let T=r.bottom+4; if(T+htip.offsetHeight>window.innerHeight-8) T=Math.max(8, r.top-htip.offsetHeight-6); htip.style.left=L+'px'; htip.style.top=T+'px'; htip.style.visibility='visible'; + if(lmeOnly) return; if(!x.bill_id){ htip.querySelector('.htip-norms').innerHTML='
(此行无定额)
'; return; } histNorms(x.bill_id).then(ns=>{ const box=htip.querySelector('.htip-norms'); if(!box) return; @@ -936,7 +952,7 @@ $('htb').addEventListener('mouseover', e=>{ if(!tr || !tr.dataset.i) return; const x=VISIBLE_ROWS[+tr.dataset.i]; if(!x) return; clearTimeout(htipT); - htipT=setTimeout(()=>{ tipTd=td; showHistTip(x, td); }, 250); + htipT=setTimeout(()=>{ tipTd=td; showHistTip(x, td, tr.dataset.lme==='1'); }, 250); }); $('htb').addEventListener('mouseout', e=>{ const td=e.target.closest('td'); @@ -1092,8 +1108,8 @@ async function recOpen(sid,keep){ const m=RECMAP[sid]||{}; SID=sid; try{ localStorage.setItem('wb_sid', sid); }catch(e){} // 记住上次审核的会话 - const p=(m.period_from!=null)?(yms(m.period_from)+(m.period_to&&m.period_to!==m.period_from?'~'+yms(m.period_to):'')):''; - $('sinfo').innerHTML=`${esc(m.name||'')}${p?' · 基准 '+esc(p):''} · 清单 ${m.n_bill??0} · 定额 ${m.n_norm??0} · 工料机 ${m.n_lme??0}`; + loadAdopt(); // 决策 28:切会话=切附件目录(该会话上次收的还在) + $('sinfo').innerHTML=`${esc(m.name||'')}`; // 2026-10-10 主人定:只留名称(基准/条数尾串取消) if(!keep) closePops(); await loadLme(); tab((document.querySelector('.tab.on')||{dataset:{p:'p0'}}).dataset.p); $('msg').textContent='已切到该会话'; @@ -1408,7 +1424,7 @@ async function initFilters(){ calcArea(); updAreaBtn(); updPerBtn(); } initFilters(); -loadAdopt(); // 顶栏「询价附件」常驻按钮:进页面就取采纳目录(计数即时可见,不依赖先打开项目) +loadAdopt(); // 顶栏「询价附件」常驻按钮:进页面先取一次(此时无会话=空);打开/切会话由 doOpen/recOpen 再取 /* 从会话管理页 /workbench.html?sid=N 直接打开某个会话(management 页「打开」用)。 2026-10-07 主人报「从后台/最近审核切回工作台,原数据消失」:URL 没有 sid 时, @@ -1432,17 +1448,16 @@ async function initFromUrl(){ // 2026-10-07 主人定:从「最近审核」点「打开」=**重新解析刷新**(哪怕哈希一致), // 旧口径数据不留在屏上;原文件已不在的老会话退回直接切过去,不打断。 // (「打开工程」/后台导入本就每次真解析;页面普通刷新恢复 wb_sid 不算“打开”,不重解析。) - let repMsg = ''; if(fromUrl){ try{ const r = await J('/api/session/reparse', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({session_id: sid})}); - if(r && r.ok){ await recLoad(); repMsg = '已重新解析刷新:清单 ' + r.n_bill + ' 条、定额 ' - + r.n_norm + ' 条、工料机 ' + r.n_lme + ' 条'; } + // 2026-10-10 主人定:完成提示改右下角浮层,只报条数(不再顶栏长句) + if(r && r.ok){ await recLoad(); + toast('清单 ' + r.n_bill + ' 条、定额 ' + r.n_norm + ' 条、工料机 ' + r.n_lme + ' 条'); } }catch(e){} } await recOpen(sid, true); - if(repMsg) $('msg').textContent = repMsg; if(['p0','p1','p2','p3'].includes(savedTab) && savedTab !== 'p3') tab(savedTab); if(!fromUrl) $('msg').textContent = '已恢复上次审核:《' + (($('sinfo').querySelector('b')||{}).textContent || '') + '》(「最近审核」页可切换其他工程)';