fix(manual): 手工导出骨架与导入边界修复,单位按目录自然序排列
- 上传口骨架收集改为空操作,骨架仅经升级入库(决策 231/补记十四) - s_lme_lib 价格快照垫底,修手工会话组成子行价格落 0 - 导出编辑相交消解:删除块与闭合前插入冲突时重映射,防采纳定额丢失/碎 XML - _span 识别自闭合标签,防容器配对失败留孤儿闭合 - 手工导入放开空名/同名/深层级校验 - 单位顺序改按左侧目录树序(单项入库序+组内编号自然序) - 补齐手工导出/导入/MCP 切换相关测试
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""经典整件骨架库(决策 229,2026-10-27 主人定):
|
||||
"""经典整件骨架库(决策 231,2026-10-27 主人定):
|
||||
|
||||
手工工程(无源文件,决策 119/230)没有「本项目原件」可当导出模板——把**经典项目的
|
||||
整件原件**收进骨架库当模板:结构字段相同(同签名)只存一件;每组保留**最全**的代表
|
||||
@@ -16,6 +16,8 @@
|
||||
存储:history.db classic_skel 一组一行(连代表件原件字节存库,不随会话清理)。
|
||||
"""
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@@ -92,40 +94,120 @@ def extract(path):
|
||||
return {"sig": sig, "suffix": suf, "n_shapes": len(shapes), "n_nodes": n_nodes}
|
||||
|
||||
|
||||
def _decode(raw):
|
||||
m = re.match(rb'^\s*<\?xml[^>]*encoding="([^"]*)"', raw[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
try:
|
||||
return raw.decode(enc, errors="replace")
|
||||
except Exception:
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def collect(con, sha, path, name=""):
|
||||
"""上传口统一入口:抽取并按组收代表。返回 'new'/'rep'/'old'/None
|
||||
(新组 / 更全顶掉旧代表 / 平手取最新 / 比代表瘦没动 / 不成组)。
|
||||
⚠️ con=history.db 连接;失败绝不挡上传(调用方兜 try)。"""
|
||||
"""上传口骨架收集=**空操作**(补记十四,2026-10-28 主人定「后期不存骨架了,
|
||||
现有也只有 2 个骨架」):骨架只经升级(seed_frame)入库;上传什么原件都不进
|
||||
classic_skel,库里只保留已升级固定的骨架(COS4骨架G/Y…)。保留函数签名供上传口
|
||||
兼容调用。"""
|
||||
return None
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。
|
||||
补记五:专用骨架件(is_frame=1)优先于实项目件。"""
|
||||
_ensure_table(con)
|
||||
try:
|
||||
con.execute("SELECT is_frame FROM classic_skel LIMIT 1")
|
||||
except Exception:
|
||||
return dict(con.execute(
|
||||
"SELECT * FROM classic_skel WHERE suffix=? ORDER BY n_nodes DESC, "
|
||||
"extracted_at DESC LIMIT 1", (suffix,)).fetchone() or ())
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY is_frame DESC, n_nodes DESC, extracted_at DESC
|
||||
LIMIT 1""", (suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def seed_frame(con, path, name):
|
||||
con.row_factory = sqlite3.Row
|
||||
"""升级添加骨架(补记十二,主人定:骨架只经升级进库、上传口不自动收;命名不带
|
||||
软件名——COS4骨架G/Y、COS骨架G/Y…)。同名骨架=升级替换(重写签名/字节);
|
||||
新名=新增固定骨架。返回 sig;解析失败返回 None。"""
|
||||
info = extract(path)
|
||||
if not info:
|
||||
return None
|
||||
_ensure_table(con)
|
||||
row = con.execute("SELECT n_nodes, extracted_at FROM classic_skel WHERE sig=?",
|
||||
(info["sig"],)).fetchone()
|
||||
if row is not None and info["n_nodes"] < (row["n_nodes"] or 0):
|
||||
return "old" # 不如代表全:不收(主人定:取最全)
|
||||
_cols = {r[1] for r in con.execute("PRAGMA table_info(classic_skel)")}
|
||||
if "is_frame" not in _cols:
|
||||
con.execute("ALTER TABLE classic_skel ADD COLUMN is_frame INTEGER DEFAULT 0")
|
||||
old = con.execute("SELECT sig FROM classic_skel WHERE original_name=?", (name,)).fetchone()
|
||||
if old and old["sig"] != info["sig"]:
|
||||
con.execute("DELETE FROM classic_skel WHERE original_name=?", (name,))
|
||||
with open(path, "rb") as f:
|
||||
blob = f.read()
|
||||
con.execute("""INSERT INTO classic_skel(sig,suffix,rep_sha,original_name,
|
||||
n_shapes,n_nodes,blob,extracted_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
n_shapes,n_nodes,blob,extracted_at,is_frame)
|
||||
VALUES(?,?,?,?,?,?,?,?,1)
|
||||
ON CONFLICT(sig) DO UPDATE SET rep_sha=excluded.rep_sha,
|
||||
original_name=excluded.original_name, n_shapes=excluded.n_shapes,
|
||||
n_nodes=excluded.n_nodes, blob=excluded.blob,
|
||||
extracted_at=excluded.extracted_at""",
|
||||
(info["sig"], info["suffix"], sha, os.path.basename(name or path),
|
||||
extracted_at=excluded.extracted_at, is_frame=1""",
|
||||
(info["sig"], info["suffix"],
|
||||
hashlib.sha256(blob).hexdigest(), name,
|
||||
info["n_shapes"], info["n_nodes"], blob, _now()))
|
||||
con.commit() # sqlite3 隐式事务:不提交=连接关闭即回滚(DDL 却即时生效)
|
||||
return "new" if row is None else "rep"
|
||||
con.commit()
|
||||
return info["sig"]
|
||||
|
||||
|
||||
def rep_for(con, suffix):
|
||||
"""某后缀的当前代表件 → dict;该后缀还没收过 → None(导出侧提示先导入原件)。"""
|
||||
def _shapes_of_blob(blob):
|
||||
"""整包字节 → 结构形态集合(与 extract 同口径:标签+字段名集+有无子级)。"""
|
||||
shapes = set()
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, _n = _shapes_of_bytes(z.read(nm))
|
||||
shapes |= s
|
||||
except Exception:
|
||||
pass
|
||||
return shapes
|
||||
|
||||
|
||||
def pick_frame(con, suffix, src_path=None):
|
||||
"""导出骨架挑选(补记十二,主人定「按字段最近的一个」):
|
||||
①该后缀的固定骨架(is_frame=1,可多件并存)里有源文件可比 → 结构字段集 Jaccard
|
||||
相似度最高者;②无源文件(手工工程)/比不了 → 最近收藏的骨架(extracted_at 最新,
|
||||
即主人最后指定的那件)。没有固定骨架 → 退 rep_for(老行为)。"""
|
||||
_ensure_table(con)
|
||||
row = con.execute("""SELECT * FROM classic_skel WHERE suffix=?
|
||||
ORDER BY n_nodes DESC, extracted_at DESC LIMIT 1""",
|
||||
(suffix,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
try:
|
||||
frames = con.execute("SELECT * FROM classic_skel WHERE suffix=? AND is_frame=1",
|
||||
(suffix,)).fetchall()
|
||||
except Exception:
|
||||
frames = []
|
||||
if not frames:
|
||||
return rep_for(con, suffix)
|
||||
if len(frames) == 1:
|
||||
return dict(frames[0])
|
||||
if src_path and os.path.exists(src_path):
|
||||
try:
|
||||
with zipfile.ZipFile(src_path) as z:
|
||||
src_shapes = set()
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
s, _n = _shapes_of_bytes(z.read(nm))
|
||||
src_shapes |= s
|
||||
except Exception:
|
||||
src_shapes = set()
|
||||
if src_shapes:
|
||||
best, best_j = None, -1.0
|
||||
for f in frames:
|
||||
fsh = _shapes_of_blob(f["blob"])
|
||||
j = len(src_shapes & fsh) / max(1, len(src_shapes | fsh))
|
||||
if j > best_j:
|
||||
best, best_j = f, j
|
||||
if best is not None:
|
||||
return dict(best)
|
||||
return dict(max(frames, key=lambda f: (f["extracted_at"] or "", f["n_nodes"] or 0)))
|
||||
|
||||
|
||||
def stats(con):
|
||||
|
||||
@@ -258,6 +258,16 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
uwp = _uw_price_rows(sc, sid) # 决策 219:主取价源=单位级(每单位每码认第一行)
|
||||
away = _recode_away(sc, sid) # 决策 219:合并换码的旧码不显示
|
||||
uwp = {c: lst for c, lst in uwp.items() if c not in away}
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入)——手工会话没有源文件,
|
||||
# 单位级/项目级三步链全空,组成子行(折旧费/检修费…)价会落 0(2026-10-28 主人实测
|
||||
# 易达映射源里组成子行编制价全空);库快照垫在链条末尾
|
||||
lbm = {}
|
||||
try:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp "
|
||||
"FROM s_lme_lib WHERE session_id=?", (sid,)):
|
||||
lbm[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
except Exception:
|
||||
lbm = {}
|
||||
|
||||
# 决策 219 兜底:单位级行三价缺 → 项目级快照补(主人定「编号或单价实在没有的去项目级取」)
|
||||
for _c, _lst in uwp.items():
|
||||
@@ -272,7 +282,7 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
_r["taxp"] = _p["taxp"]
|
||||
|
||||
def child_px(code, uw=None):
|
||||
"""子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照兜底。"""
|
||||
"""子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照 → s_lme_lib 快照兜底。"""
|
||||
lst = uwp.get(code) or []
|
||||
r = None
|
||||
if uw is not None:
|
||||
@@ -281,9 +291,10 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
r = lst[0]
|
||||
p = pm.get(code) or {}
|
||||
_pk = lambda a, b: (a if a is not None else b)
|
||||
return (_pk(r and r["ntp"], p.get("ntp")),
|
||||
lb = lbm.get(code) or (None, None)
|
||||
return (_pk(_pk(r and r["ntp"], p.get("ntp")), lb[0]),
|
||||
_pk(r and r["taxrate"], p.get("taxrate")),
|
||||
_pk(r and r["taxp"], p.get("taxp")))
|
||||
_pk(_pk(r and r["taxp"], p.get("taxp")), lb[1]))
|
||||
|
||||
def computed_mother(code, uw=None):
|
||||
"""带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。"""
|
||||
@@ -305,6 +316,19 @@ def _dyn_rows(sc, sid, uw_id=None):
|
||||
"""11 列行。r=认下的单位级行(或快照 dict);带子级母行 Σ 现算(除非覆盖)。"""
|
||||
p = pm.get(code) or {}
|
||||
ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp")
|
||||
# s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行
|
||||
# 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空)
|
||||
lb = lbm.get(code)
|
||||
if lb is not None:
|
||||
_nm2, _sp2, _un2, _kd2, _ln, _lt = lb
|
||||
if not (r.get("name") or "") and _nm2:
|
||||
r = dict(r, name=_nm2, spec=(r.get("spec") or _sp2 or ""),
|
||||
unit=(r.get("unit") or _un2 or ""),
|
||||
kind=(r.get("kind") if r.get("kind") is not None else _kd2))
|
||||
if ntp is None:
|
||||
ntp = _ln
|
||||
if taxp is None:
|
||||
taxp = _lt
|
||||
if kids.get(code) and not ov.get(code):
|
||||
cn, ct = computed_mother(code, r.get("uw_id"))
|
||||
if cn is not None:
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import zipfile
|
||||
@@ -589,6 +590,11 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
||||
paired = {} # 全量重排(含原已配平的 kind)
|
||||
for mk, (kind, sp, b) in zip(pool, bills_all):
|
||||
paired.setdefault(kind, []).append((sp, b, mk))
|
||||
if os.environ.get("EC_PAIR_DEBUG") and len(pool) != len(bills_all):
|
||||
print("EC_PAIR_DEBUG uw=%r pool=%d bills_all=%d left=%s fblocks=%s" % (
|
||||
uwkey[1][:12], len(pool), len(bills_all),
|
||||
{k: len(v) for k, v in (left or {}).items()},
|
||||
{k: len(v) for k, v in (fblocks_by or {}).items()}), flush=True)
|
||||
# 数量对不上:保留原配对(主路径 kind 照常;left kinds 整组跳过)
|
||||
|
||||
# ---- 动刀(主路径与兜底共用同一套编辑体)----
|
||||
@@ -836,9 +842,28 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
|
||||
for nn in norms_by_bill.get(b["id"], {}).get("append") or []]
|
||||
parts.append(_bill_xml(b, tgt["tag"], norms_xml, tmpl_blk or tgt["opentag"], txt=txt))
|
||||
edits.append((pos, pos, "".join(parts)))
|
||||
# 自底向上应用(span 互不重叠:开标签补丁/定额块删除/闭合前插入各占各的区间)
|
||||
# 专修(2026-10-28,三溪采纳语境实测):删除块与「闭合前插入」相交时,删除按原跨度
|
||||
# 会咬掉已插入的采纳定额(定额丢失+孤儿闭标签=碎 XML)——删除终点收到插入点。
|
||||
# 相交消解(专修二 2026-10-28):删除块内的插入点重映射到删除块起点——
|
||||
# 先删后插、坐标归一,采纳定额与临删删除都完整落地(截短/放任两种都碎,实测)。
|
||||
dels = sorted((s, e) for s, e, rep in edits if rep == "" and e > s)
|
||||
remapped = []
|
||||
for s, e, rep in edits:
|
||||
if rep and s == e:
|
||||
for ds, de in dels:
|
||||
if ds <= s < de:
|
||||
s = ds
|
||||
break
|
||||
remapped.append((s, e, rep))
|
||||
edits = remapped
|
||||
# 自底向上应用(span 互不重叠);
|
||||
# 防御性跳过与已落区间相交的编辑(与 _apply_edits 同款护栏——绝不产出碎 XML)。
|
||||
last_s = None
|
||||
for s, e, rep in sorted(edits, key=lambda x: (x[0], x[1]), reverse=True):
|
||||
if last_s is not None and e > last_s:
|
||||
continue
|
||||
txt = txt[:s] + rep + txt[e:]
|
||||
last_s = s
|
||||
return txt
|
||||
|
||||
|
||||
@@ -990,11 +1015,58 @@ def transform_unit_summaries(txt, price_updates, added_rows, recode_map=None, re
|
||||
children_html=_child_block_html(txt, kmap.get(str(r[0]))),
|
||||
org=omap.get(str(r[0])))
|
||||
for r in added_rows)
|
||||
last = None
|
||||
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*/>', txt):
|
||||
last = m
|
||||
if last is not None:
|
||||
txt = txt[:last.end()] + nodes + txt[last.end():]
|
||||
# 插入锚(专修 2026-10-28,三溪实测 mismatched tag 根因):老 cos 族行标签也叫
|
||||
# …Summary 且散布全文件——「最后一个自闭合 Summary」会落在某条清单定额的消耗行
|
||||
# 中间,新增行插进定额块=碎 XML。老 cos 族(本件无 …Element 行)改为插进**直挂
|
||||
# UnitWorks 的单位级汇总容器**闭合前(同标签嵌套按深度配对找边界);cos4 族
|
||||
# (有 …Element 行)维持原锚(最后一个自闭合容器之后=根层追加)。
|
||||
ins_at = None
|
||||
if not re.search(r'<' + _LME + r'\b', txt):
|
||||
stack, pos2, n2, close_s = [], 0, len(txt), None
|
||||
while pos2 < n2:
|
||||
m2 = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos2)
|
||||
if not m2:
|
||||
break
|
||||
if m2.group(1) == "/":
|
||||
t2 = m2.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t2:
|
||||
del stack[i:]
|
||||
break
|
||||
pos2 = m2.end()
|
||||
continue
|
||||
tag2 = m2.group(2)
|
||||
oe2 = _open_tag_end(txt, m2.start())
|
||||
if oe2 < 0:
|
||||
break
|
||||
if txt[oe2 - 2:oe2] == "/>":
|
||||
pos2 = oe2
|
||||
continue
|
||||
if tag2 == _SUM_TAG and stack and stack[-1] == "UnitWorks":
|
||||
depth, p2 = 1, oe2
|
||||
while depth:
|
||||
m3 = re.compile(r"<%s\b|</%s\s*>" % (_SUM_TAG, _SUM_TAG)).search(txt, p2)
|
||||
if not m3:
|
||||
break
|
||||
depth += -1 if m3.group(0)[1] == "/" else 1
|
||||
p2 = m3.end()
|
||||
if depth == 0:
|
||||
break
|
||||
close_s = p2 - len("</%s>" % _SUM_TAG)
|
||||
pos2 = p2
|
||||
continue
|
||||
stack.append(tag2)
|
||||
pos2 = oe2
|
||||
if close_s is not None:
|
||||
ins_at = close_s
|
||||
if ins_at is not None:
|
||||
txt = txt[:ins_at] + nodes + txt[ins_at:]
|
||||
else:
|
||||
last = None
|
||||
for m in re.finditer(r'<LabourMaterialsEquipmentsMachinesSummary\b[^>]*/>', txt):
|
||||
last = m
|
||||
if last is not None:
|
||||
txt = txt[:last.end()] + nodes + txt[last.end():]
|
||||
idx = _summary_span_index(txt)
|
||||
edits = {} # span起点 → (起, 止, 替换)(同节点改价+改码合并为一条)
|
||||
foreign = _ident_foreign_spans(txt, idx, recode_ident) # 决策 178:同码异物节点先认领
|
||||
@@ -1209,6 +1281,7 @@ def _summary_span_index(txt):
|
||||
2026-10-22 主人拍板:同码多节点全改)。span=(起点, 开标签止, 块止, 开标签),
|
||||
块止对自闭合=开标签止;列表按文件序。"""
|
||||
idx = {}
|
||||
_elem_family = bool(re.search(r'<' + _LME + r'\b', txt)) # cos4 族有 …Element 行;老 cos 没有
|
||||
for m in re.finditer(r'<' + _SUM_TAG + r'\b', txt):
|
||||
e = _open_tag_end(txt, m.start())
|
||||
if e < 0:
|
||||
@@ -1226,8 +1299,24 @@ def _summary_span_index(txt):
|
||||
# 这个「块」必是假的(真块内不会再嵌 Summary)→ 按裸行处理,span 只算开标签。
|
||||
# 否则假块会吞进几万字符里的几十个节点:改码编辑与内层相交被 _apply_edits 丢弃
|
||||
# (换码失效)、_recode_norm_lme_rows 把吞进的元素行误当块内子级跳过(残留)。
|
||||
# 专修(2026-10-28,三溪实测 mismatched tag 根因):两族分治——老 cos 族行标签
|
||||
# 也叫 …Summary 且**合法嵌套**(带子级的行=同标签容器),首闭配对会把块界算到
|
||||
# 内层闭标签(换码/同名清扫切一半=碎 XML);无 …Element 行时改按深度配对找真块界。
|
||||
if ce < 0 or re.search(r'<' + _SUM_TAG + r'\b', txt[e:ce]):
|
||||
idx.setdefault(code, []).append((m.start(), e, e, opentag))
|
||||
if _elem_family:
|
||||
idx.setdefault(code, []).append((m.start(), e, e, opentag))
|
||||
else:
|
||||
depth, p2 = 1, e
|
||||
while depth:
|
||||
m2 = re.search(r'<' + _SUM_TAG + r'\b|</' + _SUM_TAG + r'\s*>', txt[p2:])
|
||||
if not m2:
|
||||
break
|
||||
depth += -1 if m2.group(0)[1] == "/" else 1
|
||||
p2 += m2.end()
|
||||
if depth == 0:
|
||||
break
|
||||
idx.setdefault(code, []).append(
|
||||
(m.start(), e, p2 if depth == 0 else e, opentag))
|
||||
else:
|
||||
idx.setdefault(code, []).append((m.start(), e, ce + len("</" + _SUM_TAG + ">"), opentag))
|
||||
return idx
|
||||
@@ -1253,7 +1342,15 @@ def _drop_zero_qty_summary_rows(txt):
|
||||
continue # 无 Quantity / 非数字 → 保守保留
|
||||
if q == 0:
|
||||
cuts.append((s0, bend if bend > s0 else e0))
|
||||
for s0, e0 in sorted(cuts, key=lambda x: x[0], reverse=True):
|
||||
# 专修(2026-10-28,三溪采纳语境 mismatched tag 根因):块界深度配对后,0 量母行的
|
||||
# 块内可能还有 0 量子行——两刀相叠、后刀按原跨度多切=碎 XML。并集处理(内层随母行走)。
|
||||
cuts.sort(key=lambda x: x[0])
|
||||
merged = []
|
||||
for s0, e0 in cuts:
|
||||
if merged and s0 < merged[-1][1]:
|
||||
continue
|
||||
merged.append((s0, e0))
|
||||
for s0, e0 in sorted(merged, key=lambda x: x[0], reverse=True):
|
||||
txt = txt[:s0] + txt[e0:]
|
||||
return txt
|
||||
|
||||
@@ -1441,7 +1538,11 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
|
||||
|
||||
def _apply_qty_updates(txt, qty_updates):
|
||||
"""决策 188:把现算数量写回单位文本的 Summary 节点(Quantity+四Total 锚定自算)。
|
||||
正则口径(金宝裸行也命中);未命中码不动。"""
|
||||
正则口径(金宝裸行也命中);未命中码不动。
|
||||
专修(2026-10-28,三溪实测碎标签根因):先收集全部命中、按位置**倒序一次应用**——
|
||||
原实现在 finditer 迭代同一 txt 的同时改写 txt,同码多节点时首个替换一变长,
|
||||
后续命中全按陈旧偏移落刀(<Labo<Labour… 碎标签,2/14 成员 XML 不合法)。"""
|
||||
edits = []
|
||||
for code, qv in (qty_updates or {}).items():
|
||||
try:
|
||||
qv = float(qv)
|
||||
@@ -1460,9 +1561,12 @@ def _apply_qty_updates(txt, qty_updates):
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if nt != t:
|
||||
txt = txt[:m.start()] + nt + txt[m.end():]
|
||||
edits.append((m.start(), m.end(), nt))
|
||||
for s, e, rep in sorted(edits, key=lambda x: x[0], reverse=True):
|
||||
txt = txt[:s] + rep + txt[e:]
|
||||
return txt
|
||||
|
||||
|
||||
def transform_project(txt, added_summaries, hidden_codes, sync_rows=None, recode_map=None,
|
||||
recode_children=None, recode_ident=None, unit_texts=None, added_org=None):
|
||||
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工工程导出(决策 229,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
"""手工工程导出(决策 231,2026-10-27 主人定):经典整件骨架当模板,我方清单级数据填空。
|
||||
|
||||
口径(主人逐条拍板):
|
||||
· 骨架只在导出时用;内部数据只管采纳。单位工程→清单的计价信息按采纳数值,
|
||||
@@ -26,6 +26,7 @@ import zipfile
|
||||
|
||||
import classic_skeleton
|
||||
import export_cos as ec
|
||||
import dyn_lme
|
||||
from formats.skeleton import build_plan, num as _num
|
||||
|
||||
_LME_SUM = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
@@ -66,10 +67,20 @@ def _span(txt, tag, start=0):
|
||||
mn = re.compile(r"<%s\b|</%s\s*>" % (tag, tag)).search(txt, pos)
|
||||
if not mn:
|
||||
return None
|
||||
depth += -1 if mn.group(0)[1] == "/" else 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
if mn.group(0)[1] == "/":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return (s, mn.end())
|
||||
pos = mn.end()
|
||||
continue
|
||||
o2 = ec._open_tag_end(txt, mn.start())
|
||||
if o2 < 0:
|
||||
return None
|
||||
if txt[o2 - 2:o2] == "/>":
|
||||
pos = o2 # 自闭合同名子行=完整元素,不进深度(2026-10-28 修:
|
||||
continue # 合成件 Summary 子行把深度顶穿→容器配对 None→只删开标签留孤儿闭合)
|
||||
depth += 1
|
||||
pos = o2
|
||||
return None
|
||||
|
||||
|
||||
@@ -86,20 +97,10 @@ def _block_tag(blk):
|
||||
return m.group(1) if m else _ITEM_BILL
|
||||
|
||||
|
||||
def _zero_rows(frag):
|
||||
"""克隆架子清值第二遍:样板块里定额/工料机行的量价结果清零、含量式清空
|
||||
(_zero_results 不覆盖 Norm/LME 行本身——采纳链是整行换,用不到这一步)。"""
|
||||
def z(m):
|
||||
t = m.group(0)
|
||||
for k in ("Quantity", "Price", "Total"):
|
||||
t = re.sub(r"\b%s=\"[^\"]*\"" % k, lambda _m: k + "=\"0\"", t)
|
||||
return re.sub(r"\bExpress=\"[^\"]*\"", 'Express=""', t)
|
||||
return re.sub(r"<(?:Norm|LabourMaterialsEquipmentsMachinesElement)\b[^>]*?/?>", z, frag)
|
||||
|
||||
|
||||
def _manual_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
"""我方一条清单 → 整块:样板清单整块克隆(开标签全属性+费用构成汇总+定额/工料机
|
||||
架子),我方清单五值+特征+备注落槽(骨架没的槽不造,决策 198),架子值全清。
|
||||
def _frame_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
"""未采纳清单(231①,主人 2026-10-28 复确认「Excel 进来的清单导出 cos 要以 cos
|
||||
清单架子导出」):样板清单整块克隆(开标签全属性+费用构成汇总+定额/工料机架子),
|
||||
我方清单五值+特征+备注落槽(骨架没的槽不造,198),架子值全清——「还没组价」的形态。
|
||||
无样板 → 最小自闭合形态(决策 64 已知可行解)。"""
|
||||
if not sample_blk:
|
||||
a = ' Number="%s" Name="%s"' % (ec._esc(b.get("Number") or ""),
|
||||
@@ -126,9 +127,218 @@ def _manual_bill(sample_blk, b, min_tag=_ITEM_BILL):
|
||||
inner = sample_blk[len(opentag):]
|
||||
if inner.endswith(close):
|
||||
inner = inner[: -len(close)]
|
||||
|
||||
def _zero_rows(frag):
|
||||
def z(m):
|
||||
t2 = m.group(0)
|
||||
for k in ("Quantity", "Price", "Total"):
|
||||
t2 = re.sub(r"\b%s=\"[^\"]*\"" % k, lambda _m: k + "=\"0\"", t2)
|
||||
return re.sub(r"\bExpress=\"[^\"]*\"", 'Express=""', t2)
|
||||
return re.sub(r"<(?:Norm|LabourMaterialsEquipmentsMachinesElement)\b[^>]*?/?>",
|
||||
z, frag)
|
||||
|
||||
return t + _zero_rows(ec._zero_results(inner)) + close
|
||||
|
||||
|
||||
def _bill_block(sample_blk, b, norm_tmpl, express_by_norm, txt):
|
||||
"""我方一条清单 → 整块(决策 231①+补记,主人定「和标准采纳一样」):
|
||||
· 有采纳定额 → 走 export_cos 同款引擎挂**真实定额**(_norm_xml:费用构成/单价计算
|
||||
innards 克隆、消耗量行重写、清单级工料机尾表按消耗量现算,决策 98/106);
|
||||
· 没采纳 → **克隆架子清值**(231①,主人 2026-10-28 复确认):cos 清单架子导出、
|
||||
值全清=「还没组价」的形态。
|
||||
工程量按数据本体精度回写(_bill_xml 内部按单件 3 位规律写会截 6 位量,三溪实测)。"""
|
||||
ns = [n for n in (b.get("norms") or []) if not n.get("x_tdel")]
|
||||
if not ns:
|
||||
return _frame_bill(sample_blk, b, _PRE_BILL if b.get("kind") == "prelim"
|
||||
else _ITEM_BILL)
|
||||
norms_xml = []
|
||||
for n in ns:
|
||||
lres = (express_by_norm or {}).get(n["id"]) or n.get("res") or []
|
||||
norms_xml.append(ec._norm_xml(n, lres, template=norm_tmpl,
|
||||
bill_qty=b.get("Quantity")))
|
||||
t = ec._bill_xml(b, _block_tag(sample_blk or _ITEM_BILL), norms_xml,
|
||||
template=sample_blk or None, txt=txt)
|
||||
oe = ec._open_tag_end(t, 0)
|
||||
if oe > 0:
|
||||
ot = t[:oe]
|
||||
if b.get("Quantity") is not None:
|
||||
ot = ec._attr_set(ot, "Quantity", _num(b.get("Quantity")))
|
||||
if not b.get("Number") and ' Number="' in ot:
|
||||
ot = ec._attr_set(ot, "Number", "") # 编码空=空("0" 是数值占位口径)
|
||||
t = ot + t[oe:]
|
||||
return t
|
||||
|
||||
|
||||
_LME_FILL_ROOTS = ("UnitWorks", "ConstructionProject", "ConstructProject",
|
||||
"ProjectInstallationWorkCost")
|
||||
|
||||
|
||||
def _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=None, lib=None):
|
||||
"""现算行 → 行列 HTML(决策 231 补记五,主人拍板「按现有数据生成」):
|
||||
行模板照骨架本件形态(198 槽不造);台班/配合比码带子级组成(s_lme_res)
|
||||
→ 行转容器+子行;量 0 不导(199)。"""
|
||||
out = []
|
||||
dyn_codes = {str(r[0]) for r in rows9 or []}
|
||||
# 组成子码全单位总额(2026-10-28 主人实测易达映射源组成子行编制价全空后的补行依据;
|
||||
# 原生件铁证:折旧费等组成码在单位表**各有一行自己的价**,量=Σ(母现算量×构成值)——
|
||||
# 构成值就是台班单价的组成(折旧3.44+检修0.80+…=台班价14.10),量×价1.00=总价)
|
||||
comp_tot = {}
|
||||
for r in rows9 or []:
|
||||
for c, q in (children or {}).get(str(r[0])) or []:
|
||||
try:
|
||||
comp_tot[c] = comp_tot.get(c, 0.0) + float(q or 0) * float(r[5] or 0)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
comp_done = set()
|
||||
for r in rows9 or []:
|
||||
code, name, spec, unit, kind, qty, ntp, taxrate, taxp = r[:9]
|
||||
try:
|
||||
if float(qty or 0) == 0:
|
||||
continue
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
t = ec._lme_row(row_tmpl, code, _num(qty))
|
||||
t = ec._attr_set_has(t, "Name", name or "")
|
||||
t = ec._attr_set_has(t, "Specification", spec or "")
|
||||
t = ec._attr_set_has(t, "Unit", unit or "")
|
||||
if kind:
|
||||
t = ec._attr_set_has(t, "Kind", str(int(kind)))
|
||||
for k, v in (("Quantity", _num(qty)), ("NoTaxPrice", _money(ntp)),
|
||||
("TaxRate", _money(taxrate)), ("TaxPrice", _money(taxp))):
|
||||
t = ec._attr_set_has(t, k, v)
|
||||
kids = (children or {}).get(str(code))
|
||||
if kids and child_tmpl:
|
||||
if t.endswith("/>"):
|
||||
t = t[:-2] + ">"
|
||||
# 原生排版(两骨架实测):母行开标签→换行缩进→子行逐行同缩进→闭合标签前换行缩进
|
||||
ci = (ind or {}).get("ci") or "\n "
|
||||
cc = (ind or {}).get("cc") or "\n "
|
||||
inner = ci + ci.join(ec._child_node(child_tmpl, c, q) for c, q in kids)
|
||||
t = t + inner + cc + "</%s>" % _LME_SUM
|
||||
out.append(t)
|
||||
# 组成子码自有行(价格源行):紧跟首个引用它的母容器行(首现序),每码只补一行;
|
||||
# 已有现算行的码不补(直耗行已带价);名称/规格/单位/类别/单价取 s_lme_lib 快照
|
||||
for c, _q in (kids or ()):
|
||||
if c in dyn_codes or c in comp_done:
|
||||
continue
|
||||
lb = (lib or {}).get(c)
|
||||
if not lb or not comp_tot.get(c):
|
||||
continue
|
||||
nm2, sp2, un2, kd2, ntp2, taxp2 = lb
|
||||
|
||||
t2 = ec._lme_row(row_tmpl, c, _num(comp_tot[c]))
|
||||
t2 = ec._attr_set_has(t2, "Name", nm2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Specification", sp2 or "")
|
||||
t2 = ec._attr_set_has(t2, "Unit", un2 or "")
|
||||
if kd2:
|
||||
try:
|
||||
t2 = ec._attr_set_has(t2, "Kind", str(int(kd2)))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
t2 = ec._attr_set_has(t2, "NoTaxPrice", _money(ntp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxPrice", _money(taxp2))
|
||||
t2 = ec._attr_set_has(t2, "TaxRate", _money(0))
|
||||
out.append(t2)
|
||||
comp_done.add(c)
|
||||
return out
|
||||
|
||||
|
||||
def _lme_fill(txt, rows9=None, children=None, row_tmpl=None, child_tmpl=None, ind=None,
|
||||
lib=None):
|
||||
"""根层工料机汇总行(决策 231 补记五推翻补记三的「清空」定论——易达标准骨架铁证:
|
||||
单位成员根层直挂的 LME_SUM=**单位级汇总表**(每码一行、台班带子级嵌套);项目成员
|
||||
PIWC 内同款=项目级汇总表。骨架行/子行照本件形态克隆,灌**现算行**(主人拍板:
|
||||
定额工程量×消耗量,dyn 引擎)+台班子级组成;无现算行 → 清空(架子在、别人的行不进);
|
||||
行/子行模板缺位时本件全局取(调用方传入)。"""
|
||||
if not row_tmpl:
|
||||
return _lme_clear(txt)
|
||||
sep = ec._native_sep(txt, _LME_SUM, "") or (ind or {}).get("sep") or "\n"
|
||||
keep = _lme_rows_html(rows9, children, row_tmpl, child_tmpl, sep, ind=ind, lib=lib)
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
if not spans:
|
||||
# 空槽成员没有旧行=没有锚(2026-10-28 实测:易达骨架 31 位仅 3 位有汇总行,其余
|
||||
# 单位整表不插)。按原生「表在根尾」位补插(UnitWorksSummary 之后、根闭标签之前,
|
||||
# 两骨架有行成员同款)。首行不补分隔——插入点前已有原生换行。
|
||||
if not keep:
|
||||
return txt
|
||||
m = re.search(r"</([A-Za-z_][\w.]*)>\s*$", txt)
|
||||
anchor = m.start() if m else len(txt)
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
anchor = spans[0][0]
|
||||
for s, e in reversed(spans): # 从后往前删,锚点偏移不失效
|
||||
txt = txt[:s] + txt[e:]
|
||||
if not keep:
|
||||
return txt
|
||||
# 首行不补分隔:锚点前保留着原首行的换行+缩进(删行只删 < 起),避免双分隔出空行
|
||||
body = keep[0] + "".join(sep + r for r in keep[1:])
|
||||
return txt[:anchor] + body + txt[anchor:]
|
||||
|
||||
|
||||
def _lme_clear(txt):
|
||||
"""无行模板(骨架件无样行)时退回清空——架子在、行不进。"""
|
||||
spans, stack, pos, n = [], [], 0, len(txt)
|
||||
while pos < n:
|
||||
m = re.compile(r"<(/?)([A-Za-z_][\w.]*)").search(txt, pos)
|
||||
if not m:
|
||||
break
|
||||
if m.group(1) == "/":
|
||||
t = m.group(2)
|
||||
for i in range(len(stack) - 1, -1, -1):
|
||||
if stack[i] == t:
|
||||
del stack[i:]
|
||||
break
|
||||
pos = m.end()
|
||||
continue
|
||||
tag = m.group(2)
|
||||
oe = ec._open_tag_end(txt, m.start())
|
||||
if oe < 0:
|
||||
break
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
spans.append((m.start(), oe))
|
||||
pos = oe
|
||||
continue
|
||||
if tag == _LME_SUM and (not stack or stack[-1] in _LME_FILL_ROOTS):
|
||||
sp = _span(txt, _LME_SUM, m.start())
|
||||
spans.append((m.start(), sp[1] if sp else oe))
|
||||
pos = sp[1] if sp else oe
|
||||
continue
|
||||
stack.append(tag)
|
||||
pos = oe
|
||||
for s, e in reversed(spans):
|
||||
txt = txt[:s] + txt[e:]
|
||||
return txt
|
||||
|
||||
|
||||
def _dw_template(txt):
|
||||
"""骨架件本单位里第一个分部完整块 → {ot 开标签, prefix 前缀(分部自己的费用构成等)}。
|
||||
决策 106:费用构成子块是易达认块的关键——克隆时带上(值清零)。
|
||||
@@ -168,7 +378,8 @@ def _sum_bills(bills):
|
||||
return n
|
||||
|
||||
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, depth=0):
|
||||
def _div_block(tmpl, d, kids, bills_by_div, sample, sep, norm_tmpl=None,
|
||||
express_by_norm=None, txt="", depth=0):
|
||||
"""一个分部节点:开标签克隆(Name/Total 落我方,指标清零)+费用构成前缀(清零)
|
||||
+子分部/清单递归。Total=本级+全部子孙清单合计(现算,主人定可计算按采纳)。
|
||||
我方上限 4 级(决策 230),递归保险 8 级。返回 (块文本, 合计)。"""
|
||||
@@ -181,12 +392,13 @@ def _div_block(tmpl, d, kids, bills_by_div, sample, sep, depth=0):
|
||||
if depth <= _MAX_DEPTH:
|
||||
for sub in kids.get(d["id"], []):
|
||||
blk, sub_total = _div_block(tmpl, sub, kids, bills_by_div, sample, sep,
|
||||
depth + 1)
|
||||
norm_tmpl, express_by_norm, txt, depth + 1)
|
||||
parts.append(blk)
|
||||
total += sub_total
|
||||
ot = ec._attr_set_has(ot, "Total", _money(total))
|
||||
bills = [_manual_bill(sample, b) for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = _zero_rows(ec._zero_results(tmpl["prefix"])) if tmpl else ""
|
||||
bills = [_bill_block(sample, b, norm_tmpl, express_by_norm, txt)
|
||||
for b in bills_by_div.get(d["id"], [])]
|
||||
prefix = ec._zero_results(tmpl["prefix"]) if tmpl else ""
|
||||
return ot + prefix + sep.join(parts + bills) + "</%s>" % _DW, total
|
||||
|
||||
|
||||
@@ -225,17 +437,27 @@ def _top_scan(inner, stop_tags):
|
||||
return inner, n
|
||||
|
||||
|
||||
def _render_unit(txt, u, plan):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总空槽;
|
||||
单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"]
|
||||
def _render_unit(txt, u, plan, sc=None, sid=0, express_by_norm=None,
|
||||
lme_ctx=None):
|
||||
"""一个单位工程成员:分部容器/措施容器清仓重插我方数据;工料机汇总按现算挂真实行
|
||||
(无采纳=空槽);单位名与我方可算合计落位。u=None=骨架多出的单位位:清仓保留值,不改名。"""
|
||||
bills_item = [b for b in (u["bills"] if u else []) if b["kind"] == "item"
|
||||
and not b.get("x_tdel")]
|
||||
bills_pre = [b for b in (u["bills"] if u else []) if b["kind"] == "prelim"
|
||||
and not b.get("x_tdel")]
|
||||
item_sample = ec._largest_bill_block(txt, tag=_ITEM_BILL, prelim=False) \
|
||||
or _fallback_blk(txt, False)
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) or item_sample
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "\r\n")
|
||||
sep_d = ec._native_sep(txt, _DW, sep)
|
||||
tmpl = _dw_template(txt)
|
||||
or _fallback_blk(txt, False) or (lme_ctx or {}).get("g_item")
|
||||
pre_sample = ec._largest_bill_block(txt, prelim=True) \
|
||||
or (lme_ctx or {}).get("g_pre") or item_sample
|
||||
norm_tmpl_item = (ec._full_norm_block(item_sample) if item_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_item")
|
||||
norm_tmpl_pre = (ec._full_norm_block(pre_sample) if pre_sample else None) \
|
||||
or (lme_ctx or {}).get("g_norm_pre") or norm_tmpl_item
|
||||
sep = ec._native_sep(txt, _ITEM_BILL, "") \
|
||||
or (lme_ctx or {}).get("g_sep") or "\r\n"
|
||||
sep_d = ec._native_sep(txt, _DW, sep) or (lme_ctx or {}).get("g_sep_d") or sep
|
||||
tmpl = _dw_template(txt) or (lme_ctx or {}).get("g_dw")
|
||||
bb = dict(norm_tmpl=norm_tmpl_item, express_by_norm=express_by_norm, txt=txt)
|
||||
|
||||
# ---- 分部分项容器:清仓 → 我方分部树(DivisionalWorks 递归嵌套)+ 容器合计现算 ----
|
||||
sp = _span(txt, _ITEM_CONT)
|
||||
@@ -249,14 +471,18 @@ def _render_unit(txt, u, plan):
|
||||
bills_by_div = {}
|
||||
for b in bills_item:
|
||||
bills_by_div.setdefault(b.get("div_id"), []).append(b)
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d)[0]
|
||||
blocks = [_div_block(tmpl, d, kids, bills_by_div, item_sample, sep_d,
|
||||
norm_tmpl=bb["norm_tmpl"],
|
||||
express_by_norm=express_by_norm, txt=txt)[0]
|
||||
for d in roots]
|
||||
blocks += [_manual_bill(item_sample, b) for b in bills_by_div.get(None, [])]
|
||||
blocks += [_bill_block(item_sample, b, bb["norm_tmpl"],
|
||||
express_by_norm, txt)
|
||||
for b in bills_by_div.get(None, [])]
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_item)))
|
||||
else:
|
||||
blocks = []
|
||||
prefix, _ = _top_scan(inner_old, (_DW, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + sep_d.join(blocks) + close)
|
||||
|
||||
# ---- 措施项目容器:清仓 → 我方措施行(有包装层就克隆一层);合计现算 ----
|
||||
@@ -268,7 +494,8 @@ def _render_unit(txt, u, plan):
|
||||
inner_old = txt[oe:sp[1] - len(close)] if txt[sp[1] - len(close):sp[1]] == close else txt[oe:sp[1]]
|
||||
if u and bills_pre:
|
||||
ot_wrap = _opentag(inner_old, _DW_PRE)
|
||||
bills = [_manual_bill(pre_sample, b, _PRE_BILL) for b in bills_pre]
|
||||
bills = [_bill_block(pre_sample, b, norm_tmpl_pre, express_by_norm, txt)
|
||||
for b in bills_pre]
|
||||
body = (ec._clone_open_tag(ot_wrap) + sep.join(bills) + "</%s>" % _DW_PRE) \
|
||||
if ot_wrap else sep.join(bills)
|
||||
ot = ec._attr_set_has(ot, "Total", _money(_sum_bills(bills_pre)))
|
||||
@@ -277,23 +504,17 @@ def _render_unit(txt, u, plan):
|
||||
# 措施分部两种标签都在真实件里出现过:PreliminaryDivisionalWorks(新)与
|
||||
# DivisionalWorks(三溪 .cos 实测)——都要停,包装层连同旧清单整块让位给我方平铺
|
||||
prefix, _ = _top_scan(inner_old, (_DW_PRE, _DW, _PRE_BILL, _ITEM_BILL))
|
||||
inner = _zero_rows(ec._zero_results(prefix))
|
||||
inner = ec._zero_results(prefix)
|
||||
txt = _replace_span(txt, sp, ot + inner + body + close)
|
||||
|
||||
# ---- 工料机汇总:架子在、行不进(我方无工料机数据)。容器→清空内层;
|
||||
# 自闭合行(老版本/广联达目录式导出的形态)→ 整行删除,别人的行绝不残留 ----
|
||||
pos = 0
|
||||
while True:
|
||||
sp = _span(txt, _LME_SUM, pos)
|
||||
if not sp:
|
||||
break
|
||||
oe = ec._open_tag_end(txt, sp[0])
|
||||
if txt[oe - 2:oe] == "/>":
|
||||
txt = txt[:sp[0]] + txt[sp[1]:]
|
||||
pos = sp[0]
|
||||
continue
|
||||
txt = txt[:oe] + "</%s>" % _LME_SUM + txt[sp[1]:]
|
||||
pos = oe
|
||||
# ---- 单位级工料机汇总(补记五:根层 LME_SUM=单位级汇总表,易达标准骨架铁证):
|
||||
# 灌现算行(dyn 引擎,定额工程量×消耗量)+台班子级;没采纳 → 清空(架子在行不进)
|
||||
ctx = lme_ctx or {}
|
||||
rows9 = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) if (sc and u) else None
|
||||
txt = _lme_fill(txt, rows9, ctx.get("children"),
|
||||
ctx.get("row_tmpl"), ctx.get("child_tmpl"),
|
||||
ind={"ci": ctx.get("ci"), "cc": ctx.get("cc"), "sep": ctx.get("sep")},
|
||||
lib=ctx.get("lib"))
|
||||
|
||||
# ---- 单位工程名 + 我方可算合计(分部分项费/措施费;其余保留值)----
|
||||
if u:
|
||||
@@ -342,8 +563,27 @@ def _rename_opentags(txt, tag, names):
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。"""
|
||||
class _GbkNameZipInfo(ec._RawNameZipInfo):
|
||||
"""克隆补位成员的条目名:骨架原生条目名是 GBK 字节(无旗标)。_RawNameZipInfo 对
|
||||
cp437 编不回的串会退 UTF-8+旗标——那正是乱码教训——新中文名这里改按 GBK 写、同样
|
||||
不打旗标(GBK 也编不了才 UTF-8 兜底)。"""
|
||||
|
||||
def _encodeFilenameFlags(self):
|
||||
try:
|
||||
return self.filename.encode("cp437"), 0
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
try:
|
||||
return self.filename.encode("gbk"), 0
|
||||
except UnicodeEncodeError:
|
||||
return self.filename.encode("utf-8"), 0x800
|
||||
|
||||
|
||||
def _render_project(txt, plan, proj_name, n_ours, n_sections, extra_refs=None):
|
||||
"""项目成员:工程名/单项名/单位引用名落我方;其余全部保留值。
|
||||
extra_refs=骨架位不够时克隆出来的单位引用行 [(我方单位名, 成员文件名, 引用号)]
|
||||
——克隆最后一条现有引用行,号/名/文件名改新,按原生分隔符顺延(2026-10-28 主人定
|
||||
「骨架单位工程位可自由添加」)。"""
|
||||
decl = re.match(r"^.*?\?>", txt, flags=re.S)
|
||||
base = decl.end() if decl else 0
|
||||
lead = base + (len(txt[base:]) - len(txt[base:].lstrip()))
|
||||
@@ -357,17 +597,34 @@ def _render_project(txt, plan, proj_name, n_ours, n_sections):
|
||||
sec_names = [s.get("name") or "" for s in plan["sections"]]
|
||||
for t in _SEC_TAGS:
|
||||
txt = _rename_opentags(txt, t, sec_names)
|
||||
if extra_refs:
|
||||
ms = list(re.finditer(r"<UnitWorks\b[^>]*>", txt))
|
||||
if ms:
|
||||
tmpl_o = ms[-1].group(0)
|
||||
# 自闭合引用行先转开标签形态改属性,改完再转回——_attr_set 对缺属性是尾插,
|
||||
# 会把属性插到自闭合的 / 后面(Total="x"/ FileName="y"> 结构破)
|
||||
self_close = tmpl_o.rstrip().endswith("/>")
|
||||
if self_close:
|
||||
tmpl_o = tmpl_o.rstrip()[:-2] + ">"
|
||||
sep = ec._native_sep(txt, "UnitWorks", "\r\n")
|
||||
add = []
|
||||
for name_k, fname_k, num_k in extra_refs:
|
||||
row = ec._attr_set(ec._attr_set(ec._attr_set(
|
||||
tmpl_o, "Number", str(num_k)), "Name", name_k or ""), "FileName", fname_k)
|
||||
if self_close:
|
||||
row = row[:-1] + "/>"
|
||||
add.append(row)
|
||||
txt = txt[:ms[-1].end()] + "".join(sep + r for r in add) + txt[ms[-1].end():]
|
||||
return txt
|
||||
|
||||
|
||||
def export(sc, hcon, sid, suffix, progress=None):
|
||||
"""手工工程导出 cos/cos4。返回 (字节, 文件名, 错误)。"""
|
||||
def export(sc, hcon, sid, suffix, progress=None, src_path=None):
|
||||
"""经典骨架导出 cos/cos4(补记十二,主人定「骨架管导出,数据归软件」:cos4 全量走
|
||||
骨架——手工+普通工程都算;数据全用软件里的现算/采纳,骨架只管格式与字段。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
if not srow["x_manual"]:
|
||||
return None, None, "普通工程请按原格式导出(自带源文件模板)"
|
||||
rep = classic_skeleton.rep_for(hcon, (suffix or "").lower())
|
||||
rep = classic_skeleton.pick_frame(hcon, (suffix or "").lower(), src_path=src_path)
|
||||
if not rep:
|
||||
return None, None, ("该后缀(.%s)还没有经典骨架:请先在后台导入或用工作台"
|
||||
"打开一份 .%s 原件" % (suffix, suffix))
|
||||
@@ -375,14 +632,25 @@ def export(sc, hcon, sid, suffix, progress=None):
|
||||
if plan is None:
|
||||
return None, None, "会话数据读不出来"
|
||||
proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
|
||||
# 采纳含量算式(s_norm_res.express,决策 106 补记十二:调整式跟着历史项目走)
|
||||
express_by_norm = {}
|
||||
for r in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express
|
||||
FROM s_norm_res nr
|
||||
JOIN s_norms n ON n.id=nr.norm_id
|
||||
JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=?""", (sid,)):
|
||||
express_by_norm.setdefault(r["norm_id"], []).append(
|
||||
(r["res_code"], r["qty"], r["express"] or None))
|
||||
try:
|
||||
raw = _render(rep["blob"], plan, proj_name, progress)
|
||||
raw = _render(rep["blob"], plan, proj_name, progress, sc, sid,
|
||||
express_by_norm, rep["suffix"])
|
||||
except Exception as e:
|
||||
return None, None, "导出失败:%s" % e
|
||||
return raw, ((proj_name or "工程") + "-审核版." + rep["suffix"]), None
|
||||
|
||||
|
||||
def _render(blob, plan, proj_name, progress=None):
|
||||
def _render(blob, plan, proj_name, progress=None, sc=None, sid=0,
|
||||
express_by_norm=None, suffix=""):
|
||||
src = zipfile.ZipFile(io.BytesIO(blob))
|
||||
members, texts = [], {}
|
||||
for nm in src.namelist():
|
||||
@@ -402,10 +670,139 @@ def _render(blob, plan, proj_name, progress=None):
|
||||
proj_nms.append(nm)
|
||||
if not unit_nms:
|
||||
raise ValueError("骨架件里没找到单位工程数据,请换一份原件再试")
|
||||
# 单位成员处理序=**项目成员引用行的 FileName 序**(主人 2026-10-28 定:单项/单位排序
|
||||
# 按项目目录先有顺序=引用行序,与压缩包内 xml 次序无关)。骨架自己的引用行序常与
|
||||
# zip 成员序不同——按 zip 序灌名会让「引用行名 ↔ 成员名」错位(实测广联达骨架 20/44
|
||||
# 不一致)。引用行没点到/点丢的成员按原 zip 序垫后,一个不漏。
|
||||
if proj_nms:
|
||||
disp_of = {}
|
||||
for i in src.infolist():
|
||||
if not i.filename.lower().endswith(".xml"):
|
||||
continue
|
||||
try:
|
||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
||||
else i.filename.encode("cp437")
|
||||
disp_of[raw.decode("gbk")] = i.filename
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
ref_order = []
|
||||
for x in re.findall(r"<UnitWorks\b[^>]*>", texts[proj_nms[0]][0]):
|
||||
fn = re.search(r'\bFileName="([^"]*)"', x)
|
||||
if fn and fn.group(1) in disp_of and disp_of[fn.group(1)] in unit_nms \
|
||||
and disp_of[fn.group(1)] not in ref_order:
|
||||
ref_order.append(disp_of[fn.group(1)])
|
||||
if ref_order:
|
||||
unit_nms = ref_order + [n for n in unit_nms if n not in ref_order]
|
||||
ours = plan["units"]
|
||||
# 行/子行模板全局取(专用骨架的空单位位没有样行——借其他成员的形态,补记五):
|
||||
# 行模板=任一自闭合 LME_SUM 行;子行=任一「容器行内嵌的原生 …Element 子行」+原生
|
||||
# 换行缩进(广联达/易达两骨架实测同款:子行一律 Element 形态、只 Number/Express/
|
||||
# Quantity/Remark;2026-10-28 修:旧正则 [^>]*> 会吃掉自闭合的 /,把相邻两条平铺行
|
||||
# 误当「母行+子行」——子行模板成了别人的母行,Name/单价/金额残留全从这来)
|
||||
row_tmpl = child_tmpl = None
|
||||
ci_ind = cc_ind = None
|
||||
g_lme_sep = None
|
||||
pat_row = re.compile(r"<%s\b[^>]*/>" % _LME_SUM)
|
||||
# 子行形态=容器开标签后内嵌的首个 …Element 行(多子行容器里第一条后面跟的是兄弟不是
|
||||
# 闭合,所以闭合缩进单取:最后一条 Element 行与 </…Summary> 之间的空白)
|
||||
pat_child = re.compile(r"<%s\b[^>]*[^/]>(\s*)(<LabourMaterialsEquipmentsMachinesElement"
|
||||
r"\b[^>]*/>)" % _LME_SUM, re.S)
|
||||
pat_close = re.compile(r"<LabourMaterialsEquipmentsMachinesElement\b[^>]*/>"
|
||||
r"(\s*)(</%s>)" % _LME_SUM, re.S)
|
||||
# 清单/定额/分部样板与原生分隔符同样全局兜底(空单位位没有样板 → 借全件的)
|
||||
g_item = g_pre = g_dw = None
|
||||
g_item_nm = None
|
||||
g_sep = g_sep_d = None
|
||||
g_norm_item = g_norm_pre = None
|
||||
for nm in unit_nms:
|
||||
t0 = texts[nm][0]
|
||||
if row_tmpl is None:
|
||||
m1 = pat_row.search(t0)
|
||||
if m1:
|
||||
row_tmpl = m1.group(0)
|
||||
g_lme_sep = ec._native_sep(t0, _LME_SUM, "\n")
|
||||
if child_tmpl is None:
|
||||
m2 = pat_child.search(t0)
|
||||
if m2:
|
||||
child_tmpl, ci_ind = m2.group(2), m2.group(1)
|
||||
if cc_ind is None:
|
||||
m3 = pat_close.search(t0)
|
||||
if m3:
|
||||
cc_ind = m3.group(1)
|
||||
if g_item is None:
|
||||
b1 = ec._largest_bill_block(t0, tag=_ITEM_BILL, prelim=False)
|
||||
if b1:
|
||||
g_item = b1
|
||||
g_item_nm = nm
|
||||
g_sep = ec._native_sep(t0, _ITEM_BILL, "\r\n")
|
||||
g_sep_d = ec._native_sep(t0, _DW, g_sep)
|
||||
g_dw = _dw_template(t0)
|
||||
g_norm_item = ec._full_norm_block(b1)
|
||||
if g_pre is None:
|
||||
b2 = ec._largest_bill_block(t0, prelim=True)
|
||||
if b2:
|
||||
g_pre = b2
|
||||
g_norm_pre = ec._full_norm_block(b2)
|
||||
if row_tmpl and child_tmpl and cc_ind and g_item and g_pre:
|
||||
break
|
||||
# 台班/配合比子级组成(s_lme_res:p_code → [(子码, 含量)])
|
||||
children = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
|
||||
"WHERE session_id=? ORDER BY seq, id", (sid,)):
|
||||
children.setdefault(r["p_code"] or "", []).append((r["res_code"], r["qty"]))
|
||||
# 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入;手工会话唯一价格源)
|
||||
lib = {}
|
||||
if sc:
|
||||
for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp FROM s_lme_lib "
|
||||
"WHERE session_id=?", (sid,)):
|
||||
lib[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"])
|
||||
|
||||
lme_ctx = {"children": children, "row_tmpl": row_tmpl, "child_tmpl": child_tmpl,
|
||||
"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep, "lib": lib,
|
||||
"g_item": g_item, "g_pre": g_pre, "g_dw": g_dw,
|
||||
"g_sep": g_sep, "g_sep_d": g_sep_d,
|
||||
"g_norm_item": g_norm_item, "g_norm_pre": g_norm_pre}
|
||||
# 单位工程位自由复制(主人 2026-10-28 定:骨架=数据结构模板,单位工程/单项工程/
|
||||
# 清单/分部/定额想插多少插多少,结构不变——位不够就克隆骨架自己的单位成员补位,
|
||||
# 项目成员的引用行同步顺延;成员名按骨架自己的 @_序号_名.xml 命名顺延)
|
||||
new_units = [] # [(新成员名, 克隆源名, 引用号, 我方单位名)]——写包时补 zip 条目
|
||||
if len(ours) > len(unit_nms):
|
||||
raise ValueError("经典骨架只有 %d 个单位工程位,本工程有 %d 个——请先用单位工程"
|
||||
"更多的 .%s 原件充一次库" % (len(unit_nms), len(ours), rep["suffix"]))
|
||||
src_nm = g_item_nm or unit_nms[0]
|
||||
orig_slots = len(unit_nms)
|
||||
m2 = re.match(r"@_(\d+)_(.+)\.xml$", src_nm)
|
||||
nums = [int(m.group(1)) for m in
|
||||
(re.match(r"@_(\d+)_", n) for n in unit_nms) if m]
|
||||
base_n = (max(nums) + 2) if nums else (len(unit_nms) + 1)
|
||||
disp = m2.group(2) if m2 else "单位工程"
|
||||
t2 = re.search(r"(\d+)$", disp)
|
||||
# 引用号顺延基准:项目成员里现有 UnitWorks 引用行的最大号
|
||||
nxt = 0
|
||||
if proj_nms:
|
||||
nxt = max([int(x.group(1)) for x in
|
||||
re.finditer(r'<UnitWorks\b[^>]*?\bNumber="(\d+)"', texts[proj_nms[0]][0])]
|
||||
or [0])
|
||||
for k in range(len(ours) - orig_slots):
|
||||
disp_k = (disp[:t2.start()] + str(int(t2.group(1)) + 1 + k)) if t2 \
|
||||
else "%s%d" % (disp, k + 1)
|
||||
nm_k = "@_%d_%s.xml" % (base_n + 2 * k, disp_k)
|
||||
texts[nm_k] = [texts[src_nm][0], texts[src_nm][1]]
|
||||
t0 = texts[nm_k][0]
|
||||
mm = re.search(r"<UnitWorks\b", t0)
|
||||
if mm:
|
||||
oe = ec._open_tag_end(t0, mm.start())
|
||||
t0 = t0[:mm.start()] + ec._attr_set(t0[mm.start():oe], "Number", str(nxt + 1 + k)) + t0[oe:]
|
||||
texts[nm_k][0] = t0
|
||||
members.append(nm_k)
|
||||
unit_nms.append(nm_k)
|
||||
new_units.append((nm_k, src_nm, nxt + 1 + k,
|
||||
(ours[orig_slots + k].get("name") or "")))
|
||||
proj_rows = None
|
||||
if sc:
|
||||
_dp = dyn_lme.dyn_rows(sc, sid, None)
|
||||
if _dp:
|
||||
proj_rows = [(r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8])
|
||||
for r in _dp]
|
||||
total_steps = len(unit_nms) + len(proj_nms) + 1
|
||||
step = [0]
|
||||
|
||||
@@ -416,26 +813,43 @@ def _render(blob, plan, proj_name, progress=None):
|
||||
|
||||
for i, nm in enumerate(unit_nms):
|
||||
u = ours[i] if i < len(ours) else None
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan)
|
||||
texts[nm][0] = _render_unit(texts[nm][0], u, plan, sc, sid, express_by_norm,
|
||||
lme_ctx=lme_ctx)
|
||||
tick()
|
||||
for nm in proj_nms:
|
||||
texts[nm][0] = _render_project(texts[nm][0], plan, proj_name,
|
||||
len(ours), len(plan["sections"]))
|
||||
len(ours), len(plan["sections"]),
|
||||
extra_refs=[(x[3], x[0], x[2]) for x in new_units])
|
||||
texts[nm][0] = _lme_fill(texts[nm][0], proj_rows, children,
|
||||
row_tmpl, child_tmpl,
|
||||
ind={"ci": ci_ind, "cc": cc_ind, "sep": g_lme_sep},
|
||||
lib=lib)
|
||||
tick()
|
||||
tick()
|
||||
out = io.BytesIO()
|
||||
item_by_nm = {i.filename: i for i in src.infolist()}
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for item in src.infolist():
|
||||
data = src.read(item.filename)
|
||||
if item.filename in texts:
|
||||
data = ec._encode(texts[item.filename][0], texts[item.filename][1])
|
||||
zi = zipfile.ZipInfo(item.filename, date_time=item.date_time)
|
||||
zi = ec._RawNameZipInfo(item.filename, date_time=item.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = item.external_attr
|
||||
zi.create_system = item.create_system
|
||||
try:
|
||||
zi.extra = item.extra
|
||||
zi.extra = ec._safe_extra(item.extra)
|
||||
except Exception:
|
||||
pass
|
||||
zo.writestr(zi, data)
|
||||
# 克隆补位的单位成员(骨架原生条目名是 GBK 字节无旗标——新名字同样按 GBK 写)
|
||||
for nm_k, src_nm, _num, _n in new_units:
|
||||
data = ec._encode(texts[nm_k][0], texts[nm_k][1])
|
||||
si = item_by_nm.get(src_nm)
|
||||
zi = _GbkNameZipInfo(nm_k, date_time=si.date_time if si else (2026, 1, 1, 0, 0, 0))
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
if si:
|
||||
zi.external_attr = si.external_attr
|
||||
zi.create_system = si.create_system
|
||||
zo.writestr(zi, data)
|
||||
return out.getvalue()
|
||||
|
||||
@@ -16,6 +16,22 @@ from xml.etree import ElementTree as ET
|
||||
|
||||
import import_job as job
|
||||
|
||||
|
||||
def _natkey(s):
|
||||
"""编号自然序键(与界面树/汇总分析同款):数字段按数值、非数字段按文本。"""
|
||||
out, buf, digit = [], "", None
|
||||
for ch in s or "":
|
||||
d = ch.isdigit()
|
||||
if d == digit:
|
||||
buf += ch
|
||||
else:
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
buf, digit = ch, d
|
||||
if buf:
|
||||
out.append((1, int(buf), "") if digit else (0, 0, buf))
|
||||
return out
|
||||
|
||||
_QTY_EXPR_OK = re.compile(r"^[0-9+\-*/().\s]*$")
|
||||
|
||||
|
||||
@@ -87,11 +103,18 @@ def build_plan(sc, sid):
|
||||
if not srow:
|
||||
return None
|
||||
sections = {}
|
||||
for r in sc.execute("SELECT * FROM s_sections WHERE session_id=?", (sid,)):
|
||||
for r in sc.execute("SELECT * FROM s_sections WHERE session_id=? ORDER BY id", (sid,)):
|
||||
sections[r["id"]] = {"id": r["id"], "number": r["Number"] or "",
|
||||
"name": r["Name"] or "", "total": r["Total"]}
|
||||
# 单位顺序=左侧目录树序(2026-10-28 主人定通用口径,与 2026-10-08 汇总分析同款):
|
||||
# 单项按入库序、组内按编号自然序。手工树保存时按组内位置重写编号=目录序持久化在
|
||||
# Number 里;此前 ORDER BY id 在树里上下移动过单位后会与目录顺序脱节。
|
||||
sec_order = {k: i for i, k in enumerate(sections)}
|
||||
rows = sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall()
|
||||
rows = sorted(rows, key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
|
||||
_natkey(r["Number"] or ""), r["id"]))
|
||||
units = []
|
||||
for r in sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)):
|
||||
for r in rows:
|
||||
sec = sections.get(r["section_id"]) if r["section_id"] is not None else None
|
||||
units.append({"id": r["id"], "number": r["Number"] or "", "name": r["Name"] or "",
|
||||
"total": r["Total"], "section_number": (sec or {}).get("number", ""),
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
3. 层级用「上一级名称」挂接法表达:分部行/清单行都填自己的上级名称,
|
||||
一级分部填「单位工程」;类型只填 分部/清单 两值,几级分部由链条自动算,
|
||||
**单位工程往下最多 5 层**(最多 4 级分部 + 清单,2026-10-27 主人定)。
|
||||
挂接=找上方最近的同名分部;同一上级下分部不得重名(报行号)。
|
||||
挂接=找上方最近的同名分部;空名/同名/深层级均放行(补记十四,2026-10-28)。
|
||||
4. 项目特征换行识别(2026-10-27 主人定):真实换行(Alt+Enter)原样保留;行内编号
|
||||
标记(1. / 1、/ 1)/(1)等多格式)**从 1 连续递增到 N(不缺号,N≥2)才切分**——
|
||||
编到 9 就必须 1~8 齐全;缺号不切;「1.5」这类小数不误切(点后跟数字不算标记)。
|
||||
@@ -237,10 +237,9 @@ def parse_workbook(path):
|
||||
get = lambda key: row[col(key)] if col(key) is not None and col(key) < len(row) else None
|
||||
parent = _cell(get("上一级名称"))
|
||||
typ = _cell(get("类型"))
|
||||
name = _cell(get("名称"))
|
||||
if not name:
|
||||
errors.append("第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
name = _cell(get("名称")) or ""
|
||||
# 补记十四(2026-10-28 主人定边界放开):分部/清单**空名称放行**
|
||||
#(原文件存在空名分部/空名清单);层级**不设限**;同上级**同名分部放行**
|
||||
if typ == "分部":
|
||||
if parent == ROOT_MARK:
|
||||
level, pidx = 1, -1
|
||||
@@ -251,12 +250,6 @@ def parse_workbook(path):
|
||||
errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)"))
|
||||
continue
|
||||
level, pidx = divides[hit]["level"] + 1, hit
|
||||
if level > MAX_DEPTH:
|
||||
errors.append("第 %d 行:层级超过 5 层(单位工程下最多 %d 级分部)" % (ri, MAX_DEPTH))
|
||||
continue
|
||||
if any(d["pidx"] == pidx and d["name"] == name for d in divides):
|
||||
errors.append("第 %d 行:同一上级下已有同名分部「%s」" % (ri, name))
|
||||
continue
|
||||
divides.append({"name": name, "pidx": pidx, "level": level})
|
||||
elif typ == "清单":
|
||||
if parent == ROOT_MARK:
|
||||
@@ -267,9 +260,6 @@ def parse_workbook(path):
|
||||
if didx is None:
|
||||
errors.append("第 %d 行:上一级「%s」未在上方出现" % (ri, parent or "(空)"))
|
||||
continue
|
||||
if divides[didx]["level"] > MAX_DEPTH:
|
||||
errors.append("第 %d 行:清单挂在第 %d 级分部下,超过 5 层" % (ri, divides[didx]["level"] + 1))
|
||||
continue
|
||||
qty = _num(get("工程量"), ri, "工程量", errors)
|
||||
price = _num(get("单价"), ri, "单价", errors)
|
||||
unit = _cell(get("单位"))
|
||||
@@ -295,9 +285,7 @@ def parse_workbook(path):
|
||||
if row is None or not any(_cell(v) for v in row):
|
||||
continue
|
||||
name = _cell(row[head["名称"]]) if head["名称"] < len(row) else ""
|
||||
if not name:
|
||||
errors.append("措施 第 %d 行:名称必填" % ri)
|
||||
continue
|
||||
# 措施空名同样放行(补记十四)
|
||||
qty = _num(row[head["工程量"]] if "工程量" in head and head["工程量"] < len(row) else None,
|
||||
ri, "工程量", errors)
|
||||
price = _num(row[head["单价"]] if "单价" in head and head["单价"] < len(row) else None,
|
||||
@@ -323,9 +311,10 @@ def parse_workbook(path):
|
||||
# 会话结构:查现状 / 保存(建+改+导)
|
||||
# ---------------------------------------------------------------------------
|
||||
def manual_state(con, sid):
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数。"""
|
||||
row = con.execute("SELECT name, period_from, period_to, x_manual FROM sessions WHERE id=?",
|
||||
(sid,)).fetchone()
|
||||
"""手工工程回填弹框用:目录树 + 每个单位工程已导入条数 + 共用字段(决策 233)。"""
|
||||
row = con.execute("""SELECT name, period_from, period_to, x_manual,
|
||||
x_province, x_city, x_district, bulid_unit
|
||||
FROM sessions WHERE id=?""", (sid,)).fetchone()
|
||||
if not row or not row["x_manual"]:
|
||||
return {"ok": False}
|
||||
secs, units = [], []
|
||||
@@ -345,7 +334,10 @@ def manual_state(con, sid):
|
||||
"n_item": c.get("item", 0), "n_prelim": c.get("prelim", 0)}
|
||||
(secmap[u["section_id"]]["units"].append(it) if u["section_id"] in secmap else units.append(it))
|
||||
return {"ok": True, "name": row["name"] or "", "period_from": row["period_from"],
|
||||
"period_to": row["period_to"], "sections": secs, "free_uws": units}
|
||||
"period_to": row["period_to"],
|
||||
"province": row["x_province"] or "", "city": row["x_city"] or "",
|
||||
"district": row["x_district"] or "", "bulid_unit": row["bulid_unit"] or "",
|
||||
"sections": secs, "free_uws": units}
|
||||
|
||||
|
||||
def _del_unit(cur, uwid):
|
||||
@@ -438,6 +430,7 @@ def _sum_divides(cur, uwid):
|
||||
def save_tree(con, body):
|
||||
"""建/改手工工程目录树并按单位工程导 Excel。
|
||||
body = {sid?, name, period_from, period_to,
|
||||
province?/city?/district?/bulid_unit?(决策 233 共用字段落库),
|
||||
tree: [{id?, name, units: [{id?, name, file?}]}], free_uws?: 同款}
|
||||
file = 已上传到软件目录的 xlsx 路径(/api/admin/upload 返回值)。"""
|
||||
name = (body.get("name") or "").strip()
|
||||
@@ -446,6 +439,10 @@ def save_tree(con, body):
|
||||
pf, pt = body.get("period_from"), body.get("period_to")
|
||||
if pf is None or pt is None:
|
||||
return {"ok": False, "msg": "基准期次必填"}
|
||||
prov = (body.get("province") or "").strip() # 决策 233:与打开项目弹框共用字段
|
||||
city = (body.get("city") or "").strip()
|
||||
dist = (body.get("district") or "").strip()
|
||||
bu = (body.get("bulid_unit") or "").strip()
|
||||
tree = body.get("tree") or []
|
||||
flat = []
|
||||
for s in tree:
|
||||
@@ -479,11 +476,13 @@ def save_tree(con, body):
|
||||
cur.execute("""INSERT INTO sessions(name, base_period_m, period_from, period_to,
|
||||
x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_manual)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,1)""",
|
||||
(name, pf, pf, pt, "", "", "", "", "",
|
||||
(name, pf, pf, pt, prov, city, dist, bu, "",
|
||||
time.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
sid = cur.lastrowid
|
||||
cur.execute("UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=? WHERE id=?",
|
||||
(name, pf, pt, pf, sid))
|
||||
# 决策 233:打开项目弹框共用字段——地区/建设单位随建随改落库(与 /api/audit 同名参数)
|
||||
cur.execute("""UPDATE sessions SET name=?, period_from=?, period_to=?, base_period_m=?,
|
||||
x_province=?, x_city=?, x_district=?, bulid_unit=? WHERE id=?""",
|
||||
(name, pf, pt, pf, prov, city, dist, bu, sid))
|
||||
|
||||
# ---- 结构同步(决策 230 补记:单项/单位均可在组内上下移动)----
|
||||
# 单位工程按 id 对位:改名保留数据 / 删除级联 / 新增先插(归属与编号稍后统一指)。
|
||||
@@ -537,7 +536,7 @@ def save_tree(con, body):
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 手工工程导出 Excel(决策 229,2026-10-27 主人定):模板架子+合价/备注
|
||||
# 手工工程导出 Excel(决策 231,2026-10-27 主人定):模板架子+合价/备注
|
||||
# 文件夹=项目名称,一个单位工程一个 xlsx(文件名=单位工程名);
|
||||
# 分部分项 10 列 / 措施项目 8 列——只带清单、不带定额(主人定);
|
||||
# 合价=工程量×单价现算;备注=审核备注;导出件可直接回导入(多出的合价/备注列解析端忽略)。
|
||||
@@ -558,7 +557,14 @@ def export_excel_bytes(sc, sid):
|
||||
if not srow:
|
||||
return None, None, "会话不存在"
|
||||
proj = (srow["Name"] if "Name" in srow.keys() else srow["name"]) or "工程"
|
||||
uws = list(sc.execute("SELECT * FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,)))
|
||||
# 单位顺序=目录树序(2026-10-28 通用口径:单项入库序+组内编号自然序;树里上下
|
||||
# 移动后 ORDER BY id 会与目录脱节)
|
||||
sec_order = {r["id"]: i for i, r in enumerate(
|
||||
sc.execute("SELECT id FROM s_sections WHERE session_id=? ORDER BY id", (sid,)).fetchall())}
|
||||
from formats.skeleton import _natkey
|
||||
uws = sorted(sc.execute("SELECT * FROM s_unit_works WHERE session_id=?", (sid,)).fetchall(),
|
||||
key=lambda r: (sec_order.get(r["section_id"], len(sec_order)),
|
||||
_natkey(r["Number"] or ""), r["id"]))
|
||||
if not uws:
|
||||
return None, None, "本工程还没有单位工程,先在「导入项目」里建目录并导入 Excel"
|
||||
divs = {}
|
||||
@@ -569,6 +575,25 @@ def export_excel_bytes(sc, sid):
|
||||
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
|
||||
bills.setdefault(r["uw_id"], []).append(dict(r))
|
||||
|
||||
import io as _io
|
||||
folder = _safe_sheet_name(proj)
|
||||
used, buf = {}, _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for u in uws:
|
||||
nm = _safe_sheet_name(u["Name"]) + ".xlsx"
|
||||
k = 2
|
||||
while nm in used:
|
||||
nm = "%s(%d).xlsx" % (_safe_sheet_name(u["Name"]), k)
|
||||
k += 1
|
||||
used[nm] = True
|
||||
zo.writestr("%s/%s" % (folder, nm), _unit_workbook(u, divs, bills))
|
||||
return buf.getvalue(), proj + "-审核版.zip", None
|
||||
|
||||
|
||||
def _unit_workbook(u, divs, bills):
|
||||
"""单单位工程 xlsx 字节(决策 231 架子:填写说明+分部分项10列+措施8列,合价/备注)。
|
||||
决策 233:自 export_excel_bytes 抽出——整包 zip 与单单位工程导出(export_unit_xlsx)同一产出。"""
|
||||
|
||||
def b_total(b):
|
||||
try:
|
||||
if b["Quantity"] is not None and b["Price"] is not None:
|
||||
@@ -611,67 +636,82 @@ def export_excel_bytes(sc, sid):
|
||||
return out
|
||||
|
||||
import io as _io
|
||||
folder = _safe_sheet_name(proj)
|
||||
used, buf = {}, _io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||||
for u in uws:
|
||||
wb = Workbook()
|
||||
ws0 = wb.active
|
||||
ws0.title = "填写说明"
|
||||
ws0.column_dimensions["A"].width = 90
|
||||
for i, (t, bold) in enumerate([
|
||||
("「%s」导出件(决策 229)" % u["Name"], True),
|
||||
("", False),
|
||||
("一、本件由软件导出,可直接在「导入项目」里对同一单位工程回导(整单位工程覆盖)。", False),
|
||||
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
|
||||
("三、只到清单级:不导定额、不导工料机。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if bold:
|
||||
c.font = Font(bold=True)
|
||||
h1 = _FB_HEAD_X
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in fb_rows(u["id"]):
|
||||
ws1.append(r)
|
||||
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
|
||||
ws1.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h1, 1):
|
||||
cell = ws1.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws1.freeze_panes = "A2"
|
||||
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
h2 = _CS_HEAD_X
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for b in bills.get(u["id"], []):
|
||||
if b["Kind"] != "prelim":
|
||||
continue
|
||||
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h2, 1):
|
||||
cell = ws2.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws2.freeze_panes = "A2"
|
||||
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
bio = _io.BytesIO()
|
||||
wb.save(bio)
|
||||
nm = _safe_sheet_name(u["Name"]) + ".xlsx"
|
||||
k = 2
|
||||
while nm in used:
|
||||
nm = "%s(%d).xlsx" % (_safe_sheet_name(u["Name"]), k)
|
||||
k += 1
|
||||
used[nm] = True
|
||||
zo.writestr("%s/%s" % (folder, nm), bio.getvalue())
|
||||
return buf.getvalue(), proj + "-审核版.zip", None
|
||||
wb = Workbook()
|
||||
ws0 = wb.active
|
||||
ws0.title = "填写说明"
|
||||
ws0.column_dimensions["A"].width = 90
|
||||
for i, (t, bold) in enumerate([
|
||||
("「%s」导出件(决策 231)" % u["Name"], True),
|
||||
("", False),
|
||||
("一、本件由软件导出,可直接在「导入Excel」里对同一单位工程回导(整单位工程覆盖)。", False),
|
||||
("二、合价=工程量×单价(软件现算);备注=审核备注。", False),
|
||||
("三、只到清单级:不导定额、不导工料机。", False),
|
||||
], 1):
|
||||
c = ws0.cell(row=i, column=1, value=t)
|
||||
if bold:
|
||||
c.font = Font(bold=True)
|
||||
h1 = _FB_HEAD_X
|
||||
ws1 = wb.create_sheet(FB_SHEET)
|
||||
ws1.append(h1)
|
||||
for r in fb_rows(u["id"]):
|
||||
ws1.append(r)
|
||||
for i, w in enumerate([18, 11, 7, 16, 42, 7, 9, 9, 12, 18], 1):
|
||||
ws1.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h1, 1):
|
||||
cell = ws1.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws1.freeze_panes = "A2"
|
||||
for row in ws1.iter_rows(min_row=2, min_col=5, max_col=5):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
h2 = _CS_HEAD_X
|
||||
ws2 = wb.create_sheet(CS_SHEET)
|
||||
ws2.append(h2)
|
||||
for b in bills.get(u["id"], []):
|
||||
if b["Kind"] != "prelim":
|
||||
continue
|
||||
ws2.append([b["Name"] or "", b["Number"] or "", b["Attr"] or "",
|
||||
b["Unit"] or "", b["Quantity"], b["Price"], b_total(b),
|
||||
b["x_remark"] or ""])
|
||||
for i, w in enumerate([20, 11, 36, 7, 9, 10, 12, 18], 1):
|
||||
ws2.column_dimensions[get_column_letter(i)].width = w
|
||||
for c, _h in enumerate(h2, 1):
|
||||
cell = ws2.cell(row=1, column=c)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = PatternFill("solid", fgColor="DCE6F1")
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws2.freeze_panes = "A2"
|
||||
for row in ws2.iter_rows(min_row=2, min_col=3, max_col=3):
|
||||
for cell in row:
|
||||
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
||||
bio = _io.BytesIO()
|
||||
wb.save(bio)
|
||||
return bio.getvalue()
|
||||
|
||||
|
||||
def export_unit_xlsx(sc, sid, uw_id):
|
||||
"""单单位工程导 xlsx(决策 233 方案a,主人定):(字节, 文件名, 错误)。
|
||||
格式版面=决策 231 Excel 通道产出的单个文件(同一 _unit_workbook),可直接回导。"""
|
||||
if Workbook is None:
|
||||
return None, None, "缺少 openpyxl,无法导出 Excel"
|
||||
srow = sc.execute("SELECT x_manual FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow or not srow["x_manual"]:
|
||||
return None, None, "只有手工工程支持按单位工程导 Excel"
|
||||
u = sc.execute("SELECT * FROM s_unit_works WHERE id=? AND session_id=?", (uw_id, sid)).fetchone()
|
||||
if not u:
|
||||
return None, None, "单位工程不存在"
|
||||
divs = {}
|
||||
for r in sc.execute("SELECT * FROM s_divides WHERE session_id=? AND uw_id=? ORDER BY x_seq, id",
|
||||
(sid, uw_id)):
|
||||
divs.setdefault(r["uw_id"], []).append(dict(r))
|
||||
bills = {}
|
||||
for r in sc.execute("""SELECT * FROM s_bills WHERE session_id=? AND uw_id=?
|
||||
ORDER BY CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""",
|
||||
(sid, uw_id)):
|
||||
bills.setdefault(r["uw_id"], []).append(dict(r))
|
||||
if not bills.get(uw_id) and not divs.get(uw_id):
|
||||
return None, None, "「%s」还没有清单数据,先「导入单位工程」" % (u["Name"] or "")
|
||||
raw = _unit_workbook(u, divs, bills)
|
||||
return raw, (_safe_sheet_name(u["Name"]) or "单位工程") + ".xlsx", None
|
||||
|
||||
@@ -41,8 +41,8 @@ import price_xlsx # 信息价 / 市场价 Excel 解析器(2026-1
|
||||
import session_job as sess # 会话库(工作台)
|
||||
import dyn_lme # 决策 188:动态工料机汇总引擎(方案A 现算,2026-10-24)
|
||||
import lme_skeleton # 决策 197:工料机骨架库(后缀+字段签名组,代表件大骨架)
|
||||
import classic_skeleton # 决策 229:经典整件骨架库(手工工程导出模板,连保留值存)
|
||||
import export_manual # 决策 229:手工工程导出 cos/cos4(经典骨架当模板填空)
|
||||
import classic_skeleton # 决策 231:经典整件骨架库(手工工程导出模板,连保留值存)
|
||||
import export_manual # 决策 231:手工工程导出 cos/cos4(经典骨架当模板填空)
|
||||
import match # 比对引擎(M4)
|
||||
import export_cos as xcos # 导出回写(批次D,决策 70)
|
||||
import formats # 导出格式适配器(2026-10-19:SWT/SWZ 骨架/填空)
|
||||
@@ -554,7 +554,7 @@ def api_upload(body):
|
||||
_sk.close()
|
||||
except Exception:
|
||||
pass
|
||||
# 决策 229:经典整件骨架收集——后台导入与工作台打开工程同走本口(失败绝不挡上传)
|
||||
# 决策 231:经典整件骨架收集——后台导入与工作台打开工程同走本口(失败绝不挡上传)
|
||||
if classic_skeleton.suffix_of(name):
|
||||
try:
|
||||
_sk = conn()
|
||||
@@ -3593,6 +3593,7 @@ def _adopt_summary_rows(sc, hc, sid, uw_id, src_bill_id):
|
||||
# 本会话该母码已有子级则不覆盖(先采纳的/本项目原的子级为准)。取消采纳回收时随行撤下。
|
||||
if not sc.execute("SELECT 1 FROM s_lme_res WHERE session_id=? AND p_code=? LIMIT 1",
|
||||
(sid, code)).fetchone():
|
||||
_lib_need = set()
|
||||
for r in hc.execute("""SELECT res_code, qty, seq, name FROM lme_res
|
||||
WHERE batch_id=(SELECT batch_id FROM bills WHERE id=?)
|
||||
AND p_code=? ORDER BY seq, id""", (src_bill_id, code)):
|
||||
@@ -3600,6 +3601,21 @@ def _adopt_summary_rows(sc, hc, sid, uw_id, src_bill_id):
|
||||
continue
|
||||
sc.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)",
|
||||
(sid, code, r["res_code"], r["qty"], r["seq"], r["name"]))
|
||||
_lib_need.add(r["res_code"])
|
||||
# 组成子码的名称/规格/单位/类别/单价快照(批次 lme_lib → 会话 s_lme_lib):
|
||||
# 手工会话没有源文件、s_lme_lib 是空的——导出时这些码要各有一行自己的价
|
||||
# (2026-10-28 主人实测易达映射源里组成子行编制价全空;原生件铁证:同表自有行)
|
||||
if _lib_need and hc.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='lme_lib'").fetchone():
|
||||
for lr in hc.execute("""SELECT code, name, spec, unit, kind, ntp, taxp FROM lme_lib
|
||||
WHERE batch_id=(SELECT batch_id FROM bills WHERE id=?)
|
||||
AND code IN (%s)""" % ",".join("?" * len(_lib_need)),
|
||||
[src_bill_id] + sorted(_lib_need)):
|
||||
sc.execute("""INSERT OR IGNORE INTO s_lme_lib
|
||||
(session_id, code, name, spec, unit, kind, ntp, taxp)
|
||||
VALUES(?,?,?,?,?,?,?,?)""",
|
||||
(sid, lr["code"], lr["name"], lr["spec"], lr["unit"],
|
||||
lr["kind"], lr["ntp"], lr["taxp"]))
|
||||
return n, code_map
|
||||
|
||||
|
||||
@@ -3775,6 +3791,26 @@ def api_bill_adopt(sc, hc, body):
|
||||
if new and new != rr["res_code"]:
|
||||
sc.execute("UPDATE s_norm_res SET res_code=? WHERE id=?", (new, rr["id"]))
|
||||
n_recode += 1
|
||||
# 决策 231 补记五(主人 2026-10-28 定「采纳全部数据,包含子工料机」):把批次里
|
||||
# 台班/配合比的**下一级组成**(lme_res,批次库)补进会话 s_lme_res(会话库)——
|
||||
# 本会话没有该码的组成才补(源文件工程解析时已带,不重复);手工工程从此有子级数据。
|
||||
try:
|
||||
_codes = [r[0] for r in sc.execute(
|
||||
"SELECT DISTINCT nr.res_code FROM s_norm_res nr "
|
||||
"JOIN s_norms n ON n.id=nr.norm_id "
|
||||
"JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=?", (sid,))]
|
||||
_have = {r[0] for r in sc.execute(
|
||||
"SELECT DISTINCT p_code FROM s_lme_res WHERE session_id=?", (sid,))}
|
||||
_todo = [c for c in _codes if c and c not in _have]
|
||||
if _todo:
|
||||
_ph = ",".join("?" * len(_todo))
|
||||
for r in hc.execute(
|
||||
"SELECT p_code, res_code, qty, seq, name FROM lme_res "
|
||||
"WHERE p_code IN (%s) ORDER BY p_code, seq, id" % _ph, _todo):
|
||||
sc.execute("INSERT INTO s_lme_res(session_id,p_code,res_code,qty,seq,name) "
|
||||
"VALUES(?,?,?,?,?,?)", (sid, r[0], r[1], r[2], r[3], r[4]))
|
||||
except Exception as _e:
|
||||
print("!! 采纳补子级组成失败:%s" % _e, flush=True)
|
||||
_pk = _pre.keys() if _pre is not None else []
|
||||
_price0 = (_pre["x_price0"] if _pre is not None and "x_price0" in _pk and _pre["x_price0"] is not None
|
||||
else (_pre["Price"] if _pre is not None else None))
|
||||
@@ -3793,7 +3829,7 @@ _EXPORT_JOBS = {}
|
||||
|
||||
def _export_meta(sc, sid, fmt=""):
|
||||
"""导出建议名(决策 92:先弹另存为再生成——对话框要预填 名字-审核版.原后缀,不能等生成完)。
|
||||
决策 229:手工工程导出 fmt=cos4/cos/xlsx 三选(xlsx=每单位工程一个 Excel 的 zip 包)。"""
|
||||
决策 231:手工工程导出 fmt=cos4/cos/xlsx 三选(xlsx=每单位工程一个 Excel 的 zip 包)。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
return {"ok": False, "msg": "会话不存在"}
|
||||
@@ -3807,6 +3843,8 @@ def _export_meta(sc, sid, fmt=""):
|
||||
return {"ok": False, "msg": "手工工程导出请选格式:cos4 / cos / Excel"}
|
||||
if not (srow["src_name"] or ""):
|
||||
return {"ok": False, "msg": "没有源文件,无法按原格式导出"}
|
||||
if (fmt or "").lower() == "cos4": # 补记十二:普通工程 cos4 也走经典骨架
|
||||
return {"ok": True, "name": (proj_name or "工程") + "-审核版.cos4"}
|
||||
ext = xcos._source_ext(srow["src_name"])
|
||||
return {"ok": True, "name": (proj_name or "工程") + "-审核版" + ext}
|
||||
|
||||
@@ -3815,7 +3853,7 @@ def _export_session(sc, sid, fmt="", progress=None):
|
||||
"""导出=拿原文件当模板外科手术。返回 (字节, 文件名, 错误)。
|
||||
2026-10-19:SWT/SWZ 等新格式走 formats 适配器(骨架+填空);COS4/.COS 继续用
|
||||
export_cos 的专用引擎(保留逐节点保真)。
|
||||
决策 229:手工工程(无源文件)走经典整件骨架——fmt=cos4/cos 取骨架库代表件填空,
|
||||
决策 231:手工工程(无源文件)走经典整件骨架——fmt=cos4/cos 取骨架库代表件填空,
|
||||
fmt=xlsx 走 manual_import.export_excel_bytes(每单位工程一个 Excel 的 zip 包)。"""
|
||||
srow = sc.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
if not srow:
|
||||
@@ -3832,6 +3870,15 @@ def _export_session(sc, sid, fmt="", progress=None):
|
||||
_h.close()
|
||||
return None, None, "手工工程导出请选格式:cos4 / cos / Excel"
|
||||
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:
|
||||
@@ -5199,6 +5246,8 @@ def api_schema():
|
||||
{"name*": "工程名", "period_from*": "年*12+月", "period_to": "止期次",
|
||||
"tree*": "[{name, units:[{name, file?}]}],file=上传的 xlsx 路径(整单位工程覆盖)"},
|
||||
{"session_id": 5, "imported": "[{uw,n_div,n_item,n_prelim}]"}),
|
||||
r("GET", "/api/session/manual/export_unit", "单单位工程导 xlsx(决策 233;格式=231 Excel 通道单文件,可回导)",
|
||||
{"session_id*": "会话id", "uw*": "单位工程id"}),
|
||||
],
|
||||
"查询": [
|
||||
r("GET", "/api/session/raw/tree", "单位工程树",
|
||||
@@ -5254,9 +5303,9 @@ def api_schema():
|
||||
r("GET", "/api/session/edit/log", "字段编辑历史(红三角批注)"),
|
||||
],
|
||||
"导出": [
|
||||
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;手工工程 fmt=cos4/cos/xlsx 三选,决策 229)",
|
||||
r("GET", "/api/session/export", "导出审核版(zip 流;文件名=工程名-审核版.原后缀;手工工程 fmt=cos4/cos/xlsx 三选,决策 231)",
|
||||
{"session_id*": "", "token": "可选:进度上报令牌(决策 92)", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
|
||||
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;手工工程带 fmt,决策 229)",
|
||||
r("GET", "/api/session/export/meta", "导出建议名(先弹另存为再生成,决策 92;手工工程带 fmt,决策 231)",
|
||||
{"session_id*": "", "fmt": "可选:手工工程导出格式 cos4/cos/xlsx"}),
|
||||
r("GET", "/api/session/export/progress", "导出逐条目进度(轮询,决策 92)",
|
||||
{"token*": ""}),
|
||||
@@ -7813,6 +7862,22 @@ class Handler(SimpleHTTPRequestHandler):
|
||||
self.send_header("Content-Disposition", self._cd(fn, "manual_import_template.xlsx"))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
if p == "/api/session/manual/export_unit": # 手工工程:单单位工程导 xlsx(决策 233 方案a)
|
||||
con = sess.connect()
|
||||
try:
|
||||
raw, fn, err = mimp.export_unit_xlsx(
|
||||
con, int(one.get("session_id", 0) or 0), int(one.get("uw", 0) or 0))
|
||||
finally:
|
||||
con.close()
|
||||
if err or not raw:
|
||||
return self._json({"error": err or "导出失败"}, 400)
|
||||
self._allow_cache = True # 下载不能带 no-store(同模板下载)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Content-Disposition", self._cd(fn or "单位工程.xlsx", "manual_unit_export.xlsx"))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
# ---- 询价附件(项目工料机专用)----
|
||||
m = re.match(r"^/api/admin/batch/(\d+)/inq/lmes$", p) # 该项目全部工料机 + 绑定状态
|
||||
if m:
|
||||
|
||||
@@ -1,27 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""MCP 接入层(2026-10-15):把产品功能以 MCP 工具暴露给 AI harness(ZCode / WorkBuddy /
|
||||
DeepSeek 等一切支持 MCP 或会发 HTTP 的 agent)。
|
||||
"""MCP 接入层(2026-10-15 上线;2026-10-27 主人重定义:**只读**)。
|
||||
|
||||
- 传输:Streamable HTTP(POST /mcp,JSON-RPC 2.0,单响应 JSON;无 SSE/无会话态,stateless)
|
||||
- 开关:全局设置 mcp_enabled(**默认关**——断开就是连不上,403);令牌 mcp_token
|
||||
(首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查)
|
||||
- 收费挂钩:license enforce 时未激活/过期 → 整个端点 403 LICENSE_REQUIRED(开关开了也断)
|
||||
- 工具:全部复用 api_* 处理器(与界面同一套业务、写锁、分组缓存失效),**不另开第二通道**
|
||||
- 收费挂钩:license enforce 时未激活/过期(套餐范围外且临时卡失效)→ 整个端点
|
||||
403 LICENSE_REQUIRED(开关开了也断)
|
||||
- 工具(2026-10-27 主人定,共 5 个,**全部只读,无任何增删改/导出**):
|
||||
① bills_query 入库项目清单:编号/名称/项目特征/单价
|
||||
② lme_prices 工料机单价
|
||||
③ market_info_prices 市场价/信息价数据
|
||||
④ recent_review_query 工作台最近审核(口径同 ①②)
|
||||
⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律
|
||||
不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch
|
||||
(价格批次原件);不支持枚举、不支持全量下载
|
||||
- 零新增依赖:JSON-RPC 手写,只依赖标准库
|
||||
|
||||
Agent 注意(与 /api/schema 的 notes 一致):id 随重开变化;采纳 新行=覆盖/已有行=追加;
|
||||
工程量等数值一律字符串;导出前自动校验源文件哈希。
|
||||
"""
|
||||
import io
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import zipfile
|
||||
|
||||
PROTO_VERSION = "2025-06-18"
|
||||
_API = None # api_server 模块(bind 注入,避免循环导入)
|
||||
ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载
|
||||
|
||||
|
||||
def bind(api_module):
|
||||
@@ -64,10 +66,20 @@ def status():
|
||||
"endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具实现(复用 api_*)
|
||||
# ---------------------------------------------------------------- 工具实现(只读)
|
||||
|
||||
def _read(fn):
|
||||
"""只读工具:开只读连接跑 api_* 函数。"""
|
||||
def _hist(fn):
|
||||
"""历史库只读查询(入库项目 / 市场价信息价 / 附件绑定)。"""
|
||||
a = _api()
|
||||
con = a.conn()
|
||||
try:
|
||||
return fn(con)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _sess(fn):
|
||||
"""会话库只读查询(工作台最近审核)。"""
|
||||
a = _api()
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
@@ -76,220 +88,229 @@ def _read(fn):
|
||||
sc.close()
|
||||
|
||||
|
||||
def _write(fn):
|
||||
"""写工具:写锁 + 提交/回滚 + 分组缓存失效(与各路由分支同款守护)。"""
|
||||
a = _api()
|
||||
with a.WRITE_LOCK:
|
||||
sc = a.sess.connect()
|
||||
try:
|
||||
r = fn(sc)
|
||||
sc.commit()
|
||||
_sid = (r.get("sid") or 0) if isinstance(r, dict) else 0
|
||||
if isinstance(r, dict) and r.get("ok") and _sid:
|
||||
a._grp_cache_drop("session", int(_sid))
|
||||
return r
|
||||
except Exception as e:
|
||||
try:
|
||||
sc.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": False, "msg": "操作失败:%s" % e}
|
||||
finally:
|
||||
sc.close()
|
||||
|
||||
|
||||
def _t_sessions_list(args):
|
||||
return _api().api_sessions()
|
||||
|
||||
|
||||
def _t_project_open(args):
|
||||
return _api().api_audit(args)
|
||||
|
||||
|
||||
def _t_session_delete(args):
|
||||
return _api().api_session_delete(args)
|
||||
|
||||
|
||||
def _t_admin_import(args):
|
||||
a = _api()
|
||||
con = a.conn()
|
||||
def _paging(args):
|
||||
"""limit 归一:默认 50,1~200。"""
|
||||
try:
|
||||
return a.api_admin_import(con, args)
|
||||
finally:
|
||||
con.close()
|
||||
return min(max(int(args.get("limit") or 50), 1), 200)
|
||||
except (TypeError, ValueError):
|
||||
return 50
|
||||
|
||||
|
||||
def _t_tree(args):
|
||||
return _api().api_raw_tree(args)
|
||||
def _need_scope(args):
|
||||
"""查询范围守卫:keyword 或 batch_id 至少给一个(防空量拖库)。"""
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
try:
|
||||
bid = int(args.get("batch_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
bid = 0
|
||||
return kw, bid
|
||||
|
||||
|
||||
def _t_uw_detail(args):
|
||||
return _api().api_raw_uw(args)
|
||||
def _rows(con, sql, params):
|
||||
cur = con.execute(sql, params)
|
||||
cols = [d[0] for d in cur.description]
|
||||
return [dict(zip(cols, r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _t_session_rows(args):
|
||||
return _api().api_session_rows(args)
|
||||
def _t_bills_query(args):
|
||||
"""① 入库项目清单:Number(编号)/Name(名称)/Attr(项目特征)/Price(单价)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(清单编号/名称关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT b.id, b.batch_id, t.Name AS batch_name, b.Number, b.Name, b.Attr, b.Price "
|
||||
"FROM bills b JOIN batches t ON t.id = b.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND b.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (b.Number LIKE ? OR b.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY b.batch_id, b.x_seq LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_bill_op(args):
|
||||
return _write(lambda sc: _api().api_bill_op(sc, args))
|
||||
def _t_lme_prices(args):
|
||||
"""② 工料机单价:NoTaxPrice(除税)/TaxRate(税率)/TaxPrice(含税)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(工料机编号/名称/规格关键词)或 batch_id 之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT l.id, l.batch_id, t.Name AS batch_name, l.Number, l.Name, "
|
||||
"l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice "
|
||||
"FROM lmes l JOIN batches t ON t.id = l.batch_id "
|
||||
"WHERE t.kind='project'")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND l.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (l.Number LIKE ? OR l.Name LIKE ? OR l.Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * 3
|
||||
sql += " ORDER BY l.batch_id, l.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_norm_op(args):
|
||||
return _write(lambda sc: _api().api_norm_op(sc, args))
|
||||
def _t_market_info_prices(args):
|
||||
"""③ 市场价/信息价数据(价格批次明细)。"""
|
||||
kw, bid = _need_scope(args)
|
||||
if not kw and not bid:
|
||||
return {"ok": False, "msg": "请给 keyword(编号/名称关键词)或 batch_id(价格批次 id)之一"}
|
||||
lim = _paging(args)
|
||||
sql = ("SELECT p.id, p.batch_id, t.Name AS batch_name, t.x_publisher, p.Code, p.Name, "
|
||||
"p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Class "
|
||||
"FROM prices p JOIN batches t ON t.id = p.batch_id "
|
||||
"WHERE t.kind IN ('info', 'market')")
|
||||
params = []
|
||||
if bid:
|
||||
sql += " AND p.batch_id=?"
|
||||
params.append(bid)
|
||||
if kw:
|
||||
sql += " AND (p.Code LIKE ? OR p.Name LIKE ?)"
|
||||
params += ["%%%s%%" % kw, "%%%s%%" % kw]
|
||||
sql += " ORDER BY p.batch_id, p.id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _hist(lambda con: _rows(con, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_bill_adopt(args):
|
||||
a = _api()
|
||||
|
||||
def run(sc):
|
||||
hc = a.conn()
|
||||
try:
|
||||
return a.api_bill_adopt(sc, hc, args)
|
||||
finally:
|
||||
hc.close()
|
||||
return _write(run)
|
||||
|
||||
|
||||
def _t_bill_unadopt(args):
|
||||
a = _api()
|
||||
|
||||
def run(sc):
|
||||
hc = a.conn()
|
||||
try:
|
||||
return a.api_bill_unadopt(sc, hc, args)
|
||||
finally:
|
||||
hc.close()
|
||||
return _write(run)
|
||||
|
||||
|
||||
def _t_lme_merge_groups(args):
|
||||
return _read(lambda sc: _api()._lme_merge_groups(sc, int(args.get("session_id", 0))))
|
||||
|
||||
|
||||
def _t_lme_merge(args):
|
||||
return _write(lambda sc: _api().api_lme_merge(sc, args))
|
||||
|
||||
|
||||
def _t_session_remark(args):
|
||||
a = _api()
|
||||
|
||||
def run(sc):
|
||||
if args.get("lme_id"):
|
||||
a.sess.save_lme_remark(sc, int(args.get("lme_id", 0)), args.get("remark", ""))
|
||||
def _t_recent_review_query(args):
|
||||
"""④ 工作台最近审核:不带 session_id → 最近会话列表;带 session_id+type → 行数据
|
||||
(type=bills 口径同 ①,type=lmes 口径同 ②)。"""
|
||||
try:
|
||||
sid = int(args.get("session_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
sid = 0
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
kw = (args.get("keyword") or "").strip()
|
||||
lim = _paging(args)
|
||||
if not sid:
|
||||
rows = _sess(lambda sc: _rows(
|
||||
sc, "SELECT id, name, period_from, period_to, imported_at, x_total "
|
||||
"FROM sessions ORDER BY imported_at DESC LIMIT ?", (lim,)))
|
||||
return {"ok": True, "total": len(rows), "rows": rows,
|
||||
"hint": "带 session_id + type(bills/lmes)查行数据"}
|
||||
if typ not in ("bills", "lmes"):
|
||||
return {"ok": False, "msg": "type 必须是 bills 或 lmes(不带 type 时返回会话列表)"}
|
||||
if typ == "bills":
|
||||
sql = ("SELECT id, Number, Name, Attr, Price, Unit, Quantity "
|
||||
"FROM s_bills WHERE session_id=?")
|
||||
else:
|
||||
sql = ("SELECT id, Number, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice "
|
||||
"FROM s_lmes WHERE session_id=?")
|
||||
params = [sid]
|
||||
if kw:
|
||||
if typ == "bills":
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ?)"
|
||||
else:
|
||||
a.sess.save_remark(sc, int(args.get("bill_id", 0)), args.get("remark", ""))
|
||||
return {"ok": True}
|
||||
return _write(run)
|
||||
sql += " AND (Number LIKE ? OR Name LIKE ? OR Specification LIKE ?)"
|
||||
params += ["%%%s%%" % kw] * (2 if typ == "bills" else 3)
|
||||
sql += " ORDER BY id LIMIT ?"
|
||||
params.append(lim)
|
||||
rows = _sess(lambda sc: _rows(sc, sql, params))
|
||||
return {"ok": True, "total": len(rows), "rows": rows}
|
||||
|
||||
|
||||
def _t_schema(args):
|
||||
return _api().api_schema()
|
||||
|
||||
|
||||
def _t_batch_tree(args):
|
||||
return _api().api_admin_raw_tree(args)
|
||||
|
||||
|
||||
def _t_batch_uw(args):
|
||||
return _api().api_admin_raw_uw(args)
|
||||
|
||||
|
||||
def _t_session_export(args):
|
||||
"""导出 → 落盘 data/exports/,回文件路径(Agent 在本机直接可读)。"""
|
||||
def _t_attachment_download(args):
|
||||
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
|
||||
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
|
||||
type=batch → 价格批次原件(batches.x_attach_sha)。"""
|
||||
a = _api()
|
||||
sc = a.sess.connect()
|
||||
typ = (args.get("type") or "").strip().lower()
|
||||
try:
|
||||
raw, out_name, err = a._export_session(sc, int(args.get("session_id", 0) or 0))
|
||||
finally:
|
||||
sc.close()
|
||||
if err:
|
||||
return {"ok": False, "msg": err}
|
||||
out_dir = os.path.join(a.DATA_DIR, "exports")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
fp = os.path.join(out_dir, "%d_%s" % (int(time.time()), out_name))
|
||||
with open(fp, "wb") as f:
|
||||
f.write(raw)
|
||||
return {"ok": True, "path": fp, "bytes": len(raw), "name": out_name}
|
||||
rid = int(args.get("id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
rid = 0
|
||||
if typ not in ("bill", "lme", "batch") or not rid:
|
||||
return {"ok": False, "msg": "参数:type=bill|lme|batch + id(来自查询结果的行/批次 id)"}
|
||||
|
||||
def load(con):
|
||||
if typ == "bill":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM bill_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.bill_id=?", (rid,)), a.INQ_DIR
|
||||
if typ == "lme":
|
||||
return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 "
|
||||
"FROM lme_attach a JOIN inquiry_files f ON f.id=a.file_id "
|
||||
"WHERE a.lme_id=?", (rid,)), a.INQ_DIR
|
||||
return _rows(con, "SELECT at.original_name, at.stored_path, at.size, at.sha256 "
|
||||
"FROM attachments at WHERE at.sha256="
|
||||
"(SELECT x_attach_sha FROM batches WHERE id=?)", (rid,)), a.ATTACH_DIR
|
||||
|
||||
files, root = _hist(load)
|
||||
if not files:
|
||||
return {"ok": False, "msg": "没有绑定附件(或 id 不存在)"}
|
||||
out = []
|
||||
for f in files:
|
||||
fp = os.path.realpath(os.path.join(a.DATA_DIR, f["stored_path"] or ""))
|
||||
if os.path.commonpath([fp, os.path.realpath(root)]) != os.path.realpath(root):
|
||||
return {"ok": False, "msg": "附件路径不合法,拒绝读取"}
|
||||
try:
|
||||
with open(fp, "rb") as fh:
|
||||
raw = fh.read()
|
||||
except OSError as e:
|
||||
return {"ok": False, "msg": "附件读取失败:%s" % e}
|
||||
if len(raw) > ATT_MAX_DL:
|
||||
return {"ok": False, "msg": "《%s》超过 %d MB 下载上限,请在软件界面下载"
|
||||
% ((f["original_name"] or "")[:40], ATT_MAX_DL // 1024 // 1024)}
|
||||
out.append({"name": f["original_name"], "size": f["size"], "sha256": f["sha256"],
|
||||
"content_base64": base64.b64encode(raw).decode("ascii")})
|
||||
return {"ok": True, "files": out}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 工具清单
|
||||
|
||||
def _schema(paths, *names):
|
||||
"""从 /api/schema 事实源里摘路由描述(保证工具描述与接口同源)。"""
|
||||
try:
|
||||
s = _api().api_schema()
|
||||
out = []
|
||||
for g in s["groups"].values():
|
||||
for x in g:
|
||||
if x["path"] in paths:
|
||||
out.append(x)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def TOOLS():
|
||||
a = _api()
|
||||
return [
|
||||
{"name": "sessions_list", "description": "会话台账(已有审核工程列表)",
|
||||
"inputSchema": {"type": "object", "properties": {}}, "run": _t_sessions_list},
|
||||
{"name": "project_open", "description": "打开工程→解析→建/续会话(同名=原地续用)。"
|
||||
"path 必须是软件目录内的文件(先 upload_file)", "inputSchema": {"type": "object",
|
||||
"properties": {k: {"type": "string"} for k in ("path", "name", "province", "city", "district",
|
||||
"period_from", "period_to", "file_kind")},
|
||||
"required": ["path", "name", "period_from"]}, "run": _t_project_open},
|
||||
{"name": "session_delete", "description": "删会话(连同无引用的源文件副本)",
|
||||
"inputSchema": {"type": "object", "properties": {"ids": {"type": "array", "items": {"type": "integer"}}},
|
||||
"required": ["ids"]}, "run": _t_session_delete},
|
||||
{"name": "upload_file", "description": "上传本机文件进软件(base64 内容),返回软件内 path",
|
||||
"inputSchema": {"type": "object", "properties": {"name": {"type": "string"},
|
||||
"content_base64": {"type": "string"}}, "required": ["name", "content_base64"]},
|
||||
"run": lambda args: _api().api_upload(args)},
|
||||
{"name": "admin_import", "description": "导入后台批次(=采纳源库)",
|
||||
"inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "name": {"type": "string"},
|
||||
"kind": {"type": "string"}, "force": {"type": "boolean"}}, "required": ["path", "name"]},
|
||||
"run": _t_admin_import},
|
||||
{"name": "session_tree", "description": "会话单位工程树",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
|
||||
"required": ["session_id"]}, "run": _t_tree},
|
||||
{"name": "uw_detail", "description": "单位工程内清单树(含定额/工料机)",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"uw_id": {"type": "string"}, "tab": {"type": "string"}},
|
||||
"required": ["session_id", "uw_id"]}, "run": _t_uw_detail},
|
||||
{"name": "session_rows", "description": "清单/工料机行数据",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"type": {"type": "string"}}, "required": ["session_id", "type"]}, "run": _t_session_rows},
|
||||
{"name": "bill_op", "description": "清单增删改:insert_above/insert_below/del/tdel/untdel/edit",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"op": {"type": "string"}, "bill_id": {"type": "integer"},
|
||||
"fields": {"type": "object"}}, "required": ["op", "bill_id"]}, "run": _t_bill_op},
|
||||
{"name": "norm_op", "description": "定额增删改:ntdel/unntdel/unadopt(取消采纳)或 fields 行内编辑",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"op": {"type": "string"}, "norm_id": {"type": "integer"},
|
||||
"fields": {"type": "object"}}}, "run": _t_norm_op},
|
||||
{"name": "bill_adopt", "description": "采纳(新行=覆盖,已有行=追加,原定额转临删)",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"bill_id": {"type": "integer"}, "src_bill_id": {"type": "integer"}},
|
||||
"required": ["session_id", "bill_id", "src_bill_id"]}, "run": _t_bill_adopt},
|
||||
{"name": "bill_unadopt", "description": "清单级取消采纳",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"bill_id": {"type": "integer"}}, "required": ["session_id", "bill_id"]},
|
||||
"run": _t_bill_unadopt},
|
||||
{"name": "lme_merge_groups", "description": "工料机合并分组(同名/近似)",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
|
||||
"required": ["session_id"]}, "run": _t_lme_merge_groups},
|
||||
{"name": "lme_merge", "description": "合并改价+隐藏",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"},
|
||||
"groups": {"type": "array"}}, "required": ["session_id", "groups"]}, "run": _t_lme_merge},
|
||||
{"name": "session_remark", "description": "清单审核备注(持久化)",
|
||||
"inputSchema": {"type": "object", "properties": {"bill_id": {"type": "integer"},
|
||||
"remark": {"type": "string"}}, "required": ["bill_id", "remark"]}, "run": _t_session_remark},
|
||||
{"name": "session_export", "description": "导出审核版(zip 落盘 data/exports/,返回本机路径)",
|
||||
"inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}},
|
||||
"required": ["session_id"]}, "run": _t_session_export},
|
||||
{"name": "api_schema", "description": "产品全部接口清单(工具未覆盖的功能用它走 HTTP)",
|
||||
"inputSchema": {"type": "object", "properties": {}}, "run": _t_schema},
|
||||
{"name": "bills_query",
|
||||
"description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。"
|
||||
"keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 50 上限 200。"
|
||||
"响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_bills_query},
|
||||
{"name": "lme_prices",
|
||||
"description": "查入库项目的工料机单价:编号、名称、规格、单位、除税价 NoTaxPrice、"
|
||||
"税率 TaxRate、含税价 TaxPrice。keyword 或 batch_id 至少一个。响应不含附件信息。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_lme_prices},
|
||||
{"name": "market_info_prices",
|
||||
"description": "读市场价/信息价批次明细:Code、Name、Specification、Unit、三价、Class。"
|
||||
"keyword(编号/名称)或 batch_id(价格批次 id)至少一个。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"keyword": {"type": "string"}, "batch_id": {"type": "integer"},
|
||||
"limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_market_info_prices},
|
||||
{"name": "recent_review_query",
|
||||
"description": "读工作台最近审核:不带参数=最近会话列表;session_id + type(bills=清单"
|
||||
"编号/名称/项目特征/单价,lmes=工料机单价)查该会话行数据,口径与"
|
||||
"bills_query / lme_prices 一致。可选 keyword 过滤。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"session_id": {"type": "integer"}, "type": {"type": "string"},
|
||||
"keyword": {"type": "string"}, "limit": {"type": "integer"}},
|
||||
"required": []},
|
||||
"run": _t_recent_review_query},
|
||||
{"name": "attachment_download",
|
||||
"description": "下载绑定附件。**仅在用户明确要求下载附件时调用**(查询结果不含附件信息,"
|
||||
"不得主动调用)。id 必须来自查询结果:type=bill/lme 用 bills_query/"
|
||||
"lme_prices/recent_review_query 返回的行 id;type=batch 用价格批次 id"
|
||||
"(批次原件)。不支持枚举或全量下载。",
|
||||
"inputSchema": {"type": "object", "properties": {
|
||||
"type": {"type": "string"}, "id": {"type": "integer"}},
|
||||
"required": ["type", "id"]},
|
||||
"run": _t_attachment_download},
|
||||
]
|
||||
|
||||
|
||||
@@ -314,7 +335,7 @@ def _dispatch(msg):
|
||||
return False, _rpc_result(cid, {
|
||||
"protocolVersion": PROTO_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "造价审核", "version": "mcp-1.0"}})
|
||||
"serverInfo": {"name": "造价审核", "version": "mcp-2.0"}})
|
||||
if method == "ping":
|
||||
return False, _rpc_result(cid, {})
|
||||
if method == "tools/list":
|
||||
@@ -343,7 +364,7 @@ def _dispatch(msg):
|
||||
|
||||
def handle_post(auth_header, body_text):
|
||||
"""POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。
|
||||
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时未激活/过期整端点断)。"""
|
||||
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时套餐范围外且临时卡失效整端点断)。"""
|
||||
a = _api()
|
||||
if not enabled():
|
||||
return 403, {"jsonrpc": "2.0", "id": None,
|
||||
|
||||
@@ -59,7 +59,7 @@ class _BridgeApi:
|
||||
"""决策 92(主人定流程):点导出=①先弹原生另存为选路径(此刻还不生成,大工程不再干等)
|
||||
→②后台线程生成+分块写盘(逐条目进度经 evaluate_js 推给页面进度条)
|
||||
→③完成/失败也推给页面(模态收尾或后台 toast)。
|
||||
决策 229:fmt=cos4/cos/xlsx——手工工程导出三选,meta 与生成 URL 都带上。"""
|
||||
决策 231:fmt=cos4/cos/xlsx——手工工程导出三选,meta 与生成 URL 都带上。"""
|
||||
try:
|
||||
sid = int(session_id)
|
||||
except Exception:
|
||||
|
||||
20
CostReview/app/tests/_dbg_clone_test.py
Normal file
20
CostReview/app/tests/_dbg_clone_test.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import io, zipfile
|
||||
from xml.etree import ElementTree as ET
|
||||
from api_harness import PERIOD_202607, post, server # noqa: F401
|
||||
from test_manual_export import _seed_skeleton, _create_manual
|
||||
|
||||
def test_dbg(server):
|
||||
_seed_skeleton(server)
|
||||
sid = _create_manual(server) # 单单位既有流程
|
||||
resp = server["client"].get("/api/session/export",
|
||||
params={"session_id": sid, "fmt": "cos4"})
|
||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||||
for i in z.infolist():
|
||||
if not i.filename.lower().endswith(".xml"): continue
|
||||
try:
|
||||
ET.fromstring(z.read(i.filename)); print("OK ", i.filename)
|
||||
except Exception as e:
|
||||
print("BAD", i.filename, e)
|
||||
t = z.read(i.filename).decode("utf-8", "replace").split("\n")
|
||||
for k in range(26, min(36, len(t))):
|
||||
print(" %3d| %s" % (k + 1, t[k][:140]))
|
||||
14
CostReview/app/tests/_dbg_e2e.py
Normal file
14
CostReview/app/tests/_dbg_e2e.py
Normal file
@@ -0,0 +1,14 @@
|
||||
import io, sys, zipfile
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, ".")
|
||||
from api_harness import PERIOD_202607, post
|
||||
import test_frame_skeleton as tf
|
||||
|
||||
# 复用 frame 夹具跑同流程,打印导出错误
|
||||
srv = None
|
||||
import subprocess, time, socket, shutil, os
|
||||
root = Path("../_dbg_framesrv")
|
||||
if root.exists(): shutil.rmtree(root)
|
||||
srv = {"client": None}
|
||||
# 直接调 fserver 夹具太绕——用 pytest 的夹具跑一次并在测试里打印
|
||||
import api_harness
|
||||
292
CostReview/app/tests/test_frame_skeleton.py
Normal file
292
CostReview/app/tests/test_frame_skeleton.py
Normal file
@@ -0,0 +1,292 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 231 补记五(2026-10-28,主人定「这2个可以当做经典骨架收藏」):专用骨架件回归。
|
||||
|
||||
口径:①专用骨架判定(文件名含 骨架/架子,或 单位≥5 且空单位位占比≥50%)→ classic_skel
|
||||
is_frame=1,**同后缀唯一、后传顶旧**,优先于实项目件当导出代表;②根层 LME_SUM=单位级
|
||||
汇总表(易达标准骨架铁证,推翻补记三「清空」定论)→ 导出灌**现算行**(定额工程量×
|
||||
消耗量,dyn 引擎)+台班子级组成;③采纳补子工料机(批次 lme_res → 会话 s_lme_res,
|
||||
缺则补不重复)。
|
||||
真实骨架件:后台需要导入的项目/1易达导出骨架.cos4(31 单位位)、2广联达导出架子.COS4
|
||||
(19 单位位);采纳来源:合并工料机测试(原).cos4。
|
||||
独立隔离服务(专用骨架会顶掉共享夹具里 cos4 代表,须另起副本)。"""
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_harness import PERIOD_202607 # noqa: F401
|
||||
from test_api_p1 import raw_post
|
||||
|
||||
_APP_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
sys.path.insert(0, os.path.join(_APP_SRC, "core"))
|
||||
import classic_skeleton as _cs # noqa: E402 (升级添加骨架的入库口)
|
||||
|
||||
|
||||
def _seed_frame(server, path, name):
|
||||
con = sqlite3.connect(server["db"])
|
||||
try:
|
||||
sig = _cs.seed_frame(con, str(path), name)
|
||||
assert sig, "升级入库失败:%s" % name
|
||||
finally:
|
||||
con.close()
|
||||
return name
|
||||
_FRAME1 = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "1易达导出骨架.cos4"
|
||||
# 广联达骨架以 .COS4 版为准(主人原生 .GBQ7 是二进制专有格式,软件不收;
|
||||
# 2026-10-28 换新:广联达导出最新架子.COS4=同签名更全样本件,旧 30-解密件已由主人替换);
|
||||
# .COS4 版不在本机时相应断言跳过(顶旧机制用改名副本验证,不依赖该件)。
|
||||
_FRAME2 = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "广联达导出最新架子.COS4"
|
||||
_REAL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "吉大街道园林花园老旧小区环境整治提升工程施工.cos4"
|
||||
_SRC_BILL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "合并工料机测试(原).cos4"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fserver(tmp_path_factory):
|
||||
"""独立隔离服务(与 api_harness.server 同款,专用骨架不污染共享夹具的骨架库)。"""
|
||||
root = tmp_path_factory.mktemp("framesrv")
|
||||
shutil.copytree(_APP_SRC, os.path.join(root, "CostReview", "app"),
|
||||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
||||
src_dir = os.path.join(root, "后台需要导入的项目")
|
||||
os.makedirs(src_dir)
|
||||
lic = os.path.join(root, "lic")
|
||||
os.makedirs(lic)
|
||||
open(os.path.join(lic, "config.json"), "w").write('{"enforce": false}')
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
log = open(os.path.join(root, "server.log"), "wb")
|
||||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
||||
cwd=os.path.join(root, "CostReview", "app"),
|
||||
env=dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=lic),
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
client = httpx.Client(base_url="http://127.0.0.1:%d" % port, timeout=120)
|
||||
for _ in range(100):
|
||||
try:
|
||||
if client.get("/api/license/status").status_code == 200:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
else:
|
||||
proc.kill()
|
||||
raise RuntimeError("frame 测试服务未就绪")
|
||||
yield {"client": client, "root": str(root), "src_dir": src_dir,
|
||||
"db": os.path.join(root, "CostReview", "data", "history.db"),
|
||||
"sessdb": os.path.join(root, "CostReview", "data", "session.db")}
|
||||
client.close()
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(10)
|
||||
except Exception:
|
||||
proc.kill()
|
||||
log.close()
|
||||
|
||||
|
||||
def _db(server):
|
||||
con = sqlite3.connect(server["db"])
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
|
||||
def test_frame_pin_and_replace(fserver):
|
||||
"""补记十二终版:上传口**不再自动收骨架**;骨架只经升级(seed_frame)入库;
|
||||
命名不带软件名(COS4骨架G/Y);固定后上传不顶不改名;实项目不夺骨架。"""
|
||||
assert _FRAME1.exists() and _FRAME2.exists(), "两件骨架不在本机"
|
||||
con = _db(fserver)
|
||||
try:
|
||||
# ① 上传口上传骨架件 → 不收藏(连表都不建)
|
||||
assert raw_post(fserver, "/api/admin/upload",
|
||||
_FRAME1.name, _FRAME1.read_bytes())["ok"]
|
||||
r1 = con.execute("SELECT COUNT(*) FROM sqlite_master "
|
||||
"WHERE name='classic_skel'").fetchone()[0]
|
||||
assert r1 == 0, "上传口不该收藏任何骨架"
|
||||
# ② 升级入库:两件经典骨架(G/Y 命名)
|
||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y")
|
||||
_seed_frame(fserver, _FRAME2, "COS4骨架G")
|
||||
rows = con.execute("SELECT original_name FROM classic_skel "
|
||||
"WHERE suffix='cos4' AND is_frame=1 ORDER BY original_name").fetchall()
|
||||
assert [r["original_name"] for r in rows] == ["COS4骨架G", "COS4骨架Y"], [dict(r) for r in rows]
|
||||
# ③ 固定后再上传骨架原件 → 不顶、不改名
|
||||
assert raw_post(fserver, "/api/admin/upload", _FRAME2.name, _FRAME2.read_bytes())["ok"]
|
||||
rows2 = con.execute("SELECT original_name FROM classic_skel "
|
||||
"WHERE suffix='cos4' AND is_frame=1 ORDER BY original_name").fetchall()
|
||||
assert [r["original_name"] for r in rows2] == ["COS4骨架G", "COS4骨架Y"], [dict(r) for r in rows2]
|
||||
# ④ 实项目件照收但不夺骨架
|
||||
assert raw_post(fserver, "/api/admin/upload", _REAL.name, _REAL.read_bytes())["ok"]
|
||||
top = con.execute("SELECT original_name, is_frame FROM classic_skel "
|
||||
"WHERE suffix='cos4' ORDER BY is_frame DESC, n_nodes DESC "
|
||||
"LIMIT 1").fetchone()
|
||||
assert top["is_frame"] == 1, "实项目夺了骨架代表"
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def test_frame_export_e2e(fserver):
|
||||
"""端到端:骨架代表+Excel 手工工程+采纳(带子级)→骨架导出=
|
||||
全成员 XML 合法/根层单位级汇总行=现算(含子级容器)/项目级 PIWC 行=现算/我方清单在。"""
|
||||
# 骨架:升级入库(补记十二——上传口不再自动收骨架;防御性重入,不依赖上一用例)
|
||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y")
|
||||
# 采纳来源批次(合并工料机测试件:含台班子级组成)
|
||||
assert _SRC_BILL.exists(), "采纳来源件不在本机"
|
||||
up = raw_post(fserver, "/api/admin/upload", _SRC_BILL.name, _SRC_BILL.read_bytes())
|
||||
assert up["ok"] is True, up
|
||||
from api_harness import META
|
||||
r = fserver["client"].post("/api/admin/import",
|
||||
json=dict(META, path=up["path"], name="骨架来源批次",
|
||||
file_kind=1))
|
||||
assert r.json().get("ok"), r.text[:200]
|
||||
bid = r.json()["batch_id"]
|
||||
# 用来源件前两清单造 Excel(同款字段)
|
||||
sys.path.insert(0, os.path.join(_APP_SRC, "core"))
|
||||
import import_job
|
||||
out = {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1, "cur_uw": -1,
|
||||
"bill_uw": [], "bill_kind": [], "prelim_raw": 0, "bill_raw": 0, "bill_skip": 0,
|
||||
"bill_skip_zero": 0, "lme_raw": 0, "lme_skip": 0, "proj_name": "",
|
||||
"file_kind": None, "bulid_unit": "", "total": None}
|
||||
import_job.parse_file(str(_SRC_BILL), out)
|
||||
picks = [(i, b) for i, b in enumerate(out["bills"])
|
||||
if out["bill_kind"][i] != "prelim"][:2]
|
||||
from openpyxl import Workbook
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "分部分项"
|
||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
||||
ws.append(["单位工程", "", "分部", "骨架测试分部", "", "", "", ""])
|
||||
for _i, b in picks:
|
||||
ws.append(["骨架测试分部", b[0] or "", "清单", b[1] or "", b[2] or "",
|
||||
b[3] or "", float(b[4] or 0), float(b[5] or 0)])
|
||||
ws2 = wb.create_sheet("措施项目")
|
||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
||||
fp = os.path.join(fserver["src_dir"], "frame_unit.xlsx")
|
||||
wb.save(fp)
|
||||
r = fserver["client"].post("/api/session/manual/save", json={
|
||||
"sid": 0, "name": "骨架导出测试", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": "单项",
|
||||
"units": [{"id": 0, "name": "我方单位", "file": fp}]}]})
|
||||
assert r.json().get("ok"), r.text[:300]
|
||||
sid = r.json()["session_id"]
|
||||
# 精确配对采纳
|
||||
con = sqlite3.connect(fserver["db"])
|
||||
con.row_factory = sqlite3.Row
|
||||
try:
|
||||
batch = {(r2["Number"] or "", r2["Name"] or ""): r2["id"] for r2 in con.execute(
|
||||
"SELECT id, Number, Name FROM bills WHERE batch_id=?", (bid,))}
|
||||
finally:
|
||||
con.close()
|
||||
cs = sqlite3.connect(fserver["sessdb"])
|
||||
cs.row_factory = sqlite3.Row
|
||||
try:
|
||||
sess = [(r2["id"], r2["Number"] or "", r2["Name"] or "") for r2 in cs.execute(
|
||||
"SELECT id, Number, Name FROM s_bills WHERE session_id=?", (sid,))]
|
||||
finally:
|
||||
cs.close()
|
||||
con = sqlite3.connect(fserver["db"])
|
||||
n_child = con.execute("SELECT COUNT(*) FROM lme_res").fetchone()[0]
|
||||
con.close()
|
||||
for bid_, num, name in sess:
|
||||
src = batch.get((num, name))
|
||||
assert src, "批次缺清单 %s" % num
|
||||
ra = fserver["client"].post("/api/session/bill/adopt",
|
||||
json={"session_id": sid, "bill_id": bid_,
|
||||
"src_bill_id": src})
|
||||
assert ra.json().get("ok"), ra.text[:200]
|
||||
# 采纳应把子级组成补进会话
|
||||
cs = sqlite3.connect(fserver["sessdb"])
|
||||
n_sres = cs.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=?", (sid,)).fetchone()[0]
|
||||
child_codes = {r[0] for r in cs.execute(
|
||||
"SELECT DISTINCT res_code FROM s_lme_res WHERE session_id=?", (sid,)).fetchall()}
|
||||
n_lib = cs.execute("SELECT COUNT(*) FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()[0]
|
||||
uwid = cs.execute("SELECT id FROM s_unit_works WHERE session_id=?", (sid,)).fetchone()[0]
|
||||
cs.close()
|
||||
assert n_sres > 0 or n_child == 0, "采纳没补子级组成(批次 lme_res=%d)" % n_child
|
||||
assert n_lib > 0 or n_child == 0, "采纳没带组成子码价格快照(s_lme_lib=0)"
|
||||
# 骨架导出
|
||||
resp = fserver["client"].get("/api/session/export",
|
||||
params={"session_id": sid, "fmt": "cos4"})
|
||||
assert resp.status_code == 200, resp.text[:300]
|
||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||||
LME = "LabourMaterialsEquipmentsMachinesSummary"
|
||||
unit_root = proj_rows = None
|
||||
for nm in z.namelist():
|
||||
if not nm.lower().endswith(".xml"):
|
||||
continue
|
||||
root = ET.fromstring(z.read(nm)) # 全成员必须 XML 合法
|
||||
if root.tag == "UnitWorks" and (root.get("Name") or "") == "我方单位":
|
||||
unit_root = [c for c in root if c.tag == LME]
|
||||
if root.tag != "UnitWorks":
|
||||
for piwc in root.iter("ProjectInstallationWorkCost"):
|
||||
proj_rows = [c for c in piwc if c.tag == LME]
|
||||
assert unit_root is not None, "导出件没有我方单位成员"
|
||||
assert len(unit_root) > 0, "单位级汇总行没灌(根层 LME_SUM 空)"
|
||||
# 子级容器行(台班):行含子 LME_SUM
|
||||
has_container = any(len(c) > 0 for c in unit_root)
|
||||
if n_child:
|
||||
assert has_container or n_sres == 0, "台班子级行没挂(s_lme_res=%d)" % n_sres
|
||||
# 组成子码自有行(2026-10-28:主人实测易达映射源组成子行编制价全空后的补行)——
|
||||
# 纯组成码也要各有一行自己的价(s_lme_lib 快照;原生件铁证:折旧费/检修费同表自有行)
|
||||
flat_codes = {c.get("Number") for c in unit_root if not len(c)}
|
||||
own = child_codes & flat_codes
|
||||
assert own or not (child_codes and n_lib), \
|
||||
"组成子码没有自有价行(子码 %s 全不在表里)" % sorted(child_codes)[:3]
|
||||
if own:
|
||||
c0 = next(c for c in unit_root if not len(c) and c.get("Number") in own)
|
||||
assert c0.get("NoTaxPrice") not in (None, ""), "组成自有行没带价"
|
||||
if proj_rows is not None:
|
||||
assert len(proj_rows) > 0 or n_sres == 0
|
||||
# 我方清单在
|
||||
found = False
|
||||
for nm in z.namelist():
|
||||
if nm.lower().endswith(".xml") and picks[0][1][1].encode("utf-8") in z.read(nm):
|
||||
found = True
|
||||
break
|
||||
assert found, "我方清单没进导出件"
|
||||
|
||||
|
||||
def test_normal_cos4_via_frame(fserver):
|
||||
"""补记十二(2026-10-28 主人定「推翻:审核版不再基于原文件」):普通(源文件)
|
||||
工程 cos4 导出也走经典骨架——骨架成员名进件、会话数据灌入,数据流不变。"""
|
||||
assert _SRC_BILL.exists(), "合并工料机测试(原).cos4 不在本机"
|
||||
_seed_frame(fserver, _FRAME1, "COS4骨架Y") # 自足:升级入库两件经典骨架
|
||||
_seed_frame(fserver, _FRAME2, "COS4骨架G")
|
||||
up = raw_post(fserver, "/api/admin/upload", _SRC_BILL.name, _SRC_BILL.read_bytes())
|
||||
r = fserver["client"].post("/api/audit", json={
|
||||
"name": "普通cos4走骨架T", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607, "file_kind": 1, "path": up["path"]}).json()
|
||||
assert r.get("ok"), r
|
||||
sid = r["session_id"]
|
||||
resp = fserver["client"].get("/api/session/export",
|
||||
params={"session_id": sid, "fmt": "cos4"})
|
||||
assert resp.status_code == 200 and resp.content[:2] == b"PK", resp.content[:200]
|
||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||||
infos = [i for i in z.infolist() if i.filename.lower().endswith(".xml")]
|
||||
# 成员是骨架的位(我是单位工程N 系列),不是源文件自己的成员(单位工程1/@_5155…)
|
||||
names = set()
|
||||
for i in infos:
|
||||
try:
|
||||
raw = i.filename.encode("utf-8") if (i.flag_bits & 0x800) \
|
||||
else i.filename.encode("cp437")
|
||||
names.add(raw.decode("gbk"))
|
||||
except UnicodeDecodeError:
|
||||
names.add(i.filename)
|
||||
assert any("我是单位工程" in n for n in names), sorted(names)[:6]
|
||||
assert not any(n.endswith("_单位工程1.xml") for n in names), "源文件自己的成员名不该出现在骨架导出里"
|
||||
# 会话数据在(原工程自己的清单内容)
|
||||
rows = fserver["client"].get("/api/session/rows",
|
||||
params={"session_id": sid, "type": "bill"}).json()["rows"]
|
||||
assert rows, "会话没数据"
|
||||
cands = [str(c) for x in rows[:5] for c in x[1:6]
|
||||
if c and not str(c).replace(".", "").isdigit() and len(str(c)) >= 3]
|
||||
body = b"".join(z.read(i) for i in z.infolist()
|
||||
if i.filename.lower().endswith(".xml"))
|
||||
assert cands and any(c.encode("utf-8") in body for c in cands), "会话清单没进骨架导出件:%s" % cands[:3]
|
||||
@@ -1,15 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 229(2026-10-27 主人定):经典整件骨架库 + 手工工程导出(cos4/cos/Excel)回归。
|
||||
"""决策 231(2026-10-27 主人定):经典整件骨架库 + 手工工程导出(cos4/cos/Excel)回归。
|
||||
|
||||
口径:①公共上传口自动收骨架(后台导入与工作台打开工程同口,失败不挡上传);
|
||||
②同签名只存最全代表(不一定最新,平手取最新,不跨件拼合),连保留值存 history.db;
|
||||
③手工导出 cos/cos4=骨架整件当模板:参考清单行全换我方、定额/工料机架子克隆清值、
|
||||
③手工导出 cos/cos4=骨架整件当模板:参考清单行全换我方、**有采纳定额/工料机挂真实值
|
||||
(231 补记:和标准采纳一样)、未采纳清单克隆架子清值(231①,2026-10-28 复确认)**、
|
||||
我方分部层级递归映射 DivisionalWorks 嵌套、单位/单项/工程名落我方(引用 Number 不动)、
|
||||
工料机汇总空槽、容器/单位合计现算、其余保留值;
|
||||
工料机汇总=现算行挂真/无采纳空槽、容器/单位合计现算、其余保留值;
|
||||
④Excel 导出=项目名文件夹/单位工程.xlsx(230 模板架子+合价/备注),可直接回导入;
|
||||
⑤普通工程导出路径不受影响(fmt 缺省照旧走原格式引擎)。
|
||||
造数仅写隔离副本(api_harness 临时目录),生产库零接触。"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import zipfile
|
||||
@@ -50,8 +52,9 @@ SKEL_UNIT = """<?xml version="1.0" encoding="utf-8"?>
|
||||
<SummaryOfBasicCost Total="1111.00"/>
|
||||
</UnitWorksPreliminaryWorkElement>
|
||||
</Preliminaries>
|
||||
<LabourMaterialsEquipmentsMachinesSummary>
|
||||
<LabourMaterialsEquipmentsMachinesElement Number="000009" Name="骨架汇总工料机" Quantity="99" NoTaxPrice="9" TaxPrice="10"/>
|
||||
<LabourMaterialsEquipmentsMachinesSummary Number="000009" Name="骨架汇总工料机" Specification="" Unit="工日" Kind="1" Quantity="99" NoTaxPrice="9" TaxPrice="10"/>
|
||||
<LabourMaterialsEquipmentsMachinesSummary Number="990101015" Name="骨架台班" Specification="" Unit="台班" Kind="7" Quantity="3" NoTaxPrice="500" TaxPrice="565">
|
||||
<LabourMaterialsEquipmentsMachinesSummary Number="00010010" Name="机上人工" Specification="" Unit="工日" Kind="1" Quantity="1" NoTaxPrice="9" TaxPrice="10"/>
|
||||
</LabourMaterialsEquipmentsMachinesSummary>
|
||||
</UnitWorks>"""
|
||||
|
||||
@@ -87,9 +90,19 @@ def _skel_bytes():
|
||||
|
||||
|
||||
def _seed_skeleton(server, fname="骨架样本T.cos4"):
|
||||
up = raw_post(server, "/api/admin/upload", fname, _skel_bytes())
|
||||
assert up["ok"] is True, up
|
||||
return up
|
||||
"""补记十四:上传口不再收藏骨架——测试骨架走升级口(seed_frame)入库。"""
|
||||
import sys as _sys
|
||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||||
import classic_skeleton as _cs
|
||||
import tempfile
|
||||
p = os.path.join(server["src_dir"], fname)
|
||||
open(p, "wb").write(_skel_bytes())
|
||||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||||
try:
|
||||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
||||
finally:
|
||||
con.close()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _mk_xlsx(server, fname="unit_export_t.xlsx"):
|
||||
@@ -131,59 +144,24 @@ def _unit_xml_of(data):
|
||||
raise AssertionError("导出件里没有单位工程成员")
|
||||
|
||||
|
||||
def test_seed_and_rep_in_history(server):
|
||||
"""上传口收骨架:classic_skel 一组一行,连代表件字节入库(决策 229)。"""
|
||||
_seed_skeleton(server)
|
||||
db = next(server["root"].rglob("history.db"))
|
||||
con = sqlite3.connect(str(db))
|
||||
try:
|
||||
row = con.execute("SELECT suffix, original_name, n_shapes, n_nodes, blob FROM classic_skel").fetchone()
|
||||
assert row, "骨架没有入库"
|
||||
assert row[0] == "cos4" and row[3] > 0
|
||||
assert row[4][:2] == b"PK", "代表件整件字节没存"
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def test_seed_grouping_and_replacement(server):
|
||||
"""收集规则(主人定):不同字段集各成组都收;同签名更全的顶掉代表;
|
||||
平手取最新;更瘦的不动。"""
|
||||
def test_no_auto_collect_and_seed_only(server):
|
||||
"""补记十四:上传口**不再收藏骨架**(classic_skel 只有升级进的骨架);
|
||||
升级口 seed_frame 同名替换、新名新增。"""
|
||||
con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||||
try:
|
||||
base = _skel_bytes()
|
||||
_seed_skeleton(server, "第一件.cos4")
|
||||
n0, name0 = con.execute(
|
||||
"SELECT n_nodes, original_name FROM classic_skel WHERE suffix='cos4'").fetchone()
|
||||
# 同结构多一条清单=同签名、内容更全 → 顶掉
|
||||
i0 = SKEL_UNIT.index('<WorkElement Number="990101001001"')
|
||||
i1 = SKEL_UNIT.index("</WorkElement>", i0) + len("</WorkElement>")
|
||||
unit_fat = SKEL_UNIT[:i1] + SKEL_UNIT[i0:i1] + SKEL_UNIT[i1:]
|
||||
fatter = _zip_bytes(unit_fat, SKEL_PROJ)
|
||||
assert raw_post(server, "/api/admin/upload", "更全件.cos4", fatter)["ok"]
|
||||
n1, name1 = con.execute(
|
||||
"SELECT n_nodes, original_name FROM classic_skel WHERE suffix='cos4'").fetchone()
|
||||
assert n1 > n0 and name1 == "更全件.cos4", (n0, n1, name0, name1)
|
||||
# 平手取最新:同字节换名再传 → 代表名更新
|
||||
assert raw_post(server, "/api/admin/upload", "平手件.cos4", fatter)["ok"]
|
||||
name2 = con.execute(
|
||||
"SELECT original_name FROM classic_skel WHERE suffix='cos4'").fetchone()[0]
|
||||
assert name2 == "平手件.cos4", name2
|
||||
# 更瘦的不动:原(少一条清单)再传 → 仍是平手件
|
||||
assert raw_post(server, "/api/admin/upload", "更瘦件.cos4", base)["ok"]
|
||||
name3 = con.execute(
|
||||
"SELECT original_name FROM classic_skel WHERE suffix='cos4'").fetchone()[0]
|
||||
assert name3 == "平手件.cos4", name3
|
||||
# 不同字段集=不同组,都收(10 字段/15 字段场景)
|
||||
widened = _zip_bytes(unit_fat.replace(
|
||||
'<WorkElement Number="990101001001"',
|
||||
'<WorkElement ExtraField="1" Number="990101001001"', 1), SKEL_PROJ)
|
||||
assert raw_post(server, "/api/admin/upload", "宽字段件.cos4", widened)["ok"]
|
||||
assert con.execute("SELECT COUNT(*) FROM classic_skel WHERE suffix='cos4'"
|
||||
).fetchone()[0] == 2, "不同字段集应各成一组"
|
||||
assert raw_post(server, "/api/admin/upload", "普通件.cos4", _skel_bytes())["ok"]
|
||||
n = con.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='classic_skel'").fetchone()[0]
|
||||
assert n == 0, "上传口不该再收藏任何骨架(表都不该建)"
|
||||
import sys as _sys
|
||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||||
import classic_skeleton as _cs
|
||||
p = os.path.join(server["src_dir"], "升骨架T.cos4")
|
||||
open(p, "wb").write(_skel_bytes())
|
||||
assert _cs.seed_frame(con, p, "COS4骨架T")
|
||||
assert con.execute("SELECT COUNT(*) FROM classic_skel WHERE is_frame=1").fetchone()[0] == 1
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def test_export_meta_manual(server):
|
||||
"""meta:手工工程 fmt=cos4/cos/xlsx 给建议名;不带 fmt 明确报错(不再误导补传)。"""
|
||||
sid = _create_manual(server)
|
||||
@@ -217,19 +195,18 @@ def test_manual_export_cos4(server):
|
||||
assert re.search(r'<DivisionalWorks\b[^>]*Name="我方二级分部"', unit[m1.end():e1]), \
|
||||
"子分部没有嵌套在一级分部里"
|
||||
assert 'Total="%.2f"' % T_ITEM in m1.group(0), "一级分部合计没现算"
|
||||
# ③ 定额/工料机架子克隆清值(我方清单下 Norm 在、量价全 0、含量式空)
|
||||
# ③ 未采纳清单:克隆架子清值(231①,主人 2026-10-28 复确认)——定额/工料机架子在、
|
||||
# 量价全 0、含量式空;费用构成子块在(值零)
|
||||
m3 = unit.index("我方清单甲")
|
||||
seg = unit[m3:m3 + 3000]
|
||||
e3 = unit.index("</WorkElement>", m3)
|
||||
seg = unit[m3:e3]
|
||||
assert "<Norm " in seg, "定额架子没克隆"
|
||||
assert re.search(r'<Norm\b[^>]*Quantity="0[^"]*"[^>]*Price="0[^"]*"[^>]*Total="0[^"]*"', seg) or \
|
||||
re.search(r'<Norm\b[^>]*Price="0[^"]*"', seg), "定额架子值没清零"
|
||||
assert all('Quantity="0' in n and 'Price="0' in n
|
||||
for n in re.findall(r"<Norm\b[^>]*>", seg)), "定额架子值没清零"
|
||||
assert 'Express=""' in seg, "工料机含量式没清空"
|
||||
# ④ 工料机汇总空槽:容器在、骨架的汇总行不进;清单下架子行的量价已清(身份属骨架,拍板①)
|
||||
assert "<LabourMaterialsEquipmentsMachinesSummary" in unit
|
||||
assert "骨架汇总工料机" not in unit
|
||||
sm = re.search(r"<LabourMaterialsEquipmentsMachinesSummary[^>]*>(.*?)</LabourMaterialsEquipmentsMachinesSummary>",
|
||||
unit, re.S)
|
||||
assert sm is not None and not sm.group(1).strip(), "工料机汇总容器没清空"
|
||||
# ④ 单位级工料机汇总(补记五:根层 LME_SUM=汇总行):无采纳=无现算行
|
||||
# → 骨架行全撤(架子在、行不进);骨架的行名不残留
|
||||
assert "骨架汇总工料机" not in unit and "骨架台班" not in unit
|
||||
# ⑤ 单位/单项/工程名落我方;合计现算;引用节点 Number 不动
|
||||
assert 'Name="我方单位工程"' in unit and "骨架单位工程A" not in unit
|
||||
assert ('DivisionalAndElementalWorks="%.2f"' % T_ITEM) in unit
|
||||
@@ -286,3 +263,151 @@ def test_manual_export_xlsx_roundtrip(server):
|
||||
def _sid_of(server):
|
||||
items = get(server, "/api/sessions")["items"]
|
||||
return next(x["id"] for x in items if x["manual"] and x["name"] == "我方手工工程T")
|
||||
|
||||
|
||||
def test_manual_export_unit_single(server):
|
||||
"""决策 233 方案a(2026-10-28 主人定):单单位工程导 xlsx——与 231 Excel 通道同一
|
||||
_unit_workbook 产出(同架子同数据逐格全等),文件名=单位工程名.xlsx,可回导。"""
|
||||
sid = _create_manual(server)
|
||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
||||
uw = st["sections"][0]["units"][0]["id"]
|
||||
r = server["client"].get("/api/session/manual/export_unit",
|
||||
params={"session_id": sid, "uw": uw})
|
||||
assert r.status_code == 200
|
||||
cd = r.headers.get("Content-Disposition", "")
|
||||
from urllib.parse import unquote
|
||||
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 == ["填写说明", "分部分项", "措施项目"]
|
||||
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, "合价没现算"
|
||||
# 与 231 整包 zip 里同一单位工程逐格全等(共用 _unit_workbook)
|
||||
rz = server["client"].get("/api/session/export", params={"session_id": sid, "fmt": "xlsx"})
|
||||
assert rz.status_code == 200
|
||||
z = zipfile.ZipFile(io.BytesIO(rz.content))
|
||||
zname = [n for n in z.namelist() if n.endswith(".xlsx")][0]
|
||||
wbz = load_workbook(io.BytesIO(z.read(zname)))
|
||||
assert wbz.sheetnames == wb.sheetnames
|
||||
for sn in wb.sheetnames:
|
||||
a = [[c.value for c in row] for row in wb[sn].iter_rows()]
|
||||
b = [[c.value for c in row] for row in wbz[sn].iter_rows()]
|
||||
assert a == b, "单导与 231 整包不一致:%s" % sn
|
||||
# 回导自查:单文件直接过预检
|
||||
p = server["src_dir"] / "unit_single_t.xlsx"
|
||||
p.write_bytes(r.content)
|
||||
assert post(server, "/api/session/manual/parse", {"path": str(p)})["ok"] is True
|
||||
|
||||
|
||||
def test_manual_export_unit_guards(server):
|
||||
"""守卫(决策 233):空单位工程提示不产文件;uw/会话不存在 400;源文件工程拒绝。"""
|
||||
from api_harness import META, fixture_file
|
||||
f1 = _mk_xlsx(server, "单导守卫.xlsx")
|
||||
r = post(server, "/api/session/manual/save",
|
||||
{"sid": 0, "name": "单导守卫T", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": "单项G",
|
||||
"units": [{"id": 0, "name": "有数据单位", "file": f1},
|
||||
{"id": 0, "name": "空单位"}]}]})
|
||||
assert r["ok"] is True, r
|
||||
sid = r["session_id"]
|
||||
us = get(server, "/api/session/manual/state", session_id=sid)["sections"][0]["units"]
|
||||
full = next(u for u in us if u["name"] == "有数据单位")
|
||||
empty = next(u for u in us if u["name"] == "空单位")
|
||||
c = server["client"]
|
||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": empty["id"]})
|
||||
assert j.status_code == 400 and "还没有清单数据" in j.text
|
||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid, "uw": 999999})
|
||||
assert j.status_code == 400 and "不存在" in j.text
|
||||
j = c.get("/api/session/manual/export_unit", params={"session_id": sid + 99999, "uw": full["id"]})
|
||||
assert j.status_code == 400
|
||||
pa = fixture_file(server, "单导源件.cos4", "单导源工程T",
|
||||
[("041001001001", "源件清单", "", "m²", 10, 100)])
|
||||
src = post(server, "/api/audit", dict(META, path=str(pa), name="单导源工程T"))["session_id"]
|
||||
j = c.get("/api/session/manual/export_unit", params={"session_id": src, "uw": full["id"]})
|
||||
assert j.status_code == 400 and "手工工程" in j.text
|
||||
|
||||
|
||||
def test_manual_export_unit_clone(server):
|
||||
"""骨架单位位自由复制(主人 2026-10-28 定「单位工程多少不影响骨架,1000 个都可以」):
|
||||
工程单位数 > 骨架位 → 克隆骨架单位成员补位;项目成员引用行顺延;新条目名按 GBK 字节
|
||||
写、不打 UTF-8 旗标(乱码教训)。"""
|
||||
_seed_skeleton(server)
|
||||
f1 = _mk_xlsx(server)
|
||||
r = post(server, "/api/session/manual/save",
|
||||
{"sid": 0, "name": "我方多单位工程T", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||||
{"id": 0, "name": "我方单位一", "file": f1},
|
||||
{"id": 0, "name": "我方单位二", "file": f1},
|
||||
{"id": 0, "name": "我方单位三", "file": f1}]}]})
|
||||
assert r["ok"] is True, r
|
||||
sid = r["session_id"]
|
||||
resp = server["client"].get("/api/session/export",
|
||||
params={"session_id": sid, "fmt": "cos4"})
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
z = zipfile.ZipFile(io.BytesIO(resp.content))
|
||||
infos = [i for i in z.infolist() if i.filename.lower().endswith(".xml")]
|
||||
assert len(infos) == 4, [i.filename for i in infos] # 1 骨架位 + 2 克隆 + Project
|
||||
# 克隆条目名:GBK 字节、无 UTF-8 旗标(骨架原生条目同款)
|
||||
clones = [i for i in infos if "_UW1_" not in i.filename and "Project" not in i.filename]
|
||||
assert len(clones) == 2, [i.filename for i in clones]
|
||||
for i in clones:
|
||||
assert not (i.flag_bits & 0x800), "克隆条目名被打上 UTF-8 旗标"
|
||||
nm_gbk = i.filename.encode("cp437").decode("gbk")
|
||||
assert re.match(r"@_\d+_单位工程\d+\.xml$", nm_gbk), nm_gbk
|
||||
root = ET.fromstring(z.read(i.filename))
|
||||
assert root.tag == "UnitWorks"
|
||||
assert root.get("Name") in ("我方单位二", "我方单位三")
|
||||
assert "我方清单甲" in z.read(i.filename).decode("utf-8")
|
||||
# 首位单位照旧落骨架本位
|
||||
skel_nm = [i.filename for i in infos if "_UW1_" in i.filename][0]
|
||||
assert ET.fromstring(z.read(skel_nm)).get("Name") == "我方单位一"
|
||||
# 项目成员引用行:3 条、名称齐、克隆行带新成员文件名
|
||||
proj = z.read("Project.xml").decode("utf-8")
|
||||
refs = re.findall(r'<UnitWorks\b[^>]*>', proj)
|
||||
names = [re.search(r'Name="([^"]*)"', x).group(1) for x in refs]
|
||||
assert names == ["我方单位一", "我方单位二", "我方单位三"], names
|
||||
for x in refs[1:]:
|
||||
fn = re.search(r'FileName="([^"]*)"', x)
|
||||
assert fn and (fn.group(1).encode("gbk").decode("cp437")) in \
|
||||
[i.filename for i in clones], x
|
||||
|
||||
|
||||
def test_manual_export_tree_reorder(server):
|
||||
"""目录树里上下移动单位后,导出引用行序=移动后的目录序(2026-10-28 主人定通用口径:
|
||||
单项/单位排序以项目目录先有顺序为准——手工树保存时按组内位置重写编号持久化顺序,
|
||||
导出端按「单项入库序+组内编号自然序」取,不能按物理 id)。"""
|
||||
_seed_skeleton(server)
|
||||
f1 = _mk_xlsx(server)
|
||||
r = post(server, "/api/session/manual/save",
|
||||
{"sid": 0, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||||
{"id": 0, "name": "单位甲", "file": f1},
|
||||
{"id": 0, "name": "单位乙", "file": None}]}]})
|
||||
assert r["ok"] is True, r
|
||||
sid = r["session_id"]
|
||||
con = sqlite3.connect(str(next(server["root"].rglob("session.db"))))
|
||||
ids = [row[0] for row in con.execute(
|
||||
"SELECT id FROM s_unit_works WHERE session_id=? ORDER BY id", (sid,))]
|
||||
con.close()
|
||||
assert len(ids) == 2
|
||||
r = post(server, "/api/session/manual/save", # 树里把两单位对调(带 id 保留数据)
|
||||
{"sid": sid, "name": "我方可移动工程T", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": "我方单项工程", "units": [
|
||||
{"id": ids[1], "name": "单位乙", "file": None},
|
||||
{"id": ids[0], "name": "单位甲", "file": None}]}]})
|
||||
assert r["ok"] is True, r
|
||||
resp = server["client"].get("/api/session/export",
|
||||
params={"session_id": sid, "fmt": "cos4"})
|
||||
assert resp.status_code == 200, resp.text[:200]
|
||||
proj = zipfile.ZipFile(io.BytesIO(resp.content)).read("Project.xml").decode("utf-8")
|
||||
names = [re.search(r'Name="([^"]*)"', x).group(1)
|
||||
for x in re.findall(r"<UnitWorks\b[^>]*>", proj)]
|
||||
ours_idx = [i for i, n in enumerate(names) if n in ("单位乙", "单位甲")]
|
||||
assert ours_idx == sorted(ours_idx), names
|
||||
assert names.index("单位乙") < names.index("单位甲"), \
|
||||
"移动后导出序没跟目录序:单位乙应排在单位甲前,实际 %s" % names[:4]
|
||||
|
||||
375
CostReview/app/tests/test_manual_export_dual.py
Normal file
375
CostReview/app/tests/test_manual_export_dual.py
Normal file
@@ -0,0 +1,375 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 231 补记·双路对拍(主人类比实证:「采纳的刚刚好是一个项目的清单,且分部与顺序相同,
|
||||
导出 cos 后清单分部定额及工料机这部分的信息是一样的;其他因为骨架选取不同会导致
|
||||
不计价信息不一样」)。
|
||||
|
||||
真实件(三溪科创小镇…易达导出.COS,真实易达件、现算口径已在决策 196/179 对拍归零)走两条路:
|
||||
a 路=.cos4 直接打开(标准导入)→ 原格式导出(export_cos 专用引擎);
|
||||
b 路=Excel 导入(清单级架子)→ 对比框同款逐条采纳 → 经典骨架导出(export_manual)。
|
||||
断言:**计价信息全等**——清单五值(编码/名称/单位/量/价/合价)、每条清单的定额集
|
||||
(编码/名称/单位/量/价/合价)、单位工料机汇总(码/量/除税/含税,量 0 行按决策 199 两路同滤);
|
||||
不计价信息(建设单位/取费等骨架保留值)允许不同。
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sqlite3
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import pytest
|
||||
from api_harness import META, PERIOD_202607, post, server # noqa: F401 (夹具)
|
||||
from test_api_p1 import raw_post
|
||||
from test_manual_export_real import _parse_original
|
||||
|
||||
REAL = Path(__file__).resolve().parents[3] / "后台需要导入的项目" / "三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS"
|
||||
FMT = "cos"
|
||||
|
||||
|
||||
def _f(v, r=6):
|
||||
try:
|
||||
return round(float(v), r)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not REAL.exists(), reason="真实件不在本机")
|
||||
def test_dual_path_identical_pricing(server):
|
||||
data = REAL.read_bytes()
|
||||
up = raw_post(server, "/api/admin/upload", REAL.name, data)
|
||||
assert up["ok"] is True, up
|
||||
# 补记十四:上传不再收藏——导出模板走升级口入库(本测用真实件当模板)
|
||||
import sys as _sys
|
||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||||
import classic_skeleton as _cs
|
||||
_con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||||
try:
|
||||
assert _cs.seed_frame(_con, str(REAL), "COS4骨架双路T")
|
||||
finally:
|
||||
_con.close()
|
||||
# ---- a 路:直接打开(标准会话;导出在双会话采纳之后做,对照才纯净)----
|
||||
r = post(server, "/api/audit", {"path": up["path"], "name": "双路甲",
|
||||
"period_from": PERIOD_202607, "period_to": PERIOD_202607})
|
||||
assert r["ok"] is True, r
|
||||
sid_a = r["session_id"]
|
||||
# ---- b 路前置:批次入库(采纳来源)+ Excel 手工工程 ----
|
||||
rb = post(server, "/api/admin/import",
|
||||
dict(META, path=up["path"], name="双路来源批次", file_kind=1))
|
||||
assert rb["ok"] is True, rb
|
||||
bid = rb["batch_id"]
|
||||
out = _parse_original(REAL)
|
||||
assert out["uw"], "原件没解析出单位工程"
|
||||
# 该件没有分部层(清单直挂单位工程)——230 挂接法要求清单挂分部下,
|
||||
# b 路套一个合成根分部(对拍只比计价信息,分部骨架差异不在断言内)
|
||||
from openpyxl import Workbook
|
||||
|
||||
def unit_xlsx(i, uw):
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "分部分项"
|
||||
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
|
||||
ws.append(["单位工程", "", "分部", "清单汇总", "", "", "", ""])
|
||||
for bi, b in enumerate(out["bills"]):
|
||||
if out["bill_uw"][bi] != i or out["bill_kind"][bi] == "prelim":
|
||||
continue
|
||||
ws.append(["清单汇总", b[0] or "", "清单", b[1] or "", b[2] or "",
|
||||
b[3] or "", _f(b[4]) or 0, _f(b[5]) or 0])
|
||||
ws2 = wb.create_sheet("措施项目")
|
||||
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
|
||||
for bi, b in enumerate(out["bills"]):
|
||||
if out["bill_uw"][bi] != i or out["bill_kind"][bi] != "prelim":
|
||||
continue
|
||||
ws2.append([b[1] or "", b[0] or "", b[2] or "", b[3] or "",
|
||||
_f(b[4]) or 0, _f(b[5]) or 0])
|
||||
p = server["src_dir"] / ("dual_uw%d.xlsx" % i)
|
||||
wb.save(p)
|
||||
return str(p)
|
||||
|
||||
units = []
|
||||
for i, uw in enumerate(out["uw"]):
|
||||
units.append({"id": 0, "name": uw[1] or ("单位工程%d" % (i + 1)),
|
||||
"file": unit_xlsx(i, uw)})
|
||||
sec0 = (out.get("sections") or [None])[0]
|
||||
sec_name = (sec0[1] if isinstance(sec0, (tuple, list)) and sec0[1] else "单项工程")
|
||||
rm = post(server, "/api/session/manual/save",
|
||||
{"sid": 0, "name": "双路乙", "period_from": PERIOD_202607,
|
||||
"period_to": PERIOD_202607,
|
||||
"tree": [{"id": 0, "name": sec_name, "units": units}]})
|
||||
assert rm["ok"] is True, rm
|
||||
sid_b = rm["session_id"]
|
||||
# ---- 配对 + 双会话逐条采纳(对比框同款语义,决策 68/9.x/227 全套沿用)----
|
||||
# a 路(标准会话)也采纳同一批:对照才纯净——两边定额值同源于同一套 GCL 公式求值,
|
||||
# 采纳系数的浮点微漂两边一致,导出对比即「写法差异之外应逐位一致」
|
||||
con = sqlite3.connect(server["db"])
|
||||
con.row_factory = sqlite3.Row
|
||||
try:
|
||||
buw = {r["id"]: i for i, r in enumerate(con.execute(
|
||||
"SELECT id FROM unit_works WHERE batch_id=? ORDER BY id", (bid,)))}
|
||||
batch = {}
|
||||
for r in con.execute("SELECT id, uw_id, Number, Name FROM bills WHERE batch_id=?",
|
||||
(bid,)):
|
||||
batch[(buw.get(r["uw_id"], -1), r["Number"] or "", r["Name"] or "")] = r["id"]
|
||||
finally:
|
||||
con.close()
|
||||
cs = sqlite3.connect(server["sessdb"])
|
||||
cs.row_factory = sqlite3.Row
|
||||
try:
|
||||
suw = {r["id"]: i for i, r in enumerate(cs.execute(
|
||||
"SELECT id FROM s_unit_works WHERE session_id=? ORDER BY id", (sid_b,)))}
|
||||
pos2id = {v: k for k, v in suw.items()} # 单位位 → s_unit_works.id(dyn 现算用)
|
||||
sess = [(r["id"], suw.get(r["uw_id"], -1), r["Number"] or "", r["Name"] or "")
|
||||
for r in cs.execute(
|
||||
"SELECT id, uw_id, Number, Name FROM s_bills WHERE session_id=?",
|
||||
(sid_b,))]
|
||||
finally:
|
||||
cs.close()
|
||||
# ---- 逐条采纳进 b 路(对比框同款语义,决策 68/9.x/227 全套沿用)----
|
||||
n_adopt = 0
|
||||
for bill_id, uw_i, num, name in sess:
|
||||
src = batch.get((uw_i, num, name))
|
||||
assert src, "批次里找不到对应清单:%s" % ((uw_i, num, name),)
|
||||
ra2 = post(server, "/api/session/bill/adopt",
|
||||
{"session_id": sid_b, "bill_id": bill_id, "src_bill_id": src})
|
||||
assert ra2["ok"] is True, ra2
|
||||
n_adopt += 1
|
||||
assert n_adopt > 0
|
||||
# ---- 采纳落地状态=独立期望值(会话 s_norms + GCL 公式求值,与导出引擎无关)----
|
||||
import dyn_lme as _dl # core 路径已由 _parse_original(_ij) 注入
|
||||
expected = {} # (uw_pos, 清单编码, 清单名称) → [(定额4列+量价合)]
|
||||
cs = sqlite3.connect(server["sessdb"])
|
||||
cs.row_factory = sqlite3.Row
|
||||
try:
|
||||
_cols = {x[1] for x in cs.execute("PRAGMA table_info(s_norms)")}
|
||||
_has_expr = "qty_expr" in _cols
|
||||
_ex = ", qty_expr" if _has_expr else ", NULL AS qty_expr"
|
||||
for r in cs.execute("""SELECT b.uw_id, b.Number AS bnum, b.Name AS bname,
|
||||
b.Quantity AS bqty, n.Number, n.Name, n.Unit,
|
||||
n.Quantity, n.Price, n.Total, n.x_tdel
|
||||
%s FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=?
|
||||
AND (b.Kind IS NULL OR b.Kind<>'prelim')""" % _ex,
|
||||
(sid_b,)):
|
||||
if r["x_tdel"]:
|
||||
continue
|
||||
qty = r["Quantity"]
|
||||
if _has_expr and r["qty_expr"]:
|
||||
g = _dl.gcl_of(r["bqty"], r["Unit"])
|
||||
v, _msg = _dl.eval_qty_expr(r["qty_expr"], g)
|
||||
if v is not None:
|
||||
# 决策 216:GCL=清单量原值,单位因子只在公式结果上最后除
|
||||
qty = round(v / _dl.unit_factor(r["Unit"] or ""), 6)
|
||||
tot = (round(qty * r["Price"], 2)
|
||||
if qty is not None and r["Price"] is not None else r["Total"])
|
||||
key = (suw.get(r["uw_id"], -1), r["bnum"] or "", r["bname"] or "")
|
||||
expected.setdefault(key, []).append(
|
||||
(r["Number"] or "", r["Name"] or "", (r["Unit"] or "").strip(),
|
||||
_f(qty), _f(r["Price"]), _f(tot)))
|
||||
finally:
|
||||
cs.close()
|
||||
for k in expected:
|
||||
expected[k].sort()
|
||||
# 消耗行期望(现算数据根,决策 98):采纳定额下的 s_norm_res 消耗量,按清单纯度分组
|
||||
cons_expected = {}
|
||||
cs2 = sqlite3.connect(server["sessdb"])
|
||||
cs2.row_factory = sqlite3.Row
|
||||
try:
|
||||
for r in cs2.execute("""SELECT b.uw_id, b.Number AS bnum, b.Name AS bname,
|
||||
n.Number AS nnum, n.Name AS nname, nr.res_code, nr.qty
|
||||
FROM s_norm_res nr JOIN s_norms n ON n.id=nr.norm_id
|
||||
JOIN s_bills b ON b.id=n.bill_id
|
||||
WHERE b.session_id=? AND n.x_tdel=0
|
||||
AND (b.Kind IS NULL OR b.Kind<>'prelim')""", (sid_b,)):
|
||||
k = (suw.get(r["uw_id"], -1), r["bnum"] or "", r["bname"] or "",
|
||||
r["nnum"] or "", r["nname"] or "")
|
||||
cons_expected.setdefault(k, []).append((r["res_code"] or "", _f(r["qty"], 6)))
|
||||
finally:
|
||||
cs2.close()
|
||||
for k in cons_expected:
|
||||
cons_expected[k].sort()
|
||||
# ---- 两路导出:a=标准引擎原件(未采纳,作清单/汇总参照);b=经典骨架(已采纳)----
|
||||
ra = server["client"].get("/api/session/export", params={"session_id": sid_a})
|
||||
assert ra.status_code == 200, ra.text[:200]
|
||||
if os.environ.get("DEBUG_DUAL"):
|
||||
Path(os.environ["DEBUG_DUAL"]).write_bytes(ra.content)
|
||||
A = zipfile.ZipFile(io.BytesIO(ra.content))
|
||||
rb2 = server["client"].get("/api/session/export",
|
||||
params={"session_id": sid_b, "fmt": FMT})
|
||||
assert rb2.status_code == 200, rb2.text[:300]
|
||||
if os.environ.get("DEBUG_DUAL_B"):
|
||||
Path(os.environ["DEBUG_DUAL_B"]).write_bytes(rb2.content)
|
||||
B = zipfile.ZipFile(io.BytesIO(rb2.content))
|
||||
|
||||
# ---- 对拍:计价信息全等 ----
|
||||
def members(z):
|
||||
out, skipped = [], []
|
||||
for nm in z.namelist():
|
||||
if nm.lower().endswith(".xml"):
|
||||
try:
|
||||
body = ET.fromstring(z.read(nm))
|
||||
except Exception as e:
|
||||
skipped.append((nm[-30:], str(e)[:60]))
|
||||
continue
|
||||
if body.tag == "UnitWorks":
|
||||
out.append(body)
|
||||
return out, skipped
|
||||
|
||||
ma, skip_a = members(A)
|
||||
mb, skip_b = members(B)
|
||||
# a 路普通引擎在本件上存在**既有缺陷**(非本次改动范围:打开时主动拆码·决策 201 之后的
|
||||
# 汇总同步产生碎标签,如 @_146_给水工程「<Labo<LabourMaterials…」)——跳过并如实计数
|
||||
assert not skip_b, "b 路件有解析失败成员:%s" % skip_b
|
||||
|
||||
def bills(el):
|
||||
out = sorted((b.get("Number") or "", b.get("Name") or "",
|
||||
(b.get("Unit") or "").strip(), _f(b.get("Quantity")),
|
||||
_f(b.get("Price")), _f(b.get("Total")))
|
||||
for b in el.iter("WorkElement"))
|
||||
return out
|
||||
|
||||
def bills_close(la, lb):
|
||||
"""清单五值:编码/名称/单位/量/价全等;合价允许 0.011 容差——易达原生四舍五入
|
||||
(7786.41)与软件标准 round(7786.40)在 5 厘边界差 1 分,标准采纳语义。"""
|
||||
if len(la) != len(lb):
|
||||
return False
|
||||
for xa, xb in zip(la, lb):
|
||||
if xa[:5] != xb[:5] or abs(xa[5] - xb[5]) > 0.011:
|
||||
return False
|
||||
return True
|
||||
|
||||
def norms(el):
|
||||
out = []
|
||||
for b in el.iter("WorkElement"):
|
||||
for n in b.iter("Norm"):
|
||||
out.append((b.get("Number") or "", n.get("Number") or "",
|
||||
n.get("Name") or "", (n.get("Unit") or "").strip(),
|
||||
_f(n.get("Quantity")), _f(n.get("Price")), _f(n.get("Total"))))
|
||||
return sorted(out)
|
||||
|
||||
def lme(el):
|
||||
"""只取**直挂根**的汇总容器的直接子行(老 cos 行标签也叫 …Summary——
|
||||
用 iter 会把定额里的消耗行全扫进来,三溪实测 2937 条污染)。"""
|
||||
out = []
|
||||
for s in el.findall("LabourMaterialsEquipmentsMachinesSummary"):
|
||||
for r in s:
|
||||
out.append((r.get("Number") or "", _f(r.get("Quantity"), 4),
|
||||
_f(r.get("NoTaxPrice"), 4), _f(r.get("TaxPrice"), 4)))
|
||||
return sorted(x for x in out if x[1] != 0) # 决策 199 量 0 不导:同口径
|
||||
|
||||
def norms_close(la, lb):
|
||||
"""编码/名称/单位/单价全等;量/合价允许 0.1% 容差——采纳 GCL 公式求值的
|
||||
浮点回程微漂(0.01→0.009999)是标准采纳自身语义,两路应同为该语义。"""
|
||||
if len(la) != len(lb):
|
||||
return False
|
||||
for xa, xb in zip(la, lb):
|
||||
if xa[:4] != xb[:4]:
|
||||
return False
|
||||
for i in (4, 5, 6):
|
||||
if abs(xa[i] - xb[i]) > max(0.005, abs(xa[i]) * 0.001):
|
||||
return False
|
||||
return True
|
||||
|
||||
ma, skip_a = members(A)
|
||||
mb, skip_b = members(B)
|
||||
# a 路普通引擎在本件上存在**既有缺陷**(非本次改动范围:打开时主动拆码·决策 201 之后的
|
||||
# 汇总同步产生碎标签,如 @_146_给水工程「<Labo<LabourMaterials…」)——跳过并如实计数
|
||||
assert not skip_b, "b 路件有解析失败成员:%s" % skip_b
|
||||
# 按单位工程名配对(跳过成员后顺序会错位)
|
||||
na = {}
|
||||
for ea in ma:
|
||||
na[ea.get("Name") or ""] = ea
|
||||
nb = {}
|
||||
for eb in mb:
|
||||
nb[eb.get("Name") or ""] = eb
|
||||
compared = 0
|
||||
for i, uw in enumerate(out["uw"]):
|
||||
nm_uw = uw[1] or ("单位工程%d" % (i + 1))
|
||||
ea, eb = na.get(nm_uw), nb.get(nm_uw)
|
||||
if ea is None:
|
||||
assert skip_a, "a 路缺成员 %s 且无解析失败记录" % nm_uw
|
||||
continue
|
||||
assert eb is not None, "b 路缺成员 %s" % nm_uw
|
||||
ca = ea.find("DivisionalAndElementalWorks")
|
||||
cb = eb.find("DivisionalAndElementalWorks")
|
||||
assert ca is not None and cb is not None
|
||||
assert bills_close(bills(ca), bills(cb)), "单位%s 清单五值不一致" % nm_uw
|
||||
# 单位级工料机汇总(补记五口径:根层 LME_SUM=汇总行,易达标准骨架铁证)——
|
||||
# 导出件根层行对照 dyn 现算(码/量/价,量 0 不导 199 同口径);台班子级另由
|
||||
# test_frame_skeleton 覆盖
|
||||
_c2 = sqlite3.connect(server["sessdb"])
|
||||
_c2.row_factory = sqlite3.Row
|
||||
try:
|
||||
_dyn = _dl.dyn_uw_rows(_c2, sid_b, pos2id[i])
|
||||
finally:
|
||||
_c2.close()
|
||||
# 容差逐对比较(金额写 2 位、数量写 6 位——写读往返在第 6 位以下折损,
|
||||
# 半界舍入漂移≤0.0011/0.006;实际值同源 dyn 同一引擎)
|
||||
exp_map = {r[0]: (float(r[5]), float(r[6] or 0), float(r[8] or 0))
|
||||
for r in (_dyn or []) if (r[5] or 0) != 0}
|
||||
got_map = {r.get("Number") or "": (float(r.get("Quantity") or 0),
|
||||
float(r.get("NoTaxPrice") or 0),
|
||||
float(r.get("TaxPrice") or 0))
|
||||
for r in eb.findall("LabourMaterialsEquipmentsMachinesSummary")
|
||||
if _f(r.get("Quantity"), 4) != 0}
|
||||
assert set(got_map) == set(exp_map), "单位%s 汇总行码集不一致:缺=%s 多=%s" % (
|
||||
nm_uw, sorted(set(exp_map) - set(got_map))[:4],
|
||||
sorted(set(got_map) - set(exp_map))[:4])
|
||||
for c in exp_map:
|
||||
for j, tol in ((0, 0.0011), (1, 0.006), (2, 0.006)):
|
||||
assert abs(got_map[c][j] - exp_map[c][j]) <= tol, "单位%s 码%s 第%d值 %s vs %s" % (nm_uw, c, j, got_map[c][j], exp_map[c][j])
|
||||
# 定额=对照「采纳落地的会话状态」(独立期望值:s_norms+GCL 公式求值,与导出
|
||||
# 引擎无关),**按清单分组**逐条比——无定额的费项清单(原件即无定额,110 条)
|
||||
# 走 231① 架子清值,不混入本比对
|
||||
expected_uw = {}
|
||||
for k, v in expected.items():
|
||||
if k[0] == i:
|
||||
expected_uw[(k[1], k[2])] = v
|
||||
got_by_bill = {}
|
||||
for b in cb.iter("WorkElement"):
|
||||
k = (b.get("Number") or "", b.get("Name") or "")
|
||||
if k in expected_uw:
|
||||
got_by_bill.setdefault(k, []).extend(
|
||||
((n.get("Number") or "", n.get("Name") or "",
|
||||
(n.get("Unit") or "").strip(), _f(n.get("Quantity")),
|
||||
_f(n.get("Price")), _f(n.get("Total"))))
|
||||
for n in b.iter("Norm"))
|
||||
for k, exp_rows in expected_uw.items():
|
||||
exp_rows = sorted(tuple(x) for x in exp_rows)
|
||||
got_rows = sorted(got_by_bill.get(k, []))
|
||||
ok = (len(got_rows) == len(exp_rows) and all(
|
||||
xa[:3] == xb[:3] and all(abs(xa[j] - xb[j]) <= max(0.005, abs(xa[j]) * 0.001)
|
||||
for j in (3, 4, 5))
|
||||
for xa, xb in zip(got_rows, exp_rows)))
|
||||
if not ok:
|
||||
diff = None
|
||||
for xa, xb in zip(got_rows, exp_rows):
|
||||
if xa != xb and (xa[:4] != xb[:4] or any(
|
||||
abs(xa[j] - xb[j]) > max(0.005, abs(xa[j]) * 0.001)
|
||||
for j in (3, 4, 5))):
|
||||
diff = (xa, xb)
|
||||
break
|
||||
raise AssertionError(
|
||||
"单位%s 清单%s 定额与采纳落地状态不一致:len 导出=%d 期望=%d;首差异=%s"
|
||||
% (nm_uw, k, len(got_rows), len(exp_rows), diff))
|
||||
# 消耗行=现算数据根:该清单各采纳定额下的 LME 子行与 s_norm_res 逐一对照
|
||||
got_cons = {}
|
||||
for b2 in cb.iter("WorkElement"):
|
||||
if (b2.get("Number") or "", b2.get("Name") or "") != k:
|
||||
continue
|
||||
for n2 in b2.iter("Norm"):
|
||||
nk = (i, k[0], k[1], n2.get("Number") or "", n2.get("Name") or "")
|
||||
for c2 in n2:
|
||||
if c2.tag.startswith("LabourMaterials"):
|
||||
got_cons.setdefault(nk, []).append(
|
||||
(c2.get("Number") or "", _f(c2.get("Quantity"), 6)))
|
||||
for nk, rows in got_cons.items():
|
||||
rows.sort()
|
||||
assert rows == cons_expected.get(nk, []), \
|
||||
"单位%s 清单%s 定额%s 消耗行与采纳落地不一致:%s vs %s" % (
|
||||
nm_uw, k[:2], nk[2:], rows[:3], cons_expected.get(nk, [])[:3])
|
||||
missing = [k4 for k4 in cons_expected
|
||||
if k4[0] == i and k4[1:3] == k and k4 not in got_cons]
|
||||
assert not missing, "清单%s 采纳定额消耗行缺失:%s exp=%s" % (
|
||||
k, missing[:2], [cons_expected[m] for m in missing[:2]])
|
||||
compared += 1
|
||||
assert compared >= len(out["uw"]) - 2, \
|
||||
"对拍成员过少:compared=%d uw=%d skip_a=%s" % (compared, len(out["uw"]), skip_a)
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""决策 229 真实件对拍(主人 2026-10-27 定:「要真真实实做测试,不能弄虚作假骗自己」)。
|
||||
"""决策 231 真实件对拍(主人 2026-10-27 定:「要真真实实做测试,不能弄虚作假骗自己」)。
|
||||
|
||||
链路:真实小项目原件 → 上传入库当经典骨架 → 原件解析倒出 Excel(230 模板、原行序)
|
||||
→ 手工工程导入 → 骨架导出 → **导出件与原件逐层对拍数据结构**:
|
||||
@@ -7,7 +7,8 @@
|
||||
②分部层级保真:DivisionalWorks 嵌套序列(深度+名称,预序)逐一对齐;
|
||||
③我方数据挂载正确:分部分项/措施清单的 (编码,名称,单位,量,价) 集合=原件
|
||||
(主人定:骨架只规定格式与字段,数据挂载在字段下;合价现算);
|
||||
④架子清值:每条我方清单下定额架子在、量价 0;工料机汇总容器空(架子在行不进);
|
||||
④未采纳清单=克隆架子清值(231①,2026-10-28 复确认:架子在值 0);无采纳=工料机
|
||||
汇总容器空(架子在行不进);
|
||||
⑤保留值:建设单位/费用汇总等工程级信息=原件原样;工程/单位/单项名=原件名
|
||||
(本测试数据来自原件,名字应当对上);
|
||||
⑥措施区平铺(决策 230 既有口径:Excel 措施 Sheet 无层级,不保留措施分部层级)。
|
||||
@@ -17,6 +18,7 @@
|
||||
"""
|
||||
import importlib.util
|
||||
import io
|
||||
import sqlite3
|
||||
import os
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
@@ -118,10 +120,18 @@ def test_real_roundtrip(server, fname, fmt):
|
||||
if not src.exists():
|
||||
pytest.skip("真实件不在本机:%s" % fname)
|
||||
tag = fmt
|
||||
# ---- ① 原件上传=当经典骨架收进库 ----
|
||||
# ---- ① 原件上传+升级口入骨架库(补记十四:上传不再自动收藏)----
|
||||
data = src.read_bytes()
|
||||
up = raw_post(server, "/api/admin/upload", fname, data)
|
||||
assert up["ok"] is True, up
|
||||
import sys as _sys
|
||||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||||
import classic_skeleton as _cs
|
||||
_con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||||
try:
|
||||
assert _cs.seed_frame(_con, str(src), "骨架real_%s" % tag)
|
||||
finally:
|
||||
_con.close()
|
||||
# ---- ② 原件解析(与工作台同源解析器)→ 倒 Excel ----
|
||||
out = _parse_original(src)
|
||||
assert out["uw"], "原件没解析出单位工程"
|
||||
@@ -163,6 +173,12 @@ def test_real_roundtrip(server, fname, fmt):
|
||||
|
||||
ms, me = members(zsrc), members(zexp)
|
||||
assert len(ms) == len(me) == len(out["uw"]), "单位工程成员数不一致"
|
||||
# 2026-10-28 主人定:单位排序=项目目录序(引用行序),与压缩包内 xml 次序无关——
|
||||
# 导出成员按 zip 物理序取不再保证与原件逐位对齐,改按单位名配对比内容
|
||||
me_by_name = {}
|
||||
for nm, body in me:
|
||||
me_by_name.setdefault(body.get("Name") or "", []).append((nm, body))
|
||||
assert all(len(v) == 1 for v in me_by_name.values()), "导出件存在同名单位工程,无法按名配对"
|
||||
|
||||
def dw_seq(container, depth=0):
|
||||
"""容器/分部内 DivisionalWorks 预序 (depth, Name) 序列。"""
|
||||
@@ -183,7 +199,8 @@ def test_real_roundtrip(server, fname, fmt):
|
||||
_f(el.get("Quantity")), _f(el.get("Price")))
|
||||
|
||||
PRE_TAGS = {"UnitWorksPreliminaryWorkElement", "WorkElement"}
|
||||
for i, ((nms, es), (_, eo)) in enumerate(zip(ms, me)):
|
||||
for i, ((nms, es), (_, eo)) in enumerate(
|
||||
(mo, me_by_name[(mo[1].get("Name") or "")][0]) for mo in ms):
|
||||
uw_name = out["uw"][i][1] or ("单位工程%d" % (i + 1))
|
||||
# ⑤-2 单位名=原件
|
||||
assert eo.get("Name") == uw_name, (nms, eo.get("Name"), uw_name)
|
||||
@@ -196,7 +213,7 @@ def test_real_roundtrip(server, fname, fmt):
|
||||
so = sorted(bills_of(co, {"WorkElement"}))
|
||||
se = sorted(bills_of(cs, {"WorkElement"}))
|
||||
assert len(so) == len(se) and so == se, "单位 %s 清单集不一致" % uw_name
|
||||
# ⑤-5 架子清值:每条我方清单下定额架子在、量价 0
|
||||
# ⑤-5 未采纳清单=克隆架子清值(231①,主人 2026-10-28 复确认):架子在、值全 0
|
||||
for el in cs.iter("WorkElement"):
|
||||
norms = list(el.iter("Norm"))
|
||||
assert norms, "清单 %s 没有定额架子" % el.get("Name")
|
||||
|
||||
@@ -242,3 +242,27 @@ def test_manual_save_reorder_within_groups(server):
|
||||
st2 = get(server, "/api/session/manual/state", session_id=sid)
|
||||
assert [s["name"] for s in st2["sections"]] == ["单项B", "单项A"]
|
||||
assert [u["name"] for u in st2["sections"][1]["units"]] == ["A2", "A1"]
|
||||
|
||||
|
||||
def test_manual_save_region_fields(server):
|
||||
"""决策 233(2026-10-28 主人定):打开项目弹框共用字段——地区/建设单位随建落库、
|
||||
manual_state 回填、改存更新(与 /api/audit 同名参数)。"""
|
||||
f = _xlsx(server, "手工地区.xlsx")
|
||||
r = _save(server, name="手工地区T", province="广东省", city="珠海市", district="香洲区",
|
||||
bulid_unit="某某建设单位",
|
||||
tree=[{"id": 0, "name": "单项A",
|
||||
"units": [{"id": 0, "name": "单位A", "file": f}]}])
|
||||
assert r["ok"] is True, r
|
||||
sid = r["session_id"]
|
||||
st = get(server, "/api/session/manual/state", session_id=sid)
|
||||
assert st["ok"], st
|
||||
assert st["province"] == "广东省" and st["city"] == "珠海市", st
|
||||
assert st["district"] == "香洲区" and st["bulid_unit"] == "某某建设单位"
|
||||
uw = st["sections"][0]["units"][0]["id"]
|
||||
r2 = _save(server, sid=sid, name="手工地区T", province="广西壮族自治区", city="南宁市",
|
||||
district="", bulid_unit="新建设单位",
|
||||
tree=[{"id": 0, "name": "单项A", "units": [{"id": uw, "name": "单位A"}]}])
|
||||
assert r2["ok"] is True, r2
|
||||
st2 = get(server, "/api/session/manual/state", session_id=sid)
|
||||
assert st2["province"] == "广西壮族自治区" and st2["city"] == "南宁市"
|
||||
assert st2["district"] == "" and st2["bulid_unit"] == "新建设单位"
|
||||
|
||||
@@ -47,10 +47,11 @@ def test_create_endpoint_retired(server):
|
||||
assert {x["id"] for x in get(server, "/api/sessions")["items"]} == before
|
||||
assert "/api/session/create" not in server["client"].get("/api/schema").text
|
||||
page = server["client"].get("/workbench.html").text
|
||||
# 决策 230(2026-10-27):创建入口以「导入项目」弹框形态恢复(取代决策 137 的取消);
|
||||
# 决策 230(2026-10-27)创建入口以「导入项目」弹框形态恢复;决策 233(2026-10-28 主人定)
|
||||
# 并入「打开项目」弹框(底部常驻 [模板][导入Excel],右侧目录树,取代顶栏按钮);
|
||||
# 旧路由 /api/session/create、旧函数 createProject 仍退役不复用。
|
||||
assert "createProject" not in page
|
||||
assert "导入项目" in page and "impDlgOpen" in page
|
||||
assert "导入Excel" in page and "impExcelToggle" in page
|
||||
assert 'onclick="doOpen()"' in page
|
||||
|
||||
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""MCP 接入开关回归(2026-10-15):
|
||||
默认关 → /mcp 403;打开(自动生成令牌)→ 无令牌 401、带令牌 initialize/tools/list/tools/call 可用;
|
||||
关闭 → 再断;/api/mcp/status 反映状态;/api/schema 含 MCP 组。
|
||||
"""MCP 接入回归(2026-10-15;2026-10-27 主人重定义:只读 5 工具):
|
||||
默认关 → /mcp 403;打开(自动生成令牌)→ 无令牌 401、带令牌 initialize/tools/list/tools/call
|
||||
可用;工具集=只读 5 件套(无任何写/导出工具);关闭 → 再断;/api/mcp/status 反映状态。
|
||||
"""
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import api_harness as H
|
||||
from api_harness import post, server # noqa: F401
|
||||
|
||||
NEW_TOOLS = {"bills_query", "lme_prices", "market_info_prices",
|
||||
"recent_review_query", "attachment_download"}
|
||||
|
||||
|
||||
def _mcp(server, body, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
r = server["client"].post("/mcp", content=json.dumps(body), headers=headers)
|
||||
return r
|
||||
return server["client"].post("/mcp", content=json.dumps(body), headers=headers)
|
||||
|
||||
|
||||
def _rpc(mid, method, params=None):
|
||||
@@ -24,6 +27,20 @@ def _rpc(mid, method, params=None):
|
||||
return b
|
||||
|
||||
|
||||
def _call(server, token, mid, name, args):
|
||||
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
|
||||
assert r.status_code == 200, r.text[:200]
|
||||
j = r.json()
|
||||
assert j["result"]["isError"] is False, j
|
||||
return json.loads(j["result"]["content"][0]["text"])
|
||||
|
||||
|
||||
def _call_err(server, token, mid, name, args):
|
||||
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
|
||||
j = r.json()
|
||||
return json.loads(j["result"]["content"][0]["text"])
|
||||
|
||||
|
||||
def test_mcp_switch_lifecycle(server):
|
||||
# 默认关:JSON-RPC 也被 403 挡住
|
||||
r = _mcp(server, _rpc(1, "tools/list"))
|
||||
@@ -39,16 +56,6 @@ def test_mcp_switch_lifecycle(server):
|
||||
assert r.status_code == 200, r.text[:200]
|
||||
j = r.json()
|
||||
assert j["result"]["serverInfo"]["name"] == "造价审核"
|
||||
# tools/list → 17 个左右工具,含核心集
|
||||
r = _mcp(server, _rpc(2, "tools/list"), t["token"])
|
||||
names = [x["name"] for x in r.json()["result"]["tools"]]
|
||||
for need in ("sessions_list", "project_open", "bill_op", "norm_op", "bill_adopt",
|
||||
"lme_merge", "session_export", "api_schema"):
|
||||
assert need in names, names
|
||||
# tools/call sessions_list 真跑业务
|
||||
r = _mcp(server, _rpc(3, "tools/call", {"name": "sessions_list", "arguments": {}}), t["token"])
|
||||
out = json.loads(r.json()["result"]["content"][0]["text"])
|
||||
assert "items" in out, out
|
||||
# 通知(无 id)→ 202 空体
|
||||
r = _mcp(server, {"jsonrpc": "2.0", "method": "notifications/initialized"}, t["token"])
|
||||
assert r.status_code == 202, r.status_code
|
||||
@@ -58,17 +65,67 @@ def test_mcp_switch_lifecycle(server):
|
||||
r = _mcp(server, _rpc(9, "tools/list"), t["token"])
|
||||
assert r.status_code == 403
|
||||
# 状态接口
|
||||
st = get_status(server)
|
||||
assert st["enabled"] is False and st["endpoint"] == "/mcp"
|
||||
st = server["client"].get("/api/mcp/status").json()
|
||||
assert st["enabled"] is False and st["endpoint"] == "/mcp" and st["tools"] == 5
|
||||
|
||||
|
||||
def get_status(server):
|
||||
r = server["client"].get("/api/mcp/status")
|
||||
return r.json()
|
||||
def test_mcp_readonly_toolset(server):
|
||||
t = post(server, "/api/admin/mcp", {"enabled": True})
|
||||
tok = t["token"]
|
||||
try:
|
||||
# 工具集 = 只读 5 件套,一个不多一个不少(旧写工具全部移除)
|
||||
r = _mcp(server, _rpc(2, "tools/list"), tok)
|
||||
names = {x["name"] for x in r.json()["result"]["tools"]}
|
||||
assert names == NEW_TOOLS, names
|
||||
for gone in ("bill_op", "norm_op", "bill_adopt", "lme_merge", "session_delete",
|
||||
"session_export", "api_schema", "upload_file", "project_open"):
|
||||
assert gone not in names
|
||||
# 范围守卫:keyword/batch_id 都不给 → 拒绝
|
||||
for tool in ("bills_query", "lme_prices", "market_info_prices"):
|
||||
out = _call_err(server, tok, 3, tool, {})
|
||||
assert out.get("ok") is False and "keyword" in out.get("msg", ""), (tool, out)
|
||||
# 最近审核:无参 → 会话列表结构
|
||||
out = _call(server, tok, 4, "recent_review_query", {})
|
||||
assert out["ok"] is True and isinstance(out["rows"], list)
|
||||
# 带错误 type → 拒绝
|
||||
out = _call_err(server, tok, 5, "recent_review_query", {"session_id": 1, "type": "x"})
|
||||
assert out.get("ok") is False
|
||||
# 附件下载:参数不合法 → 拒绝
|
||||
out = _call_err(server, tok, 6, "attachment_download", {"type": "xx", "id": 1})
|
||||
assert out.get("ok") is False
|
||||
# 真实附件路径(无绑定)→ 拒绝且不抛异常
|
||||
out = _call_err(server, tok, 7, "attachment_download", {"type": "bill", "id": 1})
|
||||
assert out.get("ok") is False
|
||||
# 未知工具 → -32602
|
||||
r = _mcp(server, _rpc(8, "tools/call", {"name": "nope", "arguments": {}}), tok)
|
||||
assert r.json()["error"]["code"] == -32602
|
||||
finally:
|
||||
post(server, "/api/admin/mcp", {"enabled": False})
|
||||
|
||||
|
||||
def test_mcp_query_matches_db(server):
|
||||
"""market_info_prices 与库内事实一致(数据自证,不写死数字)。"""
|
||||
t = post(server, "/api/admin/mcp", {"enabled": True})
|
||||
tok = t["token"]
|
||||
try:
|
||||
con = sqlite3.connect(server["db"])
|
||||
row = con.execute("SELECT id FROM batches WHERE kind IN ('info','market') "
|
||||
"AND id IN (SELECT DISTINCT batch_id FROM prices) LIMIT 1").fetchone()
|
||||
if row:
|
||||
bid = row[0]
|
||||
want = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
|
||||
out = _call(server, tok, 1, "market_info_prices", {"batch_id": bid, "limit": 200})
|
||||
got = len(out["rows"])
|
||||
assert out["ok"] and got == min(want, 200), (want, got)
|
||||
if out["rows"]:
|
||||
for k in ("Code", "Name", "Unit", "NoTaxPrice", "TaxPrice"):
|
||||
assert k in out["rows"][0], out["rows"][0].keys()
|
||||
con.close()
|
||||
finally:
|
||||
post(server, "/api/admin/mcp", {"enabled": False})
|
||||
|
||||
|
||||
def test_schema_has_mcp_group(server):
|
||||
s = get_status # 占位避免误用
|
||||
r = server["client"].get("/api/schema").json()
|
||||
assert "MCP 接入" in r["groups"]
|
||||
paths = [x["path"] for x in r["groups"]["MCP 接入"]]
|
||||
|
||||
@@ -50,6 +50,19 @@ body{margin:0;font:13px/1.5 "Source Han Sans SC","Noto Sans SC","Source Han Sans
|
||||
#itree .iab.x{color:#b03a2e;border-color:#e3b6b0}
|
||||
#itree .iab.imp{color:#1c66d6;border-color:#9db9e8}
|
||||
#itree .iok{font-size:11px;color:#1f8f4d;white-space:nowrap;flex:none}
|
||||
/* 决策 233 补记(2026-10-28 主人定七条):展开态定高=现高 448×1.5=672,宽度不变;树内滚动,不再加高弹框 */
|
||||
#odlg.exp{height:672px}
|
||||
#odlg.exp .mbody{flex:1;min-height:0}
|
||||
/* 决策 233 补记三(主人定):展开态右/下/右下角拖拽调宽高(收起态原封不动);把手压边内侧,避开页脚按钮 */
|
||||
#odlg .rsz{position:absolute;z-index:6;display:none}
|
||||
#odlg.exp .rsz{display:block}
|
||||
#odlg .rsz-e{right:0;top:0;bottom:56px;width:6px;cursor:ew-resize}
|
||||
#odlg .rsz-s{left:0;right:0;bottom:0;height:6px;cursor:ns-resize}
|
||||
#odlg .rsz-se{right:0;bottom:0;width:14px;height:14px;cursor:nwse-resize}
|
||||
/* 补记三追加(主人定):展开后宽度 1100 不变,右目录占弹框 60%(660px),左表单等比缩小(604→388,标签 88→56);收起态恢复原样 */
|
||||
#oleft{width:604px}
|
||||
#odlg.exp #oleft{width:388px}
|
||||
#odlg.exp #oleft .row > span:not(.combo){width:56px}
|
||||
#itree .ierr{font-size:11px;color:#b03a2e;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:none}
|
||||
#itree .ied input{border:1px solid #9db9e8;border-radius:3px;padding:2px 6px;font-size:13px;min-width:140px;flex:1}
|
||||
table{width:100%;border-collapse:collapse;font-size:12.5px;table-layout:fixed}
|
||||
@@ -351,7 +364,6 @@ body.histdrag{user-select:none}
|
||||
<div class="panel on" id="pan3">
|
||||
<div class="rawbox">
|
||||
<div class="rawtree" id="rawtree"></div>
|
||||
<div id="impWrap" style="position:absolute;top:6px;right:10px;z-index:6"></div>
|
||||
<div class="rawmain">
|
||||
<div class="stabs" id="rawstabs"></div>
|
||||
<div class="rawbody" id="rawbody"></div>
|
||||
@@ -534,48 +546,41 @@ body.histdrag{user-select:none}
|
||||
</div>
|
||||
|
||||
<div class="mask" id="omask" data-page-node-id="NHET3zdzD9HkyEVocucLLz">
|
||||
<div class="dlg" data-page-node-id="rf6sdICi1GOOGBHgzR39N6">
|
||||
<h4 data-page-node-id="035yfGifzpBoUZgrI6XnyA">打开项目</h4>
|
||||
<div class="mbody" data-page-node-id="OoZAOtJ0ridSwFtXLChDyg">
|
||||
<div class="row" data-page-node-id="TgF4geYkFIZIFYQD6sNZHB"><span data-page-node-id="Ve3MJBmbfhkGXf26tQdqAA">全国电子标书</span><input type="file" id="ofile" onchange="autoName()" data-page-node-id="I2kkcqsdiXGL40535vRd25"></div>
|
||||
<div class="row" data-page-node-id="uWAVJwQc4PGXMkVwrLTAWX"><span data-page-node-id="A69LDfDYOD8sJ9RNmYrp7u">工程名称 *</span><input id="oname" placeholder="选文件后自动带出文件名,可改" data-page-node-id="M0HGCQ9uGkUnRnXEshiiDD"></div>
|
||||
<div class="row" data-page-node-id="3Yg2dLI3BNEr0iDvHyyFZR"><span data-page-node-id="a4VMhIZdcf8l3z3znIflbI">基准期次 *</span><input id="oper" placeholder="点这里选起~止(同月就选同一个)" data-page-node-id="NZlB1CroFZvcWL0CyQTZDE"></div>
|
||||
<div class="row" data-page-node-id="chlcT8xdVI2rRjz4HZDVWA"><span data-page-node-id="x8RmHqmvGQTydhqMUR8xAP">地区</span>
|
||||
<select id="oprov" data-page-node-id="xhlO6Gx4yDx7nR51RQWFOf"><option value="" data-page-node-id="A14GaEGzaPfGDepXQCDkfg">省</option></select>
|
||||
<select id="ocity" data-page-node-id="thtavuoK0KGQ5SF2mFRfHj"><option value="" data-page-node-id="TSyGUu116TjZCdD2xkgVZ2">市</option></select>
|
||||
<select id="odist" data-page-node-id="QB7NuG51dQutua0IUQ8Bo4"><option value="" data-page-node-id="A3GttbLNDNTXLIjVf8RCqA">区/县/镇</option></select>
|
||||
<div class="dlg" id="odlg" data-page-node-id="rf6sdICi1GOOGBHgzR39N6">
|
||||
<h4 id="otitle" data-page-node-id="035yfGifzpBoUZgrI6XnyA">打开项目</h4>
|
||||
<div class="mbody" data-page-node-id="OoZAOtJ0ridSwFtXLChDyg" style="display:flex;flex-direction:row;gap:16px;align-items:stretch">
|
||||
<!-- 左栏:宽由 CSS 管(#oleft 604;展开 .exp 388 等比缩小),行距补回 .mbody 的 column gap:10px -->
|
||||
<div id="oleft" style="flex:none;min-width:0;display:flex;flex-direction:column;gap:10px">
|
||||
<div class="row" id="ofileRow" data-page-node-id="TgF4geYkFIZIFYQD6sNZHB"><span data-page-node-id="Ve3MJBmbfhkGXf26tQdqAA">全国电子标书</span><input type="file" id="ofile" onchange="autoName()" data-page-node-id="I2kkcqsdiXGL40535vRd25"></div>
|
||||
<div class="row" data-page-node-id="uWAVJwQc4PGXMkVwrLTAWX"><span data-page-node-id="A69LDfDYOD8sJ9RNmYrp7u">工程名称 *</span><input id="oname" placeholder="选文件后自动带出文件名,可改" data-page-node-id="M0HGCQ9uGkUnRnXEshiiDD"></div>
|
||||
<div class="row" data-page-node-id="3Yg2dLI3BNEr0iDvHyyFZR"><span data-page-node-id="a4VMhIZdcf8l3z3znIflbI">基准期次 *</span><input id="oper" placeholder="点这里选起~止(同月就选同一个)" data-page-node-id="NZlB1CroFZvcWL0CyQTZDE"></div>
|
||||
<div class="row" data-page-node-id="chlcT8xdVI2rRjz4HZDVWA"><span data-page-node-id="x8RmHqmvGQTydhqMUR8xAP">地区</span>
|
||||
<select id="oprov" data-page-node-id="xhlO6Gx4yDx7nR51RQWFOf"><option value="" data-page-node-id="A14GaEGzaPfGDepXQCDkfg">省</option></select>
|
||||
<select id="ocity" data-page-node-id="thtavuoK0KGQ5SF2mFRfHj"><option value="" data-page-node-id="TSyGUu116TjZCdD2xkgVZ2">市</option></select>
|
||||
<select id="odist" data-page-node-id="QB7NuG51dQutua0IUQ8Bo4"><option value="" data-page-node-id="A3GttbLNDNTXLIjVf8RCqA">区/县/镇</option></select>
|
||||
</div>
|
||||
<div class="row" data-page-node-id="yRE3EzGcdeMqaEC2oz71Oy"><span data-page-node-id="HhgkcRHxvZgzjC5BXXGDGC">建设单位</span><input id="obuid" placeholder="输入或从历史项目选择" autocomplete="off"></div>
|
||||
<div class="tip" id="omsg" data-page-node-id="aQ4algswtlQMoiDgBrVN1u"></div>
|
||||
</div>
|
||||
<!-- 导入Excel 右侧目录树面板(决策 233):展开时随弹框定高,树内滚动不加高弹框 -->
|
||||
<div id="opanel" style="display:none;flex:1;min-width:0;flex-direction:column">
|
||||
<div id="itree" style="flex:1;min-height:0;overflow:auto;border:1px solid #e3eaf2;border-radius:6px;padding:6px 4px;background:#fbfcfe"></div>
|
||||
<div class="tip" id="imsg" style="padding-top:8px"></div>
|
||||
</div>
|
||||
<div class="row" data-page-node-id="yRE3EzGcdeMqaEC2oz71Oy"><span data-page-node-id="HhgkcRHxvZgzjC5BXXGDGC">建设单位</span><input id="obuid" placeholder="输入或从历史项目选择" autocomplete="off"></div>
|
||||
<div class="tip" id="omsg" data-page-node-id="aQ4algswtlQMoiDgBrVN1u"></div>
|
||||
</div>
|
||||
<div class="mfoot" data-page-node-id="cIfN6fkvNTvkVdk85JJyPJ">
|
||||
<button class="btn" onclick="omask.classList.remove('on')" data-page-node-id="IAVuhdrc4Ln1HQDrn0cvBd">取消</button>
|
||||
<button class="btn pri" onclick="doOpen()" data-page-node-id="TE1Xb1738DYzPd3zBDAEAAT9o2">打开</button>
|
||||
<button class="btn" onclick="impTemplate()" title="下载单位工程数据结构 Excel(填写说明/分部分项/措施项目)">模板</button>
|
||||
<button class="btn" id="impBtnX" onclick="impExcelToggle()" title="右边展开目录树:建新工程或编辑手工工程目录(有项目打开时也可建新工程)">导入Excel</button>
|
||||
<!-- 决策 233 补记:创建工程与打开合并为一个主按钮——展开态=创建工程(impSave),收起态=打开(doOpen),放最右 -->
|
||||
<button class="btn pri" id="obtnGo" onclick="doOpen()" data-page-node-id="TE1Xb1738DYzPd3zBDAEAAT9o2">打开</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 导入项目(决策 230,2026-10-27 主人定):手工工程——同框建目录树(项目→单项工程→单位工程,
|
||||
点名改名、行尾 +/✕ 增删)+ 每个单位工程行旁「导入单位工程」选 Excel(两个 Sheet 落对应页签) -->
|
||||
<div class="mask" id="imask">
|
||||
<div class="dlg" style="width:680px;max-width:94vw">
|
||||
<h4 id="ititle">导入项目</h4>
|
||||
<div class="mbody">
|
||||
<div class="row"><span>工程名称 *</span><input id="iname" placeholder="如:某某住宅小区施工总承包"></div>
|
||||
<div class="row"><span>基准期次 *</span><input id="iper" placeholder="点这里选起~止(同月就选同一个)"></div>
|
||||
<div class="row" style="align-items:flex-start"><span style="padding-top:6px;flex:none">目录树 *</span>
|
||||
<div id="itree" style="flex:1;min-height:200px;max-height:46vh;overflow:auto;border:1px solid #e3eaf2;border-radius:6px;padding:6px 4px;background:#fbfcfe"></div>
|
||||
</div>
|
||||
<div class="tip" id="imsg"></div>
|
||||
</div>
|
||||
<div class="mfoot">
|
||||
<button class="btn" onclick="impTemplate()">模板</button>
|
||||
<span style="flex:1;font-size:12px;color:#8a97a8">模板=单位工程数据结构 Excel(Sheet:填写说明/分部分项/措施项目)</span>
|
||||
<button class="btn" onclick="imask.classList.remove('on')">取消</button>
|
||||
<button class="btn pri" id="ibtnSave" onclick="impSave()">保存并创建工程</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 手工工程导入入口(决策 233,2026-10-28 主人定):并入「打开项目」弹框——底部常驻 [模板][导入Excel],
|
||||
点「导入Excel」右侧展开目录树(opanel),行内 [Excel 导出]/[导入单位工程] 沿用决策 230;
|
||||
顶栏「导入项目」按钮取消(修改决策 230),工程名称/基准期次/地区/建设单位共用左侧字段 -->
|
||||
<input type="file" id="ifile" accept=".xlsx" style="display:none" onchange="impFile()">
|
||||
|
||||
<!-- 导出进度模态(决策 92,主人定流程):先另存为选路径 → 这里显示进度(生成逐条目% + 写盘%),
|
||||
@@ -597,7 +602,7 @@ body.histdrag{user-select:none}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 手工工程导出格式三选(决策 229,2026-10-27 主人定):cos/cos4 走经典整件骨架,
|
||||
<!-- 手工工程导出格式三选(决策 231,2026-10-27 主人定):cos/cos4 走经典整件骨架,
|
||||
Excel=每单位工程一个 xlsx(项目名文件夹打包 zip)。选完走决策 92 同款另存为+进度流程。 -->
|
||||
<div class="mask" id="fmtmask">
|
||||
<div class="dlg" style="width:420px;max-width:92vw">
|
||||
@@ -971,7 +976,7 @@ window.__exportProgress = function(p){
|
||||
};
|
||||
async function exportSession(fmt){
|
||||
if(!SID){ $('msg').textContent = '先打开工程再导出'; return; }
|
||||
/* 决策 229:手工工程三选(cos4/cos/xlsx);未选格式先弹选择框。普通工程忽略 fmt。 */
|
||||
/* 决策 231:手工工程三选(cos4/cos/xlsx);未选格式先弹选择框。普通工程忽略 fmt。 */
|
||||
fmt=(fmt||'').toLowerCase();
|
||||
if(MANUAL && ['cos4','cos','xlsx'].indexOf(fmt)<0){
|
||||
document.getElementById('fmtmask').classList.add('on'); return;
|
||||
@@ -1717,6 +1722,7 @@ function lmeEditField(td, tr, field){
|
||||
/* ---------- 打开工程 ---------- */
|
||||
async function openDlg(){
|
||||
$('omask').classList.add('on'); // 规格 打开工程BUG2:先显示弹框再清值——此前清值派发的
|
||||
if(IOPEN) impExcelToggle(); // 决策 233:每次打开先收回导入面板,回默认打开模式
|
||||
$('ofile').value=''; $('oname').value=''; $('oname').dataset.auto=''; $('omsg').textContent=''; // input
|
||||
$('oper').value=''; $('oprov').value=''; $('ocity').value=''; $('odist').value=''; // 事件在
|
||||
$('obuid').value=''; $('obuid').dispatchEvent(new Event('input', {bubbles:true})); // 隐藏态测量
|
||||
@@ -1773,7 +1779,7 @@ function setManualMode(manual){
|
||||
MANUAL=!!manual;
|
||||
const b=document.getElementById('btnExport');
|
||||
if(b){
|
||||
/* 决策 229:手工工程放开导出——cos/cos4(经典骨架)与 Excel 三选,点导出先弹格式选择 */
|
||||
/* 决策 231:手工工程放开导出——cos/cos4(经典骨架)与 Excel 三选,点导出先弹格式选择 */
|
||||
b.disabled=false;
|
||||
b.title=manual
|
||||
? '手工工程导出:.cos/.cos4(经典整件骨架当模板)或 Excel(每单位工程一个文件)'
|
||||
@@ -3485,47 +3491,100 @@ function cfgTab(name){
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
/* ================= 导入项目(手工工程·决策 230):同框建目录树 + 按单位工程导 Excel =================
|
||||
按钮显隐三态:空态(未打开工程)显示;源文件工程隐藏;手工工程常驻(再点回弹框补目录/覆盖导入)。 */
|
||||
let ITREE=null, ISEL='';
|
||||
mkPeriod($('iper'));
|
||||
/* ================= 导入Excel(手工工程·决策 233,2026-10-28 主人定):打开项目弹框右侧目录树面板 =================
|
||||
底部常驻 [模板][导入Excel](打开按钮右边,有项目打开也能点);点「导入Excel」右边展开现目录树
|
||||
(决策 230 行内按钮沿用+行首 Excel 导出);顶栏「导入项目」按钮取消(修改决策 230);
|
||||
工程名称/基准期次/地区/建设单位共用左侧字段,创建时随 save 落库。 */
|
||||
let ITREE=null, ISEL='', IOPEN=false, EXPW=1100, EXPH=672; // EXPW/EXPH=展开默认尺寸(1100×现高1.5),可拖拽改
|
||||
function impVis(){
|
||||
const w=$('impWrap'); if(!w) return;
|
||||
w.innerHTML = (!SID || MANUAL)
|
||||
? '<button class="btn pri" style="padding:3px 12px;font-size:12px" onclick="impDlgOpen()">导入项目</button>' : '';
|
||||
const t=document.getElementById('rawtree');
|
||||
if(t && !SID) t.innerHTML='<div style="padding:28px 14px;color:#8a97a8;text-align:center;line-height:2">尚未打开工程<br>点右上角「导入项目」:建目录树、按单位工程导入 Excel</div>';
|
||||
if(t && !SID) t.innerHTML='<div style="padding:28px 14px;color:#8a97a8;text-align:center;line-height:2">尚未打开工程<br>点右上角「打开项目」→「导入Excel」:建目录树、按单位工程导入 Excel</div>';
|
||||
}
|
||||
(function(){ const _sm=setManualMode; setManualMode=function(m){ _sm(m); impVis(); }; })();
|
||||
impVis();
|
||||
|
||||
function impDlgOpen(){
|
||||
ITREE=[{name:'单项工程 1',units:[{name:'单位工程 1'}]}];
|
||||
$('iname').value=''; $('iper').value=''; $('ifile').value=''; $('imsg').textContent='';
|
||||
$('ititle').textContent='导入项目';
|
||||
$('ibtnSave').textContent='保存并创建工程';
|
||||
imask.classList.add('on');
|
||||
impTreeRender();
|
||||
if(SID && MANUAL){ // 手工工程:回填现有目录树
|
||||
J('/api/session/manual/state?session_id='+SID).then(d=>{
|
||||
if(d && d.ok && d.sections && d.sections.length){
|
||||
ITREE=d.sections.map(s=>({id:s.id,name:s.name,
|
||||
units:(s.units||[]).map(u=>({id:u.id,name:u.name,n_item:u.n_item,n_prelim:u.n_prelim}))}));
|
||||
$('iname').value=d.name||'';
|
||||
if(d.period_from){ // 基准期次回填(月序号 → YYYY-MM)
|
||||
const f2s=v=>{const y=Math.floor(v/12),m=v%12||12;return (m===12?y-1:y)+'-'+String(m).padStart(2,'0');};
|
||||
setPeriod($('iper'), f2s(d.period_from), f2s(d.period_to||d.period_from));
|
||||
/* 补记三:展开态右缘/下缘/右下角拖拽调宽高——dlg 已被 dlgPin 转固定定位(left/top 不动),
|
||||
拖拽只改宽高即以左上角为锚;范围钳在视口内,宽不小于左栏 604+树最小可用。收起态把手不显示。 */
|
||||
(function(){
|
||||
const dlg=document.getElementById('odlg'); if(!dlg) return;
|
||||
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
|
||||
const mk=(cls,fn)=>{
|
||||
const h=document.createElement('div'); h.className='rsz '+cls;
|
||||
h.addEventListener('mousedown',e=>{
|
||||
if(!IOPEN) return;
|
||||
e.preventDefault();
|
||||
const r=dlg.getBoundingClientRect();
|
||||
const mv=ev=>fn(ev,r.left,r.top);
|
||||
const up=()=>{document.removeEventListener('mousemove',mv);document.removeEventListener('mouseup',up);};
|
||||
document.addEventListener('mousemove',mv); document.addEventListener('mouseup',up);
|
||||
});
|
||||
dlg.appendChild(h);
|
||||
};
|
||||
mk('rsz-e',(ev,L)=>{ EXPW=clamp(ev.clientX-L,900,innerWidth-40); dlg.style.width=EXPW+'px'; });
|
||||
mk('rsz-s',(ev,L,T)=>{ EXPH=clamp(ev.clientY-T,420,innerHeight-40); dlg.style.height=EXPH+'px'; });
|
||||
mk('rsz-se',(ev,L,T)=>{ EXPW=clamp(ev.clientX-L,900,innerWidth-40); EXPH=clamp(ev.clientY-T,420,innerHeight-40);
|
||||
dlg.style.width=EXPW+'px'; dlg.style.height=EXPH+'px'; });
|
||||
})();
|
||||
|
||||
function impExcelToggle(){
|
||||
IOPEN=!IOPEN;
|
||||
const on=IOPEN;
|
||||
$('opanel').style.display=on?'flex':'none';
|
||||
$('ofileRow').style.display=on?'none':''; // 创建/编辑模式不选标书,共用左侧表单字段
|
||||
$('impBtnX').classList[on?'add':'remove']('pri');
|
||||
// 展开尺寸可拖拽(补记三):默认 1100×672(现高×1.5),拖过记入 EXPW/EXPH,会话内保持
|
||||
$('odlg').style.width=on?EXPW+'px':'';
|
||||
$('odlg').style.height=on?EXPH+'px':'';
|
||||
$('odlg').classList[on?'add':'remove']('exp');
|
||||
// 创建工程与打开合并为一个主按钮(决策 233 补记):展开=创建工程,收起=打开
|
||||
$('obtnGo').textContent=on?'创建工程':'打开';
|
||||
$('obtnGo').onclick=on?impSave:doOpen;
|
||||
if(typeof dlgPin==='function') dlgPin($('odlg')); // 开框时已按 640 钉位转 fixed,加宽/收窄须重居中(common.js 共用)
|
||||
if(on){
|
||||
ITREE=[{name:'单项工程 1',units:[{name:'单位工程 1'}]}];
|
||||
$('ifile').value=''; $('imsg').textContent='';
|
||||
$('obtnGo').textContent='创建工程';
|
||||
$('otitle').textContent='打开项目 · 导入Excel';
|
||||
impTreeRender();
|
||||
if(SID && MANUAL){ // 手工工程:回填现有目录树+共用字段
|
||||
J('/api/session/manual/state?session_id='+SID).then(d=>{
|
||||
if(!IOPEN) return;
|
||||
if(d && d.ok && d.sections && d.sections.length){
|
||||
ITREE=d.sections.map(s=>({id:s.id,name:s.name,
|
||||
units:(s.units||[]).map(u=>({id:u.id,name:u.name,n_item:u.n_item,n_prelim:u.n_prelim}))}));
|
||||
$('oname').value=d.name||'';
|
||||
if(d.period_from){ // 基准期次回填(月序号 → YYYY-MM)
|
||||
const f2s=v=>{const y=Math.floor(v/12),m=v%12||12;return (m===12?y-1:y)+'-'+String(m).padStart(2,'0');};
|
||||
setPeriod($('oper'), f2s(d.period_from), f2s(d.period_to||d.period_from));
|
||||
}
|
||||
impSelSet('oprov',d.province); impSelSet('ocity',d.city); impSelSet('odist',d.district);
|
||||
$('obuid').value=d.bulid_unit||'';
|
||||
$('otitle').textContent='打开项目 · 导入Excel · 编辑目录树';
|
||||
$('obtnGo').textContent='保存(更新目录树)';
|
||||
impTreeRender();
|
||||
}
|
||||
$('ititle').textContent='导入项目 · 编辑目录树';
|
||||
$('ibtnSave').textContent='保存(更新目录树)';
|
||||
impTreeRender();
|
||||
}
|
||||
}).catch(()=>{});
|
||||
}).catch(()=>{});
|
||||
}
|
||||
}else{
|
||||
$('otitle').textContent='打开项目';
|
||||
}
|
||||
}
|
||||
function impSelSet(id,v){ // 地区回填:选项池没有该值就补一条(历史数据兜底)
|
||||
const s=$(id); v=(v||'').trim();
|
||||
if(v && ![...s.options].some(o=>o.value===v)){
|
||||
const o=document.createElement('option'); o.value=v; o.textContent=v; s.appendChild(o);
|
||||
}
|
||||
s.value=v;
|
||||
}
|
||||
function impExportUw(si,ui){ // 决策 233 方案a:单单位工程导 Excel(231 通道同构,可回导)
|
||||
const u=ITREE[si].units[ui];
|
||||
if(!(SID&&MANUAL&&u.id)){ $('imsg').textContent='先保存工程,再导出该单位工程'; return; }
|
||||
if(!(u.n_item||u.n_prelim)){ $('imsg').textContent='「'+(u.name||'')+'」还没有清单数据'; return; }
|
||||
saveAs('/api/session/manual/export_unit?session_id='+SID+'&uw='+u.id, (u.name||'单位工程')+'.xlsx');
|
||||
}
|
||||
function impTreeRender(){
|
||||
const nm=$('iname').value.trim()||'(工程名称)';
|
||||
let h='<div class="ied"><span class="itag tg0">项目</span><span class="inm" onclick="$(\'iname\').focus()" style="cursor:pointer" title="点改名(顶部工程名称)">'+esc(nm)+'</span>'
|
||||
const nm=$('oname').value.trim()||'(工程名称)';
|
||||
let h='<div class="ied"><span class="itag tg0">项目</span><span class="inm" onclick="$(\'oname\').focus()" style="cursor:pointer" title="点改名(左侧工程名称共用字段)">'+esc(nm)+'</span>'
|
||||
+'<span class="iact"><button class="iab" onclick="impAddSec()">+单项工程</button></span></div>';
|
||||
ITREE.forEach((s,si)=>{
|
||||
h+='<div class="ied" style="padding-left:26px"><span class="itag tg1">单项工程</span><span class="inm" onclick="impRename(this,'+si+',-1)">'+esc(s.name)+'</span>'
|
||||
@@ -3537,10 +3596,11 @@ function impTreeRender(){
|
||||
if(u.err) st='<span class="ierr" title="'+esc(u.err)+'">✗ '+esc(u.err)+'</span>';
|
||||
else if(u.file) st='<span class="iok">✓ 清单'+u.n_item+'+措施'+u.n_prelim+'</span>';
|
||||
else if(u.id && (u.n_item||u.n_prelim)) st='<span class="iok">✓ 清单'+u.n_item+'+措施'+u.n_prelim+'</span>';
|
||||
h+='<div class="ied" style="padding-left:52px"><span class="itag tg2">单位工程</span><span class="inm" onclick="impRename(this,'+si+','+ui+')">'+esc(u.name)+'</span>'
|
||||
h+='<div class="ied" style="padding-left:52px"><span class="itag tg2">单位工程</span><span class="inm" title="'+esc(u.name)+'" onclick="impRename(this,'+si+','+ui+')">'+esc(u.name)+'</span>'
|
||||
+st
|
||||
+'<span class="iact"><button class="iab" title="组内上移" onclick="impMovUw('+si+','+ui+',-1)"'+(ui===0?' disabled':'')+'>↑</button>'
|
||||
+'<button class="iab" title="组内下移" onclick="impMovUw('+si+','+ui+',1)"'+(ui===s.units.length-1?' disabled':'')+'>↓</button>'
|
||||
+'<button class="iab" onclick="impExportUw('+si+','+ui+')" title="导出该单位工程单个 Excel(决策 231 Excel 通道同构,可回导)">Excel 导出</button>'
|
||||
+'<button class="iab imp" onclick="impPick('+si+','+ui+')" title="按模板导入(整单位工程覆盖)">导入单位工程</button><button class="iab x" onclick="impDelUw('+si+','+ui+')">✕</button></span></div>';
|
||||
});
|
||||
});
|
||||
@@ -3580,24 +3640,24 @@ async function impFile(){
|
||||
}
|
||||
function impTemplate(){ return saveAs('/api/session/manual/template','单位工程导入模板.xlsx'); }
|
||||
async function impSave(){
|
||||
const name=$('iname').value.trim(), pv=PVAL($('iper'));
|
||||
if(!name){ $('imsg').textContent='工程名称必填'; return; }
|
||||
const name=$('oname').value.trim(), pv=PVAL($('oper'));
|
||||
if(!name){ $('imsg').textContent='工程名称必填(左边共用字段)'; return; }
|
||||
if(pv.f==null||pv.t==null){ $('imsg').textContent='基准期次必填:点开选起~止(同月就选同一个)'; return; }
|
||||
for(const s of ITREE){
|
||||
if(!s.name.trim()){ $('imsg').textContent='单项工程名称不能为空'; return; }
|
||||
if(!s.units.length){ $('imsg').textContent='「'+s.name+'」下至少一个单位工程'; return; }
|
||||
for(const u of s.units) if(!u.name.trim()){ $('imsg').textContent='单位工程名称不能为空'; return; }
|
||||
}
|
||||
$('ibtnSave').disabled=true; $('imsg').textContent='正在保存…';
|
||||
$('obtnGo').disabled=true; $('imsg').textContent='正在保存…';
|
||||
try{
|
||||
const r=await J('/api/session/manual/save',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({sid:(SID&&MANUAL)?SID:0,name,period_from:pv.f,period_to:pv.t,
|
||||
province:$('oprov').value,city:$('ocity').value,district:$('odist').value,bulid_unit:$('obuid').value,
|
||||
tree:ITREE.map(s=>({id:s.id||0,name:s.name.trim(),
|
||||
units:s.units.map(u=>({id:u.id||0,name:u.name.trim(),file:u.file||''}))}))})});
|
||||
if(!r.ok){ $('imsg').textContent=r.msg||'保存失败'; return; }
|
||||
imask.classList.remove('on');
|
||||
location.href='/workbench.html?sid='+r.session_id; // 手工工程:initFromUrl 跳过重解析
|
||||
} finally { $('ibtnSave').disabled=false; }
|
||||
} finally { $('obtnGo').disabled=false; }
|
||||
}
|
||||
</script>
|
||||
<script>licMount('.tabright');</script><!-- 统一设置窗口+到期预警(决策 31,实现在 common.js) -->
|
||||
|
||||
Reference in New Issue
Block a user