rule_check.py 27 KB

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