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

351 lines
16 KiB
Python
Raw 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 -*-
"""前后台一致性校验(防分叉)—— 把「功能一致」变成可断言的契约。
为什么需要:工作台(workbench.html) 与后台(admin.html) 要求「4 个标签功能完全一致」,
但两侧是两份 HTML。若各自维护一份列定义,改动一侧就会**静默分叉**:两边都能正常出结果,
只是结论不同,极难发现。这正是 2026-10-01 重构前两侧列数不一致(12 vs 7)的根因。
硬规则:入口功能一致(4 个标签),数据流与数据库独立(session.db / history.db)。
→ 因此「渲染逻辑、列定义、标签顺序、样式」必须只有一份(common.js / common.css);
「API 地址、库名」允许不同,且**只允许**不同在 WB_OPTS 与 RawView 配置里。
守护方式(七道闸):
闸1:两侧都必须引入 common.js / common.css
闸2:两侧都**不得**再自带列定义(不许出现第二份实现)
闸3:common.js 的列与后端 BILLROW() 的字段互为映射
闸4:两侧都不得自带基础工具(esc / num / fmtAttr / headHTML / colgHTML)
闸5:两侧都不得自带渲染实现(billTR / grpTR / grpTitle / tgGrp / tgNorm / renderLme
/ 原数据的 rawTbl/rawProj/rawSec/rawUw/drawRawTree 等)—— 一律由 common.js 提供
闸6:标签不得硬编码 data-p(顺序/名称由 common.js 的 TABS 唯一决定)
闸7:后端两套接口的**行结构必须一致**(lme 10 列、定额 6 列),否则共用渲染会错位
用法:
python check_parity.py # 有问题时退出码 1
"""
import io, os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
UI = os.path.join(ROOT, "ui")
SERVER = os.path.join(ROOT, "server")
# 清单表里必须能映射到后端 BILLROW() 字段的列名(缺一个就说明列被删了 / 后端字段没跟上)
BILL_REQUIRED = ["序号", "编码", "名称", "项目特征", "单位",
"工程量", "单价", "合价", "单位工程名称"]
LME_REQUIRED = ["序号", "编码", "名称", "规格型号", "单位",
"数量", "除税编制价", "税率", "含税编制价", "备注"]
# ↑「类型」2026-10-08 起不显示(后端仍返回在 r[9],显示 10 列含备注)——要求列表随显示列走
def _read(p):
with io.open(p, encoding="utf-8") as f:
return f.read()
def _block(src, name):
"""取出 `const NAME = [ ... ];` 的内容块。"""
m = re.search(r"const\s+%s\s*=\s*\{(.*?)\n\};" % name, src, re.S)
return m.group(1) if m else None
def _col_names(block, key):
"""从 COLS 定义里取某个键(bill/lme)的列名:['序号',52,'c'] → 序号。
用**括号平衡**截到该数组真正的结尾 —— 不能用非贪婪正则,列定义跨多行时
(`['类别',52,'c'],\\n ['单位工程名称'…`)会在第一行末尾就误截断,报出假缺列。
"""
m = re.search(r"%s\s*:\s*\[" % key, block)
if not m:
return None
depth, i = 1, m.end()
while i < len(block) and depth > 0:
if block[i] == "[":
depth += 1
elif block[i] == "]":
depth -= 1
i += 1
return re.findall(r"\[\s*'([^']*)'", block[m.end():i - 1])
def main():
wb = _read(os.path.join(UI, "workbench.html"))
ad = _read(os.path.join(UI, "admin.html"))
cm = _read(os.path.join(UI, "common.js"))
api = _read(os.path.join(SERVER, "api_server.py"))
problems = []
# 注:workbench_map.html 已于 2026-10-01 废弃(它是 gen_workbench_map.py 从 workbench.html
# 自动生成的「区块编号标注版」,非独立入口,且长期过期),移入 ui/_deprecated/。
# 校验范围收敛为**两个真实入口**:工作台 + 后台。
# 闸1:两侧都引入 common.js / common.css
for tag, src in (("工作台", wb), ("后台", ad)):
if "common.js" not in src:
problems.append("%s未引入 common.js" % tag)
if "common.css" not in src:
problems.append("%s未引入 common.css" % tag)
# 闸2:两侧不得自带第二份列定义
if re.search(r"const\s+C_BILL\s*=\s*\[", wb):
problems.append("工作台仍自带 C_BILL 定义(应改为 C_BILL = COLS.bill)")
if re.search(r"const\s+COL_BILL\s*=\s*\[", ad):
problems.append("后台仍自带 COL_BILL 定义(应改为 colsObjs(COLS.bill))")
if re.search(r"const\s+C_LME\s*=\s*\[", wb):
problems.append("工作台仍自带 C_LME 定义(应改为 C_LME = COLS.lme)")
if re.search(r"const\s+COL_LME\s*=\s*\[", ad):
problems.append("后台仍自带 COL_LME 定义(应改为 colsObjs(COLS.lme))")
# 闸4/闸5:两侧不得自带基础工具与渲染实现(这些必须只有 common.js 一份)
FORBIDDEN = [
(r"function\s+esc\s*\(", "esc"),
(r"function\s+num\s*\(", "num"),
(r"function\s+fmtAttr\s*\(", "fmtAttr"),
(r"function\s+headHTML\s*\(", "headHTML"),
(r"function\s+colgHTML\s*\(", "colgHTML"),
(r"function\s+billTR\s*\(", "billTR"),
(r"function\s+grpTR\s*\(", "grpTR"),
(r"function\s+grpTitle\s*\(", "grpTitle"),
(r"function\s+tgGrp\s*\(", "tgGrp"),
(r"async function\s+tgNorm\s*\(|function\s+tgNorm\s*\(", "tgNorm"),
(r"function\s+renderLme\s*\(", "renderLme"),
(r"function\s+renderGroups\s*\(", "renderGroups"),
(r"function\s+rawTbl\s*\(", "rawTbl"),
(r"function\s+rawKV\s*\(", "rawKV"),
(r"function\s+rawProj\s*\(", "rawProj"),
(r"function\s+rawSec\s*\(", "rawSec"),
(r"function\s+rawUw\s*\(", "rawUw"),
(r"function\s+rawTreeHTML\s*\(", "rawTreeHTML"),
(r"function\s+rawTog\s*\(", "rawTog"),
(r"function\s+drawRawTree\s*\(", "drawRawTree"),
(r"async function\s+rawDraw\s*\(|function\s+rawDraw\s*\(", "rawDraw"),
]
for tag, src in (("工作台", wb), ("后台", ad)):
for pat, name in FORBIDDEN:
if re.search(pat, src):
problems.append("%s仍自带 %s()(应改为调用 common.js 的那一份)" % (tag, name))
# 闸6:标签不得硬编码(顺序/名称由 common.js 的 TABS 唯一决定)
for tag, src in (("工作台", wb), ("后台", ad)):
if re.search(r'<div class="tab[^"]*" data-p="p\d"', src):
problems.append("%s仍硬编码标签 <div class=\"tab\" data-p=...>(应改用 tabsHTML())" % tag)
# 公共层的标签顺序必须齐全
if not re.search(r"p:\s*'p3'.*p:\s*'p2'.*p:\s*'p1'.*p:\s*'p0'", cm, re.S):
problems.append("common.js 的 TABS 顺序不是 原数据→类似清单→组价不一致清单→项目工料机")
# 闸3:common.js 的列 与 后端字段映射
blk = _block(cm, "COLS")
if not blk:
problems.append("common.js 里找不到 COLS 定义")
else:
cb, cl = _col_names(blk, "bill"), _col_names(blk, "lme")
if not cb or not cl:
problems.append("common.js 的 COLS.bill / COLS.lme 解析失败")
else:
miss_b = [c for c in BILL_REQUIRED if c not in cb]
miss_l = [c for c in LME_REQUIRED if c not in cl]
if miss_b:
problems.append("COLS.bill 缺列:%s" % "、".join(miss_b))
if miss_l:
problems.append("COLS.lme 缺列:%s" % "、".join(miss_l))
# 后端:分组算法必须唯一;_billrow 与 BILLROW 列数必须相同
if api.count("def _group_by_keywords") != 1:
problems.append("_group_by_keywords 不是唯一实现(分组算法只能有一份)")
m1 = re.search(r"def _billrow\(x\):(.*?)\n\n", api, re.S)
m2 = re.search(r"def BILLROW\(x\):(.*?)\n\n", api, re.S)
if m1 and m2:
n1 = len(re.findall(r'x\["', m1.group(1)))
n2 = len(re.findall(r'x\["', m2.group(1)))
if n1 != n2:
problems.append("后端行数组列数不一致:_billrow=%d,BILLROW=%d(必须同步改)"
% (n1, n2))
# 闸7:后端两套接口的**行结构必须一致**(共用 common.js 渲染,错位就是静默错误)
def _sql_cols(fn):
"""取函数里 SELECT ... FROM 之间的列名个数(粗略但足够抓出 7 列 vs 10 列这类分叉)"""
m = re.search(r"def\s+%s\((.*?)\n\n\n" % fn, api, re.S)
if not m:
return None
s = re.search(r"SELECT\s+(.*?)\s+FROM", m.group(1), re.S)
if not s:
return None
cols = [c.strip() for c in s.group(1).replace("\n", " ").split(",") if c.strip()]
return [c.split()[-1] for c in cols] # 去掉 AS 别名前的东西,保留最终名
# 行结构由**公共实现**保证(两侧入口已是薄封装),所以直接查公共函数的列数
lm = _sql_cols("_lme_rows")
if lm and len(lm) != 10:
problems.append("_lme_rows 返回 %d 列(应为 10)→ renderLme() 会错位" % len(lm))
bn = _sql_cols("_bill_norms")
if bn and len(bn) != 6:
problems.append("_bill_norms 返回 %d 列(应为 6)→ tgNorm() 会错位" % len(bn))
# 闸8:后端的同功能接口必须走**同一个公共实现**(TBL 表映射 + _xxx 函数),不得各写一份 SQL
COMMON = ["_raw_tree", "_raw_proj", "_raw_sec", "_raw_uw", "_lme_rows", "_bill_norms"]
for fn in COMMON:
if api.count("def %s(" % fn) != 1:
problems.append("公共实现 %s() 定义数=%d(必须恰好 1 份)" % (fn, api.count("def %s(" % fn)))
if "TBL = {" not in api:
problems.append("后端缺少 TBL 表映射(数据流独立的唯一表达方式)")
# 两侧入口必须是「薄封装」:函数体里不该再有 FROM <具体表名>
for fn in ("api_raw_tree", "api_admin_raw_tree", "api_raw_proj", "api_admin_raw_proj",
"api_raw_sec", "api_admin_raw_sec", "api_raw_uw", "api_admin_raw_uw",
"api_lme_rows", "api_bill_norms", "api_session_bill_norms"):
m = re.search(r"\ndef %s\(.*?\n(?=\ndef |\Z)" % fn, api, re.S)
if m:
body = m.group(0)
if re.search(r"FROM\s+(s_bills|s_norms|s_lmes|s_divides|s_sections|s_unit_works|sessions)", body):
problems.append("%s() 仍在函数体里直接查会话表(应改为调用公共实现)" % fn)
if re.search(r"FROM\s+(bills|norms|lmes|divides|sections|unit_works|batches)", body):
problems.append("%s() 仍在函数体里直接查批次表(应改为调用公共实现)" % fn)
# 闸9:两套 schema 必须能**各自独立建库**,且结构对齐
# (2026-10-01 教训:schema.sql 长期不完整,缺表缺列,一旦重建库就全线报错)
problems.extend(_check_schema())
# 闸10:xml 格式已于 2026-10-01 停止支持 —— 解析器不得复活,入口必须显式拦截
if re.search(r"^\s*def parse_old\(", api, re.M):
problems.append("parse_old() 又出现了:xml 已停止支持,该解析器不应复活")
if 'if st == "xml"' not in api:
problems.append("api_import 缺少 xml 拦截(删除 parse_old 后,传 xml 会直接 500)")
job = _read(os.path.join(ROOT, "core", "import_job.py"))
if 'from xml.etree import ElementTree as ET' not in job:
problems.append("import_job.py 丢了 ElementTree 导入 —— cos4 是 zip 包、内部就是 xml,"
"parse_std 依赖它,删了会导致 cos4 也导不进来")
if problems:
print("[FAIL] 前后台存在分叉:")
for p in problems:
print(" - " + p)
return 1
print("[OK] 前后台结构一致(列定义唯一来源 common.js,分组算法唯一,两套 schema 可独立建库)")
return 0
# ---------------------------------------------------------------------------
# 闸9:两套库的 schema 结构
# ---------------------------------------------------------------------------
# 两库「核心业务列」必须一致(ID 列不同是数据流独立的正常差异,不比)
# 注意:主表 batches/sessions 本就不同(跨期次检索 vs 当期会话),不做全等比对
MUST_COLS = {
("bills", "s_bills"): ["Number", "Name", "Attr", "Unit", "Quantity", "Price",
"Total", "Kind", "x_name_norm", "x_attr_norm", "x_unit_norm",
"x_hash_exact", "x_seq"],
("norms", "s_norms"): ["Number", "Name", "Unit", "Quantity", "Price", "Total"],
("lmes", "s_lmes"): ["Number", "Name", "Specification", "Unit", "Quantity",
"NoTaxPrice", "TaxRate", "TaxPrice", "Kind",
"x_name_norm", "x_spec_norm", "x_unit_norm", "x_hash_exact"],
("unit_works", "s_unit_works"): ["Number", "Name", "Total",
"DivisionalAndElementalWorks", "Preliminaries",
"CostForHSE", "SundryCosts", "Tax"],
("sections", "s_sections"): ["Number", "Name", "Total"],
("divides", "s_divides"): ["Number", "Name", "Kind", "parent_id", "Total", "x_seq"],
("norm_res", "s_norm_res"): ["res_code", "qty"],
("remarks", "s_remarks"): ["rkey", "src_key"],
}
def _build_mem(sql_path):
"""用 schema 文件建一个临时库,返回 (连接, 错误)"""
import tempfile
try:
sql = _read(sql_path)
except Exception as e:
return None, "读不到 %s:%s" % (os.path.basename(sql_path), e)
p = os.path.join(tempfile.gettempdir(), "_parity_%s.db" % os.path.basename(sql_path))
if os.path.exists(p):
try:
os.remove(p)
except Exception:
pass
try:
import sqlite3
c = sqlite3.connect(p)
c.executescript(sql)
return c, None
except Exception as e:
return None, "%s 建库失败:%s" % (os.path.basename(sql_path), e)
def _tables(c):
return [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")]
def _cols(c, t):
try:
return [r[1] for r in c.execute("PRAGMA table_info(%s)" % t)]
except Exception:
return None
def _tbl_map(api_src):
"""从 api_server.py 的 TBL 里抽出两侧的表名(供「表必须存在」检查用)"""
m = re.search(r"TBL = \{(.*?)\n\}", api_src, re.S)
if not m:
return None
body = m.group(1)
out = {}
for scope in ("session", "batch"):
seg = re.search(r'"%s":\s*\{(.*?)\}' % scope, body, re.S)
if not seg:
continue
out[scope] = [v for k, v in re.findall(r'"(\w+)":\s*"([^"]+)"', seg.group(1))
if k not in ("idcol", "pname")]
return out or None
def _check_schema():
"""闸9:两套 schema 可独立建库 + 核心列对齐 + TBL 引用的表都存在"""
bad = []
API = os.path.join(SERVER, "api_server.py")
SCH_B = os.path.join(ROOT, "store", "schema.sql") # 批次库(后台/长期)
SCH_S = os.path.join(ROOT, "store", "session.sql") # 会话库(工作台/临时)
cb, e1 = _build_mem(SCH_B)
cs, e2 = _build_mem(SCH_S)
if e1:
bad.append(e1)
if e2:
bad.append(e2)
if not cb or not cs:
return bad
try:
tb, ts = _tables(cb), _tables(cs)
# 9a:TBL 里引用的每一张表,必须在对应 schema 建出的库里存在
tm = _tbl_map(_read(API))
if not tm:
bad.append("api_server.py 里解析不到 TBL 表映射")
else:
for t in tm.get("batch", []):
if t not in tb:
bad.append("批次库 schema.sql 缺表 %s(TBL['batch'] 会查它)" % t)
for t in tm.get("session", []):
if t not in ts:
bad.append("会话库 session.sql 缺表 %s(TBL['session'] 会查它)" % t)
# 9b:核心业务列必须两边都有
for (a, b), cols in MUST_COLS.items():
ca, cbb = _cols(cb, a), _cols(cs, b)
if ca is None:
bad.append("批次库缺表 %s" % a)
continue
if cbb is None:
bad.append("会话库缺表 %s" % b)
continue
miss_a = [c for c in cols if c not in ca]
miss_b = [c for c in cols if c not in cbb]
if miss_a:
bad.append("%s(批次库)缺列:%s" % (a, "、".join(miss_a)))
if miss_b:
bad.append("%s(会话库)缺列:%s" % (b, "、".join(miss_b)))
finally:
cb.close()
cs.close()
return bad
if __name__ == "__main__":
sys.exit(main())