250 lines
13 KiB
Python
250 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""导出后缀口径(2026-11-03 决策 264 补记:骨架回灌单一通路后重写)。
|
||
|
||
旧引擎 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 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 test_suffix_of_any_ext():
|
||
cases = {
|
||
"工程-招标控制价.cos4": "cos4",
|
||
"工程-招标控制价.COS4": "cos4",
|
||
"工程-招标控制价.cos": "cos",
|
||
"工程-招标控制价.COS": "cos",
|
||
"工程-招标控制价.swt": "swt",
|
||
"工程-招标控制价.abc": "abc", # 未来新格式:能导入就按原格式出
|
||
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": None,
|
||
}
|
||
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-05 主人拍板)后等价通道=_summary_node 模板克隆:
|
||
children_html 空=自闭合、非空=成对块;不能混用样板:否则另一形态的列被丢掉(主人实测)。"""
|
||
import export_cos as _xc
|
||
_T = "LabourMaterialsEquipmentsMachinesSummary"
|
||
_L = "LabourMaterialsEquipmentsMachinesElement"
|
||
tmpl_a = '<%s Number="X" Name="n" ExtraA=""/>' % _T
|
||
tmpl_b = ('<%s Number="X" Name="n" ExtraB=""><%s Number="C0" Quantity="1"/></%s>'
|
||
% (_T, _L, _T))
|
||
a = _xc._summary_node(("A1", "普通行", "", "个", 1, 2, 10, 0, 10), tmpl_a)
|
||
b = _xc._summary_node(("B1", "组合行", "", "台班", 7, 1, 20, 0, 20), tmpl_b,
|
||
children_html='<%s Number="C1" Quantity="1.500000"/>' % _L)
|
||
# 行独有扩展列经合并回写通道(_lme_apply_price._flags,决策 259 全采)落行:
|
||
a = _xc._lme_apply_price(a, {"NoTaxPrice": 10, "TaxPrice": 0, "_flags": {"ExtraA": "va"}})
|
||
b = _xc._lme_apply_price(b, {"NoTaxPrice": 20, "TaxPrice": 0, "_flags": {"ExtraB": "vb"}})
|
||
# 普通行:自闭合、模板独有列 ExtraA 保留
|
||
assert a.startswith("<%s " % _T) and a.endswith("/>"), a
|
||
assert 'Number="A1"' in a and 'ExtraA="va"' in a, a
|
||
# 组合行:成对块、模板独有列 ExtraB 保留、子级照 children_html
|
||
assert ("<%s " % _T) in b and b.endswith("</%s>" % _T), b
|
||
assert 'Number="B1"' in b and 'ExtraB="vb"' in b, b
|
||
assert '<%s Number="C1" Quantity="1.500000"/>' % _L in b, b
|
||
# 两种形态在产物上必须分开:普通行自闭合、组合行带闭合标签(上面两段形态断言)
|
||
|
||
|
||
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"]
|
||
# 恢复旧引擎(2026-11-05 主人拍板):走 /api/session/export——非数据层=源件原样保留
|
||
resp = server["client"].get("/api/session/export",
|
||
params={"session_id": sid, "name": proj,
|
||
"province": H.META["province"], "city": H.META["city"],
|
||
"period_from": H.PERIOD_202607})
|
||
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
|
||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||
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
|