refactor(cost): 优化LME成员去重与措施清单标签还原,清理临时核查脚本

This commit is contained in:
lianjianwei2024
2026-11-04 18:03:16 +08:00
parent 4e5a157687
commit 449d6d18ba
157 changed files with 82259 additions and 300 deletions

View File

@@ -1,33 +0,0 @@
# -*- coding: utf-8 -*-
"""主人指正:单位级和项目级都有这4个槽(ExtKind/Concrete/PriceSource/Delivery)。
重新到原文件核实:广联达件单位成员的 LME_SUM 是否真有这4列。"""
import sys
sys.path.insert(0, '.')
import classic_skeleton as cs
import sqlite3
import zipfile
import io
import re
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
con.row_factory = sqlite3.Row
r = con.execute("SELECT blob, original_name FROM classic_skel WHERE original_name LIKE '%广联达导出最新%'").fetchone()
src = zipfile.ZipFile(io.BytesIO(r['blob']))
for nm in src.namelist():
if not nm.lower().endswith('.xml'):
continue
t = src.read(nm).decode('utf-8', errors='replace')
if 'LabourMaterialsEquipmentsMachinesSummary' not in t:
continue
print(f'=== 成员: {nm[:40]} ===')
# 找 RGFTZ 行
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*Number="RGFTZ"[^>]*>', t):
line = m.group(0)
for col in ('ExtKind', 'Concrete', 'PriceSource', 'Delivery'):
hit = re.search(col + r'="([^"]*)"', line)
print(f' {col} = {hit.group(1) if hit else "(无属性)"}', end=' ')
print()
break
# 也看第 2 条四列行
break

View File

@@ -1,46 +0,0 @@
# -*- coding: utf-8 -*-
"""到原文件核查:广联达件里 RGFTZ(人工费调整)行的 26 列版与 30 列版
——各自在哪个成员、整行原文、逐字段差异。"""
import sys
sys.path.insert(0, '.')
import classic_skeleton as cs
import sqlite3
import zipfile
import io
import re
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
con.row_factory = sqlite3.Row
r = con.execute("SELECT blob FROM classic_skel WHERE original_name LIKE '%广联达导出最新%'").fetchone()
src = zipfile.ZipFile(io.BytesIO(r['blob']))
hits = [] # (成员, 行号(成员内), 原文整行)
for nm in src.namelist():
if not nm.lower().endswith('.xml'):
continue
t = src.read(nm).decode('utf-8', errors='replace')
try:
nm_disp = nm.encode('cp437').decode('gbk')
except Exception:
nm_disp = nm
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*Number="RGFTZ"[^>]*?/?>', t):
hits.append((nm_disp, m.group(0)))
print(f'RGFTZ 行共 {len(hits)} 条:')
for nm, line in hits:
cols = re.findall(r'(\w+)=', line)
print(f'--- {nm} ({len(cols)} 列) ---')
print(line[:600])
print()
# 逐字段 diff 两条不同列集的
if len(hits) >= 2:
import xml.etree.ElementTree as ET
a = dict(re.findall(r'(\w+)="([^"]*)"', hits[0][1]))
b = dict(re.findall(r'(\w+)="([^"]*)"', hits[1][1]))
keys = list(dict.fromkeys(list(a) + list(b)))
print('=== 逐字段差异 ===')
for k in keys:
va, vb = a.get(k, '(无)'), b.get(k, '(无)')
if va != vb:
print(f' {k}: {va!r} vs {vb!r}')

View File

@@ -1,47 +0,0 @@
# -*- coding: utf-8 -*-
"""续:30 列版(Project.xml)与 26 列版逐字段 diff;并统计全部成员分布。"""
import sys
sys.path.insert(0, '.')
import classic_skeleton as cs
import sqlite3
import zipfile
import io
import re
import xml.etree.ElementTree as ET
con = sqlite3.connect(r'D:/PricingReview/CostReview/data/history.db')
con.row_factory = sqlite3.Row
r = con.execute("SELECT blob FROM classic_skel WHERE original_name LIKE '%广联达导出最新%'").fetchone()
src = zipfile.ZipFile(io.BytesIO(r['blob']))
tp = src.read('Project.xml').decode('utf-8', errors='replace')
m30 = re.search(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*Number="RGFTZ"[^>]*/?>', tp)
line30 = m30.group(0)
a30 = dict(re.findall(r'(\w+)="([^"]*)"', line30))
# 单位成员里的 26 列版取一条(@_30_我是单位工程1.xml)
mu = None
for nm in src.namelist():
if not nm.lower().endswith('.xml'):
continue
t = src.read(nm).decode('utf-8', errors='replace')
mm = re.search(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*Number="RGFTZ"[^>]*/>', t)
if mm:
mu = nm
line26 = mm.group(0)
break
a26 = dict(re.findall(r'(\w+)="([^"]*)"', line26))
print('=== 26 列版(单位成员)vs 30 列版(项目成员)逐字段 ===')
keys = list(dict.fromkeys(list(a26) + list(a30)))
print(f'{"字段":22s} {"26列版(单位)":>20s} {"30列版(项目)":>20s}')
for k in keys:
v26, v30 = a26.get(k, '(无)'), a30.get(k, '(无)')
mark = ' ←不同' if v26 != v30 else ''
print(f' {k:22s} {v26!r:>16s} {v30!r}{mark}')
print()
print('列数: 26列版', len(a26), '列 | 30列版', len(a30), '列')
only26 = [k for k in a26 if k not in a30]
only30 = [k for k in a30 if k not in a26]
print('仅26列版有:', only26)
print('仅30列版有:', only30)

View File

@@ -16,7 +16,7 @@
覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价);
改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。
"""
import json
import json, os, threading
_QTY_EXPR_OK = __import__("re").compile(r"^[\d+\-*/().\s]*$")
@@ -159,11 +159,11 @@ def _price_map(sc, sid):
def _uw_price_rows(sc, sid):
"""决策 219(2026-10-26 主人定):单位级取价——**每个单位工程每码认导入顺序第一行**
(同一单位工程同码不同价=随便认一个,主人定;不同单位工程各认各的)。
决策 259:行另带六价扩展四值(ntp_org/ntp_expr/taxp_org/taxp_expr)与 x_flags
(文字/标志属性 JSON)——「骨架不能创造数据」,导出端按行真值灌/无源删。
{code: [行dict(uw 去重、id 序)]},行含 uw_id/名规单/类别/三价/六价扩展/flags。"""
"""决策 219(2026-10-26 主人定):单位级取价——**同单位工程内按成员(码+除数量外全字段)
分行**(2026-11-04 主人补:除数量外任一字段不同就是独立成员,不能合并/累计);
同字段组合的多行才是同一成员(数量累计,价格取该行)。
{code: [行dict(按 uw+成员 去重、id 序)]},行含 uw_id/名规单/类别/三价/六价扩展/flags。
项目级汇总(_dyn_rows uw_id=None)以这张表为分组基础——单位级先对,项目级才对。"""
out = {}
for r in sc.execute("""SELECT id, uw_id, code, name, spec, unit, kind, ntp, taxrate, taxp,
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags
@@ -171,9 +171,14 @@ def _uw_price_rows(sc, sid):
if not r["code"]:
continue
lst = out.setdefault(r["code"], [])
if any(str(m["uw_id"]) == str(r["uw_id"]) for m in lst):
continue # 同一单位工程同码只认第一行
lst.append(dict(r))
key = (str(r["uw_id"]), r["name"], r["spec"], r["unit"], r["kind"],
r["ntp"], r["taxrate"], r["taxp"],
r["ntp_org"], r["ntp_expr"], r["taxp_org"], r["taxp_expr"], r["x_flags"])
if any(m.get("_mk") == key for m in lst):
continue # 同单位同成员(字段全同)→ 合成一行
d = dict(r)
d["_mk"] = key
lst.append(d)
return out
@@ -246,17 +251,19 @@ def manual_price_codes(sc, sid):
return set()
def dyn_rows(sc, sid, uw_id=None):
def dyn_rows(sc, sid, uw_id=None, keep_zero=False):
"""动态汇总行(11 列同 _lme_rows 形状):[id,code,name,spec,unit,qty,ntp,taxrate,taxp,kind,remark]。
id=项目级行 id(存在时)——前端行级改价按它定位;骨架行无库行时 id=None。
防御:计算链不完整(老库/测试假库缺表缺列)→ 返回 None,调用方退回快照老路。"""
防御:计算链不完整(老库/测试假库缺表缺列)→ 返回 None,调用方退回快照老路。
keep_zero=True:2026-11-04 主人定「数量 0 也要参与合并工料机」——合并弹框取全量现算行,
汇总页仍走默认过滤(决策 209 显示口径不动)。"""
try:
return _dyn_rows(sc, sid, uw_id)
return _dyn_rows(sc, sid, uw_id, keep_zero)
except Exception:
return None
def _dyn_rows(sc, sid, uw_id=None):
def _dyn_rows(sc, sid, uw_id=None, keep_zero=False):
kids = _children_map(sc, sid)
pm = _price_map(sc, sid)
ov = _overrides(sc, sid)
@@ -301,10 +308,23 @@ def _dyn_rows(sc, sid, uw_id=None):
_pk(r and r["taxrate"], p.get("taxrate")),
_pk(_pk(r and r["taxp"], p.get("taxp")), lb[1]))
def _one_price_set(ch):
"""同一母码可能按单位工程挂多套组成(ESCC:一处无后缀套、别处 -0003 换算套)——
母价 Σ 只取**第一套**(按子码基码去重),避免两套相加把台班单价翻倍;
数量传导仍用全量(变体子码各自得量)。"""
seen, out = set(), []
for c, q, nm in ch:
base = (c or "").split("-")[0]
if base in seen:
continue
seen.add(base)
out.append((c, q, nm))
return out
def computed_mother(code, uw=None):
"""带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。"""
sn = st = 0.0
for c, q, _nm in kids.get(code) or ():
for c, q, _nm in _one_price_set(kids.get(code) or ()):
ntp, _rt, taxp = child_px(c, uw)
if ntp is None or taxp is None:
return None, None
@@ -346,10 +366,15 @@ def _dyn_rows(sc, sid, uw_id=None):
ntp = _ln
if taxp is None:
taxp = _lt
if kids.get(code) and not ov.get(code):
# 2026-11-04 主人按原件定(990401025 载货汽车 552.75 / 637.29 两价并存、各配一套子级):
# **有源价用源价,只有缺价时才用 Σ 子级兜底**——决策 188 的「带子级母行单价=Σ子级」
# 据此收窄:若强行 Σ 覆盖,同码多成员(不同价)会被算成同一个价,违反
# 「除数量外字段不一致就分多条」的显示规则(原版就是两条)。
if kids.get(code) and not ov.get(code) and (ntp is None or taxp is None):
cn, ct = computed_mother(code, r.get("uw_id"))
if cn is not None:
ntp, taxp = cn, ct
ntp = ntp if ntp is not None else cn
taxp = taxp if taxp is not None else ct
return [p.get("id"), code, r.get("name") or "", r.get("spec") or "", r.get("unit") or "",
qty, ntp, rate, taxp, r.get("kind"), p.get("x_remark"), # 决策 203:备注随行(采纳/手工同字段)
*org4, ((r.get("x_flags") if r.get("x_flags") is not None else p.get("x_flags"))
@@ -373,25 +398,17 @@ def _dyn_rows(sc, sid, uw_id=None):
else:
# —— 项目级(决策 219):全字段+三价一致的单位级行才并成一行,不一致各自独立;
# 行量=各成员单位现算量之和(真实归属,不按比例分摊)
buckets = _consumption_by_code(sc, sid, None, by_uw=True)
qmaps = {}
for u, m in buckets.items():
qm = dict(m)
for mcode, mch in kids.items(): # 子级推导(决策 188 数量模型,分桶同款)
mq = qm.get(mcode)
if mq is None:
continue
for c, q, _nm in mch:
try:
qm[c] = qm.get(c, 0.0) + float(mq) * float(q or 0)
except (TypeError, ValueError):
pass
qmaps[u] = qm
# 2026-11-04 主人定「改哪个单位只算哪个单位」:量图走缓存(qmap_all_cached),
# 分桶+子级传导收敛到 _propagate 一处(取代此前活读迭代,与 qty_map_uw 快照迭代
# 两处不一致的写法——仅「子级自己带子级」时两法才有差异,现库无此情形)。
qmaps = qmap_all_cached(sc, sid)
groups, gidx = [], {}
for code, lst in uwp.items(): # 顺序锚=单位级行 id 序(源文件序)
for r in lst:
k = (code, r["name"] or "", r["spec"] or "", r["unit"] or "", r["kind"],
r["ntp"], r["taxrate"], r["taxp"])
r["ntp"], r["taxrate"], r["taxp"],
r.get("ntp_org"), r.get("ntp_expr"), r.get("taxp_org"), r.get("taxp_expr"),
r.get("x_flags")) # 2026-11-04:成员=除数量外全字段(任一不同各成一行)
g = gidx.get(k)
if g is None:
g = {"code": code, "r": r, "uws": []}
@@ -433,6 +450,9 @@ def _dyn_rows(sc, sid, uw_id=None):
break
# 决策 209(2026-10-26 主人定):显示端与导出端一致(199)——数量为 0 的行整行不显示,
# 取代 196「骨架保行」的显示端口径;导出端 199 与 qty_map_uw 供数链不经过此处,不动。
# 2026-11-04 主人定(合并工料机):keep_zero=True 时全量返回——0 量品种也要能参与合并。
if keep_zero:
return rows
return [r for r in rows if r[5] is not None and float(r[5]) != 0]
@@ -457,18 +477,132 @@ def _dyn_rows_safe9(sc, sid, uw_id):
def _dyn_uw_rows_old(sc, sid, uw_id):
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8]] for r in dyn_rows(sc, sid, uw_id)]
# ── 量图缓存(2026-11-04 主人定「改哪个单位只算哪个单位,项目级再汇总」)──────────
# 现算结果 {uw_id: {码: 量}} 按 (库文件路径, 会话id) 挂进程内存:
# · 读(单位级卡/项目级卡/合并弹框/导出/检索)统一走 qmap_all_cached——首次惰性建
# (一次全扫,成本=原项目级卡一次现算),之后其余单位继续用缓存;
# · 改定额量/清单量/定额消耗量 → api_server 路由层在 commit 后调 qmap_touch_uw
# 只重算该单位;含量编辑/临删恢复/采纳/结构增删/合并/重解析 → qmap_drop 全失效;
# · 库文件 mtime 兜底网:任何漏钩写入(含外部进程)都会在下一次读取被发现并整图重建;
# · :memory: 库(pytest 假库)不缓存直接现算——与旧全算行为一致,测试无隔离风险。
# 母子传导收敛:_propagate 一处实现(从直接消耗量快照出发、只传一层,决策 268补三 口径),
# 取代此前 qty_map_uw(快照迭代)与项目级分桶(活读迭代)两处不一致的写法(2026-11-04 主人拍板)。
_QLOCK = threading.Lock()
_QCACHE = {} # (db_path, sid) -> {"mtime": float, "maps": {uw_id: {码: 量}}}
def _qpath_mt(sc):
"""(库文件路径, mtime);:memory: 路径为空 → 调用方旁路缓存。"""
path = ""
try:
for r in sc.execute("PRAGMA database_list").fetchall():
if r[1] == "main":
path = r[2] or ""
break
except Exception:
path = ""
mt = 0.0
if path:
try:
mt = os.path.getmtime(path)
except OSError:
mt = 0.0
return path, mt
def qmap_mtime_of(sc):
"""写入口取「写前库 mtime」用(api_server 持 WRITE_LOCK,读与写同线程同库)。"""
return _qpath_mt(sc)[1]
def _propagate(base, kids):
"""母子传导唯一实现:子量 = 母量 × 子含量,从直接消耗量快照出发只传一层
(决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。"""
out = dict(base)
for mcode, mq in base.items():
if mq is None:
continue
for c, q, _nm in kids.get(mcode) or ():
try:
out[c] = out.get(c, 0.0) + float(mq) * float(q or 0)
except (TypeError, ValueError):
pass
return out
def _qmap_build_all(sc, sid):
consume = _consumption_by_code(sc, sid, None, by_uw=True)
kids = _children_map(sc, sid)
return {u: _propagate(m, kids) for u, m in consume.items()}
def qmap_all_cached(sc, sid):
"""全单位量图缓存读口:{uw_id: {码: 现算量}}。链不全(老库缺列)照旧抛 RuntimeError,
由 dyn_rows 退 None 走快照老路——与全算时代同一退路。"""
path, mt = _qpath_mt(sc)
if not path:
return _qmap_build_all(sc, sid)
key = (path, int(sid))
with _QLOCK:
ent = _QCACHE.get(key)
if ent is not None and ent["mtime"] == mt:
return ent["maps"]
maps = _qmap_build_all(sc, sid)
with _QLOCK:
_QCACHE[key] = {"mtime": mt, "maps": maps}
return maps
def qmap_touch_uw(sc, sid, uw_id, pre_mt=None):
"""「改哪个单位只算哪个单位」:只重算该单位量图、刷缓存戳(其余单位继续用缓存)。
调用约定:api_server 在 commit 之后、WRITE_LOCK 之内调用;pre_mt=写前库 mtime——
与缓存戳不一致说明其间有别的写者插队,保守放弃缓存(下次读取整图重建)。"""
path, mt_now = _qpath_mt(sc)
if not path:
return
key = (path, int(sid))
with _QLOCK:
ent = _QCACHE.get(key)
if ent is not None and pre_mt is not None and ent["mtime"] != pre_mt:
_QCACHE.pop(key, None) # 期间有并发写 → 缓存不可信,整图放弃
ent = None
if ent is None:
return
try:
umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid))
except Exception:
with _QLOCK:
_QCACHE.pop(key, None)
return
with _QLOCK:
ent = _QCACHE.get(key)
if ent is not None:
ent["maps"][uw_id] = umap
ent["mtime"] = mt_now
def qmap_drop(sid=None):
"""量图全失效(含量编辑/临删恢复/采纳/结构增删/合并/重解析/删会话);
sid=None 清全部(测试收尾用)。下次读取整图重建一次,成本=原项目级卡一次现算。"""
with _QLOCK:
if sid is None:
_QCACHE.clear()
else:
for k in [k for k in _QCACHE if k[1] == int(sid)]:
_QCACHE.pop(k, None)
def qty_map_uw_all(sc, sid):
"""全部单位工程的 {uw_id: {码: 现算数量}}——量图缓存读口(2026-11-04 主人定)。
首次一次全扫建缓存,之后读缓存;改定额量/清单量由写入口单算刷新(qmap_touch_uw),
其余数量链改动整图失效(qmap_drop)。与旧「一次扫描」同形同值。"""
return qmap_all_cached(sc, sid)
def qty_map_uw(sc, sid, uw_id):
"""决策 188 数量模型(主人定稿)——某单位工程的 {码: 数量} 现算图:
母/直挂: Σ(定额含量 × 定额真实工程量)
子工料机: Σ(子含量 × 母定额含量 × 定额真实工程量) (=母量×子含量,数学全等已证)
只算不写库(原字段不动);导出/显示共同数据源。"""
consume = _consumption_by_code(sc, sid, uw_id)
kids = _children_map(sc, sid)
out = dict(consume)
for mcode, mq in consume.items():
for c, q, _nm in kids.get(mcode) or ():
try:
out[c] = out.get(c, 0.0) + mq * float(q or 0)
except (TypeError, ValueError):
pass
return out
只算不写库(原字段不动);导出/显示共同数据源。
2026-11-04:走量图缓存(qmap_all_cached)——首次建缓存=一次全扫,之后从缓存取。"""
return qmap_all_cached(sc, sid).get(uw_id) or {}

View File

@@ -289,7 +289,7 @@ def _emit_prelim(pre, u, plan, tmpls, norm_db, children):
bills = [b for b in (u.get("bills") or []) if b.get("kind") == "prelim" and not b.get("x_tdel")]
divs = [x for x in (plan.get("divides") or {}).values()
if x["uw_id"] == u["id"] and x.get("kind") == "prelim"]
if tmpls.get("pre_bill") is None:
if tmpls.get("pre_bill") is None and tmpls.get("bill") is None:
return
by_div = {}
for b in bills:
@@ -299,7 +299,12 @@ def _emit_prelim(pre, u, plan, tmpls, norm_db, children):
by_parent.setdefault(x.get("parent_id"), []).append(x)
def emit_bill(b):
return _emit_bill(b, tmpls["pre_bill"], tmpls, norm_db, children)
# 2026-11-04:措施清单有两种原生标签形态(UnitWorksPreliminaryWorkElement / WorkElement),
# 导入时存 x_ptag,导出按原形态还原(否则会被统一成一种,结构就变形了)。
tag = b.get("x_ptag") or ""
_pre = tmpls.get("pre_bill")
tmpl = tmpls["bill"] if tag == "WorkElement" else (_pre if _pre is not None else tmpls["bill"])
return _emit_bill(b, tmpl, tmpls, norm_db, children)
def emit_div(dv):
el = _deep(tmpls["pre_div"])
@@ -583,28 +588,77 @@ def _emit_proj_side(proj, side_json):
_merge_side(target, node, cols)
def _tag_cols(root):
cols = {}
for el in root.iter():
if isinstance(el.tag, str):
cols.setdefault(el.tag, set()).update(el.attrib.keys())
return cols
def _own_layers(plan):
"""本项目骨架的**数据层**要求(2026-11-04 主人定:列不算全部数据,只要数据层能全部导出)。
→ (需要存在的层标签集合, 措施清单原生标签集合, 是否有措施分部)。"""
need = set()
prelim_tags = set()
if plan.get("units"):
need.add("UnitWorks")
has_item = has_prelim = has_norm = has_res = False
need_prelim_div = False
for d in (plan.get("divides") or {}).values():
if d.get("kind") == "prelim":
need_prelim_div = True
else:
need.add("DivisionalWorks")
for u in plan.get("units") or []:
for b in u.get("bills") or []:
if b.get("x_tdel"):
continue
if b.get("kind") == "prelim":
has_prelim = True
if b.get("x_ptag"):
prelim_tags.add(b["x_ptag"])
else:
has_item = True
for n in b.get("norms") or []:
if n.get("x_tdel"):
continue
has_norm = True
if n.get("x_adjust"):
need.add("NormAdjustmentList")
if n.get("res"):
has_res = True
if has_item or (has_prelim and "WorkElement" in prelim_tags):
need.add("WorkElement")
if has_prelim:
need.add("PRELIM")
if has_norm:
need.add("Norm")
if has_res:
need.add("LabourMaterialsEquipmentsMachinesElement")
if any((u.get("lme") or []) for u in plan.get("units") or []):
need.add("LabourMaterialsEquipmentsMachinesSummary")
return need, prelim_tags, need_prelim_div
def _missing_layers(need, prelim_tags, need_prelim_div, tags):
"""层覆盖判定(**不看列**):缺层才判不覆盖;列少不算。"""
miss = [t for t in need if t != "PRELIM" and t not in tags]
if "PRELIM" in need:
if prelim_tags:
for t in prelim_tags:
if t not in tags:
miss.append(t)
elif not any(t in tags for t in ("UnitWorksPreliminaryWorkElement", "WorkElement")):
miss.append("PRELIM")
if need_prelim_div and "PreliminaryDivisionalWorks" not in tags:
miss.append("PreliminaryDivisionalWorks")
return miss
def export_v2(con, sc, sid, suffix, progress=None, src_path=None):
"""骨架回灌导出:空骨架(结构)+ 会话数据 → 原格式包。"""
rep = classic_skeleton.pick_frame(con, (suffix or "").lower(), src_path=src_path)
blank = meta = None
if rep:
blank, meta = _blank_and_meta(con, rep, suffix)
if not blank and src_path and os.path.exists(src_path):
# 库里还没有该后缀的骨架:就地按源件提炼一件**内存骨架**(不落库)——
# 骨架库为空的新环境也能导出;有骨架时仍以库里的为准(匹配度挑选)。
try:
blank, meta = classic_skeleton.refine_blank_ex(
open(src_path, "rb").read(), suffix)
except Exception:
blank, meta = None, None
if not blank:
return None, None, "该后缀还没有骨架:请先在后台导入"
skel_root, decl = classic_skeleton._blank_parse(blank.decode("utf-8"))
norm_db = {}
for r in sc.execute("""SELECT n.id, n.Total AS db_total
FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
WHERE b.session_id=?""", (sid,)):
norm_db[r["id"]] = r["db_total"]
"""骨架回灌导出(2026-11-04 决策267):**优先本项目自己的骨架**(打开工程时从源件提炼入库);
数据层列覆盖不全 → 后台骨架补充缺列;缺整层 → 回落后台骨架;再不行用源件现提炼。"""
plan = build_plan(sc, sid)
if plan is None:
return None, None, "会话数据读不出来"
@@ -622,6 +676,50 @@ def export_v2(con, sc, sid, suffix, progress=None, src_path=None):
except Exception:
attr_map = {}
# ===== 骨架选择:本项目骨架优先(只看数据层是否齐全;列少不算不覆盖) =====
need, prelim_tags, need_prelim_div = _own_layers(plan)
try:
own_blank = srow["x_own_blank"]
except (KeyError, IndexError):
own_blank = None
own_meta = None
try:
if srow["x_own_meta"]:
own_meta = json.loads(srow["x_own_meta"])
except (KeyError, IndexError, ValueError, TypeError):
own_meta = None
rep = None
blank = meta = None
if own_blank:
try:
oroot, _od = classic_skeleton._blank_parse(bytes(own_blank).decode("utf-8"))
tags = {el.tag for el in oroot.iter() if isinstance(el.tag, str)}
miss = _missing_layers(need, prelim_tags, need_prelim_div, tags)
if not miss:
blank, meta = bytes(own_blank), own_meta
except Exception:
blank, meta = None, None
if not blank:
if rep is None:
rep = classic_skeleton.pick_frame(con, (suffix or "").lower(), src_path=src_path)
if rep:
blank, meta = _blank_and_meta(con, rep, suffix)
if not blank and src_path and os.path.exists(src_path):
# 库/本项目骨架都没有:就地按源件提炼一件内存骨架(不落库)
try:
blank, meta = classic_skeleton.refine_blank_ex(
open(src_path, "rb").read(), suffix)
except Exception:
blank, meta = None, None
if not blank:
return None, None, "该后缀还没有骨架:请先在后台导入"
skel_root, decl = classic_skeleton._blank_parse(blank.decode("utf-8"))
norm_db = {}
for r in sc.execute("""SELECT n.id, n.Total AS db_total
FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
WHERE b.session_id=?""", (sid,)):
norm_db[r["id"]] = r["db_total"]
# 单位工程模板=骨架里内嵌的那棵单位子树(项目骨架同一位置换成 N 条索引行)
unit_tmpl = None
for par in skel_root.iter():

View File

@@ -27,7 +27,7 @@ REGION = ("广东省", "珠海市", "香洲区")
# 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。
# 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。
# 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。
PARSER_VER = "2026.11.03-4" # 2026.11.03-4:项目级非数据层整棵采集(x_side:SummaryOfCost 两处/AddiCost/ProjectInstallationWorkCostSummary…;老批次需重导);-3:单位工程非数据层 x_attr;-2:清单/定额固定子块 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259)
PARSER_VER = "2026.11.04-1" # 2026.11.04-1:清单 x_ptag 采集(措施清单原生标签 WorkElement / UnitWorksPreliminaryWorkElement,导出按原形态还原;老批次需重导);-2026.11.03-4:项目级非数据层 x_side;-3:单位工程 x_attr;-2:清单/定额 x_side;-1:x_flags 补采 ProviderBase/Weight;2026.11.02-1:lme_uw 尾部追加 x_flags(决策 259)
# LME_SUM 行的文字/标志属性集(2026-11-02 主人定「原文件有按原文件导,没有则不导出」):
# 数值属性(量/价/合价)另有专列,不在此列;Remark 属数据性质备注,一并按原文件采。
@@ -346,6 +346,7 @@ def parse_std(path, out):
out.setdefault("bill_uw", []).append(out.get("cur_uw", -1))
out.setdefault("bill_kind", []).append("prelim" if out.get("in_prelim") else None)
out.setdefault("bill_div", []).append(out.get("cur_div")) # 归属分部
out.setdefault("bill_tag", []).append("WorkElement")
# 措施项目条目(UnitWorksPreliminaryWorkElement)
# ★ 2026-09-29 决策 17:措施条目**进** bills(Kind='prelim'),它的 Norm 挂在自己名下,
@@ -362,6 +363,7 @@ def parse_std(path, out):
out.setdefault("bill_uw", []).append(out.get("cur_uw", -1))
out.setdefault("bill_kind", []).append("prelim")
out.setdefault("bill_div", []).append(out.get("cur_div")) # 措施清单归措施分部
out.setdefault("bill_tag", []).append("UnitWorksPreliminaryWorkElement")
# ⚠️ 2026-09-30:Project.xml 里也埋着一份 UnitWorks(那是汇总用的**引用节点**,不是真实单位工程)。
# 照单全收会让单位工程数量翻倍 —— 横琴 40 实为 20、三溪 28 实为 14,还连带一半没有造价构成。
@@ -972,7 +974,7 @@ def parse_esc(path, out):
st = {"sp": None, "unit": None, "in_bill": False, "in_measure": False,
"div_stack": [], "mdiv_stack": [], "cur_bill": -1, "cur_norm": -1,
"sec_seen": set(), "uw_nums": set()}
"sec_seen": set(), "uw_nums": set(), "cur_res": ""}
def add_divide(kind, number, name, total, parent=None):
u = st["unit"]
@@ -1062,8 +1064,16 @@ def parse_esc(path, out):
(a.get("Unit") or "").strip(), f(a.get("Quantity")),
f(a.get("Price")), f(a.get("Total"))))
elif tag == "ResElementItem":
# 定额消耗(在 Norm 内)或清单级资源引用(ResElements 直挂 Bill)——后者跳过
if st["cur_norm"] >= 0:
# ① 台班 / 配合比的下一级组成(本 ResourceItem 内;决策 265 扩展 2026-11-04)
_pr = st.get("cur_res") or ""
if _pr:
_cc = (a.get("ResCode") or "").strip()
if _cc:
_lst = out["lme_res"].setdefault(_pr, [])
if all(x[0] != _cc for x in _lst): # 同子码只收第一份
_lst.append((_cc, f(a.get("Quantity"))))
# ② 定额消耗(在 Norm 内)或清单级资源引用(ResElements 直挂 Bill)——后者跳过
elif st["cur_norm"] >= 0:
out["norm_res"].append((st["cur_norm"], (a.get("ResCode") or "").strip(),
f(a.get("Quantity")), None))
elif tag == "ExpressItem":
@@ -1074,6 +1084,17 @@ def parse_esc(path, out):
out.setdefault("bill_expr", {})[st["cur_bill"]] = ex
elif tag == "ResourceItem":
code = (a.get("Code") or "").strip()
# 决策 265 扩展(2026-11-04 主人定「数据只来源原数据」):ESCC2 的台班/配合比
# 组成挂在本 ResourceItem 的 ResElements > ResElementItem 下,此前整层漏采 →
# 导入后 s_lme_res 恒空,只能靠采纳从别的批次借(数据来源不纯、还会跨批次重复)。
# 每码只收第一份:同一台班在每个单位工程汇总里重复声明、内容一致(与 COS/SWT 同口径)。
if code and (a.get("Name") or "").strip():
out["lme_name"].setdefault(code, (a.get("Name") or "").strip())
# 2026-11-04 主人定「都有引用啊」:同一台班在不同单位工程可带不同组成
# (如 990401025 一处是 00010003 套、别处是 00010003-0003 换算套)——
# 只收第一份会把变体码整批丢掉(→ 被引用集判为未引用 → 剪枝 → 合并弹框缺品种)。
# 改为每个声明都收、子码去重(同子码含量取第一份)。
st["cur_res"] = code
if not code:
pass
elif st["unit"] is not None and st.get("_uw_res"):
@@ -1144,6 +1165,8 @@ def parse_esc(path, out):
st["mdiv_stack"].pop()
elif st["in_bill"] and st["div_stack"]:
st["div_stack"].pop()
elif tag == "ResourceItem":
st["cur_res"] = "" # 组成采集只在本 ResourceItem 范围内(决策 265 扩展)
elif tag == "Bill":
st["cur_bill"] = -1
st["cur_norm"] = -1
@@ -1411,12 +1434,13 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None
cur.execute("""INSERT INTO bills(batch_id, uw_id, div_id, Number, Name, Attr, Unit,
Quantity, Price, Total, Kind, src_remark,
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq, x_side, x_ptag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk,
norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("bill_side") or {}).get(i))))
(out.get("bill_side") or {}).get(i)),
((out.get("bill_tag") or [])[i] if i < len(out.get("bill_tag") or []) else None)))
n_bill += 1
bill_ids.append(cur.lastrowid)
seen_bill.add(h)
@@ -1639,3 +1663,5 @@ def main():
if __name__ == "__main__":
main()

View File

@@ -266,16 +266,18 @@ def wipe(con, sid, clean_orphans=True):
def dedupe_lme_res(con=None):
"""存量自愈:s_lme_res 按 (session_id, p_code, res_code, qty, seq) 去重,保最新一行。
"""存量自愈:s_lme_res 按 (session_id, p_code, res_code) 去重,保最新一行。
2026-10-10 一次性清理(上面 wipe 漏表的存量受害者),幂等——反复跑无副作用。
2026-11-04 主人定「耗弹框不许重复」:去重键去掉 qty/seq——此前同码不同 qty/seq 的重复套
(采纳补子级跨批次灌入的脏数据)能躲过去重、弹框照样重复;组成同码只该有一条。
保留 MAX(rowid):越新的行采集口径越全(name 列早期常为空)。"""
own = con is None
if own:
con = connect()
con.execute("""DELETE FROM s_lme_res WHERE rowid NOT IN
(SELECT MAX(rowid) FROM s_lme_res
GROUP BY session_id, p_code, res_code, qty, seq)""")
GROUP BY session_id, p_code, res_code)""")
if own:
con.commit()
con.close()
@@ -494,12 +496,14 @@ def connect():
# 2026-10-18:定额换算调整记录(JSON,采纳携带;决策 106 补记十三)
("s_norms", ("x_adjust TEXT",)),
# 2026-11-03:结构固定子块原样值(单价行/管理费/费用构成/表达式行,JSON 文档序)
("s_bills", ("x_side TEXT",)),
("s_bills", ("x_side TEXT", "x_ptag TEXT")),
("s_norms", ("x_side TEXT",)),
# 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环)
("s_unit_works", ("x_attr TEXT",)),
# 2026-11-03:项目级非数据层结构树
("sessions", ("x_side TEXT",)),
# 2026-11-04:本项目自己的空骨架(打开工程时提炼,导出优先用)
("sessions", ("x_own_blank BLOB", "x_own_meta TEXT")),
):
for col in cols:
try:
@@ -697,14 +701,15 @@ def open_project(con, files, meta, job, sid=None):
cur.execute("""INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit,
Quantity, Price, Total, Kind, src_remark,
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq,
x_price0, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_price0, x_side, x_ptag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk,
norm(nm), norm(attr), norm(unit),
md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq,
price, # 决策 217:x_price0=第一次导进来的单价,此后改价/采纳不更新
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("bill_side") or {}).get(i))))
(out.get("bill_side") or {}).get(i)),
((out.get("bill_tag") or [])[i] if i < len(out.get("bill_tag") or []) else None)))
# 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义);
# 与 history.db.bills(import_job)同口径,启动迁移重算老数据
bill_ids.append(cur.lastrowid)
@@ -823,3 +828,4 @@ def open_project(con, files, meta, job, sid=None):
con.commit()
return sid, stat

View File

@@ -359,6 +359,15 @@ def build_blank(blob, ind_unit=" "):
return text, derive_meta(roots_for_meta)
unit_best = max(units, key=lambda r: len(list(r.iter())))
unit = collapse(unit_best)
# 2026-11-04 决策267:单位骨架取**全成员并集**——只取一个成员会丢别的成员才有的
# 层/列(实测:本项目分部 13 列、某个成员只有 7 列,导致导出丢列)。值仍为空。
for _u in units:
if _u is unit_best:
continue
try:
collapse_into(unit, collapse(_u))
except Exception:
continue
# 连接:主骨架里第一条带 FileName 的索引行 → 换成单位骨架
placed = False
for par in main.iter():
@@ -377,7 +386,7 @@ def build_blank(blob, ind_unit=" "):
# 退化样例(Project.xml 没有单位索引行):单位骨架直接挂主根,导出端仍能按它建成员
main.append(unit)
text = _serialize(main, ind_unit)
meta = derive_meta(mains + [unit_best], unit_tag=unit_best.tag)
meta = derive_meta(mains + units, unit_tag=unit_best.tag)
# 决策 264:记下被替换掉的**索引行**(导出时按它复制成 N 行),否则项目索引无法还原
meta["index_row"] = {"tag": None, "attrs": []}
for par in collapse(mains[0]).iter():