#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SKU 审核规则一致性核验工具 ========================= 用途:规则文档(飞书 docx)与训练校准工具包(xlsx)之间的自动比对。 每次规则变更后跑一遍,确认判定表没有落后于规则。 用法: python3 rule_check.py fetch # 拉取最新规则并保存快照,与上一版比对 python3 rule_check.py verify # 核对工具包是否与最新规则一致 python3 rule_check.py all # 上面两步一起跑(默认) python3 rule_check.py verify --workbook 路径 --report 输出.xlsx 凭证(按顺序取第一个可用来源,不会写入任何输出): 1) 环境变量:FEISHU_APP_ID / FEISHU_APP_SECRET 2) 文件:~/.sku_audit/credentials.json {"app_id": "...", "app_secret": "..."} 3) 文件:技能包根目录 credentials.json(托管沙箱随包提供,格式同上) 退出码: 0 = 全部通过 1 = 存在偏差(需处理) 2 = 执行错误(取凭证/拉文档/读表格失败) """ import argparse import json import os import re import sys import difflib import re as _re from datetime import datetime try: import requests except ImportError: print("缺少依赖:pip3 install requests", file=sys.stderr) sys.exit(2) DEFAULT_DOC = "SFQjdsMoRoxPjsx4wGhc95uxnEc" _HERE = os.path.dirname(os.path.abspath(__file__)) if _HERE not in sys.path: sys.path.insert(0, _HERE) import feishu_credentials # noqa: E402 # 默认工作簿:优先用技能包内的 assets/,否则用当前目录同名文件 def _pick_workbook(): """优先取 assets 下版本号最高的工具包,避免升级后仍指向旧文件名""" import glob for d in (os.path.join(os.path.dirname(_HERE), "assets"), os.path.join(_HERE, "assets"), os.getcwd()): hits = sorted(glob.glob(os.path.join(d, "SKU审核专员-训练校准工具包_v*.xlsx"))) hits = [h for h in hits if not os.path.basename(h).startswith("~$")] if hits: hits.sort(key=lambda h: [int(x) if x.isdigit() else 0 for x in _re.findall(r"v(\d+(?:\.\d+)*)", os.path.basename(h))[0].split(".")]) return hits[-1] return os.path.join(os.path.dirname(_HERE), "assets", "SKU审核专员-训练校准工具包_v0.3.xlsx") DEFAULT_WB = _pick_workbook() HOME_DIR = os.path.expanduser("~/.sku_audit") SNAP_DIR = os.path.join(HOME_DIR, "snapshots") # ---------------- 规则要素清单(文档应包含、工具包应覆盖) ---------------- HARD_RULES = ["R-001", "R-002", "R-003", "R-004", "R-005", "R-006", "R-007"] FZ_ITEMS = ["FZ-01", "FZ-02", "FZ-03", "FZ-04", "FZ-05", "FZ-06"] # 应付编码合并清单:应付中文品名 -> 编码(文档原文口径) PAY_EXPECT = { "灯泡": "8539.52.0091", "装饰灯": "8539.22.8030", "装饰品": "9505.10.5020", "塑料餐具": "3924.10.4000", "塑料盒": "3924.90.5650", } # 关键话术 / 关键概念:(文档中的写法, 工具包中的写法, 说明) # 双向核对:文档没有该写法说明本清单已过期;工具包没有说明判定表落后于规则。 KEY_TOKENS = [ ("未上传产品图片", "未上传产品图片", "无图驳回话术"), ("品牌栏却填", "品牌栏却填", "品牌标识驳回话术"), ("Lab ID", "Lab ID", "CPC 实验室编号要求"), ("测试结束日", "测试结束日", "CPC 有效期按测试报告结束日起算"), ("第三方测试报告", "第三方测试报告", "CPC 两件套"), ("撤销名单", "撤销名单", "CPSC 名单未提供时转待核实"), ("FDA申报+认证", "FDA申报+认证", "FDA 申报+认证规则"), ("历史相似产品", "历史相似产品", "历史相似产品匹配定义"), ("明确禁配项", "禁配", "应收编码驳回条件"), ("历史数据最低应收单价", "最低应收单价", "应收单价不低于历史最低"), ("产品附加费", "产品附加费", "产品附加费规则"), ("取最高的收取", "取最高的收取", "产品附加费多档取最高"), ("普货", "普货", "普货判断"), ("应付", "应付", "应付编码/单价"), ("手表", "手表", "手表品类转人工"), ("目的国", "目的国", "目的国限美国"), ] # 工具包执行表(02/04/05/06)声称的口径必须仍有文档依据:(工具包写法, 文档写法, 说明) # 文档写法要与工具包口径同样具体,避免文档里其他地方顺带出现的短词把过期口径掩盖掉。 KIT_CLAIMS = [ ("二档=无", "二档=无", "关税附加费二档并入无"), ("税率标签", "税率标签", "关税附加费按税率标签判档"), ("箱规", "箱规信息判断", "按箱规判断单价合理性"), ("手表类", "手表类", "应付清单含手表类"), ("USD/双", "USD/双", "单价按双计"), ("空档", "空档", "单价空档"), ] # 文档条款 → 02 表对应项必须体现的口径:(文档正则, 判定表项号, 列, 必含写法, 说明) TOPIC_LINKS = [ (r"用途过于宽泛→待核实", "18", 3, "待核实", "R-005 用途宽泛→待核实"), (r"商品属性、品名或用途命中玩具、儿童、婴儿", "20", 2, "儿童", "玩具认证触发含儿童/婴儿"), (r"缺少任一文件,均按不合格处理", "27", 2, "缺任一", "CPC 两件缺一不合格"), (r"无法核验名单状态时转待核实", "34", 2, "待核实", "CPSC 名单无法核验转待核实"), (r"有效期按第三方测试报告载明的测试结束日", "35", 2, "测试结束日", "CPC 有效期起算点"), (r"仅在存在明确禁配项", "36", 2, "禁配", "应收编码驳回条件"), (r"不可小于历史数据最低应收单价", "46", 2, "历史", "应收单价历史最低"), (r"应收单价 ≤ 1", "48", 2, "≤ 1", "应付单价等于 1 并入等值档"), (r"关税附加费规则(按历史相似产品", "50", 2, "历史", "关税附加费按历史相似产品"), (r"历史相似产品匹配定义", "60", 2, "品类", "历史相似产品匹配口径"), (r"判断本 SKU 是否需要勾选“FDA申报\+认证”", "61", 2, "历史", "FDA 申报+认证历史判断"), (r"命中手表品类时,直接转人工审核,不填写应付清关编码", "P2", 4, "不填写应付清关编码", "手表不填应付编码"), ] HTS_RE = re.compile(r"\b\d{4}\.\d{2}\.\d{4}\b") # ---------------- 基础工具 ---------------- def die(msg, code=2): print(f"[错误] {msg}", file=sys.stderr) sys.exit(code) def load_credentials(): return feishu_credentials.load() or die(feishu_credentials.missing_message()) def get_token(app_id, app_secret): try: r = requests.post( "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", json={"app_id": app_id, "app_secret": app_secret}, timeout=20) d = r.json() except Exception as e: die(f"获取 token 失败:{e}") if d.get("code") != 0: die(f"获取 token 失败:code={d.get('code')} msg={d.get('msg')}") return d["tenant_access_token"] def fetch_doc(doc_id, token): url = f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/raw_content" try: r = requests.get(url, headers={"Authorization": "Bearer " + token}, timeout=30) d = r.json() except Exception as e: die(f"拉取文档失败:{e}") if d.get("code") != 0: die(f"拉取文档失败:code={d.get('code')} msg={d.get('msg')}(检查应用是否有该文档读权限)") content = (d.get("data") or {}).get("content", "") if not content: die("文档内容为空") return content def normalize(text): """去掉行首缩进和空行,便于比对""" lines = [ln.strip() for ln in text.split("\n")] return "\n".join([ln for ln in lines if ln]) def save_snapshot(content): os.makedirs(SNAP_DIR, exist_ok=True) ts = datetime.now().strftime("%Y%m%d_%H%M%S") path = os.path.join(SNAP_DIR, f"doc_{ts}.txt") open(path, "w", encoding="utf-8").write(content) return path def latest_snapshot(before=None): if not os.path.isdir(SNAP_DIR): return None files = sorted(f for f in os.listdir(SNAP_DIR) if f.startswith("doc_") and f.endswith(".txt")) if before: files = [f for f in files if f != before] return os.path.join(SNAP_DIR, files[-1]) if files else None # ---------------- 文档变更检测 ---------------- PACKAGED_SNAPSHOT = os.path.join(os.path.dirname(_HERE), "references", "doc-snapshot.txt") def print_diffs(title, old, new, quiet=False): a = normalize(old).split("\n") b = normalize(new).split("\n") diffs = [ln for ln in difflib.unified_diff(a, b, lineterm="", n=0) if ln.startswith(("+", "-")) and not ln.startswith(("+++", "---"))] if quiet: return diffs print(f"{title}检测到 {len(diffs)} 行差异:") for ln in diffs[:40]: flag = "新增" if ln.startswith("+") else "删除" print(f" [{flag}] {ln[1:][:100]}") if len(diffs) > 40: print(f" ... 另有 {len(diffs) - 40} 行") return diffs def cmd_fetch(doc_id, token, quiet=False): """两条基线:上一次本地拉取(看规则是否刚变),技能包同步基线(看工具包是否已跟上)。 只比本地快照会出现盲区:规则改动后第一次拉取建立的快照已是新版, 此后每次都显示「一致」,但技能包从未同步过。 """ content = fetch_doc(doc_id, token) prev = latest_snapshot() old = open(prev, encoding="utf-8").read() if prev else None snap = save_snapshot(content) result = {"first": old is None, "changed": False, "changes": [], "snapshot": snap, "package_synced": None, "package_changes": [], "content": content} if old is None: if not quiet: print("【文档变更】首次建立本地快照,无本地历史可比对") elif normalize(old) == normalize(content): if not quiet: print(f"【文档变更】与上一次本地拉取一致({len(content)} 字符)") else: result["changed"] = True result["changes"] = print_diffs("【文档变更】与上一次本地拉取相比", old, content, quiet) if os.path.exists(PACKAGED_SNAPSHOT): base = open(PACKAGED_SNAPSHOT, encoding="utf-8").read() synced = normalize(base) == normalize(content) result["package_synced"] = synced if synced: if not quiet: print("【同步基线】与技能包同步基线一致(references/doc-snapshot.txt),工具包已按当前规则同步") else: result["package_changes"] = print_diffs( "【同步基线】技能包尚未同步到当前规则,与 references/doc-snapshot.txt 相比", base, content, quiet) elif not quiet: print("【同步基线】技能包缺少 references/doc-snapshot.txt,无法确认工具包是否已同步") return result # ---------------- 工具包核验 ---------------- def sheet_text(ws): out = [] for row in ws.iter_rows(values_only=True): for v in row: if v is not None: out.append(str(v)) return "\n".join(out) # 执行表中参与判定的列(1 起);说明、备注、依赖规则、历史记录列不计入 EXEC_COLUMNS = {"02": (2, 3, 4, 5), "04": (3, 4, 5), "05": (2,), "06": (4, 5, 6)} def executable_text(wb): out = [] for name in wb.sheetnames: cols = EXEC_COLUMNS.get(name[:2]) if not cols: continue for row in wb[name].iter_rows(min_row=2, values_only=True): for c in cols: if len(row) >= c and row[c - 1] is not None: out.append(str(row[c - 1])) return "\n".join(out) def compact(text): """去掉空白与中英文标点差异后再比较原文""" return re.sub(r"[\s、,,;;。..:://]+", "", str(text or "")).replace("$", "") def parse_doc_price_limits(doc_text): """从「海关编码限制单价清单」段解析 编码 → 限制条件原文""" start = doc_text.find("海关编码限制单价清单") if start < 0: return {} end = doc_text.find("应付单价", start) lines = [ln.strip() for ln in doc_text[start:end if end > 0 else None].split("\n") if ln.strip()] out, code = {}, None for ln in lines[1:]: if HTS_RE.fullmatch(ln): code = ln elif code: out[code] = ln code = None return out def cmd_verify(doc_text, workbook_path, report_path=None, quiet=False): try: import openpyxl except ImportError: die("缺少依赖:pip3 install openpyxl") if not os.path.exists(workbook_path): die(f"找不到工具包:{workbook_path}") wb = openpyxl.load_workbook(workbook_path) whole = "\n".join(sheet_text(wb[s]) for s in wb.sheetnames) results = [] # (类别, 检查项, 状态, 说明) def add(cat, item, ok, note, warn=False): results.append((cat, item, "⚠️" if warn else ("✅" if ok else "❌"), note)) # 1. 规则要素 for r in HARD_RULES: add("规则要素", f"核心规则 {r}", r in whole, "文档有、工具包有" if r in whole else "工具包缺失该规则") for f in FZ_ITEMS: add("规则要素", f"图片判定 {f}", f in whole, "已覆盖" if f in whole else "工具包缺失该项") # 2. 应付编码映射(双向) pay_ws = None for name in wb.sheetnames: if "应付编码" in name: pay_ws = wb[name] break if pay_ws is None: add("应付编码", "映射表存在", False, "工具包内无应付编码映射表") else: got = {} triggers = [] for row in pay_ws.iter_rows(min_row=2, values_only=True): if row and len(row) >= 5 and row[0] and str(row[0]).isdigit(): got[str(row[2])] = str(row[4]) if HTS_RE.fullmatch(str(row[4] or "")): triggers.append(str(row[1] or "")) for name, code in PAY_EXPECT.items(): ok = got.get(name) == code add("应付编码", f"{name} → {code}", ok, "一致" if ok else f"表内为 {got.get(name, '(缺失)')}") # 应收品名类别(触发条件)须与文档清单原文一致,防止删除/新增品类后表内仍按旧类别映射 doc_flat = compact(doc_text) off = [t for t in triggers if compact(t) not in doc_flat] add("应付编码", f"应收品名类别与文档一致({len(triggers)} 类)", not off, "一致" if not off else "文档无此写法:" + ";".join(off)) # 3. 单价限制清单(文档 vs 表,双向) doc_codes = sorted(set(HTS_RE.findall(doc_text))) price_ws = None for name in wb.sheetnames: if "单价" in name: price_ws = wb[name] break if price_ws is None: add("单价限制", "清单存在", False, "工具包内无单价限制清单") else: kit_codes = set() for row in price_ws.iter_rows(min_row=2, values_only=True): if row and len(row) > 1 and row[1] and HTS_RE.fullmatch(str(row[1])): kit_codes.add(str(row[1])) doc_price = set(c for c in doc_codes if c.startswith(("7013", "6403", "6404", "6208", "6108", "8452"))) missing = doc_price - kit_codes extra = kit_codes - doc_price add("单价限制", f"文档 {len(doc_price)} 个受限编码是否齐全", not missing, "齐全" if not missing else "缺:" + ",".join(sorted(missing))) add("单价限制", "表内是否有文档以外的编码", not extra, "无多余" if not extra else "多出:" + ",".join(sorted(extra))) # 3.1 逐编码核对限制条件原文(只核编码是否存在会漏掉金额、单位、分段的改动) doc_limits = parse_doc_price_limits(doc_text) kit_limits = {} for row in price_ws.iter_rows(min_row=2, values_only=True): if row and len(row) > 3 and row[1] and HTS_RE.fullmatch(str(row[1])): kit_limits[str(row[1])] = str(row[3] or "") if not doc_limits: add("单价限制", "限制条件原文逐值核对", False, "无法从文档解析单价限制清单,请人工核对", warn=True) else: diff = [f"{code}:文档「{doc_limits[code]}」/工具包「{kit_limits.get(code, '(缺失)')}」" for code in sorted(doc_limits) if compact(doc_limits[code]) != compact(kit_limits.get(code, ""))] add("单价限制", f"限制条件原文逐值核对({len(doc_limits)} 个)", not diff, "全部一致" if not diff else ";".join(diff)) # 4. 关键话术与概念(双向) for doc_tok, kit_tok, label in KEY_TOKENS: if doc_tok not in doc_text: add("关键要素", label, False, f"规则文档已不含「{doc_tok}」:核验清单或判定表需随规则更新") else: add("关键要素", label, kit_tok in whole, "已覆盖" if kit_tok in whole else f"工具包未见「{kit_tok}」") # 4.1 工具包执行表的口径必须仍有文档依据(说明/备注/历史列不计) exec_text = executable_text(wb) for kit_tok, doc_tok, label in KIT_CLAIMS: stale = kit_tok in exec_text and doc_tok not in doc_text add("过期口径", label, not stale, f"执行表仍含「{kit_tok}」,规则文档已无「{doc_tok}」" if stale else "未发现") # 4.2 文档条款 → 判定表项的口径联动 check_ws = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None) check_rows = {} if check_ws is not None: for row in check_ws.iter_rows(min_row=2, values_only=True): if row and row[0] is not None: check_rows[str(row[0])] = row for pattern, seq, col, token, label in TOPIC_LINKS: if not re.search(pattern, doc_text): add("条款联动", label, False, f"规则文档已不含该条款:确认 02 表 #{seq} 是否仍应保留该口径,并更新 TOPIC_LINKS") continue row = check_rows.get(seq) cell = str(row[col] or "") if row is not None and len(row) > col else "" add("条款联动", label, token in cell, f"02 表 #{seq} 已体现「{token}」" if token in cell else f"02 表 #{seq} 未体现「{token}」:判定表落后于规则") # 4.5 定量阈值专项核对(FZ-06 长边像素) # 背景:v0.5→v0.6 规则把 800 改成 50 又改回 800,旧版本只核编号是否存在, # 阈值变了仍报"一致",属严重盲区。此处直接比对数值。 doc_px = None m = re.search(r"FZ-06[::]\s*长边像素需在\s*(\d+)\s*(?:及)?以上", doc_text) if m: doc_px = m.group(1) else: m = re.search(r"FZ-06[::][^\n]{0,20}?(\d+)\s*(?:及)?以上", doc_text) doc_px = m.group(1) if m else None kit_px = kit_px_tpl = None ws02 = next((wb[s] for s in wb.sheetnames if s.startswith("02")), None) if ws02 is not None: for row in ws02.iter_rows(min_row=2, values_only=True): if row and len(row) > 2 and row[1] and "长边像素" in str(row[1]): mm = re.search(r"<\s*(\d+)", str(row[2] or "")) if mm: kit_px = mm.group(1) mm2 = re.search(r"≥\s*(\d+)", str(row[4] or "") if len(row) > 4 else "") if mm2: kit_px_tpl = mm2.group(1) break if doc_px and kit_px: ok = (doc_px == kit_px) and (kit_px_tpl in (None, doc_px)) add("定量阈值", f"FZ-06 长边像素阈值(文档 {doc_px} / 判定条件 {kit_px} / 话术 {kit_px_tpl or '-'})", ok, "三处一致" if ok else f"文档={doc_px},工具包判定条件={kit_px},话术={kit_px_tpl}:判定表落后于规则") else: add("定量阈值", "FZ-06 长边像素阈值", False, f"无法解析(文档={doc_px},工具包={kit_px}),请人工确认", warn=True) # 5. 说明数字与实际是否一致 text00 = "" for name in wb.sheetnames: if name.startswith("00"): text00 = sheet_text(wb[name]) break m = re.search(r"下面\s*(\d+)\s*张表", text00) if m: add("说明一致性", "说明中的工作表数量", int(m.group(1)) == len(wb.sheetnames), f"说明={m.group(1)},实际={len(wb.sheetnames)}") sheet02 = None for name in wb.sheetnames: if name.startswith("02"): sheet02 = wb[name] break m = re.search(r"本次\s*(\d+)\s*项", text00) if m and sheet02 is not None: actual = sheet02.max_row - 1 add("说明一致性", "说明中的判定项数量", int(m.group(1)) == actual, f"说明={m.group(1)},实际={actual}") m = re.search(r"((\d+)\s*条)", text00) chg = [s for s in wb.sheetnames if s.startswith("10")] if m and chg: actual = wb[chg[0]].max_row - 1 add("说明一致性", "说明中的变更记录条数", int(m.group(1)) == actual, f"说明={m.group(1)},实际={actual}") # 6. 结构性检查 order = [s[:2] for s in wb.sheetnames] expected = [f"{i:02d}" for i in range(len(wb.sheetnames))] add("结构", "工作表编号顺序连续", order == expected, "顺序正常" if order == expected else f"实际顺序 {order}") for prefix, label, mincnt in [("01", "待裁决清单条目", 10), ("10", "变更记录条目", 3), ("07", "金标集样本", 5)]: name = next((s for s in wb.sheetnames if s.startswith(prefix)), None) if name: ws = wb[name] if prefix == "07": n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True) if r[0] and str(r[0]).startswith("G-")) else: n = sum(1 for r in ws.iter_rows(min_row=2, values_only=True) if r[0]) add("结构", label, n >= mincnt, f"{n} 条") # 7. 文档自身健康度(提醒类,不阻断) head_lines = [ln.strip() for ln in doc_text.split("\n") if re.match(r"^[一二三四五六七八九十]+、", ln.strip())] dup_full = [h for h in set(head_lines) if head_lines.count(h) > 1] nums = [re.match(r"^([一二三四五六七八九十]+)、", h).group(1) for h in head_lines] reused = sorted({n for n in nums if nums.count(n) > 1}) add("文档健康度", "章节标题是否完全重复", not dup_full, "无" if not dup_full else f"重复标题:{dup_full}", warn=bool(dup_full)) add("文档健康度", "章节编号是否被复用", not reused, "编号唯一" if not reused else f"编号 {'/'.join(reused)} 出现多次(如 CPC 章节内另起一、二、三,属嵌套编号,可忽略)", warn=bool(reused)) # ---------------- 输出 ---------------- ok_n = sum(1 for r in results if r[2] == "✅") warn_n = sum(1 for r in results if r[2] == "⚠️") bad_n = sum(1 for r in results if r[2] == "❌") if not quiet: print() print(f"【工具包核验】{os.path.basename(workbook_path)}") print(f" ✅ 通过 {ok_n} | ⚠️ 提醒 {warn_n} | ❌ 偏差 {bad_n} | 合计 {len(results)}") print() cur = None for cat, item, st, note in results: if cat != cur: print(f" ── {cat} ──") cur = cat print(f" {st} {item}" + (f":{note}" if note else "")) if report_path: write_report(results, report_path, workbook_path) if not quiet: print(f"\n报告已写入:{report_path}") return {"ok": ok_n, "warn": warn_n, "bad": bad_n, "results": results} def write_report(results, path, workbook_path): from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter wb = Workbook() ws = wb.active ws.title = "核验结果" ws.append(["类别", "检查项", "状态", "说明"]) H = PatternFill("solid", fgColor="1F4E79") HF = Font(color="FFFFFF", bold=True, size=11, name="微软雅黑") BODY = Font(size=10, name="微软雅黑") T = Side(style="thin", color="BFBFBF") BD = Border(left=T, right=T, top=T, bottom=T) FILL = {"✅": PatternFill("solid", fgColor="C6EFCE"), "⚠️": PatternFill("solid", fgColor="FFEB9C"), "❌": PatternFill("solid", fgColor="FFC7CE")} for c in ws[1]: c.fill = H c.font = HF c.border = BD c.alignment = Alignment(horizontal="center", vertical="center") for r in results: ws.append(list(r)) for row in ws.iter_rows(min_row=2, max_row=ws.max_row, max_col=4): for c in row: c.font = BODY c.border = BD c.alignment = Alignment(vertical="top", wrap_text=True) row[2].fill = FILL.get(row[2].value, PatternFill()) for i, w in enumerate([14, 40, 8, 62], 1): ws.column_dimensions[get_column_letter(i)].width = w ws.freeze_panes = "A2" ws2 = wb.create_sheet("元信息") ws2.append(["项目", "值"]) ws2.append(["核验时间", datetime.now().strftime("%Y-%m-%d %H:%M:%S")]) ws2.append(["被检工作簿", os.path.basename(workbook_path)]) ws2.append(["规则文档", "飞书 docx(已实时拉取)"]) ws2.append(["生成方式", "rule_check.py"]) ws2.column_dimensions["A"].width = 18 ws2.column_dimensions["B"].width = 60 wb.save(path) # ---------------- 入口 ---------------- def main(): ap = argparse.ArgumentParser(description="SKU 审核规则一致性核验") ap.add_argument("action", nargs="?", default="all", choices=["fetch", "verify", "all"]) ap.add_argument("--doc", default=DEFAULT_DOC, help="飞书文档 ID 或完整 URL") ap.add_argument("--workbook", default=DEFAULT_WB, help="工具包 xlsx 路径") ap.add_argument("--report", default=None, help="输出 xlsx 路径(可选)") ap.add_argument("--quiet", action="store_true") args = ap.parse_args() doc_id = args.doc m = re.search(r"/docx/([A-Za-z0-9]+)", doc_id) if m: doc_id = m.group(1) app_id, secret = load_credentials() token = get_token(app_id, secret) exit_code = 0 fetch_res = None if args.action in ("fetch", "all"): fetch_res = cmd_fetch(doc_id, token, quiet=args.quiet) if fetch_res.get("changed") or fetch_res.get("package_synced") is not True: exit_code = 1 if args.action in ("verify", "all"): # all 模式复用 fetch 拿到的同一份正文,避免两次请求之间文档被改、前后核验不同版本 doc_text = fetch_res["content"] if fetch_res else fetch_doc(doc_id, token) v = cmd_verify(doc_text, args.workbook, args.report, quiet=args.quiet) if v["bad"] > 0: exit_code = 1 if not args.quiet: print() if v["bad"] == 0: print("结论:工具包与规则一致。") else: print(f"结论:有 {v['bad']} 处偏差需要处理。") sys.exit(exit_code) if __name__ == "__main__": main()