rule_check.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. 退出码:
  17. 0 = 全部通过
  18. 1 = 存在偏差(需处理)
  19. 2 = 执行错误(取凭证/拉文档/读表格失败)
  20. """
  21. import argparse
  22. import json
  23. import os
  24. import re
  25. import sys
  26. import difflib
  27. import re as _re
  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. # 默认工作簿:优先用技能包内的 assets/,否则用当前目录同名文件
  37. def _pick_workbook():
  38. """优先取 assets 下版本号最高的工具包,避免升级后仍指向旧文件名"""
  39. import glob
  40. for d in (os.path.join(os.path.dirname(_HERE), "assets"), os.path.join(_HERE, "assets"), os.getcwd()):
  41. hits = sorted(glob.glob(os.path.join(d, "SKU审核专员-训练校准工具包_v*.xlsx")))
  42. hits = [h for h in hits if not os.path.basename(h).startswith("~$")]
  43. if hits:
  44. hits.sort(key=lambda h: [int(x) if x.isdigit() else 0
  45. for x in _re.findall(r"v(\d+(?:\.\d+)*)", os.path.basename(h))[0].split(".")])
  46. return hits[-1]
  47. return os.path.join(os.path.dirname(_HERE), "assets", "SKU审核专员-训练校准工具包_v0.3.xlsx")
  48. DEFAULT_WB = _pick_workbook()
  49. HOME_DIR = os.path.expanduser("~/.sku_audit")
  50. SNAP_DIR = os.path.join(HOME_DIR, "snapshots")
  51. # ---------------- 规则要素清单(文档应包含、工具包应覆盖) ----------------
  52. HARD_RULES = ["R-001", "R-002", "R-003", "R-004", "R-005", "R-006", "R-007"]
  53. FZ_ITEMS = ["FZ-01", "FZ-02", "FZ-03", "FZ-04", "FZ-05", "FZ-06"]
  54. # 应付编码合并清单:应付中文品名 -> 编码(文档原文口径)
  55. PAY_EXPECT = {
  56. "灯泡": "8539.52.0091",
  57. "装饰灯": "8539.22.8030",
  58. "装饰品": "9505.10.5020",
  59. "塑料餐具": "3924.10.4000",
  60. "塑料盒": "3924.90.5650",
  61. }
  62. # 关键话术 / 关键概念:文档有,工具包也必须有
  63. KEY_TOKENS = [
  64. ("未上传产品图片", "无图驳回话术"),
  65. ("品牌栏却填", "品牌标识驳回话术"),
  66. ("Lab ID", "CPC 实验室编号要求"),
  67. ("12 个月", "CPC 有效期算法"),
  68. ("四档", "关税附加费四档"),
  69. ("产品附加费", "产品附加费规则"),
  70. ("FDA", "FDA 申报规则"),
  71. ("普货", "普货判断"),
  72. ("应付", "应付编码/单价"),
  73. ("手表", "手表品类转人工"),
  74. ("目的国", "目的国限美国"),
  75. ("二档=无", "关税附加费二档并入无"),
  76. ("取最高的收取", "产品附加费多档取最高"),
  77. ]
  78. HTS_RE = re.compile(r"\b\d{4}\.\d{2}\.\d{4}\b")
  79. # ---------------- 基础工具 ----------------
  80. def die(msg, code=2):
  81. print(f"[错误] {msg}", file=sys.stderr)
  82. sys.exit(code)
  83. def load_credentials():
  84. app_id = os.environ.get("FEISHU_APP_ID")
  85. secret = os.environ.get("FEISHU_APP_SECRET")
  86. if app_id and secret:
  87. return app_id, secret
  88. p = os.path.join(HOME_DIR, "credentials.json")
  89. if os.path.exists(p):
  90. try:
  91. d = json.load(open(p, encoding="utf-8"))
  92. if d.get("app_id") and d.get("app_secret"):
  93. return d["app_id"], d["app_secret"]
  94. except Exception:
  95. pass
  96. die("未找到凭证。请设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,"
  97. f"或写入 {p}")
  98. def get_token(app_id, app_secret):
  99. try:
  100. r = requests.post(
  101. "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
  102. json={"app_id": app_id, "app_secret": app_secret}, timeout=20)
  103. d = r.json()
  104. except Exception as e:
  105. die(f"获取 token 失败:{e}")
  106. if d.get("code") != 0:
  107. die(f"获取 token 失败:code={d.get('code')} msg={d.get('msg')}")
  108. return d["tenant_access_token"]
  109. def fetch_doc(doc_id, token):
  110. url = f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/raw_content"
  111. try:
  112. r = requests.get(url, headers={"Authorization": "Bearer " + token}, timeout=30)
  113. d = r.json()
  114. except Exception as e:
  115. die(f"拉取文档失败:{e}")
  116. if d.get("code") != 0:
  117. die(f"拉取文档失败:code={d.get('code')} msg={d.get('msg')}(检查应用是否有该文档读权限)")
  118. content = (d.get("data") or {}).get("content", "")
  119. if not content:
  120. die("文档内容为空")
  121. return content
  122. def normalize(text):
  123. """去掉行首缩进和空行,便于比对"""
  124. lines = [ln.strip() for ln in text.split("\n")]
  125. return "\n".join([ln for ln in lines if ln])
  126. def save_snapshot(content):
  127. os.makedirs(SNAP_DIR, exist_ok=True)
  128. ts = datetime.now().strftime("%Y%m%d_%H%M%S")
  129. path = os.path.join(SNAP_DIR, f"doc_{ts}.txt")
  130. open(path, "w", encoding="utf-8").write(content)
  131. return path
  132. def latest_snapshot(before=None):
  133. if not os.path.isdir(SNAP_DIR):
  134. return None
  135. files = sorted(f for f in os.listdir(SNAP_DIR) if f.startswith("doc_") and f.endswith(".txt"))
  136. if before:
  137. files = [f for f in files if f != before]
  138. return os.path.join(SNAP_DIR, files[-1]) if files else None
  139. # ---------------- 文档变更检测 ----------------
  140. def cmd_fetch(doc_id, token, quiet=False):
  141. content = fetch_doc(doc_id, token)
  142. prev = latest_snapshot()
  143. old = open(prev, encoding="utf-8").read() if prev else None
  144. snap = save_snapshot(content)
  145. if old is None:
  146. if not quiet:
  147. print("【文档变更】首次建立快照,无历史版本可比对")
  148. return {"first": True, "changes": []}
  149. if normalize(old) == normalize(content):
  150. if not quiet:
  151. print(f"【文档变更】与上一版一致({len(content)} 字符),规则未变动")
  152. return {"first": False, "changed": False, "changes": []}
  153. a = normalize(old).split("\n")
  154. b = normalize(content).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 not quiet:
  158. print(f"【文档变更】检测到 {len(diffs)} 行差异:")
  159. for ln in diffs[:40]:
  160. flag = "新增" if ln.startswith("+") else "删除"
  161. print(f" [{flag}] {ln[1:][:100]}")
  162. if len(diffs) > 40:
  163. print(f" ... 另有 {len(diffs) - 40} 行")
  164. return {"first": False, "changed": True, "changes": diffs, "snapshot": snap}
  165. # ---------------- 工具包核验 ----------------
  166. def sheet_text(ws):
  167. out = []
  168. for row in ws.iter_rows(values_only=True):
  169. for v in row:
  170. if v is not None:
  171. out.append(str(v))
  172. return "\n".join(out)
  173. def cmd_verify(doc_text, workbook_path, report_path=None, quiet=False):
  174. try:
  175. import openpyxl
  176. except ImportError:
  177. die("缺少依赖:pip3 install openpyxl")
  178. if not os.path.exists(workbook_path):
  179. die(f"找不到工具包:{workbook_path}")
  180. wb = openpyxl.load_workbook(workbook_path)
  181. whole = "\n".join(sheet_text(wb[s]) for s in wb.sheetnames)
  182. results = [] # (类别, 检查项, 状态, 说明)
  183. def add(cat, item, ok, note, warn=False):
  184. results.append((cat, item, "⚠️" if warn else ("✅" if ok else "❌"), note))
  185. # 1. 规则要素
  186. for r in HARD_RULES:
  187. add("规则要素", f"核心规则 {r}", r in whole,
  188. "文档有、工具包有" if r in whole else "工具包缺失该规则")
  189. for f in FZ_ITEMS:
  190. add("规则要素", f"图片判定 {f}", f in whole,
  191. "已覆盖" if f in whole else "工具包缺失该项")
  192. # 2. 应付编码映射(双向)
  193. pay_ws = None
  194. for name in wb.sheetnames:
  195. if "应付编码" in name:
  196. pay_ws = wb[name]
  197. break
  198. if pay_ws is None:
  199. add("应付编码", "映射表存在", False, "工具包内无应付编码映射表")
  200. else:
  201. got = {}
  202. for row in pay_ws.iter_rows(min_row=2, values_only=True):
  203. if row and len(row) >= 5 and row[0] and str(row[0]).isdigit():
  204. got[str(row[2])] = str(row[4])
  205. for name, code in PAY_EXPECT.items():
  206. ok = got.get(name) == code
  207. add("应付编码", f"{name} → {code}", ok,
  208. "一致" if ok else f"表内为 {got.get(name, '(缺失)')}")
  209. # 3. 单价限制清单(文档 vs 表,双向)
  210. doc_codes = sorted(set(HTS_RE.findall(doc_text)))
  211. price_ws = None
  212. for name in wb.sheetnames:
  213. if "单价" in name:
  214. price_ws = wb[name]
  215. break
  216. if price_ws is None:
  217. add("单价限制", "清单存在", False, "工具包内无单价限制清单")
  218. else:
  219. kit_codes = set()
  220. for row in price_ws.iter_rows(min_row=2, values_only=True):
  221. if row and len(row) > 1 and row[1] and HTS_RE.fullmatch(str(row[1])):
  222. kit_codes.add(str(row[1]))
  223. doc_price = set(c for c in doc_codes if c.startswith(("7013", "6403", "6404", "6208", "6108", "8452")))
  224. missing = doc_price - kit_codes
  225. extra = kit_codes - doc_price
  226. add("单价限制", f"文档 {len(doc_price)} 个受限编码是否齐全", not missing,
  227. "齐全" if not missing else "缺:" + ",".join(sorted(missing)))
  228. add("单价限制", "表内是否有文档以外的编码", not extra,
  229. "无多余" if not extra else "多出:" + ",".join(sorted(extra)))
  230. # 4. 关键话术与概念
  231. for tok, label in KEY_TOKENS:
  232. add("关键要素", label, tok in whole,
  233. "已覆盖" if tok in whole else f"工具包未见「{tok}」")
  234. # 4.1 文档未裁决项不能被工具包静默固化为默认口径。
  235. check_ws = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None)
  236. check_rows = {}
  237. if check_ws is not None:
  238. for row in check_ws.iter_rows(min_row=2, values_only=True):
  239. if row and row[0] is not None:
  240. check_rows[str(row[0])] = row
  241. usage_conflict = "R-003" in doc_text and "R-005" in doc_text
  242. usage_defaulted = "18" in check_rows and "通过" in str(check_rows["18"][3] or "")
  243. add("文档待裁决", "文档冲突:用途宽泛默认口径", not (usage_conflict and usage_defaulted),
  244. "规则存在 R-003/R-005 冲突,工具包仍默认通过" if usage_conflict and usage_defaulted else "未发现工具包固化冲突口径")
  245. price_boundary_missing = ("应收单价小于1" in doc_text and "应收单价大于1" in doc_text
  246. and "应收单价等于1" not in doc_text and "应收单价=1" not in doc_text)
  247. price_defaulted = ("49" in check_rows and "≥ 1" in str(check_rows["49"][2] or "")
  248. and "50%" in str(check_rows["49"][3] or ""))
  249. add("文档待裁决", "文档缺口:应收单价等于1", not (price_boundary_missing and price_defaulted),
  250. "文档未定义等于1,工具包仍默认按50%" if price_boundary_missing and price_defaulted else "未发现工具包固化等于1口径")
  251. # 4.5 定量阈值专项核对(FZ-06 长边像素)
  252. # 背景:v0.5→v0.6 规则把 800 改成 50 又改回 800,旧版本只核编号是否存在,
  253. # 阈值变了仍报"一致",属严重盲区。此处直接比对数值。
  254. doc_px = None
  255. m = re.search(r"FZ-06[::]\s*长边像素需在\s*(\d+)\s*(?:及)?以上", doc_text)
  256. if m:
  257. doc_px = m.group(1)
  258. else:
  259. m = re.search(r"FZ-06[::][^\n]{0,20}?(\d+)\s*(?:及)?以上", doc_text)
  260. doc_px = m.group(1) if m else None
  261. kit_px = kit_px_tpl = None
  262. ws02 = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None)
  263. if ws02 is not None:
  264. for row in ws02.iter_rows(min_row=2, values_only=True):
  265. if row and len(row) > 2 and row[1] and "长边像素" in str(row[1]):
  266. mm = re.search(r"<\s*(\d+)", str(row[2] or ""))
  267. if mm:
  268. kit_px = mm.group(1)
  269. mm2 = re.search(r"≥\s*(\d+)", str(row[4] or "") if len(row) > 4 else "")
  270. if mm2:
  271. kit_px_tpl = mm2.group(1)
  272. break
  273. if doc_px and kit_px:
  274. ok = (doc_px == kit_px) and (kit_px_tpl in (None, doc_px))
  275. add("定量阈值", f"FZ-06 长边像素阈值(文档 {doc_px} / 判定条件 {kit_px} / 话术 {kit_px_tpl or '-'})",
  276. ok, "三处一致" if ok else
  277. f"文档={doc_px},工具包判定条件={kit_px},话术={kit_px_tpl}:判定表落后于规则")
  278. else:
  279. add("定量阈值", "FZ-06 长边像素阈值", False,
  280. f"无法解析(文档={doc_px},工具包={kit_px}),请人工确认", warn=True)
  281. # 5. 说明数字与实际是否一致
  282. text00 = ""
  283. for name in wb.sheetnames:
  284. if name.startswith("00"):
  285. text00 = sheet_text(wb[name])
  286. break
  287. m = re.search(r"下面\s*(\d+)\s*张表", text00)
  288. if m:
  289. add("说明一致性", "说明中的工作表数量", int(m.group(1)) == len(wb.sheetnames),
  290. f"说明={m.group(1)},实际={len(wb.sheetnames)}")
  291. sheet02 = None
  292. for name in wb.sheetnames:
  293. if name.startswith("02"):
  294. sheet02 = wb[name]
  295. break
  296. m = re.search(r"本次\s*(\d+)\s*项", text00)
  297. if m and sheet02 is not None:
  298. actual = sheet02.max_row - 1
  299. add("说明一致性", "说明中的判定项数量", int(m.group(1)) == actual,
  300. f"说明={m.group(1)},实际={actual}")
  301. m = re.search(r"((\d+)\s*条)", text00)
  302. chg = [s for s in wb.sheetnames if s.startswith("10")]
  303. if m and chg:
  304. actual = wb[chg[0]].max_row - 1
  305. add("说明一致性", "说明中的变更记录条数", int(m.group(1)) == actual,
  306. f"说明={m.group(1)},实际={actual}")
  307. # 6. 结构性检查
  308. order = [s[:2] for s in wb.sheetnames]
  309. expected = [f"{i:02d}" for i in range(len(wb.sheetnames))]
  310. add("结构", "工作表编号顺序连续", order == expected,
  311. "顺序正常" if order == expected else f"实际顺序 {order}")
  312. for prefix, label, mincnt in [("01", "待裁决清单条目", 10), ("10", "变更记录条目", 3), ("07", "金标集样本", 5)]:
  313. name = next((s for s in wb.sheetnames if s.startswith(prefix)), None)
  314. if name:
  315. ws = wb[name]
  316. if prefix == "07":
  317. n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True)
  318. if r[0] and str(r[0]).startswith("G-"))
  319. else:
  320. n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True) if r[0])
  321. add("结构", label, n >= mincnt, f"{n} 条")
  322. # 7. 文档自身健康度(提醒类,不阻断)
  323. head_lines = [ln.strip() for ln in doc_text.split("\n")
  324. if re.match(r"^[一二三四五六七八九十]+、", ln.strip())]
  325. dup_full = [h for h in set(head_lines) if head_lines.count(h) > 1]
  326. nums = [re.match(r"^([一二三四五六七八九十]+)、", h).group(1) for h in head_lines]
  327. reused = sorted({n for n in nums if nums.count(n) > 1})
  328. add("文档健康度", "章节标题是否完全重复", not dup_full,
  329. "无" if not dup_full else f"重复标题:{dup_full}", warn=bool(dup_full))
  330. add("文档健康度", "章节编号是否被复用", not reused,
  331. "编号唯一" if not reused else
  332. f"编号 {'/'.join(reused)} 出现多次(如 CPC 章节内另起一、二、三,属嵌套编号,可忽略)",
  333. warn=bool(reused))
  334. # ---------------- 输出 ----------------
  335. ok_n = sum(1 for r in results if r[2] == "✅")
  336. warn_n = sum(1 for r in results if r[2] == "⚠️")
  337. bad_n = sum(1 for r in results if r[2] == "❌")
  338. if not quiet:
  339. print()
  340. print(f"【工具包核验】{os.path.basename(workbook_path)}")
  341. print(f" ✅ 通过 {ok_n} | ⚠️ 提醒 {warn_n} | ❌ 偏差 {bad_n} | 合计 {len(results)}")
  342. print()
  343. cur = None
  344. for cat, item, st, note in results:
  345. if cat != cur:
  346. print(f" ── {cat} ──")
  347. cur = cat
  348. print(f" {st} {item}" + (f":{note}" if note else ""))
  349. if report_path:
  350. write_report(results, report_path, workbook_path)
  351. if not quiet:
  352. print(f"\n报告已写入:{report_path}")
  353. return {"ok": ok_n, "warn": warn_n, "bad": bad_n, "results": results}
  354. def write_report(results, path, workbook_path):
  355. from openpyxl import Workbook
  356. from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
  357. from openpyxl.utils import get_column_letter
  358. wb = Workbook()
  359. ws = wb.active
  360. ws.title = "核验结果"
  361. ws.append(["类别", "检查项", "状态", "说明"])
  362. H = PatternFill("solid", fgColor="1F4E79")
  363. HF = Font(color="FFFFFF", bold=True, size=11, name="微软雅黑")
  364. BODY = Font(size=10, name="微软雅黑")
  365. T = Side(style="thin", color="BFBFBF")
  366. BD = Border(left=T, right=T, top=T, bottom=T)
  367. FILL = {"✅": PatternFill("solid", fgColor="C6EFCE"),
  368. "⚠️": PatternFill("solid", fgColor="FFEB9C"),
  369. "❌": PatternFill("solid", fgColor="FFC7CE")}
  370. for c in ws[1]:
  371. c.fill = H
  372. c.font = HF
  373. c.border = BD
  374. c.alignment = Alignment(horizontal="center", vertical="center")
  375. for r in results:
  376. ws.append(list(r))
  377. for row in ws.iter_rows(min_row=2, max_row=ws.max_row, max_col=4):
  378. for c in row:
  379. c.font = BODY
  380. c.border = BD
  381. c.alignment = Alignment(vertical="top", wrap_text=True)
  382. row[2].fill = FILL.get(row[2].value, PatternFill())
  383. for i, w in enumerate([14, 40, 8, 62], 1):
  384. ws.column_dimensions[get_column_letter(i)].width = w
  385. ws.freeze_panes = "A2"
  386. ws2 = wb.create_sheet("元信息")
  387. ws2.append(["项目", "值"])
  388. ws2.append(["核验时间", datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
  389. ws2.append(["被检工作簿", os.path.basename(workbook_path)])
  390. ws2.append(["规则文档", "飞书 docx(已实时拉取)"])
  391. ws2.append(["生成方式", "rule_check.py"])
  392. ws2.column_dimensions["A"].width = 18
  393. ws2.column_dimensions["B"].width = 60
  394. wb.save(path)
  395. # ---------------- 入口 ----------------
  396. def main():
  397. ap = argparse.ArgumentParser(description="SKU 审核规则一致性核验")
  398. ap.add_argument("action", nargs="?", default="all", choices=["fetch", "verify", "all"])
  399. ap.add_argument("--doc", default=DEFAULT_DOC, help="飞书文档 ID 或完整 URL")
  400. ap.add_argument("--workbook", default=DEFAULT_WB, help="工具包 xlsx 路径")
  401. ap.add_argument("--report", default=None, help="输出 xlsx 路径(可选)")
  402. ap.add_argument("--quiet", action="store_true")
  403. args = ap.parse_args()
  404. doc_id = args.doc
  405. m = re.search(r"/docx/([A-Za-z0-9]+)", doc_id)
  406. if m:
  407. doc_id = m.group(1)
  408. app_id, secret = load_credentials()
  409. token = get_token(app_id, secret)
  410. exit_code = 0
  411. fetch_res = None
  412. if args.action in ("fetch", "all"):
  413. fetch_res = cmd_fetch(doc_id, token, quiet=args.quiet)
  414. if fetch_res.get("changed"):
  415. exit_code = 1
  416. if args.action in ("verify", "all"):
  417. doc_text = fetch_doc(doc_id, token)
  418. v = cmd_verify(doc_text, args.workbook, args.report, quiet=args.quiet)
  419. if v["bad"] > 0:
  420. exit_code = 1
  421. if not args.quiet:
  422. print()
  423. if v["bad"] == 0:
  424. print("结论:工具包与规则一致。")
  425. else:
  426. print(f"结论:有 {v['bad']} 处偏差需要处理。")
  427. sys.exit(exit_code)
  428. if __name__ == "__main__":
  429. main()