feat: 落实决策216/219/227取价锚点与公式口径,增加商业版权益和源码完整性校验
This commit is contained in:
@@ -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)后「需重导」口径不再成立;
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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 """<!DOCTYPE html>
|
||||
<html lang="zh"><head><meta charset="utf-8"><title>软件文件校验失败</title>
|
||||
<style>body{font-family:"Microsoft YaHei",sans-serif;background:#f0f2f5;display:flex;
|
||||
align-items:center;justify-content:center;min-height:100vh;margin:0}
|
||||
.c{background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);
|
||||
max-width:520px;padding:32px 36px}h1{font-size:19px;color:#b02a2a;margin:0 0 12px}
|
||||
p{color:#33475b;line-height:1.8;font-size:14px;margin:8px 0}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:16px}</style></head><body><div class="c">
|
||||
<h1>⚠ 软件文件完整性校验失败</h1>
|
||||
<p>检测到程序文件被改动,为保障授权与数据安全,软件已停止服务。</p>
|
||||
<p>请重新安装官方软件包,或联系软件提供方处理。您的数据不受影响。</p>
|
||||
<div class="k">涉及文件见服务日志「完整性校验失败」行。</div>
|
||||
</div></body></html>"""
|
||||
|
||||
|
||||
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}
|
||||
<div class="st" id="impPv" style="display:none;margin-top:12px;margin-bottom:0"></div>
|
||||
<div class="msg" id="msg"></div>
|
||||
<div class="tip">本页面由本机服务(127.0.0.1)提供;激活凭据只保存在本机,不会上传到别处。
|
||||
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。</div>
|
||||
激活成功后页面会自动进入系统。若长时间显示网络错误,请检查本机能否访问授权服务器。
|
||||
授权到期或被冻结时会停在本页(到期即锁):联系软件提供方续费/解冻并重新激活即可恢复使用,本机数据不受任何影响。</div>
|
||||
</div></div>
|
||||
<script>
|
||||
var TIMER=null;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
- canonical_sha256 是规范化字节的 SHA-256 十六进制,仅辅助校验,不能代替公钥验签。
|
||||
- 拒绝:未知版本、缺字段/多字段、非法类型、含 CR/LF/NUL 的字段、未知或已撤销
|
||||
key_id、非 P-256 公钥、绑定到其他实例的信封、legacy v1。
|
||||
(证书例外:OPTIONAL_CERT_FIELDS 两个可选权益字段可缺省,见下方注释。)
|
||||
|
||||
信任根:只信随软件/受控渠道固定分发的公钥(pinned_keys.json),绝不在线发现。
|
||||
"""
|
||||
@@ -33,6 +34,20 @@ FIELDSETS = {
|
||||
LEASE_V2: ("version", "instance_id", "state", "server_time",
|
||||
"entitlement_expires_at", "lease_expires_at", "key_id"),
|
||||
}
|
||||
|
||||
# 商业版权益字段(2026-10-27,《企业和个人版.md》5.1):仅证书载荷**可选**携带;
|
||||
# 出现 → 纳入 canonical(按本元组顺序追加在必填之后)并校验取值;
|
||||
# 缺省 → edition=personal、max_seats=1(fail-closed 不放大权益;平台未升级协议仍能签发)。
|
||||
OPTIONAL_CERT_FIELDS = ("edition", "max_seats")
|
||||
EDITIONS = ("personal", "enterprise", "trial")
|
||||
|
||||
|
||||
def entitlements(cert):
|
||||
"""从证书载荷取商业版权益(规范化缺省)。门禁与状态视图共用唯一口径。"""
|
||||
if not isinstance(cert, dict):
|
||||
return {"edition": "personal", "max_seats": 1}
|
||||
return {"edition": cert.get("edition") or "personal",
|
||||
"max_seats": cert.get("max_seats") or 1}
|
||||
UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
re.IGNORECASE)
|
||||
RFC3339_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
|
||||
@@ -145,6 +160,12 @@ def canonical_bytes(payload, version):
|
||||
if name not in payload:
|
||||
raise VerifyError("payload 缺字段 %s" % name)
|
||||
out.append("%s=%s" % (name, _field_value(payload, name)))
|
||||
if version == LICENSE_V2:
|
||||
# 可选权益字段:签发方带了才进 canonical(顺序固定);取值合法性由 _check_payload 管
|
||||
for name in OPTIONAL_CERT_FIELDS:
|
||||
if name in payload:
|
||||
v = payload[name]
|
||||
out.append("%s=%s" % (name, str(v) if isinstance(v, int) else v))
|
||||
return "\n".join(out).encode("utf-8")
|
||||
|
||||
|
||||
@@ -153,7 +174,20 @@ def canonical_bytes(payload, version):
|
||||
def _check_payload(payload, version, expected_instance):
|
||||
if not isinstance(payload, dict):
|
||||
raise VerifyError("payload 不是对象")
|
||||
if set(payload.keys()) != set(FIELDSETS[version]):
|
||||
keys = set(payload.keys())
|
||||
required = set(FIELDSETS[version])
|
||||
if version == LICENSE_V2:
|
||||
# 必填全在;多出的键只能是可选权益字段(edition/max_seats),其余多字段仍拒
|
||||
if (keys - required) - set(OPTIONAL_CERT_FIELDS) or required - keys:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
ed = payload.get("edition")
|
||||
if ed is not None and (not isinstance(ed, str) or ed not in EDITIONS
|
||||
or any(c in ed for c in ("\r", "\n", "\x00"))):
|
||||
raise VerifyError("edition 取值非法")
|
||||
ms = payload.get("max_seats")
|
||||
if ms is not None and (isinstance(ms, bool) or not isinstance(ms, int) or ms < 1):
|
||||
raise VerifyError("max_seats 必须是正整数")
|
||||
elif keys != required:
|
||||
raise VerifyError("payload 字段集不符(缺/多字段)")
|
||||
if payload["version"] != version:
|
||||
raise VerifyError("payload.version=%r 不是 %s" % (payload["version"], version))
|
||||
|
||||
226
CostReview/app/server/version_gate.py
Normal file
226
CostReview/app/server/version_gate.py
Normal file
@@ -0,0 +1,226 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""强制更新门禁 version_gate(2026-10-27,《企业和个人版.md》5.9,主人拍板)。
|
||||
|
||||
- 版本信息文件:软件商统一服务器静态 JSON
|
||||
{latest_version, min_required_version, release_notes, package_url, sha256}
|
||||
(URL 出包烧入 BUILD.VERSION_INFO_URL;开发态无 BUILD → 一律旁路,不拉取不拦截)。
|
||||
- 拉取:启动 + 后台低频线程(默认 30 分钟),成功后原子落盘 data/version_cache.json
|
||||
(首装包可预置一份快照,由 build_portable 负责;拉取失败静默沿用旧缓存)。
|
||||
- 判定(纯本地,只读缓存):当前 APP_VERSION < min_required_version → 全员阻断
|
||||
(页面回自包含强制更新页;API 回 403 UPDATE_REQUIRED,绝不回 HTML 给 API——
|
||||
同授权门禁纪律);否则放行,仅版本卡提示有新版。
|
||||
- fail 原则:版本检查不得比授权更硬——从未拉到且无快照 = 不拦;
|
||||
min_required_version 解析失败 = 不拦(视为 0);断网用最近缓存判定
|
||||
(与租约 7 天口径天然对齐:长期断网本来就会被授权先拦住)。
|
||||
- 升级 = 换包(B/S 只更服务器):新版 APP_VERSION ≥ min_required 自动解除拦截。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import license_build_config as BUILD # 出包生成;开发态不存在
|
||||
except Exception:
|
||||
try:
|
||||
import license_build_config as BUILD # 裸跑(server/ 直挂 sys.path)时
|
||||
except Exception:
|
||||
BUILD = None
|
||||
|
||||
CACHE_NAME = "version_cache.json"
|
||||
ALWAYS_PREFIX = ("/api/license/", "/api/version") # 授权三口 + 版本状态口:永不拦
|
||||
DEFAULT_INTERVAL = 30 * 60 # 后台拉取间隔(秒)
|
||||
FETCH_TIMEOUT = 10.0
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache = None # 最近一次成功拉取的信息(含 fetched_at)
|
||||
_cfg = {"app_version": None, "info_url": None, "interval": DEFAULT_INTERVAL,
|
||||
"data_dir": None}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 版本比较
|
||||
|
||||
def vkey(s):
|
||||
"""'1.2.10' → (1, 2, 10);解析失败 → ()(配合调用方 fail-open,不当硬门禁)。"""
|
||||
try:
|
||||
return tuple(int(x) for x in str(s).strip().lstrip("vV").split("."))
|
||||
except Exception:
|
||||
return ()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 初始化/缓存
|
||||
|
||||
def init(data_dir, build=None, start_thread=True):
|
||||
"""run() 启动时调用。build 不传 = 读出包烧入的 license_build_config。"""
|
||||
b = build if build is not None else BUILD
|
||||
_cfg["data_dir"] = data_dir
|
||||
_cfg["app_version"] = str(getattr(b, "APP_VERSION", "") or "").strip() if b else None
|
||||
_cfg["info_url"] = str(getattr(b, "VERSION_INFO_URL", "") or "").strip() if b else None
|
||||
try:
|
||||
_cfg["interval"] = int(getattr(b, "VERSION_CHECK_INTERVAL", DEFAULT_INTERVAL)
|
||||
or DEFAULT_INTERVAL) if b else DEFAULT_INTERVAL
|
||||
except Exception:
|
||||
_cfg["interval"] = DEFAULT_INTERVAL
|
||||
load_cache()
|
||||
if start_thread and effective() and _cfg["info_url"]:
|
||||
threading.Thread(target=_loop, name="version-gate", daemon=True).start()
|
||||
|
||||
|
||||
def effective():
|
||||
"""开发态(无 BUILD / APP_VERSION 空 / 'dev')旁路:不拦截。"""
|
||||
v = _cfg.get("app_version")
|
||||
return bool(v) and v not in ("dev", "0.0.0")
|
||||
|
||||
|
||||
def _cache_path():
|
||||
dd = _cfg.get("data_dir")
|
||||
return os.path.join(dd, CACHE_NAME) if dd else None
|
||||
|
||||
|
||||
def load_cache():
|
||||
global _cache
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return None
|
||||
try:
|
||||
with open(fp, "r", encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
if isinstance(d, dict):
|
||||
_cache = d
|
||||
return d
|
||||
except Exception:
|
||||
pass # 快照损坏 = 当没有(fail-open)
|
||||
return None
|
||||
|
||||
|
||||
def _save_cache(info):
|
||||
global _cache
|
||||
_cache = info
|
||||
fp = _cache_path()
|
||||
if not fp:
|
||||
return
|
||||
tmp = fp + ".tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, ensure_ascii=False, indent=1)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, fp) # 原子写:中断不留半个文件
|
||||
except Exception:
|
||||
pass # 写盘失败不致命:内存缓存仍在
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 拉取
|
||||
|
||||
def fetch_once(http_get=None):
|
||||
"""拉一次版本信息文件。成功 → 落缓存返回 True;失败静默返回 False(用旧缓存)。"""
|
||||
url = _cfg.get("info_url")
|
||||
if not url:
|
||||
return False
|
||||
try:
|
||||
get = http_get or _http_get
|
||||
d = get(url)
|
||||
if not isinstance(d, dict):
|
||||
return False
|
||||
if not isinstance(d.get("latest_version"), str) or \
|
||||
not isinstance(d.get("min_required_version"), str):
|
||||
return False
|
||||
keep = {k: d.get(k) for k in ("latest_version", "min_required_version",
|
||||
"release_notes", "package_url", "sha256")}
|
||||
keep["fetched_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
with _lock:
|
||||
_save_cache(keep)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _http_get(url):
|
||||
import httpx # 决策 30 已入包依赖
|
||||
r = httpx.get(url, timeout=FETCH_TIMEOUT,
|
||||
headers={"User-Agent": "costreview-versiongate/1"})
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def _loop():
|
||||
fetch_once()
|
||||
while True:
|
||||
time.sleep(max(300, _cfg.get("interval") or DEFAULT_INTERVAL))
|
||||
fetch_once()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 判定/拦截
|
||||
|
||||
def check():
|
||||
"""(ok, info)。ok=False = 低于最低要求版本。"""
|
||||
if not effective():
|
||||
return True, {"bypass": "dev"}
|
||||
c = _cache or load_cache() or {}
|
||||
cur = vkey(_cfg.get("app_version"))
|
||||
req = vkey(c.get("min_required_version"))
|
||||
info = {"current": _cfg.get("app_version"),
|
||||
"latest": c.get("latest_version") or "",
|
||||
"min_required": c.get("min_required_version") or "",
|
||||
"notes": c.get("release_notes") or "",
|
||||
"package_url": c.get("package_url") or "",
|
||||
"last_check": c.get("fetched_at") or ""}
|
||||
if not cur or not req: # 无缓存/解析失败:不拦(fail-open)
|
||||
return True, info
|
||||
return (cur >= req), info
|
||||
|
||||
|
||||
def intercept(method, path):
|
||||
"""仿 license_client.gate.intercept:None=放行;dict=拦截(html 强制页 / json 403)。"""
|
||||
if not effective():
|
||||
return None
|
||||
ok, info = check()
|
||||
if ok:
|
||||
return None
|
||||
p = (path or "").split("?")[0]
|
||||
if p.startswith(ALWAYS_PREFIX):
|
||||
return None
|
||||
if method == "GET":
|
||||
return {"kind": "html", "code": 200, "text": forced_page(info)}
|
||||
return {"kind": "json", "code": 403,
|
||||
"obj": {"error": {"code": "UPDATE_REQUIRED",
|
||||
"message": "当前版本已停止服务,请升级到 %s 或更高版本"
|
||||
% (info.get("min_required") or "最新版")}}}
|
||||
|
||||
|
||||
def status():
|
||||
"""/api/version_info:当前/最新/最低要求/是否被强制/是否有新版。"""
|
||||
ok, info = check()
|
||||
out = dict(info)
|
||||
out["forced"] = not ok
|
||||
cur, lat = vkey(info.get("current")), vkey(info.get("latest"))
|
||||
out["update_available"] = bool(ok and cur and lat and cur < lat)
|
||||
return out
|
||||
|
||||
|
||||
def forced_page(info):
|
||||
cur = info.get("current") or "?"
|
||||
req = info.get("min_required") or "?"
|
||||
notes = str(info.get("notes") or "")
|
||||
pkg = str(info.get("package_url") or "")
|
||||
return """<!DOCTYPE html>
|
||||
<html lang="zh"><head><meta charset="utf-8">
|
||||
<title>软件需要升级</title><style>
|
||||
body{font-family:"Microsoft YaHei",sans-serif;background:#f0f2f5;display:flex;
|
||||
align-items:center;justify-content:center;min-height:100vh;margin:0}
|
||||
.c{background:#fff;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);
|
||||
max-width:560px;padding:34px 38px}
|
||||
h1{font-size:20px;color:#b02a2a;margin:0 0 14px}
|
||||
p{color:#33475b;line-height:1.8;margin:8px 0;font-size:14px}
|
||||
.k{color:#8a97a5;font-size:12px;margin-top:18px;line-height:1.7}
|
||||
b{color:#1f2d3d}
|
||||
</style></head><body><div class="c">
|
||||
<h1>⚠ 当前版本已停止服务,需要升级</h1>
|
||||
<p>当前版本:<b>__CUR__</b> | 本软件要求的最低版本:<b>__REQ__</b></p>
|
||||
<p>升级方法:请联系软件提供方获取升级包(或在服务器上运行升级流程),完成后重新打开本页即可自动恢复。</p>
|
||||
__PKG____NOTES__
|
||||
<div class="k">本页面由本机服务提供。升级不会影响任何数据;如对升级有疑问,请联系软件提供方。
|
||||
版本状态口:/api/version_info(供排查用)。</div>
|
||||
</div></body></html>""".replace("__CUR__", cur).replace("__REQ__", req) \
|
||||
.replace("__PKG__", '<p>升级包地址:<a href="%s">%s</a></p>' % (pkg, pkg) if pkg else "") \
|
||||
.replace("__NOTES__", "<p>更新说明:%s</p>" % notes if notes else "")
|
||||
Reference in New Issue
Block a user