# -*- coding: utf-8 -*- """动态工料机汇总引擎(决策 188,2026-10-24 主人定·方案A): 单位工程汇总/项目级汇总不再读导入快照,而是从真源现算—— 数量: 定额消耗量(s_norm_res 含量 × s_norms 定额量)按码聚合;子级行=母行量×组成含量; 项目级=Σ各单位同键。 单价: 库内现值(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 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 = {} 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) rows, seen = [], set() order = list(consume.keys()) # 兜底行的顺序锚:快照序 snap_order = [c for c in pm if pm[c].get("hid") == 0] 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 ch and qty is not None: pass # 母行量=直接消耗 if qty is None and not ch: if p.get("hid"): continue # 隐藏且无消耗 → 不出 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)]) # 子级行:该单位内所有母的量×含量 聚合 child_qty = {} for mcode, ch in kids.items(): mq = consume.get(mcode) if mq is None: continue for c, q, _nm in ch: try: child_qty[c] = child_qty.get(c, 0.0) + float(mq) * float(q or 0) except (TypeError, ValueError): pass 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