Files
pricing_review/release/testdata/panel_server.py

333 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""testdata 控制台(本地网页版,2026-10-09)。
双击「启动testdata.bat」自动打开浏览器:http://127.0.0.1:8412
填参数 → 开始生成 → 实时日志;停止 = 软暂停;删除 = 分块删除全部测试数据;
版本对齐 = 测试库换到别的母体后,把测试批次解析器版本对齐到该母体当前版本。
生成写入独立测试库 history-test.db / session-test.db,真实库零污染。
只在本机 127.0.0.1 监听。不改任何软件代码。
"""
import json
import os
import subprocess
import sys
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import gen_testdata as G # noqa: E402
G._safe_stdio() # GBK 控制台容错(U+200C 等)
PORT = 8412
_state = {"proc": None, "mode": None}
_lock = threading.Lock()
LOG = []
def log(msg):
LOG.append("%s %s" % (__import__("time").strftime("%H:%M:%S"), msg))
if len(LOG) > 2000:
del LOG[:500]
try:
print(msg, flush=True)
except Exception:
pass
def running():
p = _state["proc"]
return p is not None and p.poll() is None
def _drain(proc):
try:
for line in iter(proc.stdout.readline, ""):
if not line:
break
log(line.rstrip())
except Exception:
pass
def start_sub(mode, cfg):
with _lock:
if running():
return False, "已有任务在跑,请先停止。"
args = [sys.executable, "-u", os.path.join(HERE, "gen_testdata.py")]
if mode == "run":
cfgpath = os.path.join(HERE, "run_cfg.json")
with open(cfgpath, "w", encoding="utf-8") as f:
json.dump(cfg, f, ensure_ascii=False, indent=2)
args += ["--run", cfgpath]
elif mode == "delete":
args += ["--delete", "--yes"]
else:
return False, "未知操作"
try:
if os.path.exists(G.PAUSE_FLAG):
os.remove(G.PAUSE_FLAG)
except Exception:
pass
proc = subprocess.Popen(args, cwd=HERE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True,
encoding="utf-8", errors="replace")
_state["proc"] = proc
_state["mode"] = mode
threading.Thread(target=_drain, args=(proc,), daemon=True).start()
return True, "已启动:%s" % mode
def stop_sub():
with _lock:
if not running():
return "没有在跑的任务。"
open(G.PAUSE_FLAG, "w").close() # 软暂停:当前份做完即退出
return "已发软暂停信号:当前这一份做完就安全停(不丢已提交进度)。"
class H(BaseHTTPRequestHandler):
def _send(self, code, body, ctype="application/json; charset=utf-8"):
raw = body if isinstance(body, bytes) else json.dumps(
body, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def log_message(self, *a):
pass
def do_GET(self):
if self.path in ("/", "/index.html"):
self._send(200, PAGE.encode("utf-8"), "text/html; charset=utf-8")
elif self.path == "/api/stats":
dd = G.find_data_dir()
try:
s = G.stats_of(dd) if dd else {"data_dir": None}
except Exception as e:
s = {"data_dir": dd, "error": str(e)}
s["running"] = running()
s["mode"] = _state["mode"] if running() else None
self._send(200, s)
elif self.path == "/api/log":
self._send(200, {"lines": LOG[-400:], "running": running()})
else:
self._send(404, {"ok": False, "msg": "not found"})
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
try:
body = json.loads(self.rfile.read(n).decode("utf-8")) if n else {}
except Exception:
body = {}
if self.path == "/api/dir":
p = (body.get("data_dir") or "").strip()
if p and (os.path.exists(os.path.join(p, "history.db"))
or os.path.exists(os.path.join(p, G.TEST_H))):
G.set_data_dir(p)
self._send(200, {"ok": True, "data_dir": p})
else:
self._send(200, {"ok": False,
"msg": "目录里没有 history.db / history-test.db"})
elif self.path == "/api/run":
cfg = {k: G.DEFAULTS.get(k) for k in G.DEFAULTS}
cfg.update({k: v for k, v in body.items() if k in G.DEFAULTS})
cfg["data_dir"] = G.find_data_dir()
ok, msg = start_sub("run", cfg)
self._send(200, {"ok": ok, "msg": msg})
elif self.path == "/api/align":
dd = G.find_data_dir()
if not dd:
self._send(200, {"ok": False, "msg": "找不到数据目录"})
else:
try:
n = G.align_testdata(dd, log=log)
self._send(200, {"ok": True, "msg": "已对齐 %d 个批次" % n})
except Exception as e:
self._send(200, {"ok": False, "msg": str(e)})
elif self.path == "/api/delete":
ok, msg = start_sub("delete", {})
self._send(200, {"ok": ok, "msg": msg})
elif self.path == "/api/stop":
self._send(200, {"ok": True, "msg": stop_sub()})
else:
self._send(404, {"ok": False, "msg": "not found"})
PAGE = """<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8">
<title>testdata · 测试数据生成器</title>
<style>
:root{--bg:#f5f6f8;--card:#fff;--line:#e2e5ea;--txt:#1f2329;--sub:#646a73;
--pri:#245bdb;--pri-h:#1c4fc4;--ok:#2ea121;--warn:#d83931;--chip:#eef3ff}
*{box-sizing:border-box;margin:0;padding:0}
body{font:14px/1.6 "Microsoft YaHei",system-ui,sans-serif;background:var(--bg);
color:var(--txt);padding:24px;max-width:1080px;margin:0 auto}
h1{font-size:20px;margin-bottom:4px}
.sub{color:var(--sub);font-size:12px;margin-bottom:16px}
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;
padding:16px 20px;margin-bottom:14px}
.card h2{font-size:15px;margin-bottom:12px;padding-left:8px;border-left:3px solid var(--pri)}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px 16px}
.grid .w2{grid-column:span 2}
label{display:block;font-size:12px;color:var(--sub);margin-bottom:2px}
input[type=number],input[type=text],input[type=month],select{
width:100%;padding:5px 8px;border:1px solid var(--line);border-radius:4px;font-size:13px;
background:#fff;color:var(--txt)}
input:focus{outline:none;border-color:var(--pri)}
.pair{display:flex;gap:6px;align-items:center}
.pair input{width:70px}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px}
button{padding:7px 22px;border:none;border-radius:4px;font-size:14px;cursor:pointer;
color:#fff;background:var(--pri)}
button:hover{background:var(--pri-h)}
button.gray{background:#8f959e}button.gray:hover{background:#7a808a}
button.red{background:var(--warn)}button.red:hover{background:#b72e27}
button:disabled{opacity:.45;cursor:not-allowed}
#dd{width:420px}
#log{background:#0d1117;color:#c9d1d9;font:12px/1.55 Consolas,monospace;
height:300px;overflow-y:auto;padding:12px;border-radius:6px;white-space:pre-wrap}
.kpis{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}
.kpi{background:var(--chip);border-radius:6px;padding:6px 12px;font-size:12px}
.kpi b{color:var(--pri);font-size:14px}
.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)}
@media(max-width:860px){.grid{grid-template-columns:repeat(2,1fr)}}
</style></head><body>
<h1>testdata · 测试数据生成器</h1>
<div class="sub">数据目录自动跟随母体(release 包改名/挪动均可)。生成写入<b>独立测试库</b>
history-test.db / session-test.db(首次自动从真实库克隆底子),<b>真实库零污染</b>——
对接软件时把测试库改名换上即可;换到别的母体后点一次「版本对齐」,删除只是兜底手段。</div>
<div class="card"><h2>数据目录</h2>
<div class="row">
<input type="text" id="dd" placeholder="自动探测……">
<button class="gray" onclick="saveDir()">保存</button>
<span id="ddmsg" class="sub"></span></div></div>
<div class="card"><h2>一、后台数据(history-test.db)</h2>
<div class="sec-h">入库项目</div>
<div class="grid">
<div><label>项目个数</label><input type="number" id="n_project" value="10" min="0"></div>
<div><label>清单条数/项目(约)</label><div class="pair">
<input type="number" id="bill_lo" value="300"><span>~</span>
<input type="number" id="bill_hi" value="800"></div></div>
<div><label>定额条数/清单</label><div class="pair">
<input type="number" id="norm_lo" value="3"><span>~</span>
<input type="number" id="norm_hi" value="5"></div></div>
<div><label>工料机条数/定额</label><div class="pair">
<input type="number" id="res_lo" value="3"><span>~</span>
<input type="number" id="res_hi" value="5"></div></div>
<div><label>询价附件份数/项目</label><input type="number" id="inq_per_project" value="4" min="0"></div>
<div><label>工料机附件绑定率 %</label><input type="number" id="bind_rate" value="50" min="0" max="100"></div>
</div>
<div class="sec-h">市场价</div>
<div class="grid">
<div><label>份数</label><input type="number" id="n_market" value="20" min="0"></div>
<div><label>每份条数(约)</label><div class="pair">
<input type="number" id="market_lo" value="500"><span>~</span>
<input type="number" id="market_hi" value="800"></div></div>
<div><label>带附件率 %</label><input type="number" id="market_attach_rate" value="80" min="0" max="100"></div>
</div>
<div class="sec-h">信息价</div>
<div class="grid">
<div><label>份数</label><input type="number" id="n_info" value="20" min="0"></div>
<div><label>每份条数(约)</label><div class="pair">
<input type="number" id="info_lo" value="500"><span>~</span>
<input type="number" id="info_hi" value="800"></div></div>
<div><label>带附件率 %</label><input type="number" id="info_attach_rate" value="90" min="0" max="100"></div>
</div></div>
<div class="card"><h2>二、工作台数据(session-test.db)</h2>
<div class="grid">
<div class="w2"><label class="chk"><input type="checkbox" id="session_linked" checked
onchange="linkedChange()"> 与后台项目联动(每份测试项目自动镜像 1 份会话,数量=项目数)</label></div>
<div><label>独立会话份数(不联动时生效)</label><input type="number" id="n_session" value="5" min="0"></div>
<div><label>清单条数/会话(独立时)</label><div class="pair">
<input type="number" id="sbill_lo" value="150"><span>~</span>
<input type="number" id="sbill_hi" value="400"></div></div>
</div></div>
<div class="card"><h2>三、时间跨度</h2>
<div class="grid">
<div><label>期次起(年-月)</label><input type="text" id="from_ym" value="2024-01" placeholder="2024-01"></div>
<div><label>期次止(年-月)</label><input type="text" id="to_ym" value="2026-10" placeholder="2026-10"></div>
</div></div>
<div class="card"><h2>操作</h2>
<div class="row">
<button id="bRun" onclick="doRun()">开始生成</button>
<button class="gray" onclick="doStop()">停止(软暂停)</button>
<button class="red" onclick="doDel()">删除全部测试数据</button>
<button class="gray" onclick="doAlign()">版本对齐</button>
<button class="gray" onclick="loadStats()">刷新统计</button>
</div>
<div class="kpis" id="kpis"></div></div>
<div class="card"><h2>日志</h2><div id="log">就绪。</div></div>
<script>
const IDS=["n_project","bill_lo","bill_hi","norm_lo","norm_hi","res_lo","res_hi",
"inq_per_project","bind_rate","n_market","market_lo","market_hi","market_attach_rate",
"n_info","info_lo","info_hi","info_attach_rate","n_session","sbill_lo","sbill_hi"];
function cfg(){
const c={};IDS.forEach(i=>c[i]=parseInt(document.getElementById(i).value)||0);
c.session_linked=document.getElementById("session_linked").checked;
c.from_ym=document.getElementById("from_ym").value||"2024-01";
c.to_ym=document.getElementById("to_ym").value||"2026-10";
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",{});}
async function doDel(){if(!confirm("确认真删除全部「测试」前缀的模拟数据?此操作不可恢复!"))return;
await post("/api/delete",{});poll();}
async function doAlign(){const r=await post("/api/align",{});alert(r.msg||"完成");}
async function saveDir(){const r=await post("/api/dir",{data_dir:document.getElementById("dd").value});
document.getElementById("ddmsg").textContent=r.ok?"已保存":(r.msg||"失败");loadStats();}
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();
if(s.data_dir)document.getElementById("dd").value=s.data_dir;
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;}
let last=0;
async function poll(){const r=await(await fetch("/api/log")).json();
if(r.lines.length!==last){const el=document.getElementById("log");
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);}
linkedChange();loadStats();poll();
</script></body></html>"""
def main():
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
log("testdata 控制台:http://127.0.0.1:%d" % PORT)
threading.Timer(0.6, lambda: webbrowser.open("http://127.0.0.1:%d" % PORT)).start()
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()