Files
pricing_review/CostReview/app/core/dyn_lme.py

317 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""动态工料机汇总引擎(决策 188,2026-10-24 主人定;数量归零口径=决策 196,2026-10-25 主人定):
单位工程汇总/项目级汇总不再读导入快照,而是从真源现算——
骨架(决策 196): 空骨架保行——行集合=快照可见码∪现算码(项目级;单位级=本单位快照码∪本单位
现算码,本单位快照无此码不出行),骨架只定行与属性槽、不供任何量;
合并隐藏且链上无量的纯重复行仍不出。
数量: 直接工料机=Σ(定额含量×定额真实工程量);子工料机=Σ(子含量×母定额含量×定额真实工程量)
(=母量×子含量,数学全等)——同码双重身份相加,与 qty_map_uw 同式(2026-10-25 主人复确权);
项目级=Σ各单位同键;链算不出一律归零(决策 196:快照值兜底取消,188 方案A原
「直挂/费用科目行快照原样补位」随之废止,费用行量恒 0)。
单价: 库内现值(s_lme_proj);带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的,
实测 990304016:Σ=1156.6425→1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。
覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价);
改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。
"""
import json
_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)
def eval_qty_expr(expr, gcl):
"""GCL 公式求值(决策 90;决策 205 从 api_server 收口到核心层供聚合链共用)。
全角归一;除零/非法字符/非有限值返回 (None, msg);结果 round 6 位。"""
import re
s = (expr or "").strip()
for a, b in (("(", "("), (")", ")"), ("+", "+"), ("-", "-"), ("*", "*"),
("×", "*"), ("÷", "/"), (",", ",")):
s = s.replace(a, b)
s = s.upper()
if not _QTY_EXPR_OK.match(s.replace("GCL", "")):
return None, "公式只能含 GCL、数字和 + - * / ( )"
try:
v = eval(s, {"__builtins__": {}}, {"GCL": gcl}) # 字符集白名单已排除一切标识符/函数
except ZeroDivisionError:
return None, "公式除数为 0"
except Exception:
return None, "公式无法计算"
v = float(v)
if v != v or v in (float("inf"), float("-inf")):
return None, "公式结果不是有限数"
return round(v, 6), None
def _norm_qty(nq, expr, unit, bill_qty):
"""定额量取数(决策 205):公式按 GCL 求值(决策 90 跟随),无公式用存储量;都无 → None。"""
if expr:
try:
v, _msg = eval_qty_expr(expr, gcl_of(bill_qty, unit))
if v is not None:
return float(v)
except Exception:
pass
try:
return float(nq) if nq is not None else None
except (TypeError, ValueError):
return None
def _consumption_by_code(sc, sid, uw_id=None):
"""每码消耗量:{code: qty}。uw_id=None=全会话(项目级)。剔除临删定额/清单。
决策 205(2026-10-25 主人定):定额量**按求值取数**——采纳挂 GCL 公式的定额
(存储量 NULL,如 10# D3-6-5)此前整条丢掉,自算 0 vs 回导入 1,040 分叉的根因。"""
# ⚠️ s_norm_res 无 session_id 列——会话域经 norm→bill 链传达
# 防御(与 dyn_rows 同款):老库可能缺 qty_expr/Unit 列 → 可选补位;
# 但 **Quantity 必须存在**——缺失说明计算链不完整,抛错让 dyn_rows 退 None 走快照老路
# (测试假库契约:src='agg' 回退,test_lme_price 实测)。
have = lambda t, c: any(x[1] == c for x in sc.execute("PRAGMA table_info(%s)" % t))
if not have("s_norms", "Quantity"):
raise RuntimeError("s_norms 缺 Quantity 列:计算链不完整")
sel_nq = "n.Quantity AS nq"
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_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
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)
args = [sid]
if uw_id is not None:
sql += " AND b.uw_id=?"
args.append(uw_id)
out = {}
cache = {} # norm_id → 求值后的定额量(同一定额只算一次)
for r in sc.execute(sql, args):
if not r["c"]:
continue
nid = r["nid"]
if nid not in cache:
cache[nid] = _norm_qty(r["nq"], r["nex"], r["nu"], r["bq"])
nq = cache[nid]
if nq is None:
continue
try:
out[r["c"]] = out.get(r["c"], 0.0) + float(r["qty"] or 0) * nq
except (TypeError, ValueError):
pass
return out
def _children_map(sc, sid):
"""{母码: [(res_code, qty含量, name), ...]} 按 seq。"""
out = {}
for r in sc.execute("""SELECT p_code, res_code, qty, name FROM s_lme_res
WHERE session_id=? ORDER BY p_code, seq, id""", (sid,)):
out.setdefault(r["p_code"], []).append((r["res_code"], r["qty"], r["name"]))
return out
def _price_map(sc, sid):
"""{code: {name,spec,unit,kind,ntp,taxrate,taxp,qty,id,hide,x_remark}} 项目级现值快照(价格/名规单/备注真值)。"""
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
FROM s_lme_proj WHERE session_id=?""", (sid,)):
out[r["code"]] = dict(r)
return out
def _overrides(sc, sid):
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_ov'", ("session:%d" % sid,)).fetchone()
try:
return json.loads(row["v"] or "{}") if row else {}
except (TypeError, ValueError):
return {}
def set_override(sc, sid, code, on):
"""改母行价=置覆盖;改子级价/含量=清母覆盖。⚠️ 与调用方同 sc 连接。"""
ov = _overrides(sc, sid)
changed = False
if on:
if not ov.get(code):
ov[code] = 1
changed = True
elif code in ov:
del ov[code]
changed = True
if changed:
sc.execute("INSERT INTO s_settings(scope,k,v) VALUES(?,?,?) ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v",
("session:%d" % sid, "lme_px_ov", json.dumps(ov)))
def mothers_of(sc, sid, child_code):
"""引用该子码的全部母码(清覆盖用)。"""
return [r[0] for r in sc.execute(
"SELECT DISTINCT p_code FROM s_lme_res WHERE session_id=? AND res_code=?", (sid, child_code))]
def mark_manual_price(sc, sid, code):
"""决策 191(2026-10-25 主人定):手工改价标记——合并态重放跳过被手工改过价的码。
跨清场存活链:标记存 s_settings(无 session_id 列,天然不沾 wipe),价格真值由
决策 68 快照 lme_vals 跨重解析带回,重放跑在快照回填之后 → 跳过=手工价存活。"""
try:
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_manual'",
("session:%d" % sid,)).fetchone()
m = json.loads(row["v"] or "{}") if row else {}
if not m.get(code):
m[code] = 1
sc.execute("INSERT INTO s_settings(scope,k,v) VALUES(?,?,?) "
"ON CONFLICT(scope,k) DO UPDATE SET v=excluded.v",
("session:%d" % sid, "lme_px_manual", json.dumps(m)))
except Exception:
pass # 假库缺表/缺列 → 标记失败不挡编辑
def manual_price_codes(sc, sid):
"""决策 191:本会话被手工改过价的码集合(重放跳过用)。假库/缺表 → 空集。"""
try:
row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_manual'",
("session:%d" % sid,)).fetchone()
return set(json.loads(row["v"] or "{}").keys()) if row else set()
except Exception:
return set()
def dyn_rows(sc, sid, uw_id=None):
"""动态汇总行(11 列同 _lme_rows 形状):[id,code,name,spec,unit,qty,ntp,taxrate,taxp,kind,remark]。
id=项目级行 id(存在时)——前端行级改价按它定位;骨架行无库行时 id=None。
防御:计算链不完整(老库/测试假库缺表缺列)→ 返回 None,调用方退回快照老路。"""
try:
return _dyn_rows(sc, sid, uw_id)
except Exception:
return 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"])
def price_of(code):
p = pm.get(code)
if not p:
return None, None, None
return p["ntp"], p["taxrate"], p["taxp"]
def computed_mother(code):
"""带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退库值)。"""
sn = st = 0.0
for c, q, _nm in kids.get(code) or ():
ntp, _rt, taxp = price_of(c)
if ntp is None or taxp is None:
return None, None
try:
sn += float(q or 0) * float(ntp)
st += float(q or 0) * float(taxp)
except (TypeError, ValueError):
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)
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:备注随行(采纳/手工同字段)
# 名称空白的子级行:从 lme_res.name 兜底
for row in rows:
if not row[2]:
for mcode, ch in kids.items():
for c, q, nm in ch:
if c == row[1] and nm:
row[2] = nm
break
# 决策 209(2026-10-26 主人定):显示端与导出端一致(199)——数量为 0 的行整行不显示,
# 取代 196「骨架保行」的显示端口径;导出端 199 与 qty_map_uw 供数链不经过此处,不动。
return [r for r in rows if r[5] is not None and float(r[5]) != 0]
def dyn_uw_rows(sc, sid, uw_id):
"""单位工程级 9 列(同 _raw_uw lme 形状):[码,名,规,单,类别,量,除税,税率,含税]。链不全→None。"""
rows = _dyn_rows_safe9(sc, sid, uw_id)
return rows
def _dyn_rows_safe9(sc, sid, uw_id):
try:
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8]] for r in _dyn_rows(sc, sid, uw_id)]
except Exception:
return None
def _dyn_uw_rows_old(sc, sid, uw_id):
return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8]] for r in dyn_rows(sc, sid, uw_id)]
def qty_map_uw(sc, sid, uw_id):
"""决策 188 数量模型(主人定稿)——某单位工程的 {码: 数量} 现算图:
母/直挂: Σ(定额含量 × 定额真实工程量)
子工料机: Σ(子含量 × 母定额含量 × 定额真实工程量) (=母量×子含量,数学全等已证)
只算不写库(原字段不动);导出/显示共同数据源。"""
consume = _consumption_by_code(sc, sid, uw_id)
kids = _children_map(sc, sid)
out = dict(consume)
for mcode, mq in consume.items():
for c, q, _nm in kids.get(mcode) or ():
try:
out[c] = out.get(c, 0.0) + mq * float(q or 0)
except (TypeError, ValueError):
pass
return out