""" backend/app/services/voucher_check/query_service.py 用途:查询检核批次列表、批次明细、兼容旧状态表,以及工作台强制重检入队。 依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。 逻辑:优先读新引擎表;无引擎批次时回退旧 run_items / invoice_states;强制重检写入 run_options.mode=force_all。 """ from __future__ import annotations from datetime import date, datetime from typing import Any from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ScheduleRun from app.models.voucher_check import ( VoucherCheckFileResult, VoucherCheckInvoiceState, VoucherCheckRun, VoucherCheckRunItem, ) from app.services.voucher_check.aggregator import aggregate_file_results from app.services.voucher_check.erp_repository import previous_period_bounds def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]: return { "id": state.id, "scope_code": state.scope_code, "period_month": state.period_month.isoformat() if state.period_month else None, "invoice_no": state.invoice_no, "invoice_date": state.invoice_date.isoformat() if state.invoice_date else None, "status": state.status, "folder_path": state.folder_path, "folder_exists": state.folder_exists, "material_fingerprint": state.material_fingerprint, "matched_files": state.matched_files_json or {}, "missing_materials": state.missing_materials_json or [], "last_actual_run_id": state.last_actual_run_id, "last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None, "last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None, "last_missing_notified_on": ( state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None ), "updated_at": state.updated_at.isoformat() if state.updated_at else None, } def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]: return { "id": item.id, "schedule_run_id": item.schedule_run_id, "invoice_state_id": item.invoice_state_id, "scope_code": item.scope_code, "period_month": item.period_month.isoformat() if item.period_month else None, "invoice_no": item.invoice_no, "invoice_date": item.invoice_date.isoformat() if item.invoice_date else None, "result": item.result, "folder_path": item.folder_path, "folder_exists": item.folder_exists, "material_fingerprint": item.material_fingerprint, "matched_files": item.matched_files_json or {}, "missing_materials": item.missing_materials_json or [], "error_code": item.error_code, "error_message": item.error_message, "checked_at": item.checked_at.isoformat() if item.checked_at else None, "created_at": item.created_at.isoformat() if item.created_at else None, } def parse_period_month(raw: str | None) -> date: """解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。""" if not raw: period_month, *_ = previous_period_bounds() return period_month text = str(raw).strip() try: if len(text) == 7: dt = datetime.strptime(text, "%Y-%m") else: dt = datetime.strptime(text[:10], "%Y-%m-%d") return date(dt.year, dt.month, 1) except ValueError as exc: raise ValidationError( "period 格式须为 YYYY-MM", code="VOUCHER_CHECK.CONFIG_INVALID", ) from exc def list_missing_states( *, task_id: int | None = None, scope_code: str = "HXJM", period: str | None = None, limit: int = 200, ) -> dict[str, Any]: """ 查询指定月份缺资料票(最新状态表)。 task_id 预留与排程绑定校验,本期仅用于响应回显。 """ period_month = parse_period_month(period) limit = max(1, min(int(limit or 200), 1000)) q = ( VoucherCheckInvoiceState.query.filter_by( scope_code=scope_code, period_month=period_month, status="missing", ) .order_by(VoucherCheckInvoiceState.invoice_no.asc()) .limit(limit) ) items = [_serialize_state(s) for s in q.all()] return { "task_id": task_id, "scope_code": scope_code, "period": period_month.strftime("%Y-%m"), "count": len(items), "items": items, } def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]: return { "id": run.id, "schedule_run_id": run.schedule_run_id, "run_no": run.run_no, "profile_code": run.profile_code, "period_month": run.period_month.strftime("%Y-%m") if run.period_month else None, "mode": run.mode, "status": run.status, "subject_count": int(run.subject_count or 0), "archived_file_count": int(run.archived_file_count or 0), "missing_file_count": int(run.missing_file_count or 0), "missing_invoice_count": int(run.missing_invoice_count or 0), "technical_error_count": int(run.technical_error_count or 0), "staged_file_count": int(run.staged_file_count or 0), "skipped_file_count": int(run.skipped_file_count or 0), "started_at": run.started_at.isoformat() if run.started_at else None, "finished_at": run.finished_at.isoformat() if run.finished_at else None, } def list_runs( *, period: str | None = None, profile_code: str | None = None, status: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: """工作台任务列表:按执行时间倒序返回引擎批次快照。""" page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) q = VoucherCheckRun.query if period: q = q.filter(VoucherCheckRun.period_month == parse_period_month(period)) if profile_code: q = q.filter(VoucherCheckRun.profile_code == str(profile_code).strip()) if status: q = q.filter(VoucherCheckRun.status == str(status).strip()) total = q.count() rows = ( q.order_by(VoucherCheckRun.id.desc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) return { "page": page, "page_size": page_size, "total": total, "items": [_serialize_engine_run(row) for row in rows], } def _engine_invoice_items(engine_run: VoucherCheckRun, *, result: str | None = None) -> list[dict[str, Any]]: rows = ( VoucherCheckFileResult.query.filter_by(run_id=engine_run.id) .order_by(VoucherCheckFileResult.invoice_no.asc(), VoucherCheckFileResult.id.asc()) .all() ) payload = [ { "invoice_no": row.invoice_no, "rule_code": row.rule_code, "rule_name": row.rule_name, "status": row.status, "invoice_date": None, } for row in rows ] rules = (engine_run.profile_snapshot_json or {}).get("file_rules") or [] aggregated = aggregate_file_results(payload, rules=rules) items: list[dict[str, Any]] = [] for excel_row in aggregated["excel_rows"]: missing = [ {"code": code, "name": next((r.get("name") for r in rules if r.get("code") == code), code)} for code, cell in (excel_row.get("cells") or {}).items() if cell == "缺件" ] mapped_status = { "完整": "complete", "缺件": "missing", "待处理": "pending", }.get(str(excel_row.get("status") or ""), "pending") if result and mapped_status != result: continue items.append( { "id": 0, "invoice_no": excel_row["invoice_no"], "invoice_date": None, "result": mapped_status, "cells": excel_row.get("cells") or {}, "status_label": excel_row.get("status"), "missing_materials": missing, "folder_path": None, "folder_exists": False, "error_code": None, "error_message": None, "checked_at": engine_run.finished_at.isoformat() if engine_run.finished_at else None, } ) return items def list_run_items( *, run_id: int, result: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: """分页查询批次明细;优先返回新引擎按 invoice 聚合行。""" run = ScheduleRun.query.get(run_id) if not run: raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND") page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) engine_run = ( VoucherCheckRun.query.filter_by(schedule_run_id=run_id) .order_by(VoucherCheckRun.id.desc()) .first() ) if engine_run is not None: items = _engine_invoice_items(engine_run, result=str(result).strip() if result else None) total = len(items) sliced = items[(page - 1) * page_size : page * page_size] return { "run_id": run_id, "engine_run_id": engine_run.id, "run_no": run.run_no, "page": page, "page_size": page_size, "total": total, "items": sliced, } q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id) if result: q = q.filter(VoucherCheckRunItem.result == str(result).strip()) total = q.count() rows = ( q.order_by(VoucherCheckRunItem.invoice_no.asc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) return { "run_id": run_id, "run_no": run.run_no, "page": page, "page_size": page_size, "total": total, "items": [_serialize_run_item(r) for r in rows], } def get_invoice_latest( *, invoice_no: str, scope_code: str = "HXJM", period: str | None = None, ) -> dict[str, Any]: """查询单票最新状态及近期批次快照。""" inv = str(invoice_no or "").strip() if not inv: raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED") period_month = parse_period_month(period) state = ( VoucherCheckInvoiceState.query.filter_by( scope_code=scope_code, period_month=period_month, invoice_no=inv, ).one_or_none() ) if not state: raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND") history = ( VoucherCheckRunItem.query.filter_by( scope_code=scope_code, period_month=period_month, invoice_no=inv, ) .order_by(VoucherCheckRunItem.id.desc()) .limit(20) .all() ) return { "state": _serialize_state(state), "recent_run_items": [_serialize_run_item(h) for h in history], } def list_states( *, scope_code: str = "HXJM", period: str | None = None, status: str | None = None, invoice_no: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: """工作台:按月/状态/发票号筛选最新状态。""" period_month = parse_period_month(period) page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) q = VoucherCheckInvoiceState.query.filter_by( scope_code=scope_code, period_month=period_month, ) if status: q = q.filter(VoucherCheckInvoiceState.status == str(status).strip()) if invoice_no: q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%")) total = q.count() rows = ( q.order_by(VoucherCheckInvoiceState.invoice_no.asc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) return { "scope_code": scope_code, "period": period_month.strftime("%Y-%m"), "page": page, "page_size": page_size, "total": total, "items": [_serialize_state(r) for r in rows], } def enqueue_force_all_run(*, triggered_by_user_id: int | None) -> dict[str, Any]: """ 将默认立账凭证排程以 force_all 入队,全量重检上一个自然月。 核心逻辑:复用周批 ScheduleTask;已有 queued/running 时冲突失败,不覆盖进行中的批次。 """ from app.services.schedule.queue_service import enqueue_manual_schedule_run from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule task = ensure_default_voucher_check_schedule(commit=True) if task is None: raise NotFoundError( "未找到立账凭证检核排程任务", code="VOUCHER_CHECK.SCHEDULE_NOT_FOUND", ) run, job_id, created = enqueue_manual_schedule_run( task.id, triggered_by_user_id=triggered_by_user_id, api_request_json={ "trigger_source": "workspace_force_all", "run_options": {"mode": "force_all"}, }, ) if not created: raise ConflictError( "立账凭证检核正在执行或排队中", code="VOUCHER_CHECK.RUN_IN_PROGRESS", details={"schedule_run_id": run.id, "run_no": run.run_no}, ) return { "schedule_task_id": task.id, "schedule_run_id": run.id, "run_no": run.run_no, "job_id": job_id, "mode": "force_all", "status": run.status, }