""" backend/app/services/voucher_check/query_service.py 用途:查询批次明细、当月缺资料与单票最新状态。 依赖:models.voucher_check、ScheduleRun。 逻辑:Tool API 与工作台 API 调用;不触发扫描。 """ from __future__ import annotations from datetime import date, datetime from typing import Any from app.core.errors import NotFoundError, ValidationError from app.models import ScheduleRun from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem from app.services.voucher_check.erp_repository import current_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, *_ = current_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 list_run_items( *, run_id: int, result: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: """分页查询批次明细。""" 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)) 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], }