""" backend/app/services/voucher_check/runner.py 用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。 依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。 逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。 """ from __future__ import annotations from datetime import datetime from typing import Any from flask import current_app from app import db from app.core.errors import AppError, NotFoundError, ServiceUnavailableError, ValidationError from app.models import ScheduleRun, ScheduleTask from app.models.voucher_check import VoucherCheckInvoiceState from app.services.voucher_check.config import load_voucher_check_config from app.services.voucher_check.erp_repository import fetch_month_invoices from app.services.voucher_check.excel_rows import to_excel_detail_row from app.services.voucher_check.notification import send_failure_alert, send_missing_notifications from app.services.voucher_check.persistence import persist_batch_results from app.services.voucher_check.share_scanner import ensure_share_healthy, scan_invoice_folder ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] def _extract_run_options(run: ScheduleRun) -> dict[str, Any]: payload = run.api_request_json if isinstance(run.api_request_json, dict) else {} options = payload.get("run_options") if not isinstance(options, dict): options = {} mode = str(options.get("mode") or "incremental").strip().lower() if mode not in {"incremental", "force_all", "single"}: mode = "incremental" invoice_no = options.get("invoice_no") invoice_no = str(invoice_no).strip() if invoice_no else None return {"mode": mode, "invoice_no": invoice_no} def _update_progress( run: ScheduleRun, *, step: str, label: str, processed: int = 0, voucher_summary: dict[str, Any] | None = None, ) -> None: summary = dict(run.response_summary_json or {}) summary["current_step"] = { "step": step, "label": label, "processed_count": processed, } if voucher_summary: summary["voucher_check"] = voucher_summary summary["file_judgement"] = { "qualified_count": int(voucher_summary.get("complete_count") or 0), "unqualified_count": int(voucher_summary.get("missing_count") or 0), "manual_count": 0, "system_error_count": int(voucher_summary.get("technical_error_count") or 0), } summary["progress_metrics"] = [ {"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("total_count") or 0)}, {"key": "scan", "label_key": "chat.voucherCheck.scanned", "value": int(voucher_summary.get("scan_count") or 0)}, {"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_count") or 0)}, {"key": "complete", "label_key": "chat.voucherCheck.complete", "value": int(voucher_summary.get("complete_count") or 0)}, {"key": "missing", "label_key": "chat.voucherCheck.missing", "value": int(voucher_summary.get("missing_count") or 0)}, ] summary["domain_notification_managed"] = True run.response_summary_json = summary db.session.commit() def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ 执行立账凭证检核批次。 核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。 Returns: ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs) """ step_logs: list[dict[str, Any]] = [] errors: list[str] = [] options = _extract_run_options(run) mode = options["mode"] single_invoice = options["invoice_no"] try: config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {}) except AppError as exc: send_failure_alert( task=task, run=run, stage="config", error_code=exc.code, error_message=exc.message, enabled=True, ) raise # [STEP 1] 拉取 ERP 当月发票清单 _update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证") try: period_month, invoices = fetch_month_invoices(config) except ServiceUnavailableError as exc: send_failure_alert( task=task, run=run, stage="fetch_erp", error_code=exc.code, error_message=exc.message, enabled=config.notify_failure_enabled, ) raise step_logs.append( { "step": "fetch_erp", "status": "success", "detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")}, } ) if mode == "single": if not single_invoice: raise ValidationError( "single 模式必须提供 invoice_no", code="VOUCHER_CHECK.INVOICE_REQUIRED", ) invoices = [row for row in invoices if row.invoice_no == single_invoice] if not invoices: raise NotFoundError( "指定发票不在当前月 ERP 集合", code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD", ) # [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing) _update_progress(run, step="share_health", label="检查共享盘可用性") try: root = ensure_share_healthy(config) except ServiceUnavailableError as exc: send_failure_alert( task=task, run=run, stage="share_health", error_code=exc.code, error_message=exc.message, enabled=config.notify_failure_enabled, ) raise step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}}) # [STEP 3] 读取历史状态,供增量判定 existing_states = ( db.session.query(VoucherCheckInvoiceState) .filter_by(scope_code=config.scope_code, period_month=period_month) .all() ) state_map = {s.invoice_no: s for s in existing_states} results: list[dict[str, Any]] = [] complete_count = 0 missing_count = 0 skipped_count = 0 technical_error_count = 0 now = datetime.utcnow() force = mode in {"force_all", "single"} # [STEP 4] 逐票扫描 / 指纹比对 _update_progress( run, step="scan_share", label="扫描共享盘文件名", processed=0, voucher_summary={ "scope_code": config.scope_code, "period": period_month.strftime("%Y-%m"), "mode": mode, "total_count": len(invoices), "complete_count": 0, "missing_count": 0, "scan_count": 0, "skipped_count": 0, "technical_error_count": 0, }, ) for idx, row in enumerate(invoices, start=1): hist = state_map.get(row.invoice_no) scan = scan_invoice_folder( config, root=root, period_month=period_month, invoice_no=row.invoice_no, ) # 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹) can_skip = ( not force and hist is not None and hist.status == "complete" and hist.material_fingerprint and scan.result == "complete" and scan.material_fingerprint == hist.material_fingerprint ) if can_skip: item = { "invoice_no": row.invoice_no, "invoice_date": row.invoice_date, "result": "skipped", "folder_path": scan.folder_path, "folder_exists": scan.folder_exists, "material_fingerprint": scan.material_fingerprint, "matched_files": scan.matched_files, "missing_materials": [], "checked_at": None, } skipped_count += 1 elif scan.result == "technical_error": item = { "invoice_no": row.invoice_no, "invoice_date": row.invoice_date, "result": "technical_error", "folder_path": scan.folder_path, "folder_exists": False, "material_fingerprint": None, "matched_files": {}, "missing_materials": [], "error_code": scan.error_code, "error_message": scan.error_message, "checked_at": now, } technical_error_count += 1 else: item = { "invoice_no": row.invoice_no, "invoice_date": row.invoice_date, "result": scan.result, "folder_path": scan.folder_path, "folder_exists": scan.folder_exists, "material_fingerprint": scan.material_fingerprint, "matched_files": scan.matched_files, "missing_materials": scan.missing_materials, "checked_at": now, } if scan.result == "complete": complete_count += 1 else: missing_count += 1 results.append(item) if idx % 20 == 0 or idx == len(invoices): scan_count = complete_count + missing_count + technical_error_count _update_progress( run, step="scan_share", label="扫描共享盘文件名", processed=idx, voucher_summary={ "scope_code": config.scope_code, "period": period_month.strftime("%Y-%m"), "mode": mode, "total_count": len(invoices), "complete_count": complete_count, "missing_count": missing_count, "scan_count": scan_count, "skipped_count": skipped_count, "technical_error_count": technical_error_count, }, ) step_logs.append( { "step": "scan_share", "status": "success", "detail": { "complete": complete_count, "missing": missing_count, "skipped": skipped_count, "technical_error": technical_error_count, }, } ) # [STEP 5] 事务落库 _update_progress(run, step="persist", label="写入检核记录") try: persist_batch_results( schedule_run_id=run.id, scope_code=config.scope_code, period_month=period_month, items=results, now=now, ) db.session.commit() except Exception as exc: db.session.rollback() current_app.logger.error("[voucher-check] persist failed run_id=%s: %s", run.id, exc, exc_info=True) send_failure_alert( task=task, run=run, stage="persist", error_code="VOUCHER_CHECK.PERSIST_FAILED", error_message=str(exc), enabled=config.notify_failure_enabled, ) raise # [STEP 6] 缺资料通知 missing_items = [r for r in results if r["result"] == "missing"] notified = send_missing_notifications( task=task, run=run, scope_code=config.scope_code, period_month=period_month, missing_items=missing_items, same_day_dedup=config.same_day_dedup_enabled, enabled=config.notify_missing_enabled, ) step_logs.append( { "step": "notify", "status": "success", "detail": {"missing": len(missing_items), "notified": notified}, } ) period = period_month.strftime("%Y-%m") scan_count = complete_count + missing_count + technical_error_count voucher_summary = { "scope_code": config.scope_code, "period": period, "mode": mode, "total_count": len(invoices), "complete_count": complete_count, "missing_count": missing_count, "scan_count": scan_count, "skipped_count": skipped_count, "technical_error_count": technical_error_count, "missing_notification_count": notified, } _update_progress( run, step="done", label="检核完成", processed=len(invoices), voucher_summary=voucher_summary, ) details = [ to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results ] # success_count = complete + missing(业务成功);failed_count 仅技术异常 success_count = complete_count + missing_count total_count = len(invoices) return ( total_count, success_count, technical_error_count, skipped_count, details, errors, step_logs, )