diff --git a/CostReview/app/core/import_job.py b/CostReview/app/core/import_job.py index 4249196..c180e1a 100644 --- a/CostReview/app/core/import_job.py +++ b/CostReview/app/core/import_job.py @@ -109,6 +109,10 @@ def sniff(path): # 认出来单独走 parse_swt;其余散装 xml 仍按原口径拒绝(决策:不再支持 xml 格式)。 if 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("Price")), f(a.get("Total")))) + elif tag == "ResElementItem": + # 定额消耗(在 Norm 内)或清单级资源引用(ResElements 直挂 Bill)——后者跳过 + if st["cur_norm"] >= 0: + out["norm_res"].append((st["cur_norm"], (a.get("ResCode") or "").strip(), + f(a.get("Quantity")), None)) + elif tag == "ExpressItem": + # 工程量表达式(清单/定额都可有):GCL 公式原样(会话库 qty_expr 通道) + if st["cur_norm"] < 0 and st["cur_bill"] >= 0: + ex = (a.get("Express") or "").strip() + if ex: + out.setdefault("bill_expr", {})[st["cur_bill"]] = ex + elif tag == "ResourceItem": + code = (a.get("Code") or "").strip() + if not code: + pass + elif st["unit"] is not None and st.get("_uw_res"): + # 单位工程自带 Resource(样本未见,防未来变体):本单位另存一份 + price = f(a.get("Price")) + qty = f(a.get("Quantity")) + nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip() + kd = (a.get("Kind") or "").strip() or None + out["lmes"].append((code, nm, sp, un, price, 0.0, price, qty, kd)) + out["lme_uw"].append((st["unit"]["idx"], code, nm, sp, un, price, 0.0, + price, qty, kd, None, None, None, None)) + elif st["unit"] is None: + # 项目级 Resource 价格表 → lme_lib/lme_proj(决策 122 A:除税=含税=Price) + price, org = f(a.get("Price")), f(a.get("OrgPrice")) + qty = f(a.get("Quantity")) + nm, sp, un = (a.get("Name") or "").strip(), (a.get("Specification") or "").strip(), (a.get("Unit") or "").strip() + kd = (a.get("Kind") or "").strip() or None + out["lme_lib"].setdefault(code, [nm, sp, un, kd, org, price]) + out["lme_name"].setdefault(code, nm) + p = out["lme_proj"].get(code) + if p is None: + out["lme_proj"][code] = [nm, sp, un, kd, qty or 0.0, price, price, 0.0] + else: + p[4] = (p[4] or 0.0) + (qty or 0.0) + p[5] = price + p[6] = price + elif tag == "Resource": + st["_uw_res"] = st["unit"] is not None # 区分项目级/单位级 Resource 容器 + elif tag == "SummaryItem": + # 单位汇总分析树:文档序(父先子后),kind/number 按层级—— + # ESCC 无 Number,用组/行区分(kind='grp' 有子级不行——iterparse 无法预知, + # 统一 kind='item'+number 按 Top 级编码;前端按 Formula 层级不依赖 number 归层, + # 与 parse_std 的 proj_summary 同结构入库(uw 层走 uw_summary)。 + rec = {"kind": "item", "number": (a.get("Code") or "").strip() or None, + "code": (a.get("Code") or "").strip() or None, + "name": a.get("Name"), "formula": a.get("Formula"), + "rate": f(a.get("Rate")), "total": f(a.get("Total")), + "remark": (a.get("Remark") or "").strip()} + if st["unit"] is not None: + out.setdefault("uw_summary", {}).setdefault(st["unit"]["idx"], []).append(rec) + else: # end + if tag == "ProjectItem": + u = st["unit"] + if u is not None: + pc = pi_cost = None + pc = costs_from(el.find("ProjectCosts")) if el.find("ProjectCosts") is not None else {} + if pc: + out["uw_cost"][u["idx"]] = pc + st["unit"] = None + st["in_bill"] = st["in_measure"] = False + st["div_stack"] = [] + st["mdiv_stack"] = [] + st["cur_bill"] = st["cur_norm"] = -1 + elif tag == "ProjectGroup": + if st["sp"] is not None and st["sp"]["uw_nums"]: + key = (st["sp"]["name"] or "", st["sp"]["number"] or "", + tuple(st["sp"]["uw_nums"])) + if key not in st["sec_seen"]: # 重名单项组去重(样本 Group Name 全是 "1") + st["sec_seen"].add(key) + out["sections"].append(st["sp"]) + st["sp"] = None + elif tag == "BillTable": + st["in_bill"] = False + elif tag == "MeasureTable": + st["in_measure"] = False + elif tag in ("Branch",): + if st["in_measure"] and st["mdiv_stack"]: + st["mdiv_stack"].pop() + elif st["in_bill"] and st["div_stack"]: + st["div_stack"].pop() + elif tag == "Bill": + st["cur_bill"] = -1 + st["cur_norm"] = -1 + elif tag == "Norm": + st["cur_norm"] = -1 + el.clear() + + # 项目级汇总分析(根 Summary:项目层 ZZJ/QDF/…树)→ proj_summary(决策 244 通道) + # 根下 Summary 在 ProjectGroup 之外(样本:根直接有一个 Summary;单位级在 ProjectItem 内同名)。 + # iterparse 已经按单位收走单位级;这里补收项目级:重扫一次太贵——改为上面 start 时 + # st["unit"] is None 且父链在根 → 其实 iterparse 拿不到父链,改用文件级二遍小解析: + # 只取 Projects 直接子 Summary(rfind 用 ElementTree 一次即可,量小)。 + try: + _root = ET.parse(path).getroot() + _sum = _root.find("Summary") + if _sum is not None: + for si in _sum.iter("SummaryItem"): + out.setdefault("proj_summary", []).append({ + "kind": "item", "number": (si.get("Code") or "").strip() or None, + "code": (si.get("Code") or "").strip() or None, + "name": si.get("Name"), "formula": si.get("Formula"), + "rate": f(si.get("Rate")), "total": f(si.get("Total")), + "ratios": f(si.get("Rate")), "remark": (si.get("Remark") or "").strip()}) + # 项目级 AttrInfos → feat(项目特征条目,最多 60,名称去重) + for ai in _root.iter("AttrInfoItem"): + nm = (ai.get("Name") or ai.get("Code") or "").strip() + if not nm: + continue + _f = out.setdefault("feat", []) + if all(x[0] != nm for x in _f) and len(_f) < 60: + _f.append((nm, ai.get("Value") or "")) + # 项目级 InfoList 的关键条目并入 info(弹框兜底信息) + _info = out.setdefault("info", {}) + for ii in _root.iter("InfoItem"): + _c = (ii.get("Code") or "").strip() + _v = (ii.get("Value") or "").strip() + if _c and _v and _c not in _info: + _info[_c] = _v + except ET.ParseError: + pass + + # 总造价兜底:Projects@Total 缺失时用各单位工程 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 "ESCC2" + + def _zip_swt_member(z): """在 zip 里找根节点 ConstructProject 的 XML。 @@ -975,9 +1229,11 @@ def parse_file(path, out): return parse_std(path, out) if st == "swt": return parse_swt(path, out) + if st == "esc": + return parse_esc(path, out) if st == "xml": - raise ValueError("这个 XML 不是已知的计价结构(当前支持:COS/COS4 压缩包、SWT/SWZ 数据交换标准;" - "同族新后缀可直接打开,扩展名不拦)") + raise ValueError("这个 XML 不是已知的计价结构(当前支持:COS/COS4 压缩包、SWT/SWZ、" + "ESCC2.0 广东省标准;同族新后缀可直接打开,扩展名不拦)") if st == "encrypted": raise ValueError("这是加密件,无法解析") raise ValueError("文件头无法识别,不是计价文件") diff --git a/CostReview/app/tests/test_api_p0.py b/CostReview/app/tests/test_api_p0.py index 7a37fda..e76822b 100644 --- a/CostReview/app/tests/test_api_p0.py +++ b/CostReview/app/tests/test_api_p0.py @@ -78,8 +78,9 @@ def test_import_unknown_rejected(server): def test_import_xml_rejected(server): + # 2026-11-03:Projects 根现在是合法 ESCC2 格式(parse_esc),未知 XML 改用无名根 p = server["src_dir"] / "old.xml.cos4" - p.write_bytes(b'') + p.write_bytes(b'') r = post(server, "/api/admin/import", dict(META, path=str(p), name="老xmlT")) assert r["ok"] is False and "xml" in r["msg"] diff --git a/CostReview/app/tests/test_esc_import.py b/CostReview/app/tests/test_esc_import.py new file mode 100644 index 0000000..4e259de --- /dev/null +++ b/CostReview/app/tests/test_esc_import.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +"""ESCC2.0(广东省造价数据标准 DBJ/T 15-145-2018)明文 XML 解析回归。 +2026-11-03 主人定:恢复散装 xml 中 ESCC 支持(推翻 2026-10-01「不再支持 xml」的 ESCC 部分)。 +样本:后台需要导入的项目/y程ESCC2.xml(珠海高新区 2024 地灾治理,7 单位工程,变更工程负量)。""" +import os +import sys + +import pytest + +from api_harness import post, server # noqa: F401 (夹具) + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core")) +import import_job as ij # noqa: E402 + +SAMPLE = os.path.join(os.path.dirname(__file__), "..", "..", "..", + "后台需要导入的项目", "y程ESCC2.xml") + + +def test_parse_esc_dry(): + """干跑:容器行数与关键值与样本实测一致。""" + out = {"uw": [], "bills": [], "norms": [], "lmes": []} + kind = ij.parse_esc(SAMPLE, out) + assert kind == "ESCC2" + assert out["proj_name"] == "珠海市高新区2024年地质灾害隐患点、风险点治理工程" + assert out["total"] == pytest.approx(-238931.60, abs=0.01) + assert len(out["uw"]) == 7 # 2 单项组(4+3)单位工程 + assert len(out["sections"]) == 2 + assert len(out["bills"]) == 186 # 分部分项 65 + 措施 121 + assert sum(1 for k in out["bill_kind"] if k == "prelim") == 121 + assert len(out["norms"]) == 127 # WorkContent 组内定额全收 + assert len(out["norm_res"]) == 698 # 定额消耗 + assert len(out["lme_proj"]) == 126 # 项目级 Resource 价格表 + assert len(out["lme_uw"]) == 512 # 单位级 Resource 全收(96+72+40 ×2 +96) + assert len(out["uw_cost"]) == 7 + assert len(out["uw_summary"]) == 7 # 单位级 Summary 树(样本无项目级) + assert len(out["bill_expr"]) == 186 # 清单工程量表达式 + # 负数量/负合价原样保真(变更工程特性) + b0 = out["bills"][0] + assert b0[0] == "010102001004" and b0[1] == "孤石清理" + assert b0[4] == pytest.approx(-170.0) and b0[6] == pytest.approx(-9661.10) + # 措施分部嵌套(样本 13 层 Branch/Branch)→ parent 链正确 + md = [d for d in out["divides"] if d["kind"] == "prelim"] + assert len(md) == 105 + by_idx = {i: d for i, d in enumerate(out["divides"])} + for d in md: + if d["parent"] is not None: + assert by_idx[d["parent"]]["kind"] == "prelim" + + +def test_parse_file_dispatch_esc(): + """sniff/parse_file 分流:根节点 Projects → parse_esc;其他散装 XML 仍拒绝。""" + assert ij.sniff(SAMPLE) == "esc" + out = {"uw": [], "bills": [], "norms": [], "lmes": []} + assert ij.parse_file(SAMPLE, out) == "ESCC2" + # 未知散装 XML 仍报错 + import tempfile + p = os.path.join(tempfile.gettempdir(), "not_priced.xml") + with open(p, "w", encoding="utf-8") as fh: + fh.write('') + try: + with pytest.raises(ValueError): + ij.parse_file(p, {"uw": [], "bills": [], "norms": [], "lmes": []}) + finally: + os.unlink(p) + + +def test_esc_open_via_audit(server): + """端到端:走 /api/audit 真实入库(批次库),断言库内行数与树结构。""" + p = server["src_dir"] / "esc_t.xml" + p.write_bytes(open(SAMPLE, "rb").read()) + j = post(server, "/api/audit", { + "path": str(p), "name": "ESCC回归工程", + "period_from": 24319, "period_to": 24319, + "province": "广东省", "city": "珠海市", "district": "香洲区", + "bulid_unit": "测试建设单位", "file_kind": 1}) + assert j.get("ok") is True, j + sid = j["session_id"] + import sqlite3 + con = sqlite3.connect(str(next(server["root"].rglob("session.db")))) + con.row_factory = sqlite3.Row + try: + uw = con.execute("SELECT COUNT(*) c FROM s_unit_works WHERE session_id=?", (sid,)).fetchone()["c"] + assert uw == 7, uw + sec = con.execute("SELECT COUNT(*) c FROM s_sections WHERE session_id=?", (sid,)).fetchone()["c"] + assert sec == 2, sec + nb = con.execute("""SELECT COUNT(*) c FROM s_bills b JOIN s_unit_works u ON u.id=b.uw_id + WHERE u.session_id=?""", (sid,)).fetchone()["c"] + assert nb == 186, nb + nn = con.execute("""SELECT COUNT(*) c FROM s_norms n JOIN s_bills b ON b.id=n.bill_id + JOIN s_unit_works u ON u.id=b.uw_id WHERE u.session_id=?""", (sid,)).fetchone()["c"] + assert nn == 127, nn + # 项目级价格表 126 条入库后,决策 201 打开收尾「未引用即删」会清掉 + # 只在价格表出现、无任何定额/台班组成引用的行(样本 27 条费用科目行)——与其他格式同口径 + lp = con.execute("SELECT COUNT(*) c FROM s_lme_proj WHERE session_id=?", (sid,)).fetchone()["c"] + assert lp == 99, lp + lib = con.execute("SELECT COUNT(*) c FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()["c"] + assert lib == 126, lib # s_lme_lib 是全量兜底库,不删 + us = con.execute("""SELECT COUNT(*) c FROM s_uw_summary s JOIN s_unit_works u ON u.id=s.uw_id + WHERE u.session_id=?""", (sid,)).fetchone()["c"] + assert us > 0, "单位汇总分析没入库" + # 负数量保真 + neg = con.execute("""SELECT b.Quantity q FROM s_bills b JOIN s_unit_works u ON u.id=b.uw_id + WHERE u.session_id=? AND b.Number='010102001004'""", (sid,)).fetchone() + assert neg and neg["q"] == pytest.approx(-170.0) + finally: + con.close() diff --git a/决策台账.md b/决策台账.md index 885b9a6..2cc915e 100644 --- a/决策台账.md +++ b/决策台账.md @@ -5970,3 +5970,18 @@ pytest 全量 **354 passed**(353 存量+1 新增 e2e);node --check 前端 - **测试**:`test_rule_registry`(区域 1/行块 0、max 取数、无「固定」)、`test_lme_summary_two_shapes`(两种汇总行形态各自输出)、空骨架标注断言无「固定」。 - **术语表**新增:自增区域 / 自增块 / 自增行 / 基数下限(min_count)。**全量 pytest 367 passed / 3 skipped**。 + +## 决策 265(2026-11-03,主人定):解析器升级支持 ESCC2.0 广东省造价数据标准(明文 XML) + +**口径**:主人给样本 `y程ESCC2.xml`(珠海高新区2024地灾治理)指令「升级解析器支持这个格式」;追问规模「100 或 10000 单位工程也一样解析」——用 iterparse 流式(内存恒定,规模线性只影响耗时)。**推翻 2026-10-01「不再支持 xml」中 ESCC 部分**(import_job 注释所记 git 可考古经核实不成立——初始提交即删除后版本,parse_esc 全新编写);其他散装 XML 仍拒绝(test_api_p0 改用无名根样料)。 + +**落地**:core/import_job.py——sniff 加 `esc` 分支(头部 `