feat(sdk): hr_sdk 0.2.4 工资卡导入、desktopauto 0.5.0 证件照识别、新增插件 XQ0084
- hr_sdk.wage_import:DrissionPage 注入 cookie 打开 HR 门户,页面内 WS 订阅 + fetch 上传,解析 over: 结果;build_xlsx 第 9 列卡号强制数值(修复「卡号必须是数字」) - 纯 HTTP 导入不可用:服务端异步任务与浏览器会话强绑定,且前端无轮询接口(已核实),结果通道只能用浏览器上下文 - desktopauto 0.5.0 新增 cardocr:身份证/银行卡 OCR、号码纠错、Luhn 与模 11-2 校验、交叉核对 - 新增插件 XQ0084 银行卡更新EHR系统:AI 表格待处理行 → 影像识别 → 一致性核对/异常名单 - .gitignore 忽略 tests/aitable_probe/_out/(含员工证件照,禁止入库)
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 银行卡更新EHR系统 插件入口(第一阶段)。
|
||||
|
||||
流程编排:
|
||||
1) 读取 AI 表格「银行卡-变更收集表」,筛选「是否更新HR系统 / 收到纸质资料 / 登记日期」
|
||||
任一为空的待处理行;
|
||||
2) 下载银行卡卡号面照片、持卡人身份证照片;
|
||||
3) desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 输出核对工作簿(核对结果 + 异常名单),识别不出或不一致的推送钉钉群提醒人事手动处理。
|
||||
|
||||
HR 系统「薪资管理-工资数据-工资卡管理」的写入(现金发放/新增/修改主卡、回写
|
||||
「是否更新HR系统=是」)留到后续阶段,本阶段不写 HR、不改 AI 表格。
|
||||
"""
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .logic.runner import run_verify
|
||||
|
||||
|
||||
class BankCardEhrUpdatePlugin(ScenePlugin):
|
||||
"""银行卡变更影像核对 + 后续 EHR 工资卡更新(需求 XQ0084)。"""
|
||||
|
||||
id = "xq0084"
|
||||
name = "银行卡更新EHR系统"
|
||||
version = "0.1.0"
|
||||
description = ("读取人资 AI 表格「银行卡变更收集表」待处理行(是否更新HR系统/收到纸质资料/"
|
||||
"登记日期任一为空),下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行,"
|
||||
"与表格登记值比对;一致放行,不一致或识别不出进异常名单并提醒人事手动处理。"
|
||||
"当前阶段只核对不写 HR 系统。")
|
||||
platform = ""
|
||||
uses_month = False
|
||||
capabilities = ["xq0084"]
|
||||
permissions = {}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "核对结果工作簿与下载影像的保存目录;每次运行独立留档,按留档份数自动清理旧文件",
|
||||
},
|
||||
"keep_files": {
|
||||
"type": "integer", "title": "结果留档份数",
|
||||
"default": config.DEFAULT_KEEP_FILES,
|
||||
"description": "输出目录最多保留最近 N 份结果工作簿与 N 批影像(含本次);0 = 不清理",
|
||||
},
|
||||
"limit_rows": {
|
||||
"type": "integer", "title": "最多处理条数",
|
||||
"default": 0,
|
||||
"description": "0 = 处理全部待处理记录;调试时可填小数字只跑前几条",
|
||||
},
|
||||
"push_webhook": {
|
||||
"type": "string", "title": "钉钉群机器人 Webhook",
|
||||
"default": "",
|
||||
"description": "留空=只导出不推送;存在异常时推送异常名单摘要(文本,文件需到输出目录自取)",
|
||||
},
|
||||
"push_secret": {
|
||||
"type": "string", "title": "钉钉机器人加签密钥", "format": "password",
|
||||
"default": "",
|
||||
"description": "机器人安全设置为「加签」时填写,未配置加签留空",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
config.set_log(ctx.log)
|
||||
ctx.progress(1)
|
||||
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
keep_files = config.normalize_keep(fields.get("keep_files"))
|
||||
push_webhook = (fields.get("push_webhook") or "").strip()
|
||||
push_secret = fields.get("push_secret") or ""
|
||||
try:
|
||||
limit_rows = max(int(str(fields.get("limit_rows") or 0).strip()), 0)
|
||||
except (TypeError, ValueError):
|
||||
limit_rows = 0
|
||||
|
||||
ctx.log(f"===== 银行卡变更影像核对启动:输出目录 {save_dir}(留档 {keep_files} 份)=====",
|
||||
"INFO")
|
||||
result = run_verify(
|
||||
save_dir=save_dir,
|
||||
keep_files=keep_files,
|
||||
push_webhook=push_webhook,
|
||||
push_secret=push_secret,
|
||||
limit_rows=limit_rows,
|
||||
progress=ctx.progress,
|
||||
)
|
||||
|
||||
stats = result["stats"]
|
||||
if not stats["total"]:
|
||||
return {"summary": "无待处理记录:AI 表格三项缺失字段均无命中",
|
||||
"detail": {"待处理": 0}, "path": ""}
|
||||
|
||||
summary = ("银行卡变更核对完成:共 {total} 条,通过 {passed} / 需人工 {manual} / "
|
||||
"现金发放 {cash}。文件:{path}").format(path=result["path"], **stats)
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
"待处理": stats["total"],
|
||||
"通过": stats["passed"],
|
||||
"需人工": stats["manual"],
|
||||
"现金发放": stats["cash"],
|
||||
"未更新HR系统": stats["trigger"][config.F_DONE],
|
||||
"未收纸质资料": stats["trigger"][config.F_PAPER],
|
||||
"缺登记日期": stats["trigger"][config.F_REG_DATE],
|
||||
"清理历史留档": len(result["cleaned"]),
|
||||
"推送": "成功" if result["push"].get("success") else result["push"].get("message", ""),
|
||||
},
|
||||
"path": result["path"],
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(BankCardEhrUpdatePlugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)。
|
||||
|
||||
把插件压成 dist-plugin/xq0084_v<版本>.zip(zip 根含 plugin.json)。
|
||||
排除:__pycache__、_selftest*、本脚本、*.pyc。
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"__pycache__", "debug", ".sessions", "out", "images"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_PREFIXES = ("_selftest",)
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES:
|
||||
continue
|
||||
if p.name.startswith(_EXCLUDE_PREFIXES) or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 判定规则自测(不联网、不依赖底座,仅验证纯逻辑)。
|
||||
|
||||
运行:python -m xq0084._selftest(开发态把插件目录放到 PYTHONPATH 或将本目录
|
||||
临时复制为 plugins/xq0084/)。打包时 `_` 前缀文件会被 _pack.py 排除。
|
||||
"""
|
||||
from .logic.verify import verify
|
||||
|
||||
CARD = "6214832377534396"
|
||||
ID = "500228199001011235"
|
||||
|
||||
|
||||
def _item(card=CARD, id_no=ID, holder="张三", reason="个人原因换新卡", images=("a.jpg",)):
|
||||
row = {
|
||||
"员工姓名.工号": "37000001",
|
||||
"持卡人姓名": holder,
|
||||
"变更原因": reason,
|
||||
"开户银行": "招商银行",
|
||||
"银行卡号": card,
|
||||
"持卡人身份证号": id_no,
|
||||
"是否更新HR系统": "",
|
||||
}
|
||||
return {"row": row, "triggers": ["收到纸质资料"], "images": list(images), "errors": []}
|
||||
|
||||
|
||||
def _ocr(id_no=ID, name="张三", card=CARD, bank="招商银行"):
|
||||
return {"id": {"number": id_no, "name": name},
|
||||
"bank": {"number": card, "bank": bank},
|
||||
"runs": [id_no, card], "errors": []}
|
||||
|
||||
|
||||
def main():
|
||||
cases = [
|
||||
("全部一致", _item(), _ocr(), "通过"),
|
||||
("身份证不一致", _item(), _ocr(id_no="500228199002021235"), "需人工核实"),
|
||||
("卡号读不出", _item(), _ocr(card=""), "需人工核实"),
|
||||
("姓名不一致", _item(), _ocr(name="李四"), "需人工核实"),
|
||||
("开户银行不一致", _item(), _ocr(bank="建设银行"), "需人工核实"),
|
||||
("缺影像", _item(images=()), _ocr(), "需人工核实"),
|
||||
("表格缺卡号", _item(card=""), _ocr(), "需人工核实"),
|
||||
("现金发放跳过核对", _item(card="", reason="银行卡收款异常改“现金发放”"),
|
||||
{}, "现金发放(无需影像核对)"),
|
||||
("多人一行", _item(holder="张三、李四"), _ocr(), "需人工核实"),
|
||||
]
|
||||
failed = 0
|
||||
for name, item, ocr, expect in cases:
|
||||
got = verify(item, ocr)["conclusion"]
|
||||
ok = got == expect
|
||||
failed += 0 if ok else 1
|
||||
print(f"{'OK ' if ok else 'FAIL'} {name}: {got}(期望 {expect})")
|
||||
print(f"完成:{len(cases) - failed}/{len(cases)} 通过")
|
||||
return failed
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,221 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 银行卡更新EHR系统 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库 / 执行机挂载的 SDK
|
||||
(desktopauto、dingtalk_sdk),不 import 任何插件包之外的业务代码。
|
||||
|
||||
当前实现范围(第一阶段):
|
||||
1) 从 AI 表格「37°人资领域相关工作台账-银行卡变更收集表」拉取待处理行;
|
||||
2) 下载员工上传的银行卡卡号面照片、持卡人身份证照片;
|
||||
3) 用 desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 输出核对工作簿;识别不出或不一致的进异常名单,推送钉钉群提醒人事手动处理。
|
||||
HR 系统「薪资管理-工资数据-工资卡管理」的写入留到后续阶段。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
|
||||
# ==================== 钉钉 AI 表格 ====================
|
||||
# 人资 base(XQ0034/XQ0035/XQ0037 同一套);sheet 为「银行卡-变更收集表」
|
||||
AI_BASE = "hr"
|
||||
AI_SHEET = "uavChPe"
|
||||
|
||||
# 企业内部应用凭证(与 XQ0012/XQ0034 同一应用;插件自包含,不读根 .env)
|
||||
DINGTALK_APP_KEY = "dingc1fnokzybr3u5bbl"
|
||||
DINGTALK_APP_SECRET = "AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A"
|
||||
AITABLE_OPERATOR_UNIONID = "o3mB4s7fjPUtELmYbl5Q3AiEiE" # 人资专用号(固定操作人)
|
||||
|
||||
# 待处理判定:以下任一字段为空即需要处理(用户 2026-11-17 明确口径)
|
||||
PENDING_FIELDS = ("是否更新HR系统", "收到纸质资料", "登记日期")
|
||||
|
||||
# ==================== AI 表格字段名 ====================
|
||||
F_EMP_NAME = "员工姓名" # 人员字段
|
||||
F_EMP_NO = "员工姓名.工号" # 人员字段带出的工号(文本列)
|
||||
F_HOLDER = "持卡人姓名"
|
||||
F_BANK = "开户银行"
|
||||
F_CARD = "银行卡号"
|
||||
F_ID = "持卡人身份证号"
|
||||
F_REASON = "变更原因"
|
||||
F_DONE = "是否更新HR系统"
|
||||
F_PAPER = "收到纸质资料"
|
||||
F_REG_DATE = "登记日期"
|
||||
F_CARD_IMG = "银行卡卡号面照片"
|
||||
F_ID_IMG = "持卡人身份证照片"
|
||||
F_REMARK = "具体说明"
|
||||
F_UNIT = "单位"
|
||||
F_TRUST = "是否委托发放"
|
||||
|
||||
REASON_CASH_KEYWORD = "现金" # 变更原因含「现金」=> 改现金发放,不做影像核对
|
||||
|
||||
# ==================== 输出 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\银行卡更新"
|
||||
RESULT_STEM = "银行卡变更核对结果"
|
||||
IMAGE_DIR_NAME = "images"
|
||||
DEFAULT_KEEP_FILES = 30 # 结果工作簿 + 每批影像目录的留档份数
|
||||
|
||||
_RESULT_FILE_RE = re.compile(rf"^{re.escape(RESULT_STEM)}_(\d{{8}}_\d{{6}})(?:_(\d+))?\.xlsx$")
|
||||
|
||||
SHEET_FULL = "核对结果"
|
||||
SHEET_ABNORMAL = "异常名单"
|
||||
|
||||
|
||||
def blank(value):
|
||||
"""AI 表格字段是否为空(None / 空串 / 空列表 / 空字典)。"""
|
||||
if value is None:
|
||||
return True
|
||||
if isinstance(value, str):
|
||||
return not value.strip()
|
||||
if isinstance(value, (list, dict, tuple, set)):
|
||||
return len(value) == 0
|
||||
return False
|
||||
|
||||
|
||||
def text(value):
|
||||
"""字段值 → 去首尾空白的字符串(列表取首项,dict 取 name/text/value)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, str):
|
||||
return value.strip()
|
||||
if isinstance(value, (int, float)):
|
||||
return str(value).strip()
|
||||
if isinstance(value, dict):
|
||||
for key in ("name", "text", "value", "title"):
|
||||
if value.get(key):
|
||||
return str(value[key]).strip()
|
||||
return ""
|
||||
if isinstance(value, (list, tuple)):
|
||||
parts = [text(v) for v in value]
|
||||
return "、".join(p for p in parts if p)
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def safe_name(value, fallback="未命名"):
|
||||
"""目录/文件名安全化:去掉 Windows 非法字符与换行。"""
|
||||
s = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", text(value) or "")
|
||||
s = s.strip(" ._")
|
||||
return s[:60] or fallback
|
||||
|
||||
|
||||
def build_result_path(save_dir):
|
||||
"""带时间戳的结果工作簿路径,同一秒重复运行追加序号。"""
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
path = os.path.join(save_dir, f"{RESULT_STEM}_{stamp}.xlsx")
|
||||
seq = 2
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{RESULT_STEM}_{stamp}_{seq}.xlsx")
|
||||
seq += 1
|
||||
return path
|
||||
|
||||
|
||||
def normalize_keep(value):
|
||||
try:
|
||||
n = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_KEEP_FILES
|
||||
return max(n, 0)
|
||||
|
||||
|
||||
def cleanup_old_results(save_dir, keep=DEFAULT_KEEP_FILES, protect=None):
|
||||
"""只清理本插件命名规则的历史工作簿,其它文件一律不动。"""
|
||||
if keep <= 0 or not os.path.isdir(save_dir):
|
||||
return []
|
||||
try:
|
||||
names = os.listdir(save_dir)
|
||||
except OSError as e:
|
||||
logger.warning("清理历史结果失败:无法读取目录 %s(%s)", save_dir, e)
|
||||
return []
|
||||
|
||||
files = []
|
||||
for name in names:
|
||||
m = _RESULT_FILE_RE.match(name)
|
||||
if m:
|
||||
files.append(((m.group(1), int(m.group(2) or 1)),
|
||||
os.path.abspath(os.path.join(save_dir, name))))
|
||||
files.sort(key=lambda item: item[0], reverse=True)
|
||||
|
||||
keep_abs = {os.path.abspath(protect)} if protect else set()
|
||||
removed = []
|
||||
for _, full in files:
|
||||
if full in keep_abs:
|
||||
continue
|
||||
if len(keep_abs) < keep:
|
||||
keep_abs.add(full)
|
||||
continue
|
||||
try:
|
||||
os.remove(full)
|
||||
removed.append(os.path.basename(full))
|
||||
except OSError as e:
|
||||
logger.warning("清理历史结果失败:%s(%s)", os.path.basename(full), e)
|
||||
if removed:
|
||||
logger.info("已清理历史结果 %d 份(保留最近 %d 份)", len(removed), keep)
|
||||
return removed
|
||||
|
||||
|
||||
def cleanup_old_images(image_root, keep=DEFAULT_KEEP_FILES, protect=None):
|
||||
"""按批次目录清理历史影像(目录名以 20 开头的时间戳),保留最近 keep 批。"""
|
||||
if keep <= 0 or not os.path.isdir(image_root):
|
||||
return []
|
||||
try:
|
||||
names = [n for n in os.listdir(image_root)
|
||||
if re.match(r"^\d{8}_\d{6}", n) and os.path.isdir(os.path.join(image_root, n))]
|
||||
except OSError as e:
|
||||
logger.warning("清理历史影像失败:无法读取目录 %s(%s)", image_root, e)
|
||||
return []
|
||||
names.sort(reverse=True)
|
||||
keep_abs = {os.path.abspath(protect)} if protect else set()
|
||||
removed = []
|
||||
for name in names:
|
||||
full = os.path.abspath(os.path.join(image_root, name))
|
||||
if full in keep_abs:
|
||||
continue
|
||||
if len(keep_abs) < keep:
|
||||
keep_abs.add(full)
|
||||
continue
|
||||
try:
|
||||
shutil.rmtree(full)
|
||||
removed.append(name)
|
||||
except OSError as e:
|
||||
logger.warning("清理历史影像失败:%s(%s)", name, e)
|
||||
if removed:
|
||||
logger.info("已清理历史影像 %d 批(保留最近 %d 批)", len(removed), keep)
|
||||
return removed
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到底座 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 data 子包。"""
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 数据层:AI 表格读取与影像下载。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from dingtalk_sdk.aitable import AiTable, attachment_items, flatten
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_client():
|
||||
"""创建 AI 表格客户端(凭证内置,不依赖执行机 .env)。"""
|
||||
return AiTable(
|
||||
app_key=config.DINGTALK_APP_KEY,
|
||||
app_secret=config.DINGTALK_APP_SECRET,
|
||||
operator=config.AITABLE_OPERATOR_UNIONID,
|
||||
log=lambda m: config.logger.debug(m),
|
||||
)
|
||||
|
||||
|
||||
def list_pending(cli):
|
||||
"""拉全表并按「是否更新HR系统 / 收到纸质资料 / 登记日期 任一为空」筛选。"""
|
||||
records = cli.records(config.AI_BASE, config.AI_SHEET)
|
||||
items = []
|
||||
for rec in records:
|
||||
fields = rec.get("fields") or {}
|
||||
triggers = [name for name in config.PENDING_FIELDS if config.blank(fields.get(name))]
|
||||
if not triggers:
|
||||
continue
|
||||
row = flatten(rec)
|
||||
holder = config.text(row.get(config.F_HOLDER)) or config.text(row.get(config.F_EMP_NAME))
|
||||
items.append({
|
||||
"record_id": rec.get("id") or rec.get("recordId") or "",
|
||||
"fields": fields,
|
||||
"row": row,
|
||||
"triggers": triggers,
|
||||
"reason": config.text(row.get(config.F_REASON)),
|
||||
"holder": holder,
|
||||
"emp_no": config.text(row.get(config.F_EMP_NO)),
|
||||
"errors": [],
|
||||
"images": [],
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def download_images(cli, item, batch_dir):
|
||||
"""下载一条记录的银行卡/身份证照片到批次目录,返回本地路径列表。"""
|
||||
fields = item["fields"]
|
||||
folder = os.path.join(
|
||||
batch_dir,
|
||||
config.safe_name(f"{item.get('emp_no') or '无工号'}_{item.get('holder') or '无姓名'}"),
|
||||
)
|
||||
saved = []
|
||||
expected = 0
|
||||
for field, prefix in ((config.F_CARD_IMG, "银行卡"), (config.F_ID_IMG, "身份证")):
|
||||
attachments = attachment_items(fields.get(field))
|
||||
expected += len(attachments)
|
||||
if not attachments:
|
||||
continue
|
||||
try:
|
||||
got = cli.download_attachments(fields.get(field), folder,
|
||||
prefix=f"{prefix}_", col=field)
|
||||
except Exception as e: # 预签名过期/网络异常 → 转人工
|
||||
item["errors"].append(f"{field}下载失败:{e}")
|
||||
config.logger.warning("%s %s 下载失败:%s", item.get("emp_no"), field, e)
|
||||
continue
|
||||
for g in got:
|
||||
if g.get("path"):
|
||||
saved.append(g["path"])
|
||||
item["images"] = saved
|
||||
item["expected_images"] = expected
|
||||
item["image_dir"] = folder if saved else ""
|
||||
return saved
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 logic 子包。"""
|
||||
@@ -0,0 +1,92 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 识别层:调用 desktopauto 的银行卡/身份证识别能力。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
|
||||
def _digit_runs(results):
|
||||
runs = []
|
||||
for res in results:
|
||||
for raw in (res.get("raw") or []):
|
||||
runs.extend(raw.get("digit_runs") or [])
|
||||
return runs
|
||||
|
||||
|
||||
def _best(results, kind, prefer):
|
||||
"""在同一条记录的多张照片里取最优识别结果(优先校验通过,其次位数更长)。"""
|
||||
cands = [r.get(kind) or {} for r in results if (r.get(kind) or {})]
|
||||
if not cands:
|
||||
return {}
|
||||
return max(cands, key=lambda c: (1 if c.get(prefer) else 0,
|
||||
len(str(c.get("number") or ""))))
|
||||
|
||||
|
||||
def _enhance(paths, bank_hint):
|
||||
"""常规识别读不出卡号时,用浮雕增强接口兜底(只采信 Luhn 自身合法的高置信结果)。"""
|
||||
try:
|
||||
from desktopauto import read_bank_card_number
|
||||
except Exception: # noqa: BLE001 老版本 SDK 没有该接口
|
||||
return None
|
||||
best = None
|
||||
for path in paths:
|
||||
try:
|
||||
r = read_bank_card_number(path, face_text=bank_hint)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if r.status == "ok":
|
||||
return r
|
||||
if best is None or _erank(r) > _erank(best):
|
||||
best = r
|
||||
return best
|
||||
|
||||
|
||||
def _erank(r):
|
||||
level = {"high": 3, "medium": 2, "low": 1}.get(r.confidence, 0)
|
||||
return (1 if r.luhn_ok else 0, level, len(r.candidates))
|
||||
|
||||
|
||||
def recognize(paths, expected_name=""):
|
||||
"""识别一批照片,合并出身份证/银行卡最佳结果。
|
||||
|
||||
Returns:
|
||||
{"id": {...}, "bank": {...}, "runs": [...], "errors": [...], "files": [...]}
|
||||
"""
|
||||
from desktopauto.cardocr.pipeline import analyze_image
|
||||
|
||||
results, errors = [], []
|
||||
for path in paths:
|
||||
try:
|
||||
results.append(analyze_image(path, expected_name=expected_name))
|
||||
except Exception as e:
|
||||
errors.append(f"{os.path.basename(path)}:{e}")
|
||||
|
||||
idc = _best(results, "id_card", "checksum_ok")
|
||||
bk = _best(results, "bank_card", "luhn_ok")
|
||||
bank = {
|
||||
"number": str(bk.get("number") or ""),
|
||||
"bank": str(bk.get("bank") or ""),
|
||||
"luhn_ok": bool(bk.get("luhn_ok")),
|
||||
}
|
||||
# 常规通道没读到可信卡号:浮雕/反光增强兜底;仍不合法则只留候选,交人工
|
||||
if not bank["luhn_ok"]:
|
||||
enh = _enhance(paths, bank["bank"])
|
||||
if enh is not None and enh.status == "ok":
|
||||
bank.update(number=enh.number, bank=enh.bank or bank["bank"],
|
||||
luhn_ok=True, confidence=enh.confidence, source="enhance")
|
||||
elif enh is not None:
|
||||
bank["confidence"] = enh.confidence
|
||||
# 只有「差 1~2 位就能通过校验」的候选才值得给人看;差太多的是噪声
|
||||
if enh.candidates and enh.candidates[0].get("cost", 9) <= 2:
|
||||
bank["candidates"] = [c["number"] for c in enh.candidates]
|
||||
return {
|
||||
"id": {
|
||||
"number": str(idc.get("number") or ""),
|
||||
"name": str(idc.get("name") or ""),
|
||||
"checksum_ok": bool(idc.get("checksum_ok")),
|
||||
},
|
||||
"bank": bank,
|
||||
"runs": _digit_runs(results),
|
||||
"errors": errors,
|
||||
"files": list(paths),
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 流程编排:拉取待处理行 → 下载影像 → 识别 → 判定 → 输出/提醒。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
from ..data.ai_table import download_images, list_pending, open_client
|
||||
from ..report.notify import send_markdown
|
||||
from ..report.workbook import write_workbook
|
||||
from .recognize import recognize
|
||||
from .verify import verify
|
||||
|
||||
|
||||
def _push_text(rows, stats, path):
|
||||
lines = [
|
||||
"### 银行卡变更影像核对(XQ0084)",
|
||||
f"- 待处理:**{stats['total']}** 条;通过 **{stats['passed']}**、"
|
||||
f"需人工 **{stats['manual']}**、现金发放 **{stats['cash']}**",
|
||||
"- 触发原因:未更新HR系统 {0} / 未收纸质资料 {1} / 缺登记日期 {2}".format(
|
||||
stats["trigger"][config.F_DONE],
|
||||
stats["trigger"][config.F_PAPER],
|
||||
stats["trigger"][config.F_REG_DATE],
|
||||
),
|
||||
]
|
||||
manual = [r for r in rows if r["conclusion"] == "需人工核实"]
|
||||
if manual:
|
||||
lines.append(f"#### 需人工核实({len(manual)})")
|
||||
for r in manual[:20]:
|
||||
lines.append(f"- {r['holder']}({r['emp_no']}):{r['notes'][:120]}")
|
||||
if len(manual) > 20:
|
||||
lines.append(f"- …… 其余 {len(manual) - 20} 条见结果文件")
|
||||
lines.append(f"- 结果文件:{path}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run_verify(save_dir, keep_files=config.DEFAULT_KEEP_FILES, push_webhook="",
|
||||
push_secret="", limit_rows=0, progress=None):
|
||||
p = progress or (lambda _pct: None)
|
||||
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||
image_batch = os.path.join(save_dir, config.IMAGE_DIR_NAME, stamp)
|
||||
os.makedirs(image_batch, exist_ok=True)
|
||||
p(3)
|
||||
|
||||
with open_client() as cli:
|
||||
items = list_pending(cli)
|
||||
config.logger.info("AI 表格待处理记录:%d 条(筛选:%s 任一为空)",
|
||||
len(items), "、".join(config.PENDING_FIELDS))
|
||||
if limit_rows and limit_rows > 0:
|
||||
items = items[:limit_rows]
|
||||
config.logger.info("按配置仅处理前 %d 条", len(items))
|
||||
if not items:
|
||||
return {"path": "", "rows": [], "stats": _stats([], []),
|
||||
"push": {"success": False, "message": "无待处理记录"},
|
||||
"cleaned": [], "batch_dir": image_batch}
|
||||
|
||||
# 1) 先集中下载影像(预签名有效期短,避免识别耗时导致后续地址过期)
|
||||
for i, item in enumerate(items):
|
||||
if config.REASON_CASH_KEYWORD in (item.get("reason") or ""):
|
||||
continue
|
||||
download_images(cli, item, image_batch)
|
||||
p(5 + int(20 * (i + 1) / len(items)))
|
||||
|
||||
# 2) 逐条识别 + 判定
|
||||
rows = []
|
||||
for i, item in enumerate(items):
|
||||
if config.REASON_CASH_KEYWORD in (item.get("reason") or ""):
|
||||
ocr = {}
|
||||
else:
|
||||
ocr = recognize(item.get("images") or [], expected_name=item.get("holder") or "")
|
||||
result = verify(item, ocr)
|
||||
rows.append(result)
|
||||
config.logger.info("%s %s(%s)→ %s%s",
|
||||
result["emp_no"], result["holder"], result["reason"],
|
||||
result["conclusion"],
|
||||
f":{result['notes']}" if result["notes"] else "")
|
||||
p(25 + int(65 * (i + 1) / len(items)))
|
||||
|
||||
stats = _stats(rows, items)
|
||||
path = write_workbook(rows, config.build_result_path(save_dir))
|
||||
p(94)
|
||||
|
||||
cleaned = config.cleanup_old_results(save_dir, keep_files, protect=path)
|
||||
config.cleanup_old_images(os.path.join(save_dir, config.IMAGE_DIR_NAME), keep_files,
|
||||
protect=image_batch)
|
||||
|
||||
push = {"success": False, "message": "无需推送(无异常)"}
|
||||
if stats["manual"] and push_webhook:
|
||||
push = send_markdown(push_webhook, push_secret, "银行卡变更影像核对异常",
|
||||
_push_text(rows, stats, path))
|
||||
p(100)
|
||||
return {"path": path, "rows": rows, "stats": stats, "push": push,
|
||||
"cleaned": cleaned, "batch_dir": image_batch}
|
||||
|
||||
|
||||
def _stats(rows, items):
|
||||
trigger = {name: 0 for name in config.PENDING_FIELDS}
|
||||
for item in items:
|
||||
for name in item.get("triggers") or []:
|
||||
trigger[name] = trigger.get(name, 0) + 1
|
||||
return {
|
||||
"total": len(rows),
|
||||
"passed": sum(1 for r in rows if r.get("conclusion") == "通过"),
|
||||
"manual": sum(1 for r in rows if r.get("conclusion") == "需人工核实"),
|
||||
"cash": sum(1 for r in rows if str(r.get("conclusion", "")).startswith("现金发放")),
|
||||
"trigger": trigger,
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 判定层:表格登记值与影像识别值的一致性核对。
|
||||
|
||||
判定口径(第一阶段,只核对不写 HR):
|
||||
- 一致 => 通过;
|
||||
- 不一致 / 无法识别 / 表格缺关键字段 / 多人一行 => 需人工核实;
|
||||
- 变更原因含「现金」=> 改现金发放,不做影像核对。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from desktopauto.cardocr.match import EXACT, PARTIAL, STRONG, WEAK, coverage, digits
|
||||
from desktopauto.cardocr.validators import bin_bank, id_checksum_ok, luhn_ok
|
||||
|
||||
from .. import config
|
||||
|
||||
LABEL = {EXACT: "一致", STRONG: "高度疑似", PARTIAL: "部分命中", WEAK: "无法识别"}
|
||||
|
||||
# 银行名称归一:去掉公司后缀后按关键字映射到统一简称
|
||||
_BANK_CANON = {
|
||||
"中国工商": "工商", "工商": "工商", "工行": "工商",
|
||||
"中国建设": "建设", "建设": "建设", "建行": "建设",
|
||||
"中国农业": "农业", "农业": "农业", "农行": "农业",
|
||||
"中国银行": "中行", "中行": "中行",
|
||||
"邮政储蓄": "邮储", "邮储": "邮储",
|
||||
"重庆农村商业": "重庆农商", "重庆农商": "重庆农商",
|
||||
"农村商业": "农商", "农村信用": "农商", "农商": "农商",
|
||||
"招商": "招商", "招行": "招商",
|
||||
"浦东发展": "浦发", "浦发": "浦发",
|
||||
"民生": "民生", "兴业": "兴业", "华夏": "华夏", "中信": "中信",
|
||||
"光大": "光大", "平安": "平安", "三峡": "三峡", "交通": "交通",
|
||||
}
|
||||
_BANK_KEYS = sorted(_BANK_CANON, key=len, reverse=True)
|
||||
|
||||
|
||||
def bank_core(name):
|
||||
s = re.sub(r"[\s()()·-]", "", config.text(name))
|
||||
for noise in ("股份有限公司", "有限责任公司", "有限公司", "分行", "支行", "银行"):
|
||||
s = s.replace(noise, "")
|
||||
for key in _BANK_KEYS:
|
||||
if key in s:
|
||||
return _BANK_CANON[key]
|
||||
return s
|
||||
|
||||
|
||||
def compare_bank(table_bank, ocr_bank):
|
||||
a, b = bank_core(table_bank), bank_core(ocr_bank)
|
||||
if not config.text(table_bank):
|
||||
return "表格缺失"
|
||||
if not b:
|
||||
return "无法识别"
|
||||
return "一致" if a == b else "不一致"
|
||||
|
||||
|
||||
def _status(value, truth, runs, card_mode, id_digits=""):
|
||||
"""用 match.coverage 判定识别值与登记值的命中程度。"""
|
||||
if not truth:
|
||||
return "表格缺失"
|
||||
if not value and not runs:
|
||||
return "无法识别"
|
||||
_cov, status, _run = coverage(truth, list(runs) + ([value] if value else []),
|
||||
card_mode=card_mode, id_digits=id_digits)
|
||||
return LABEL.get(status, "无法识别")
|
||||
|
||||
|
||||
def _is_multi(holder, table_id):
|
||||
return bool(re.search(r"[、,,;;/]", holder or "")) or bool(re.search(r"[\r\n、,,;;/]", table_id or ""))
|
||||
|
||||
|
||||
def verify(item, ocr):
|
||||
"""比对一条记录,返回核对结果 dict(字段见 report 输出列)。"""
|
||||
row = item.get("row") or {}
|
||||
holder = config.text(row.get(config.F_HOLDER))
|
||||
reason = config.text(row.get(config.F_REASON))
|
||||
table_card = digits(config.text(row.get(config.F_CARD)))
|
||||
table_id = digits(config.text(row.get(config.F_ID)))
|
||||
table_bank = config.text(row.get(config.F_BANK))
|
||||
done = config.text(row.get(config.F_DONE))
|
||||
|
||||
base = {
|
||||
"emp_no": config.text(row.get(config.F_EMP_NO)),
|
||||
"holder": holder or config.text(row.get(config.F_EMP_NAME)),
|
||||
"reason": reason,
|
||||
"triggers": "、".join(item.get("triggers") or []),
|
||||
"table_bank": table_bank,
|
||||
"table_card": table_card,
|
||||
"table_id": table_id,
|
||||
"ocr_id": "",
|
||||
"ocr_name": "",
|
||||
"ocr_card": "",
|
||||
"ocr_bank": "",
|
||||
"id_status": "-",
|
||||
"name_status": "-",
|
||||
"card_status": "-",
|
||||
"bank_status": "-",
|
||||
"self_check": "",
|
||||
"conclusion": "",
|
||||
"notes": "",
|
||||
"image_dir": item.get("image_dir") or "",
|
||||
"image_count": len(item.get("images") or []),
|
||||
}
|
||||
|
||||
# 改现金发放:HR 侧只改发放方式,不需要核对新卡影像
|
||||
if config.REASON_CASH_KEYWORD in reason:
|
||||
base["conclusion"] = "现金发放(无需影像核对)"
|
||||
base["notes"] = "变更原因为现金发放,HR 侧改为现金/卡号 0,无需核对银行卡与身份证影像"
|
||||
return base
|
||||
|
||||
runs = list((ocr or {}).get("runs") or [])
|
||||
ocr_id = digits((ocr or {}).get("id", {}).get("number") or "")
|
||||
ocr_name = config.text((ocr or {}).get("id", {}).get("name") or "")
|
||||
ocr_card = digits((ocr or {}).get("bank", {}).get("number") or "")
|
||||
ocr_bank = config.text((ocr or {}).get("bank", {}).get("bank") or "")
|
||||
base.update(ocr_id=ocr_id, ocr_name=ocr_name, ocr_card=ocr_card, ocr_bank=ocr_bank)
|
||||
|
||||
base["id_status"] = _status(ocr_id, table_id, runs, card_mode=False)
|
||||
base["card_status"] = _status(ocr_card, table_card, runs, card_mode=True, id_digits=ocr_id or table_id)
|
||||
if not table_id:
|
||||
base["id_status"] = "表格缺失"
|
||||
if not table_card:
|
||||
base["card_status"] = "表格缺失"
|
||||
|
||||
if not holder:
|
||||
base["name_status"] = "表格缺失"
|
||||
elif not ocr_name:
|
||||
base["name_status"] = "无法识别"
|
||||
elif _is_multi(holder, config.text(row.get(config.F_ID))):
|
||||
base["name_status"] = "多人未拆分"
|
||||
else:
|
||||
base["name_status"] = "一致" if ocr_name.replace(" ", "") == holder.replace(" ", "") else "不一致"
|
||||
base["bank_status"] = compare_bank(table_bank, ocr_bank)
|
||||
|
||||
blockers, notes = [], []
|
||||
if _is_multi(holder, config.text(row.get(config.F_ID))):
|
||||
blockers.append("持卡人为多人/多卡,需人工拆分核对")
|
||||
if not table_card:
|
||||
blockers.append("表格缺银行卡号")
|
||||
if not table_id:
|
||||
blockers.append("表格缺身份证号")
|
||||
if not holder:
|
||||
blockers.append("表格缺持卡人姓名")
|
||||
if not item.get("images"):
|
||||
blockers.append("未上传或未下载到银行卡/身份证影像")
|
||||
if base["id_status"] != "一致":
|
||||
blockers.append(f"身份证号{base['id_status']}")
|
||||
if base["card_status"] != "一致":
|
||||
blockers.append(f"银行卡号{base['card_status']}")
|
||||
if base["name_status"] == "不一致":
|
||||
blockers.append("持卡人姓名不一致")
|
||||
elif base["name_status"] == "无法识别":
|
||||
notes.append("身份证姓名未读出")
|
||||
if base["bank_status"] == "不一致":
|
||||
blockers.append("开户银行不一致")
|
||||
elif base["bank_status"] == "无法识别":
|
||||
notes.append("开户银行未读出")
|
||||
|
||||
# 浮雕/反光卡:增强识别给出若干通过 Luhn 的候选,供人工对照影像确认
|
||||
bank_info = (ocr or {}).get("bank", {})
|
||||
card_cands = bank_info.get("candidates") or []
|
||||
if card_cands and base["card_status"] != "一致":
|
||||
notes.append("卡号未读准,候选:" + "、".join(card_cands[:3]) + "(请对照影像人工确认)")
|
||||
elif bank_info.get("confidence") == "low" and base["card_status"] != "一致":
|
||||
notes.append("卡号反光/浮雕未读准,请对照影像人工录入")
|
||||
|
||||
# 表格自身校验:卡号位数/Luhn/BIN、身份证校验位
|
||||
issues = []
|
||||
if table_card:
|
||||
if len(table_card) not in (16, 18, 19):
|
||||
issues.append(f"卡号位数 {len(table_card)} 异常")
|
||||
else:
|
||||
if not luhn_ok(table_card):
|
||||
issues.append("卡号校验位不通过")
|
||||
guessed = bin_bank(table_card)
|
||||
if guessed and table_bank and bank_core(guessed) != bank_core(table_bank):
|
||||
issues.append(f"卡号 BIN({guessed}) 与开户银行({table_bank}) 不一致")
|
||||
if len(table_id) == 18 and not id_checksum_ok(table_id):
|
||||
issues.append("身份证校验位不通过")
|
||||
blockers.extend(issues)
|
||||
base["self_check"] = ";".join(issues)
|
||||
|
||||
for err in item.get("errors") or []:
|
||||
blockers.append(err)
|
||||
if (ocr or {}).get("errors"):
|
||||
blockers.append("影像识别异常:" + ";".join(ocr["errors"]))
|
||||
|
||||
if done == "是":
|
||||
notes.insert(0, "HR 系统已标记已更新,本次仅核对影像")
|
||||
|
||||
base["conclusion"] = "需人工核实" if blockers else "通过"
|
||||
base["notes"] = ";".join(blockers + notes)
|
||||
return base
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0084",
|
||||
"name": "银行卡更新EHR系统",
|
||||
"version": "0.1.0",
|
||||
"description": "读取人资 AI 表格「银行卡变更收集表」待处理行(是否更新HR系统/收到纸质资料/登记日期任一为空),下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行并比对;不一致或识别不出进异常名单提醒人事手动处理。当前阶段只核对不写 HR 系统。",
|
||||
"category": "人事薪酬",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": false,
|
||||
"capabilities": ["xq0084"],
|
||||
"permissions": {},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"desktopauto": {
|
||||
"compat": "^0.5"
|
||||
},
|
||||
"dingtalk_sdk": {
|
||||
"compat": "^0.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\银行卡更新",
|
||||
"description": "核对结果工作簿与下载影像的保存目录;每次运行独立留档,按留档份数自动清理旧文件"
|
||||
},
|
||||
"keep_files": {
|
||||
"type": "integer",
|
||||
"title": "结果留档份数",
|
||||
"default": 30,
|
||||
"description": "输出目录最多保留最近 N 份结果工作簿与 N 批影像(含本次);0 = 不清理"
|
||||
},
|
||||
"limit_rows": {
|
||||
"type": "integer",
|
||||
"title": "最多处理条数",
|
||||
"default": 0,
|
||||
"description": "0 = 处理全部待处理记录;调试时可填小数字只跑前几条"
|
||||
},
|
||||
"push_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉群机器人 Webhook",
|
||||
"default": "",
|
||||
"description": "留空=只导出不推送;存在异常时推送异常名单摘要(文本,文件需到输出目录自取)"
|
||||
},
|
||||
"push_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉机器人加签密钥",
|
||||
"format": "password",
|
||||
"default": "",
|
||||
"description": "机器人安全设置为「加签」时填写,未配置加签留空"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 report 子包。"""
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 提醒层:钉钉群机器人 Markdown 推送(仅标准库 + 项目级重试)。"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from ..config import logger
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"),
|
||||
digestmod=hashlib.sha256).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=""):
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = "&" if "?" in webhook else "?"
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
def send_markdown(webhook, secret, title, text):
|
||||
"""向群机器人推送 Markdown;webhook 为空时跳过。"""
|
||||
webhook = (webhook or "").strip()
|
||||
if not webhook:
|
||||
return {"success": False, "message": "未配置 Webhook,跳过推送"}
|
||||
payload = {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": title or "通知", "text": text or ""},
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
url = _build_url(webhook, (secret or "").strip())
|
||||
last_err = ""
|
||||
for attempt in range(1, DEFAULT_RETRY_TIMES + 1):
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, data=body, method="POST",
|
||||
headers={"Content-Type": "application/json; charset=utf-8"})
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT) as resp:
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
data = json.loads(raw) if raw else {}
|
||||
if data.get("errcode") == 0:
|
||||
logger.info("钉钉群消息推送成功")
|
||||
return {"success": True, "message": "ok"}
|
||||
last_err = f"errcode={data.get('errcode')} errmsg={data.get('errmsg')}"
|
||||
except Exception as e:
|
||||
last_err = str(e)
|
||||
logger.warning("钉钉推送第 %d/%d 次失败:%s", attempt, DEFAULT_RETRY_TIMES, last_err)
|
||||
if attempt < DEFAULT_RETRY_TIMES:
|
||||
time.sleep(1.0 * attempt)
|
||||
return {"success": False, "message": last_err}
|
||||
@@ -0,0 +1,79 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 输出层:核对结果工作簿。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from .. import config
|
||||
|
||||
COLUMNS = [
|
||||
("emp_no", "工号", 11),
|
||||
("holder", "持卡人姓名", 14),
|
||||
("reason", "变更原因", 24),
|
||||
("table_bank", "开户银行(表格)", 18),
|
||||
("table_card", "银行卡号(表格)", 23),
|
||||
("table_id", "身份证号(表格)", 23),
|
||||
("ocr_id", "身份证号(识别)", 23),
|
||||
("ocr_name", "姓名(识别)", 11),
|
||||
("ocr_card", "银行卡号(识别)", 23),
|
||||
("ocr_bank", "开户银行(识别)", 18),
|
||||
("id_status", "身份证核对", 11),
|
||||
("name_status", "姓名核对", 11),
|
||||
("card_status", "卡号核对", 11),
|
||||
("bank_status", "开户银行核对", 13),
|
||||
("self_check", "表格自检", 26),
|
||||
("triggers", "触发原因", 22),
|
||||
("conclusion", "核对结论", 22),
|
||||
("notes", "说明", 60),
|
||||
("image_count", "影像数", 8),
|
||||
("image_dir", "影像目录", 50),
|
||||
]
|
||||
|
||||
_HEAD_FILL = PatternFill("solid", fgColor="1F4E78")
|
||||
_HEAD_FONT = Font(color="FFFFFF", bold=True)
|
||||
_MANUAL_FILL = PatternFill("solid", fgColor="FFF2CC")
|
||||
_PASS_FILL = PatternFill("solid", fgColor="E2EFDA")
|
||||
_CASH_FILL = PatternFill("solid", fgColor="DDEBF7")
|
||||
|
||||
|
||||
def _write_sheet(ws, rows):
|
||||
ws.append([title for _, title, _ in COLUMNS])
|
||||
for col, (_, title, width) in enumerate(COLUMNS, start=1):
|
||||
cell = ws.cell(row=1, column=col)
|
||||
cell.fill = _HEAD_FILL
|
||||
cell.font = _HEAD_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
ws.row_dimensions[1].height = 24
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
for record in rows:
|
||||
ws.append([record.get(key, "") for key, _, _ in COLUMNS])
|
||||
r = ws.max_row
|
||||
for col in range(1, len(COLUMNS) + 1):
|
||||
ws.cell(row=r, column=col).alignment = Alignment(vertical="center", wrap_text=True)
|
||||
conclusion = record.get("conclusion", "")
|
||||
fill = (_MANUAL_FILL if conclusion == "需人工核实"
|
||||
else _CASH_FILL if conclusion.startswith("现金发放") else _PASS_FILL)
|
||||
ws.cell(row=r, column=[k for k, _, _ in COLUMNS].index("conclusion") + 1).fill = fill
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(COLUMNS))}{max(ws.max_row, 1)}"
|
||||
|
||||
|
||||
def write_workbook(rows, path):
|
||||
"""写出「核对结果 / 异常名单」两个 sheet。"""
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.SHEET_FULL
|
||||
_write_sheet(ws, rows)
|
||||
|
||||
abnormal = [r for r in rows if r.get("conclusion") == "需人工核实"]
|
||||
ws2 = wb.create_sheet(config.SHEET_ABNORMAL)
|
||||
_write_sheet(ws2, abnormal)
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
Reference in New Issue
Block a user