fix(costreview): 历史清单定额展开支持重导后按批次+哈希重定位,并后台预升级过期批次

This commit is contained in:
lianjianwei2024
2026-11-15 10:26:48 +08:00
parent 0e5785f1dc
commit 4b54ee1cfa
5 changed files with 95 additions and 13 deletions

View File

@@ -458,7 +458,19 @@ def api_adopt_list(sid=0):
finally:
c.close()
_UPGRADE_LOCK = threading.Lock() # 决策 341:采纳内升级与后台预升级互斥——同批次绝不并发重导
def _upgrade_batch_row(hc, row):
"""决策 341 薄壳:过期判断(快速路径不占锁)→ 持锁重导。采纳内升级与后台预升级共用,
绝不并发重导同一批。"""
if row["kind"] != "project" or row["x_parser_ver"] == job.PARSER_VER:
return None
with _UPGRADE_LOCK:
return _upgrade_batch_row_locked(hc, row)
def _upgrade_batch_row_locked(hc, row):
"""决策 34 的核心:把一个旧版批次行用**当前解析器**原位重导(row 需含 batches 全列)。
原位升级口径(区别于手动重导的「删旧插新」——绑定不能丢):
@@ -471,8 +483,6 @@ def _upgrade_batch_row(hc, row):
护栏:源文件缺失/内容哈希不符/加密/解析失败 → 保留旧数据只打日志,**绝不影响调用方**。
返回 None(没升级)或 {"dropped_binds": n};异常由调用方兜(本函数自己 rollback 后转 None)。
"""
if row["kind"] != "project" or row["x_parser_ver"] == job.PARSER_VER:
return None
nm = row["x_src_hash"]
path = _src_path(nm) if nm else None
if not path:
@@ -578,6 +588,53 @@ def _lme_lib_map(con, T, oid):
return {r["code"]: [r["name"], r["spec"], r["unit"], r["kind"], r["ntp"], r["taxp"]]
for r in rows if r["code"]}
def upgrade_stale_batches_once():
"""决策 341(2026-11-15 主人拍板「修下」):把解析器过期的工程批次**逐批预升级**一遍——
把 279 按需重导的一次性成本从「采纳时卡几分钟」集中到启动后台消化。只升 kind='project';
每批独立兜错(失败不挡后续);与采纳内升级共用 _upgrade_batch_row(内置互斥锁,绝不并发重导)。
返回 (已升级数, 跳过数, 总数)。测试可同步直调;服务启动走 upgrade_stale_batches_bg()。"""
hc = conn()
try:
rows = hc.execute("""SELECT * FROM batches WHERE kind='project'
AND COALESCE(x_parser_ver,'')<>? ORDER BY id""",
(job.PARSER_VER,)).fetchall()
finally:
hc.close()
up = skip = 0
for i, row in enumerate(rows):
try:
hc2 = conn()
try:
r = _upgrade_batch_row(hc2, row)
finally:
hc2.close()
if r:
up += 1
else:
skip += 1
print("279 预升级 %d/%d:批次 #%s「%s」%s"
% (i + 1, len(rows), row["id"], (row["Name"] or "")[:20],
"已升级" if r else "跳过(源件缺失/哈希不符/不可解析)"), flush=True)
except Exception as _e:
skip += 1
print("279 预升级批次 #%s 失败(不挡后续):%s" % (row["id"], _e), flush=True)
return (up, skip, len(rows))
def upgrade_stale_batches_bg():
"""决策 341:启动后台线程跑 upgrade_stale_batches_once()——先让服务就绪(3s)再动库。"""
def _bg():
time.sleep(3)
try:
up, skip, total = upgrade_stale_batches_once()
if total:
print("279 后台预升级完成:升级 %d / 跳过 %d / 共 %d 批" % (up, skip, total), flush=True)
except Exception as _e:
print("279 预升级线程异常(不挡服务):%s" % _e, flush=True)
threading.Thread(target=_bg, name="upgrade-stale-batches", daemon=True).start()
def _norm_res(con, T, norm_id):
"""一条定额下挂的工料机(**两侧唯一实现**):定额 → 消耗量 → 工料机。

View File

@@ -8616,17 +8616,32 @@ def _bill_norms(con, T, bill_id):
return {"rows": out}
def api_bill_norms(bill_id):
"""批次内:一条清单下挂的定额(批次库)"""
def api_bill_norms(bill_id, bhash=None, batch=None):
"""批次内:一条清单下挂的定额(批次库)。
决策 341(2026-11-15 主人拍板「修下」):279 按需重导会把 bills/norms 的 id 全部换新——
对比框/检索行手里攥的旧 id 展开「定额/耗」会空。前端随 ± 把手带 bhash+batch,旧 id
查不到清单行时按 **批次+内容哈希** 重定位(279 延伸同款),用新 id 取数;响应带重定位后的 bill_id。"""
c = conn()
try:
d = _bill_norms(c, TBL["batch"], bill_id)
_b = c.execute("SELECT batch_id FROM bills WHERE id=?", (bill_id,)).fetchone()
if _b is None and bhash and batch:
try:
batch = int(batch)
except (TypeError, ValueError):
batch = 0
_nb = c.execute("""SELECT id, batch_id FROM bills WHERE batch_id=? AND x_hash_exact=?
ORDER BY id DESC LIMIT 1""", (batch, bhash)).fetchone()
if _nb is not None:
bill_id = _nb["id"]
d = _bill_norms(c, TBL["batch"], bill_id)
_b = _nb
# 决策 289 补三(2026-11-09 主人定「显示哪条,耗就开他来源的工料机」):入库历史行
# 耗浮层的**子级组成**要按批次取(/api/admin/lme/res?batch_id=)——响应带上本清单
# 所属批次号,前端沿 tgHist→耗钮→浮层→± 传递,检索行/定额行本身都不用改。
_b = c.execute("SELECT batch_id FROM bills WHERE id=?", (bill_id,)).fetchone()
if _b is not None:
d["batch_id"] = _b[0]
d["bill_id"] = bill_id # 决策 341:重定位后的新 id
return d
finally:
c.close()
@@ -9255,7 +9270,7 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(_norm_res(_shared_ro("hist"), TBL["batch"], int(m.group(1))))
m = re.match(r"^/api/admin/bill/(\d+)/norms$", p)
if m:
return self._json(api_bill_norms(int(m.group(1))))
return self._json(api_bill_norms(int(m.group(1)), one.get("bhash"), one.get("batch")))
except Exception as e:
import traceback as _tb
_tb.print_exc() # 决策 288:500 带栈落日志(排查基建,不再静默)
@@ -9865,6 +9880,7 @@ def run():
print("serving on http://127.0.0.1:%d (db=%s) (PID=%d)" % (PORT, DB, os.getpid()), flush=True)
# 决策 126:端口已 listening,先让启动器/窗口走;清理回收在后台跑,慢也不再挡住开窗。
threading.Thread(target=_startup_selfheal_bg, name="startup-selfheal", daemon=True).start()
adopt_api.upgrade_stale_batches_bg() # 决策 341(主人拍板「修下」):后台逐批预升级过期批次——把采纳时的一次性重导卡顿集中到启动后台消化
srv.serve_forever()

View File

@@ -2703,7 +2703,7 @@ function renderHist(){
// ± 把手:只有历史「清单」行(带 bill_id)可展开定额 —— 同「类似清单」的交互;
// 工料机/信息价/市场价行没有下挂定额,不渲染把手列。
const tg=(!isLme && x.bill_id)
? `<span class="tog" title="展开/收起该历史清单下的定额" onclick="event.stopPropagation();tgHist(this,${x.bill_id})">+</span>`
? `<span class="tog" title="展开/收起该历史清单下的定额" onclick="event.stopPropagation();tgHist(this,${x.bill_id},'${x.bhash||''}',${x.batch_id||0})">+</span>` // 决策 341:带哈希+批次,重导换 id 后展开仍可重定位
: (!isLme && x.norms)
? `<span class="tog" title="展开/收起该清单下的定额" onclick="event.stopPropagation();tgHistSelf(this,${x.self_bill_id})">+</span>`
: '';
@@ -2765,8 +2765,11 @@ let HSEL=-1;
let HINDEP=false; // true=独立检索模式(B 方案):行来自 /api/hist/search,无匹配档位/相似度,精确度不适用
const HNORM={}; // 历史库定额缓存:bill_id → Promise<rows>(6 列:编码/名称/单位/工程量/单价/合价)
const HBATCH={}; // 决策 289 补三:bill_id → batch_id(入库耗浮层的子级组成按批次取数)
function histNorms(bid){
if(!HNORM[bid]) HNORM[bid]=fetch('/api/admin/bill/'+bid+'/norms').then(r=>r.json()).then(d=>{ HBATCH[bid]=d.batch_id||0; return (d&&d.rows)||[]; });
function histNorms(bid, bhash, batch){
/* 决策 341:279 按需重导换 id 后,行里攥的旧 bid 展开会空——随 ± 把手带 bhash+batch,
服务端旧 id 查不到时按 批次+内容哈希 重定位取新 id 的定额(前端缓存键沿用旧 bid 无妨)。 */
const q=(bhash?('?bhash='+encodeURIComponent(bhash)+'&batch='+(batch||0)):'');
if(!HNORM[bid]) HNORM[bid]=fetch('/api/admin/bill/'+bid+'/norms'+q).then(r=>r.json()).then(d=>{ HBATCH[bid]=d.batch_id||0; return (d&&d.rows)||[]; });
return HNORM[bid];
}
function pickHistRow(i,tr){
@@ -2787,7 +2790,7 @@ function hattrShow(x){
: '<div class="empty">(该清单下没有定额)</div>'; return; } // 决策 158:会话源行内联定额
if(!x.bill_id){ n.innerHTML='<div class="empty">(此行无定额)</div>'; return; }
n.innerHTML='<div class="empty">正在读取…</div>';
histNorms(x.bill_id).then(rows=>{
histNorms(x.bill_id, x.bhash, x.batch_id).then(rows=>{ // 决策 341:带哈希+批次可重定位
n.innerHTML = rows.length
? rows.map(r=>`<div class="hnorm-it" title="${esc((r[0]||'')+' '+(r[1]||''))}"><span class="nc">${esc(r[0]||'—')}</span>${esc(r[1]||'—')}</div>`).join('')
: '<div class="empty">(该清单下没有定额)</div>';
@@ -2815,7 +2818,7 @@ function tgHistSelf(el,sbid){
while(frag.firstChild) tr.parentNode.insertBefore(frag.firstChild,n2);
}
/* ± 展开一条历史清单的定额(子行列序跟 C_H 对齐:编码并入名称列,同 tgNorm 的排法) */
async function tgHist(el,bid){
async function tgHist(el,bid,bhash,batch){
const tr=el.closest('tr');
let nx=tr.nextElementSibling;
while(nx&&nx.classList.contains('hsub')){ const n2=nx.nextElementSibling; nx.remove(); nx=n2; }
@@ -2824,7 +2827,7 @@ async function tgHist(el,bid){
const _gen=(parseInt(el.dataset.gen||'0',10)||0)+1; // 决策 289 补四:代次守窗——+−+快速切换时
el.dataset.gen=String(_gen); // 第一次的迟到响应会在重展开后插行→子行重样(工作区老毛病)
try{
const rows=await histNorms(bid);
const rows=await histNorms(bid,bhash,batch); // 决策 341:带哈希+批次,重导换 id 后可重定位
if(el.dataset.gen!==String(_gen)||el.dataset.open!=='1') return; // 换代次/被收起:丢弃迟到响应
const frag=document.createElement('tbody');
frag.innerHTML = rows.length
@@ -2867,7 +2870,7 @@ function showHistTip(x, td, lmeOnly){
return;
}
if(!x.bill_id){ htip.querySelector('.htip-norms').innerHTML='<div class="tip" style="padding:4px 10px">(此行无定额)</div>'; return; }
histNorms(x.bill_id).then(ns=>{
histNorms(x.bill_id, x.bhash, x.batch_id).then(ns=>{ // 决策 341:带哈希+批次可重定位
const box=htip.querySelector('.htip-norms'); if(!box) return;
box.innerHTML = ns.length
? ns.map(n=>'<div class="hnorm-it"><span class="nc">'+esc(n[0]||'—')+'</span>'+esc(n[1]||'—')+'</div>').join('')