fix: 模拟生成PDF

This commit is contained in:
sophie committed 2026-09-10 10:18:44 +08:00
1 parent c4a27324c8
commit 204e71b786
19 files changed
+2064 -110

No files matched your search

+14 -4
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
逻辑:对话与检核任务页共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
"""
from __future__ import annotations
@@ -37,7 +37,7 @@ def _require_admin():
def workspace_voucher_runs():
"""
分页查看检核任务列表。
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
"""
_require_user()
data = query_service.list_runs(
@@ -69,6 +69,16 @@ def workspace_voucher_force_run():
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
def workspace_voucher_latest_run():
"""
读取最近一次立账凭证检核批次(含排队/执行中)。
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
"""
_require_user()
return ok(query_service.get_latest_run())
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
@@ -89,7 +99,7 @@ def workspace_voucher_run_items(run_id: int):
def workspace_voucher_notifications():
"""
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
"""
_require_user()
data = query_service.list_notifications(
@@ -1,9 +1,9 @@
"""
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。
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
依赖: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
@@ -20,6 +20,7 @@ from app.models.voucher_check import (
)
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:
@@ -38,9 +39,92 @@ def parse_period_month(raw: str | None) -> date:
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,
@@ -93,6 +177,238 @@ def _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]:
}
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,
@@ -105,12 +421,11 @@ def list_runs(
工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。
核心逻辑:正常场景读取 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 = VoucherCheckRun.query
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
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:
@@ -120,7 +435,7 @@ def list_runs(
fallback_query = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(
ScheduleTask.platform_api_path == "accounting-voucher-check",
ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
ScheduleRun.status == "failed",
)
)
@@ -132,7 +447,7 @@ def list_runs(
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"))
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)
@@ -284,6 +599,7 @@ def list_notifications(
"""
分页查询企微缺件汇总发送记录。
核心逻辑:以 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))
@@ -291,8 +607,7 @@ def list_notifications(
VoucherCheckRun,
VoucherCheckNotification.run_id == VoucherCheckRun.id,
)
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
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)