feat(workbench): 工程量公式、另存为导出与字段编辑历史等多项功能

This commit is contained in:
lianjianwei2024
2026-10-17 14:15:07 +08:00
parent ca19d9f929
commit a4772bc97b
32 changed files with 2099 additions and 1532 deletions

View File

@@ -6,7 +6,7 @@ M5 窗口壳:双击这个脚本 → 直接弹出「造价审核」软件窗口
排错:每一步都会打印,并同时写进 造价审核\\data\\launch.log
"""
import os, sys, time, threading, urllib.request, urllib.error, socket, traceback
import os, re, sys, json, time, threading, urllib.request, urllib.error, urllib.parse, socket, traceback
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) # 造价审核/
@@ -33,6 +33,165 @@ ADMIN_URL = "http://127.0.0.1:%d/admin.html?v=%s" % (PORT, _page_ver("admin.html
LOG = os.path.join(ROOT, "data", "launch.log")
# ---------- 原生「另存为」桥(决策 91,2026-10-17 主人定「全部是另存为」)----------
# 壳里的 WebView2 对 JS 的 showSaveFilePicker 支持不稳(实测直接抛错掉进静默下载,
# 文件落到下载目录深处主人找不到)——由 Python 侧接管:页面调
# window.pywebview.api.download_save_as(相对url, 建议名),这里弹**原生另存为对话框**
# (文件名预填 工程名-审核版.原后缀),把本地服务的下载内容写到所选位置。
# 普通浏览器没有这个桥,页面自动落回原有 showSaveFilePicker 分支,互不影响。
_LAST_SAVE_DIR = {"d": ""} # 本次运行记住的上一另存位置(下次同目录打开)
class _BridgeApi:
def export_save_as(self, session_id, suggested_name=""):
"""决策 92(主人定流程):点导出=①先弹原生另存为选路径(此刻还不生成,大工程不再干等)
→②后台线程生成+分块写盘(逐条目进度经 evaluate_js 推给页面进度条)
→③完成/失败也推给页面(模态收尾或后台 toast)。"""
try:
sid = int(session_id)
except Exception:
return {"ok": False, "msg": "会话参数不合法"}
name = (suggested_name or "").strip()
if not name:
try:
req = urllib.request.urlopen(
"http://127.0.0.1:%d/api/session/export/meta?session_id=%d" % (PORT, sid), timeout=15)
j = json.loads(req.read().decode("utf-8", "replace"))
if j.get("ok"):
name = j.get("name") or name
except Exception:
pass
if not name:
name = "工程导出.cos4"
import webview
win = webview.windows[0] if webview.windows else None
if win is None:
return {"ok": False, "msg": "窗口未就绪"}
ext = os.path.splitext(name)[1]
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
fd = getattr(webview, "FileDialog", None)
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
save_filename=name, file_types=ftypes)
if not picked:
return {"ok": False, "cancel": True}
p = picked if isinstance(picked, str) else picked[0]
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
threading.Thread(target=self._export_worker, args=(win, sid, p, name), daemon=True).start()
return {"ok": True, "started": True, "path": p, "name": name}
def _push(self, win, payload):
"""进度推给页面(window.__exportProgress 由 workbench 定义;后台与否页面自己决定展示)。"""
try:
win.evaluate_js("window.__exportProgress && window.__exportProgress(%s)"
% json.dumps(payload, ensure_ascii=False))
except Exception:
pass
def _export_worker(self, win, sid, path, name):
token = "x%d" % int(time.time() * 1000000)
base = "http://127.0.0.1:%d" % PORT
stop = threading.Event()
def poller(): # 生成阶段(响应头没回来)轮询逐条目进度
while not stop.is_set():
try:
r = urllib.request.urlopen(
base + "/api/session/export/progress?token=" + token, timeout=5)
j = json.loads(r.read().decode("utf-8", "replace"))
if j.get("total"):
self._push(win, {"phase": "gen", "done": j.get("done", 0),
"total": j.get("total", 0)})
except Exception:
pass
stop.wait(1.0)
pt = threading.Thread(target=poller, daemon=True)
pt.start()
tmp = path + ".part"
try:
self._push(win, {"phase": "gen"})
req = urllib.request.urlopen(base + "/api/session/export?session_id=%d&token=%s" % (sid, token),
timeout=3600)
stop.set() # 响应头到了=生成完毕,轮询停;接下来按字节真实进度
if "json" in (req.headers.get("Content-Type") or "").lower():
j = json.loads(req.read().decode("utf-8", "replace"))
self._push(win, {"done": False, "msg": j.get("msg") or "服务端返回错误"})
return
total = int(req.headers.get("Content-Length") or 0)
done, last = 0, -1
with open(tmp, "wb") as f:
while True:
chunk = req.read(262144)
if not chunk:
break
f.write(chunk)
done += len(chunk)
if total:
pct = int(done * 100 / total)
if pct != last:
last = pct
self._push(win, {"phase": "put", "pct": pct})
if total and done != total:
raise IOError("下载不完整 %d/%d 字节" % (done, total))
os.replace(tmp, path)
_log("已另存为:%s(%d 字节)" % (path, done))
self._push(win, {"done": True, "path": path, "name": os.path.basename(path)})
except Exception as e:
stop.set()
try:
os.remove(tmp)
except OSError:
pass
_log("导出失败:%s\n%s" % (e, traceback.format_exc()))
self._push(win, {"done": False, "msg": str(e)})
finally:
stop.set()
def download_save_as(self, url, suggested_name=""):
try:
if not url or not url.startswith("/") or url.startswith("//"):
return {"ok": False, "msg": "非法下载地址"}
req = urllib.request.urlopen("http://127.0.0.1:%d%s" % (PORT, url), timeout=600)
data = req.read()
if "json" in (req.headers.get("Content-Type") or "").lower():
j = json.loads(data.decode("utf-8", "replace"))
return {"ok": False, "msg": j.get("msg") or "服务端返回错误"}
cd = req.headers.get("Content-Disposition") or ""
name = (suggested_name or "").strip()
m = re.search(r"filename\*=UTF-8''([^;]+)", cd)
if not m:
m = re.search(r'filename="([^"]+)"', cd)
if m:
try:
name = urllib.parse.unquote(m.group(1), errors="replace")
except Exception:
pass
if not name:
name = "下载文件"
import webview
win = webview.windows[0] if webview.windows else None
if win is None:
return {"ok": False, "msg": "窗口未就绪"}
ext = os.path.splitext(name)[1]
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
fd = getattr(webview, "FileDialog", None)
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
save_filename=name, file_types=ftypes)
if not picked:
return {"ok": False, "cancel": True}
p = picked if isinstance(picked, str) else picked[0]
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
with open(p, "wb") as f:
f.write(data)
_log("已另存为:%s(%d 字节)" % (p, len(data)))
return {"ok": True, "path": p, "name": os.path.basename(p)}
except Exception as e:
_log("另存为失败:%s\n%s" % (e, traceback.format_exc()))
return {"ok": False, "msg": str(e)}
def _log(msg):
line = "[%s] %s" % (time.strftime("%H:%M:%S"), msg)
print(line, flush=True)
@@ -65,6 +224,55 @@ def server_healthy():
return False
def _code_mtime():
"""程序代码更新时间——与 api_server._code_mtime 同口径(api_server.py + core/*.py +
server/*.py 的最新 mtime)。启动器拿它和端口上实例自报的版本比,判断是不是旧代码。"""
import glob
files = [os.path.abspath(__file__)]
for sub in ("core", "server"):
files += glob.glob(os.path.join(api_server.ROOT, sub, "*.py"))
mt = 0.0
for f in files:
try:
mt = max(mt, os.path.getmtime(f))
except OSError:
pass
return mt
def remote_code_mtime():
"""端口上健康实例自报的代码时间;报不出来(更老的实例没有 /api/version)→ None=视为过期。"""
import json
try:
r = urllib.request.urlopen("http://127.0.0.1:%d/api/version" % PORT, timeout=2)
j = json.loads(r.read().decode("utf-8"))
return float(j["code_mtime_f"]) if j.get("ok") else None
except Exception:
return None
def kill_port_owner():
"""结束占用本端口的进程——只可能是我们自己的旧实例(单实例互斥保证)。"""
import subprocess
try:
out = subprocess.check_output(["netstat", "-ano", "-p", "TCP"], text=True, errors="replace")
except Exception:
return False
pids = set()
for line in out.splitlines():
parts = line.split()
if len(parts) >= 5 and parts[1] == "127.0.0.1:%d" % PORT and parts[3] == "LISTENING":
pids.add(parts[4])
hit = False
for pid in pids:
try:
subprocess.run(["taskkill", "/PID", pid, "/F"], capture_output=True)
hit = True
except Exception:
pass
return hit
def wait_ready(timeout=15):
for _ in range(int(timeout / 0.25)):
try:
@@ -166,8 +374,28 @@ def main():
_log("端口 %d 被占但服务无响应(疑似旧进程收尾中),2 秒后重试 %d/5" % (PORT, attempt + 1))
time.sleep(2)
if healthy:
_log("端口 %d 已有健康服务在跑,直接复用" % PORT)
reused = True
# 2026-10-17 主人需求「重启后永远是最新程序」:端口上的健康实例,代码比磁盘旧
# (或老到不认识版本接口)→ 自动结束它、加载新代码再开窗;同版本才复用。
remote = remote_code_mtime()
local = _code_mtime()
if remote is not None and remote >= local - 1: # 1 秒容差(mtime 秒级)
_log("端口 %d 服务已是最新版本,直接复用" % PORT)
reused = True
else:
_log("端口 %d 上是旧版本程序(代码时间 %s,磁盘已是 %s),自动升级重启…" % (
PORT,
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(remote)) if remote else "未知(更老的实例)",
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(local))))
kill_port_owner()
for _ in range(40): # 最多 10 秒等端口让出
if not port_in_use():
break
time.sleep(0.25)
if port_in_use():
_log("旧实例未能结束(端口仍被占),请到任务管理器结束 python.exe 后重试")
print("旧版本实例结束失败,请到任务管理器结束 python.exe 后再双击本文件", flush=True)
return 1
_log("旧实例已结束,加载新代码…")
elif port_in_use():
_log("服务启动失败:端口 %d 被占且多次探活无响应(残留进程),请到任务管理器结束 python.exe 后重试" % PORT)
print("端口 %d 被残留进程占用且无响应,请到任务管理器结束 python.exe 后再双击本文件" % PORT, flush=True)
@@ -208,6 +436,7 @@ def main():
width=1440, height=900, min_size=(1100, 700),
text_select=True, # 允许选中复制表格里的文字
confirm_close=True,
js_api=_BridgeApi(), # 原生另存为桥(决策 91):页面导出/附件一律弹系统保存框
)
except Exception as e:
_log("窗口创建失败:%s" % e)