Files
pricing_review/CostReview/app/tools/backfill_lme_lib.py
2026-10-11 10:52:01 +08:00

145 lines
7.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""给**已导入**的历史批次补建 lme_lib(项目级工料机资源库)—— 2026-10-07。
背景:子目工料机的名称/规格此前只靠编码去 join lmes 反查,而 lmes 有两道有意的口径:
① UNIQUE(batch_id, x_hash_exact) 把同名同规格的换算编码只留第一条;
② 费用科目(人工费 / 其他材料费 / 折旧费 …)按 09-28 口径不入库。
结果消耗量里引用的编码大量查不到名称(实测批次16 缺 78 个,00010010 就是其中之一)。
新导入的批次由解析器自动写 lme_lib;**已经导入的批次**用本工具回填,不用重导。
做法:按 batches.x_src_hash 找到 data/uploads 里的源 .cos4 / .COS,重新只跑"解析"
拿到 lme_lib 全集(源文件所有工料机汇总节点),INSERT OR IGNORE 进库。
只新增 lme_lib 行,不碰 bills / lmes / norms —— 不改变任何既有口径,也不触发
「解析器版本过期需重导」提示(PARSER_VER 不动)。
会话库(session.db):会话只存源文件名不存路径,无法重解析;改用 x_batch_id 关联——
同一份文件在后台导入过就把批次的 lme_lib 复制给会话(s_lme_lib)。没关联的会话等
用户在工作台点「重新解析」时由新解析器自动补。
用法:
python tools/backfill_lme_lib.py # 实际执行
"""
import io
import os
import sqlite3
import sys
APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, APP_DIR)
sys.path.insert(0, os.path.join(APP_DIR, "core"))
import import_job # noqa: E402 (只用它的 parse_std;不碰它的 main)
ROOT_DATA = os.path.abspath(os.path.join(APP_DIR, "..", "data"))
HIST_DB = os.path.join(ROOT_DATA, "history.db")
SESS_DB = os.path.join(ROOT_DATA, "session.db")
UPLOADS = os.path.join(ROOT_DATA, "uploads")
def _seed_out():
"""parse_std 需要的计数器 / 容器(真实调用方 api_server/session_job 也是这么撒的)。"""
return {"uw": [], "bills": [], "norms": [], "lmes": [], "cur_bill": -1,
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
"lme_raw": 0, "lme_skip": 0}
def _src_path(src_hash):
"""uploads/<sha前2位>/<sha_原文件名>;找不到返回 None"""
if not src_hash:
return None
p = os.path.join(UPLOADS, src_hash[:2], src_hash)
return p if os.path.isfile(p) else None
def _apply_schema(db, schema_file):
con = sqlite3.connect(db)
con.executescript(io.open(os.path.join(APP_DIR, "store", schema_file),
encoding="utf-8").read())
con.commit()
return con
def backfill_batches():
con = _apply_schema(HIST_DB, "schema.sql")
rows = con.execute("SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
ok = miss_file = miss_hash = 0
for bid, name, src in rows:
if not src:
print(" 批次 %-3s %-24s 无源文件记录,跳过" % (bid, (name or "")[:24]))
miss_hash += 1
continue
p = _src_path(src)
if not p:
print(" 批次 %-3s %-24s 源文件不在 uploads(%s…),跳过" % (bid, (name or "")[:24], src[:12]))
miss_file += 1
continue
try:
out = _seed_out()
import_job.parse_std(p, out)
except Exception as e:
print(" 批次 %-3s %-24s 解析失败:%s" % (bid, (name or "")[:24], e))
miss_file += 1
continue
lib = out.get("lme_lib") or {}
n = 0
for code, (nm, sp, un, kd, ntp, taxp) in lib.items():
cur = con.execute(
"""INSERT OR IGNORE INTO lme_lib(batch_id, code, name, spec, unit, kind, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?)""", (bid, code, nm, sp, un, kd, ntp, taxp))
n += cur.rowcount
# 项目级工料机汇总(2026-10-07):Project.xml 原样(含项目级合计消耗量/单价)
proj = out.get("lme_proj") or {}
np_ = 0
for code, (nm, sp, un, kd, q, ntp, taxp) in proj.items():
cur = con.execute(
"""INSERT OR IGNORE INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)
VALUES(?,?,?,?,?,?,?,?,?)""", (bid, code, nm, sp, un, kd, q, ntp, taxp))
np_ += cur.rowcount
have = con.execute("SELECT COUNT(*) FROM lme_lib WHERE batch_id=?", (bid,)).fetchone()[0]
havep = con.execute("SELECT COUNT(*) FROM lme_proj WHERE batch_id=?", (bid,)).fetchone()[0]
ok += 1
print(" 批次 %-3s %-24s 资源库补 %s(现 %s)· 项目级汇总补 %s(现 %s,源文件 %s 条)"
% (bid, (name or "")[:24], n, have, np_, havep, len(proj)))
con.commit()
print("批次库回填完成:%s 个批次成功,%s 个缺源文件/失败,%s 个无源记录" % (ok, miss_file, miss_hash))
def backfill_sessions():
"""会话库:按 x_batch_id 复制批次的 lme_lib / lme_proj(同一份文件才可靠)。"""
con = _apply_schema(SESS_DB, "session.sql")
con.execute("ATTACH DATABASE ? AS hist", (HIST_DB,)) # 批次库的表跨库引用(显式 hist. 前缀)
rows = con.execute("SELECT id, name, x_batch_id FROM sessions").fetchall()
n_all = 0
for sid, name, bid in rows:
if not bid:
print(" 会话 %-3s %-24s 未关联后台批次(重新解析时自动补),跳过" % (sid, (name or "")[:24]))
continue
src = con.execute("SELECT COUNT(*) FROM hist.lme_lib WHERE batch_id=?", (bid,)).fetchone()[0]
srcp = con.execute("SELECT COUNT(*) FROM hist.lme_proj WHERE batch_id=?", (bid,)).fetchone()[0]
if not src and not srcp:
print(" 会话 %-3s %-24s 关联的批次 %s 还没有资源库,跳过" % (sid, (name or "")[:24], bid))
continue
cur = con.execute("""INSERT OR IGNORE INTO s_lme_lib(session_id, code, name, spec, unit, kind, ntp, taxp)
SELECT ?, code, name, spec, unit, kind, ntp, taxp
FROM hist.lme_lib WHERE batch_id=?""", (sid, bid))
n = cur.rowcount
cur = con.execute("""INSERT OR IGNORE INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)
SELECT ?, code, name, spec, unit, kind, qty, ntp, taxp
FROM hist.lme_proj WHERE batch_id=?""", (sid, bid))
np_ = cur.rowcount
have = con.execute("SELECT COUNT(*) FROM s_lme_lib WHERE session_id=?", (sid,)).fetchone()[0]
havep = con.execute("SELECT COUNT(*) FROM s_lme_proj WHERE session_id=?", (sid,)).fetchone()[0]
n_all += 1
print(" 会话 %-3s %-24s 资源库补 %s(现 %s)· 项目级汇总补 %s(现 %s,来自批次 %s)"
% (sid, (name or "")[:24], n, have, np_, havep, bid))
con.commit()
print("会话库回填完成:%s 个会话补上" % n_all)
if __name__ == "__main__":
print("== 批次库 history.db ==")
backfill_batches()
print("== 会话库 session.db ==")
backfill_sessions()