diff --git a/.zcodeignore b/.zcodeignore index 96447c4..ff12495 100644 --- a/.zcodeignore +++ b/.zcodeignore @@ -64,3 +64,8 @@ pip-wheel-metadata/ wheels/ # ----- ↑ 以上为 ZCode 默认排除规则(自定义规则请写在本行下方,不会被同步/恢复改动)----- # 自定义规则写在下方(本行提示可删除) +# 省 token(2026-10-20):临时测试副本/体检截图不进搜索,避免搜到大文件副本 +/CostReview/.pt/ +/CostReview/.pytest_tmp/ +/test/界面体检/out/shots/ +/test/界面体检/out/diffs/ diff --git a/AGENTS.md b/AGENTS.md index cd9e9bc..deabdb2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,10 +3,17 @@ ## 🚫 红线的红线(主人定,2026-10-18,永久有效) **新指令与历史决策冲突时,必须当场指出冲突点,并请主人决策——禁止自行取舍、禁止静默改口。** -凡与历史决策(`决策台账.md`)不一致的改动,动手前必须对照台账列明「与决策 NN 冲突」,等主人拍板后再实施。宁可多问一轮,不可擅自变更已定决策。 +凡与历史决策(`决策台账.md`)不一致的改动,动手前必须对照台账列明「与决策 NN 冲突」,等主人拍板后再实施。宁可多问一轮,不可擅自变更已定决策。**主人维护的只读 Markdown 差异中明确提出的新要求,按下节流程作为本次决策更新台账后执行,不重复请求已给出的决策。** > 来源:2026-10-18 定额工程量编辑口径反复(决策 90/96 ↔ 实际量编辑),因未指出冲突、自行改口造成多轮返工。主人原话:「要是决策前后矛盾,一定要指出来,并且要主人决策,不能你自己决策。凡是和历史决策不一样的。这个是红线的红线。禁区的禁区。」 +## 主人维护的 Markdown:只读差异后执行(2026-10-20 主人定) + +- 凡主人编写、AI 无权修改的 Markdown(包括 `功能清单(主人填写).md`、`系统规格.md`),一律与上一版对比,只读取差异并列出本次新增/修改/取消的任务;不得通读后重列旧任务,空白占位不算任务。 +- 功能清单运行 `python "test/界面体检/清单差异.py"`;系统规格走 spec-diff;其他只读 Markdown 用对应上一版快照对比。无基准时明确说明,不编造差异。原文只读,快照/差异/manifest 可由工具维护。 +- 工作顺序固定为:**读取差异 → 列本次任务 → 增删改决策(注明取代关系)→ 执行 → 验证**。差异中主人明确的新要求就是本次决策,不属于需要重复请示的未决冲突;以本次为准更新旧决策。只有差异自身存在歧义或有未获授权的范围变化才请主人决定,不得自行推断。 +- 历史记录保留追溯,作废/取代处标注新决策;已完成的 AI 状态补记不重新变成任务。未经专项授权不回写主人原文。 + ## 项目记忆文件(改口径先查这里) | 文件 | 用途 | @@ -24,6 +31,15 @@ 4. **排查/测试产生的批次、会话、临时文件,收尾时自己清理**;只删自己建的,主人的数据绝不碰。 5. 采纳/新增内容的填空三分类:**有值填值、没算留空、别人的数据擦掉**;架子(结构)严格照被导出文件自己的原生块克隆,不发明、不清零别人有的结构。 +## 省 token 铁律(2026-10-20 主人授权) + +1. **大文件禁止整读**:超过 20KB 的文件先 `grep -n` 定位,再 `sed -n '起,止p'` 只读相关片段;页面代码只读相关函数,不整读 `workbench.html` / `common.js` / `api_server.py`。 +2. **查决策先看索引**:先查 `决策台账索引.md` 的行号,再只读该条;禁止整读 `决策台账.md`(约 10.7 万 token)。 +3. **界面核对先跑体检**:跑 `test/界面体检`,先读 `out/report.md`;只有失败项才看截图/源码。 +4. **一个任务一个会话**:任务切换或上下文超过约 60k 时,收口开新会话;不在 200 条消息的老会话里继续问。 +5. **思考级别**:日常改动/核对用 high 或 medium;只有根因排查才用 max。 +6. **工具调用合并**:能一个脚本一次打印摘要的,不拆成多次 Bash;输出只打印结论/差异,不打印整文件。 + ## 数值口径速查(详见 术语表.md 与决策台账) - GCL = 清单工程量 ÷ 定额单位数字前缀;系数存后台(x_qty_coef);采纳挂公式 `GCL×系数`(不落数字)。 diff --git a/CostReview/app/core/export_cos.py b/CostReview/app/core/export_cos.py index 2069c2b..0ed38f1 100644 --- a/CostReview/app/core/export_cos.py +++ b/CostReview/app/core/export_cos.py @@ -329,6 +329,60 @@ def _eligible_bill_block(blk): return ' 0 else blk + return (blk.count(" txt.rfind("", 0, pos) + + +def _largest_bill_block(txt, tag=None, prelim=None): + """本项目某单位 XML 内、同标签下**最大最全的合格清单块**(没有则 None)。 + prelim=True/False 可限定分部分项/措施,避免两种清单互相套模板。""" + best, best_score = None, None + for mk in _scan_bills(txt): + if tag and mk["tag"] != tag: + continue + is_pre = (mk["tag"] == "UnitWorksPreliminaryWorkElement" + or _in_prelim(txt, mk["s"])) + if prelim is not None and is_pre != prelim: + continue + blk = txt[mk["s"]:mk["end"]] + if not _eligible_bill_block(blk): + continue + sc = _bill_block_score(blk) + if best_score is None or sc > best_score: + best, best_score = blk, sc + return best + + +def _largest_norm_block(txt): + """块内属性齐全的 Norm 里,取 innards/属性最多的一条(作采纳定额完整模板)。""" + best, best_score = None, None + for nsp in _norm_spans(txt): + if ' NormIdentity="' not in nsp["opentag"] or ' Quantity="' not in nsp["opentag"]: + continue + blk = txt[nsp["s"]:nsp["end"]] + sc = (len(re.findall(r'\b\w+="', nsp["opentag"])), blk.count("<" + _LME), len(blk)) + if best_score is None or sc > best_score: + best, best_score = blk, sc + return best + + +def _largest_lme_row(txt): + """取属性最全的工料机行当模板(各格式属性集不同,不写死)。""" + rows = re.findall(r'<' + _LME + r'\b[^>]*>', txt) + return max(rows, key=lambda t: (len(re.findall(r'\b\w+="', t)), len(t))) if rows else None + + def _bill_xml(b, tag, norms_xml, template=None, txt=None): """新增清单:优先克隆锚点清单的**完整块**——开标签全属性 + innards(费用构成汇总、 工程量表达式行、定额区的 WorkContent 包装、清单级工料机尾表)原样保留,结果值清零、 @@ -349,6 +403,9 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None): if b["Attr"]: want = _restore_attr_breaks(txt, b["Attr"]) if txt else b["Attr"] t = _attr_set(t, "Attr", want) + elif ' Attr="' in t: + # 新增清单没有特征:模板的 Attr 是锚点清单的,不能带(同下方 Remark) + t = _attr_set(t, "Attr", "") if b["src_remark"]: t = _attr_set(t, "Remark", b["src_remark"]) elif ' Remark="' in t: @@ -445,7 +502,7 @@ def _restore_attr_breaks(txt, s): return re.sub(r"[ \t]+(?=\d{1,3}、)", _attr_sep_of(txt), s) -def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): +def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmpls=None): """一份单位工程 xml 的手术。 uwkey = (uwNumber, uwName)——与文件里 匹配 @@ -464,6 +521,7 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): edits = [] # (start, end, replacement) blocks = _scan_bills(txt) norm_tmpl = _full_norm_template(txt) + proj_tmpls = bill_tmpls or {} CLOSE = {"WorkElement": _CLOSE_WE, "UnitWorksPreliminaryWorkElement": _CLOSE_PRE} # ---- ① 按标签数配对(主路径)---- @@ -596,13 +654,17 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): if newn != nsp["opentag"]: edits.append((s0, nsp["e"] + mk["s"], newn)) if napp: - # 决策 106:模板取同清单**属性齐全定额的完整块**(innards 一起克隆), - # 没有再退回全文件模板开标签(旧形态)。 - tmpl = norm_tmpl - for nsp in nspans: # 同清单自己的定额优先(上下文最贴近) - if ' NormIdentity="' in nsp["opentag"]: - tmpl = txt[nsp["s"] + mk["s"]: nsp["end"] + mk["s"]] - break + # 2026-10-20 主人定:先用**本项目范围内最大最全**的合格清单块里的定额模板; + # 没有再退回同清单/全文件模板(旧形态)。 + _pb = proj_tmpls.get(mk["tag"]) + tmpl = _largest_norm_block(_pb) if _pb else None + if not tmpl: + for nsp in nspans: # 同清单自己的定额次选(上下文最贴近) + if ' NormIdentity="' in nsp["opentag"]: + tmpl = txt[nsp["s"] + mk["s"]: nsp["end"] + mk["s"]] + break + if not tmpl: + tmpl = norm_tmpl # 决策 98:采纳定额按原生结构写入——**包 WorkContent**、插在最后一个 # WorkContent 之后(工料机汇总平铺表之前)。此前裸 Norm 插在块尾 # (汇总表和单价计算节点之后),广联达按 schema 解析错位 → @@ -663,7 +725,10 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): agg[cc] = agg.get(cc, 0.0) + float(qq) * nq except (TypeError, ValueError): pass - row_tmpl = txt[dspans[0][0]:dspans[0][1]] if dspans else None + _pb = proj_tmpls.get(mk["tag"]) + row_tmpl = _largest_lme_row(_pb) if _pb else None + if not row_tmpl: + row_tmpl = txt[dspans[0][0]:dspans[0][1]] if dspans else None kid = "" for c in add: vs = "%.4f" % round((agg.get(c, 0.0) / bq if bq else 0.0), 4) @@ -678,10 +743,32 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): # 拼成一段才能保传入序=文件序)。克隆模板:锚点块合格先用锚点,否则取本组任一合格块 # (带费用构成汇总 + 属性齐全定额);全组都不合格退回旧的开标签形态。 srcpos_of = {sp: mk for sp, _b, mk in plist} + # 2026-10-20 主人实测(220kV 电力通道):新增清单的 div_id 与「前一条源清单」不在同一分部时, + # 旧逻辑会把新增块克隆到前一条源清单所属的 DivisionalWorks 里(C20原色透水混凝土落到 + # 顶管井部分,工作台里其实挂在「支撑下挖土」)。落位先按新增行自己的 div_id 找**同分部** + # 源清单:有前序源清单→插在它后面;没有前序→插在同分部第一条源清单之前; + # 同分部没有源清单才退回旧的全局锚点。 + same_div = {} + for sp, bb, mk in plist: + same_div.setdefault(bb.get("div_id"), []).append((sp, mk)) ins_at = {} # (插入位置, 是否块前) → [(bill, 锚点块)...] 传入序 for b in news.get(kind) or []: anc = b.get("_anchor") - if anc == 0 and plist: + cand = same_div.get(b.get("div_id")) or [] + if cand: + before = [x for x in cand if x[0] <= (anc or 0)] + if before: + mk = max(before, key=lambda x: x[0])[1] + key = (mk["end"], False) + else: + mk = min(cand, key=lambda x: x[0])[1] + key = (mk["s"], True) + elif b.get("div_id") is None and plist: + # 无分部(loose)新增行:工作台显示在单位工程树尾;导出件没有“无分部”容器, + # 放到本组最后一条源清单之后,保证“插在最后”不会跑到第一条前面。 + mk = plist[-1][2] + key = (mk["end"], False) + elif anc == 0 and plist: mk = plist[0][2] key = (mk["s"], True) else: @@ -693,18 +780,25 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm): for (pos, _before), group in ins_at.items(): parts = [] for b, tgt in group: - tmpl_blk = None - for mk2 in [tgt] + [x[2] for x in plist]: - blk2 = txt[mk2["s"]:mk2["end"]] - if _eligible_bill_block(blk2): - tmpl_blk = blk2 - break - nn_tmpl = _full_norm_block(tmpl_blk) if tmpl_blk else None + # 2026-10-20 主人定:优先用**本项目范围内同标签最大最全的合格清单块**当骨架 + #(只认块的起止位置,不依赖字段名;广联达/易达骨架不同也通用)。 + tmpl_blk = (proj_tmpls.get(tgt["tag"]) + if (kind == "item" or tgt["tag"] == "UnitWorksPreliminaryWorkElement") + else None) + if not tmpl_blk: + for mk2 in [tgt] + [x[2] for x in plist]: + blk2 = txt[mk2["s"]:mk2["end"]] + if _eligible_bill_block(blk2): + tmpl_blk = blk2 + break + nn_tmpl = _largest_norm_block(tmpl_blk) if tmpl_blk else None if nn_tmpl is None: for nsp in _norm_spans(txt[tgt["s"]:tgt["end"]]): if ' NormIdentity="' in nsp["opentag"]: nn_tmpl = nsp["opentag"] break + if nn_tmpl is None: + nn_tmpl = norm_tmpl norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl, bill_qty=b["Quantity"]) for nn in norms_by_bill.get(b["id"], {}).get("append") or []] @@ -1000,6 +1094,27 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd zin = zipfile.ZipFile(io.BytesIO(src_bytes)) zout = io.BytesIO() entries = zin.infolist() + # 2026-10-20 主人定:先扫全项目,取「同一清单标签下最大最全的合格块」当骨架。 + # 只按清单块起止位置认,不依赖字段名——COS/COS4/广联达/易达骨架不同也能用。 + bill_tmpls, bill_scores = {}, {} + for item in entries: + raw0 = zin.read(item.filename) + try: + txt0, _enc0 = _decode(raw0) + except Exception: + continue + if " bill_scores[tag]: + bill_tmpls[tag] = blk0 + bill_scores[tag] = sc0 if progress: progress(0, len(entries)) with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo: @@ -1027,7 +1142,8 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd for k in keys: plan = unit_plans[k] txt = transform_unit(txt, k, plan["pairs"], plan["news"], - plan["norms_by_bill"], res_by_norm) + plan["norms_by_bill"], res_by_norm, + bill_tmpls=bill_tmpls) # 决策 74(主人口径 5.1/5.2/5.3):本单位汇总=被查找对象—— # 同步行按编码写回本单位汇总(改价/名称规格单位不一致项);采纳新增品类行追加进本单位汇总 added_rows = [] diff --git a/CostReview/app/core/formats/__init__.py b/CostReview/app/core/formats/__init__.py new file mode 100644 index 0000000..937b412 --- /dev/null +++ b/CostReview/app/core/formats/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +"""导出格式适配器包:import 本包即完成各格式注册。""" +from .registry import get_exporter + +from . import swt # noqa: F401 (导入即注册 SWT/SWZ) + +__all__ = ["get_exporter"] diff --git a/CostReview/app/core/formats/registry.py b/CostReview/app/core/formats/registry.py new file mode 100644 index 0000000..cac02a2 --- /dev/null +++ b/CostReview/app/core/formats/registry.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +"""导出格式注册表:按源文件后缀选「骨架/填空」适配器。 + +新格式接入 = 写一个 Exporter(提供 exts + export())并 register, +api_server 不用改;COS4/.COS 仍走现有专用引擎(不在本表)。 +""" +_EXPORTERS = [] + + +def register(exporter): + _EXPORTERS.append(exporter) + return exporter + + +def get_exporter(src_name): + """按源文件名后缀找适配器(不分大小写);没有则返回 None(回落 COS 引擎)。""" + low = (src_name or "").lower() + for e in _EXPORTERS: + if any(low.endswith(ext) for ext in e.exts): + return e + return None diff --git a/CostReview/app/core/formats/skeleton.py b/CostReview/app/core/formats/skeleton.py new file mode 100644 index 0000000..fae92bf --- /dev/null +++ b/CostReview/app/core/formats/skeleton.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- +"""骨架/填空导出的公共层:与格式无关的导出模型 + XML/zip 工具。 + +思路(2026-10-19 主人定): + · **骨架** = 源文件里固定的开头/结尾/固定段(每个格式各准备一份/profile); + · **填空** = 中间重复块(清单/定额/工料机/汇总)由本模块的导出模型统一供给; + · 新格式只写一个 Exporter(标签名/容器定位/汇总公式),不复制取数逻辑。 + +导出模型直接读会话库:清单(含新增/临删/编辑)、定额(含采纳/临删)、 +定额消耗、单位工料机;格式适配器负责把这些值填回自己的骨架。 +""" +import io +import re +import zipfile +from xml.etree import ElementTree as ET + +import import_job as job + +_QTY_EXPR_OK = re.compile(r"^[0-9+\-*/().\s]*$") + + +def f(x): + try: + return float(x) + except Exception: + return None + + +def num(v): + """SWT/XML 数字写法:整数不带小数点,其余最多 6 位(源文件规律)。""" + if v is None: + return None + try: + x = float(v) + except Exception: + return str(v) + if abs(x - round(x)) < 1e-9: + return str(int(round(x))) + return ("%.6f" % x).rstrip("0").rstrip(".") + + +def set_attr(el, name, val): + if val is None: + el.attrib.pop(name, None) + else: + el.attrib[name] = str(val) + + +def max_id(elements, attr, start=0): + n = start + for e in elements: + try: + n = max(n, int((e.attrib.get(attr) or "0").strip() or 0)) + except Exception: + pass + return n + + +def eval_qty(expr, bill_qty, norm_unit): + """GCL 公式求值(GCL=清单量÷定额单位数字前缀;纯数字四则也合法)。""" + s = (expr or "").strip() + for a, b in (("(", "("), (")", ")"), ("+", "+"), ("-", "-"), ("*", "*"), + ("×", "*"), ("÷", "/"), (",", ",")): + s = s.replace(a, b) + s = s.upper() + if not _QTY_EXPR_OK.match(s.replace("GCL", "")): + return None + gcl = round((float(bill_qty) if bill_qty is not None else 0.0) + / job.unit_prefix(norm_unit), 6) + try: + v = float(eval(s, {"__builtins__": {}}, {"GCL": gcl})) + except Exception: + return None + if v != v or v in (float("inf"), float("-inf")): + return None + return round(v, 6) + + +def source_ext(src_name): + m = re.search(r"(\.[A-Za-z0-9]+)$", (src_name or "").strip()) + return m.group(1) if m else ".swt" + + +def build_plan(sc, sid): + """从会话库建一份格式无关的导出模型;返回 None=会话不存在。""" + srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone() + if not srow: + return None + sections = {} + for r in sc.execute("SELECT * FROM s_sections WHERE session_id=?", (sid,)): + sections[r["id"]] = {"id": r["id"], "number": r["Number"] or "", + "name": r["Name"] or "", "total": r["Total"]} + units = [] + for r in sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)): + sec = sections.get(r["section_id"]) if r["section_id"] is not None else None + units.append({"id": r["id"], "number": r["Number"] or "", "name": r["Name"] or "", + "total": r["Total"], "section_number": (sec or {}).get("number", ""), + "bills": [], "lme": []}) + uw_by_id = {u["id"]: u for u in units} + divides = {} + for r in sc.execute("SELECT * FROM s_divides WHERE session_id=?", (sid,)): + divides[r["id"]] = {"id": r["id"], "uw_id": r["uw_id"], "parent_id": r["parent_id"], + "kind": r["Kind"], "number": r["Number"] or "", + "name": r["Name"] or "", "code": r["Code"] or ""} + # 定额:先按 bill 归组,再挂到清单(含采纳/临删/公式求值) + norms_by_bill, res_by_norm = {}, {} + for r in sc.execute("""SELECT n.* FROM s_norms n + JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=? ORDER BY n.id""", (sid,)): + norms_by_bill.setdefault(r["bill_id"], []).append(dict(r)) + for r in sc.execute("""SELECT nr.* FROM s_norm_res nr + JOIN s_norms n ON n.id=nr.norm_id + JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=?""", (sid,)): + res_by_norm.setdefault(r["norm_id"], []).append((r["res_code"], r["qty"])) + for bill_id, ns in norms_by_bill.items(): + for n in ns: + n["res"] = res_by_norm.get(n["id"], []) + n["x_adopt"] = int(n.get("x_adopt") or 0) + n["x_tdel"] = int(n.get("x_tdel") or 0) + # 清单:x_seq 是单位工程内源序(导入时按原件顺序编号) + for r in sc.execute("""SELECT * FROM s_bills WHERE session_id=? + ORDER BY uw_id, + CASE WHEN Kind='prelim' THEN 1 ELSE 0 END, + CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)): + b = dict(r) + b["kind"] = "prelim" if r["Kind"] == "prelim" else "item" + b["x_new"] = int(r["x_new"] or 0) + b["x_tdel"] = int(r["x_tdel"] or 0) + b["norms"] = norms_by_bill.get(r["id"], []) + # 公式定额:按导出时的清单量求值(与 COS 导出同口径) + for n in b["norms"]: + if n.get("qty_expr"): + q = eval_qty(n["qty_expr"], b["Quantity"], n["Unit"]) + if q is not None: + n["Quantity"] = q + if n["Quantity"] is not None and n["Price"] is not None: + n["Total"] = round(float(n["Quantity"]) * float(n["Price"]), 2) + if b["Quantity"] is not None and b["Price"] is not None: + b["Total"] = round(float(b["Quantity"]) * float(b["Price"]), 2) + u = uw_by_id.get(r["uw_id"]) + if u: + u["bills"].append(b) + for r in sc.execute("SELECT * FROM s_lme_uw WHERE session_id=? ORDER BY id", (sid,)): + u = uw_by_id.get(r["uw_id"]) + if u: + u["lme"].append(dict(r)) + lme_proj = {} + for r in sc.execute("SELECT * FROM s_lme_proj WHERE session_id=?", (sid,)): + lme_proj[r["code"]] = dict(r) + return {"srow": srow, "sections": list(sections.values()), "units": units, + "divides": divides, "lme_proj": lme_proj} + + +def load_xml(src_bytes, root_tag="ConstructProject"): + """返回 (root, zip_member, 是否zip)。SWZ/SWT 都可能是裸 XML 或压缩包。""" + if src_bytes[:2] == b"PK": + z = zipfile.ZipFile(io.BytesIO(src_bytes)) + member = None + for n in z.namelist(): + if not n.lower().endswith((".xml", ".swt", ".swz")): + continue + try: + if ("<%s" % root_tag).encode() in z.read(n)[:16384]: + member = n + break + except Exception: + continue + if not member: + raise ValueError("压缩包里没有 %s XML" % root_tag) + return ET.fromstring(z.read(member)), member, True + return ET.fromstring(src_bytes), None, False + + +def save_xml(root, src_bytes, member, is_zip): + data = ET.tostring(root, encoding="utf-8", xml_declaration=True) + if not is_zip: + return data + zin = zipfile.ZipFile(io.BytesIO(src_bytes)) + out = io.BytesIO() + with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo: + for item in zin.infolist(): + raw = zin.read(item.filename) + if item.filename == member: + raw = data + zi = zipfile.ZipInfo(item.filename, date_time=item.date_time) + zi.compress_type = zipfile.ZIP_DEFLATED + zi.external_attr = item.external_attr + zi.create_system = item.create_system + try: + zi.extra = item.extra + except Exception: + pass + zo.writestr(zi, raw) + return out.getvalue() diff --git a/CostReview/app/core/formats/swt.py b/CostReview/app/core/formats/swt.py new file mode 100644 index 0000000..494d242 --- /dev/null +++ b/CostReview/app/core/formats/swt.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +"""SWT/SWZ(深圳市工程造价数据交换标准)的「骨架+填空」导出适配器。 + +骨架:源文件本身(ConstructProject/SingleProject/UnitProject/固定表); +填空:BQItem/MeasureItem/NormItem/ResourceItem/SummaryItem 这些重复块按下表映射。 + +mapping(SWT → 会话库): + BQItem.Code/Name/Feature/Unit/Quantity/Rate/Total/Remark + NormItem.Code/Name/Unit/Quantity/Rate/Total + ResourceItem.Code/Name/Spec/Unit/Rate/Quantity/CostKind + SummaryItem CostCode A/B/C/D/E、B1(安全文明施工费) +2026-10-19 主人定:税率 A —— ResourceItem 只有一个 Rate(不含税预算价), + 不写含税/税率字段(SWT 本来就没有这两列)。 +""" +import copy +import re +from xml.etree import ElementTree as ET + +from .registry import register +from .skeleton import (build_plan, f, load_xml, max_id, num, save_xml, + set_attr, source_ext) + + +def _name_norm(s): + s = (s or "").strip() + for a, b in (("(", "("), (")", ")"), (",", ","), (";", ";"), (" ", "")): + s = s.replace(a, b) + return s + + +def _pick_largest(els, score): + """从源文件同类行里挑**最完整**的当模板(属性多、子结构全)。 + 主人 2026-10-20:自动截取最大清单/定额/工料机骨架,按需要的值回填。""" + return max(els, key=score) if els else None + + +def _bill_score(el): + norms = el.find("Norms") + return (1 if norms is not None else 0, + len(el.findall("BQPriceAnalysisItem")), + len(norms.findall("NormItem")) if norms is not None else 0, + len(list(el.iter("NormResUsageItem"))), + len(el.attrib), sum(1 for _ in el)) + + +def _simple_score(el): + return (len(el.attrib), sum(1 for _ in el), sum(1 for _ in el.iter())) + + +class SWTExporter: + exts = (".swt", ".swz") + + # ---------------- 对外入口 ---------------- + def export(self, sc, sid, src_bytes, srow, progress=None): + plan = build_plan(sc, sid) + if plan is None: + raise ValueError("会话不存在") + root, member, is_zip = load_xml(src_bytes, "ConstructProject") + self._apply(root, plan) + data = save_xml(root, src_bytes, member, is_zip) + ext = source_ext(srow["src_name"]) + name = ((srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程") + "-审核版" + ext + if progress: + progress(1, 1) + return data, name + + # ---------------- 主流程 ---------------- + def _apply(self, root, plan): + src_units = root.findall(".//UnitProject") + by_num, by_name = {}, {} + for el in src_units: + by_num.setdefault((el.get("ProjectID") or "").strip(), []).append(el) + by_name.setdefault((el.get("Name") or "").strip(), []).append(el) + # 2026-10-20 主人定:模板取**本项目范围内**最大最全的同类块(不是只看本单位)。 + all_bq = list(root.iter("BQItem")) + all_ml = [e for e in root.iter("MeasureItem") + if not any(c.tag == "MeasureItem" for c in e)] + all_norm = list(root.iter("NormItem")) + all_res = list(root.iter("ResourceItem")) + res_by_kind = {} + for x in all_res: + k = (x.get("CostKind") or "").strip() + if k not in res_by_kind or _simple_score(x) > _simple_score(res_by_kind[k]): + res_by_kind[k] = x + proj_tpl = {"item": _pick_largest(all_bq, _bill_score), + "measure": _pick_largest(all_ml, _simple_score), + "norm": _pick_largest(all_norm, _simple_score), + "res": _pick_largest(all_res, _simple_score), + "res_by_kind": res_by_kind} + used = set() + for u in plan["units"]: + el = None + for cand in by_num.get(u["number"], []): + if id(cand) not in used: + el = cand + break + if el is None: + for cand in by_name.get(u["name"], []): + if id(cand) not in used: + el = cand + break + if el is None: + continue # 新单位没有骨架:暂不生成(不在本轮范围) + used.add(id(el)) + self._apply_unit(el, u, plan, proj_tpl) + + # 单项工程 = 其下单位工程合计;TenderInfo = 各单项合计 + for sp in root.findall(".//SingleProject"): + us = [u for u in sp.findall("UnitProject")] + if us: + set_attr(sp, "Total", num(sum(f(u.get("Total")) or 0 for u in us))) + ti = root.find("TenderInfo") + if ti is not None: + sps = root.findall("SingleProject") + if sps: + set_attr(ti, "Total", num(sum(f(sp.get("Total")) or 0 for sp in sps))) + + def _apply_unit(self, unit, u, plan, proj_tpl=None): + proj_tpl = proj_tpl or {} + parents = {c: p for p in unit.iter() for c in p} + res_ctx = self._apply_resources(unit, u, plan, proj_tpl) + item_els = list(unit.iter("BQItem")) + measure_els = [e for e in unit.iter("MeasureItem") + if not any(c.tag == "MeasureItem" for c in e)] + state = {"item_pos": 0, "prelim_pos": 0, + "item_tpl": proj_tpl.get("item") or _pick_largest(item_els, _bill_score), + "measure_tpl": proj_tpl.get("measure") or _pick_largest(measure_els, _simple_score), + "norm_tpl": proj_tpl.get("norm") or _pick_largest(list(unit.iter("NormItem")), + _simple_score), + "bq_id": max_id(unit.iter("BQItem"), "BQItemID"), + "mi_id": max_id(unit.iter("MeasureItem"), "MeasureItemID"), + "norm_id": max_id(unit.iter("NormItem"), "NormItemID")} + for b in u["bills"]: + if b["kind"] == "item": + el = self._bill_slot(b, item_els, "item_pos", state) + else: + el = self._bill_slot(b, measure_els, "prelim_pos", state) + if b["x_new"]: + el = self._new_bill(unit, b, plan, state) + elif el is None: + continue + elif b["x_tdel"]: + if el in parents: + parents[el].remove(el) + el = None + if el is None: + continue + self._fill_bill(el, b) + self._apply_norms(el, b, unit, state, res_ctx, plan["lme_proj"]) + self._recalc_totals(unit) + + def _bill_slot(self, b, els, key, state): + if b["x_new"]: + return None + i = state[key] + state[key] = i + 1 + return els[i] if i < len(els) else None + + # ---------------- 工料机骨架 ---------------- + def _apply_resources(self, unit, u, plan, proj_tpl=None): + res = unit.find("Resource") + if res is None: + res = ET.SubElement(unit, "Resource") + items = list(res.findall("ResourceItem")) + by_code = {(x.get("Code") or "").strip(): x for x in items} + by_id = {(x.get("ResourceID") or "").strip(): x for x in items} + # 项目范围内同类资源模板优先;本单位更大的同类行可以覆盖 + tpl_by_kind = dict((proj_tpl or {}).get("res_by_kind") or {}) + for x in items: + k = (x.get("CostKind") or "").strip() + if k not in tpl_by_kind or _simple_score(x) > _simple_score(tpl_by_kind[k]): + tpl_by_kind[k] = x + ctx = {"res": res, "items": items, "by_code": by_code, "by_id": by_id, + "tpl": (proj_tpl or {}).get("res") or _pick_largest(items, _simple_score), + "tpl_by_kind": tpl_by_kind, + "next_id": max_id(items, "ResourceID") + 1} + for row in u.get("lme") or []: + code = (row.get("code") or "").strip() + if not code: + continue + el = by_code.get(code) + if el is None: + if not int(row.get("x_adopt_added") or 0): + continue # 源里没有、也不是采纳新增:不硬造 + el = self._new_resource(ctx, code, row.get("kind")) + by_code[code] = el + for attr, key in (("Name", "name"), ("Spec", "spec"), ("Unit", "unit")): + v = row.get(key) + if v is not None and str(v).strip() != "": + set_attr(el, attr, v) + if row.get("ntp") is not None: + set_attr(el, "Rate", num(row.get("ntp"))) + if row.get("qty") is not None: + set_attr(el, "Quantity", num(row.get("qty"))) + if row.get("kind") is not None: + set_attr(el, "CostKind", num(row.get("kind"))) + if row.get("ntp") is not None and row.get("qty") is not None: + set_attr(el, "Total", num(round(float(row["qty"]) * float(row["ntp"]), 2))) + by_id[(el.get("ResourceID") or "").strip()] = el + return ctx + + def _new_resource(self, ctx, code, kind=None): + tpl = ctx["tpl_by_kind"].get(str(kind or "").strip()) or ctx["tpl"] + el = copy.deepcopy(tpl) if tpl is not None else ET.Element("ResourceItem") + for c in list(el): + el.remove(c) + rid = str(ctx["next_id"]) + ctx["next_id"] += 1 + set_attr(el, "ResourceID", rid) + set_attr(el, "Code", code) + set_attr(el, "StandardCode", code) + set_attr(el, "Name", code) + set_attr(el, "Spec", "") + set_attr(el, "Unit", "") + set_attr(el, "Rate", "") + set_attr(el, "Quantity", "") + ctx["res"].append(el) + ctx["by_id"][rid] = el + return el + + def _ensure_resource(self, code, unit, res_ctx, lme_proj): + code = (code or "").strip() + if not code: + return None + el = res_ctx["by_code"].get(code) + if el is not None: + return (el.get("ResourceID") or "").strip() + # 采纳消耗里引用了源 Resource 表没有的编码:按项目级/单位级数据补一条 + row = lme_proj.get(code) or {} + el = self._new_resource(res_ctx, code, row.get("kind")) + for attr, key in (("Name", "name"), ("Spec", "spec"), ("Unit", "unit")): + v = row.get(key) + if v is not None and str(v).strip() != "": + set_attr(el, attr, v) + if row.get("ntp") is not None: + set_attr(el, "Rate", num(row.get("ntp"))) + if row.get("qty") is not None: + set_attr(el, "Quantity", num(row.get("qty"))) + if row.get("kind") is not None: + set_attr(el, "CostKind", num(row.get("kind"))) + if row.get("ntp") is not None and row.get("qty") is not None: + set_attr(el, "Total", num(round(float(row["qty"]) * float(row["ntp"]), 2))) + res_ctx["by_code"][code] = el + rid = (el.get("ResourceID") or "").strip() + res_ctx["by_id"][rid] = el + return rid + + # ---------------- 清单骨架 ---------------- + def _new_bill(self, unit, b, plan, state): + if b["kind"] == "item": + el = self._clone(state["item_tpl"], "BQItem") + state["bq_id"] += 1 + set_attr(el, "BQItemID", state["bq_id"]) + container = self._item_container(unit, b, plan) + else: + el = self._clone(state["measure_tpl"], "MeasureItem") + state["mi_id"] += 1 + set_attr(el, "MeasureItemID", state["mi_id"]) + container = self._measure_container(unit, b, plan) + self._prepare_new_bill(el, b["kind"]) + if container is None: + return None + seq = sum(1 for c in container + if c.tag == ("BQItem" if b["kind"] == "item" else "MeasureItem")) + 1 + set_attr(el, "Sequence", seq) + container.append(el) + return el + + def _prepare_new_bill(self, el, kind): + """新增行只保留骨架结构:清单保留 Norms(空)和单价构成行(结果清零), + 其余模板数据删掉;措施叶子无子结构。""" + if kind == "item": + for c in list(el): + if c.tag == "Norms": + for n in list(c): + c.remove(n) + elif c.tag == "BQPriceAnalysisItem": + set_attr(c, "Total", "0") + else: + el.remove(c) + else: + for c in list(el): + el.remove(c) + + def _clone(self, tpl, tag): + if tpl is not None: + return copy.deepcopy(tpl) + return ET.Element(tag) + + def _item_container(self, unit, b, plan): + titles = list(unit.iter("BQTitle")) + div = plan["divides"].get(b["div_id"]) if b["div_id"] is not None else None + if div and div["kind"] == "item" and div["code"]: + for t in titles: + if (t.get("BQTitleID") or "").strip() == str(div["code"]).strip(): + return t + return titles[0] if titles else unit.find("BQTable") + + def _measure_container(self, unit, b, plan): + div = plan["divides"].get(b["div_id"]) if b["div_id"] is not None else None + titles = list(unit.iter("MeasureTitle")) + if div and div["kind"] == "prelim": + if div["code"]: + for t in titles: + if (t.get("MeasureTitleID") or "").strip() == str(div["code"]).strip(): + return t + if div["number"]: + for g in unit.iter("MeasureItem"): + if (g.get("Code") or "").strip() == str(div["number"]).strip() \ + and any(c.tag == "MeasureItem" for c in g): + return g + return titles[0] if titles else unit.find("MeasureTable") + + def _fill_bill(self, el, b): + if b["x_new"]: + # 新增行是从模板克隆的:模板里的旧编码/名称/单位/费用分析都不是这行的值, + # 按骨架有的字段逐个写;骨架没有的(如单价为空)就保持为空,不拿旧值顶。 + set_attr(el, "Code", b.get("Number") or "") + set_attr(el, "Name", b.get("Name") or "") + set_attr(el, "Unit", b.get("Unit") or None) + if b.get("src_remark") is not None: + set_attr(el, "Remark", b.get("src_remark")) + if b["kind"] == "item": + set_attr(el, "Feature", b.get("Attr") or "") + set_attr(el, "Quantity", + num(b.get("Quantity")) if b.get("Quantity") is not None else "0") + if b.get("Price") is not None: + set_attr(el, "Rate", num(b.get("Price"))) + set_attr(el, "Total", num(b.get("Total"))) + else: + set_attr(el, "Rate", None) + set_attr(el, "Total", None) + for attr in ("LaborRate", "MaterialRate", "MachineRate", + "OverheadRate", "ProfitRate"): + set_attr(el, attr, "0") + else: + set_attr(el, "Total", + num(b.get("Total")) if b.get("Total") is not None else "0") + return + if b.get("Number") is not None: + set_attr(el, "Code", b.get("Number")) + for attr, key in (("Name", "Name"), ("Feature", "Attr"), ("Unit", "Unit")): + v = b.get(key) + if v is not None: + set_attr(el, attr, v) + if b.get("src_remark") is not None: + set_attr(el, "Remark", b.get("src_remark")) + if b["kind"] == "item": + if b.get("Quantity") is not None: + set_attr(el, "Quantity", num(b["Quantity"])) + if b.get("Price") is not None: + set_attr(el, "Rate", num(b["Price"])) + set_attr(el, "Total", num(b.get("Total"))) + else: + if b.get("Total") is not None: + set_attr(el, "Total", num(b.get("Total"))) + + def _apply_norms(self, bill_el, b, unit, state, res_ctx, lme_proj=None): + norms = b.get("norms") or [] + src = [n for n in norms if not n["x_adopt"]] + add = [n for n in norms if n["x_adopt"] and not n["x_tdel"]] + if not src and not add: + return + np = bill_el.find("Norms") + if np is None: + np = ET.SubElement(bill_el, "Norms") + src_els = list(np.findall("NormItem")) + for i, n in enumerate(src): + if i >= len(src_els): + continue + el = src_els[i] + if n["x_tdel"]: + np.remove(el) + continue + for attr, key in (("Code", "Number"), ("Name", "Name"), + ("Unit", "Unit"), ("Quantity", "Quantity"), + ("Rate", "Price"), ("Total", "Total")): + v = n.get(key) + if v is not None: + set_attr(el, attr, num(v) if key in ("Quantity", "Price", "Total") else v) + for n in add: + el = self._clone(state["norm_tpl"], "NormItem") + for c in list(el): + el.remove(c) + state["norm_id"] += 1 + set_attr(el, "NormItemID", state["norm_id"]) + set_attr(el, "Code", n.get("Number") or "") + set_attr(el, "StandardCode", n.get("Number") or "") + for attr in ("LaborRate", "MaterialRate", "MachineRate", + "OverheadRate", "ProfitRate"): + set_attr(el, attr, "0") + for attr, key in (("Code", "Number"), ("Name", "Name"), + ("Unit", "Unit"), ("Quantity", "Quantity"), + ("Rate", "Price"), ("Total", "Total")): + v = n.get(key) + if v is not None: + set_attr(el, attr, num(v) if key in ("Quantity", "Price", "Total") else v) + for code, q in n.get("res") or []: + rid = self._ensure_resource(code, unit, res_ctx, lme_proj or {}) + if rid: + ue = ET.SubElement(el, "NormResUsageItem") + set_attr(ue, "ResourceID", rid) + set_attr(ue, "Usage", num(q)) + np.append(el) + + # ---------------- 汇总骨架 ---------------- + def _recalc_totals(self, unit): + def recalc_measure(el): + kids = [c for c in el if c.tag == "MeasureItem"] + if kids: + total = sum(recalc_measure(c) for c in kids) + set_attr(el, "Total", num(total)) + return total + return f(el.get("Total")) or 0.0 + + measure_total = 0.0 + measure_by_name = {} + for title in unit.iter("MeasureTitle"): + for m in title.findall("MeasureItem"): + total = recalc_measure(m) + measure_total += total + measure_by_name[_name_norm(m.get("Name"))] = total + for leaf in m.iter("MeasureItem"): + measure_by_name[_name_norm(leaf.get("Name"))] = f(leaf.get("Total")) or 0.0 + bq_total = sum(f(x.get("Total")) or 0.0 for x in unit.iter("BQItem")) + other = unit.find("OtherTable") + other_total = sum(f(x.get("Total")) or 0.0 for x in other.findall("OtherItem")) \ + if other is not None else 0.0 + sm = unit.find("Summary") + items = {} + if sm is not None: + for x in sm.iter("SummaryItem"): + code = (x.get("CostCode") or "").strip() + if code and code not in items: + items[code] = x + c2 = f(items["C2"].get("Total")) if "C2" in items else 0.0 + base = bq_total + measure_total + other_total - (c2 or 0.0) + d0 = f(items["D"].get("Total")) if "D" in items else 0.0 + rate = f(items["D"].get("CostRate")) if "D" in items else None + # 源文件没写税率时,用源 D/计费基数反推有效税率(不把已有税金抹成 0) + if (rate is None or rate == 0) and base and d0: + rate = d0 / base * 100.0 + rate = 0.0 if rate is None else rate + d_total = round(base * rate / 100.0, 2) + e_total = round(bq_total + measure_total + other_total + d_total, 2) + for code, val in (("A", bq_total), ("B", measure_total), ("C", other_total), + ("D", d_total), ("E", e_total)): + if code in items: + set_attr(items[code], "Total", num(val)) + # 措施明细(B1/B11/B12/B13):按名称对到措施行,避免只改 B 不改明细 + if "B1" in items: + for nm, val in measure_by_name.items(): + if "安全文明施工费" in nm: + set_attr(items["B1"], "Total", num(val)) + break + for code, needle in (("B11", "按费率计算"), ("B12", "按清单列项"), + ("B13", "产业工人职业训练")): + if code in items: + for nm, val in measure_by_name.items(): + if needle in nm: + set_attr(items[code], "Total", num(val)) + break + set_attr(unit, "Total", num(e_total)) + + +register(SWTExporter()) diff --git a/CostReview/app/core/import_job.py b/CostReview/app/core/import_job.py index f0f5fb8..4a8b3a7 100644 --- a/CostReview/app/core/import_job.py +++ b/CostReview/app/core/import_job.py @@ -86,12 +86,16 @@ def clean_attr(s): # ---------- 分派 ---------- def sniff(path): with io.open(path, "rb") as fh: - head = fh.read(4) + head = fh.read(16384) if head[:4] == b"PK\x03\x04": return "zip" if head[:2] == b"\x88\x7d": return "encrypted" if head[:2] in (b"= 0: + st["cur_norm"] = len(out["norms"]) + out["norms"].append((st["cur_bill"], a.get("Code", ""), a.get("Name", ""), + (a.get("Unit") or "").strip(), f(a.get("Quantity")), + f(a.get("Rate")), f(a.get("Total")))) + elif tag == "NormResUsageItem": + if st["unit"] is not None and st["cur_norm"] >= 0: + st["unit"]["deferred"].append( + (st["cur_norm"], a.get("ResourceID"), f(a.get("Usage")))) + elif tag == "ResourceItem": + rec = dict(a) + rec["_subs"] = [] + if st["unit"] is not None: + st["unit"]["resources"].append(rec) + st["cur_res"] = rec + elif tag == "ResourceUsage": + if st["cur_res"] is not None: + st["cur_res"]["_subs"].append((a.get("ResourceID"), f(a.get("Usage")))) + elif tag == "MeasureTable": + st["measure_nodes"] = [] + st["measure_stack"] = [] + st["measure_title"] = None + elif tag == "MeasureTitle": + st["measure_title"] = add_divide( + "prelim", "", (a.get("Name") or "").strip(), None, + a.get("MeasureTitleID"), None) + elif tag == "MeasureItem": + node = {"attrs": dict(a), "has_child": False, "div": None, + "parent": st["measure_stack"][-1] if st["measure_stack"] else None, + "title": st["measure_title"]} + if st["measure_stack"]: + st["measure_stack"][-1]["has_child"] = True + st["measure_nodes"].append(node) + st["measure_stack"].append(node) + elif tag == "Summary": + st["summary"] = [] + elif tag == "SummaryItem": + st["summary"].append(dict(a)) + else: + if tag == "BQTitle": + if st["title_stack"]: + st["title_stack"].pop() + elif tag == "BQItem": + st["cur_bill"] = -1 + st["cur_norm"] = -1 + elif tag == "NormItem": + st["cur_norm"] = -1 + elif tag == "ResourceItem": + st["cur_res"] = None + elif tag == "MeasureItem": + if st["measure_stack"]: + st["measure_stack"].pop() + elif tag == "MeasureTitle": + st["measure_title"] = None + elif tag == "MeasureTable": + flush_measures() + elif tag == "SingleProject": + if st["sp"] is not None and st["sp"]["uw_nums"]: + out["sections"].append(st["sp"]) + st["sp"] = None + elif tag == "UnitProject": + flush_unit() + st["unit"] = None + el.clear() + + # 总造价兜底:TenderInfo 缺失时用各单位工程 Total 求和(原文件口径,不用清单合价) + if out.get("total") is None: + vals = [t for _, _, t in out["uw"] if t is not None] + if vals: + out["total"] = sum(vals) + return "SWT" + + +def _zip_swt_member(z): + """在 zip 里找根节点 ConstructProject 的 XML。 + + 2026-10-19:.SWZ 有可能是压缩包(里面装同一份深圳数据交换标准 XML), + 不能因为文件头是 PK 就一律按 COS4 的 parse_std 处理。 + """ + for n in z.namelist(): + if not n.lower().endswith((".xml", ".swt", ".swz")): + continue + try: + with z.open(n) as f: + if b"_<原名>)。 @@ -1431,6 +1457,15 @@ def _purge_upload_files(names): return gone +def _fresh_file(fp, seconds=600): + """决策 126:启动自愈改后台后,刚上传/刚复制的文件可能还没落库引用—— + 10 分钟内的一律不回收,留给下一次启动对账(宁留勿误删)。""" + try: + return time.time() - os.path.getmtime(fp) < seconds + except OSError: + return True + + def _purge_orphan_uploads(): """启动自愈:uploads 里**零引用**的源文件副本全量对账回收(幂等)。 @@ -1444,6 +1479,8 @@ def _purge_orphan_uploads(): for f in os.listdir(UPLOAD_DIR): if not os.path.isfile(os.path.join(UPLOAD_DIR, f)) or "_" not in f: continue + if _fresh_file(os.path.join(UPLOAD_DIR, f)): + continue # 刚上传的还没落库引用(决策 126 宽限) head = f.split("_", 1)[0].lower() if len(head) < 8 or any(ch not in "0123456789abcdef" for ch in head): continue # 只认 _<原名> 规矩文件,别的一律不碰 @@ -1513,6 +1550,8 @@ def _purge_orphan_inq(): fp = os.path.join(INQ_DIR, f) if not os.path.isfile(fp) or "_" not in f: continue + if _fresh_file(fp): + continue head = f.split("_", 1)[0].lower() if len(head) < 8 or any(ch not in "0123456789abcdef" for ch in head) or head in ref: continue @@ -1542,6 +1581,8 @@ def _purge_orphan_attach(): fp = os.path.join(ATTACH_DIR, f) if not os.path.isfile(fp) or "_" not in f: continue + if _fresh_file(fp): + continue head = f.split("_", 1)[0].lower() if len(head) < 8 or any(ch not in "0123456789abcdef" for ch in head) or head in ref: continue @@ -1560,10 +1601,10 @@ def api_sessions(): 现在同名即同一工程:列表一行、打开=最近一次审核(继续上次的活)、删除=该名称下全部删除。 每条仍带 all(该名称下全部会话 id + 元数据),前端删除时整组提交。 """ - con = sess.connect() + con = sess.connect_readonly() try: rows = con.execute("""SELECT id, name, src_name, imported_at, period_from, period_to, - x_province, x_city, x_district, bulid_unit, x_total + x_province, x_city, x_district, bulid_unit, x_total, x_manual FROM sessions ORDER BY id DESC""").fetchall() cnt = {} for sid, nb, nn, nl, nu, nr in con.execute( @@ -1586,6 +1627,16 @@ def api_sessions(): "SELECT COUNT(*) FROM s_remarks WHERE remark IS NOT NULL AND TRIM(remark)<>''").fetchone()[0] finally: con.close() + # 新会话的源文件名通常就是 uploads 根目录下的精确文件名;只有命中旧格式 + # 的缺失路径时才做一次兼容扫描,避免每次打开列表都递归扫整个源文件目录。 + source_names = None + for r in rows: + src_name = (r["src_name"] or "").strip() + if src_name and not os.path.exists(os.path.join(UPLOAD_DIR, src_name)): + source_names = _source_file_names() + break + if source_names is None: + source_names = (set(), set()) groups, order = {}, [] for r in rows: # 分组键 = 项目名称(同名不同文件也算同一个工程;空名称退回源文件名 / 会话 id) @@ -1604,6 +1655,7 @@ def api_sessions(): items = [] for k in order: g = groups[k] + _manual = bool(g.get("x_manual")) items.append({ "id": g["id"], "name": g["name"], "src_name": g["src_name"], "at": g["imported_at"], "period_from": g["period_from"], "period_to": g["period_to"], @@ -1613,7 +1665,8 @@ def api_sessions(): "n_uw": g["cnt"]["uw"], "n_remark": g["cnt"]["remark"], "total": g.get("x_total"), # 工程总造价(原文件口径,不是清单合价求和) "all": g["all"], "dup": len(g["all"]), - "can_reparse": bool(_src_path(g["src_name"])), + "manual": _manual, + "can_reparse": _src_exists_in_names(g["src_name"], source_names) and not _manual, }) return {"ok": True, "items": items, "keep_days": SESSION_KEEP_DAYS, "db_mb": db_mb, "remark_total": remark_total} @@ -2369,6 +2422,8 @@ def api_session_reparse(body): row = con.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone() if not row: return {"ok": False, "msg": "会话不存在"} + if row["x_manual"]: + return {"ok": False, "msg": "手工工程没有源文件,无法重新解析;请用「打开项目」选择同名源文件补传"} path = _src_path(row["src_name"]) if not path: return {"ok": False, "msg": "原文件已经不在软件里了(可能被清理),只能重新「打开工程」"} @@ -2403,37 +2458,85 @@ def api_session_reparse(body): def api_session_delete(body): """台账删除:可以一次给多个 id。 + 2026-10-19 主人定:**两段式删除**(解决大工程删除要等数秒) + 第一段(同步、返回前):记下会话元数据 → 删采纳事件(按 rowid,防 id 复用)→ 删 sessions 行。 + 第二段(后台线程):清子表、备注、源文件;失败留孤儿,启动自愈兜底。 + 备注/源文件仍按「引用清零才删」检查(后台执行时再查,防止刚重导的同一文件被误删)。 + 2026-10-07 主人定:**连同源文件副本一并彻底删**(uploads 里那份)—— 还有别的会话/批次引用同一份文件时不删,引用清零才动磁盘(_purge_upload_files)。 2026-10-08 主人定:**采纳备注(s_remarks)跟着一起删**——同一份文件还被别的 会话开着时不误伤(sess.drop_remarks,引用清零才删)。""" - ids = [int(x) for x in (body.get("ids") or []) if str(x).isdigit()] + ids = sorted({int(x) for x in (body.get("ids") or []) if str(x).isdigit()}) if not ids: return {"ok": False, "msg": "没选中任何会话"} con = sess.connect() - names = [] - n_remark = 0 + meta = [] try: - rk = set() for sid in ids: r = con.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone() - if r and r[0]: - names += [x.strip() for x in r[0].split(";") if x.strip()] - rk |= sess.bill_rkeys(con, sid) # 删之前收持久键,删完行就没了 - rk |= sess.lme_rkeys(con, sid) # 工料机采纳键一并收('L:' 前缀,2026-10-08) - sess.drop(con, sid) - n_remark = sess.drop_remarks(con, rk, _batch_src_hashes()) + if r: + meta.append({"sid": sid, "src_name": (r[0] or "")}) + # 采纳事件先删(按 rowid,避免后台延迟清理时会话 id 被新会话复用而误删) + hc = conn() + try: + rows = [] + for m in meta: + rows += [x[0] for x in hc.execute("SELECT rowid FROM adopt_hits WHERE sid=?", (m["sid"],))] + if rows: + hc.executemany("DELETE FROM adopt_hits WHERE rowid=?", [(x,) for x in rows]) + _adopt_purge_orphans(hc) + hc.commit() + except Exception: + hc.rollback() + raise + finally: + hc.close() + # 第一段只删会话行:子表/备注/文件交给后台,界面立即看到行消失 + for m in meta: + con.execute("DELETE FROM sessions WHERE id=?", (m["sid"],)) con.commit() + except Exception as e: + try: + con.rollback() + except Exception: + pass + return {"ok": False, "msg": "删除失败:%s" % e} finally: con.close() - _adopt_drop_sessions(ids) # 采纳事件同会话共生(备注没了事件也没了) - gone = _purge_upload_files(names) - extra = "" - if n_remark: - extra += ",采纳备注已一并删除 %d 条" % n_remark - if gone: - extra += ",源文件已一并删除 %d 个" % gone - return {"ok": True, "msg": "已删除 %d 个会话%s" % (len(ids), extra)} + if meta: + threading.Thread(target=_session_cleanup_worker, args=(meta,), daemon=True, + name="session-cleanup").start() + return {"ok": True, "msg": "已删除", "n": len(meta)} + + +def _session_cleanup_worker(meta): + """后台清理(第二段):子表、备注、源文件。幂等;失败只留孤儿数据,启动自愈会兜底。""" + names, rk = [], set() + try: + with WRITE_LOCK: + con = sess.connect() + try: + for m in meta: + sid, src = m["sid"], m.get("src_name") or "" + for seg in src.split(";"): + seg = seg.strip() + if seg and seg not in names: + names.append(seg) + # 会话行已删:src_name 显式传入,不能再 JOIN sessions + rk |= sess.bill_rkeys(con, sid, src) + rk |= sess.lme_rkeys(con, sid, src) + sess.wipe(con, sid, clean_orphans=False) + con.commit() + n = sess.drop_remarks(con, rk, _batch_src_hashes()) + con.commit() + finally: + con.close() + gone = _purge_upload_files(names) + print("[后台删除] 清理完成:会话 %d 个、备注 %d 条、源文件 %d 个" + % (len(meta), n, gone), flush=True) + except Exception as e: + print("[后台删除] 清理失败(启动自愈会兜底):%s" % e, flush=True) def _adopt_drop_sessions(sids): @@ -3268,19 +3371,24 @@ def _export_meta(sc, sid): srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone() if not srow: return {"ok": False, "msg": "会话不存在"} + if srow["x_manual"]: + return {"ok": False, "msg": "手工工程没有源文件,无法按原格式导出;请用「打开项目」选择同名源文件补传"} + if not (srow["src_name"] or ""): + return {"ok": False, "msg": "没有源文件,无法按原格式导出"} proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"] ext = xcos._source_ext(srow["src_name"]) return {"ok": True, "name": (proj_name or "工程") + "-审核版" + ext} def _export_session(sc, sid, progress=None): - """导出=拿原文件当模板外科手术。返回 (zip字节, 文件名, 错误)。 - 数据计划:每个 (uw, kind) 一份 pairs(源序位序的源清单)+ news(x_new 行,锚点=源序位); - zip 内每个 xml 按 UnitWorks(Number,Name) 认领自己的计划——文件名编码不可靠,靠内容认。 - progress=逐条目进度回调(决策 92,透传给 export_zip)。""" + """导出=拿原文件当模板外科手术。返回 (字节, 文件名, 错误)。 + 2026-10-19:SWT/SWZ 等新格式走 formats 适配器(骨架+填空);COS4/.COS 继续用 + export_cos 的专用引擎(保留逐节点保真)。""" srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone() if not srow: return None, None, "会话不存在" + if srow["x_manual"]: + return None, None, "手工工程没有源文件,无法按原格式导出;请先用「打开项目」选同名源文件补传" path = _src_path(srow["src_name"]) if not path or not os.path.exists(path): return None, None, "原文件已不在软件里(可能被清理),无法导出" @@ -3297,10 +3405,19 @@ def _export_session(sc, sid, progress=None): if re.fullmatch(r"[0-9a-f]{64}", _want) and hashlib.sha256(src_bytes).hexdigest() != _want: return None, None, ("源文件内容与打开该工程时不一致(可能被外部改动后同名覆盖)。" "请重新打开这个文件后再导出") + # 2026-10-19:新格式(SWT/SWZ…)走「骨架/填空」适配器;COS4/.COS 仍走下面的专用引擎。 + # 一个格式一个骨架:适配器只填骨架里有的字段,骨架没有的字段不硬造。 + fmt = formats.get_exporter(srow["src_name"]) + if fmt: + try: + raw, out_name = fmt.export(sc, sid, src_bytes, srow, progress) + except Exception as e: + return None, None, "导出失败:%s" % e + return raw, out_name, None proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"] # 每组 (uw, kind):x_seq 序走一遍——源清单计源序位,x_new 行记锚点 groups = {} - for b in sc.execute("""SELECT id, uw_id, Number, Name, Attr, Unit, Quantity, Price, Total, + for b in sc.execute("""SELECT id, uw_id, div_id, Number, Name, Attr, Unit, Quantity, Price, Total, Kind, x_new, x_tdel, x_seq, src_remark FROM s_bills WHERE session_id=? ORDER BY uw_id, @@ -4702,7 +4819,7 @@ def api_import(con, body): "bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0, "lme_raw": 0, "lme_skip": 0, "proj_name": "", "file_kind": None, "bulid_unit": "", "total": None} try: - schema = job.parse_std(p, out) # 只可能是 zip(xml / 加密 / 未知已在上面拦掉) + schema = job.parse_file(p, out) # zip=COS4/.COS;swt=深圳数据交换标准(2026-10-19) except Exception as e: return {"ok": False, "msg": "解析失败:%s" % e} @@ -5908,9 +6025,12 @@ class Handler(SimpleHTTPRequestHandler): return self._json({"ok": False, "msg": err}) self._allow_cache = True self.send_response(200) - self.send_header("Content-Type", "application/zip") + # SWT 裸 XML 用 application/xml;SWZ/COS 压缩包用 application/zip + self.send_header("Content-Type", + "application/zip" if raw[:2] == b"PK" else "application/xml") self.send_header("Content-Length", str(len(raw))) - self.send_header("Content-Disposition", self._cd(out_name, "export.zip")) + self.send_header("Content-Disposition", self._cd( + out_name, "export" + (os.path.splitext(out_name)[1] or ".zip"))) self.end_headers() self.wfile.write(raw) return @@ -6344,6 +6464,66 @@ class Handler(SimpleHTTPRequestHandler): pass +# ---------------------------------------------------------------- 启动自愈(后台) + +# 2026-10-20 决策 126(主人拍板):端口先就绪、窗口先开,启动自愈改到**后台线程**。 +# 起因:run() 原先做完整套全库自愈才 bind,冷启动实测 sess.drop_orphan_rows 单步 52 秒, +# 超过启动器约 75 秒预算就报「端口 8365 起不来」并整进程退出(launch.log 14 次失败全是 76~78 秒)。 +# 自愈全部幂等、晚几秒做不影响正确性;接口依赖的建表/补列/迁移仍留在 bind 之前。 +_SELFHEAL_DELAY = 8.0 # 秒:先让首屏接口与用户操作起来,避免刚开窗就抢库 +_SELFHEAL = {"running": False, "done": False, "started": ""} + + +def _selfheal_step(label, fn): + """跑一步自愈:异常只跳过自己(下次启动重做),慢步骤打耗时便于排查。""" + t0 = time.time() + try: + return fn() + except Exception as e: + print("[启动自愈] %s失败(已跳过,不影响使用):%s" % (label, e), flush=True) + return None + finally: + d = time.time() - t0 + if d >= 2: + print("[启动自愈] %s用时 %.1f 秒" % (label, d), flush=True) + + +def _startup_selfheal_bg(): + """后台启动自愈:端口已 listening、页面可打开之后才跑(决策 126)。""" + _SELFHEAL["running"] = True + _SELFHEAL["started"] = time.strftime("%Y-%m-%d %H:%M:%S") + try: + time.sleep(_SELFHEAL_DELAY) + _selfheal_step("退役设置键清除", _purge_dead_settings) # 决策 32 + _selfheal_step("过期会话清理", cleanup_sessions) # 只碰 session.db + _selfheal_step("工料机组成去重", sess.dedupe_lme_res) # 2026-10-10 + _n = _selfheal_step("孤儿行清理", sess.drop_orphan_rows) # 2026-10-11 + if _n and _n > 0: + print("[启动自愈] 清掉已删会话的孤儿数据 %d 行" % _n, flush=True) + # 2026-10-19:两段式删除的备注兜底——无会话/批次引用的孤儿备注清掉 + _bh = _selfheal_step("读取后台批次引用", _batch_src_hashes) + if _bh is None: + _bh = set() + _nr = _selfheal_step("孤儿备注清理", lambda: sess.drop_orphan_remarks(_bh)) + if _nr and _nr > 0: + print("[启动自愈] 清掉无宿主的孤儿备注 %d 条" % _nr, flush=True) + _g = _selfheal_step("零引用源文件回收", _purge_orphan_uploads) # 2026-10-11 + if _g: + print("[启动自愈] 回收零引用源文件副本 %d 个" % _g, flush=True) + _gr = _selfheal_step("裸哈希源文件找回原名", _recover_bare_upload_names) # 2026-10-15 + if _gr: + print("[启动自愈] 裸哈希源文件找回原名 %d 个" % _gr, flush=True) + _gi = _selfheal_step("零引用询价附件回收", _purge_orphan_inq) # 2026-10-14 + if _gi: + print("[启动自愈] 回收零引用询价附件 %d 个" % _gi, flush=True) + _ga = _selfheal_step("零引用价格附件回收", _purge_orphan_attach) # 2026-10-14 + if _ga: + print("[启动自愈] 回收零引用价格附件 %d 个" % _ga, flush=True) + _SELFHEAL["done"] = True + finally: + _SELFHEAL["running"] = False + + def run(): # 单实例护栏(2026-10-15):Windows 的 SO_REUSEADDR 允许两个进程同时绑 8366(双实例并存, # 请求随机落到新旧代码——今天实测踩坑)。连接探测有同秒竞态窗口,改用**内核命名互斥量**: @@ -6367,7 +6547,6 @@ def run(): ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block / x_setkey) _ensure_edit_cols() # 决策 67:清单编辑状态列(x_new/x_tdel 两库 + s_norms 三列,幂等) migrate_match_keys() # 决策 27:清单哈希改编码前9位 + 字集键回填(幂等,探针跳过) - _purge_dead_settings() # 决策 32:专业体系/第7点合并退役设置键清除(幂等) ensure_dict_schema() # 数据源字典(首次用库里已有值播种) backfill_session_batch() # 老会话补 x_batch_id → 工作台才能看到该项目的询价附件 try: # 决策 40:项目工料机切项目级汇总——采纳备注/事件平移到 s_lme_proj @@ -6386,25 +6565,8 @@ def run(): except Exception as e: print("[启动自愈] 采纳迁移出错(不影响启动):%s" % e) license_gate.init(DATA_DIR) # 授权门禁:读配置/状态,配了凭据则起心跳线程(内部吞异常) - cleanup_sessions() # 启动时清掉超过保留天数的会话(只碰 session.db) - sess.dedupe_lme_res() # 2026-10-10:s_lme_res 存量去重自愈(wipe 曾漏这张表,台班组成重复) - _n = sess.drop_orphan_rows() # 2026-10-11:s_ 表孤儿行自愈(已删会话的幽灵 sid 残留) - if _n > 0: - print("[启动自愈] 清掉已删会话的孤儿数据 %d 行" % _n) - elif _n < 0: - print("[启动自愈] 孤儿数据清理出错(已回滚,不影响启动)") - _g = _purge_orphan_uploads() # 2026-10-11:uploads 零引用源文件副本对账回收(幂等) - if _g: - print("[启动自愈] 回收零引用源文件副本 %d 个" % _g) - _gr = _recover_bare_upload_names() # 2026-10-15:裸哈希源文件找回原名(导出格式/文件名依赖它) - if _gr: - print("[启动自愈] 裸哈希源文件找回原名 %d 个" % _gr) - _gi = _purge_orphan_inq() # 2026-10-14:询价附件零引用对账回收(拍平后同款自愈) - if _gi: - print("[启动自愈] 回收零引用询价附件 %d 个" % _gi) - _ga = _purge_orphan_attach() # 2026-10-14:价格附件零引用对账回收(启动也扫,不只挂在删除流程) - if _ga: - print("[启动自愈] 回收零引用价格附件 %d 个" % _ga) + # 2026-10-20 决策 126:过期会话清理/去重/孤儿清理/附件回收等**纯清理**步骤已挪到 + # bind 之后的后台线程 _startup_selfheal_bg(幂等,晚几秒做不影响正确性)。 # 2026-10-11:启动「数据过期」打印已取消(主人定)——打开即自动升级(决策 34)后「需重导」口径不再成立; # stale_batches() 保留:/api/admin/summary 的 stale 字段仍返回,供后续一键批量升级(方案 B)复用。 mcpmod.bind(sys.modules[__name__]) # MCP 工具复用本模块的 api_*(惰性取属性,循环安全) @@ -6412,7 +6574,9 @@ def run(): import time as _t _STARTED_AT = _t.strftime("%Y-%m-%d %H:%M:%S") srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler) - print("serving on http://127.0.0.1:%d (db=%s) (PID=%d)" % (PORT, DB, os.getpid())) + print("serving on http://127.0.0.1:%d (db=%s) (PID=%d)" % (PORT, DB, os.getpid()), flush=True) + # 决策 126:端口已 listening,先让启动器/窗口走;清理回收在后台跑,慢也不再挡住开窗。 + threading.Thread(target=_startup_selfheal_bg, name="startup-selfheal", daemon=True).start() srv.serve_forever() diff --git a/CostReview/app/shell.py b/CostReview/app/shell.py index 6b8fdb2..6ec0a7a 100644 --- a/CostReview/app/shell.py +++ b/CostReview/app/shell.py @@ -43,6 +43,18 @@ _LAST_SAVE_DIR = {"d": ""} # 本次运行记住的上一另存位 class _BridgeApi: + def set_title(self, text=""): + """全局语言切换时同步软件窗口标题(2026-10-19 主人定:语言控制整个软件)。""" + try: + import webview + win = webview.windows[0] if webview.windows else None + if win is None: + return {"ok": False, "msg": "窗口未就绪"} + win.set_title(str(text or "造价审核")[:80]) + return {"ok": True} + except Exception as e: + return {"ok": False, "msg": str(e)} + def export_save_as(self, session_id, suggested_name=""): """决策 92(主人定流程):点导出=①先弹原生另存为选路径(此刻还不生成,大工程不再干等) →②后台线程生成+分块写盘(逐条目进度经 evaluate_js 推给页面进度条) @@ -353,6 +365,21 @@ def warn_webview2_missing(): pass +_SRV_ERR = {} + + +def _run_srv(): + """后台服务线程:异常写进 launch.log,避免只剩一句“端口起不来”。""" + try: + api_server.run() + except Exception: + import traceback + tb = traceback.format_exc() + _SRV_ERR["tb"] = tb + _log("本地服务异常退出:\n" + tb) + print("本地服务异常退出:\n" + tb, flush=True) + + def main(): _log("启动中…(端口 %d)" % PORT) @@ -401,10 +428,15 @@ def main(): print("端口 %d 被残留进程占用且无响应,请到任务管理器结束 python.exe 后再双击本文件" % PORT, flush=True) return 1 if not reused: - threading.Thread(target=api_server.run, daemon=True).start() + threading.Thread(target=_run_srv, daemon=True).start() if not wait_ready(): _log("服务启动失败:端口 %d 起不来(可能被其他程序占用)" % PORT) - print("服务启动失败,请检查端口 %d 是否被占用" % PORT, flush=True) + if _SRV_ERR.get("tb"): + _log("服务异常:\n" + _SRV_ERR["tb"]) + print("服务异常(详见 launch.log):%s" % _SRV_ERR["tb"].splitlines()[-1], flush=True) + else: + print("服务启动失败,请检查端口 %d 是否被占用;若刚关过软件,请等 5 秒、只开一个窗口再试" % PORT, + flush=True) return 1 _log("本地服务就绪") diff --git a/CostReview/app/store/session.sql b/CostReview/app/store/session.sql index fcf36ad..2c768f9 100644 --- a/CostReview/app/store/session.sql +++ b/CostReview/app/store/session.sql @@ -14,9 +14,11 @@ CREATE TABLE IF NOT EXISTS sessions( x_total REAL, -- 工程总造价(2026-09-30):原文件口径,不是清单合价求和 x_info TEXT, -- 项目根节点属性 JSON → 项目级「基本信息」卡 x_feat TEXT, -- AttrInfo/AddiInfo 条目 JSON → 项目级「项目特征信息」卡 - x_batch_id INTEGER -- 后台批次 id(2026-10-06):同一份文件在后台导入过就能对上, + x_batch_id INTEGER, -- 后台批次 id(2026-10-06):同一份文件在后台导入过就能对上, -- 工作台据此**只读**展示该项目的询价附件。对不上 = 0 / NULL, -- 界面上就不显示「询价附件」入口(不是错误,是没在后台导入过) + x_manual INTEGER DEFAULT 0 -- 2026-10-19:手工工程(无源文件)。1=创建工程建的空工程, + -- 不能按原格式导出/重新解析;用同名源文件打开即变回 0。 ); -- 2026-09-30 再加两张项目级标签卡的数据,都以 JSON 存(字段随格式而变,不值得各开一列): -- x_info = 项目根节点属性(编号/名称/专业/计价标准/单位/规模…)→ 「基本信息」卡 diff --git a/CostReview/app/tests/api_harness.py b/CostReview/app/tests/api_harness.py index 42e3de6..2ced268 100644 --- a/CostReview/app/tests/api_harness.py +++ b/CostReview/app/tests/api_harness.py @@ -94,6 +94,94 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位", return path +def make_swt(path, proj_name, units, total=None, tenderee="测试建设单位"): + """构造最小可解析的 .SWT(深圳市工程造价数据交换标准 SJG77-2020)。 + + units: [{ + "id","name","total","a","b","c","d","e","b1", # 单位工程与 Summary 五项 + "bills":[{"code","name","feature","unit","qty","rate", + "norms":[{"code","name","unit","qty","rate","res":[(rid, usage)]}]}], + "resources":[{"id","code","name","spec","unit","rate","qty","kind", + "subs":[(rid, usage)]}], + "measures":[{"code","name","unit","total","children":[...]}] # 可嵌套 + }] + ⚠️ ResourceID 在 SWT 里是单位工程内部编号:不同 unit 可用同一个 id 指不同编码, + 这正是回归要覆盖的重号场景。 + """ + def attrs(d): + return " ".join("%s=%s" % (k, quoteattr(str(v))) for k, v in d.items() if v is not None) + + def measure_xml(m): + return '%s' % ( + attrs({"MeasureItemID": m.get("id", ""), "Code": m["code"], "Name": m["name"], + "Unit": m.get("unit", "项"), "Total": m.get("total", 0), "Sequence": 1}), + "".join(measure_xml(c) for c in m.get("children", []))) + + ups = [] + for u in units: + resources = "".join( + '%s' % ( + attrs({"ResourceID": r["id"], "Code": r["code"], "Name": r["name"], + "Spec": r.get("spec", ""), "Unit": r.get("unit", ""), + "Rate": r.get("rate", 0), "Quantity": r.get("qty", 0), "Total": 0, + "CostKind": r.get("kind", 2), "Provider": 0, + "StandardCode": r["code"], "NormLibrary": ""}), + "".join('' % ( + quoteattr(str(rid)), quoteattr(str(usage))) for rid, usage in r.get("subs", []))) + for r in u.get("resources", [])) + bills = "".join( + '%s' % ( + attrs({"BQItemID": b.get("id", ""), "Code": b["code"], "Name": b["name"], + "Feature": b.get("feature", ""), "Unit": b["unit"], "Quantity": b["qty"], + "Rate": b["rate"], "Total": round(float(b["qty"]) * float(b["rate"]), 2), + "Sequence": 1}), + "".join( + '%s' % ( + attrs({"NormItemID": n.get("id", ""), "Code": n["code"], "Name": n["name"], + "Unit": n["unit"], "Quantity": n["qty"], "Rate": n["rate"], + "Total": round(float(n["qty"]) * float(n["rate"]), 2), "Sequence": 1}), + "".join('' % ( + quoteattr(str(rid)), quoteattr(str(usage))) + for rid, usage in n.get("res", []))) + for n in b.get("norms", []))) + for b in u.get("bills", [])) + measures = "".join(measure_xml(m) for m in u.get("measures", [])) + summary = "".join( + '' % ( + quoteattr(code), quoteattr(str(kind)), quoteattr(name), + quoteattr(str(u.get(key, 0)))) + for code, kind, name, key in (("A", 8, "分部分项工程", "a"), ("B", 15, "措施项目", "b"), + ("B1", 22, "安全文明施工费", "b1"), + ("C", 16, "其他项目", "c"), ("D", 21, "增值税", "d"), + ("E", 24, "工程造价", "e"))) + ups.append( + '' + '%s' + '%s' + '%s' + '%s' + '' % ( + quoteattr(str(u["id"])), quoteattr(u["name"]), quoteattr(str(u.get("total", 0))), + summary, bills, + ('%s' + '' % measures) if measures else "", + resources)) + if total is None: + total = sum(float(u.get("total", 0)) for u in units) + xml = ('\r\n' + '' + '' + '' + '%s' + '' % ( + quoteattr(proj_name), quoteattr(tenderee), quoteattr(str(total)), + quoteattr(str(total)), "".join(ups))) + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(xml) + return str(path) + + # ------------------------------------------------------------------ 服务夹具 @pytest.fixture(scope="session") def server(tmp_path_factory): diff --git a/CostReview/app/tests/test_api_p0.py b/CostReview/app/tests/test_api_p0.py index 83ce070..fcfe824 100644 --- a/CostReview/app/tests/test_api_p0.py +++ b/CostReview/app/tests/test_api_p0.py @@ -126,6 +126,10 @@ def test_audit_open_reuse_and_remark(server): r2 = post(server, "/api/audit", body) assert r2["ok"] is True and r2["session_id"] == sid # 同名只留一个会话 assert r2["n_bill"] == 3 # 重写后的条数 + recent = get(server, "/api/sessions") + assert recent["ok"] is True and isinstance(recent["items"], list) + item = next(x for x in recent["items"] if x["id"] == sid) + assert item["all"] and item["all"][0]["id"] == sid rows2 = get(server, "/api/session/rows", session_id=sid, type="bill") assert rows2["total"] == 3 # ⚠️ 防翻倍回归:旧数据必须被清场 remark = _q(server["sessdb"], "SELECT x_remark FROM s_bills" diff --git a/CostReview/app/tests/test_export_structure.py b/CostReview/app/tests/test_export_structure.py index 4c9299d..3daa286 100644 --- a/CostReview/app/tests/test_export_structure.py +++ b/CostReview/app/tests/test_export_structure.py @@ -81,6 +81,13 @@ def test_new_bill_full_structure_cos(): assert we.get("Remark") == "" # 模板备注(别人的)不带 +def test_new_bill_empty_attr_cleared(): + """新增清单无特征:不得把锚点/模板的特征带过去(2026-10-20 220kV 实测)。""" + b = dict(NEW_BILL, Attr="") + we = _parse(xcos._bill_xml(b, "WorkElement", [], RICH_BILL)) + assert we.get("Attr") == "" + + def test_appended_norm_keeps_innards(): """采纳定额追加进原有清单:innards 一并克隆(此前裸 Norm 同样过不了结构关)。""" out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], xcos._full_norm_block(RICH_BILL)) @@ -249,6 +256,100 @@ def test_new_bill_top_anchor_position(server): assert txt.index('Name="顶部新增清单"') < txt.index('Number="B001"'), "新增清单应在第一条源清单之前" +def test_new_bill_follows_own_division(): + """新增清单落位按自己的 div_id 找同分部锚点——2026-10-20 220kV 实测: + C20原色透水混凝土 div=支撑下挖土,但前一条源清单在顶管井部分,旧逻辑会插错分部。""" + xml = ( + '' + '' + '' + '' + '' + '' + '' + '') + + def bill(i, div, num, name, price): + return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "", + "Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price, + "src_remark": None, "x_tdel": 0} + + a, b = bill(1, 1, "A001", "源清单A", "10.00"), bill(2, 2, "B001", "源清单B", "20.00") + new = bill(3, 2, "C001", "新增透水混凝土", "53.23") + new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0}) + out = xcos.transform_unit(xml, ("U1", "UW1"), + {"item": [(1, a), (2, b)]}, + {"item": [new]}, {}, {}) + i_div_b = out.index('Name="DIV_B"') + i_new = out.index('Name="新增透水混凝土"') + i_b = out.index('Number="B001"') + assert i_div_b < i_new < i_b, out + + +def test_new_bill_middle_of_own_division(): + """分部内下插:锚点在同一个分部时,插在锚点源清单之后、下一条同分部源清单之前。""" + xml = ( + '' + '' + '' + '' + '' + '' + '' + '' + '') + + def bill(i, div, num, name, price): + return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "", + "Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price, + "src_remark": None, "x_tdel": 0} + + a1, a2, b1 = (bill(1, 1, "A1", "源A1", "10.00"), + bill(2, 1, "A2", "源A2", "20.00"), + bill(3, 2, "B1", "源B1", "30.00")) + new = bill(4, 1, "C1", "分部内新增", "30.00") + new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 3000.0}) + out = xcos.transform_unit(xml, ("U3", "UW3"), + {"item": [(1, a1), (2, a2), (3, b1)]}, + {"item": [new]}, {}, {}) + assert (out.index('Number="A1"') < out.index('Name="分部内新增"') + < out.index('Number="A2"')), out + + +def test_new_loose_bill_appends_at_end(): + """无分部(loose)新增行:工作台显示在单位工程树尾,导出也要落在本组最后, + 不能按 x_seq=1 跑到最前(2026-10-20 220kV 实测)。""" + xml = ( + '' + '' + '' + '' + '' + '' + '' + '') + + def bill(i, div, num, name, price): + return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "", + "Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price, + "src_remark": None, "x_tdel": 0} + + a, b = bill(1, 1, "A1", "源清单A", "10.00"), bill(2, 2, "B1", "源清单B", "20.00") + new = bill(3, None, "C1", "末尾新增清单", "53.23") + new.update({"_anchor": 0, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0}) + out = xcos.transform_unit(xml, ("U2", "UW2"), + {"item": [(1, a), (2, b)]}, + {"item": [new]}, {}, {}) + assert out.index('Number="B1"') < out.index('Name="末尾新增清单"'), out + + def test_amount_aggregate_row_price_never_synced(): """决策 106 补记九:广联达文件的「人工费」类汇总行是金额汇总行(数量=金额合计、 单价恒 1、单位=元)。会话里合并改价把它的单价改成资源口径(如人工 500 元/工日) diff --git a/CostReview/app/tests/test_manual_project.py b/CostReview/app/tests/test_manual_project.py new file mode 100644 index 0000000..8ac9d79 --- /dev/null +++ b/CostReview/app/tests/test_manual_project.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +"""创建入口退役及旧手工工程兼容回归;造数仅写隔离副本。""" +import base64 +import sqlite3 +import time + +from api_harness import PERIOD_202607, get, make_cos4, post, server # noqa: F401 + +CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500) +LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356") +AUDIT_BASE = {"province": "广东省", "city": "珠海市", "district": "香洲区", + "period_from": PERIOD_202607, "period_to": PERIOD_202607, "file_kind": 1} + + +def _legacy_manual(server, name): + con = sqlite3.connect(server["sessdb"]) + try: + cur = con.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to, + src_name, imported_at, x_manual) VALUES(?,?,?,?,?,?,1)""", + (name, PERIOD_202607, PERIOD_202607, PERIOD_202607, "", + time.strftime("%Y-%m-%d %H:%M:%S"))) + con.commit() + return cur.lastrowid + finally: + con.close() + + +def _upload(server, path, name): + with open(path, "rb") as f: + raw = f.read() + r = post(server, "/api/admin/upload", + {"name": name, "data": base64.b64encode(raw).decode("ascii")}) + assert r["ok"] is True, r + return r["path"] + + +def _item(server, sid): + return next((x for x in get(server, "/api/sessions")["items"] if x["id"] == sid), None) + + +def test_create_endpoint_retired(server): + before = {x["id"] for x in get(server, "/api/sessions")["items"]} + r = server["client"].post("/api/session/create", + json={"name": "不应创建的工程", "period_from": PERIOD_202607}) + assert r.status_code == 404, r.text + assert r.json()["error"] == "not found" + assert {x["id"] for x in get(server, "/api/sessions")["items"]} == before + assert "/api/session/create" not in server["client"].get("/api/schema").text + page = server["client"].get("/workbench.html").text + assert "createProject" not in page and "创建工程" not in page + assert 'onclick="doOpen()"' in page + + +def test_legacy_manual_project_guards_and_delete(server): + sid = _legacy_manual(server, "旧手工工程A") + it = _item(server, sid) + assert it is not None and it["manual"] is True and it["src_name"] == "" + assert it["can_reparse"] is False + assert get(server, "/api/session/rows", session_id=sid, type="bill")["total"] == 0 + assert get(server, "/api/session/raw/tree", session_id=sid) is not None + meta = get(server, "/api/session/export/meta", session_id=sid) + assert meta["ok"] is False and "手工工程" in meta["msg"] + rp = post(server, "/api/session/reparse", {"session_id": sid}) + assert rp["ok"] is False and "手工工程" in rp["msg"] + assert post(server, "/api/session/delete", {"ids": [sid]})["ok"] is True + assert _item(server, sid) is None + + +def test_legacy_manual_project_supply_source_restores(server): + sid = _legacy_manual(server, "旧手工工程B") + p = make_cos4(str(server["src_dir"] / "manualB.cos4"), "旧手工工程B", [CAM], [LME_CAM]) + up = _upload(server, p, "manualB.cos4") + a = post(server, "/api/audit", dict(AUDIT_BASE, path=up, name="旧手工工程B")) + assert a["ok"] is True and a["session_id"] == sid, a + it = _item(server, sid) + assert it is not None and it["manual"] is False and it["src_name"] + assert get(server, "/api/session/rows", session_id=sid, type="bill")["total"] > 0 diff --git a/CostReview/app/tests/test_session_delete_async.py b/CostReview/app/tests/test_session_delete_async.py new file mode 100644 index 0000000..4e32516 --- /dev/null +++ b/CostReview/app/tests/test_session_delete_async.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +"""最近审核删除回归(2026-10-19 两段式): + ① 接口只删会话行、立即返回;子表/备注/源文件由后台清理; + ② 后台恰好也有同一份源文件时,源文件/备注/批次保留(决策 110 例外)。 +""" +import base64 +import os +import sqlite3 +import time + +from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: F401 + +CAM = ("030507008001", "高清网络摄像机", "1、400万像素;2、H.265", "台", 10, 1500) +LME_CAM = ("000001", "网络摄像机", "400万", "台", "1200", "1356") +AUDIT_BASE = {"province": "广东省", "city": "珠海市", "district": "香洲区", + "period_from": PERIOD_202607, "period_to": PERIOD_202607, "file_kind": 1} + + +def _q(db, sql, args=()): + con = sqlite3.connect("file:%s?mode=ro" % db, uri=True) + try: + return con.execute(sql, args).fetchall() + finally: + con.close() + + +def _upload(server, path, name): + with open(path, "rb") as f: + raw = f.read() + r = post(server, "/api/admin/upload", + {"name": name, "data": base64.b64encode(raw).decode("ascii")}) + assert r["ok"] is True, r + return r["path"] + + +def _wait(fn, timeout=10.0): + end = time.time() + timeout + while time.time() < end: + if fn(): + return True + time.sleep(0.1) + return False + + +def _add_remark(server, sid, text): + rows = get(server, "/api/session/rows", session_id=sid, type="bill") + post(server, "/api/session/remark", {"bill_id": rows["rows"][0][0], "remark": text}) + + +def test_delete_async_no_backend(server): + p = make_cos4(str(server["src_dir"] / "asyncA.cos4"), "异步删除A", [CAM], [LME_CAM]) + up = _upload(server, p, "asyncA.cos4") + sid = post(server, "/api/audit", dict(AUDIT_BASE, path=up, name="异步删除A"))["session_id"] + _add_remark(server, sid, "异步删除备注A") + + t0 = time.time() + r = post(server, "/api/session/delete", {"ids": [sid]}) + dt = time.time() - t0 + assert r["ok"] is True, r + assert dt < 2.0, "删除接口应快速返回,实测 %.2fs" % dt + # 第一段:会话行立刻没了(界面据此立即消行) + assert _q(server["sessdb"], "SELECT COUNT(*) FROM sessions WHERE id=?", (sid,))[0][0] == 0 + # 第二段:后台把子表、备注、源文件清干净 + assert _wait(lambda: _q(server["sessdb"], + "SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 0) + assert _wait(lambda: _q(server["sessdb"], + "SELECT COUNT(*) FROM s_remarks WHERE remark=?", + ("异步删除备注A",))[0][0] == 0) + assert _wait(lambda: not os.path.exists(up)) + + +def test_delete_async_backend_same_source_keeps(server): + p = make_cos4(str(server["src_dir"] / "asyncB.cos4"), "异步删除B", [CAM], [LME_CAM]) + up = _upload(server, p, "asyncB.cos4") + imp = post(server, "/api/admin/import", + dict(META, path=up, name="异步删除B", file_kind=1)) + assert imp["ok"] is True, imp + bid = imp["batch_id"] + sid = post(server, "/api/audit", dict(AUDIT_BASE, path=up, name="异步删除B"))["session_id"] + _add_remark(server, sid, "异步删除备注B") + + r = post(server, "/api/session/delete", {"ids": [sid]}) + assert r["ok"] is True, r + assert _q(server["sessdb"], "SELECT COUNT(*) FROM sessions WHERE id=?", (sid,))[0][0] == 0 + assert _wait(lambda: _q(server["sessdb"], + "SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 0) + time.sleep(0.8) # 等后台跑完备注/文件阶段 + assert _q(server["sessdb"], "SELECT COUNT(*) FROM s_remarks WHERE remark=?", + ("异步删除备注B",))[0][0] >= 1 + assert os.path.exists(up) + assert _q(server["db"], "SELECT COUNT(*) FROM batches WHERE id=?", (bid,))[0][0] == 1 diff --git a/CostReview/app/tests/test_swt_import.py b/CostReview/app/tests/test_swt_import.py new file mode 100644 index 0000000..4f4b4a3 --- /dev/null +++ b/CostReview/app/tests/test_swt_import.py @@ -0,0 +1,316 @@ +# -*- coding: utf-8 -*- +"""SWT(深圳市工程造价数据交换标准 SJG77-2020)导入回归。 + +覆盖: + · 项目/单项/单位/分部/清单/定额/措施/工料机/汇总 的层级映射; + · ResourceID 是单位工程内部编号——两个单位工程用同一个 ResourceID 指不同编码, + norm_res 必须各归各的(这是 SWT 与 COS 最大的结构差异); + · 税率口径 A(2026-10-19 主人定):SWT 资源只有一个 Rate, + NoTaxPrice = TaxPrice = Rate、TaxRate = 0; + · 重新解析可重跑;原格式导出走「骨架+填空」回写(SWT/SWZ 同名后缀); + · 后台批次导入与工作台会话导入共用同一套解析/写库。 +""" +import base64 +import io +import sqlite3 +import zipfile +import xml.etree.ElementTree as ET + +from api_harness import META, get, make_swt, post, server # noqa: F401 + +UNITS = [ + {"id": "11", "name": "建筑工程", "total": 1000, "a": 800, "b": 100, "b1": 100, + "c": 0, "d": 100, "e": 1000, + "bills": [{"code": "010101001001", "name": "清单一", "feature": "特征一", + "unit": "m3", "qty": 10, "rate": 50, + "norms": [{"code": "N1", "name": "定额一", "unit": "10m3", "qty": 1, + "rate": 500, "res": [(1, 2.5)]}]}], + "resources": [{"id": 1, "code": "R00001", "name": "普工", "unit": "元", + "rate": 1.5, "qty": 25, "kind": 1}], + "measures": [{"id": "m1", "code": "1", "name": "安全文明施工费", "total": 100, + "children": [{"id": "m2", "code": "(1)", "name": "子措施", + "total": 100}]}]}, + {"id": "12", "name": "装饰工程", "total": 234.56, "a": 200, "b": 0, "b1": 0, + "c": 0, "d": 34.56, "e": 234.56, + "bills": [{"code": "020101001001", "name": "清单二", "feature": "特征二", + "unit": "m2", "qty": 10, "rate": 20, + "norms": [{"code": "N2", "name": "定额二", "unit": "10m2", "qty": 1, + "rate": 200, "res": [(1, 0.5)]}]}], + "resources": [{"id": 1, "code": "C00001", "name": "钢材", "spec": "δ=8mm", + "unit": "t", "rate": 2.0, "qty": 100, "kind": 2}]}, +] + + +def _q(db, sql, args=()): + con = sqlite3.connect(db) + try: + return con.execute(sql, args).fetchall() + finally: + con.close() + + +def _upload(server, path, name): + """走真实「打开工程」路径:文件先传进 uploads,src_name 才能被重新解析找到。""" + with open(path, "rb") as f: + raw = f.read() + r = post(server, "/api/admin/upload", + {"name": name, "data": base64.b64encode(raw).decode("ascii")}) + assert r["ok"] is True, r + return r["path"] + + +def test_swt_open_map_reparse_export_meta(server): + src = str(server["src_dir"] / "swt_open.swt") + make_swt(src, "SWT测试工程", UNITS) + p = _upload(server, src, "swt_open.swt") + r = post(server, "/api/audit", dict(META, path=p, name="SWT工程A")) + assert r["ok"] is True, r + sid = r["session_id"] + db = server["sessdb"] + + # 项目级 + x_total, x_info, x_feat, src = _q( + db, "SELECT x_total,x_info,x_feat,src_name FROM sessions WHERE id=?", (sid,))[0] + assert x_total == 1234.56 + assert "深圳市工程造价数据交换标准" in x_info and "编制人" in x_feat + assert src.lower().endswith(".swt") + + # 单项 / 单位 / 造价构成 + secs = _q(db, "SELECT id,Number,Name,Total FROM s_sections WHERE session_id=?", (sid,)) + assert len(secs) == 1 and secs[0][1:] == ("1", "单项一", 1234.56) + sec_id = secs[0][0] + uws = _q(db, """SELECT Number,Name,Total,section_id,Construction, + DivisionalAndElementalWorks,Preliminaries,CostForHSE, + SundryCosts,Tax + FROM s_unit_works WHERE session_id=? ORDER BY id""", (sid,)) + assert [x[0] for x in uws] == ["11", "12"] + assert all(x[3] == sec_id for x in uws) + assert uws[0][4:] == (900.0, 800.0, 100.0, 100.0, 0.0, 100.0) + assert uws[1][4:] == (200.0, 200.0, 0.0, 0.0, 0.0, 34.56) + + # 分部:单位1 分部分项标题 / 措施标题 / 措施分组(嵌套);单位2 分部分项标题 + divs = _q(db, "SELECT id,parent_id,Kind,Number,Name FROM s_divides" + " WHERE session_id=? ORDER BY id", (sid,)) + assert len(divs) == 4 + assert (divs[0][2], divs[0][4]) == ("item", "整个项目") + assert (divs[1][2], divs[1][4]) == ("prelim", "措施项目") + assert (divs[2][2], divs[2][3], divs[2][4]) == ("prelim", "1", "安全文明施工费") + assert divs[2][1] == divs[1][0] # 分组挂在措施标题下 + assert (divs[3][2], divs[3][4]) == ("item", "整个项目") + + # 清单:2 条清单 + 1 条措施叶子;措施叶子挂到分组,不挂标题 + bills = {x[0]: x for x in _q( + db, "SELECT Number,Name,Unit,Quantity,Price,Total,Kind,uw_id,div_id" + " FROM s_bills WHERE session_id=?", (sid,))} + assert len(bills) == 3 + assert bills["010101001001"][2:6] == ("m3", 10.0, 50.0, 500.0) + assert bills["010101001001"][6] is None + assert bills["020101001001"][2:6] == ("m2", 10.0, 20.0, 200.0) + assert bills["(1)"][6] == "prelim" and bills["(1)"][8] == divs[2][0] + + # 定额 + 消耗:同名 ResourceID=1 在两个单位工程分别解析为 R00001 / C00001 + norms = {x[0]: x[1:] for x in _q( + db, """SELECT n.Number,n.Unit,n.Quantity,n.Price,n.Total + FROM s_norms n JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=?""", (sid,))} + assert norms["N1"] == ("10m3", 1.0, 500.0, 500.0) + assert norms["N2"] == ("10m2", 1.0, 200.0, 200.0) + nres = _q(db, """SELECT n.Number,r.res_code,r.qty FROM s_norm_res r + JOIN s_norms n ON n.id=r.norm_id + JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=? ORDER BY n.Number""", (sid,)) + assert nres == [("N1", "R00001", 2.5), ("N2", "C00001", 0.5)] + + # 工料机 + 税率口径 A:除税价=含税价=Rate、税率 0 + lmes = {x[0]: x[1:] for x in _q( + db, "SELECT Number,Name,Unit,Quantity,NoTaxPrice,TaxRate,TaxPrice,Kind" + " FROM s_lmes WHERE session_id=?", (sid,))} + assert lmes["R00001"] == ("普工", "元", 25.0, 1.5, 0.0, 1.5, 1) + assert lmes["C00001"] == ("钢材", "t", 100.0, 2.0, 0.0, 2.0, 2) + assert _q(db, "SELECT COUNT(*) FROM s_lme_uw WHERE session_id=?", (sid,))[0][0] == 2 + assert dict(_q(db, "SELECT code,qty FROM s_lme_proj WHERE session_id=?", (sid,))) == { + "R00001": 25.0, "C00001": 100.0} + for row in _q(db, "SELECT ntp,taxp,taxrate FROM s_lme_proj WHERE session_id=?", (sid,)): + assert row[0] is not None and row[1] == row[0] and row[2] == 0.0 + for row in _q(db, "SELECT ntp,taxrate,taxp FROM s_lme_uw WHERE session_id=?", (sid,)): + assert row[0] is not None and row[1] == 0.0 and row[2] == row[0] + + # 重新解析:SWT 源文件可重跑,条数不变 + rp = post(server, "/api/session/reparse", {"session_id": sid}) + assert rp["ok"] is True, rp + assert _q(db, "SELECT COUNT(*) FROM s_bills WHERE session_id=?", (sid,))[0][0] == 3 + assert _q(db, """SELECT COUNT(*) FROM s_norm_res r JOIN s_norms n ON n.id=r.norm_id + JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=?""", (sid,))[0][0] == 2 + + # 原格式导出:建议名保留源后缀(SWT/SWZ 都走骨架回写) + m = get(server, "/api/session/export/meta", session_id=sid) + assert m["ok"] is True and m["name"].lower().endswith(".swt") + + +def test_swt_batch_import(server): + src = str(server["src_dir"] / "swt_batch.swt") + make_swt(src, "SWT批次工程", UNITS) + p = _upload(server, src, "swt_batch.swt") + r = post(server, "/api/admin/import", dict(META, path=p, name="SWT批次A")) + assert r["ok"] is True, r + bid = r["batch_id"] + db = server["db"] + assert _q(db, "SELECT x_total FROM batches WHERE id=?", (bid,))[0][0] == 1234.56 + assert _q(db, "SELECT COUNT(*) FROM bills WHERE batch_id=?", (bid,))[0][0] == 3 + assert _q(db, "SELECT COUNT(*) FROM norms WHERE bill_id IN" + " (SELECT id FROM bills WHERE batch_id=?)", (bid,))[0][0] == 2 + assert _q(db, "SELECT COUNT(*) FROM lmes WHERE batch_id=?", (bid,))[0][0] == 2 + assert _q(db, "SELECT COUNT(*) FROM lme_uw WHERE batch_id=?", (bid,))[0][0] == 2 + assert _q(db, "SELECT COUNT(*) FROM lme_proj WHERE batch_id=?", (bid,))[0][0] == 2 + nres = _q(db, """SELECT n.Number,r.res_code,r.qty FROM norm_res r + JOIN norms n ON n.id=r.norm_id + WHERE n.bill_id IN (SELECT id FROM bills WHERE batch_id=?) + ORDER BY n.Number""", (bid,)) + assert nres == [("N1", "R00001", 2.5), ("N2", "C00001", 0.5)] + + +def _f(x): + try: + return float(x) + except Exception: + return None + + +def test_swt_export_roundtrip_edits(server): + """原格式导出(骨架+填空):改名/改量、临删、新增清单都要回写,汇总按现量重算, + 导出的 SWT 还能再次被本软件解析。""" + src = str(server["src_dir"] / "swt_export.swt") + make_swt(src, "SWT导出工程", UNITS) + p = _upload(server, src, "swt_export.swt") + r = post(server, "/api/audit", dict(META, path=p, name="SWT导出工程A")) + assert r["ok"] is True, r + sid = r["session_id"] + db = server["sessdb"] + bills = _q(db, "SELECT id,Number FROM s_bills WHERE session_id=? AND Kind IS NULL" + " ORDER BY id", (sid,)) + assert len(bills) == 2 + b1, b2 = bills[0][0], bills[1][0] + assert post(server, "/api/session/bill/op", + {"op": "edit", "bill_id": b1, + "fields": {"Name": "清单一改", "Quantity": 20}})["ok"] + assert post(server, "/api/session/bill/op", {"op": "tdel", "bill_id": b2})["ok"] + ins = post(server, "/api/session/bill/op", {"op": "insert_below", "bill_id": b1}) + assert ins["ok"], ins + assert post(server, "/api/session/bill/op", + {"op": "edit", "bill_id": ins["id"], + "fields": {"Name": "新增清单", "Attr": "新增特征", + "Quantity": 5}})["ok"] + + resp = server["client"].get("/api/session/export", params={"session_id": sid}) + assert resp.status_code == 200, resp.text[:300] + assert resp.content[:2] == b"' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '') + p = str(server["src_dir"] / "swz_blank.SWZ") + with open(p, "w", encoding="utf-8", newline="") as f: + f.write(xml) + up = _upload(server, p, "swz_blank.SWZ") + r = post(server, "/api/audit", dict(META, path=up, name="SWZ空白量单")) + assert r["ok"] is True, r + sid = r["session_id"] + db = server["sessdb"] + bills = _q(db, "SELECT Number,Quantity,Price,Total,Kind FROM s_bills" + " WHERE session_id=? ORDER BY id", (sid,)) + assert len(bills) == 2 + bq = [x for x in bills if x[0] == "010101001001"][0] + assert bq[1] == 100.0 and bq[2] is None and bq[3] is None + assert _q(db, """SELECT COUNT(*) FROM s_norms n JOIN s_bills b ON b.id=n.bill_id + WHERE b.session_id=?""", (sid,))[0][0] == 0 + assert _q(db, "SELECT COUNT(*) FROM s_lmes WHERE session_id=?", (sid,))[0][0] == 0 + assert _q(db, "SELECT x_total FROM sessions WHERE id=?", (sid,))[0][0] == 0.0 diff --git a/CostReview/app/tests/test_wipe.py b/CostReview/app/tests/test_wipe.py index 098a8ac..b2fddb4 100644 --- a/CostReview/app/tests/test_wipe.py +++ b/CostReview/app/tests/test_wipe.py @@ -82,3 +82,40 @@ def test_wipe_scoped_to_session_and_keeps_sessions_row(): def test_wipe_keep_list_has_documented_members(): """保留清单必须精确等于这两张表 —— 多了会漏清数据,少了会丢用户数据。""" assert session_job.WIPE_KEEP == {"s_remarks", "s_settings"} + + +def test_drop_orphan_rows_cleans_norm_orphans(tmp_path, monkeypatch): + """两段式删除兜底:会话行已删、后台没来得及清子表 → 启动自愈按父表引用清干净。""" + monkeypatch.setattr(session_job, "DB", str(tmp_path / "s.db")) + con = session_job.connect() + con.execute("INSERT INTO sessions(id,name,src_name) VALUES(1,'a','a')") + con.execute("INSERT INTO s_bills(id,session_id) VALUES(1,1)") + con.execute("INSERT INTO s_bills(id,session_id) VALUES(2,2)") # 孤儿清单(会话2已删) + con.execute("INSERT INTO s_norms(id,bill_id) VALUES(1,1)") + con.execute("INSERT INTO s_norms(id,bill_id) VALUES(2,2)") # 孤儿定额 + con.execute("INSERT INTO s_norm_res(id,norm_id) VALUES(1,1)") + con.execute("INSERT INTO s_norm_res(id,norm_id) VALUES(2,2)") # 孤儿消耗量 + con.commit(); con.close() + n = session_job.drop_orphan_rows() + con = session_job.connect() + assert con.execute("SELECT COUNT(*) FROM s_bills").fetchone()[0] == 1 + assert con.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0] == 1 + assert con.execute("SELECT COUNT(*) FROM s_norm_res").fetchone()[0] == 1 + con.close() + assert n >= 3 + + +def test_drop_orphan_remarks_only_when_no_host(tmp_path, monkeypatch): + """两段式删除兜底:备注源文件无会话/批次引用才删;有宿主整组保留。""" + monkeypatch.setattr(session_job, "DB", str(tmp_path / "s.db")) + con = session_job.connect() + con.execute("INSERT INTO sessions(id,name,src_name) VALUES(1,'a','a')") + con.execute("INSERT INTO s_remarks(id,src_key,rkey,remark) VALUES(1,'a','r1','keep')") + con.execute("INSERT INTO s_remarks(id,src_key,rkey,remark) VALUES(2,'b','r2','drop')") + con.commit(); con.close() + n = session_job.drop_orphan_remarks(set()) + assert n == 1 + con = session_job.connect() + rows = con.execute("SELECT src_key FROM s_remarks ORDER BY id").fetchall() + con.close() + assert [r[0] for r in rows] == ["a"] diff --git a/CostReview/app/ui/admin.html b/CostReview/app/ui/admin.html index edd747d..db6a509 100644 --- a/CostReview/app/ui/admin.html +++ b/CostReview/app/ui/admin.html @@ -113,9 +113,6 @@ td.name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .pager{display:flex;gap:8px;align-items:center;justify-content:flex-end;padding:8px 12px;font-size:13px;color:var(--muted)} a{color:var(--c2);text-decoration:none} a:hover{text-decoration:underline} -.tab .n{display:inline-block;margin-left:6px;padding:0 6px;border-radius:9px;background:rgba(255,255,255,.28); - font-size:11px;font-weight:700} -.tab:not(.on) .n{background:#c4d3e6;color:#234} .dlg .tabs{border-bottom:2px solid var(--c1)} .mask{position:fixed;inset:0;background:rgba(0,0,0,.35);display:none;align-items:center;justify-content:center;z-index:50} .mask.on{display:flex} @@ -227,7 +224,7 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb .newflag{display:inline-block;margin-left:6px;padding:0 5px;border-radius:3px;background:#fff7e6; border:1px solid #f0d9a8;color:#8a6d1a;font-size:11px} - +
@@ -247,11 +244,12 @@ td.pcell input{width:100%;padding:3px 7px;font-size:12.5px;border:1px solid #9fb + 2026-10-19 主人定:去掉 ▶ 图标,蓝底让位,尺寸样式对齐工作台顶栏按钮 + (28px 高 / 左右 12px / 12.5px 字号白底,与工作台「打开项目」同款)。 --> - ▶ 工作台 +
@@ -1260,15 +1258,6 @@ async function loadTab(pid, fresh){ if(pid==='p0'){ ldStage(30,'正在加载项目工料机…'); const d=await J(`/api/admin/batch/${DID}/lme`); - n0.textContent=d.total+' 项'; - if(!n1.textContent) { /* 首次也把另两个数量取出来 */ - // 2026-10-13 主人定进度条:这两个是重计算接口(南屏 1.5 万条清单各要 6s+), - // 必须分段报阶段,否则首开工料机标签像卡死 - ldStage(55,'正在统计组价不一致(同名同规格比对,工程大要稍等)…'); - const a=await J(`/api/admin/batch/${DID}/inconsistent`); n1.textContent=a.total+' 组'; - ldStage(75,'正在统计类似清单分组(工程大要稍等)…'); - const b=await J(`/api/admin/batch/${DID}/similar`); n2.textContent=b.total+(b.extra||[]).length+' 组'; - } ALME_ROWS=d.rows||[]; ALME_SORT={k:-1,dir:1}; // 新批次:排序复位(同工作台换数据) cg.innerHTML=colgHTML(AC_LME); // 后台列=共享层派生(noWB 剔除工作台独有的取消采纳列) flexFit($('dtb'), AC_LME); // 与工作台同款:伸缩列撑满容器(2026-10-08 主人定) @@ -1285,8 +1274,6 @@ async function loadTab(pid, fresh){ const url = pid==='p1' ? `/api/admin/batch/${DID}/inconsistent` : `/api/admin/batch/${DID}/similar` + (fresh ? '?fresh=1' : ''); const d=await J(url); - // 徽标含落单组(与左树根一致,2026-10-11 主人定);组价不一致 extra 恒空、数值不变 - (pid==='p1'?n1:n2).textContent=d.total+(d.extra||[]).length+' 组'; BILL_SORT={k:-1,dir:1}; // 新数据:组内排序复位(2026-10-10) cg.innerHTML=colgHTML(AC_BILL); sumw($('dtb')); colwApply($('dtb')); // 后台列=noWB 派生(隐藏取消采纳) // 2026-10-10 主人定:类似清单/组价不一致表头都可点=在展开的组内排序(与工作台同款) @@ -1320,13 +1307,14 @@ async function openImp(){ ifile.value=''; UPF=null; iname.value=''; iname.dataset.auto=''; // 每次重新带出文件名 // 2026-10-12 重设计(主人定):价格类**只收标准模板 .xlsx**(HTML 导入退役); - // 工程类只认计价文件 **.cos4 / .cos**(主人 2026-10-06)。 - ifile.accept = isPrice ? '.xlsx' : '.cos4,.cos'; + // 工程类认计价文件 **.cos4 / .cos**;2026-10-19 加 **.swt / .swz** + //(深圳数据交换标准,散装 XML 或压缩包内 XML;扩展名不分大小写)。 + ifile.accept = isPrice ? '.xlsx' : '.cos4,.cos,.swt,.swz'; document.getElementById('ifileInfo').textContent=''; document.getElementById('irowTip').textContent = isPrice ? '信息价/市场价:只收「标准模板」Excel(.xlsx,每次一个)+ 附件原件(任意格式,选填)。' + '名称留空或点文件后自动带出文件名(可改);期次留空时自动从文件名里认(如「珠海信息价_2026年7月」→ 2026-07)。' - : '工程:选择一个 .cos4 或 .cos 文件(可从电脑任意位置选,每次只能一个)。全部必填。'; + : '工程:选择一个 .cos4 / .cos / .swt / .swz 文件(可从电脑任意位置选,每次只能一个)。全部必填。'; imsg.textContent=''; await loadImpFilters(); } @@ -1338,9 +1326,10 @@ async function pickFile(inp){ const r = await uploadFile('/api/admin/upload', f); if(!r.ok){ info.textContent='× '+r.msg; UPF=null; return; } UPF=r; - // 2026-10-12 重设计:价格类只认标准模板 Excel;工程类只认 .cos4/.cos + // 2026-10-12 重设计:价格类只认标准模板 Excel;工程类认 .cos4/.cos; + // 2026-10-19 加 .swt(深圳数据交换标准,classify 返回 "swt") const ok = (KIND!=='project') ? (r.state==='price_xlsx') - : (r.state==='zip'||r.state==='xml'); + : (r.state==='zip'||r.state==='xml'||r.state==='swt'); info.textContent = ok ? `已选:${r.name}(${(r.size/1048576).toFixed(2)} MB)· 已存进软件目录` : `已选:${r.name},但这不是${KIND!=='project'?'标准模板 Excel(请点「标准模板」按钮下载后填写)':'计价工程文件'},无法导入`; diff --git a/CostReview/app/ui/common.css b/CostReview/app/ui/common.css index e92c1bc..79d274d 100644 --- a/CostReview/app/ui/common.css +++ b/CostReview/app/ui/common.css @@ -7,6 +7,8 @@ 依赖变量:--c1 主色 / --c2 次色 / --line 分隔线 / --muted 次要文字 / --head 表头底色 ============================================================ */ +#tabbar .tab, #dtabs .tab{height:24px;min-height:24px;max-height:24px;flex-shrink:0;align-self:flex-end} + /* ---- 原数据:左侧目录树 + 右侧标签卡 ---- */ .rawbox{display:flex;height:100%;min-height:0} .rawtree{width:300px;flex:none;border-right:1px solid var(--line);overflow:auto;padding:6px 4px;background:#fcfdfe} diff --git a/CostReview/app/ui/common.js b/CostReview/app/ui/common.js index 4d1f7a4..4241c44 100644 --- a/CostReview/app/ui/common.js +++ b/CostReview/app/ui/common.js @@ -89,10 +89,10 @@ const TABS = [ ]; const TAB_DEFAULT = 'p3'; function tabsHTML() { - // 2026-10-11 主人定:原数据标签**不挂徽标**(n3 从未有数据源,恒显 0 误导);其余标签徽标保留 + // 2026-10-20 主人定:四个页签保留、计数徽标全部取消(覆盖决策 35「其余三个标签徽标保留」) return TABS.map(t => `
` - + `${t.name}${t.p === 'p3' ? '' : '0'}
`).join(''); + + `${t.name}
`).join(''); } /* 标签点击 → 转交各页自己的切换函数。 工作台:window.onWBTab = tab; 后台:window.onWBTab = loadTab; @@ -2564,7 +2564,7 @@ function licActivate() { + 'align-items:center;justify-content:center;z-index:130'; d.innerHTML = '
' - + '
正在加载
' + + '
正在加载
' + '
' + '
' + '