feat(全链): 落实决策322-333——采纳落价Σ合价÷量、编制价三件套归一、块进块出、导出通用化只改导入、母随子动回算、台账分层留存

This commit is contained in:
lianjianwei2024
2026-11-14 23:40:41 +08:00
parent b05b34ffbf
commit b400454f74
12 changed files with 1572 additions and 384 deletions

View File

@@ -12,7 +12,7 @@ import session_job as sess
import import_job as job
import norm_closure
import dyn_lme
from code_identity import resolve_adopt, readopt_unhide, unadopt_drop # 决策 304:同码异物统一册(2026-11-12 撤=物理删改名)
from code_identity import resolve_adopt, readopt_unhide, unadopt_drop, reprice_all_lme # 决策 304 统一册+323 导入/采纳收尾全层级回算
def _have_col_set(sc, tbl):
@@ -1124,6 +1124,110 @@ def _lme_ntp_of(sc, sid, uw_id, code):
(sid, code)).fetchone()
return (r["ntp"], r["taxp"]) if r else (None, None)
# 决策 251(2026-11-01 主人定):决策 227 的改价失效回链随锚改导入价口径取消,函数已删。
def _batch_bill_uw(hc, bill_id):
"""批库清单所属单位工程(老夹具 bills 无 uw_id 列 → None,按无映射降级)。"""
try:
r = hc.execute("SELECT uw_id FROM bills WHERE id=?", (bill_id,)).fetchone()
return r[0] if r else None
except sqlite3.OperationalError:
return None
def _swt_src_rids(sid, src_name):
"""目标会话源件里已有 ResourceItem 的 (码→ID, 已占用ID集)。
采纳分配新 ID 前必须先避开这些号(它们不在 s_lme_uw 里也要算占用);
读不到源件/非 SWT → 空。"""
try:
path = _src_path(src_name or "")
if not path or not os.path.exists(path):
return {}, set()
raw = io.open(path, "rb").read()
if raw[:2] == b"PK":
import zipfile
with zipfile.ZipFile(io.BytesIO(raw)) as z:
txt = ""
for n in z.namelist():
b = z.read(n)
if b"<ConstructProject" in b[:20000] or b"<ResourceItem" in b[:20000]:
txt = b.decode("utf-8-sig", "replace")
break
else:
txt = raw.decode("utf-8-sig", "replace")
code2rid, used = {}, set()
for m in re.finditer(r'<ResourceItem\b[^>]*>', txt):
t = m.group(0)
c = re.search(r'\bCode="([^"]*)"', t)
r = re.search(r'\bResourceID="(\d+)"', t)
if not r:
continue
rid = int(r.group(1))
used.add(rid)
if c and c.group(1) and c.group(1) not in code2rid:
code2rid[c.group(1)] = rid
return code2rid, used
except Exception:
return {}, set()
def _swt_rid_remap(sc, hc, sid, batch_id, dst_uw, src_uw, block_xml):
"""P1-②(2026-11-14 主人拍板 331/332):SWT 清单块内 `NormResUsageItem@ResourceID` 是
批次**单位本地** ID——采纳时按「批次ID→码→目标单位码→目标ID」重写;目标单位缺 x_rid 的
码就地分配(不与既有 ID 冲突),采纳新增行也补 x_rid(导出补 ResourceItem 用)。
cos/esc 块(非 BQItem/MeasureItem 开头)原样返回。返回新块文本。"""
if not block_xml or not re.match(r'\s*<(BQItem|MeasureItem)\b', block_xml):
return block_xml
try:
src = {}
for r in hc.execute("""SELECT x_rid, code FROM lme_uw WHERE batch_id=? AND uw_id=?
AND x_rid IS NOT NULL""", (batch_id, src_uw)):
if r["x_rid"] is not None and r["code"]:
src[int(r["x_rid"])] = r["code"]
except Exception:
src = {}
if not src:
return block_xml
# SWT 的 ResourceID 是**全文件全局**的(同码跨单位同 ID)——按码建全会话映射,不按单位。
gmap = {}
for r in sc.execute("""SELECT code, x_rid FROM s_lme_uw WHERE session_id=?
AND x_rid IS NOT NULL AND code IS NOT NULL ORDER BY id""", (sid,)):
gmap.setdefault(r["code"], r["x_rid"])
used = set(gmap.values())
# 目标源件已有 ResourceItem(其 ID 未进 s_lme_uw 也算占用,必须先避开/按码复用)
_srow = sc.execute("SELECT src_name FROM sessions WHERE id=?", (sid,)).fetchone()
_src_code2rid, _used_src = _swt_src_rids(sid, (_srow[0] if _srow else "") or "")
used |= _used_src
for _c, _sr in _src_code2rid.items():
gmap.setdefault(_c, _sr)
nxt = (max(used) if used else 0) + 1
def _rid_for(code):
nonlocal nxt
if code in gmap:
return gmap[code]
rid = nxt
nxt += 1
gmap[code] = rid
used.add(rid)
# 同码跨单位统一用同一个 ID(导出 ResourceItem 全局唯一)
sc.execute("UPDATE s_lme_uw SET x_rid=? WHERE session_id=? AND code=?",
(rid, sid, code))
return rid
for _rid, code in src.items():
_rid_for(code)
# 采纳新增行(块没引用的也补)——导出按 x_rid 补 ResourceItem,块内引用才对得上
for r in sc.execute("""SELECT DISTINCT code FROM s_lme_uw WHERE session_id=?
AND COALESCE(x_adopt_added,0)=1 AND x_rid IS NULL
AND code IS NOT NULL""", (sid,)):
_rid_for(r["code"])
mp = {rid: gmap[c] for rid, c in src.items() if c in gmap}
if not mp:
return block_xml
return re.sub(r'ResourceID="(\d+)"',
lambda m: 'ResourceID="%d"' % mp.get(int(m.group(1)), int(m.group(1))),
block_xml)
def api_bill_adopt(sc, hc, body):
"""采纳(数据落地)。body={session_id, bill_id, src_bill_id}
统一路径(2026-11-07 主人定「新清单/原清单一个逻辑」,取代规格 9.1/9.3 双分支字段口径):
@@ -1146,6 +1250,8 @@ def api_bill_adopt(sc, hc, body):
# 决策 304 补记:清单级整藏四列幂等保列(再采纳反藏分支依赖)
_ensure_cols(sc, "s_norm_res", [("x_adopt_hidden", "INTEGER DEFAULT 0")])
_ensure_cols(sc, "s_norms", [("x_adopt_hidden", "INTEGER DEFAULT 0")])
_ensure_cols(sc, "s_norms", [("x_price_basis", "TEXT"), ("x_price_anchor", "REAL"),
("x_total_anchor", "REAL"), ("x_lme_total", "REAL")]) # 决策322 锚四列
_ensure_cols(sc, "s_block_bank", [("x_adopt_hidden", "INTEGER DEFAULT 0")])
_ensure_cols(sc, "s_bills", [("x_adopt_hidden", "INTEGER DEFAULT 0")])
_sbhid = sc.execute("SELECT COALESCE(x_adopt_hidden,0) FROM s_bills WHERE id=? AND session_id=?",
@@ -1194,7 +1300,8 @@ def api_bill_adopt(sc, hc, body):
if not bb:
return {"ok": False, "msg": "本工程来源清单不存在(可能已被删除,请刷新)"}
bnorms = sc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total,
NULL AS x_qty_coef, x_adjust, qty_expr, x_side
NULL AS x_qty_coef, x_adjust, qty_expr, x_side,
x_price_basis, x_price_anchor, x_total_anchor, x_lme_total
FROM s_norms WHERE bill_id=? AND (x_tdel IS NULL OR x_tdel=0) ORDER BY id""",
(src_self,)).fetchall()
else:
@@ -1213,7 +1320,16 @@ def api_bill_adopt(sc, hc, body):
src_id = bb["id"]
if not bb:
return {"ok": False, "msg": "入库项目清单不存在(批次可能已删除)"}
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side
# 决策322:批次侧锚列/冻结合计列保底 + 来源锚列判定(NULL=存疑默认除税)
_ensure_cols(hc, "norms", [("x_lme_total_nt", "REAL"), ("x_lme_total_tx", "REAL")])
_ensure_cols(hc, "batches", [("x_price_basis", "TEXT")])
try:
_basis_r = hc.execute("SELECT x_price_basis FROM batches WHERE id=?", (bb["batch_id"],)).fetchone()
_src_basis = (_basis_r[0] if _basis_r else None)
except sqlite3.OperationalError: # 夹具/极老库无 batches 表 → 默认除税
_src_basis = None
bnorms = hc.execute("""SELECT id, Number, Name, Unit, Quantity, Price, Total, x_qty_coef, x_adjust, x_side,
x_lme_total_nt, x_lme_total_tx
FROM norms WHERE bill_id=? ORDER BY id""", (src_id,)).fetchall()
# 决策 279(2026-11-07 主人定「整体采纳=块进块出」):273 行组模板链与 275 乙判定
@@ -1314,11 +1430,25 @@ def api_bill_adopt(sc, hc, body):
return mo.group(0)
return mo.group(0).replace('Number="%s"' % mo.group(1), 'Number="%s"' % _new, 1)
for nn in bnorms:
# 决策322(2026-11-14 主人拍板):锚四列落地——差额法不变式的起点
# (Price=锚价+(现合计−锚合计);改价/含量编辑按 Δ=差额×含量 增量维护,见 _norm_price_cascade)。
# 本会话来源:四列原样携带(再采纳=同一来源值);批次来源:锚列=批次判定(NULL→除税),
# 锚价=源单价(单价照带),锚合计=后台冻结源锚(norms.x_lme_total_nt/tx 按锚列口径取一)。
if src_self:
_vb, _va = nn["x_price_basis"], nn["x_price_anchor"]
_vt = nn["x_total_anchor"]; _vl = nn["x_lme_total"]
else:
_vb = _src_basis or "ntp"
_va = nn["Price"]
_vt = nn["x_lme_total_tx"] if _vb == "taxp" else nn["x_lme_total_nt"]
_vl = _vt
cur = sc.execute("""INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total,
x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?)""",
x_adopt, x_src_norm_id, qty_expr, x_adjust, x_side,
x_price_basis, x_price_anchor, x_total_anchor, x_lme_total)
VALUES(?,?,?,?,NULL,?,NULL,1,?,?,?,?,?,?,?,?)""",
(bid, nn["Number"], nn["Name"], nn["Unit"], nn["Price"],
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], None))
None if src_self else nn["id"], _norm_expr(nn), nn["x_adjust"], None,
_vb, _va, _vt, _vl))
adopted_norm_ids.append(cur.lastrowid)
# 决策 279:Norm 块原文随行拷入 s_block_bank(同后缀采纳=块进块出)。
# 拷入前按 108 code_map 改写块内消耗码(块与库同码,导出件消耗码指向本地价)。
@@ -1354,9 +1484,26 @@ def api_bill_adopt(sc, hc, body):
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]))
# 决策 333(2026-11-14 主人拍板 B,取代决策 19「采纳单价恒跟源」):
# 清单价=Σ(定额量×定额价)÷清单量(2 位半升);定额量按来源清单量→当前清单量等比缩放
# (x_qty_coef 优先,缺则 源定额量/源清单量),与导出/显示的 GCL 求值同一把尺。
_qb = _pre["Quantity"]
_qs = bb["Quantity"]
_sum333, _ok333 = 0.0, False
for nn in bnorms:
try:
_coef = (float(nn["Quantity"] or 0) / float(_qs)) if _qs not in (None, 0) else 1.0
_sum333 += float(_coef) * float(_qb or 0) * float(nn["Price"] or 0)
_ok333 = True
except Exception:
pass
if _ok333 and _qb not in (None, 0) and float(_qb) != 0:
new_price = _r2(_sum333 / float(_qb))
else:
new_price = None
# —— 清单字段统一口径(2026-11-07 主人定):编码/名称/项目特征/单位/工程量
# **空则引入、非空利旧**;新清单工程量恒清 0 待填;单价恒跟源(规格 19);
# 合价=工程量×新单价现算(原清单量空→引入来源量,Total 随之现算)。
# **空则引入、非空利旧**;新清单工程量恒清 0 待填;
# 单价按决策 333=Σ定额合价÷清单量(取代 19 的“恒跟源”);合价=量×价现算。
sets, vals = [], []
for col in ("Number", "Name", "Attr", "Unit"):
_sv = bb[col]
@@ -1382,8 +1529,8 @@ def api_bill_adopt(sc, hc, body):
# 决策 279/290:清单壳块随采纳拷入(新清单/原清单共用);只认最新有效同源块,
# 错代/错号/无 Norm 槽的壳一律拒用(回模板克隆,绝不拿错壳导出)。
if not src_self:
_want_tag = bb["x_ptag"] or ("UnitWorksPreliminaryWorkElement"
if bb["Kind"] == "prelim" else "WorkElement")
# 330:只认原生标签;老批次无 x_ptag → 传 None,由 pick_bill_block 以块自身标签兜底
_want_tag = bb["x_ptag"]
_shell = None
try:
_shell = job.pick_bill_block(hc, src_id, want_number=bb["Number"],
@@ -1396,9 +1543,15 @@ def api_bill_adopt(sc, hc, body):
except sqlite3.OperationalError:
_shell = None # 无表(夹具/旧库)→ 无块路径
if _shell and _has_sbb:
_bx = _shell.get("block_xml") or ""
try: # P1-②:SWT 块内 ResourceID 按目标单位重分配(cos/esc 原样)
_bx = _swt_rid_remap(sc, hc, sid, bb["batch_id"], sb["uw_id"],
_batch_bill_uw(hc, src_id), _bx)
except Exception as _e:
print("331 ResourceID 重分配失败(块原样):%s" % _e, flush=True)
sc.execute("""INSERT INTO s_block_bank(sid, bill_id, norm_id, kind, block_xml, src_batch, src_sha)
VALUES(?,?,NULL,'bill',?,?,?)""",
(sid, bid, _shell["block_xml"], _shell.get("batch_id"), _shell.get("src_sha")))
(sid, bid, _bx, _shell.get("batch_id"), _shell.get("src_sha")))
# 决策 108 改码落库(code_map 已在插定额前算好,见上):s_norm_res 随映射改成落地码
n_recode = 0
for nid in adopted_norm_ids:
@@ -1487,6 +1640,17 @@ def api_bill_adopt(sc, hc, body):
except Exception:
pass
print("采纳收尾数据链自愈失败(不挡采纳):%s" % _e, flush=True)
# 决策 323(2026-11-14 主人定,取代 316 补记九):采纳收尾同口径全层级母随子动——
# 采纳落库/换码后全库带子级行按 Σ(边含量×子价) 回算(与导入收尾同一函数),失败不挡采纳。
try:
reprice_all_lme(sc, sid)
sc.commit()
except Exception as _e:
try:
sc.rollback()
except Exception:
pass
print("采纳收尾全层级回算失败(不挡采纳):%s" % _e, flush=True)
return {"ok": True, "sid": sid, "price0": _price0,
"n_norm": len(bnorms), "n_sum": n_sum, "n_recode": n_recode, "n_att": _n_att,
"mode": "覆盖" if is_new else "追加", "price": new_price}