Files
37duAutomation/plugins/XQ0001-0100/XQ0084 银行卡更新EHR系统/logic/runner.py
T
puddy de7eeee08f feat(plugin): XQ0084 0.1.1 插件界面 + 核对通过自动导入 HR 工资卡并回写台账
- 新增 ui-src(Vue3+Element Plus,v3 规范)与构建产物 ui/,plugin.json 开启 ui
- 接入 hr_sdk.wage_import:核对通过记录按身份证匹配导入工资卡,成功后回写「是否更新HR系统=是」
- 委托发放/缺开户银行记录跳过并注明原因,现金发放仍不导入;导入失败不中断出表与推送
- 工作簿新增 HR导入/说明列,推送正文补充导入统计;_pack 排除 ui-src 并校验 ui/index.html
2026-11-18 11:02:25 +08:00

133 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0084 流程编排:拉取待处理行 → 下载影像 → 识别 → 判定 → 导入 HR → 回写/输出/提醒。"""
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
from .wage import import_passed
def _push_text(rows, stats, path, hr=None):
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],
),
]
if hr and hr.get("enabled"):
lines.append(f"- HR 工资卡导入:成功 **{hr['imported']}**、失败 **{hr['failed']}**、"
f"跳过 **{hr['skipped']}**;台账已回写 **{hr['written']}** 条")
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} 条见结果文件")
failed = [r for r in rows if r.get("hr_status") == "导入失败"]
if failed:
lines.append(f"#### HR 导入失败({len(failed)})")
for r in failed[:10]:
lines.append(f"- {r['holder']}({r['emp_no']}):{r.get('hr_note', '')[:120]}")
if len(failed) > 10:
lines.append(f"- …… 其余 {len(failed) - 10} 条见结果文件")
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, write_hr=False, hr_session=None,
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([], []),
"hr": {"enabled": bool(write_hr)},
"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)
# 3) 闭环:核对通过 → 导入 HR 工资卡 → 回写 AI 表格(关闭时只核对出表)
hr = {"enabled": bool(write_hr)}
if write_hr:
if not hr_session:
raise RuntimeError("未获取到 HR 登录态,无法导入工资卡;请先在壳子登录 HR")
p(88)
hr = import_passed(rows, hr_session, progress=p)
hr["enabled"] = True
path = write_workbook(rows, config.build_result_path(save_dir))
p(98)
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)
abnormal = bool(stats["manual"] or any(r.get("hr_status") == "导入失败" for r in rows))
push = {"success": False, "message": "无需推送(无异常)"}
if abnormal and push_webhook:
push = send_markdown(push_webhook, push_secret, "银行卡变更影像核对异常",
_push_text(rows, stats, path, hr))
p(100)
return {"path": path, "rows": rows, "stats": stats, "hr": hr, "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,
}