feat: 落实决策216/219/227取价锚点与公式口径,增加商业版权益和源码完整性校验

This commit is contained in:
lianjianwei2024
2026-10-27 12:16:47 +08:00
parent 5d9eaf774b
commit 380a39f8db
36 changed files with 18821 additions and 879 deletions

View File

@@ -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)后「需重导」口径不再成立;