# -*- coding: utf-8 -*-
"""决策 106(2026-10-17)两件实测事故的回归:
①插入节点整块克隆——此前新增清单/采纳定额只克隆开标签,缺原生 innards(费用构成汇总、
单价计算公式行、WorkContent 壳…),易达按结构取数看不到新增清单(cos 与 cos4 同样
实测),广联达整包报「不是有效标书」;
②工程量系数 GCL 口径——旧口径(定额量÷清单量)在 10m/100m 类单位上把单位换算双算两遍
(前山河 040501004001:10m 定额导出量少 10 倍实测)。
"""
import io
import os
import re
import sqlite3
import sys
import zipfile
import xml.etree.ElementTree as ET
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "server")))
import export_cos as xcos # noqa: E402
import api_harness as H # noqa: E402
from api_harness import server # noqa: F401,E402 (夹具须经导入注册)
from api_harness import get, post # noqa: E402
# 珠海 .cos 形态的原生清单块(费用构成 + 工程量表达式行 + 定额内 管理费/单价计算公式行)
RICH_BILL = (
''
''
''
''
''
''
''
''
''
'')
NEW_BILL = {"id": 901, "Number": "040101001002", "Name": "路基挖土方(可利用方)",
"Attr": "1、土类别:综合", "Unit": "m3", "Quantity": 1000.0,
"Price": 4.54, "Total": 4540.0, "src_remark": None}
NEW_NORM = {"id": 902, "Number": "D1-1-29", "Name": "挖掘机挖一般土方 一、二类土",
"Unit": "1000m3天然密实方", "Quantity": 1.0, "Price": 4540.91, "Total": 4540.91}
def _parse(frag):
return ET.fromstring("%s" % frag)[0]
def test_new_bill_full_structure_cos():
"""新增清单整块克隆:费用构成清零在位、公式保留、定额带单价计算公式行、备注不带模板的。"""
out = xcos._bill_xml(NEW_BILL, "WorkElement",
[xcos._norm_xml(NEW_NORM, [("00010010", 594.0)],
xcos._full_norm_block(RICH_BILL))],
RICH_BILL)
we = _parse(out)
assert [c.tag for c in we] == ["SummaryOfBasicCost", "ExpressElement", "Norm"]
sbc = we.find("SummaryOfBasicCost")
assert all(v == "0" for v in sbc.attrib.values()) # 别人的金额一个不带
ee = we.find("ExpressElement")
assert ee.get("Quantity") == "0" and ee.get("Express") == ""
assert ee.get("OrderNumber") == "1" # 结构属性保留
norm = we.find("Norm")
assert norm.get("Number") == "D1-1-29" and norm.get("Quantity") == "1.000000"
assert norm.get("NormIdentity") == "GD 99 2019" # 属性集照旧齐全(决策 64)
upc = norm.findall("UnitPriceCalculationOfItem")
assert len(upc) == 2 and all(c.get("Total") == "0" for c in upc)
assert upc[0].get("QtyFormula") == "_RGF" # 公式保留,易达打开可重算
assert norm.find("ManageFees").get("Rate") == "1.00"
assert norm.find("ManageFees").get("Fee1") == "0"
assert [c.get("Number") for c in norm.findall("LabourMaterialsEquipmentsMachinesElement")] == ["00010010"]
assert we.get("Remark") == "" # 模板备注(别人的)不带
def test_new_bill_empty_attr_cleared():
"""新增清单无特征:不得把锚点/模板的特征带过去(2026-10-20 220kV 实测)。"""
b = dict(NEW_BILL, Attr="")
we = _parse(xcos._bill_xml(b, "WorkElement", [], RICH_BILL))
assert we.get("Attr") == ""
def test_appended_norm_keeps_innards():
"""采纳定额追加进原有清单:innards 一并克隆(此前裸 Norm 同样过不了结构关)。"""
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], xcos._full_norm_block(RICH_BILL))
norm = _parse(out)
# 补记二十一:采纳定额不带数量算式行(Express 大于 Quantity,易达会按算式显示代号/方括号)
assert [c.tag for c in norm] == ["ManageFees",
"LabourMaterialsEquipmentsMachinesElement",
"UnitPriceCalculationOfItem", "UnitPriceCalculationOfItem"]
assert all(c.get("Total") == "0" for c in norm.findall("UnitPriceCalculationOfItem"))
assert norm.findall("ExpressElement") == [] # 补记二十一:采纳定额不带数量算式行(易达才显示纯数字,不带方括号)
assert norm.get("Remark") == "" # 决策 101 口径不变
def test_legacy_minimal_template_unchanged():
"""模板只是开标签(旧调用形态/夹具最小清单)→ 输出与旧版一致,不造 innards。"""
nb = xcos._full_norm_block(RICH_BILL)
opentag = nb[:xcos._open_tag_end(nb, 0)]
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], opentag)
norm = _parse(out)
assert [c.tag for c in norm] == ["LabourMaterialsEquipmentsMachinesElement"]
bill_opentag = RICH_BILL[:xcos._open_tag_end(RICH_BILL, 0)]
out_b = xcos._bill_xml(NEW_BILL, "WorkElement", [out], bill_opentag)
we = _parse(out_b)
assert [c.tag for c in we] == ["Norm"]
assert we.get("Remark") == "" # 决策 106:新增清单没源备注时模板备注一律不带(旧版会泄漏锚点的备注)
def test_yida_sample_template_leaks_fixed():
"""主人 2026-10-17 提供的易达样本(锚杆 010302006002,LME 带 Express 值、定额带
NormAdjustmentList 换算记录):克隆进新节点时这些「别人的值」一律不带——
Express 清空、换算记录整行不落(架子可以有,别人的数据不能有)。"""
yida_norm = (
''
''
''
''
''
''
'')
out = xcos._norm_xml(NEW_NORM, [("00010010", 594.0)], yida_norm)
norm = _parse(out)
lme = norm.find("LabourMaterialsEquipmentsMachinesElement")
assert lme.get("Express") == "594.0" and lme.get("Quantity") == "594.0" # 模板的 1715.0700 不带,填本行含量
assert norm.findall("NormAdjustmentList") == [] # 换算记录不背给新定额
assert norm.find("UnitPriceCalculationOfItem").get("Total") == "0"
assert norm.find("UnitPriceCalculationOfItem").get("QtyFormula") == "_RGF"
# 清单级单价公式行的 QtyFormula 若是**纯数字字面量**(有的文件直接存数值)也清空——
# 那是模板清单自己的单价/合价,留着会被按公式求值显示(220kV 件实测背 189006.16)
assert xcos._zero_results('').count('QtyFormula=""') == 1
assert '_GCL*7' in xcos._zero_results('') # 通用公式保留
# 工料机行模板(bill 尾表重建)同样清 Express
row = xcos._lme_row('', "GLF", 0)
assert 'Number="GLF"' in row and 'Express=""' in row and 'Quantity="0"' in row
def test_new_bill_workcontent_profile_cos4():
"""cos4(WorkContent 画像):新增清单的定额逐条包 WorkContent 壳(决策 98 同款),
清单级工料机尾表按会话资源重建(0 量)、模板的金额清零。"""
tmpl = (''
''
''
''
''
''
''
''
''
''
'')
out = xcos._bill_xml(NEW_BILL, "WorkElement",
[xcos._norm_xml(NEW_NORM, [("990101015", 0.117)],
xcos._full_norm_block(tmpl))],
tmpl)
we = _parse(out)
wcs = we.findall("WorkContent")
assert len(wcs) == 1 and wcs[0].get("Name") == "路基挖土方(可利用方)" # 逐条包壳,名照本清单
assert wcs[0].get("Total") == "4540.00"
assert wcs[0].find("Norm").get("Number") == "D1-1-29"
assert wcs[0].find("Norm").find("UnitPriceCalculationOfItem").get("Total") == "0"
tail = [c for c in we.findall("LabourMaterialsEquipmentsMachinesElement")]
assert [c.get("Number") for c in tail] == ["990101015"] # 尾表按会话资源重建
assert tail[0].get("Quantity") == "0.0001" # 0.117×1÷1000 = 每单位消耗量
assert we.find("SummaryOfBasicCost").get("DivisionalAndElementalWorks") == "0"
assert we.find("ExpressElement").get("Quantity") == "0"
def test_bill_tail_lme_real_values():
"""清单级消耗量架子填真值(决策 106 补记,主人广联达样本同款算法):
Σ(定额含量×定额量)÷清单量,跨定额同码合并一行、Express 照原生填同值;
广联达样本实测数:人工 (1611.66×100+595.03×10)÷10000 = 16.7116。"""
tmpl = (''
''
''
''
''
''
''
''
''
''
''
''
''
''
'')
bill = dict(NEW_BILL, Quantity=10000.0)
n1 = dict(NEW_NORM, Number="A1-1-5", Unit="100m3", Quantity=100.0)
n2 = dict(NEW_NORM, Number="A1-1-37", Unit="1000m3", Quantity=10.0)
out = xcos._bill_xml(bill, "WorkElement",
[xcos._norm_xml(n1, [("00010010", 1611.66)], xcos._full_norm_block(tmpl)),
xcos._norm_xml(n2, [("00010010", 595.03), ("990101015", 0.17)],
xcos._full_norm_block(tmpl))],
tmpl)
we = _parse(out)
tail = we.findall("LabourMaterialsEquipmentsMachinesElement")
assert [(c.get("Number"), c.get("Quantity"), c.get("Express")) for c in tail] == [
("00010010", "16.7116", "16.7116"), # 同码合并:(1611.66×100+595.03×10)÷10000
("990101015", "0.0002", "0.0002"), # 0.17×10÷10000
], [(c.get("Number"), c.get("Quantity")) for c in tail]
def test_new_bill_top_anchor_position(server):
"""决策 106 补记四:工作台插在最上面(insert_above 第一条 → 锚点 0)的新增清单,
导出落位 = 第一条源清单**之前**。此前锚点 0 被当「无锚点」甩到组尾
(主人 2026-10-18 实测:软件里插序号 1,易达里跑到最后)。"""
import hashlib
import sqlite3
import uuid
proj = "顶部插入工程-" + uuid.uuid4().hex[:6]
bills = [("B00%d" % i, "清单%d" % i, "1、x", "m3", 10 + i, 100.0) for i in (1, 2, 3)]
p = H.make_cos4(str(server["src_dir"] / ("top_%s_raw.cos4" % proj[-6:])), proj, bills)
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_top.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "w+b") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
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"] # 决策 243:工作台用同内容双胞胎件
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
first_id = [r[0] for r in rows if r[1] == "B001"][0]
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "insert_above",
"bill_id": first_id})
assert r["ok"] is True, r
new_id = r["id"]
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit", "bill_id": new_id,
"fields": {"Name": "顶部新增清单"}})
assert r["ok"] is True, r
zf = _export_zip(server, sid)
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
if n.lower() != "project.xml")
assert txt.index('Name="顶部新增清单"') < txt.index('Number="B001"'), "新增清单应在第一条源清单之前"
def test_new_bill_follows_own_division():
"""新增清单落位按自己的 div_id 找同分部锚点——2026-10-20 220kV 实测:
C20原色透水混凝土 div=支撑下挖土,但前一条源清单在顶管井部分,旧逻辑会插错分部。"""
xml = (
''
''
''
''
''
''
''
'')
def bill(i, div, num, name, price):
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
"src_remark": None, "x_tdel": 0}
a, b = bill(1, 1, "A001", "源清单A", "10.00"), bill(2, 2, "B001", "源清单B", "20.00")
new = bill(3, 2, "C001", "新增透水混凝土", "53.23")
new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0})
out = xcos.transform_unit(xml, ("U1", "UW1"),
{"item": [(1, a), (2, b)]},
{"item": [new]}, {}, {})
i_div_b = out.index('Name="DIV_B"')
i_new = out.index('Name="新增透水混凝土"')
i_b = out.index('Number="B001"')
assert i_div_b < i_new < i_b, out
def test_new_bill_middle_of_own_division():
"""分部内下插:锚点在同一个分部时,插在锚点源清单之后、下一条同分部源清单之前。"""
xml = (
''
''
''
''
''
''
''
''
'')
def bill(i, div, num, name, price):
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
"src_remark": None, "x_tdel": 0}
a1, a2, b1 = (bill(1, 1, "A1", "源A1", "10.00"),
bill(2, 1, "A2", "源A2", "20.00"),
bill(3, 2, "B1", "源B1", "30.00"))
new = bill(4, 1, "C1", "分部内新增", "30.00")
new.update({"_anchor": 1, "Unit": "m2", "Quantity": 100.0, "Total": 3000.0})
out = xcos.transform_unit(xml, ("U3", "UW3"),
{"item": [(1, a1), (2, a2), (3, b1)]},
{"item": [new]}, {}, {})
assert (out.index('Number="A1"') < out.index('Name="分部内新增"')
< out.index('Number="A2"')), out
def test_new_loose_bill_appends_at_end():
"""无分部(loose)新增行:工作台显示在单位工程树尾,导出也要落在本组最后,
不能按 x_seq=1 跑到最前(2026-10-20 220kV 实测)。"""
xml = (
''
''
''
''
''
''
''
'')
def bill(i, div, num, name, price):
return {"id": i, "div_id": div, "Number": num, "Name": name, "Attr": "",
"Unit": "m3", "Quantity": 1.0, "Price": price, "Total": price,
"src_remark": None, "x_tdel": 0}
a, b = bill(1, 1, "A1", "源清单A", "10.00"), bill(2, 2, "B1", "源清单B", "20.00")
new = bill(3, None, "C1", "末尾新增清单", "53.23")
new.update({"_anchor": 0, "Unit": "m2", "Quantity": 100.0, "Total": 5323.0})
out = xcos.transform_unit(xml, ("U2", "UW2"),
{"item": [(1, a), (2, b)]},
{"item": [new]}, {}, {})
assert out.index('Number="B1"') < out.index('Name="末尾新增清单"'), out
def test_amount_aggregate_row_synced_like_normal():
"""决策 169(2026-10-22 主人定):金额汇总行(数量=金额合计、单价=1 的费用科目行)
**视同普通工料机**——编辑/同步/导出回填全部同普通行,价格照写。
原决策 106 补记九「金额行不回写价格」防护撤除:实测爆炸来自旧全量同步的大面积
误写,现通道(merged_codes/field_codes 白名单)只有编辑过的编码才会被写。"""
txt = (''
''
''
'')
sync = [("00010010", "人工费", "", "元", 500.0, 0.0, 500.0),
("990101015", "履带式推土机", "", "台班", 1232.54, 0.0, 1232.54)]
out = xcos.transform_project(txt, [], [], sync_rows=sync)
agg = re.search(r']*', out).group(0)
assert 'NoTaxPrice="500.0"' in agg and 'TaxPrice="500.0"' in agg # 视同普通行:价格照写
mac = re.search(r']*', out).group(0)
assert 'NoTaxPrice="1232.54"' in mac # 正常资源行照常回写
def test_adoption_carries_express_adjustment(server):
"""决策 106 补记十二:定额换算调整式(含量 Express,如人工费 *1.2)跟历史项目走——
导入捕获入库 → 采纳携带 → 导出按算式原样填写(此前只存数值,调整信息丢失)。"""
import hashlib
import sqlite3
import uuid
proj = "调整式工程-" + uuid.uuid4().hex[:6]
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
p = H.make_cos4(str(server["src_dir"] / ("expr_%s_raw.cos4" % proj[-6:])), proj, bills)
# 给夹具的定额工料机行补上换算算式(模拟广联达原生 Express)
z = _zipfile.ZipFile(p) if False else zipfile.ZipFile(p)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for nm in z.namelist():
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' 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",
"%s_expr.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
hc = sqlite3.connect(server["db"])
got = hc.execute("SELECT express FROM norm_res WHERE express IS NOT NULL").fetchall()
hc.close()
assert got and got[0][0] == "1.5*1.2", got[:3] # 导入捕获算式
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}
resp = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp))) # 决策 243
assert resp.get("session_id"), resp
sid = resp["session_id"]
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
bill_id = [r[0] for r in rows if r[1] == bills[0][0]][0]
src_id = sqlite3.connect(server["db"]).execute(
"SELECT id FROM bills WHERE Number=?", (bills[0][0],)).fetchone()[0]
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
"src_bill_id": src_id})
assert r["ok"] is True, r
se = sqlite3.connect(server["sessdb"])
got = se.execute("SELECT express FROM s_norm_res WHERE norm_id IN "
"(SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1)", (bill_id,)).fetchall()
se.close()
assert got and got[0][0] == "1.5*1.2", got[:3] # 采纳携带
zf = _export_zip(server, sid)
txt = "".join(zf.read(n).decode("utf-8", errors="replace") for n in zf.namelist()
if n.lower() != "project.xml")
import re as _re
mm = _re.search(r'', txt, _re.S)
print('ADOPTED NORM BLOCK:', mm.group(0)[:600] if mm else '(N-1 不在导出中)')
print('txt has N-1:', 'N-1' in txt, '| txt len:', len(txt))
assert 'Express="1.5*1.2"' in txt # 导出按历史调整式填写
def test_resource_pseudo_norm_skipped_on_import(server):
"""决策 106 补记十四:广联达把清单级资源构成行(人工费等,编码=纯数字工料机码、
单位=元)也写成 元素——不是定额,导入即滤掉(此前被采纳当定额带进
工作台=人工费外溢实测);真定额与调整记录不受影响。"""
import hashlib
import sqlite3
import uuid
proj = "伪定额过滤工程-" + uuid.uuid4().hex[:6]
bills = [("010101001001", "挖单独土方", "1、x", "m3", 10000, 126.17)]
p = H.make_cos4(str(server["src_dir"] / ("pseudo_%s_raw.cos4" % proj[-6:])), proj, bills)
z = zipfile.ZipFile(p)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for nm in z.namelist():
d = z.read(nm)
if nm.lower() != "project.xml":
pseudo = ('').encode("utf-8")
d = d.replace(b'', b'' + pseudo + b'')
zo.writestr(nm, d)
raw = buf.getvalue()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_pseudo.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
hc = sqlite3.connect(server["db"])
n = hc.execute("SELECT COUNT(*) FROM norms WHERE Number='00010010'").fetchone()[0]
hc.close()
assert n == 0, n # 伪定额不落批次库
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"] # 决策 243:工作台用同内容双胞胎件
sc = sqlite3.connect(server["sessdb"])
n2 = sc.execute("SELECT COUNT(*) FROM s_norms WHERE Number='00010010'").fetchone()[0]
n3 = sc.execute("SELECT COUNT(*) FROM s_norms").fetchone()[0]
sc.close()
assert n2 == 0 and n3 >= 1, (n2, n3) # 工作台也不出现(外溢源头掐断)
def test_edited_totals_follow_qty_times_price(server):
"""决策 106 补记十六(主人定):清单/定额 合价 = 工程量×单价——
改工程量后(工作台保存时 + 导出兜底)合价跟着走;数值相同不产生字节改动。"""
import hashlib
import sqlite3
import uuid
proj = "合价口径工程-" + uuid.uuid4().hex[:6]
bills = [("B001", "挖单独土方", "1、x", "m3", 10, 500)]
p = H.make_cos4(str(server["src_dir"] / ("total_%s_raw.cos4" % proj[-6:])), proj, bills)
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_total.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
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"] # 决策 243:工作台用同内容双胞胎件
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
bill_id = [r[0] for r in rows if r[1] == "B001"][0]
norm_id = sqlite3.connect(server["sessdb"]).execute(
"SELECT id FROM s_norms WHERE bill_id=?", (bill_id,)).fetchone()[0]
# 改清单工程量 10→20:合价 = 20×500
r = post(server, "/api/session/bill/op", {"session_id": sid, "op": "edit",
"bill_id": bill_id, "fields": {"Quantity": "20"}})
assert r["ok"] is True, r
tb = sqlite3.connect(server["sessdb"]).execute(
"SELECT Total FROM s_bills WHERE id=?", (bill_id,)).fetchone()[0]
assert abs(tb - 10000) < 0.01, tb # 工作台保存即同步
# 改定额工程量 10→15(数字):合价 = 15×80
r = post(server, "/api/session/norm/op", {"session_id": sid, "norm_id": norm_id,
"fields": {"Quantity": "15"}})
assert r["ok"] is True, r
tn = sqlite3.connect(server["sessdb"]).execute(
"SELECT Total FROM s_norms WHERE id=?", (norm_id,)).fetchone()[0]
assert abs(tn - 1200) < 0.01, tn # 15×80
zf = _export_zip(server, sid)
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"
def _export_zip(server, sid):
# 决策 264 补记(2026-11-03):原格式导出只走骨架回灌——测试就地从本会话源件提炼一件骨架
# (真实流程=后台上传骨架;这里不依赖本机预置件,保证同口径可跑)。
sc = sqlite3.connect(server["sessdb"])
sc.row_factory = sqlite3.Row
try:
srow = sc.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
finally:
sc.close()
src_name = srow["src_name"] if srow else ""
sfx = xcos_suffix(src_name)
hc = sqlite3.connect(server["db"])
hc.row_factory = sqlite3.Row
try:
src = os.path.join(str(server["root"]), "CostReview", "data", "source_files", src_name)
if os.path.exists(src):
import classic_skeleton as _cs
_cs.seed_frame(hc, src, "测试骨架-" + (sfx or "x"))
finally:
hc.close()
resp = server["client"].get("/api/session/export", params={"session_id": sid})
if not resp.headers["content-type"].startswith("application/zip"):
raise AssertionError("导出失败: " + resp.text[:300])
return zipfile.ZipFile(io.BytesIO(resp.content))
def xcos_suffix(name):
import classic_skeleton as _cs
return _cs.suffix_of(name)
def test_coef_unit_prefix_no_double_count(server):
"""10m 定额:历史 清单1094.68 / 定额109.468 → 系数 GCL 口径 = 1.0,
清单量改 90000000 后导出定额量 = 9000000(=GCL,单位换算只算一次)。"""
import hashlib
import sqlite3
import uuid
proj = "系数口径工程-" + uuid.uuid4().hex[:6]
bill = ("040501004001", "高性能硬聚乙烯PVC-UH排水管DN200", "1、x", "m", 1094.68, 63.31)
lme = ("000001", "网络摄像机", "400万", "台", "1200", "1356")
p = H.make_cos4(str(server["src_dir"] / ("coef_%s_raw.cos4" % proj[-6:])), proj, [bill], [lme])
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_coef.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "w+b") as f:
f.write(raw)
imp = post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))
assert imp["ok"] is True, imp
# 把该批次定额改成 10m 口径的历史形态(清单 1094.68m、定额 109.468 每 10m),
# 系数按 GCL 口径 = 定额量×前缀÷清单量 = 1.0
hc = sqlite3.connect(server["db"])
hc.execute("UPDATE norms SET Unit='10m', Quantity=109.468,"
" x_qty_coef=ROUND(109.468*10/(SELECT Quantity FROM bills WHERE bills.id=norms.bill_id),6)")
hc.commit(); hc.close()
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"] # 决策 243:工作台用同内容双胞胎件
rows = get(server, "/api/session/rows", session_id=sid, type="bill")["rows"]
bill_id = [r[0] for r in rows if r[1] == bill[0]][0]
src_id = sqlite3.connect(server["db"]).execute(
"SELECT id FROM bills WHERE Number=?", (bill[0],)).fetchone()[0]
r = post(server, "/api/session/bill/adopt", {"session_id": sid, "bill_id": bill_id,
"src_bill_id": src_id})
assert r["ok"] is True, r
expr = sqlite3.connect(server["sessdb"]).execute(
"SELECT qty_expr FROM s_norms WHERE bill_id=? AND x_adopt=1", (bill_id,)).fetchone()[0]
assert expr == "GCL*1.0000", expr # 旧口径这里会给 GCL*0.1000(双算单位)
con = sqlite3.connect(server["sessdb"])
con.execute("UPDATE s_bills SET Quantity=90000000 WHERE id=?", (bill_id,))
con.commit(); con.close()
zf = _export_zip(server, sid)
hits = sum(zf.read(n).count(b'Quantity="9000000.000000"') for n in zf.namelist())
assert hits == 1, hits # 90000000 ÷ 10m 前缀 = 9000000,不是 900000