""" backend/app/services/voucher_check/engine_persistence.py 用途:新引擎批次、主体、单文件结果与通知审计的写入。 依赖:models.voucher_check 新表。 逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。SQLite 测试库的 BigInteger 主键不会自增,persist_notification 会补 id。 """ from __future__ import annotations from datetime import date, datetime from typing import Any from app import db from app.models.voucher_check import ( VoucherCheckFileResult, VoucherCheckNotification, VoucherCheckRun, VoucherCheckSubject, ) def create_run( *, schedule_run_id: int | None, run_no: str, profile_code: str, profile_version: str, profile_snapshot: dict[str, Any], period_month: date, mode: str, started_at: datetime, ) -> VoucherCheckRun: """创建 running 状态的检核批次。""" run = VoucherCheckRun( schedule_run_id=schedule_run_id, run_no=run_no, profile_code=profile_code, profile_version=profile_version, profile_snapshot_json=profile_snapshot, period_month=period_month, mode=mode, status="running", started_at=started_at, created_at=started_at, ) db.session.add(run) db.session.flush() return run def persist_engine_results( *, run: VoucherCheckRun, subjects: list[dict[str, Any]], file_results: list[dict[str, Any]], stats: dict[str, Any], now: datetime | None = None, ) -> None: """ 写入主体与单文件结果,并固化批次统计快照。 核心逻辑:file_results 是缺件/Excel 真相源;列表查询不再重算。 """ ts = now or datetime.utcnow() subject_ids: dict[str, int] = {} for item in subjects: invoice_no = str(item["invoice_no"]).strip() row = VoucherCheckSubject( run_id=run.id, invoice_no=invoice_no, invoice_date=item.get("invoice_date"), source_fingerprint=item.get("source_fingerprint"), attributes_json=item.get("attributes") or {}, created_at=ts, ) db.session.add(row) db.session.flush() subject_ids[invoice_no] = row.id for item in file_results: invoice_no = str(item["invoice_no"]).strip() db.session.add( VoucherCheckFileResult( run_id=run.id, subject_id=subject_ids.get(invoice_no), invoice_no=invoice_no, rule_code=str(item["rule_code"]), rule_name=str(item.get("rule_name") or item["rule_code"]), source_type=str(item.get("source_type") or "directory_scan"), expected_name=item.get("expected_name"), matched_name=item.get("matched_name"), source_folder_id=item.get("source_folder_id"), source_item_id=item.get("source_item_id"), archive_folder_id=item.get("archive_folder_id"), archive_item_id=item.get("archive_item_id"), source_path=item.get("source_path"), archive_path=item.get("archive_path"), status=str(item["status"]), missing_reason=item.get("missing_reason"), error_code=item.get("error_code"), error_message=item.get("error_message"), source_fingerprint=item.get("source_fingerprint"), checked_at=item.get("checked_at") or ts, created_at=ts, ) ) run.subject_count = int(stats.get("subject_count") or 0) run.archived_file_count = int(stats.get("archived_file_count") or 0) run.skipped_file_count = int(stats.get("skipped_file_count") or 0) run.missing_file_count = int(stats.get("missing_file_count") or 0) run.missing_invoice_count = int(stats.get("missing_invoice_count") or 0) run.technical_error_count = int(stats.get("technical_error_count") or 0) run.staged_file_count = int(stats.get("staged_file_count") or 0) run.stats_json = { "by_file_type": stats.get("by_file_type") or {}, "batch_status": stats.get("batch_status"), } run.status = str(stats.get("batch_status") or "completed") run.finished_at = ts db.session.flush() def persist_notification( *, run_id: int, excel_filename: str | None, recipient_user_ids: list[int], send_status: str, skip_reason: str | None, summary: dict[str, Any], sent_at: datetime | None, ) -> VoucherCheckNotification: """写入或覆盖本批次通知审计(一个 run 一条)。SQLite 测试库需显式补 BigInteger 主键。""" row = ( db.session.query(VoucherCheckNotification) .filter_by(run_id=run_id) .one_or_none() ) if row is None: row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow()) bind = db.session.get_bind() if bind is not None and bind.dialect.name == "sqlite": max_id = db.session.query(db.func.max(VoucherCheckNotification.id)).scalar() or 0 row.id = int(max_id) + 1 db.session.add(row) row.excel_filename = excel_filename row.recipient_user_ids_json = recipient_user_ids row.send_status = send_status row.skip_reason = skip_reason row.summary_json = summary row.sent_at = sent_at db.session.flush() return row def load_previous_archived_fingerprints( *, profile_code: str, period_month: date, exclude_run_id: int | None = None, ) -> dict[tuple[str, str], str]: """ 读取同 Profile+期间已归档文件的最新指纹,供增量跳过。 核心逻辑:按 file_results.id 倒序,每个 invoice+rule 只留一条 archived。 """ query = ( db.session.query(VoucherCheckFileResult, VoucherCheckRun) .join(VoucherCheckRun, VoucherCheckFileResult.run_id == VoucherCheckRun.id) .filter( VoucherCheckRun.profile_code == profile_code, VoucherCheckRun.period_month == period_month, VoucherCheckFileResult.status == "archived", ) .order_by(VoucherCheckFileResult.id.desc()) ) if exclude_run_id: query = query.filter(VoucherCheckFileResult.run_id != exclude_run_id) found: dict[tuple[str, str], str] = {} for result, _run in query.all(): key = (result.invoice_no, result.rule_code) if key in found: continue if result.source_fingerprint: found[key] = result.source_fingerprint return found