# -*- coding: utf-8 -*-
"""决策 267(2026-11-04):导出骨架优先用**本项目自己的骨架**。
- 打开工程时从源件提炼存 sessions.x_own_blank/x_own_meta;
- 数据层列覆盖齐全 → 独占使用,后台骨架不参与;
- 缺列 → 后台骨架补列;缺整层 → 回落后台骨架。
"""
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 post, server # noqa: F401,E402
def test_own_layers_only_not_columns():
"""2026-11-04 主人定:**列不算全部数据,只要数据层齐全就算覆盖**。"""
plan = {
"units": [{"id": 1, "number": "01", "name": "单位", "total": 10.0, "lme": [{}],
"bills": [{"Number": "B1", "Name": "清单", "Attr": "特征",
"Unit": "m3", "Quantity": 2.0, "Price": 3.0, "Total": 6.0,
"qty_expr": "", "kind": "item", "x_tdel": 0,
"norms": [{"Number": "N1", "Name": "定额", "Unit": "m3",
"Quantity": 1.0, "Price": 2.0, "Total": 2.0,
"x_tdel": 0, "res": [("C1", 1.5, "1.5*1.0")]}]}]}],
"divides": {1: {"id": 1, "uw_id": 1, "kind": "item", "number": "D1", "name": "分部"}},
}
need, prelim_tags, need_prelim_div = ev._own_layers(plan)
assert {"UnitWorks", "DivisionalWorks", "WorkElement", "Norm",
"LabourMaterialsEquipmentsMachinesElement",
"LabourMaterialsEquipmentsMachinesSummary"} <= need
# 空骨架:缺层 → 判不覆盖
empty = ET.fromstring("")
tags0 = {e.tag for e in empty.iter()}
miss = ev._missing_layers(need, prelim_tags, need_prelim_div, tags0)
assert "UnitWorks" in miss and "Norm" in miss
# 只有层、一列都没有:仍算覆盖(列不算全部数据)
bare = ET.fromstring(
""
""
"")
tags1 = {e.tag for e in bare.iter()}
assert ev._missing_layers(need, prelim_tags, need_prelim_div, tags1) == []
def test_export_uses_own_skeleton_with_extra_columns(server):
"""本项目骨架有、后台骨架没有的列 → 导出仍保留(证明优先本项目骨架)。"""
proj = "本项目骨架工程-" + uuid.uuid4().hex[:6]
# ① 后台骨架:另一件(没有 TechnicalAndEconomicIndex 列)
p_back = H.make_cos4(str(server["src_dir"] / ("ownback_%s.cos4" % proj[-6:])), "后台骨架件",
[("B900", "后台清单", "", "m3", 1, 1)])
con = sqlite3.connect(server["db"])
con.row_factory = sqlite3.Row
try:
assert cs.seed_frame(con, p_back, "后台骨架-" + proj[-6:])
finally:
con.close()
# ② 本项目源件:分部带一列 TechnicalAndEconomicIndex(后台骨架没有)
p = H.make_cos4(str(server["src_dir"] / ("own_%s_raw.cos4" % proj[-6:])), proj,
[("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
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").replace(
'',
'')
d = t.encode("utf-8")
zo.writestr(n, d)
src = server["src_dir"] / ("own_%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_own.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
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"]
# 打开后应已存本项目骨架
sc = sqlite3.connect(server["sessdb"])
row = sc.execute("SELECT x_own_blank FROM sessions WHERE id=?", (sid,)).fetchone()
sc.close()
assert row and row[0], "打开工程应提炼并保存本项目骨架"
resp = server["client"].get("/api/session/export", params={"session_id": sid})
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")
dv = [ln for ln in unit.splitlines() if ln.strip().startswith("