feat(costreview): 落实决策292工料机引用完整性闸门并升级YHY v2完整会话包
This commit is contained in:
@@ -27,6 +27,8 @@ import re
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
import integrity
|
||||
|
||||
BILL_TAGS = ("WorkElement", "UnitWorksPreliminaryWorkElement")
|
||||
_CLOSE_WE = "</WorkElement>"
|
||||
_CLOSE_PRE = "</UnitWorksPreliminaryWorkElement>"
|
||||
@@ -2671,6 +2673,15 @@ def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidd
|
||||
if _elem_recode: # 决策 174:Project.xml 的块外元素行同口径换码
|
||||
txt = _recode_norm_lme_rows(txt, _elem_recode)
|
||||
finals[item.filename] = _encode(txt, enc)
|
||||
# 决策 292:写出前最后一道引用完整性闸门——全项目源集 vs 所有引用地;
|
||||
# 缺一即拦截(不补占位)。无动作源样也过闸,源件孤儿在这里暴露,不静默导错。
|
||||
_cos_texts = [t for _uk, t in unit_final_texts]
|
||||
for item in entries:
|
||||
if item.filename.rsplit("/", 1)[-1].lower() == "project.xml":
|
||||
_rawp = finals.get(item.filename) or zin.read(item.filename)
|
||||
_tp, _ep = _decode(_rawp)
|
||||
_cos_texts.append(_tp)
|
||||
integrity.validate_cos(_cos_texts, where=out_name)
|
||||
# 按原条目顺序写出(zip 条目序=源框架不动)
|
||||
for item in entries:
|
||||
raw = finals.get(item.filename) or zin.read(item.filename)
|
||||
@@ -2970,8 +2981,65 @@ def _esc_ident_print(txt, units, unit_mig, recode_ident):
|
||||
return edits
|
||||
|
||||
|
||||
def _escc_added_lme_edits(txt, u, plan, added_children):
|
||||
"""决策 292:ESCC 采纳新增工料机补源——单位 <Resources> 末尾补
|
||||
<ResourceItem Code ...>(与源同属性集);有子级时补 <ResElements>。
|
||||
已有同码不重复补;无 <Resources>/模板则返回空,由导出完整性闸门拦截。"""
|
||||
adds = [t for t in (plan.get("added_lme") or []) if t and t[0]]
|
||||
if not adds:
|
||||
return []
|
||||
seg = txt[u["s"]:u["end"]]
|
||||
close = seg.rfind("</Resources>")
|
||||
if close < 0:
|
||||
return []
|
||||
tm = re.search(r'<ResourceItem\b[^>]*>', seg)
|
||||
if not tm:
|
||||
return []
|
||||
tmpl = tm.group(0).strip()
|
||||
blocks = []
|
||||
for t in adds:
|
||||
code = str(t[0])
|
||||
if re.search(r'<ResourceItem\b[^>]*?\bCode="%s"' % re.escape(code), seg):
|
||||
continue
|
||||
name = t[1] if len(t) > 1 else ""
|
||||
spec = t[2] if len(t) > 2 else ""
|
||||
unit = t[3] if len(t) > 3 else ""
|
||||
qty = t[4] if len(t) > 4 else 0
|
||||
ntp = t[6] if len(t) > 6 else None
|
||||
kind = t[8] if len(t) > 8 else None
|
||||
try:
|
||||
qf = float(qty or 0)
|
||||
except (TypeError, ValueError):
|
||||
qf = 0.0
|
||||
try:
|
||||
pf = float(ntp or 0)
|
||||
except (TypeError, ValueError):
|
||||
pf = 0.0
|
||||
tag = _attr_set_has(tmpl, "Code", code)
|
||||
for k, v in (("Name", name), ("Specification", spec), ("Unit", unit),
|
||||
("OrgPrice", "%.4f" % pf), ("Price", "%.4f" % pf),
|
||||
("Quantity", "%.4f" % qf),
|
||||
("OrgTotal", "%.2f" % (qf * pf)), ("Total", "%.2f" % (qf * pf)),
|
||||
("Kind", "" if kind is None else str(kind))):
|
||||
tag = _attr_set_has(tag, k, _esc(v))
|
||||
if tag.rstrip().endswith("/>"):
|
||||
tag = tag.rstrip()[:-2] + ">"
|
||||
kids = added_children.get(code) if added_children else None
|
||||
if kids:
|
||||
body = "".join('<ResElementItem ResCode="%s" Quantity="%s"/>'
|
||||
% (_esc(str(c)), _fmt_qty(q, 4)) for c, q in kids if c)
|
||||
tag = tag + "<ResElements>" + body + "</ResElements></ResourceItem>"
|
||||
else:
|
||||
tag = tag + "</ResourceItem>"
|
||||
blocks.append(tag)
|
||||
if not blocks:
|
||||
return []
|
||||
return [(u["s"] + close, u["s"] + close, "".join(blocks))]
|
||||
|
||||
|
||||
def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
recode_ident=None, unit_mig=None, progress=None, price_updates=None):
|
||||
recode_ident=None, unit_mig=None, progress=None, price_updates=None,
|
||||
added_children=None):
|
||||
"""ESCC2.0 散装单文件 xml 导出(决策 283)。
|
||||
unit_plans 键=(Number,Name)(与 cos 同构);unit_mig={(Number,Name):{旧码:新码}}——
|
||||
api 侧从 s_lme_uw 现值推导(旧码不在且新码在=该单位整体迁移),归属与导入拆分一致。
|
||||
@@ -2996,6 +3064,7 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
plan = unit_plans.get(u["key"])
|
||||
if plan:
|
||||
_transform_esc_unit(txt, u, plan, res_by_norm, tmpls, edits)
|
||||
edits += _escc_added_lme_edits(txt, u, plan, added_children) # 决策 292
|
||||
if progress:
|
||||
progress(i + 1, len(units))
|
||||
edits += _esc_ident_print(txt, units, unit_mig or {}, recode_ident or {})
|
||||
@@ -3005,6 +3074,7 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
edits += _res_price_edits(txt, price_updates or {}, price_attr="Price", total_attr="Total",
|
||||
fmt=lambda v: "%.2f" % float(v))
|
||||
if not edits:
|
||||
integrity.validate_escc(txt, where=out_name) # 决策 292:源样也过闸
|
||||
return src_bytes, out_name # 无动作:字节级一模一样
|
||||
# 应用(升序扫;同起点大块优先=整块替换/删除在前,落其内的小改写自然丢弃——同点插入按收集序)
|
||||
edits.sort(key=lambda x: (x[0], -(x[1] - x[0])))
|
||||
@@ -3016,7 +3086,9 @@ def export_esc(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
out.append(rep)
|
||||
cursor = e0
|
||||
out.append(txt[cursor:])
|
||||
return _encode("".join(out), enc), out_name
|
||||
_out_text = "".join(out)
|
||||
integrity.validate_escc(_out_text, where=out_name) # 决策 292:成品引用完整性
|
||||
return _encode(_out_text, enc), out_name
|
||||
|
||||
|
||||
# ═══ 决策 284(2026-11-07):SWT/SWZ 手术引擎标签层(ConstructProject 系) ═══
|
||||
@@ -3489,6 +3561,7 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
edits += _res_price_edits(txt, price_updates or {}, price_attr="Rate", total_attr="Total",
|
||||
fmt=_swt_num)
|
||||
if not edits:
|
||||
integrity.validate_swt(txt, where=out_name) # 决策 292
|
||||
return src_bytes, out_name # 无动作:字节级一模一样
|
||||
edits.sort(key=lambda x: (x[0], -(x[1] - x[0])))
|
||||
out, cursor = [], 0
|
||||
@@ -3499,7 +3572,9 @@ def export_swt(src_bytes, proj_name, src_name, unit_plans, res_by_norm,
|
||||
out.append(rep)
|
||||
cursor = e0
|
||||
out.append(txt[cursor:])
|
||||
new_body = _encode("".join(out), enc)
|
||||
_swt_text = "".join(out)
|
||||
integrity.validate_swt(_swt_text, where=out_name) # 决策 292
|
||||
new_body = _encode(_swt_text, enc)
|
||||
if not member:
|
||||
return new_body, out_name
|
||||
zout = io.BytesIO()
|
||||
|
||||
@@ -1,23 +1,31 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""".yhy 专有格式导出(2026-11-03 主人定):审核等全部数据打包单文件,不同租户相互交流。
|
||||
""" .yhy 专有格式导出(2026-11-03 主人定,2026-11-10 升为完整会话包):
|
||||
审核等全部**可继续操作**的数据打包单文件,不同租户相互交流。
|
||||
|
||||
内容 = 该会话在会话库里的全部数据:
|
||||
· sessions 行(17 列全带,含 x_info/x_feat 等原文)
|
||||
· 全部带 session_id 的 s_* 表(动态枚举 sqlite_master,将来加表自动带上,防漏表)
|
||||
· s_norms / s_norm_res(无 session_id,按 bills→norms 父引用带出)
|
||||
不导:s_settings(软件设置,非会话数据)、s_remarks(按源文件共享的备注源库,备注本体
|
||||
已在 s_bills.x_remark)、s_edit_log(审计日志按内容锚关联,无法按会话切分)。
|
||||
· s_block_bank(列名 sid,不是 session_id;块进块出/采纳块原文必须带走)
|
||||
· s_settings 的 session:<id> 域(合并/换码/导出等操作状态)
|
||||
· s_edit_log 中本会话清单/LME 内容锚(b:/L: rkey)相关的操作记录
|
||||
· source/<原名>:原始源件字节(原格式导出靠它;缺源件时 manifest.source_missing=true)
|
||||
不导:s_settings 的 global/sys 域、s_remarks(源级备注库;备注本体已在 s_bills.x_remark)。
|
||||
|
||||
格式:zip 包(manifest.json + sessions.json + rows/<表>.json,UTF-8 JSON)。
|
||||
导入(收方建会话)另立项——子表 id 全局自增、跨会话会撞号,方案待主人拍板。"""
|
||||
导入口径见 import_yhy:id 整体平移、sid/bill/norm/settings 一并换新;收方打开后可继续操作。
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
|
||||
import session_job as sess
|
||||
|
||||
YHY_MAGIC = "YHY"
|
||||
YHY_VERSION = 1
|
||||
YHY_VERSION = 2 # v2:补块库/会话设置/操作记录/原始源件;v1 旧包仍可导入(缺源件时提示)
|
||||
_SKIP_TABLES = ("s_settings", "s_remarks", "s_edit_log")
|
||||
|
||||
|
||||
@@ -69,12 +77,65 @@ def export(sc, sid):
|
||||
else:
|
||||
payload["s_norm_res"] = []
|
||||
|
||||
# 2026-11-10 主人定:YHY = 可继续操作的完整会话包,不只是数据表。
|
||||
# ① 块库(列名是 sid,不是 session_id,动态枚举会漏)——采纳/取消采纳的块原文必须带走
|
||||
# ② 会话级设置(merged_codes/recode_map/... 等操作状态)
|
||||
# ③ 本会话内容锚相关的操作记录(s_edit_log 无 session_id,按 b:/L: rkey 过滤)
|
||||
try:
|
||||
payload["s_block_bank"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM s_block_bank WHERE sid=? ORDER BY id", (sid,)).fetchall()]
|
||||
except Exception:
|
||||
payload["s_block_bank"] = []
|
||||
try:
|
||||
payload["s_settings"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM s_settings WHERE scope=? ORDER BY k", ("session:%d" % sid,)).fetchall()]
|
||||
except Exception:
|
||||
payload["s_settings"] = []
|
||||
try:
|
||||
src_name = srow["src_name"] or ""
|
||||
uw_names = {r["id"]: r["Name"] for r in sc.execute(
|
||||
"SELECT id, Name FROM s_unit_works WHERE session_id=?", (sid,)).fetchall()}
|
||||
keys = set()
|
||||
for b in payload.get("s_bills", []):
|
||||
keys.add("b:" + sess.rkey(src_name, uw_names.get(b.get("uw_id"), ""),
|
||||
b.get("Number") or "", b.get("Name") or "",
|
||||
b.get("Unit") or ""))
|
||||
for t in ("s_lme_uw", "s_lme_proj", "s_lme_lib"):
|
||||
for r in payload.get(t, []):
|
||||
keys.add("L:" + sess.rkey(src_name, "", r.get("code") or "",
|
||||
r.get("name") or "", r.get("unit") or ""))
|
||||
payload["s_edit_log"] = [dict(r) for r in sc.execute(
|
||||
"SELECT * FROM s_edit_log ORDER BY id").fetchall()
|
||||
if r["ekbase"] in keys] if keys else []
|
||||
except Exception:
|
||||
payload["s_edit_log"] = []
|
||||
|
||||
# 2026-11-10 主人问「YHY 导入后还能原格式导出吗」:YHY 必须带**原始源件字节**,
|
||||
# 否则收方只有 src_name、没有文件,原格式手术无框架可套。源件按 source/<原名> 入包,
|
||||
# 导入端落回 source_files/<原名> 后,原格式导出的哈希闸/块通道照常成立。
|
||||
src_name = srow["src_name"] or ""
|
||||
sources = []
|
||||
if src_name and not srow["x_manual"]:
|
||||
src_dir = os.path.join(os.path.dirname(sess.DB), "source_files")
|
||||
for nm in str(src_name).split(";"):
|
||||
nm = nm.strip()
|
||||
if not nm or "/" in nm or "\\" in nm or nm in (".", ".."):
|
||||
continue
|
||||
fp = os.path.join(src_dir, nm)
|
||||
if os.path.exists(fp):
|
||||
try:
|
||||
sources.append((nm, open(fp, "rb").read()))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
manifest = {
|
||||
"magic": YHY_MAGIC,
|
||||
"version": YHY_VERSION,
|
||||
"exported_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"session_name": proj,
|
||||
"tables": {t: len(v) for t, v in sorted(payload.items())},
|
||||
"source": [{"name": nm, "bytes": len(data)} for nm, data in sources],
|
||||
"source_missing": bool(src_name and not sources),
|
||||
}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
@@ -86,4 +147,6 @@ def export(sc, sid):
|
||||
continue
|
||||
zo.writestr("rows/%s.json" % t, json.dumps(rows, ensure_ascii=False,
|
||||
default=_json_default))
|
||||
for nm, data in sources:
|
||||
zo.writestr("source/" + nm, data)
|
||||
return buf.getvalue(), proj + "-审核版.yhy", None
|
||||
|
||||
@@ -1914,6 +1914,17 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||
(bid, bill_ids[idx] if 0 <= idx < len(bill_ids) else None,
|
||||
norm_ids[-1], _nblk, sha, fn))
|
||||
|
||||
# 决策 292:全项目工料机源集(lme_uw ∪ lme_proj ∪ lme_lib ∪ lmes)——
|
||||
# 引用地(定额消耗/子级组成)出现源集没有的码,导入即舍弃该条引用行;
|
||||
# 不留悬空码、不造占位。空源集(老数据/未知格式)不裁,保持 fail-open。
|
||||
_src_codes = set()
|
||||
for _r in (out.get("lme_uw") or []):
|
||||
if len(_r) > 1 and _r[1]:
|
||||
_src_codes.add(_r[1])
|
||||
_src_codes |= set((out.get("lme_proj") or {}).keys())
|
||||
_src_codes |= set((out.get("lme_lib") or {}).keys())
|
||||
_n_drop_norm = _n_drop_res = 0
|
||||
|
||||
# 定额消耗工料机(对应 s_norm_res)。
|
||||
# 决策 200(2026-10-25 主人定):同一定额下的相同工料机只出一条——消耗量相加
|
||||
# (原件分部重复列码,如 A1-3-1 的汽车式起重机 4.263/0.179 两条→并成 4.442 一条)。
|
||||
@@ -1930,6 +1941,9 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||
_nr_agg[k] = (q, express)
|
||||
_nr_order.append(k)
|
||||
for nidx, code in _nr_order:
|
||||
if _src_codes and code and code not in _src_codes:
|
||||
_n_drop_norm += 1
|
||||
continue
|
||||
q, express = _nr_agg[(nidx, code)]
|
||||
nid = norm_ids[nidx] if 0 <= nidx < len(norm_ids) else None
|
||||
cur.execute("INSERT INTO norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)",
|
||||
@@ -1959,6 +1973,9 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||
for i, (code, q) in enumerate(subs):
|
||||
if not code:
|
||||
continue
|
||||
if _src_codes and (code not in _src_codes or pcode not in _src_codes):
|
||||
_n_drop_res += 1
|
||||
continue
|
||||
# 子项名称:源文件汇总节点上记的那份;带 -0001 换算后缀的也认(去掉后缀再查一次)
|
||||
_nm = _lname.get(code) or _lname.get(code.split("-")[0]) or None
|
||||
try:
|
||||
@@ -1972,6 +1989,9 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
|
||||
if n_lme_errs or n_lres_errs:
|
||||
print("导入警告(batch=%s):工料机 %d 条、台班组成 %d 条入库失败" % (bid, n_lme_errs, n_lres_errs),
|
||||
flush=True)
|
||||
if _n_drop_norm or _n_drop_res:
|
||||
print("导入完整性(batch=%s):源集 %d 码;舍弃无源引用 定额消耗 %d 条 / 组成子级 %d 条"
|
||||
% (bid, len(_src_codes), _n_drop_norm, _n_drop_res), flush=True)
|
||||
|
||||
# 项目级工料机资源库(2026-10-07):源文件汇总节点全集,名称/规格兜底用
|
||||
n_lib = 0
|
||||
|
||||
@@ -11,13 +11,18 @@
|
||||
s_norms.bill_id → s_bills.id;s_norms.x_src_norm_id → s_norms.id(自引用)
|
||||
s_norm_res.norm_id → s_norms.id
|
||||
s_lme_uw.uw_id / s_sundry.uw_id / s_uw_summary.uw_id → s_unit_works.id
|
||||
其余带 session_id 表只换 session_id。s_settings/s_remarks/s_edit_log 不在导出面(导入天然无关)。
|
||||
s_block_bank.sid → @SID;bill_id → s_bills.id;norm_id → s_norms.id
|
||||
s_settings:只收 session:<旧> 域,scope 换 session:<新>;global/sys 不搬
|
||||
s_edit_log:按 id 平移追加(内容锚 ekbase 不变,收方可继续挂操作记录)
|
||||
其余带 session_id 表只换 session_id。s_remarks 仍在导出面外(备注本体在 s_bills.x_remark)。
|
||||
|
||||
sessions 行=新会话:name/期次/地区/建设单位/单价类型用弹框传入覆盖(「名称等一切按弹框」,
|
||||
2026-11-03 主人定),其余列(x_info/x_feat/src_name/x_manual 等)原样保真;x_batch_id 跨库
|
||||
引用置空。同名工程拒绝(决策 242)。导入不 commit——事务由调用方提交/回滚(api_server 模式)。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import hashlib
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
|
||||
@@ -37,6 +42,9 @@ _TABLES = [
|
||||
("s_proj_summary", {"session_id": "@SID"}),
|
||||
("s_sundry", {"session_id": "@SID", "uw_id": "s_unit_works"}),
|
||||
("s_uw_summary", {"session_id": "@SID", "uw_id": "s_unit_works"}),
|
||||
# 2026-11-10:YHY 完整会话包——块库(sid 不是 session_id)、操作记录;会话设置另处理
|
||||
("s_block_bank", {"sid": "@SID", "bill_id": "s_bills", "norm_id": "s_norms"}),
|
||||
("s_edit_log", {}),
|
||||
]
|
||||
|
||||
|
||||
@@ -50,14 +58,18 @@ def _read_zip(zip_path):
|
||||
for name in z.namelist():
|
||||
if name.startswith("rows/") and name.endswith(".json"):
|
||||
rows[name[5:-5]] = json.loads(z.read(name).decode("utf-8"))
|
||||
return man, sessions, rows
|
||||
sources = {}
|
||||
for name in z.namelist():
|
||||
if name.startswith("source/") and not name.endswith("/"):
|
||||
sources[name[7:]] = z.read(name)
|
||||
return man, sessions, rows, sources
|
||||
|
||||
|
||||
def run(con, zip_path, name=None, overrides=None):
|
||||
"""导入 .yhy:成功 {ok,sid,name,manual,tables,msg};失败 {ok:False,msg}。不 commit。"""
|
||||
ov = overrides or {}
|
||||
try:
|
||||
man, sess_rows, rows = _read_zip(zip_path)
|
||||
man, sess_rows, rows, sources = _read_zip(zip_path)
|
||||
except (zipfile.BadZipFile, KeyError, ValueError) as e:
|
||||
return {"ok": False, "msg": str(e)}
|
||||
if not sess_rows:
|
||||
@@ -74,7 +86,10 @@ def run(con, zip_path, name=None, overrides=None):
|
||||
for t, _refs in _TABLES:
|
||||
ids = [r.get("id") for r in rows.get(t, []) if isinstance(r.get("id"), int)]
|
||||
if ids:
|
||||
cur = con.execute("SELECT COALESCE(MAX(id),0) FROM %s" % t).fetchone()[0]
|
||||
try:
|
||||
cur = con.execute("SELECT COALESCE(MAX(id),0) FROM %s" % t).fetchone()[0]
|
||||
except Exception:
|
||||
continue
|
||||
offsets[t] = cur + 1 - min(ids)
|
||||
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
@@ -102,6 +117,8 @@ def run(con, zip_path, name=None, overrides=None):
|
||||
continue
|
||||
off = offsets.get(t, 0)
|
||||
tcols = [c[1] for c in con.execute("PRAGMA table_info('%s')" % t)]
|
||||
if not tcols:
|
||||
continue
|
||||
use = [c for c in tcols if c in data[0]]
|
||||
sql = "INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(use), ",".join("?" * len(use)))
|
||||
for r in data:
|
||||
@@ -112,14 +129,58 @@ def run(con, zip_path, name=None, overrides=None):
|
||||
v = (v or 0) + off
|
||||
elif c == "session_id":
|
||||
v = new_sid
|
||||
elif c == "sid" and refs.get(c) == "@SID":
|
||||
v = new_sid
|
||||
elif c in refs and refs[c] != "@SID" and isinstance(v, int):
|
||||
v = v + offsets.get(refs[c], 0)
|
||||
vals.append(_json_safe(v))
|
||||
con.execute(sql, vals)
|
||||
stat[t] = len(data)
|
||||
# 会话级设置:只带 session:<旧> 域,scope 换新会话;global/sys 不搬
|
||||
settings = rows.get("s_settings") or []
|
||||
n_set = 0
|
||||
if settings:
|
||||
for r in settings:
|
||||
scope = str(r.get("scope") or "")
|
||||
if not scope.startswith("session:"):
|
||||
continue
|
||||
con.execute("INSERT OR REPLACE INTO s_settings(scope,k,v) VALUES(?,?,?)",
|
||||
("session:%d" % new_sid, r.get("k"), _json_safe(r.get("v"))))
|
||||
n_set += 1
|
||||
if n_set:
|
||||
stat["s_settings"] = n_set
|
||||
# 源件随包:落到 source_files/<原名>,与 sessions.src_name 对上;原格式导出才有框架可套
|
||||
n_src = 0
|
||||
if sources:
|
||||
try:
|
||||
dbp = con.execute("PRAGMA database_list").fetchone()[2]
|
||||
src_dir = os.path.join(os.path.dirname(os.path.abspath(dbp)), "source_files")
|
||||
os.makedirs(src_dir, exist_ok=True)
|
||||
for nm, data in sources.items():
|
||||
base = os.path.basename(nm)
|
||||
if not base or base in (".", ".."):
|
||||
continue
|
||||
want = base.split("_", 1)[0].lower()
|
||||
got = hashlib.sha256(data).hexdigest()
|
||||
if len(want) == 64 and want != got:
|
||||
return {"ok": False, "msg": "YHY 源件哈希不符:%s" % base}
|
||||
fp = os.path.join(src_dir, base)
|
||||
if os.path.exists(fp):
|
||||
if hashlib.sha256(open(fp, "rb").read()).hexdigest() == got:
|
||||
n_src += 1
|
||||
continue
|
||||
return {"ok": False, "msg": "源件已存在且内容不同,拒绝覆盖:%s" % base}
|
||||
with open(fp, "wb") as f:
|
||||
f.write(data)
|
||||
n_src += 1
|
||||
stat["source_files"] = n_src
|
||||
except OSError as e:
|
||||
return {"ok": False, "msg": "YHY 源件落盘失败:%s" % e}
|
||||
return {"ok": True, "sid": new_sid, "session_id": new_sid, "name": new_name,
|
||||
"manual": bool(src.get("x_manual")), "tables": stat,
|
||||
"msg": "导入完成:%s(新会话 #%d)" % (new_name, new_sid)}
|
||||
"msg": "导入完成:%s(新会话 #%d)%s"
|
||||
% (new_name, new_sid,
|
||||
";注意:包内没有源文件,原格式导出不可用" if man.get("source_missing") else "")}
|
||||
|
||||
|
||||
def _json_safe(v):
|
||||
|
||||
91
CostReview/app/core/integrity.py
Normal file
91
CostReview/app/core/integrity.py
Normal file
@@ -0,0 +1,91 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 292:工料机引用完整性(全格式一条方法)。
|
||||
|
||||
源集 = 全项目工料机汇总源行;引用集 = 定额消耗 / 组成子级 / 汇总子级里的引用。
|
||||
导入端清孤儿在 import_job.save;本模块负责导出端最后一道闸:
|
||||
最终引用地仍有码找不到源 → ExportIntegrityError,拦截导出,绝不补占位。
|
||||
|
||||
格式只差标签:
|
||||
COS 源 LabourMaterialsEquipmentsMachinesSummary@Number
|
||||
引用 LabourMaterialsEquipmentsMachinesElement@Number
|
||||
ESCC 源 ResourceItem@Code
|
||||
引用 ResElementItem@ResCode
|
||||
SWT 源 ResourceItem@Code
|
||||
引用 NormResUsageItem@ResourceID(按单位 Resource.ID→Code 映射)
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
class ExportIntegrityError(RuntimeError):
|
||||
"""导出工料机引用完整性闸门:引用地有码、全项目源集没有。"""
|
||||
|
||||
|
||||
_SUM = re.compile(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*?\bNumber="([^"]*)"')
|
||||
_ELEM = re.compile(r'<LabourMaterialsEquipmentsMachinesElement\b[^>]*?\bNumber="([^"]*)"')
|
||||
|
||||
|
||||
def cos_sets(txt):
|
||||
src = {m.group(1) for m in _SUM.finditer(txt) if m.group(1)}
|
||||
refs = {m.group(1) for m in _ELEM.finditer(txt) if m.group(1)}
|
||||
return src, refs
|
||||
|
||||
|
||||
def escc_sets(txt):
|
||||
src = {m.group(1) for m in re.finditer(
|
||||
r'<ResourceItem\b[^>]*?\bCode="([^"]*)"', txt) if m.group(1)}
|
||||
refs = {m.group(1) for m in re.finditer(
|
||||
r'<ResElementItem\b[^>]*?\bResCode="([^"]*)"', txt) if m.group(1)}
|
||||
return src, refs
|
||||
|
||||
|
||||
def swt_sets(txt):
|
||||
"""SWT:ResourceItem@Code 是源;NormResUsageItem@ResourceID 是引用地,
|
||||
Resource@ID→Code 是映射。映射不全时只校验能映射的引用,不误杀。"""
|
||||
src = {m.group(1) for m in re.finditer(
|
||||
r'<ResourceItem\b[^>]*?\bCode="([^"]*)"', txt) if m.group(1)}
|
||||
id2code = {}
|
||||
for m in re.finditer(r'<Resource\b[^>]*?>', txt):
|
||||
ot = m.group(0)
|
||||
rid = re.search(r'\bID="([^"]*)"', ot)
|
||||
if not rid:
|
||||
continue
|
||||
seg = txt[m.end():m.end() + 6000]
|
||||
cm = re.search(r'<ResourceItem\b[^>]*?\bCode="([^"]*)"', seg)
|
||||
if cm:
|
||||
id2code[rid.group(1)] = cm.group(1)
|
||||
refs = set()
|
||||
for m in re.finditer(r'<NormResUsageItem\b[^>]*?\bResourceID="([^"]*)"', txt):
|
||||
rid = m.group(1)
|
||||
if rid in id2code:
|
||||
refs.add(id2code[rid])
|
||||
return src, refs
|
||||
|
||||
|
||||
def _raise_if_missing(kind, src, refs):
|
||||
missing = sorted(refs - src)
|
||||
if missing:
|
||||
raise ExportIntegrityError(
|
||||
"%s 导出引用完整性失败:引用地 %d 个码找不到全项目工料机源,缺 %d 个(例:%s)。"
|
||||
"按决策 292 拦截导出,不补占位。" % (kind, len(refs), len(missing), "、".join(missing[:8])))
|
||||
|
||||
|
||||
def validate_cos(txts, where=""):
|
||||
src, refs = set(), set()
|
||||
for t in txts:
|
||||
s, r = cos_sets(t)
|
||||
src |= s
|
||||
refs |= r
|
||||
_raise_if_missing("COS/COS4" + (" " + where if where else ""), src, refs)
|
||||
return len(src), len(refs)
|
||||
|
||||
|
||||
def validate_escc(txt, where=""):
|
||||
src, refs = escc_sets(txt)
|
||||
_raise_if_missing("ESCC/XML" + (" " + where if where else ""), src, refs)
|
||||
return len(src), len(refs)
|
||||
|
||||
|
||||
def validate_swt(txt, where=""):
|
||||
src, refs = swt_sets(txt)
|
||||
_raise_if_missing("SWT/SWZ" + (" " + where if where else ""), src, refs)
|
||||
return len(src), len(refs)
|
||||
@@ -4826,6 +4826,10 @@ def _export_meta(sc, sid, fmt=""):
|
||||
return {"ok": False, "msg": "会话不存在"}
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
f = (fmt or "").lower()
|
||||
# 2026-11-10 主人报「选导出yhy,另存为还是 .xml」:meta 缺 yhy 分支,原生另存为
|
||||
# 预填了源后缀,YHY 数据包被写成 .xml,收方按 .yhy 识别就收不到。先判 yhy。
|
||||
if f == "yhy":
|
||||
return {"ok": True, "name": (proj_name or "工程") + "-审核版.yhy"}
|
||||
if f == "html":
|
||||
return {"ok": True, "name": (proj_name or "工程") + "-审核版.yhy"}
|
||||
if f == "xlsx":
|
||||
@@ -5356,7 +5360,8 @@ def _export_session(sc, sid, fmt="", progress=None):
|
||||
recode_ident=recode_ident,
|
||||
unit_mig=_unit_code_mig(sc, sid, uwmap, recode_ident),
|
||||
progress=progress,
|
||||
price_updates=price_updates)
|
||||
price_updates=price_updates,
|
||||
added_children=added_children)
|
||||
except Exception as e:
|
||||
return None, None, "导出失败:%s" % e
|
||||
return raw, out_name, None
|
||||
|
||||
Reference in New Issue
Block a user