feat: 决策64-81——共享层地基/数据采纳/合并工料机/导出回写/子级物理整字段替换 + MCP工具接入层 + 规格收工存档

- 决策65-72 批次A-E:共享层清单插入/临删/恢复/删除/行内编辑、数据采纳全语义、合并工料机弹框+税率采集、导出原格式回写、历史对比框共享到分部分项/措施/组价不一致
- 决策73-77:5.0 正式样本验收、导出管线三连修、工料机改价口径定稿(有子级改子数据)
- 决策78-81+追记:合并弹框带子级放回/固定表头、s_lme_res 子级物理整字段替换、recode_map/recode_children 落库、导出 _apply_recode 重建子级全字段、修 _find_summary_span 自闭合判断恒 False
- 新增 server/mcp_server.py:Streamable HTTP /mcp(stateless JSON-RPC),mcp_enabled 默认关+Bearer 令牌+license 403,复用 api_* 处理器,零新增依赖
- 新增测试 mcp_switch/lme_price/export_ext/norm_op/norm_res_name,test_source_guards 扩充
- 收尾:.gitignore 忽略 .mimosa/(曾被全量暂存5785个缓存文件);删 备份代码.bat;规格完工存档 20261016_2051;新增方案文档 清单替换与共享层
This commit is contained in:
lianjianwei2024
2026-10-16 20:54:32 +08:00
parent 9464f74e17
commit ca19d9f929
35 changed files with 6172 additions and 400 deletions

View File

@@ -0,0 +1,577 @@
# -*- coding: utf-8 -*-
"""导出回写(批次D,决策 70;方案 §7):拿原文件当模板外科手术,只动改过的部分。
铁律(决策 64):编辑状态绝不作为自定义属性写进文件(对方软件只认自己的列,一存就扔)——
状态的「数据效果」直接体现为文件内容:
· 临删清单/临删定额 → 从文件里真实省略(删就是删);
· 新增清单 / 采纳追加定额 → 按上下文同款标签插入(跟锚点块同标签,天然适配
WorkElement 与措施条目 UnitWorksPreliminaryWorkElement 两种形态);
2026-10-15 起插入节点克隆源文件同类节点的**完整属性集**再覆盖会话值——
广联达导入按属性取数,属性残缺(缺 Quantity/NormIdentity/IsNorm 等)整包被拒
(样本实测:最小形态导不进广联达,易达补全属性后能进);
· 字段编辑 → 只改开标签的对应属性(与文件现值不同才写);
· 汇总:采纳补的品类行追加进 Project.xml;合并隐藏的汇总行省略;
· 其余字节原样保留。
所有插入只用源文件里出现过的标签与属性名,且插在同类节点旁边——结构合法性由此保证。
对不上的块(源文件与会话不同源、或被外部改过)一律保留原样:宁可不改,不可改错。
"""
import io
import re
import zipfile
BILL_TAGS = ("WorkElement", "UnitWorksPreliminaryWorkElement")
_CLOSE_WE = "</WorkElement>"
_CLOSE_PRE = "</UnitWorksPreliminaryWorkElement>"
_UNESC = {"&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&apos;": "'"}
def _unesc(s):
for k, v in _UNESC.items():
if k in s:
s = s.replace(k, v)
return s
def _esc(v):
return ("" if v is None else str(v)).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
def _attr(open_tag, name):
"""开标签里取属性值(已反转义);没有返回 None。"""
m = re.search(r'\b' + name + r'="([^"]*)"', open_tag)
return _unesc(m.group(1)) if m else None
def _attr_set(open_tag, name, value):
v = _esc(value)
if re.search(r'\b' + name + r'="', open_tag):
return re.sub(r'\b' + name + r'="[^"]*"', lambda _m: name + '="' + v + '"', open_tag, count=1)
return open_tag[:-1] + " " + name + '="' + v + '">'
def _num_eq(a, b):
"""数值相等比较('55.000000' == 55.0):编辑比对用,避免把源文件的数字格式当改动重写。"""
try:
return abs(float(a) - float(b)) < 1e-9
except (TypeError, ValueError):
return False
def _ws_eq(a, b):
"""空白规范化比较:XML 解析器按规范把属性值里的换行/制表符规范化成空格——
会话库里的项目特征是空格版、源文件是换行版,内容其实一致。
不做这一步,导出补丁会把整个项目特征重写成空格版(主人实测:换行丢失)。"""
na = re.sub(r"\s+", " ", a or "")
nb = re.sub(r"\s+", " ", b or "")
return na == nb
def _open_tag_end(txt, start):
"""标签起点 → 开标签结束位置(越过属性值里的 '>' 与换行)。"""
i, inq, n = start, False, len(txt)
while i < n:
c = txt[i]
if c == '"':
inq = not inq
elif c == '>' and not inq:
return i + 1
i += 1
return -1
def _detect_enc(raw):
m = re.match(rb'^\s*<\?xml[^>]*encoding="([^"]*)"', raw[:200])
if m:
try:
return m.group(1).decode("ascii")
except Exception:
pass
return "utf-8"
def _decode(raw):
enc = _detect_enc(raw)
try:
return raw.decode(enc), enc
except (LookupError, UnicodeDecodeError):
return raw.decode("utf-8", errors="replace"), "utf-8"
def _encode(txt, enc):
try:
return txt.encode(enc)
except (LookupError, UnicodeEncodeError):
return txt.encode(enc, errors="xmlcharrefreplace") # 数字字符引用是合法 XML
# ---------------------------------------------------------------- 单位工程 xml
def _scan_bills(txt):
"""清单块列表(文档序):{tag, s, e(开标签止), end(块止), opentag, uw(最近 UnitWorks 开标签)}"""
marks, last_uw = [], None
for m in re.finditer(r'<(WorkElement|UnitWorksPreliminaryWorkElement|UnitWorks)\b', txt):
tag = m.group(1)
e = _open_tag_end(txt, m.start())
if e < 0:
continue
opentag = txt[m.start():e]
if tag == "UnitWorks":
last_uw = opentag
continue
close = "</" + tag + ">"
ce = txt.find(close, e)
if ce < 0:
continue
marks.append({"tag": tag, "s": m.start(), "e": e, "end": ce + len(close),
"opentag": opentag, "uw": last_uw or ""})
return marks
def _norm_spans(block_txt):
out = []
for m in re.finditer(r'<Norm\b', block_txt):
e = _open_tag_end(block_txt, m.start())
if e < 0:
continue
ce = block_txt.find("</Norm>", e)
if ce < 0:
continue
out.append({"s": m.start(), "e": e, "end": ce + len("</Norm>"), "opentag": block_txt[m.start():e]})
return out
def _full_norm_template(txt):
"""文件里第一条属性齐全的 Norm 开标签(作克隆模板)。广联达导入要求
Quantity/NormIdentity/IsNorm/Type/CalculationKind/CostKind 等字段在位——
2026-10-15 样本实测:采纳定额按最小属性写出后整包导不进广联达,
易达补全属性再导出才能进。缺关键属性的残行不配当模板。"""
for nsp in _norm_spans(txt):
if ' NormIdentity="' in nsp["opentag"] and ' Quantity="' in nsp["opentag"]:
return nsp["opentag"]
return None
def _clone_open_tag(template):
"""模板开标签 → 非自闭合(克隆出的节点要带子节点/闭合标签)。"""
return template[:-2] + ">" if template.endswith("/>") else template
def _norm_xml(n, lres, template=None):
"""定额行:优先克隆源文件同类 Norm 的完整属性集(值除会话字段外原样保留,
与易达的已知可行解一致);没有模板时退回最小形态。会话没算出的数值写 0
(易达同款处理)——占位属性可以在位为 0,但不能缺席。"""
if template:
tag = _clone_open_tag(template)
for k, v in (("Number", n["Number"]), ("Name", n["Name"]), ("Unit", n["Unit"])):
tag = _attr_set(tag, k, v)
for k, v in (("Quantity", n["Quantity"]), ("Price", n["Price"]), ("Total", n["Total"])):
tag = _attr_set(tag, k, "0" if v is None else v)
else:
a = ' Number="%s" Name="%s" Unit="%s"' % (_esc(n["Number"]), _esc(n["Name"]), _esc(n["Unit"]))
if n["Quantity"] is not None:
a += ' Quantity="%s"' % n["Quantity"]
if n["Price"] is not None:
a += ' Price="%s"' % n["Price"]
if n["Total"] is not None:
a += ' Total="%s"' % n["Total"]
tag = "<Norm" + a + ">"
kids = "".join('<LabourMaterialsEquipmentsMachinesElement Number="%s" Express="%s" Quantity="%s" Remark=""/>'
% (_esc(c), _esc(q), _esc(q))
for c, q in lres if c)
return tag + kids + "</Norm>"
def _bill_xml(b, tag, norms_xml, template=None):
"""新增清单:优先克隆锚点清单的开标签(完整 27 属性,易达同款——
新增清单同样因属性残缺导不进广联达);没有模板时退回最小形态。"""
if template:
t = _clone_open_tag(template)
for k, v in (("Number", b["Number"]), ("Name", b["Name"]),
("Quantity", b["Quantity"]), ("Price", b["Price"]), ("Total", b["Total"])):
t = _attr_set(t, k, "0" if v is None else v)
if b["Unit"]:
t = _attr_set(t, "Unit", b["Unit"])
if b["Attr"]:
t = _attr_set(t, "Attr", b["Attr"])
if b["src_remark"]:
t = _attr_set(t, "Remark", b["src_remark"])
else:
a = ' Number="%s" Name="%s"' % (_esc(b["Number"]), _esc(b["Name"]))
if b["Attr"]:
a += ' Attr="%s"' % _esc(b["Attr"])
if b["Unit"]:
a += ' Unit="%s"' % _esc(b["Unit"])
a += ' Quantity="%s" Price="%s" Total="%s"' % (
b["Quantity"] if b["Quantity"] is not None else 0,
b["Price"] if b["Price"] is not None else 0,
b["Total"] if b["Total"] is not None else 0)
if b["src_remark"]:
a += ' Remark="%s"' % _esc(b["src_remark"])
t = "<" + tag + a + ">"
return t + "".join(norms_xml) + "</" + tag + ">"
def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
"""一份单位工程 xml 的手术。
uwkey = (uwNumber, uwName)——与文件里 <UnitWorks Number Name> 匹配
pairs = {"item": [(源序位, bill)], "prelim": [...]} # x_new 不在内;顺序=文件序
news = {"item": [bill...], "prelim": [...]} # x_new 行(bill["_anchor"]=锚点源序位)
norms_by_bill = {bill_id: {"source": [norm...], "append": [norm...]}} # 与文件/插入序一致
res_by_norm = {norm_id: [(code, qty), ...]}
"""
def uv(mk):
return (_attr(mk["uw"], "Number"), _attr(mk["uw"], "Name"))
edits = [] # (start, end, replacement)
blocks = _scan_bills(txt)
norm_tmpl = _full_norm_template(txt)
for kind, tag, close in (("item", "WorkElement", _CLOSE_WE),
("prelim", "UnitWorksPreliminaryWorkElement", _CLOSE_PRE)):
pairs_k = pairs.get(kind) or []
fblocks = [mk for mk in blocks if mk["tag"] == tag and uv(mk) == uwkey]
if not pairs_k and not (news.get(kind) or []):
continue
if len(fblocks) != len(pairs_k):
continue # 数对不上:这一组整体不动(护栏)
paired = list(zip(pairs_k, fblocks)) # [((源序位, bill), 文件块)]
for (srcpos, b), mk in paired:
if b["x_tdel"]:
edits.append((mk["s"], mk["end"], ""))
continue
# 字段差异回写(只动开标签;决策 73 主人定「按最小的替代方式」:
# 原来没有的属性不凭空新增(避免 Attr=""/Remark="" 这类扩大修改),
# 数值型属性按数值比较(源文件 3803.180 与会话 3803.18 不算改动,不重写格式))
newtag = mk["opentag"]
for attr, col in (("Name", "Name"), ("Attr", "Attr"), ("Unit", "Unit"),
("Quantity", "Quantity"), ("Remark", "src_remark")):
want = b["src_remark"] if col == "src_remark" else b[col]
if want is None:
continue # 会话没值的字段不回写(写 "None" 反而是破坏)
cur = _attr(newtag, attr)
if cur is None:
if want:
newtag = _attr_set(newtag, attr, want)
elif attr == "Quantity" and _num_eq(cur, want):
continue
elif attr in ("Attr", "Remark", "Name") and _ws_eq(cur, want):
continue
elif want != cur:
newtag = _attr_set(newtag, attr, want)
if newtag != mk["opentag"]:
edits.append((mk["s"], mk["e"], newtag))
# 定额:源定额 ↔ 块内 Norm 一一对应;追加定额插块尾
nb = norms_by_bill.get(b["id"], {})
nsrc, napp = nb.get("source") or [], nb.get("append") or []
nspans = _norm_spans(txt[mk["s"]:mk["end"]])
if len(nspans) == len(nsrc):
for nsp, nn in zip(nspans, nsrc):
s0, e0 = nsp["s"] + mk["s"], nsp["end"] + mk["s"]
if nn["x_tdel"]:
edits.append((s0, e0, ""))
continue
newn = nsp["opentag"]
for attr in ("Name", "Quantity"):
if nn[attr] is None or (attr == "Quantity" and _num_eq(_attr(newn, attr), nn[attr])):
continue
if _attr(newn, attr) != nn[attr]:
newn = _attr_set(newn, attr, nn[attr])
if newn != nsp["opentag"]:
edits.append((s0, nsp["e"] + mk["s"], newn))
if napp:
tmpl = norm_tmpl
for nsp in nspans: # 同清单自己的定额优先(上下文最贴近)
if ' NormIdentity="' in nsp["opentag"]:
tmpl = nsp["opentag"]
break
ci = mk["end"] - len(close)
edits.append((ci, ci, "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl)
for nn in napp)))
# 新增清单:锚点块之后插入(锚点=源序位;同锚点按传入序依次跟随)
srcpos_of = {id(mk): sp for (sp, _b), mk in paired}
for b in news.get(kind) or []:
tgt = None
for mk in fblocks:
if srcpos_of.get(id(mk)) == b.get("_anchor"):
tgt = mk
break
if tgt is None:
tgt = fblocks[-1]
tmpl = norm_tmpl
for nsp in _norm_spans(txt[tgt["s"]:tgt["end"]]):
if ' NormIdentity="' in nsp["opentag"]:
tmpl = nsp["opentag"]
break
norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl)
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
edits.append((tgt["end"], tgt["end"],
_bill_xml(b, tgt["tag"], norms_xml, tgt["opentag"])))
# 自底向上应用(span 互不重叠:开标签补丁/定额块删除/闭合前插入各占各的区间)
for s, e, rep in sorted(edits, key=lambda x: (x[0], x[1]), reverse=True):
txt = txt[:s] + rep + txt[e:]
return txt
# ---------------------------------------------------------------- 单位工程 xml 的汇总节点(决策 74,主人口径 5.1/5.2/5.3)
def _full_summary_template(txt):
"""文件里第一条属性齐全的工料机汇总开标签(作克隆模板,32 属性形态)。
与清单/定额同理:属性残缺的汇总行有整包被广联达拒绝的风险——
采纳新增品类行必须按源文件同款字段全集落盘。"""
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
def _summary_node(fields, template=None):
"""一条工料机汇总节点。fields=(code,name,spec,unit,qty,taxrate,ntp,taxp,kind)。
优先克隆源文件汇总行的完整属性集再覆盖会话值;新行无组成子节点 → 自闭合。"""
c, nm, sp, un, q, rt, np_, tp, kd = fields
if template:
tag = _clone_open_tag(template)
for k, v in (("Number", c), ("Name", nm), ("Specification", sp), ("Unit", un),
("Quantity", q), ("TaxRate", rt), ("NoTaxPrice", np_), ("TaxPrice", tp),
("Kind", kd)):
tag = _attr_set(tag, k, "" if v is None else v)
return tag[:-1] + "/>"
return ('<LabourMaterialsEquipmentsMachinesSummary Number="%s" Name="%s" Specification="%s" Unit="%s"'
' Quantity="%s" TaxRate="%s" NoTaxPrice="%s" TaxPrice="%s" Kind="%s"/>' % (
_esc(c), _esc(nm), _esc(sp), _esc(un),
"" if q is None else q, "" if rt is None else rt,
"" if np_ is None else np_, "" if tp is None else tp, "" if kd is None else kd))
def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, recode_children=None):
"""本单位工程的工料机汇总 = 单价被查找的对象(主人口径 5.1/5.3):
①采纳新增的品类行追加到本单位汇总末尾(克隆完整属性集);
②合并改价按编码写回本单位汇总节点(除税/税率/含税,只动不一致项)——
2026-10-15 起**先追加后改价**:采纳新增行的价格来自入库项目参考价,
合并价必须同样落到它头上,否则同一编码在项目级与单位级两价(环山路实测踩坑)。
③规格 第11/12 条(2026-10-16):合并改码——被合并码节点 Number 换成保留码(母数据只替换
编码),其子级组成元素**全字段重建**为保留行子级(子数据全部字段替换,主人纠偏定稿)。
放在改价之后执行:改价按保留码找节点,别让刚改码的节点被二次命中。"""
tmpl = _full_summary_template(txt)
if added_rows:
nodes = "".join(_summary_node(r, tmpl) for r in added_rows)
last = None
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*/>', txt):
last = m
if last is not None:
txt = txt[:last.end()] + nodes + txt[last.end():]
for code, (ntp, rate, taxp) in (price_updates or {}).items():
span = _find_summary_span(txt, 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:
txt = txt[:s0] + newtag + txt[e0:]
return _apply_recode(txt, recode_map, recode_children)
def _apply_recode(txt, recode_map, recode_children):
"""被合并码 → 保留码:节点 Number 换码(母数据只替换编码);带子级组成的节点把子级
元素整体重建为保留行子级(Number/Quantity 等全字段按保留行来,属性集沿用原子级模板——
子级元素本身只携带 Number/Express/Quantity/Remark,名称规格单位价格按子编码从汇总行解析)。
本单位没有该码节点时不动;数据来自 s_settings(api_lme_merge 落库)。"""
for old, new in (recode_map or {}).items():
if old == new:
continue
span = _find_summary_span(txt, str(old))
if not span:
continue
s0, e0, bend, opentag = span
newtag = _attr_set(opentag, "Number", str(new))
rows = (recode_children or {}).get(str(old)) or []
if rows:
kids = re.findall(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>', txt[e0:bend])
tmpl = kids[0] if kids else \
'<LabourMaterialsEquipmentsMachinesElement Number="" Express="1.0000" Quantity="0.0000" Remark=""/>'
newkids = "".join(_child_node(tmpl, c, q) for (c, q) in rows)
txt = txt[:s0] + newtag + newkids + "</" + _SUM_TAG + ">" + txt[bend:]
else:
# 无子级替换数据(childless 合并或本单位节点无组成):只换码
txt = txt[:s0] + newtag + txt[e0:]
return txt
def _child_node(tmpl, code, qty):
"""按模板重建一条子级组成元素:Number=保留行子编码、Quantity=保留行含量(其余属性随模板)。"""
t = _attr_set(tmpl, "Number", str(code))
try:
t = _attr_set(t, "Quantity", "%.4f" % float(qty))
except (TypeError, ValueError):
pass
return t
# ---------------------------------------------------------------- Project.xml
_SUM_TAG = "LabourMaterialsEquipmentsMachinesSummary"
def _find_summary_span(txt, code):
"""按编码找工料机汇总节点,返回 (起点, 开标签止, 块止, 开标签);没有返回 None。
⚠️ 台班/配合比的汇总节点带子节点(组成),不是自闭合——必须成对匹配(决策 76 实测踩坑:
此前只匹配自闭合 `/>` 形态,台班类的改价全部漏写)。
⚠️⚠️ 自闭合判断必须是 `/>`(2026-10-16 修):`endswith("/")` 恒 False(e 指向 `>` 之后),
自闭合节点会借后面成对节点的闭标签撑出一个越界 span——改价只写开标签侥幸没事,
按块删除(隐藏行省略)会连后面节点一起删掉。"""
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
opentag = txt[m.start():e]
if _attr(opentag, "Number") != code:
continue
if opentag.endswith("/>"):
return (m.start(), e, e, opentag)
ce = txt.find("</" + _SUM_TAG + ">", e)
if ce < 0:
continue
return (m.start(), e, ce + len("</" + _SUM_TAG + ">"), opentag)
return None
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
sync_rows = [(编码,名称,规格,单位,除税价,税率,含税价), ...](会话侧项目级汇总现值,全量传入)。
同步规则:编码命中 → 只更新 名称/规格/单位/除税价/税率/含税价 **不一致** 的字段(最小替代);
编码缺失(采纳新增品类)→ 由 added_summaries 追加。隐藏行照旧省略。"""
for code in hidden_codes or []:
span = _find_summary_span(txt, str(code))
if span:
txt = txt[:span[0]] + txt[span[2]:]
if added_summaries:
# 采纳新增行先落位(2026-10-15 环山路实测:先追加后同步,合并/同步价才能覆盖到新增行)
tmpl = _full_summary_template(txt)
# added_summaries 元组序 (码,名,规格,单位,类别,量,税率,除税,含税) → 汇总节点按规范序重排
nodes = "".join(
_summary_node((c, nm, sp, un, q, rt, np_, tp, kd), tmpl)
for (c, nm, sp, un, kd, q, rt, np_, tp) in added_summaries)
last = None
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
if txt[e - 1] == "/":
last = (m.start(), e)
else:
ce = txt.find("</" + _SUM_TAG + ">", e)
if ce < 0:
continue
last = (m.start(), ce + len("</" + _SUM_TAG + ">"))
if last is not None:
txt = txt[:last[1]] + nodes + txt[last[1]:]
else:
txt = txt.replace("</ConstructionProject>", nodes + "</ConstructionProject>")
for (code, name, spec, unit, ntp, rate, taxp) in (sync_rows or []):
span = _find_summary_span(txt, 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
if attr in ("NoTaxPrice", "TaxRate", "TaxPrice") and _num_eq(cur, want):
continue
if attr in ("Name", "Specification", "Unit") and (cur or "").strip() == (want or "").strip():
continue
if want != cur:
newtag = _attr_set(newtag, attr, want)
if newtag != opentag:
txt = txt[:s0] + newtag + txt[e0:]
return txt
# ---------------------------------------------------------------- 主入口
class _RawNameZipInfo(zipfile.ZipInfo):
"""保真条目名:源包里的 GBK 条目名被 zipfile 读成 cp437 串,直接 writestr 会被再编码成
UTF-8 字节(主人实测:单位工程名全部变乱码、广联达打不开)。这里强制按 cp437 编回原始字节
(UTF-8 条目名 encode cp437 失败时自动回退 utf-8+标志位,同样保真)。"""
def _encodeFilenameFlags(self):
try:
return self.filename.encode("cp437"), 0
except UnicodeEncodeError:
return self.filename.encode("utf-8"), 0x800
def _source_ext(src_name):
"""按源文件名取**原后缀**(保留原大小写)——约定「按原格式导出」:
.cos4 进 .cos4 出;今后新格式(.cos5 / 任何 .xxx)只要能导入,导出就跟原格式,
不写死两种(2026-10-15 主人指出环山路 .cos4 出成 .cos 的违约)。
无后缀(裸哈希等自愈没找回原名的历史残留)退 .cos 维持旧行为。"""
m = re.search(r"(\.[A-Za-z0-9]+)$", (src_name or "").strip())
return m.group(1) if m else ".cos"
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):
"""src_bytes=原文件字节;unit_plans={uw键(Number,Name): plan};
plan={"pairs":{...}, "news":{...}, "norms_by_bill":{...}, "added_lme":[(码,名,规格,单位,量,税率,除税,含税,类别)]}。
recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出)。
返回 (新zip字节, 建议文件名)。"""
ext = _source_ext(src_name)
out_name = (proj_name or "工程") + "-审核版" + ext
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
zout = io.BytesIO()
with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo:
for item in zin.infolist():
raw = zin.read(item.filename)
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)
raw = _encode(txt, enc)
else:
# 单位工程 xml:按内容里的 UnitWorks(Number,Name) 认领计划——
# zip 条目名是 GBK 乱码、不可靠;一个包内可能多个 uw,逐个应用
txt, enc = _decode(raw)
if "<WorkElement" in txt or "<UnitWorksPreliminaryWorkElement" in txt:
keys = []
for m in re.finditer(r'<UnitWorks\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
ot = txt[m.start():e]
k = (_attr(ot, "Number") or "", _attr(ot, "Name") or "")
if k in unit_plans and k not in keys:
keys.append(k)
for k in keys:
plan = unit_plans[k]
txt = transform_unit(txt, k, plan["pairs"], plan["news"],
plan["norms_by_bill"], res_by_norm)
# 决策 74(主人口径 5.1/5.2/5.3):本单位汇总=被查找对象——
# 同步行按编码写回本单位汇总(改价/名称规格单位不一致项);采纳新增品类行追加进本单位汇总
added_rows = []
for k in keys:
added_rows.extend(unit_plans[k].get("added_lme") or [])
# 单位汇总只接受**合并改价**(被查找对象的精准更新),
# 全字段 sync 是项目级的事——否则零编辑也会大面积误改(已实测踩坑)
upd = {c: v for c, v in (price_updates or {}).items()}
if upd or added_rows:
txt = transform_unit_summaries(txt, upd, added_rows, recode_map, recode_children)
raw = _encode(txt, enc)
# 条目名按原始字节保真回写(修单位工程名乱码)
zi = _RawNameZipInfo(item.filename, date_time=item.date_time)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = item.external_attr
zi.create_system = item.create_system
zo.writestr(zi, raw)
return zout.getvalue(), out_name

View File

@@ -170,13 +170,16 @@ def parse_std(path, out):
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))])
# 决策 69(批次C):lme_proj 增采 TaxRate——合并工料机弹框的「税率」字段要真值
# (此前认为源汇总节点无此属性,实测有:横琴 0、南屏 16.52 等都能采到)
out.setdefault("lme_proj", {}).setdefault(_c, [
(sm.attrib.get("Name") or "").strip(),
(sm.attrib.get("Specification") or "").strip(),
(sm.attrib.get("Unit") or "").strip(),
f(sm.attrib.get("Kind")),
f(sm.attrib.get("Quantity")),
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice"))])
f(sm.attrib.get("NoTaxPrice")), f(sm.attrib.get("TaxPrice")),
f(sm.attrib.get("TaxRate"))])
# 单项工程层(2026-09-30):两种新格式节点名不同,都试一遍,谁有取谁。
# 记下每个单项工程下挂哪些单位工程编号 —— 靠它把单位工程归到单项工程下。
for tag in ("DivisionalAndElementalProject", "SectionalWorks"):
@@ -617,10 +620,12 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
# 项目级工料机汇总(2026-10-07):Project.xml 原样入库,「原数据 → 工料机汇总」项目级读它
n_proj = 0
for _c, (_nm, _sp, _un, _kd, _q, _ntp, _taxp) in (out.get("lme_proj") or {}).items():
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 # 老结构兼容(理论不再出现)
try:
cur.execute("""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?,?)""", (bid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp))
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))
n_proj += cur.rowcount
except Exception as e:
print("项目级汇总入库失败 %s:%s" % (_c, e), flush=True)

View File

@@ -154,6 +154,23 @@ def restore_lme_remarks(con, sid):
return n
def migrate_remark_keys(con, old_src, new_src):
"""源文件换了(同名工程换文件重开,闸②同步 src_name 时调用):把 s_remarks 里挂在
旧 src_name 下的持久键平移到新键。rkey 是单向散列改不了,但每行存了明文分量
(src_key/uw_name/bill_no/bill_name/bill_unit,清单与工料机备注同构)——
按「内容分量不变、只换源文件分量」重算即可:内容还对得上的备注跨文件版本存活,
内容已变的自然失配(内容键的本意)。返回平移条数。"""
n = 0
for r in con.execute("SELECT id, uw_name, bill_no, bill_name, bill_unit FROM s_remarks WHERE src_key=?",
(old_src,)).fetchall():
nk = rkey(new_src, r["uw_name"], r["bill_no"], r["bill_name"], r["bill_unit"])
con.execute("""UPDATE s_remarks SET src_key=?, rkey=? WHERE id=?
AND NOT EXISTS(SELECT 1 FROM s_remarks WHERE rkey=?)""",
(new_src, nk, r["id"], nk))
n += 1
return n
# 「重新解析」时**刻意保留**的表(跨解析存在的人为数据/配置)。
# ⚠️ 语义反转的防呆清单:新表**默认被清**,要保留必须显式加进来并写明理由——
# 反过来维护"要删的表清单"已经两次漏表(2026-09-30 s_sections、2026-10-10 s_lme_res)。
@@ -534,9 +551,11 @@ def open_project(con, files, meta, job, sid=None):
# 2026-10-07:项目级工料机汇总(s_lme_proj)——Project.xml 原样入库,
# 「原数据 → 工料机汇总」项目级读这里(与原版软件同源)
for _c, (_nm, _sp, _un, _kd, _q, _ntp, _taxp) in (out.get("lme_proj") or {}).items():
cur.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?,?)""", (sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp))
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))
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
if ptotal is not None or pinfo or pfeat:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? WHERE id=?",