Files
syops/backend/app/services/voucher_check/query_service.py
T

435 lines
17 KiB
Python

"""
backend/app/services/voucher_check/query_service.py
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 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, ScheduleTask, User
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckRun,
)
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
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 _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 _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]:
"""
序列化尚未创建引擎批次的立账凭证排程记录。
核心逻辑:配置或外部依赖在引擎建批前失败时,仍须在工作台展示失败原因,
避免用户只能看到空列表而无法判断强制重检是否已执行。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
voucher_summary = summary.get("voucher_check") if isinstance(summary.get("voucher_check"), dict) else {}
period_month, *_ = previous_period_bounds()
return {
"id": run.id,
"schedule_run_id": run.id,
"run_no": run.run_no,
"profile_code": str(voucher_summary.get("profile_code") or "sales"),
"period_month": str(voucher_summary.get("period") or period_month.strftime("%Y-%m")),
"mode": str(voucher_summary.get("mode") or "incremental"),
# 工作台按引擎状态筛选;排程在建批前失败统一映射为技术失败。
"status": "technical_failed",
"subject_count": int(run.total_count or 0),
"archived_file_count": 0,
"missing_file_count": 0,
"missing_invoice_count": 0,
"technical_error_count": 1 if run.status == "failed" else 0,
"staged_file_count": 0,
"skipped_file_count": int(run.skipped_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,
"error_message": run.error_message,
}
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]:
"""
工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。
核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在
create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。
"""
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())
engine_rows = q.order_by(VoucherCheckRun.id.desc()).all()
engine_schedule_run_ids = {row.schedule_run_id for row in engine_rows if row.schedule_run_id}
fallback_query = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(
ScheduleTask.platform_api_path == "accounting-voucher-check",
ScheduleRun.status == "failed",
)
)
if status and str(status).strip() != "technical_failed":
fallback_rows: list[ScheduleRun] = []
else:
fallback_rows = fallback_query.order_by(ScheduleRun.id.desc()).all()
fallback_rows = [
row
for row in fallback_rows
if row.id not in engine_schedule_run_ids
and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m"))
]
merged = [_serialize_engine_run(row) for row in engine_rows]
merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows)
merged.sort(key=lambda row: row.get("finished_at") or row.get("started_at") or "", reverse=True)
total = len(merged)
rows = merged[(page - 1) * page_size : page * page_size]
return {
"page": page,
"page_size": page_size,
"total": total,
"items": rows,
}
def _serialize_file_type_rows(aggregated: dict[str, Any]) -> list[dict[str, Any]]:
"""
将聚合器的 by_file_type 转成工作台「按文件类型」表格行。
核心逻辑:缺失占比 = 该类型缺件 invoice 数 / 本批主体总数。
"""
subject_count = int(aggregated.get("subject_count") or 0)
by_type = aggregated.get("by_file_type") or {}
rows: list[dict[str, Any]] = []
for item in by_type.values():
if not isinstance(item, dict):
continue
missing_invoices = int(item.get("missing_invoice_count") or 0)
ratio = (missing_invoices / subject_count) if subject_count else 0.0
rows.append(
{
"rule_code": item.get("rule_code"),
"rule_name": item.get("rule_name"),
"missing_file_count": int(item.get("missing_file_count") or 0),
"missing_invoice_count": missing_invoices,
"missing_ratio": round(ratio, 4),
}
)
return rows
def _engine_invoice_items(engine_run: VoucherCheckRun) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
将单文件结果聚合成 invoice 行,并返回同一批的类型汇总。
核心逻辑:按 invoice 汇总缺件材料;类型汇总来自聚合器,不受 invoice 行筛选影响。
"""
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")
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,
"missing_count": len(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, aggregated
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 None:
return {
"run_id": run_id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": 0,
"items": [],
"subject_count": 0,
"by_file_type": [],
}
items, aggregated = _engine_invoice_items(engine_run)
result_filter = str(result).strip() if result else ""
if result_filter:
items = [row for row in items if row.get("result") == result_filter]
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,
"subject_count": int(aggregated.get("subject_count") or 0),
"by_file_type": _serialize_file_type_rows(aggregated),
}
def list_notifications(
*,
period: str | None = None,
send_status: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""
分页查询企微缺件汇总发送记录。
核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。
"""
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckNotification.query.join(
VoucherCheckRun,
VoucherCheckNotification.run_id == VoucherCheckRun.id,
)
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
status_filter = str(send_status or "").strip()
if status_filter:
q = q.filter(VoucherCheckNotification.send_status == status_filter)
total = q.count()
rows = (
q.order_by(VoucherCheckNotification.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
engine_runs = {
run.id: run
for run in VoucherCheckRun.query.filter(
VoucherCheckRun.id.in_([row.run_id for row in rows] or [0])
).all()
}
schedule_ids = [
engine_runs[row.run_id].schedule_run_id
for row in rows
if row.run_id in engine_runs and engine_runs[row.run_id].schedule_run_id
]
schedule_map = {
item.id: item
for item in ScheduleRun.query.filter(ScheduleRun.id.in_(schedule_ids or [0])).all()
}
recipient_ids: set[int] = set()
for row in rows:
for raw in row.recipient_user_ids_json or []:
try:
recipient_ids.add(int(raw))
except (TypeError, ValueError):
continue
users = {
user.id: user
for user in (User.query.filter(User.id.in_(recipient_ids)).all() if recipient_ids else [])
}
items: list[dict[str, Any]] = []
for row in rows:
engine_run = engine_runs.get(row.run_id)
summary = row.summary_json if isinstance(row.summary_json, dict) else {}
names: list[str] = []
for raw in row.recipient_user_ids_json or []:
try:
user = users.get(int(raw))
except (TypeError, ValueError):
user = None
if user:
names.append(str(user.real_name or user.username or user.id))
schedule_run_id = engine_run.schedule_run_id if engine_run else None
schedule_run = schedule_map.get(schedule_run_id) if schedule_run_id else None
items.append(
{
"id": row.id,
"run_id": row.run_id,
"schedule_run_id": schedule_run_id,
"run_no": (
(engine_run.run_no if engine_run else None)
or summary.get("run_no")
or (schedule_run.run_no if schedule_run else None)
),
"period_month": (
engine_run.period_month.strftime("%Y-%m")
if engine_run and engine_run.period_month
else summary.get("period")
),
"subject_count": int(
(engine_run.subject_count if engine_run else None) or summary.get("subject_count") or 0
),
"missing_file_count": int(
(engine_run.missing_file_count if engine_run else None)
or summary.get("missing_file_count")
or 0
),
"missing_invoice_count": int(
(engine_run.missing_invoice_count if engine_run else None)
or summary.get("missing_invoice_count")
or 0
),
"send_status": row.send_status,
"skip_reason": row.skip_reason,
"excel_filename": row.excel_filename or (schedule_run.excel_file_name if schedule_run else None),
"has_excel": bool(schedule_run and schedule_run.excel_file_name),
"recipient_names": names,
"sent_at": row.sent_at.isoformat() if row.sent_at else None,
"created_at": row.created_at.isoformat() if row.created_at else None,
}
)
return {
"page": page,
"page_size": page_size,
"total": total,
"items": items,
}
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.config import load_engine_config
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
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",
)
# [STEP 1] 入队前完成不依赖外部 IO 的配置预校验,避免 worker 失败后页面空白。
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()
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,
}