""" backend/app/services/voucher_check/runner.py 用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。 依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。 逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。 """ 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.services.voucher_check import adapters as _register_adapters # noqa: F401 from app.services.voucher_check.adapters.registry import get_adapter from app.services.voucher_check.aggregator import aggregate_file_results from app.services.voucher_check.config import load_engine_config from app.services.voucher_check.dms_client import SalesDmsClient from app.services.voucher_check.engine_persistence import ( create_run, load_previous_archived_fingerprints, persist_engine_results, ) from app.services.voucher_check.erp_repository import previous_period_bounds from app.services.voucher_check.excel_rows import to_excel_invoice_row from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition from app.services.voucher_check.profiles.sales import required_file_rules 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_invoice_count") or 0), "unqualified_count": int(voucher_summary.get("missing_invoice_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("subject_count") or 0)}, {"key": "missing_files", "label_key": "chat.voucherCheck.missingFiles", "value": int(voucher_summary.get("missing_file_count") or 0)}, {"key": "missing", "label_key": "chat.voucherCheck.missingInvoices", "value": int(voucher_summary.get("missing_invoice_count") or 0)}, {"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_file_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: """ 执行立账凭证周批次。 核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。 启动日志带 path=accounting-voucher-check,便于在全是 schedule 的 worker 输出中识别本任务。 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"] now = datetime.utcnow() current_app.logger.info( "[voucher-check] start name=%s path=accounting-voucher-check run_no=%s mode=%s", getattr(task, "name", None) or "立账凭证检核", run.run_no, mode, ) try: config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {}) profile = load_profile_definition(config.profile_code) ensure_published_profile(config.profile_code) SalesDmsClient.ensure_configured() except AppError as exc: send_failure_alert( task=task, run=run, stage="config", error_code=exc.code, error_message=exc.message, enabled=True, ) raise rules = required_file_rules(profile) period_month, _current, _start, _end = previous_period_bounds() period = period_month.strftime("%Y-%m") # [STEP 1] 拉取上月销售 invoice 清单 _update_progress(run, step="fetch_erp", label="拉取上月销售 invoice") try: subject_adapter = get_adapter(str(profile.get("subject_adapter") or "hxjm_apa")) subjects = subject_adapter.fetch(period_month=period_month, config=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(subjects), "period": period}, } ) if mode == "single": if not single_invoice: raise ValidationError( "single 模式必须提供 invoice_no", code="VOUCHER_CHECK.INVOICE_REQUIRED", ) subjects = [row for row in subjects if row.invoice_no == single_invoice] if not subjects: raise NotFoundError( "指定发票不在上一个月 ERP 集合", code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD", ) engine_run = create_run( schedule_run_id=run.id, run_no=str(run.run_no or f"VC-{run.id}"), profile_code=str(profile["profile_code"]), profile_version=str(profile["profile_version"]), profile_snapshot=profile, period_month=period_month, mode=mode, started_at=now, ) db.session.commit() scan_adapter = get_adapter("directory_scan") archive_adapter = get_adapter("dms_archive") force = mode in {"force_all", "single"} previous_fp = {} if force else load_previous_archived_fingerprints( profile_code=str(profile["profile_code"]), period_month=period_month, exclude_run_id=engine_run.id, ) # [STEP 2] 扫描六类类型目录(不调用 PO/OA 打印 Adapter) _update_progress( run, step="scan_dms", label="扫描销售开票附件类型目录", processed=0, voucher_summary={ "scope_code": config.scope_code, "period": period, "mode": mode, "subject_count": len(subjects), "missing_file_count": 0, "missing_invoice_count": 0, "skipped_file_count": 0, "technical_error_count": 0, "complete_invoice_count": 0, }, ) file_results: list[dict[str, Any]] = [] yyyy = f"{period_month.year:04d}" mm = f"{period_month.month:02d}" for idx, subject in enumerate(subjects, start=1): for rule in rules: rule_code = str(rule["code"]) expected = str(rule.get("filename_template") or "").replace("{invoice}", subject.invoice_no) prev_key = (subject.invoice_no, rule_code) outcome = scan_adapter.scan( period_month=period_month, invoice_no=subject.invoice_no, rule=rule, ) result: dict[str, Any] = { "invoice_no": subject.invoice_no, "invoice_date": subject.invoice_date, "rule_code": rule_code, "rule_name": rule.get("name") or rule_code, "source_type": "directory_scan", "expected_name": expected, "source_folder_id": outcome.folder_id, "source_path": outcome.folder_path, "checked_at": now, } if ( not force and outcome.status == "matched" and outcome.file and outcome.file.fingerprint and previous_fp.get(prev_key) == outcome.file.fingerprint ): result.update( { "status": "skipped", "matched_name": outcome.file.filename, "source_item_id": outcome.file.item_id, "source_fingerprint": outcome.file.fingerprint, } ) elif outcome.status == "technical_error": result.update( { "status": "technical_error", "error_code": outcome.error_code, "error_message": outcome.error_message, } ) elif outcome.status != "matched" or outcome.file is None: result.update( { "status": "missing", "missing_reason": "类型目录未找到匹配文件", } ) else: scanned = outcome.file result.update( { "matched_name": scanned.filename, "source_item_id": scanned.item_id, "source_fingerprint": scanned.fingerprint, } ) archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{subject.invoice_no}/{scanned.filename}" result["archive_path"] = archive_path if getattr(archive_adapter, "wired", False): try: archived = archive_adapter.archive( period_month=period_month, invoice_no=subject.invoice_no, file=scanned, rule=rule, ) extra = archived.extra or {} result.update( { "status": "archived", "archive_item_id": archived.item_id, "archive_folder_id": archived.folder_id, "archive_skipped_same_name": bool(extra.get("skipped_same_name")), } ) except ServiceUnavailableError as exc: result.update( { "status": "technical_error", "error_code": exc.code, "error_message": exc.message, } ) else: result["status"] = "staged" file_results.append(result) if idx % 20 == 0 or idx == len(subjects): preview = aggregate_file_results(file_results, rules=rules) _update_progress( run, step="scan_dms", label="扫描销售开票附件类型目录", processed=idx, voucher_summary={ "scope_code": config.scope_code, "period": period, "mode": mode, "subject_count": len(subjects), "missing_file_count": preview["missing_file_count"], "missing_invoice_count": preview["missing_invoice_count"], "skipped_file_count": preview["skipped_file_count"], "technical_error_count": preview["technical_error_count"], "complete_invoice_count": sum( 1 for row in preview["excel_rows"] if row["status"] == "完整" ), }, ) stats = aggregate_file_results(file_results, rules=rules) step_logs.append( { "step": "scan_dms", "status": "success", "detail": { "missing_files": stats["missing_file_count"], "missing_invoices": stats["missing_invoice_count"], "staged": stats["staged_file_count"], "skipped": stats["skipped_file_count"], "technical_error": stats["technical_error_count"], }, } ) # [STEP 3] 落库单文件结果 _update_progress(run, step="persist", label="写入检核记录") try: persist_engine_results( run=engine_run, subjects=[ { "invoice_no": row.invoice_no, "invoice_date": row.invoice_date, "source_fingerprint": row.source_fingerprint, "attributes": row.attributes, } for row in subjects ], file_results=file_results, stats=stats, 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 excel_filename = f"voucher_check_{profile['profile_code']}_{period}_{run.run_no}.xlsx" executed_at = now.strftime("%Y-%m-%d %H:%M:%S") details = [ to_excel_invoice_row(item, period=period, executed_at=executed_at) for item in stats["excel_rows"] ] # [STEP 4] 每批一条企微汇总 notify_status = send_batch_missing_summary( task=task, schedule_run=run, engine_run_id=engine_run.id, profile_code=str(profile["profile_code"]), period_month=period, stats=stats, excel_filename=excel_filename, enabled=config.notify_missing_enabled, ) step_logs.append( { "step": "notify", "status": "success", "detail": {"send_status": notify_status, "missing_files": stats["missing_file_count"]}, } ) complete_invoices = sum(1 for row in stats["excel_rows"] if row["status"] == "完整") voucher_summary = { "scope_code": config.scope_code, "period": period, "mode": mode, "engine_run_id": engine_run.id, "subject_count": stats["subject_count"], "missing_file_count": stats["missing_file_count"], "missing_invoice_count": stats["missing_invoice_count"], "skipped_file_count": stats["skipped_file_count"], "technical_error_count": stats["technical_error_count"], "staged_file_count": stats["staged_file_count"], "complete_invoice_count": complete_invoices, "notify_status": notify_status, } _update_progress( run, step="done", label="检核完成", processed=len(subjects), voucher_summary=voucher_summary, ) success_count = stats["subject_count"] failed_count = 1 if stats["batch_status"] == "technical_failed" and stats["missing_file_count"] == 0 else 0 return ( stats["subject_count"], success_count, failed_count, stats["skipped_file_count"], details, errors, step_logs, )