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

171 lines
8.7 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 -*-
"""形态银行(决策 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()