# -*- 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']}**", f"- 待处理口径:是否更新HR系统 为空 **{stats['trigger'].get('空', 0)}**、" f"为否 **{stats['trigger'].get('否', 0)}**", ] 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} 条见结果文件") branch_missing = [r for r in manual if "开户支行" in (r.get("notes") or "")] if branch_missing: lines.append(f"#### 工商银行缺开户支行({len(branch_missing)})") for r in branch_missing[:20]: lines.append(f"- {r['holder']}({r['emp_no']}):开户银行「{r.get('table_bank') or '未填'}」," f"未填具体支行/网点") if len(branch_missing) > 20: lines.append(f"- …… 其余 {len(branch_missing) - 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), config.PENDING_FIELD) 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 = {"空": 0, "否": 0} for item in items: for name in item.get("triggers") or []: key = name.split("=", 1)[-1] if "=" in name else name trigger[key] = trigger.get(key, 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, }