Files
pricing_review/CostReview/app/tests/test_manual_export_real.py

233 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""决策 229 真实件对拍(主人 2026-10-27 定:「要真真实实做测试,不能弄虚作假骗自己」)。
链路:真实小项目原件 → 上传入库当经典骨架 → 原件解析倒出 Excel(230 模板、原行序)
→ 手工工程导入 → 骨架导出 → **导出件与原件逐层对拍数据结构**:
①zip 成员名集合一致(整件字节外科手术不丢成员);
②分部层级保真:DivisionalWorks 嵌套序列(深度+名称,预序)逐一对齐;
③我方数据挂载正确:分部分项/措施清单的 (编码,名称,单位,量,价) 集合=原件
(主人定:骨架只规定格式与字段,数据挂载在字段下;合价现算);
④架子清值:每条我方清单下定额架子在、量价 0;工料机汇总容器空(架子在行不进);
⑤保留值:建设单位/费用汇总等工程级信息=原件原样;工程/单位/单项名=原件名
(本测试数据来自原件,名字应当对上);
⑥措施区平铺(决策 230 既有口径:Excel 措施 Sheet 无层级,不保留措施分部层级)。
真实件(后台需要导入的项目/,主人库内小体量项目):
· 三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS(.cos 代)
· 吉大街道园林花园老旧小区环境整治提升工程施工.cos4(cos4 代)
"""
import importlib.util
import io
import os
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET
import pytest
from api_harness import PERIOD_202607, get, post, server # noqa: F401 (夹具)
from test_api_p1 import raw_post
_CORE = Path(__file__).resolve().parents[1] / "core"
_REAL_DIR = Path(__file__).resolve().parents[3] / "后台需要导入的项目"
FB_H = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"]
CS_H = ["名称", "编码", "项目特征", "单位", "工程量", "单价"]
REAL_CASES = [
("三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS", "cos"),
("吉大街道园林花园老旧小区环境整治提升工程施工.cos4", "cos4"),
]
def _ij():
import sys
if str(_CORE) not in sys.path:
sys.path.insert(0, str(_CORE)) # import_job 平铺引 match 等 core 模块
spec = importlib.util.spec_from_file_location("ij_real", _CORE / "import_job.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def _parse_original(path):
ij = _ij()
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
"cur_bill": -1, "cur_uw": -1, "bill_uw": [],
"bill_kind": [], "prelim_raw": 0,
"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}
ij.parse_file(str(path), out)
return out
def _f(v):
try:
return round(float(v), 6)
except (TypeError, ValueError):
return 0.0
def _unit_xlsx(server, tag, uw_i, out):
"""原件第 uw_i 个单位工程 → 230 模板 Excel(原行序:分部预序、清单挂各自分部名下)。
量价空值落 0(决策 196 口径:算不出归零)。"""
from openpyxl import Workbook
glo = [i for i, d in enumerate(out["divides"]) if d["uw"] == uw_i and d["kind"] == "item"]
local = {g: k for k, g in enumerate(glo)}
kids, roots = {}, []
for k, g in enumerate(glo):
d = out["divides"][g]
p = d.get("parent")
(kids.setdefault(local[p], []).append(k)) if p in local else roots.append(k)
by_div = {}
for bi, b in enumerate(out["bills"]):
if out["bill_uw"][bi] != uw_i or out["bill_kind"][bi] == "prelim":
continue
by_div.setdefault(out["bill_div"][bi], []).append(b)
prels = [b for bi, b in enumerate(out["bills"])
if out["bill_uw"][bi] == uw_i and out["bill_kind"][bi] == "prelim"]
wb = Workbook()
ws = wb.active
ws.title = "分部分项"
ws.append(FB_H)
def emit(k, parent_name):
g = glo[k]
d = out["divides"][g]
ws.append([parent_name, "", "分部", d["name"] or "", "", "", "", ""])
for b in by_div.get(g, []):
ws.append([d["name"] or "", b[0] or "", "清单", b[1] or "", b[2] or "",
b[3] or "", _f(b[4]) or 0, _f(b[5]) or 0])
for sub in kids.get(k, []):
emit(sub, d["name"] or "")
for k in roots:
emit(k, "单位工程")
ws2 = wb.create_sheet("措施项目")
ws2.append(CS_H)
for b in prels:
ws2.append([b[1] or "", b[0] or "", b[2] or "", b[3] or "",
_f(b[4]) or 0, _f(b[5]) or 0])
p = server["src_dir"] / ("real_%s_uw%d.xlsx" % (tag, uw_i))
wb.save(p)
return str(p), sum(len(v) for v in by_div.values()), len(prels)
@pytest.mark.parametrize("fname,fmt", REAL_CASES)
def test_real_roundtrip(server, fname, fmt):
src = _REAL_DIR / fname
if not src.exists():
pytest.skip("真实件不在本机:%s" % fname)
tag = fmt
# ---- ① 原件上传=当经典骨架收进库 ----
data = src.read_bytes()
up = raw_post(server, "/api/admin/upload", fname, data)
assert up["ok"] is True, up
# ---- ② 原件解析(与工作台同源解析器)→ 倒 Excel ----
out = _parse_original(src)
assert out["uw"], "原件没解析出单位工程"
units = []
for i, uw in enumerate(out["uw"]):
fp, n_item, n_pre = _unit_xlsx(server, tag, i, out)
units.append({"id": 0, "name": uw[1] or ("单位工程%d" % (i + 1)), "file": fp})
sec_name = (out.get("sections") or [None])[0]
sec_name = (sec_name[1] if isinstance(sec_name, (tuple, list)) and sec_name[1]
else "单项工程")
# ---- ③ 手工工程导入 ----
r = post(server, "/api/session/manual/save",
{"sid": 0, "name": out["proj_name"] or "真实件对拍", "period_from": PERIOD_202607,
"period_to": PERIOD_202607,
"tree": [{"id": 0, "name": sec_name, "units": units}]})
assert r["ok"] is True, r
sid = r["session_id"]
# ---- ④ 骨架导出 ----
resp = server["client"].get("/api/session/export",
params={"session_id": sid, "fmt": fmt})
assert resp.status_code == 200, resp.text[:300]
if os.environ.get("DEBUG_EXPORT"): # 排查用:落盘导出件(主人可随时关掉)
Path(os.environ["DEBUG_EXPORT"]).write_bytes(resp.content)
zexp = zipfile.ZipFile(io.BytesIO(resp.content))
zsrc = zipfile.ZipFile(str(src))
# ---- ⑤ 对拍 ----
# ⑤-1 成员名集合一致
assert sorted(zsrc.namelist()) == sorted(zexp.namelist()), "zip 成员不一致"
def members(z):
m = []
for nm in z.namelist():
if not nm.lower().endswith(".xml"):
continue
body = ET.fromstring(z.read(nm))
if body.tag == "UnitWorks":
m.append((nm, body))
return m
ms, me = members(zsrc), members(zexp)
assert len(ms) == len(me) == len(out["uw"]), "单位工程成员数不一致"
def dw_seq(container, depth=0):
"""容器/分部内 DivisionalWorks 预序 (depth, Name) 序列。"""
seq = []
for el in container:
if el.tag == "DivisionalWorks":
seq.append((depth, el.get("Name") or ""))
seq.extend(dw_seq(el, depth + 1))
return seq
def bills_of(container, tags):
return [(_norm_b(el)) for el in container.iter() if el.tag in tags]
def _norm_b(el):
# 单位按内部口径 strip 后比较(解析端把「个 」归一成「个」,原件留原样属预期差异)
return (el.get("Number") or "", el.get("Name") or "",
(el.get("Unit") or "").strip(),
_f(el.get("Quantity")), _f(el.get("Price")))
PRE_TAGS = {"UnitWorksPreliminaryWorkElement", "WorkElement"}
for i, ((nms, es), (_, eo)) in enumerate(zip(ms, me)):
uw_name = out["uw"][i][1] or ("单位工程%d" % (i + 1))
# ⑤-2 单位名=原件
assert eo.get("Name") == uw_name, (nms, eo.get("Name"), uw_name)
cs = eo.find("DivisionalAndElementalWorks")
co = es.find("DivisionalAndElementalWorks")
assert cs is not None and co is not None
# ⑤-3 分部层级(深度+名称)逐一保真
assert dw_seq(co) == dw_seq(cs), "单位 %s 分部嵌套不一致" % uw_name
# ⑤-4 我方清单集合=原件(骨架只定字段,数据挂载;合价现算不比原件 Total 口径)
so = sorted(bills_of(co, {"WorkElement"}))
se = sorted(bills_of(cs, {"WorkElement"}))
assert len(so) == len(se) and so == se, "单位 %s 清单集不一致" % uw_name
# ⑤-5 架子清值:每条我方清单下定额架子在、量价 0
for el in cs.iter("WorkElement"):
norms = list(el.iter("Norm"))
assert norms, "清单 %s 没有定额架子" % el.get("Name")
assert all(_f(n.get("Quantity")) == 0 and _f(n.get("Price")) == 0
for n in norms), "清单 %s 定额架子没清零" % el.get("Name")
# ⑤-6 措施平铺:清单集合=原件(分部层级不保留,决策 230 口径)
po = es.find("Preliminaries")
pe = eo.find("Preliminaries")
assert po is not None and pe is not None
so = sorted(bills_of(po, PRE_TAGS))
se = sorted(bills_of(pe, PRE_TAGS))
assert len(so) == len(se) and so == se, "单位 %s 措施清单集不一致" % uw_name
# ⑤-7 工料机汇总:架子在、行不进
for el in eo.iter("LabourMaterialsEquipmentsMachinesSummary"):
assert len(el) == 0, "单位 %s 工料机汇总没清空" % uw_name
# ⑤-8 项目层:工程名/单项名/建设单位(保留值)=原件
ps, pe2 = None, None
for nm in zsrc.namelist():
if nm.lower().endswith("project.xml"):
ps = ET.fromstring(zsrc.read(nm))
for nm in zexp.namelist():
if nm.lower().endswith("project.xml"):
pe2 = ET.fromstring(zexp.read(nm))
assert ps is not None and pe2 is not None
assert pe2.get("Name") == (out["proj_name"] or ps.get("Name"))
assert pe2.get("BulidUnit") == ps.get("BulidUnit"), "建设单位保留值变了"
ss = ps.find("SectionalWorks")
se2 = pe2.find("SectionalWorks")
if ss is not None:
assert se2 is not None and se2.get("Name") == sec_name, "单项工程名没落位"
refs = pe2.findall(".//UnitWorks")
assert [r.get("Name") for r in refs[:len(out["uw"])]] == \
[u[1] for u in out["uw"]], "单位引用名没落位"