Files
pricing_review/CostReview/app/tests/test_export_structure.py

473 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""决策 106(2026-10-17)两件实测事故的回归:
①插入节点整块克隆——此前新增清单/采纳定额只克隆开标签,缺原生 innards(费用构成汇总、
单价计算公式行、WorkContent 壳…),易达按结构取数看不到新增清单(cos 与 cos4 同样
实测),广联达整包报「不是有效标书」;
②工程量系数 GCL 口径——旧口径(定额量÷清单量)在 10m/100m 类单位上把单位换算双算两遍
(前山河 040501004001:10m 定额导出量少 10 倍实测)。
"""
import io
import os
import re
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 = (
'<WorkElement Number="040803004001" Name="管道封堵" Attr="1、封堵现状管" WorkContent="" Unit="个"'
' Quantity="2.000" QtyFormula="" Price="1187.14" Total="2374.28" EquipmentPrice="0" Rate="0"'
' PriceLow="0" PriceHigh="0" Major="false" CalcType="1" Code="" ListingIdentity="GB50857-2013 4 GD"'
' Specialty="4" Kind="1" CalculationKind="15" CostKind="3" Remark="L:3平面图中只见2个">'
'<SummaryOfBasicCost Labor="269.72" Material="880.90" MainMaterial="0" Equipment="0"'
' MainMaterialEquipment="0" Appraisal="0" Machine="856.42" Overhead="198.32" Profit="168.92"'
' StatutoryFees="0" Tax="0" ForeignCurrency="0" ConvertedIntoRMB="0"/>'
'<ExpressElement OrderNumber="1" Express="2" Quantity="2" Kind="1" Remark=""/>'
'<Norm Number="3-1-1" Name="管堵砌筑 直径(mm内) DN600//调:" Unit="只" Quantity="2.000000"'
' Price="1187.14" EquipmentPrice="0" Total="2374.28" EfficiencyKind="2" IncFeeKind="2"'
' Conversion="" Specialty="99" NormIdentity="GD 99 2019" Volume="0" Chapter="0"'
' EquipmentTotal="0" ForeignCurrency="0" ConvertedIntoRMB="0" IsNorm="true" Kind="1"'
' CalculationKind="15" CostKind="3" Remark="">'
'<ExpressElement OrderNumber="1" Express="QGCL" Quantity="2" Kind="1" Remark=""/>'
'<ManageFees Fee1="17.61" Fee2="17.61" Fee3="17.61" Fee4="17.61" Rate="1.00"'
' AddFee1="0" AddFee2="0" AddFee3="0" AddFee4="0"/>'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="134.86" NOCost="false" Remark=""/>'
'<UnitPriceCalculationOfItem Code="RGF" Name="人工费" Total="134.86" QtyFormula="_RGF" Rate="100.000" Remark="人工费"/>'
'<UnitPriceCalculationOfItem Code="HJ" Name="子目合价" Total="2374.28" QtyFormula="_GCL*7" Rate="100.000" Remark="工程量*单价"/>'
'</Norm></WorkElement>')
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("<r>%s</r>" % 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_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 = (
'<Norm Number="A1-2-48" Name="锚杆土钉机械成孔 土层 孔径≤150mm" Unit="100m" Quantity="19.010000"'
' Price="6077.49" Total="115533.08" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
'<ExpressElement OrderNumber="1" Area="" Express="QGCL" Explain="" Quantity="1901" Kind="1" Remark=""/>'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="1715.0700" Quantity="1715.0700" Remark=""/>'
'<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00" Total="1852.28" Code="RGF" Remark="人工费"/>'
'<NormAdjustmentList OrderNumber="1" Value="换:工程地质液压钻机 "/>'
'<NormAdjustmentList OrderNumber="3" Value="修改990212120-0001单价:760.74"/>'
'</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('<UnitPriceCalculationOfItem Name="子目合价" QtyFormula="189006.16"'
' Rate="100.00" Total="0" Code="HJ" Remark=""/>').count('QtyFormula=""') == 1
assert '_GCL*7' in xcos._zero_results('<UnitPriceCalculationOfItem Name="子目合价" QtyFormula="_GCL*7"'
' Rate="100.00" Total="0" Code="HJ" Remark=""/>') # 通用公式保留
# 工料机行模板(bill 尾表重建)同样清 Express
row = xcos._lme_row('<LabourMaterialsEquipmentsMachinesElement Number="00010010"'
' Express="90.5224" Quantity="90.5224" Remark=""/>', "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 = ('<WorkElement Number="040101001001" Name="挖一般土方" Attr="1、土壤类别:综合" WorkContent=""'
' Unit="m3" Quantity="1483.220" Price="4.29" Total="6363.01" Type="1" PriceType="1"'
' ListingIdentity="GB/T 50857-2024 4 440000" Specialty="4" Kind="1" Remark="">'
'<SummaryOfBasicCost Labor="951.52" Material="0" Machine="4034.54" Overhead="628.74"'
' Profit="747.91" DivisionalAndElementalWorks="6363.01" Tax="0"/>'
'<ExpressElement OrderNumber="1" Area="" Express="1483.22" Explain="" Quantity="1483.22" Kind="1" Remark=""/>'
'<WorkContent Name="土方开挖" Total="6362.70" Remark="">'
'<Norm Number="D1-1-29" Name="挖掘机挖一般土方 一、二类土" Unit="1000m3天然密实方" Quantity="1.483220"'
' Price="4289.79" Total="6362.70" Specialty="4" NormIdentity="440000 4 2018" IsNorm="true" Type="1" Remark="">'
'<ExpressElement OrderNumber="1" Area="" Express="QGCL" Explain="" Quantity="1483.22" Kind="1" Remark=""/>'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="" Quantity="594.0000" Remark=""/>'
'<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00" Total="641.52" Code="RGF" Remark="人工费"/>'
'</Norm></WorkContent>'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Express="" Quantity="881.00" Remark=""/>'
'</WorkElement>')
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 = ('<WorkElement Number="010101001001" Name="挖单独土方" WorkContent="" Unit="m3"'
' Quantity="10000" Price="126.17" Total="1261700" NormIdentity="X" Kind="1" Remark="">'
'<SummaryOfBasicCost Labor="1" Material="0" Tax="0"/>'
'<WorkContent Name="开挖" Total="1" Remark="">'
'<Norm Number="A1-1-5" Name="人工挖一般土方 一、二类土" Unit="100m3" Quantity="100"'
' Price="2183.8" Total="218380" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="1611.6600" Remark="" Express="1611.66*1"/>'
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
'</Norm>'
'<Norm Number="A1-1-37" Name="挖掘机挖一般土方 一、二类土" Unit="1000m3" Quantity="10"'
' Price="4323.21" Total="43232.1" NormIdentity="440000 1 2018" IsNorm="true" Remark="">'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="595.0300" Remark="" Express="595.03*1"/>'
'<LabourMaterialsEquipmentsMachinesElement Number="990101015" Quantity="0.1700" Remark="" Express="0.17*1"/>'
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
'</Norm></WorkContent>'
'<LabourMaterialsEquipmentsMachinesElement Number="00010010" Quantity="90.5224" Remark="" Express="90.5224"/>'
'<UnitPriceCalculationOfItem Name="单价" QtyFormula="RGF" Rate="100" Total="0" Code="DJ" Remark=""/>'
'</WorkElement>')
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=hp))["session_id"]
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_amount_aggregate_row_price_never_synced():
"""决策 106 补记九:广联达文件的「人工费」类汇总行是金额汇总行(数量=金额合计、
单价恒 1、单位=元)。会话里合并改价把它的单价改成资源口径(如人工 500 元/工日)
后,导出同步不得回写——原文件 数量×500 会让 Glodon 人工费爆炸外溢(样例工程实测)。"""
txt = ('<ConstructionProject>'
'<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="人工费" Unit="元"'
' Quantity="4142082.6" NoTaxPrice="1" TaxRate="0" TaxPrice="1"/>'
'<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="履带式推土机" Unit="台班"'
' Quantity="6.1" NoTaxPrice="1039.8" TaxRate="9.48" TaxPrice="1138.37"/>'
'</ConstructionProject>')
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'<LabourMaterialsEquipmentsMachinesSummary Number="00010010"[^>]*', out).group(0)
assert 'NoTaxPrice="1"' in agg and 'TaxPrice="1"' in agg # 金额汇总行价格不动
mac = re.search(r'<LabourMaterialsEquipmentsMachinesSummary Number="990101015"[^>]*', out).group(0)
assert 'NoTaxPrice="1232.54"' in mac # 正常资源行照常回写
assert xcos._is_amount_aggregate(
'<LabourMaterialsEquipmentsMachinesSummary Number="X" Unit="元" NoTaxPrice="1"/>')
assert not xcos._is_amount_aggregate(
'<LabourMaterialsEquipmentsMachinesSummary Number="X" Unit="台班" NoTaxPrice="1039.8"/>')
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'<Norm ', b'<Norm NormIdentity="TEST 1 2018" ')
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=hp))
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'<Norm Number="N-1".{0,600}?</Norm>', 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 补记十四:广联达把清单级资源构成行(人工费等,编码=纯数字工料机码、
单位=元)也写成 <Norm> 元素——不是定额,导入即滤掉(此前被采纳当定额带进
工作台=人工费外溢实测);真定额与调整记录不受影响。"""
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 = ('<Norm Number="00010010" Name="人工费" Unit="元" Quantity="89.1513"'
' Price="1.2" Total="106.98" IsNorm="true" Type="1" CalculationKind="1"'
' CostKind="1" EfficiencyKind="2" IncFeeKind="2" Specialty="1"'
' NormIdentity="TEST 1 2018" Remark=""/>').encode("utf-8")
d = d.replace(b'</Norm></WorkElement>', b'</Norm>' + pseudo + b'</WorkElement>')
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=hp))["session_id"]
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=hp))["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] == "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.0"' in txt, "清单合价应=20×500"
assert 'Total="1200.00"' in txt, "定额合价应=15×80"
def _export_zip(server, sid):
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 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=hp))["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] == 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