feat(export): 决策263-266 单一骨架导出通路/数据全量入库/空骨架规则标注/导入按内容判族

- 决策 263:定额单价专题(三同合并全字段统一、原价三级链、LME Summary 26 属性收口、x_flags 采集、e2e 回归)
- 决策 264 补记五:原格式导出只保留骨架回灌一条通路;删除 export_cos.export_zip 旧引擎;新增 skeleton_engine(内容判族/唯一结构位/结构旁注/路径指纹);单位级/项目级非数据层 x_attr/x_side 采集与回灌;导出件成员名改 GBK 原始字节(_GbkZipInfo);后台「导出设置」导出空骨架(标注)
- 决策 265:导入按内容判族(zip 内含 ConstructProject→SWT 族,否则 COS 族;裸 XML 同),扩展名不参与拦截;api_scan 取消 EXT_OK 过滤
- 决策 266:结构位统一「自增区域/自增块/自增行」,取消「固定」;min_count(区域1/块行0),导出条数=max;区域数据0条保底1空壳;LME 汇总两形态(带组成闭合块/普通自闭合行)按行硬分派
- 前序未提交:HTML 导出整体移除(export_html.py 删除)、Excel 导出加序号列并移除说明页、.yhy 导入(import_yhy.py)
- 测试:367 passed / 3 skipped;新增 test_topic_price/test_yhy_import/test_import_suffix 等
This commit is contained in:
lianjianwei2024
2026-11-03 23:39:46 +08:00
parent 5470286f66
commit 78e58a40c7
40 changed files with 2700 additions and 1373 deletions

View File

@@ -43,8 +43,8 @@ import dyn_lme # 决策 188:动态工料机汇总引擎(方
import lme_skeleton # 决策 197:工料机骨架库(后缀+字段签名组,代表件大骨架)
import classic_skeleton # 决策 231:经典整件骨架库(手工工程导出模板,连保留值存)
import export_manual # 决策 231:手工工程导出 cos/cos4(经典骨架当模板填空)
import export_html # 2026-11-03:HTML 导出(界面数据全量单文件,含审核备注)
import export_yhy # 2026-11-03:.yhy 专有格式导出(审核等全部数据,租户交流)
import import_yhy # 2026-11-03:.yhy 导入(id 整体平移法,主人定)
import match # 比对引擎(M4)
import export_cos as xcos # 导出回写(批次D,决策 70)
import formats # 导出格式适配器(2026-10-19:SWT/SWZ 骨架/填空)
@@ -98,13 +98,15 @@ def classify(path, fn):
def api_scan():
"""列出待导入目录里的文件(后台导入用)"""
"""列出待导入目录里的文件(后台导入用)。
2026-11-03(A 方案):**不按扩展名过滤**——能不能导入由内容决定(classify/sniff),
同族新后缀(.cos5/.xml/.abc…)一样列出来;认不出的显示状态,用户自己判断。"""
files = []
try:
for fn in sorted(os.listdir(SRC_DIR)):
if not fn.lower().endswith(EXT_OK):
continue
p = os.path.join(SRC_DIR, fn)
if not os.path.isfile(p) or fn.startswith("."):
continue
st = classify(p, fn)
files.append({"name": fn, "path": p, "size": os.path.getsize(p), "state": st})
except Exception as e:
@@ -140,6 +142,15 @@ def ensure_attach_schema():
con.execute("ALTER TABLE bills ADD COLUMN x_setkey TEXT")
if "x_setkey" not in lcols:
con.execute("ALTER TABLE lmes ADD COLUMN x_setkey TEXT")
# 2026-11-03:结构固定子块原样值(单价行/管理费/费用构成/表达式行;JSON 文档序)
ncols = [r[1] for r in con.execute("PRAGMA table_info(norms)")]
if "x_side" not in bcols:
con.execute("ALTER TABLE bills ADD COLUMN x_side TEXT")
if "x_side" not in ncols:
con.execute("ALTER TABLE norms ADD COLUMN x_side TEXT")
ucols = [r[1] for r in con.execute("PRAGMA table_info(unit_works)")]
if "x_attr" not in ucols:
con.execute("ALTER TABLE unit_works ADD COLUMN x_attr TEXT")
# 2026-10-06:价格条数从 x_rows_lme 拆出来,单独一列。
# x_rows_lme 此前被复用(项目=工料机数 / 价格批次=价格数),
# 导致「x_rows_lme>0 ⇒ 有工料机」的写法会把信息价批次误判。
@@ -150,6 +161,8 @@ def ensure_attach_schema():
WHERE kind <> 'project' AND x_rows_lme > 0 AND (x_rows_price IS NULL OR x_rows_price = 0)""")
if "is_mock" not in cols: # 2026-10-07:模拟数据标记(测试数据隔离/一键清空)
con.execute("ALTER TABLE batches ADD COLUMN is_mock INTEGER NOT NULL DEFAULT 0")
if "x_side" not in cols: # 2026-11-03:项目级非数据层结构(JSON 路径树)
con.execute("ALTER TABLE batches ADD COLUMN x_side TEXT")
con.commit(); con.close()
@@ -186,6 +199,11 @@ def _ensure_edit_cols():
_add(sc, "s_lme_proj", "x_flags", "TEXT") # LME_SUM 文字/标志属性 JSON 全采(原文件有才导)
_add(sc, "s_lme_proj", "taxrate", "REAL") # 批次C:税率(源节点采集/弹框可编辑)
_add(sc, "s_lme_proj", "x_merged_hide", "INTEGER DEFAULT 0") # 批次C:合并隐藏标记
# 定额单价专题(2026-11-03 主人定):两原价第③级兜底源=「第一次外部采纳价」——
# 采纳落价时列空才写(写过不再动,后续采纳不改);NoTaxOrgPrice/TaxOrgPrice 取值
# 优先级:①单位级 → ②项目级 → ③此列 → 无则空。与决策 251 采纳旧价锚(+旧价备注)无关。
_add(sc, "s_lme_proj", "x_org_ntp0", "REAL")
_add(sc, "s_lme_proj", "x_org_taxp0", "REAL")
# 决策 227(2026-10-27 主人定):本项目内采纳「后采纳的为准」——消耗量行级采纳价锚
# (除税/含税)。锚=采纳时刻来源侧现显价,浮层显示锚优先;取消/再次采纳随整组删重建。
_add(sc, "s_norm_res", "x_ntp", "REAL")
@@ -1590,7 +1608,8 @@ def api_audit(body):
skel_note = ""
try:
suffix = (os.path.splitext(os.path.basename(path))[1][1:] or "").lower()
if classic_skeleton.suffix_of(os.path.basename(path)) and suffix in ("cos", "cos4"):
# 决策 262:不再限定 cos/cos4——骨架匹配对任何能解析的格式都算(后缀只作分组键)
if classic_skeleton.suffix_of(os.path.basename(path)):
_h2 = conn()
try:
frames = _h2.execute(
@@ -1602,9 +1621,9 @@ def api_audit(body):
for fr in frames:
s = None
if fr["x_layer_cols"]:
skel_cols = {k: set(v) for k, v in
json.loads(fr["x_layer_cols"]).items()}
s = classic_skeleton.match_score(src_cols, skel_cols)
skel_cols = json.loads(fr["x_layer_cols"])
if isinstance(skel_cols, dict) and skel_cols.get("v") == 2:
s = classic_skeleton.match_score(src_cols, skel_cols)
scored.append((s if s is not None else -1, fr["original_name"]))
scored.sort(reverse=True)
best_s, best_n = scored[0]
@@ -4019,15 +4038,13 @@ _EXPORT_JOBS = {}
def _export_meta(sc, sid, fmt=""):
"""导出建议名(决策 92:先弹另存为再生成——对话框要预填 名字-审核版.原后缀,不能等生成完)。
2026-11-03 主人定:fmt=html/yhy/xlsx/空(原格式)弹框四选一;cos4/cos 后端保留(界面入口已取消)。"""
2026-11-03 主人定:fmt=yhy/xlsx/空(原格式)弹框三选一;cos4/cos 后端保留(界面入口已取消)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
return {"ok": False, "msg": "会话不存在"}
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
f = (fmt or "").lower()
if f == "html":
return {"ok": True, "name": (proj_name or "工程") + "-审核版.html"}
if f == "yhy":
return {"ok": True, "name": (proj_name or "工程") + "-审核版.yhy"}
if f == "xlsx":
return {"ok": True, "name": (proj_name or "工程") + "-审核版.zip"}
@@ -4118,19 +4135,16 @@ def _uw_rollup_totals(con, uw_id):
def _export_session(sc, sid, fmt="", progress=None):
"""导出=拿原文件当模板外科手术。返回 (字节, 文件名, 错误)。
2026-11-03 主人定(导出弹框四选一):fmt=html → export_html(界面数据全量单文件,通用);
fmt=yhy → export_yhy(专有格式,审核等全部数据,租户交流,通用);
fmt=xlsx → manual_import.export_excel_bytes(清单级 zip+项目级工料机汇总,通用);
fmt=cos4/cos → 经典骨架(界面入口已取消、后端保留);空 fmt=原格式(手工工程没有源格式不可选)。
2026-10-19:SWT/SWZ 等新格式走 formats 适配器(骨架+填空);COS4/.COS 继续用
export_cos 的专用引擎(保留逐节点保真)。"""
"""导出入口。返回 (字节, 文件名, 错误)。
2026-11-03 主人定(导出弹框三选一):fmt=yhy → export_yhy;fmt=xlsx →
manual_import.export_excel_bytes;空 fmt=原格式。HTML 导出已整体去除(同日主人定)。
原格式导出(2026-11-03 决策 264 补记):**只保留骨架回灌一条通路**——空骨架给格式,
会话库给全部数据;旧 export_cos.export_zip 外科手术引擎已拆除。SWT/SWZ 等不同构
数据模型仍走 formats 适配器(决策 264②)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
return None, None, "会话不存在"
f = (fmt or "").lower()
if f == "html":
return export_html.export(sc, sid)
if f == "yhy":
return export_yhy.export(sc, sid)
if f == "xlsx":
@@ -4144,312 +4158,46 @@ def _export_session(sc, sid, fmt="", progress=None):
_h.close()
return None, None, "手工工程没有源格式,不可按原格式导出"
path = _src_path(srow["src_name"])
# 补记十二(2026-10-28 主人定「推翻:审核版不再基于原文件」):cos4 全量走经典骨架
# (骨架管导出、数据归软件);其余格式维持原格式导出。源文件在=按字段相近挑骨架,
# 不在也照导(挑最近收藏的骨架)。
if (fmt or "").lower() == "cos4":
_h = conn()
try:
return export_manual.export(sc, _h, sid, "cos4", progress, src_path=path)
finally:
_h.close()
if not path or not os.path.exists(path):
return None, None, "原文件已不在软件里(可能被清理),无法导出"
try:
src_bytes = io.open(path, "rb").read()
except OSError as e:
return None, None, "原文件读不出来:%s" % e
# 闸①(2026-10-15):导出前核对源文件内容。src_name 形如「<sha256>_<原名>」——
# 闸①(2026-10-15 主人定):导出前核对源文件内容。src_name 形如「<sha256>_<原名>」——
# 哈希对不上 = 文件在打开后被外部改动/同名覆盖,审核动作会拼进别人的底稿:
# 宁可不导,不可导错。老格式(前缀非 64 位十六进制)与多文件会话(含 ;)不校验。
_src_id = srow["src_name"] or ""
if ";" not in _src_id:
if path and os.path.exists(path) and ";" not in _src_id:
_want = _src_id.split("_", 1)[0].lower()
if re.fullmatch(r"[0-9a-f]{64}", _want) and hashlib.sha256(src_bytes).hexdigest() != _want:
return None, None, ("源文件内容与打开该工程时不一致(可能被外部改动后同名覆盖)。"
"请重新打开这个文件后再导出")
# 2026-10-19:新格式(SWT/SWZ…)走「骨架/填空」适配器;COS4/.COS 仍走下面的专用引擎。
# 一个格式一个骨架:适配器只填骨架里有的字段,骨架没有的字段不硬造。
fmt = formats.get_exporter(srow["src_name"])
if fmt:
if re.fullmatch(r"[0-9a-f]{64}", _want):
try:
_sb = io.open(path, "rb").read()
except OSError:
_sb = None
if _sb is not None and hashlib.sha256(_sb).hexdigest() != _want:
return None, None, ("源文件内容与打开该工程时不一致(可能被外部改动后同名覆盖)。"
"请重新打开这个文件后再导出")
# 决策 264 补记(2026-11-03 主人定「新开发的软件,旧的引擎就拆了,不要了」):
# 原格式导出只保留一条通路——**骨架回灌**(空骨架=格式/列集,会话库=全部数据)。
# 旧 export_cos.export_zip(在源件上做外科手术)已拆除;源文件只用于挑骨架,读不到也照导。
#
# ① SWT/SWZ 等数据模型不同构的格式仍走 formats 适配器(决策 264②:单独适配器边界)
_exp = formats.get_exporter(srow["src_name"])
if _exp:
if not path or not os.path.exists(path):
return None, None, "原文件已不在软件里(可能被清理),无法导出"
try:
raw, out_name = fmt.export(sc, sid, src_bytes, srow, progress)
src_bytes = io.open(path, "rb").read()
except OSError as e:
return None, None, "原文件读不出来:%s" % e
try:
raw, out_name = _exp.export(sc, sid, src_bytes, srow, progress)
except Exception as e:
return None, None, "导出失败:%s" % e
return raw, out_name, None
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
# 每组 (uw, kind):x_seq 序走一遍——源清单计源序位,x_new 行记锚点
groups = {}
for b in sc.execute("""SELECT id, uw_id, div_id, Number, Name, Attr, Unit, Quantity, Price, Total,
Kind, x_new, x_tdel, x_seq, src_remark
FROM s_bills WHERE session_id=?
ORDER BY uw_id,
CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
kind = "prelim" if b["Kind"] == "prelim" else "item"
g = groups.setdefault((b["uw_id"], kind), {"pos": 0, "pairs": [], "news": []})
bd = dict(b)
# 补记十六:合价口径——**新增清单** 导出时按 工程量×单价 现算;
# 已有清单在编辑保存时已同步(上面的 API 入口),导出按会话现值原样写穿(决策 90)
if b["x_new"]:
_q, _p2 = f_(b["Quantity"]), f_(b["Price"])
bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
if b["x_new"]:
bd["_anchor"] = g["pos"]
# 补记十六(主人定):新增清单 合价 = 工程量×单价——工作台不预存合价,导出时现算
_q, _p2 = f_(b["Quantity"]), f_(b["Price"])
bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
g["news"].append(bd)
else:
g["pos"] += 1
g["pairs"].append((g["pos"], bd))
norms_by_bill = {}
for nb in sc.execute("""SELECT id, bill_id, Number, Name, Unit, Quantity, Price, Total, x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust
FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?)
ORDER BY id""", (sid,)):
entry = norms_by_bill.setdefault(nb["bill_id"], {"source": [], "append": []})
if nb["x_adopt"] and nb["x_tdel"]:
continue # 临删的采纳定额:导出直接不写(2026-10-15 定额级 ntdel 配套;原有定额的
# 临删仍走 transform_unit 的原位省略,保住与文件的对位关系)
(entry["append"] if nb["x_adopt"] else entry["source"]).append(dict(nb))
# 决策 90(2026-10-17):工程量公式(GCL/数字四则)→ 按**当时**清单量求值
# (决策 216 新口径:GCL=清单工程量原值,公式结果整体÷单位因子,dyn_lme.formula_qty)。
# 合价=求值量×单价(金额2位)。
# 采纳后清单量再改,导出自动跟最新值——这正是公式原文不落死数字的意义。
bill_qtys = {r["id"]: r["Quantity"] for r in sc.execute(
"SELECT id, Quantity FROM s_bills WHERE session_id=?", (sid,))}
for entry in norms_by_bill.values():
for nb in entry["append"] + entry["source"]:
if nb.get("qty_expr"):
q, _msg = _formula_qty(nb["qty_expr"], bill_qtys.get(nb["bill_id"]), nb["Unit"]) # 决策 216
if q is not None:
nb["Quantity"] = q
nb["Total"] = round(q * (float(nb["Price"]) if nb["Price"] is not None else 0.0), 2)
# 采纳定额的工程量/合价回填(2026-10-15 主人指出:留 0 导致易达清单综合单价为空、
# 与广联达不一致)。公式没接住(求值失败/结果 0)而批次源定额有原值的,从批次源定额
# (x_src_norm_id)取原值,与原 cos4 一致;审核已在软件里改过量的(非 NULL)不覆盖。
hc = conn()
# ② 其余(cos/cos4 及后期新后缀)统一走骨架回灌
_sfx = (fmt or "").strip().lower() or (classic_skeleton.suffix_of(srow["src_name"]) or "cos4")
_hc = conn()
try:
for entry in norms_by_bill.values():
for nb in entry["append"] + entry["source"]:
if nb.get("x_src_norm_id") and (nb["Quantity"] is None or xcos._num_eq(nb["Quantity"], 0)):
row = hc.execute("SELECT Quantity, Total FROM norms WHERE id=?",
(nb["x_src_norm_id"],)).fetchone()
if row:
nb["Quantity"], nb["Total"] = row["Quantity"], row["Total"]
import export_v2 as _ev2
return _ev2.export_v2(_hc, sc, sid, _sfx, progress, src_path=path)
finally:
hc.close()
# 补记十六:定额 合价 = 工程量×单价(统一口径;单价缺失的行保持原值)
for entry in norms_by_bill.values():
for nb in entry["append"] + entry["source"]:
if nb.get("Quantity") is not None and nb.get("Price") is not None:
nb["Total"] = round(float(nb["Quantity"]) * float(nb["Price"]), 2)
res_by_norm = {}
for rr in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express FROM s_norm_res nr
WHERE nr.norm_id IN (SELECT id FROM s_norms
WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?))""", (sid,)):
res_by_norm.setdefault(rr["norm_id"], []).append((rr["res_code"], rr["qty"], rr["express"]))
# (uw_id, kind) → uw 键;同 uw 的两种 kind 合成一份 plan
uwmap = {r["id"]: ((r["Number"] or ""), (r["Name"] or ""))
for r in sc.execute("SELECT id, Number, Name FROM s_unit_works WHERE session_id=?", (sid,))}
# 决策 186:源文本按单位缓存(映射源注入判据=源 xml 有没有该汇总节点;导出 truth=源文本)
_uw_src_text = {}
try:
_zin = zipfile.ZipFile(io.BytesIO(src_bytes))
for _n in _zin.namelist():
if not _n.lower().endswith(".xml") or _n.lower().startswith("project"):
continue
_t = _zin.read(_n).decode("utf-8", "replace")
for _uid, _k in uwmap.items():
if _k[0] and ('<UnitWorks Number="%s"' % _k[0]) in _t:
_uw_src_text[_k] = _t
except Exception:
pass
unit_plans = {}
for (uw_id, kind), g in groups.items():
uwkey = uwmap.get(uw_id)
if not uwkey:
continue
plan = unit_plans.setdefault(uwkey, {"pairs": {}, "news": {}, "norms_by_bill": norms_by_bill})
plan["pairs"][kind] = g["pairs"]
plan["news"][kind] = g["news"]
added = [tuple(r) for r in sc.execute(
"""SELECT code, name, spec, unit, kind, qty, taxrate, ntp, taxp FROM s_lme_proj
WHERE session_id=? AND COALESCE(x_adopt_added,0)=1""", (sid,))]
# 决策 186 定稿「块=母行+Element+映射源」项目级:骨架组映射源行缺失 → added 通道注入
_pj_have = {r[0] for r in sc.execute("SELECT code FROM s_lme_proj WHERE session_id=?", (sid,))}
for rc in {r[0] for r in sc.execute(
"""SELECT DISTINCT res_code FROM s_lme_res WHERE session_id=? AND res_code IS NOT NULL""", (sid,))}:
if not rc or rc in _pj_have:
continue
_p = sc.execute("""SELECT code, name, spec, unit, kind, qty, taxrate, ntp, taxp
FROM s_lme_proj WHERE session_id=? AND code=?""", (sid, rc)).fetchone()
if _p:
added.append(tuple(_p))
# 决策 74(主人口径 5.2):本单位采纳新增的品类行 → 写回**本单位工程**的工料机汇总(全字段尽力齐)
# 决策 188 数量模型(主人定稿):每单位 {码:现算数量}——母=Σ(定额含量×定额量);
# 子=Σ(子含量×母含量×定额量)。只算不写库;导出件 Quantity/四Total 按此写回。
_uw_qty = {}
for uw_id in uwmap:
try:
_uw_qty[uwmap[uw_id]] = dyn_lme.qty_map_uw(sc, sid, uw_id)
except Exception:
pass
# 决策 244 补记三:现算链故障的单位标记 _live_ok=False → 导出 0 量判定退老行为(不误删全部)
for plan in unit_plans.values():
plan["added_lme"] = []
for uw_id, uwkey in uwmap.items():
plan = unit_plans.get(uwkey)
if not plan:
continue
plan["qty_updates"] = _uw_qty.get(uwkey) or {}
# 决策 205 修订(原 204 口径降级为兜底):自算聚合链已按公式求值(决策 90),
# 现算值是真相(10# 螺纹钢=1.04×1000=1,040),**不得用快照覆盖现算**;
# 仅当现算图里完全缺码(公式与存储量都无的存量行)才用快照兜底,保证行不被 199 吃掉。
for _ar in sc.execute("""SELECT code, qty FROM s_lme_uw WHERE session_id=? AND uw_id=?
AND COALESCE(x_adopt_added,0)=1 AND qty IS NOT NULL AND code IS NOT NULL""",
(sid, uw_id)):
if _ar["code"] and _ar["code"] not in plan["qty_updates"]:
plan["qty_updates"][_ar["code"]] = float(_ar["qty"])
plan["added_lme"] = [tuple(r) for r in sc.execute(
"""SELECT code, name, spec, unit, qty, taxrate, ntp, taxp, kind FROM s_lme_uw
WHERE session_id=? AND uw_id=? AND COALESCE(x_adopt_added,0)=1 ORDER BY id""",
(sid, uw_id))]
# 决策 186 定稿「块=母行+Element+映射源」导出侧:骨架组映射源行在**源文件该单位**缺失
# → added 通道注入。⚠️ 判据=源文本有没有(导出 truth=源 xml),不是库 uw 有没有——
# 显示端三层落位会把行写进 uw(显示用),库有≠源有(1009 单位2 实测:库有 99450660、
# 源无 → 此前按库判 continue → 导出件缺行)。值优先取该单位 uw 现值,无则项目级。
_refs = {r[0] for r in sc.execute("""SELECT DISTINCT res_code FROM s_lme_res
WHERE session_id=? AND res_code IS NOT NULL""", (sid,))}
_src_txt = _uw_src_text.get(uwkey)
for rc in _refs:
if not rc:
continue
_u = sc.execute("""SELECT code, name, spec, unit, qty, taxrate, ntp, taxp, kind
FROM s_lme_uw WHERE session_id=? AND uw_id=? AND code=?""",
(sid, uw_id, rc)).fetchone()
_p = sc.execute("""SELECT code, name, spec, unit, qty, taxrate, ntp, taxp, kind
FROM s_lme_proj WHERE session_id=? AND code=?""", (sid, rc)).fetchone()
_src_has = (_src_txt is not None and
('<LabourMaterialsEquipmentsMachinesSummary Number="%s"' % rc) in _src_txt)
if not _src_has and (_u is not None or _p is not None):
plan["added_lme"].append(tuple(_u) if _u is not None else tuple(_p))
# 决策 204/205:采纳新增行的子级组成(带子级整组照原生结构导出,子级码照映射、含量不动)
# + 三恒值回填映射(主人定:NoTaxOrgPrice / TaxOrgPrice / 税率 按原数据回填,
# 本单位→项目级回退;库中无 → 留空不编造)。added_children={码:[(子码,含量)]},added_org={码:(除税定额价,含税定额价,税率)}
added_children, added_org = {}, {}
for plan0 in unit_plans.values():
for _t in plan0.get("added_lme") or []:
if not (_t and _t[0]):
continue
_code = str(_t[0])
if _code not in added_children:
added_children[_code] = [
(r["res_code"], r["qty"]) for r in sc.execute(
"""SELECT res_code, qty FROM s_lme_res WHERE session_id=? AND p_code=?
ORDER BY seq, id""", (sid, _code)) if r["res_code"]]
if _code not in added_org:
_o = sc.execute("""SELECT COALESCE(u.ntp_org,p.ntp_org) ntp_org,
COALESCE(u.taxp_org,p.taxp_org) taxp_org,
COALESCE(u.taxrate,p.taxrate) taxrate
FROM s_lme_uw u LEFT JOIN s_lme_proj p
ON p.session_id=u.session_id AND p.code=u.code
WHERE u.session_id=? AND u.code=? LIMIT 1""",
(sid, _code)).fetchone()
added_org[_code] = (_o["ntp_org"], _o["taxp_org"], _o["taxrate"]) if _o else (None, None, None)
hidden = [r[0] for r in sc.execute(
"SELECT code FROM s_lme_proj WHERE session_id=? AND COALESCE(x_merged_hide,0)=1", (sid,))]
# 决策 244 补五(2026-11-01 主人定「导出也按现算值,尽量按修改后的数据」):
# 每单位的 分部 Total / 费用表合计 现算随 plan 带入导出引擎(_apply_div_totals 回填);
# 配不上 XML 分部的保持原件值(fail-open),见 _uw_rollup_totals。
for _uid, _uk in uwmap.items():
_pl = unit_plans.get(_uk)
if not _pl:
continue
try:
_pl["div_totals"], _pl["summary_updates"] = _uw_rollup_totals(sc, _uid)
except Exception:
pass
# 决策 75(主人定数据流):导出时把会话侧项目级汇总现值全量带入——
# 决策 176 起:编码命中全量写回(提供即写不比较);缺失码由 added 追加
sync_rows = [tuple(r) for r in sc.execute(
"""SELECT code, name, spec, unit, ntp, taxrate, taxp FROM s_lme_proj
WHERE session_id=? AND COALESCE(x_merged_hide,0)=0""", (sid,))]
# 决策 186 导出侧兜底(2026-10-24,主人报「1009 仍然缺 99450660」存量场景):recode_map 收敛
# 成员(被归并码)即使库中 hid=0(历史合并时弹框看不到、hide 没带全——04110001-0001 只在
# 项目级有行),导出时也按归并处理:计入 hidden(Project 侧删除)+ 从 sync_rows 排除
# (不再写现值)——导出端与合并语义一致,显示端由合并收尾兜底补隐藏,两端归一。
_rmx = json.loads(_setting_get("session:%d" % sid, "recode_map") or "{}")
if _rmx:
_flatx = xcos._resolve_recode_chains(_rmx)
_members = {o for o, n in _flatx.items() if o != n}
hidden = sorted(set(hidden) | _members)
sync_rows = [t for t in sync_rows if t[0] not in _members]
# 单位级改价 = 合并过的编码 ∩ 该单位汇总已有的行(5.1/5.3:单位汇总是被查找对象)
_mc_raw = _setting_get("session:%d" % sid, "merged_codes")
merged_codes = set(json.loads(_mc_raw) if _mc_raw else [])
price_updates = {}
for r in sc.execute("""SELECT code, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr
FROM s_lme_proj WHERE session_id=?""", (sid,)):
if r["code"] in merged_codes:
# 决策 183(主人定:整套按骨架,属性匹配):采纳值按属性一一对应直填;
# 值为 None(老数据未采)→ 不写,骨架保留原值(新值没有的不动)
price_updates[r["code"]] = {
"NoTaxPrice": r["ntp"], "TaxRate": r["taxrate"], "TaxPrice": r["taxp"],
"NoTaxOrgPrice": r["ntp_org"], "NoTaxPriceExpress": r["ntp_expr"],
"TaxOrgPrice": r["taxp_org"], "TaxPriceExpress": r["taxp_expr"]}
# 规格 第11/12 条:合并改码映射 + 被合并码的子级替换数据(子级元素全字段重建用)
_rm_raw = _setting_get("session:%d" % sid, "recode_map")
recode_map = json.loads(_rm_raw) if _rm_raw else {}
recode_children = {}
for old in recode_map:
_rc_raw = _setting_get("session:%d" % sid, "recode_children:" + old)
if _rc_raw:
recode_children[old] = json.loads(_rc_raw)
# 决策 186 严格修正(2026-10-24,主人问「软件错还是方案错」实证:幸存保留码节点导出时
# 照抄源文件子级,而源文件同名行子级引用乱(基码/换算码不一),与显示端归一子级不一致——
# 实测 1001 会话:显示端灰土子级=04090090(9262.80 口径),导出件=04090090-0001(39.45)。
# **补齐最后一环:保留码自身也按显示端库值(s_lme_res)登记子级重建**——凡 price_updates
# 命中的码(=显示端幸存行),导出时其节点子级一律按库值整组重建(「导出件=显示端」不变式);
# 显示端该码无子级(s_lme_res 无行)→ 登记空表=剥子级,同样与显示端一致。被合并码的登记
# (合并时写入)优先保留,不被此处的补全覆盖。qty 精度 4 位(与 _child_node 写出口径一致)。
# 库值是唯一真相:凡 price_updates 命中的码,**一律**用 s_lme_res 现值覆盖登记
# (存量 recode_children:码 可能是旧合并从源节点抓的、带换算码的脏数据——1001 实测
# 存量 80310015 登记 04090190-0001,库值已是 04090190 → 存量必须让位于库值)。
for code in price_updates:
rows = [[r["res_code"], round(float(r["qty"]), 4) if r["qty"] is not None else 0.0]
for r in sc.execute(
"""SELECT res_code, qty FROM s_lme_res
WHERE session_id=? AND p_code=? ORDER BY seq""", (sid, code))]
recode_children[code] = rows
# 决策 178:按码+名规单的拆分映射(同码异物节点改印新码)
_ri_raw = _setting_get("session:%d" % sid, "recode_ident")
recode_ident = json.loads(_ri_raw) if _ri_raw else {}
# 2026-10-22 主人定(编辑名称/规格/单位要写回):单位汇总节点只回写**编辑过的编码**的
# 名称/规格/单位(lme_field_codes 圈定,现值从 s_lme_proj 取)——不做全量同步,
# 零编辑大面积误改的坑(决策 75)不重踩;项目级 Project.xml 仍走 sync_rows 全字段。
field_updates = {}
_fc_raw = _setting_get("session:%d" % sid, "lme_field_codes")
if _fc_raw:
_fcs = tuple(json.loads(_fc_raw))
if _fcs:
for r in sc.execute("""SELECT code, name, spec, unit FROM s_lme_proj
WHERE session_id=? AND code IN (%s)"""
% ",".join("?" * len(_fcs)), (sid,) + _fcs):
field_updates[r["code"]] = (r["name"], r["spec"], r["unit"])
try:
raw, out_name = xcos.export_zip(src_bytes, proj_name, srow["src_name"],
unit_plans, added, hidden, res_by_norm,
price_updates=price_updates,
added_lme_by_uw=None, sync_rows=sync_rows,
recode_map=recode_map, recode_children=recode_children,
recode_ident=recode_ident,
field_updates=field_updates,
added_children=added_children,
added_org=added_org,
progress=progress)
except Exception as e:
return None, None, "导出失败:%s" % e
return raw, out_name, None
_hc.close()
# ---------- 合并工料机(批次C,决策 69;方案 §6,主人定稿的树形弹框)----------
@@ -4763,7 +4511,7 @@ def _lme_merge_groups(con, sid, sub=False):
FROM s_lme_proj WHERE session_id=? AND COALESCE(x_merged_hide,0)=0
ORDER BY id""", (sid,)).fetchall()
rows_u = con.execute("""SELECT uw_id, id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp,
ntp_org, ntp_expr, taxp_org, taxp_expr
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags
FROM s_lme_uw WHERE session_id=? ORDER BY uw_id, id""", (sid,)).fetchall()
sub_codes = set(_lme_sub_codes(con, TBL["session"], sid))
# 决策 184(2026-10-23 主人定):弹框过滤**子工料机**——被台班/配合比子级引用的编码
@@ -4852,6 +4600,7 @@ def _lme_merge_groups(con, sid, sub=False):
"units": len({x["uw_id"] for x in rs}),
"uw_ids": sorted({x["uw_id"] for x in rs}),
"kind": rs[0]["kind"],
"x_flags": rs[0]["x_flags"], # 定额单价专题:合并=勾选行全字段(2026-11-03 主人定)
"ntp_org": _mid([x["ntp_org"] for x in rs]),
"ntp_expr": _mid([x["ntp_expr"] for x in rs]),
"taxp_org": _mid([x["taxp_org"] for x in rs]),
@@ -4918,6 +4667,7 @@ def api_lme_merge(sc, body):
for g in groups:
keep_code = None
keep_px = None
keep_kf = None # 定额单价专题:保留行 (kind, x_flags),变体统一用
variants = []
sel = g.get("sel") if isinstance(g.get("sel"), dict) else None
hides = g.get("hide") if isinstance(g.get("hide"), list) else []
@@ -4930,6 +4680,7 @@ def api_lme_merge(sc, body):
_g_ident = ((sel.get("name") or "").strip(), (sel.get("spec") or "").strip(),
(sel.get("unit") or "").strip()) # 决策 241 加固:同组名规单(uw 换码兜底用)
keep_px = (_num_or_none(sel.get("ntp")), _num_or_none(sel.get("taxrate")), _num_or_none(sel.get("taxp")))
keep_kf = (sel.get("kind"), sel.get("x_flags")) # 勾选聚合行:kind/x_flags 随行
keep_x = _sel_px6(sel)
kept += 1
if keep_code:
@@ -4943,22 +4694,28 @@ def api_lme_merge(sc, body):
row_u = sc.execute("""SELECT id, COALESCE(x_merged_hide,0) AS hid FROM s_lme_proj
WHERE session_id=? AND code=?""", (sid, keep_code)).fetchone()
if row_u:
sc.execute(("UPDATE s_lme_proj SET ntp=?, taxrate=?, taxp=?, qty=?, x_merged_hide=0%s"
# 定额单价专题(2026-11-03 主人定「合并=勾选谁按哪一行的字段」):幸存行
# kind/x_flags 一并统一为勾选行(唯一值约束:合并后输出一条、全字段统一)。
sc.execute(("UPDATE s_lme_proj SET ntp=?, taxrate=?, taxp=?, qty=?, x_merged_hide=0,"
" kind=COALESCE(?, kind), x_flags=?%s"
" WHERE session_id=? AND id=?") % _xs,
keep_px + (_num_or_none(sel.get("qty")),) + tuple(_xa) + (sid, row_u["id"]))
keep_px + (_num_or_none(sel.get("qty")),)
+ (_num_or_none(sel.get("kind")), sel.get("x_flags"))
+ tuple(_xa) + (sid, row_u["id"]))
else:
sc.execute(("INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty,"
" ntp, taxrate, taxp%s) VALUES(?,?,?,?,?,?,?,?,?,?%s)") % (_ics, _iph),
" ntp, taxrate, taxp, x_flags%s) VALUES(?,?,?,?,?,?,?,?,?,?,?%s)") % (_ics, _iph),
(sid, keep_code, sel.get("name") or "", sel.get("spec") or "",
sel.get("unit") or "", _num_or_none(sel.get("kind")),
_num_or_none(sel.get("qty"))) + keep_px + tuple(_xa))
_num_or_none(sel.get("qty"))) + keep_px
+ (sel.get("x_flags"),) + tuple(_xa))
_merged_codes_add(sc, sid, keep_code)
else:
try:
rid = int(sel.get("id", 0) or 0)
except (TypeError, ValueError):
continue
row = sc.execute("""SELECT code, name, spec, unit FROM s_lme_proj WHERE session_id=? AND id=?
row = sc.execute("""SELECT code, name, spec, unit, kind, x_flags FROM s_lme_proj WHERE session_id=? AND id=?
AND COALESCE(x_merged_hide,0)=0""", (sid, rid)).fetchone()
if not row:
continue
@@ -4980,12 +4737,15 @@ def api_lme_merge(sc, body):
kept += 1
keep_code = row["code"]
keep_px = (_ntp, _rate, _taxp)
keep_kf = (row["kind"], row["x_flags"]) # 勾选项目级行:kind/x_flags=保留行自身
# 决策 178:保留码强制唯一——先拆同码异物(占用行自动换未占用新码)再同步三价
_split_occupied_code(sc, sid, keep_code, (row["name"], row["spec"], row["unit"]))
# 决策 75 通道:保留码登记 + 存在该码的单位汇总同步三价(单位汇总是被查找对象)
_merged_codes_add(sc, sid, keep_code)
sc.execute(("UPDATE s_lme_uw SET ntp=?, taxrate=?, taxp=?%s WHERE session_id=? AND code=?") % _xs,
keep_px + tuple(_xa) + (sid, keep_code))
# 定额单价专题:同步时 kind/x_flags 一并统一为保留行(唯一值约束)
sc.execute(("UPDATE s_lme_uw SET ntp=?, taxrate=?, taxp=?,"
" kind=COALESCE(?, kind), x_flags=?%s WHERE session_id=? AND code=?") % _xs,
keep_px + (row["kind"], row["x_flags"]) + tuple(_xa) + (sid, keep_code))
# 决策 251:锚列停止维护(旧 219「合并后首次三价」写入随退役删除)——合并生成的行
# 无导入原件价(_org 空),采纳备注退改前现值兜底,见 api_lme_price。
if not keep_code:
@@ -5102,8 +4862,14 @@ def api_lme_merge(sc, body):
# 此时组内变体已全部=keep_code,一条 UPDATE 覆盖全部归并行(含原本就有保留码的单位)。
if keep_px:
_xs, _xa = _px_extra(keep_x)
sc.execute(("UPDATE s_lme_uw SET ntp=?, taxrate=?, taxp=?%s WHERE session_id=? AND code=?") % _xs,
keep_px + tuple(_xa) + (sid, keep_code))
# 定额单价专题(2026-11-03 主人定「合并=勾选谁按哪一行的字段」):变体行换码后
# kind/x_flags 一并统一为勾选行值(唯一值约束:合并后一个项目该三同只输出一条、
# 全字段统一,项目级并一行不因类别/标志不一致而分裂)。
sc.execute(("UPDATE s_lme_uw SET ntp=?, taxrate=?, taxp=?, kind=COALESCE(?, kind),"
" x_flags=?%s WHERE session_id=? AND code=?") % _xs,
keep_px
+ ((_num_or_none(keep_kf[0]), keep_kf[1]) if keep_kf else (None, None))
+ tuple(_xa) + (sid, keep_code))
# 决策 186 收尾兜底(2026-10-24 主人报「1009 仍然缺 99450660」根因):**骨架块语义落库**——
# 凡 recode_map 收敛到某保留码的项目级同组未隐藏行,自动隐藏。此前靠前端弹框 hide 传全;
# 并集视野下单位级无行的变体(04110001-0001 只在项目级有行)弹框看不到 → 不在 hide 里 →
@@ -5538,6 +5304,12 @@ def api_lme_price(sc, body):
ntp = _r2(taxp / div)
sc.execute("UPDATE s_lme_proj SET ntp=?, taxrate=?, taxp=? WHERE session_id=? AND id=?",
(ntp, rate, taxp, sid, rid))
# 定额单价专题(2026-11-03 主人定):采纳落价时登记「第一次外部采纳价」(原价③级兜底源)——
# 列空才写(COALESCE):后续采纳不改;手工行级改价不带 adopt 标志、永不写。
if body.get("adopt"):
sc.execute("""UPDATE s_lme_proj SET x_org_ntp0=COALESCE(x_org_ntp0, ?),
x_org_taxp0=COALESCE(x_org_taxp0, ?) WHERE session_id=? AND id=?""",
(ntp, taxp, sid, rid))
# 决策 188 联动:改的是某母的子级价→清该母覆盖(回Σ现算)。(母行直改已收严拒绝,不再设覆盖)
try:
for _m in dyn_lme.mothers_of(sc, sid, row["code"]):
@@ -5747,9 +5519,9 @@ def api_schema():
r("GET", "/api/session/edit/log", "字段编辑历史(红三角批注)"),
],
"导出": [
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;fmt=html=HTML 全量 / yhy=专有格式全量 / xlsx=Excel zip / 空=原格式,2026-11-03 弹框四选一)",
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;yhy=专有格式全量 / xlsx=Excel zip / 空=原格式,2026-11-03 弹框三选一)",
{"session_id*": "", "token": "可选:进度上报令牌(决策 92)", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;fmt=html/yhy/xlsx/空,2026-11-03)",
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;fmt=yhy/xlsx/空,2026-11-03)",
{"session_id*": "", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
r("GET", "/api/session/export/progress", "导出逐条目进度(轮询,决策 92)",
{"token*": ""}),
@@ -8565,6 +8337,24 @@ class Handler(SimpleHTTPRequestHandler):
self.end_headers()
self.wfile.write(data)
return None
m = re.match(r"^/api/admin/frames/blankpkg/([0-9a-f]{32})$", p) # 空骨架+导出规则标注(原格式包;2026-11-03 新增)
if m:
_c = conn()
try:
import export_v2 as _ev2
data, fn, err = _ev2.build_blank_package(_c, m.group(1))
finally:
_c.close()
if err:
return self._json({"error": err}, 404)
self.send_response(200)
self.send_header("Content-Type",
"application/zip" if data[:2] == b"PK" else "application/octet-stream")
self.send_header("Content-Length", str(len(data)))
self.send_header("Content-Disposition", self._cd(fn or "空骨架(标注).cos4", "blank.cos4"))
self.end_headers()
self.wfile.write(data)
return None
if p == "/api/admin/filters":
return self._json(api_filters())
if p == "/api/admin/scan":
@@ -8763,6 +8553,32 @@ class Handler(SimpleHTTPRequestHandler):
if u.path == "/api/session/manual/save": # 手工工程:建/改目录树+按单位工程导Excel(决策230)
with WRITE_LOCK:
return self._json(api_manual_save(body))
if u.path == "/api/session/yhy/import": # 决策 261 补三:.yhy 导入(id 整体平移法,主人定)——同名拒绝,不 commit 由此处管
path = _allowed_source_path(body.get("path") or "")
if not path:
return self._json({"ok": False, "msg": "导入文件已失效,请重新选择"})
with WRITE_LOCK:
c = sess.connect()
try:
r = import_yhy.run(c, path, name=body.get("name"),
overrides={"period_from": body.get("period_from"),
"period_to": body.get("period_to"),
"province": body.get("province"),
"city": body.get("city"),
"district": body.get("district"),
"bulid_unit": body.get("bulid_unit"),
"file_kind": body.get("file_kind")})
if r.get("ok"):
c.commit()
except Exception as e:
try:
c.rollback()
except Exception:
pass
r = {"ok": False, "msg": "导入异常:%s" % e}
finally:
c.close()
return self._json(r)
if u.path == "/api/session/manual/import_project": # 手工工程:整项目一把导入(决策238)
with WRITE_LOCK:
c = sess.connect()