feat(workbench): 工程量公式、另存为导出与字段编辑历史等多项功能

This commit is contained in:
lianjianwei2024
2026-10-17 14:15:07 +08:00
parent ca19d9f929
commit a4772bc97b
32 changed files with 2099 additions and 1532 deletions

View File

@@ -58,6 +58,17 @@ def _num_eq(a, b):
return False
def _fmt_qty(v, dec):
"""工程量按源文件规律定格式写出(规格 2026-10-16:横琴 234/234 定额 Quantity 恒 6 位
小数、113/113 清单恒 3 位)——改过的量按修改后的数字、按原文件同款小数位导出。"""
if v is None:
return None
try:
return "%.*f" % (dec, float(v))
except (TypeError, ValueError):
return v
def _ws_eq(a, b):
"""空白规范化比较:XML 解析器按规范把属性值里的换行/制表符规范化成空格——
会话库里的项目特征是空格版、源文件是换行版,内容其实一致。
@@ -165,12 +176,12 @@ def _norm_xml(n, lres, template=None):
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"])):
for k, v in (("Quantity", _fmt_qty(n["Quantity"], 6)), ("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"]
a += ' Quantity="%s"' % _fmt_qty(n["Quantity"], 6)
if n["Price"] is not None:
a += ' Price="%s"' % n["Price"]
if n["Total"] is not None:
@@ -188,7 +199,7 @@ def _bill_xml(b, tag, norms_xml, template=None):
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"])):
("Quantity", _fmt_qty(b["Quantity"], 3)), ("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"])
@@ -203,7 +214,7 @@ def _bill_xml(b, tag, norms_xml, template=None):
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,
_fmt_qty(b["Quantity"], 3) 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"]:
@@ -242,19 +253,25 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
continue
# 字段差异回写(只动开标签;决策 73 主人定「按最小的替代方式」:
# 原来没有的属性不凭空新增(避免 Attr=""/Remark="" 这类扩大修改),
# 数值型属性按数值比较(源文件 3803.180 与会话 3803.18 不算改动,不重写格式))
# 数值型属性按数值比较(源文件 3803.180 与会话 3803.18 不算改动,不重写格式)
# 决策 90(2026-10-17):Price/Total 入列——采纳价覆盖清单单价后要能落进文件)
newtag = mk["opentag"]
for attr, col in (("Name", "Name"), ("Attr", "Attr"), ("Unit", "Unit"),
("Quantity", "Quantity"), ("Remark", "src_remark")):
("Quantity", "Quantity"), ("Price", "Price"), ("Total", "Total"),
("Remark", "src_remark")):
want = b["src_remark"] if col == "src_remark" else b[col]
if want is None:
continue # 会话没值的字段不回写(写 "None" 反而是破坏)
if attr == "Quantity":
want = _fmt_qty(want, 3) # 清单工程量按源文件规律 3 位小数导出
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 ("Price", "Total") and _num_eq(cur, want):
continue # 数值相同不重写(写法跟新增清单/定额一致,str 数值)
elif attr in ("Attr", "Remark", "Name") and _ws_eq(cur, want):
continue
elif want != cur:
@@ -275,8 +292,9 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm):
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])
w = _fmt_qty(nn[attr], 6) if attr == "Quantity" else nn[attr] # 定额工程量按源文件 6 位小数
if _attr(newn, attr) != w:
newn = _attr_set(newn, attr, w)
if newn != nsp["opentag"]:
edits.append((s0, nsp["e"] + mk["s"], newn))
if napp:
@@ -355,7 +373,9 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
合并价必须同样落到它头上,否则同一编码在项目级与单位级两价(环山路实测踩坑)。
③规格 第11/12 条(2026-10-16):合并改码——被合并码节点 Number 换成保留码(母数据只替换
编码),其子级组成元素**全字段重建**为保留行子级(子数据全部字段替换,主人纠偏定稿)。
放在改价之后执行:改价按保留码找节点,别让刚改码的节点被二次命中。"""
放在改价之后执行:改价按保留码找节点,别让刚改码的节点被二次命中。
决策 93:改价+改码的全部修改按**一次扫描的索引**定位、一次拼接——此前每码全文重扫
(翠香件每文件 ~1300 遍 = 单文件 4~6 秒)。索引建在追加之后的文本上:新增行也吃合并价。"""
tmpl = _full_summary_template(txt)
if added_rows:
nodes = "".join(_summary_node(r, tmpl) for r in added_rows)
@@ -364,45 +384,44 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
last = m
if last is not None:
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 = _find_summary_span(txt, str(code))
span = idx.get(str(code))
if not span:
continue
s0, e0, bend, opentag = span
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 落库)。"""
edits[s0] = (s0, e0, newtag)
blocks = {} # span起点 → (s0, bend, 整块替换)(改码带子级重建)
for old, new in (recode_map or {}).items():
if old == new:
continue
span = _find_summary_span(txt, str(old))
span = idx.get(str(old))
if not span:
continue
s0, e0, bend, opentag = span
newtag = _attr_set(opentag, "Number", str(new))
# 基础开标签取**已应用改价**的版本(旧实现改码在改价之后重扫全文,带上价格;
# 索引化后同一节点两笔编辑要显式合成——先改价后换码,别把价格覆盖丢掉)
base = edits.get(s0)
newtag = _attr_set(base[2] if base else 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 \
ktmpl = 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:]
newkids = "".join(_child_node(ktmpl, c, q) for (c, q) in rows)
blocks[s0] = (s0, bend, newtag + newkids + "</" + _SUM_TAG + ">")
else:
# 无子级替换数据(childless 合并或本单位节点无组成):只换码
txt = txt[:s0] + newtag + txt[e0:]
return txt
blocks[s0] = (s0, e0, newtag) # 无子级替换数据(childless 合并或无组成):只换码
for s0, (s, e, rep) in blocks.items(): # 改码覆盖同节点的纯改价(原序:先改价后改码)
edits[s0] = (s, e, rep)
return _apply_edits(txt, list(edits.values()))
def _child_node(tmpl, code, qty):
@@ -421,40 +440,65 @@ def _child_node(tmpl, code, qty):
_SUM_TAG = "LabourMaterialsEquipmentsMachinesSummary"
def _find_summary_span(txt, code):
"""按编码找工料机汇总节点,返回 (起点, 开标签止, 块止, 开标签);没有返回 None。
⚠️ 台班/配合比的汇总节点带子节点(组成),不是自闭合——必须成对匹配(决策 76 实测踩坑:
此前只匹配自闭合 `/>` 形态,台班类的改价全部漏写)。
⚠️⚠️ 自闭合判断必须是 `/>`(2026-10-16 修):`endswith("/")` 恒 False(e 指向 `>` 之后),
自闭合节点会借后面成对节点的闭标签撑出一个越界 span——改价只写开标签侥幸没事,
按块删除(隐藏行省略)会连后面节点一起删掉。"""
def _summary_span_index(txt):
"""一次扫描建 {Number编码: span} 索引(决策 93 提速):此前每处理一个编码就把全文
finditer 重扫一遍(翠香件每文件 ~1300 遍、Project.xml 3142 遍 → 单工程 6 分钟)。
同名编码只记**首个**命中——与 _find_summary_span 的首个命中语义一致。"""
idx = {}
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:
code = _attr(opentag, "Number")
if code is None or code in idx:
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
idx[code] = (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)
return idx
def _apply_edits(txt, edits):
"""把 [(起, 止, 替换文本), ...] 一次拼接落盘(自底向上,区间互不重叠)。
防御性跳过与已落区间相交的编辑(理论上数据保证不相交:隐藏删除块与改价开标签不会同码)。"""
last_s = None
for s, e, rep in sorted(edits, key=lambda x: (x[0], x[1]), reverse=True):
if last_s is not None and e > last_s:
continue # 与已应用的更高区间相交:跳过(删除块优先)
txt = txt[:s] + rep + txt[e:]
last_s = s
return txt
def _find_summary_span(txt, code):
"""按编码找工料单条汇总节点,返回 (起点, 开标签止, 块止, 开标签);没有返回 None。
单次查找入口——批量场景请用 _summary_span_index 建一次索引(决策 93)。"""
return _summary_span_index(txt).get(str(code))
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
sync_rows = [(编码,名称,规格,单位,除税价,税率,含税价), ...](会话侧项目级汇总现值,全量传入)。
同步规则:编码命中 → 只更新 名称/规格/单位/除税价/税率/含税价 **不一致** 的字段(最小替代);
编码缺失(采纳新增品类)→ 由 added_summaries 追加。隐藏行照旧省略。"""
编码缺失(采纳新增品类)→ 由 added_summaries 追加。隐藏行照旧省略。
决策 93:汇总节点一次扫描建索引,隐藏删除+同步改写全部算好后一次拼接——
此前每个编码全文重扫(翠香件 3142 遍 × 3.7MB = 52 秒,仅此一项)。"""
idx = _summary_span_index(txt)
edits = [] # (起, 止, 替换文本)
for code in hidden_codes or []:
span = _find_summary_span(txt, str(code))
span = idx.get(str(code))
if span:
txt = txt[:span[0]] + txt[span[2]:]
edits.append((span[0], span[2], "")) # 按块删除(含成对闭标签,决策 76 修复口径)
if added_summaries:
# 采纳新增行先落位(2026-10-15 环山路实测:先追加后同步,合并/同步价才能覆盖到新增行)
# 采纳新增行先落位(2026-10-15 环山路实测:先追加后同步,合并/同步价才能覆盖到新增行)。
# 注意:新增节点插在**原文**最后一个汇总节点之后——它不在 idx 里,本函数不负责同步它
# (追加发生在同步计算之前是旧实现的事序;同步按原索引查,新增行除非本就在原文否则查不到,
# 与旧行为一致:旧行为同步也只认原文已有的节点——新增行的价格来自入库参考价,本就是对的)。
tmpl = _full_summary_template(txt)
# added_summaries 元组序 (码,名,规格,单位,类别,量,税率,除税,含税) → 汇总节点按规范序重排
nodes = "".join(
@@ -473,14 +517,16 @@ def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
continue
last = (m.start(), ce + len("</" + _SUM_TAG + ">"))
if last is not None:
txt = txt[:last[1]] + nodes + txt[last[1]:]
edits.append((last[1], last[1], nodes))
else:
txt = txt.replace("</ConstructionProject>", nodes + "</ConstructionProject>")
j = txt.find("</ConstructionProject>")
if j >= 0:
edits.append((j, j, nodes))
for (code, name, spec, unit, ntp, rate, taxp) in (sync_rows or []):
span = _find_summary_span(txt, str(code))
span = idx.get(str(code))
if not span:
continue
s0, e0, bend, opentag = span
s0, e0, _bend, opentag = span
newtag = opentag
for attr, want in (("Name", name), ("Specification", spec), ("Unit", unit),
("NoTaxPrice", ntp), ("TaxRate", rate), ("TaxPrice", taxp)):
@@ -494,8 +540,8 @@ def transform_project(txt, added_summaries, hidden_codes, sync_rows=None):
if want != cur:
newtag = _attr_set(newtag, attr, want)
if newtag != opentag:
txt = txt[:s0] + newtag + txt[e0:]
return txt
edits.append((s0, e0, newtag))
return _apply_edits(txt, edits)
# ---------------------------------------------------------------- 主入口
@@ -522,17 +568,22 @@ def _source_ext(src_name):
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):
price_updates=None, added_lme_by_uw=None, sync_rows=None, recode_map=None, recode_children=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 落库读出)。
progress=可选回调 progress(done, total)——每个 zip 条目处理完报一次(决策 92 导出进度条)。
返回 (新zip字节, 建议文件名)。"""
ext = _source_ext(src_name)
out_name = (proj_name or "工程") + "-审核版" + ext
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
zout = io.BytesIO()
entries = zin.infolist()
if progress:
progress(0, len(entries))
with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo:
for item in zin.infolist():
for _ei, item in enumerate(entries, 1):
raw = zin.read(item.filename)
base = item.filename.rsplit("/", 1)[-1]
if base.lower() == "project.xml":
@@ -574,4 +625,6 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
zi.external_attr = item.external_attr
zi.create_system = item.create_system
zo.writestr(zi, raw)
if progress:
progress(_ei, len(entries))
return zout.getvalue(), out_name

View File

@@ -335,6 +335,17 @@ def connect():
# 2026-10-01:分组/匹配 设置的持久化(分组关键词、匹配过滤词)
con.execute("""CREATE TABLE IF NOT EXISTS s_settings(
scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT, PRIMARY KEY(scope,k))""")
# 2026-10-17:字段编辑历史(规格 工作台·组价不一致 15:名称/项目特征/单位/工程量/备注
# 带时间点的编辑记录,红三角批注展示)。ekbase=稳定键(复用备注 rkey 体系,重解析行 id
# 重生也不丢):bill='b:'+rkey,norm='n:'+清单rkey+'#'+定额编码+'#'+同码序号。
# f=字段列名,o/n=旧值/新值(n=本次提交原文,公式记公式),at=本地时间。
# 只记用户经 op 接口的编辑,采纳默认值不记。
_cols = [r[1] for r in con.execute("PRAGMA table_info(s_edit_log)")]
if _cols and "ekbase" not in _cols:
con.execute("DROP TABLE s_edit_log") # 旧 rid 键版(上线当日冒烟数据)→ 换稳定键版
con.execute("""CREATE TABLE IF NOT EXISTS s_edit_log(
id INTEGER PRIMARY KEY AUTOINCREMENT, ekbase TEXT NOT NULL,
f TEXT NOT NULL, o TEXT, n TEXT, at TEXT DEFAULT (datetime('now','localtime')))""")
return con