feat(match): 落地搜索匹配口径四件套与次精确名称护栏,同步字集键入库及测试面板改进

This commit is contained in:
lianjianwei2024
2026-10-10 14:58:13 +08:00
parent a3697ba271
commit 6de1370ce5
12 changed files with 940 additions and 286 deletions

View File

@@ -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}
# ---------------- 分块删除 ----------------

View File

@@ -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(首次自动从真实库克隆底子),<b>真实库零污染</b>——
对接软件时把测试库改名换上即可;换到别的母体后点一次「版本对齐」,删除只是兜底手段。</div>
<div id="banner" class="banner"></div>
<div class="card"><h2>数据库</h2>
<div class="row" style="margin-top:0">
<span class="dblab ref">参考数据库</span>
@@ -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 '<div class="kpi">'+t+' <b'+(cls?' class="'+cls+'"':'')+'>'+v+'</b></div>';}
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='<tr><td>暂无数据(数据目录未就绪)</td></tr>';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='<tr><th>指标</th><th>参考库 history</th><th>测试库 history-test</th><th>参考库 session</th><th>测试库 session-test</th></tr>';
HH.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>'+fmt((t.ref_h||{})[k])
+'</td><td>'+fmt((t.test_h||{})[k])+'</td><td>—</td><td>—</td></tr>';});
SS.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>—</td><td>—</td><td>'+fmt((t.ref_s||{})[k])
+'</td><td>'+fmt((t.test_s||{})[k])+'</td></tr>';});
HH.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>'+fmt((t.ref_h||{})[k],occH)
+'</td><td>'+fmt((t.test_h||{})[k],occTH)+'</td><td>—</td><td>—</td></tr>';});
SS.forEach(([k,n])=>{h+='<tr><td>'+n+'</td><td>—</td><td>—</td><td>'+fmt((t.ref_s||{})[k],occS)
+'</td><td>'+fmt((t.test_s||{})[k],occTS)+'</td></tr>';});
if(occ.size)h+='<tr><td colspan="5" style="color:#d83931;text-align:left">⚠ 以下库被占用(造价审核软件打开中或正在生成),数字暂不可用,稍后点「刷新统计」:'+[...occ].join("、")+'</td></tr>';
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();
</script></body></html>"""
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)

View File

@@ -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"
}

View File

@@ -2,13 +2,17 @@
chcp 936 >nul
title testdata - <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
cd /d "%~dp0"
rem <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: <20><><EFBFBD><EFBFBD>venv python(<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>batͬ<74><CDAC>) <20>̰<EFBFBD><CCB0>Դ<EFBFBD>python ϵͳpython
rem <20>Ƚ<EFBFBD><C8BD><EFBFBD>ռ<EFBFBD><D5BC> 8412 <20>˿ڵľ<DAB5>ʵ<EFBFBD><CAB5><EFBFBD><EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ǵ<EFBFBD>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD>
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 ʹ<><CAB9> Python: %PY%
echo <20><><EFBFBD><EFBFBD>̨<EFBFBD><CCA8>ַ: http://127.0.0.1:8412
rem <20>˿ڱ<CBBF>ռʱ panel_server <20><><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE>ֱ<EFBFBD>ӿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
echo <20><><EFBFBD><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD>Զ<EFBFBD><D4B6>򿪣<EFBFBD><F2BFAAA3><EFBFBD><EFBFBD>ֶ<EFBFBD><D6B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ĵ<EFBFBD>ַ<EFBFBD><EFBFBD>
"%PY%" panel_server.py
pause