412 lines
23 KiB
Python
412 lines
23 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""决策 231(2026-10-27 主人定):经典整件骨架库 + 手工工程导出(cos4/cos/Excel)回归。
|
||
|
||
口径:①公共上传口自动收骨架(后台导入与工作台打开工程同口,失败不挡上传);
|
||
②同签名只存最全代表(不一定最新,平手取最新,不跨件拼合),连保留值存 history.db;
|
||
③手工导出 cos/cos4=骨架整件当模板:参考清单行全换我方、**有采纳定额/工料机挂真实值
|
||
(231 补记:和标准采纳一样)、未采纳清单=我方五值+无定额(补记十五推翻克隆架子清值)**、
|
||
我方分部层级递归映射 DivisionalWorks 嵌套、单位/单项/工程名落我方(引用 Number 不动)、
|
||
工料机汇总=现算行挂真/无采纳空槽、容器/单位合计现算、其余保留值;
|
||
④Excel 导出=项目名文件夹/单位工程.xlsx(230 模板架子+合价/备注),可直接回导入;
|
||
⑤普通工程导出路径不受影响(fmt 缺省照旧走原格式引擎)。
|
||
造数仅写隔离副本(api_harness 临时目录),生产库零接触。"""
|
||
import io
|
||
import os
|
||
import re
|
||
import sqlite3
|
||
import zipfile
|
||
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
|
||
|
||
# ---------------- 造「原生感」骨架 cos4:两级分部嵌套+样板清单(费用构成+定额+工料机架子) ----------------
|
||
SKEL_UNIT = """<?xml version="1.0" encoding="utf-8"?>
|
||
<UnitWorks Number="UW1" Name="骨架单位工程A" DivisionalAndElementalWorks="8888.00" Preliminaries="1111.00" Total="9999.00">
|
||
<SummaryOfCost DivisionalAndElementalWorks="8888.00" Preliminaries="1111.00" Total="9999.00"/>
|
||
<DivisionalAndElementalWorks Total="8888.00">
|
||
<SummaryOfBasicCost Total="8888.00"/>
|
||
<DivisionalWorks Number="" Name="骨架一级分部" Total="8888.00" Quantity="0" TechnicalAndEconomicIndex="9.90" ChapterKind="4">
|
||
<SummaryOfBasicCost Total="8888.00"/>
|
||
<WorkElement Number="990101001001" Name="骨架清单甲" Attr="1.骨架特征" Unit="m2" Quantity="10.000" Price="100" Total="1000.00">
|
||
<SummaryOfBasicCost Total="1000.00"/>
|
||
<Norm Number="N1-1" Name="骨架定额" Unit="m3" Quantity="10.000" Price="80" Total="800.00">
|
||
<LabourMaterialsEquipmentsMachinesElement Number="000001" Name="骨架工料机" Quantity="1.500" Price="55" Total="82.50" Express="1.5"/>
|
||
</Norm>
|
||
</WorkElement>
|
||
<DivisionalWorks Number="" Name="骨架二级分部" Total="7888.00" Quantity="0" TechnicalAndEconomicIndex="8.80" ChapterKind="4">
|
||
<SummaryOfBasicCost Total="7888.00"/>
|
||
<WorkElement Number="990101001002" Name="骨架清单乙" Attr="" Unit="m3" Quantity="5.000" Price="50" Total="250.00">
|
||
<SummaryOfBasicCost Total="250.00"/>
|
||
<Norm Number="N1-2" Name="骨架定额2" Unit="m3" Quantity="5.000" Price="70" Total="350.00">
|
||
<LabourMaterialsEquipmentsMachinesElement Number="000002" Name="骨架工料机2" Quantity="2.000" Price="60" Total="120.00" Express="2"/>
|
||
</Norm>
|
||
</WorkElement>
|
||
</DivisionalWorks>
|
||
</DivisionalWorks>
|
||
</DivisionalAndElementalWorks>
|
||
<Preliminaries Total="1111.00">
|
||
<SummaryOfBasicCost Total="1111.00"/>
|
||
<UnitWorksPreliminaryWorkElement Number="990501001001" Name="骨架措施清单" Unit="项" Quantity="1.000" Price="1111" Total="1111.00">
|
||
<SummaryOfBasicCost Total="1111.00"/>
|
||
</UnitWorksPreliminaryWorkElement>
|
||
</Preliminaries>
|
||
<LabourMaterialsEquipmentsMachinesSummary Number="000009" Name="骨架汇总工料机" Specification="" Unit="工日" Kind="1" Quantity="99" NoTaxPrice="9" TaxPrice="10"/>
|
||
<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="骨架台班" Specification="" Unit="台班" Kind="7" Quantity="3" NoTaxPrice="500" TaxPrice="565">
|
||
<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="机上人工" Specification="" Unit="工日" Kind="1" Quantity="1" NoTaxPrice="9" TaxPrice="10"/>
|
||
</LabourMaterialsEquipmentsMachinesSummary>
|
||
</UnitWorks>"""
|
||
|
||
SKEL_PROJ = """<?xml version="1.0" encoding="utf-8"?>
|
||
<ConstructionProject Name="骨架工程项目" FileKind="1" BulidUnit="骨架建设单位">
|
||
<SectionalWorks Number="" Name="骨架单项工程" Total="9999.00">
|
||
<UnitWorks Number="UW1" Name="骨架单位工程A" Total="9999.00"/>
|
||
</SectionalWorks>
|
||
</ConstructionProject>"""
|
||
|
||
ROWS = [
|
||
["单位工程", "", "分部", "我方一级分部", "", "", "", ""],
|
||
["我方一级分部", "", "分部", "我方二级分部", "", "", "", ""],
|
||
["我方二级分部", "041001001001", "清单", "我方清单甲", "1.我方特征一2.我方特征二", "m²", 126.5, 385],
|
||
["我方一级分部", "011101001001", "清单", "我方清单乙", "", "m²", 88.4, 35.2],
|
||
]
|
||
PREL = [["安全文明施工费", "", "", "项", 1, 120000]]
|
||
T_JIA = round(126.5 * 385, 2) # 48702.5
|
||
T_YI = round(88.4 * 35.2, 2) # 3111.68
|
||
T_ITEM = round(T_JIA + T_YI, 2) # 一级分部/分部分项合计
|
||
|
||
|
||
def _zip_bytes(unit_xml, proj_xml):
|
||
bio = io.BytesIO()
|
||
with zipfile.ZipFile(bio, "w", zipfile.ZIP_DEFLATED) as z:
|
||
z.writestr("@_UW1_骨架单位工程A.xml", unit_xml)
|
||
z.writestr("Project.xml", proj_xml)
|
||
return bio.getvalue()
|
||
|
||
|
||
def _skel_bytes():
|
||
return _zip_bytes(SKEL_UNIT, SKEL_PROJ)
|
||
|
||
|
||
def _seed_skeleton(server, fname="骨架样本T.cos4"):
|
||
"""补记十四:上传口不再收藏骨架——测试骨架走升级口(seed_frame)入库。"""
|
||
import sys as _sys
|
||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||
import classic_skeleton as _cs
|
||
import tempfile
|
||
p = os.path.join(server["src_dir"], fname)
|
||
open(p, "wb").write(_skel_bytes())
|
||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||
try:
|
||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
||
finally:
|
||
con.close()
|
||
return {"ok": True}
|
||
|
||
|
||
def _mk_xlsx(server, fname="unit_export_t.xlsx"):
|
||
from openpyxl import Workbook
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "分部分项"
|
||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
||
for r in ROWS:
|
||
ws.append(r)
|
||
ws2 = wb.create_sheet("措施项目")
|
||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
||
for r in PREL:
|
||
ws2.append(r)
|
||
p = str(server["src_dir"] / fname)
|
||
wb.save(p)
|
||
return p
|
||
|
||
|
||
def _create_manual(server, name="我方手工工程T"):
|
||
f1 = _mk_xlsx(server)
|
||
r = post(server, "/api/session/manual/save",
|
||
{"sid": 0, "name": name, "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": "我方单项工程",
|
||
"units": [{"id": 0, "name": "我方单位工程", "file": f1}]}]})
|
||
assert r["ok"] is True, r
|
||
return r["session_id"]
|
||
|
||
|
||
def _unit_xml_of(data):
|
||
z = zipfile.ZipFile(io.BytesIO(data))
|
||
for nm in z.namelist():
|
||
if nm.lower().endswith(".xml"):
|
||
txt = z.read(nm).decode("utf-8")
|
||
body = re.sub(r"^.*?\?>", "", txt, count=1, flags=re.S).lstrip()
|
||
if body.startswith("<UnitWorks"):
|
||
return body, z.read("Project.xml").decode("utf-8")
|
||
raise AssertionError("导出件里没有单位工程成员")
|
||
|
||
|
||
def test_no_auto_collect_and_seed_only(server):
|
||
"""补记十四:上传口**不再收藏骨架**(classic_skel 只有升级进的骨架);
|
||
升级口 seed_frame 同名替换、新名新增。"""
|
||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||
try:
|
||
assert raw_post(server, "/api/admin/upload", "普通件.cos4", _skel_bytes())["ok"]
|
||
n = con.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='classic_skel'").fetchone()[0]
|
||
assert n == 0, "上传口不该再收藏任何骨架(表都不该建)"
|
||
import sys as _sys
|
||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||
import classic_skeleton as _cs
|
||
p = os.path.join(server["src_dir"], "升骨架T.cos4")
|
||
open(p, "wb").write(_skel_bytes())
|
||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
||
assert con.execute("SELECT COUNT(*) FROM classic_skel WHERE is_frame=1").fetchone()[0] == 1
|
||
finally:
|
||
con.close()
|
||
|
||
def test_export_meta_manual(server):
|
||
"""meta:手工工程 fmt=cos4/cos/xlsx 给建议名;不带 fmt 明确报错(不再误导补传)。"""
|
||
sid = _create_manual(server)
|
||
c = server["client"]
|
||
j = c.get("/api/session/export/meta", params={"session_id": sid, "fmt": "cos4"}).json()
|
||
assert j["ok"] is True and j["name"] == "我方手工工程T-审核版.cos4", j
|
||
j = c.get("/api/session/export/meta", params={"session_id": sid, "fmt": "xlsx"}).json()
|
||
assert j["ok"] is True and j["name"] == "我方手工工程T-审核版.zip", j
|
||
j = c.get("/api/session/export/meta", params={"session_id": sid}).json()
|
||
assert j["ok"] is False and "格式" in j["msg"], j
|
||
|
||
|
||
def test_manual_export_cos4(server):
|
||
"""cos4 导出全口径:我方行进、骨架行清、架子值零、分部嵌套、名字落位、引用 Number 不动。"""
|
||
_seed_skeleton(server)
|
||
sid = _create_manual(server)
|
||
r = server["client"].get("/api/session/export",
|
||
params={"session_id": sid, "fmt": "cos4"})
|
||
assert r.status_code == 200, r.text[:200]
|
||
cd = r.headers.get("Content-Disposition", "")
|
||
assert "cos4" in cd, cd
|
||
unit, proj = _unit_xml_of(r.content)
|
||
|
||
# ① 骨架的清单/措施不残留;我方清单在
|
||
assert "骨架清单甲" not in unit and "骨架清单乙" not in unit and "骨架措施清单" not in unit
|
||
assert "我方清单甲" in unit and "我方清单乙" in unit and "安全文明施工费" in unit
|
||
# ② 我方分部层级=DivisionalWorks 嵌套(一级含二级)
|
||
m1 = re.search(r'<DivisionalWorks\b[^>]*Name="我方一级分部"[^>]*>', unit)
|
||
assert m1, "我方一级分部没落位"
|
||
e1 = unit.index("</DivisionalWorks>", m1.end())
|
||
assert re.search(r'<DivisionalWorks\b[^>]*Name="我方二级分部"', unit[m1.end():e1]), \
|
||
"子分部没有嵌套在一级分部里"
|
||
assert 'Total="%.2f"' % T_ITEM in m1.group(0), "一级分部合计没现算"
|
||
# ③ 未采纳清单(补记十五,主人定「分部/清单/定额/工料机全按自己的值,不用骨架值
|
||
# 兜底」——推翻克隆架子清值):我方五值照出、**无定额**(骨架样例定额不进)
|
||
m3 = unit.index("我方清单甲")
|
||
e3 = unit.index("</WorkElement>", m3)
|
||
seg = unit[m3:e3]
|
||
assert "<Norm " not in seg, "未采纳清单不该带(骨架样例)定额"
|
||
assert "126.5" in seg, "我方工程量没照出"
|
||
# ④ 单位级工料机汇总(补记五:根层 LME_SUM=汇总行):无采纳=无现算行
|
||
# → 骨架行全撤(架子在、行不进);骨架的行名不残留
|
||
assert "骨架汇总工料机" not in unit and "骨架台班" not in unit
|
||
# ⑤ 单位/单项/工程名落我方;合计现算;引用节点 Number 不动
|
||
assert 'Name="我方单位工程"' in unit and "骨架单位工程A" not in unit
|
||
assert ('DivisionalAndElementalWorks="%.2f"' % T_ITEM) in unit
|
||
assert 'Preliminaries="120000.00"' in unit
|
||
assert 'Name="我方手工工程T"' in proj and 'Name="我方单项工程"' in proj
|
||
assert '<UnitWorks Number="UW1" Name="我方单位工程"' in proj
|
||
# ⑥ 保留值:骨架的取费类工程级信息留着(SummaryOfCost Total 等未动)
|
||
assert 'BulidUnit="骨架建设单位"' in proj
|
||
|
||
|
||
def test_manual_export_without_skeleton(server):
|
||
"""该后缀没收过骨架:明确报错提示先导入原件(fail-closed)。cos 全程不充库。"""
|
||
sid = _create_manual(server, "无骨架工程T")
|
||
r = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "cos"})
|
||
assert r.status_code == 200
|
||
j = r.json()
|
||
assert j["ok"] is False and "经典骨架" in j["msg"], j
|
||
|
||
|
||
def test_manual_export_xlsx_roundtrip(server):
|
||
"""Excel 导出:项目名文件夹/单位工程.xlsx,模板架子+合价/备注;可直接回导入。"""
|
||
_create_manual(server)
|
||
r = server["client"].get("/api/session/export",
|
||
params={"session_id": _sid_of(server), "fmt": "xlsx"})
|
||
assert r.status_code == 200
|
||
z = zipfile.ZipFile(io.BytesIO(r.content))
|
||
names = z.namelist()
|
||
assert names and names[0].split("/")[0] == "我方手工工程T", names
|
||
xname = [n for n in names if n.endswith(".xlsx")][0]
|
||
assert xname == "我方手工工程T/我方单位工程.xlsx", xname
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(z.read(xname)))
|
||
ws = wb["分部分项"]
|
||
head = [c.value for c in ws[1]]
|
||
assert head == ["上一级名称", "编码", "类型", "名称", "项目特征", "单位",
|
||
"工程量", "单价", "合价", "备注"], head
|
||
rows = [list(r) for r in ws.iter_rows(min_row=2, values_only=True)]
|
||
jia = next(r for r in rows if r[3] == "我方清单甲")
|
||
assert jia[2] == "清单" and jia[1] == "041001001001"
|
||
assert abs(jia[6] * jia[7] - T_JIA) < 0.01 and abs(jia[8] - T_JIA) < 0.01, "合价没现算"
|
||
er = next(r for r in rows if r[3] == "我方二级分部")
|
||
assert er[0] == "我方一级分部" and er[2] == "分部"
|
||
ws2 = wb["措施项目"]
|
||
assert [c.value for c in ws2[1]] == ["名称", "编码", "项目特征", "单位",
|
||
"工程量", "单价", "合价", "备注"]
|
||
# 回导入自查:多出的合价/备注列解析端忽略,整份通过且行数对上
|
||
p = server["src_dir"] / "roundtrip_t.xlsx"
|
||
p.write_bytes(z.read(xname))
|
||
j = post(server, "/api/session/manual/parse", {"path": str(p)})
|
||
assert j["ok"] is True, j
|
||
assert (j["n_div"], j["n_item"], j["n_prelim"]) == (2, 2, 1), j
|
||
|
||
|
||
def _sid_of(server):
|
||
items = get(server, "/api/sessions")["items"]
|
||
return next(x["id"] for x in items if x["manual"] and x["name"] == "我方手工工程T")
|
||
|
||
|
||
def test_manual_export_unit_single(server):
|
||
"""决策 233 方案a(2026-10-28 主人定):单单位工程导 xlsx——与 231 Excel 通道同一
|
||
_unit_workbook 产出(同架子同数据逐格全等),文件名=单位工程名.xlsx,可回导。"""
|
||
sid = _create_manual(server)
|
||
st = get(server, "/api/session/manual/state", session_id=sid)
|
||
uw = st["sections"][0]["units"][0]["id"]
|
||
r = server["client"].get("/api/session/manual/export_unit",
|
||
params={"session_id": sid, "uw": uw})
|
||
assert r.status_code == 200
|
||
cd = r.headers.get("Content-Disposition", "")
|
||
from urllib.parse import unquote
|
||
assert "filename*=UTF-8''" in cd and unquote(cd.split("filename*=UTF-8''", 1)[1]) == "我方单位工程.xlsx", cd
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(io.BytesIO(r.content))
|
||
assert wb.sheetnames == ["填写说明", "分部分项", "措施项目"]
|
||
rows = [list(x) for x in wb["分部分项"].iter_rows(min_row=2, values_only=True)]
|
||
jia = next(x for x in rows if x[3] == "我方清单甲")
|
||
assert jia[1] == "041001001001" and abs(jia[8] - T_JIA) < 0.01, "合价没现算"
|
||
# 与 231 整包 zip 里同一单位工程逐格全等(共用 _unit_workbook)
|
||
rz = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "xlsx"})
|
||
assert rz.status_code == 200
|
||
z = zipfile.ZipFile(io.BytesIO(rz.content))
|
||
zname = [n for n in z.namelist() if n.endswith(".xlsx")][0]
|
||
wbz = load_workbook(io.BytesIO(z.read(zname)))
|
||
assert wbz.sheetnames == wb.sheetnames
|
||
for sn in wb.sheetnames:
|
||
a = [[c.value for c in row] for row in wb[sn].iter_rows()]
|
||
b = [[c.value for c in row] for row in wbz[sn].iter_rows()]
|
||
assert a == b, "单导与 231 整包不一致:%s" % sn
|
||
# 回导自查:单文件直接过预检
|
||
p = server["src_dir"] / "unit_single_t.xlsx"
|
||
p.write_bytes(r.content)
|
||
assert post(server, "/api/session/manual/parse", {"path": str(p)})["ok"] is True
|
||
|
||
|
||
def test_manual_export_unit_guards(server):
|
||
"""守卫(决策 233):空单位工程提示不产文件;uw/会话不存在 400;源文件工程拒绝。"""
|
||
from api_harness import META, fixture_file
|
||
f1 = _mk_xlsx(server, "单导守卫.xlsx")
|
||
r = post(server, "/api/session/manual/save",
|
||
{"sid": 0, "name": "单导守卫T", "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": "单项G",
|
||
"units": [{"id": 0, "name": "有数据单位", "file": f1},
|
||
{"id": 0, "name": "空单位"}]}]})
|
||
assert r["ok"] is True, r
|
||
sid = r["session_id"]
|
||
us = get(server, "/api/session/manual/state", session_id=sid)["sections"][0]["units"]
|
||
full = next(u for u in us if u["name"] == "有数据单位")
|
||
empty = next(u for u in us if u["name"] == "空单位")
|
||
c = server["client"]
|
||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": empty["id"]})
|
||
assert j.status_code == 400 and "还没有清单数据" in j.text
|
||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": 999999})
|
||
assert j.status_code == 400 and "不存在" in j.text
|
||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid + 99999, "uw": full["id"]})
|
||
assert j.status_code == 400
|
||
pa = fixture_file(server, "单导源件.cos4", "单导源工程T",
|
||
[("041001001001", "源件清单", "", "m²", 10, 100)])
|
||
src = post(server, "/api/audit", dict(META, path=str(pa), name="单导源工程T"))["session_id"]
|
||
j = c.get("/api/session/manual/export_unit", params={"session_id": src, "uw": full["id"]})
|
||
assert j.status_code == 400 and "手工工程" in j.text
|
||
|
||
|
||
def test_manual_export_unit_clone(server):
|
||
"""骨架单位位自由复制(主人 2026-10-28 定「单位工程多少不影响骨架,1000 个都可以」):
|
||
工程单位数 > 骨架位 → 克隆骨架单位成员补位;项目成员引用行顺延;新条目名按 GBK 字节
|
||
写、不打 UTF-8 旗标(乱码教训)。"""
|
||
_seed_skeleton(server)
|
||
f1 = _mk_xlsx(server)
|
||
r = post(server, "/api/session/manual/save",
|
||
{"sid": 0, "name": "我方多单位工程T", "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||
{"id": 0, "name": "我方单位一", "file": f1},
|
||
{"id": 0, "name": "我方单位二", "file": f1},
|
||
{"id": 0, "name": "我方单位三", "file": f1}]}]})
|
||
assert r["ok"] is True, r
|
||
sid = r["session_id"]
|
||
resp = server["client"].get("/api/session/export",
|
||
params={"session_id": sid, "fmt": "cos4"})
|
||
assert resp.status_code == 200, resp.text[:200]
|
||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||
infos = [i for i in z.infolist() if i.filename.lower().endswith(".xml")]
|
||
assert len(infos) == 4, [i.filename for i in infos] # 1 骨架位 + 2 克隆 + Project
|
||
# 克隆条目名:GBK 字节、无 UTF-8 旗标(骨架原生条目同款)
|
||
clones = [i for i in infos if "_UW1_" not in i.filename and "Project" not in i.filename]
|
||
assert len(clones) == 2, [i.filename for i in clones]
|
||
for i in clones:
|
||
assert not (i.flag_bits & 0x800), "克隆条目名被打上 UTF-8 旗标"
|
||
nm_gbk = i.filename.encode("cp437").decode("gbk")
|
||
assert re.match(r"@_\d+_单位工程\d+\.xml$", nm_gbk), nm_gbk
|
||
root = ET.fromstring(z.read(i.filename))
|
||
assert root.tag == "UnitWorks"
|
||
assert root.get("Name") in ("我方单位二", "我方单位三")
|
||
assert "我方清单甲" in z.read(i.filename).decode("utf-8")
|
||
# 首位单位照旧落骨架本位
|
||
skel_nm = [i.filename for i in infos if "_UW1_" in i.filename][0]
|
||
assert ET.fromstring(z.read(skel_nm)).get("Name") == "我方单位一"
|
||
# 项目成员引用行:3 条、名称齐、克隆行带新成员文件名
|
||
proj = z.read("Project.xml").decode("utf-8")
|
||
refs = re.findall(r'<UnitWorks\b[^>]*>', proj)
|
||
names = [re.search(r'Name="([^"]*)"', x).group(1) for x in refs]
|
||
assert names == ["我方单位一", "我方单位二", "我方单位三"], names
|
||
for x in refs[1:]:
|
||
fn = re.search(r'FileName="([^"]*)"', x)
|
||
assert fn and (fn.group(1).encode("gbk").decode("cp437")) in \
|
||
[i.filename for i in clones], x
|
||
|
||
|
||
def test_manual_export_tree_reorder(server):
|
||
"""目录树里上下移动单位后,导出引用行序=移动后的目录序(2026-10-28 主人定通用口径:
|
||
单项/单位排序以项目目录先有顺序为准——手工树保存时按组内位置重写编号持久化顺序,
|
||
导出端按「单项入库序+组内编号自然序」取,不能按物理 id)。"""
|
||
_seed_skeleton(server)
|
||
f1 = _mk_xlsx(server)
|
||
r = post(server, "/api/session/manual/save",
|
||
{"sid": 0, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||
{"id": 0, "name": "单位甲", "file": f1},
|
||
{"id": 0, "name": "单位乙", "file": None}]}]})
|
||
assert r["ok"] is True, r
|
||
sid = r["session_id"]
|
||
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
|
||
ids = [row[0] for row in con.execute(
|
||
"SELECT id FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,))]
|
||
con.close()
|
||
assert len(ids) == 2
|
||
r = post(server, "/api/session/manual/save", # 树里把两单位对调(带 id 保留数据)
|
||
{"sid": sid, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||
{"id": ids[1], "name": "单位乙", "file": None},
|
||
{"id": ids[0], "name": "单位甲", "file": None}]}]})
|
||
assert r["ok"] is True, r
|
||
resp = server["client"].get("/api/session/export",
|
||
params={"session_id": sid, "fmt": "cos4"})
|
||
assert resp.status_code == 200, resp.text[:200]
|
||
proj = zipfile.ZipFile(io.BytesIO(resp.content)).read("Project.xml").decode("utf-8")
|
||
names = [re.search(r'Name="([^"]*)"', x).group(1)
|
||
for x in re.findall(r"<UnitWorks\b[^>]*>", proj)]
|
||
ours_idx = [i for i, n in enumerate(names) if n in ("单位乙", "单位甲")]
|
||
assert ours_idx == sorted(ours_idx), names
|
||
assert names.index("单位乙") < names.index("单位甲"), \
|
||
"移动后导出序没跟目录序:单位乙应排在单位甲前,实际 %s" % names[:4]
|