feat(export): 决策263-266 单一骨架导出通路/数据全量入库/空骨架规则标注/导入按内容判族

- 决策 263:定额单价专题(三同合并全字段统一、原价三级链、LME Summary 26 属性收口、x_flags 采集、e2e 回归)
- 决策 264 补记五:原格式导出只保留骨架回灌一条通路;删除 export_cos.export_zip 旧引擎;新增 skeleton_engine(内容判族/唯一结构位/结构旁注/路径指纹);单位级/项目级非数据层 x_attr/x_side 采集与回灌;导出件成员名改 GBK 原始字节(_GbkZipInfo);后台「导出设置」导出空骨架(标注)
- 决策 265:导入按内容判族(zip 内含 ConstructProject→SWT 族,否则 COS 族;裸 XML 同),扩展名不参与拦截;api_scan 取消 EXT_OK 过滤
- 决策 266:结构位统一「自增区域/自增块/自增行」,取消「固定」;min_count(区域1/块行0),导出条数=max;区域数据0条保底1空壳;LME 汇总两形态(带组成闭合块/普通自闭合行)按行硬分派
- 前序未提交:HTML 导出整体移除(export_html.py 删除)、Excel 导出加序号列并移除说明页、.yhy 导入(import_yhy.py)
- 测试:367 passed / 3 skipped;新增 test_topic_price/test_yhy_import/test_import_suffix 等
This commit is contained in:
lianjianwei2024
2026-11-03 23:39:46 +08:00
parent 5470286f66
commit 78e58a40c7
40 changed files with 2700 additions and 1373 deletions

View File

@@ -1,37 +1,268 @@
# -*- coding: utf-8 -*-
"""导出后缀跟随源格式(2026-10-15 主人定「按原格式导出」不写死):
.cos4 / .COS4 / .cos / 未来新后缀(.cos5、任意 .xxx)导出都跟原格式;裸名退 .cos。"""
import os
import sys
"""导出后缀口径(2026-11-03 决策 264 补记:骨架回灌单一通路后重写)。
import api_harness as H
旧引擎 export_cos.export_zip 已拆除;后缀不再由旧引擎从源文件名猜——
①骨架挑选按内容/后缀(classic_skeleton.suffix_of 支持任意后缀);
②导出文件名后缀跟导出格式走(export_v2.out_name)。
"""
import hashlib
import io
import os
import sqlite3
import sys
import uuid
import zipfile
from xml.etree import ElementTree as ET
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
import export_cos as xcos # noqa: E402
import api_harness as H # noqa: E402
import classic_skeleton as cs # noqa: E402
import export_v2 as ev # noqa: E402
from api_harness import get, post, server # noqa: F401,E402 (夹具须经导入注册)
def _src_bytes(tmp_path):
p = H.make_cos4(str(tmp_path / "ext.cos4"), "后缀工程",
[("B001", "清单甲", "1、x", "项", 1, 100)])
with open(p, "rb") as f:
return f.read()
def test_ext_follows_source(tmp_path):
raw = _src_bytes(tmp_path)
def test_suffix_of_any_ext():
cases = {
"工程-招标控制价.cos4": ".cos4",
"工程-招标控制价.COS4": ".COS4",
"工程-招标控制价.cos": ".cos",
"工程-招标控制价.cos5": ".cos5", # 未来新格式:能导入就按原格式出
"工程-招标控制价.abc": ".abc",
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": ".cos", # 裸名退默认
"工程-招标控制价.cos4": "cos4",
"工程-招标控制价.COS4": "cos4",
"工程-招标控制价.cos": "cos",
"工程-招标控制价.COS": "cos",
"工程-招标控制价.swt": "swt",
"工程-招标控制价.abc": "abc", # 未来新格式:能导入就按原格式出
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": None,
}
for src_name, want in cases.items():
_bytes, out_name = xcos.export_zip(raw, "后缀工程", src_name, {}, [], [], {},
added_lme_by_uw=None)
assert out_name == "后缀工程-审核版" + want, "%s → %s (期望 %s)" % (src_name, out_name, want)
# 出包可用(zip 可读)
import io
import zipfile
zipfile.ZipFile(io.BytesIO(_bytes)).namelist()
for name, want in cases.items():
assert cs.suffix_of(name) == want, "%s → %s (期望 %s)" % (name, cs.suffix_of(name), want)
def test_out_name_follows_suffix():
assert ev.out_name("后缀工程", "cos4") == "后缀工程-审核版.cos4"
assert ev.out_name("后缀工程", "cos") == "后缀工程-审核版.cos"
assert ev.out_name("", "abc") == "工程-审核版.abc"
def test_blank_package_annotated(tmp_path):
"""骨架库导出「完全空骨架(原格式)+自增/固定标注」(2026-11-03 新增功能):
包内两个成员、值全空、每个结构位带规则注释、XML 可解析。"""
src = H.make_cos4(str(tmp_path / "blank_src.cos4"), "骨架标注工程",
[("B001", "清单甲", "1、x", "m3", 1, 100)],
[("000001", "人工", "", "工日", "1", "1")])
# 给夹具补一条单价计算行(x_side 类固定子块的标注样本)
buf = io.BytesIO()
with zipfile.ZipFile(src) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for n in z.namelist():
d = z.read(n)
if n.lower() != "project.xml":
d = d.replace(b"</Norm>", b'<UnitPriceCalculationOfItem Code="RGF" Name="" Total=""/></Norm>', 1)
zo.writestr(n, d)
src2 = tmp_path / "blank_src2.cos4"
src2.write_bytes(buf.getvalue())
con = sqlite3.connect(str(tmp_path / "h.db"))
con.row_factory = sqlite3.Row
sig = cs.seed_frame(con, str(src2), "标注骨架")
assert sig
data, fn, err = ev.build_blank_package(con, sig)
con.close()
assert err is None and fn.endswith(".cos4") and data[:2] == b"PK"
z = zipfile.ZipFile(io.BytesIO(data))
names = [i.filename for i in z.infolist()]
assert "Project.xml" in names and len(names) == 2, names
proj = z.read("Project.xml").decode("utf-8")
unit = z.read([n for n in names if n != "Project.xml"][0]).decode("utf-8")
ET.fromstring(proj)
ET.fromstring(unit)
assert "导出规则:自增区域" in unit
assert "自增区域:至少 1 个" in unit
assert "自增块:按数据块循环" in unit or "自增行:按数据行循环" in unit
assert "固定" not in unit
assert 'Number="B001"' not in unit and 'Number="B001"' not in proj # 完全空(不带数据)
def test_rule_registry():
"""结构位规则:区域下限 1(至少一个空壳)、行/块下限 0;全部自增,不再有「固定」。"""
region = ET.fromstring('<SummaryOfCost Total=""/>')
assert ev.min_count("SummaryOfCost") == 1
assert "自增区域" in ev.rule_note(region) and "固定" not in ev.rule_note(region)
leaf = ET.fromstring('<AddiCost Code=""/>')
assert ev.min_count("AddiCost") == 0
assert "自增行" in ev.rule_note(leaf)
block = ET.fromstring("<AttrInfoItem><AttrInfoItem Name='子'/></AttrInfoItem>")
assert "自增块" in ev.rule_note(block)
at = ET.fromstring('<AttrInfo><AttrInfoItem/></AttrInfo>')
assert "自增区域" in ev.rule_note(at)
# 导出条数 = max(下限, 数据条数)
assert ev.row_count("SummaryOfCost", 0) == 1
assert ev.row_count("AttrInfo", 0) == 1
assert ev.row_count("AddiCost", 0) == 0
assert ev.row_count("AddiCost", 3) == 3
def test_lme_summary_two_shapes():
"""工料机汇总行两种形态(普通行 / 带台班组成的块行)各按自己的样板输出——
不能只用一个样板:否则另一形态的列被丢掉(2026-11-03 主人实测)。"""
import json as _json
host = ET.fromstring(
"<UnitWorks>"
'<LabourMaterialsEquipmentsMachinesSummary Number="" Name="" ExtraA=""/>'
'<LabourMaterialsEquipmentsMachinesSummary Number="" Name="" ExtraB="">'
'<LabourMaterialsEquipmentsMachinesElement Number="" Quantity=""/>'
"</LabourMaterialsEquipmentsMachinesSummary>"
"</UnitWorks>")
rows = [
["A1", "普通行", "", "个", 1, 2, 10, 0, 10, None, None, None, None,
_json.dumps({"ExtraA": "va"})],
["B1", "组合行", "", "台班", 7, 1, 20, 0, 20, None, None, None, None,
_json.dumps({"ExtraB": "vb"})],
]
ev._emit_sums(host, rows, {"B1": [("C1", 1.5)]})
sums = [c for c in host if c.tag == "LabourMaterialsEquipmentsMachinesSummary"]
assert len(sums) == 2
by = {s.get("Number"): s for s in sums}
assert by["A1"].get("ExtraA") == "va" and len(by["A1"]) == 0
assert by["B1"].get("ExtraB") == "vb"
kids = [c for c in by["B1"] if c.tag == "LabourMaterialsEquipmentsMachinesElement"]
assert len(kids) == 1 and kids[0].get("Number") == "C1"
assert kids[0].get("Quantity") == "1.500000"
# 两种形态在序列化上必须分开:普通行自闭合、组合行带闭合标签
import skeleton_engine as _se
txt = _se.serialize(host, 0, " ", keep_values=True)
line_a = next(ln for ln in txt.splitlines() if 'Number="A1"' in ln)
line_b = next(ln for ln in txt.splitlines() if 'Number="B1"' in ln)
assert line_a.rstrip().endswith("/>"), line_a
assert line_b.rstrip().endswith(">"), line_b
assert "</LabourMaterialsEquipmentsMachinesSummary>" in txt
def test_blankpkg_endpoint(server):
"""后台接口:/api/admin/frames/blankpkg/<sig> 直接下载原格式空骨架(带标注)。"""
p = H.make_cos4(str(server["src_dir"] / "blank_ep_raw.cos4"), "标注端点工程",
[("B001", "清单甲", "1、x", "m3", 1, 100)],
[("000001", "人工", "", "工日", "1", "1")])
con = sqlite3.connect(server["db"])
con.row_factory = sqlite3.Row
try:
sig = cs.seed_frame(con, p, "端点骨架")
finally:
con.close()
assert sig
r = server["client"].get("/api/admin/frames/blankpkg/%s" % sig)
assert r.status_code == 200, r.text[:200]
assert r.content[:2] == b"PK"
z = zipfile.ZipFile(io.BytesIO(r.content))
assert "Project.xml" in z.namelist()
for i in z.infolist(): # 成员名必须是 GBK 原始字节(不带 UTF-8 旗标)
assert not (i.flag_bits & 0x800), i.filename
if i.filename != "Project.xml":
assert i.filename.encode("cp437").decode("gbk") == "@_1_单位工程.xml"
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
ET.fromstring(unit)
assert "自增" in unit and "固定" not in unit
assert "导出规则:自增区域" in unit
def test_export_member_names_gbk(server):
"""导出件成员名=GBK 原始字节、与 Project.xml 的 FileName 对得上(2026-11-03 主人实测乱码回归):
易达/广联达原件都是 GBK 条目名且不带 UTF-8 旗标;写成 UTF-8+旗标会被对方按 GBK 解读成乱码。"""
proj = "成员名工程-" + uuid.uuid4().hex[:6]
p = H.make_cos4(str(server["src_dir"] / ("nm_%s_raw.cos4" % proj[-6:])), proj,
[("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_nm.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
r = server["client"].get("/api/session/export", params={"session_id": sid})
assert r.headers["content-type"].startswith("application/zip"), r.text[:300]
z = zipfile.ZipFile(io.BytesIO(r.content))
proj_xml = z.read("Project.xml").decode("utf-8")
n = 0
for i in z.infolist():
if i.filename == "Project.xml":
continue
n += 1
assert not (i.flag_bits & 0x800), "成员名不能带 UTF-8 旗标:%r" % i.filename
gbk = i.filename.encode("cp437").decode("gbk")
assert gbk.endswith(".xml"), gbk
assert 'FileName="%s"' % gbk in proj_xml, (gbk, proj_xml[:200])
assert n >= 1
def test_unit_side_rows_exported(server):
"""单位工程非数据层(SummaryOfCost/AddiCost、AttrInfo…)也是数据:导入采集、导出按数据行重建。
2026-11-03 主人定「AddiCost 也是自增行,代码务必匹配」回归。"""
proj = "非数据层工程-" + uuid.uuid4().hex[:6]
p = H.make_cos4(str(server["src_dir"] / ("side_%s_raw.cos4" % proj[-6:])), proj,
[("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
# 给夹具补:SummaryOfCost 带 2 条 AddiCost;AttrInfo 一组两行;(项目级同款 2 条)
buf = io.BytesIO()
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for n in z.namelist():
d = z.read(n)
if n.lower() == "project.xml":
t = d.decode("utf-8")
t = t.replace(
'<SummaryOfCost Total="1234567.89"/>',
'<SummaryOfCost Total="1234567.89">'
'<AddiCost Code="P1" Name="项目附加费" Total="88"/>'
'<AddiCost Code="P2" Name="项目税差" Total="12"/></SummaryOfCost>')
d = t.encode("utf-8")
else:
t = d.decode("utf-8")
t = t.replace(
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>',
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000">'
'<AddiCost Code="A1" Name="附加费甲" Total="123"/>'
'<AddiCost Code="A2" Name="附加费乙" Total="45"/></SummaryOfCost>')
t = t.replace(
"</UnitWorks>",
'<AttrInfo><AttrInfoItem Name="组A" Code="G1" Value="" Remark="">'
'<AttrInfoItem Name="子1" Code="C1" Value="" Remark=""/>'
'</AttrInfoItem></AttrInfo></UnitWorks>')
d = t.encode("utf-8")
zo.writestr(n, d)
src = server["src_dir"] / ("side_%s.cos4" % proj[-6:])
src.write_bytes(buf.getvalue())
raw = open(str(src), "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_side.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
# 用独立骨架库(只放本件骨架)直接走 export_v2,避免并行用例的骨架库干扰
hpath = str(server["root"] / ("side_hist_%s.db" % proj[-6:]))
hic = sqlite3.connect(hpath)
hic.row_factory = sqlite3.Row
try:
assert cs.seed_frame(hic, hp, "非数据层骨架-" + proj[-6:])
sc = sqlite3.connect(server["sessdb"])
sc.row_factory = sqlite3.Row
try:
data, _fn, err = ev.export_v2(hic, sc, sid, "cos4", src_path=hp)
finally:
sc.close()
finally:
hic.close()
assert err is None, err
z = zipfile.ZipFile(io.BytesIO(data))
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
assert unit.count("<AddiCost") == 2, unit[:800]
assert 'Name="附加费甲"' in unit and 'Name="附加费乙"' in unit
assert 'Code="A2"' in unit and 'Total="45"' in unit
assert 'Name="组A"' in unit and 'Name="子1"' in unit
proj_xml = z.read("Project.xml").decode("utf-8")
assert proj_xml.count("<AddiCost") == 2, proj_xml[:800]
assert 'Name="项目附加费"' in proj_xml and 'Name="项目税差"' in proj_xml
assert 'Code="P2"' in proj_xml and 'Total="12"' in proj_xml