feat(lme): 决策183 六价全采按骨架属性对应回填,并支持合并状态按源文件哈希重放

This commit is contained in:
lianjianwei2024
2026-10-23 16:21:22 +08:00
parent 378855cd3e
commit 30de80cf32
20 changed files with 1098 additions and 213 deletions

View File

@@ -812,23 +812,36 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
# ---------------------------------------------------------------- 单位工程 xml 的汇总节点(决策 74,主人口径 5.1/5.2/5.3)
def _full_summary_template(txt):
"""文件里第一条属性齐全的工料机汇总开标签(作克隆模板,32 属性形态)。
def _full_summary_template(txt, kind=None):
"""文件里属性齐全的工料机汇总开标签(作克隆模板,32 属性形态)。
与清单/定额同理:属性残缺的汇总行有整包被广联达拒绝的风险——
采纳新增品类行必须按源文件同款字段全集落盘。"""
采纳新增品类行必须按源文件同款字段全集落盘。
决策 183(主人定):骨架三型(无子数据/台班/配合比)——kind 给定时**同型优先**
(Kind=7 台班、Kind=6 配合比、其余普通),找不到同型退任意候选(原行为)。"""
cands = []
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
ot = txt[m.start():e]
if ' NoTaxPrice="' in ot and ' Provider="' in ot:
return ot
return None
if kind is None:
return ot
cands.append((ot, (re.search(r'\bKind="([^"]*)"', ot) or [None, ""])[1] or ""))
if kind is None:
return cands[-1][0] if cands else None
k = str(kind)
same = [t for t, tk in cands if tk == k]
return (same or [t for t, tk in cands])[-1] if cands else None
def _summary_node(fields, template=None):
"""一条工料机汇总节点。fields=(code,name,spec,unit,qty,taxrate,ntp,taxp,kind)。
优先克隆源文件汇总行的完整属性集再覆盖会话值;新行无组成子节点 → 自闭合。"""
优先克隆源文件汇总行的完整属性集再覆盖会话值;新行无组成子节点 → 自闭合。
2026-10-23 主人定(骨架许可全按新数据、残留清空):六价+四 Total 按本行数据
(不吃模板残留),分类属性(Class/Provider/Concrete/MainMaterial/ProvisionalMaterial)
随模板保留,文字残留(PriceSource/Delivery/Location/ProducingArea/Supplier/Character/
Remark)一律清空。"""
c, nm, sp, un, q, rt, np_, tp, kd = fields
if template:
tag = _clone_open_tag(template)
@@ -836,6 +849,10 @@ def _summary_node(fields, template=None):
("Quantity", q), ("TaxRate", rt), ("NoTaxPrice", np_), ("TaxPrice", tp),
("Kind", kd)):
tag = _attr_set(tag, k, "" if v is None else v)
tag = _lme_apply_price(tag, {"NoTaxPrice": np_, "TaxPrice": tp}) # 决策 183:属性匹配回填
for k in ("PriceSource", "Delivery", "Location", "ProducingArea", "Supplier",
"Character", "Remark"):
tag = _attr_set(tag, k, "")
return tag[:-1] + "/>"
return ('<LabourMaterialsEquipmentsMachinesSummary Number="%s" Name="%s" Specification="%s" Unit="%s"'
' Quantity="%s" TaxRate="%s" NoTaxPrice="%s" TaxPrice="%s" Kind="%s"/>' % (
@@ -847,8 +864,43 @@ def _summary_node(fields, template=None):
_PRICE_ATTRS = ("NoTaxPrice", "TaxRate", "TaxPrice")
def _lme_apply_price(newtag, px):
"""改价/换码/采纳行的回填口径(决策 183,2026-10-23 主人定:整套按骨架,属性匹配):
px = {属性名: 采纳值}——骨架有该属性且新值非 None → 按属性一一对应直填(TaxOrgPrice 填
新数据自己的 TaxOrgPrice,不与 TaxPrice 同值化);新值 None/骨架无该属性 → 不动(不发明、
不覆盖)。**自己算的字段**只有四个 Total,按源文件原生配对:OrgTotal=数量×OrgPrice、
Total=数量×PriceExpress(除税/含税两侧同构);数量取骨架行自己的 Quantity。
px 兼容旧三元组 (ntp, taxrate, taxp)——映射为对应三属性,其余属性不动。"""
if isinstance(px, tuple):
px = {"NoTaxPrice": px[0], "TaxRate": px[1], "TaxPrice": px[2]}
try:
q = float(_attr(newtag, "Quantity"))
except (TypeError, ValueError):
q = None
def _set(attr, val):
nonlocal newtag
if val is not None and re.search(r'\b' + attr + r'="', newtag):
newtag = _attr_set(newtag, attr, val)
for attr in ("NoTaxPrice", "NoTaxPriceExpress", "NoTaxOrgPrice", "TaxRate",
"TaxPrice", "TaxPriceExpress", "TaxOrgPrice"):
_set(attr, px.get(attr))
for tot, pattr in (("NoTaxOrgTotal", "NoTaxOrgPrice"), ("NoTaxTotal", "NoTaxPriceExpress"),
("TaxOrgTotal", "TaxOrgPrice"), ("TaxTotal", "TaxPriceExpress")):
if not re.search(r'\b' + tot + r'="', newtag):
continue # 骨架没有的属性不发明
try:
pv = px.get(pattr)
tv = "" if (q is None or pv is None) else "%.2f" % (q * float(pv))
except (TypeError, ValueError):
tv = ""
_set(tot, tv)
return newtag
def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, recode_children=None,
field_updates=None):
field_updates=None, recode_ident=None):
"""本单位工程的工料机汇总 = 单价被查找的对象(主人口径 5.1/5.3):
①采纳新增的品类行追加到本单位汇总末尾(克隆完整属性集);
②合并改价按编码写回本单位汇总节点(除税/税率/含税,只动不一致项)——
@@ -862,9 +914,11 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
改码命中的节点(该单位原是旧码)同样吃到保留码的编辑值。
决策 93:改价+改码的全部修改按**一次扫描的索引**定位、一次拼接——此前每码全文重扫
(翠香件每文件 ~1300 遍 = 单文件 4~6 秒)。索引建在追加之后的文本上:新增行也吃合并价。"""
tmpl = _full_summary_template(txt)
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
if added_rows:
nodes = "".join(_summary_node(r, tmpl) for r in added_rows)
# 决策 183:骨架三型选取——按采纳行的 Kind 同型优先选模板(台班/配合比/普通不跨型)
nodes = "".join(_summary_node(r, _full_summary_template(txt, r[8] if len(r) > 8 else None))
for r in added_rows)
last = None
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*/>', txt):
last = m
@@ -872,68 +926,72 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
txt = txt[:last.end()] + nodes + txt[last.end():]
idx = _summary_span_index(txt)
edits = {} # span起点 → (起, 止, 替换)(同节点改价+改码合并为一条)
for code, (ntp, rate, taxp) in (price_updates or {}).items():
span = idx.get(str(code))
if not span:
continue
s0, e0, _bend, opentag = span
newtag = opentag
for attr, v in (("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
if v is None:
continue
newtag = _attr_set(newtag, attr, v)
if newtag != opentag:
edits[s0] = (s0, e0, newtag)
foreign = _ident_foreign_spans(txt, idx, recode_ident) # 决策 178:同码异物节点先认领
for s0, (fs, fe, ntag) in foreign.items():
edits[s0] = (fs, fe, ntag)
for code, px in (price_updates or {}).items():
for s0, e0, _bend, opentag in idx.get(str(code)) or ():
if s0 in foreign:
continue # 决策 178:异物节点不吃合并价(另一种资源)
newtag = _lme_apply_price(opentag, px) # 决策 183:属性级对应+Total 配对自算
if newtag != opentag:
edits[s0] = (s0, e0, newtag)
for code, (name, spec, unit) in (field_updates or {}).items():
# ④编辑回写:Name/Specification/Unit 与改价同一索引通道、同一合成规则。
# 2026-10-22 决策 169(主人定):金额汇总行(数量=金额合计、单价=1 的费用科目行)
# **视同普通工料机**——价格/名规格一律照常回写,不再有任何跳过
# (原「补记九金额行不回写价格」防护撤除:误写路径已随 merged_codes/field_codes
# 白名单通道消失,只有编辑/合并过的编码才会被写)。
span = idx.get(str(code))
if not span:
continue
s0, e0, _bend, opentag = span
base = edits.get(s0)
start_tag = base[2] if base else opentag
newtag = start_tag
for attr, v in (("Name", name), ("Specification", spec), ("Unit", unit)):
if v is None:
continue
newtag = _attr_set(newtag, attr, v)
if newtag != start_tag:
edits[s0] = (s0, e0, newtag)
for s0, e0, _bend, opentag in idx.get(str(code)) or ():
if s0 in foreign:
continue # 决策 178:异物节点不吃编辑回写
base = edits.get(s0)
start_tag = base[2] if base else opentag
newtag = start_tag
for attr, v in (("Name", name), ("Specification", spec), ("Unit", unit)):
if v is None:
continue
newtag = _attr_set(newtag, attr, v)
if newtag != start_tag:
edits[s0] = (s0, e0, newtag)
blocks = {} # span起点 → (s0, bend, 整块替换)(改码带子级重建)
_claimed = set() # 决策 184:换码占位(每保留码在本单位只占一条)
for old, new in (recode_map or {}).items():
if old == new:
continue
span = idx.get(str(old))
if not span:
continue
s0, e0, bend, opentag = span
# 基础开标签取**已应用改价**的版本(旧实现改码在改价之后重扫全文,带上价格;
# 索引化后同一节点两笔编辑要显式合成——先改价后换码,别把价格覆盖丢掉)
base = edits.get(s0)
newtag = _attr_set(base[2] if base else opentag, "Number", str(new))
_fu = (field_updates or {}).get(str(new))
if _fu: # 改码后的节点也吃到保留码的编辑值(该单位原是旧码时)
for attr, v in (("Name", _fu[0]), ("Specification", _fu[1]), ("Unit", _fu[2])):
if v is not None:
newtag = _attr_set(newtag, attr, v)
_pu = (price_updates or {}).get(str(new))
if _pu: # 决策 171 补(主人定「三价要同步更新」):换码节点同样
for attr, v in (("NoTaxPrice", _pu[0]), ("TaxRate", _pu[1]), ("TaxPrice", _pu[2])):
if v is not None: # 带上保留行三价——只换码不换价会让导出件里
newtag = _attr_set(newtag, attr, v) # 新旧两价并存(实测:导入广联达显示 126)
rows = (recode_children or {}).get(str(old)) or []
if rows:
kids = re.findall(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>', txt[e0:bend])
ktmpl = kids[0] if kids else \
'<LabourMaterialsEquipmentsMachinesElement Number="" Quantity="0.0000" NOCost="false" Remark=""/>'
newkids = "".join(_child_node(ktmpl, c, q) for (c, q) in rows)
blocks[s0] = (s0, bend, newtag + newkids + "</" + _SUM_TAG + ">")
else:
blocks[s0] = (s0, e0, newtag) # 无子级替换数据(childless 合并或无组成):只换码
has_keep = bool(idx.get(str(new))) # 本单位已有保留码行?
for s0, e0, bend, opentag in idx.get(str(old)) or ():
if s0 in foreign:
continue # 决策 178:异物节点不是合并码,不换码不重建
# 决策 184(2026-10-23 主人定 A 清洗):本单位已有保留码行、或该保留码已被先到
# 换码占位 → 此被合并码节点**整块删除**(每单位工程每码只留一条,条目数=显示端);
# 单位内无保留码行 → 第一条换码保留(不丢结构),其余删除。
if has_keep or str(new) in _claimed:
blocks[s0] = (s0, bend if bend > e0 else e0, "")
continue
_claimed.add(str(new))
# 基础开标签取**已应用改价**的版本(旧实现改码在改价之后重扫全文,带上价格;
# 索引化后同一节点两笔编辑要显式合成——先改价后换码,别把价格覆盖丢掉)
base = edits.get(s0)
newtag = _attr_set(base[2] if base else opentag, "Number", str(new))
_fu = (field_updates or {}).get(str(new))
if _fu: # 改码后的节点也吃到保留码的编辑值(该单位原是旧码时)
for attr, v in (("Name", _fu[0]), ("Specification", _fu[1]), ("Unit", _fu[2])):
if v is not None:
newtag = _attr_set(newtag, attr, v)
_pu = (price_updates or {}).get(str(new))
if _pu: # 决策 171 补(主人定「三价要同步更新」):换码节点同样
newtag = _lme_apply_price(newtag, _pu) # 决策 183:属性级对应全字段回填
rows = (recode_children or {}).get(str(old))
if rows is not None and bend > e0: # 决策 178:登记即重建(空表=[]=子级清空,全部替换);
kids = re.findall(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>', txt[e0:bend])
ktmpl = kids[0] if kids else \
'<LabourMaterialsEquipmentsMachinesElement Number="" Quantity="0.0000" NOCost="false" Remark=""/>'
newkids = "".join(_child_node(ktmpl, c, q) for (c, q) in rows)
blocks[s0] = (s0, bend, newtag + newkids + "</" + _SUM_TAG + ">")
else:
# 未登记(None=无重建数据)或裸行/自闭合:只换码,不发明闭块结构
blocks[s0] = (s0, e0, newtag)
for s0, (s, e, rep) in blocks.items(): # 改码覆盖同节点的纯改价(原序:先改价后改码)
edits[s0] = (s, e, rep)
return _apply_edits(txt, list(edits.values()))
@@ -949,29 +1007,40 @@ def _child_node(tmpl, code, qty):
return t
def _ident_foreign_spans(txt, idx, recode_ident):
"""决策 178(2026-10-23 主人定「不同名规单不能共用一个编码」):同码异物节点认领——
recode_ident {原码: {名规单key: 新码}},节点自带名称/规格/单位命中 → 该节点改印新码。
返回 {span起点: (起, 止, 改后开标签)};认领的节点是另一种资源,不再吃改价/字段/普通换码。"""
out = {}
if not recode_ident:
return out
for old_code, idents in recode_ident.items():
for (s0, e0, _bend, opentag) in idx.get(str(old_code)) or ():
ident = "\x1f".join(((_attr(opentag, "Name") or "").strip(),
(_attr(opentag, "Specification") or "").strip(),
(_attr(opentag, "Unit") or "").strip()))
new_code = idents.get(ident)
if new_code and new_code != old_code:
out[s0] = (s0, e0, _attr_set(opentag, "Number", str(new_code)))
return out
_LME_ROW_TAG = "LabourMaterialsEquipmentsMachinesElement"
def _recode_norm_lme_rows(txt, recode_map):
"""定额消耗量行的编码替换(2026-10-22 主人定:合并改码贯通到全部定额)。
Summary 块**外**的 LabourMaterialsEquipmentsMachinesElement = 定额下工料机行
(清单直挂行同标签同处理);块内的是台班/配合比子级组成,已由 recode_children
重建为保留行子级,绝不再碰。开标签一次扫描定位替换(同决策 93 索引手法),
LabourMaterialsEquipmentsMachinesElement = 定额下工料机行(清单直挂行同标签同处理)。
决策 178(2026-10-23 主人定「全部替换」):**块内子级行也照映射换码**——原「块内子级
绝不再碰」口径撤除;有重建数据的块刚被整组替换过,其子级编码若本身也是被合并码,
照映射再换一层(映射是权威)。行只有编码跟映射走,含量等其余字段不动。
开标签一次扫描定位替换(同决策 93 索引手法),
顺序在 transform_unit_summaries 之后:Summary 节点已换好码,这里只管行。"""
if not recode_map:
return txt
spans = []
for m in re.finditer(r'<' + _SUM_TAG + r'\b[^>]*>', txt):
if m.group(0).rstrip().endswith('/>'):
spans.append((m.start(), m.end()))
else:
e = txt.find('</' + _SUM_TAG + '>', m.end())
if e >= 0:
spans.append((m.start(), e + len('</' + _SUM_TAG + '>')))
recode_map = _resolve_recode_chains(recode_map)
edits = []
for m in re.finditer(r'<' + _LME_ROW_TAG + r'\b[^>]*>', txt):
if any(s <= m.start() < e for s, e in spans):
continue
tag = m.group(0)
old = _attr(tag, "Number")
new = recode_map.get(old) if old else None
@@ -987,9 +1056,13 @@ _SUM_TAG = "LabourMaterialsEquipmentsMachinesSummary"
def _summary_span_index(txt):
"""一次扫描建 {Number编码: span} 索引(决策 93 提速):此前每处理一个编码就把全文
finditer 重扫一遍(翠香件每文件 ~1300 遍、Project.xml 3142 遍 → 单工程 6 分钟)。
同名编码只记**首个**命中——与 _find_summary_span 的首个命中语义一致。"""
"""一次扫描建 {Number编码: [span, ...]} 索引(决策 93 提速 + 决策 174 全命中):
此前每处理一个编码就把全文 finditer 重扫一遍(翠香件每文件 ~1300 遍、Project.xml
3142 遍 → 单工程 6 分钟)。决策 93 索引化时沿用旧首中语义「同名编码只记首个」——
实测广联达件同码会在同一文件里出多条汇总节点(按分部重复列码),只改首条=导出件
残留旧码旧价(华宇路 37270101@3 三条只换一条、金宝 Summary 残留 1100 条,
2026-10-22 主人拍板:同码多节点全改)。span=(起点, 开标签止, 块止, 开标签),
块止对自闭合=开标签止;列表按文件序。"""
idx = {}
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
e = _open_tag_end(txt, m.start())
@@ -997,15 +1070,21 @@ def _summary_span_index(txt):
continue
opentag = txt[m.start():e]
code = _attr(opentag, "Number")
if code is None or code in idx:
if code is None:
continue
if opentag.endswith("/>"):
idx[code] = (m.start(), e, e, opentag)
idx.setdefault(code, []).append((m.start(), e, e, opentag))
else:
ce = txt.find("</" + _SUM_TAG + ">", e)
if ce < 0:
continue
idx[code] = (m.start(), e, ce + len("</" + _SUM_TAG + ">"), opentag)
# 决策 174 补(金宝实测):广联达件大量无子级行是**裸开标签**——无 /> 也无自己的
# 闭标签,下一行就是下一个 <Summary>。若在找到的闭标签之前又出现本表开标签,
# 这个「块」必是假的(真块内不会再嵌 Summary)→ 按裸行处理,span 只算开标签。
# 否则假块会吞进几万字符里的几十个节点:改码编辑与内层相交被 _apply_edits 丢弃
# (换码失效)、_recode_norm_lme_rows 把吞进的元素行误当块内子级跳过(残留)。
if ce < 0 or re.search(r'<' + _SUM_TAG + r'\b', txt[e:ce]):
idx.setdefault(code, []).append((m.start(), e, e, opentag))
else:
idx.setdefault(code, []).append((m.start(), e, ce + len("</" + _SUM_TAG + ">"), opentag))
return idx
@@ -1023,23 +1102,36 @@ def _apply_edits(txt, edits):
def _find_summary_span(txt, code):
"""按编码找工料单条汇总节点,返回 (起点, 开标签止, 块止, 开标签);没有返回 None。
单次查找入口——批量场景请用 _summary_span_index 建一次索引(决策 93)。"""
return _summary_span_index(txt).get(str(code))
单次查找入口(取首条,兼容旧单点语义)——批量场景请用 _summary_span_index
建一次索引并遍历全部命中(决策 93/174)。"""
spans = _summary_span_index(txt).get(str(code))
return spans[0] if spans else None
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None, recode_map=None,
recode_children=None, recode_ident=None):
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
sync_rows = [(编码,名称,规格,单位,除税价,税率,含税价), ...](会话侧项目级汇总现值,全量传入)。
同步规则:编码命中 → 只更新 名称/规格/单位/除税价/税率/含税价 **不一致** 的字段(最小替代);
同步规则(决策 176 改):编码命中 → 名称/规格/单位/除税价/税率/含税价 **全量写回**,
提供即写、不比较新旧是否一致(取代 75 的「只更新不一致字段」最小替代);
编码缺失(采纳新增品类)→ 由 added_summaries 追加。隐藏行照旧省略。
决策 93:汇总节点一次扫描建索引,隐藏删除+同步改写全部算好后一次拼接——
此前每个编码全文重扫(翠香件 3142 遍 × 3.7MB = 52 秒,仅此一项)。"""
此前每个编码全文重扫(翠香件 3142 遍 × 3.7MB = 52 秒,仅此一项)。
决策 174(2026-10-22 主人定):①同码**全部命中**节点同改(同码多条只改首条=金宝实测
Summary 残留 1100 条的根源);②补**换码通道**——recode_map 旧码节点 Number 换保留码
并带保留行同步值(此前 Project.xml 压根没有换码通道,单位级合并而项目级行未隐藏时
旧码节点整条原样出件)。"""
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
idx = _summary_span_index(txt)
foreign = _ident_foreign_spans(txt, idx, recode_ident) # 决策 178:同码异物节点先认领
edits = [] # (起, 止, 替换文本)
for s0, (fs, fe, ntag) in foreign.items():
edits.append((fs, fe, ntag))
hidden_s0 = set()
for code in hidden_codes or []:
span = idx.get(str(code))
if span:
edits.append((span[0], span[2], "")) # 按块删除(含成对闭标签,决策 76 修复口径)
for span in idx.get(str(code)) or ():
hidden_s0.add(span[0])
edits.append((span[0], span[2], "")) # 按块删除(含成对闭标签,决策 76 修复口径);同码全部删
if added_summaries:
# 采纳新增行先落位(2026-10-15 环山路实测:先追加后同步,合并/同步价才能覆盖到新增行)。
# 注意:新增节点插在**原文**最后一个汇总节点之后——它不在 idx 里,本函数不负责同步它
@@ -1068,26 +1160,52 @@ def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
j = txt.find("</ConstructionProject>")
if j >= 0:
edits.append((j, j, nodes))
sync_by_code = {str(c): (nm, sp, un, np_, rt, tp)
for (c, nm, sp, un, np_, rt, tp) in (sync_rows or [])}
sync_edits = {} # span起点 → (起, 止, 开标签改后)(换码在其上合成)
# 决策 176(2026-10-22 主人定):同步=**全量写回**——提供即写,不比较新旧是否一致
# (取代决策 75「只更新不一致字段」的最小替代;决策 169 金额行视同普通行不变,
# 其撤除的「aggregate 跳过」本就是另一回事)。属性在骨架里不存在(_attr None)才跳过。
for (code, name, spec, unit, ntp, rate, taxp) in (sync_rows or []):
span = idx.get(str(code))
if not span:
continue
s0, e0, _bend, opentag = span
newtag = opentag
for attr, want in (("Name", name), ("Specification", spec), ("Unit", unit),
("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
cur = _attr(newtag, attr)
if cur is None or want is None:
continue
# 2026-10-22 决策 169:金额汇总行视同普通工料机,原「aggregate 价格跳过」撤除
if attr in _PRICE_ATTRS and _num_eq(cur, want):
continue
if attr in ("Name", "Specification", "Unit") and (cur or "").strip() == (want or "").strip():
continue
if want != cur:
for s0, e0, _bend, opentag in idx.get(str(code)) or ():
if s0 in foreign:
continue # 决策 178:异物节点不吃项目级同步(另一种资源)
newtag = opentag
for attr, want in (("Name", name), ("Specification", spec), ("Unit", unit),
("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
if want is None or _attr(newtag, attr) is None:
continue
newtag = _attr_set(newtag, attr, want)
if newtag != opentag:
edits.append((s0, e0, newtag))
if newtag != opentag:
sync_edits[s0] = (s0, e0, newtag)
# 决策 174:换码通道——旧码节点 Number 换保留码并带保留行同步值;被隐藏删除的块不再碰
# (_apply_edits 的相交防御也会兜底:删除块优先)。同码全部命中;带值同决策 176 全量写回。
for old, new in (recode_map or {}).items():
if old == new:
continue
rows = (recode_children or {}).get(str(old))
for s0, e0, bend, opentag in idx.get(str(old)) or ():
if s0 in hidden_s0 or s0 in foreign:
continue
base = sync_edits.get(s0)
start_tag = base[2] if base else opentag
newtag = _attr_set(start_tag, "Number", str(new))
_keep = sync_by_code.get(str(new))
if _keep:
for attr, want in (("Name", _keep[0]), ("Specification", _keep[1]), ("Unit", _keep[2]),
("NoTaxPrice", _keep[3]), ("TaxRate", _keep[4]), ("TaxPrice", _keep[5])):
if want is None or _attr(newtag, attr) is None:
continue
newtag = _attr_set(newtag, attr, want)
if rows is not None and bend > e0: # 决策 178:成对块子级整组替换成保留码子级(空表=清空)
kids = re.findall(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>', txt[e0:bend])
ktmpl = kids[0] if kids else \
'<LabourMaterialsEquipmentsMachinesElement Number="" Quantity="0.0000" NOCost="false" Remark=""/>'
newkids = "".join(_child_node(ktmpl, c, q) for (c, q) in rows)
sync_edits[s0] = (s0, bend, newtag + newkids + "</" + _SUM_TAG + ">")
else:
sync_edits[s0] = (s0, e0, newtag)
edits.extend(sync_edits.values())
return _apply_edits(txt, edits)
@@ -1128,15 +1246,36 @@ def _source_ext(src_name):
return m.group(1) if m else ".cos"
def _resolve_recode_chains(m):
"""改码链压平(决策 174 补,2026-10-22 主人定「合并后为准」):登记映射是多次合并
累积的森林(A→B 与 B→C 会共存),导出换码必须落到**链尾**——A 的最终保留码是 C,
不压平就停在中途码(金宝实测 -0004→-0001→-0009,-0004 节点停在 -0001 = 真残留)。
环(A→B 且 B→A,历史反复合并方向翻滚的脏映射)无解,按访问集停在入口码。"""
out = {}
for k in m:
cur, seen = k, {k}
for _ in range(len(m) + 1):
nxt = m.get(cur)
if not nxt or nxt == cur or nxt in seen:
break
seen.add(nxt)
cur = nxt
if cur != k:
out[k] = cur
return out
def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidden_codes, res_by_norm,
price_updates=None, added_lme_by_uw=None, sync_rows=None, recode_map=None, recode_children=None,
field_updates=None,
recode_ident=None, field_updates=None,
progress=None):
"""src_bytes=原文件字节;unit_plans={uw键(Number,Name): plan};
plan={"pairs":{...}, "news":{...}, "norms_by_bill":{...}, "added_lme":[(码,名,规格,单位,量,税率,除税,含税,类别)]}。
recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出)。
recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出);
recode_map 进通道前先压平改码链(决策 174 补)。
progress=可选回调 progress(done, total)——每个 zip 条目处理完报一次(决策 92 导出进度条)。
返回 (新zip字节, 建议文件名)。"""
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
ext = _source_ext(src_name)
out_name = (proj_name or "工程") + "-审核版" + ext
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
@@ -1171,7 +1310,11 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
base = item.filename.rsplit("/", 1)[-1]
if base.lower() == "project.xml":
txt, enc = _decode(raw)
txt = transform_project(txt, added_summaries, hidden_codes, sync_rows)
txt = transform_project(txt, added_summaries, hidden_codes, sync_rows,
recode_map=recode_map, recode_children=recode_children,
recode_ident=recode_ident)
if recode_map: # 决策 174:Project.xml 的块外元素行同口径换码
txt = _recode_norm_lme_rows(txt, recode_map)
raw = _encode(txt, enc)
else:
# 单位工程 xml:按内容里的 UnitWorks(Number,Name) 认领计划——
@@ -1201,9 +1344,11 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
# (field_updates,2026-10-22)——全字段 sync 是项目级的事——
# 否则零编辑也会大面积误改(已实测踩坑)
upd = {c: v for c, v in (price_updates or {}).items()}
if upd or added_rows or field_updates:
# 决策 174:recode_map 有映射也要进(该单位没有合并改价码时,变体码节点
# 照样要换码——此前整个跳过=该单位文件变体码全残留)
if upd or added_rows or field_updates or recode_map or recode_ident:
txt = transform_unit_summaries(txt, upd, added_rows, recode_map, recode_children,
field_updates=field_updates)
field_updates=field_updates, recode_ident=recode_ident)
if recode_map: # 2026-10-22:定额消耗量行编码替换(Summary 块外)
txt = _recode_norm_lme_rows(txt, recode_map)
raw = _encode(txt, enc)

View File

@@ -213,7 +213,10 @@ def parse_std(path, out):
f(sm.attrib.get("Kind")),
f(sm.attrib.get("Quantity")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice")),
f(sm.attrib.get("TaxRate"))])
f(sm.attrib.get("TaxRate")),
# 决策 183(2026-10-23 主人定):整套按骨架——六价全采,回填按属性一一对应
f(sm.attrib.get("NoTaxOrgPrice")), f(sm.attrib.get("NoTaxPriceExpress")),
f(sm.attrib.get("TaxOrgPrice")), f(sm.attrib.get("TaxPriceExpress"))])
# 单项工程层(2026-09-30):两种新格式节点名不同,都试一遍,谁有取谁。
# 记下每个单项工程下挂哪些单位工程编号 —— 靠它把单位工程归到单项工程下。
for tag in ("DivisionalAndElementalProject", "SectionalWorks"):
@@ -462,7 +465,10 @@ def parse_std(path, out):
out.setdefault("lme_uw", []).append((
_st[-1], a.get("Number", ""), a.get("Name", ""), a.get("Specification", ""),
a.get("Unit", ""), f(a.get("NoTaxPrice")), f(a.get("TaxRate")),
f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or "")))
f(a.get("TaxPrice")), f(a.get("Quantity")), str(a.get("Kind") or ""),
# 决策 183:六价全采(属性级对应回填)
f(a.get("NoTaxOrgPrice")), f(a.get("NoTaxPriceExpress")),
f(a.get("TaxOrgPrice")), f(a.get("TaxPriceExpress"))))
out["cur_lme"] = "" # 出这条汇总:后面的 Element 不再算它的组成
el.clear()
return "2025标准"
@@ -552,7 +558,8 @@ def parse_swt(path, out):
# 主人定 A(2026-10-19,决策 122 恢复;覆盖决策 121 的 B):
# SWT 只有一个 Rate(不含税预算价)→ 除税价=含税价=Rate、税率=0。
out["lmes"].append((code, nm, sp, un, rate, 0.0, rate, qty, kd))
out["lme_uw"].append((u["idx"], code, nm, sp, un, rate, 0.0, rate, qty, kd))
out["lme_uw"].append((u["idx"], code, nm, sp, un, rate, 0.0, rate, qty, kd,
None, None, None, None)) # SWT 无六价源(决策 122:Rate 同值)
out["lme_lib"][code] = [nm, sp, un, kd, rate, rate]
out["lme_name"][code] = nm
p = out["lme_proj"].get(code)
@@ -1018,9 +1025,13 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
for _c, v in (out.get("lme_proj") or {}).items():
_nm, _sp, _un, _kd, _q, _ntp, _taxp = v[0], v[1], v[2], v[3], v[4], v[5], v[6]
_rate = v[7] if len(v) > 7 else None # 老结构兼容(理论不再出现)
# 决策 183:六价全采(NoTaxOrgPrice/NoTaxPriceExpress/TaxOrgPrice/TaxPriceExpress)
_x = (v[8:12] + [None] * 4)[:4] if len(v) > 8 else [None] * 4
try:
cur.execute("""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp, taxrate)
VALUES(?,?,?,?,?,?,?,?,?,?)""", (bid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate))
cur.execute("""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp, taxrate,
ntp_org, ntp_expr, taxp_org, taxp_expr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate) + tuple(_x))
n_proj += cur.rowcount
except Exception as e:
print("项目级汇总入库失败 %s:%s" % (_c, e), flush=True)
@@ -1030,14 +1041,16 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
# 各单位工程自己的工料机汇总(2026-10-11 决策 41):解析时按单位工程归属原样入库,
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
n_uwlme = 0
for (k, num, name, spec, unit, ntp, taxrate, taxp, qty, kind) in (out.get("lme_uw") or []):
for _row in (out.get("lme_uw") or []):
k, num, name, spec, unit, ntp, taxrate, taxp, qty, kind = _row[:10]
_x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(老结构 len 兼容)
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
if not uwid:
continue
try:
cur.execute("""INSERT INTO lme_uw(batch_id, uw_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, num, name, spec, unit, kind, qty, ntp, taxrate, taxp))
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, num, name, spec, unit, kind, qty, ntp, taxrate, taxp) + tuple(_x))
n_uwlme += 1
except Exception as e:
print("单位工程工料机汇总入库失败 %s:%s" % (num, e), flush=True)

View File

@@ -108,10 +108,26 @@ def ensure_lme_proj_remark_scoped():
con = connect()
try:
ensure_lme_proj_remark(con)
ensure_lme_price_cols(con)
finally:
con.close()
_LME_PRICE_COLS = ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr") # 决策 183:六价全采
def ensure_lme_price_cols(con):
"""老会话库 s_lme_proj/s_lme_uw 补六价四列(幂等,决策 183:整套按骨架属性对应回填)。"""
for t in ("s_lme_proj", "s_lme_uw"):
cols = [r[1] for r in con.execute("PRAGMA table_info(%s)" % t)]
if not cols:
continue # 表还没建(首次初始化走 CREATE)
for cn in _LME_PRICE_COLS:
if cn not in cols:
con.execute("ALTER TABLE %s ADD COLUMN %s REAL" % (t, cn))
con.commit()
def _lme_keys(con, sid, src_name=None):
"""这个会话每条工料机的持久键 → {rkey: 行id}(回填备注用)。前缀 'L:' 隔离清单键。
2026-10-11 决策 40:行 = 项目级汇总 s_lme_proj(标签数据源所在)。
@@ -625,13 +641,15 @@ def open_project(con, files, meta, job, sid=None):
# 2026-10-11 决策 41:各单位工程**自己的工料机汇总**按 uw 归属原样入库(s_lme_uw),
# 「原数据 · 单位工程级工料机汇总」直接读它(总数量=源文件原样,不走消耗量归集)。
for (k, num, nm, spec, unit, ntp, tax, tp, qty, kind) in (out.get("lme_uw") or []):
for _row in (out.get("lme_uw") or []):
k, num, nm, spec, unit, ntp, tax, tp, qty, kind = _row[:10]
_x = (list(_row[10:14]) + [None] * 4)[:4] # 决策 183:六价尾部扩展(SWT/老结构为 None)
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
if not uwid:
continue
cur.execute("""INSERT INTO s_lme_uw(session_id, uw_id, code, name, spec, unit, kind,
qty, ntp, taxrate, taxp) VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp))
qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, num, nm, spec, unit, kind, qty, ntp, tax, tp) + tuple(_x))
# 2026-10-02:机械台班 / 配合比的下一级组成(s_lme_res)
_lname = out.get("lme_name") or {}
@@ -655,8 +673,11 @@ def open_project(con, files, meta, job, sid=None):
for _c, v in (out.get("lme_proj") or {}).items():
_nm, _sp, _un, _kd, _q, _ntp, _taxp = v[0], v[1], v[2], v[3], v[4], v[5], v[6]
_rate = v[7] if len(v) > 7 else None # 决策 69:TaxRate 采集(合并弹框税率字段)
cur.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp, taxrate)
VALUES(?,?,?,?,?,?,?,?,?,?)""", (sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate))
_x = (v[8:12] + [None] * 4)[:4] # 决策 183:六价全采(属性级对应回填)
cur.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp, taxrate,
ntp_org, ntp_expr, taxp_org, taxp_expr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate) + tuple(_x))
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
if ptotal is not None or pinfo or pfeat:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? WHERE id=?",