# -*- coding: utf-8 -*-
"""决策 174(2026-10-22 主人定):导出换码/改价/字段回写/隐藏删除 **同码全部命中**。
实测背景:广联达件同一单位工程里同码会出现多条汇总节点(按分部重复列码),旧首中语义
只改首条 → 导出件残留旧码旧价(华宇路 37270101@3 三条只换一条、金宝 Summary 残留
1100 条、Project.xml 无换码通道残留 487 条)。本文件用最小样件锁死全命中口径。"""
import os
import re
import sys
_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 export_cos as xcos # noqa: E402
S = "LabourMaterialsEquipmentsMachinesSummary"
def _two_nodes(code, price="6.99", qty1="64.1300", qty2="47.8060"):
"""同码两条自闭合汇总节点(华宇路 37270101@3 的真实形态缩影)。"""
return (''
f'<{S} Number="{code}" Name="镀铜角钢" Specification="L50×50×5" Unit="kg" '
f'Quantity="{qty1}" NoTaxPrice="{price}" TaxRate="0.0" TaxPrice="{price}"/>'
f'<{S} Number="{code}" Name="镀铜角钢" Specification="L50×50×5" Unit="kg" '
f'Quantity="{qty2}" NoTaxPrice="{price}" TaxRate="0.0" TaxPrice="{price}"/>'
'')
def test_recode_all_hits_same_code_multi_nodes():
"""换码通道 + 决策 184 A 清洗:同码两条节点归并后**每码只留一条**(保留最后一条
47.806,前一条被吸收删除——条目数=显示端,2026-10-23 主人定)。"""
out = xcos.transform_unit_summaries(_two_nodes("A3"), {}, None, recode_map={"A3": "A1"})
assert out.count('Number="A1"') == 1
assert 'Number="A3"' not in out
qs = re.findall(r'Quantity="([0-9.]+)"', out)
assert qs == ["47.8060"]
def test_price_updates_all_hits():
"""改价通道:同码两条节点全部吃到新价(旧首中语义只改首条)。"""
out = xcos.transform_unit_summaries(_two_nodes("A1", price="6.99"),
{"A1": (58.88, 0.0, 58.88)}, None)
assert out.count('NoTaxPrice="58.88"') == 2
assert 'NoTaxPrice="6.99"' not in out
def test_field_updates_all_hits():
"""字段回写通道:同码两条节点的名称/规格/单位全部更新。"""
out = xcos.transform_unit_summaries(_two_nodes("A1"), {}, None,
field_updates={"A1": ("热镀锌角钢接地极", "L50×50×5 L=2500", "根")})
assert out.count('Name="热镀锌角钢接地极"') == 2
assert "镀铜角钢" not in out
def test_recode_with_children_all_hits():
"""换码+子级重建:同码两条成对节点全部换码、子级各自整字段重建为保留行子级。"""
blk = ('<{S} Number="B3" Name="焊机台班" Unit="台班" Quantity="{{q}}" NoTaxPrice="6.00" TaxPrice="7.00">'
''
'{S}>').format(S=S)
txt = "" + blk.format(q="1.0000") + blk.format(q="2.0000") + ""
out = xcos.transform_unit_summaries(txt, {}, None,
recode_map={"B3": "C1"},
recode_children={"B3": [["000002", 9.0]]})
assert out.count('Number="C1"') == 1 and 'Number="B3"' not in out # 决策 184 A 清洗:每码一条
kids = re.findall(r']*Quantity="([^"]+)"', out)
assert kids == [("000002", "9.0000")] # 保留最全成对块,子级照常重建
assert out.count(f"{S}>") == 1 # 成对块结构完好
def test_project_hidden_deletes_all_hits():
"""Project.xml 隐藏删除:同码两条块全部删除(旧首中语义会留一条)。"""
blk = '<{S} Number="H1" Name="x" Quantity="{{q}}">{S}>'.format(S=S)
txt = "" + blk.format(q="1.0000") + blk.format(q="2.0000") + ""
out = xcos.transform_project(txt, [], ["H1"])
assert "Number=\"H1\"" not in out and "LabourMaterialsEquipmentsMachinesElement" not in out
def test_project_sync_all_hits():
"""Project.xml 同步:同码两条节点全部吃到现值。"""
out = xcos.transform_project(_two_nodes("K1"), [], [],
sync_rows=[("K1", "现值名", "现值规", "t", 10.0, 0.0, 10.0)])
assert out.count('Name="现值名"') == 2 and "镀铜角钢" not in out
def test_project_recode_channel_renames_and_carries_kept_values():
"""Project.xml 换码通道(决策 174 新增):旧码节点 Number 换保留码并带保留行同步值。"""
txt = _two_nodes("A3")
out = xcos.transform_project(txt, [], [],
sync_rows=[("A1", "热镀锌角钢接地极", "L50×50×5 L=2500", "根", 73.98, 0.0, 73.98)],
recode_map={"A3": "A1"})
assert out.count('Number="A1"') == 2 and 'Number="A3"' not in out
# 换码节点带保留行同步值(旧值 6.99 不许残留=新旧两价并存)
assert 'NoTaxPrice="73.98"' in out and 'NoTaxPrice="6.99"' not in out
assert "热镀锌角钢接地极" in out
def test_project_recode_skips_hidden_blocks():
"""换码不复活隐藏块:同码既被隐藏又在换码映射里 → 删除优先,不出现换码后的节点。"""
txt = '<{S} Number="A3" Name="x" Quantity="1.0000"/>'.format(S=S)
out = xcos.transform_project(txt, [], ["A3"], sync_rows=[("A1", "n", "", "", 1.0, 0.0, 1.0)],
recode_map={"A3": "A1"})
assert "Number=" not in out.replace('Number=""', "")
def test_bare_open_tag_rows_all_recode():
"""金宝件实测结构:无子级行是**裸开标签**(无 /> 无闭标签,下一行即下一节点)。
索引不得把裸行误判成「成对块」吞到远处的别人闭标签——否则假块与内层编辑相交,
_apply_edits 相交防御丢弃外层编辑=换码失效(Sum 残留 88 的根源);
_recode_norm_lme_rows 同理不得把裸行间的元素行误当块内子级跳过。
走真实管线:transform_unit_summaries(换码+子级重建)后接 _recode_norm_lme_rows(块外行)。"""
row = '<{S} Number="{{c}}" Name="白布" Unit="kg" Quantity="29.5515" NoTaxPrice="2.48">'.format(S=S)
txt = (''
+ row.format(c="A3")
+ ''
+ row.format(c="A3")
+ row.format(c="B9")
+ '<{S} Number="A3" Name="焊机台班" Quantity="2.0000">'.format(S=S)
+ ''
+ f'{S}>'
+ '')
out = xcos.transform_unit_summaries(txt, {}, None,
recode_map={"A3": "A1", "B9": "B1"},
recode_children={"A3": [["000002", 9.0]]})
out = xcos._recode_norm_lme_rows(out, {"A3": "A1", "B9": "B1"})
assert 'Number="A3"' not in out and 'Number="B9"' not in out
assert out.count('Number="A1"') == 2 # 决策 184 A 清洗:三处 A3 留最全成对块一条 + 块外元素行
assert 'Number="B1"' in out
assert 'Number="000002"' in out and 'Number="000001"' not in out # 最全成对块的子级照常重建
assert out.count(f"{S}>") == 1 # 只保留的真块有闭标签:裸行被清洗,不发明闭块结构
def test_recode_norm_lme_rows_all_element_rows():
"""决策 178:元素行编码**全部**跟映射换——块内子级、块外直挂行一视同仁(含量不动)。"""
txt = (''
'<{S} Number="A3" Name="x" Quantity="1.0">'.format(S=S)
+ ''
+ '<{S} Number="P1" Name="t" Quantity="2.0">'.format(S=S)
+ ''
+ f'{S}>'
+ '')
out = xcos._recode_norm_lme_rows(txt, {"A3": "A1"})
assert not re.search(r''
'<{S} Number="A3" Name="x" Quantity="1.0000"/>'.format(S=S)
+ '<{S} Number="A1" Name="y" Quantity="2.0000"/>'.format(S=S)
+ '')
out = xcos.transform_unit_summaries(txt, {}, None, recode_map={"A3": "A1", "A1": "A9"})
assert 'Number="A3"' not in out and 'Number="A1"' not in out
assert out.count('Number="A9"') == 1 # 链上两码全部落到链尾 + 决策 184 A 清洗:每码一条
def test_recode_chain_resolve_helper():
"""压平助手:链取尾;环(A↔B 历史脏映射)按访问集停,不静默改方向。"""
assert xcos._resolve_recode_chains({"A3": "A1", "A1": "A9"}) == {"A3": "A9", "A1": "A9"}
assert xcos._resolve_recode_chains({"B": "C", "C": "C"}) == {"B": "C"}
assert xcos._resolve_recode_chains({"X": "Y", "Y": "X"}) == {"X": "Y", "Y": "X"}
assert xcos._resolve_recode_chains({"Z": "Z"}) == {}
def test_project_sync_writes_unconditionally():
"""决策 176:Project.xml 同步=**全量写回**,提供即写、不比较新旧(取代 75 的
「只更新不一致字段」最小替代)。语义相等但文本不同也要归一成提供值。"""
txt = (''
f'<{S} Number="K1" Name="白布" Unit="kg"'
' Quantity="29.5515" TaxRate="0" NoTaxPrice="2.48" TaxPrice="2.48"/>'
'')
out = xcos.transform_project(txt, [], [],
sync_rows=[("K1", "白布", "", "kg", 2.48, 0.0, 2.48)])
assert 'TaxRate="0.0"' in out # 相等也写:文本归一为提供值格式
assert 'NoTaxPrice="2.48"' in out and 'TaxPrice="2.48"' in out
def test_ident_foreign_node_split():
"""决策 178:同码异物拆分——保留码被组外名规单占用时,导出按节点自带名规单改印新码;
异物节点不吃合并价/换码,组内节点照常。"""
txt = (''
f'<{S} Number="K1" Name="白布" Specification="" Unit="kg" Quantity="1.0000" NoTaxPrice="6.00"/>'
f'<{S} Number="K1" Name="铁钉" Specification="50mm" Unit="kg" Quantity="2.0000" NoTaxPrice="9.00"/>'
'')
out = xcos.transform_unit_summaries(txt, {"K1": (58.88, 0.0, 58.88)}, None,
recode_ident={"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}})
# 组内节点:保留码+合并价;异物节点:改印新码、价格原样
assert out.count('Number="K1@1"') == 1 and 'Name="铁钉"' in out
assert 'NoTaxPrice="9.00"' in out # 异物不吃合并价
assert 'NoTaxPrice="58.88"' in out # 组内照常吃合并价
def test_children_registered_empty_strips_block_children():
"""决策 178:重建数据登记为空表=[] → 成对块子级清空(全部替换的真意:保留码无子级)。"""
txt = ('<{S} Number="B3" Name="焊机台班" Quantity="2.0000">'
''
f'{S}>').format(S=S)
out = xcos.transform_unit_summaries(txt, {}, None,
recode_map={"B3": "C1"}, recode_children={"B3": []})
assert 'Number="C1"' in out and 'Number="B3"' not in out
assert "LabourMaterialsEquipmentsMachinesElement" not in out # 子级清空
assert out.count(f"{S}>") == 1
def test_project_children_rebuild_and_ident_split():
"""决策 178:Project.xml 成对块子级整组替换成保留码子级;同码异物节点改印新码。"""
txt = (''
'<{S} Number="B3" Name="焊机台班" Quantity="2.0000">'
''
'{S}>'.format(S=S)
+ '<{S} Number="K1" Name="铁钉" Specification="50mm" Unit="kg" Quantity="1.0000"/>'.format(S=S)
+ '')
out = xcos.transform_project(txt, [], [],
recode_map={"B3": "C1"}, recode_children={"B3": [["000002", 9.0]]},
recode_ident={"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}})
assert 'Number="C1"' in out and 'Number="B3"' not in out
assert 'Number="000002"' in out and 'Number="000001"' not in out # 子级整组替换
assert 'Number="K1@1"' in out # 同码异物拆分
def test_split_occupied_code_assigns_fresh_codes():
"""决策 178:保留码被组外名规单占用 → 占用行自动换未占用新码(两级表+登记)。"""
import sqlite3
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
con.execute("CREATE TABLE s_lme_proj(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)")
con.execute("CREATE TABLE s_lme_uw(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)")
con.execute("CREATE TABLE s_settings(scope TEXT, k TEXT, v TEXT, PRIMARY KEY(scope, k))")
for c, nm, sp, un in (("K1", "白布", "", "kg"), ("K1", "铁钉", "50mm", "kg")):
con.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit) VALUES(1,?,?,?,?)", (c, nm, sp, un))
con.execute("INSERT INTO s_lme_uw(session_id, code, name, spec, unit) VALUES(1,'K1','铁钉','50mm','kg')")
import importlib
srv = importlib.import_module("api_server")
n = srv._split_occupied_code(con, 1, "K1", ("白布", "", "kg"))
assert n == 1 # 一个异物名规单(proj+uw 同批改)
codes = sorted(r[0] for r in con.execute("SELECT code FROM s_lme_proj"))
assert codes == ["K1", "K1@1"] # 组内保码,异物换新码
assert con.execute("SELECT COUNT(*) FROM s_lme_uw WHERE code='K1@1'").fetchone()[0] == 1
ri = json_loads(con)
assert ri == {"K1": {"铁钉\x1f50mm\x1fkg": "K1@1"}}
def json_loads(con):
import json as _j
return _j.loads(con.execute("SELECT v FROM s_settings WHERE k='recode_ident'").fetchone()[0])