From 380a39f8db78816b097d3428d1c78a29d4959aa5 Mon Sep 17 00:00:00 2001 From: lianjianwei2024 <168657369+lianjianwei2024@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:16:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=90=BD=E5=AE=9E=E5=86=B3=E7=AD=96216?= =?UTF-8?q?/219/227=E5=8F=96=E4=BB=B7=E9=94=9A=E7=82=B9=E4=B8=8E=E5=85=AC?= =?UTF-8?q?=E5=BC=8F=E5=8F=A3=E5=BE=84=EF=BC=8C=E5=A2=9E=E5=8A=A0=E5=95=86?= =?UTF-8?q?=E4=B8=9A=E7=89=88=E6=9D=83=E7=9B=8A=E5=92=8C=E6=BA=90=E7=A0=81?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=E6=80=A7=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CostReview/_patch_ehsnap.py | 142 + CostReview/app/core/dyn_lme.py | 256 +- CostReview/app/core/session_job.py | 55 +- CostReview/app/server/api_server.py | 260 +- .../app/server/license_client/client.py | 7 +- CostReview/app/server/license_client/gate.py | 56 +- .../app/server/license_client/verify.py | 36 +- CostReview/app/server/version_gate.py | 226 + CostReview/app/store/schema.sql | 1 + CostReview/app/store/session.sql | 3 +- CostReview/app/tests/lic_helpers.py | 14 +- .../app/tests/test_adopt_children220.py | 81 + CostReview/app/tests/test_build_integrity.py | 70 + CostReview/app/tests/test_license_client.py | 23 + CostReview/app/tests/test_license_verify.py | 57 + CostReview/app/tests/test_lme_chain219.py | 100 + CostReview/app/tests/test_norm_op.py | 4 +- CostReview/app/tests/test_version_gate.py | 150 + CostReview/app/ui/admin.html | 68 +- CostReview/app/ui/common.css | 10 + CostReview/app/ui/common.js | 123 +- CostReview/app/ui/sessions.html | 3 +- CostReview/app/ui/workbench.html | 388 +- _j222_out.txt | 1 + build_portable.py | 155 +- test/_tmp_ui227_prep.py | 114 + tmp09bciepmcacert.pem | 3936 +++++++++++++++++ tmp2elv0nij/cacert.pem | 3936 +++++++++++++++++ tmpae1fvno0cacert.pem | 3936 +++++++++++++++++ tmpt1ulju79cacert.pem | 3936 +++++++++++++++++ 代码地图.md | 875 ++-- 企业和个人版.md | 397 ++ 决策台账.md | 169 + 决策台账索引.md | 13 + 授权平台扩展任务书(发同事).md | 87 + 术语表.md | 12 +- 36 files changed, 18821 insertions(+), 879 deletions(-) create mode 100644 CostReview/_patch_ehsnap.py create mode 100644 CostReview/app/server/version_gate.py create mode 100644 CostReview/app/tests/test_adopt_children220.py create mode 100644 CostReview/app/tests/test_build_integrity.py create mode 100644 CostReview/app/tests/test_lme_chain219.py create mode 100644 CostReview/app/tests/test_version_gate.py create mode 100644 _j222_out.txt create mode 100644 test/_tmp_ui227_prep.py create mode 100644 tmp09bciepmcacert.pem create mode 100644 tmp2elv0nij/cacert.pem create mode 100644 tmpae1fvno0cacert.pem create mode 100644 tmpt1ulju79cacert.pem create mode 100644 企业和个人版.md create mode 100644 授权平台扩展任务书(发同事).md diff --git a/CostReview/_patch_ehsnap.py b/CostReview/_patch_ehsnap.py new file mode 100644 index 0000000..150baab --- /dev/null +++ b/CostReview/_patch_ehsnap.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# 决策 218 补二:编辑历史改版——按清单快照(时间|工程量|单价|合价),只记清单,本次不出现 +import io + +p = r'D:\PricingReview\CostReview\app\server\api_server.py' +with io.open(p, encoding='utf-8') as f: + t = f.read() + +def rep(old, new, tag): + global t + assert t.count(old) == 1, tag + ' count=' + str(t.count(old)) + t = t.replace(old, new) + +# 1) 清单快照函数(_edit_log 前) +rep('def _edit_log(sc, ekbase, fields, cols, row):', +'''def _bill_snap_log(sc, brow): + """清单编辑快照(决策 218 补二,2026-10-26 主人定):清单被编辑/采纳覆盖**前**的三值快照 + (工程量|单价|合价)——编辑历史浮层按 时间|工程量|单价|合价 展示;记的是改前值, + 本次(最新)状态就在格子上看,天然不重复出现。只记清单,定额不再记。""" + import json as _json + o = _json.dumps({"q": brow["Quantity"], "p": brow["Price"], "t": brow["Total"]}, + ensure_ascii=False) + sc.execute("INSERT INTO s_edit_log(ekbase, f, o, n) VALUES(?,?,?,'')", + (_bill_ekbase(sc, brow), "SNAP", o)) + + +def _edit_log(sc, ekbase, fields, cols, row):''', 'snap函数') + +# 2) 清单行内编辑:改前快照替代逐字段日志 +rep(''' cur_row = sc.execute("SELECT * FROM s_bills WHERE id=?", (bid,)).fetchone() + vals.append(bid) + sc.execute("UPDATE s_bills SET %s WHERE id=?" % ",".join(sets), vals) + _edit_log(sc, _bill_ekbase(sc, cur_row), ef, _BILL_EDIT_FIELDS, cur_row)''', +''' cur_row = sc.execute("SELECT * FROM s_bills WHERE id=?", (bid,)).fetchone() + _bill_snap_log(sc, cur_row) # 决策 218 补二:改前快照(时间|工程量|单价|合价),只记清单 + vals.append(bid) + sc.execute("UPDATE s_bills SET %s WHERE id=?" % ",".join(sets), vals)''', 'bill edit') + +# 3) 定额编辑不再记日志 +rep(''' sc.execute("UPDATE s_norms SET %s WHERE id=?" % ",".join(sets), vals) + _edit_log(sc, _norm_ekbase(sc, cur_row), + {k: fields[k] for k in ("Name", "Quantity") if k in fields}, + {"Name": "Name", "Quantity": "Quantity"}, cur_row)''', +''' sc.execute("UPDATE s_norms SET %s WHERE id=?" % ",".join(sets), vals) + # 决策 218 补二:定额编辑不再记日志(编辑历史只记清单快照)''', 'norm edit') + +# 4) 采纳覆盖也记改前快照(在 9.3 单价覆盖 UPDATE 前抓 sb——sb 已在函数头取过,补快照) +rep(''' new_price = bb["Price"] + src_qty = f_(bb["Quantity"])''', +''' new_price = bb["Price"] + _bill_snap_log(sc, sb) # 决策 218 补二:采纳覆盖前快照(采纳也是一次变更) + src_qty = f_(bb["Quantity"])''', 'adopt snap') + +# 5) api_edit_log:下发快照(清单键=ekbase 本身);旧字段级行不再下发(口径换,铁律6) +rep(''' bases = set(m.values()) + log = [] + for r in sc.execute("SELECT ekbase, f, o, n, at FROM s_edit_log ORDER BY id DESC").fetchall(): + if r["ekbase"] in bases: + log.append({"k": r["ekbase"] + ":" + r["f"], "o": r["o"], "n": r["n"], "at": r["at"]})''', +''' bases = set(m.values()) + log = [] + # 决策 218 补二:只下发清单快照行(f=SNAP,o=json{q,p,t});字段级旧行不再下发 + import json as _json + for r in sc.execute("SELECT ekbase, f, o, n, at FROM s_edit_log WHERE f='SNAP' ORDER BY id DESC").fetchall(): + if r["ekbase"] in bases: + try: + s = _json.loads(r["o"] or "{}") + except Exception: + s = {} + log.append({"k": r["ekbase"], "at": r["at"], + "q": s.get("q"), "p": s.get("p"), "t": s.get("t")})''', 'api_edit_log') + +with io.open(p, 'w', encoding='utf-8', newline='\n') as f: + f.write(t) +print('后端五处已改') + +# ---------- 前端 common.js ---------- +p = r'D:\PricingReview\CostReview\app\ui\common.js' +with io.open(p, encoding='utf-8') as f: + t = f.read() + +# 1) 映射简化:只挂清单行工程量格(组表 idx8 / 原数据 idx7);定额映射弃 +rep("""const EH_FIELDS_BILL = { Name: 5, Attr: 6, Unit: 7, Quantity: 8, src_remark: 12 }; // 组表列位 +const EH_FIELDS_BILL_RAW = { Name: 4, Attr: 5, Quantity: 7 }; // 决策 218 补:原数据行列位(0把手1序号2编码3类型4名称5特征7工程量) +const EH_FIELDS_NORM = { Name: 5, Quantity: 8 };""", +"""/* 决策 218 补二:编辑历史只挂**清单行工程量格**(组表 idx8 / 原数据 idx7);键=清单 ekbase; + 浮层按 时间|工程量|单价|合价 展示改前快照。定额不再有编辑历史。 */ +const EH_QTY_IDX = { grp: 8, raw: 7 };""", '映射简化') + +# 2) markGroupEH:只挂清单行、键=ekbase +rep(""" const mark = (tr, fields, rid) => { + const base = EH_M[String(rid)]; // 稳定键基(重解析不丢,服务端下发) + if (!base) return; + for (const f in fields) { + const k = base + ':' + f; + if (EH_LOG[k] && EH_LOG[k].length) { + const td = tr.children[fields[f]]; + if (td) { td.classList.add('eh'); td.dataset.ehk = k; } + } + } + }; + const billMap = (tb.id === 'rawbody') ? EH_FIELDS_BILL_RAW : EH_FIELDS_BILL; + tb.querySelectorAll('tr[data-bid]').forEach(tr => mark(tr, billMap, tr.dataset.bid)); + tb.querySelectorAll('tr.sub[data-nid]').forEach(tr => mark(tr, EH_FIELDS_NORM, tr.dataset.nid));""", +""" const mark = (tr, qtyIdx, rid) => { + const k = EH_M[String(rid)]; // 决策 218 补二:键=清单 ekbase(快照聚合) + if (k && EH_LOG[k] && EH_LOG[k].length) { + const td = tr.children[qtyIdx]; + if (td) { td.classList.add('eh'); td.dataset.ehk = k; } + } + }; + const isRaw = (tb.id === 'rawbody'); + tb.querySelectorAll('tr[data-bid]').forEach(tr => mark(tr, EH_QTY_IDX[isRaw ? 'raw' : 'grp'], tr.dataset.bid));""", 'markGroupEH') + +# 3) loadEditLog 解析(键不再拼字段) +rep(""" EH_M = d.m || {}; EH_LOG = {}; + (d.log || []).forEach(r => { + (EH_LOG[r.k] = EH_LOG[r.k] || []).push({ at: r.at, o: r.o, n: r.n }); + });""", +""" EH_M = d.m || {}; EH_LOG = {}; + (d.log || []).forEach(r => { // 决策 218 补二:快照行 {k,at,q,p,t},k=清单键 + (EH_LOG[r.k] = EH_LOG[r.k] || []).push({ at: r.at, q: r.q, p: r.p, t: r.t }); + });""", 'loadEditLog') + +# 4) 浮层:四列表 +rep(""" pop.innerHTML = '
编辑历史
' + + list.map((r, i) => '').join('') + + '
' + (i + 1) + '' + esc(r.at || '') + + '' + esc((r.o ? r.o + ' → ' : '') + (r.n == null ? '' : r.n)) + + '
';""", +""" // 决策 218 补二:编辑时间|工程量|单价|合价(改前快照,新→旧;本次=格子现值不在此列) + const f3 = v => (v == null || v === '') ? '—' : v; + pop.innerHTML = '
编辑历史
' + + '' + + list.map(r => '').join('') + + '
编辑时间工程量单价合价
' + esc(r.at || '') + '' + esc(f3(r.q)) + + '' + esc(f3(r.p)) + '' + esc(f3(r.t)) + + '
';""", '浮层四列') + +with io.open(p, 'w', encoding='utf-8', newline='\n') as f: + f.write(t) +print('前端四处已改') diff --git a/CostReview/app/core/dyn_lme.py b/CostReview/app/core/dyn_lme.py index bdf58be..388656c 100644 --- a/CostReview/app/core/dyn_lme.py +++ b/CostReview/app/core/dyn_lme.py @@ -8,8 +8,11 @@ (=母量×子含量,数学全等)——同码双重身份相加,与 qty_map_uw 同式(2026-10-25 主人复确权); 项目级=Σ各单位同键;链算不出一律归零(决策 196:快照值兜底取消,188 方案A原 「直挂/费用科目行快照原样补位」随之废止,费用行量恒 0)。 - 单价: 库内现值(s_lme_proj);带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的, - 实测 990304016:Σ=1156.6425→1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。 + 单价: 决策 219(2026-10-26 主人定)——主取价源=**单位级 s_lme_uw**(每单位每码认导入序第一行, + 同码不同价随便认一个);项目级行=单位级行按 全字段+三价 一致才归并、不一致各自独立, + 行量=各成员单位现算量之和;缺码/缺价兜底 s_lme_proj 快照;与源文件自带汇总不保证一致。 + 带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的,实测 990304016:Σ=1156.6425 + →1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。 覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价); 改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。 """ @@ -19,11 +22,8 @@ _QTY_EXPR_OK = __import__("re").compile(r"^[\d+\-*/().\s]*$") def gcl_of(bill_qty, unit): - """GCL 数值(决策 205 收口核心层,与原 api_server._gcl_of 同款算法——聚合链与编辑/导出同一把尺): - 清单工程量 ÷ 定额单位数字前缀(10t→10);纯字母/无数字单位 GCL=清单工程量;清单量空按 0。round 6 位。""" - import import_job - div = import_job.unit_prefix(unit) - return round((float(bill_qty) if bill_qty is not None else 0.0) / div, 6) + """兼容旧调用的 GCL 原值——决策 216:GCL=清单工程量原值,单位因子只在公式结果上最后除。""" + return round(float(bill_qty) if bill_qty is not None else 0.0, 6) def eval_qty_expr(expr, gcl): @@ -49,11 +49,29 @@ def eval_qty_expr(expr, gcl): return round(v, 6), None +def unit_factor(unit): + """定额单位数字前缀因子(10m3→10、1000m3→1000;纯字母/无数字=1)。决策 216 用。""" + import import_job + div = import_job.unit_prefix(unit) + return div if div and div > 0 else 1.0 + + +def formula_qty(expr, bill_qty, unit): + """公式定额量——决策 216(2026-10-26 主人定,取代 90/106 的 GCL 先÷单位口径): + GCL=**清单工程量原值**(不先除单位);公式不论多少层括号/加减乘除, + **最后的结果整体÷单位数字前缀**=定额量。求值失败 → (None, msg)。""" + v, msg = eval_qty_expr(expr, bill_qty if bill_qty is not None else 0.0) + if v is None: + return None, msg + return round(v / unit_factor(unit), 6), None + + def _norm_qty(nq, expr, unit, bill_qty): - """定额量取数(决策 205):公式按 GCL 求值(决策 90 跟随),无公式用存储量;都无 → None。""" + """定额量取数(决策 205;公式口径决策 216 改:GCL=清单原值,结果整体÷单位)。 + 无公式用存储量(纯数字=实际量÷因子口径不变);都无 → None。""" if expr: try: - v, _msg = eval_qty_expr(expr, gcl_of(bill_qty, unit)) + v, _msg = formula_qty(expr, bill_qty, unit) if v is not None: return float(v) except Exception: @@ -64,10 +82,12 @@ def _norm_qty(nq, expr, unit, bill_qty): return None -def _consumption_by_code(sc, sid, uw_id=None): +def _consumption_by_code(sc, sid, uw_id=None, by_uw=False): """每码消耗量:{code: qty}。uw_id=None=全会话(项目级)。剔除临删定额/清单。 决策 205(2026-10-25 主人定):定额量**按求值取数**——采纳挂 GCL 公式的定额 - (存储量 NULL,如 10# D3-6-5)此前整条丢掉,自算 0 vs 回导入 1,040 分叉的根因。""" + (存储量 NULL,如 10# D3-6-5)此前整条丢掉,自算 0 vs 回导入 1,040 分叉的根因。 + 决策 219 by_uw=True:一次扫描按单位分桶 {uw_id: {code: qty}}(项目级行量=各成员 + 单位现算量之和——组量有真实归属,不再需要按比例分摊)。""" # ⚠️ s_norm_res 无 session_id 列——会话域经 norm→bill 链传达 # 防御(与 dyn_rows 同款):老库可能缺 qty_expr/Unit 列 → 可选补位; # 但 **Quantity 必须存在**——缺失说明计算链不完整,抛错让 dyn_rows 退 None 走快照老路 @@ -79,20 +99,21 @@ def _consumption_by_code(sc, sid, uw_id=None): sel_nex = "n.qty_expr AS nex" if have("s_norms", "qty_expr") else "NULL AS nex" sel_nu = "n.Unit AS nu" if have("s_norms", "Unit") else "NULL AS nu" sel_bq = "b.Quantity AS bq" if have("s_bills", "Quantity") else "NULL AS bq" + sel_buw = "b.uw_id AS buw" if have("s_bills", "uw_id") else "NULL AS buw" # 决策 219 分桶 sel_td_n = "COALESCE(n.x_tdel,0)=0" if have("s_norms", "x_tdel") else "1=1" sel_td_b = "COALESCE(b.x_tdel,0)=0" if have("s_bills", "x_tdel") else "1=1" sql = """SELECT nr.res_code AS c, nr.qty, n.id AS nid, %s, - %s, %s, %s + %s, %s, %s, %s 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 nr.res_code IS NOT NULL - AND %s AND %s""" % (sel_nq, sel_nex, sel_nu, sel_bq, sel_td_n, sel_td_b) + AND %s AND %s""" % (sel_nq, sel_nex, sel_nu, sel_bq, sel_buw, sel_td_n, sel_td_b) args = [sid] if uw_id is not None: sql += " AND b.uw_id=?" args.append(uw_id) - out = {} + out = {} # by_uw=True 时值= {uw_id: {code: qty}} cache = {} # norm_id → 求值后的定额量(同一定额只算一次) for r in sc.execute(sql, args): if not r["c"]: @@ -104,9 +125,14 @@ def _consumption_by_code(sc, sid, uw_id=None): if nq is None: continue try: - out[r["c"]] = out.get(r["c"], 0.0) + float(r["qty"] or 0) * nq + q = float(r["qty"] or 0) * nq except (TypeError, ValueError): - pass + continue + if by_uw: + b = out.setdefault(r["buw"], {}) + b[r["c"]] = b.get(r["c"], 0.0) + q + else: + out[r["c"]] = out.get(r["c"], 0.0) + q return out @@ -120,7 +146,8 @@ def _children_map(sc, sid): def _price_map(sc, sid): - """{code: {name,spec,unit,kind,ntp,taxrate,taxp,qty,id,hide,x_remark}} 项目级现值快照(价格/名规单/备注真值)。""" + """{code: {name,spec,unit,kind,ntp,taxrate,taxp,qty,id,hide,x_remark}} 项目级现值快照(价格/名规单/备注真值)。 + 决策 219 起降为**兜底**(缺码/缺价才取)+行id/备注/隐藏标记来源;主取价源=单位级 _uw_price_rows。""" out = {} for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp, COALESCE(x_merged_hide,0) AS hid, x_remark @@ -129,6 +156,34 @@ def _price_map(sc, sid): return out +def _uw_price_rows(sc, sid): + """决策 219(2026-10-26 主人定):单位级取价——**每个单位工程每码认导入顺序第一行** + (同一单位工程同码不同价=随便认一个,主人定;不同单位工程各认各的)。 + {code: [行dict(uw 去重、id 序)]},行含 uw_id/名规单/类别/三价。""" + out = {} + for r in sc.execute("""SELECT id, uw_id, code, name, spec, unit, kind, ntp, taxrate, taxp + FROM s_lme_uw WHERE session_id=? ORDER BY id""", (sid,)): + if not r["code"]: + continue + lst = out.setdefault(r["code"], []) + if any(str(m["uw_id"]) == str(r["uw_id"]) for m in lst): + continue # 同一单位工程同码只认第一行 + lst.append(dict(r)) + return out + + +def _recode_away(sc, sid): + """已合并换码的旧码集(决策 219 显示端防复活:合并后单位级表可能还留着旧码行, + 与项目级隐藏口径不一致 → 不再显示,归并到保留码)。""" + row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='recode_map'", + ("session:%d" % sid,)).fetchone() + try: + rm = json.loads(row["v"] or "{}") if row else {} + except (TypeError, ValueError): + rm = {} + return set(k for k, v in rm.items() if k and v and k != v) + + def _overrides(sc, sid): row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_ov'", ("session:%d" % sid,)).fetchone() try: @@ -197,29 +252,44 @@ def dyn_rows(sc, sid, uw_id=None): def _dyn_rows(sc, sid, uw_id=None): - consume = _consumption_by_code(sc, sid, uw_id) kids = _children_map(sc, sid) pm = _price_map(sc, sid) ov = _overrides(sc, sid) - fb_codes = [] - if uw_id is not None: - # 单位级骨架=本单位快照 s_lme_uw 的码(决策 41 本单位汇总节点)——只取码不取量: - # 原实现取 s_lme_proj.qty(项目级总量),每个单位都显示项目级总量,2026-10-25 实测报障 - for r in sc.execute("SELECT code FROM s_lme_uw WHERE session_id=? AND uw_id=? " - "GROUP BY code ORDER BY MIN(id)", (sid, uw_id)): - fb_codes.append(r["code"]) + 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} - def price_of(code): - p = pm.get(code) - if not p: - return None, None, None - return p["ntp"], p["taxrate"], p["taxp"] + # 决策 219 兜底:单位级行三价缺 → 项目级快照补(主人定「编号或单价实在没有的去项目级取」) + for _c, _lst in uwp.items(): + _p = pm.get(_c) + for _r in _lst: + if _p: + if _r["ntp"] is None: + _r["ntp"] = _p["ntp"] + if _r["taxrate"] is None: + _r["taxrate"] = _p["taxrate"] + if _r["taxp"] is None: + _r["taxp"] = _p["taxp"] - def computed_mother(code): - """带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退库值)。""" + def child_px(code, uw=None): + """子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照兜底。""" + lst = uwp.get(code) or [] + r = None + if uw is not None: + r = next((m for m in lst if str(m["uw_id"]) == str(uw)), None) + if r is None and lst: + 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")), + _pk(r and r["taxrate"], p.get("taxrate")), + _pk(r and r["taxp"], p.get("taxp"))) + + def computed_mother(code, uw=None): + """带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。""" sn = st = 0.0 for c, q, _nm in kids.get(code) or (): - ntp, _rt, taxp = price_of(c) + ntp, _rt, taxp = child_px(c, uw) if ntp is None or taxp is None: return None, None try: @@ -229,47 +299,87 @@ def _dyn_rows(sc, sid, uw_id=None): return None, None return round(sn, 2), round(st, 2) - # 子级推导量(先于主循环算好):Σ各母(母量×子含量)——决策 188 数量模型定稿 - child_qty = {} - for mcode, mch in kids.items(): - mq = consume.get(mcode) - if mq is None: - continue - for c, q, _nm in mch: - try: - child_qty[c] = child_qty.get(c, 0.0) + float(mq) * float(q or 0) - except (TypeError, ValueError): - pass - rows, seen = [], set() - # 骨架保行(决策 196):骨架=快照可见码∪现算码,只定行不供量;顺序锚=快照序,现算新码附后 - if uw_id is not None: - skeleton = fb_codes # 本单位快照无此码且无现算量 → 不出 - else: - skeleton = [c for c in pm if pm[c].get("hid") == 0] - skel_set = set(skeleton) - order = skeleton + [c for c in list(consume) + list(child_qty) if c not in skel_set] - for code in order: - if code in seen: - continue - seen.add(code) + _SNAP_KEYS = ("name", "spec", "unit", "kind", "ntp", "taxrate", "taxp") + + def mk_row(code, r, qty): + """11 列行。r=认下的单位级行(或快照 dict);带子级母行 Σ 现算(除非覆盖)。""" p = pm.get(code) or {} - ch = kids.get(code) - qty = consume.get(code) - if code in child_qty: - qty = (qty or 0.0) + child_qty[code] # 决策 188 数量模型:直接消耗+子级推导并入, - # 子级推导量不再被快照兜底顶掉(2026-10-25 修) - if qty is None: - qty = 0.0 # 决策 196:骨架行无现算量 → 归零(快照值兜底废止) - if p.get("hid") and not ch: - continue # 合并隐藏且链上无量的纯重复行 → 不出 - ntp, rate, taxp = price_of(code) - if ch: # 带子级:Σ 现算,除非覆盖 - if not ov.get(code): - cn, ct = computed_mother(code) - if cn is not None: - ntp, taxp = cn, ct - rows.append([p.get("id"), code, p.get("name") or "", p.get("spec") or "", p.get("unit") or "", - qty, ntp, rate, taxp, p.get("kind"), p.get("x_remark")]) # 决策 203:备注随行(采纳/手工同字段) + ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp") + if kids.get(code) and not ov.get(code): + cn, ct = computed_mother(code, r.get("uw_id")) + if cn is not None: + ntp, taxp = cn, ct + return [p.get("id"), code, r.get("name") or "", r.get("spec") or "", r.get("unit") or "", + qty, ntp, rate, taxp, r.get("kind"), p.get("x_remark")] # 决策 203:备注随行(采纳/手工同字段) + + rows, seen = [], set() + if uw_id is not None: + # —— 单位工程级(决策 219):本单位每码一行(认第一行),量=本单位现算(含子级推导) + qmap = qty_map_uw(sc, sid, uw_id) + mine = [(code, r) for code, lst in uwp.items() for r in lst + if str(r["uw_id"]) == str(uw_id)] # id 序=源文件序(顺序锚,决策 41) + for code, r in mine: + seen.add(code) + rows.append(mk_row(code, r, qmap.get(code) or 0.0)) + for code in qmap: # 本单位现算有量而表无行的码(名从快照/子级兜底) + if code and code not in seen and code not in away: + seen.add(code) + p = pm.get(code) or {} + rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), + qmap.get(code) or 0.0)) + else: + # —— 项目级(决策 219):全字段+三价一致的单位级行才并成一行,不一致各自独立; + # 行量=各成员单位现算量之和(真实归属,不按比例分摊) + buckets = _consumption_by_code(sc, sid, None, by_uw=True) + qmaps = {} + for u, m in buckets.items(): + qm = dict(m) + for mcode, mch in kids.items(): # 子级推导(决策 188 数量模型,分桶同款) + mq = qm.get(mcode) + if mq is None: + continue + for c, q, _nm in mch: + try: + qm[c] = qm.get(c, 0.0) + float(mq) * float(q or 0) + except (TypeError, ValueError): + pass + qmaps[u] = qm + groups, gidx = [], {} + for code, lst in uwp.items(): # 顺序锚=单位级行 id 序(源文件序) + for r in lst: + k = (code, r["name"] or "", r["spec"] or "", r["unit"] or "", r["kind"], + r["ntp"], r["taxrate"], r["taxp"]) + g = gidx.get(k) + if g is None: + g = {"code": code, "r": r, "uws": []} + gidx[k] = g + groups.append(g) + g["uws"].append(r["uw_id"]) + for g in groups: + code = g["code"] + seen.add(code) + qty = 0.0 + for u in g["uws"]: + qty += qmaps.get(u, {}).get(code) or 0.0 + rows.append(mk_row(code, g["r"], qty)) + for code, p in pm.items(): # 兜底:单位表全无、仅项目级有的码 + if not code or code in seen or code in away or p.get("hid"): + continue + seen.add(code) + qty = 0.0 + for qm in qmaps.values(): + qty += qm.get(code) or 0.0 + rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), qty)) + _extra = {} # 现算有量而两处都无行的码(名从子级/快照兜底) + for qm in qmaps.values(): + for code, q in qm.items(): + if code: + _extra[code] = _extra.get(code, 0.0) + (q or 0.0) + for code, q in _extra.items(): + if code not in seen and code not in away: + seen.add(code) + p = pm.get(code) or {} + rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), q)) # 名称空白的子级行:从 lme_res.name 兜底 for row in rows: if not row[2]: diff --git a/CostReview/app/core/session_job.py b/CostReview/app/core/session_job.py index 137c27a..f2ad7e2 100644 --- a/CostReview/app/core/session_job.py +++ b/CostReview/app/core/session_job.py @@ -109,6 +109,7 @@ def ensure_lme_proj_remark_scoped(): try: ensure_lme_proj_remark(con) ensure_lme_price_cols(con) + ensure_lme_anchor_cols(con) finally: con.close() @@ -128,6 +129,34 @@ def ensure_lme_price_cols(con): con.commit() +_LME_ANCHOR_COLS = ("x_ntp0", "x_rate0", "x_taxp0") # 决策 219:第一次计算的三价锚(采纳备注旧价源) + + +def ensure_lme_anchor_cols(con): + """老会话库 s_lme_proj 补采纳锚三列(幂等,决策 219)+ 锚空回填:按导入同款公式 + (单位级每码第一行三价,无单位行退汇总自身值)补 NULL 锚——没被改过价的码回填即真值; + 已被改过价的码回填当前值并把锚**冻住**(此后连采纳不再漂)。真值以重导/合并端点为准。""" + cols = [r[1] for r in con.execute("PRAGMA table_info(s_lme_proj)")] + if not cols: + return + for cn in _LME_ANCHOR_COLS: + if cn not in cols: + con.execute("ALTER TABLE s_lme_proj ADD COLUMN %s REAL" % cn) + cols.append(cn) + first = {} + for r in con.execute("SELECT session_id, code, ntp, taxrate, taxp FROM s_lme_uw ORDER BY id"): + first.setdefault((r[0], r[1]), (r[2], r[3], r[4])) # 每码导入序第一行(决策 219 同款) + upd = [] + for r in con.execute("SELECT id, session_id, code, ntp, taxrate, taxp FROM s_lme_proj WHERE x_ntp0 IS NULL"): + f = first.get((r[1], r[2])) + upd.append(((f[0] if f and f[0] is not None else r[3]), + (f[1] if f and f[1] is not None else r[4]), + (f[2] if f and f[2] is not None else r[5]), r[0])) + if upd: + con.executemany("UPDATE s_lme_proj SET x_ntp0=?, x_rate0=?, x_taxp0=? WHERE id=?", upd) + con.commit() + + def _lme_keys(con, sid, src_name=None): """这个会话每条工料机的持久键 → {rkey: 行id}(回填备注用)。前缀 'L:' 隔离清单键。 2026-10-11 决策 40:行 = 项目级汇总 s_lme_proj(标签数据源所在)。 @@ -438,7 +467,9 @@ def connect(): "SundryCosts REAL", "Tax REAL")), ("s_bills", ("div_id INTEGER", # 源文件备注(清单节点 Remark 属性,2026-10-08 加;老库补列,老会话重解析才有) - "src_remark TEXT")), + "src_remark TEXT", + # 决策 217:第一次导进来的原始单价(采纳备注旧价固定源;老库补列后重开工程生效) + "x_price0 REAL")), # 2026-10-08:工料机审核备注(采纳写入,持久副本 s_remarks rkey 前缀 'L:') # + 次精确档(md5 名称+单位,与历史库 lmes 同口径) ("s_lmes", ("x_remark TEXT", "x_hash_semi TEXT")), @@ -616,11 +647,13 @@ def open_project(con, files, meta, job, sid=None): divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None cur.execute("""INSERT INTO s_bills(session_id, uw_id, div_id, Number, Name, Attr, Unit, Quantity, Price, Total, Kind, src_remark, - x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq) - VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", + x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq, + x_price0) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk, norm(nm), norm(attr), norm(unit), - md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq)) + md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq, + price)) # 决策 217:x_price0=第一次导进来的单价,此后改价/采纳不更新 # 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义); # 与 history.db.bills(import_job)同口径,启动迁移重算老数据 bill_ids.append(cur.lastrowid) @@ -712,6 +745,20 @@ def open_project(con, files, meta, job, sid=None): ntp_org, ntp_expr, taxp_org, taxp_expr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (sid, _c, _nm, _sp, _un, _kd, _q, _ntp, _taxp, _rate) + tuple(_x)) + # 决策 219(2026-10-26 主人定):第一次计算的三价锚=单位级每码认第一行的三价 + # (无单位行退汇总自身值)。采纳备注「+旧价」恒取此,改价/再采纳/合并重放不漂; + # 合并工料机生成的行由合并端点把锚改写为合并后首次三价。 + cur.execute("""UPDATE s_lme_proj SET + x_ntp0=COALESCE((SELECT u.ntp FROM s_lme_uw u + WHERE u.session_id=s_lme_proj.session_id AND u.code=s_lme_proj.code + ORDER BY u.id LIMIT 1), ntp), + x_rate0=COALESCE((SELECT u.taxrate FROM s_lme_uw u + WHERE u.session_id=s_lme_proj.session_id AND u.code=s_lme_proj.code + ORDER BY u.id LIMIT 1), taxrate), + x_taxp0=COALESCE((SELECT u.taxp FROM s_lme_uw u + WHERE u.session_id=s_lme_proj.session_id AND u.code=s_lme_proj.code + ORDER BY u.id LIMIT 1), taxp) + WHERE session_id=?""", (sid,)) # 这几样都要**解析完**才知道(sessions 行在解析之前就插好了),所以这里补一笔 if ptotal is not None or pinfo or pfeat: cur.execute("UPDATE sessions SET x_total=?, x_info=?, x_feat=? WHERE id=?", diff --git a/CostReview/app/server/api_server.py b/CostReview/app/server/api_server.py index 378ae31..9c3d2bd 100644 --- a/CostReview/app/server/api_server.py +++ b/CostReview/app/server/api_server.py @@ -45,6 +45,7 @@ import match # 比对引擎(M4) import export_cos as xcos # 导出回写(批次D,决策 70) import formats # 导出格式适配器(2026-10-19:SWT/SWZ 骨架/填空) import license_client.gate as license_gate # 授权门禁(license-v2/lease-v2,2026-10-10) +import version_gate as vgate # 强制更新门禁(2026-10-27,《企业和个人版.md》5.9) import mcp_server as mcpmod # MCP 接入层(2026-10-15;开关+令牌+授权挂钩) # ⚠️ 2026-10-06 删除 `from search_demo import build`:search_demo 的 FTS/x_period 索引只为它 # 自己的演示查询服务,生产比对引擎 match.py 全程用 x_hash_exact/x_hash_semi + LIKE, @@ -178,6 +179,10 @@ def _ensure_edit_cols(): _add(sc, "s_lme_proj", "x_adopt_added", "INTEGER DEFAULT 0") _add(sc, "s_lme_proj", "taxrate", "REAL") # 批次C:税率(源节点采集/弹框可编辑) _add(sc, "s_lme_proj", "x_merged_hide", "INTEGER DEFAULT 0") # 批次C:合并隐藏标记 + # 决策 227(2026-10-27 主人定):本项目内采纳「后采纳的为准」——消耗量行级采纳价锚 + # (除税/含税)。锚=采纳时刻来源侧现显价,浮层显示锚优先;取消/再次采纳随整组删重建。 + _add(sc, "s_norm_res", "x_ntp", "REAL") + _add(sc, "s_norm_res", "x_taxp", "REAL") hc2 = conn() try: _add(hc2, "lme_proj", "taxrate", "REAL") # 批次库 lme_proj 同步(导入采集) @@ -2093,8 +2098,13 @@ def _norm_res(con, T, norm_id): # 公共功能4(2026-10-15):尾位追加税率(下标 9,不动前端既有 0~8 下标)。 # 老库 lmes 可能没有 TaxRate 列 —— 仿 _lme_res 的 PRAGMA 探测:缺列就不 SELECT、恒补 None。 has_tax = any(x[1] == "TaxRate" for x in con.execute("PRAGMA table_info(%s)" % T["lmes"])) + # 决策 227(2026-10-27 主人定):本项目内采纳的消耗量行带**采纳价锚**(x_ntp/x_taxp,采纳时刻 + # 来源侧现显价)——有锚价格用锚(名称/规格等照常走汇总匹配),实现「采纳本项目的以后采纳的为准」; + # 批次库 norm_res 无这两列,PRAGMA 探测缺列=无锚走原链(采纳外部的以本项目为准,不受影响)。 + _anc = [x[1] for x in con.execute("PRAGMA table_info(%s)" % T["norm_res"])] + has_anc = "x_ntp" in _anc and "x_taxp" in _anc rows = con.execute("""SELECT r.res_code, l.Name, l.Specification, l.Unit, l.Kind, - r.qty, l.NoTaxPrice, l.TaxPrice, %(tax)s + r.qty, l.NoTaxPrice, l.TaxPrice, %(tax)s%(anc)s EXISTS(SELECT 1 FROM %(lr)s x WHERE x.%(idc)s= (SELECT %(idc)s FROM %(nm)s nn JOIN %(bl)s b ON b.id=nn.bill_id WHERE nn.id=r.norm_id) @@ -2109,7 +2119,8 @@ def _norm_res(con, T, norm_id): WHERE r.norm_id=? ORDER BY r.id""" % {"nr": T["norm_res"], "lm": T["lmes"], "idc": T["idcol"], "nm": T["norms"], "bl": T["bills"], "lr": T["lme_res"], - "tax": ("l.TaxRate," if has_tax else "")}, + "tax": ("l.TaxRate," if has_tax else ""), + "anc": ("r.x_ntp, r.x_taxp," if has_anc else "")}, (norm_id,)).fetchall() # 定额所属 单位工程id + 批次/会话id(一次查全,供下面三张表定位) _uw = con.execute("""SELECT b.uw_id, b.%(idc)s FROM %(nm)s nn JOIN %(bl)s b ON b.id=nn.bill_id @@ -2149,6 +2160,8 @@ def _norm_res(con, T, norm_id): if _s["ntp"] is not None: ntp = _s["ntp"] if _s["taxp"] is not None: taxp = _s["taxp"] break + if has_anc and r["x_ntp"] is not None: # 决策 227:采纳价锚锁价(覆盖前面链取的价格) + ntp, taxp = r["x_ntp"], (r["x_taxp"] if r["x_taxp"] is not None else taxp) if not name: # 兜底①:项目级资源库 —— 源文件汇总节点上原样带着名称/规格/单位/类别/单价 librow = lib.get(r["res_code"] or "") @@ -2347,8 +2360,7 @@ def _raw_uw(con, T, uwid, tab): # 第 0 位 = 定额 id:前端点定额行要拿它去取工料机(2026-10-01 加) _eval = None if n["qty_expr"]: - _g = _gcl_of(_bq.get(n["bill_id"]), n["Unit"]) - _eval, _msg = _eval_qty_expr(n["qty_expr"], _g) + _eval, _msg = _formula_qty(n["qty_expr"], _bq.get(n["bill_id"]), n["Unit"]) # 决策 216 norms.setdefault(n["bill_id"], []).append( [n["id"], n["Number"], n["Name"], n["Unit"], n["Quantity"], n["Price"], n["Total"], n["x_tdel"], n["x_adopt"], n["qty_expr"], _eval]) @@ -2437,7 +2449,7 @@ def _snap_norms(con, bill_id): if not (n["x_tdel"] or n["x_adopt"] or n["x_src_norm_id"] or n["qty_expr"]): continue # 干净定额:重导自然重建,不 snapshot res = [list(x) for x in con.execute( - "SELECT res_code, qty, express FROM s_norm_res WHERE norm_id=? ORDER BY id", (n["id"],))] + "SELECT res_code, qty, express, x_ntp, x_taxp FROM s_norm_res WHERE norm_id=? ORDER BY id", (n["id"],))] out.append({"Number": n["Number"], "Name": n["Name"], "Unit": n["Unit"], "Quantity": n["Quantity"], "Price": n["Price"], "Total": n["Total"], "x_tdel": n["x_tdel"], "x_adopt": n["x_adopt"], @@ -2486,6 +2498,12 @@ def _bill_state_snapshot(con, sid): lme_proj = [list(r) for r in con.execute( """SELECT code, name, spec, unit, kind, qty, ntp, taxp FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1""", (sid,))] + # 决策 220:③随行带来的子级组成一并快照(采纳新增母行的 s_lme_res),重导后原位补回 + lme_res = [[r[0], r[1], r[2], r[3], r[4]] for r in con.execute( + """SELECT r.p_code, r.res_code, r.qty, r.seq, r.name FROM s_lme_res r + WHERE r.session_id=? AND r.p_code IN + (SELECT code FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1) + ORDER BY r.p_code, r.seq, r.id""", (sid, sid))] lme_hide = [r["code"] for r in con.execute( """SELECT code FROM s_lme_proj WHERE session_id=? AND COALESCE(x_merged_hide,0)=1""", (sid,))] # 合并弹框的价格改值(键=code;code 本身被改的边角不保,登记台账) @@ -2495,7 +2513,7 @@ def _bill_state_snapshot(con, sid): if not src and not news and not lme_uw and not lme_proj and not lme_hide: return None return {"src": src, "news": news, "lme_uw": lme_uw, "lme_proj": lme_proj, - "lme_hide": lme_hide, "lme_vals": lme_vals} + "lme_res": lme_res, "lme_hide": lme_hide, "lme_vals": lme_vals} def _restore_norms(con, bill_id, norms): @@ -2513,19 +2531,22 @@ def _restore_norms(con, bill_id, norms): # 金宝实测:决策 68 快照把重导已聚合的 2.53+3.55 旧对原样复活,绕过导入聚合。 _ra = {} _ro = [] - for code, qty, express in n["res"]: + for r5 in n["res"]: + code, qty, express = r5[0], r5[1], r5[2] + anc = (r5[3], r5[4]) if len(r5) > 4 else (None, None) # 决策 227:老快照无锚列 → (None,None) k = code if k in _ra: - q0, e0 = _ra[k] + q0, e0, a0 = _ra[k] _ra[k] = (((q0 or 0) + (qty or 0)) if (q0 is not None or qty is not None) else None, - e0 or express) + e0 or express, + (a0 if a0[0] is not None else anc) if a0[0] is not None or anc[0] is not None else (None, None)) else: - _ra[k] = (qty, express) + _ra[k] = (qty, express, anc) _ro.append(k) for code in _ro: - qty, express = _ra[code] - con.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)", - (cur.lastrowid, code, qty, express or None)) + qty, express, anc = _ra[code] + con.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp) VALUES(?,?,?,?,?,?)", + (cur.lastrowid, code, qty, express or None, anc[0], anc[1])) def _bill_state_restore(con, sid, snap): @@ -2604,6 +2625,13 @@ def _bill_state_restore(con, sid, snap): qty, ntp, taxp, x_adopt_added) VALUES(?,?,?,?,?,?,?,?,?,1)""", (sid, code, name, spec, unit, kind, qty, ntp, taxp)) n += 1 + # 决策 220:③随行子级组成原位补回(重导后母行在而子级缺 → 按快照重插) + for p, c, q, s2, nm in snap.get("lme_res") or []: + if not con.execute("SELECT 1 FROM s_lme_res WHERE session_id=? AND p_code=? AND res_code=? LIMIT 1", + (sid, p, c)).fetchone(): + con.execute("INSERT INTO s_lme_res(session_id, p_code, res_code, qty, seq, name) VALUES(?,?,?,?,?,?)", + (sid, p, c, q, s2, nm)) + n += 1 # 决策 69:合并隐藏标记原位恢复(重导行存在则打回隐藏;源里真没有就算了) for code in snap.get("lme_hide") or []: con.execute("UPDATE s_lme_proj SET x_merged_hide=1 WHERE session_id=? AND code=? AND COALESCE(x_merged_hide,0)=0", @@ -3131,9 +3159,9 @@ def api_bill_op(sc, body): if not sets: return {"ok": False, "msg": "没有可保存的字段"} cur_row = sc.execute("SELECT * FROM s_bills WHERE id=?", (bid,)).fetchone() + _bill_snap_log(sc, cur_row) # 决策 218 补二:改前快照(时间|工程量|单价|合价),只记清单 vals.append(bid) sc.execute("UPDATE s_bills SET %s WHERE id=?" % ",".join(sets), vals) - _edit_log(sc, _bill_ekbase(sc, cur_row), ef, _BILL_EDIT_FIELDS, cur_row) if "Name" in fields or "Attr" in fields: _bill_rehash(sc, bid) # 补记十六(主人定):改工程量 → 合价 = 工程量×单价(工作台即时同步,导出同口径) @@ -3204,8 +3232,14 @@ def api_norm_op(sc, body): return sc.execute("DELETE FROM %s WHERE %s AND x_adopt_added=1" % (tbl, where), params).rowcount + _drop_cand = [r[0] for r in sc.execute( + "SELECT DISTINCT code FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1", (sid,))] n_uw = _drop_added("s_lme_uw", "session_id=? AND uw_id IS ?", (sid, uw_id), keep_uw) n_proj = _drop_added("s_lme_proj", "session_id=?", (sid,), keep_proj) + # 决策 220:撤下的采纳新增母行若已无项目级行 → ③随行带来的子级组成一并撤(精确按码,不扫全表) + for _c in _drop_cand: + if not sc.execute("SELECT 1 FROM s_lme_proj WHERE session_id=? AND code=? LIMIT 1", (sid, _c)).fetchone(): + sc.execute("DELETE FROM s_lme_res WHERE session_id=? AND p_code=?", (sid, _c)) # 决策 209(2026-10-26 主人定):撤下本条后清单内已无采纳定额 → 原定额恢复(x_tdel=0)。 # 原定额的临删**只有取消采纳才恢复**(清单级 unadopt 同款;定额级=撤最后一条采纳时同口径)。 if not sc.execute("SELECT 1 FROM s_norms WHERE bill_id=? AND x_adopt=1 LIMIT 1", @@ -3220,27 +3254,35 @@ def api_norm_op(sc, body): # 公式定额(采纳挂 GCL,存储量 NULL)不再被聚合链丢掉。此处保留旧名作别名兼容既有调用。 _gcl_of = dyn_lme.gcl_of _eval_qty_expr = dyn_lme.eval_qty_expr +_formula_qty = dyn_lme.formula_qty # 决策 216:公式新口径(GCL=清单原值,结果整体÷单位) +unit_factor = dyn_lme.unit_factor def api_edit_log(one): """字段编辑历史(规格 2026-10-17 ⑮):会话全量,新→旧。 - m = {行id: ekbase}(有历史的现行行);log = [{k: ekbase+':'+字段, at, o, n}]。""" + m = {清单id: ekbase}(决策 225 主人定:编辑历史只在清单——定额键(222 的 n 前缀)退役, + 两表 id 相撞的根因随之消失);log = [{k, at, o, n}]。""" sid = int(one.get("session_id", 0) or 0) if not sid: return {"ok": False, "msg": "缺少 session_id"} sc = sess.connect() try: - m = {} + m = {} # 决策 225:只发清单键;定额编辑自 218 补二起不再写日志,历史定额行不再下发 for b in sc.execute("SELECT * FROM s_bills WHERE session_id=?", (sid,)).fetchall(): - m[str(b["id"])] = _bill_ekbase(sc, b) - for n in sc.execute("SELECT * FROM s_norms WHERE bill_id=? ORDER BY id", (b["id"],)).fetchall(): - m[str(n["id"])] = _norm_ekbase(sc, n) + m["b" + str(b["id"])] = _bill_ekbase(sc, b) bases = set(m.values()) log = [] - for r in sc.execute("SELECT ekbase, f, o, n, at FROM s_edit_log ORDER BY id DESC").fetchall(): + # 决策 218 补二:只下发清单快照行(f=SNAP,o=json{q,p,t});字段级旧行不再下发 + import json as _json + for r in sc.execute("SELECT ekbase, f, o, n, at FROM s_edit_log WHERE f='SNAP' ORDER BY id DESC").fetchall(): if r["ekbase"] in bases: - log.append({"k": r["ekbase"] + ":" + r["f"], "o": r["o"], "n": r["n"], "at": r["at"]}) + try: + s = _json.loads(r["o"] or "{}") + except Exception: + s = {} + log.append({"k": r["ekbase"], "at": r["at"], + "q": s.get("q"), "p": s.get("p"), "t": s.get("t")}) return {"ok": True, "m": m, "log": log} finally: sc.close() @@ -3277,14 +3319,15 @@ def _bill_ekbase(sc, brow): brow["Number"] or "", brow["Name"] or "", brow["Unit"] or "") -def _norm_ekbase(sc, nrow): - """定额的稳定编辑键基:'n:' + 清单键基 + '#' + 编码 + '#' + 同码序号(按 id 序, - 重解析后顺序一致 → 序号一致)。nrow=s_norms 行(含 bill_id/Number)。""" - b = sc.execute("SELECT * FROM s_bills WHERE id=?", (nrow["bill_id"],)).fetchone() - base = _bill_ekbase(sc, b) - occ = sc.execute("SELECT COUNT(*) FROM s_norms WHERE bill_id=? AND Number IS ? AND id<=?", - (nrow["bill_id"], nrow["Number"], nrow["id"])).fetchone()[0] - 1 - return base + "#" + (nrow["Number"] or "") + "#" + str(occ) +def _bill_snap_log(sc, brow): + """清单编辑快照(决策 218 补二,2026-10-26 主人定):清单被编辑/采纳覆盖**前**的三值快照 + (工程量|单价|合价)——编辑历史浮层按 时间|工程量|单价|合价 展示;记的是改前值, + 本次(最新)状态就在格子上看,天然不重复出现。只记清单,定额不再记。""" + import json as _json + o = _json.dumps({"q": brow["Quantity"], "p": brow["Price"], "t": brow["Total"]}, + ensure_ascii=False) + sc.execute("INSERT INTO s_edit_log(ekbase, f, o, n) VALUES(?,?,?,'')", + (_bill_ekbase(sc, brow), "SNAP", o)) def _edit_log(sc, ekbase, fields, cols, row): @@ -3296,16 +3339,15 @@ def _edit_log(sc, ekbase, fields, cols, row): sc.execute("INSERT INTO s_edit_log(ekbase, f, o, n) VALUES(?,?,?,?)", (ekbase, k, "" if o is None else str(o), "" if fields[k] is None else str(fields[k]))) -def _norm_gcl(sc, nid): - """GCL(规格 2026-10-16 工作台·组价不一致清单):定额依附清单的工程量 ÷ 定额单位的 - 从左到右数字前缀(到字母处截断,如 10t→10、100m3天然密实方→100);单位纯字母或 - 无数字(t、m、空)则 GCL=清单工程量。清单工程量空按 0。返回 (gcl, None) / (None, msg)。""" +def _norm_bill_qty(sc, nid): + """定额依附清单的工程量原值(决策 216 新口径:GCL=清单原值,单位因子在公式结果上除)。 + 返回 (清单工程量, None) / (None, msg)。""" n = sc.execute("SELECT bill_id, Unit FROM s_norms WHERE id=?", (nid,)).fetchone() if not n: return None, "定额不存在(可能已被删除,请刷新)" b = sc.execute("SELECT Quantity FROM s_bills WHERE id=?", (n["bill_id"],)).fetchone() bq = float(b["Quantity"]) if b and b["Quantity"] is not None else 0.0 - return _gcl_of(bq, n["Unit"]), None + return bq, None # (_QTY_EXPR_OK / _eval_qty_expr 已收口 dyn_lme.eval_qty_expr,见 _gcl_of 处别名) @@ -3340,10 +3382,10 @@ def api_norm_edit(sc, body): if div <= 0: div = 1.0 if "GCL" in s.upper(): - gcl, msg = _norm_gcl(sc, nid) + bq, msg = _norm_bill_qty(sc, nid) if msg: return {"ok": False, "msg": msg} - q, msg = _eval_qty_expr(s, gcl) + q, msg = _formula_qty(s, bq, cur_row["Unit"]) # 决策 216:GCL=清单原值,结果整体÷单位 if msg: return {"ok": False, "msg": msg} sets.append("Quantity=?") @@ -3365,9 +3407,7 @@ def api_norm_edit(sc, body): return {"ok": False, "msg": "没有可保存的字段"} vals.append(nid) sc.execute("UPDATE s_norms SET %s WHERE id=?" % ",".join(sets), vals) - _edit_log(sc, _norm_ekbase(sc, cur_row), - {k: fields[k] for k in ("Name", "Quantity") if k in fields}, - {"Name": "Name", "Quantity": "Quantity"}, cur_row) + # 决策 218 补二:定额编辑不再记日志(编辑历史只记清单快照) # 补记十六(主人定):改工程量(数字) → 合价 = 工程量×单价(工作台即时同步) if "Quantity" in fields: sc.execute("""UPDATE s_norms SET Total=ROUND(COALESCE(Quantity,0)*COALESCE(Price,0),2) @@ -3490,6 +3530,18 @@ def _adopt_summary_rows(sc, hc, sid, uw_id, src_bill_id): (sid, uw_id, code, lm["Name"], lm["Specification"], lm["Unit"], f_(lm["Kind"]), f_(lm["Quantity"]), f_(lm["NoTaxPrice"]), f_(lm["TaxPrice"]))) n += 1 + # 决策 220(主人定「只有新加入的带子级工料机,本项目完全没有,采纳才会补进来」): + # ③补来源行时连**子级组成**整套带上(来源批次 lme_res → 会话 s_lme_res); + # 本会话该母码已有子级则不覆盖(先采纳的/本项目原的子级为准)。取消采纳回收时随行撤下。 + if not sc.execute("SELECT 1 FROM s_lme_res WHERE session_id=? AND p_code=? LIMIT 1", + (sid, code)).fetchone(): + 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)): + if not r["res_code"]: + 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"])) return n, code_map @@ -3507,18 +3559,29 @@ def _gcl_coef_expr(norm_qty, bill_qty, coef=None, unit=None): 定额量 300 → GCL*0.6000)——采纳到本清单后定额量按比例跟随本清单工程量。 系数**导入时已预存**(norms.x_qty_coef,主人定:导入算好、采纳直接用),优先取用; 老数据缺失时现算兜底。历史清单量缺失/为 0/定额量缺失 → 退回裸 GCL(决策 90 口径)。 - 2026-10-17 决策 106 修正:系数一律 **GCL 口径**(定额量÷历史GCL)。旧口径 - (定额量÷清单量)在定额单位带数字前缀(10m/100m…)时把单位换算双算两遍—— + 决策 216(2026-10-26):采纳系数改为配套新公式口径,coef=定额量×单位因子÷清单原量,取代决策106旧系数口径。此前旧口径 + (定额量÷历史GCL)在新公式口径下系数会少乘单位因子—— GCL 求值已除过一次前缀,前山河 040501004001(10m 定额)导出量少 10 倍实测。 现算兜底同样按 GCL 口径(传入单位)。""" if coef is None: nq, bq = f_(norm_qty), f_(bill_qty) if nq is None or bq in (None, 0): return "GCL" - coef = nq / _gcl_of(bq, unit) + coef = nq * unit_factor(unit) / bq # 决策 216:反推新口径系数(公式结果整体÷单位) return "GCL*%.4f" % coef +def _lme_ntp_of(sc, sid, uw_id, code): + """工料机编码在本会话的现显价(决策 227):先定额所属单位工程汇总、后项目级—— + 与工料机浮层取价链同源。返回 (除税价, 含税价),两级都缺则 (None, None)。""" + r = sc.execute("SELECT ntp, taxp FROM s_lme_uw WHERE uw_id=? AND code=? LIMIT 1", + (uw_id, code)).fetchone() + if not r or (r["ntp"] is None and r["taxp"] is None): + r = sc.execute("SELECT ntp, taxp FROM s_lme_proj WHERE session_id=? AND code=? LIMIT 1", + (sid, code)).fetchone() + return (r["ntp"], r["taxp"]) if r else (None, None) + + def api_bill_adopt(sc, hc, body): """采纳(数据落地)。body={session_id, bill_id, src_bill_id} 9.1 新增清单(x_new=1):清单字段照入库项目覆盖、工程量0;定额整组替换(工程量=GCL公式/单价照带/合价0), @@ -3543,7 +3606,7 @@ def api_bill_adopt(sc, hc, body): if src_self: if src_self == bid: return {"ok": False, "msg": "不能采纳清单自己"} - bb = sc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity FROM s_bills WHERE id=? AND session_id=?", + bb = sc.execute("SELECT id, Number, Name, Attr, Unit, Price, Quantity, uw_id FROM s_bills WHERE id=? AND session_id=?", (src_self, sid)).fetchone() if not bb: return {"ok": False, "msg": "本工程来源清单不存在(可能已被删除,请刷新)"} @@ -3559,9 +3622,15 @@ def api_bill_adopt(sc, hc, body): FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall() def _norm_expr(nn): - # 批次来源:GCL×系数公式现算(规格 19);会话来源:qty_expr 原样带(公式本就按 GCL 走, - # 换到目标清单后随目标工程量求值,语义同款) - return nn["qty_expr"] if src_self else _gcl_coef_expr(nn["Quantity"], bb["Quantity"], nn["x_qty_coef"], nn["Unit"]) + # 决策 217(2026-10-26 主人定):采纳定额公式**四入口统一为分部分项同款 GCL×系数**—— + # 分部分项/措施项目/类似清单/组价不一致(含范围=是 的本工程源)都是同一 api_bill_adopt。 + # 会话源定额自带 GCL 公式的原样带(语义同款);数字定额按 决策216 新口径现算系数 + # (定额量×单位因子÷源清单原量,_gcl_coef_expr coef=None 现算),源清单量缺失退裸 GCL。 + # 此前 self 分支数字定额不带公式且 Quantity 置空 → 采纳后量与公式双空(组价不一致实测)。 + if src_self and nn["qty_expr"]: + return nn["qty_expr"] + return _gcl_coef_expr(nn["Quantity"], bb["Quantity"], + None if src_self else nn["x_qty_coef"], nn["Unit"]) def _norm_res(nn_id): if src_self: @@ -3573,6 +3642,8 @@ def api_bill_adopt(sc, hc, body): # 系数 = 历史定额量 ÷ 历史清单量(例:历史清单量 500、定额量 300 → GCL*0.6000)—— # 换本清单工程量后定额量按比例走。历史清单量缺失/为 0 / 定额量缺失 → 退回裸 GCL。 new_price = bb["Price"] + _pre = sc.execute("SELECT * FROM s_bills WHERE id=?", (bid,)).fetchone() + _bill_snap_log(sc, _pre) # 决策 218 补二:采纳覆盖前快照(sb 窄查没带量价,重查整行) src_qty = f_(bb["Quantity"]) if is_new: # 9.1 整体覆盖 @@ -3590,8 +3661,12 @@ def api_bill_adopt(sc, hc, body): None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"])) adopted_norm_ids.append(cur.lastrowid) for rr in _norm_res(nn["id"]): - sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)", - (cur.lastrowid, rr["res_code"], rr["qty"], rr["express"])) + # 决策 227(主人定):采纳本项目的「后采纳的为准」——消耗量行落来源侧现显价锚; + # 采纳外部的以本项目为准(9.4 本地匹配),不落锚走原链。合并工料机只动汇总现值, + # 不碰行级锚——上下游各自生效不冲突(主人 2026-10-27 拍板)。 + a = _lme_ntp_of(sc, sid, bb["uw_id"], rr["res_code"]) if src_self else (None, None) + sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp) VALUES(?,?,?,?,?,?)", + (cur.lastrowid, rr["res_code"], rr["qty"], rr["express"], a[0], a[1])) else: # 9.3 定额追加 + 原定额转临删 + 清单单价按采纳价覆盖 adopted_norm_ids = [] @@ -3606,8 +3681,12 @@ def api_bill_adopt(sc, hc, body): None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"])) adopted_norm_ids.append(cur.lastrowid) for rr in _norm_res(nn["id"]): - sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express) VALUES(?,?,?,?)", - (cur.lastrowid, rr["res_code"], rr["qty"], rr["express"])) + # 决策 227(主人定):采纳本项目的「后采纳的为准」——消耗量行落来源侧现显价锚; + # 采纳外部的以本项目为准(9.4 本地匹配),不落锚走原链。合并工料机只动汇总现值, + # 不碰行级锚——上下游各自生效不冲突(主人 2026-10-27 拍板)。 + a = _lme_ntp_of(sc, sid, bb["uw_id"], rr["res_code"]) if src_self else (None, None) + sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp) VALUES(?,?,?,?,?,?)", + (cur.lastrowid, rr["res_code"], rr["qty"], rr["express"], a[0], a[1])) bqty = sc.execute("SELECT Quantity FROM s_bills WHERE id=?", (bid,)).fetchone()["Quantity"] btotal = round((float(bqty) if bqty is not None else 0.0) * (float(new_price) if new_price is not None else 0.0), 2) sc.execute("UPDATE s_bills SET Price=?, Total=?, x_adopt=1 WHERE id=?", (new_price, btotal, bid)) @@ -3624,7 +3703,13 @@ 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 - return {"ok": True, "sid": sid, "n_norm": len(bnorms), "n_sum": n_sum, "n_recode": n_recode, + _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)) + # 决策 217/219:旧价锚=第一次导进来单价(x_price0);老会话列空退**改前**当前价—— + # 此前在 UPDATE 之后读,第二次采纳起锚跟着上次采纳价漂(实测报障),改前抓取修复。 + return {"ok": True, "sid": sid, "price0": _price0, + "n_norm": len(bnorms), "n_sum": n_sum, "n_recode": n_recode, "mode": "覆盖" if is_new else "追加", "price": new_price} @@ -3717,15 +3802,15 @@ def _export_session(sc, sid, progress=None): # 临删仍走 transform_unit 的原位省略,保住与文件的对位关系) (entry["append"] if nb["x_adopt"] else entry["source"]).append(dict(nb)) # 决策 90(2026-10-17):工程量公式(GCL/数字四则)→ 按**当时**清单量求值 - # (GCL=清单工程量÷定额单位数字前缀,_gcl_of 同款算法)。合价=求值量×单价(金额2位)。 + # (决策 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"): - gcl = _gcl_of(bill_qtys.get(nb["bill_id"]), nb["Unit"]) - q, _msg = _eval_qty_expr(nb["qty_expr"], gcl) + 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) @@ -4385,6 +4470,13 @@ def api_lme_merge(sc, body): _merged_codes_add(sc, sid, keep_code) sc.execute(("UPDATE s_lme_uw SET ntp=?, taxrate=?, taxp=?%s WHERE session_id=? AND code=?") % _xs, keep_px + tuple(_xa) + (sid, keep_code)) + if keep_code and keep_px: + # 决策 219:合并保留下来的行——采纳旧价锚=**合并后的首次三价**(主人定) + try: + sc.execute("UPDATE s_lme_proj SET x_ntp0=?, x_rate0=?, x_taxp0=? WHERE session_id=? AND code=?", + tuple(keep_px) + (sid, keep_code)) + except Exception: + pass if not keep_code: continue # 决策 186 补(2026-10-24 主人提醒「项目级不是不在弹框显示了吗」定位的盲区): @@ -4898,8 +4990,15 @@ def api_lme_price(sc, body): (ntp, rate, taxp, sid, row["code"])) _merged_codes_add(sc, sid, row["code"]) dyn_lme.mark_manual_price(sc, sid, row["code"]) # 决策 191:手工改价标记(重放跳过,假库失败不挡) + try: # 决策 219:采纳锚(第一次计算/合并后首次三价;老库列缺/空=None→前端退改前现值) + _a = sc.execute("SELECT x_ntp0, x_rate0, x_taxp0 FROM s_lme_proj WHERE session_id=? AND id=?", + (sid, rid)).fetchone() + except Exception: + _a = None return {"ok": True, "sid": sid, "id": rid, "code": row["code"], - "ntp": ntp, "taxrate": rate, "taxp": taxp, "synced": cur.rowcount} + "ntp": ntp, "taxrate": rate, "taxp": taxp, "synced": cur.rowcount, + "ntp0": (_a["x_ntp0"] if _a else None), "rate0": (_a["x_rate0"] if _a else None), + "taxp0": (_a["x_taxp0"] if _a else None)} def api_lme_field(sc, body): @@ -4964,8 +5063,14 @@ def api_bill_unadopt(sc, hc, body): sc.execute("DELETE FROM s_norm_res WHERE norm_id IN (SELECT id FROM s_norms WHERE bill_id=? AND x_adopt=1)", (bid,)) sc.execute("DELETE FROM s_norms WHERE bill_id=? AND x_adopt=1", (bid,)) sc.execute("UPDATE s_norms SET x_tdel=0 WHERE bill_id=?", (bid,)) + # 决策 220:③随行带来的子级组成——先记候选,撤行后已无项目级行的码连子级一并撤 + _drop_cand = [r[0] for r in sc.execute( + "SELECT DISTINCT code FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1", (sid,))] sc.execute("DELETE FROM s_lme_uw WHERE session_id=? AND uw_id=? AND x_adopt_added=1", (sid, sb["uw_id"])) sc.execute("DELETE FROM s_lme_proj WHERE session_id=? AND x_adopt_added=1", (sid,)) + for _c in _drop_cand: + if not sc.execute("SELECT 1 FROM s_lme_proj WHERE session_id=? AND code=? LIMIT 1", (sid, _c)).fetchone(): + sc.execute("DELETE FROM s_lme_res WHERE session_id=? AND p_code=?", (sid, _c)) if sb["x_new"]: sc.execute("""UPDATE s_bills SET Number=NULL, Name=NULL, Attr=NULL, Unit=NULL, Quantity=0, Price=NULL, Total=0, x_adopt=0 WHERE id=?""", (bid,)) @@ -5267,7 +5372,8 @@ def api_self_search(body): 排除自己,现行规则)。关键字「查询」路径同样跟随下拉。 type='bill':本工程其他清单(跨单位工程同名/近似;scope='self_group'=组价不一致:会话内 本组其他清单——规格 20 的组定义直读会话,不再绕批次库);type='lme':本工程自己的工料机 - (s_lmes 各单位明细行)。 + (决策 219:走 dyn_lme 现算链——单位级取价/项目级归并,与项目工料机页同码同值同并集; + 此前读 s_lmes 明细快照,与主表两价不一致是「检索出来不是本项目价」报障的根源)。 行结构与 /api/search 一致(renderHist/右栏/±/采纳零改动复用),差异: · src='本工程'、proj=单位工程名(工料机行无单位归属,恒『本工程』)、period=本工程基准期次; · 清单行带 norms=6+2 列(同 _bill_norms 形状,右栏/±/悬停直读,不走 histNorms); @@ -5376,35 +5482,37 @@ def api_self_search(body): setk = match.lme_setkey(row["name"], row["spec"], row["unit"]) if row is not None else None qn = match.norm_match(row["name"]) if row is not None else None pre = match.norm(row["name"])[:6] if row is not None else None - for l in sc.execute("SELECT * FROM s_lmes WHERE session_id=? ORDER BY id", (sid,)).fetchall(): + # 决策 219:候选=项目工料机同一现算链(dyn_lme)——检索行就是主表行 + for d in (dyn_lme.dyn_rows(sc, sid, None) or []): + _lid, _code, nm, sp, un, _q, ntp, rate, taxp, _kd, _rm = d # 决策 211(2026-10-26 主人定):本项目范围工料机 0 价不出(NULL 保留) - if l["NoTaxPrice"] is not None and float(l["NoTaxPrice"] or 0) == 0: + if ntp is not None and float(ntp or 0) == 0: continue if row is None: rows.append({ - "tier": "检索", "name": l["Name"], "attr": "", "spec": l["Specification"], - "unit": l["Unit"], "price": l["NoTaxPrice"], "tax": l["TaxRate"], - "price_tax": l["TaxPrice"], "note": "", "period": period, "period_m": pf, + "tier": "检索", "name": nm, "attr": "", "spec": sp, + "unit": un, "price": ntp, "tax": rate, + "price_tax": taxp, "note": "", "period": period, "period_m": pf, "dist": 0, "sim": None, "src": "本工程", "proj": "本工程", "bunit": bunit, "region": region, "file": "", "file_url": ""}) continue tier, sim = None, None - j = match.jaccard(qn, match.norm_match(l["Name"])) - if l["x_hash_exact"] and l["x_hash_exact"] == h_e: + j = match.jaccard(qn, match.norm_match(nm)) + if h_e and job.md5(nm, sp, un) == h_e: tier, sim = "精确", 1.0 - elif l["x_hash_semi"] and l["x_hash_semi"] == h_s: + elif h_s and job.md5(nm, un) == h_s: tier, sim = "次精确", 1.0 - elif match.lme_setkey(l["Name"], l["Specification"], l["Unit"]) == setk: + elif match.lme_setkey(nm, sp, un) == setk: tier, sim = "字集", 1.0 - elif pre and match.norm(l["Name"]).startswith(pre) and match.norm(l["Unit"]) == match.norm(row["unit"]): + elif pre and match.norm(nm).startswith(pre) and match.norm(un) == match.norm(row["unit"]): if j >= match.SIM_MIN: tier, sim = "模糊", round(j, 2) if tier is None: continue rows.append({ - "tier": tier, "name": l["Name"], "attr": "", "spec": l["Specification"], - "unit": l["Unit"], "price": l["NoTaxPrice"], "tax": l["TaxRate"], - "price_tax": l["TaxPrice"], "note": "", "period": period, "period_m": pf, + "tier": tier, "name": nm, "attr": "", "spec": sp, + "unit": un, "price": ntp, "tax": rate, + "price_tax": taxp, "note": "", "period": period, "period_m": pf, "dist": 0, "sim": sim, "src": "本工程", "proj": "本工程", "bunit": bunit, "region": region, "file": "", "file_url": ""}) rows = [r for r in rows @@ -6296,7 +6404,7 @@ def _repair_session_exprs(): (n["bill_id"],)).fetchone() if n["Quantity"] is None or not bq or bq["Quantity"] in (None, 0): continue - coef = n["Quantity"] / _gcl_of(bq["Quantity"], n["Unit"]) + coef = n["Quantity"] * unit_factor(n["Unit"]) / bq["Quantity"] # 决策 216:反推新口径系数 fixes.append(("GCL*%.4f" % coef, r["id"])) if fixes: sc.executemany("UPDATE s_norms SET qty_expr=? WHERE id=?", fixes) @@ -7054,8 +7162,7 @@ def _bill_norms(con, T, bill_id): bq = bq_row["Quantity"] if bq_row else None for r in out: if r[9]: - gcl = _gcl_of(bq, r[2]) - q, _msg = _eval_qty_expr(r[9], gcl) + q, _msg = _formula_qty(r[9], bq, r[2]) # 决策 216 r.append(q) # 公式行:r[10]=当前清单量下的求值数字 else: r.append(None) @@ -7409,12 +7516,17 @@ class Handler(SimpleHTTPRequestHandler): _g = license_gate.intercept("GET", p) # 授权门禁:未激活/过期只放授权页与 /api/license/* if _g is not None: return self._gate_send(_g) + _v = vgate.intercept("GET", p) # 强制更新门禁:低于最低版本只回强制更新页 + if _v is not None: + return self._gate_send(_v) one = {k: v[0] for k, v in q.items()} try: if p == "/api/sessions": # 最近审核(会话台账,按源文件去重) return self._json(api_sessions()) if p == "/api/schema": # Agent 接入(2026-10-15):能力自描述 return self._json(api_schema()) + if p == "/api/version_info": # 强制更新状态(2026-10-27):当前/最新/最低要求 + return self._json(vgate.status()) if p == "/api/version": # 程序版本(代码时间/启动时间)——启动器 import time as _t # 靠它判断端口上的实例是不是旧代码 return self._json({"ok": True, "port": PORT, @@ -7649,6 +7761,9 @@ class Handler(SimpleHTTPRequestHandler): _g = license_gate.intercept("POST", u.path, body) # 授权门禁(/api/license/activate 在此放行) if _g is not None: return self._gate_send(_g) + _v = vgate.intercept("POST", u.path) # 强制更新门禁:API 回 403,绝不回 HTML + if _v is not None: + return self._gate_send(_v) try: if u.path == "/api/admin/batch/upgrade": # 方案 A′:后台打开明细 = 看一次升一次 with WRITE_LOCK: @@ -8083,6 +8198,7 @@ def run(): except Exception as e: print("[启动自愈] 采纳迁移出错(不影响启动):%s" % e) license_gate.init(DATA_DIR) # 授权门禁:读配置/状态,配了凭据则起心跳线程(内部吞异常) + vgate.init(DATA_DIR) # 强制更新门禁:读烧入版本与缓存(开发态无 BUILD 自动旁路) # 2026-10-20 决策 126:过期会话清理/去重/孤儿清理/附件回收等**纯清理**步骤已挪到 # bind 之后的后台线程 _startup_selfheal_bg(幂等,晚几秒做不影响正确性)。 # 2026-10-11:启动「数据过期」打印已取消(主人定)——打开即自动升级(决策 34)后「需重导」口径不再成立; diff --git a/CostReview/app/server/license_client/client.py b/CostReview/app/server/license_client/client.py index 251b2b4..b6804c8 100644 --- a/CostReview/app/server/license_client/client.py +++ b/CostReview/app/server/license_client/client.py @@ -23,7 +23,7 @@ from datetime import timedelta try: from .verify import (VerifyError, verify_certificate, verify_lease, - parse_rfc3339, rfc3339) + parse_rfc3339, rfc3339, entitlements) from .store import StorageError except ImportError as _e: # 只对"相对导入不可用"退裸导入;包内真实依赖缺失(如 cryptography)必须原样抛出, @@ -31,7 +31,7 @@ except ImportError as _e: if "attempted relative import" not in str(_e): raise from verify import (VerifyError, verify_certificate, verify_lease, - parse_rfc3339, rfc3339) + parse_rfc3339, rfc3339, entitlements) from store import StorageError DEFAULT_API_BASE = "https://license.yihuiyong.cn" @@ -333,6 +333,7 @@ class LicenseClient: return out lease = st.get("lease") or {} cert = st.get("certificate") or {} + ent = entitlements(cert) if cert else {"edition": None, "max_seats": None} ok, reason = self.can_run_safe() days_left = None try: @@ -348,6 +349,8 @@ class LicenseClient: "license_id": cert.get("license_id"), "product_id": cert.get("product_id"), "expected_product_id": self.expected_product_id, + "edition": ent["edition"], # 商业版权益(未激活为 None;证书缺省=personal) + "max_seats": ent["max_seats"], "days_left": days_left, "starts_at": cert.get("starts_at"), "entitlement_expires_at": cert.get("expires_at") or lease.get("entitlement_expires_at"), diff --git a/CostReview/app/server/license_client/gate.py b/CostReview/app/server/license_client/gate.py index 200bcc2..98b1d14 100644 --- a/CostReview/app/server/license_client/gate.py +++ b/CostReview/app/server/license_client/gate.py @@ -12,6 +12,7 @@ pinned_keys.json + 已存授权状态;配置了凭据且信任根就绪则起 本地开发豁免:data/license/config.json 写 "enforce": false(交付/发布环境 不带该文件或 enforce=true,代码默认 true)。 """ +import hashlib import json import os import threading @@ -32,6 +33,34 @@ _cfg = {"enforce": True, "api_base": DEFAULT_API_BASE, "selfheal_seconds": 300} _hb_thread = None _hb_stop = None _last_selfheal = 0.0 # monotonic:门禁自愈触发节流 +_INTEGRITY_FAIL = "" # N1 源码保护(2026-10-27):非空 = 交付包文件被改,全线拦截 + + +def _check_build_integrity(): + """N1 源码保护:交付包启动时校验 .py 哈希清单(build 期烧入 BUILD.INTEGRITY, + 覆盖 server/core 全部 .py)。被改 = fail closed 全线拦截(含授权口——防的是 + 「改掉本文件/门禁调用后再激活」的绕过路径)。开发版(BUILD=None)不校验。 + INTEGRITY 键相对 app 根(server/...、core/...、shell.py)。""" + global _INTEGRITY_FAIL + if BUILD is None: + return + manifest = getattr(BUILD, "INTEGRITY", None) + if not isinstance(manifest, dict) or not manifest: + return + app_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + for rel, want in sorted(manifest.items()): + p = os.path.join(app_root, rel.replace("/", os.sep)) + try: + with open(p, "rb") as f: + got = hashlib.sha256(f.read()).hexdigest() + except OSError: + _INTEGRITY_FAIL = rel + "(缺失)" + print("⚠ 完整性校验失败:%s" % _INTEGRITY_FAIL) + return + if got != str(want).lower(): + _INTEGRITY_FAIL = rel + print("⚠ 完整性校验失败:%s 哈希不符(文件被改动?)" % rel) + return # ---------------------------------------------------------------- 初始化 @@ -73,6 +102,7 @@ def init(data_dir): expected_product = None selfheal = 300 if BUILD is not None: + _check_build_integrity() # N1:烧入清单校验,被改 → 全线拦截 _cfg = {"enforce": bool(BUILD.ENFORCE), "api_base": str(BUILD.API_BASE).rstrip("/"), "selfheal_seconds": getattr(BUILD, "SELFHEAL_SECONDS", 300)} @@ -167,6 +197,12 @@ def heartbeat_running(): def intercept(method, path, body=None): """None = 放行;否则返回 {"kind":"json"|"html","code":int,...} 由 Handler 发送。""" + if _INTEGRITY_FAIL: # N1:文件被改 = 无任何放行(含授权口) + if method == "GET" and not path.startswith("/api/"): + return {"kind": "html", "code": 200, "text": _integrity_page()} + return {"kind": "json", "code": 403, + "obj": {"error": {"code": "INTEGRITY_FAILED", + "message": "软件文件完整性校验失败,请重新安装或联系软件提供方"}}} if path.startswith("/api/license/"): return _license_api(method, path, body) if not _cfg.get("enforce", True): @@ -194,6 +230,23 @@ def can_run_now(): return c.can_run_safe() +def _integrity_page(): + """N1 完整性拦截页(自包含):文件被改时的唯一可见页面。""" + return """ +软件文件校验失败 +
+

⚠ 软件文件完整性校验失败

+

检测到程序文件被改动,为保障授权与数据安全,软件已停止服务。

+

请重新安装官方软件包,或联系软件提供方处理。您的数据不受影响。

+
涉及文件见服务日志「完整性校验失败」行。
+
""" + + def _blocked(reason): return {"kind": "json", "code": 403, "obj": {"error": {"code": "LICENSE_REQUIRED", "message": reason}}} @@ -406,7 +459,8 @@ button:disabled{opacity:.5;cursor:default}
本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。 -激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。
+激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。 +授权到期或被冻结时会停在本页(到期即锁):联系软件提供方续费/解冻并重新激活即可恢复使用,本机数据不受任何影响。