| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497 |
- #!/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": "..."}
- 退出码:
- 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__))
- # 默认工作簿:优先用技能包内的 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", "CPC 实验室编号要求"),
- ("12 个月", "CPC 有效期算法"),
- ("四档", "关税附加费四档"),
- ("产品附加费", "产品附加费规则"),
- ("FDA", "FDA 申报规则"),
- ("普货", "普货判断"),
- ("应付", "应付编码/单价"),
- ("手表", "手表品类转人工"),
- ("目的国", "目的国限美国"),
- ("二档=无", "关税附加费二档并入无"),
- ("取最高的收取", "产品附加费多档取最高"),
- ]
- 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():
- app_id = os.environ.get("FEISHU_APP_ID")
- secret = os.environ.get("FEISHU_APP_SECRET")
- if app_id and secret:
- return app_id, secret
- p = os.path.join(HOME_DIR, "credentials.json")
- if os.path.exists(p):
- try:
- d = json.load(open(p, encoding="utf-8"))
- if d.get("app_id") and d.get("app_secret"):
- return d["app_id"], d["app_secret"]
- except Exception:
- pass
- die("未找到凭证。请设置环境变量 FEISHU_APP_ID / FEISHU_APP_SECRET,"
- f"或写入 {p}")
- 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
- # ---------------- 文档变更检测 ----------------
- 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)
- if old is None:
- if not quiet:
- print("【文档变更】首次建立快照,无历史版本可比对")
- return {"first": True, "changes": []}
- if normalize(old) == normalize(content):
- if not quiet:
- print(f"【文档变更】与上一版一致({len(content)} 字符),规则未变动")
- return {"first": False, "changed": False, "changes": []}
- a = normalize(old).split("\n")
- b = normalize(content).split("\n")
- diffs = [ln for ln in difflib.unified_diff(a, b, lineterm="", n=0)
- if ln.startswith(("+", "-")) and not ln.startswith(("+++", "---"))]
- if not quiet:
- print(f"【文档变更】检测到 {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 {"first": False, "changed": True, "changes": diffs, "snapshot": snap}
- # ---------------- 工具包核验 ----------------
- 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)
- 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 = {}
- 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])
- for name, code in PAY_EXPECT.items():
- ok = got.get(name) == code
- add("应付编码", f"{name} → {code}", ok,
- "一致" if ok else f"表内为 {got.get(name, '(缺失)')}")
- # 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)))
- # 4. 关键话术与概念
- for tok, label in KEY_TOKENS:
- add("关键要素", label, tok in whole,
- "已覆盖" if tok in whole else f"工具包未见「{tok}」")
- # 4.1 文档未裁决项不能被工具包静默固化为默认口径。
- 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
- usage_conflict = "R-003" in doc_text and "R-005" in doc_text
- usage_defaulted = "18" in check_rows and "通过" in str(check_rows["18"][3] or "")
- add("文档待裁决", "文档冲突:用途宽泛默认口径", not (usage_conflict and usage_defaulted),
- "规则存在 R-003/R-005 冲突,工具包仍默认通过" if usage_conflict and usage_defaulted else "未发现工具包固化冲突口径")
- price_boundary_missing = ("应收单价小于1" in doc_text and "应收单价大于1" in doc_text
- and "应收单价等于1" not in doc_text and "应收单价=1" not in doc_text)
- price_defaulted = ("49" in check_rows and "≥ 1" in str(check_rows["49"][2] or "")
- and "50%" in str(check_rows["49"][3] or ""))
- add("文档待裁决", "文档缺口:应收单价等于1", not (price_boundary_missing and price_defaulted),
- "文档未定义等于1,工具包仍默认按50%" if price_boundary_missing and price_defaulted else "未发现工具包固化等于1口径")
- # 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"):
- exit_code = 1
- if args.action in ("verify", "all"):
- doc_text = 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()
|