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

@@ -27,14 +27,18 @@ import tempfile
import zipfile
import xml.etree.ElementTree as ET
# cos 族 = 易达两代格式,同一条代码路径(决策 105);其余后缀注册即收
import skeleton_engine as _se # 决策 262:格式无关骨架引擎(族判定/收敛/旁注/匹配)
# 决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」):
# **后缀不再参与拦截**——能不能用由内容判定(zip 内 XML / 裸 XML),见 skeleton_engine。
# 这里只保留"从文件名取后缀"的能力;当前已实件验过的四种=cos/cos4/swt/swz。
_COS_RE = re.compile(r"\.(cos4?)$", re.I)
def suffix_of(name):
"""文件名 → 规范后缀 cos|cos4;本次未注册的格式返回 None(不收不挡)。"""
m = _COS_RE.search(os.path.basename(name or ""))
return m.group(1).lower() if m else None
"""文件名 → 小写后缀(任意后缀都返回;能不能用由 skeleton_engine.family_of 按内容判)。"""
ext = os.path.splitext(os.path.basename(name or ""))[1]
return ext[1:].lower() if ext else None
def _now():
@@ -57,6 +61,10 @@ def _ensure_table(con):
# 决策 260 补记三/四:该骨架的**空骨架**(单 XML 空数据模板字节)——由本件
# 自动总结(值全空、列集按样板自增行规整),「每件一个小骨架」并存
con.execute("ALTER TABLE classic_skel ADD COLUMN x_blank BLOB")
if "x_meta" not in _cols:
# 决策 262:结构旁注(角色路径 unit/bill/norm/lme + 各路径出现次数)——
# 骨架文件只放结构,重复次数与数据源这类"文件里没有的语义"单独存这里
con.execute("ALTER TABLE classic_skel ADD COLUMN x_meta TEXT")
if "x_layer_cols" not in _cols:
# 决策 260 补记八(2026-11-03 主人定「根据第一行的列选骨架」):该骨架的
# **分层列集指纹** JSON——{标签: 列集并集},入库时预计算;导出/打开项目时
@@ -75,88 +83,36 @@ _MATCH_LAYERS = ("ConstructionProject", "UnitWorks", "WorkElement", "Norm",
def layer_cols_of(z_or_blob):
"""一份实件(zip 或字节)→ {标签: 该层列集并集}(全成员汇总)。"""
"""一份实件 → **分层列集指纹**(决策 262:路径键、格式无关、不含次数)。
返回 {'v':2,'p':{路径:[列名…]}};认不出格式(加密壳/坏件)→ {}。
旧指纹(标签键)由 match_score 兼容读,pick_frame 见非 v2 会重算回写。"""
try:
z = z_or_blob if isinstance(z_or_blob, zipfile.ZipFile) \
else zipfile.ZipFile(io.BytesIO(z_or_blob))
blob = z_or_blob if isinstance(z_or_blob, (bytes, bytearray)) \
else (z_or_blob.read() if hasattr(z_or_blob, "read") else None)
except Exception:
return {}
if not blob:
return {}
try:
mains, units, fam = _se.split_roots(blob)
except Exception:
return {}
if fam is None:
return {}
try:
return _se.layer_cols(mains + units)
except Exception:
return {}
out = {}
for nm in z.namelist():
if not nm.lower().endswith(".xml"):
continue
try:
root = ET.fromstring(z.read(nm))
except Exception:
continue
for el in root.iter():
if el.tag is ET.Comment:
continue
if el.tag not in _MATCH_LAYERS:
continue
s = out.setdefault(el.tag, set())
s.update(el.attrib.keys())
return out
def match_score(src_cols, skel_cols):
"""分层匹配度(0~100):第一层(根)权重最高,逐层下探;每层=列集 Jaccard×100。
根列集完全一致→直接满分命中(主人定「第一行相同才下探」)。"""
if not skel_cols:
"""匹配度 0~100(决策 262,主人定「字段越匹配分越高、区域越匹配分越高」):
字段=同层列集重合(根层权重最高);区域=骨架结构位在原件里的覆盖率;
根标签不同=不同格式族,直接压到 10 分以下。"""
try:
return _se.match_score(src_cols, skel_cols)
except Exception:
return 0.0
root_t = _MATCH_LAYERS[0]
sy = src_cols.get(root_t) or set()
sk = skel_cols.get(root_t) or set()
if sy and sk:
if sy == sk:
base = 100.0 # 第一行完全一致:满分命中
else:
inter = len(sy & sk)
base = inter / max(1, len(sy | sk)) * 60.0 # 根不一致:上限 60
else:
base = 30.0 # 某方缺根层:低分
# 下探层:平均 Jaccard
rest = [t for t in _MATCH_LAYERS[1:] if (src_cols.get(t) or skel_cols.get(t))]
if rest:
acc = 0.0
for t in rest:
a = src_cols.get(t) or set()
b = skel_cols.get(t) or set()
if a or b:
acc += len(a & b) / max(1, len(a | b))
base = base * 0.7 + (acc / len(rest)) * 100.0 * 0.3
return round(base, 2)
# ---------------------------------------------------------------------------
# 空骨架提炼引擎(决策 260 补记三/四,2026-11-02 主人定「每个骨架实件各自总结出
# 一个小骨架(空数据模板);引擎做成活的——后期很多不同后缀文件」)
# 流程(共用):骨架实件 → 按 SKEL_RULES[后缀] 提炼 → 单 XML 空数据模板(值全空)
# → 与主人样板对比无误 → 数据回灌。新后缀接入=加一份 SKEL_RULES 配置,引擎零改动。
# 骨架正定义见术语表「导出骨架」:标签=卡槽、属性=列(值留空)、数据按需自动增行、
# 自闭合行=自增行(数据行样板),排序列=模板节点顺序,不提供任何数值。
# ---------------------------------------------------------------------------
SKEL_RULES = {
"cos4": {
# 项目成员识别:body 含任一标识标签
"proj_ident": ("<SectionalWorks", "<ConstructionProject"),
# 单位成员根标签
"unit_root": "UnitWorks",
# 引用行样例保留数(连接时内嵌的单位子树数)
"keep_refs": 1,
},
# cos 与 cos4 同构(决策 105:易达两代格式同一条代码路径)
"cos": {
"proj_ident": ("<SectionalWorks", "<ConstructionProject"),
"unit_root": "UnitWorks",
"keep_refs": 1,
},
# "swt": {...} # 后期注册:SWT 锚点集与规则(决策 122 单 Rate 口径)
# "swz": {...}
}
_BLANK_KEEP_REFS_DEFAULT = 1
def _blank_parse(xml_text):
@@ -321,72 +277,42 @@ def _blank_ind_unit(xml_text):
def refine_blank(con, blob, suffix="cos4"):
"""骨架实件(zip 字节)→ 该件的**空数据模板**(单 XML 字节,值全空、列集按自增行规整)。
"""骨架实件(zip 或裸 XML 字节)→ 该件的**空数据模板**(单 XML 字节,值全空)。
规律(决策 260,主人样板《骨架结构-空数据模板.xml》同款):实件 zip = Project.xml +
N 个单位成员;提炼 = ①值全清空(声明按骨架豁免;注释原文件有才保留,引擎不造);
②Project.xml 引用行只留样例;③单位成员取最全 1 个;④样例引用行位置内嵌单位成员
完整子树(2 个 xml 连接展示);⑤**自增行规整**——同类行列集统一到样板自增行列序。
suffix 走 SKEL_RULES——新后缀加配置即接入(活引擎)。con 供样板基准表(skel_ref_件)。"""
rule = SKEL_RULES.get((suffix or "").lower())
if not rule:
return None
src = zipfile.ZipFile(io.BytesIO(blob))
proj_nm = None
unit_best = None # (元素数, 内部名, xml文本)
texts = {}
for nm in src.namelist():
if not nm.lower().endswith(".xml"):
continue
txt, enc = _decode_pair(src.read(nm))
texts[nm] = (txt, enc)
body = re.sub(r"^.*?\?>", "", txt, count=1, flags=re.S).lstrip()
if any(k in body for k in rule["proj_ident"]):
proj_nm = nm
elif body.startswith("<" + rule["unit_root"]):
n = len(re.findall(r"<[A-Za-z_]", txt))
if unit_best is None or n > unit_best[0]:
unit_best = (n, nm, txt)
if not proj_nm or unit_best is None:
return None
base, tag_base = _blank_ref_base(con, suffix)
# Project.xml:清值+规整+引用行只留样例(ET 树上做;引用行嵌在 SectionalWorks
# 等容器内——递归收集 (父节点, 引用行) 对,从各自父节点删多余、留首条样例)
pr, decl = _blank_parse(texts[proj_nm][0])
_blank_normalize(pr, base, tag_base, "", is_root=True)
keep = rule.get("keep_refs", _BLANK_KEEP_REFS_DEFAULT)
uroot = rule["unit_root"]
pairs = []
for par in pr.iter():
for k in list(par):
if k.tag == uroot:
pairs.append((par, k))
for par, k in pairs[keep:]:
par.remove(k)
# 单位成员:清值+规整(取最全 1 个的文本重新解析)
ur, _uenc = _blank_parse(unit_best[2])
# 缩进单位从实件锚定(主人 2026-11-03 定「注意换行对齐」):取成员里最内层
# 子标签相对父标签的缩进步进(易达 4 空格;SWT 等其他后缀按各自实件自动适配)
ind_unit = _blank_ind_unit(unit_best[2])
_blank_normalize(ur, base, tag_base, "")
# 连接:首条样例引用行的位置 → 内嵌单位成员完整子树(引用行属性列集=成员根列集,
# 同源同构;其余样例引用行保留)
if not pairs:
return None
ref_par, ref_k = pairs[0]
pos = list(ref_par).index(ref_k)
ref_par.remove(ref_k)
ref_par.insert(pos, ur)
# 序列化(缩进按实件锚定、LF、无自造注释;声明按骨架原样,编码回写按声明)
out = [decl]
_blank_ser(pr, 0, out, is_root=True, ind_unit=ind_unit)
enc_m = re.search(r'encoding="([^"]*)"', decl)
enc = enc_m.group(1) if enc_m else "utf-8"
text = "\n".join(out) + "\n"
决策 262(2026-11-03 主人定「引擎写活了,后期还有很多后缀」)起改由
skeleton_engine 统一提炼——**不看后缀,按内容判族**:
· zip 内 XML(cos/cos4 型):主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
· 裸 XML(swt/swz 型):整件收敛。
收敛口径=唯一结构位(父路径+标签+列集)只留一个样板、子节点取并集、值全清空;
缩进按实件锚定(主人 2026-11-03 定「注意换行对齐」)。con 保留给旧样板基准表用。"""
blank, _meta = refine_blank_ex(blob, suffix)
return blank
def refine_blank_ex(blob, suffix="cos4"):
"""→ (空骨架字节, 结构旁注 meta)。meta 随骨架入库(x_meta),导出端按它定位层。
认不出格式族(加密壳/二进制)→ (None, None)。"""
try:
return text.encode(enc)
ind = " "
text0 = None
try:
members = _se._members(blob)
if members:
raw0, _e0 = _decode_pair(members[-1][1])
text0 = raw0
except Exception:
text0 = None
if text0:
ind = _blank_ind_unit(text0)
text, meta = _se.build_blank(blob, ind_unit=ind)
except Exception:
return text.encode("utf-8")
return None, None
if not text:
return None, None
try:
return text.encode("utf-8"), meta
except Exception:
return None, None
def blank_from_frame(blob):
@@ -450,16 +376,16 @@ def extract(path):
return None
shapes, n_nodes = set(), 0
try:
with zipfile.ZipFile(path) as z:
members = 0
for nm in z.namelist():
if not nm.lower().endswith(".xml"):
continue
s, n = _shapes_of_bytes(z.read(nm))
if n:
members += 1
shapes |= s
n_nodes += n
blob = open(path, "rb").read()
if _se.family_of(blob) is None: # 决策 262:内容判族,后缀不拦截
return None
members = 0
for _nm, raw in _se._members(blob):
s, n = _shapes_of_bytes(raw)
if n:
members += 1
shapes |= s
n_nodes += n
except Exception:
return None
if not members or not shapes:
@@ -530,10 +456,12 @@ def seed_frame(con, path, name):
with open(path, "rb") as f:
blob = f.read()
_blank = None
_meta = None
try:
_blank = refine_blank(con, blob, info["suffix"]) # 决策 260 补记四:入库即总结该件空骨架(单 XML 空数据模板)
# 决策 262:入库即提炼空骨架 + 结构旁注(meta 供导出端定位层,不写进骨架文件)
_blank, _meta = refine_blank_ex(blob, info["suffix"])
except Exception:
_blank = None
_blank, _meta = None, None
# 决策 260 补记八:入库即预计算**分层列集指纹**(导出/打开项目时算匹配度用)
_layer_cols = {}
try:
@@ -541,19 +469,21 @@ def seed_frame(con, path, name):
except Exception:
_layer_cols = {}
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
n_shapes,n_nodes,blob,extracted_at,is_frame,x_blank,x_layer_cols)
VALUES(?,?,?,?,?,?,?,?,1,?,?)
n_shapes,n_nodes,blob,extracted_at,is_frame,x_blank,x_layer_cols,x_meta)
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, is_frame=1,
x_blank=COALESCE(excluded.x_blank, x_blank),
x_layer_cols=COALESCE(excluded.x_layer_cols, x_layer_cols)""",
x_layer_cols=COALESCE(excluded.x_layer_cols, x_layer_cols),
x_meta=COALESCE(excluded.x_meta, x_meta)""",
(info["sig"], info["suffix"],
hashlib.sha256(blob).hexdigest(), name,
info["n_shapes"], info["n_nodes"], blob, _now(), _blank,
json.dumps({k: sorted(v) for k, v in _layer_cols.items()},
ensure_ascii=False) if _layer_cols else None))
info["n_shapes"], info["n_nodes"], blob, _now(),
_blank if isinstance(_blank, (bytes, bytearray)) else None,
json.dumps(_layer_cols, ensure_ascii=False) if _layer_cols else None,
json.dumps(_meta, ensure_ascii=False) if _meta else None))
con.commit()
return info["sig"]
@@ -608,8 +538,8 @@ def frame_blob(con, sig):
def frame_blank(con, sig):
"""取一件骨架的**空骨架**(决策 260 补记三「每件一个小骨架」):x_blank 有→直接回;
无(存量件)→ 现场总结并回写(惰性补齐,幂等)。→ (空骨架 XML 字节, original_name)。"""
row = con.execute("SELECT sig, blob, original_name, x_blank, suffix FROM classic_skel WHERE sig=?",
(sig,)).fetchone()
row = con.execute("SELECT sig, blob, original_name, x_blank, suffix, x_meta "
"FROM classic_skel WHERE sig=?", (sig,)).fetchone()
if not row:
return None, None
blank = row["x_blank"]
@@ -621,11 +551,34 @@ def frame_blank(con, sig):
if blank:
con.execute("UPDATE classic_skel SET x_blank=? WHERE sig=?", (blank, sig))
con.commit()
try: # 决策 262:顺带补齐结构旁注(幂等)
if not row["x_meta"]:
_b2, _m2 = refine_blank_ex(row["blob"], row["suffix"])
if _m2:
con.execute("UPDATE classic_skel SET x_meta=? WHERE sig=?",
(json.dumps(_m2, ensure_ascii=False), sig))
con.commit()
except Exception:
pass
if not blank:
return None, row["original_name"]
return bytes(blank), row["original_name"]
def frame_meta(con, sig):
"""取一件骨架的**结构旁注**(决策 262):{v,paths,roles};无→None(可惰性补齐)。"""
try:
row = con.execute("SELECT x_meta FROM classic_skel WHERE sig=?", (sig,)).fetchone()
except Exception:
return None
if not row or not row["x_meta"]:
return None
try:
return json.loads(row["x_meta"])
except Exception:
return None
def seed_pack(con, path):
"""骨架包安装(2026-11-02 主人定两阶段架构:阶段二上市版「后台直接上传骨架包、
租户客户端接收」——本函数是包→库的共用解包口,阶段一后台手动传包同走这里)。
@@ -637,7 +590,7 @@ def seed_pack(con, path):
with zipfile.ZipFile(path) as z:
for info in z.infolist():
nm = info.filename
if not _COS_RE.search(nm):
if not _se.family_of(z.read(info)): # 决策 262:按内容认,不按后缀
continue
try: # zip 成员名常见 GBK 存 KB:cp437 转回
nm2 = nm.encode("cp437").decode("gbk")
@@ -692,18 +645,19 @@ def pick_frame(con, suffix, src_path=None, src_blob=None):
s = None
try:
if f["x_layer_cols"]:
skel_cols = {k: set(v) for k, v in json.loads(f["x_layer_cols"]).items()}
s = match_score(src_cols, skel_cols)
skel_cols = json.loads(f["x_layer_cols"])
# 决策 262:只认新指纹(v2 路径键);旧标签键指纹→按 v2 重算回写
if isinstance(skel_cols, dict) and skel_cols.get("v") == 2:
s = match_score(src_cols, skel_cols)
except Exception:
s = None
if s is None:
# 旧骨架无指纹 → 现场算(并回写)
# 旧骨架/旧指纹 → 现场算(并回写 v2 指纹)
try:
skel_cols = layer_cols_of(f["blob"])
s = match_score(src_cols, skel_cols)
con.execute("UPDATE classic_skel SET x_layer_cols=? WHERE sig=?",
(json.dumps({k: sorted(v) for k, v in skel_cols.items()},
ensure_ascii=False), f["sig"]))
(json.dumps(skel_cols, ensure_ascii=False), f["sig"]))
con.commit()
except Exception:
s = -1.0

View File

@@ -151,6 +151,7 @@ def _price_map(sc, sid):
out = {}
for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp,
ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags,
x_org_ntp0, x_org_taxp0,
COALESCE(x_merged_hide,0) AS hid, x_remark
FROM s_lme_proj WHERE session_id=?""", (sid,)):
out[r["code"]] = dict(r)
@@ -324,6 +325,14 @@ def _dyn_rows(sc, sid, uw_id=None):
ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp")
_pk6 = lambda a, b: (a if a is not None else b)
org4 = tuple(_pk6(r.get(k), p.get(k)) for k in ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr"))
# 定额单价专题(2026-11-03 主人定):原价第③级兜底=第一次外部采纳价(x_org_*0,
# 采纳落价时列空才写);①单位级 → ②项目级 → ③此列;Expr(调价式)无采纳源、不兜底。
_o = list(org4)
if _o[0] is None and p.get("x_org_ntp0") is not None:
_o[0] = p["x_org_ntp0"]
if _o[2] is None and p.get("x_org_taxp0") is not None:
_o[2] = p["x_org_taxp0"]
org4 = tuple(_o)
# s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行
# 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空)
lb = lbm.get(code)

View File

@@ -1046,6 +1046,29 @@ def _lme_apply_price(newtag, px):
for attr in ("NoTaxPrice", "NoTaxPriceExpress", "NoTaxOrgPrice", "TaxRate",
"TaxPrice", "TaxPriceExpress", "TaxOrgPrice"):
_set(attr, px.get(attr))
# 定额单价专题(2026-11-03 主人定「合并=勾选谁按哪一行的字段」):合并统一全列回写——
# Kind + 文字/标志属性(x_flags JSON,决策 259 全采);恒空链键(Remark/PriceSource/
# Delivery/Location/ProducingArea/Supplier/Character)不回写;骨架无该属性=卡槽无 →
# 不写(_set 内属性存在才设=「按源数据+骨架过滤输出」)。
_kd = px.get("Kind")
if _kd is not None:
try:
_set("Kind", str(int(_kd)))
except (TypeError, ValueError):
pass
_fl = px.get("_flags")
if isinstance(_fl, dict):
for k, v in _fl.items():
if k in ("Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
"Supplier", "Character") or v is None:
continue
_set(k, str(v))
# 恒空链:合并回写行上源文件残留的 Remark/询价类属性清空(2026-11-03 主人定「恒空」;
# 源行自带值也不保留——真件实测 CL01 源行 Remark="原始备注" 残留)。_set 只动骨架有槽的。
for k in ("Remark", "PriceSource", "Delivery", "Location", "ProducingArea",
"Supplier", "Character"):
if re.search(r'\b' + k + r'="', newtag) and _attr(newtag, k):
newtag = _attr_set(newtag, k, "")
for tot, pattr in (("NoTaxOrgTotal", "NoTaxOrgPrice"), ("NoTaxTotal", "NoTaxPriceExpress"),
("TaxOrgTotal", "TaxOrgPrice"), ("TaxTotal", "TaxPriceExpress")):
if not re.search(r'\b' + tot + r'="', newtag):
@@ -1835,137 +1858,3 @@ def _resolve_recode_chains(m):
if tail != k:
out[k] = tail
return out
def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidden_codes, res_by_norm,
price_updates=None, added_lme_by_uw=None, sync_rows=None, recode_map=None, recode_children=None,
recode_ident=None, field_updates=None, added_children=None, added_org=None,
progress=None):
"""src_bytes=原文件字节;unit_plans={uw键(Number,Name): plan};
plan={"pairs":{...}, "news":{...}, "norms_by_bill":{...}, "added_lme":[(码,名,规格,单位,量,税率,除税,含税,类别)]}。
recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出);
recode_map 进通道前先压平改码链(决策 174 补)。
added_children:采纳新增行的子级组成 {码:[(子码,含量)]}(决策 204:带子级整组照原生结构导出)。
added_org:采纳新增行三恒值 {码:(除税定额价,含税定额价,税率)}(决策 205 主人定:按原数据回填,不编造)。
progress=可选回调 progress(done, total)——每个 zip 条目处理完报一次(决策 92 导出进度条)。
返回 (新zip字节, 建议文件名)。"""
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
ext = _source_ext(src_name)
out_name = (proj_name or "工程") + "-审核版" + ext
zin = zipfile.ZipFile(io.BytesIO(src_bytes))
zout = io.BytesIO()
entries = zin.infolist()
# 2026-10-20 主人定:先扫全项目,取「同一清单标签下最大最全的合格块」当骨架。
# 只按清单块起止位置认,不依赖字段名——COS/COS4/广联达/易达骨架不同也能用。
bill_tmpls, bill_scores = {}, {}
for item in entries:
raw0 = zin.read(item.filename)
try:
txt0, _enc0 = _decode(raw0)
except Exception:
continue
if "<WorkElement" not in txt0 and "<UnitWorksPreliminaryWorkElement" not in txt0:
continue
for tag in ("WorkElement", "UnitWorksPreliminaryWorkElement"):
blk0 = _largest_bill_block(
txt0, tag,
prelim=(tag == "UnitWorksPreliminaryWorkElement"))
if not blk0:
continue
sc0 = _bill_block_score(blk0)
if tag not in bill_tmpls or sc0 > bill_scores[tag]:
bill_tmpls[tag] = blk0
bill_scores[tag] = sc0
if progress:
progress(0, len(entries))
# 决策 187:两遍式——第一遍处理单位 xml 并**收集成品文本**(Project 聚合的数据源),
# Project.xml 延迟到第二遍(保证 Project=各单位之和);条目按原顺序写出,框架零变动。
finals = {} # filename → 变换后 raw
unit_final_texts = [] # 各单位成品文本(Project 聚合用)
with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo:
for _ei, item in enumerate(entries, 1):
raw = zin.read(item.filename)
base = item.filename.rsplit("/", 1)[-1]
if base.lower() == "project.xml":
finals[item.filename] = raw # 延迟处理
continue
txt, enc = _decode(raw)
if "<WorkElement" in txt or "<UnitWorksPreliminaryWorkElement" in txt:
keys = []
for m in re.finditer(r'<UnitWorks\b', txt):
e = _open_tag_end(txt, m.start())
if e < 0:
continue
ot = txt[m.start():e]
k = (_attr(ot, "Number") or "", _attr(ot, "Name") or "")
if k in unit_plans and k not in keys:
keys.append(k)
for k in keys:
plan = unit_plans[k]
txt = transform_unit(txt, k, plan["pairs"], plan["news"],
plan["norms_by_bill"], res_by_norm,
bill_tmpls=bill_tmpls)
# 决策 74(主人口径 5.1/5.2/5.3):本单位汇总=被查找对象——
# 同步行按编码写回本单位汇总(改价/名称规格单位不一致项);采纳新增品类行追加进本单位汇总
added_rows = []
for k in keys:
added_rows.extend(unit_plans[k].get("added_lme") or [])
# 单位汇总只接受**合并改价**(被查找对象的精准更新)+ 编辑过的名称/规格/单位
# (field_updates,2026-10-22)——全字段 sync 是项目级的事——
# 否则零编辑也会大面积误改(已实测踩坑)
upd = {c: v for c, v in (price_updates or {}).items()}
# 决策 174:recode_map 有映射也要进(该单位没有合并改价码时,变体码节点
# 照样要换码——此前整个跳过=该单位文件变体码全残留)
if upd or added_rows or field_updates or recode_map or recode_ident:
txt = transform_unit_summaries(txt, upd, added_rows, recode_map, recode_children,
field_updates=field_updates, recode_ident=recode_ident,
added_children=added_children, added_org=added_org)
# 决策 188 数量模型:本单位的现算数量写回导出件(Project 聚合随之正确)——
# 放在 if 外:该单位即使没有其他编辑通道,数量也要按现算写(2026-10-24 实测漏)。
# 一个 xml 可能含多个 uw:各 uw 的数量图合并(同码相加)。
qu = {}
for k in keys:
for _c, _q in (unit_plans[k].get("qty_updates") or {}).items():
qu[_c] = qu.get(_c, 0.0) + float(_q or 0)
if qu:
txt = _apply_qty_updates(txt, qu)
# 决策 244 补五:分部 Total/费用表合计按现算回填(api 层算好随 plan 带入;
# 旧调用方 plan 无此键 → 原样,fail-open)
txt = _apply_div_totals(txt, {k: unit_plans[k] for k in keys})
if recode_map: # 2026-10-22:定额消耗量行编码替换(Summary 块外)
txt = _recode_norm_lme_rows(txt, recode_map)
# 决策 244 补记三:传现算图(码不在图=没被引用、或现算 0 → 都不导);
# 现算链故障(_live_ok=False)退回老行为(按节点 Quantity==0 判)
txt = _drop_zero_qty_summary_rows(
txt, qu if all(unit_plans[k].get("_live_ok", True) for k in keys) else None) # 决策 199/244
txt = _merge_norm_lme_elements(txt) # 决策 200:定额尾表同码并一条
raw = _encode(txt, enc)
unit_final_texts.append(txt) # 决策 187:成品收集
finals[item.filename] = raw
if progress:
progress(_ei, len(entries))
# 第二遍:Project.xml 聚合重建(决策 187 取代 sync 修补——广联达拒导入根治)
for item in entries:
base = item.filename.rsplit("/", 1)[-1]
if base.lower() != "project.xml":
continue
raw = finals.get(item.filename) or zin.read(item.filename)
txt, enc = _decode(raw)
txt = transform_project(txt, added_summaries, hidden_codes, sync_rows,
recode_map=recode_map, recode_children=recode_children,
recode_ident=recode_ident, unit_texts=unit_final_texts,
added_org=added_org)
if recode_map: # 决策 174:Project.xml 的块外元素行同口径换码
txt = _recode_norm_lme_rows(txt, recode_map)
finals[item.filename] = _encode(txt, enc)
# 按原条目顺序写出(zip 条目序=源框架不动)
for item in entries:
raw = finals.get(item.filename) or zin.read(item.filename)
# 条目名按原始字节保真回写(修单位工程名乱码)
zi = _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
zi.extra = _safe_extra(item.extra) # 附加块保真(NTFS 时间戳等,见 _safe_extra)
zo.writestr(zi, raw)
return zout.getvalue(), out_name

View File

@@ -1,268 +0,0 @@
# -*- coding: utf-8 -*-
"""HTML 导出(2026-11-03 主人定):导出「界面可以看到的一模一样的数据,包含审核的备注内容」,
全部已有数据渲染成一个自包含 .html 单文件(内嵌样式,浏览器直接打开)。
层级与数据源(与工作台同一套会话库 + 决策 188 现算引擎,显示=导出):
· 项目标题 / 目录树概览(s_sections → s_unit_works,树序=单项入库序+编号自然序,231 补记十)
· 项目级工料机汇总(dyn_lme.dyn_rows 现算,前 11 列=界面项目级卡同形,决策 147/259)
· 项目汇总分析(s_proj_summary 原样树,决策 244)
· 单位工程:分部分项表(分部→清单→定额子行,审核备注列 x_remark)+措施项目表
+单位级工料机汇总(dyn_lme.dyn_uw_rows 现算 9 列)
· 临删行保留并打删除线(界面所见);没算的数值留空(填空三分类)
只读会话库,不碰源文件;cos/cos4/xlsx 通道一概不经过这里。"""
import io
import html as _h
import dyn_lme
def _fmt_money(v):
if v is None or v == "":
return ""
try:
return "{:,.2f}".format(float(v))
except (TypeError, ValueError):
return str(v)
def _fmt_qty(v):
if v is None or v == "":
return ""
try:
f = float(v)
s = ("%f" % f).rstrip("0").rstrip(".")
return s if s else "0"
except (TypeError, ValueError):
return str(v)
def _e(v):
return _h.escape("" if v is None else str(v), quote=True)
def _tree_order(sc, sid):
"""单位工程树序(=export_excel_bytes 同款:单项入库序+组内编号自然序)。"""
from formats.skeleton import _natkey
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())}
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"]))
secs = sc.execute("SELECT * FROM s_sections WHERE session_id=? ORDER BY id", (sid,)).fetchall()
return secs, uws
def _proj_lme_table(sc, sid):
"""项目级工料机汇总表(dyn_rows 前 11 列,与界面卡同形)。"""
try:
rows = dyn_lme.dyn_rows(sc, sid, None) or []
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr>",
"<th>编码</th><th>名称</th><th>规格型号</th><th>单位</th><th>类别</th>",
"<th>消耗量</th><th>除税编制价</th><th>税率(%)</th><th>含税编制价</th><th>备注</th>",
"</tr></thead><tbody>"]
for r in rows:
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td><td>%s</td></tr>"
% (_e(r[1]), _e(r[2]), _e(r[3]), _e(r[4]), _e(r[9]),
_fmt_qty(r[5]), _fmt_money(r[6]), _fmt_qty(r[7]), _fmt_money(r[8]), _e(r[10])))
out.append("</tbody></table>")
return "".join(out)
def _uw_lme_table(sc, sid, uw_id):
"""单位级工料机汇总表(dyn_uw_rows 前 9 列=界面形状:码/名/规/单/类别/量/除税/税率/含税)。"""
try:
rows = dyn_lme.dyn_uw_rows(sc, sid, uw_id) or []
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr>",
"<th>编码</th><th>名称</th><th>规格型号</th><th>单位</th><th>类别</th>",
"<th>数量</th><th>除税价</th><th>税率(%)</th><th>含税价</th>",
"</tr></thead><tbody>"]
for r in rows:
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td></tr>"
% (_e(r[0]), _e(r[1]), _e(r[2]), _e(r[3]), _e(r[4]),
_fmt_qty(r[5]), _fmt_money(r[6]), _fmt_qty(r[7]), _fmt_money(r[8])))
out.append("</tbody></table>")
return "".join(out)
def _proj_summary_table(sc, sid):
"""项目汇总分析(s_proj_summary 原样树,决策 244;无表/无数据=空卡)。"""
try:
rows = sc.execute("""SELECT Kind, Number, Code, Name, Formula, Rate, Total, Remark
FROM s_proj_summary WHERE session_id=? ORDER BY id""",
(sid,)).fetchall()
except Exception:
rows = []
if not rows:
return "<p class='empty'>没有数据</p>"
out = ["<table class='grid'><thead><tr><th>序号</th><th>编码</th><th>名称</th>",
"<th>计算公式/说明</th><th>费率(%)</th><th>金额</th><th>备注</th>",
"</tr></thead><tbody>"]
for r in rows:
num = r["Number"] or ""
out.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td>%s</td></tr>"
% (_e(num), _e(r["Code"]), _e(r["Name"]), _e(r["Formula"]),
_fmt_qty(r["Rate"]), _fmt_money(r["Total"]), _e(r["Remark"])))
out.append("</tbody></table>")
return "".join(out)
def _bills_tables(sc, uw_id):
"""单位工程的 分部分项+措施 两张表(分部树递归照 export_excel_bytes 同款挂接)。"""
ds_all = [dict(r) for r in sc.execute(
"SELECT * FROM s_divides WHERE uw_id=? ORDER BY x_seq, id", (uw_id,)).fetchall()]
bills = [dict(r) for r in sc.execute(
"""SELECT * FROM s_bills WHERE uw_id=?
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (uw_id,)).fetchall()]
def b_total(b):
try:
if b.get("Quantity") is not None and b.get("Price") is not None:
return round(float(b["Quantity"]) * float(b["Price"]), 2)
except (TypeError, ValueError):
pass
return b.get("Total")
def norm_rows_html(bill_id):
out = []
for n in sc.execute("""SELECT Number, Name, Unit, Quantity, Price, Total, x_tdel
FROM s_norms WHERE bill_id=? ORDER BY id""", (bill_id,)).fetchall():
out.append("<tr%s><td class='ind'>└ %s</td><td>%s</td><td></td><td>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td class='n'>%s</td><td></td></tr>"
% ((" class='tdel'" if n["x_tdel"] else ""),
_e(n["Number"]), _e(n["Name"]), _e(n["Unit"]),
_fmt_qty(n["Quantity"]), _fmt_money(n["Price"]), _fmt_money(n["Total"])))
return "".join(out)
def bill_html(b):
return ("<tr%s><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class='n'>%s</td>"
"<td class='n'>%s</td><td class='n'>%s</td><td>%s</td></tr>%s"
% ((" class='tdel'" if b.get("x_tdel") else ""),
_e(b.get("Number")), _e(b.get("Name")), _e(b.get("Attr")), _e(b.get("Unit")),
_fmt_qty(b.get("Quantity")), _fmt_money(b.get("Price")),
_fmt_money(b_total(b)), _e(b.get("x_remark")), norm_rows_html(b["id"])))
def table(head_html, rows_html):
if not rows_html:
return "<p class='empty'>没有数据</p>"
return "<table class='grid'><thead><tr>%s</tr></thead><tbody>%s</tbody></table>" % (
head_html, rows_html)
head = ("<th>编码</th><th>名称</th><th>项目特征</th><th>单位</th><th>工程数量</th>"
"<th>单价</th><th>合价</th><th>审核备注</th>")
# 分部分项:分部树递归(子分部/清单挂上级名下,同 231 补记十树口径)
ds = [d for d in ds_all if d.get("Kind") != "prelim"]
ids = {d["id"] for d in ds}
kids, roots = {}, []
for d in ds:
p = d.get("parent_id")
(kids.setdefault(p, []).append(d)) if p in ids else roots.append(d)
by_div = {}
for b in bills:
if b.get("Kind") == "prelim":
continue
by_div.setdefault(b.get("div_id"), []).append(b)
def walk(d, out):
out.append("<tr class='div'><td></td><td colspan='7'>▣ %s</td></tr>" % _e(d.get("Name")))
for b in by_div.get(d["id"], []):
out.append(bill_html(b))
for sub in kids.get(d["id"], []):
walk(sub, out)
fb_rows = []
for d in roots:
walk(d, fb_rows)
for b in by_div.get(None, []): # 无分部挂靠的清单:落首个一级分部名下兜底(同 Excel 通道)
if roots:
fb_rows.insert(0, bill_html(b))
else:
fb_rows.append(bill_html(b))
# 措施项目:清单平铺(带上级分部名列省略,界面措施区同数据)
prelim_rows = [bill_html(b) for b in bills if b.get("Kind") == "prelim"]
return (table(head, "".join(fb_rows)), table(head, "".join(prelim_rows)))
_CSS = """
body{font-family:"Microsoft YaHei",Arial,sans-serif;margin:24px;color:#243b53;background:#f7f9fc}
h1{font-size:22px;border-bottom:2px solid #1f66d1;padding-bottom:8px}
h2{font-size:18px;margin:28px 0 10px;color:#1f66d1}
h3{font-size:15px;margin:20px 0 8px;background:#eaf1fb;padding:6px 10px;border-left:4px solid #1f66d1}
h4{font-size:13px;margin:14px 0 6px;color:#5b6b80}
table.grid{border-collapse:collapse;width:100%;font-size:12px;background:#fff}
table.grid th,table.grid td{border:1px solid #c9d6e8;padding:4px 7px;text-align:left;vertical-align:top}
table.grid th{background:#eaf1fb;color:#243b53;white-space:nowrap}
td.n,th.n{text-align:right;white-space:nowrap}
tr.div td{background:#f2f6fc;font-weight:600}
tr.tdel td{text-decoration:line-through;color:#98a6b8;background:#fafbfc}
td.ind{padding-left:22px;color:#5b6b80}
p.empty{color:#98a6b8;font-size:12px;margin:6px 0}
.meta{color:#8a97a8;font-size:12px;margin:4px 0 18px}
.toc li{margin:2px 0;font-size:13px}
"""
def export(sc, sid):
"""HTML 导出入口:返回 (字节, 文件名, 错误)。"""
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
if not srow:
return None, None, "会话不存在"
proj = (srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程"
secs, uws = _tree_order(sc, sid)
if not uws:
return None, None, "本工程还没有单位工程,无数据可导出"
secs_by_id = {r["id"]: r for r in secs}
out = ["<!DOCTYPE html><html lang='zh-CN'><head><meta charset='utf-8'>",
"<title>%s-审核版</title><style>%s</style></head><body>" % (_e(proj), _CSS)]
out.append("<h1>%s <span style='font-size:13px;color:#8a97a8'>(审核版 HTML 导出)</span></h1>" % _e(proj))
# 目录树概览
out.append("<h2>目录树</h2><ul class='toc'>")
cur_sec = None
for i, u in enumerate(uws):
s = secs_by_id.get(u["section_id"])
if s is not None and s["id"] != cur_sec:
cur_sec = s["id"]
out.append("<li><b>%s %s</b></li><ul>" % (_e(s["Number"]), _e(s["Name"])))
out.append("<li>%s %s <span class='meta'>合价 %s</span></li>"
% (_e(u["Number"]), _e(u["Name"]), _fmt_money(u["Total"])))
nxt = uws[i + 1] if i + 1 < len(uws) else None
if s is not None and (nxt is None or nxt["section_id"] != cur_sec):
out.append("</ul>")
out.append("</ul>")
# 项目级:汇总分析 + 工料机汇总(界面原数据卡同数据)
out.append("<h2>项目汇总分析</h2>")
out.append(_proj_summary_table(sc, sid))
out.append("<h2>项目级工料机汇总</h2>")
out.append(_proj_lme_table(sc, sid))
# 单位工程明细
for u in uws:
out.append("<h3>%s %s <span style='font-weight:400'>合价 %s</span></h3>"
% (_e(u["Number"]), _e(u["Name"]), _fmt_money(u["Total"])))
fb, prelim = _bills_tables(sc, u["id"])
out.append("<h4>分部分项</h4>")
out.append(fb)
out.append("<h4>措施项目</h4>")
out.append(prelim)
out.append("<h4>单位级工料机汇总</h4>")
out.append(_uw_lme_table(sc, sid, u["id"]))
out.append("<p class='meta'>导出时间:%s 数据与工作台显示同源(含审核备注)</p>" %
__import__("datetime").datetime.now().strftime("%Y-%m-%d %H:%M"))
out.append("</body></html>")
return "".join(out).encode("utf-8"), proj + "-审核版.html", None

File diff suppressed because it is too large Load Diff

View File

@@ -136,7 +136,8 @@ def build_plan(sc, sid):
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,)):
res_by_norm.setdefault(r["norm_id"], []).append((r["res_code"], r["qty"]))
res_by_norm.setdefault(r["norm_id"], []).append(
(r["res_code"], r["qty"], r["express"]))
for bill_id, ns in norms_by_bill.items():
for n in ns:
n["res"] = res_by_norm.get(n["id"], [])

View File

@@ -27,16 +27,23 @@ REGION = ("广东省", "珠海市", "香洲区")
# 改过滤规则、改层级记账方式、修了会导致旧数据错/缺的 bug),就把号往上加一位。
# 只改界面 / 只改查询,不动入库结构 —— 不用改号,否则会白白提示全库重导。
# 格式建议 YYYY.MM.DD-N(同一天多次改口径就 +1)。
PARSER_VER = "2026.11.02-1" # 2026.11.02-1:lme_uw 尾部追加 x_flags(文字/标志属性 JSON 全采)——「骨架不能创造数据」原则落地(决策 259,老批次需重导/升级才带 flags)
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)
# LME_SUM 行的文字/标志属性集(2026-11-02 主人定「原文件有按原文件导,没有则不导出」):
# 数值属性(量/价/合价)另有专列,不在此列;Remark 属数据性质备注,一并按原文件采。
# 2026-11-03 主人定补:ProviderBase/Weight 同口径(按源数据、卡槽决定输出)。
_LME_SUM_FLAGS = ("LossRate", "Class", "Concrete", "ExtKind", "AddiKind", "MainMaterial",
"ProvisionalMaterial", "Provider", "PriceSource", "Delivery", "Location",
"ProducingArea", "Supplier", "Character", "Remark")
"ProvisionalMaterial", "Provider", "ProviderBase", "Weight", "PriceSource",
"Delivery", "Location", "ProducingArea", "Supplier", "Character", "Remark")
# 2026.10.10-1:clean_attr 剥号加小数点护栏(x_attr_norm 口径变,老批次需重导)
# 2026.10.08-1:清单节点开始采集源文件备注 Remark(老批次需重导才有)
# 2026-11-03 主人定「所有值来自数据库,骨架只管导出格式/是否自增」:
# 清单/定额下这些**结构固定子块**(单价计算行、管理费费率、费用构成、表达式行)的值
# 随导入原样入库(x_side JSON,文档序),导出按骨架列闸门回填,行数按库。
_SIDE_TAGS = ("SummaryOfBasicCost", "ExpressElement", "ManageFees", "UnitPriceCalculationOfItem")
# ---------- 归一化 ----------
def norm(s):
s = (s or "").strip()
@@ -166,6 +173,68 @@ def _encode_attr_newlines(txt):
return "".join(out)
def _side_tree(el):
"""元素 → {tag, attrs(原值), kids}(导出按骨架列闸门重建)。"""
node = {"tag": el.tag, "attrs": {k: v for k, v in el.attrib.items()}, "kids": []}
for c in el:
if isinstance(c.tag, str):
node["kids"].append(_side_tree(c))
return node
def _capture_unit_side(txt, out):
"""单位工程里**非数据层**的结构整棵采集(带值):AttrInfo/AddiInfo/SummaryOfCost(含 AddiCost)/
UnitWorksSummary/Sundry/Tax/ProvisionalMaterialEquipment 等。
骨架里这些层标注为「自增块/自增行」,导出按这份数据重建(行数=数据行数)。"""
try:
r = ET.fromstring(txt)
except Exception:
return
for u in r.iter("UnitWorks"):
if not (u.attrib.get("Name") or "").strip():
continue
idx = out.get("cur_uw", -1)
if idx < 0:
return
out.setdefault("uw_side", {})[idx] = [
_side_tree(c) for c in u
if isinstance(c.tag, str)
and c.tag not in ("DivisionalAndElementalWorks", "DivisionalWorks",
"Preliminaries", "WorkElement", "Norm",
"LabourMaterialsEquipmentsMachinesElement",
"LabourMaterialsEquipmentsMachinesSummary")]
return
def _side_tree_filtered(el, skip):
"""同 _side_tree,但递归跳过数据层标签(项目级:SectionalWorks/UnitWorks/清单定额等)。"""
node = {"tag": el.tag, "attrs": {k: v for k, v in el.attrib.items()}, "kids": []}
for c in el:
if isinstance(c.tag, str) and c.tag not in skip:
node["kids"].append(_side_tree_filtered(c, skip))
return node
_PROJ_SKIP = {"SectionalWorks", "UnitWorks", "DivisionalAndElementalWorks",
"DivisionalWorks", "WorkElement", "Norm",
"LabourMaterialsEquipmentsMachinesElement",
"LabourMaterialsEquipmentsMachinesSummary"}
def _capture_proj_side(root):
"""项目级非数据层整棵采集(带值):根属性 / SummaryOfCost(项目级与单项级两处)/
ProjectInstallationWorkCostSummary / Tax / Sundry / ProvisionalMaterialEquipment…
每项记绝对路径(标签链),导出按路径对位重建。数据层(单项工程/单位/清单/定额)不入。"""
recs = [{"path": [], "node": {"tag": root.tag,
"attrs": {k: v for k, v in root.attrib.items()}, "kids": []}}]
for c in root:
if not isinstance(c.tag, str) or c.tag in _PROJ_SKIP:
continue
recs.append({"path": [root.tag, c.tag],
"node": _side_tree_filtered(c, _PROJ_SKIP)})
return recs
def parse_std(path, out):
out.setdefault("lme_res", {}) # 机械台班 / 配合比的**下一级组成**:编码 → [(子编码, 含量)]
z = zipfile.ZipFile(path)
@@ -183,6 +252,8 @@ def parse_std(path, out):
out["bulid_unit"] = r.attrib.get("BulidUnit", "")
out["total"] = proj_total(r) # 2026-09-30:根节点常无 Total,改三级兜底
out["info"] = {k: v for k, v in r.attrib.items() if (v or "").strip() != ""}
# 2026-11-03:项目级非数据层整棵采集(SummaryOfCost 两处/AddiCost/ProjectInstallationWorkCostSummary…)
out["proj_side"] = _capture_proj_side(r)
# 2026-10-07 主人定:项目特征信息**只从 Project.xml 收**(根节点下的 AttrInfoItem /
# AddiInfoItem 编制信息条目)。此前从各单位工程 XML 收——那是同一表单的逐工程拷贝,
# 「项目级」卡片理应取项目级文件。名称去重、最多 60 条(口径不变)。
@@ -300,6 +371,10 @@ def parse_std(path, out):
out["cur_div"] = None
out["div_stack"] = []
out["in_prelim"] = False
# 工程特征树捕获(2026-11-03:单位工程 AttrInfo 整棵入库,导出按数据循环)
out["_attr_depth"] = None
out["_attr_stack"] = []
out["_attr_roots"] = []
# ⚠️ 2026-09-29 修:UnitWorks 是**容器**标签(每个数据 xml 的根元素就是它),
# 它下面所有 WorkElement / Norm 的 end 事件都排在它自己 end 之前。
# 只监听 end 的话,cur_uw 要到整个文件扫完才被赋值 —— 结果是每条清单挂的
@@ -317,6 +392,14 @@ def parse_std(path, out):
# 绝不能拿最后一条清单去接(那才是原来最致命的错挂)。
for event, el in ET.iterparse(io.StringIO(txt), events=("start", "end")):
if event == "start":
out.setdefault("_stack", []).append(el.tag)
if el.tag == "AttrInfo" and out.get("_attr_depth") is None:
out["_attr_depth"] = len(out["_stack"])
elif (isinstance(el.tag, str) and el.tag.endswith("InfoItem")
and out.get("_attr_depth") is not None):
# 单位工程工程特征:AttrInfo 下的 InfoItem 按层级建树(导出按块/行循环)
out.setdefault("_attr_stack", []).append(
(len(out["_stack"]), {"tag": el.tag, "attrs": dict(el.attrib), "kids": []}))
if el.tag == "UnitWorks" and (el.attrib.get("Name") or "").strip():
out["uw"].append((el.attrib.get("Number", ""), el.attrib.get("Name", ""),
f(el.attrib.get("Total"))))
@@ -478,6 +561,20 @@ def parse_std(path, out):
if _n >= 0 and v.strip():
# 主人定(补记十五改):导入什么就是什么,原样整串入库,导出原样回填
out.setdefault("norm_adj", {}).setdefault(_n, []).append(v)
elif tag in _SIDE_TAGS:
# 2026-11-03:结构固定子块的值随导入入库(文档序、属性原样)——导出端按
# 骨架列闸门回填;行数由库决定(库里 8 行就导 8 行,不是骨架样板 1 行)。
_st = out.get("_stack") or []
_par = _st[-2] if len(_st) >= 2 else None
rec = {"tag": tag, "attrs": {k: v for k, v in a.items()}}
if _par == "Norm":
_n = out.get("cur_norm", -1)
if _n >= 0:
out.setdefault("norm_side", {}).setdefault(_n, []).append(rec)
elif _par in ("WorkElement", "UnitWorksPreliminaryWorkElement"):
_b = out.get("cur_bill", -1)
if _b >= 0:
out.setdefault("bill_side", {}).setdefault(_b, []).append(rec)
elif tag == "SummaryOfCost":
# 2026-09-30:单位工程造价构成。同样因为 clear 会清空 attrib,只能在自己的 end 里读。
# 归栈顶那个 UnitWorks(嵌套时内层优先),且每个单位工程只认它的第一个 SummaryOfCost。
@@ -541,7 +638,22 @@ def parse_std(path, out):
json.dumps({k: a.get(k) for k in _LME_SUM_FLAGS if a.get(k) is not None},
ensure_ascii=False) if any(a.get(k) is not None for k in _LME_SUM_FLAGS) else None))
out["cur_lme"] = "" # 出这条汇总:后面的 Element 不再算它的组成
if isinstance(tag, str) and tag.endswith("InfoItem") and out.get("_attr_stack"):
_lvl, _node = out["_attr_stack"].pop()
if out["_attr_stack"]:
out["_attr_stack"][-1][1]["kids"].append(_node)
else:
out.setdefault("_attr_roots", []).append(_node)
if tag == "AttrInfo" and out.get("_attr_depth") is not None:
out.setdefault("uw_attr", {})[out.get("cur_uw", -1)] = out.get("_attr_roots") or []
out["_attr_roots"] = []
out["_attr_stack"] = []
out["_attr_depth"] = None
_st = out.get("_stack")
if _st:
_st.pop()
el.clear()
_capture_unit_side(txt, out)
return "2025标准"
@@ -846,26 +958,26 @@ def _zip_swt_member(z):
def parse_file(path, out):
"""按文件头分派解析器:zip=COS4/.COS;swt/swz=深圳数据交换标准(XML 或压缩包内 XML);
散装 xml 仍拒绝。扩展名 .SWT/.SWZ 不分大小写。"""
"""**按内容分派解析器,扩展名不参与拦截**(2026-11-03 主人定 A 方案):
zip 包内有无 ConstructProject → 有=SWT 族、无=COS 族;裸 XML 根节点 ConstructProject=SWT 族。
同族新后缀(.cos5/.xml/.abc…)零代码可开;不认识的散装 XML 仍明确报错。"""
st = sniff(path)
if st == "zip":
# 2026-10-19:.SWZ/.SWT 若是压缩包,先看里面有没有 ConstructProject;
# 有就按 SWT 解析,没有才回落到 COS4(parse_std)。
if str(path).lower().endswith((".swz", ".swt")):
try:
with zipfile.ZipFile(path) as z:
member = _zip_swt_member(z)
if member:
with z.open(member) as f:
return parse_swt(f, out)
except (zipfile.BadZipFile, OSError):
pass
# 不再看后缀:任何 zip 先找 ConstructProject 成员(SWT 族),没有才按 COS 族解析
try:
with zipfile.ZipFile(path) as z:
member = _zip_swt_member(z)
if member:
with z.open(member) as f:
return parse_swt(f, out)
except (zipfile.BadZipFile, OSError):
pass
return parse_std(path, out)
if st == "swt":
return parse_swt(path, out)
if st == "xml":
raise ValueError("已不再支持 xml 格式,请导出为 COS4(或 .COS)后打开")
raise ValueError("这个 XML 不是已知的计价结构(当前支持:COS/COS4 压缩包、SWT/SWZ 数据交换标准;"
"同族新后缀可直接打开,扩展名不拦)")
if st == "encrypted":
raise ValueError("这是加密件,无法解析")
raise ValueError("文件头无法识别,不是计价文件")
@@ -913,19 +1025,22 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
info_json = json.dumps(_info, ensure_ascii=False) if _info else None
_feat = out.get("feat") or []
feat_json = json.dumps([{"n": n, "v": v} for n, v in _feat], ensure_ascii=False) if _feat else None
_pside = out.get("proj_side") or []
side_json = json.dumps(_pside, ensure_ascii=False) if _pside else None
if bid is None:
cur.execute("""INSERT INTO batches(kind, Name, FileKind, BulidUnit, x_province, x_city, x_district,
x_period_start_m, x_period_end_m, x_enabled, x_total, x_rows_bill, x_rows_lme, x_imported_at,
x_src_hash, x_note, x_parser_ver, x_info, x_feat) VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?)""",
x_src_hash, x_note, x_parser_ver, x_info, x_feat, x_side)
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?,?)""",
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"], 0, 0,
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json))
time.strftime("%Y-%m-%d %H:%M:%S"), sha, "", PARSER_VER, info_json, feat_json, side_json))
bid = cur.lastrowid
else:
cur.execute("""UPDATE batches SET kind=?, Name=?, FileKind=?, BulidUnit=?, x_province=?, x_city=?,
x_district=?, x_period_start_m=?, x_period_end_m=?, x_total=?, x_rows_bill=0, x_rows_lme=0,
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=? WHERE id=?""",
x_imported_at=?, x_parser_ver=?, x_info=?, x_feat=?, x_side=? WHERE id=?""",
(kind, name, fk, bu, prov, city, dist, p_from, p_to, out["total"],
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, bid))
time.strftime("%Y-%m-%d %H:%M:%S"), PARSER_VER, info_json, feat_json, side_json, bid))
if cur.rowcount != 1:
raise RuntimeError("原位升级失败:批次 #%s 不存在" % bid)
@@ -959,14 +1074,16 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
_um = (out.get("uw_meta") or {}).get(i) or (None, None)
cur.execute("""INSERT INTO unit_works(batch_id, section_id, Number, Name, Specialty, Total,
Construction, DivisionalAndElementalWorks, Preliminaries,
CostForHSE, SundryCosts, Tax, Code, Unit, Scale, ztotal)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
CostForHSE, SundryCosts, Tax, Code, Unit, Scale, ztotal, x_attr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
total, c.get("Construction"),
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
_z if _z is not None else total))
_z if _z is not None else total,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("uw_side") or {}).get(i))))
uw_ids.append(cur.lastrowid)
# 决策 244:单位工程「汇总分析」/「其他项目」两卡源数据原样入库(老格式无这些键 → 空转)
@@ -1038,10 +1155,12 @@ 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)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq, x_side)
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))
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))))
n_bill += 1
bill_ids.append(cur.lastrowid)
seen_bill.add(h)
@@ -1057,11 +1176,13 @@ def save(con, kind, out, fn, sha, mtime, meta=None, bid=None):
bqty = out["bills"][idx][4] if 0 <= idx < len(out["bills"]) else None
coef = (round(qty * unit_prefix(unit) / bqty, 6)
if (qty is not None and bqty not in (None, 0)) else None)
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust)
VALUES(?,?,?,?,?,?,?,?,?)""",
cur.execute("""INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side)
VALUES(?,?,?,?,?,?,?,?,?,?)""",
(bid2, num, name, unit, qty, price, total, coef,
(lambda vals: json.dumps(vals, ensure_ascii=False) if vals else None)(
out.get("norm_adj", {}).get(norm_idx, []))))
out.get("norm_adj", {}).get(norm_idx, [])),
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("norm_side") or {}).get(norm_idx))))
norm_ids.append(cur.lastrowid)
# 定额消耗工料机(对应 s_norm_res)。
@@ -1261,3 +1382,4 @@ def main():
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,128 @@
# -*- coding: utf-8 -*-
""".yhy 专有格式导入(2026-11-03 主人定):**id 整体平移法**——
每表全部 id 统一加 offset(offset=库内该表当前 max(id)+1−导出件最小 id),
父 id/平面 id 引用按被引用表的同款 offset 一并平移,数据行原样保真(含全部 x_* 状态列)。
引用映射(与 export_yhy 的导出面一致;@SID=换成新会话 id):
s_sections.id
s_unit_works.section_id → s_sections.id
s_divides.uw_id → s_unit_works.id;s_divides.parent_id → s_divides.id(自引用)
s_bills.uw_id → s_unit_works.id;s_bills.div_id → s_divides.id
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 不在导出面(导入天然无关)。
sessions 行=新会话:name/期次/地区/建设单位/单价类型用弹框传入覆盖(「名称等一切按弹框」,
2026-11-03 主人定),其余列(x_info/x_feat/src_name/x_manual 等)原样保真;x_batch_id 跨库
引用置空。同名工程拒绝(决策 242)。导入不 commit——事务由调用方提交/回滚(api_server 模式)。"""
import json
import zipfile
from datetime import datetime
# (表名, {引用列: 被引用表});顺序=依赖序(被引用表先插)。
_TABLES = [
("s_sections", {"session_id": "@SID"}),
("s_unit_works", {"session_id": "@SID", "section_id": "s_sections"}),
("s_divides", {"session_id": "@SID", "uw_id": "s_unit_works", "parent_id": "s_divides"}),
("s_bills", {"session_id": "@SID", "uw_id": "s_unit_works", "div_id": "s_divides"}),
("s_norms", {"bill_id": "s_bills", "x_src_norm_id": "s_norms"}),
("s_norm_res", {"norm_id": "s_norms"}),
("s_lme_lib", {"session_id": "@SID"}),
("s_lme_proj", {"session_id": "@SID"}),
("s_lme_res", {"session_id": "@SID"}),
("s_lme_uw", {"session_id": "@SID", "uw_id": "s_unit_works"}),
("s_lmes", {"session_id": "@SID"}),
("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"}),
]
def _read_zip(zip_path):
z = zipfile.ZipFile(zip_path)
man = json.loads(z.read("manifest.json").decode("utf-8"))
if man.get("magic") != "YHY":
raise ValueError("这不是本软件导出的 .yhy 工程包")
sessions = json.loads(z.read("sessions.json").decode("utf-8"))
rows = {}
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
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)
except (zipfile.BadZipFile, KeyError, ValueError) as e:
return {"ok": False, "msg": str(e)}
if not sess_rows:
return {"ok": False, "msg": "工程包里没有会话数据"}
src = sess_rows[0]
new_name = (name or "").strip() or src.get("name") or "工程"
if con.execute("SELECT 1 FROM sessions WHERE name=?", (new_name,)).fetchone():
return {"ok": False, "msg": "同名工程已存在:%s(请换个名称再导入)" % new_name}
new_sid = con.execute("SELECT COALESCE(MAX(id),0)+1 FROM sessions").fetchone()[0]
# 每表 offset=库内当前 max(id)+1−导出件最小 id(空库导入时 offset=0,id 原样)
offsets = {}
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]
offsets[t] = cur + 1 - min(ids)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# ① sessions 新行(弹框字段覆盖)
cols = [c[1] for c in con.execute("PRAGMA table_info('sessions')")]
srow = dict(src)
srow["id"] = new_sid
srow["name"] = new_name
srow["imported_at"] = now
srow["x_batch_id"] = None # 跨库批次引用置空
for k in ("period_from", "period_to", "province", "city", "district",
"bulid_unit", "file_kind"):
if k in cols and ov.get(k) not in (None, ""):
srow[k] = ov[k]
if "base_period_m" in cols and ov.get("period_from") is not None:
srow["base_period_m"] = ov["period_from"]
use = [c for c in cols if c in srow]
con.execute("INSERT INTO sessions(%s) VALUES(%s)" % (",".join(use), ",".join("?" * len(use))),
[_json_safe(srow[c]) for c in use])
# ② 各数据表(id 平移+引用平移+换 sid)
stat = {}
for t, refs in _TABLES:
data = rows.get(t) or []
if not data:
continue
off = offsets.get(t, 0)
tcols = [c[1] for c in con.execute("PRAGMA table_info('%s')" % t)]
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:
vals = []
for c in use:
v = r.get(c)
if c == "id":
v = (v or 0) + off
elif c == "session_id":
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)
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)}
def _json_safe(v):
if isinstance(v, bool):
return int(v)
return v

View File

@@ -165,7 +165,7 @@ def template_bytes():
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1):
ws1.column_dimensions[get_column_letter(i)].width = w
_head(ws1, h1)
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
for row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
@@ -462,7 +462,7 @@ def template_project_bytes():
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9], 1):
ws1.column_dimensions[get_column_letter(i)].width = w
_head(ws1, h1)
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
for row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
@@ -862,8 +862,8 @@ def save_tree(con, body):
# 分部分项 10 列 / 措施项目 8 列——只带清单、不带定额(主人定);
# 合价=工程量×单价现算;备注=审核备注;导出件可直接回导入(多出的合价/备注列解析端忽略)。
# ---------------------------------------------------------------------------
_FB_HEAD_X = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_CS_HEAD_X = ["名称", "编码", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_FB_HEAD_X = ["序号", "上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
_CS_HEAD_X = ["序号", "名称", "编码", "项目特征", "单位", "工程量", "单价", "合价", "备注"]
def _safe_sheet_name(name):
@@ -938,7 +938,7 @@ def _proj_lme_workbook(sc, sid):
def _unit_workbook(u, divs, bills):
"""单单位工程 xlsx 字节(决策 231 架子:填写说明+分部分项10列+措施8列,合价/备注)。
"""单单位工程 xlsx 字节(2026-11-03 主人定:填写说明去除;分部分项11列+措施9列,首列序号照工作台口径)。
决策 233:自 export_excel_bytes 抽出——整包 zip 与单单位工程导出(export_unit_xlsx)同一产出。"""
def b_total(b):
@@ -963,10 +963,12 @@ def _unit_workbook(u, divs, bills):
continue
by_div.setdefault(b["div_id"], []).append(b)
seq = [0] # 清单行序号跨分部连续、分部行留空(照工作台序号列口径,2026-11-03 主人定)
def walk(d, parent_name, out):
out.append([parent_name, "", "分部", d["Name"] or "", "", "", "", "", "", ""])
out.append(["", parent_name, "", "分部", d["Name"] or "", "", "", "", "", "", ""])
for b in by_div.get(d["id"], []):
out.append([d["Name"] or "", b["Number"] or "", "清单", b["Name"] or "",
seq[0] += 1
out.append([seq[0], d["Name"] or "", b["Number"] or "", "清单", b["Name"] or "",
b["Attr"] or "", b["Unit"] or "", b["Quantity"], b["Price"],
b_total(b), b["x_remark"] or ""])
for sub in kids.get(d["id"], []):
@@ -977,32 +979,22 @@ def _unit_workbook(u, divs, bills):
walk(d, "单位工程", out)
for b in by_div.get(None, []): # 无分部挂靠的清单:落在首个一级分部名下兜底
pn = roots[0]["Name"] if roots else "单位工程"
out.append([pn, b["Number"] or "", "清单", b["Name"] or "", b["Attr"] or "",
seq[0] += 1
out.append([seq[0], pn, b["Number"] or "", "清单", b["Name"] or "", b["Attr"] or "",
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
b["x_remark"] or ""])
return out
import io as _io
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)
# 2026-11-03 主人定:填写说明 sheet 去除,分部分项为首 sheet
ws1 = wb.active
ws1.title = FB_SHEET
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):
for i, w in enumerate([8, 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)
@@ -1010,19 +1002,21 @@ def _unit_workbook(u, divs, bills):
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 row in ws1.iter_rows(min_row=2, min_col=6, max_col=6):
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)
_cs_seq = [0]
for b in bills.get(u["id"], []):
if b["Kind"] != "prelim":
continue
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
_cs_seq[0] += 1
ws2.append([_cs_seq[0], 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):
for i, w in enumerate([8, 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)
@@ -1030,7 +1024,7 @@ def _unit_workbook(u, divs, bills):
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 row in ws2.iter_rows(min_row=2, min_col=4, max_col=4):
for cell in row:
cell.alignment = Alignment(wrap_text=True, vertical="top")
bio = _io.BytesIO()

View File

@@ -493,6 +493,13 @@ def connect():
("s_norm_res", ("express TEXT",)),
# 2026-10-18:定额换算调整记录(JSON,采纳携带;决策 106 补记十三)
("s_norms", ("x_adjust TEXT",)),
# 2026-11-03:结构固定子块原样值(单价行/管理费/费用构成/表达式行,JSON 文档序)
("s_bills", ("x_side TEXT",)),
("s_norms", ("x_side TEXT",)),
# 2026-11-03:单位工程工程特征树(AttrInfo 原样,导出按数据循环)
("s_unit_works", ("x_attr TEXT",)),
# 2026-11-03:项目级非数据层结构树
("sessions", ("x_side TEXT",)),
):
for col in cols:
try:
@@ -547,7 +554,7 @@ def open_project(con, files, meta, job, sid=None):
stat = {"bill": 0, "norm": 0, "lme": 0, "uw": 0}
bill_ids = []
ptotal = None # 工程总造价:多文件时取最后一个有值的
pinfo, pfeat = None, None # 项目根节点属性 / 项目特征条目(项目级标签卡用)
pinfo, pfeat, pside = None, None, None # 项目根属性 / 项目特征 / 项目级非数据层结构树
num2sec, sec_built = {}, set() # 2026-09-30:单位工程编号 → 单项工程 id
for path, name in files:
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
@@ -567,6 +574,8 @@ def open_project(con, files, meta, job, sid=None):
pinfo = out["info"] # 项目根节点属性(编号/专业/计价标准/单位…)
if out.get("feat"):
pfeat = out["feat"] # 项目特征条目 [(名称, 值)]
if out.get("proj_side"):
pside = out["proj_side"] # 项目级非数据层结构(SummaryOfCost/AddiCost…)
# 单项工程先入(2026-09-30):记下「单位工程编号 → 单项工程 id」,单位工程靠编号归位。
# 没有单项工程层的格式(如三溪 .COS)这里就是空的,树退化成两层,不硬造。
@@ -597,14 +606,16 @@ def open_project(con, files, meta, job, sid=None):
cur.execute("""INSERT INTO s_unit_works(session_id, section_id, Number, Name,
Specialty, Total, Construction, DivisionalAndElementalWorks,
Preliminaries, CostForHSE, SundryCosts, Tax,
Code, Unit, Scale, ztotal)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
Code, Unit, Scale, ztotal, x_attr)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, num2sec.get(num), num, nm, (out.get("uw_spec") or {}).get(i),
total, c.get("Construction"),
c.get("DivisionalAndElementalWorks"), c.get("Preliminaries"),
c.get("CostForHSE"), c.get("SundryCosts"), c.get("Tax"),
(out.get("uw_code") or {}).get(i), _um[0], _um[1],
_z if _z is not None else total))
_z if _z is not None else total,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("uw_side") or {}).get(i))))
uw_ids.append(cur.lastrowid)
stat["uw"] += 1
@@ -686,12 +697,14 @@ 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)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_price0, x_side)
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=第一次导进来的单价,此后改价/采纳不更新
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))))
# 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义);
# 与 history.db.bills(import_job)同口径,启动迁移重算老数据
bill_ids.append(cur.lastrowid)
@@ -705,10 +718,12 @@ def open_project(con, files, meta, job, sid=None):
for norm_idx, (idx, num, nm, unit, qty, price, total) in enumerate(out["norms"]):
bid = bill_ids[idx0 + idx] if 0 <= idx < len(out["bills"]) else None
vals = adj.get(norm_idx, [])
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust)
VALUES(?,?,?,?,?,?,?,?)""",
cur.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total, x_adjust, x_side)
VALUES(?,?,?,?,?,?,?,?,?)""",
(bid, num, nm, unit, qty, price, total,
json.dumps(vals, ensure_ascii=False) if vals else None))
json.dumps(vals, ensure_ascii=False) if vals else None,
(lambda v: json.dumps(v, ensure_ascii=False) if v is not None else None)(
(out.get("norm_side") or {}).get(norm_idx))))
norm_ids.append(cur.lastrowid)
stat["norm"] += 1
@@ -793,11 +808,12 @@ def open_project(con, files, meta, job, sid=None):
x_ntp0=ntp, x_rate0=taxrate, x_taxp0=taxp
WHERE session_id=?""", (sid,))
# 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔
if ptotal is not None or pinfo or pfeat:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? WHERE id=?",
if ptotal is not None or pinfo or pfeat or pside:
cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=?, x_side=? WHERE id=?",
(ptotal,
json.dumps(pinfo, ensure_ascii=False) if pinfo else None,
json.dumps([{"n": n, "v": v} for n, v in pfeat], ensure_ascii=False) if pfeat else None,
json.dumps(pside, ensure_ascii=False) if pside else None,
sid))
stat["total"] = ptotal
stat["feat"] = len(pfeat or [])
@@ -806,3 +822,4 @@ def open_project(con, files, meta, job, sid=None):
stat["lremark"] = restore_lme_remarks(con, sid) # 工料机采纳备注按 rkey 回填(2026-10-08)
con.commit()
return sid, stat

View File

@@ -0,0 +1,427 @@
# -*- coding: utf-8 -*-
"""格式无关骨架引擎(决策 262,2026-11-03 主人定「引擎写活了,后期还有很多后缀」)。
口径(主人逐条定 + 实件勘察结论):
· **后缀不参与拦截**:能不能用由**内容**判定——zip 内 XML(cos/cos4 型)/ 裸 XML(swt/swz 型)。
后期新后缀(st/uuy…)只要是这两种之一,零代码接入。
· **唯一结构位** = (父路径, 标签, 列集):三者相同即同一结构位,只留 1 个样板;值全清空(卡槽)。
· **子节点取并集**:同一结构位的子节点按身份合并(递归);自嵌套按实件最大深度保留有限层。
· **区域/自增块/自增行**不是三种标签,而是同一套结构位的三种出现形态:
区域=全实件恒 1 次;自增块=容器重复;自增行=自闭合行重复。
· **次数不进骨架**:骨架只给结构+列序,重复次数由数据条数决定(0 条不输出)。
实测(2026-11-03):cos4 9507→131、cos 25581→73、swt 463→38、swz 185→37 个唯一结构位。
"""
import copy
import io
import zipfile
from xml.etree import ElementTree as ET
# ---------------------------------------------------------------------------
# 一、格式族判定(按内容,不按后缀)
# ---------------------------------------------------------------------------
FAMILY_ZIP = "zip" # zip 容器 + 若干 XML 成员(主文件 + 单位工程成员)
FAMILY_RAW = "raw" # 裸 XML 单文件(单位工程内嵌)
def family_of(blob):
"""字节 → FAMILY_ZIP / FAMILY_RAW / None(加密壳、二进制、坏件一律 None)。"""
if not blob:
return None
if blob[:2] == b"PK":
try:
with zipfile.ZipFile(io.BytesIO(blob)) as z:
for nm in z.namelist():
if nm.lower().endswith(".xml"):
try:
ET.fromstring(z.read(nm))
return FAMILY_ZIP
except Exception:
continue
except Exception:
return None
return None
head = blob[:6].lstrip()
if head[:5].lower().startswith(b"<?xml") or head[:1] == b"<":
try:
ET.fromstring(blob)
return FAMILY_RAW
except Exception:
return None
return None
def _decode_bytes(raw):
"""按声明解码,声明缺失/错时退 utf-8、gb18030。返回 (bytes, encoding)。"""
import re
m = re.match(rb'(?:\xef\xbb\xbf|\s)*<\?xml[^>]*encoding="([^"]+)"', raw[:300])
enc = m.group(1).decode("ascii", "ignore") if m else "utf-8"
for e in (enc, "utf-8", "gb18030"):
try:
raw.decode(e)
return raw, e
except Exception:
continue
return raw, "utf-8"
def parse_root(raw):
"""字节 → (根元素, 声明文本)。保留注释节点(原文件有才保留,引擎不造)。"""
import re
blob, _enc = _decode_bytes(raw)
text = blob.decode(_enc, errors="replace")
m = re.match(r"\s*<\?xml[^>]*\?>", text)
decl = m.group(0) if m else '<?xml version="1.0" encoding="utf-8"?>'
body = text[m.end():] if m else text
parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
return ET.fromstring(body, parser=parser), decl
# ---------------------------------------------------------------------------
# 二、唯一结构收敛(本次核心)
# ---------------------------------------------------------------------------
def _key(el):
return (el.tag, tuple(sorted(el.attrib.keys())))
# 骨架只给格式(列集 + 每层是否自增);**所有值来自数据库**,骨架一个值都不带。
# 主人 2026-11-03 定:「骨架只管导出格式及是不是自增行」——单价行/管理费/费用构成
# 这些值全部随导入进库(s_bills/s_norms 的 x_side),导出时有几行出几行。
_DATA_TAGS = set()
_ZERO_RULES = {}
def _copy_fixed(c):
"""(保留占位)固定结构节点深拷贝。"""
return copy.deepcopy(c)
def collapse_into(node, el):
"""把源元素 el 的子结构并入样板 node:同身份合并、子节点递归取并集、值清空。"""
seen = {}
for k in node:
if isinstance(k.tag, str):
seen[_key(k)] = k
for c in el:
if not isinstance(c.tag, str): # 注释:原样保留一次
if not any(isinstance(k.tag, type(c.tag)) and k.text == c.text for k in node):
node.append(c)
continue
key = _key(c)
sub = seen.get(key)
if sub is None:
sub = ET.SubElement(node, c.tag)
for a in c.attrib: # 列序=首次出现序,值=空卡槽
sub.set(a, "")
seen[key] = sub
collapse_into(sub, c)
return node
def collapse(root):
"""整树 → 唯一结构位树(每个结构位只出现一次,值全空)。"""
out = ET.Element(root.tag)
for a in root.attrib:
out.set(a, "")
collapse_into(out, root)
return out
def paths_of(root):
"""→ {路径字符串: 出现次数};路径=根到该元素的标签链('A/B/C')。"""
out = {}
stack = [(root, root.tag)]
while stack:
el, p = stack.pop()
out[p] = out.get(p, 0) + 1
for c in el:
if isinstance(c.tag, str):
stack.append((c, p + "/" + c.tag))
return out
# ---------------------------------------------------------------------------
# 三、结构旁注(sidecar):哪些层是清单/定额/工料机/单位工程
# 判定只看结构(重复次数+嵌套关系),不看标签名——新后缀零配置。
# ---------------------------------------------------------------------------
def _attrs_by_path(roots):
"""→ {路径: 列集}(只取出现过的属性名,不看值)。"""
out = {}
for r in roots:
stack = [(r, r.tag)]
while stack:
el, p = stack.pop()
s = out.setdefault(p, set())
s.update(el.attrib.keys())
for c in el:
if isinstance(c.tag, str):
stack.append((c, p + "/" + c.tag))
return out
def derive_meta(roots, unit_tag=None):
"""多份实件根 → {'v':1,'paths':{path:count},'roles':{...}}。
角色判定只用**结构 + 属性名**(不看标签名、不看后缀),顺序:
①工料机行=重复的自闭合叶行里,属性同时有"数量"和"编号/代码"、次数最多者;
②定额=工料机行的父节点(父是壳也照取——壳在清单层再跳);
③清单=从定额往上最近的非壳容器(壳=只有一个子标签的容器);
④分部=清单上方能重复的容器;⑤单位=根标签里出现最多的那个(zip 族=单位成员根)。
认结构(清单→定额→工料机三层嵌套)的格式适用;数据模型不同的族(如 SWT 工料机是
独立表、不挂在定额下)只认得出部分角色,导出端会回退旧引擎——这是适配器边界。"""
counts = {}
for r in roots:
for p, n in paths_of(r).items():
counts[p] = counts.get(p, 0) + n
attrs = _attrs_by_path(roots)
parent = {p: p.rsplit("/", 1)[0] for p in counts if "/" in p}
has_kid = {p: False for p in counts}
for p in counts:
if p in parent:
has_kid[parent[p]] = True
def kids(p):
return [q for q in counts if parent.get(q) == p]
def is_shell(p):
return len({q.rsplit("/", 1)[-1] for q in kids(p)}) == 1
colset = lambda p: {a.lower() for a in attrs.get(p, ())}
def is_norm_like(p):
"""定额样:有 名称/单位/数量/单价(Price 或 Rate 精确名,不用 NoTaxPrice 这类)。"""
c = colset(p)
return {"name", "unit", "quantity"} <= c and (("price" in c) or ("rate" in c))
# ① 工料机行="定额样"节点的子行(数量+编号),次数最大者;避免把汇总表当定额
rows = [p for p in counts
if counts[p] >= 2 and not has_kid[p]
and "quantity" in colset(p) and ({"number", "code"} & colset(p))
and is_norm_like(parent.get(p, ""))]
lme = max(rows, key=lambda p: counts[p]) if rows else None
# ② 定额 = 工料机行父节点
norm = parent.get(lme) if lme else None
# ③ 清单 = 从定额往上最近的非壳容器
bill = None
p = parent.get(norm) if norm else None
while p:
if has_kid[p] and not is_shell(p):
bill = p
break
p = parent.get(p)
# ④ 分部 = 清单上方能重复的容器
div = None
p = parent.get(bill) if bill else None
while p:
if counts.get(p, 0) >= 2 and not is_shell(p):
div = p
break
p = parent.get(p)
# ⑤ 单位 = 调用方指定的单位根(zip 族=单位成员根);否则取出现最多的根标签
from collections import Counter
roots_cnt = Counter(r.tag for r in roots)
unit = unit_tag or (roots_cnt.most_common(1)[0][0] if roots_cnt else None)
# 单位级工料机汇总行:单位之下、不在清单/定额链上、重复的自闭合叶行
lme_sum = None
if unit:
sub = [q for q in counts
if q.startswith(unit + "/") and counts[q] >= 2 and not has_kid[q]
and not (norm and q.startswith(norm))]
lme_sum = max(sub, key=lambda q: counts[q]) if sub else None
return {"v": 1, "paths": counts,
"roles": {"unit": unit, "bill": bill, "div": div,
"norm": norm, "lme": lme, "lme_sum": lme_sum}}
# ---------------------------------------------------------------------------
# 四、分层列集指纹与匹配度(字段越像分越高 + 区域越像分越高)
# ---------------------------------------------------------------------------
def layer_cols(roots):
"""多份实件根 → {'v':2,'p':{路径:[列名…]}}(每层列集并集,首见列序)。"""
out = {}
for r in roots:
stack = [(r, r.tag)]
while stack:
el, p = stack.pop()
cols = out.setdefault(p, [])
for a in el.attrib:
if a not in cols:
cols.append(a)
for c in el:
if isinstance(c.tag, str):
stack.append((c, p + "/" + c.tag))
return {"v": 2, "p": out}
def _finger_paths(fp):
"""兼容新旧两种指纹 → {path: set(cols)}。旧= {tag:[...]};新= {'v':2,'p':{path:[...]}}。"""
if not isinstance(fp, dict):
return {}
if fp.get("v") == 2 and isinstance(fp.get("p"), dict):
return {k: set(v) for k, v in fp["p"].items()}
return {k: set(v) for k, v in fp.items() if isinstance(v, (list, tuple, set))}
def _root_path(paths):
for p in paths:
if "/" not in p:
return p, paths[p]
return None, set()
def match_score(src_fp, skel_fp):
"""0~100:字段匹配(同层列集重合,根层权重最高)+ 区域匹配(骨架的结构区域在原件里有没有)。
根标签不同=不同格式族,直接压低到 10 分以下。"""
src = _finger_paths(src_fp)
skel = _finger_paths(skel_fp)
if not src or not skel:
return 0.0
sroot, scols = _root_path(src)
kroot, kcols = _root_path(skel)
if sroot != kroot:
return 10.0 * (len(scols & kcols) / max(1, len(scols | kcols)))
# 字段:逐层 Jaccard,根层×3、二三层×2、其余×1
num = den = 0.0
for p, cols in skel.items():
if p not in src:
continue
depth = p.count("/")
w = 3.0 if depth == 0 else (2.0 if depth <= 2 else 1.0)
num += w * len(cols & src[p]) / max(1, len(cols | src[p]))
den += w
field = (num / den * 100.0) if den else 0.0
# 区域:骨架里出现过的结构位,原件里覆盖多少(只看骨架,不看原件多出来的)
cover = sum(1 for p in skel if p in src) / max(1, len(skel))
return round(field * 0.65 + cover * 100.0 * 0.35, 2)
# ---------------------------------------------------------------------------
# 五、从实件提炼空骨架(主驱动:family 判定,不看后缀)
# ---------------------------------------------------------------------------
def _members(blob):
"""→ [(成员名, 字节)];裸 XML 时 → [('(single)', blob)]。"""
if family_of(blob) == FAMILY_ZIP:
with zipfile.ZipFile(io.BytesIO(blob)) as z:
return [(nm, z.read(nm)) for nm in z.namelist() if nm.lower().endswith(".xml")]
return [("(single)", blob)]
def split_roots(blob):
"""→ (主根列表, 单位根列表, family)。zip:单位根=多数成员根标签;raw:整件即主根。
单位工程判定不靠标签名,靠"同一个根标签在多个成员里重复出现"。"""
fam = family_of(blob)
if fam is None:
return [], [], None
members = _members(blob)
roots = []
for nm, raw in members:
try:
r, _d = parse_root(raw)
except Exception:
continue
roots.append((nm, r))
if fam == FAMILY_RAW:
return [r for _n, r in roots], [], fam
# zip:根标签计数,出现 ≥2 次的当单位成员
from collections import Counter
cnt = Counter(r.tag for _n, r in roots)
unit_tag = None
for t, n in cnt.most_common():
if n >= 2:
unit_tag = t
break
if unit_tag is None and len(roots) > 1:
unit_tag = cnt.most_common()[-1][0]
units = [r for _n, r in roots if r.tag == unit_tag]
mains = [r for _n, r in roots if r.tag != unit_tag]
if not mains:
mains = [roots[0][1]]
units = [r for _n, r in roots[1:]]
return mains, units, fam
def build_blank(blob, ind_unit=" "):
"""实件 → (空骨架单 XML 文本, meta)。meta 给导出用(角色路径)。
zip 族:主文件骨架 + 首条单位索引行内嵌单位骨架(连接展示);
raw 族:整件收敛。两种家族同一个收敛器,零后缀配置。"""
mains, units, fam = split_roots(blob)
if fam is None or not mains:
return None, None
main = collapse(mains[0])
if not units:
roots_for_meta = mains
text = _serialize(main, ind_unit)
return text, derive_meta(roots_for_meta)
unit_best = max(units, key=lambda r: len(list(r.iter())))
unit = collapse(unit_best)
# 连接:主骨架里第一条带 FileName 的索引行 → 换成单位骨架
placed = False
for par in main.iter():
for k in list(par):
if not isinstance(k.tag, str):
continue
if "FileName" in k.attrib:
idx = list(par).index(k)
par.remove(k)
par.insert(idx, unit)
placed = True
break
if placed:
break
if not placed:
# 退化样例(Project.xml 没有单位索引行):单位骨架直接挂主根,导出端仍能按它建成员
main.append(unit)
text = _serialize(main, ind_unit)
meta = derive_meta(mains + [unit_best], unit_tag=unit_best.tag)
# 决策 264:记下被替换掉的**索引行**(导出时按它复制成 N 行),否则项目索引无法还原
meta["index_row"] = {"tag": None, "attrs": []}
for par in collapse(mains[0]).iter():
for k in par:
if isinstance(k.tag, str) and "FileName" in k.attrib:
meta["index_row"] = {"tag": k.tag, "attrs": list(k.attrib.keys())}
break
else:
continue
break
return text, meta
def _ind_unit(root):
"""缩进单位:优先从实件文本锚定(4 空格常见);此处按层给 4 空格,
真实缩进由 refine_blank 传入的件锚定(见 classic_skeleton._blank_ind_unit)。"""
return " "
def serialize(el, depth=0, ind=" ", keep_values=False, first=True, note_fn=None):
"""唯一结构位树 → 文本行(一行一层、叶自闭合、无空行)。
属性值按 XML 规则转义(数据里的 & < > " 会原样出现,不转义整件就坏)。
note_fn(el)→字符串:在开标签后追加 XML 注释(骨架库「空骨架+导出规则标注」用)。"""
pad = "" if first else "\n" + ind * depth
if keep_values:
from xml.sax.saxutils import escape
attrs = "".join(' %s="%s"' % (k, escape(str(v), {'"': "&quot;"}))
for k, v in el.attrib.items())
else:
attrs = "".join(' %s=""' % k for k, _ in el.attrib.items())
kids = [k for k in el if isinstance(k.tag, str)]
note = note_fn(el) if note_fn else ""
note = ("<!-- %s -->" % str(note).replace("--", "-")) if note else ""
out = [pad + "<" + el.tag + attrs]
if not kids:
out[0] += " />" + note
return "".join(out)
out[0] += ">" + note
for k in kids:
out.append(serialize(k, depth + 1, ind, keep_values, first=False, note_fn=note_fn))
out.append("\n" + ind * depth + "</" + el.tag + ">")
return "".join(out)
def _serialize(root, ind=" ", keep_values=False):
decl = '<?xml version="1.0" encoding="utf-8"?>'
return decl + "\n" + serialize(root, 0, ind, keep_values) + "\n"

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()

View File

@@ -31,6 +31,7 @@ CREATE TABLE IF NOT EXISTS batches(
x_publisher TEXT, -- 发布单位(信息价用)
x_info TEXT, -- 项目级「基本信息」卡(原文件项目节点属性 JSON)
x_feat TEXT, -- 项目级「项目特征信息」卡(AttrInfo/AddiInfo JSON)
x_side TEXT, -- 2026-11-03:项目级非数据层整棵(SummaryOfCost/AddiCost/项目汇总…,JSON 路径树)
x_parser_ver TEXT, -- 导入时的解析器版本(import_job.PARSER_VER / price_html.PARSER_VER)
-- 与当前代码版本不一致 = 数据口径过期,后台顶部提示重导
is_mock INTEGER NOT NULL DEFAULT 0 -- 1=自动模拟生成(测试数据);后台「清空模拟数据」按此整批删除
@@ -69,7 +70,8 @@ CREATE TABLE IF NOT EXISTS unit_works(
-- 决策 244(2026-11-01):四张汇总卡——Code=单位工程代号(UnitWorks@Code,如 G130)、
-- Unit=单位(UnitWorks@Unit)、Scale=建设规模(UnitWorks@Scale,逐单位重复存)、
-- ztotal=总造价(UnitWorksSummary 的 ZZJ 行;缺则回退 SummaryOfCost@Total / UnitWorks@Total)
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL,
x_attr TEXT -- 2026-11-03:单位工程「工程特征」树(AttrInfo 结构原样,JSON;导出按数据循环)
);
CREATE INDEX IF NOT EXISTS ix_uw_batch ON unit_works(batch_id);
@@ -232,7 +234,8 @@ CREATE TABLE IF NOT EXISTS bills(
x_adopt INTEGER DEFAULT 0, -- 同上
x_price0 REAL, -- 决策 217:第一次导进来的原始单价(采纳备注旧价取此;改价/采纳覆盖都不动;新增清单恒空→备注显「无」)
x_period_start_m INTEGER, -- 期次起(从批次继承,_ensure_period 回填)
x_period_end_m INTEGER -- 期次止
x_period_end_m INTEGER, -- 期次止
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/费用构成/表达式行)
);
CREATE INDEX IF NOT EXISTS ix_bill_exact_pe ON bills(x_hash_exact);
CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey); -- 字集精确档(决策 27)
@@ -248,7 +251,8 @@ CREATE TABLE IF NOT EXISTS norms(
Unit TEXT,
Quantity REAL, -- 2026-10-01 加(与 s_norms 对齐)
Price REAL,
Total REAL -- 2026-10-01 加
Total REAL, -- 2026-10-01 加
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行)
, x_adjust TEXT -- 换算调整记录(JSON 数组,Value 串;补记十三)
);
CREATE INDEX IF NOT EXISTS ix_norm_bill ON norms(bill_id);

View File

@@ -16,6 +16,7 @@ CREATE TABLE IF NOT EXISTS sessions(
x_total REAL, -- 工程总造价(2026-09-30):原文件口径,不是清单合价求和
x_info TEXT, -- 项目根节点属性 JSON → 项目级「基本信息」卡
x_feat TEXT, -- AttrInfo/AddiInfo 条目 JSON → 项目级「项目特征信息」卡
x_side TEXT, -- 2026-11-03:项目级非数据层整棵(SummaryOfCost/AddiCost/项目汇总…,JSON 路径树;导出按数据重建)
x_batch_id INTEGER, -- 后台批次 id(2026-10-06):同一份文件在后台导入过就能对上,
-- 工作台据此**只读**展示该项目的询价附件。对不上 = 0 / NULL,
-- 界面上就不显示「询价附件」入口(不是错误,是没在后台导入过)
@@ -52,7 +53,8 @@ CREATE TABLE IF NOT EXISTS s_unit_works(
Tax REAL, -- 税金
-- 决策 244(2026-11-01):四张汇总卡——Code=单位工程代号(UnitWorks@Code,如 G130)、
-- Unit=单位、Scale=建设规模、ztotal=总造价(UnitWorksSummary 的 ZZJ 行,缺则回退)
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL
Code TEXT, Unit TEXT, Scale REAL, ztotal REAL,
x_attr TEXT -- 2026-11-03:单位工程「工程特征」树(AttrInfo 结构原样,JSON;导出按数据循环)
);
-- 决策 244(2026-11-01):单位工程「汇总分析」卡 = 源文件 UnitWorksSummary 原样入库
@@ -103,7 +105,8 @@ CREATE TABLE IF NOT EXISTS s_bills(
x_hash_exact TEXT, x_hash_semi TEXT, x_seq INTEGER,
x_new INTEGER DEFAULT 0, -- 本软件新增的清单(唯一可真删;淡绿底)——决策 67
x_tdel INTEGER DEFAULT 0, -- 临时删除(假删,浅灰+横线,可恢复)——决策 67
x_adopt INTEGER DEFAULT 0 -- 数据采纳标记(取消采纳列;决策 68 批次B)
x_adopt INTEGER DEFAULT 0, -- 数据采纳标记(取消采纳列;决策 68 批次B)
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/费用构成/表达式行)
);
CREATE INDEX IF NOT EXISTS ix_sb_sess ON s_bills(session_id);
CREATE INDEX IF NOT EXISTS ix_sb_uw ON s_bills(uw_id); -- 原数据按 uw 取清单(2026-10-07)
@@ -117,7 +120,8 @@ CREATE TABLE IF NOT EXISTS s_norms(
x_adopt INTEGER DEFAULT 0, -- 采纳标记(批次B)——决策 67 预埋
x_src_norm_id INTEGER -- 来源定额 id(取消采纳撤行用,批次B)——决策 67 预埋
,
x_adjust TEXT -- 换算调整记录(JSON;采纳携带,补记十三)
x_adjust TEXT, -- 换算调整记录(JSON;采纳携带,补记十三)
x_side TEXT -- 2026-11-03:结构固定子块原样值(JSON,文档序:单价行/管理费/表达式行)
);
CREATE INDEX IF NOT EXISTS ix_sn_bill ON s_norms(bill_id);

View File

@@ -35,15 +35,19 @@ def _free_port():
# ------------------------------------------------------------------ 造数
def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
proj_lmes=None, uw_lmes=None, zip_ts=None):
proj_lmes=None, uw_lmes=None, zip_ts=None, uw_lme_attrs=None,
lme_rot=False):
"""构造最小可解析的 .cos4(zip 内 Project.xml + 单位工程 xml)。
bills: [(编码, 名称, 特征, 单位, 工程量, 单价)] —— 分部分项清单(自动配 1 条定额 + 定额消耗)
lmes: [(编码, 名称, 规格, 单位, 不含税价, 含税价)] —— 工料机(会进 lmes 与项目级汇总)
proj_lmes/uw_lmes: 分别覆盖项目级/单位级汇总的行(默认都用 lmes;
决策 108 测试用——造「仅项目工料机有」的场景)
uw_lme_attrs: {编码: ' Class="A" Weight="0"...'} 单位级 LME_SUM 追加的文字/标志属性
(定额单价专题·决策 259 flags 全采链路测试用;值须自带引号、前导空格)
另固定带:1 条措施清单(安全文明施工费)、项目特征 1 条、总造价 1234567.89。
"""
_uw_attr = (uw_lme_attrs or {}).get
lme_proj = "".join(
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s Unit=%s'
' Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s/>'
@@ -62,7 +66,8 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
def _bill_xml(i, b):
num, name, attr, unit, qty, price = b
qty, price = float(qty), float(price)
lme0 = lmes[0][0] if lmes else "000001"
lme0 = ((lmes[i % len(lmes)][0] if lme_rot else lmes[0][0])
if lmes else "000001") # lme_rot=多清单轮转引用不同 LME(各配现算量)
return (
'<WorkElement Number=%s Name=%s Attr=%s Unit=%s Quantity=%s Price=%s Total=%s>'
'<Norm Number="N-%d" Name=%s Unit=%s Quantity=%s Price="80" Total=%s>'
@@ -84,9 +89,9 @@ def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
% ("".join(_bill_xml(i, b) for i, b in enumerate(bills)),
"".join(
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s'
' Unit=%s Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s/>'
' Unit=%s Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s%s/>'
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
quoteattr(it[4]), quoteattr(it[5]))
quoteattr(it[4]), quoteattr(it[5]), _uw_attr(it[0]) or "")
for it in (lmes if uw_lmes is None else uw_lmes))))
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
# zip_ts(决策 243 测试用):同内容不同 zip 时间戳 → 不同 sha256(前后台禁同文件后,

View File

@@ -18,7 +18,7 @@ def _mk_sc():
c = sc.cursor()
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
taxp REAL, x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")
taxp REAL, x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, code TEXT,
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxrate REAL,
taxp REAL, x_adopt_added INTEGER DEFAULT 0, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")

View File

@@ -1,37 +1,268 @@
# -*- coding: utf-8 -*-
"""导出后缀跟随源格式(2026-10-15 主人定「按原格式导出」不写死):
.cos4 / .COS4 / .cos / 未来新后缀(.cos5、任意 .xxx)导出都跟原格式;裸名退 .cos。"""
import os
import sys
"""导出后缀口径(2026-11-03 决策 264 补记:骨架回灌单一通路后重写)。
import api_harness as H
旧引擎 export_cos.export_zip 已拆除;后缀不再由旧引擎从源文件名猜——
①骨架挑选按内容/后缀(classic_skeleton.suffix_of 支持任意后缀);
②导出文件名后缀跟导出格式走(export_v2.out_name)。
"""
import hashlib
import io
import os
import sqlite3
import sys
import uuid
import zipfile
from xml.etree import ElementTree as ET
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
import export_cos as xcos # noqa: E402
import api_harness as H # noqa: E402
import classic_skeleton as cs # noqa: E402
import export_v2 as ev # noqa: E402
from api_harness import get, post, server # noqa: F401,E402 (夹具须经导入注册)
def _src_bytes(tmp_path):
p = H.make_cos4(str(tmp_path / "ext.cos4"), "后缀工程",
[("B001", "清单甲", "1、x", "项", 1, 100)])
with open(p, "rb") as f:
return f.read()
def test_ext_follows_source(tmp_path):
raw = _src_bytes(tmp_path)
def test_suffix_of_any_ext():
cases = {
"工程-招标控制价.cos4": ".cos4",
"工程-招标控制价.COS4": ".COS4",
"工程-招标控制价.cos": ".cos",
"工程-招标控制价.cos5": ".cos5", # 未来新格式:能导入就按原格式出
"工程-招标控制价.abc": ".abc",
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": ".cos", # 裸名退默认
"工程-招标控制价.cos4": "cos4",
"工程-招标控制价.COS4": "cos4",
"工程-招标控制价.cos": "cos",
"工程-招标控制价.COS": "cos",
"工程-招标控制价.swt": "swt",
"工程-招标控制价.abc": "abc", # 未来新格式:能导入就按原格式出
"8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": None,
}
for src_name, want in cases.items():
_bytes, out_name = xcos.export_zip(raw, "后缀工程", src_name, {}, [], [], {},
added_lme_by_uw=None)
assert out_name == "后缀工程-审核版" + want, "%s → %s (期望 %s)" % (src_name, out_name, want)
# 出包可用(zip 可读)
import io
import zipfile
zipfile.ZipFile(io.BytesIO(_bytes)).namelist()
for name, want in cases.items():
assert cs.suffix_of(name) == want, "%s → %s (期望 %s)" % (name, cs.suffix_of(name), want)
def test_out_name_follows_suffix():
assert ev.out_name("后缀工程", "cos4") == "后缀工程-审核版.cos4"
assert ev.out_name("后缀工程", "cos") == "后缀工程-审核版.cos"
assert ev.out_name("", "abc") == "工程-审核版.abc"
def test_blank_package_annotated(tmp_path):
"""骨架库导出「完全空骨架(原格式)+自增/固定标注」(2026-11-03 新增功能):
包内两个成员、值全空、每个结构位带规则注释、XML 可解析。"""
src = H.make_cos4(str(tmp_path / "blank_src.cos4"), "骨架标注工程",
[("B001", "清单甲", "1、x", "m3", 1, 100)],
[("000001", "人工", "", "工日", "1", "1")])
# 给夹具补一条单价计算行(x_side 类固定子块的标注样本)
buf = io.BytesIO()
with zipfile.ZipFile(src) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for n in z.namelist():
d = z.read(n)
if n.lower() != "project.xml":
d = d.replace(b"</Norm>", b'<UnitPriceCalculationOfItem Code="RGF" Name="" Total=""/></Norm>', 1)
zo.writestr(n, d)
src2 = tmp_path / "blank_src2.cos4"
src2.write_bytes(buf.getvalue())
con = sqlite3.connect(str(tmp_path / "h.db"))
con.row_factory = sqlite3.Row
sig = cs.seed_frame(con, str(src2), "标注骨架")
assert sig
data, fn, err = ev.build_blank_package(con, sig)
con.close()
assert err is None and fn.endswith(".cos4") and data[:2] == b"PK"
z = zipfile.ZipFile(io.BytesIO(data))
names = [i.filename for i in z.infolist()]
assert "Project.xml" in names and len(names) == 2, names
proj = z.read("Project.xml").decode("utf-8")
unit = z.read([n for n in names if n != "Project.xml"][0]).decode("utf-8")
ET.fromstring(proj)
ET.fromstring(unit)
assert "导出规则:自增区域" in unit
assert "自增区域:至少 1 个" in unit
assert "自增块:按数据块循环" in unit or "自增行:按数据行循环" in unit
assert "固定" not in unit
assert 'Number="B001"' not in unit and 'Number="B001"' not in proj # 完全空(不带数据)
def test_rule_registry():
"""结构位规则:区域下限 1(至少一个空壳)、行/块下限 0;全部自增,不再有「固定」。"""
region = ET.fromstring('<SummaryOfCost Total=""/>')
assert ev.min_count("SummaryOfCost") == 1
assert "自增区域" in ev.rule_note(region) and "固定" not in ev.rule_note(region)
leaf = ET.fromstring('<AddiCost Code=""/>')
assert ev.min_count("AddiCost") == 0
assert "自增行" in ev.rule_note(leaf)
block = ET.fromstring("<AttrInfoItem><AttrInfoItem Name='子'/></AttrInfoItem>")
assert "自增块" in ev.rule_note(block)
at = ET.fromstring('<AttrInfo><AttrInfoItem/></AttrInfo>')
assert "自增区域" in ev.rule_note(at)
# 导出条数 = max(下限, 数据条数)
assert ev.row_count("SummaryOfCost", 0) == 1
assert ev.row_count("AttrInfo", 0) == 1
assert ev.row_count("AddiCost", 0) == 0
assert ev.row_count("AddiCost", 3) == 3
def test_lme_summary_two_shapes():
"""工料机汇总行两种形态(普通行 / 带台班组成的块行)各按自己的样板输出——
不能只用一个样板:否则另一形态的列被丢掉(2026-11-03 主人实测)。"""
import json as _json
host = ET.fromstring(
"<UnitWorks>"
'<LabourMaterialsEquipmentsMachinesSummary Number="" Name="" ExtraA=""/>'
'<LabourMaterialsEquipmentsMachinesSummary Number="" Name="" ExtraB="">'
'<LabourMaterialsEquipmentsMachinesElement Number="" Quantity=""/>'
"</LabourMaterialsEquipmentsMachinesSummary>"
"</UnitWorks>")
rows = [
["A1", "普通行", "", "个", 1, 2, 10, 0, 10, None, None, None, None,
_json.dumps({"ExtraA": "va"})],
["B1", "组合行", "", "台班", 7, 1, 20, 0, 20, None, None, None, None,
_json.dumps({"ExtraB": "vb"})],
]
ev._emit_sums(host, rows, {"B1": [("C1", 1.5)]})
sums = [c for c in host if c.tag == "LabourMaterialsEquipmentsMachinesSummary"]
assert len(sums) == 2
by = {s.get("Number"): s for s in sums}
assert by["A1"].get("ExtraA") == "va" and len(by["A1"]) == 0
assert by["B1"].get("ExtraB") == "vb"
kids = [c for c in by["B1"] if c.tag == "LabourMaterialsEquipmentsMachinesElement"]
assert len(kids) == 1 and kids[0].get("Number") == "C1"
assert kids[0].get("Quantity") == "1.500000"
# 两种形态在序列化上必须分开:普通行自闭合、组合行带闭合标签
import skeleton_engine as _se
txt = _se.serialize(host, 0, " ", keep_values=True)
line_a = next(ln for ln in txt.splitlines() if 'Number="A1"' in ln)
line_b = next(ln for ln in txt.splitlines() if 'Number="B1"' in ln)
assert line_a.rstrip().endswith("/>"), line_a
assert line_b.rstrip().endswith(">"), line_b
assert "</LabourMaterialsEquipmentsMachinesSummary>" in txt
def test_blankpkg_endpoint(server):
"""后台接口:/api/admin/frames/blankpkg/<sig> 直接下载原格式空骨架(带标注)。"""
p = H.make_cos4(str(server["src_dir"] / "blank_ep_raw.cos4"), "标注端点工程",
[("B001", "清单甲", "1、x", "m3", 1, 100)],
[("000001", "人工", "", "工日", "1", "1")])
con = sqlite3.connect(server["db"])
con.row_factory = sqlite3.Row
try:
sig = cs.seed_frame(con, p, "端点骨架")
finally:
con.close()
assert sig
r = server["client"].get("/api/admin/frames/blankpkg/%s" % sig)
assert r.status_code == 200, r.text[:200]
assert r.content[:2] == b"PK"
z = zipfile.ZipFile(io.BytesIO(r.content))
assert "Project.xml" in z.namelist()
for i in z.infolist(): # 成员名必须是 GBK 原始字节(不带 UTF-8 旗标)
assert not (i.flag_bits & 0x800), i.filename
if i.filename != "Project.xml":
assert i.filename.encode("cp437").decode("gbk") == "@_1_单位工程.xml"
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
ET.fromstring(unit)
assert "自增" in unit and "固定" not in unit
assert "导出规则:自增区域" in unit
def test_export_member_names_gbk(server):
"""导出件成员名=GBK 原始字节、与 Project.xml 的 FileName 对得上(2026-11-03 主人实测乱码回归):
易达/广联达原件都是 GBK 条目名且不带 UTF-8 旗标;写成 UTF-8+旗标会被对方按 GBK 解读成乱码。"""
proj = "成员名工程-" + uuid.uuid4().hex[:6]
p = H.make_cos4(str(server["src_dir"] / ("nm_%s_raw.cos4" % proj[-6:])), proj,
[("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
raw = open(p, "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_nm.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
r = server["client"].get("/api/session/export", params={"session_id": sid})
assert r.headers["content-type"].startswith("application/zip"), r.text[:300]
z = zipfile.ZipFile(io.BytesIO(r.content))
proj_xml = z.read("Project.xml").decode("utf-8")
n = 0
for i in z.infolist():
if i.filename == "Project.xml":
continue
n += 1
assert not (i.flag_bits & 0x800), "成员名不能带 UTF-8 旗标:%r" % i.filename
gbk = i.filename.encode("cp437").decode("gbk")
assert gbk.endswith(".xml"), gbk
assert 'FileName="%s"' % gbk in proj_xml, (gbk, proj_xml[:200])
assert n >= 1
def test_unit_side_rows_exported(server):
"""单位工程非数据层(SummaryOfCost/AddiCost、AttrInfo…)也是数据:导入采集、导出按数据行重建。
2026-11-03 主人定「AddiCost 也是自增行,代码务必匹配」回归。"""
proj = "非数据层工程-" + uuid.uuid4().hex[:6]
p = H.make_cos4(str(server["src_dir"] / ("side_%s_raw.cos4" % proj[-6:])), proj,
[("B001", "清单甲", "1、x", "m3", 10, 100)],
[("000001", "人工", "", "工日", "1", "1")])
# 给夹具补:SummaryOfCost 带 2 条 AddiCost;AttrInfo 一组两行;(项目级同款 2 条)
buf = io.BytesIO()
with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for n in z.namelist():
d = z.read(n)
if n.lower() == "project.xml":
t = d.decode("utf-8")
t = t.replace(
'<SummaryOfCost Total="1234567.89"/>',
'<SummaryOfCost Total="1234567.89">'
'<AddiCost Code="P1" Name="项目附加费" Total="88"/>'
'<AddiCost Code="P2" Name="项目税差" Total="12"/></SummaryOfCost>')
d = t.encode("utf-8")
else:
t = d.decode("utf-8")
t = t.replace(
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>',
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000">'
'<AddiCost Code="A1" Name="附加费甲" Total="123"/>'
'<AddiCost Code="A2" Name="附加费乙" Total="45"/></SummaryOfCost>')
t = t.replace(
"</UnitWorks>",
'<AttrInfo><AttrInfoItem Name="组A" Code="G1" Value="" Remark="">'
'<AttrInfoItem Name="子1" Code="C1" Value="" Remark=""/>'
'</AttrInfoItem></AttrInfo></UnitWorks>')
d = t.encode("utf-8")
zo.writestr(n, d)
src = server["src_dir"] / ("side_%s.cos4" % proj[-6:])
src.write_bytes(buf.getvalue())
raw = open(str(src), "rb").read()
hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
"%s_side.cos4" % hashlib.sha256(raw).hexdigest())
with open(hp, "wb") as f:
f.write(raw)
assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"]
audit = {"name": proj, "province": H.META["province"], "city": H.META["city"],
"district": H.META["district"], "period_from": H.PERIOD_202607,
"period_to": H.PERIOD_202607, "file_kind": 1}
sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"]
# 用独立骨架库(只放本件骨架)直接走 export_v2,避免并行用例的骨架库干扰
hpath = str(server["root"] / ("side_hist_%s.db" % proj[-6:]))
hic = sqlite3.connect(hpath)
hic.row_factory = sqlite3.Row
try:
assert cs.seed_frame(hic, hp, "非数据层骨架-" + proj[-6:])
sc = sqlite3.connect(server["sessdb"])
sc.row_factory = sqlite3.Row
try:
data, _fn, err = ev.export_v2(hic, sc, sid, "cos4", src_path=hp)
finally:
sc.close()
finally:
hic.close()
assert err is None, err
z = zipfile.ZipFile(io.BytesIO(data))
unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8")
assert unit.count("<AddiCost") == 2, unit[:800]
assert 'Name="附加费甲"' in unit and 'Name="附加费乙"' in unit
assert 'Code="A2"' in unit and 'Total="45"' in unit
assert 'Name="组A"' in unit and 'Name="子1"' in unit
proj_xml = z.read("Project.xml").decode("utf-8")
assert proj_xml.count("<AddiCost") == 2, proj_xml[:800]
assert 'Name="项目附加费"' in proj_xml and 'Name="项目税差"' in proj_xml
assert 'Code="P2"' in proj_xml and 'Total="12"' in proj_xml

View File

@@ -105,6 +105,7 @@ def test_rollup_end_to_end(server):
assert sm.attrib["DivisionalAndElementalWorks"] == "2000.00" # QDF 现算
assert sm.attrib["Preliminaries"] == "50000.00" # 措施散清单现算(原件值)
dv = root.find("DivisionalWorks")
assert dv.attrib["Total"] == "2000.00" # 分部合价=修改后的清单合价
if "Total" in dv.attrib: # 骨架有该列才回填(列由骨架闸门)
assert dv.attrib["Total"] == "2000.00" # 分部合价=修改后的清单合价
assert root.find(".//WorkElement").attrib["Total"] == "2000.00" # 清单合价 2 位(决策 244 补六)
assert root.find(".//WorkElement").attrib["Quantity"] == "20.000" # 清单数量 3 位
assert root.find(".//WorkElement").attrib["Quantity"] == "20.000000" # 数量 6 位(决策 264 补记五)

View File

@@ -9,6 +9,7 @@
import io
import os
import re
import sqlite3
import sys
import zipfile
import xml.etree.ElementTree as ET
@@ -519,12 +520,36 @@ def test_edited_totals_follow_qty_times_price(server):
def _export_zip(server, sid):
# 决策 264 补记(2026-11-03):原格式导出只走骨架回灌——测试就地从本会话源件提炼一件骨架
# (真实流程=后台上传骨架;这里不依赖本机预置件,保证同口径可跑)。
sc = sqlite3.connect(server["sessdb"])
sc.row_factory = sqlite3.Row
try:
srow = sc.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
finally:
sc.close()
src_name = srow["src_name"] if srow else ""
sfx = xcos_suffix(src_name)
hc = sqlite3.connect(server["db"])
hc.row_factory = sqlite3.Row
try:
src = os.path.join(str(server["root"]), "CostReview", "data", "source_files", src_name)
if os.path.exists(src):
import classic_skeleton as _cs
_cs.seed_frame(hc, src, "测试骨架-" + (sfx or "x"))
finally:
hc.close()
resp = server["client"].get("/api/session/export", params={"session_id": sid})
if not resp.headers["content-type"].startswith("application/zip"):
raise AssertionError("导出失败: " + resp.text[:300])
return zipfile.ZipFile(io.BytesIO(resp.content))
def xcos_suffix(name):
import classic_skeleton as _cs
return _cs.suffix_of(name)
def test_coef_unit_prefix_no_double_count(server):
"""10m 定额:历史 清单1094.68 / 定额109.468 → 系数 GCL 口径 = 1.0,
清单量改 90000000 后导出定额量 = 9000000(=GCL,单位换算只算一次)。"""

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""导入认内容不认后缀(2026-11-03 主人定 A 方案):
同族新后缀(.cos5/.xml/.abc…)零代码可开;zip 内有无 ConstructProject 决定 SWT 族 / COS 族;
散装 XML 只有 SWT 族(根 ConstructProject)能开,其他明确报错。"""
import os
import sys
import zipfile
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core")))
import import_job as job # noqa: E402
def _mkzip(tmp_path, outer, member, body):
p = tmp_path / outer
with zipfile.ZipFile(str(p), "w") as z:
z.writestr(member, body)
return str(p)
def test_zip_cos_family_any_suffix(tmp_path, monkeypatch):
calls = []
monkeypatch.setattr(job, "parse_std", lambda path, out: calls.append("std") or "2025标准")
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
p = _mkzip(tmp_path, "工程.cos5", "Project.xml", "<ConstructionProject Name='x'/>")
job.parse_file(p, {})
assert calls == ["std"], "COS 族 zip:后缀 .cos5 不拦,走 parse_std"
def test_zip_swt_member_any_suffix(tmp_path, monkeypatch):
calls = []
monkeypatch.setattr(job, "parse_std", lambda path, out: calls.append("std") or "2025标准")
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
p = _mkzip(tmp_path, "工程.abc", "标书.xml",
'<?xml version="1.0" encoding="utf-8"?><ConstructProject></ConstructProject>')
job.parse_file(p, {})
assert calls == ["swt"], "zip 内含 ConstructProject:后缀 .abc 也按 SWT 族解析"
def test_raw_xml_swt_any_suffix(tmp_path, monkeypatch):
calls = []
monkeypatch.setattr(job, "parse_swt", lambda f, out: calls.append("swt") or "swt")
p = tmp_path / "工程.xml"
p.write_text('<?xml version="1.0" encoding="utf-8"?><ConstructProject></ConstructProject>',
encoding="utf-8")
job.parse_file(str(p), {})
assert calls == ["swt"], "裸 XML 根 ConstructProject:.xml 后缀也能开"
def test_raw_xml_unknown_rejected(tmp_path):
p = tmp_path / "未知.xml"
p.write_text('<?xml version="1.0" encoding="utf-8"?><Foo><Bar/></Foo>', encoding="utf-8")
try:
job.parse_file(str(p), {})
except ValueError as e:
assert "不是已知的计价结构" in str(e)
else:
raise AssertionError("未知散装 XML 应明确报错")

View File

@@ -24,7 +24,7 @@ def _mk():
c.execute("""CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT,
name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
ntp REAL, taxrate REAL, taxp REAL, x_merged_hide INTEGER DEFAULT 0,
x_remark TEXT, x_ntp0 REAL, x_rate0 REAL, x_taxp0 REAL, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")
x_remark TEXT, x_ntp0 REAL, x_rate0 REAL, x_taxp0 REAL, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, ntp_org REAL, ntp_expr TEXT, taxp_org REAL, taxp_expr TEXT, x_flags TEXT)""")

View File

@@ -40,11 +40,11 @@ def _mk_sess(with_norms=False):
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,

View File

@@ -38,11 +38,11 @@ def _mk_sess():
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,

View File

@@ -41,11 +41,11 @@ def _mk_sess():
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT,
p_code TEXT, res_code TEXT, qty REAL, seq INTEGER, name TEXT)""")
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,

View File

@@ -34,7 +34,7 @@ def _mk_sess():
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT, x_org_ntp0 REAL, x_org_taxp0 REAL)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,

View File

@@ -29,7 +29,7 @@ def _mk_sess():
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
Number TEXT, Name TEXT, Unit TEXT, x_remark TEXT)""")
c.execute("""CREATE TABLE s_remarks(id INTEGER PRIMARY KEY, src_key TEXT, uw_name TEXT,

View File

@@ -36,11 +36,11 @@ def _mk():
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT, qty REAL,
ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_settings(scope TEXT NOT NULL, k TEXT NOT NULL, v TEXT,
PRIMARY KEY(scope,k))""")
c.executemany("INSERT INTO s_bills VALUES(?,?,?,0)", [(1, SID, 101), (2, SID, 102)])

View File

@@ -231,8 +231,8 @@ def test_split_occupied_code_assigns_fresh_codes():
import sqlite3
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
con.execute("CREATE TABLE s_lme_proj(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)")
con.execute("CREATE TABLE s_lme_uw(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)")
con.execute("CREATE TABLE s_lme_proj(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT)")
con.execute("CREATE TABLE s_lme_uw(session_id INT, code TEXT, name TEXT, spec TEXT, unit TEXT, ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)")
con.execute("CREATE TABLE s_settings(scope TEXT, k TEXT, v TEXT, PRIMARY KEY(scope, k))")
for c, nm, sp, un in (("K1", "白布", "", "kg"), ("K1", "铁钉", "50mm", "kg")):
con.execute("INSERT INTO s_lme_proj(session_id, code, name, spec, unit) VALUES(1,?,?,?,?)", (c, nm, sp, un))

View File

@@ -25,7 +25,7 @@ def _mk_sess(with_summary):
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL)""")
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT)""")
c.execute("""CREATE TABLE s_lmes(id INTEGER PRIMARY KEY, session_id INT,
Number TEXT, Name TEXT, Specification TEXT, Unit TEXT, Kind INT,
NoTaxPrice REAL, TaxPrice REAL)""")

View File

@@ -245,17 +245,19 @@ def test_manual_export_xlsx_roundtrip(server):
from openpyxl import load_workbook
wb = load_workbook(io.BytesIO(z.read(xname)))
ws = wb["分部分项"]
assert wb.sheetnames == ["分部分项", "措施项目"], wb.sheetnames # 2026-11-03 主人定:填写说明去除
head = [c.value for c in ws[1]]
assert head == ["上一级名称", "编码", "类型", "名称", "项目特征", "单位",
assert head == ["序号", "上一级名称", "编码", "类型", "名称", "项目特征", "单位",
"工程量", "单价", "合价", "备注"], head
rows = [list(r) for r in ws.iter_rows(min_row=2, values_only=True)]
jia = next(r for r in rows if r[3] == "我方清单甲")
assert jia[2] == "清单" and jia[1] == "041001001001"
assert abs(jia[6] * jia[7] - T_JIA) < 0.01 and abs(jia[8] - T_JIA) < 0.01, "合价没现算"
er = next(r for r in rows if r[3] == "我方二级分部")
assert er[0] == "我方一级分部" and er[2] == "分部"
jia = next(r for r in rows if r[4] == "我方清单甲")
assert jia[3] == "清单" and jia[2] == "041001001001"
assert jia[0] == 2, "清单行序号(树序跨分部连续:乙=1、甲=2,2026-11-03)"
assert abs(jia[7] * jia[8] - T_JIA) < 0.01 and abs(jia[9] - T_JIA) < 0.01, "合价没现算"
er = next(r for r in rows if r[4] == "我方二级分部")
assert er[1] == "我方一级分部" and er[3] == "分部" and er[0] in (None, ""), "分部行序号留空"
ws2 = wb["措施项目"]
assert [c.value for c in ws2[1]] == ["名称", "编码", "项目特征", "单位",
assert [c.value for c in ws2[1]] == ["序号", "名称", "编码", "项目特征", "单位",
"工程量", "单价", "合价", "备注"]
# 回导入自查:多出的合价/备注列解析端忽略,整份通过且行数对上
p = server["src_dir"] / "roundtrip_t.xlsx"
@@ -279,10 +281,10 @@ def test_manual_export_unit_single(server):
assert "filename*=UTF-8''" in cd and unquote(cd.split("filename*=UTF-8''", 1)[1]) == "我方单位工程.xlsx", cd
from openpyxl import load_workbook
wb = load_workbook(io.BytesIO(r.content))
assert wb.sheetnames == ["填写说明", "分部分项", "措施项目"]
assert wb.sheetnames == ["分部分项", "措施项目"] # 2026-11-03 主人定:填写说明去除
rows = [list(x) for x in wb["分部分项"].iter_rows(min_row=2, values_only=True)]
jia = next(x for x in rows if x[3] == "我方清单甲")
assert jia[1] == "041001001001" and abs(jia[8] - T_JIA) < 0.01, "合价没现算"
jia = next(x for x in rows if x[4] == "我方清单甲")
assert jia[2] == "041001001001" and abs(jia[9] - T_JIA) < 0.01, "合价没现算"
# 与 231 整包 zip 里同一单位工程逐格全等(共用 _unit_workbook)
rz = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "xlsx"})
assert rz.status_code == 200

View File

@@ -77,16 +77,14 @@ def test_norm_ntdel_export_omits(server):
r = post(server, "/api/session/norm/op", {"session_id": sid, "op": "unntdel", "norm_id": norm_id})
assert r["ok"] is True
assert _n_norm_in_export(server, sid, b'Number="N-1"') == base # 恢复后又在场
# 采纳定额工程量回填(2026-10-15):导出应带批次原工程量 10.0;规格 2026-10-16 起定额
# 工程量按源文件规律 6 位小数导出(清单仍 3 位)→ 采纳定额处为 Quantity="10.000000"
# 2026-11-03 决策 264 补记五:工程量统一按数据本体 6 位导出(清单/定额同口径)——
# 清单 10 → 10.000000;采纳定额 10 → 10.000000
import io as _io
import zipfile as _zipfile
resp = server["client"].get("/api/session/export", params={"session_id": sid})
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="10.0"') for n in zf.namelist())
assert cnt == 1, cnt # 清单工程量 1 处(原文件原样,源清单未改不重写);原定额已按 9.3 转临删省略
cnt6 = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
assert cnt6 == 1, cnt6 # 采纳定额(带批次原工程量,6 位小数格式)
cnt = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
assert cnt == 2, cnt # 清单 1 处 + 采纳定额 1 处(原定额已按 9.3 转临删省略)
def test_adopt_gcl_default_and_price_overwrite(server):
@@ -109,7 +107,7 @@ def test_adopt_gcl_default_and_price_overwrite(server):
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:300]
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="10.000000"') for n in zf.namelist())
assert cnt == 1, cnt
assert cnt == 2, cnt # 清单 10 + 采纳定额 10(统一 6 位)
# 公式跟清单量走:清单量改 20 → 不改定额、直接导出 → 定额量 20.0
con = sqlite3.connect(server["sessdb"])
con.execute("UPDATE s_bills SET Quantity=20 WHERE id=?", (bill_id,))
@@ -119,17 +117,16 @@ def test_adopt_gcl_default_and_price_overwrite(server):
resp = server["client"].get("/api/session/export", params={"session_id": sid})
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
cnt = sum(zf.read(n).count(b'Quantity="20.000000"') for n in zf.namelist())
assert cnt == 1, cnt
# 决策 244 补六:清单行三值 = 数量 3 位、单价/合价 2 位(XML 精确断言;
# 子串计数会误配 NoTaxPrice / WorkContent 的既有 2 位值)
assert cnt == 2, cnt # 清单 20 + 公式定额跟清单量走 20(统一 6 位)
# 决策 233/264:合价=工程量×单价(导出按现算写穿,不照搬库里不一致的旧 Total)
import xml.etree.ElementTree as _ET
_unit_txt = "".join(zf.read(n).decode("utf-8", "replace") for n in zf.namelist()
if n.lower() != "project.xml")
_root = _ET.fromstring(_unit_txt)
_we = _root.find(".//WorkElement")
assert _we is not None
assert _we.attrib["Quantity"] == "20.000" and _we.attrib["Price"] == "600.00" \
and _we.attrib["Total"] == "6000.00", dict(_we.attrib)
assert _we.attrib["Quantity"] == "20.000000" and _we.attrib["Price"] == "600.00" \
and _we.attrib["Total"] == "12000.00", dict(_we.attrib)
def test_norm_unadopt_hard_delete(server):
@@ -237,9 +234,9 @@ def test_qty_export_follows_source_pattern(server):
assert resp.headers["content-type"].startswith("application/zip"), resp.text[:200]
zf = _zipfile.ZipFile(_io.BytesIO(resp.content))
allx = b"".join(zf.read(n) for n in zf.namelist())
assert allx.count(b'Quantity="1.425000"') == 1, allx.count(b'Quantity="1.425000"') # 采纳定额 6 位
assert allx.count(b'Quantity="7.125"') == 1, allx.count(b'Quantity="7.125"') # 改过的清单 3 位
assert allx.count(b'Quantity="10.0"') == 1, allx.count(b'Quantity="10.0"') # 未改的原定额,原格式保留
assert allx.count(b'Quantity="1.425000"') == 1, allx.count(b'Quantity="1.425000"') # 采纳定额 6 位
assert allx.count(b'Quantity="7.125000"') == 1, allx.count(b'Quantity="7.125000"') # 改过的清单(6 位口径)
assert allx.count(b'Quantity="10.000000"') == 1, allx.count(b'Quantity="10.000000"') # 未改的原定额(6 位口径)
def test_schema_self_describe(server):

View File

@@ -27,11 +27,11 @@ CREATE TABLE s_lme_res(id INTEGER PRIMARY KEY, session_id INT, p_code TEXT,
CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT, code TEXT,
name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL);
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_flags TEXT);
CREATE TABLE s_lme_proj(id INTEGER PRIMARY KEY, session_id INT, code TEXT, name TEXT,
spec TEXT, unit TEXT, kind INT, qty REAL, ntp REAL, taxp REAL,
taxrate REAL, x_merged_hide INT DEFAULT 0,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL);
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL, x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT);
"""

View File

@@ -36,7 +36,7 @@ def _mk():
qty REAL, ntp REAL, taxrate REAL, taxp REAL,
x_adopt_added INTEGER DEFAULT 0, x_merged_hide INTEGER DEFAULT 0, x_remark TEXT,
ntp_org REAL, ntp_expr REAL, taxp_org REAL, taxp_expr REAL,
UNIQUE(session_id, code))""")
x_org_ntp0 REAL, x_org_taxp0 REAL, x_flags TEXT, UNIQUE(session_id, code))""")
c.execute("""CREATE TABLE s_lme_uw(id INTEGER PRIMARY KEY, session_id INT, uw_id INT,
code TEXT, name TEXT, spec TEXT, unit TEXT, kind INT,
qty REAL, ntp REAL, taxrate REAL, taxp REAL, x_adopt_added INTEGER DEFAULT 0,

View File

@@ -0,0 +1,150 @@
# -*- coding: utf-8 -*-
"""定额单价专题(2026-11-03 主人定)端到端回归:三同合并全字段统一 + 原价三级链 + flags 导出。
钉死口径:
① 导入捕获:LME_SUM 文字/标志属性全采进 x_flags(含本次补的 ProviderBase/Weight);
合并弹框聚合行带 x_flags 透传。
② 三同合并=「勾选谁按哪一行的字段」:保留行 kind/x_flags=勾选行;变体行换码后 kind/x_flags
一并统一(唯一值约束:合并后一个项目该三同只输出一条、全字段统一)。
③ 原价三级链:①单位级 → ②项目级 → ③第一次外部采纳价(x_org_*0 专列,采纳落价空则写、
后续采纳不改、手工改价永不写);显示端 dyn 链与导出端 price_updates 同口径。
④ 导出:合并码 Kind/x_flags 经 price_updates 回写(骨架卡槽在才写=骨架过滤);恒空链键
(Remark/PriceSource/Delivery/Location/ProducingArea/Supplier/Character)不回写;
未合并行=源文件原样(按源数据+骨架过滤输出)。
"""
import io
import json
import sqlite3
import zipfile
import pytest
from api_harness import META, PERIOD_202607, fixture_file, get, post, server # noqa: F401
from test_api_p1 import raw_post # 复用二进制直传
CLS_A = (' Class="A" MainMaterial="false" Weight="0" ProviderBase="0" Provider="1"'
' ProvisionalMaterial="false" Remark="原始备注"')
CLS_B = ' Class="B" MainMaterial="true" Weight="1.2"'
# 三同组「柴油 0#」两码:CL01=勾选行(Kind 改成 2 的样子造不出来——make_cos4 固定 Kind=1,
# 用 x_flags/kind 断言以聚合行返回值为准),CL02=变体
UW_LMES = [("CL01", "柴油 0#", "0#", "kg", "6.50", "6.89"),
("CL02", "柴油 0#", "0#", "kg", "7.20", "7.66")]
UW_ATTRS = {"CL01": CLS_A, "CL02": CLS_B}
def _mk(server, name):
"""造件+真实流程导入:upload → admin/import → audit 开会话。返回 sid。"""
from api_harness import make_cos4
fname = name + ".cos4"
fix = server["root"] / "fixsrc"
fix.mkdir(exist_ok=True)
# 两条清单分别消耗 CL01/CL02(_bill_xml 按序轮转)→ 两码都有现算量、可进合并弹框(决策244)
make_cos4(str(fix / fname), name,
[("030507008001", name + "清单项A", "", "台", 3, 500),
("030507008002", name + "清单项B", "", "台", 2, 400)],
lmes=UW_LMES, uw_lmes=UW_LMES, uw_lme_attrs=UW_ATTRS, lme_rot=True)
# 幂等重跑:先删同名旧批次(删批次会清 uploads 副本,必须在 upload 之前删)
import sqlite3 as _s
_con = _s.connect(server["db"])
try:
bids = [x[0] for x in _con.execute(
"SELECT id FROM batches WHERE name=?", (name,)).fetchall()]
finally:
_con.close()
for b in bids:
post(server, "/api/admin/batch/%d/delete" % b, {})
up = raw_post(server, "/api/admin/upload", fname, (fix / fname).read_bytes())
assert up["ok"] is True, up
r = post(server, "/api/audit",
dict(META, path=up["path"], name=name, file_kind=1))
assert r.get("ok") is True, r
return r["session_id"]
def _sess_q(server, sql, args=()):
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
con.row_factory = sqlite3.Row
try:
return con.execute(sql, args).fetchall()
finally:
con.close()
def test_groups_carries_flags_and_merge_unifies_all(server): # noqa: F811
sid = _mk(server, "定额单价专题一")
# ① 弹框分组:聚合行带 x_flags(ProviderBase/Weight 采进来了)
g = get(server, "/api/session/lme/merge/groups", session_id=sid)
grp = next(x for x in g["groups"] if x["name"] == "柴油 0#")
agg = next(x for x in grp["rows"] if x["lvl"] == "uw" and x["code"] == "CL01")
fl = json.loads(agg["x_flags"]) if agg.get("x_flags") else {}
assert fl.get("ProviderBase") == "0" and fl.get("Weight") == "0", fl
assert fl.get("Class") == "A" and fl.get("MainMaterial") == "false", fl
# ② 合并=勾 CL01 → 全字段统一
r = post(server, "/api/session/lme/merge", {"session_id": sid, "groups": [{
"sel": {"uw": 1, "code": "CL01", "uw_ids": agg["uw_ids"], "ntp": 6.50,
"taxrate": 0, "taxp": 6.89, "name": "柴油 0#", "spec": "0#", "unit": "kg",
"kind": agg.get("kind"), "x_flags": agg["x_flags"], "qty": 0},
"hide": [{"uw": 1, "code": "CL02", "uw_ids": agg["uw_ids"]},
{"uw": 1, "code": "CL01", "uw_ids": agg["uw_ids"]}]}]})
assert r["ok"] is True, r
keep = _sess_q(server, "SELECT code,kind,x_flags,ntp,x_merged_hide FROM s_lme_proj "
"WHERE session_id=? AND code='CL01'", (sid,))[0]
assert keep["kind"] is not None and keep["x_flags"], (keep["kind"], keep["x_flags"])
kfl = json.loads(keep["x_flags"])
assert kfl.get("ProviderBase") == "0" and kfl.get("Class") == "A", kfl
gone = _sess_q(server, "SELECT COALESCE(x_merged_hide,0) h FROM s_lme_proj "
"WHERE session_id=? AND code='CL02'", (sid,))
assert all(x["h"] == 1 for x in gone), gone # 变体项目行隐藏
uw01 = _sess_q(server, "SELECT kind,x_flags FROM s_lme_uw WHERE session_id=? AND code='CL01'",
(sid,))
assert len(uw01) == 1, uw01 # 造件单单位:CL02 换码归并进 CL01(变体消失)
assert all(x["kind"] is not None for x in uw01), uw01 # kind 统一为勾选行
assert all(json.loads(x["x_flags"]).get("Class") == "A" for x in uw01), uw01 # flags 统一
# ③ 原价③级:采纳落价写专列;第二次采纳不改;手工改价不写
pid = _sess_q(server, "SELECT id FROM s_lme_proj WHERE session_id=? AND code='CL01'",
(sid,))[0]["id"]
r1 = post(server, "/api/session/lme/price",
{"session_id": sid, "id": pid, "ntp": 7.10, "taxrate": 0, "taxp": 7.10, "adopt": 1})
assert r1["ok"] is True, r1
org1 = _sess_q(server, "SELECT x_org_ntp0, x_org_taxp0 FROM s_lme_proj WHERE id=?", (pid,))[0]
assert org1["x_org_ntp0"] == 7.10 and org1["x_org_taxp0"] == 7.10, org1
post(server, "/api/session/lme/price",
{"session_id": sid, "id": pid, "ntp": 8.80, "taxrate": 0, "taxp": 8.80, "adopt": 1})
org2 = _sess_q(server, "SELECT x_org_ntp0, ntp FROM s_lme_proj WHERE id=?", (pid,))[0]
assert org2["x_org_ntp0"] == 7.10 and org2["ntp"] == 8.80, org2 # 后续采纳不改专列
post(server, "/api/session/lme/price", {"session_id": sid, "id": pid, "ntp": 9.90})
org3 = _sess_q(server, "SELECT x_org_ntp0 FROM s_lme_proj WHERE id=?", (pid,))[0]
assert org3["x_org_ntp0"] == 7.10, org3 # 手工改价不写
# ④ 导出原格式:保留行全字段统一+卡槽回写+恒空链;变体行消失(唯一输出)
resp = server["client"].get("/api/session/export",
params={"session_id": sid, "name": "定额单价专题一",
"province": "广东省", "city": "珠海市",
"period_from": PERIOD_202607})
assert resp.status_code == 200, resp.text[:200]
z = zipfile.ZipFile(io.BytesIO(resp.content))
import re as _re
import sys as _sys
print("ZIP条目:", z.namelist(), file=_sys.stderr)
hits = []
for n in z.namelist():
if n.endswith(".xml") and n != "Project.xml":
txt = z.read(n).decode("utf-8", "replace")
for m in _re.finditer("<LabourMaterialsEquipmentsMachinesSummary[^>]*>", txt):
hits.append(m.group(0))
blob = "\n".join(hits)
print("LME片段数:", len(hits), file=_sys.stderr)
assert "Number=\"CL02\"" not in blob, "变体行应整块消失"
assert "Number=\"CL01\"" in blob
# 取真正的 Summary 行(排除定额下同码 Element 行干扰 find)
summ = [h for h in hits if h.startswith("<LabourMaterialsEquipmentsMachinesSummary")]
assert len(summ) == 1, summ
line = summ[0]
print("SUMMARY行:", line, file=_sys.stderr)
assert "Number=\"CL01\"" in line
assert "Kind=" in line
assert 'Remark=""' in line, "Remark 恒空"
assert "原始备注" not in blob, "flags 里的 Remark 不得回写"
assert 'MainMaterial="' in line, "flags 属性按卡槽输出"
post(server, "/api/session/delete", {"ids": [sid]})

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
"""决策 261 补三(2026-11-03 主人定):.yhy 导入(id 整体平移法)回归——
导出→导入→逐表对拍:行数一致、数据列内容一致(id/引用列按 offset 平移)、id 不撞库、同名拒绝。"""
import io
import json
import os
import sqlite3
import sys
import zipfile
from api_harness import post, server # noqa: F401 (夹具)
from test_manual_export import _create_manual
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
import import_yhy # noqa: E402
_TABS = ["s_sections", "s_unit_works", "s_divides", "s_bills", "s_lme_lib",
"s_lme_proj", "s_lme_res", "s_lme_uw", "s_lmes", "s_proj_summary",
"s_sundry", "s_uw_summary"]
_REF_COLS = {t: (set(refs) - {"session_id"}) for t, refs in import_yhy._TABLES}
def test_yhy_roundtrip(server):
sid1 = _create_manual(server)
c = server["client"]
# ① 导出 .yhy
r = c.get("/api/session/export", params={"session_id": sid1, "fmt": "yhy"})
assert r.status_code == 200
ybytes = r.content
assert zipfile.ZipFile(io.BytesIO(ybytes)).read("manifest.json")
# ② 写入待导入目录并导入(换名)
ypath = server["src_dir"] / "roundtrip_t.yhy"
ypath.write_bytes(ybytes)
j = post(server, "/api/session/yhy/import", {"path": str(ypath), "name": "回导测试工程"})
assert j.get("ok") is True, j
sid2 = j["session_id"]
assert sid2 != sid1 and j["name"] == "回导测试工程"
# ③ 同名拒绝(决策 242)
r2 = c.post("/api/session/yhy/import", json={"path": str(ypath), "name": "回导测试工程"})
j2 = r2.json()
assert (not j2.get("ok")) and ("同名" in j2.get("msg", "")), j2
# ④ 逐表对拍:导出件行 vs 库内新会话行
z = zipfile.ZipFile(io.BytesIO(ybytes))
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
con.row_factory = sqlite3.Row
try:
for t in _TABS:
src = json.loads(z.read("rows/%s.json" % t))
if not src:
continue
off = None
newrows = [dict(x) for x in con.execute(
"SELECT * FROM %s WHERE session_id=?" % t, (sid2,))]
assert len(newrows) == len(src), "%s 行数不一致 %d != %d" % (t, len(newrows), len(src))
# offset=新 id −旧 id,须全表恒定且不与旧会话撞
old_ids = sorted(x["id"] for x in src)
new_ids = sorted(x["id"] for x in newrows)
off = new_ids[0] - old_ids[0]
assert off > 0 or old_ids[0] == 1, t
for x, y in zip(sorted(src, key=lambda r: r["id"]), sorted(newrows, key=lambda r: r["id"])):
assert y["id"] == x["id"] + off, "%s id 平移不恒定" % t
# 数据列(非 id/session_id/引用列)逐列一致;引用列平移正确性由下面⑤子表抽验覆盖
for col, v in x.items():
if col in ("id", "session_id") or col in _REF_COLS.get(t, ()):
continue
assert y.get(col) == v, "%s.%s 不一致:%r != %r" % (t, col, y.get(col), v)
# ⑤ 子表引用链抽验:源有定额时,s_norms.bill_id 必须落在 sid2 的清单 id 集内
src_norms = json.loads(z.read("rows/s_norms.json"))
bids = {x["id"] for x in con.execute("SELECT id FROM s_bills WHERE session_id=?", (sid2,))}
if src_norms:
nids = [x[0] for x in con.execute(
"SELECT n.id FROM s_norms n WHERE n.bill_id IN (SELECT id FROM s_bills WHERE session_id=?)",
(sid2,))]
assert len(nids) == len(src_norms), "定额没平移全 %d != %d" % (len(nids), len(src_norms))
assert bids, "清单没平移过来"
finally:
con.close()
def test_yhy_import_bad_file(server):
"""非 yhy 包 / 坏 zip → 明确报错不落库。"""
p = server["src_dir"] / "bad.yhy"
p.write_bytes(b"not a zip")
r = c = server["client"].post("/api/session/yhy/import",
json={"path": str(p), "name": "坏包测试"})
j = r.json()
assert not j.get("ok"), j

View File

@@ -2539,7 +2539,7 @@ function framesRender(){
const first = r.suffix!==last;
const esc = (r.original_name||'').replace(/'/g,'');
const dl = ` <a href="/api/admin/frames/file/${r.sig}" style="color:#26405e" title="下载骨架原件">下载</a>`
+ ` <a href="/api/admin/frames/blank/${r.sig}" download style="color:#26405e" title="导出该骨架的空精简骨架 XML(不带数据)——浏览器另存为">导出</a>`
+ ` <a href="javascript:framesExportAnnotated('${r.sig}')" style="color:#26405e" title="按原格式导出完全空的骨架(含自增/固定标注)——直接另存为">导出</a>`
+ ` <a href="javascript:framesDel('${r.sig}')" style="color:#c0392b">删</a>`;
if(first){ // 组首行:后缀列 rowspan 合并本组全部行(2026-11-02 主人定)
const st = last!==null ? ` style="${SEP}"` : ''; // 组间横线:非首组才加
@@ -2565,13 +2565,29 @@ function framesRender(){
function framesAdd(){ $('ffile').value=''; $('ffile').click(); }
/* 导出=空骨架(标注):按该骨架原后缀直接另存为(不新增按钮;2026-11-03 主人定) */
function framesExportAnnotated(sig){
const r = (FRAMES||[]).find(x => x.sig === sig) || {};
framesSaveFile(sig, r.original_name || '骨架', '空骨架(标注)', r.suffix || 'cos4');
}
/* 统一另存为(2026-11-03 主人定「导出一律另存为方式」):
showSaveFilePicker 弹系统保存对话框(WebView2/Chrome 同款),用户选路径后写入。
kind='原件' → 取 /api/admin/frames/file/{sig};kind='空精简骨架' → /api/admin/frames/blank/{sig}。 */
async function framesSaveFile(sig, name, kind){
const url = kind==='空精简骨架'
? `/api/admin/frames/blank/${sig}` : `/api/admin/frames/file/${sig}`;
const fn = `${kind}-${name}.xml`;
showSaveFilePicker 弹系统保存对话框,用户选路径后写入。
kind='空骨架(标注)' → /api/admin/frames/blankpkg/{sig}(原格式空骨架+自增/固定标注,后缀跟骨架);
kind='空精简骨架' → /api/admin/frames/blank/{sig}(单 XML);
其余(原件) → /api/admin/frames/file/{sig}。 */
async function framesSaveFile(sig, name, kind, suffix){
let url, fn;
if(kind==='空骨架(标注)'){
url = `/api/admin/frames/blankpkg/${sig}`;
fn = `${name}-空骨架(标注).${suffix||'cos4'}`;
}else if(kind==='空精简骨架'){
url = `/api/admin/frames/blank/${sig}`;
fn = `${kind}-${name}.xml`;
}else{
url = `/api/admin/frames/file/${sig}`;
fn = `${kind}-${name}.${suffix||'bin'}`;
}
try{
const resp = await fetch(url);
if(!resp.ok){ $('fmsg').textContent = `获取失败(HTTP ${resp.status})`; return; }

View File

@@ -634,8 +634,6 @@ body.histdrag{user-select:none}
<div class="mbody" style="display:flex;flex-direction:column;gap:10px;font-size:14px">
<label id="expf_xlsx_lbl" style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="expf_xlsx" onchange="expPick('xlsx')">导出excel</label>
<label id="expf_html_lbl" style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="expf_html" onchange="expPick('html')">导出html</label>
<label id="expf_yhy_lbl" style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="expf_yhy" onchange="expPick('yhy')">导出yhy</label>
<label id="expf_nat_lbl" style="display:flex;align-items:center;gap:8px;cursor:pointer">
@@ -1018,7 +1016,7 @@ window.__exportProgress = function(p){
function exportAsk(){
if(!SID){ $('msg').textContent = '先打开工程再导出'; return; }
if ($('expmask').classList.contains('on')){ $('msg').textContent = '已有导出进行中(可点「后台导出」转后台)'; return; }
['expf_xlsx','expf_html','expf_yhy','expf_nat'].forEach(function(id){
['expf_xlsx','expf_yhy','expf_nat'].forEach(function(id){
document.getElementById(id).checked = false;
});
const manual = !!MANUAL;
@@ -1029,14 +1027,13 @@ function exportAsk(){
document.getElementById('expoptmask').classList.add('on');
}
function expPick(which){ /* 复选框限勾一个:勾谁清别人 */
const ids = {xlsx:'expf_xlsx', html:'expf_html', yhy:'expf_yhy', nat:'expf_nat'};
const ids = {xlsx:'expf_xlsx', yhy:'expf_yhy', nat:'expf_nat'};
for(const k in ids){ if(k !== which) document.getElementById(ids[k]).checked = false; }
}
function expClose(){ document.getElementById('expoptmask').classList.remove('on'); }
function expGo(){
let fmt = '';
if(document.getElementById('expf_xlsx').checked) fmt = 'xlsx';
else if(document.getElementById('expf_html').checked) fmt = 'html';
else if(document.getElementById('expf_yhy').checked) fmt = 'yhy';
else if(document.getElementById('expf_nat').checked && !document.getElementById('expf_nat').disabled) fmt = '';
else { $('msg').textContent = '先勾选一种导出格式'; return; }
@@ -1050,7 +1047,7 @@ async function exportSession(fmt){
fmt=(fmt||'').toLowerCase();
if(MANUAL && fmt===''){ $('msg').textContent = '手工工程没有源格式,不可按原格式导出'; return; }
if ($('expmask').classList.contains('on')){ $('msg').textContent = '已有导出进行中(可点「后台导出」转后台)'; return; }
const FNAME = {xlsx:'Excel', html:'HTML', yhy:'YHY'};
const FNAME = {xlsx:'Excel', yhy:'YHY'};
$('msg').textContent = '正在按' + (FNAME[fmt] || '原格式') + '导出(大工程稍等)…';
try{
const hasBridge = window.pywebview && window.pywebview.api;
@@ -1069,7 +1066,7 @@ async function exportSession(fmt){
if (r && r.cancel){ $('msg').textContent = '已取消导出'; return; }
if (r && r.msg){ $('msg').textContent = '导出失败:' + r.msg; return; }
}
const resp = await fetch('/api/session/export?session_id=' + SID + (fmt?('&fmt='+encodeURIComponent(fmt)):''));
const resp = await fetch('/api/session/export?session_id=' + SID + (fmt?('&fmt='+encodeURIComponent(fmt)):''));
if(!resp.ok){ const j = await resp.json().catch(()=>null); throw new Error((j && j.msg) || ('HTTP ' + resp.status)); }
const cd = resp.headers.get('Content-Disposition') || '';
// 服务端同时发 filename="export.zip"(ASCII 兜底)和 filename*=UTF-8''真名(原工程名-审核版.原后缀)。
@@ -1172,7 +1169,7 @@ function renderMergeTree(){
+ ' data-ntp-org="' + (r.ntp_org == null ? '' : r.ntp_org) + '" data-ntp-expr="' + (r.ntp_expr == null ? '' : r.ntp_expr) + '"'
+ ' data-taxp-org="' + (r.taxp_org == null ? '' : r.taxp_org) + '" data-taxp-expr="' + (r.taxp_expr == null ? '' : r.taxp_expr) + '"'
+ (isUw ? ' data-ucode="' + esc(r.code || '') + '" data-uwids="' + esc((r.uw_ids || []).join(',')) + '"'
+ ' data-kind="' + (r.kind == null ? '' : r.kind) + '"' : '')
+ ' data-kind="' + (r.kind == null ? '' : r.kind) + '" data-xflags="' + esc(r.x_flags == null ? '' : r.x_flags) + '"' : '')
+ (r.def ? ' checked' : '') + ' title="单选:合并后全组按此行归并(数值=行现值;改价在外面·行级改价/原数据)"></td>'
+ '<td class="c">' + no + '</td>'
+ '<td class="c">' + esc(r.code || '—') + '</td>'
@@ -1215,7 +1212,8 @@ async function mergeApply(){
taxp_org: cb.dataset.taxpOrg === '' || cb.dataset.taxpOrg == null ? null : Number(cb.dataset.taxpOrg),
taxp_expr: cb.dataset.taxpExpr === '' || cb.dataset.taxpExpr == null ? null : Number(cb.dataset.taxpExpr),
name: g.name || '', spec: g.spec || '', unit: g.unit || '',
kind: cb.dataset.kind === '' ? null : Number(cb.dataset.kind), qty: 0 };
kind: cb.dataset.kind === '' ? null : Number(cb.dataset.kind),
x_flags: cb.dataset.xflags || null, qty: 0 }; // 定额单价专题:合并全列随勾选行(2026-11-03)
} else {
// 决策 184:弹框全部字段只读(纯勾选归并,数值=行现值;改价在外面·行级改价/原数据)
const d6 = k => cb.dataset[k] === '' || cb.dataset[k] == null ? null : Number(cb.dataset[k]);
@@ -1836,6 +1834,35 @@ async function doOpen(){
if(!$('oprov').value||!$('ocity').value||!$('odist').value){ $('omsg').textContent='请填写:地区(省/市/区)'; return; }
if(!$('obuid').value.trim()){ $('omsg').textContent='请填写:建设单位'; return; }
if(!$('okind').value){ $('omsg').textContent='请选择单价类型'; return; }
// .yhy 工程包(决策 261 补三,2026-11-03 主人定):上传→id 整体平移导入→原地打开新会话;
// 名称/期次/地区/建设单位/单价类型一切按本弹框字段(覆盖包内值)
if(/\.yhy$/i.test(f.name)){
ldShow($('oname').value||f.name,'正在上传工程包…',6);
const upy=await uploadFile('/api/admin/upload', f);
if(!upy.ok){ ldHide(); $('omsg').textContent=upy.msg; return; }
try{
const r=await J('/api/session/yhy/import',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({path:upy.path,name:$('oname').value||f.name,
period_from:pv.f, period_to:pv.t,
province:$('oprov').value,city:$('ocity').value,district:$('odist').value,
bulid_unit:$('obuid').value,file_kind:+$('okind').value})});
if(!r.ok){
$('omsg').textContent=r.msg||'导入失败';
if(/同名/.test(r.msg)) alert(r.msg);
return;
}
SID=r.session_id;
setManualMode(!!r.manual);
try{ localStorage.setItem('wb_sid', SID); }catch(e){}
loadAdopt();
$('sinfo').innerHTML='<b>'+esc($('oname').value||f.name)+'</b>';
$('omask').classList.remove('on');
ldStage(86,'正在加载清单与原数据…');
await loadLme(); await tab('p3');
$('msg').textContent=r.msg;
} finally { ldHide(); }
return;
}
$('omsg').textContent='正在上传并解析…';
// 2026-10-13 主人定:打开工程的全程(上传→解析→首屏)挂进度条,工程名+阶段可见
ldShow($('oname').value||f.name,'正在上传工程文件…',6);
@@ -2719,7 +2746,7 @@ async function adoptLme(i){
let rp=null;
try{
rp=await J('/api/session/lme/price',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({session_id:SID,id:CUR.id,ntp:x.price,taxrate:x.tax,taxp:x.price_tax})});
body:JSON.stringify({session_id:SID,id:CUR.id,ntp:x.price,taxrate:x.tax,taxp:x.price_tax,adopt:1})});
}catch(e){ rp=null; }
if(!rp || !rp.ok){ dlMsg('采纳改价失败:'+(rp&&rp.msg?rp.msg:'服务未响应'),'err'); return; }
if(rp.ntp0!=null) _lmeAnchor={price:rp.ntp0,tax:rp.rate0,taxp:rp.taxp0}; // 决策 219:锚由改价端点带回