From f142910bbdf22e30b76108fe21ec34d7b93cf58f Mon Sep 17 00:00:00 2001
From: lianjianwei2024 <168657369+lianjianwei2024@users.noreply.github.com>
Date: Fri, 6 Nov 2026 10:15:07 +0800
Subject: [PATCH] =?UTF-8?q?feat(export):=20=E6=81=A2=E5=A4=8D=E6=97=A7?=
=?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=BC=95=E6=93=8E=E5=B9=B6=E5=8A=A0=E5=9B=BA?=
=?UTF-8?q?=E6=8D=A2=E8=A1=8C=E4=B8=8E=E8=88=8D=E5=85=A5=E3=80=81=E6=96=B0?=
=?UTF-8?q?=E5=A2=9E=E9=87=87=E7=BA=B3=E6=9D=A5=E6=BA=90=E6=BA=AF=E6=BA=90?=
=?UTF-8?q?=E4=B8=8E=E9=A1=B9=E7=9B=AE=E7=9B=AE=E5=BD=95=E6=8E=92=E5=BA=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
CostReview/app/core/classic_skeleton.py | 66 ++
CostReview/app/core/export_cos.py | 336 +++++++-
CostReview/app/core/export_v2.py | 757 ------------------
CostReview/app/core/session_job.py | 2 +
CostReview/app/server/api_server.py | 623 +++++++++++++-
CostReview/app/server/license_client/gate.py | 8 +-
CostReview/app/server/mcp_server.py | 21 +
CostReview/app/server/version_gate.py | 4 +-
CostReview/app/store/schema.sql | 1 +
CostReview/app/store/session.sql | 23 +-
CostReview/app/tests/api_harness.py | 6 +-
CostReview/app/tests/test_adopt_src256.py | 56 ++
CostReview/app/tests/test_export_ext.py | 79 +-
CostReview/app/tests/test_export_rollup.py | 6 +-
CostReview/app/tests/test_export_structure.py | 4 +-
CostReview/app/tests/test_form_bank.py | 170 ++++
CostReview/app/tests/test_norm_op.py | 23 +-
CostReview/app/tests/test_own_skeleton.py | 4 +-
CostReview/app/ui/admin.html | 69 +-
CostReview/app/ui/common.css | 8 +
CostReview/app/ui/fonts/LICENSE-OFL.txt | 93 +++
CostReview/app/ui/sessions.html | 150 +++-
CostReview/app/ui/workbench.html | 48 ++
test/字体加固/生成字体.py | 90 +++
决策台账.md | 106 +++
决策台账索引.md | 13 +
26 files changed, 1832 insertions(+), 934 deletions(-)
create mode 100644 CostReview/app/tests/test_adopt_src256.py
create mode 100644 CostReview/app/tests/test_form_bank.py
create mode 100644 CostReview/app/ui/fonts/LICENSE-OFL.txt
create mode 100644 test/字体加固/生成字体.py
diff --git a/CostReview/app/core/classic_skeleton.py b/CostReview/app/core/classic_skeleton.py
index f7e44ea..36f2774 100644
--- a/CostReview/app/core/classic_skeleton.py
+++ b/CostReview/app/core/classic_skeleton.py
@@ -674,3 +674,69 @@ def stats(con):
return [dict(r) for r in con.execute(
"SELECT suffix,original_name,n_shapes,n_nodes,extracted_at FROM classic_skel "
"ORDER BY suffix, n_nodes DESC")]
+
+
+# ---------------- 形态银行(决策 274 补,2026-11-05 主人定)----------------
+# 「先盘查同后缀的大骨架的卡槽相似度,主要以卡槽为准」——本项目源件分层列集 vs
+# 候选件(同后缀的历史项目源件含最近审核项目+后台骨架库件)分层列集逐件打分,
+# 得分最多的件被采用,从它身上提取局部小骨架(行/块形态)。借形态不借条数:
+# 形态只当自增样板,输出条数按库数据走(266 自增口径);值一律来自库(259 不造数据)。
+
+_FORM_TAGS = ("Norm", "LabourMaterialsEquipmentsMachinesElement", "NormAdjustmentList",
+ "UnitPriceCalculationOfItem", "LabourMaterialsEquipmentsMachinesSummary")
+
+
+def _local_forms(blob, tags=None):
+ """一份同后缀原格式件 → 关键 tag 的最全局部形态 {tag: 串}。
+ 行=属性最多的自闭合行(Express 槽优先);Norm=属性最多+最长的完整块。
+ 认不出/没有该 tag → 该键缺席(fail-open=现状硬编码最小形态)。"""
+ tags = list(tags or _FORM_TAGS)
+ text = None
+ try:
+ z = zipfile.ZipFile(io.BytesIO(bytes(blob)))
+ cands = [n for n in z.namelist()
+ if n.lower() != "project.xml" and n.lower().endswith(".xml")]
+ scored = []
+ for n in cands:
+ t = z.read(n).decode("utf-8", "replace")
+ scored.append((t.count("]*?>.*?', text, re.S)
+ if not blocks:
+ blocks = re.findall(r']*?/>', text)
+ if blocks:
+ out[tag] = max(blocks, key=lambda b: (len(re.findall(r'[A-Za-z]+="', b)), len(b)))
+ continue
+ rows = re.findall('<' + tag + r'\b[^>]*?/>', text)
+ if not rows:
+ m = re.search(r'<' + tag + r'\b[^>]*?>.*?' + tag + '>', text, re.S)
+ rows = [m.group(0)] if m else []
+ if rows:
+ out[tag] = max(rows, key=lambda r: (len(re.findall(r'[A-Za-z]+="', r)),
+ ' Express="' in r, len(r)))
+ return out
+
+
+def local_form_bank(src_cols, candidates, tags=None):
+ """形态银行挑选:candidates=[(名, blob字节)](调用方保证**同后缀**),
+ 逐件 match_score(卡槽相似度)盘查,得分最多的件 → 它的局部小骨架。
+ src_cols=本项目源件分层列集(layer_cols_of);无候选/全零分 → {}。"""
+ best, best_s = None, -1.0
+ for nm, blob in candidates or []:
+ try:
+ s = match_score(src_cols or {}, layer_cols_of(blob))
+ except Exception:
+ s = -1.0
+ if s > best_s:
+ best, best_s = blob, s
+ if best is None or best_s <= 0:
+ return {}
+ return _local_forms(best, tags)
diff --git a/CostReview/app/core/export_cos.py b/CostReview/app/core/export_cos.py
index 0c210c2..ffc546b 100644
--- a/CostReview/app/core/export_cos.py
+++ b/CostReview/app/core/export_cos.py
@@ -41,7 +41,10 @@ def _unesc(s):
def _esc(v):
- return ("" if v is None else str(v)).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
+ # 换行加固(2026-11-05 主人定「恢复旧引擎+加固换行恢复逻辑」):属性值里的字面 LF/CR
+ # 在 XML 解析时按规范归一成空格——写回编辑值必须显式转实体才能保住换行
+ # (项目特征 Names 老毛病根治;未编辑节点原文原样保留不经此路径,无影响)。
+ return ("" if v is None else str(v)).replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("\r", "
").replace("\n", "
")
def _attr(open_tag, name):
@@ -82,13 +85,26 @@ def _num_eq(a, b):
return False
+from decimal import Decimal, ROUND_HALF_UP as _RHU
+
+
+def _ru(v, dec):
+ """四舍五入 half-up 格式化(对齐易达——Python %.*f 与 round 是银行家舍入+浮点表示
+ 偏差,3.68475 实证:易达 3.6848、我们 3.6847;2026-11-05 三方对拍根因)。返回定长小数字符串。"""
+ try:
+ q = Decimal(1) if dec <= 0 else Decimal("1e-%d" % dec)
+ return str(Decimal(str(float(v))).quantize(q, rounding=_RHU))
+ except Exception:
+ return "" if v is None else str(v)
+
+
def _fmt_qty(v, dec):
"""工程量按源文件规律定格式写出(规格 2026-10-16:横琴 234/234 定额 Quantity 恒 6 位
小数、113/113 清单恒 3 位)——改过的量按修改后的数字、按原文件同款小数位导出。"""
if v is None:
return None
try:
- return "%.*f" % (dec, float(v))
+ return _ru(v, dec)
except (TypeError, ValueError):
return v
@@ -148,6 +164,24 @@ def _apply_div_totals(txt, plans):
return txt if not out else "".join(out)
+def _qty_like(raw, v):
+ """按**该清单源件原文**的小数位写工程量(决策 274 补记三,2026-11-05 主人定
+ 「原数据来多少位保留多少位」——编辑过的原有清单逐条随源件原文位数;
+ 原文位数装不下真值(round-trip 不等)→ 升位保真不丢值;新增清单仍 3 位=244 补六)。"""
+ try:
+ fv = float(v)
+ except (TypeError, ValueError):
+ return v
+ dec = 0
+ if raw and "." in str(raw):
+ dec = len(str(raw).split(".", 1)[1])
+ s = "%.*f" % (dec, fv)
+ while dec < 8 and float(s) != fv:
+ dec += 1
+ s = "%.*f" % (dec, fv)
+ return s
+
+
def _ws_eq(a, b):
"""空白规范化比较:XML 解析器按规范把属性值里的换行/制表符规范化成空格——
会话库里的项目特征是空格版、源文件是换行版,内容其实一致。
@@ -321,7 +355,7 @@ def _norm_parts(tmpl):
return opentag, inner[:spans[0].start()], spans[0].group(0), inner[spans[-1].end():]
-def _norm_xml(n, lres, template=None, bill_qty=None):
+def _norm_xml(n, lres, template=None, bill_qty=None, form_bank=None):
"""定额行:优先克隆源文件同类 Norm 的完整属性集(值除会话字段外原样保留,
与易达的已知可行解一致);没有模板时退回最小形态。会话没算出的数值写 0
(易达同款处理)——占位属性可以在位为 0,但不能缺席。
@@ -329,6 +363,9 @@ def _norm_xml(n, lres, template=None, bill_qty=None):
公式行)一并保留(结果值清零、工料机行按模板首行形态重写为会话资源)。此前只克隆
开标签,插出的定额缺单价计算公式行:易达看不到新增清单、广联达整包报「不是有效标书」
(前山河 cos / 屏西五路 cos4 同因实测)。传开标签时行为与旧版一致。"""
+ # 形态银行(决策 274 补,2026-11-05 主人定「同后缀卡槽相似度」):源件没有合格定额块
+ # → 借相似件的定额块当**自增块样板**(借形态不借值,库值照灌;无银行=原最小形态)
+ template = template or (form_bank or {}).get("Norm")
opentag, pre, row_tmpl, post = _norm_parts(template or "")
if opentag:
tag = _clone_open_tag(opentag)
@@ -359,21 +396,53 @@ def _norm_xml(n, lres, template=None, bill_qty=None):
ex = it[2] if len(it) > 2 else None
yield c, q, ex
+ # 决策 273(2026-11-05 主人定稿;恢复旧引擎后通道移回手术层):库带行组(x_side)时
+ # 单价计算行按库整组替换——列序照模板第一条单价行(骨架列闸门),值照库(采纳时已按
+ # Name 匹配好外部 Total);模板行有而行组没有的属性不写(决策 259 同款:来源没有不造)。
+ # 无行组 → 维持决策 106 语义(模板 innards 保留、结果值清零)。
+ _side_rows = None
+ try:
+ _sd = json.loads(n.get("x_side") or "")
+ if isinstance(_sd, list):
+ _side_rows = [r for r in _sd if r.get("tag")]
+ except (TypeError, ValueError):
+ _side_rows = None
# 决策 204:组成行照本件原生分隔换行(一行一条、缩进同源),不再堆成一团
sep_el = _native_sep(template, _LME)
- if row_tmpl is None:
+ _row_t = row_tmpl or (form_bank or {}).get(_LME)
+ if not _row_t:
kids = sep_el.join('<%s Number="%s" Quantity="%s" NOCost="false" Remark=""/>' % (_LME, _esc(c), _esc(q))
for c, q, _ex in _lres())
else:
# 决策 106 补记十二:含量行 Express 优先填**历史项目自己的调整式**(如 1611.66*1.2),
# 没有算式的退裸含量——采纳定额的换算调整跟着历史项目走。
- kids = sep_el.join(_lme_row(row_tmpl, c, q, express=_esc(ex) if ex else _esc(q))
+ kids = sep_el.join(_lme_row(_row_t, c, q, express=_esc(ex) if ex else _esc(q))
for c, q, ex in _lres())
- if pre or row_tmpl is not None or post:
+ # 换算记录提前解析:无模板但有 x_adjust(或银行借到 adj 形态)也必须走 innards 分支,
+ # 否则换算行整段跳过(264 前同类潜伏缺陷:无模板定额的调整记录静默丢失)
+ try:
+ adj_vals = json.loads(n.get("x_adjust") or "[]")
+ except (TypeError, ValueError):
+ adj_vals = []
+ if not (isinstance(adj_vals, list) and adj_vals):
+ adj_vals = []
+ if pre or row_tmpl is not None or post or adj_vals:
# 数量算式行(ExpressElement):**采纳/新增的定额一律不带**——主人实测:易达对带
# 算式行的定额按计算式显示(QGCL 代号 / [24.7157] 方括号值),都不是要的纯数字;
# 去掉算式行后易达直接显示 Quantity 属性。原生未动定额的算式行原样保留(原样原则)。
+ _m_up = (re.search(']*?/>', pre)
+ or re.search(']*?/>', post))
pre, post = _zero_results(pre), _zero_results(post)
+ if _side_rows and _m_up:
+ _order = re.findall(' ([A-Za-z0-9_]+)="', _m_up.group(0))
+ _rows = []
+ for _r in _side_rows:
+ _at = _r.get("attrs") or {}
+ _rows.append('<%s%s/>' % (_r.get("tag"), "".join(
+ ' %s="%s"' % (k, _esc(_at[k])) for k in _order if _at.get(k) is not None)))
+ pre = re.sub(']*?/>', '', pre)
+ post = re.sub(']*?/>', '', post)
+ post = "".join(_rows) + post # 回插 LME 之后原区域(行序照库=显示端一致)
pre = re.sub(r']*/>', '', pre)
post = re.sub(r']*/>', '', post)
# 换算调整记录(补记十三):先剥掉模板的记录(那是模板定额的历史),再按本定额
@@ -383,14 +452,11 @@ def _norm_xml(n, lres, template=None, bill_qty=None):
# 会话携带的 x_adjust 重写——采纳定额的调整工艺(GConvInfo 标准换算/R*2,J*2/送桩
# 材料含量…)跟历史项目走,主人定「有信息就要搬」。行形态照模板首行克隆。
m_adj = re.search(r']*/>', post)
- adj_tmpl = m_adj.group(0) if m_adj else ''
+ adj_tmpl = m_adj.group(0) if m_adj else ((form_bank or {}).get("NormAdjustmentList")
+ or '')
post = re.sub(r']*/>', '', post)
post = re.sub(r']*>.*?', '', post)
- try:
- adj_vals = json.loads(n.get("x_adjust") or "[]")
- except (TypeError, ValueError):
- adj_vals = []
- if isinstance(adj_vals, list) and adj_vals:
+ if adj_vals:
rows = "".join(_attr_set(_attr_set(adj_tmpl, "OrderNumber", str(i + 1)), "Value", str(v))
for i, v in enumerate(adj_vals))
post += rows
@@ -542,7 +608,7 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
if m0.group(1) == "WorkContent":
wc = '' % (
_esc(b.get("Name") or ""),
- ("%.2f" % b["Total"]) if b.get("Total") is not None else "0")
+ _ru(b["Total"], 2) if b.get("Total") is not None else "0")
region = sep_n.join(wc + nx + "" for nx in norms_xml)
else:
region = sep_n.join(norms_xml) # pre 自带首个分隔(原生克隆),块间补齐
@@ -576,7 +642,7 @@ def _bill_xml(b, tag, norms_xml, template=None, txt=None):
bq = 0.0
rows = []
for c in order:
- vs = "%.4f" % round((agg[c] / bq if bq else 0.0), 4)
+ vs = _ru((agg[c] / bq if bq else 0.0), 4)
rows.append(_lme_row(lspans[0].group(0), c, vs, express=vs))
post = post[:lspans[0].start()] + _native_sep(tmpl_blk, _LME).join(rows) + post[lspans[-1].end():]
return t + _zero_results(pre) + region + _zero_results(post) + close
@@ -602,7 +668,7 @@ def _restore_attr_breaks(txt, s):
return re.sub(r"[ \t]+(?=\d{1,3}、)", _attr_sep_of(txt), s)
-def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmpls=None):
+def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmpls=None, form_bank=None, lme_untouched=False):
"""一份单位工程 xml 的手术。
uwkey = (uwNumber, uwName)——与文件里 匹配
@@ -681,6 +747,8 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
# 原来没有的属性不凭空新增(避免 Attr=""/Remark="" 这类扩大修改),
# 数值型属性按数值比较(源文件 3803.180 与会话 3803.18 不算改动,不重写格式)
# 决策 90(2026-10-17):Price/Total 入列——采纳价覆盖清单单价后要能落进文件)
+ if lme_untouched: # 决策 274 补记四:无动作会话原位零写回(库=打开时采集值,
+ continue # 字段差异=采集误差,源件为准——含 Attr 等文本字段)
newtag = mk["opentag"]
for attr, col in (("Name", "Name"), ("Attr", "Attr"), ("Unit", "Unit"),
("Quantity", "Quantity"), ("Price", "Price"), ("Total", "Total"),
@@ -689,7 +757,9 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
if want is None:
continue # 会话没值的字段不回写(写 "None" 反而是破坏)
if attr == "Quantity":
- want = _fmt_qty(want, 3) # 清单工程量按源文件规律 3 位小数导出
+ # 决策 274 补记三:编辑过的原有清单按**该清单源件原文的小数位**写
+ # (原数据来多少位保留多少位);位数装不下真值时升位保真(_qty_like)
+ want = _qty_like(_attr(mk["opentag"], "Quantity"), want)
elif attr in ("Price", "Total"):
# 决策 244 补六(2026-11-01 主人定):清单单价/合价统一 2 位小数导出
# (数值未变的行不重写,原件格式保持)
@@ -748,10 +818,12 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
newn = nsp["opentag"]
for attr in ("Name", "Quantity", "Total"):
if attr == "Total":
- # 补记十六:改过工程量的定额 合价=工程量×单价(数值相同不重写)
- if nn["Quantity"] is None or nn["Price"] is None:
+ # 决策 274 补记七(2026-11-05 主人定「导入=导出,不失真」):合价写库值——
+ # 用户编辑量/价时保存 API 已同步=新量×价;未编辑=源件原值(实证
+ # 891.31,按显示舍入量重算=891.33 放大误差——撤补记十六现算)。
+ if nn["Total"] is None:
continue
- w = "%.2f" % round(float(nn["Quantity"]) * float(nn["Price"]), 2)
+ w = _ru(float(nn["Total"]), 2) # 合价 2 位(244 补六;half-up)
if not _num_eq(_attr(newn, "Total"), w):
newn = _attr_set(newn, "Total", w)
continue
@@ -778,14 +850,14 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
# WorkContent 之后(工料机汇总平铺表之前)。此前裸 Norm 插在块尾
# (汇总表和单价计算节点之后),广联达按 schema 解析错位 →
# 采纳定额的工料机外溢到定额层(屏西五路 040301004001 实测)。
- body = "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"])
+ body = "".join(_norm_xml(nn, res_by_norm.get(nn["id"], []), tmpl, bill_qty=b["Quantity"], form_bank=form_bank)
for nn in napp)
if has_wc and wc_close != -1:
ins = wc_close + len("")
# 决策 99:原生 WorkContent 恒带 Name/Total/Remark 三属性(清单名/清单合价 2 位/空)
wc_tag = '' % (
_esc(b.get("Name") or ""),
- ("%.2f" % b["Total"]) if b.get("Total") is not None else "0")
+ _ru(b["Total"], 2) if b.get("Total") is not None else "0")
edits.append((ins, ins, wc_tag + body + ""))
else:
ci = mk["end"] - len(CLOSE[mk["tag"]])
@@ -840,7 +912,7 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
row_tmpl = txt[dspans[0][0]:dspans[0][1]] if dspans else None
kid = ""
for c in add:
- vs = "%.4f" % round((agg.get(c, 0.0) / bq if bq else 0.0), 4)
+ vs = _ru((agg.get(c, 0.0) / bq if bq else 0.0), 4)
kid += (_lme_row(row_tmpl, c, vs, express=vs) if row_tmpl else
'<%s Number="%s" Express="%s" Quantity="%s" Remark=""/>'
% (_LME, _esc(c), _esc(vs), _esc(vs)))
@@ -908,7 +980,7 @@ def transform_unit(txt, uwkey, pairs, news, norms_by_bill, res_by_norm, bill_tmp
break
if nn_tmpl is None:
nn_tmpl = norm_tmpl
- norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl,
+ norms_xml = [_norm_xml(nn, res_by_norm.get(nn["id"], []), nn_tmpl or norm_tmpl, form_bank=form_bank,
bill_qty=b["Quantity"])
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))
@@ -1075,7 +1147,7 @@ def _lme_apply_price(newtag, px):
continue # 骨架没有的属性不发明
try:
pv = px.get(pattr)
- tv = "" if (q is None or pv is None) else "%.2f" % (q * float(pv))
+ tv = "" if (q is None or pv is None) else _ru(q * float(pv), 2)
except (TypeError, ValueError):
tv = ""
_set(tot, tv)
@@ -1305,7 +1377,7 @@ def _child_node(tmpl, code, qty):
(两属性语义同源=组成含量,2026-10-24 实测:源行只有 Express 时只写 Quantity 会让
Express 残留模板第一条的值——三行 1.1320 的根源),两个都在则同值同写。"""
t = _attr_set(tmpl, "Number", str(code))
- v = "%.4f" % float(qty) if qty is not None else None
+ v = _ru(qty, 4) if qty is not None else None
try:
float(qty)
except (TypeError, ValueError):
@@ -1497,7 +1569,7 @@ def _merge_norm_lme_elements(txt):
q = sum(float(_attr(t, "Quantity") or 0) for t in texts)
except (TypeError, ValueError):
continue # 数值异常保守不并
- merged = _attr_set(first, "Quantity", "%.4f" % q)
+ merged = _attr_set(first, "Quantity", _ru(q, 4))
keep[c] = merged
for t in texts[1:]:
drop.add(t)
@@ -1557,7 +1629,7 @@ def _agg_key(opentag):
锚定自算。"""
return tuple([_attr(opentag, a) or "" for a in ("Number", "Name", "Specification", "Unit")])
-def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
+def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes, uw_groups=None):
"""Project 工料机汇总区块由各单位最终文本聚合重建(决策 187)。返回新 Project 文本。
单位文本=各自 transform 后的成品(含换码/清扫/注入结果),Project=各单位之和严格成立。
纯项目级行兜底:源 Project 行未隐藏、非合并变体、键不在聚合 → 原块保留(框架不动)。"""
@@ -1575,11 +1647,15 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
hidden = set(str(c) for c in (hidden_codes or []))
# ① 聚合各单位行
order, agg = [], {}
- for ut in unit_texts or ():
+ for item in unit_texts or ():
+ _uk, ut = item if isinstance(item, tuple) else (None, item)
uidx = _summary_span_index(ut)
uspans = sorted((sp for sps in uidx.values() for sp in sps), key=lambda sp: sp[0])
for (s0, e0, bend, opentag) in uspans:
- key = _agg_key(opentag)
+ # 决策 274 补记七:聚合键并入 uw 组别(显示端同一分组键,flags 全参与)——
+ # 行级查组:(uw键, 码)→组id,同码不同组各自成行(人工费 3 组=导出 3 条)
+ _gk = (uw_groups or {}).get((_uk, _attr(opentag, "Number") or ""))
+ key = _agg_key(opentag) + (_gk,)
if key not in agg:
agg[key] = {"qty": 0.0, "best": (s0, e0, bend, opentag), "besttxt": ut}
order.append(key)
@@ -1599,7 +1675,7 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
kids = re.findall(r'<' + _LME + r'\b[^>]*/>', ut[e0:bend]) if bend > e0 else []
tag = opentag
try:
- tag = _attr_set(tag, "Quantity", "%.4f" % a["qty"])
+ tag = _attr_set(tag, "Quantity", _ru(a["qty"], 4))
except Exception:
pass
try:
@@ -1612,7 +1688,7 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
continue
try:
pv = float(_attr(tag, pattr))
- tag = _attr_set(tag, tot, "%.2f" % (q * pv))
+ tag = _attr_set(tag, tot, _ru(q * pv, 2))
except (TypeError, ValueError):
pass
if bend > e0: # 成对块:底版子级+闭标签原样(bend 含闭标签)
@@ -1628,7 +1704,7 @@ def _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes):
c = row[0]
if any(_attr(sp[3], "Number") == c for sp in spans_all) or c in hidden:
continue # 源已有该码(兜底已保留)或已隐藏
- if any(k and k[0] == c for k in agg_keys):
+ if any(k and k[0][0] == c for k in agg): # 聚合键=(_agg_key元组, 组别)——k[0][0]=编码(补记七扩键后取内层)
continue # 聚合已有该码
tmpl = _full_summary_template(txt, row[4] if len(row) > 4 else None)
node = _summary_node((row[0], row[1], row[2], row[3], row[5] if len(row) > 5 else None,
@@ -1654,14 +1730,14 @@ def _apply_qty_updates(txt, qty_updates):
continue
for m in re.finditer(r'<' + _SUM_TAG + r'\b[^>]*Number="' + re.escape(str(code)) + r'"[^>]*>', txt):
t = m.group(0)
- nt = _attr_set(t, "Quantity", "%.4f" % qv)
+ nt = _attr_set(t, "Quantity", _ru(qv, 4))
for tot, pa in (("NoTaxOrgTotal", "NoTaxOrgPrice"), ("NoTaxTotal", "NoTaxPriceExpress"),
("TaxOrgTotal", "TaxOrgPrice"), ("TaxTotal", "TaxPriceExpress")):
if not re.search(r'\b' + tot + r'="', nt):
continue
try:
pv = float(_attr(nt, pa))
- nt = _attr_set(nt, tot, "%.2f" % (qv * pv))
+ nt = _attr_set(nt, tot, _ru(qv * pv, 2))
except (TypeError, ValueError):
pass
if nt != t:
@@ -1672,7 +1748,8 @@ def _apply_qty_updates(txt, qty_updates):
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):
+ recode_children=None, recode_ident=None, unit_texts=None, added_org=None,
+ uw_groups=None):
"""Project.xml 的工料机 = 单位工程汇总的汇总(决策 75,2026-10-15 主人定数据流):
sync_rows = [(编码,名称,规格,单位,除税价,税率,含税价), ...](会话侧项目级汇总现值,全量传入)。
同步规则(决策 176 改):编码命中 → 名称/规格/单位/除税价/税率/含税价 **全量写回**,
@@ -1689,7 +1766,7 @@ def transform_project(txt, added_summaries, hidden_codes, sync_rows=None, recode
sync/hidden/recode/ident 通道——源「同码多行异名规单」被 sync 抹齐撞名=广联达拒导入
根源。旧路径保留仅为无 unit_texts 的兼容调用。"""
if unit_texts:
- return _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes)
+ return _rebuild_project_lme(txt, unit_texts, added_summaries, hidden_codes, uw_groups=uw_groups)
recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
idx = _summary_span_index(txt)
foreign = _ident_foreign_spans(txt, idx, recode_ident) # 决策 178:同码异物节点先认领
@@ -1829,6 +1906,47 @@ def _source_ext(src_name):
return m.group(1) if m else ".cos"
+def src_qty_multiset(src_bytes):
+ """源件清单/定额 (Number, Quantity, Price, Total) 多重集(决策 274 补记四:
+ 量价是否被编辑的对照基准——数值化比较,3803.180 与 3803.18 算同值)。
+ 解析失败 → (None, None)=判不了,按「动过」处理(宁手术不冒险)。"""
+ def _ot_attrs(open_tag):
+ return tuple(_attr(open_tag, k) for k in ("Number", "Quantity", "Price", "Total"))
+ def _numeric(bag):
+ out = []
+ for t in bag:
+ try:
+ out.append((t[0] or "",) + tuple(
+ None if (x is None or str(x).strip() == "") else round(float(x), 6) for x in t[1:]))
+ except (TypeError, ValueError):
+ out.append((t[0] or "", None, None, None))
+ return sorted(out)
+ bills, norms = [], []
+ try:
+ z = zipfile.ZipFile(io.BytesIO(src_bytes))
+ for n in z.namelist():
+ if not n.lower().endswith(".xml"):
+ continue
+ t = z.read(n).decode("utf-8", "replace")
+ pat_we = '<(WorkElement|UnitWorksPreliminaryWorkElement)' + chr(92) + 'b[^>]*>'
+ pat_nm = ']*>'
+ if n.lower().startswith("project"):
+ for m in re.finditer(pat_nm, t):
+ norms.append(_ot_attrs(m.group(0)))
+ continue
+ for m in re.finditer(pat_we, t):
+ bills.append(_ot_attrs(m.group(0)))
+ for m in re.finditer(pat_nm, t):
+ norms.append(_ot_attrs(m.group(0)))
+ return _numeric(bills), _numeric(norms)
+ except Exception:
+ return None, None
+
+
+ except Exception:
+ return None, None
+
+
def _resolve_recode_chains(m):
"""改码链压平(决策 174 补,2026-10-22 主人定「合并后为准」):登记映射是多次合并
累积的森林(A→B 与 B→C 会共存),导出换码必须落到**链尾**——A 的最终保留码是 C,
@@ -1858,3 +1976,149 @@ def _resolve_recode_chains(m):
if tail != k:
out[k] = tail
return out
+
+
+# ============================================================
+# export_zip 外科手术引擎入口(2026-11-05 主人拍板「恢复旧引擎」——
+# 推翻决策 264 补记「旧的引擎就拆了」;本函数自 78e58a4^ 原样恢复,
+# 数据准备层在 api_server._export_session,工料机口径=现行 268 系库值+dyn_lme 现算)
+# ============================================================
+def export_zip(src_bytes, proj_name, src_name, unit_plans, added_summaries, hidden_codes, res_by_norm,
+ price_updates=None, added_lme_by_uw=None, sync_rows=None, recode_map=None, recode_children=None,
+ recode_ident=None, field_updates=None, added_children=None, added_org=None,
+ progress=None, form_bank=None, lme_untouched=False, uw_groups=None):
+ """src_bytes=原文件字节;unit_plans={uw键(Number,Name): plan};
+ plan={"pairs":{...}, "news":{...}, "norms_by_bill":{...}, "added_lme":[(码,名,规格,单位,量,税率,除税,含税,类别)]}。
+ recode_map/recode_children:合并改码映射与子级替换数据(规格 第11/12 条,api_server 落库读出);
+ recode_map 进通道前先压平改码链(决策 174 补)。
+ added_children:采纳新增行的子级组成 {码:[(子码,含量)]}(决策 204:带子级整组照原生结构导出)。
+ added_org:采纳新增行三恒值 {码:(除税定额价,含税定额价,税率)}(决策 205 主人定:按原数据回填,不编造)。
+ progress=可选回调 progress(done, total)——每个 zip 条目处理完报一次(决策 92 导出进度条)。
+ 返回 (新zip字节, 建议文件名)。"""
+ recode_map = _resolve_recode_chains(recode_map) if recode_map else recode_map
+ ext = _source_ext(src_name)
+ out_name = (proj_name or "工程") + "-审核版" + ext
+ zin = zipfile.ZipFile(io.BytesIO(src_bytes))
+ zout = io.BytesIO()
+ entries = zin.infolist()
+ # 2026-10-20 主人定:先扫全项目,取「同一清单标签下最大最全的合格块」当骨架。
+ # 只按清单块起止位置认,不依赖字段名——COS/COS4/广联达/易达骨架不同也能用。
+ bill_tmpls, bill_scores = {}, {}
+ for item in entries:
+ raw0 = zin.read(item.filename)
+ try:
+ txt0, _enc0 = _decode(raw0)
+ except Exception:
+ continue
+ if " bill_scores[tag]:
+ bill_tmpls[tag] = blk0
+ bill_scores[tag] = sc0
+ if progress:
+ progress(0, len(entries))
+ # 决策 187:两遍式——第一遍处理单位 xml 并**收集成品文本**(Project 聚合的数据源),
+ # Project.xml 延迟到第二遍(保证 Project=各单位之和);条目按原顺序写出,框架零变动。
+ finals = {} # filename → 变换后 raw
+ unit_final_texts = [] # 各单位成品文本(Project 聚合用):元素=(uw键, 文本)
+ with zipfile.ZipFile(zout, "w", zipfile.ZIP_DEFLATED) as zo:
+ for _ei, item in enumerate(entries, 1):
+ raw = zin.read(item.filename)
+ base = item.filename.rsplit("/", 1)[-1]
+ if base.lower() == "project.xml":
+ finals[item.filename] = raw # 延迟处理
+ continue
+ txt, enc = _decode(raw)
+ if "= 13 else (None,) * 4
- el = _deep(tmpl)
- _put(el, {
- "Number": code or "", "Name": name or "", "Specification": spec or "",
- "Unit": unit or "", "Quantity": _num(qty),
- "NoTaxPrice": _money(ntp), "TaxRate": _money(rate), "TaxPrice": _money(taxp),
- "NoTaxOrgPrice": _money(org4[0]), "NoTaxPriceExpress": org4[1],
- "TaxOrgPrice": _money(org4[2]), "TaxPriceExpress": org4[3],
- "NoTaxTotal": _money((float(qty or 0) * float(ntp or 0)) or None),
- "TaxTotal": _money((float(qty or 0) * float(taxp or 0)) or None),
- "Kind": str(int(kind)) if kind else "", "Remark": "",
- })
- if len(r) > 13 and r[13]:
- try:
- fl = json.loads(r[13])
- except (ValueError, TypeError):
- fl = None
- if isinstance(fl, dict):
- _put(el, {k: v for k, v in fl.items() if v is not None})
- _strip(el, {LME})
- for ccode, cqty in (children.get(code) or []):
- if child_t is None:
- break
- row = _deep(child_t)
- _put(row, {"Number": ccode or "", "Quantity": _num(cqty), "Remark": ""})
- el.append(row)
- out.append(el)
- return out
-
-
-def _apply_side(el, side, tags):
- """结构固定子块:按库里采集的 x_side 行数/值回填(列集由骨架闸门决定)。
- side=None(老批次没采)→ 保留骨架样板 1 行(值空),不造。"""
- if side in (None, ""):
- return
- try:
- rows = json.loads(side) if isinstance(side, str) else side
- except (ValueError, TypeError):
- return
- if not isinstance(rows, list):
- return
- by = {}
- for r in rows:
- if isinstance(r, dict):
- by.setdefault(r.get("tag"), []).append(r.get("attrs") or {})
- for tag in tags:
- samples = _kids(el, tag)
- if not samples:
- continue
- pos = list(el).index(samples[0])
- for s in samples:
- el.remove(s)
- for attrs in by.get(tag, []):
- new = _deep(samples[0])
- for k in list(new.attrib):
- v = attrs.get(k)
- new.set(k, "" if v is None else str(v))
- el.insert(pos, new)
- pos += 1
-
-
-def _emit_norm(n, tmpl, children, norm_db):
- el = _deep(tmpl)
- db_total = (norm_db or {}).get(n.get("id"))
- _put(el, {
- "Number": n.get("Number") or "", "Name": n.get("Name") or "",
- "Unit": n.get("Unit") or "", "Quantity": _num(n.get("Quantity")),
- "Price": _money(n.get("Price")),
- "Total": _money(db_total if db_total is not None else n.get("Total")),
- "IsNorm": "true", "Remark": "",
- })
- rows = _kids(el, LME)
- pos = list(el).index(rows[0]) if rows else len(list(el))
- for r in rows:
- el.remove(r)
- if rows:
- for _res in (n.get("res") or []):
- code, qty = _res[0], _res[1]
- exp = _res[2] if len(_res) > 2 else None
- if not code:
- continue
- row = _deep(rows[0])
- _put(row, {"Number": code, "Quantity": _num(qty), "Express": exp or "",
- "Remark": ""})
- el.insert(pos, row)
- pos += 1
- adjs = _kids(el, "NormAdjustmentList")
- apos = list(el).index(adjs[0]) if adjs else None
- for r in adjs:
- el.remove(r)
- adj = n.get("x_adjust") or ""
- if adj and adjs:
- row = _deep(adjs[0])
- _put(row, {"OrderNumber": "1", "Value": adj})
- el.insert(apos, row)
- _apply_side(el, n.get("x_side"),
- ("ExpressElement", "ManageFees", "UnitPriceCalculationOfItem"))
- return el
-
-
-def _emit_bill(b, tmpl, tmpls, norm_db, children):
- el = _deep(tmpl)
- _put(el, {
- "Number": b.get("Number") or "", "Name": b.get("Name") or "",
- "Attr": b.get("Attr") or "", "Unit": b.get("Unit") or "",
- "Quantity": _num(b.get("Quantity")),
- "QtyFormula": b.get("qty_expr") or "",
- "Price": _money(b.get("Price")), "Total": _money(b.get("Total")),
- "Remark": "", "WorkContent": "",
- })
- wc = _kids(el, "WorkContent")
- hosts = []
- for h in ([wc[0]] if wc else []) + [el]:
- ns = _kids(h, "Norm")
- if ns:
- hosts.append((h, ns))
- if hosts:
- host, norms = hosts[0]
- else:
- host = wc[0] if wc else el
- norms = []
- if wc:
- _put(host, {"Name": "", "Total": _money(b.get("Total")), "Remark": ""})
- pos = list(host).index(norms[0]) if norms else len(list(host))
- for _h, _ns in hosts: # 模板里定额可能挂在 WorkContent 或清单本身(两种形态都清)
- for c in _ns:
- _h.remove(c)
- _strip(el, {LME})
- for n in (b.get("norms") or []):
- if n.get("x_tdel"):
- continue
- host.insert(pos, _emit_norm(n, tmpls["norm"], children, norm_db))
- pos += 1
- _apply_side(el, b.get("x_side"),
- ("SummaryOfBasicCost", "ExpressElement", "UnitPriceCalculationOfItem"))
- return el
-
-
-def _emit_div(dv, kids, bills, tmpls, norm_db, children, by_parent):
- el = _deep(tmpls["div"]) if tmpls.get("div") is not None else ET.Element("DivisionalWorks")
- _strip(el, {"DivisionalWorks", "WorkElement", "UnitWorksPreliminaryWorkElement"})
- _put(el, {"Number": dv.get("number") or "", "Name": dv.get("name") or ""})
- total = sum(float(b.get("Total") or 0) for b in bills)
- for kid in kids:
- total += sum(float(b.get("Total") or 0) for b in by_parent["bills"].get(kid["id"], []))
- if "Total" in el.attrib:
- el.set("Total", _money(total))
- for b in bills:
- el.append(_emit_bill(b, tmpls["bill"], tmpls, norm_db, children))
- for kid in kids:
- el.append(_emit_div(kid, by_parent["kids"].get(kid["id"], []),
- by_parent["bills"].get(kid["id"], []), tmpls, norm_db,
- children, by_parent))
- return el
-
-
-def _emit_works(dea, u, plan, tmpls, norm_db, children):
- _strip(dea, {"DivisionalWorks", "WorkElement"})
- divs = [x for x in (plan.get("divides") or {}).values()
- if x["uw_id"] == u["id"] and x.get("kind") != "prelim"]
- bills = [b for b in (u.get("bills") or []) if b.get("kind") != "prelim" and not b.get("x_tdel")]
- by_parent = {"kids": {}, "bills": {}}
- for x in divs:
- by_parent["kids"].setdefault(x.get("parent_id"), []).append(x)
- for b in bills:
- by_parent["bills"].setdefault(b.get("div_id"), []).append(b)
- for dv in by_parent["kids"].get(None, []):
- dea.append(_emit_div(dv, by_parent["kids"].get(dv["id"], []),
- by_parent["bills"].get(dv["id"], []), tmpls, norm_db,
- children, by_parent))
- for b in by_parent["bills"].get(None, []):
- dea.append(_emit_bill(b, tmpls["bill"], tmpls, norm_db, children))
-
-
-def _emit_prelim(pre, u, plan, tmpls, norm_db, children):
- """措施区:骨架有分部层→按分部嵌套;无→直挂(骨架形态决定)。"""
- _strip(pre, {"PreliminaryDivisionalWorks", "UnitWorksPreliminaryWorkElement",
- "PreliminaryWorkElement", "Norm", "WorkElement", "DivisionalWorks"})
- bills = [b for b in (u.get("bills") or []) if b.get("kind") == "prelim" and not b.get("x_tdel")]
- divs = [x for x in (plan.get("divides") or {}).values()
- if x["uw_id"] == u["id"] and x.get("kind") == "prelim"]
- if tmpls.get("pre_bill") is None and tmpls.get("bill") is None:
- return
- by_div = {}
- for b in bills:
- by_div.setdefault(b.get("div_id"), []).append(b)
- by_parent = {}
- for x in divs:
- by_parent.setdefault(x.get("parent_id"), []).append(x)
-
- def emit_bill(b):
- # 2026-11-04:措施清单有两种原生标签形态(UnitWorksPreliminaryWorkElement / WorkElement),
- # 导入时存 x_ptag,导出按原形态还原(否则会被统一成一种,结构就变形了)。
- tag = b.get("x_ptag") or ""
- _pre = tmpls.get("pre_bill")
- tmpl = tmpls["bill"] if tag == "WorkElement" else (_pre if _pre is not None else tmpls["bill"])
- return _emit_bill(b, tmpl, tmpls, norm_db, children)
-
- def emit_div(dv):
- el = _deep(tmpls["pre_div"])
- _strip(el, {"PreliminaryDivisionalWorks", "UnitWorksPreliminaryWorkElement",
- "WorkElement", "DivisionalWorks"})
- _put(el, {"Number": dv.get("number") or "", "Name": dv.get("name") or ""})
- for b in by_div.get(dv["id"], []):
- el.append(emit_bill(b))
- for kid in by_parent.get(dv["id"], []):
- el.append(emit_div(kid))
- return el
-
- if tmpls.get("pre_div") is not None and divs:
- for dv in by_parent.get(None, []):
- pre.append(emit_div(dv))
- for b in by_div.get(None, []):
- pre.append(emit_bill(b))
- else:
- for b in bills:
- pre.append(emit_bill(b))
-
-
-def _sum_values(r):
- """动态汇总行(14 列)→ 骨架列字典 + 母码。"""
- code, name, spec, unit, kind, qty, ntp, rate, taxp = (list(r) + [None] * 9)[:9]
- org4 = (tuple(r[9:13]) + (None,) * 4)[:4] if len(r) >= 13 else (None,) * 4
- vals = {
- "Number": code or "", "Name": name or "", "Specification": spec or "",
- "Unit": unit or "", "Quantity": _num(qty),
- "NoTaxPrice": _money(ntp), "TaxRate": _money(rate), "TaxPrice": _money(taxp),
- "NoTaxOrgPrice": _money(org4[0]), "NoTaxPriceExpress": org4[1],
- "TaxOrgPrice": _money(org4[2]), "TaxPriceExpress": org4[3],
- "NoTaxTotal": _money((float(qty or 0) * float(ntp or 0)) or None),
- "TaxTotal": _money((float(qty or 0) * float(taxp or 0)) or None),
- "Kind": str(int(kind)) if kind else "", "Remark": "",
- }
- if len(r) > 13 and r[13]:
- try:
- fl = json.loads(r[13])
- except (ValueError, TypeError):
- fl = None
- if isinstance(fl, dict):
- # 决策 263:恒空链(备注/价格来源/交货地…)不随行输出,清残留
- vals.update({k: v for k, v in fl.items()
- if v is not None and k not in _HANG_KONG})
- return code, vals
-
-
-def _emit_sums(host, rows, children):
- """工料机汇总:骨架里的汇总行样板整组替换为库数据(骨架没这层→不造)。
- 行本身就是槽(可能带台班/配合比子级行),行数由库决定。
- 2026-11-03 加固:汇总行可能有**两种形态**(普通行 / 带组成的块行,列集不同)——
- 每行按「列集覆盖 + 有无子级」挑最合适的样板,避免把另一形态的属性丢掉。"""
- sample = None
- for e in host.iter(LME_SUM):
- sample = e
- break
- if sample is None:
- return
- parent = None
- for par in host.iter():
- for c in _kids(par):
- if c is sample:
- parent = par
- break
- if parent is not None:
- break
- if parent is None:
- return
- tmpls = [c for c in _kids(parent) if c.tag == LME_SUM]
- if not tmpls:
- return
-
- def _pick(vals, want_child):
- """两种导出形态按行硬分派(2026-11-03 主人定):
- · 带组成的行 → 闭合块形态(…,内有 Element 子行);
- · 普通行 → 自闭合行形态()。
- 形态优先,列覆盖只用于同形态内选最全的样板;该形态没有样板才退回另一形态。"""
- cands = [t for t in tmpls if bool(_kids(t)) == bool(want_child)]
- if not cands:
- cands = tmpls
- need = set(vals.keys())
- best, best_s = cands[0], -1
- for t in cands:
- have = set(t.attrib.keys())
- s = 2 * len(need & have)
- if need <= have:
- s += 5 # 模板列集能全覆盖该行
- if s > best_s:
- best, best_s = t, s
- return best
-
- pos = list(parent).index(tmpls[0])
- for t in tmpls:
- parent.remove(t)
- for r in (rows or []):
- code, vals = _sum_values(r)
- comp = children.get(code) or []
- t = _pick(vals, comp)
- el = _deep(t)
- _put(el, vals)
- kids_t = _kids(t)
- if kids_t:
- ct = kids_t[0]
- _strip(el, {ct.tag})
- for ccode, cqty in comp:
- row = _deep(ct)
- _put(row, {"Number": ccode or "", "Quantity": _num(cqty), "Remark": ""})
- el.append(row)
- parent.insert(pos, el)
- pos += 1
-
-
-# ---------------------------------------------------------------------------
-# 主入口
-# ---------------------------------------------------------------------------
-
-def _blank_and_meta(con, rep, suffix):
- blank = rep.get("x_blank")
- if not blank:
- blank, _fn = classic_skeleton.frame_blank(con, rep["sig"])
- if not blank:
- return None, None
- meta = classic_skeleton.frame_meta(con, rep["sig"])
- if not meta:
- try:
- _b, meta = classic_skeleton.refine_blank_ex(rep["blob"], suffix)
- except Exception:
- meta = None
- return bytes(blank), meta
-
-
-def _load_children(sc, sid):
- out = {}
- try:
- for r in sc.execute("SELECT p_code, res_code, qty FROM s_lme_res "
- "WHERE session_id=? ORDER BY seq, id", (sid,)):
- if r["p_code"]:
- out.setdefault(r["p_code"], []).append((r["res_code"], r["qty"]))
- except Exception:
- pass
- return out
-
-
-def _unit_cols(uw):
- """骨架单位层各标签的列集(顺序按首次出现)——side 数据重建的列闸门。"""
- cols = {}
- for el in uw.iter():
- if isinstance(el.tag, str):
- c = cols.setdefault(el.tag, [])
- for a in el.attrib:
- if a not in c:
- c.append(a)
- return cols
-
-
-def _mk_side(node, cols):
- """数据树节点 → 元素(只写骨架里有的列;骨架没有的标签/列不造)。"""
- tag = node.get("tag")
- if tag not in cols:
- return None
- el = ET.Element(tag)
- attrs = node.get("attrs") or {}
- for a in cols[tag]:
- v = attrs.get(a)
- el.set(a, "" if v is None else str(v))
- for k in node.get("kids") or []:
- c = _mk_side(k, cols)
- if c is not None:
- el.append(c)
- return el
-
-
-def _emit_unit_side(uw, side_json):
- """单位工程非数据层(AttrInfo/SummaryOfCost(含 AddiCost)/UnitWorksSummary/Sundry/Tax…):
- 按库里采集的原始结构重建——块数/行数=数据,列由骨架闸门决定;骨架没有的层不造;
- 老批次没采集→保留骨架样板。"""
- if not side_json:
- return
- try:
- tree = json.loads(side_json)
- except (ValueError, TypeError):
- return
- if not isinstance(tree, list) or not tree:
- return
- cols = _unit_cols(uw)
- by = {}
- for rec in tree:
- if isinstance(rec, dict):
- by.setdefault(rec.get("tag"), []).append(rec)
- for tag, recs in by.items():
- tmpls = [c for c in _kids(uw) if c.tag == tag]
- if not tmpls:
- continue # 骨架没有该层:不造
- pos = list(uw).index(tmpls[0])
- keep = tmpls[0]
- for t in tmpls:
- uw.remove(t)
- made = []
- for rec in recs:
- el = _mk_side(rec, cols)
- if el is not None:
- made.append(el)
- if not made and min_count(tag) == 1:
- made = [_deep(keep)] # 加固:区域至少 1 个空壳,防结构缺失
- for el in made:
- uw.insert(pos, el)
- pos += 1
-
-
-def _merge_side(el, node, cols):
- """把数据树合并进模板元素:写骨架里有的列;同 tag 子块按数据行整组替换
- (数据里没有的 tag 保留骨架原样——如 ProjectInstallationWorkCost 下的 SectionalWorks)。"""
- attrs = node.get("attrs") or {}
- for a in cols.get(el.tag) or []:
- v = attrs.get(a)
- el.set(a, "" if v is None else str(v))
- by = {}
- for k in node.get("kids") or []:
- if isinstance(k, dict):
- by.setdefault(k.get("tag"), []).append(k)
- for tag, recs in by.items():
- tmpls = [c for c in _kids(el) if c.tag == tag]
- if not tmpls:
- continue # 骨架没有该层:不造
- pos = list(el).index(tmpls[0])
- keep = tmpls[0]
- for t in tmpls:
- el.remove(t)
- made = []
- for rec in recs:
- c = _mk_side(rec, cols)
- if c is not None:
- made.append(c)
- if not made and min_count(tag) == 1:
- made = [_deep(keep)] # 加固:区域至少 1 个空壳
- for c in made:
- el.insert(pos, c)
- pos += 1
-
-
-def _emit_proj_side(proj, side_json):
- """项目级非数据层:根属性 / SummaryOfCost(项目级+单项级两处,按路径区分)/ AddiCost /
- ProjectInstallationWorkCostSummary 等,按库数据合并重建。"""
- if not side_json:
- return
- try:
- recs = json.loads(side_json)
- except (ValueError, TypeError):
- return
- if not isinstance(recs, list):
- return
- cols = _unit_cols(proj)
- for rec in recs:
- if not isinstance(rec, dict):
- continue
- path = rec.get("path") or []
- if path and path[0] == proj.tag:
- path = path[1:] # 路径从根开始;根就是 proj 自身
- node = rec.get("node") or {}
- if not path: # 根属性
- attrs = node.get("attrs") or {}
- for a in cols.get(proj.tag) or []:
- if a in attrs:
- proj.set(a, "" if attrs[a] is None else str(attrs[a]))
- continue
- target = proj
- ok = True
- for tag in path:
- nxt = None
- for c in _kids(target):
- if c.tag == tag:
- nxt = c
- break
- if nxt is None:
- ok = False
- break
- target = nxt
- if not ok or target is proj:
- continue
- _merge_side(target, node, cols)
-
-
-def _tag_cols(root):
- cols = {}
- for el in root.iter():
- if isinstance(el.tag, str):
- cols.setdefault(el.tag, set()).update(el.attrib.keys())
- return cols
-
-
def _own_layers(plan):
"""本项目骨架的**数据层**要求(2026-11-04 主人定:列不算全部数据,只要数据层能全部导出)。
→ (需要存在的层标签集合, 措施清单原生标签集合, 是否有措施分部)。"""
@@ -656,224 +117,6 @@ def _missing_layers(need, prelim_tags, need_prelim_div, tags):
return miss
-def export_v2(con, sc, sid, suffix, progress=None, src_path=None):
- """骨架回灌导出(2026-11-04 决策267):**优先本项目自己的骨架**(打开工程时从源件提炼入库);
- 数据层列覆盖不全 → 后台骨架补充缺列;缺整层 → 回落后台骨架;再不行用源件现提炼。"""
- plan = build_plan(sc, sid)
- if plan is None:
- return None, None, "会话数据读不出来"
- srow = plan["srow"]
- proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
- try:
- proj_side = srow["x_side"]
- except (KeyError, IndexError):
- proj_side = None
- children = _load_children(sc, sid)
- attr_map = {}
- try:
- for r in sc.execute("SELECT id, x_attr FROM s_unit_works WHERE session_id=?", (sid,)):
- attr_map[r["id"]] = r["x_attr"]
- except Exception:
- attr_map = {}
-
- # ===== 骨架选择:本项目骨架优先(只看数据层是否齐全;列少不算不覆盖) =====
- need, prelim_tags, need_prelim_div = _own_layers(plan)
- try:
- own_blank = srow["x_own_blank"]
- except (KeyError, IndexError):
- own_blank = None
- own_meta = None
- try:
- if srow["x_own_meta"]:
- own_meta = json.loads(srow["x_own_meta"])
- except (KeyError, IndexError, ValueError, TypeError):
- own_meta = None
- rep = None
- blank = meta = None
- if own_blank:
- try:
- oroot, _od = classic_skeleton._blank_parse(bytes(own_blank).decode("utf-8"))
- tags = {el.tag for el in oroot.iter() if isinstance(el.tag, str)}
- miss = _missing_layers(need, prelim_tags, need_prelim_div, tags)
- if not miss:
- blank, meta = bytes(own_blank), own_meta
- except Exception:
- blank, meta = None, None
- if not blank:
- if rep is None:
- rep = classic_skeleton.pick_frame(con, (suffix or "").lower(), src_path=src_path)
- if rep:
- blank, meta = _blank_and_meta(con, rep, suffix)
- if not blank and src_path and os.path.exists(src_path):
- # 库/本项目骨架都没有:就地按源件提炼一件内存骨架(不落库)
- try:
- blank, meta = classic_skeleton.refine_blank_ex(
- open(src_path, "rb").read(), suffix)
- except Exception:
- blank, meta = None, None
- if not blank:
- return None, None, "该后缀还没有骨架:请先在后台导入"
- skel_root, decl = classic_skeleton._blank_parse(blank.decode("utf-8"))
- norm_db = {}
- for r in sc.execute("""SELECT n.id, n.Total AS db_total
- FROM s_norms n JOIN s_bills b ON b.id=n.bill_id
- WHERE b.session_id=?""", (sid,)):
- norm_db[r["id"]] = r["db_total"]
-
- # 单位工程模板=骨架里内嵌的那棵单位子树(项目骨架同一位置换成 N 条索引行)
- unit_tmpl = None
- for par in skel_root.iter():
- for k in _kids(par, "UnitWorks"):
- if _kids(k):
- unit_tmpl = k
- break
- if unit_tmpl is not None:
- break
- if unit_tmpl is None:
- return None, None, "骨架缺单位工程样板"
-
- dea_t = _first(unit_tmpl, "DivisionalAndElementalWorks")
- pre_t = _first(unit_tmpl, "Preliminaries")
- scope_t = dea_t if dea_t is not None else unit_tmpl
- _pre_ids = set()
- for _tag in ("WorkElement", "DivisionalWorks"):
- if pre_t is not None:
- for _e in pre_t.iter(_tag):
- _pre_ids.add(id(_e))
- bills_t = [w for w in scope_t.iter("WorkElement") if id(w) not in _pre_ids]
- tmpls = {"bill": bills_t[0] if bills_t else None}
- if tmpls["bill"] is None:
- return None, None, "骨架缺清单样板"
- wc_t = _first(tmpls["bill"], "WorkContent")
- host_t = wc_t if wc_t is not None else tmpls["bill"]
- tmpls["norm"] = _first(host_t, "Norm")
- if tmpls["norm"] is None:
- return None, None, "骨架缺定额样板"
- deepest = None
- for c in scope_t.iter("DivisionalWorks"):
- if id(c) in _pre_ids:
- continue
- if _kids(c, "WorkElement"):
- deepest = c
- tmpls["div"] = deepest if deepest is not None else next(
- (c for c in scope_t.iter("DivisionalWorks") if id(c) not in _pre_ids), None)
- tmpls["pre_bill"] = _first(pre_t, "UnitWorksPreliminaryWorkElement") if pre_t is not None else None
- tmpls["pre_div"] = _first(pre_t, "PreliminaryDivisionalWorks") if pre_t is not None else None
- if pre_t is not None and tmpls["pre_bill"] is None:
- # 老 cos 族:措施条目就是 WorkElement/DivisionalWorks(标签与分部分项相同)
- tmpls["pre_bill"] = _first(pre_t, "WorkElement") or tmpls.get("bill")
- tmpls["pre_div"] = _first(pre_t, "DivisionalWorks")
-
- unit_xmls = []
- for i, u in enumerate(plan["units"], 1):
- uw = _deep(unit_tmpl)
- _put(uw, {
- "Number": u.get("number") or "", "Name": u.get("name") or "",
- "FileName": "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip()),
- "Total": _money(u.get("total")),
- })
- dea = _kids(uw, "DivisionalAndElementalWorks")
- works_host = dea[0] if dea else uw
- _emit_works(works_host, u, plan, tmpls, norm_db, children)
- pre = _kids(uw, "Preliminaries")
- if pre:
- _emit_prelim(pre[0], u, plan, tmpls, norm_db, children)
- try:
- rows = dyn_lme.dyn_uw_rows(sc, sid, u["id"]) or []
- except Exception:
- rows = []
- _emit_sums(uw, rows, children)
- for region in uw.iter():
- if isinstance(region.tag, str) and region.tag in _RESULT_REGIONS:
- _blank_values(region)
- _emit_unit_side(uw, attr_map.get(u["id"]))
- # 单位工程 SummaryOfCost 合价回填(决策 264③):全部按现算清单/措施合价
- qdf = sum(float(b.get("Total") or 0) for b in (u.get("bills") or [])
- if b.get("kind") != "prelim" and not b.get("x_tdel"))
- qsf = sum(float(b.get("Total") or 0) for b in (u.get("bills") or [])
- if b.get("kind") == "prelim" and not b.get("x_tdel"))
- for sm in _kids(uw, "SummaryOfCost"):
- _put(sm, {"DivisionalAndElementalWorks": _money(qdf),
- "Preliminaries": _money(qsf)})
- name = "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip())
- unit_xmls.append((name, decl + "\n" + se.serialize(uw, 0, " ", keep_values=True)))
-
- # 项目文件:骨架项目树 + N 条单位索引行 + 项目级工料机汇总
- proj = _deep(skel_root)
- hm = None
- for par in proj.iter():
- for k in _kids(par, "UnitWorks"):
- if _kids(k):
- hm = (par, k)
- break
- if hm:
- break
- if hm:
- hm[0].remove(hm[1])
- holder2 = hm[0]
- else:
- holder2 = proj
- attrs = ((meta or {}).get("index_row") or {}).get("attrs") or []
- for i, u in enumerate(plan["units"], 1):
- row = ET.SubElement(holder2, "UnitWorks")
- for a in attrs:
- row.set(a, "")
- fname = "@_%s_%s.xml" % (u.get("number") or i, (u.get("name") or "").strip())
- row.set("FileName", fname) # 引用成员名:骨架没这列也要写(否则成员对不上)
- _put(row, {
- "Number": u.get("number") or "", "Name": u.get("name") or "",
- "Total": _money(u.get("total")),
- })
- try:
- prows = dyn_lme.dyn_rows(sc, sid, None) or []
- prows = [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8],
- r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None] for r in prows]
- except Exception:
- prows = []
- _emit_sums(proj, prows, children)
- for region in proj.iter():
- if isinstance(region.tag, str) and region.tag in _RESULT_REGIONS:
- _blank_values(region)
- _emit_proj_side(proj, proj_side)
- _put(proj, {"Name": proj_name}) # 工程名以当前会话为准(覆盖 side 里的原名)
- proj_xml = decl + "\n" + se.serialize(proj, 0, " ", keep_values=True)
-
- out = io.BytesIO()
- with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zo:
- zi = zipfile.ZipInfo("Project.xml", date_time=(2026, 1, 1, 0, 0, 0))
- zo.writestr(zi, proj_xml.encode("utf-8"))
- for nm, txt in unit_xmls:
- zi = _GbkZipInfo(nm, date_time=(2026, 1, 1, 0, 0, 0))
- zi.compress_type = zipfile.ZIP_DEFLATED
- zo.writestr(zi, txt.encode("utf-8"))
- if progress:
- progress(len(unit_xmls) + 1, len(unit_xmls) + 1)
- return out.getvalue(), out_name(proj_name, suffix), None
-
-
-# ---------------------------------------------------------------------------
-# 骨架库:导出「完全空的骨架 + 导出规则标注」(2026-11-03 主人定,新增功能)
-# ---------------------------------------------------------------------------
-
-# 自增层:行数=会话数据条数(导出时按数据循环)
-_LOOP_TAGS = {
- "UnitWorks", "DivisionalWorks", "WorkElement", "Norm",
- "LabourMaterialsEquipmentsMachinesElement", "LabourMaterialsEquipmentsMachinesSummary",
- "UnitWorksPreliminaryWorkElement", "PreliminaryWorkElement", "PreliminaryDivisionalWorks",
- "NormAdjustmentList",
-}
-# 按库行:行数/值来自 x_side(Import 采集的原件固定子块)
-_SIDE_TAGS = {
- "UnitPriceCalculationOfItem", "ManageFees", "SummaryOfBasicCost", "ExpressElement",
-}
-# 工程特征树(2026-11-03 主人定):AttrInfo 下的组=自增块、叶=自增行,数据来自 s_unit_works.x_attr
-_ATTR_TAGS = {"AttrInfoItem", "InfoItem"}
-
-
-# 结构位规则(2026-11-03 主人定「全部按自增区域/自增块/自增行设计」):
-# · 自增区域 min_count=1 —— 结构壳,数据 0 条也输出 1 个空壳(不然接收软件缺结构);
-# · 自增块 / 自增行 min_count=0 —— 条数=数据条数,0 条不输出。
-# 「固定」概念取消,内核只剩「基数下限」。
_REGION_TAGS = {
"ConstructionProject", "ProjectInstallationWorkCost", "SectionalWorks",
"SystemInfo", "ConstructionInfo", "ProjectInfo", "TendereeInfo", "BidderInfo",
diff --git a/CostReview/app/core/session_job.py b/CostReview/app/core/session_job.py
index b99e9fa..390b357 100644
--- a/CostReview/app/core/session_job.py
+++ b/CostReview/app/core/session_job.py
@@ -504,6 +504,8 @@ def connect():
("sessions", ("x_side TEXT",)),
# 2026-11-04:本项目自己的空骨架(打开工程时提炼,导出优先用)
("sessions", ("x_own_blank BLOB", "x_own_meta TEXT")),
+ # 2026-11-05:项目目录——项目组内同级顺序(dir_id=0 的行只表达未归类排序,不代表归属)
+ ("s_proj_dir_map", ("sort INTEGER DEFAULT 0",)),
):
for col in cols:
try:
diff --git a/CostReview/app/server/api_server.py b/CostReview/app/server/api_server.py
index 4486b6e..939bbfe 100644
--- a/CostReview/app/server/api_server.py
+++ b/CostReview/app/server/api_server.py
@@ -977,6 +977,104 @@ def _adopt_hits_ensure_rkey(c):
c.commit()
+def adopt_src_record(sc, sid, row_type, row_id, src):
+ """决策 256(2026-11-06 主人定「乙 后端溯源」):记/覆盖工作台行的采纳来源快照。
+ 快照式(不依赖历史库行存活),一行一条在效采纳(UNIQUE 重采纳覆盖)。src=对比框渲染行同形 dict。"""
+ if not sid or row_type not in ("bill", "lme") or not row_id or not isinstance(src, dict):
+ return {"ok": False, "msg": "参数不齐:sid/row_type(bill|lme)/row_id/src 必填"}
+ sc.execute("""INSERT INTO adopt_src(sid,row_type,row_id,src,src_id,name,attr,spec,unit,price,tax,price_tax,proj,period,adopted_at)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ ON CONFLICT(sid,row_type,row_id) DO UPDATE SET
+ src=excluded.src, src_id=excluded.src_id, name=excluded.name, attr=excluded.attr,
+ spec=excluded.spec, unit=excluded.unit, price=excluded.price, tax=excluded.tax,
+ price_tax=excluded.price_tax, proj=excluded.proj, period=excluded.period,
+ adopted_at=excluded.adopted_at""",
+ (sid, row_type, int(row_id), (src.get("src") or None),
+ src.get("src_id"), src.get("name"), src.get("attr"), src.get("spec"), src.get("unit"),
+ src.get("price"), src.get("tax"), src.get("price_tax"),
+ src.get("proj"), src.get("period"), time.strftime("%Y-%m-%d %H:%M:%S")))
+ return {"ok": True}
+
+
+def adopt_src_get(sc, sid, row_type, row_id):
+ """取工作台行的采纳来源快照(对比框渲染行同形;tier/dist 给中性值供 renderHist 消费)。"""
+ r = sc.execute("""SELECT src, src_id, name, attr, spec, unit, price, tax, price_tax, proj, period
+ FROM adopt_src WHERE sid=? AND row_type=? AND row_id=?""",
+ (sid, row_type, int(row_id))).fetchone()
+ if r is None:
+ return None
+ d = dict(r)
+ if row_type == "lme":
+ return {"tier": "溯源", "dist": 0, "sim": None, "src": d.get("src") or "project",
+ "src_id": d.get("src_id"), "name": d.get("name"), "spec": d.get("spec"),
+ "attr": d.get("attr"), "unit": d.get("unit"), "price": d.get("price"),
+ "tax": d.get("tax"), "price_tax": d.get("price_tax"),
+ "proj": d.get("proj"), "period": d.get("period")}
+ return {"tier": "溯源", "dist": 0, "sim": None, "src": "project", "bill_id": d.get("src_id"),
+ "src_id": d.get("src_id"), "name": d.get("name"), "attr": d.get("attr"),
+ "unit": d.get("unit"), "price": d.get("price"),
+ "proj": d.get("proj"), "period": d.get("period")}
+
+
+def adopt_src_clear(sc, sid, row_type, row_id):
+ sc.execute("DELETE FROM adopt_src WHERE sid=? AND row_type=? AND row_id=?",
+ (sid, row_type, int(row_id)))
+
+
+def api_adopt_src_get(body):
+ """决策 256:读取端点(跨重开/换浏览器溯源)——工作台行有采纳备注时前端取回来源行插框定位。"""
+ sid = int(body.get("session_id") or 0)
+ row_type = body.get("type") or "bill"
+ try:
+ row_id = int(body.get("row_id") or 0)
+ except (TypeError, ValueError):
+ row_id = 0
+ if not sid or row_id <= 0 or row_type not in ("bill", "lme"):
+ return {"ok": False, "msg": "参数:session_id + type(bill|lme) + row_id"}
+ sc = sess.connect()
+ try:
+ row = adopt_src_get(sc, sid, row_type, row_id)
+ finally:
+ sc.close()
+ return {"ok": True, "row": row}
+
+
+def api_adopt_src_record(body):
+ """决策 256:写入端点(页面工料机采纳链路用;清单/MCP 链路在后端采纳函数内直记)。"""
+ sid = int(body.get("session_id") or 0)
+ row_type = body.get("type") or "bill"
+ try:
+ row_id = int(body.get("row_id") or 0)
+ except (TypeError, ValueError):
+ row_id = 0
+ sc = sess.connect()
+ try:
+ r = adopt_src_record(sc, sid, row_type, row_id, body.get("src") or {})
+ sc.commit()
+ finally:
+ sc.close()
+ return r
+
+
+def api_adopt_src_clear(body):
+ """决策 256:清除端点(工料机取消采纳后前端调;清单取消在后端 unadopt 内直清)。"""
+ sid = int(body.get("session_id") or 0)
+ row_type = body.get("type") or "bill"
+ try:
+ row_id = int(body.get("row_id") or 0)
+ except (TypeError, ValueError):
+ row_id = 0
+ if not sid or row_id <= 0 or row_type not in ("bill", "lme"):
+ return {"ok": False, "msg": "参数:session_id + type(bill|lme) + row_id"}
+ sc = sess.connect()
+ try:
+ adopt_src_clear(sc, sid, row_type, row_id)
+ sc.commit()
+ finally:
+ sc.close()
+ return {"ok": True}
+
+
def _adopt_bill_attachments(sc, hc, sid, bid, src_bill_id):
"""决策 243(2026-10-30 主人定):清单采纳也收附件——来源入库清单挂的询价附件
收进顶栏附件目录的「清单附件」标签(取代 2026-10-09「清单采纳本就不收附件」口径)。
@@ -2040,17 +2138,23 @@ def _projdir_desc(con, did):
def api_projdirs():
- """项目目录弹框数据:目录列表 + 项目归属(一次取全)。connect() 幂等建表。"""
+ """项目目录弹框数据:目录列表 + 项目归属 + 组内顺序(一次取全)。connect() 幂等建表。"""
con = sess.connect()
try:
dirs, m = _projdir_all(con)
- return {"ok": True, "dirs": dirs, "map": m}
+ # 组内同级顺序(2026-11-05 主人定:项目可 ↑↓ 同级移动):porder[目录id] = 项目名有序表;
+ # 没排过序的项目不在表里,前端按列表原序排在已排序的后面。dir_id=0=未归类组。
+ porder = {}
+ for r in con.execute("SELECT proj, dir_id FROM s_proj_dir_map ORDER BY sort, rowid"):
+ porder.setdefault(str(r["dir_id"] or 0), []).append(r["proj"])
+ return {"ok": True, "dirs": dirs, "map": m, "porder": porder}
finally:
con.close()
def api_projdirs_save(body):
- """项目目录维护:op = add(新增)/ ren(改名)/ del(删除)/ move(↑↓)/ assign(项目归类)"""
+ """项目目录维护:op = add(新增)/ ren(改名)/ del(删除)/ move(目录↑↓)/
+ move_proj(项目↑↓,同级移动不改归属,2026-11-05 主人定)/ assign(项目归类)"""
op = body.get("op")
con = sess.connect()
try:
@@ -2136,11 +2240,51 @@ def api_projdirs_save(body):
return {"ok": False, "msg": "无名项目不能归类(打开时间列对应的工程没有名称)"}
if did and not con.execute("SELECT id FROM s_proj_dirs WHERE id=?", (did,)).fetchone():
return {"ok": False, "msg": "目标目录不存在(可能已被删除),请刷新后重试"}
- if did:
- con.execute("""INSERT INTO s_proj_dir_map(proj, dir_id) VALUES(?,?)
- ON CONFLICT(proj) DO UPDATE SET dir_id=excluded.dir_id""", (name, did))
+ # 归类 = 换组并落到目标组末尾(sort=目标组最大值+1;保留行让组内排序不丢)
+ mx = con.execute("SELECT MAX(sort) FROM s_proj_dir_map WHERE dir_id=?", (did,)).fetchone()[0]
+ con.execute("""INSERT INTO s_proj_dir_map(proj, dir_id, sort) VALUES(?,?,?)
+ ON CONFLICT(proj) DO UPDATE SET dir_id=excluded.dir_id, sort=excluded.sort""",
+ (name, did, (mx or 0) + 1))
+ con.commit()
+ return {"ok": True}
+
+ if op == "move_proj":
+ # 项目同级移动(2026-11-05 主人定):只在所属组(目录或未归类)内换位,**不改归属、不可跨级**
+ name = (body.get("name") or "").strip()
+ d = int(body.get("d") or 0) # -1=上移 / 1=下移
+ if not name:
+ return {"ok": False, "msg": "无名项目不能移动"}
+ r = con.execute("SELECT dir_id FROM s_proj_dir_map WHERE proj=?", (name,)).fetchone()
+ did = (r["dir_id"] or 0) if r else 0
+ # 组内顺序:已物化行(sort,rowid)在前;未归类组再把「没有任何归属行」的成员按台账序补后
+ # (目录组的成员必然有行——归类入组时就写了行)
+ proj_all, seen = [], set()
+ for r_ in con.execute("SELECT name FROM sessions ORDER BY id DESC"):
+ n = (r_[0] or "").strip()
+ if n and n not in seen:
+ seen.add(n)
+ proj_all.append(n)
+ if did == 0:
+ mapped_names = {r_[0] for r_ in con.execute("SELECT proj FROM s_proj_dir_map WHERE dir_id!=0")}
+ group = [r_[0] for r_ in con.execute(
+ "SELECT proj FROM s_proj_dir_map WHERE dir_id=0 ORDER BY sort, rowid") if r_[0] in seen]
+ have = set(group)
+ group += [n for n in proj_all if n not in have and n not in mapped_names]
else:
- con.execute("DELETE FROM s_proj_dir_map WHERE proj=?", (name,)) # 归「未归类」= 清挂接
+ group = [r_[0] for r_ in con.execute(
+ "SELECT proj FROM s_proj_dir_map WHERE dir_id=? ORDER BY sort, rowid", (did,))
+ if r_[0] in seen]
+ if name not in group:
+ return {"ok": False, "msg": "项目不在同级序列里,请刷新后重试"}
+ i = group.index(name)
+ j = i + d
+ if j < 0 or j >= len(group):
+ return {"ok": False, "msg": "已经到头了"}
+ group[i], group[j] = group[j], group[i]
+ for pos, n in enumerate(group):
+ con.execute("""INSERT INTO s_proj_dir_map(proj, dir_id, sort) VALUES(?,?,?)
+ ON CONFLICT(proj) DO UPDATE SET dir_id=excluded.dir_id, sort=excluded.sort""",
+ (n, did, pos + 1))
con.commit()
return {"ok": True}
return {"ok": False, "msg": "未知操作:%s" % op}
@@ -4389,14 +4533,17 @@ def _uw_rollup_totals(con, uw_id):
div_totals.setdefault(k, []).append(round(div_val.get(r["id"], 0.0), 2))
upd = {"DivisionalAndElementalWorks": None, "Preliminaries": None,
"Total": None, "Construction": None, "_uw_total": None}
- uw = con.execute("""SELECT DivisionalAndElementalWorks, Preliminaries, SundryCosts, Tax, Construction
+ uw = con.execute("""SELECT DivisionalAndElementalWorks, Preliminaries, SundryCosts, Tax, Construction, CostForHSE
FROM s_unit_works WHERE id=?""", (uw_id,)).fetchone()
if uw:
qdf0, qsf0 = uw["DivisionalAndElementalWorks"], uw["Preliminaries"]
sundry, tax = uw["SundryCosts"] or 0.0, uw["Tax"] or 0.0
con0, tot0 = uw["Construction"], None
upd["DivisionalAndElementalWorks"] = round(qdf, 2)
- upd["Preliminaries"] = round(qsf, 2)
+ # 决策 274 补记七(2026-11-05 三方对拍实证):易达 Preliminaries **含安全文明施工费**——
+ # 散措施现算 15144.25 + HSE 9353.81 = 24498.06(uw001 逐一吻合);此前只算散措施=少 9353.81。
+ _hse = float(uw["CostForHSE"] or 0) if "CostForHSE" in (uw.keys() or ()) else 0.0
+ upd["Preliminaries"] = round(qsf + _hse, 2)
# 费用恒等式核对:原件 Total==Construction+Preliminaries+Sundry+Tax 且 Construction==QDF
# → 三项一起跟随现算;否则只回填 QDF/QSF 两项(不猜异构文件的费用结构)
_rt = con.execute("SELECT Total FROM s_unit_works WHERE id=?", (uw_id,)).fetchone()
@@ -4466,15 +4613,416 @@ def _export_session(sc, sid, fmt="", progress=None):
except Exception as e:
return None, None, "导出失败:%s" % e
return raw, out_name, None
- # ② 其余(cos/cos4 及后期新后缀)统一走骨架回灌
- _sfx = (fmt or "").strip().lower() or (classic_skeleton.suffix_of(srow["src_name"]) or "cos4")
- _hc = conn()
+ # ② cos/cos4 原格式导出=旧外科手术引擎(2026-11-05 主人拍板「恢复旧引擎」——
+ # 推翻决策 264 补记「旧的引擎就拆了」:export_zip 自 78e58a4^ 原样恢复;
+ # 数据准备层口径=现行 268 系库值+dyn_lme 现算,合并工料机/项目级/单位级汇总
+ # 逻辑不动;取代 264 补五「单一通路 export_v2」的会话导出职责)
+ if not path or not os.path.exists(path):
+ return None, None, "原文件已不在软件里(可能被清理),无法导出"
try:
- import export_v2 as _ev2
- return _ev2.export_v2(_hc, sc, sid, _sfx, progress, src_path=path)
- finally:
- _hc.close()
+ src_bytes = io.open(path, "rb").read()
+ except OSError as e:
+ return None, None, "原文件读不出来:%s" % e
+ # 闸①(2026-10-15 源文件哈希校验)已在上方 formats 适配器之前做毕——到此=底稿可信。
+ proj_name = srow["Name"] if "Name" in srow.keys() else srow["name"]
+ # 每组 (uw, kind):x_seq 序走一遍——源清单计源序位,x_new 行记锚点
+ groups = {}
+ for b in sc.execute("""SELECT id, uw_id, div_id, Number, Name, Attr, Unit, Quantity, Price, Total,
+ Kind, x_new, x_tdel, x_seq, src_remark
+ FROM s_bills WHERE session_id=?
+ ORDER BY uw_id,
+ CASE WHEN x_seq IS NULL THEN 1 ELSE 0 END, x_seq, id""", (sid,)):
+ kind = "prelim" if b["Kind"] == "prelim" else "item"
+ g = groups.setdefault((b["uw_id"], kind), {"pos": 0, "pairs": [], "news": []})
+ bd = dict(b)
+ # 补记十六:合价口径——**新增清单** 导出时按 工程量×单价 现算;
+ # 已有清单在编辑保存时已同步(上面的 API 入口),导出按会话现值原样写穿(决策 90)
+ if b["x_new"]:
+ _q, _p2 = f_(b["Quantity"]), f_(b["Price"])
+ bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
+ if b["x_new"]:
+ bd["_anchor"] = g["pos"]
+ # 补记十六(主人定):新增清单 合价 = 工程量×单价——工作台不预存合价,导出时现算
+ _q, _p2 = f_(b["Quantity"]), f_(b["Price"])
+ bd["Total"] = round((_q or 0) * (_p2 or 0), 2)
+ g["news"].append(bd)
+ else:
+ g["pos"] += 1
+ g["pairs"].append((g["pos"], bd))
+ # 决策 274 补记四判定(2026-11-05 主人定「什么都没动,导出应与原件一模一样」)——
+ # 提前到映射源注入段之前:无工料机动作(没合并/改价/拆分/字段编辑)且清单/定额量价
+ # 未编辑(源件四元组多重集数值化对照)→ 工料机汇总区一律源样直出(注入/换码/删行/
+ # 现算写回/Project 重建全跳)。有任一动作 → 照常手术链(199/244 补三 在审核场景保留)。
+ _lme_untouched = False
+ try:
+ _acts = bool(_setting_get("session:%d" % sid, "merged_codes")
+ or _setting_get("session:%d" % sid, "recode_map")
+ or _setting_get("session:%d" % sid, "lme_field_codes"))
+ _n_acts = sc.execute("SELECT 1 FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?) AND (x_adopt=1 OR x_tdel=1) LIMIT 1", (sid,)).fetchone()
+ _b_acts = sc.execute("SELECT 1 FROM s_bills WHERE session_id=? AND (COALESCE(x_new,0)=1 OR COALESCE(x_tdel,0)=1) LIMIT 1", (sid,)).fetchone()
+ if not (_acts or _n_acts or _b_acts):
+ _sb, _sn = xcos.src_qty_multiset(src_bytes)
+ if _sb is not None:
+ def _ndef(rows):
+ return sorted(
+ (str(r[0] or ""), None if r[1] is None else round(float(r[1]), 6),
+ None if r[2] is None else round(float(r[2]), 6),
+ None if r[3] is None else round(float(r[3]), 6)) for r in rows)
+ _lb = _ndef(sc.execute("SELECT Number, Quantity, Price, Total FROM s_bills WHERE session_id=? AND COALESCE(x_new,0)=0 AND COALESCE(x_tdel,0)=0", (sid,)))
+ _ln = _ndef(sc.execute("SELECT n.Number, n.Quantity, n.Price, n.Total FROM s_norms n WHERE n.bill_id IN (SELECT id FROM s_bills WHERE session_id=?) AND COALESCE(n.x_adopt,0)=0", (sid,)))
+ _lme_untouched = (_lb == _sb) and (_ln == _sn)
+ except Exception:
+ import traceback as _tb
+ _tb.print_exc()
+ _lme_untouched = False
+ # 决策 274 补记七(2026-11-05 主人定「维持原决策:显示什么导出什么,口径一致」):
+ # 判定结果仅作对照记录,不再切换导出路径——导出恒走现算链(与显示同口径,
+ # 人工费 3 组=导出 3 条)。源样直出已下线(补记五)。
+ _lme_untouched = False
+ norms_by_bill = {}
+ for nb in sc.execute("""SELECT id, bill_id, Number, Name, Unit, Quantity, Price, Total, x_tdel, x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side
+ FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?)
+ ORDER BY id""", (sid,)):
+ entry = norms_by_bill.setdefault(nb["bill_id"], {"source": [], "append": []})
+ if nb["x_adopt"] and nb["x_tdel"]:
+ continue # 临删的采纳定额:导出直接不写(2026-10-15 定额级 ntdel 配套;原有定额的
+ # 临删仍走 transform_unit 的原位省略,保住与文件的对位关系)
+ (entry["append"] if nb["x_adopt"] else entry["source"]).append(dict(nb))
+ # 决策 90(2026-10-17):工程量公式(GCL/数字四则)→ 按**当时**清单量求值
+ # (决策 216 新口径:GCL=清单工程量原值,公式结果整体÷单位因子,dyn_lme.formula_qty)。
+ # 合价=求值量×单价(金额2位)。
+ # 采纳后清单量再改,导出自动跟最新值——这正是公式原文不落死数字的意义。
+ bill_qtys = {r["id"]: r["Quantity"] for r in sc.execute(
+ "SELECT id, Quantity FROM s_bills WHERE session_id=?", (sid,))}
+ for entry in norms_by_bill.values():
+ for nb in entry["append"] + entry["source"]:
+ if nb.get("qty_expr"):
+ q, _msg = _formula_qty(nb["qty_expr"], bill_qtys.get(nb["bill_id"]), nb["Unit"]) # 决策 216
+ if q is not None:
+ nb["Quantity"] = q
+ nb["Total"] = round(q * (float(nb["Price"]) if nb["Price"] is not None else 0.0), 2)
+ # 采纳定额的工程量/合价回填(2026-10-15 主人指出:留 0 导致易达清单综合单价为空、
+ # 与广联达不一致)。公式没接住(求值失败/结果 0)而批次源定额有原值的,从批次源定额
+ # (x_src_norm_id)取原值,与原 cos4 一致;审核已在软件里改过量的(非 NULL)不覆盖。
+ hc = conn()
+ try:
+ for entry in norms_by_bill.values():
+ for nb in entry["append"] + entry["source"]:
+ if nb.get("x_src_norm_id") and (nb["Quantity"] is None or xcos._num_eq(nb["Quantity"], 0)):
+ row = hc.execute("SELECT Quantity, Total FROM norms WHERE id=?",
+ (nb["x_src_norm_id"],)).fetchone()
+ if row:
+ nb["Quantity"], nb["Total"] = row["Quantity"], row["Total"]
+ finally:
+ hc.close()
+ # 决策 274 补记七(2026-11-05 主人定「导入=导出,不失真」):撤补记十六「合价=量×价现算」——
+ # 实证源件合价 891.31(易达内部全精度量算的),按显示舍入量重算=891.33 放大误差 ±0.02;
+ # 库合价=采集源件值(采集层实证无错),写穿即保真;用户编辑量/价时保存 API 已同步合价,两态都对。
+ res_by_norm = {}
+ for rr in sc.execute("""SELECT nr.norm_id, nr.res_code, nr.qty, nr.express FROM s_norm_res nr
+ WHERE nr.norm_id IN (SELECT id FROM s_norms
+ WHERE bill_id IN (SELECT id FROM s_bills WHERE session_id=?))""", (sid,)):
+ res_by_norm.setdefault(rr["norm_id"], []).append((rr["res_code"], rr["qty"], rr["express"]))
+ # (uw_id, kind) → uw 键;同 uw 的两种 kind 合成一份 plan
+ uwmap = {r["id"]: ((r["Number"] or ""), (r["Name"] or ""))
+ for r in sc.execute("SELECT id, Number, Name FROM s_unit_works WHERE session_id=?", (sid,))}
+ # 决策 186:源文本按单位缓存(映射源注入判据=源 xml 有没有该汇总节点;导出 truth=源文本)
+ _uw_src_text = {}
+ try:
+ _zin = zipfile.ZipFile(io.BytesIO(src_bytes))
+ for _n in _zin.namelist():
+ if not _n.lower().endswith(".xml") or _n.lower().startswith("project"):
+ continue
+ _t = _zin.read(_n).decode("utf-8", "replace")
+ for _uid, _k in uwmap.items():
+ if _k[0] and ('? AND src_name IS NOT NULL "
+ "ORDER BY id DESC LIMIT 12", (sid,)):
+ _nm = rr[0] or ""
+ if ";" in _nm or classic_skeleton.suffix_of(_nm) != _sfx0:
+ continue
+ _p2 = os.path.join(UPLOAD_DIR, _nm)
+ if os.path.exists(_p2):
+ _cands.append((_nm, open(_p2, "rb").read()))
+ _hc2 = conn()
+ try:
+ for f2 in _hc2.execute(
+ "SELECT original_name, blob FROM classic_skel WHERE suffix=? AND is_frame=1",
+ (_sfx0,)):
+ _cands.append((f2[0] or "骨架", bytes(f2[1] or b"")))
+ finally:
+ _hc2.close()
+ _bank = classic_skeleton.local_form_bank(_src_cols, _cands)
+ except Exception:
+ _bank = {}
+ # 决策 274 补记四(2026-11-05 主人定「什么都没动,导出应与原件一模一样」):
+ # 无工料机动作(没合并/改价/采纳/隐藏/字段编辑)且清单/定额量价未编辑(源件四元组
+ # 多重集数值化对照)→ 工料机汇总区一律**源样直出**:sync/price/added/hidden 置空、
+ # 0 量行不删(易达原件自带 -0.0000 行)、同码不并、现算数量不写回、Project.xml 整件源样。
+ # 有任一动作/编辑 → 照常手术链(199/244 补三 口径在审核场景保留)。
+ # 判定已提前(映射源注入段之前)——此处只做无动作置空
+ # 决策 274 补记五(2026-11-05 主人定「只能按现算导出,不一致查原因修正;源样直出仅作范本」):
+ # _lme_untouched 判定保留为对照工具,但不再切换导出路径——导出恒走现算链。
+ # 实证:现算与易达实时重算一致(大修理费 49.0325=易达汇总页 49.0325;折旧费
+ # 18697.8863≈18697.8895)——A 源件 LME_SUM 行是导出快照(项目级 590.2310),非重算真相。
+ # 决策 274 补记七(2026-11-05 主人定「维持原决策:显示什么导出什么,口径一致」):
+ # 项目级工料机汇总的聚合组别=显示端同一分组键(除数量外 12 元组,flags 全参与)——
+ # uw 键→组序映射,供 Project 聚合重建按组拆行(人工费 3 组=导出 3 条,与显示一致)。
+ _uw_groups = {}
+ try:
+ _ukey_of = {}
+ for _i, (_nn, _nm) in uwmap.items():
+ _ukey_of[(_nn, _nm)] = (_nn, _nm)
+ _grows = sc.execute("""SELECT uw_id, code, name, spec, unit, kind, ntp, taxrate, taxp,
+ ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags
+ FROM s_lme_uw WHERE session_id=? ORDER BY uw_id, id""", (sid,)).fetchall()
+ _gidx, _gseq = {}, []
+ for _r in _grows:
+ _k = (_r["code"], _r["name"] or "", _r["spec"] or "", _r["unit"] or "", _r["kind"],
+ _r["ntp"], _r["taxrate"], _r["taxp"], _r["ntp_org"], _r["ntp_expr"],
+ _r["taxp_org"], _r["taxp_expr"], _r["x_flags"])
+ if _k not in _gidx:
+ _gidx[_k] = len(_gseq)
+ _gseq.append(_k)
+ _ukey = uwmap.get(_r["uw_id"])
+ if _ukey:
+ _uw_groups[(_ukey, _r["code"])] = _gidx[_k] # 行级:一个 uw 的多行分属不同组
+ except Exception:
+ _uw_groups = {}
+ try:
+ raw, out_name = xcos.export_zip(src_bytes, proj_name, srow["src_name"],
+ unit_plans, added, hidden, res_by_norm,
+ form_bank=_bank, lme_untouched=_lme_untouched,
+ uw_groups=_uw_groups,
+ price_updates=price_updates,
+ added_lme_by_uw=None, sync_rows=sync_rows,
+ recode_map=recode_map, recode_children=recode_children,
+ recode_ident=recode_ident,
+ field_updates=field_updates,
+ added_children=added_children,
+ added_org=added_org,
+ progress=progress)
+ except Exception as e:
+ return None, None, "导出失败:%s" % e
+ return raw, out_name, None
# ---------- 合并工料机(批次C,决策 69;方案 §6,主人定稿的树形弹框)----------
def _merged_codes_add(sc, sid, code):
@@ -4829,7 +5377,6 @@ def _lme_merge_groups(con, sid, sub=False):
_kval(r, "kind"), _kval(r, "ntp"), _kval(r, "taxrate"), _kval(r, "taxp"),
_kval(r, "ntp_org"), _kval(r, "ntp_expr"), _kval(r, "taxp_org"), _kval(r, "taxp_expr"),
_kval(r, "x_flags"))
-
def _mid(ps):
# 升序中位(空价靠后):1条→它、2条→低、3条→居中(决策 108 单价规则同款)
ps = [p for p in ps]
@@ -5763,6 +6310,7 @@ def api_bill_unadopt(sc, hc, body):
if not sb:
return {"ok": False, "msg": "清单不存在"}
if not sb["x_adopt"]:
+ adopt_src_clear(sc, sid, "bill", bid) # 决策 256:备注式采纳也无来源快照残留
return {"ok": True, "sid": sid, "noop": 1} # 只有备注式采纳:数据侧无动作,前端照旧清备注
# 决策 243:撤清单附件采纳事件(失败不挡取消采纳本身)
try:
@@ -5792,6 +6340,7 @@ def api_bill_unadopt(sc, hc, body):
Quantity=0, Price=NULL, Total=0, x_adopt=0 WHERE id=?""", (bid,))
else:
sc.execute("UPDATE s_bills SET x_adopt=0 WHERE id=?", (bid,))
+ adopt_src_clear(sc, sid, "bill", bid) # 决策 256:取消采纳=来源快照一并清(含 noop 分支之上)
return {"ok": True, "sid": sid}
@@ -5814,8 +6363,9 @@ def api_schema():
{"session_id": 5, "n_bill": 1262, "n_norm": 1973}),
r("POST", "/api/session/delete", "删会话", {"ids*": "[会话id,...]"}),
r("GET", "/api/projdirs", "项目目录列表+项目归属(最近审核「项目目录」弹框,2026-11-04)"),
- r("POST", "/api/projdirs/save", "项目目录维护:目录增/改名/删/上下移 + 项目归类",
- {"op*": "add(name,parent) | ren(id,name) | del(id) | move(id,d=-1/1) | assign(name,dir_id=0归未归类)"}),
+ r("POST", "/api/projdirs/save", "项目目录维护:目录增/改名/删/上下移 + 项目归类/同级移动",
+ {"op*": "add(name,parent) | ren(id,name) | del(id) | move(id,d=-1/1) | "
+ "move_proj(name,d=-1/1 同级移动不改归属) | assign(name,dir_id=0归未归类)"}),
r("GET", "/api/session/manual/state", "手工工程目录树回填(导入项目弹框,决策 230)",
{"session_id*": "会话id"}),
r("GET", "/api/session/manual/template", "单位工程导入模板 xlsx(填写说明/分部分项/措施项目)"),
@@ -8846,6 +9396,8 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(api_lme_src(one))
if p == "/api/dup_check": # 决策 243 补记五:导入预检(选文件即查重,两侧共用)
return self._json(api_dup_check(one))
+ if p == "/api/session/adopt/src": # 决策 256:采纳来源快照读取(溯源定位,跨重开)
+ return self._json(api_adopt_src_get(one))
if p == "/api/session/lme/res": # 会话内:台班/配合比的下一级组成
sc0 = sess.connect()
try:
@@ -9541,7 +10093,40 @@ class Handler(SimpleHTTPRequestHandler):
r = api_adopt_cancel(body)
except Exception as e:
r = {"ok": False, "msg": "取消采纳失败:%s" % e}
+ try:
+ # 决策 256:来源快照一并清(工料机取消无统一后端入口,此处权威清)
+ if body.get("lme_id"):
+ sc0 = sess.connect()
+ try:
+ adopt_src_clear(sc0, int(body.get("session_id") or 0), "lme", int(body.get("lme_id") or 0))
+ sc0.commit()
+ finally:
+ sc0.close()
+ except Exception as e:
+ print("清采纳来源快照失败:%s" % e, flush=True)
return self._json(r)
+ if u.path == "/api/session/adopt/src": # 决策 256:采纳来源快照(record/clear)
+ try:
+ if body.get("act") == "clear":
+ with WRITE_LOCK:
+ sc0 = sess.connect()
+ try:
+ adopt_src_clear(sc0, int(body.get("session_id") or 0),
+ body.get("type") or "bill", int(body.get("row_id") or 0))
+ sc0.commit()
+ finally:
+ sc0.close()
+ return self._json({"ok": True})
+ with WRITE_LOCK:
+ sc0 = sess.connect()
+ try:
+ r = api_adopt_src_record(body)
+ sc0.commit()
+ finally:
+ sc0.close()
+ return self._json(r)
+ except Exception as e:
+ return self._json({"ok": False, "msg": "采纳来源快照失败:%s" % e})
m = re.match(r"^/api/admin/batch/(\d+)/delete$", u.path)
if m:
with WRITE_LOCK:
diff --git a/CostReview/app/server/license_client/gate.py b/CostReview/app/server/license_client/gate.py
index 55b1944..ace8bb0 100644
--- a/CostReview/app/server/license_client/gate.py
+++ b/CostReview/app/server/license_client/gate.py
@@ -238,7 +238,9 @@ def _integrity_page():
"""N1 完整性拦截页(自包含):文件被改时的唯一可见页面。"""
return """
软件文件校验失败
-