fix: 模拟生成PDF
This commit is contained in:
1 parent
c4a27324c8
commit
204e71b786
19 files changed
+2064
-110
No files matched your search
@@ -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)
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_latest_run.py
|
||||
|
||||
用途:工作台「最近一次检核」接口契约(含排队/执行中/终态/建批前失败)。
|
||||
依赖:pytest、Flask client、voucher_check.query_service。
|
||||
逻辑:GET /runs/latest 按 ScheduleRun.id 倒序,不跟列表 period;queued 不得被标成 technical_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, User
|
||||
from app.models.voucher_check import VoucherCheckRun
|
||||
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
|
||||
|
||||
|
||||
def _ensure_user(*, username: str, role: str) -> User:
|
||||
"""测试用户幂等创建。"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _add_schedule_run(
|
||||
*,
|
||||
run_no: str,
|
||||
status: str,
|
||||
mode: str | None = None,
|
||||
error_message: str | None = None,
|
||||
summary: dict | None = None,
|
||||
started_at: datetime | None = None,
|
||||
finished_at: datetime | None = None,
|
||||
) -> ScheduleRun:
|
||||
"""为本任务排程插入一条 ScheduleRun。"""
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
payload = {"run_options": {"mode": mode}} if mode else None
|
||||
run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no=run_no,
|
||||
trigger_type="manual",
|
||||
status=status,
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=1 if status == "failed" else 0,
|
||||
error_message=error_message,
|
||||
api_request_json=payload,
|
||||
response_summary_json=summary,
|
||||
started_at=started_at,
|
||||
finished_at=finished_at,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def _add_engine_run(
|
||||
*,
|
||||
schedule_run: ScheduleRun,
|
||||
status: str = "missing",
|
||||
period_month: date | None = None,
|
||||
subject_count: int = 128,
|
||||
archived_file_count: int = 742,
|
||||
missing_file_count: int = 11,
|
||||
missing_invoice_count: int = 6,
|
||||
) -> VoucherCheckRun:
|
||||
"""为排程批次挂一条引擎快照。"""
|
||||
payload = schedule_run.api_request_json if isinstance(schedule_run.api_request_json, dict) else {}
|
||||
options = payload.get("run_options") if isinstance(payload.get("run_options"), dict) else {}
|
||||
engine = VoucherCheckRun(
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no=schedule_run.run_no,
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=period_month or date(2026, 8, 1),
|
||||
mode=str(options.get("mode") or "incremental"),
|
||||
status=status,
|
||||
subject_count=subject_count,
|
||||
archived_file_count=archived_file_count,
|
||||
missing_file_count=missing_file_count,
|
||||
missing_invoice_count=missing_invoice_count,
|
||||
started_at=schedule_run.started_at,
|
||||
finished_at=schedule_run.finished_at,
|
||||
)
|
||||
db.session.add(engine)
|
||||
return engine
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers):
|
||||
"""入队中的强制重检必须显示 queued,而不是建批前失败口径。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-QUEUED",
|
||||
status="queued",
|
||||
mode="force_all",
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload is not None
|
||||
assert payload["run_no"] == "RUN-LATEST-QUEUED"
|
||||
assert payload["status"] == "queued"
|
||||
assert payload["mode"] == "force_all"
|
||||
assert payload["progress_percent"] == 8
|
||||
assert payload["current_step"]["step"] == "queued"
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, user_headers):
|
||||
"""终态缺件批次返回四指标与 100% 进度。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
sched = _add_schedule_run(
|
||||
run_no="RUN-LATEST-DONE",
|
||||
status="success",
|
||||
mode="incremental",
|
||||
started_at=datetime(2026, 9, 8, 1, 48, 7),
|
||||
finished_at=datetime(2026, 9, 8, 1, 50, 19),
|
||||
summary={
|
||||
"current_step": {"step": "done", "label": "检核完成", "processed_count": 128},
|
||||
"voucher_check": {"period": "2026-08", "mode": "incremental", "subject_count": 128},
|
||||
},
|
||||
)
|
||||
_add_engine_run(schedule_run=sched, status="missing")
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
# 关键断言:卡片数字来自引擎快照,状态用缺件而非排程 success。
|
||||
assert payload["run_no"] == "RUN-LATEST-DONE"
|
||||
assert payload["status"] == "missing"
|
||||
assert payload["period_month"] == "2026-08"
|
||||
assert payload["mode"] == "incremental"
|
||||
assert payload["progress_percent"] == 100
|
||||
assert payload["subject_count"] == 128
|
||||
assert payload["archived_file_count"] == 742
|
||||
assert payload["missing_file_count"] == 11
|
||||
assert payload["missing_invoice_count"] == 6
|
||||
|
||||
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, user_headers):
|
||||
"""执行中进度跟 runner 步骤走,且 latest 不吃列表 period。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
old = _add_schedule_run(
|
||||
run_no="RUN-LATEST-OLD-AUG",
|
||||
status="success",
|
||||
mode="incremental",
|
||||
finished_at=datetime(2026, 9, 1, 6, 0, 0),
|
||||
)
|
||||
_add_engine_run(schedule_run=old, status="completed", period_month=date(2026, 8, 1), subject_count=10)
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-RUNNING",
|
||||
status="running",
|
||||
mode="force_all",
|
||||
started_at=datetime(2026, 9, 9, 6, 5, 22),
|
||||
summary={
|
||||
"current_step": {
|
||||
"step": "scan_dms",
|
||||
"label": "扫描销售开票附件类型目录",
|
||||
"processed_count": 54,
|
||||
},
|
||||
"voucher_check": {
|
||||
"period": "2026-07",
|
||||
"mode": "force_all",
|
||||
"subject_count": 128,
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
latest = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert latest.status_code == 200
|
||||
payload = parse_api_data(latest.get_json())
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
assert payload["status"] == "running"
|
||||
assert payload["period_month"] == "2026-07"
|
||||
assert payload["processed_count"] == 54
|
||||
assert payload["progress_percent"] == min(86, 22 + int(64 * 54 / 128))
|
||||
assert payload["finished_at"] is None
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
nos = {item["run_no"] for item in parse_api_data(filtered.get_json())["items"]}
|
||||
# 关键断言:列表按 8 月过滤看不到 7 月执行中批次,但 latest 仍是该批。
|
||||
assert "RUN-LATEST-RUNNING" not in nos
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
|
||||
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
"""建批前失败仍作为最近一次检核,状态为技术失败。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-FAILED",
|
||||
status="failed",
|
||||
mode="incremental",
|
||||
error_message="未配置销售开票附件文档库根目录",
|
||||
started_at=datetime(2026, 9, 7, 8, 31, 51),
|
||||
finished_at=datetime(2026, 9, 7, 8, 32, 10),
|
||||
summary={
|
||||
"current_step": {"step": "fetch_erp", "label": "拉取上月销售 invoice", "processed_count": 0},
|
||||
"voucher_check": {"period": "2026-08"},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload["run_no"] == "RUN-LATEST-FAILED"
|
||||
assert payload["status"] == "technical_failed"
|
||||
assert payload["error_message"] == "未配置销售开票附件文档库根目录"
|
||||
assert payload["current_step"]["step"] == "fetch_erp"
|
||||
assert payload["progress_percent"] == 18
|
||||
@@ -0,0 +1,185 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_period_filter.py
|
||||
|
||||
用途:工作台检核任务 / 企微发送记录的期间筛选(YYYY 全年、YYYY-MM 单月)。
|
||||
依赖:pytest、Flask client、voucher_check.query_service。
|
||||
逻辑:同一年多个月份应被 year 筛出;单月筛仍精确;建批前失败记录按年也能命中。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ScheduleRun, User
|
||||
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun
|
||||
from app.services.voucher_check.query_service import parse_period_filter
|
||||
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
|
||||
|
||||
|
||||
def _ensure_user(*, username: str, role: str) -> User:
|
||||
"""测试用户幂等创建。"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _engine_run(*, run_no: str, period_month: date, status: str = "missing") -> VoucherCheckRun:
|
||||
"""构造列表用引擎批次。"""
|
||||
return VoucherCheckRun(
|
||||
run_no=run_no,
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=period_month,
|
||||
mode="incremental",
|
||||
status=status,
|
||||
subject_count=1,
|
||||
finished_at=datetime(period_month.year, period_month.month, 2, 6, 0, 0),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_period_filter_year_and_month():
|
||||
"""YYYY 覆盖全年,YYYY-MM 只覆盖该月。"""
|
||||
start, end = parse_period_filter("2026")
|
||||
assert start == date(2026, 1, 1)
|
||||
assert end == date(2027, 1, 1)
|
||||
start, end = parse_period_filter("2026-08")
|
||||
assert start == date(2026, 8, 1)
|
||||
assert end == date(2026, 9, 1)
|
||||
start, end = parse_period_filter("2026-12")
|
||||
assert start == date(2026, 12, 1)
|
||||
assert end == date(2027, 1, 1)
|
||||
assert parse_period_filter(None) == (None, None)
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
parse_period_filter("2026-13")
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
"""任务列表 year 筛出同年多月,month 仍只返回单月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
db.session.add(_engine_run(run_no="VC-202608-Y", period_month=date(2026, 8, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202607-Y", period_month=date(2026, 7, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202512-Y", period_month=date(2025, 12, 1)))
|
||||
db.session.commit()
|
||||
|
||||
year_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert year_resp.status_code == 200
|
||||
year_payload = parse_api_data(year_resp.get_json())
|
||||
year_nos = {item["run_no"] for item in year_payload["items"]}
|
||||
# 关键断言:全年筛选包含 7、8 月,不含跨年 12 月。
|
||||
assert "VC-202608-Y" in year_nos
|
||||
assert "VC-202607-Y" in year_nos
|
||||
assert "VC-202512-Y" not in year_nos
|
||||
|
||||
month_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert month_resp.status_code == 200
|
||||
month_payload = parse_api_data(month_resp.get_json())
|
||||
month_nos = {item["run_no"] for item in month_payload["items"]}
|
||||
assert "VC-202608-Y" in month_nos
|
||||
assert "VC-202607-Y" not in month_nos
|
||||
|
||||
|
||||
def test_workspace_year_filter_includes_pre_engine_failure(app, client, admin_headers):
|
||||
"""建批前失败记录在按年筛选时仍须出现。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
db.session.add(
|
||||
ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-PREENGINE-YEAR",
|
||||
trigger_type="manual",
|
||||
status="failed",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=1,
|
||||
error_message="未配置销售开票附件文档库根目录",
|
||||
response_summary_json={"voucher_check": {"period": "2026-08"}},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026&status=technical_failed",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
nos = {item["run_no"] for item in payload["items"]}
|
||||
assert "RUN-PREENGINE-YEAR" in nos
|
||||
|
||||
|
||||
def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
"""企微发送记录按年筛选应覆盖该年各月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
august = _engine_run(run_no="VC-202608-N", period_month=date(2026, 8, 1))
|
||||
july = _engine_run(run_no="VC-202607-N", period_month=date(2026, 7, 1), status="completed")
|
||||
db.session.add_all([august, july])
|
||||
db.session.flush()
|
||||
db.session.add_all(
|
||||
[
|
||||
VoucherCheckNotification(
|
||||
run_id=august.id,
|
||||
send_status="sent",
|
||||
summary_json={"period": "2026-08"},
|
||||
),
|
||||
VoucherCheckNotification(
|
||||
run_id=july.id,
|
||||
send_status="skipped_no_missing",
|
||||
summary_json={"period": "2026-07"},
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
nos = {item["run_no"] for item in payload["items"]}
|
||||
assert "VC-202608-N" in nos
|
||||
assert "VC-202607-N" in nos
|
||||
|
||||
|
||||
def test_workspace_rejects_invalid_period(app, client, user_headers):
|
||||
"""非法 period 返回配置错误,而不是空列表。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-13",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 400
|
||||
error = parse_api_error(response.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
Reference in new issue
Block a user