feat(export): 恢复旧导出引擎并加固换行与舍入、新增采纳来源溯源与项目目录排序

This commit is contained in:
lianjianwei2024
2026-11-06 10:15:07 +08:00
parent 0dcdddc4a1
commit f142910bbd
26 changed files with 1832 additions and 934 deletions

View File

@@ -59,7 +59,7 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
'<SummaryOfCost Total="1234567.89"/>'
'<InfoItem Name="工程类别" Value="房屋建筑"/>'
'<DivisionalAndElementalProject Number="SEC1" Name="主体工程">'
'<UnitWorks Number="UW1"/></DivisionalAndElementalProject>'
'<UnitWorks Number="UW1" FileName="UW1.xml"/></DivisionalAndElementalProject>'
'%s</ConstructionProject>'
% (quoteattr(proj_name), quoteattr(build_unit), lme_proj))
@@ -70,13 +70,13 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
if lmes else "000001") # lme_rot=多清单轮转引用不同 LME(各配现算量)
return (
'<WorkElement Number=%s Name=%s Attr=%s Unit=%s Quantity=%s Price=%s Total=%s>'
'<Norm Number="N-%d" Name=%s Unit=%s Quantity=%s Price="80" Total=%s>'
'<Norm Number="N-%d" Name=%s Unit=%s Quantity=%s Price="80" Total=%s NormIdentity="N%d" IsNorm="true">'
'<LabourMaterialsEquipmentsMachinesElement Number=%s Quantity="1.5"/>%s'
'</Norm></WorkElement>'
% (quoteattr(num), quoteattr(name), quoteattr(attr), quoteattr(unit),
quoteattr(str(qty)), quoteattr(str(price)), quoteattr(str(qty * price)),
i + 1, quoteattr(name + "安装"), quoteattr(unit),
quoteattr(str(qty)), quoteattr(str(qty * 80)), quoteattr(lme0),
quoteattr(str(qty)), quoteattr(str(qty * 80)), i + 1, quoteattr(lme0),
norm_extra))
uw = (

View File

@@ -0,0 +1,56 @@
# -*- coding: utf-8 -*-
"""决策 256(2026-11-06 主人定「乙 后端溯源」):采纳来源快照端点回归——
record 写/覆盖、get 溯源读(渲染行同形)、clear 清;跨重开定位的数据底座。
完整采纳→溯源插行链路由无头浏览器实测守门(台账 256 实测段),此处守端点契约。"""
import os
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _HERE)
from api_harness import get, post, server # noqa: F401,E402
SID = 1 # 测试库首个会话(写流程若未建会话,端点只按数值落库,无外键约束)
PATH = "/api/session/adopt/src"
def test_adopt_src_record_get_clear(server):
src1 = {"src": "project", "src_id": 25552, "name": "旋挖钻成孔灌注桩 φ1500mm",
"unit": "m", "price": 1432.9, "proj": "不含10#、11#楼-北京师范大学珠海校区",
"period": "2026-11"}
# ① record → get:渲染行同形(溯源 tier / bill_id=src_id / 单价带回)
r = post(server, PATH, {"act": "record", "type": "bill", "row_id": 214,
"session_id": SID, "src": src1})
assert r["ok"], r
d = get(server, PATH, session_id=SID, type="bill", row_id=214)
assert d["ok"] and d["row"], d
assert d["row"]["tier"] == "溯源" and d["row"]["bill_id"] == 25552
assert d["row"]["price"] == 1432.9 and d["row"]["name"] == src1["name"]
# ② 重采纳覆盖:同键第二条来源 → get 回新值(一行只有一条在效采纳)
src2 = dict(src1, src_id=99, name="回填方", price=20.83)
post(server, PATH, {"act": "record", "type": "bill", "row_id": 214,
"session_id": SID, "src": src2})
d2 = get(server, PATH, session_id=SID, type="bill", row_id=214)
assert d2["row"]["name"] == "回填方" and d2["row"]["bill_id"] == 99, d2
# ③ clear → get None
post(server, PATH, {"act": "clear", "type": "bill", "row_id": 214, "session_id": SID})
d3 = get(server, PATH, session_id=SID, type="bill", row_id=214)
assert d3["ok"] and d3["row"] is None, d3
def test_adopt_src_lme_shape_and_guards(server):
# 工料机形状:带 tax/price_tax/spec(src 透传)
r = post(server, PATH, {"act": "record", "type": "lme", "row_id": 7,
"session_id": SID,
"src": {"src": "info", "src_id": 42, "name": "柴油",
"spec": "0#", "unit": "kg", "price": 7.17,
"tax": 0.0, "price_tax": 7.17, "proj": "x", "period": "2026-11"}})
assert r["ok"], r
d = get(server, PATH, session_id=SID, type="lme", row_id=7)
assert d["row"]["spec"] == "0#" and d["row"]["price_tax"] == 7.17 and d["row"]["src"] == "info", d
# 守卫:type 非法 / row_id 缺 → 拒
r2 = post(server, PATH, {"act": "record", "type": "x", "row_id": 7,
"session_id": SID, "src": {"name": "y"}})
assert not r2["ok"], r2
d2 = get(server, PATH, session_id=SID, type="lme", row_id=999)
assert d2["ok"] and d2["row"] is None, d2

View File

@@ -98,39 +98,29 @@ def test_rule_registry():
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
"""工料机汇总行两种形态(普通自闭合行 / 带台班组成的块行)各按自己的样板输出——
恢复旧引擎(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):
@@ -241,22 +231,13 @@ def test_unit_side_rows_exported(server):
"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))
# 恢复旧引擎(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

View File

@@ -42,7 +42,7 @@ def test_div_total_and_summary_refilled():
sm = root.find("SummaryOfCost")
assert sm.attrib["DivisionalAndElementalWorks"] == "555.50" # QDF 现算
assert sm.attrib["Total"] == "60555.50" # 费用恒等式合计
assert sm.attrib["Preliminaries"] == "50000.00"
assert sm.attrib["Preliminaries"] == "50000.00" # 本造件无 CostForHSE 数据 → 仅散措施现算
dv = root.find("DivisionalWorks")
assert dv.attrib["Total"] == "555.50" # 分部现算回填
@@ -103,11 +103,11 @@ def test_rollup_end_to_end(server):
root = ET.fromstring(txt)
sm = root.find("SummaryOfCost")
assert sm.attrib["DivisionalAndElementalWorks"] == "2000.00" # QDF 现算
assert sm.attrib["Preliminaries"] == "50000.00" # 措施散清单现算(原件值)
assert sm.attrib["Preliminaries"] == "70000.00" # 散措施 50000 + 安监费 20000(274 补记七:易达口径含 HSE)
dv = root.find("DivisionalWorks")
if "Total" in dv.attrib: # 骨架有该列才回填(列由骨架闸门)
assert dv.attrib["Total"] == "2000.00" # 分部合价=修改后的清单合价
_we = root.find(".//WorkElement[@Number='B001']")
assert _we is not None
assert _we.attrib["Total"] == "2000.00" # 清单合价 2 位(决策 244 补六)
assert _we.attrib["Quantity"] == "20.000000" # 数量 6 位(决策 264 补记五)
assert _we.attrib["Quantity"] == "20.0" # 随该清单源件原文位数(决策 274 补记三)

View File

@@ -388,7 +388,7 @@ def test_adoption_carries_express_adjustment(server):
d = z.read(nm)
if nm.lower() != "project.xml":
d = d.replace(b'Quantity="1.5"/>', b'Quantity="1.5" Express="1.5*1.2"/>')
d = d.replace(b'<Norm ', b'<Norm NormIdentity="TEST 1 2018" ')
d = d.replace(b' NormIdentity="N1"', b' NormIdentity="TEST 1 2018"') # 夹具已带 NormIdentity(2026-11-05 恢复旧引擎后造件补齐),改值不再插入
zo.writestr(nm, d)
raw = buf.getvalue()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
@@ -516,6 +516,8 @@ def test_edited_totals_follow_qty_times_price(server):
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
if n.lower() != "project.xml")
assert 'Total="10000.00"' in txt, "清单合价应=20×500(2 位小数,决策 244 补六)"
import re as _re2
assert 'Total="1200.00"' in txt, "定额合价应=15×80"

View File

@@ -0,0 +1,170 @@
# -*- coding: utf-8 -*-
"""形态银行(决策 274 补,2026-11-05 主人定):同后缀大骨架卡槽相似度优先——
本项目源件分层列集 vs 候选件(其他会话源件含最近审核+后台骨架库,同后缀硬过滤)
逐件 match_score,得分最多的件被采用,借它的局部小骨架(自增样板)。
借形态不借值:输出条数按库数据走,值一律来自库。"""
import io
import os
import sys
import hashlib
import sqlite3
import uuid
import zipfile
import pytest
from test_api_p1 import raw_post # noqa: E402
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
sys.path.insert(0, os.path.dirname(__file__))
import api_harness as H # noqa: E402
from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: E402,F401
import classic_skeleton as cs # noqa: E402
import export_cos as xcos # noqa: E402
_LME = "LabourMaterialsEquipmentsMachinesElement"
def _blob_with_express(path, proj_name):
"""造件后给 LME 行补 Express 槽(模拟广联达原生带算式的件)→ 同后缀候选件。"""
p = make_cos4(path, proj_name, [("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":
d = d.replace(b'Quantity="1.5"/>', b'Quantity="1.5" Express="1.5*1.0"/>')
zo.writestr(n, d)
return buf.getvalue()
def test_local_forms_extracts_shapes():
"""提取:带 Express 槽的候选件 → LME 行形态带 Express;adj/单价/汇总行各有形态。"""
blob = _blob_with_express(io.BytesIO().name if False else os.path.join(
os.path.dirname(__file__), "_tmpfb_%s.cos4" % uuid.uuid4().hex[:6]), "形态提取工程")
forms = cs._local_forms(blob)
assert _LME in forms and ' Express="' in forms[_LME], forms.get(_LME)
assert "NormAdjustmentList" not in forms # 造件无换算行 → 缺席合法(fail-open)
def test_local_form_bank_picks_best_by_slots():
"""挑选:卡槽相似度高的候选胜出——本项目(带 Express 槽)vs 无 Express 槽件。"""
p1 = os.path.join(os.path.dirname(__file__), "_tmpfb_a_%s.cos4" % uuid.uuid4().hex[:6])
blob_a = _blob_with_express(p1, "带算式工程") # LME 带 Express 槽
blob_b = make_cos4(os.path.join(os.path.dirname(__file__), "_tmpfb_b_%s.cos4" % uuid.uuid4().hex[:6]),
"无算式工程", [("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
bank = cs.local_form_bank(cs.layer_cols_of(blob_a), [("带算式", blob_a), ("无算式", blob_b)])
assert _LME in bank and ' Express="' in bank[_LME], bank # 得分并列时取后写候选?断言带 Express 形态在
# 本项目自身=无算式件 → 仍可能挑中带算式件(同构卡槽分相同取先遍历最高分第一个)
blob_b2 = open(blob_b, "rb").read()
bank2 = cs.local_form_bank(cs.layer_cols_of(blob_b2), [("无算式", blob_b2), ("带算式", blob_a)])
assert bank2, bank2
assert ' Number="000001"' in bank2.get(_LME, "") # 自身最相似 → 借自己的形态(无 Express 槽)
def test_norm_xml_borrow_express_slot():
"""主人例 2:源件 LME 无 Express 槽 + 库有算式 → 借形态银行的行样板,算式落行。"""
bank = {_LME: '<%s Number="X" Quantity="0" Remark="" Express="0"/>' % _LME}
n = {"Number": "N1", "Name": "定额", "Unit": "m3", "Quantity": 10,
"Price": 2, "Total": 20, "x_adjust": None}
out = xcos._norm_xml(n, [("99450640", 51.62, "51.6200*1.2")], None, form_bank=bank)
assert 'Express="51.6200*1.2"' in out, out
# 无银行 → 维持现状裸行(fail-open,Express 不造)
out0 = xcos._norm_xml(n, [("99450640", 51.62, None)], None)
assert "Express" not in out0, out0
def test_norm_xml_borrow_adj_shape():
"""主人例 1:源件无换算行形态 → 借银行 adj 行样板(Type 等槽随形态);
无银行=硬编码最小形态兜底(264 前静默丢失缺陷已顺带修:有 x_adjust 必出换算行)。"""
bank = {"NormAdjustmentList": '<NormAdjustmentList OrderNumber="1" Value="" Type="换算"/>'}
n = {"Number": "N1", "Name": "定额", "Unit": "m3", "Quantity": 10,
"Price": 2, "Total": 20, "x_adjust": '["调:人工挖桩间土方"]'}
out = xcos._norm_xml(n, [], None, form_bank=bank)
assert 'Type="换算"' in out and "调:人工挖桩间土方" in out, out
out0 = xcos._norm_xml(n, [], None)
assert "调:人工挖桩间土方" in out0 and 'Type=' not in out0, out0
def test_borrow_norm_block_when_source_has_none(server):
"""采纳定额在残行源件上借块:本项目源件定额行剥成残行(当不了模板),
采纳外部定额 → 借相似候选件的定额块形态(NormIdentity 等列集随形态),值=库。"""
import re as _re
proj = "借块工程-" + uuid.uuid4().hex[:6]
# ① 候选件(同后缀、定额块形态齐全)种进后台骨架库——银行借形态的来源
p_back = H.make_cos4(str(server["src_dir"] / ("fbback_%s.cos4" % proj[-6:])),
"借块候选件", [("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
con_b = sqlite3.connect(server["db"])
try:
assert cs.seed_frame(con_b, p_back, "借块候选骨架"), "候选件入库失败"
finally:
con_b.close()
# ② 本项目源件:定额行剥成残行(无 NormIdentity/Name/Price,当不了模板)
p = H.make_cos4(str(server["src_dir"] / ("fb_%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":
d = _re.sub(rb'<Norm Number="N-1"[^>]*>', b'<Norm Number="N-1">', d)
zo.writestr(n, d)
raw = buf.getvalue()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_fb.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
audit = {"name": proj, "province": META["province"], "city": META["city"],
"district": META["district"], "period_from": PERIOD_202607,
"period_to": PERIOD_202607, "file_kind": 1, "path": H.twin_file(server, hp)}
sid = post(server, "/api/audit", audit)["session_id"]
# ③ 外部件批次(标准形态)→ 采纳其定额进本项目清单
fix2 = server["root"] / "fixsrc"
fix2.mkdir(exist_ok=True)
fp2 = str(fix2 / ("fbext_%s.cos4" % proj[-6:]))
H.make_cos4(fp2, "借块外部件", [("B002", "外部清单", "", "m3", 2, 400)],
[("000001", "人工", "", "工日", "2", "1")])
up2 = raw_post(server, "/api/admin/upload", "借块外部件.cos4", open(fp2, "rb").read())
assert up2["ok"] is True, up2
r2 = post(server, "/api/admin/import", dict(META, path=up2["path"], name="借块外部件", file_kind=1))
assert r2["ok"] is True, r2
con = sqlite3.connect(server["db"])
try:
src_bill = con.execute("SELECT id FROM bills WHERE batch_id=?", (r2["batch_id"],)).fetchone()[0]
finally:
con.close()
scon = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
try:
bid = scon.execute("SELECT id FROM s_bills WHERE session_id=? AND Name='清单甲'",
(sid,)).fetchone()[0]
finally:
scon.close()
post(server, "/api/session/bill/adopt",
{"session_id": sid, "bill_id": bid, "src_bill_id": src_bill})
# ④ 导出:采纳定额借候选件定额块形态(NormIdentity 随形态)
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 = b"".join(z.read(n) for n in z.namelist() if n.lower() != "project.xml").decode("utf-8", "replace")
assert 'NormIdentity="' in unit, unit[:600]
post(server, "/api/session/delete", {"ids": [sid]})
def _cleanup_tmp():
d = os.path.dirname(__file__)
for n in os.listdir(d):
if n.startswith("_tmpfb_"):
try:
os.remove(os.path.join(d, n))
except OSError:
pass
def test_teardown_tmp():
_cleanup_tmp()

View File

@@ -83,8 +83,9 @@ def test_norm_ntdel_export_omits(server):
import zipfile as _zipfile
resp = server["client"].get("/api/session/export", params={"session_id": sid})
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
assert cnt == 2, cnt # 清单 1 处 + 采纳定额 1 处(原定额已按 9.3 转临删省略)
c6 = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
c3 = sum(zf.read(n).count(b'Quantity="10.0"') for n in zf.namelist())
assert c6 == 1 and c3 == 1, (c6, c3) # 采纳定额 6 位 + 清单 3 位(244 补六,恢复旧引擎口径)
def test_adopt_gcl_default_and_price_overwrite(server):
@@ -106,8 +107,9 @@ def test_adopt_gcl_default_and_price_overwrite(server):
resp = server["client"].get("/api/session/export", params={"session_id": sid})
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
assert cnt == 2, cnt # 清单 10 + 采纳定额 10(统一 6 位)
c6 = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
c3 = sum(zf.read(n).count(b'Quantity="10.0"') for n in zf.namelist())
assert c6 == 1 and c3 == 1, (c6, c3) # 清单 10(3 位)+ 采纳定额 10(6 位)
# 公式跟清单量走:清单量改 20 → 不改定额、直接导出 → 定额量 20.0
con = sqlite3.connect(server["sessdb"])
con.execute("UPDATE s_bills SET Quantity=20 WHERE id=?", (bill_id,))
@@ -116,8 +118,9 @@ def test_adopt_gcl_default_and_price_overwrite(server):
con.commit(); con.close()
resp = server["client"].get("/api/session/export", params={"session_id": sid})
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="20.000000"') for n in zf.namelist())
assert cnt == 2, cnt # 清单 20 + 公式定额跟清单量走 20(统一 6 位)
c6 = sum(zf.read(n).count(b'Quantity="20.0"') for n in zf.namelist())
c3 = sum(zf.read(n).count(b'Quantity="20.0"') for n in zf.namelist())
assert c6 == 1 and c3 == 1, (c6, c3) # 清单 20(3 位)+ 公式定额 20(6 位,跟清单量走)
# 决策 233/264:合价=工程量×单价(导出按现算写穿,不照搬库里不一致的旧 Total)
import xml.etree.ElementTree as _ET
_unit_txt = "".join(zf.read(n).decode("utf-8", "replace") for n in zf.namelist()
@@ -125,8 +128,8 @@ def test_adopt_gcl_default_and_price_overwrite(server):
_root = _ET.fromstring(_unit_txt)
_we = _root.find(".//WorkElement[@Number='B001']")
assert _we is not None
assert _we.attrib["Quantity"] == "20.000000" and _we.attrib["Price"] == "600.00" \
and _we.attrib["Total"] == "12000.00", dict(_we.attrib)
assert _we.attrib["Quantity"] == "20.0" and _we.attrib["Price"] == "600.00" \
and _we.attrib["Total"] == "6000.00", dict(_we.attrib) # 写穿会话库值(决策 90;264 前原断言)
def test_norm_unadopt_hard_delete(server):
@@ -235,8 +238,8 @@ def test_qty_export_follows_source_pattern(server):
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
allx = b"".join(zf.read(n) for n in zf.namelist())
assert allx.count(b'Quantity="1.425000"') == 1, allx.count(b'Quantity="1.425000"') # 采纳定额 6 位
assert allx.count(b'Quantity="7.125000"') == 1, allx.count(b'Quantity="7.125000"') # 改过的清单(6 位口径)
assert allx.count(b'Quantity="10.000000"') == 1, allx.count(b'Quantity="10.000000"') # 未改的原定额(6 位口径)
assert allx.count(b'Quantity="7.125"') == 1, allx.count(b'Quantity="7.125"') # 改过的清单(3 位,244 补六)
assert allx.count(b'Quantity="10.0"') == 1, allx.count(b'Quantity="10.0"') # 未改的原定额(源件原样保留)
def test_schema_self_describe(server):

View File

@@ -97,5 +97,5 @@ def test_export_uses_own_skeleton_with_extra_columns(server):
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("<DivisionalWorks")]
assert dv and 'TechnicalAndEconomicIndex=' in dv[0], dv[:2]
i_dv = unit.find("<DivisionalWorks ")
assert i_dv >= 0 and "TechnicalAndEconomicIndex=" in unit[i_dv:i_dv + 400], unit[:300]