Files
syops/backend/app/services/voucher_check/query_service.py
T
2026-09-10 10:18:44 +08:00

750 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/voucher_check/query_service.py
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 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
from app.services.voucher_check.schedule_seed import DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
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",
details={"period": text},
) from exc
def parse_period_filter(raw: str | None) -> tuple[date | None, date | None]:
"""
将工作台列表 period 解析为 [start, end) 半开区间。
核心逻辑:空值不过滤;YYYY 覆盖该自然年;YYYY-MM / YYYY-MM-DD 覆盖该自然月。
Args:
raw: 查询参数 period,允许 YYYY、YYYY-MM、YYYY-MM-DD 或空。
Returns:
(start, end);空 period 时为 (None, None)。
Raises:
ValidationError: 格式无法解析。
"""
if not raw or not str(raw).strip():
return None, None
text = str(raw).strip()
try:
if len(text) == 4 and text.isdigit():
year = int(text)
return date(year, 1, 1), date(year + 1, 1, 1)
start = parse_period_month(text)
if start.month == 12:
end = date(start.year + 1, 1, 1)
else:
end = date(start.year, start.month + 1, 1)
return start, end
except ValidationError as exc:
raise ValidationError(
"period 格式须为 YYYY 或 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"period": text},
) from exc
except (TypeError, ValueError, OverflowError) as exc:
raise ValidationError(
"period 格式须为 YYYY 或 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"period": text},
) from exc
def _apply_period_filter(query, column, period: str | None):
"""
按 period 的年或月区间过滤 period_month 列。
Args:
query: SQLAlchemy 查询。
column: 期间列,通常为 VoucherCheckRun.period_month。
period: YYYY、YYYY-MM,或空。
Returns:
加上区间条件后的查询;period 为空时原样返回。
"""
start, end = parse_period_filter(period)
if start is None or end is None:
return query
return query.filter(column >= start, column < end)
def _period_value_in_filter(period_month: str | None, period: str | None) -> bool:
"""
判断 YYYY-MM 文本是否落在列表 period 筛选区间内。
Args:
period_month: 批次期间,例如 2026-08。
period: 与列表查询相同的 YYYY 或 YYYY-MM。
Returns:
无需过滤或文本落在区间内时为 True。
"""
start, end = parse_period_filter(period)
if start is None or end is None:
return True
if not period_month:
return False
try:
row = datetime.strptime(str(period_month)[:7], "%Y-%m").date().replace(day=1)
except ValueError:
return False
return start <= row < end
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 _as_summary_dict(raw: Any) -> dict[str, Any]:
"""把 JSON 字段收成 dict;非 dict 视为空。"""
return raw if isinstance(raw, dict) else {}
def _iso_dt(value: datetime | None) -> str | None:
"""将 datetime 转 ISO 文本,空值保持 None。"""
return value.isoformat() if value else None
def _latest_voucher_summary(schedule_run: ScheduleRun) -> dict[str, Any]:
"""从排程 response_summary_json 取出 voucher_check 快照。"""
summary = _as_summary_dict(schedule_run.response_summary_json)
voucher = summary.get("voucher_check")
return voucher if isinstance(voucher, dict) else {}
def _latest_current_step(schedule_run: ScheduleRun) -> dict[str, Any]:
"""从排程 response_summary_json 取出 runner 写入的 current_step。"""
summary = _as_summary_dict(schedule_run.response_summary_json)
current = summary.get("current_step")
return current if isinstance(current, dict) else {}
def _latest_run_mode(
schedule_run: ScheduleRun,
engine: VoucherCheckRun | None,
voucher_summary: dict[str, Any],
) -> str:
"""
解析最近一批的执行模式。
核心逻辑:优先引擎批次 mode;否则读 api_request_json.run_options,再回退 summary。
"""
if engine and engine.mode:
return str(engine.mode)
request_json = _as_summary_dict(schedule_run.api_request_json)
options = request_json.get("run_options")
option_mode = options.get("mode") if isinstance(options, dict) else None
return str(option_mode or voucher_summary.get("mode") or "incremental")
def _latest_period_month(
schedule_run: ScheduleRun,
engine: VoucherCheckRun | None,
voucher_summary: dict[str, Any],
) -> str:
"""最近一批的资料所属期间;无快照时回退上一个自然月。"""
if engine and engine.period_month:
return engine.period_month.strftime("%Y-%m")
raw = voucher_summary.get("period")
if raw:
return str(raw)[:7]
period_month, *_ = previous_period_bounds()
return period_month.strftime("%Y-%m")
def _latest_card_status(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> str:
"""
将排程状态与引擎批次状态收成工作台卡片状态。
核心逻辑:queued/running 必须保留,不能走建批前失败那条 technical_failed 映射。
"""
schedule_status = str(schedule_run.status or "")
if schedule_status == "queued":
return "queued"
if schedule_status == "running":
return "running"
if schedule_status == "failed":
return "technical_failed"
if engine is not None:
return str(engine.status or "completed")
if schedule_status in {"success", "partial_failed"}:
return "completed"
return schedule_status or "queued"
def _latest_progress_percent(
*,
card_status: str,
step: str | None,
processed: int,
subject_count: int,
) -> int:
"""
按 runner 步骤估算进度百分比。
核心逻辑:无精确进度字段;scan_dms 用已处理 invoice / 总数插值,终态固定 100。
"""
if card_status in {"completed", "missing"}:
return 100
if not step and card_status == "queued":
return 8
if step == "scan_dms" and subject_count > 0:
return min(86, 22 + int(64 * processed / subject_count))
step_base = {
"queued": 8,
"fetch_erp": 18,
"scan_dms": 22,
"persist": 88,
"notify": 94,
"done": 100,
}
if step in step_base:
return step_base[step]
if card_status == "technical_failed":
return 18
if card_status == "running":
return 12
return 0
def _serialize_latest_run(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> dict[str, Any]:
"""
序列化工作台「最近一次检核」卡片。
核心逻辑:进度与四指标来自 ScheduleRun.response_summary_json 与引擎快照;不跟列表 period 筛选。
"""
voucher_summary = _latest_voucher_summary(schedule_run)
current_step = _latest_current_step(schedule_run)
card_status = _latest_card_status(schedule_run, engine)
step_code = str(current_step.get("step") or "") or None
if not step_code and card_status == "queued":
step_code = "queued"
processed = int(current_step.get("processed_count") or 0)
subject_count = int(
(engine.subject_count if engine is not None else 0)
or voucher_summary.get("subject_count")
or 0
)
archived_file_count = int(
(engine.archived_file_count if engine is not None else 0)
or voucher_summary.get("archived_file_count")
or 0
)
missing_file_count = int(
(engine.missing_file_count if engine is not None else 0)
or voucher_summary.get("missing_file_count")
or 0
)
missing_invoice_count = int(
(engine.missing_invoice_count if engine is not None else 0)
or voucher_summary.get("missing_invoice_count")
or 0
)
started_at = (engine.started_at if engine is not None else None) or schedule_run.started_at
finished_at = (engine.finished_at if engine is not None else None) or schedule_run.finished_at
if card_status in {"queued", "running"}:
finished_at = None
return {
"schedule_run_id": schedule_run.id,
"engine_run_id": engine.id if engine is not None else None,
"run_no": schedule_run.run_no,
"period_month": _latest_period_month(schedule_run, engine, voucher_summary),
"mode": _latest_run_mode(schedule_run, engine, voucher_summary),
"status": card_status,
"progress_percent": _latest_progress_percent(
card_status=card_status,
step=step_code,
processed=processed,
subject_count=subject_count,
),
"subject_count": subject_count,
"archived_file_count": archived_file_count,
"missing_file_count": missing_file_count,
"missing_invoice_count": missing_invoice_count,
"processed_count": processed,
"started_at": _iso_dt(started_at),
"finished_at": _iso_dt(finished_at),
"error_message": schedule_run.error_message,
"current_step": {
"step": step_code,
"label": str(current_step.get("label") or "") or None,
"processed_count": processed,
}
if step_code
else None,
}
def _serialize_latest_from_engine(engine: VoucherCheckRun) -> dict[str, Any]:
"""
无对应排程时,用引擎批次充当最近一次检核。
核心逻辑:历史/测试数据可能只有 voucher_check_runs;终态进度为 100。
"""
card_status = str(engine.status or "completed")
return {
"schedule_run_id": engine.schedule_run_id,
"engine_run_id": engine.id,
"run_no": engine.run_no,
"period_month": engine.period_month.strftime("%Y-%m") if engine.period_month else None,
"mode": engine.mode,
"status": card_status,
"progress_percent": _latest_progress_percent(
card_status=card_status,
step="done" if card_status in {"completed", "missing"} else None,
processed=int(engine.subject_count or 0),
subject_count=int(engine.subject_count or 0),
),
"subject_count": int(engine.subject_count or 0),
"archived_file_count": int(engine.archived_file_count or 0),
"missing_file_count": int(engine.missing_file_count or 0),
"missing_invoice_count": int(engine.missing_invoice_count or 0),
"processed_count": int(engine.subject_count or 0),
"started_at": _iso_dt(engine.started_at),
"finished_at": _iso_dt(engine.finished_at),
"error_message": None,
"current_step": {"step": "done", "label": None, "processed_count": int(engine.subject_count or 0)}
if card_status in {"completed", "missing"}
else None,
}
def get_latest_run() -> dict[str, Any] | None:
"""
取立账凭证最近一次排程批次(按 ScheduleRun.id 倒序),不跟随列表 period/status。
核心逻辑:有排程则 join 引擎快照与 response_summary_json;仅有引擎批次时回退引擎表。
Returns:
卡片载荷;从未跑过任何批次时为 None。
"""
schedule_run = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
.order_by(ScheduleRun.id.desc())
.first()
)
if schedule_run is not None:
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run.id).first()
return _serialize_latest_run(schedule_run, engine)
latest_engine = VoucherCheckRun.query.order_by(VoucherCheckRun.id.desc()).first()
if latest_engine is None:
return None
return _serialize_latest_from_engine(latest_engine)
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,保证强制重检结果可见。
period 支持 YYYY(全年)或 YYYY-MM(单月)。
"""
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = _apply_period_filter(VoucherCheckRun.query, VoucherCheckRun.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 == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
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 _period_value_in_filter(_serialize_schedule_fallback_run(row)["period_month"], period)
]
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 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。
period 支持 YYYY(全年)或 YYYY-MM(单月)。
"""
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,
)
q = _apply_period_filter(q, VoucherCheckRun.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,
}