Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

+232 -174
View File
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/runner.py
用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。
依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。
逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。
"""
from __future__ import annotations
@@ -16,13 +16,21 @@ from flask import current_app
from app import db
from app.core.errors import AppError, NotFoundError, ServiceUnavailableError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.voucher_check.config import load_voucher_check_config
from app.services.voucher_check.erp_repository import fetch_month_invoices
from app.services.voucher_check.excel_rows import to_excel_detail_row
from app.services.voucher_check.notification import send_failure_alert, send_missing_notifications
from app.services.voucher_check.persistence import persist_batch_results
from app.services.voucher_check.share_scanner import ensure_share_healthy, scan_invoice_folder
from app.services.voucher_check import adapters as _register_adapters # noqa: F401
from app.services.voucher_check.adapters.registry import get_adapter
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.engine_persistence import (
create_run,
load_previous_archived_fingerprints,
persist_engine_results,
)
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.excel_rows import to_excel_invoice_row
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
from app.services.voucher_check.profiles.sales import required_file_rules
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -57,17 +65,16 @@ def _update_progress(
if voucher_summary:
summary["voucher_check"] = voucher_summary
summary["file_judgement"] = {
"qualified_count": int(voucher_summary.get("complete_count") or 0),
"unqualified_count": int(voucher_summary.get("missing_count") or 0),
"qualified_count": int(voucher_summary.get("complete_invoice_count") or 0),
"unqualified_count": int(voucher_summary.get("missing_invoice_count") or 0),
"manual_count": 0,
"system_error_count": int(voucher_summary.get("technical_error_count") or 0),
}
summary["progress_metrics"] = [
{"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("total_count") or 0)},
{"key": "scan", "label_key": "chat.voucherCheck.scanned", "value": int(voucher_summary.get("scan_count") or 0)},
{"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_count") or 0)},
{"key": "complete", "label_key": "chat.voucherCheck.complete", "value": int(voucher_summary.get("complete_count") or 0)},
{"key": "missing", "label_key": "chat.voucherCheck.missing", "value": int(voucher_summary.get("missing_count") or 0)},
{"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("subject_count") or 0)},
{"key": "missing_files", "label_key": "chat.voucherCheck.missingFiles", "value": int(voucher_summary.get("missing_file_count") or 0)},
{"key": "missing", "label_key": "chat.voucherCheck.missingInvoices", "value": int(voucher_summary.get("missing_invoice_count") or 0)},
{"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_file_count") or 0)},
]
summary["domain_notification_managed"] = True
run.response_summary_json = summary
@@ -76,8 +83,9 @@ def _update_progress(
def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核批次。
核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。
执行立账凭证周批次。
核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。
启动日志带 path=accounting-voucher-check,便于在全是 schedule 的 worker 输出中识别本任务。
Returns:
ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs)
@@ -87,9 +95,19 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
options = _extract_run_options(run)
mode = options["mode"]
single_invoice = options["invoice_no"]
now = datetime.utcnow()
current_app.logger.info(
"[voucher-check] start name=%s path=accounting-voucher-check run_no=%s mode=%s",
getattr(task, "name", None) or "立账凭证检核",
run.run_no,
mode,
)
try:
config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {})
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()
except AppError as exc:
send_failure_alert(
task=task,
@@ -101,10 +119,15 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
)
raise
# [STEP 1] 拉取 ERP 当月发票清单
_update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证")
rules = required_file_rules(profile)
period_month, _current, _start, _end = previous_period_bounds()
period = period_month.strftime("%Y-%m")
# [STEP 1] 拉取上月销售 invoice 清单
_update_progress(run, step="fetch_erp", label="拉取上月销售 invoice")
try:
period_month, invoices = fetch_month_invoices(config)
subject_adapter = get_adapter(str(profile.get("subject_adapter") or "hxjm_apa"))
subjects = subject_adapter.fetch(period_month=period_month, config=config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
@@ -119,7 +142,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
{
"step": "fetch_erp",
"status": "success",
"detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")},
"detail": {"count": len(subjects), "period": period},
}
)
@@ -129,169 +152,200 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
"single 模式必须提供 invoice_no",
code="VOUCHER_CHECK.INVOICE_REQUIRED",
)
invoices = [row for row in invoices if row.invoice_no == single_invoice]
if not invoices:
subjects = [row for row in subjects if row.invoice_no == single_invoice]
if not subjects:
raise NotFoundError(
"指定发票不在当前月 ERP 集合",
"指定发票不在上一个月 ERP 集合",
code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD",
)
# [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing)
_update_progress(run, step="share_health", label="检查共享盘可用性")
try:
root = ensure_share_healthy(config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
run=run,
stage="share_health",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
)
raise
step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}})
# [STEP 3] 读取历史状态,供增量判定
existing_states = (
db.session.query(VoucherCheckInvoiceState)
.filter_by(scope_code=config.scope_code, period_month=period_month)
.all()
engine_run = create_run(
schedule_run_id=run.id,
run_no=str(run.run_no or f"VC-{run.id}"),
profile_code=str(profile["profile_code"]),
profile_version=str(profile["profile_version"]),
profile_snapshot=profile,
period_month=period_month,
mode=mode,
started_at=now,
)
state_map = {s.invoice_no: s for s in existing_states}
db.session.commit()
results: list[dict[str, Any]] = []
complete_count = 0
missing_count = 0
skipped_count = 0
technical_error_count = 0
now = datetime.utcnow()
scan_adapter = get_adapter("directory_scan")
archive_adapter = get_adapter("dms_archive")
force = mode in {"force_all", "single"}
previous_fp = {} if force else load_previous_archived_fingerprints(
profile_code=str(profile["profile_code"]),
period_month=period_month,
exclude_run_id=engine_run.id,
)
# [STEP 4] 逐票扫描 / 指纹比对
# [STEP 2] 扫描六类类型目录(不调用 PO/OA 打印 Adapter)
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
step="scan_dms",
label="扫描销售开票附件类型目录",
processed=0,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": 0,
"missing_count": 0,
"scan_count": 0,
"skipped_count": 0,
"subject_count": len(subjects),
"missing_file_count": 0,
"missing_invoice_count": 0,
"skipped_file_count": 0,
"technical_error_count": 0,
"complete_invoice_count": 0,
},
)
for idx, row in enumerate(invoices, start=1):
hist = state_map.get(row.invoice_no)
scan = scan_invoice_folder(
config,
root=root,
period_month=period_month,
invoice_no=row.invoice_no,
)
# 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹)
can_skip = (
not force
and hist is not None
and hist.status == "complete"
and hist.material_fingerprint
and scan.result == "complete"
and scan.material_fingerprint == hist.material_fingerprint
)
if can_skip:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "skipped",
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": [],
"checked_at": None,
}
skipped_count += 1
elif scan.result == "technical_error":
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "technical_error",
"folder_path": scan.folder_path,
"folder_exists": False,
"material_fingerprint": None,
"matched_files": {},
"missing_materials": [],
"error_code": scan.error_code,
"error_message": scan.error_message,
file_results: list[dict[str, Any]] = []
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
for idx, subject in enumerate(subjects, start=1):
for rule in rules:
rule_code = str(rule["code"])
expected = str(rule.get("filename_template") or "").replace("{invoice}", subject.invoice_no)
prev_key = (subject.invoice_no, rule_code)
outcome = scan_adapter.scan(
period_month=period_month,
invoice_no=subject.invoice_no,
rule=rule,
)
result: dict[str, Any] = {
"invoice_no": subject.invoice_no,
"invoice_date": subject.invoice_date,
"rule_code": rule_code,
"rule_name": rule.get("name") or rule_code,
"source_type": "directory_scan",
"expected_name": expected,
"source_folder_id": outcome.folder_id,
"source_path": outcome.folder_path,
"checked_at": now,
}
technical_error_count += 1
else:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": scan.result,
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": scan.missing_materials,
"checked_at": now,
}
if scan.result == "complete":
complete_count += 1
if (
not force
and outcome.status == "matched"
and outcome.file
and outcome.file.fingerprint
and previous_fp.get(prev_key) == outcome.file.fingerprint
):
result.update(
{
"status": "skipped",
"matched_name": outcome.file.filename,
"source_item_id": outcome.file.item_id,
"source_fingerprint": outcome.file.fingerprint,
}
)
elif outcome.status == "technical_error":
result.update(
{
"status": "technical_error",
"error_code": outcome.error_code,
"error_message": outcome.error_message,
}
)
elif outcome.status != "matched" or outcome.file is None:
result.update(
{
"status": "missing",
"missing_reason": "类型目录未找到匹配文件",
}
)
else:
missing_count += 1
results.append(item)
scanned = outcome.file
result.update(
{
"matched_name": scanned.filename,
"source_item_id": scanned.item_id,
"source_fingerprint": scanned.fingerprint,
}
)
archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{subject.invoice_no}/{scanned.filename}"
result["archive_path"] = archive_path
if getattr(archive_adapter, "wired", False):
try:
archived = archive_adapter.archive(
period_month=period_month,
invoice_no=subject.invoice_no,
file=scanned,
rule=rule,
)
extra = archived.extra or {}
result.update(
{
"status": "archived",
"archive_item_id": archived.item_id,
"archive_folder_id": archived.folder_id,
"archive_skipped_same_name": bool(extra.get("skipped_same_name")),
}
)
except ServiceUnavailableError as exc:
result.update(
{
"status": "technical_error",
"error_code": exc.code,
"error_message": exc.message,
}
)
else:
result["status"] = "staged"
file_results.append(result)
if idx % 20 == 0 or idx == len(invoices):
scan_count = complete_count + missing_count + technical_error_count
if idx % 20 == 0 or idx == len(subjects):
preview = aggregate_file_results(file_results, rules=rules)
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
step="scan_dms",
label="扫描销售开票附件类型目录",
processed=idx,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
"subject_count": len(subjects),
"missing_file_count": preview["missing_file_count"],
"missing_invoice_count": preview["missing_invoice_count"],
"skipped_file_count": preview["skipped_file_count"],
"technical_error_count": preview["technical_error_count"],
"complete_invoice_count": sum(
1 for row in preview["excel_rows"] if row["status"] == "完整"
),
},
)
stats = aggregate_file_results(file_results, rules=rules)
step_logs.append(
{
"step": "scan_share",
"step": "scan_dms",
"status": "success",
"detail": {
"complete": complete_count,
"missing": missing_count,
"skipped": skipped_count,
"technical_error": technical_error_count,
"missing_files": stats["missing_file_count"],
"missing_invoices": stats["missing_invoice_count"],
"staged": stats["staged_file_count"],
"skipped": stats["skipped_file_count"],
"technical_error": stats["technical_error_count"],
},
}
)
# [STEP 5] 事务落库
# [STEP 3] 落库单文件结果
_update_progress(run, step="persist", label="写入检核记录")
try:
persist_batch_results(
schedule_run_id=run.id,
scope_code=config.scope_code,
period_month=period_month,
items=results,
persist_engine_results(
run=engine_run,
subjects=[
{
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"source_fingerprint": row.source_fingerprint,
"attributes": row.attributes,
}
for row in subjects
],
file_results=file_results,
stats=stats,
now=now,
)
db.session.commit()
@@ -308,58 +362,62 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
)
raise
# [STEP 6] 缺资料通知
missing_items = [r for r in results if r["result"] == "missing"]
notified = send_missing_notifications(
excel_filename = f"voucher_check_{profile['profile_code']}_{period}_{run.run_no}.xlsx"
executed_at = now.strftime("%Y-%m-%d %H:%M:%S")
details = [
to_excel_invoice_row(item, period=period, executed_at=executed_at)
for item in stats["excel_rows"]
]
# [STEP 4] 每批一条企微汇总
notify_status = send_batch_missing_summary(
task=task,
run=run,
scope_code=config.scope_code,
period_month=period_month,
missing_items=missing_items,
same_day_dedup=config.same_day_dedup_enabled,
schedule_run=run,
engine_run_id=engine_run.id,
profile_code=str(profile["profile_code"]),
period_month=period,
stats=stats,
excel_filename=excel_filename,
enabled=config.notify_missing_enabled,
)
step_logs.append(
{
"step": "notify",
"status": "success",
"detail": {"missing": len(missing_items), "notified": notified},
"detail": {"send_status": notify_status, "missing_files": stats["missing_file_count"]},
}
)
period = period_month.strftime("%Y-%m")
scan_count = complete_count + missing_count + technical_error_count
complete_invoices = sum(1 for row in stats["excel_rows"] if row["status"] == "完整")
voucher_summary = {
"scope_code": config.scope_code,
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
"missing_notification_count": notified,
"engine_run_id": engine_run.id,
"subject_count": stats["subject_count"],
"missing_file_count": stats["missing_file_count"],
"missing_invoice_count": stats["missing_invoice_count"],
"skipped_file_count": stats["skipped_file_count"],
"technical_error_count": stats["technical_error_count"],
"staged_file_count": stats["staged_file_count"],
"complete_invoice_count": complete_invoices,
"notify_status": notify_status,
}
_update_progress(
run,
step="done",
label="检核完成",
processed=len(invoices),
processed=len(subjects),
voucher_summary=voucher_summary,
)
details = [
to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results
]
# success_count = complete + missing(业务成功);failed_count 仅技术异常
success_count = complete_count + missing_count
total_count = len(invoices)
success_count = stats["subject_count"]
failed_count = 1 if stats["batch_status"] == "technical_failed" and stats["missing_file_count"] == 0 else 0
return (
total_count,
stats["subject_count"],
success_count,
technical_error_count,
skipped_count,
failed_count,
stats["skipped_file_count"],
details,
errors,
step_logs,