fix(manual): 手工导出骨架与导入边界修复,单位按目录自然序排列
- 上传口骨架收集改为空操作,骨架仅经升级入库(决策 231/补记十四) - s_lme_lib 价格快照垫底,修手工会话组成子行价格落 0 - 导出编辑相交消解:删除块与闭合前插入冲突时重映射,防采纳定额丢失/碎 XML - _span 识别自闭合标签,防容器配对失败留孤儿闭合 - 手工导入放开空名/同名/深层级校验 - 单位顺序改按左侧目录树序(单项入库序+组内编号自然序) - 补齐手工导出/导入/MCP 切换相关测试
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""经典整件骨架库(决策 229,2026-10-27 主人定):
|
||||
"""经典整件骨架库(决策 231,2026-10-27 主人定):
|
||||
|
||||
手工工程(无源文件,决策 119/230)没有「本项目原件」可当导出模板——把**经典项目的
|
||||
整件原件**收进骨架库当模板:结构字段相同(同签名)只存一件;每组保留**最全**的代表
|
||||
@@ -16,6 +16,8 @@
|
||||
存储:history.db classic_skel 一组一行(连代表件原件字节存库,不随会话清理)。
|
||||
"""
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@@ -92,40 +94,120 @@ def extract(path):
|
||||
return {"sig": sig, "suffix": suf, "n_shapes": len(shapes), "n_nodes": n_nodes}
|
||||
|
||||
|
||||
def _decode(raw):
|
||||
m = re.match(rb'^\s*<\?xml[^>]*encoding="([^"]*)"', raw[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
try:
|
||||
return raw.decode(enc, errors="replace")
|
||||
except Exception:
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def collect(con, sha, path, name=""):
|
||||
"""上传口统一入口:抽取并按组收代表。返回 'new'/'rep'/'old'/None
|
||||
(新组 / 更全顶掉旧代表 / 平手取最新 / 比代表瘦没动 / 不成组)。
|
||||
⚠️ con=history.db 连接;失败绝不挡上传(调用方兜 try)。"""
|
||||
"""上传口骨架收集=**空操作**(补记十四,2026-10-28 主人定「后期不存骨架了,
|
||||
现有也只有 2 个骨架」):骨架只经升级(seed_frame)入库;上传什么原件都不进
|
||||
classic_skel,库里只保留已升级固定的骨架(COS4骨架G/Y…)。保留函数签名供上传口
|
||||
兼容调用。"""
|
||||
return None
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。
|
||||
补记五:专用骨架件(is_frame=1)优先于实项目件。"""
|
||||
_ensure_table(con)
|
||||
try:
|
||||
con.execute("SELECT is_frame FROM classic_skel LIMIT 1")
|
||||
except Exception:
|
||||
return dict(con.execute(
|
||||
"SELECT * FROM classic_skel WHERE suffix=? ORDER BY n_nodes DESC, "
|
||||
"extracted_at DESC LIMIT 1", (suffix,)).fetchone() or ())
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY is_frame DESC, n_nodes DESC, extracted_at DESC
|
||||
LIMIT 1""", (suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def seed_frame(con, path, name):
|
||||
con.row_factory = sqlite3.Row
|
||||
"""升级添加骨架(补记十二,主人定:骨架只经升级进库、上传口不自动收;命名不带
|
||||
软件名——COS4骨架G/Y、COS骨架G/Y…)。同名骨架=升级替换(重写签名/字节);
|
||||
新名=新增固定骨架。返回 sig;解析失败返回 None。"""
|
||||
info = extract(path)
|
||||
if not info:
|
||||
return None
|
||||
_ensure_table(con)
|
||||
row = con.execute("SELECT n_nodes, extracted_at FROM classic_skel WHERE sig=?",
|
||||
(info["sig"],)).fetchone()
|
||||
if row is not None and info["n_nodes"] < (row["n_nodes"] or 0):
|
||||
return "old" # 不如代表全:不收(主人定:取最全)
|
||||
_cols = {r[1] for r in con.execute("PRAGMA table_info(classic_skel)")}
|
||||
if "is_frame" not in _cols:
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN is_frame INTEGER DEFAULT 0")
|
||||
old = con.execute("SELECT sig FROM classic_skel WHERE original_name=?", (name,)).fetchone()
|
||||
if old and old["sig"] != info["sig"]:
|
||||
con.execute("DELETE FROM classic_skel WHERE original_name=?", (name,))
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
|
||||
n_shapes,n_nodes,blob,extracted_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
n_shapes,n_nodes,blob,extracted_at,is_frame)
|
||||
VALUES(?,?,?,?,?,?,?,?,1)
|
||||
ON CONFLICT(sig) DO UPDATE SET rep_sha=excluded.rep_sha,
|
||||
original_name=excluded.original_name, n_shapes=excluded.n_shapes,
|
||||
n_nodes=excluded.n_nodes, blob=excluded.blob,
|
||||
extracted_at=excluded.extracted_at""",
|
||||
(info["sig"], info["suffix"], sha, os.path.basename(name or path),
|
||||
extracted_at=excluded.extracted_at, is_frame=1""",
|
||||
(info["sig"], info["suffix"],
|
||||
hashlib.sha256(blob).hexdigest(), name,
|
||||
info["n_shapes"], info["n_nodes"], blob, _now()))
|
||||
con.commit() # sqlite3 隐式事务:不提交=连接关闭即回滚(DDL 却即时生效)
|
||||
return "new" if row is None else "rep"
|
||||
con.commit()
|
||||
return info["sig"]
|
||||
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。"""
|
||||
def _shapes_of_blob(blob):
|
||||
"""整包字节 → 结构形态集合(与 extract 同口径:标签+字段名集+有无子级)。"""
|
||||
shapes = set()
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, _n = _shapes_of_bytes(z.read(nm))
|
||||
shapes |= s
|
||||
except Exception:
|
||||
pass
|
||||
return shapes
|
||||
|
||||
|
||||
def pick_frame(con, suffix, src_path=None):
|
||||
"""导出骨架挑选(补记十二,主人定「按字段最近的一个」):
|
||||
①该后缀的固定骨架(is_frame=1,可多件并存)里有源文件可比 → 结构字段集 Jaccard
|
||||
相似度最高者;②无源文件(手工工程)/比不了 → 最近收藏的骨架(extracted_at 最新,
|
||||
即主人最后指定的那件)。没有固定骨架 → 退 rep_for(老行为)。"""
|
||||
_ensure_table(con)
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY n_nodes DESC, extracted_at DESC LIMIT 1""",
|
||||
(suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
try:
|
||||
frames = con.execute("SELECT * FROM classic_skel WHERE suffix=? AND is_frame=1",
|
||||
(suffix,)).fetchall()
|
||||
except Exception:
|
||||
frames = []
|
||||
if not frames:
|
||||
return rep_for(con, suffix)
|
||||
if len(frames) == 1:
|
||||
return dict(frames[0])
|
||||
if src_path and os.path.exists(src_path):
|
||||
try:
|
||||
with zipfile.ZipFile(src_path) as z:
|
||||
src_shapes = set()
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, _n = _shapes_of_bytes(z.read(nm))
|
||||
src_shapes |= s
|
||||
except Exception:
|
||||
src_shapes = set()
|
||||
if src_shapes:
|
||||
best, best_j = None, -1.0
|
||||
for f in frames:
|
||||
fsh = _shapes_of_blob(f["blob"])
|
||||
j = len(src_shapes & fsh) / max(1, len(src_shapes | fsh))
|
||||
if j > best_j:
|
||||
best, best_j = f, j
|
||||
if best is not None:
|
||||
return dict(best)
|
||||
return dict(max(frames, key=lambda f: (f["extracted_at"] or "", f["n_nodes"] or 0)))
|
||||
|
||||
|
||||
def stats(con):
|
||||
|
||||
@@ -258,6 +258,16 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
uwp = _uw_price_rows(sc, sid) # 决策 219:主取价源=单位级(每单位每码认第一行)
|
||||
away = _recode_away(sc, sid) # 决策 219:合并换码的旧码不显示
|
||||
uwp = {c: lst for c, lst in uwp.items() if c not in away}
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入)——手工会话没有源文件,
|
||||
# 单位级/项目级三步链全空,组成子行(折旧费/检修费…)价会落 0(2026-10-28 主人实测
|
||||
# 易达映射源里组成子行编制价全空);库快照垫在链条末尾
|
||||
lbm = {}
|
||||
try:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp "
|
||||
"FROM s_lme_lib WHERE session_id=?", (sid,)):
|
||||
lbm[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
except Exception:
|
||||
lbm = {}
|
||||
|
||||
# 决策 219 兜底:单位级行三价缺 → 项目级快照补(主人定「编号或单价实在没有的去项目级取」)
|
||||
for _c, _lst in uwp.items():
|
||||
@@ -272,7 +282,7 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
_r["taxp"] = _p["taxp"]
|
||||
|
||||
def child_px(code, uw=None):
|
||||
"""子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照兜底。"""
|
||||
"""子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照 → s_lme_lib 快照兜底。"""
|
||||
lst = uwp.get(code) or []
|
||||
r = None
|
||||
if uw is not None:
|
||||
@@ -281,9 +291,10 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
r = lst[0]
|
||||
p = pm.get(code) or {}
|
||||
_pk = lambda a, b: (a if a is not None else b)
|
||||
return (_pk(r and r["ntp"], p.get("ntp")),
|
||||
lb = lbm.get(code) or (None, None)
|
||||
return (_pk(_pk(r and r["ntp"], p.get("ntp")), lb[0]),
|
||||
_pk(r and r["taxrate"], p.get("taxrate")),
|
||||
_pk(r and r["taxp"], p.get("taxp")))
|
||||
_pk(_pk(r and r["taxp"], p.get("taxp")), lb[1]))
|
||||
|
||||
def computed_mother(code, uw=None):
|
||||
"""带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。"""
|
||||
@@ -305,6 +316,19 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
"""11 列行。r=认下的单位级行(或快照 dict);带子级母行 Σ 现算(除非覆盖)。"""
|
||||
p = pm.get(code) or {}
|
||||
ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp")
|
||||
# s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行
|
||||
# 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空)
|
||||
lb = lbm.get(code)
|
||||
if lb is not None:
|
||||
_nm2, _sp2, _un2, _kd2, _ln, _lt = lb
|
||||
if not (r.get("name") or "") and _nm2:
|
||||
r = dict(r, name=_nm2, spec=(r.get("spec") or _sp2 or ""),
|
||||
unit=(r.get("unit") or _un2 or ""),
|
||||
kind=(r.get("kind") if r.get("kind") is not None else _kd2))
|
||||
if ntp is None:
|
||||
ntp = _ln
|
||||
if taxp is None:
|
||||
taxp = _lt
|
||||
if kids.get(code) and not ov.get(code):
|
||||
cn, ct = computed_mother(code, r.get("uw_id"))
|
||||
if cn is not None:
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import zipfile
|
||||
@@ -589,6 +590,11 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
||||
paired = {} # 全量重排(含原已配平的 kind)
|
||||
for mk, (kind, sp, b) in zip(pool, bills_all):
|
||||
paired.setdefault(kind, []).append((sp, b, mk))
|
||||
if os.environ.get("EC_PAIR_DEBUG") and len(pool) != len(bills_all):
|
||||
print("EC_PAIR_DEBUG uw=%r pool=%d bills_all=%d left=%s fblocks=%s" % (
|
||||
uwkey[1][:12], len(pool), len(bills_all),
|
||||
{k: len(v) for k, v in (left or {}).items()},
|
||||
{k: len(v) for k, v in (fblocks_by or {}).items()}), flush=True)
|
||||
# 数量对不上:保留原配对(主路径 kind 照常;left kinds 整组跳过)
|
||||
|
||||
# ---- 动刀(主路径与兜底共用同一套编辑体)----
|
||||
@@ -836,9 +842,28 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
||||
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
|
||||
parts.append(_bill_xml(b, tgt["tag"], norms_xml, tmpl_blk or tgt["opentag"], txt=txt))
|
||||
edits.append((pos, pos, "".join(parts)))
|
||||
# 自底向上应用(span 互不重叠:开标签补丁/定额块删除/闭合前插入各占各的区间)
|
||||
# 专修(2026-10-28,三溪采纳语境实测):删除块与「闭合前插入」相交时,删除按原跨度
|
||||
# 会咬掉已插入的采纳定额(定额丢失+孤儿闭标签=碎 XML)——删除终点收到插入点。
|
||||
# 相交消解(专修二 2026-10-28):删除块内的插入点重映射到删除块起点——
|
||||
# 先删后插、坐标归一,采纳定额与临删删除都完整落地(截短/放任两种都碎,实测)。
|
||||
dels = sorted((s, e) for s, e, rep in edits if rep == "" and e > s)
|
||||
remapped = []
|
||||
for s, e, rep in edits:
|
||||
if rep and s == e:
|
||||
for ds, de in dels:
|
||||
if ds <= s < de:
|
||||
s = ds
|
||||
break
|
||||
remapped.append((s, e, rep))
|
||||
edits = remapped
|
||||
# 自底向上应用(span 互不重叠);
|
||||
# 防御性跳过与已落区间相交的编辑(与 _apply_edits 同款护栏——绝不产出碎 XML)。
|
||||
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
|
||||
|
||||
|
||||
@@ -990,11 +1015,58 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
|
||||
children_html=_child_block_html(txt, kmap.get(str(r[0]))),
|
||||
org=omap.get(str(r[0])))
|
||||
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():]
|
||||
# 插入锚(专修 2026-10-28,三溪实测 mismatched tag 根因):老 cos 族行标签也叫
|
||||
# …Summary 且散布全文件——「最后一个自闭合 Summary」会落在某条清单定额的消耗行
|
||||
# 中间,新增行插进定额块=碎 XML。老 cos 族(本件无 …Element 行)改为插进**直挂
|
||||
# UnitWorks 的单位级汇总容器**闭合前(同标签嵌套按深度配对找边界);cos4 族
|
||||
# (有 …Element 行)维持原锚(最后一个自闭合容器之后=根层追加)。
|
||||
ins_at = None
|
||||
if not re.search(r'<' + _LME + r'\b', txt):
|
||||
stack, pos2, n2, close_s = [], 0, len(txt), None
|
||||
while pos2 < n2:
|
||||
m2 = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos2)
|
||||
if not m2:
|
||||
break
|
||||
if m2.group(1) == "/":
|
||||
t2 = m2.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t2:
|
||||
del stack[i:]
|
||||
break
|
||||
pos2 = m2.end()
|
||||
continue
|
||||
tag2 = m2.group(2)
|
||||
oe2 = _open_tag_end(txt, m2.start())
|
||||
if oe2 < 0:
|
||||
break
|
||||
if txt[oe2 - 2:oe2] == "/>":
|
||||
pos2 = oe2
|
||||
continue
|
||||
if tag2 == _SUM_TAG and stack and stack[-1] == "UnitWorks":
|
||||
depth, p2 = 1, oe2
|
||||
while depth:
|
||||
m3 = re.compile(r"<%s\b|</%s\s*>" % (_SUM_TAG, _SUM_TAG)).search(txt, p2)
|
||||
if not m3:
|
||||
break
|
||||
depth += -1 if m3.group(0)[1] == "/" else 1
|
||||
p2 = m3.end()
|
||||
if depth == 0:
|
||||
break
|
||||
close_s = p2 - len("</%s>" % _SUM_TAG)
|
||||
pos2 = p2
|
||||
continue
|
||||
stack.append(tag2)
|
||||
pos2 = oe2
|
||||
if close_s is not None:
|
||||
ins_at = close_s
|
||||
if ins_at is not None:
|
||||
txt = txt[:ins_at] + nodes + txt[ins_at:]
|
||||
else:
|
||||
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():]
|
||||
idx = _summary_span_index(txt)
|
||||
edits = {} # span起点 → (起, 止, 替换)(同节点改价+改码合并为一条)
|
||||
foreign = _ident_foreign_spans(txt, idx, recode_ident) # 决策 178:同码异物节点先认领
|
||||
@@ -1209,6 +1281,7 @@ def _summary_span_index(txt):
|
||||
2026-10-22 主人拍板:同码多节点全改)。span=(起点, 开标签止, 块止, 开标签),
|
||||
块止对自闭合=开标签止;列表按文件序。"""
|
||||
idx = {}
|
||||
_elem_family = bool(re.search(r'<' + _LME + r'\b', txt)) # cos4 族有 …Element 行;老 cos 没有
|
||||
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
|
||||
e = _open_tag_end(txt, m.start())
|
||||
if e < 0:
|
||||
@@ -1226,8 +1299,24 @@ def _summary_span_index(txt):
|
||||
# 这个「块」必是假的(真块内不会再嵌 Summary)→ 按裸行处理,span 只算开标签。
|
||||
# 否则假块会吞进几万字符里的几十个节点:改码编辑与内层相交被 _apply_edits 丢弃
|
||||
# (换码失效)、_recode_norm_lme_rows 把吞进的元素行误当块内子级跳过(残留)。
|
||||
# 专修(2026-10-28,三溪实测 mismatched tag 根因):两族分治——老 cos 族行标签
|
||||
# 也叫 …Summary 且**合法嵌套**(带子级的行=同标签容器),首闭配对会把块界算到
|
||||
# 内层闭标签(换码/同名清扫切一半=碎 XML);无 …Element 行时改按深度配对找真块界。
|
||||
if ce < 0 or re.search(r'<' + _SUM_TAG + r'\b', txt[e:ce]):
|
||||
idx.setdefault(code, []).append((m.start(), e, e, opentag))
|
||||
if _elem_family:
|
||||
idx.setdefault(code, []).append((m.start(), e, e, opentag))
|
||||
else:
|
||||
depth, p2 = 1, e
|
||||
while depth:
|
||||
m2 = re.search(r'<' + _SUM_TAG + r'\b|</' + _SUM_TAG + r'\s*>', txt[p2:])
|
||||
if not m2:
|
||||
break
|
||||
depth += -1 if m2.group(0)[1] == "/" else 1
|
||||
p2 += m2.end()
|
||||
if depth == 0:
|
||||
break
|
||||
idx.setdefault(code, []).append(
|
||||
(m.start(), e, p2 if depth == 0 else e, opentag))
|
||||
else:
|
||||
idx.setdefault(code, []).append((m.start(), e, ce + len("</" + _SUM_TAG + ">"), opentag))
|
||||
return idx
|
||||
@@ -1253,7 +1342,15 @@ def _drop_zero_qty_summary_rows(txt):
|
||||
continue # 无 Quantity / 非数字 → 保守保留
|
||||
if q == 0:
|
||||
cuts.append((s0, bend if bend > s0 else e0))
|
||||
for s0, e0 in sorted(cuts, key=lambda x: x[0], reverse=True):
|
||||
# 专修(2026-10-28,三溪采纳语境 mismatched tag 根因):块界深度配对后,0 量母行的
|
||||
# 块内可能还有 0 量子行——两刀相叠、后刀按原跨度多切=碎 XML。并集处理(内层随母行走)。
|
||||
cuts.sort(key=lambda x: x[0])
|
||||
merged = []
|
||||
for s0, e0 in cuts:
|
||||
if merged and s0 < merged[-1][1]:
|
||||
continue
|
||||
merged.append((s0, e0))
|
||||
for s0, e0 in sorted(merged, key=lambda x: x[0], reverse=True):
|
||||
txt = txt[:s0] + txt[e0:]
|
||||
return txt
|
||||
|
||||
@@ -1441,7 +1538,11 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
|
||||
|
||||
def _apply_qty_updates(txt, qty_updates):
|
||||
"""决策 188:把现算数量写回单位文本的 Summary 节点(Quantity+四Total 锚定自算)。
|
||||
正则口径(金宝裸行也命中);未命中码不动。"""
|
||||
正则口径(金宝裸行也命中);未命中码不动。
|
||||
专修(2026-10-28,三溪实测碎标签根因):先收集全部命中、按位置**倒序一次应用**——
|
||||
原实现在 finditer 迭代同一 txt 的同时改写 txt,同码多节点时首个替换一变长,
|
||||
后续命中全按陈旧偏移落刀(<Labo<Labour… 碎标签,2/14 成员 XML 不合法)。"""
|
||||
edits = []
|
||||
for code, qv in (qty_updates or {}).items():
|
||||
try:
|
||||
qv = float(qv)
|
||||
@@ -1460,9 +1561,12 @@ def _apply_qty_updates(txt, qty_updates):
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if nt != t:
|
||||
txt = txt[:m.start()] + nt + txt[m.end():]
|
||||
edits.append((m.start(), m.end(), nt))
|
||||
for s, e, rep in sorted(edits, key=lambda x: x[0], reverse=True):
|
||||
txt = txt[:s] + rep + txt[e:]
|
||||
return txt
|
||||
|
||||
|
||||
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None, recode_map=None,
|
||||
recode_children=None, recode_ident=None, unit_texts=None, added_org=None):
|
||||
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工工程导出(决策 229,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
"""手工工程导出(决策 231,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
|
||||
口径(主人逐条拍板):
|
||||
· 骨架只在导出时用;内部数据只管采纳。单位工程→清单的计价信息按采纳数值,
|
||||
@@ -26,6 +26,7 @@ import zipfile
|
||||
|
||||
import classic_skeleton
|
||||
import export_cos as ec
|
||||
import dyn_lme
|
||||
from formats.skeleton import build_plan, num as _num
|
||||
|
||||
_LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
@@ -66,10 +67,20 @@ def _span(txt, tag, start=0):
|
||||
mn = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(txt, pos)
|
||||
if not mn:
|
||||
return None
|
||||
depth += -1 if mn.group(0)[1] == "/" else 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
if mn.group(0)[1] == "/":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
continue
|
||||
o2 = ec._open_tag_end(txt, mn.start())
|
||||
if o2 < 0:
|
||||
return None
|
||||
if txt[o2 - 2:o2] == "/>":
|
||||
pos = o2 # 自闭合同名子行=完整元素,不进深度(2026-10-28 修:
|
||||
continue # 合成件 Summary 子行把深度顶穿→容器配对 None→只删开标签留孤儿闭合)
|
||||
depth += 1
|
||||
pos = o2
|
||||
return None
|
||||
|
||||
|
||||
@@ -86,20 +97,10 @@ def _block_tag(blk):
|
||||
return m.group(1) if m else _ITEM_BILL
|
||||
|
||||
|
||||
def _zero_rows(frag):
|
||||
"""克隆架子清值第二遍:样板块里定额/工料机行的量价结果清零、含量式清空
|
||||
(_zero_results 不覆盖 Norm/LME 行本身——采纳链是整行换,用不到这一步)。"""
|
||||
def z(m):
|
||||
t = m.group(0)
|
||||
for k in ("Quantity", "Price", "Total"):
|
||||
t = re.sub(r"\b%s=\"[^\"]*\"" % k, lambda _m: k + "=\"0\"", t)
|
||||
return re.sub(r"\bExpress=\"[^\"]*\"", 'Express=""', t)
|
||||
return re.sub(r"<(?:Norm|LabourMaterialsEquipmentsMachinesElement)\b[^>]*?/?>", z, frag)
|
||||
|
||||
|
||||
def _manual_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
"""我方一条清单 → 整块:样板清单整块克隆(开标签全属性+费用构成汇总+定额/工料机
|
||||
架子),我方清单五值+特征+备注落槽(骨架没的槽不造,决策 198),架子值全清。
|
||||
def _frame_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
"""未采纳清单(231①,主人 2026-10-28 复确认「Excel 进来的清单导出 cos 要以 cos
|
||||
清单架子导出」):样板清单整块克隆(开标签全属性+费用构成汇总+定额/工料机架子),
|
||||
我方清单五值+特征+备注落槽(骨架没的槽不造,198),架子值全清——「还没组价」的形态。
|
||||
无样板 → 最小自闭合形态(决策 64 已知可行解)。"""
|
||||
if not sample_blk:
|
||||
a = ' Number="%s" Name="%s"' % (ec._esc(b.get("Number") or ""),
|
||||
@@ -126,9 +127,218 @@ def _manual_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
inner = sample_blk[len(opentag):]
|
||||
if inner.endswith(close):
|
||||
inner = inner[: -len(close)]
|
||||
|
||||
def _zero_rows(frag):
|
||||
def z(m):
|
||||
t2 = m.group(0)
|
||||
for k in ("Quantity", "Price", "Total"):
|
||||
t2 = re.sub(r"\b%s=\"[^\"]*\"" % k, lambda _m: k + "=\"0\"", t2)
|
||||
return re.sub(r"\bExpress=\"[^\"]*\"", 'Express=""', t2)
|
||||
return re.sub(r"<(?:Norm|LabourMaterialsEquipmentsMachinesElement)\b[^>]*?/?>",
|
||||
z, frag)
|
||||
|
||||
return t + _zero_rows(ec._zero_results(inner)) + close
|
||||
|
||||
|
||||
def _bill_block(sample_blk, b, norm_tmpl, express_by_norm, txt):
|
||||
"""我方一条清单 → 整块(决策 231①+补记,主人定「和标准采纳一样」):
|
||||
· 有采纳定额 → 走 export_cos 同款引擎挂**真实定额**(_norm_xml:费用构成/单价计算
|
||||
innards 克隆、消耗量行重写、清单级工料机尾表按消耗量现算,决策 98/106);
|
||||
· 没采纳 → **克隆架子清值**(231①,主人 2026-10-28 复确认):cos 清单架子导出、
|
||||
值全清=「还没组价」的形态。
|
||||
工程量按数据本体精度回写(_bill_xml 内部按单件 3 位规律写会截 6 位量,三溪实测)。"""
|
||||
ns = [n for n in (b.get("norms") or []) if not n.get("x_tdel")]
|
||||
if not ns:
|
||||
return _frame_bill(sample_blk, b, _PRE_BILL if b.get("kind") == "prelim"
|
||||
else _ITEM_BILL)
|
||||
norms_xml = []
|
||||
for n in ns:
|
||||
lres = (express_by_norm or {}).get(n["id"]) or n.get("res") or []
|
||||
norms_xml.append(ec._norm_xml(n, lres, template=norm_tmpl,
|
||||
bill_qty=b.get("Quantity")))
|
||||
t = ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), norms_xml,
|
||||
template=sample_blk or None, txt=txt)
|
||||
oe = ec._open_tag_end(t, 0)
|
||||
if oe > 0:
|
||||
ot = t[:oe]
|
||||
if b.get("Quantity") is not None:
|
||||
ot = ec._attr_set(ot, "Quantity", _num(b.get("Quantity")))
|
||||
if not b.get("Number") and ' Number="' in ot:
|
||||
ot = ec._attr_set(ot, "Number", "") # 编码空=空("0" 是数值占位口径)
|
||||
t = ot + t[oe:]
|
||||
return t
|
||||
|
||||
|
||||
_LME_FILL_ROOTS = ("UnitWorks", "ConstructionProject", "ConstructProject",
|
||||
"ProjectInstallationWorkCost")
|
||||
|
||||
|
||||
def _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=None, lib=None):
|
||||
"""现算行 → 行列 HTML(决策 231 补记五,主人拍板「按现有数据生成」):
|
||||
行模板照骨架本件形态(198 槽不造);台班/配合比码带子级组成(s_lme_res)
|
||||
→ 行转容器+子行;量 0 不导(199)。"""
|
||||
out = []
|
||||
dyn_codes = {str(r[0]) for r in rows9 or []}
|
||||
# 组成子码全单位总额(2026-10-28 主人实测易达映射源组成子行编制价全空后的补行依据;
|
||||
# 原生件铁证:折旧费等组成码在单位表**各有一行自己的价**,量=Σ(母现算量×构成值)——
|
||||
# 构成值就是台班单价的组成(折旧3.44+检修0.80+…=台班价14.10),量×价1.00=总价)
|
||||
comp_tot = {}
|
||||
for r in rows9 or []:
|
||||
for c, q in (children or {}).get(str(r[0])) or []:
|
||||
try:
|
||||
comp_tot[c] = comp_tot.get(c, 0.0) + float(q or 0) * float(r[5] or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
comp_done = set()
|
||||
for r in rows9 or []:
|
||||
code, name, spec, unit, kind, qty, ntp, taxrate, taxp = r[:9]
|
||||
try:
|
||||
if float(qty or 0) == 0:
|
||||
continue
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
t = ec._lme_row(row_tmpl, code, _num(qty))
|
||||
t = ec._attr_set_has(t, "Name", name or "")
|
||||
t = ec._attr_set_has(t, "Specification", spec or "")
|
||||
t = ec._attr_set_has(t, "Unit", unit or "")
|
||||
if kind:
|
||||
t = ec._attr_set_has(t, "Kind", str(int(kind)))
|
||||
for k, v in (("Quantity", _num(qty)), ("NoTaxPrice", _money(ntp)),
|
||||
("TaxRate", _money(taxrate)), ("TaxPrice", _money(taxp))):
|
||||
t = ec._attr_set_has(t, k, v)
|
||||
kids = (children or {}).get(str(code))
|
||||
if kids and child_tmpl:
|
||||
if t.endswith("/>"):
|
||||
t = t[:-2] + ">"
|
||||
# 原生排版(两骨架实测):母行开标签→换行缩进→子行逐行同缩进→闭合标签前换行缩进
|
||||
ci = (ind or {}).get("ci") or "\n "
|
||||
cc = (ind or {}).get("cc") or "\n "
|
||||
inner = ci + ci.join(ec._child_node(child_tmpl, c, q) for c, q in kids)
|
||||
t = t + inner + cc + "</%s>" % _LME_SUM
|
||||
out.append(t)
|
||||
# 组成子码自有行(价格源行):紧跟首个引用它的母容器行(首现序),每码只补一行;
|
||||
# 已有现算行的码不补(直耗行已带价);名称/规格/单位/类别/单价取 s_lme_lib 快照
|
||||
for c, _q in (kids or ()):
|
||||
if c in dyn_codes or c in comp_done:
|
||||
continue
|
||||
lb = (lib or {}).get(c)
|
||||
if not lb or not comp_tot.get(c):
|
||||
continue
|
||||
nm2, sp2, un2, kd2, ntp2, taxp2 = lb
|
||||
|
||||
t2 = ec._lme_row(row_tmpl, c, _num(comp_tot[c]))
|
||||
t2 = ec._attr_set_has(t2, "Name", nm2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Specification", sp2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Unit", un2 or "")
|
||||
if kd2:
|
||||
try:
|
||||
t2 = ec._attr_set_has(t2, "Kind", str(int(kd2)))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
t2 = ec._attr_set_has(t2, "NoTaxPrice", _money(ntp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxPrice", _money(taxp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxRate", _money(0))
|
||||
out.append(t2)
|
||||
comp_done.add(c)
|
||||
return out
|
||||
|
||||
|
||||
def _lme_fill(txt, rows9=None, children=None, row_tmpl=None, child_tmpl=None, ind=None,
|
||||
lib=None):
|
||||
"""根层工料机汇总行(决策 231 补记五推翻补记三的「清空」定论——易达标准骨架铁证:
|
||||
单位成员根层直挂的 LME_SUM=**单位级汇总表**(每码一行、台班带子级嵌套);项目成员
|
||||
PIWC 内同款=项目级汇总表。骨架行/子行照本件形态克隆,灌**现算行**(主人拍板:
|
||||
定额工程量×消耗量,dyn 引擎)+台班子级组成;无现算行 → 清空(架子在、别人的行不进);
|
||||
行/子行模板缺位时本件全局取(调用方传入)。"""
|
||||
if not row_tmpl:
|
||||
return _lme_clear(txt)
|
||||
sep = ec._native_sep(txt, _LME_SUM, "") or (ind or {}).get("sep") or "\n"
|
||||
keep = _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=ind, lib=lib)
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
if not spans:
|
||||
# 空槽成员没有旧行=没有锚(2026-10-28 实测:易达骨架 31 位仅 3 位有汇总行,其余
|
||||
# 单位整表不插)。按原生「表在根尾」位补插(UnitWorksSummary 之后、根闭标签之前,
|
||||
# 两骨架有行成员同款)。首行不补分隔——插入点前已有原生换行。
|
||||
if not keep:
|
||||
return txt
|
||||
m = re.search(r"</([A-Za-z_][\w.]*)>\s*$", txt)
|
||||
anchor = m.start() if m else len(txt)
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
anchor = spans[0][0]
|
||||
for s, e in reversed(spans): # 从后往前删,锚点偏移不失效
|
||||
txt = txt[:s] + txt[e:]
|
||||
if not keep:
|
||||
return txt
|
||||
# 首行不补分隔:锚点前保留着原首行的换行+缩进(删行只删 < 起),避免双分隔出空行
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
|
||||
|
||||
def _lme_clear(txt):
|
||||
"""无行模板(骨架件无样行)时退回清空——架子在、行不进。"""
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
for s, e in reversed(spans):
|
||||
txt = txt[:s] + txt[e:]
|
||||
return txt
|
||||
|
||||
|
||||
def _dw_template(txt):
|
||||
"""骨架件本单位里第一个分部完整块 → {ot 开标签, prefix 前缀(分部自己的费用构成等)}。
|
||||
决策 106:费用构成子块是易达认块的关键——克隆时带上(值清零)。
|
||||
@@ -168,7 +378,8 @@ def _sum_bills(bills):
|
||||
return n
|
||||
|
||||
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, depth=0):
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, norm_tmpl=None,
|
||||
express_by_norm=None, txt="", depth=0):
|
||||
"""一个分部节点:开标签克隆(Name/Total 落我方,指标清零)+费用构成前缀(清零)
|
||||
+子分部/清单递归。Total=本级+全部子孙清单合计(现算,主人定可计算按采纳)。
|
||||
我方上限 4 级(决策 230),递归保险 8 级。返回 (块文本, 合计)。"""
|
||||
@@ -181,12 +392,13 @@ def _div_block(tmpl, d, kids, bills_by_div, sample, sep, depth=0):
|
||||
if depth <= _MAX_DEPTH:
|
||||
for sub in kids.get(d["id"], []):
|
||||
blk, sub_total = _div_block(tmpl, sub, kids, bills_by_div, sample, sep,
|
||||
depth + 1)
|
||||
norm_tmpl, express_by_norm, txt, depth + 1)
|
||||
parts.append(blk)
|
||||
total += sub_total
|
||||
ot = ec._attr_set_has(ot, "Total", _money(total))
|
||||
bills = [_manual_bill(sample, b) for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = _zero_rows(ec._zero_results(tmpl["prefix"])) if tmpl else ""
|
||||
bills = [_bill_block(sample, b, norm_tmpl, express_by_norm, txt)
|
||||
for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = ec._zero_results(tmpl["prefix"]) if tmpl else ""
|
||||
return ot + prefix + sep.join(parts + bills) + "</%s>" % _DW, total
|
||||
|
||||
|
||||
@@ -225,17 +437,27 @@ def _top_scan(inner, stop_tags):
|
||||
return inner, n
|
||||
|
||||
|
||||
def _render_unit(txt, u, plan):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总空槽;
|
||||
单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"]
|
||||
def _render_unit(txt, u, plan, sc=None, sid=0, express_by_norm=None,
|
||||
lme_ctx=None):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总按现算挂真实行
|
||||
(无采纳=空槽);单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"
|
||||
and not b.get("x_tdel")]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"
|
||||
and not b.get("x_tdel")]
|
||||
item_sample = ec._largest_bill_block(txt, tag=_ITEM_BILL, prelim=False) \
|
||||
or _fallback_blk(txt, False)
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) or item_sample
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "\r\n")
|
||||
sep_d = ec._native_sep(txt, _DW, sep)
|
||||
tmpl = _dw_template(txt)
|
||||
or _fallback_blk(txt, False) or (lme_ctx or {}).get("g_item")
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) \
|
||||
or (lme_ctx or {}).get("g_pre") or item_sample
|
||||
norm_tmpl_item = (ec._full_norm_block(item_sample) if item_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_item")
|
||||
norm_tmpl_pre = (ec._full_norm_block(pre_sample) if pre_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_pre") or norm_tmpl_item
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "") \
|
||||
or (lme_ctx or {}).get("g_sep") or "\r\n"
|
||||
sep_d = ec._native_sep(txt, _DW, sep) or (lme_ctx or {}).get("g_sep_d") or sep
|
||||
tmpl = _dw_template(txt) or (lme_ctx or {}).get("g_dw")
|
||||
bb = dict(norm_tmpl=norm_tmpl_item, express_by_norm=express_by_norm, txt=txt)
|
||||
|
||||
# ---- 分部分项容器:清仓 → 我方分部树(DivisionalWorks 递归嵌套)+ 容器合计现算 ----
|
||||
sp = _span(txt, _ITEM_CONT)
|
||||
@@ -249,14 +471,18 @@ def _render_unit(txt, u, plan):
|
||||
bills_by_div = {}
|
||||
for b in bills_item:
|
||||
bills_by_div.setdefault(b.get("div_id"), []).append(b)
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d)[0]
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d,
|
||||
norm_tmpl=bb["norm_tmpl"],
|
||||
express_by_norm=express_by_norm, txt=txt)[0]
|
||||
for d in roots]
|
||||
blocks += [_manual_bill(item_sample, b) for b in bills_by_div.get(None, [])]
|
||||
blocks += [_bill_block(item_sample, b, bb["norm_tmpl"],
|
||||
express_by_norm, txt)
|
||||
for b in bills_by_div.get(None, [])]
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_item)))
|
||||
else:
|
||||
blocks = []
|
||||
prefix, _ = _top_scan(inner_old, (_DW, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + sep_d.join(blocks) + close)
|
||||
|
||||
# ---- 措施项目容器:清仓 → 我方措施行(有包装层就克隆一层);合计现算 ----
|
||||
@@ -268,7 +494,8 @@ def _render_unit(txt, u, plan):
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u and bills_pre:
|
||||
ot_wrap = _opentag(inner_old, _DW_PRE)
|
||||
bills = [_manual_bill(pre_sample, b, _PRE_BILL) for b in bills_pre]
|
||||
bills = [_bill_block(pre_sample, b, norm_tmpl_pre, express_by_norm, txt)
|
||||
for b in bills_pre]
|
||||
body = (ec._clone_open_tag(ot_wrap) + sep.join(bills) + "</%s>" % _DW_PRE) \
|
||||
if ot_wrap else sep.join(bills)
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_pre)))
|
||||
@@ -277,23 +504,17 @@ def _render_unit(txt, u, plan):
|
||||
# 措施分部两种标签都在真实件里出现过:PreliminaryDivisionalWorks(新)与
|
||||
# DivisionalWorks(三溪 .cos 实测)——都要停,包装层连同旧清单整块让位给我方平铺
|
||||
prefix, _ = _top_scan(inner_old, (_DW_PRE, _DW, _PRE_BILL, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + body + close)
|
||||
|
||||
# ---- 工料机汇总:架子在、行不进(我方无工料机数据)。容器→清空内层;
|
||||
# 自闭合行(老版本/广联达目录式导出的形态)→ 整行删除,别人的行绝不残留 ----
|
||||
pos = 0
|
||||
while True:
|
||||
sp = _span(txt, _LME_SUM, pos)
|
||||
if not sp:
|
||||
break
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
txt = txt[:sp[0]] + txt[sp[1]:]
|
||||
pos = sp[0]
|
||||
continue
|
||||
txt = txt[:oe] + "</%s>" % _LME_SUM + txt[sp[1]:]
|
||||
pos = oe
|
||||
# ---- 单位级工料机汇总(补记五:根层 LME_SUM=单位级汇总表,易达标准骨架铁证):
|
||||
# 灌现算行(dyn 引擎,定额工程量×消耗量)+台班子级;没采纳 → 清空(架子在行不进)
|
||||
ctx = lme_ctx or {}
|
||||
rows9 = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) if (sc and u) else None
|
||||
txt = _lme_fill(txt, rows9, ctx.get("children"),
|
||||
ctx.get("row_tmpl"), ctx.get("child_tmpl"),
|
||||
ind={"ci": ctx.get("ci"), "cc": ctx.get("cc"), "sep": ctx.get("sep")},
|
||||
lib=ctx.get("lib"))
|
||||
|
||||
# ---- 单位工程名 + 我方可算合计(分部分项费/措施费;其余保留值)----
|
||||
if u:
|
||||
@@ -342,8 +563,27 @@ def _rename_opentags(txt, tag, names):
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。"""
|
||||
class _GbkNameZipInfo(ec._RawNameZipInfo):
|
||||
"""克隆补位成员的条目名:骨架原生条目名是 GBK 字节(无旗标)。_RawNameZipInfo 对
|
||||
cp437 编不回的串会退 UTF-8+旗标——那正是乱码教训——新中文名这里改按 GBK 写、同样
|
||||
不打旗标(GBK 也编不了才 UTF-8 兜底)。"""
|
||||
|
||||
def _encodeFilenameFlags(self):
|
||||
try:
|
||||
return self.filename.encode("cp437"), 0
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
try:
|
||||
return self.filename.encode("gbk"), 0
|
||||
except UnicodeEncodeError:
|
||||
return self.filename.encode("utf-8"), 0x800
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections, extra_refs=None):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。
|
||||
extra_refs=骨架位不够时克隆出来的单位引用行 [(我方单位名, 成员文件名, 引用号)]
|
||||
——克隆最后一条现有引用行,号/名/文件名改新,按原生分隔符顺延(2026-10-28 主人定
|
||||
「骨架单位工程位可自由添加」)。"""
|
||||
decl = re.match(r"^.*?\?>", txt, flags=re.S)
|
||||
base = decl.end() if decl else 0
|
||||
lead = base + (len(txt[base:]) - len(txt[base:].lstrip()))
|
||||
@@ -357,17 +597,34 @@ def _render_project(txt, plan, proj_name, n_ours, n_sections):
|
||||
sec_names = [s.get("name") or "" for s in plan["sections"]]
|
||||
for t in _SEC_TAGS:
|
||||
txt = _rename_opentags(txt, t, sec_names)
|
||||
if extra_refs:
|
||||
ms = list(re.finditer(r"<UnitWorks\b[^>]*>", txt))
|
||||
if ms:
|
||||
tmpl_o = ms[-1].group(0)
|
||||
# 自闭合引用行先转开标签形态改属性,改完再转回——_attr_set 对缺属性是尾插,
|
||||
# 会把属性插到自闭合的 / 后面(Total="x"/ FileName="y"> 结构破)
|
||||
self_close = tmpl_o.rstrip().endswith("/>")
|
||||
if self_close:
|
||||
tmpl_o = tmpl_o.rstrip()[:-2] + ">"
|
||||
sep = ec._native_sep(txt, "UnitWorks", "\r\n")
|
||||
add = []
|
||||
for name_k, fname_k, num_k in extra_refs:
|
||||
row = ec._attr_set(ec._attr_set(ec._attr_set(
|
||||
tmpl_o, "Number", str(num_k)), "Name", name_k or ""), "FileName", fname_k)
|
||||
if self_close:
|
||||
row = row[:-1] + "/>"
|
||||
add.append(row)
|
||||
txt = txt[:ms[-1].end()] + "".join(sep + r for r in add) + txt[ms[-1].end():]
|
||||
return txt
|
||||
|
||||
|
||||
def export(sc, hcon, sid, suffix, progress=None):
|
||||
"""手工工程导出 cos/cos4。返回 (字节, 文件名, 错误)。"""
|
||||
def export(sc, hcon, sid, suffix, progress=None, src_path=None):
|
||||
"""经典骨架导出 cos/cos4(补记十二,主人定「骨架管导出,数据归软件」:cos4 全量走
|
||||
骨架——手工+普通工程都算;数据全用软件里的现算/采纳,骨架只管格式与字段。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
if not srow["x_manual"]:
|
||||
return None, None, "普通工程请按原格式导出(自带源文件模板)"
|
||||
rep = classic_skeleton.rep_for(hcon, (suffix or "").lower())
|
||||
rep = classic_skeleton.pick_frame(hcon, (suffix or "").lower(), src_path=src_path)
|
||||
if not rep:
|
||||
return None, None, ("该后缀(.%s)还没有经典骨架:请先在后台导入或用工作台"
|
||||
"打开一份 .%s 原件" % (suffix, suffix))
|
||||
@@ -375,14 +632,25 @@ def export(sc, hcon, sid, suffix, progress=None):
|
||||
if plan is None:
|
||||
return None, None, "会话数据读不出来"
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
# 采纳含量算式(s_norm_res.express,决策 106 补记十二:调整式跟着历史项目走)
|
||||
express_by_norm = {}
|
||||
for r in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express
|
||||
FROM s_norm_res nr
|
||||
JOIN s_norms n ON n.id=nr.norm_id
|
||||
JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=?""", (sid,)):
|
||||
express_by_norm.setdefault(r["norm_id"], []).append(
|
||||
(r["res_code"], r["qty"], r["express"] or None))
|
||||
try:
|
||||
raw = _render(rep["blob"], plan, proj_name, progress)
|
||||
raw = _render(rep["blob"], plan, proj_name, progress, sc, sid,
|
||||
express_by_norm, rep["suffix"])
|
||||
except Exception as e:
|
||||
return None, None, "导出失败:%s" % e
|
||||
return raw, ((proj_name or "工程") + "-审核版." + rep["suffix"]), None
|
||||
|
||||
|
||||
def _render(blob, plan, proj_name, progress=None):
|
||||
def _render(blob, plan, proj_name, progress=None, sc=None, sid=0,
|
||||
express_by_norm=None, suffix=""):
|
||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
||||
members, texts = [], {}
|
||||
for nm in src.namelist():
|
||||
@@ -402,10 +670,139 @@ def _render(blob, plan, proj_name, progress=None):
|
||||
proj_nms.append(nm)
|
||||
if not unit_nms:
|
||||
raise ValueError("骨架件里没找到单位工程数据,请换一份原件再试")
|
||||
# 单位成员处理序=**项目成员引用行的 FileName 序**(主人 2026-10-28 定:单项/单位排序
|
||||
# 按项目目录先有顺序=引用行序,与压缩包内 xml 次序无关)。骨架自己的引用行序常与
|
||||
# zip 成员序不同——按 zip 序灌名会让「引用行名 ↔ 成员名」错位(实测广联达骨架 20/44
|
||||
# 不一致)。引用行没点到/点丢的成员按原 zip 序垫后,一个不漏。
|
||||
if proj_nms:
|
||||
disp_of = {}
|
||||
for i in src.infolist():
|
||||
if not i.filename.lower().endswith(".xml"):
|
||||
continue
|
||||
try:
|
||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
||||
else i.filename.encode("cp437")
|
||||
disp_of[raw.decode("gbk")] = i.filename
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
ref_order = []
|
||||
for x in re.findall(r"<UnitWorks\b[^>]*>", texts[proj_nms[0]][0]):
|
||||
fn = re.search(r'\bFileName="([^"]*)"', x)
|
||||
if fn and fn.group(1) in disp_of and disp_of[fn.group(1)] in unit_nms \
|
||||
and disp_of[fn.group(1)] not in ref_order:
|
||||
ref_order.append(disp_of[fn.group(1)])
|
||||
if ref_order:
|
||||
unit_nms = ref_order + [n for n in unit_nms if n not in ref_order]
|
||||
ours = plan["units"]
|
||||
# 行/子行模板全局取(专用骨架的空单位位没有样行——借其他成员的形态,补记五):
|
||||
# 行模板=任一自闭合 LME_SUM 行;子行=任一「容器行内嵌的原生 …Element 子行」+原生
|
||||
# 换行缩进(广联达/易达两骨架实测同款:子行一律 Element 形态、只 Number/Express/
|
||||
# Quantity/Remark;2026-10-28 修:旧正则 [^>]*> 会吃掉自闭合的 /,把相邻两条平铺行
|
||||
# 误当「母行+子行」——子行模板成了别人的母行,Name/单价/金额残留全从这来)
|
||||
row_tmpl = child_tmpl = None
|
||||
ci_ind = cc_ind = None
|
||||
g_lme_sep = None
|
||||
pat_row = re.compile(r"<%s\b[^>]*/>" % _LME_SUM)
|
||||
# 子行形态=容器开标签后内嵌的首个 …Element 行(多子行容器里第一条后面跟的是兄弟不是
|
||||
# 闭合,所以闭合缩进单取:最后一条 Element 行与 </…Summary> 之间的空白)
|
||||
pat_child = re.compile(r"<%s\b[^>]*[^/]>(\s*)(<LabourMaterialsEquipmentsMachinesElement"
|
||||
r"\b[^>]*/>)" % _LME_SUM, re.S)
|
||||
pat_close = re.compile(r"<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>"
|
||||
r"(\s*)(</%s>)" % _LME_SUM, re.S)
|
||||
# 清单/定额/分部样板与原生分隔符同样全局兜底(空单位位没有样板 → 借全件的)
|
||||
g_item = g_pre = g_dw = None
|
||||
g_item_nm = None
|
||||
g_sep = g_sep_d = None
|
||||
g_norm_item = g_norm_pre = None
|
||||
for nm in unit_nms:
|
||||
t0 = texts[nm][0]
|
||||
if row_tmpl is None:
|
||||
m1 = pat_row.search(t0)
|
||||
if m1:
|
||||
row_tmpl = m1.group(0)
|
||||
g_lme_sep = ec._native_sep(t0, _LME_SUM, "\n")
|
||||
if child_tmpl is None:
|
||||
m2 = pat_child.search(t0)
|
||||
if m2:
|
||||
child_tmpl, ci_ind = m2.group(2), m2.group(1)
|
||||
if cc_ind is None:
|
||||
m3 = pat_close.search(t0)
|
||||
if m3:
|
||||
cc_ind = m3.group(1)
|
||||
if g_item is None:
|
||||
b1 = ec._largest_bill_block(t0, tag=_ITEM_BILL, prelim=False)
|
||||
if b1:
|
||||
g_item = b1
|
||||
g_item_nm = nm
|
||||
g_sep = ec._native_sep(t0, _ITEM_BILL, "\r\n")
|
||||
g_sep_d = ec._native_sep(t0, _DW, g_sep)
|
||||
g_dw = _dw_template(t0)
|
||||
g_norm_item = ec._full_norm_block(b1)
|
||||
if g_pre is None:
|
||||
b2 = ec._largest_bill_block(t0, prelim=True)
|
||||
if b2:
|
||||
g_pre = b2
|
||||
g_norm_pre = ec._full_norm_block(b2)
|
||||
if row_tmpl and child_tmpl and cc_ind and g_item and g_pre:
|
||||
break
|
||||
# 台班/配合比子级组成(s_lme_res:p_code → [(子码, 含量)])
|
||||
children = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
|
||||
"WHERE session_id=? ORDER BY seq, id", (sid,)):
|
||||
children.setdefault(r["p_code"] or "", []).append((r["res_code"], r["qty"]))
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入;手工会话唯一价格源)
|
||||
lib = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp FROM s_lme_lib "
|
||||
"WHERE session_id=?", (sid,)):
|
||||
lib[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
|
||||
lme_ctx = {"children": children, "row_tmpl": row_tmpl, "child_tmpl": child_tmpl,
|
||||
"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep, "lib": lib,
|
||||
"g_item": g_item, "g_pre": g_pre, "g_dw": g_dw,
|
||||
"g_sep": g_sep, "g_sep_d": g_sep_d,
|
||||
"g_norm_item": g_norm_item, "g_norm_pre": g_norm_pre}
|
||||
# 单位工程位自由复制(主人 2026-10-28 定:骨架=数据结构模板,单位工程/单项工程/
|
||||
# 清单/分部/定额想插多少插多少,结构不变——位不够就克隆骨架自己的单位成员补位,
|
||||
# 项目成员的引用行同步顺延;成员名按骨架自己的 @_序号_名.xml 命名顺延)
|
||||
new_units = [] # [(新成员名, 克隆源名, 引用号, 我方单位名)]——写包时补 zip 条目
|
||||
if len(ours) > len(unit_nms):
|
||||
raise ValueError("经典骨架只有 %d 个单位工程位,本工程有 %d 个——请先用单位工程"
|
||||
"更多的 .%s 原件充一次库" % (len(unit_nms), len(ours), rep["suffix"]))
|
||||
src_nm = g_item_nm or unit_nms[0]
|
||||
orig_slots = len(unit_nms)
|
||||
m2 = re.match(r"@_(\d+)_(.+)\.xml$", src_nm)
|
||||
nums = [int(m.group(1)) for m in
|
||||
(re.match(r"@_(\d+)_", n) for n in unit_nms) if m]
|
||||
base_n = (max(nums) + 2) if nums else (len(unit_nms) + 1)
|
||||
disp = m2.group(2) if m2 else "单位工程"
|
||||
t2 = re.search(r"(\d+)$", disp)
|
||||
# 引用号顺延基准:项目成员里现有 UnitWorks 引用行的最大号
|
||||
nxt = 0
|
||||
if proj_nms:
|
||||
nxt = max([int(x.group(1)) for x in
|
||||
re.finditer(r'<UnitWorks\b[^>]*?\bNumber="(\d+)"', texts[proj_nms[0]][0])]
|
||||
or [0])
|
||||
for k in range(len(ours) - orig_slots):
|
||||
disp_k = (disp[:t2.start()] + str(int(t2.group(1)) + 1 + k)) if t2 \
|
||||
else "%s%d" % (disp, k + 1)
|
||||
nm_k = "@_%d_%s.xml" % (base_n + 2 * k, disp_k)
|
||||
texts[nm_k] = [texts[src_nm][0], texts[src_nm][1]]
|
||||
t0 = texts[nm_k][0]
|
||||
mm = re.search(r"<UnitWorks\b", t0)
|
||||
if mm:
|
||||
oe = ec._open_tag_end(t0, mm.start())
|
||||
t0 = t0[:mm.start()] + ec._attr_set(t0[mm.start():oe], "Number", str(nxt + 1 + k)) + t0[oe:]
|
||||
texts[nm_k][0] = t0
|
||||
members.append(nm_k)
|
||||
unit_nms.append(nm_k)
|
||||
new_units.append((nm_k, src_nm, nxt + 1 + k,
|
||||
(ours[orig_slots + k].get("name") or "")))
|
||||
proj_rows = None
|
||||
if sc:
|
||||
_dp = dyn_lme.dyn_rows(sc, sid, None)
|
||||
if _dp:
|
||||
proj_rows = [(r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8])
|
||||
for r in _dp]
|
||||
total_steps = len(unit_nms) + len(proj_nms) + 1
|
||||
step = [0]
|
||||
|
||||
@@ -416,26 +813,43 @@ def _render(blob, plan, proj_name, progress=None):
|
||||
|
||||
for i, nm in enumerate(unit_nms):
|
||||
u = ours[i] if i < len(ours) else None
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan)
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan, sc, sid, express_by_norm,
|
||||
lme_ctx=lme_ctx)
|
||||
tick()
|
||||
for nm in proj_nms:
|
||||
texts[nm][0] = _render_project(texts[nm][0], plan, proj_name,
|
||||
len(ours), len(plan["sections"]))
|
||||
len(ours), len(plan["sections"]),
|
||||
extra_refs=[(x[3], x[0], x[2]) for x in new_units])
|
||||
texts[nm][0] = _lme_fill(texts[nm][0], proj_rows, children,
|
||||
row_tmpl, child_tmpl,
|
||||
ind={"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep},
|
||||
lib=lib)
|
||||
tick()
|
||||
tick()
|
||||
out = io.BytesIO()
|
||||
item_by_nm = {i.filename: i for i in src.infolist()}
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for item in src.infolist():
|
||||
data = src.read(item.filename)
|
||||
if item.filename in texts:
|
||||
data = ec._encode(texts[item.filename][0], texts[item.filename][1])
|
||||
zi = zipfile.ZipInfo(item.filename, date_time=item.date_time)
|
||||
zi = ec._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
|
||||
try:
|
||||
zi.extra = item.extra
|
||||
zi.extra = ec._safe_extra(item.extra)
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, data)
|
||||
# 克隆补位的单位成员(骨架原生条目名是 GBK 字节无旗标——新名字同样按 GBK 写)
|
||||
for nm_k, src_nm, _num, _n in new_units:
|
||||
data = ec._encode(texts[nm_k][0], texts[nm_k][1])
|
||||
si = item_by_nm.get(src_nm)
|
||||
zi = _GbkNameZipInfo(nm_k, date_time=si.date_time if si else (2026, 1, 1, 0, 0, 0))
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
if si:
|
||||
zi.external_attr = si.external_attr
|
||||
zi.create_system = si.create_system
|
||||
zo.writestr(zi, data)
|
||||
return out.getvalue()
|
||||
|
||||
@@ -16,6 +16,22 @@ from xml.etree import ElementTree as ET
|
||||
|
||||
import import_job as job
|
||||
|
||||
|
||||
def _natkey(s):
|
||||
"""编号自然序键(与界面树/汇总分析同款):数字段按数值、非数字段按文本。"""
|
||||
out, buf, digit = [], "", None
|
||||
for ch in s or "":
|
||||
d = ch.isdigit()
|
||||
if d == digit:
|
||||
buf += ch
|
||||
else:
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
buf, digit = ch, d
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
return out
|
||||
|
||||
_QTY_EXPR_OK = re.compile(r"^[0-9+\-*/().\s]*$")
|
||||
|
||||
|
||||
@@ -87,11 +103,18 @@ def build_plan(sc, sid):
|
||||
if not srow:
|
||||
return None
|
||||
sections = {}
|
||||
for r in sc.execute("SELECT * FROM s_sections WHERE session_id=?", (sid,)):
|
||||
for r in sc.execute("SELECT * FROM s_sections WHERE session_id=? ORDER BY id", (sid,)):
|
||||
sections[r["id"]] = {"id": r["id"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "total": r["Total"]}
|
||||
# 单位顺序=左侧目录树序(2026-10-28 主人定通用口径,与 2026-10-08 汇总分析同款):
|
||||
# 单项按入库序、组内按编号自然序。手工树保存时按组内位置重写编号=目录序持久化在
|
||||
# Number 里;此前 ORDER BY id 在树里上下移动过单位后会与目录顺序脱节。
|
||||
sec_order = {k: i for i, k in enumerate(sections)}
|
||||
rows = sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall()
|
||||
rows = sorted(rows, key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
|
||||
_natkey(r["Number"] or ""), r["id"]))
|
||||
units = []
|
||||
for r in sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)):
|
||||
for r in rows:
|
||||
sec = sections.get(r["section_id"]) if r["section_id"] is not None else None
|
||||
units.append({"id": r["id"], "number": r["Number"] or "", "name": r["Name"] or "",
|
||||
"total": r["Total"], "section_number": (sec or {}).get("number", ""),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
3. 层级用「上一级名称」挂接法表达:分部行/清单行都填自己的上级名称,
|
||||
一级分部填「单位工程」;类型只填 分部/清单 两值,几级分部由链条自动算,
|
||||
**单位工程往下最多 5 层**(最多 4 级分部 + 清单,2026-10-27 主人定)。
|
||||
挂接=找上方最近的同名分部;同一上级下分部不得重名(报行号)。
|
||||
挂接=找上方最近的同名分部;空名/同名/深层级均放行(补记十四,2026-10-28)。
|
||||
4. 项目特征换行识别(2026-10-27 主人定):真实换行(Alt+Enter)原样保留;行内编号
|
||||
标记(1. / 1、/ 1)/(1)等多格式)**从 1 连续递增到 N(不缺号,N≥2)才切分**——
|
||||
编到 9 就必须 1~8 齐全;缺号不切;「1.5」这类小数不误切(点后跟数字不算标记)。
|
||||
@@ -237,10 +237,9 @@ def parse_workbook(path):
|
||||
get = lambda key: row[col(key)] if col(key) is not None and col(key) < len(row) else None
|
||||
parent = _cell(get("上一级名称"))
|
||||
typ = _cell(get("类型"))
|
||||
name = _cell(get("名称"))
|
||||
if not name:
|
||||
errors.append("第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
name = _cell(get("名称")) or ""
|
||||
# 补记十四(2026-10-28 主人定边界放开):分部/清单**空名称放行**
|
||||
#(原文件存在空名分部/空名清单);层级**不设限**;同上级**同名分部放行**
|
||||
if typ == "分部":
|
||||
if parent == ROOT_MARK:
|
||||
level, pidx = 1, -1
|
||||
@@ -251,12 +250,6 @@ def parse_workbook(path):
|
||||
errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)"))
|
||||
continue
|
||||
level, pidx = divides[hit]["level"] + 1, hit
|
||||
if level > MAX_DEPTH:
|
||||
errors.append("第 %d 行:层级超过 5 层(单位工程下最多 %d 级分部)" % (ri, MAX_DEPTH))
|
||||
continue
|
||||
if any(d["pidx"] == pidx and d["name"] == name for d in divides):
|
||||
errors.append("第 %d 行:同一上级下已有同名分部「%s」" % (ri, name))
|
||||
continue
|
||||
divides.append({"name": name, "pidx": pidx, "level": level})
|
||||
elif typ == "清单":
|
||||
if parent == ROOT_MARK:
|
||||
@@ -267,9 +260,6 @@ def parse_workbook(path):
|
||||
if didx is None:
|
||||
errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)"))
|
||||
continue
|
||||
if divides[didx]["level"] > MAX_DEPTH:
|
||||
errors.append("第 %d 行:清单挂在第 %d 级分部下,超过 5 层" % (ri, divides[didx]["level"] + 1))
|
||||
continue
|
||||
qty = _num(get("工程量"), ri, "工程量", errors)
|
||||
price = _num(get("单价"), ri, "单价", errors)
|
||||
unit = _cell(get("单位"))
|
||||
@@ -295,9 +285,7 @@ def parse_workbook(path):
|
||||
if row is None or not any(_cell(v) for v in row):
|
||||
continue
|
||||
name = _cell(row[head["名称"]]) if head["名称"] < len(row) else ""
|
||||
if not name:
|
||||
errors.append("措施 第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
# 措施空名同样放行(补记十四)
|
||||
qty = _num(row[head["工程量"]] if "工程量" in head and head["工程量"] < len(row) else None,
|
||||
ri, "工程量", errors)
|
||||
price = _num(row[head["单价"]] if "单价" in head and head["单价"] < len(row) else None,
|
||||
@@ -323,9 +311,10 @@ def parse_workbook(path):
|
||||
# 会话结构:查现状 / 保存(建+改+导)
|
||||
# ---------------------------------------------------------------------------
|
||||
def manual_state(con, sid):
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数。"""
|
||||
row = con.execute("SELECT name, period_from, period_to, x_manual FROM sessions WHERE id=?",
|
||||
(sid,)).fetchone()
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数 + 共用字段(决策 233)。"""
|
||||
row = con.execute("""SELECT name, period_from, period_to, x_manual,
|
||||
x_province, x_city, x_district, bulid_unit
|
||||
FROM sessions WHERE id=?""", (sid,)).fetchone()
|
||||
if not row or not row["x_manual"]:
|
||||
return {"ok": False}
|
||||
secs, units = [], []
|
||||
@@ -345,7 +334,10 @@ def manual_state(con, sid):
|
||||
"n_item": c.get("item", 0), "n_prelim": c.get("prelim", 0)}
|
||||
(secmap[u["section_id"]]["units"].append(it) if u["section_id"] in secmap else units.append(it))
|
||||
return {"ok": True, "name": row["name"] or "", "period_from": row["period_from"],
|
||||
"period_to": row["period_to"], "sections": secs, "free_uws": units}
|
||||
"period_to": row["period_to"],
|
||||
"province": row["x_province"] or "", "city": row["x_city"] or "",
|
||||
"district": row["x_district"] or "", "bulid_unit": row["bulid_unit"] or "",
|
||||
"sections": secs, "free_uws": units}
|
||||
|
||||
|
||||
def _del_unit(cur, uwid):
|
||||
@@ -438,6 +430,7 @@ def _sum_divides(cur, uwid):
|
||||
def save_tree(con, body):
|
||||
"""建/改手工工程目录树并按单位工程导 Excel。
|
||||
body = {sid?, name, period_from, period_to,
|
||||
province?/city?/district?/bulid_unit?(决策 233 共用字段落库),
|
||||
tree: [{id?, name, units: [{id?, name, file?}]}], free_uws?: 同款}
|
||||
file = 已上传到软件目录的 xlsx 路径(/api/admin/upload 返回值)。"""
|
||||
name = (body.get("name") or "").strip()
|
||||
@@ -446,6 +439,10 @@ def save_tree(con, body):
|
||||
pf, pt = body.get("period_from"), body.get("period_to")
|
||||
if pf is None or pt is None:
|
||||
return {"ok": False, "msg": "基准期次必填"}
|
||||
prov = (body.get("province") or "").strip() # 决策 233:与打开项目弹框共用字段
|
||||
city = (body.get("city") or "").strip()
|
||||
dist = (body.get("district") or "").strip()
|
||||
bu = (body.get("bulid_unit") or "").strip()
|
||||
tree = body.get("tree") or []
|
||||
flat = []
|
||||
for s in tree:
|
||||
@@ -479,11 +476,13 @@ def save_tree(con, body):
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_manual)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,1)""",
|
||||
(name, pf, pf, pt, "", "", "", "", "",
|
||||
(name, pf, pf, pt, prov, city, dist, bu, "",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
cur.execute("UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=? WHERE id=?",
|
||||
(name, pf, pt, pf, sid))
|
||||
# 决策 233:打开项目弹框共用字段——地区/建设单位随建随改落库(与 /api/audit 同名参数)
|
||||
cur.execute("""UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=?,
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=? WHERE id=?""",
|
||||
(name, pf, pt, pf, prov, city, dist, bu, sid))
|
||||
|
||||
# ---- 结构同步(决策 230 补记:单项/单位均可在组内上下移动)----
|
||||
# 单位工程按 id 对位:改名保留数据 / 删除级联 / 新增先插(归属与编号稍后统一指)。
|
||||
@@ -537,7 +536,7 @@ def save_tree(con, body):
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 手工工程导出 Excel(决策 229,2026-10-27 主人定):模板架子+合价/备注
|
||||
# 手工工程导出 Excel(决策 231,2026-10-27 主人定):模板架子+合价/备注
|
||||
# 文件夹=项目名称,一个单位工程一个 xlsx(文件名=单位工程名);
|
||||
# 分部分项 10 列 / 措施项目 8 列——只带清单、不带定额(主人定);
|
||||
# 合价=工程量×单价现算;备注=审核备注;导出件可直接回导入(多出的合价/备注列解析端忽略)。
|
||||
@@ -558,7 +557,14 @@ def export_excel_bytes(sc, sid):
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
proj = (srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程"
|
||||
uws = list(sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)))
|
||||
# 单位顺序=目录树序(2026-10-28 通用口径:单项入库序+组内编号自然序;树里上下
|
||||
# 移动后 ORDER BY id 会与目录脱节)
|
||||
sec_order = {r["id"]: i for i, r in enumerate(
|
||||
sc.execute("SELECT id FROM s_sections WHERE session_id=? ORDER BY id", (sid,)).fetchall())}
|
||||
from formats.skeleton import _natkey
|
||||
uws = sorted(sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall(),
|
||||
key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
|
||||
_natkey(r["Number"] or ""), r["id"]))
|
||||
if not uws:
|
||||
return None, None, "本工程还没有单位工程,先在「导入项目」里建目录并导入 Excel"
|
||||
divs = {}
|
||||
@@ -569,6 +575,25 @@ def export_excel_bytes(sc, sid):
|
||||
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
|
||||
bills.setdefault(r["uw_id"], []).append(dict(r))
|
||||
|
||||
import io as _io
|
||||
folder = _safe_sheet_name(proj)
|
||||
used, buf = {}, _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for u in uws:
|
||||
nm = _safe_sheet_name(u["Name"]) + ".xlsx"
|
||||
k = 2
|
||||
while nm in used:
|
||||
nm = "%s(%d).xlsx" % (_safe_sheet_name(u["Name"]), k)
|
||||
k += 1
|
||||
used[nm] = True
|
||||
zo.writestr("%s/%s" % (folder, nm), _unit_workbook(u, divs, bills))
|
||||
return buf.getvalue(), proj + "-审核版.zip", None
|
||||
|
||||
|
||||
def _unit_workbook(u, divs, bills):
|
||||
"""单单位工程 xlsx 字节(决策 231 架子:填写说明+分部分项10列+措施8列,合价/备注)。
|
||||
决策 233:自 export_excel_bytes 抽出——整包 zip 与单单位工程导出(export_unit_xlsx)同一产出。"""
|
||||
|
||||
def b_total(b):
|
||||
try:
|
||||
if b["Quantity"] is not None and b["Price"] is not None:
|
||||
@@ -611,67 +636,82 @@ def export_excel_bytes(sc, sid):
|
||||
return out
|
||||
|
||||
import io as _io
|
||||
folder = _safe_sheet_name(proj)
|
||||
used, buf = {}, _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for u in uws:
|
||||
wb = Workbook()
|
||||
ws0 = wb.active
|
||||
ws0.title = "填写说明"
|
||||
ws0.column_dimensions["A"].width = 90
|
||||
for i, (t, bold) in enumerate([
|
||||
("「%s」导出件(决策 229)" % u["Name"], True),
|
||||
("", False),
|
||||
("一、本件由软件导出,可直接在「导入项目」里对同一单位工程回导(整单位工程覆盖)。", False),
|
||||
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
|
||||
("三、只到清单级:不导定额、不导工料机。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if bold:
|
||||
c.font = Font(bold=True)
|
||||
h1 = _FB_HEAD_X
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in fb_rows(u["id"]):
|
||||
ws1.append(r)
|
||||
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
|
||||
ws1.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h1, 1):
|
||||
cell = ws1.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws1.freeze_panes = "A2"
|
||||
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
h2 = _CS_HEAD_X
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for b in bills.get(u["id"], []):
|
||||
if b["Kind"] != "prelim":
|
||||
continue
|
||||
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h2, 1):
|
||||
cell = ws2.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws2.freeze_panes = "A2"
|
||||
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
bio = _io.BytesIO()
|
||||
wb.save(bio)
|
||||
nm = _safe_sheet_name(u["Name"]) + ".xlsx"
|
||||
k = 2
|
||||
while nm in used:
|
||||
nm = "%s(%d).xlsx" % (_safe_sheet_name(u["Name"]), k)
|
||||
k += 1
|
||||
used[nm] = True
|
||||
zo.writestr("%s/%s" % (folder, nm), bio.getvalue())
|
||||
return buf.getvalue(), proj + "-审核版.zip", None
|
||||
wb = Workbook()
|
||||
ws0 = wb.active
|
||||
ws0.title = "填写说明"
|
||||
ws0.column_dimensions["A"].width = 90
|
||||
for i, (t, bold) in enumerate([
|
||||
("「%s」导出件(决策 231)" % u["Name"], True),
|
||||
("", False),
|
||||
("一、本件由软件导出,可直接在「导入Excel」里对同一单位工程回导(整单位工程覆盖)。", False),
|
||||
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
|
||||
("三、只到清单级:不导定额、不导工料机。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if bold:
|
||||
c.font = Font(bold=True)
|
||||
h1 = _FB_HEAD_X
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in fb_rows(u["id"]):
|
||||
ws1.append(r)
|
||||
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
|
||||
ws1.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h1, 1):
|
||||
cell = ws1.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws1.freeze_panes = "A2"
|
||||
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
h2 = _CS_HEAD_X
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for b in bills.get(u["id"], []):
|
||||
if b["Kind"] != "prelim":
|
||||
continue
|
||||
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h2, 1):
|
||||
cell = ws2.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws2.freeze_panes = "A2"
|
||||
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
bio = _io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
def export_unit_xlsx(sc, sid, uw_id):
|
||||
"""单单位工程导 xlsx(决策 233 方案a,主人定):(字节, 文件名, 错误)。
|
||||
格式版面=决策 231 Excel 通道产出的单个文件(同一 _unit_workbook),可直接回导。"""
|
||||
if Workbook is None:
|
||||
return None, None, "缺少 openpyxl,无法导出 Excel"
|
||||
srow = sc.execute("SELECT x_manual FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow or not srow["x_manual"]:
|
||||
return None, None, "只有手工工程支持按单位工程导 Excel"
|
||||
u = sc.execute("SELECT * FROM s_unit_works WHERE id=? AND session_id=?", (uw_id, sid)).fetchone()
|
||||
if not u:
|
||||
return None, None, "单位工程不存在"
|
||||
divs = {}
|
||||
for r in sc.execute("SELECT * FROM s_divides WHERE session_id=? AND uw_id=? ORDER BY x_seq, id",
|
||||
(sid, uw_id)):
|
||||
divs.setdefault(r["uw_id"], []).append(dict(r))
|
||||
bills = {}
|
||||
for r in sc.execute("""SELECT * FROM s_bills WHERE session_id=? AND uw_id=?
|
||||
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""",
|
||||
(sid, uw_id)):
|
||||
bills.setdefault(r["uw_id"], []).append(dict(r))
|
||||
if not bills.get(uw_id) and not divs.get(uw_id):
|
||||
return None, None, "「%s」还没有清单数据,先「导入单位工程」" % (u["Name"] or "")
|
||||
raw = _unit_workbook(u, divs, bills)
|
||||
return raw, (_safe_sheet_name(u["Name"]) or "单位工程") + ".xlsx", None
|
||||
|
||||
Reference in New Issue
Block a user