feat(adopt): 决策273 单价行 Total 采纳逻辑迁回 API 侧并调整 x_side 读取

This commit is contained in:
lianjianwei2024
2026-11-05 08:24:06 +08:00
parent e113eb0264
commit 0dcdddc4a1
19 changed files with 196 additions and 216 deletions

View File

@@ -270,17 +270,6 @@ def _child_block_html(txt, rows):
return "".join(sep_e + _child_node(ktmpl, c, q) for (c, q) in rows)
def _adopt_totals(frag, sm):
"""决策 273:单价行 Total 按 Name 匹配回填——一致=外部该行 Total;不一致=空串(留空)。
只动骨架已有的 UnitPriceCalculationOfItem 自闭合行(卡槽在才写)。"""
def _f(m):
a = dict(re.findall(r'(\w+)="([^"]*)"', m.group(1)))
nm = (a.get("Name") or "").strip()
v = sm.get(nm)
return _attr_set(m.group(0), "Total", "" if v is None else v)
return re.sub(r'<UnitPriceCalculationOfItem\b([^>]*?)/>', _f, frag)
def _zero_results(frag):
"""决策 106:克隆模板 innards 时把「结果值」属性清零——金额/数量是别人清单算出来的,
带过来就是脏数据;公式(QtyFormula/Express 文本)、费率(Rate)、结构属性原样保留,
@@ -387,21 +376,6 @@ def _norm_xml(n, lres, template=None, bill_qty=None):
pre, post = _zero_results(pre), _zero_results(post)
pre = re.sub(r'<ExpressElement\b[^>]*/>', '', pre)
post = re.sub(r'<ExpressElement\b[^>]*/>', '', post)
# 决策 273(2026-11-04 主人定):采纳定额的单价行 Total 按 Name 匹配外部——
# x_side(采纳时构造:同区模板行组+Total 按 Name 匹配外部,一致=外部值/不一致留空)
# 有值时回填 Total 覆盖清零;无 x_side 维持清零现状(106 口径不动)。
_sm = {}
if n.get("x_side"):
try:
for _rec in json.loads(n["x_side"]):
if _rec.get("tag") == "UnitPriceCalculationOfItem":
_a = _rec.get("attrs") or {}
_sm[(_a.get("Name") or "").strip()] = _a.get("Total")
except Exception:
_sm = {}
if _sm:
pre = _adopt_totals(pre, _sm)
post = _adopt_totals(post, _sm)
# 换算调整记录(补记十三):先剥掉模板的记录(那是模板定额的历史),再按本定额
# 会话携带的 x_adjust 重写——采纳定额的调整工艺(GConvInfo 标准换算/R*2,J*2/送桩
# 材料含量…)跟历史项目走,主人定「有信息就要搬」。行形态照模板首行克隆。

View File

@@ -4143,16 +4143,16 @@ def api_bill_adopt(sc, hc, body):
_a = _rec.get("attrs") or {}
_m[(_a.get("Name") or "").strip()] = _a.get("Total")
_ext_by_norm[_n2["id"]] = _m
except Exception:
pass
except Exception as _e:
print("273 ext err:", _e, flush=True)
_tmpl_side = None
try:
_pt = sc.execute("SELECT x_ptag FROM s_bills WHERE id=?", (bid,)).fetchone()
_ptag = ((_pt["x_ptag"] if _pt else None) or "")
_t = sc.execute("""SELECT n.x_side FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
WHERE b.session_id=? AND COALESCE(n.x_adopt,0)=0 AND n.x_side IS NOT NULL
AND b.id<>? AND COALESCE(b.x_ptag,'')=?
ORDER BY n.id LIMIT 1""", (sid, bid, _ptag)).fetchone()
AND COALESCE(b.x_ptag,'')=?
ORDER BY n.id LIMIT 1""", (sid, _ptag)).fetchone()
if _t and _t["x_side"]:
_tmpl_side = _t["x_side"]
except Exception:

View File

@@ -36,7 +36,7 @@ def _free_port():
# ------------------------------------------------------------------ 造数
def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
proj_lmes=None, uw_lmes=None, zip_ts=None, uw_lme_attrs=None,
lme_rot=False):
lme_rot=False, norm_extra=""):
"""构造最小可解析的 .cos4(zip 内 Project.xml + 单位工程 xml)。
bills: [(编码, 名称, 特征, 单位, 工程量, 单价)] —— 分部分项清单(自动配 1 条定额 + 定额消耗)
@@ -71,12 +71,13 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
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>'
'<LabourMaterialsEquipmentsMachinesElement Number=%s Quantity="1.5"/>'
'<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)), quoteattr(lme0),
norm_extra))
uw = (
'<UnitWorks Number="UW1" Name="1号楼" Total="999999" Specialty="建筑工程">'

View File

@@ -54,7 +54,7 @@ def _mk_hc():
def test_adopt_children_full_path():
sc, hc = _mk_sc(), _mk_hc()
hc.execute("CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT)")
hc.execute("CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
hc.execute("CREATE TABLE norm_res(norm_id INT, res_code TEXT, qty REAL)")
hc.execute("INSERT INTO norms(id, bill_id) VALUES(10, 900)")
hc.executemany("INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)",

View File

@@ -28,7 +28,7 @@ def _mk_sc():
x_price0 REAL, x_seq INT, src_remark TEXT, x_remark TEXT)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Number TEXT, Name TEXT,
Unit TEXT, Quantity REAL, Price REAL, Total REAL, x_tdel INT, x_adopt INT,
x_src_norm_id INT, x_adjust TEXT, qty_expr TEXT)""")
x_src_norm_id INT, x_adjust TEXT, qty_expr TEXT, x_side TEXT)""")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT,
qty REAL, express TEXT, x_ntp REAL, x_taxp REAL)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
@@ -58,7 +58,7 @@ def _mk_hc():
c.execute("""CREATE TABLE bills(id INTEGER PRIMARY KEY, batch_id INT, Number TEXT, Name TEXT,
Attr TEXT, Unit TEXT, Price REAL, Quantity REAL)""")
c.execute("""CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT, Number TEXT, Name TEXT,
Unit TEXT, Quantity REAL, Price REAL, Total REAL, x_qty_coef REAL, x_adjust TEXT)""")
Unit TEXT, Quantity REAL, Price REAL, Total REAL, x_qty_coef REAL, x_adjust TEXT, x_side TEXT)""")
c.execute("""CREATE TABLE norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT,
qty REAL, express TEXT)""")
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT, p_code TEXT,

View File

@@ -0,0 +1,160 @@
# -*- coding: utf-8 -*-
"""决策 273 e2e 回归:采纳外部定额的单价行组——行与列按本项目同区模板复制,
Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空);导出件同口径。"""
import io
import json
import os
import sys
import zipfile
import pytest
_HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(_HERE), "core"))
sys.path.insert(0, _HERE)
from api_harness import META, PERIOD_202607, get, make_cos4, post, server # noqa: F401,E402
from test_api_p1 import raw_post # noqa: E402
TPL_XML = ('<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00"'
' Total="100.00" Code="RGF" Remark="人工费"/>'
'<UnitPriceCalculationOfItem Name="材料费" QtyFormula="_CLF" Rate="100.00"'
' Total="200.00" Code="CLF" Remark="材料费"/>'
'<UnitPriceCalculationOfItem Name="子目单价" QtyFormula="1..3" Rate="100.00"'
' Total="350.00" Code="DJ" Remark=""/>')
EXT_XML = ('<UnitPriceCalculationOfItem Name="人工费" QtyFormula="_RGF" Rate="100.00"'
' Total="999.00" Code="RGF" Remark="人工费"/>'
'<UnitPriceCalculationOfItem Name="子目单价" QtyFormula="1..2" Rate="100.00"'
' Total="777.00" Code="DJ" Remark=""/>')
# 本项目模板行组(3 行)与外部行组(2 行:人工费 Total 不同值、无材料费 → 验留空)
TPL_SIDE = [
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "人工费", "QtyFormula": "_RGF",
"Rate": "100.00", "Total": "100.00", "Code": "RGF", "Remark": "人工费"}},
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "材料费", "QtyFormula": "_CLF",
"Rate": "100.00", "Total": "200.00", "Code": "CLF", "Remark": "材料费"}},
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "子目单价", "QtyFormula": "1..3",
"Rate": "100.00", "Total": "350.00", "Code": "DJ", "Remark": ""}},
]
EXT_SIDE = [
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "人工费", "QtyFormula": "_RGF",
"Rate": "100.00", "Total": "999.00", "Code": "RGF", "Remark": "人工费"}},
{"tag": "UnitPriceCalculationOfItem", "attrs": {"Name": "子目单价", "QtyFormula": "1..2",
"Rate": "100.00", "Total": "777.00", "Code": "DJ", "Remark": ""}},
]
def _import(server, fname, name, norm_extra=""):
"""造件+upload+audit 开会话(幂等:先删同名批次)。返回 (sid, db, sessdb)。"""
from api_harness import make_cos4
fix = server["root"] / "fixsrc"
fix.mkdir(exist_ok=True)
make_cos4(str(fix / fname), name,
[("030507008001", name + "清单项", "", "台", 3, 500)],
[("DTPL001", "模板定额", "", "m3", "10", "350")],
norm_extra=norm_extra)
import sqlite3 as _s
_con = _s.connect(server["db"])
try:
bids = [x[0] for x in _con.execute("SELECT id FROM batches WHERE name=?", (name,)).fetchall()]
finally:
_con.close()
for b in bids:
post(server, "/api/admin/batch/%d/delete" % b, {})
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
assert up["ok"] is True, up
r = post(server, "/api/audit", dict(META, path=up["path"], name=name, file_kind=1))
assert r.get("ok") is True, r
return r["session_id"]
def test_adopt_side_name_match(server): # noqa: F811
sid = _import(server, "决策273项目.cos4", "决策273项目", norm_extra=TPL_XML)
# 模板行组随造件导入自动入库(norm_side 通道 2026-11-03)——校验落到 s_norms.x_side
scon = __import__("sqlite3").connect("file:%s?mode=ro" % server["sessdb"], uri=True)
try:
bid = scon.execute("SELECT id FROM s_bills WHERE Name LIKE '%清单项%'").fetchone()[0]
xs = scon.execute("SELECT x_side FROM s_norms WHERE bill_id=? AND Number='N-1'",
(bid,)).fetchone()[0]
assert xs, "模板行组未入库"
finally:
scon.close()
# 外部件导入(批次;不再 audit 开会话——作为采纳源)
fix2 = server["root"] / "fixsrc"
make_cos4(str(fix2 / "决策273外部.cos4"), "决策273外部",
[("030507008002", "外部清单项", "", "台", 2, 400)],
[("DEXT001", "外部定额", "", "m3", "5", "777")])
make_cos4(str(fix2 / "决策273外部.cos4"), "决策273外部",
[("030507008002", "外部清单项", "", "台", 2, 400)],
[("DEXT001", "外部定额", "", "m3", "5", "777")],
norm_extra=EXT_XML)
up2 = raw_post(server, "/api/admin/upload", "决策273外部.cos4",
(fix2 / "决策273外部.cos4").read_bytes())
assert up2["ok"] is True, up2
r2 = post(server, "/api/admin/import",
dict(META, path=up2["path"], name="决策273外部", file_kind=1))
assert r2["ok"] is True, r2
con = __import__("sqlite3").connect(server["db"])
try:
src_bill = con.execute(
"SELECT id FROM bills WHERE batch_id=?", (r2["batch_id"],)).fetchone()[0]
finally:
con.close()
# 采纳:目标清单(本项目)← 外部源清单
post(server, "/api/session/bill/adopt",
{"session_id": sid, "bill_id": bid, "src_bill_id": src_bill})
# 断言:采纳落库的新定额行 x_side=模板行组+Total 按 Name 匹配
scon2 = __import__("sqlite3").connect("file:%s?mode=ro" % server["sessdb"], uri=True)
scon2.row_factory = __import__("sqlite3").Row
try:
row = scon2.execute(
"SELECT x_side FROM s_norms WHERE bill_id=? AND x_adopt=1", (bid,)).fetchone()
finally:
scon2.close()
assert row and row["x_side"], "采纳行应带行组"
side = json.loads(row["x_side"])
rows = [x["attrs"] for x in side if x.get("tag") == "UnitPriceCalculationOfItem"]
names = [x["Name"] for x in rows]
assert names == ["人工费", "材料费", "子目单价"], names # 行与列=本项目模板(3 行)
by = {x["Name"]: x["Total"] for x in rows}
assert by["人工费"] == "999.00", by # Name 一致 → 外部值
assert by["子目单价"] == "777.00", by # Name 一致 → 外部值
assert by["材料费"] == "", by # 外部无同名行 → 留空
# 导出前:从件1 源文件提炼骨架入库(骨架回灌引擎需要骨架在库)
import classic_skeleton as _cs
_up = str(next(iter(server["root"].rglob("*决策273项目.cos4")))) # 件1 副本(内容=原件)
_hc = __import__("sqlite3").connect(server["db"])
try:
_cs.seed_frame(_hc, _up, "骨架273")
finally:
_hc.close()
# 导出原格式:采纳定额块单价行同口径
resp = server["client"].get("/api/session/export",
params={"session_id": sid, "name": "决策273项目",
"province": "广东省", "city": "珠海市",
"period_from": PERIOD_202607})
assert resp.status_code == 200, resp.text[:200]
z = zipfile.ZipFile(io.BytesIO(resp.content))
import re as _re
got = []
for n in z.namelist():
if n.endswith(".xml") and n != "Project.xml":
txt = z.read(n).decode("utf-8", "replace")
for mm in _re.finditer(r'<Norm\b[^>]*Name="外部清单项安装".*?</Norm>', txt, _re.S):
blk = mm.group(0)
got += [dict(_re.findall(r'(\w+)="([^"]*)"', x.group(1)))
for x in _re.finditer(r"<UnitPriceCalculationOfItem\b([^>]*?)/>", blk)]
if not got:
import sys as _sys
for n2 in z.namelist():
if n2.endswith(".xml"):
txt2 = z.read(n2).decode("utf-8", "replace")
print("=== 条目", n2, "len", len(txt2), file=_sys.stderr)
print(txt2[:1600], file=_sys.stderr)
assert got, "导出件应有采纳定额单价行"
byx = {x["Name"]: x["Total"] for x in got}
assert byx.get("人工费") == "999.00", byx
assert byx.get("子目单价") == "777.00", byx
assert byx.get("材料费") == "", byx # 留空
post(server, "/api/session/delete", {"ids": [sid]})

View File

@@ -34,7 +34,7 @@ def _mk():
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, Quantity REAL)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL, Unit TEXT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL, Unit TEXT, x_side TEXT)")
c.execute("CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL)")
# 单位级行(id 序=导入序)——101/102 各有电:101 认第一行 0.77(0.75 被随便认掉)
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, spec, unit, kind,

View File

@@ -66,7 +66,7 @@ def _mk_sess(with_norms=False):
qty, ntp, taxrate, taxp) VALUES(14,1,101,'C9','钢筋','kg',2, 5, 88.0, 3.5, 91.04)""")
if with_norms:
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL, express TEXT)""")
c.executemany("INSERT INTO s_bills(id, session_id, uw_id) VALUES(?,?,?)",

View File

@@ -48,7 +48,7 @@ def _mk_sess():
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL, express TEXT)""")
# 项目级:K 保留码 + P 项目码(同 名称|规格|单位、价不同 → 成组);D800 另名(不成组)

View File

@@ -51,7 +51,7 @@ def _mk_sess():
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL, express TEXT)""")
# 一级台班(挖掘机两码=可合并组;载重车单码不成组)

View File

@@ -47,7 +47,7 @@ def _mk_sess():
# 夹具补空表防 no such table(数据面见 test_lme_field._mk_sess(with_norms=True))。
# IF NOT EXISTS:部分用例自建 s_bills(uw agg 回退),不能冲突。
c.execute("CREATE TABLE IF NOT EXISTS s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)")
c.execute("CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, bill_id INT)")
c.execute("CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT)")
c.execute("""CREATE TABLE IF NOT EXISTS s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL, express TEXT)""")
# id=1 正常材料(税率 3.5);id=2 台班(lme_res 有 p_code → 带子级组成);id=3 已隐藏
@@ -268,7 +268,7 @@ def test_raw_uw_agg_fallback_nine_wide_taxrate_at_7():
Quantity, NoTaxPrice, TaxRate, TaxPrice) VALUES(1,'C1','钢筋','kg',2, 10, 99.99, 3.5, 103.49)""")
sc.execute("""CREATE TABLE IF NOT EXISTS s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT)""")
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(1, 1, 101)")
sc.execute("""CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT)""")
sc.execute("""CREATE TABLE IF NOT EXISTS s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT, x_side TEXT)""")
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(1, 1)") # 形状随 _mk_sess(经 s_bills 圈会话,无 session_id 列)
sc.execute("""CREATE TABLE IF NOT EXISTS s_norm_res(id INTEGER PRIMARY KEY, session_id INT,
norm_id INT, res_code TEXT, qty REAL)""")

View File

@@ -28,7 +28,7 @@ def _mk():
sc.row_factory = sqlite3.Row
c = sc.cursor()
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, x_tdel INTEGER DEFAULT 0)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_tdel INTEGER DEFAULT 0)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_tdel INTEGER DEFAULT 0, x_side TEXT)""")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
@@ -44,7 +44,7 @@ def _mk():
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.executemany("INSERT INTO s_bills VALUES(?,?,?,0)", [(1, SID, 101), (2, SID, 102)])
c.executemany("INSERT INTO s_norms VALUES(?,?,0)", [(10, 1), (11, 2)])
c.executemany("INSERT INTO s_norms VALUES(?,?,0, NULL)", [(10, 1), (11, 2)])
c.executemany("INSERT INTO s_norm_res VALUES(?,?,?,?)",
[(100, 10, "DIESEL", 2.0), (101, 10, "TB", 0.5),
(102, 11, "TEMP", 1.0)]) # 定额 11 挂临删清单(x_tdel=1)

View File

@@ -30,7 +30,7 @@ def _mk_session():
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
uw_name TEXT, Number TEXT, Name TEXT, Quantity REAL)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT,
Number TEXT, Name TEXT, Quantity REAL)""")
Number TEXT, Name TEXT, Quantity REAL, x_side TEXT)""")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
@@ -38,7 +38,7 @@ def _mk_session():
c.executemany("INSERT INTO s_bills VALUES(?,?,?,?,?,?,?)",
[(1, SID, 101, "2#楼", "A4-1", "浇筑清单", 10.0),
(2, SID, 102, "3#楼", "B7-2", "回填清单", 5.0)])
c.executemany("INSERT INTO s_norms VALUES(?,?,?,?,?)",
c.executemany("INSERT INTO s_norms VALUES(?,?,?,?,?, NULL)",
[(10, 1, "A4-1H", "浇筑定额", 2.0), # 定额量 2(无公式→存储量)
(11, 2, "B7-2H", "回填定额", 1.0)])
c.executemany("INSERT INTO s_norm_res VALUES(?,?,?,?)",
@@ -76,7 +76,7 @@ def test_batch_branch_join_uworks():
c.execute("""CREATE TABLE unit_works(id INTEGER PRIMARY KEY, batch_id INT,
Number TEXT, Name TEXT)""")
c.execute("""CREATE TABLE norms(id INTEGER PRIMARY KEY, bill_id INT,
Number TEXT, Name TEXT, Quantity REAL)""")
Number TEXT, Name TEXT, Quantity REAL, x_side TEXT)""")
c.execute("""CREATE TABLE norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL)""")
c.execute("""CREATE TABLE lme_res(id INTEGER PRIMARY KEY, batch_id INT,
@@ -86,7 +86,7 @@ def test_batch_branch_join_uworks():
c.executemany("INSERT INTO bills VALUES(?,?,?,?,?,?)",
[(1, 1, 101, "A4-1", "浇筑清单", 10.0),
(2, 1, 102, "B7-2", "回填清单", 5.0)])
c.executemany("INSERT INTO norms VALUES(?,?,?,?,?)",
c.executemany("INSERT INTO norms VALUES(?,?,?,?,?, NULL)",
[(10, 1, "A4-1H", "浇筑定额", 2.0), (11, 2, "B7-2H", "回填定额", 1.0)])
c.executemany("INSERT INTO norm_res VALUES(?,?,?,?)",
[(100, 10, "TB1", 0.5), (101, 11, "RG1", 0.2)])

View File

@@ -31,7 +31,7 @@ def _mk_sess(with_summary):
NoTaxPrice REAL, TaxPrice REAL)""")
c.execute("""CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
Number TEXT)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, session_id INT, bill_id INT, x_side TEXT)""")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL)""")
c.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
@@ -45,7 +45,7 @@ def _mk_sess(with_summary):
else:
c.execute("INSERT INTO s_lmes VALUES(1, 1, '05010002', '普通硅酸盐水泥', '', 'kg', 2, 0.38, 0.4104)")
c.execute("INSERT INTO s_bills VALUES(1, 1, 10, 'B1')")
c.execute("INSERT INTO s_norms VALUES(1, 1, 1)")
c.execute("INSERT INTO s_norms VALUES(1, 1, 1, NULL)")
c.execute("INSERT INTO s_norm_res VALUES(1, 1, '05010002', 33.5)")
sc.commit()
return sc

View File

@@ -18,7 +18,7 @@ import api_server as srv # noqa: E402
DDL = """
CREATE TABLE sessions(id INTEGER PRIMARY KEY, name TEXT, src_name TEXT);
CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, Number TEXT);
CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT);
CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, x_side TEXT);
CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT, res_code TEXT, qty REAL);
CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT, Number TEXT, Name TEXT,
Specification TEXT, Unit TEXT, Kind INT, NoTaxPrice REAL, TaxPrice REAL);
@@ -42,7 +42,7 @@ def _mk():
sc.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
# 清单1(属单位工程 10)→ 定额1
sc.execute("INSERT INTO s_bills VALUES(1, 1, 10, 'B1')")
sc.execute("INSERT INTO s_norms VALUES(1, 1)")
sc.execute("INSERT INTO s_norms VALUES(1, 1, NULL)")
sc.commit()
return sc

View File

@@ -46,7 +46,7 @@ def _mk():
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.execute("CREATE TABLE s_bills(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, x_tdel INTEGER DEFAULT 0)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL DEFAULT 1, x_tdel INTEGER DEFAULT 0)")
c.execute("CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT, Quantity REAL DEFAULT 1, x_tdel INTEGER DEFAULT 0, x_side TEXT)")
c.execute("""CREATE TABLE s_norm_res(id INTEGER PRIMARY KEY, norm_id INT,
res_code TEXT, qty REAL, express TEXT)""")
c.execute("CREATE TABLE sessions(id INTEGER PRIMARY KEY, src_name TEXT)")

View File

@@ -31,28 +31,28 @@ def _mk():
x_new INT, x_tdel INT, x_adopt INT, x_seq INT, x_remark TEXT)""")
c.execute("""CREATE TABLE s_norms(id INTEGER PRIMARY KEY, bill_id INT,
Number TEXT, Name TEXT, Unit TEXT, Quantity REAL, Price REAL, Total REAL,
x_tdel INT, x_adopt INT, qty_expr TEXT)""")
x_tdel INT, x_adopt INT, qty_expr TEXT, x_side TEXT)""")
c.execute("INSERT INTO sessions VALUES(1,'工程甲','H_甲.cos4')")
c.execute("INSERT INTO s_unit_works VALUES(10, 1, NULL, 'UW-1', '土建', 660, '建筑')")
# B1 清单量 100,两条定额:429 + 121 = 550 → 单价 5.50、合价 550.00
c.execute("INSERT INTO s_bills VALUES(1,1,10,NULL,'B1','挖方',NULL,'m3',100,4.29,429,NULL,NULL,0,0,0,1,NULL)")
c.execute("INSERT INTO s_norms VALUES(11,1,'D1','挖槽','1000m3',0.429,1000,429,0,0,NULL)")
c.execute("INSERT INTO s_norms VALUES(12,1,'D2','运土','1000m3',0.121,1000,121,0,0,NULL)")
c.execute("INSERT INTO s_norms VALUES(11,1,'D1','挖槽','1000m3',0.429,1000,429,0,0,NULL, NULL)")
c.execute("INSERT INTO s_norms VALUES(12,1,'D2','运土','1000m3',0.121,1000,121,0,0,NULL, NULL)")
# B2 清单量 0:三值全 None
c.execute("INSERT INTO s_bills VALUES(2,1,10,NULL,'B2','空量',NULL,'m2',0,3.5,0,NULL,NULL,0,0,0,2,NULL)")
c.execute("INSERT INTO s_norms VALUES(21,2,'D3','垫层','10m2',5,70,350,0,0,NULL)")
c.execute("INSERT INTO s_norms VALUES(21,2,'D3','垫层','10m2',5,70,350,0,0,NULL, NULL)")
# B3 清单量 100,临删定额 500 不进 ∑,有效定额 300 → 单价 3.00
c.execute("INSERT INTO s_bills VALUES(3,1,10,NULL,'B3','回填',NULL,'m3',100,5,500,NULL,NULL,0,0,0,3,NULL)")
c.execute("INSERT INTO s_norms VALUES(31,3,'D4','临删行','10m3',5,100,500,1,0,NULL)")
c.execute("INSERT INTO s_norms VALUES(32,3,'D5','有效行','10m3',3,100,300,0,1,NULL)")
c.execute("INSERT INTO s_norms VALUES(31,3,'D4','临删行','10m3',5,100,500,1,0,NULL, NULL)")
c.execute("INSERT INTO s_norms VALUES(32,3,'D5','有效行','10m3',3,100,300,0,1,NULL, NULL)")
# B4 公式定额:GCL*0.5 → 50×2=100 → 单价 1.00
c.execute("INSERT INTO s_bills VALUES(4,1,10,NULL,'B4','公式',NULL,'m2',100,1,100,NULL,NULL,0,0,0,4,NULL)")
c.execute("INSERT INTO s_norms VALUES(41,4,'D6','公式行','10m2',NULL,2,NULL,0,1,'GCL*0.5')")
c.execute("INSERT INTO s_norms VALUES(41,4,'D6','公式行','10m2',NULL,2,NULL,0,1,'GCL*0.5', NULL)")
# B5 手工清单(无定额):照捕获值
c.execute("INSERT INTO s_bills VALUES(5,1,10,NULL,'B5','手工',NULL,'项',3,12.34,37.02,NULL,NULL,0,0,0,5,NULL)")
# B6 单定额四舍五入半升:0.535×5=2.675 → 2.68(银行家舍入会得 2.67)
c.execute("INSERT INTO s_bills VALUES(6,1,10,NULL,'B6','半升',NULL,'t',1,2.67,2.67,NULL,NULL,0,0,0,6,NULL)")
c.execute("INSERT INTO s_norms VALUES(61,6,'D7','半发行','t',0.535,5,2.67,0,0,NULL)")
c.execute("INSERT INTO s_norms VALUES(61,6,'D7','半发行','t',0.535,5,2.67,0,0,NULL, NULL)")
sc.commit()
return sc

View File

@@ -1,104 +0,0 @@
# -*- coding: utf-8 -*-
"""决策 273 实施:采纳外部定额的单价行组——行与列按本项目同区模板复制,
Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空)。
改动:①api_server 采纳段 bnorms SELECT+INSERT 带 x_side(采纳时构造最终行组)
②export_cos._norm_xml 按 x_side 回填单价行 Total(无 x_side 维持清零现状)。"""
import io
p = r"D:\PricingReview\CostReview\app\server\api_server.py"
s = io.open(p, encoding="utf-8").read()
# ---- ① 两处 bnorms SELECT 加 x_side ----
old = ''' bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
NULL AS x_qty_coef, x_adjust, qty_expr
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
(src_self,)).fetchall()'''
new = ''' bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
NULL AS x_qty_coef, x_adjust, qty_expr, x_side
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
(src_self,)).fetchall()'''
assert old in s, "bnorms sc NOT FOUND"
s = s.replace(old, new)
old2 = ''' bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()'''
new2 = ''' bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()'''
assert old2 in s, "bnorms hc NOT FOUND"
s = s.replace(old2, new2)
# ---- ② bnorms 取完后构造:外部 Name→Total 映射 + 本项目同区模板行组 ----
old3 = ''' def _norm_expr(nn):
# 决策 217(2026-10-26 主人定):采纳定额公式**四入口统一为分部分项同款 GCL×系数**——'''
new3 = ''' # 决策 273(2026-11-04 主人定):采纳定额的单价行组——行与列按本项目同区模板复制,
# Total 按 Name 匹配外部(一致=外部该行 Total,不一致留空)。外部单价行=norms.x_side
# (norm_side 通道 2026-11-03 已入库);本项目同区模板=同 x_ptag(措施/分部)任一条
# 非采纳定额的 x_side;本项目无同区模板→x_side 置空(骨架态,等原软件组价)。
_ext_by_norm = {}
if not src_self:
for _n2 in bnorms:
if not _n2["x_side"]:
continue
try:
_m = {}
for _rec in json.loads(_n2["x_side"]):
if _rec.get("tag") == "UnitPriceCalculationOfItem":
_a = _rec.get("attrs") or {}
_m[(_a.get("Name") or "").strip()] = _a.get("Total")
_ext_by_norm[_n2["id"]] = _m
except Exception:
pass
_tmpl_side = None
try:
_pt = sc.execute("SELECT x_ptag FROM s_bills WHERE id=?", (bid,)).fetchone()
_ptag = ((_pt["x_ptag"] if _pt else None) or "")
_t = sc.execute("""SELECT n.x_side FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
WHERE b.session_id=? AND COALESCE(n.x_adopt,0)=0 AND n.x_side IS NOT NULL
AND b.id<>? AND COALESCE(b.x_ptag,'')=?
ORDER BY n.id LIMIT 1""", (sid, bid, _ptag)).fetchone()
if _t and _t["x_side"]:
_tmpl_side = _t["x_side"]
except Exception:
_tmpl_side = None
def _adopt_side(nn):
"""本条采纳定额的 x_side:本项目来源=源行组原样复制;外部来源=同区模板行组
+ Total 按 Name 匹配外部(一致=外部值,不一致留空);无模板=None。"""
if src_self:
return nn["x_side"]
_m = _ext_by_norm.get(nn["id"])
if not _tmpl_side or _m is None:
return None
try:
_side = json.loads(_tmpl_side)
for _rec in _side:
if _rec.get("tag") == "UnitPriceCalculationOfItem":
_a = _rec.get("attrs") or {}
_nm = (_a.get("Name") or "").strip()
_a["Total"] = _m.get(_nm, "")
_rec["attrs"] = _a
return json.dumps(_side, ensure_ascii=False)
except Exception:
return None
def _norm_expr(nn):
# 决策 217(2026-10-26 主人定):采纳定额公式**四入口统一为分部分项同款 GCL×系数**——'''
assert old3 in s, "norm_expr anchor NOT FOUND"
s = s.replace(old3, new3)
# ---- ③ 两处采纳 INSERT 加 x_side ----
old4 = ''' cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr, x_adjust)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"]))'''
new4 = ''' cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], _adopt_side(nn)))'''
c = s.count(old4)
assert c == 2, "INSERT count=%d" % c
s = s.replace(old4, new4)
io.open(p, "w", encoding="utf-8").write(s)
print("api_server adopt side done")

View File

@@ -1,51 +0,0 @@
# -*- coding: utf-8 -*-
"""决策 273 导出端:采纳定额(x_side 有值)的单价行 Total 按 x_side 回填——
一致=外部值/不一致=空串;无 x_side 维持清零现状(106 口径不动)。"""
import io
p = r"D:\PricingReview\CostReview\app\core\export_cos.py"
s = io.open(p, encoding="utf-8").read()
# ---- ① _norm_xml 里 pre/post 清零后按 x_side 回填单价行 Total ----
old = ''' pre, post = _zero_results(pre), _zero_results(post)
pre = re.sub(r'<ExpressElement\\b[^>]*/>', '', pre)
post = re.sub(r'<ExpressElement\\b[^>]*/>', '', post)'''
new = ''' pre, post = _zero_results(pre), _zero_results(post)
pre = re.sub(r'<ExpressElement\\b[^>]*/>', '', pre)
post = re.sub(r'<ExpressElement\\b[^>]*/>', '', post)
# 决策 273(2026-11-04 主人定):采纳定额的单价行 Total 按 Name 匹配外部——
# x_side(采纳时构造:同区模板行组+Total 按 Name 匹配外部,一致=外部值/不一致留空)
# 有值时回填 Total 覆盖清零;无 x_side 维持清零现状(106 口径不动)。
_sm = {}
if n.get("x_side"):
try:
for _rec in json.loads(n["x_side"]):
if _rec.get("tag") == "UnitPriceCalculationOfItem":
_a = _rec.get("attrs") or {}
_sm[(_a.get("Name") or "").strip()] = _a.get("Total")
except Exception:
_sm = {}
if _sm:
pre = _adopt_totals(pre, _sm)
post = _adopt_totals(post, _sm)'''
assert old in s, "zero block NOT FOUND"
s = s.replace(old, new)
# ---- ② _adopt_totals 函数(挂在 _zero_results 后面) ----
old2 = '''def _zero_results(frag):'''
new2 = '''def _adopt_totals(frag, sm):
"""决策 273:单价行 Total 按 Name 匹配回填——一致=外部该行 Total;不一致=空串(留空)。
只动骨架已有的 UnitPriceCalculationOfItem 自闭合行(卡槽在才写)。"""
def _f(m):
a = dict(re.findall(r'(\\w+)="([^"]*)"', m.group(1)))
nm = (a.get("Name") or "").strip()
v = sm.get(nm)
return _attr_set(m.group(0), "Total", "" if v is None else v)
return re.sub(r'<UnitPriceCalculationOfItem\\b([^>]*?)/>', _f, frag)
def _zero_results(frag):'''
assert old2 in s, "_zero_results anchor NOT FOUND"
s = s.replace(old2, new2)
io.open(p, "w", encoding="utf-8").write(s)
print("export side done")