# -*- coding: utf-8 -*- """动态工料机汇总引擎(决策 188,2026-10-24 主人定;数量归零口径=决策 196,2026-10-25 主人定): 单位工程汇总/项目级汇总不再读导入快照,而是从真源现算—— 骨架(决策 196): 空骨架保行——行集合=快照可见码∪现算码(项目级;单位级=本单位快照码∪本单位 现算码,本单位快照无此码不出行),骨架只定行与属性槽、不供任何量; 合并隐藏且链上无量的纯重复行仍不出。 数量: 直接工料机=Σ(定额含量×定额真实工程量);子工料机=Σ(子含量×母定额含量×定额真实工程量) (=母量×子含量,数学全等)——同码双重身份相加,与 qty_map_uw 同式(2026-10-25 主人复确权); 项目级=Σ各单位同键;链算不出一律归零(决策 196:快照值兜底取消,188 方案A原 「直挂/费用科目行快照原样补位」随之废止,费用行量恒 0)。 单价: 决策 219(2026-10-26 主人定)——主取价源=**单位级 s_lme_uw**(每单位每码认导入序第一行, 同码不同价随便认一个);项目级行=单位级行按 全字段+三价 一致才归并、不一致各自独立, 行量=各成员单位现算量之和;缺码/缺价兜底 s_lme_proj 快照;与源文件自带汇总不保证一致。 带子级母行单价=Σ(子级含量×子级单价)(除税/含税各算各的,实测 990304016:Σ=1156.6425 →1156.64 ✓),用户显式改过母行价=覆盖值(优先显示)。 覆盖标记: s_settings 域键 lme_px_ov = {"码":1,...}(用户显式改过母行价); 改子级价/含量 → 清其母的覆盖(母行回到 Σ 现算)。 """ import json, os, threading _QTY_EXPR_OK = __import__("re").compile(r"^[\d+\-*/().\s]*$") def gcl_of(bill_qty, unit): """兼容旧调用的 GCL 原值——决策 216:GCL=清单工程量原值,单位因子只在公式结果上最后除。""" return round(float(bill_qty) if bill_qty is not None else 0.0, 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 unit_factor(unit): """定额单位数字前缀因子(10m3→10、1000m3→1000;纯字母/无数字=1)。决策 216 用。""" import import_job div = import_job.unit_prefix(unit) return div if div and div > 0 else 1.0 def formula_qty(expr, bill_qty, unit): """公式定额量——决策 216(2026-10-26 主人定,取代 90/106 的 GCL 先÷单位口径): GCL=**清单工程量原值**(不先除单位);公式不论多少层括号/加减乘除, **最后的结果整体÷单位数字前缀**=定额量。求值失败 → (None, msg)。""" v, msg = eval_qty_expr(expr, bill_qty if bill_qty is not None else 0.0) if v is None: return None, msg return round(v / unit_factor(unit), 6), None def _norm_qty(nq, expr, unit, bill_qty): """定额量取数(决策 205;公式口径决策 216 改:GCL=清单原值,结果整体÷单位)。 无公式用存储量(纯数字=实际量÷因子口径不变);都无 → None。""" if expr: try: v, _msg = formula_qty(expr, 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, by_uw=False): """每码消耗量:{code: qty}。uw_id=None=全会话(项目级)。剔除临删定额/清单。 决策 205(2026-10-25 主人定):定额量**按求值取数**——采纳挂 GCL 公式的定额 (存储量 NULL,如 10# D3-6-5)此前整条丢掉,自算 0 vs 回导入 1,040 分叉的根因。 决策 219 by_uw=True:一次扫描按单位分桶 {uw_id: {code: qty}}(项目级行量=各成员 单位现算量之和——组量有真实归属,不再需要按比例分摊)。""" # ⚠️ s_norm_res 无 session_id 列——会话域经 norm→bill 链传达 # 防御(与 dyn_rows 同款):老库可能缺 qty_expr/Unit 列 → 可选补位; # 但 **Quantity 必须存在**——缺失说明计算链不完整,抛错让 dyn_rows 退 None 走快照老路 # (测试假库契约: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_buw = "b.uw_id AS buw" if have("s_bills", "uw_id") else "NULL AS buw" # 决策 219 分桶 sel_td_n = "COALESCE(n.x_tdel,0)=0" if have("s_norms", "x_tdel") else "1=1" sel_hid_n = "COALESCE(n.x_adopt_hidden,0)=0" if have("s_norms", "x_adopt_hidden") else "1=1" sel_td_b = "COALESCE(b.x_tdel,0)=0" if have("s_bills", "x_tdel") else "1=1" sel_hid_r = "COALESCE(nr.x_adopt_hidden,0)=0" if have("s_norm_res", "x_adopt_hidden") else "1=1" sql = """SELECT nr.res_code AS c, nr.qty, n.id AS nid, %s, %s, %s, %s, %s FROM s_norm_res nr JOIN s_norms n ON n.id = nr.norm_id JOIN s_bills b ON b.id = n.bill_id WHERE b.session_id=? AND nr.res_code IS NOT NULL AND %s AND %s AND %s AND %s""" % (sel_nq, sel_nex, sel_nu, sel_bq, sel_buw, sel_td_n, sel_td_b, sel_hid_n, sel_hid_r) args = [sid] if uw_id is not None: sql += " AND b.uw_id=?" args.append(uw_id) out = {} # by_uw=True 时值= {uw_id: {code: qty}} 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: q = float(r["qty"] or 0) * nq except (TypeError, ValueError): continue if by_uw: b = out.setdefault(r["buw"], {}) b[r["c"]] = b.get(r["c"], 0.0) + q else: out[r["c"]] = out.get(r["c"], 0.0) + q return out 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}} 项目级现值快照(价格/名规单/备注真值)。 决策 219 起降为**兜底**(缺码/缺价才取)+行id/备注/隐藏标记来源;主取价源=单位级 _uw_price_rows。""" out = {} for r in sc.execute("""SELECT id, code, name, spec, unit, kind, qty, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags, x_org_ntp0, x_org_taxp0, COALESCE(x_merged_hide,0) AS hid, x_remark FROM s_lme_proj WHERE session_id=? AND COALESCE(x_adopt_hidden,0)=0""", (sid,)): out[r["code"]] = dict(r) return out def _uw_price_rows(sc, sid): """决策 219(2026-10-26 主人定):单位级取价——**同单位工程内按成员(码+除数量外全字段) 分行**(2026-11-04 主人补:除数量外任一字段不同就是独立成员,不能合并/累计); 同字段组合的多行才是同一成员(数量累计,价格取该行)。 {code: [行dict(按 uw+成员 去重、id 序)]},行含 uw_id/名规单/类别/三价/六价扩展/flags。 项目级汇总(_dyn_rows uw_id=None)以这张表为分组基础——单位级先对,项目级才对。""" out = {} for r in sc.execute("""SELECT id, uw_id, code, name, spec, unit, kind, ntp, taxrate, taxp, ntp_org, ntp_expr, taxp_org, taxp_expr, x_flags FROM s_lme_uw WHERE session_id=? AND COALESCE(x_adopt_hidden,0)=0 ORDER BY id""", (sid,)): if not r["code"]: continue lst = out.setdefault(r["code"], []) key = (str(r["uw_id"]), r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxrate"], r["taxp"], r["ntp_org"], r["ntp_expr"], r["taxp_org"], r["taxp_expr"], r["x_flags"]) if any(m.get("_mk") == key for m in lst): continue # 同单位同成员(字段全同)→ 合成一行 d = dict(r) d["_mk"] = key lst.append(d) return out def _recode_away(sc, sid): """已合并换码的旧码集(决策 219 显示端防复活:合并后单位级表可能还留着旧码行, 与项目级隐藏口径不一致 → 不再显示,归并到保留码)。""" row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='recode_map'", ("session:%d" % sid,)).fetchone() try: rm = json.loads(row["v"] or "{}") if row else {} except (TypeError, ValueError): rm = {} return set(k for k, v in rm.items() if k and v and k != v) def _overrides(sc, sid): row = sc.execute("SELECT v FROM s_settings WHERE scope=? AND k='lme_px_ov'", ("session:%d" % sid,)).fetchone() try: 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, keep_zero=False): """动态汇总行(11 列同 _lme_rows 形状):[id,code,name,spec,unit,qty,ntp,taxrate,taxp,kind,remark]。 id=项目级行 id(存在时)——前端行级改价按它定位;骨架行无库行时 id=None。 防御:计算链不完整(老库/测试假库缺表缺列)→ 返回 None,调用方退回快照老路。 keep_zero=True:2026-11-04 主人定「数量 0 也要参与合并工料机」——合并弹框取全量现算行, 汇总页仍走默认过滤(决策 209 显示口径不动)。""" try: return _dyn_rows(sc, sid, uw_id, keep_zero) except Exception: return None def _dyn_rows(sc, sid, uw_id=None, keep_zero=False): kids = _children_map(sc, sid) pm = _price_map(sc, sid) ov = _overrides(sc, sid) uwp = _uw_price_rows(sc, sid) # 决策 219:主取价源=单位级(每单位每码认第一行) away = _recode_away(sc, sid) # 决策 219:合并换码的旧码不显示 uwp = {c: lst for c, lst in uwp.items() if c not in away} # 组成子码价格快照(s_lme_lib:采纳时从来源批次 lme_lib 带入)——手工会话没有源文件, # 单位级/项目级三步链全空,组成子行(折旧费/检修费…)价会落 0(2026-10-28 主人实测 # 易达映射源里组成子行编制价全空);库快照垫在链条末尾 lbm = {} try: for r in sc.execute("SELECT code, name, spec, unit, kind, ntp, taxp " "FROM s_lme_lib WHERE session_id=?", (sid,)): lbm[r["code"]] = (r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"]) except Exception: lbm = {} # 决策 219 兜底:单位级行三价缺 → 项目级快照补(主人定「编号或单价实在没有的去项目级取」) for _c, _lst in uwp.items(): _p = pm.get(_c) for _r in _lst: if _p: if _r["ntp"] is None: _r["ntp"] = _p["ntp"] if _r["taxrate"] is None: _r["taxrate"] = _p["taxrate"] if _r["taxp"] is None: _r["taxp"] = _p["taxp"] def child_px(code, uw=None): """子级三价(母行Σ用,决策 219):本单位行 → 第一行 → 项目级快照 → s_lme_lib 快照兜底。""" lst = uwp.get(code) or [] r = None if uw is not None: r = next((m for m in lst if str(m["uw_id"]) == str(uw)), None) if r is None and lst: r = lst[0] p = pm.get(code) or {} _pk = lambda a, b: (a if a is not None else b) lb = lbm.get(code) or (None, None) return (_pk(_pk(r and r["ntp"], p.get("ntp")), lb[0]), _pk(r and r["taxrate"], p.get("taxrate")), _pk(_pk(r and r["taxp"], p.get("taxp")), lb[1])) def _one_price_set(ch): """同一母码可能按单位工程挂多套组成(ESCC:一处无后缀套、别处 -0003 换算套)—— 母价 Σ 只取**第一套**(按子码基码去重),避免两套相加把台班单价翻倍; 数量传导仍用全量(变体子码各自得量)。""" seen, out = set(), [] for c, q, nm in ch: base = (c or "").split("-")[0] if base in seen: continue seen.add(base) out.append((c, q, nm)) return out def computed_mother(code, uw=None): """带子级母行 Σ 单价(除税,含税);任一子级无价→None(算不齐退行值)。""" sn = st = 0.0 for c, q, _nm in _one_price_set(kids.get(code) or ()): ntp, _rt, taxp = child_px(c, uw) 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) _SNAP_KEYS = ("name", "spec", "unit", "kind", "ntp", "taxrate", "taxp") def mk_row(code, r, qty): """16 列行(决策 259 前 11 列)。r=认下的单位级行(或快照 dict);带子级母行 Σ 现算(除非覆盖)。 尾部 5 元素=六价扩展四值(ntp_org/ntp_expr/taxp_org/taxp_expr,决策 219 同链:认下行 → 项目级快照补缺 → lib 无 org 即 None)+ x_flags(文字/标志属性 JSON,原文件有才导)。""" p = pm.get(code) or {} ntp, rate, taxp = r.get("ntp"), r.get("taxrate"), r.get("taxp") _pk6 = lambda a, b: (a if a is not None else b) org4 = tuple(_pk6(r.get(k), p.get(k)) for k in ("ntp_org", "ntp_expr", "taxp_org", "taxp_expr")) # 定额单价专题(2026-11-03 主人定):原价第③级兜底=第一次外部采纳价(x_org_*0, # 采纳落价时列空才写);①单位级 → ②项目级 → ③此列;Expr(调价式)无采纳源、不兜底。 _o = list(org4) if _o[0] is None and p.get("x_org_ntp0") is not None: _o[0] = p["x_org_ntp0"] if _o[2] is None and p.get("x_org_taxp0") is not None: _o[2] = p["x_org_taxp0"] org4 = tuple(_o) # s_lme_lib 快照兜底(手工会话没有源文件:单位级/项目级行都没有,组成子行 # 折旧费/检修费等的名称/单位/单价从这里来——2026-10-28 主人实测映射源价全空) lb = lbm.get(code) if lb is not None: _nm2, _sp2, _un2, _kd2, _ln, _lt = lb if not (r.get("name") or "") and _nm2: r = dict(r, name=_nm2, spec=(r.get("spec") or _sp2 or ""), unit=(r.get("unit") or _un2 or ""), kind=(r.get("kind") if r.get("kind") is not None else _kd2)) if ntp is None: ntp = _ln if taxp is None: taxp = _lt # 2026-11-04 主人按原件定(990401025 载货汽车 552.75 / 637.29 两价并存、各配一套子级): # **有源价用源价,只有缺价时才用 Σ 子级兜底**——决策 188 的「带子级母行单价=Σ子级」 # 据此收窄:若强行 Σ 覆盖,同码多成员(不同价)会被算成同一个价,违反 # 「除数量外字段不一致就分多条」的显示规则(原版就是两条)。 if kids.get(code) and not ov.get(code) and (ntp is None or taxp is None): cn, ct = computed_mother(code, r.get("uw_id")) if cn is not None: ntp = ntp if ntp is not None else cn taxp = taxp if taxp is not None else ct # 决策 291:带子级父行本身不带税率(显示端与导出件一致显示空/—) if kids.get(code): rate = None return [p.get("id"), code, r.get("name") or "", r.get("spec") or "", r.get("unit") or "", qty, ntp, rate, taxp, r.get("kind"), p.get("x_remark"), # 决策 203:备注随行(采纳/手工同字段) *org4, ((r.get("x_flags") if r.get("x_flags") is not None else p.get("x_flags")) if (r.get("x_flags") is not None or p.get("x_flags") is not None) else None)] rows, seen = [], set() if uw_id is not None: # —— 单位工程级(决策 219):本单位每码一行(认第一行),量=本单位现算(含子级推导) qmap = qty_map_uw(sc, sid, uw_id) mine = [(code, r) for code, lst in uwp.items() for r in lst if str(r["uw_id"]) == str(uw_id)] # id 序=源文件序(顺序锚,决策 41) for code, r in mine: seen.add(code) rows.append(mk_row(code, r, qmap.get(code) or 0.0)) for code in qmap: # 本单位现算有量而表无行的码(名从快照/子级兜底) if code and code not in seen and code not in away: seen.add(code) p = pm.get(code) or {} rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), qmap.get(code) or 0.0)) else: # —— 项目级(决策 219):全字段+三价一致的单位级行才并成一行,不一致各自独立; # 行量=各成员单位现算量之和(真实归属,不按比例分摊) # 2026-11-04 主人定「改哪个单位只算哪个单位」:量图走缓存(qmap_all_cached), # 分桶+子级传导收敛到 _propagate 一处(取代此前活读迭代,与 qty_map_uw 快照迭代 # 两处不一致的写法——仅「子级自己带子级」时两法才有差异,现库无此情形)。 qmaps = qmap_all_cached(sc, sid) groups, gidx = [], {} for code, lst in uwp.items(): # 顺序锚=单位级行 id 序(源文件序) for r in lst: # 决策 303(2026-11-11 主人定「按 B 改,并冻结此功能」):分组键=**界面可见字段** # (码/名/规/单位/类别/三价)——可见字段全一致即并一行、量相加; # 原价四字段(ntp_org/ntp_expr/taxp_org/taxp_expr)与属性 flags 不再参与拆行 # (并一行后取首成员的值)。单价/规格等**可见字段**不同的照样分条, # 保住 2026-11-04「载货汽车 552.75/637.29 两价并存」的意图不受影响。 k = (code, r["name"] or "", r["spec"] or "", r["unit"] or "", r["kind"], r["ntp"], r["taxrate"], r["taxp"]) g = gidx.get(k) if g is None: g = {"code": code, "r": r, "uws": []} gidx[k] = g groups.append(g) g["uws"].append(r["uw_id"]) for g in groups: code = g["code"] seen.add(code) qty = 0.0 for u in g["uws"]: qty += qmaps.get(u, {}).get(code) or 0.0 rows.append(mk_row(code, g["r"], qty)) for code, p in pm.items(): # 兜底:单位表全无、仅项目级有的码 if not code or code in seen or code in away or p.get("hid"): continue seen.add(code) qty = 0.0 for qm in qmaps.values(): qty += qm.get(code) or 0.0 rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), qty)) _extra = {} # 现算有量而两处都无行的码(名从子级/快照兜底) for qm in qmaps.values(): for code, q in qm.items(): if code: _extra[code] = _extra.get(code, 0.0) + (q or 0.0) for code, q in _extra.items(): if code not in seen and code not in away: seen.add(code) p = pm.get(code) or {} rows.append(mk_row(code, dict(zip(_SNAP_KEYS, [p.get(k) for k in _SNAP_KEYS])), q)) # 名称空白的子级行:从 lme_res.name 兜底 for row in rows: if not row[2]: 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 供数链不经过此处,不动。 # 2026-11-04 主人定(合并工料机):keep_zero=True 时全量返回——0 量品种也要能参与合并。 if keep_zero: return rows 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): """单位工程级 14 列(决策 259):前 9 列同 _raw_uw lme 形状 [码,名,规,单,类别,量,除税,税率,含税], 尾部追加六价扩展四值 + x_flags(导出链灌 org/调价式/Total 用;显示端截前 9 列)。链不全→None。""" try: return [[r[1], r[2], r[3], r[4], r[9], r[5], r[6], r[7], r[8], r[11], r[12], r[13], r[14], r[15] if len(r) > 15 else None] for r in _dyn_rows(sc, sid, uw_id)] except Exception: return None 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)] # ── 量图缓存(2026-11-04 主人定「改哪个单位只算哪个单位,项目级再汇总」)────────── # 现算结果 {uw_id: {码: 量}} 按 (库文件路径, 会话id) 挂进程内存: # · 读(单位级卡/项目级卡/合并弹框/导出/检索)统一走 qmap_all_cached——首次惰性建 # (一次全扫,成本=原项目级卡一次现算),之后其余单位继续用缓存; # · 改定额量/清单量/定额消耗量 → api_server 路由层在 commit 后调 qmap_touch_uw # 只重算该单位;含量编辑/临删恢复/采纳/结构增删/合并/重解析 → qmap_drop 全失效; # · 库文件 mtime 兜底网:任何漏钩写入(含外部进程)都会在下一次读取被发现并整图重建; # · :memory: 库(pytest 假库)不缓存直接现算——与旧全算行为一致,测试无隔离风险。 # 母子传导收敛:_propagate 一处实现(从直接消耗量快照出发、只传一层,决策 268补三 口径), # 取代此前 qty_map_uw(快照迭代)与项目级分桶(活读迭代)两处不一致的写法(2026-11-04 主人拍板)。 _QLOCK = threading.Lock() _QCACHE = {} # (db_path, sid) -> {"mtime": float, "maps": {uw_id: {码: 量}}} def _qpath_mt(sc): """(库文件路径, mtime);:memory: 路径为空 → 调用方旁路缓存。 决策 288 修(2026-11-08):会话库是 **WAL**——提交只写 -wal 文件、主库 mtime 不动, 只看主库会误判「缓存仍新鲜」(实测时好时坏/导出指纹漂移的根);mtime 取 主库与 -wal 两者较大值,任何提交都换戳。""" path = "" try: for r in sc.execute("PRAGMA database_list").fetchall(): if r[1] == "main": path = r[2] or "" break except Exception: path = "" mt = 0.0 if path: try: mt = os.path.getmtime(path) if os.path.exists(path + "-wal"): mt = max(mt, os.path.getmtime(path + "-wal")) except OSError: mt = 0.0 return path, mt def qmap_mtime_of(sc): """写入口取「写前库 mtime」用(api_server 持 WRITE_LOCK,读与写同线程同库)。""" return _qpath_mt(sc)[1] def _propagate(base, kids): """母子传导唯一实现:子量 = 母量 × 子含量,从直接消耗量快照出发只传一层 (决策 268补三 2026-11-04 主人定口径;子级自己带子级不二次传导)。""" out = dict(base) for mcode, mq in base.items(): if mq is None: continue for c, q, _nm in kids.get(mcode) or (): try: out[c] = out.get(c, 0.0) + float(mq) * float(q or 0) except (TypeError, ValueError): pass return out def _qmap_build_all(sc, sid): consume = _consumption_by_code(sc, sid, None, by_uw=True) kids = _children_map(sc, sid) return {u: _propagate(m, kids) for u, m in consume.items()} def qmap_all_cached(sc, sid): """全单位量图缓存读口:{uw_id: {码: 现算量}}。链不全(老库缺列)照旧抛 RuntimeError, 由 dyn_rows 退 None 走快照老路——与全算时代同一退路。""" path, mt = _qpath_mt(sc) if not path: return _qmap_build_all(sc, sid) key = (path, int(sid)) with _QLOCK: ent = _QCACHE.get(key) if ent is not None and ent["mtime"] == mt: return ent["maps"] maps = _qmap_build_all(sc, sid) with _QLOCK: _QCACHE[key] = {"mtime": mt, "maps": maps} return maps def qmap_touch_uw(sc, sid, uw_id, pre_mt=None): """「改哪个单位只算哪个单位」:只重算该单位量图、刷缓存戳(其余单位继续用缓存)。 调用约定:api_server 在 commit 之后、WRITE_LOCK 之内调用;pre_mt=写前库 mtime—— 与缓存戳不一致说明其间有别的写者插队,保守放弃缓存(下次读取整图重建)。""" path, mt_now = _qpath_mt(sc) if not path: return key = (path, int(sid)) with _QLOCK: ent = _QCACHE.get(key) if ent is not None and pre_mt is not None and ent["mtime"] != pre_mt: _QCACHE.pop(key, None) # 期间有并发写 → 缓存不可信,整图放弃 ent = None if ent is None: return try: umap = _propagate(_consumption_by_code(sc, sid, uw_id), _children_map(sc, sid)) except Exception: with _QLOCK: _QCACHE.pop(key, None) return with _QLOCK: ent = _QCACHE.get(key) if ent is not None: ent["maps"][uw_id] = umap ent["mtime"] = mt_now def qmap_drop(sid=None): """量图全失效(含量编辑/临删恢复/采纳/结构增删/合并/重解析/删会话); sid=None 清全部(测试收尾用)。下次读取整图重建一次,成本=原项目级卡一次现算。""" with _QLOCK: if sid is None: _QCACHE.clear() else: for k in [k for k in _QCACHE if k[1] == int(sid)]: _QCACHE.pop(k, None) def qty_map_uw_all(sc, sid): """全部单位工程的 {uw_id: {码: 现算数量}}——量图缓存读口(2026-11-04 主人定)。 首次一次全扫建缓存,之后读缓存;改定额量/清单量由写入口单算刷新(qmap_touch_uw), 其余数量链改动整图失效(qmap_drop)。与旧「一次扫描」同形同值。""" return qmap_all_cached(sc, sid) def qty_map_uw(sc, sid, uw_id): """决策 188 数量模型(主人定稿)——某单位工程的 {码: 数量} 现算图: 母/直挂: Σ(定额含量 × 定额真实工程量) 子工料机: Σ(子含量 × 母定额含量 × 定额真实工程量) (=母量×子含量,数学全等已证) 只算不写库(原字段不动);导出/显示共同数据源。 2026-11-04:走量图缓存(qmap_all_cached)——首次建缓存=一次全扫,之后从缓存取。""" return qmap_all_cached(sc, sid).get(uw_id) or {}