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('')

View File

@@ -1269,3 +1269,8 @@ ESCC2.0 散装 xml 原格式导出=同一手术引擎扩展到单文件(tran
- **口径**:主人实录「输入建设单位/项目名称框短词不中,整串才中」→ 确认决策 141 的 `bt.Name IN` 精确匹配口径后拍板改:**输入的每个字(norm 归一去重)都出现在批次项目名/建设单位里即命中,与顺序无关**;**按输入顺序连续出现**(如「金宝」连续 ⊇ 「宝金」散字)的行**排序置顶**(pord 键:连续=2 散字=1)。作用面=四入口统一(match_bill/match_lme/hist_search/hist_search_lme 的 units+projs 筛选;工料机侧建设单位=orgs 联查仅排序层联动)。取代决策 141 的「精确 IN」匹配方式。
- **落地**:match.py `_filters` units/projs 分支改 instr 逐字 AND(batches 小表,毫秒级,随后走索引);`char_hit_level/proj_unit_kws` 助手;四入口排序挂 pord(match_bill/match_lme 主键位、两检索 kwrank 后次位);无筛选时 pord 恒 0 顺序与旧完全一致。**修一表别名错**:hist_search pord 列首版写 `b.BulidUnit`(bills 无此列)→ 端到端 0 行/500 抓出 → 改 `bt.BulidUnit`。
- **测试**:新增 `test_match_projunit_340.py` 4 用例(字集不分顺序命中+连续置顶/缺字不中/建设单位同款/无筛选顺序不变);pytest 全量 **455 passed** 退出码 0(451+新增 4);隔离实例 HTTP 端到端 **PASS**——主人场景复刻:项目名称框输「金宝」两字命中『金宝改造项目装修工程副本』(修复前空),整串照常命中。
## 决策 341(2026-11-15,主人拍板「修下」):展开定额按批次+哈希重定位+后台预升级过期批次
- **背景(主人实录三症状一并查实)**:①对比框历史行展开「该清单下没有定额」、耗没了;②采纳点了很久一直「采纳中…」;③采纳源的单价会变动。三症状同根因=**决策 279 按需重导**:决策 322-333 落地把 PARSER_VER 升到 2026.11.14-1 → 老批次第一次被采纳自动原位重导整批(生产库批次 #14「金宝改造项目」3535 bills/3403 norms,2026-11-15 09:42:44 重导实证)→ 重导期间采纳挂起(a)、单价按 329 新口径重算(c)、bills/norms id 全变 → 对比框/检索行攥旧 id 展开定额/耗查旧 id 为空(b)。**非 337-340 所致**(其全在检索/展示层;批次库写路径只有 279 重导)。主人指示:一次性成本不再修;两件后续问题拍板「修下」。
- **落地**:①展开重定位——`api_bill_norms(bill_id, bhash, batch)`:旧 id 查不到清单行时按 批次+内容哈希 重定位(279 延伸同款),响应带新 bill_id;路由读 GET 参数;前端 histNorms(bid,bhash,batch)+± 把手/悬停提示两处传参(决策 341 注)。②后台预升级——adopt_api `_UPGRADE_LOCK` 互斥锁薄壳(`_upgrade_batch_row` 过期早退不占锁→持锁调 `_upgrade_batch_row_locked`)+`upgrade_stale_batches_once/bg`(逐批预升级 kind='project' 过期批次,每批独立兜错,启动后台线程跑,adopt_api.upgrade_stale_batches_bg 挂 run() 自愈线程旁)——把 12 个存量老批次的采纳时卡顿集中到启动后台消化。
- **测试**:新增 `test_upgrade_relocate_341.py`(真件导入→置过期→采纳触发重导换 id→旧 id 带 bhash/batch 展开重定位命中+预升级函数升级到当前解析器);node --check 三脚本块+py_compile 全过;pytest 全量 **456 passed** 退出码 0。另证:重导后旧 bill_id 的 norms 孤儿残留(另一会话重导实现细节,未清孤儿行)——展示层已由重定位兜住,孤儿清理不另立决策。

View File

@@ -161,3 +161,4 @@
| 338 | 决策 338(2026-11-15,主人拍板):批次库 bills 补次精确档索引 ix_bill_semi(对齐 lmes/prices;schema.sql+migrate_match_keys 双落点,老库启动自动补)——20 万行实测次精确档 33ms→0.1ms(362 倍),治「大库点清单全表扫」;②模糊档去 LIKE/③慢档护栏等主人另定 | 1257 | 1260 |
| 339 | 决策 339(2026-11-15,主人拍板「继续」):模糊档去前置通配——导入落前缀列 x_name_pre(match.name_pre=norm 前 6 字)+等值+索引;固化语义变化=名称开头同前 6 字才入模糊档(中段含词不再入;工料机侧不动);③独立检索 5 秒扫描护栏超时降级(前端零改动);导入参数错位事故端到端抓出修正;test_match_namepre_339 4 用例+pytest 451 passed+端到端 PASS;补记一=启动事故快速修复(回填撤除、补列提前) | 1262 | 1266 |
| 340 | 决策 340(2026-11-15,主人拍板):项目名称/建设单位筛选改「字集包含+输入顺序连续优先」(取代 141 精确 IN)——每字都出现即中(instr 逐字 AND,batches 小表毫秒级);连续出现(pord=2)排最前、散字(pord=1)排后;四入口统一;修 b.BulidUnit 表别名错;test_match_projunit_340 4 用例+pytest 455 passed+HTTP 端到端 PASS(金宝短词命中) | 1268 | 1271 |
| 341 | 决策 341(2026-11-15,主人拍板「修下」):①对比框/检索行展开定额按 批次+内容哈希 重定位(api_bill_norms 带 bhash/batch,279 重导换 id 后旧 id 展开不再空,前端 ±/悬停随传);②启动后台逐批预升级过期批次(_UPGRADE_LOCK 互斥薄壳+upgrade_stale_batches_once/bg,把 279 一次性重导卡顿集中到后台消化)——三症状(展开空/采纳中很久/源单价变动)查实=279 按需重导一次性升级,非 337-340 所致;test_upgrade_relocate_341+pytest 456 passed | 1273 | 1276 |