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

464 lines
28 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 -*-
"""项目级工料机汇总 行级改价防回归(2026-10-16 主人口径)。
钉死四件事:
①三价联动恒满足 除税编制价 × (1 + 税率/100) = 含税编制价(金额四舍五入 2 位,税率空按 0):
改除税→按税率算含税;改税率→按除税算含税;改含税→反解除税。
②落库位置 = s_lme_proj 那一行(code 不动),响应回带服务端复核后的三值。
③按编码同步**存在该编码**的 s_lme_uw(全单位覆盖,决策 73/75 口径),别的编码不动;
编码登记进 s_settings 的 merged_codes(导出侧 price_updates 唯一来源)。
④行形状:_raw_proj(_raw_uw) 工料机卡 9 列、税率在下标 7(ntp 之后、taxp 之前),
ids 与行一一并行;隐藏行(x_merged_hide=1)不出现在 ids 里且拒改。
另带一例 api_lme_merge 回归:_merged_codes_add 抽取后合并照旧登记编码。
"""
import sqlite3
import json
import sys, os
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, os.path.join(os.path.dirname(_HERE), "server"))
import api_server as srv # noqa: E402
SID = 1
def _mk_sess():
"""内存会话库:项目级汇总 3 行(正常材料 / 台班带子级 / 隐藏行)+ 单位级 3 行(C1 两单位 + C2)。"""
sc = sqlite3.connect(":memory:")
sc.row_factory = sqlite3.Row
c = sc.cursor()
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
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)""")
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
# 2026-10-22 合并贯通:api_lme_merge 会 UPDATE s_norm_res(经 s_norms/s_bills 圈会话),
# 夹具补空表防 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, 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 已隐藏
c.executemany("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp, x_merged_hide) VALUES(?,1,?,?, '', 'kg',2, 100, ?, ?, ?, ?)""",
[(1, "C1", "钢筋", 99.99, 3.5, 103.49, 0),
(2, "P1", "挖掘机台班", 900.0, 3.5, 931.5, 0),
(3, "C9", "已隐藏", 1.0, 0.0, 1.0, 1)])
c.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq) VALUES(1,'P1',?,?,?)",
[("00010003", 2.0, 1), ("99450680", 63.0, 2)])
# 单位级:C1 在两个单位工程各有行;C2 一行(不该被 C1 的改价波及)
c.executemany("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(?,1,?,'C1','钢筋','kg',2, 10, 99.99, 3.5, 103.49)""",
[(11, 101), (12, 102)])
c.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(13,1,103,'C2','水泥','kg',2, 10, 200.0, 3.5, 207.0)""")
sc.commit()
return sc
def _merged_codes(sc):
r = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k=?",
("session:1", "merged_codes")).fetchone()
return set(json.loads(r[0])) if r else set()
# ---------- ① 三价联动 ----------
def test_linkage_edit_ntp_uses_current_rate():
"""改除税 → 按当前税率算含税:99.99 × (1+3.5/100) = 103.49(主人给的例)。"""
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
assert r["ok"] is True
assert round(r["taxp"], 2) == 103.49 and r["taxrate"] == 3.5
row = sc.execute("SELECT ntp, taxrate, taxp, code FROM s_lme_proj WHERE id=1").fetchone()
assert (row["ntp"], row["taxrate"], row["taxp"]) == (99.99, 3.5, 103.49)
assert row["code"] == "C1" # code 永不被改价动到
def test_linkage_edit_taxrate_recalcs_taxp():
"""改税率 → 按当前除税算含税:100 × (1+13/100) = 113.00。"""
sc = _mk_sess()
sc.execute("UPDATE s_lme_proj SET ntp=100 WHERE id=1")
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxrate": 13})
assert r["ok"] is True and r["taxp"] == 113.0
row = sc.execute("SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=1").fetchone()
assert (row["ntp"], row["taxrate"], row["taxp"]) == (100.0, 13.0, 113.0)
def test_linkage_edit_taxp_backs_out_ntp():
"""改含税 → 反解除税:103.49 ÷ (1+3.5/100) → 99.99。"""
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxp": 103.49})
assert r["ok"] is True and r["ntp"] == 99.99
row = sc.execute("SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=1").fetchone()
assert (round(row["ntp"], 2), row["taxp"]) == (99.99, 103.49)
def test_linkage_empty_rate_treated_as_zero():
"""税率空按 0:清空税率后 100×(1+0)=100;老行税率 NULL 时改除税 → 含税=除税。"""
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 100, "taxrate": None})
assert r["ok"] is True and r["taxp"] == 100.0 and r["taxrate"] is None
sc.execute("UPDATE s_lme_proj SET ntp=NULL, taxrate=NULL, taxp=NULL WHERE id=1")
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "taxrate": ""}) # 税率清空=0
assert r2["ok"] is True and r2["taxp"] == 0.0
def test_linkage_rounding_half_up():
"""金额四舍五入 2 位(十进制半升,非银行家舍入)。"""
assert srv._r2(103.48965) == 103.49
assert srv._r2(2.675) == 2.68 # round() 会给 2.67
assert srv._r2(1.005) == 1.01
# ---------- ② 落库位置 / ③ 单位级同步 / merged_codes ----------
def test_sync_updates_only_matching_code_rows():
"""按编码同步存在该编码的单位级汇总(全单位覆盖);别的编码不动。"""
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
assert r["ok"] is True and r["synced"] == 2 # C1 的两个单位工程行
vals = {x["id"]: (x["ntp"], x["taxp"]) for x in
sc.execute("SELECT id, ntp, taxp FROM s_lme_uw WHERE code='C1'")}
assert vals == {11: (99.99, 103.49), 12: (99.99, 103.49)}
c2 = sc.execute("SELECT ntp, taxp FROM s_lme_uw WHERE code='C2'").fetchone()
assert (c2["ntp"], c2["taxp"]) == (200.0, 207.0) # 撞不上编码的不跟
def test_edit_registers_code_into_merged_codes():
"""改价必须登记 merged_codes —— 导出侧 price_updates 的唯一来源(api_server 2994-2999)。"""
sc = _mk_sess()
assert _merged_codes(sc) == set()
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 99.99})
assert _merged_codes(sc) == {"C1"}
# 决策 188 收严(主人定「有子数据的单价不可编辑,只能通过子数据修改」):P1 带子级→三价全拒
r = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "taxrate": 9})
assert r["ok"] is False and "不可编辑" in r["msg"]
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "ntp": 88.0})
assert r2["ok"] is False and "不可编辑" in r2["msg"]
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": 90.0}) # C1 无子级,可改→登记
assert _merged_codes(sc) == {"C1"}
def test_sub_composition_rows_are_editable():
"""带子级组成的台班可改(2026-10-16 主人定,与合并弹框的整行过滤不同);_raw_proj 带出 sub 集。"""
sc = _mk_sess()
# 决策 188 收严:带子级行三价**全部拒改**(只能通过子数据修改);sub 集照常带出
r = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "taxrate": 9})
assert r["ok"] is False and "不可编辑" in r["msg"]
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 2, "ntp": 88.0})
assert r2["ok"] is False and "不可编辑" in r2["msg"]
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
assert d["sub"] == ["P1"]
# ---------- 拒改 / 容错 ----------
def test_rejects_hidden_and_missing_rows():
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 3, "ntp": 5}) # 隐藏行
assert r["ok"] is False and "隐藏" in r["msg"]
assert sc.execute("SELECT ntp FROM s_lme_proj WHERE id=3").fetchone()[0] == 1.0
r2 = srv.api_lme_price(sc, {"session_id": SID, "id": 999, "ntp": 5}) # 不存在
assert r2["ok"] is False and "行不存在" in r2["msg"]
def test_rejects_garbage_number():
"""垃圾数字报错拒写(防手滑把价格清成 NULL),而不是当清空处理。"""
sc = _mk_sess()
with pytest.raises(ValueError):
srv.api_lme_price(sc, {"session_id": SID, "id": 1, "ntp": "abc"})
row = sc.execute("SELECT ntp, taxp FROM s_lme_proj WHERE id=1").fetchone()
assert (row["ntp"], row["taxp"]) == (99.99, 103.49) # 库纹丝没动
def test_no_price_fields_is_noop():
sc = _mk_sess()
r = srv.api_lme_price(sc, {"session_id": SID, "id": 1})
assert r["ok"] is False and "没有要改的价字段" in r["msg"]
# ---------- 行形状(前后端同改的铁律处)----------
def test_raw_proj_rows_are_eleven_wide_id_first():
"""决策 147(2026-10-21):项目级卡与「项目工料机」同形 —— 行 11 列 id 在首位、备注位 10;
税率在下标 7、含税在下标 8;不再 rows/ids 分离;隐藏行被过滤。"""
sc = _mk_sess()
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
assert len(d["rows"]) == 2 # 隐藏行被过滤
assert all(len(r) == 11 for r in d["rows"])
r0 = d["rows"][0]
assert r0[0] == 1 and r0[1] == "C1" and r0[6] == 99.99 and r0[7] == 3.5 and r0[8] == 103.49
assert "ids" not in d
assert d["sub"] == ["P1"]
def test_raw_uw_rows_are_nine_wide_with_taxrate_at_7():
"""单位级卡同款 9 列(保持只读,不给 ids)。"""
sc = _mk_sess()
sc.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
Number TEXT, Name TEXT, Specialty TEXT, Total REAL)""")
sc.execute("INSERT INTO s_unit_works(id, session_id, Number, Name) VALUES(101,1,'1','土建')")
d = srv._raw_uw(sc, srv.TBL["session"], 101, "lme")
assert d["src"] == "summary"
assert all(len(r) == 9 for r in d["rows"])
assert d["rows"][0][7] == 3.5 and d["rows"][0][8] == 103.49
assert "ids" not in d
# ---------- 老库回退支的行形状(评审发现:税率曾落在下标 8 —— 2026-10-16 修)----------
def _mk_lmes(sc, with_taxrate=True):
"""给回退支建 s_lmes:with_taxrate=False 模拟老库没有 TaxRate 列。"""
tx = ", TaxRate REAL" if with_taxrate else ""
sc.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
Number TEXT, Name TEXT, Specification TEXT, Unit TEXT, Kind INT,
Quantity REAL, NoTaxPrice REAL, TaxPrice REAL%(tx)s)""" % {"tx": tx})
def test_raw_proj_fallback_eleven_wide_taxrate_at_7():
"""老会话(s_lme_proj 无数据)回退 lmes:决策 147 后 11 列 id 首位、税率在下标 7、含税在下标 8;无 ids=只读。"""
sc = _mk_sess()
sc.execute("DELETE FROM s_lme_proj")
_mk_lmes(sc, with_taxrate=True)
sc.executemany("""INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Kind,
Quantity, NoTaxPrice, TaxRate, TaxPrice) VALUES(1,?,?,?,'kg',2, 10, ?, ?, ?)""",
[("C1", "钢筋", "", 99.99, 3.5, 103.49),
("C2", "水泥", "", 200.0, 3.5, 207.0)])
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
assert all(len(r) == 11 for r in d["rows"])
assert d["rows"][0][1] == "C1" and d["rows"][0][6] == 99.99
assert d["rows"][0][7] == 3.5 and d["rows"][0][8] == 103.49
assert "ids" not in d
def test_raw_proj_fallback_without_taxrate_column():
"""老库 lmes 没有 TaxRate 列:下标 7 恒 None(显示 —),含税仍在下标 8 —— 不得把含税顶进税率列。"""
sc = _mk_sess()
sc.execute("DELETE FROM s_lme_proj")
_mk_lmes(sc, with_taxrate=False)
sc.execute("""INSERT INTO s_lmes(session_id, Number, Name, Unit, Kind,
Quantity, NoTaxPrice, TaxPrice) VALUES(1,'C1','钢筋','kg',2, 10, 99.99, 103.49)""")
d = srv._raw_proj(sc, srv.TBL["session"], SID, "lme")
r0 = d["rows"][0]
assert len(r0) == 11 and r0[6] == 99.99 and r0[7] is None and r0[8] == 103.49
def test_raw_uw_agg_fallback_nine_wide_taxrate_at_7():
"""单位级归集回退(s_lme_uw 无数据):9 列、税率在下标 7、含税在下标 8(评审同款错位修)。"""
sc = _mk_sess()
sc.execute("DELETE FROM s_lme_uw")
sc.execute("""CREATE TABLE s_unit_works(id INTEGER PRIMARY KEY, session_id INT,
Number TEXT, Name TEXT, Specialty TEXT, Total REAL)""")
sc.execute("INSERT INTO s_unit_works(id, session_id, Number, Name) VALUES(101,1,'1','土建')")
_mk_lmes(sc, with_taxrate=True)
sc.execute("""INSERT INTO s_lmes(session_id, Number, Name, Unit, Kind,
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, 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)""")
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(1, 1, 'C1', 4.0)")
d = srv._raw_uw(sc, srv.TBL["session"], 101, "lme")
assert d["src"] == "agg"
assert all(len(r) == 9 for r in d["rows"])
r0 = d["rows"][0]
assert r0[0] == "C1" and r0[5] == 4.0 and r0[6] == 99.99
assert r0[7] == 3.5 and r0[8] == 103.49
def test_merge_still_registers_codes_after_refactor():
"""回归:_merged_codes_add 抽取共用后,合并执行照旧登记编码 + 同步单位级。"""
sc = _mk_sess()
# 决策 244 夹具接线:C1 接定额消耗引用(只留被引用的工料机)
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(9, 1, 101)")
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(9, 9)")
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(9, 9, 'C1', 1.0)")
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [
{"sel": {"id": 1, "ntp": 88.8, "taxrate": 3.5}, "hide": []}]})
assert r["ok"] is True and r["kept"] == 1
assert _merged_codes(sc) == {"C1"}
uw = sc.execute("SELECT ntp FROM s_lme_uw WHERE id=11").fetchone()
assert uw["ntp"] == 88.8
# ---------- 规格 第9/11/12条:带子数据进弹框 + 单位级母行只替换编码(2026-10-16)----------
def test_merge_group_includes_child_rows_with_flag():
"""带子级组成的行进合并弹框(决策78 整行过滤废止),行带 sub 标记、编码最短默认勾选。
决策 171:组内另含单位级按码聚合行(lvl=uw,带 units/uw_ids)。"""
sc = _mk_sess()
sc.execute("UPDATE s_lme_proj SET name='钢筋', unit='kg' WHERE id=2") # P1(带子级) 与 C1 同组
# 决策 186 v3 并集视野:补单位级行(C1/P1 同名规单)成组;项目级不进组
sc.executemany("INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind, "
"qty, ntp, taxrate, taxp) VALUES(?,1,?,?,'钢筋','kg',2,?,?,3.5,?)",
[(21, 101, "C1", 10, 99.0, 103.0), (22, 101, "P1", 5, 99.0, 103.0),
(23, 102, "C1", 12, 99.0, 103.0)])
d = srv._lme_merge_groups(sc, SID)
g = [x for x in d["groups"] if x["name"] == "钢筋"][0]
# 2026-11-04 规则:组=名规单;成员=除数量外任一字段不同即独立成员。
# 夹具预置 C1@99.99 两行(同成员,数量累计)+ 本用例 C1@99.0 两行(另一成员)→ C1 两个成员
codes = [r["code"] for r in g["rows"]]
assert codes.count("C1") == 2 and codes.count("P1") == 1
c1 = [r for r in g["rows"] if r["code"] == "C1" and r["ntp"] == 99.99][0]
assert c1["units"] == 2 and c1["qty"] is not None # 同字段组合两个单位行 → 一个成员
assert {r["code"]: r["sub"] for r in g["rows"] if r["code"] == "P1"} == {"P1": True}
assert g["rows"][0]["def"] is True
def test_merge_child_group_repoints_unit_mothers_and_replaces_children():
"""规格 第11/12条(决策 171 升级):合并后单位汇总里被合并码的母行**物理换成保留码**
(无撞码跳过——主人定「合并后每个单位工程里只显示保留码」,同码双行镜像源文件多行现实);
变体行只换码不换价(本单位价格原样),保留码价格同步走决策 75 通道;
子级组成**物理整字段替换**为保留行的子级(2026-10-16 主人纠偏「要真正替换全部字段」);
改码映射+子级替换数据落 s_settings 供导出重建。
(弹框真实流程对组内每条单位级聚合行都发 keep/hide——本测试按同款入参模拟。)"""
sc = _mk_sess()
# 决策 244 夹具接线:C1 接定额消耗引用(合并后只留被引用的)
sc.execute("INSERT INTO s_bills(id, session_id, uw_id) VALUES(9, 1, 101)")
sc.execute("INSERT INTO s_norms(id, bill_id) VALUES(9, 9)")
sc.execute("INSERT INTO s_norm_res(id, norm_id, res_code, qty) VALUES(9, 9, 'C1', 1.0)")
# 决策 244 口径自洽(主人定「原版数据流:定额消耗量展开写入单位级汇总,子级码必有汇总行」):
# C1 的子级 C101/C102 在两级汇总本来就有行——注入兜底不再被触发
sc.execute("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp) VALUES(4, 1, 'C101', '盘圆', '', 'kg', 2, 5, 4.2, 0, 4.5)""")
sc.execute("""INSERT INTO s_lme_proj(id, session_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp) VALUES(5, 1, 'C102', '螺纹钢', '', 'kg', 2, 6, 4.6, 0, 5.0)""")
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(16, 1, 101, 'C101', '盘圆', 'kg', 2, 5, 4.2, 0, 4.5)""")
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(17, 1, 102, 'C102', '螺纹钢', 'kg', 2, 6, 4.6, 0, 5.0)""")
sc.execute("UPDATE s_lme_proj SET name='钢筋', unit='kg' WHERE id=2") # P1 并入 C1 组
# 保留行 C1 也有子级组成(2 条)——替换后 P1 的子级应变成这两条的全字段拷贝
sc.executemany("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(1,'C1',?,?,?,?)",
[("C101", 1.5, 1, "盘圆"), ("C102", 9.0, 2, "螺纹钢")])
# uw104:只有 P1 行 → 应被改码为 C1,价格保持本单位原值
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(14,1,104,'P1','钢筋','kg',2, 7, 222.0, 3.5, 229.77)""")
# uw102:C1、P1 都在 → 决策 171 无跳过:P1 行也换成 C1(同码双行)
sc.execute("""INSERT INTO s_lme_uw(id, session_id, uw_id, code, name, unit, kind,
qty, ntp, taxrate, taxp) VALUES(15,1,102,'P1','钢筋','kg',2, 8, 210.0, 3.5, 217.35)""")
r = srv.api_lme_merge(sc, {"session_id": SID, "groups": [
{"sel": {"id": 1, "ntp": 99.99, "taxrate": 3.5, "taxp": 103.49},
"hide": [{"id": 2}, {"uw": 1, "code": "P1", "uw_ids": [104, 102]},
{"uw": 1, "code": "C1", "uw_ids": [101, 102]}]}]})
assert r["ok"] is True and r["hidden"] == 2
# 变体行换码后三价统一为保留行三价(决策 171 补:主人定「三价要同步更新」)
row14 = sc.execute("SELECT code, ntp, taxp FROM s_lme_uw WHERE id=14").fetchone()
assert row14["code"] == "C1" and (row14["ntp"], row14["taxp"]) == (99.99, 103.49)
# 决策 171 无跳过(uw102):P1 行也换成 C1
assert sc.execute("SELECT code FROM s_lme_uw WHERE id=15").fetchone()[0] == "C1"
# 保留码价格同步照旧:全部 C1 行(含换码而来的变体行)按保留行三价统一
vals = {x["id"]: round(x["ntp"], 2) for x in sc.execute("SELECT id, ntp FROM s_lme_uw WHERE code='C1'")}
assert vals[11] == 99.99 and vals[12] == 99.99 and vals[14] == 99.99 and vals[15] == 99.99
# 子级物理整字段替换:P1 名下现在是保留行 C1 的子级(全字段同源),不是空
kids = sc.execute("SELECT res_code, qty, seq, name FROM s_lme_res WHERE session_id=1 AND p_code='P1' ORDER BY seq").fetchall()
assert [(k["res_code"], k["qty"], k["seq"], k["name"]) for k in kids] == \
[("C101", 1.5, 1, "盘圆"), ("C102", 9.0, 2, "螺纹钢")]
# 项目级 P1 换码后零引用 → 决策 244 剪枝删除;改码映射+子级替换数据落 s_settings(导出侧重建节点用)
assert sc.execute("SELECT COUNT(*) FROM s_lme_proj WHERE session_id=1 AND id=2").fetchone()[0] == 0
assert _merged_codes(sc) == {"C1"}
rm = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_map'").fetchone()[0])
assert rm == {"P1": "C1"}
rc = json.loads(sc.execute("SELECT v FROM s_settings WHERE scope='session:1' AND k='recode_children:P1'").fetchone()[0])
assert rc == [["C101", 1.5], ["C102", 9.0]]
def test_export_recode_renames_mother_and_rebuilds_children():
"""导出侧第12条真身:单位件里被合并码节点 Number 换成保留码(母只换码),
子级组成元素全字段重建为保留行子级(编码/含量按替换数据来)。"""
import re
import export_cos as xcos
txt = ('<r><LabourMaterialsEquipmentsMachinesSummary Number="B1" Name="焊机台班" Unit="台班" '
'Quantity="3.0000" NoTaxPrice="6.00" TaxPrice="7.00">'
'<LabourMaterialsEquipmentsMachinesElement Number="00010003" Express="1.0000" Quantity="2.0000" Remark=""/>'
'<LabourMaterialsEquipmentsMachinesElement Number="99450700" Express="1.0000" Quantity="63.0000" Remark=""/>'
'</LabourMaterialsEquipmentsMachinesSummary></r>')
out = xcos.transform_unit_summaries(txt, {}, None,
recode_map={"B1": "C1"},
recode_children={"B1": [["00010003", 1.5], ["99450700", 63.0]]})
assert 'Number="B1"' not in out and 'Number="C1"' in out # 母只换码
pairs = re.findall(r'Number="([^"]+)" Express="([^"]+)" Quantity="([^"]+)"', out)
assert pairs == [("00010003", "1.5000", "1.5000"), ("99450700", "63.0000", "63.0000")] # 子级全字段重建(决策183:Express/Quantity 同源同写=库值)
assert out.count("</LabourMaterialsEquipmentsMachinesSummary>") == 1 # 成对结构完好
def test_export_recode_childless_renames_only():
"""无子级替换数据(childless 合并):只换码,节点结构原样。"""
import export_cos as xcos
txt = ('<r><LabourMaterialsEquipmentsMachinesSummary Number="A12" Name="水泥" Unit="kg" '
'Quantity="5.0000" NoTaxPrice="2.00" TaxPrice="3.00"/></r>')
out = xcos.transform_unit_summaries(txt, {}, None, recode_map={"A12": "A1"})
assert 'Number="A1"' in out and 'Number="A12"' not in out
assert out.count("LabourMaterialsEquipmentsMachinesSummary") == 1 # 自闭合节点原样,只换了码
# ---------- HTTP 全链路(隔离副本服务,与 test_api_p0 同款夹具)----------
import sqlite3 as _sq # noqa: E402
from api_harness import PERIOD_202607, fixture_file, get, post, server # noqa: E402, F401
def _q(db, sql, args=()):
con = _sq.connect("file:%s?mode=ro" % db, uri=True)
try:
return con.execute(sql, args).fetchall()
finally:
con.close()
def test_http_lme_price_end_to_end(server):
"""真服务链路:打开工程 → raw/proj 九列带 ids → POST lme/price 三价联动
→ 项目级行落库 + 单位级按编码同步 + merged_codes 登记(导出侧能看到)。"""
p = fixture_file(server, "lmeprice.cos4", "改价联动工程",
[("030507008001", "高清网络摄像机", "", "台", 10, 1500)],
[("000001", "网络摄像机", "400万", "台", "1200", "1356")])
sid = post(server, "/api/audit",
{"name": "改价联动工程", "province": "广东省", "city": "珠海市",
"district": "香洲区", "period_from": PERIOD_202607,
"period_to": PERIOD_202607, "file_kind": 1, "path": p})["session_id"]
d = get(server, "/api/session/raw/proj", session_id=sid, tab="lme")
# 决策 147:11 列 id 首位,不再 rows/ids 分离
assert d["ok"] is True and d["rows"] and all(len(r) == 11 for r in d["rows"])
rid = d["rows"][0][0]
code = d["rows"][0][1]
# 改除税 99.99 + 税率 3.5 → 含税 103.49(主人给的例,服务端复核)
r = post(server, "/api/session/lme/price",
{"session_id": sid, "id": rid, "ntp": 99.99, "taxrate": 3.5})
assert r["ok"] is True and r["ntp"] == 99.99 and r["taxrate"] == 3.5 and r["taxp"] == 103.49
# 项目级行已落库
row = _q(server["sessdb"], "SELECT ntp, taxrate, taxp FROM s_lme_proj WHERE id=?", (rid,))[0]
assert (row[0], row[1], row[2]) == (99.99, 3.5, 103.49)
# 单位级按编码同步(该编码在 UW1 汇总里有一行)
assert r["synced"] >= 1
uw = _q(server["sessdb"], "SELECT ntp, taxrate, taxp FROM s_lme_uw WHERE session_id=? AND code=?",
(sid, code))[0]
assert (uw[0], uw[1], uw[2]) == (99.99, 3.5, 103.49)
# merged_codes 已登记(导出侧 price_updates 的唯一来源)
mc = _q(server["sessdb"], "SELECT v FROM s_settings WHERE scope=? AND k=?",
("session:%d" % sid, "merged_codes"))[0][0]
assert code in set(json.loads(mc))
# 只改含税 → 反解除税
r2 = post(server, "/api/session/lme/price", {"session_id": sid, "id": rid, "taxp": 113.0})
assert r2["ok"] is True and r2["taxrate"] == 3.5
assert abs(r2["ntp"] - 109.18) < 0.011 # 113/1.035 = 109.179…
# 界面再读:税率在下标 7、含税在下标 8
d2 = get(server, "/api/session/raw/proj", session_id=sid, tab="lme")
row2 = d2["rows"][0]
assert row2[7] == 3.5 and row2[8] == 113.0