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

257 lines
11 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 主人定·方案A):
单位工程汇总/项目级汇总不再读导入快照,而是从真源现算——
数量: 直接工料机=Σ(定额含量×定额真实工程量);子工料机=Σ(子含量×母定额含量×定额真实工程量)
(=母量×子含量,数学全等)——同码双重身份相加,与 qty_map_uw 同式(2026-10-25 主人复确权);
项目级=Σ各单位同键;单位级兜底量取本单位快照 s_lme_uw(决策 41 本单位原样口径)。
单价: 库内现值(s_lme_proj);带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的,
实测 990304016:Σ=1156.6425→1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。
兜底(方案A): 定额链算不出、也不是子级的行(清单直挂工料机/费用科目行)用快照
(s_lme_uw/s_lme_proj)原样补位——不丢行。
覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价);
改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。
"""
import json
def _consumption_by_code(sc, sid, uw_id=None):
"""每码消耗量:{code: qty}。uw_id=None=全会话(项目级)。剔除临删定额/清单。"""
# ⚠️ s_norm_res 无 session_id 列——会话域经 norm→bill 链传达
sql = """SELECT nr.res_code AS c, SUM(nr.qty * n.Quantity)
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 COALESCE(n.x_tdel,0)=0 AND COALESCE(b.x_tdel,0)=0"""
args = [sid]
if uw_id is not None:
sql += " AND b.uw_id=?"
args.append(uw_id)
sql += " GROUP BY nr.res_code"
out = {}
for r in sc.execute(sql, args):
try:
out[r["c"]] = float(r[1] or 0)
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}} 项目级现值快照(价格/名规单真值)。"""
out = {}
for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp,
COALESCE(x_merged_hide,0) AS hid
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)
remark = {}
fb_qty = {}
if uw_id is not None:
# 单位级兜底量取本单位快照 s_lme_uw(决策 41 本单位汇总节点原样)——
# 原实现取 s_lme_proj.qty(项目级总量),每个单位都显示项目级总量,2026-10-25 实测报障
for r in sc.execute("SELECT code, qty FROM s_lme_uw WHERE session_id=? AND uw_id=?",
(sid, uw_id)):
fb_qty[r["code"]] = r["qty"]
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()
order = list(consume.keys())
# 兜底行的顺序锚:快照序
snap_order = [c for c in pm if pm[c].get("hid") == 0]
if uw_id is not None:
snap_order += [c for c in fb_qty if c not in pm] # 本单位独有直挂/费用行(项目现值表没有)
for code in order + [c for c in snap_order if c not in consume]:
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 and not ch:
if p.get("hid"):
continue # 隐藏且无消耗 → 不出
if uw_id is not None:
qty = fb_qty.get(code)
if qty is None:
continue # 本单位快照无此码 → 非本单位的行,不出
else:
qty = p.get("qty") # 兜底行(直挂/费用):快照量
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
# 子级行作为独立汇总行(量=Σ各母引用)——由下方 kids 段补
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"), remark.get(code)])
for c, q in child_qty.items():
if c in seen:
continue # 主循环已出行(直接消耗/兜底)——子级量已并入该行
seen.add(c)
p = pm.get(c) or {}
if p.get("hid"):
continue
ntp, rate, taxp = price_of(c)
rows.append([p.get("id"), c, p.get("name") or (kids and ""), p.get("spec") or "", p.get("unit") or "",
q, ntp, rate, taxp, p.get("kind"), remark.get(c)])
# 名称空白的子级行:从 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
return rows
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