rule_check.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. SKU 审核规则一致性核验工具
  5. =========================
  6. 用途:规则文档(飞书 docx)与训练校准工具包(xlsx)之间的自动比对。
  7. 每次规则变更后跑一遍,确认判定表没有落后于规则。
  8. 用法:
  9. python3 rule_check.py fetch # 拉取最新规则并保存快照,与上一版比对
  10. python3 rule_check.py verify # 核对工具包是否与最新规则一致
  11. python3 rule_check.py all # 上面两步一起跑(默认)
  12. python3 rule_check.py verify --workbook 路径 --report 输出.xlsx
  13. 凭证(按顺序取第一个可用来源,不会写入任何输出):
  14. 1) 环境变量:FEISHU_APP_ID / FEISHU_APP_SECRET
  15. 2) 文件:~/.sku_audit/credentials.json {"app_id": "...", "app_secret": "..."}
  16. 3) 文件:技能包根目录 credentials.json(托管沙箱随包提供,格式同上)
  17. 退出码:
  18. 0 = 全部通过
  19. 1 = 存在偏差(需处理)
  20. 2 = 执行错误(取凭证/拉文档/读表格失败)
  21. """
  22. import argparse
  23. import json
  24. import os
  25. import re
  26. import sys
  27. import difflib
  28. from datetime import datetime
  29. try:
  30. import requests
  31. except ImportError:
  32. print("缺少依赖:pip3 install requests", file=sys.stderr)
  33. sys.exit(2)
  34. DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc"
  35. _HERE = os.path.dirname(os.path.abspath(__file__))
  36. if _HERE not in sys.path:
  37. sys.path.insert(0, _HERE)
  38. import feishu_credentials # noqa: E402
  39. import kit_path # noqa: E402
  40. def _pick_workbook():
  41. """取版本号最高的工具包;找不到时返回期望的文件名模式,供报错提示"""
  42. return kit_path.find() or os.path.join(kit_path.ASSET_DIRS[0], kit_path.PATTERN)
  43. DEFAULT_WB = _pick_workbook()
  44. HOME_DIR = os.path.expanduser("~/.sku_audit")
  45. SNAP_DIR = os.path.join(HOME_DIR, "snapshots")
  46. # ---------------- 规则要素清单(文档应包含、工具包应覆盖) ----------------
  47. HARD_RULES = ["R-001", "R-002", "R-003", "R-004", "R-005", "R-006", "R-007"]
  48. FZ_ITEMS = ["FZ-01", "FZ-02", "FZ-03", "FZ-04", "FZ-05", "FZ-06"]
  49. # 应付编码合并清单:应付中文品名 -> 编码(文档原文口径)
  50. PAY_EXPECT = {
  51. "灯泡": "8539.52.0091",
  52. "装饰灯": "8539.22.8030",
  53. "装饰品": "9505.10.5020",
  54. "塑料餐具": "3924.10.4000",
  55. "塑料盒": "3924.90.5650",
  56. }
  57. # 关键话术 / 关键概念:(文档中的写法, 工具包中的写法, 说明)
  58. # 双向核对:文档没有该写法说明本清单已过期;工具包没有说明判定表落后于规则。
  59. KEY_TOKENS = [
  60. ("未上传产品图片", "未上传产品图片", "无图驳回话术"),
  61. ("品牌栏却填", "品牌栏却填", "品牌标识驳回话术"),
  62. ("Lab ID", "Lab ID", "CPC 实验室编号要求"),
  63. ("测试结束日", "测试结束日", "CPC 有效期按测试报告结束日起算"),
  64. ("第三方测试报告", "第三方测试报告", "CPC 两件套"),
  65. ("撤销名单", "撤销名单", "CPSC 名单未提供时转待核实"),
  66. ("FDA申报+认证", "FDA申报+认证", "FDA 申报+认证规则"),
  67. ("历史相似产品", "历史相似产品", "历史相似产品匹配定义"),
  68. ("明确禁配项", "禁配", "应收编码驳回条件"),
  69. ("历史数据最低应收单价", "最低应收单价", "应收单价不低于历史最低"),
  70. ("产品附加费", "产品附加费", "产品附加费规则"),
  71. ("取最高的收取", "取最高的收取", "产品附加费多档取最高"),
  72. ("普货", "普货", "普货判断"),
  73. ("应付", "应付", "应付编码/单价"),
  74. ("手表", "手表", "手表品类转人工"),
  75. ("目的国", "目的国", "目的国限美国"),
  76. ]
  77. # 工具包执行表(02/04/05/06)声称的口径必须仍有文档依据:(工具包写法, 文档写法, 说明)
  78. # 文档写法要与工具包口径同样具体,避免文档里其他地方顺带出现的短词把过期口径掩盖掉。
  79. KIT_CLAIMS = [
  80. ("二档=无", "二档=无", "关税附加费二档并入无"),
  81. ("税率标签", "税率标签", "关税附加费按税率标签判档"),
  82. ("箱规", "箱规信息判断", "按箱规判断单价合理性"),
  83. ("手表类", "手表类", "应付清单含手表类"),
  84. ("USD/双", "USD/双", "单价按双计"),
  85. ("空档", "空档", "单价空档"),
  86. ]
  87. # 文档条款 → 02 表对应项必须体现的口径:(文档正则, 判定表项号, 列, 必含写法, 说明)
  88. TOPIC_LINKS = [
  89. (r"用途过于宽泛→待核实", "18", 3, "待核实", "R-005 用途宽泛→待核实"),
  90. (r"商品属性、品名或用途命中玩具、儿童、婴儿", "20", 2, "儿童", "玩具认证触发含儿童/婴儿"),
  91. (r"缺少任一文件,均按不合格处理", "27", 2, "缺任一", "CPC 两件缺一不合格"),
  92. (r"无法核验名单状态时转待核实", "34", 2, "待核实", "CPSC 名单无法核验转待核实"),
  93. (r"有效期按第三方测试报告载明的测试结束日", "35", 2, "测试结束日", "CPC 有效期起算点"),
  94. (r"仅在存在明确禁配项", "36", 2, "禁配", "应收编码驳回条件"),
  95. (r"不可小于历史数据最低应收单价", "46", 2, "历史", "应收单价历史最低"),
  96. (r"应收单价 ≤ 1", "48", 2, "≤ 1", "应付单价等于 1 并入等值档"),
  97. (r"关税附加费规则(按历史相似产品", "50", 2, "历史", "关税附加费按历史相似产品"),
  98. (r"历史相似产品匹配定义", "60", 2, "品类", "历史相似产品匹配口径"),
  99. (r"判断本 SKU 是否需要勾选“FDA申报\+认证”", "61", 2, "历史", "FDA 申报+认证历史判断"),
  100. (r"命中手表品类时,直接转人工审核,不填写应付清关编码", "P2", 4, "不填写应付清关编码", "手表不填应付编码"),
  101. ]
  102. HTS_RE = re.compile(r"\b\d{4}\.\d{2}\.\d{4}\b")
  103. # ---------------- 基础工具 ----------------
  104. def die(msg, code=2):
  105. print(f"[错误] {msg}", file=sys.stderr)
  106. sys.exit(code)
  107. def load_credentials():
  108. return feishu_credentials.load() or die(feishu_credentials.missing_message())
  109. def get_token(app_id, app_secret):
  110. try:
  111. r = requests.post(
  112. "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
  113. json={"app_id": app_id, "app_secret": app_secret}, timeout=20)
  114. d = r.json()
  115. except Exception as e:
  116. die(f"获取 token 失败:{e}")
  117. if d.get("code") != 0:
  118. die(f"获取 token 失败:code={d.get('code')} msg={d.get('msg')}")
  119. return d["tenant_access_token"]
  120. def fetch_doc(doc_id, token):
  121. url = f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/raw_content"
  122. try:
  123. r = requests.get(url, headers={"Authorization": "Bearer " + token}, timeout=30)
  124. d = r.json()
  125. except Exception as e:
  126. die(f"拉取文档失败:{e}")
  127. if d.get("code") != 0:
  128. die(f"拉取文档失败:code={d.get('code')} msg={d.get('msg')}(检查应用是否有该文档读权限)")
  129. content = (d.get("data") or {}).get("content", "")
  130. if not content:
  131. die("文档内容为空")
  132. return content
  133. def normalize(text):
  134. """去掉行首缩进和空行,便于比对"""
  135. lines = [ln.strip() for ln in text.split("\n")]
  136. return "\n".join([ln for ln in lines if ln])
  137. def save_snapshot(content):
  138. os.makedirs(SNAP_DIR, exist_ok=True)
  139. ts = datetime.now().strftime("%Y%m%d_%H%M%S")
  140. path = os.path.join(SNAP_DIR, f"doc_{ts}.txt")
  141. open(path, "w", encoding="utf-8").write(content)
  142. return path
  143. def latest_snapshot(before=None):
  144. if not os.path.isdir(SNAP_DIR):
  145. return None
  146. files = sorted(f for f in os.listdir(SNAP_DIR) if f.startswith("doc_") and f.endswith(".txt"))
  147. if before:
  148. files = [f for f in files if f != before]
  149. return os.path.join(SNAP_DIR, files[-1]) if files else None
  150. # ---------------- 文档变更检测 ----------------
  151. PACKAGED_SNAPSHOT = os.path.join(os.path.dirname(_HERE), "references", "doc-snapshot.txt")
  152. def print_diffs(title, old, new, quiet=False):
  153. a = normalize(old).split("\n")
  154. b = normalize(new).split("\n")
  155. diffs = [ln for ln in difflib.unified_diff(a, b, lineterm="", n=0)
  156. if ln.startswith(("+", "-")) and not ln.startswith(("+++", "---"))]
  157. if quiet:
  158. return diffs
  159. print(f"{title}检测到 {len(diffs)} 行差异:")
  160. for ln in diffs[:40]:
  161. flag = "新增" if ln.startswith("+") else "删除"
  162. print(f" [{flag}] {ln[1:][:100]}")
  163. if len(diffs) > 40:
  164. print(f" ... 另有 {len(diffs) - 40} 行")
  165. return diffs
  166. def cmd_fetch(doc_id, token, quiet=False):
  167. """两条基线:上一次本地拉取(看规则是否刚变),技能包同步基线(看工具包是否已跟上)。
  168. 只比本地快照会出现盲区:规则改动后第一次拉取建立的快照已是新版,
  169. 此后每次都显示「一致」,但技能包从未同步过。
  170. """
  171. content = fetch_doc(doc_id, token)
  172. prev = latest_snapshot()
  173. old = open(prev, encoding="utf-8").read() if prev else None
  174. snap = save_snapshot(content)
  175. result = {"first": old is None, "changed": False, "changes": [], "snapshot": snap,
  176. "package_synced": None, "package_changes": [], "content": content}
  177. if old is None:
  178. if not quiet:
  179. print("【文档变更】首次建立本地快照,无本地历史可比对")
  180. elif normalize(old) == normalize(content):
  181. if not quiet:
  182. print(f"【文档变更】与上一次本地拉取一致({len(content)} 字符)")
  183. else:
  184. result["changed"] = True
  185. result["changes"] = print_diffs("【文档变更】与上一次本地拉取相比", old, content, quiet)
  186. if os.path.exists(PACKAGED_SNAPSHOT):
  187. base = open(PACKAGED_SNAPSHOT, encoding="utf-8").read()
  188. synced = normalize(base) == normalize(content)
  189. result["package_synced"] = synced
  190. if synced:
  191. if not quiet:
  192. print("【同步基线】与技能包同步基线一致(references/doc-snapshot.txt),工具包已按当前规则同步")
  193. else:
  194. result["package_changes"] = print_diffs(
  195. "【同步基线】技能包尚未同步到当前规则,与 references/doc-snapshot.txt 相比", base, content, quiet)
  196. elif not quiet:
  197. print("【同步基线】技能包缺少 references/doc-snapshot.txt,无法确认工具包是否已同步")
  198. return result
  199. # ---------------- 工具包核验 ----------------
  200. def sheet_text(ws):
  201. out = []
  202. for row in ws.iter_rows(values_only=True):
  203. for v in row:
  204. if v is not None:
  205. out.append(str(v))
  206. return "\n".join(out)
  207. # 执行表中参与判定的列(1 起);说明、备注、依赖规则、历史记录列不计入
  208. EXEC_COLUMNS = {"02": (2, 3, 4, 5), "04": (3, 4, 5), "05": (2,), "06": (4, 5, 6)}
  209. def executable_text(wb):
  210. out = []
  211. for name in wb.sheetnames:
  212. cols = EXEC_COLUMNS.get(name[:2])
  213. if not cols:
  214. continue
  215. for row in wb[name].iter_rows(min_row=2, values_only=True):
  216. for c in cols:
  217. if len(row) >= c and row[c - 1] is not None:
  218. out.append(str(row[c - 1]))
  219. return "\n".join(out)
  220. def compact(text):
  221. """去掉空白与中英文标点差异后再比较原文"""
  222. return re.sub(r"[\s、,,;;。..:://]+", "", str(text or "")).replace("$", "")
  223. def parse_doc_price_limits(doc_text):
  224. """从「海关编码限制单价清单」段解析 编码 → 限制条件原文"""
  225. start = doc_text.find("海关编码限制单价清单")
  226. if start < 0:
  227. return {}
  228. end = doc_text.find("应付单价", start)
  229. lines = [ln.strip() for ln in doc_text[start:end if end > 0 else None].split("\n") if ln.strip()]
  230. out, code = {}, None
  231. for ln in lines[1:]:
  232. if HTS_RE.fullmatch(ln):
  233. code = ln
  234. elif code:
  235. out[code] = ln
  236. code = None
  237. return out
  238. def cmd_verify(doc_text, workbook_path, report_path=None, quiet=False):
  239. try:
  240. import openpyxl
  241. except ImportError:
  242. die("缺少依赖:pip3 install openpyxl")
  243. if not os.path.exists(workbook_path):
  244. die(f"找不到工具包:{workbook_path}")
  245. wb = openpyxl.load_workbook(workbook_path)
  246. whole = "\n".join(sheet_text(wb[s]) for s in wb.sheetnames)
  247. results = [] # (类别, 检查项, 状态, 说明)
  248. def add(cat, item, ok, note, warn=False):
  249. results.append((cat, item, "⚠️" if warn else ("✅" if ok else "❌"), note))
  250. # 1. 规则要素
  251. for r in HARD_RULES:
  252. add("规则要素", f"核心规则 {r}", r in whole,
  253. "文档有、工具包有" if r in whole else "工具包缺失该规则")
  254. for f in FZ_ITEMS:
  255. add("规则要素", f"图片判定 {f}", f in whole,
  256. "已覆盖" if f in whole else "工具包缺失该项")
  257. # 2. 应付编码映射(双向)
  258. pay_ws = None
  259. for name in wb.sheetnames:
  260. if "应付编码" in name:
  261. pay_ws = wb[name]
  262. break
  263. if pay_ws is None:
  264. add("应付编码", "映射表存在", False, "工具包内无应付编码映射表")
  265. else:
  266. got = {}
  267. triggers = []
  268. for row in pay_ws.iter_rows(min_row=2, values_only=True):
  269. if row and len(row) >= 5 and row[0] and str(row[0]).isdigit():
  270. got[str(row[2])] = str(row[4])
  271. if HTS_RE.fullmatch(str(row[4] or "")):
  272. triggers.append(str(row[1] or ""))
  273. for name, code in PAY_EXPECT.items():
  274. ok = got.get(name) == code
  275. add("应付编码", f"{name} → {code}", ok,
  276. "一致" if ok else f"表内为 {got.get(name, '(缺失)')}")
  277. # 应收品名类别(触发条件)须与文档清单原文一致,防止删除/新增品类后表内仍按旧类别映射
  278. doc_flat = compact(doc_text)
  279. off = [t for t in triggers if compact(t) not in doc_flat]
  280. add("应付编码", f"应收品名类别与文档一致({len(triggers)} 类)", not off,
  281. "一致" if not off else "文档无此写法:" + ";".join(off))
  282. # 3. 单价限制清单(文档 vs 表,双向)
  283. doc_codes = sorted(set(HTS_RE.findall(doc_text)))
  284. price_ws = None
  285. for name in wb.sheetnames:
  286. if "单价" in name:
  287. price_ws = wb[name]
  288. break
  289. if price_ws is None:
  290. add("单价限制", "清单存在", False, "工具包内无单价限制清单")
  291. else:
  292. kit_codes = set()
  293. for row in price_ws.iter_rows(min_row=2, values_only=True):
  294. if row and len(row) > 1 and row[1] and HTS_RE.fullmatch(str(row[1])):
  295. kit_codes.add(str(row[1]))
  296. doc_price = set(c for c in doc_codes if c.startswith(("7013", "6403", "6404", "6208", "6108", "8452")))
  297. missing = doc_price - kit_codes
  298. extra = kit_codes - doc_price
  299. add("单价限制", f"文档 {len(doc_price)} 个受限编码是否齐全", not missing,
  300. "齐全" if not missing else "缺:" + ",".join(sorted(missing)))
  301. add("单价限制", "表内是否有文档以外的编码", not extra,
  302. "无多余" if not extra else "多出:" + ",".join(sorted(extra)))
  303. # 3.1 逐编码核对限制条件原文(只核编码是否存在会漏掉金额、单位、分段的改动)
  304. doc_limits = parse_doc_price_limits(doc_text)
  305. kit_limits = {}
  306. for row in price_ws.iter_rows(min_row=2, values_only=True):
  307. if row and len(row) > 3 and row[1] and HTS_RE.fullmatch(str(row[1])):
  308. kit_limits[str(row[1])] = str(row[3] or "")
  309. if not doc_limits:
  310. add("单价限制", "限制条件原文逐值核对", False, "无法从文档解析单价限制清单,请人工核对", warn=True)
  311. else:
  312. diff = [f"{code}:文档「{doc_limits[code]}」/工具包「{kit_limits.get(code, '(缺失)')}」"
  313. for code in sorted(doc_limits) if compact(doc_limits[code]) != compact(kit_limits.get(code, ""))]
  314. add("单价限制", f"限制条件原文逐值核对({len(doc_limits)} 个)", not diff,
  315. "全部一致" if not diff else ";".join(diff))
  316. # 4. 关键话术与概念(双向)
  317. for doc_tok, kit_tok, label in KEY_TOKENS:
  318. if doc_tok not in doc_text:
  319. add("关键要素", label, False, f"规则文档已不含「{doc_tok}」:核验清单或判定表需随规则更新")
  320. else:
  321. add("关键要素", label, kit_tok in whole,
  322. "已覆盖" if kit_tok in whole else f"工具包未见「{kit_tok}」")
  323. # 4.1 工具包执行表的口径必须仍有文档依据(说明/备注/历史列不计)
  324. exec_text = executable_text(wb)
  325. for kit_tok, doc_tok, label in KIT_CLAIMS:
  326. stale = kit_tok in exec_text and doc_tok not in doc_text
  327. add("过期口径", label, not stale,
  328. f"执行表仍含「{kit_tok}」,规则文档已无「{doc_tok}」" if stale else "未发现")
  329. # 4.2 文档条款 → 判定表项的口径联动
  330. check_ws = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None)
  331. check_rows = {}
  332. if check_ws is not None:
  333. for row in check_ws.iter_rows(min_row=2, values_only=True):
  334. if row and row[0] is not None:
  335. check_rows[str(row[0])] = row
  336. for pattern, seq, col, token, label in TOPIC_LINKS:
  337. if not re.search(pattern, doc_text):
  338. add("条款联动", label, False, f"规则文档已不含该条款:确认 02 表 #{seq} 是否仍应保留该口径,并更新 TOPIC_LINKS")
  339. continue
  340. row = check_rows.get(seq)
  341. cell = str(row[col] or "") if row is not None and len(row) > col else ""
  342. add("条款联动", label, token in cell,
  343. f"02 表 #{seq} 已体现「{token}」" if token in cell else f"02 表 #{seq} 未体现「{token}」:判定表落后于规则")
  344. # 4.5 定量阈值专项核对(FZ-06 长边像素)
  345. # 背景:v0.5→v0.6 规则把 800 改成 50 又改回 800,旧版本只核编号是否存在,
  346. # 阈值变了仍报"一致",属严重盲区。此处直接比对数值。
  347. doc_px = None
  348. m = re.search(r"FZ-06[::]\s*长边像素需在\s*(\d+)\s*(?:及)?以上", doc_text)
  349. if m:
  350. doc_px = m.group(1)
  351. else:
  352. m = re.search(r"FZ-06[::][^\n]{0,20}?(\d+)\s*(?:及)?以上", doc_text)
  353. doc_px = m.group(1) if m else None
  354. kit_px = kit_px_tpl = None
  355. ws02 = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None)
  356. if ws02 is not None:
  357. for row in ws02.iter_rows(min_row=2, values_only=True):
  358. if row and len(row) > 2 and row[1] and "长边像素" in str(row[1]):
  359. mm = re.search(r"<\s*(\d+)", str(row[2] or ""))
  360. if mm:
  361. kit_px = mm.group(1)
  362. mm2 = re.search(r"≥\s*(\d+)", str(row[4] or "") if len(row) > 4 else "")
  363. if mm2:
  364. kit_px_tpl = mm2.group(1)
  365. break
  366. if doc_px and kit_px:
  367. ok = (doc_px == kit_px) and (kit_px_tpl in (None, doc_px))
  368. add("定量阈值", f"FZ-06 长边像素阈值(文档 {doc_px} / 判定条件 {kit_px} / 话术 {kit_px_tpl or '-'})",
  369. ok, "三处一致" if ok else
  370. f"文档={doc_px},工具包判定条件={kit_px},话术={kit_px_tpl}:判定表落后于规则")
  371. else:
  372. add("定量阈值", "FZ-06 长边像素阈值", False,
  373. f"无法解析(文档={doc_px},工具包={kit_px}),请人工确认", warn=True)
  374. # 5. 说明数字与实际是否一致
  375. text00 = ""
  376. for name in wb.sheetnames:
  377. if name.startswith("00"):
  378. text00 = sheet_text(wb[name])
  379. break
  380. m = re.search(r"下面\s*(\d+)\s*张表", text00)
  381. if m:
  382. add("说明一致性", "说明中的工作表数量", int(m.group(1)) == len(wb.sheetnames),
  383. f"说明={m.group(1)},实际={len(wb.sheetnames)}")
  384. sheet02 = None
  385. for name in wb.sheetnames:
  386. if name.startswith("02"):
  387. sheet02 = wb[name]
  388. break
  389. m = re.search(r"本次\s*(\d+)\s*项", text00)
  390. if m and sheet02 is not None:
  391. actual = sheet02.max_row - 1
  392. add("说明一致性", "说明中的判定项数量", int(m.group(1)) == actual,
  393. f"说明={m.group(1)},实际={actual}")
  394. m = re.search(r"((\d+)\s*条)", text00)
  395. chg = [s for s in wb.sheetnames if s.startswith("10")]
  396. if m and chg:
  397. actual = wb[chg[0]].max_row - 1
  398. add("说明一致性", "说明中的变更记录条数", int(m.group(1)) == actual,
  399. f"说明={m.group(1)},实际={actual}")
  400. # 6. 结构性检查
  401. order = [s[:2] for s in wb.sheetnames]
  402. expected = [f"{i:02d}" for i in range(len(wb.sheetnames))]
  403. add("结构", "工作表编号顺序连续", order == expected,
  404. "顺序正常" if order == expected else f"实际顺序 {order}")
  405. for prefix, label, mincnt in [("01", "待裁决清单条目", 10), ("10", "变更记录条目", 3), ("07", "金标集样本", 5)]:
  406. name = next((s for s in wb.sheetnames if s.startswith(prefix)), None)
  407. if name:
  408. ws = wb[name]
  409. if prefix == "07":
  410. n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True)
  411. if r[0] and str(r[0]).startswith("G-"))
  412. else:
  413. n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True) if r[0])
  414. add("结构", label, n >= mincnt, f"{n} 条")
  415. # 7. 文档自身健康度(提醒类,不阻断)
  416. head_lines = [ln.strip() for ln in doc_text.split("\n")
  417. if re.match(r"^[一二三四五六七八九十]+、", ln.strip())]
  418. dup_full = [h for h in set(head_lines) if head_lines.count(h) > 1]
  419. nums = [re.match(r"^([一二三四五六七八九十]+)、", h).group(1) for h in head_lines]
  420. reused = sorted({n for n in nums if nums.count(n) > 1})
  421. add("文档健康度", "章节标题是否完全重复", not dup_full,
  422. "无" if not dup_full else f"重复标题:{dup_full}", warn=bool(dup_full))
  423. add("文档健康度", "章节编号是否被复用", not reused,
  424. "编号唯一" if not reused else
  425. f"编号 {'/'.join(reused)} 出现多次(如 CPC 章节内另起一、二、三,属嵌套编号,可忽略)",
  426. warn=bool(reused))
  427. # ---------------- 输出 ----------------
  428. ok_n = sum(1 for r in results if r[2] == "✅")
  429. warn_n = sum(1 for r in results if r[2] == "⚠️")
  430. bad_n = sum(1 for r in results if r[2] == "❌")
  431. if not quiet:
  432. print()
  433. print(f"【工具包核验】{kit_path.display_name(workbook_path)}")
  434. print(f" ✅ 通过 {ok_n} | ⚠️ 提醒 {warn_n} | ❌ 偏差 {bad_n} | 合计 {len(results)}")
  435. print()
  436. cur = None
  437. for cat, item, st, note in results:
  438. if cat != cur:
  439. print(f" ── {cat} ──")
  440. cur = cat
  441. print(f" {st} {item}" + (f":{note}" if note else ""))
  442. if report_path:
  443. write_report(results, report_path, workbook_path)
  444. if not quiet:
  445. print(f"\n报告已写入:{report_path}")
  446. return {"ok": ok_n, "warn": warn_n, "bad": bad_n, "results": results}
  447. def write_report(results, path, workbook_path):
  448. from openpyxl import Workbook
  449. from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
  450. from openpyxl.utils import get_column_letter
  451. wb = Workbook()
  452. ws = wb.active
  453. ws.title = "核验结果"
  454. ws.append(["类别", "检查项", "状态", "说明"])
  455. H = PatternFill("solid", fgColor="1F4E79")
  456. HF = Font(color="FFFFFF", bold=True, size=11, name="微软雅黑")
  457. BODY = Font(size=10, name="微软雅黑")
  458. T = Side(style="thin", color="BFBFBF")
  459. BD = Border(left=T, right=T, top=T, bottom=T)
  460. FILL = {"✅": PatternFill("solid", fgColor="C6EFCE"),
  461. "⚠️": PatternFill("solid", fgColor="FFEB9C"),
  462. "❌": PatternFill("solid", fgColor="FFC7CE")}
  463. for c in ws[1]:
  464. c.fill = H
  465. c.font = HF
  466. c.border = BD
  467. c.alignment = Alignment(horizontal="center", vertical="center")
  468. for r in results:
  469. ws.append(list(r))
  470. for row in ws.iter_rows(min_row=2, max_row=ws.max_row, max_col=4):
  471. for c in row:
  472. c.font = BODY
  473. c.border = BD
  474. c.alignment = Alignment(vertical="top", wrap_text=True)
  475. row[2].fill = FILL.get(row[2].value, PatternFill())
  476. for i, w in enumerate([14, 40, 8, 62], 1):
  477. ws.column_dimensions[get_column_letter(i)].width = w
  478. ws.freeze_panes = "A2"
  479. ws2 = wb.create_sheet("元信息")
  480. ws2.append(["项目", "值"])
  481. ws2.append(["核验时间", datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
  482. ws2.append(["被检工作簿", kit_path.display_name(workbook_path)])
  483. ws2.append(["规则文档", "飞书 docx(已实时拉取)"])
  484. ws2.append(["生成方式", "rule_check.py"])
  485. ws2.column_dimensions["A"].width = 18
  486. ws2.column_dimensions["B"].width = 60
  487. wb.save(path)
  488. # ---------------- 入口 ----------------
  489. def main():
  490. ap = argparse.ArgumentParser(description="SKU 审核规则一致性核验")
  491. ap.add_argument("action", nargs="?", default="all", choices=["fetch", "verify", "all"])
  492. ap.add_argument("--doc", default=DEFAULT_DOC, help="飞书文档 ID 或完整 URL")
  493. ap.add_argument("--workbook", default=DEFAULT_WB, help="工具包 xlsx 路径")
  494. ap.add_argument("--report", default=None, help="输出 xlsx 路径(可选)")
  495. ap.add_argument("--quiet", action="store_true")
  496. args = ap.parse_args()
  497. doc_id = args.doc
  498. m = re.search(r"/docx/([A-Za-z0-9]+)", doc_id)
  499. if m:
  500. doc_id = m.group(1)
  501. app_id, secret = load_credentials()
  502. token = get_token(app_id, secret)
  503. exit_code = 0
  504. fetch_res = None
  505. if args.action in ("fetch", "all"):
  506. fetch_res = cmd_fetch(doc_id, token, quiet=args.quiet)
  507. if fetch_res.get("changed") or fetch_res.get("package_synced") is not True:
  508. exit_code = 1
  509. if args.action in ("verify", "all"):
  510. # all 模式复用 fetch 拿到的同一份正文,避免两次请求之间文档被改、前后核验不同版本
  511. doc_text = fetch_res["content"] if fetch_res else fetch_doc(doc_id, token)
  512. v = cmd_verify(doc_text, args.workbook, args.report, quiet=args.quiet)
  513. if v["bad"] > 0:
  514. exit_code = 1
  515. if not args.quiet:
  516. print()
  517. if v["bad"] == 0:
  518. print("结论:工具包与规则一致。")
  519. else:
  520. print(f"结论:有 {v['bad']} 处偏差需要处理。")
  521. sys.exit(exit_code)
  522. if __name__ == "__main__":
  523. main()