1
This commit is contained in:
1 parent
78576f5745
commit
63b997a7e4
68 files changed
+3680
-1413
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。
|
||||
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
|
||||
逻辑:对话与检核任务页共用;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.voucher_check import query_service
|
||||
|
||||
@@ -25,6 +25,50 @@ def _require_user():
|
||||
return user
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError("Admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs", methods=["GET"])
|
||||
def workspace_voucher_runs():
|
||||
"""
|
||||
分页查看检核任务列表。
|
||||
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
data = query_service.list_runs(
|
||||
period=request.args.get("period"),
|
||||
profile_code=request.args.get("profile_code"),
|
||||
status=request.args.get("status"),
|
||||
page=request.args.get("page", default=1, type=int) or 1,
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs", methods=["POST"])
|
||||
def workspace_voucher_force_run():
|
||||
"""
|
||||
强制重检上一个自然月(不走增量跳过)。
|
||||
核心逻辑:body.mode 仅接受 force_all;入队默认周批排程,由 schedule worker 执行。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
mode = str(payload.get("mode") or "force_all").strip().lower()
|
||||
if mode != "force_all":
|
||||
raise ValidationError(
|
||||
"工作台仅支持 force_all",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"mode": mode},
|
||||
)
|
||||
data = query_service.enqueue_force_all_run(triggered_by_user_id=getattr(user, "id", None))
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
|
||||
def workspace_voucher_run_items(run_id: int):
|
||||
"""
|
||||
|
||||
@@ -630,7 +630,7 @@ class Config:
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# 立账凭证检核:共享盘只读根 + Oracle 只读账号(密码仅 env)
|
||||
# 立账凭证检核:ERP 只读 + 销售开票附件文档库根目录(密码仅 env)
|
||||
VOUCHER_CHECK_SHARE_UNC = os.getenv('VOUCHER_CHECK_SHARE_UNC', '').strip()
|
||||
VOUCHER_CHECK_LOCAL_ROOT = os.getenv('VOUCHER_CHECK_LOCAL_ROOT', '').strip()
|
||||
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH = os.getenv(
|
||||
@@ -641,6 +641,11 @@ class Config:
|
||||
VOUCHER_CHECK_ERP_USERNAME = os.getenv('VOUCHER_CHECK_ERP_USERNAME', '').strip()
|
||||
VOUCHER_CHECK_ERP_PASSWORD = os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
|
||||
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS', '30') or '30')
|
||||
VOUCHER_CHECK_DMS_BASE_URL = os.getenv('VOUCHER_CHECK_DMS_BASE_URL', '').strip().rstrip('/')
|
||||
VOUCHER_CHECK_DMS_USERNAME = os.getenv('VOUCHER_CHECK_DMS_USERNAME', '').strip()
|
||||
VOUCHER_CHECK_DMS_PASSWORD = os.getenv('VOUCHER_CHECK_DMS_PASSWORD', '')
|
||||
VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip()
|
||||
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip()
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
|
||||
@@ -194,7 +194,15 @@ from app.models.shipping_inventory_preparation import (
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckInvoiceState,
|
||||
VoucherCheckNotification,
|
||||
VoucherCheckProfile,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckRunItem,
|
||||
VoucherCheckSubject,
|
||||
)
|
||||
from app.models.contract_payment import (
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
@@ -381,6 +389,11 @@ __all__ = [
|
||||
'ShippingTaskInventoryRpaAttempt',
|
||||
'VoucherCheckInvoiceState',
|
||||
'VoucherCheckRunItem',
|
||||
'VoucherCheckProfile',
|
||||
'VoucherCheckRun',
|
||||
'VoucherCheckSubject',
|
||||
'VoucherCheckFileResult',
|
||||
'VoucherCheckNotification',
|
||||
'ContractPaymentContract',
|
||||
'ContractPaymentAttachment',
|
||||
'ContractPaymentNode',
|
||||
|
||||
@@ -34,6 +34,7 @@ class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
||||
"""
|
||||
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/voucher_check.py
|
||||
|
||||
用途:立账凭证检核单票最新状态与批次明细 ORM。
|
||||
用途:立账凭证检核 ORM。含旧一票一状态表,以及销售一期单文件结果引擎表。
|
||||
依赖:models.base.Base、schedule_runs。
|
||||
逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。
|
||||
逻辑:旧 runner 写 invoice_states/run_items;新引擎写 profiles/runs/subjects/file_results/notifications。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -112,3 +112,156 @@ class VoucherCheckRunItem(Base):
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckProfile(Base):
|
||||
"""已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。"""
|
||||
|
||||
__tablename__ = "voucher_check_profiles"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"),
|
||||
Index("ix_voucher_check_profiles_status", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
definition_json: Mapped[dict] = mapped_column(JSON, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(24), nullable=False, default="published")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class VoucherCheckRun(Base):
|
||||
"""一次检核批次;列表统计取本表快照,不在查询时重算单文件结果。"""
|
||||
|
||||
__tablename__ = "voucher_check_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_voucher_check_runs_period_profile", "period_month", "profile_code"),
|
||||
Index("ix_voucher_check_runs_status", "status"),
|
||||
Index("ix_voucher_check_runs_finished_at", "finished_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
profile_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
profile_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False)
|
||||
period_month: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
mode: Mapped[str] = mapped_column(String(24), nullable=False, default="incremental")
|
||||
status: Mapped[str] = mapped_column(String(24), nullable=False, default="running")
|
||||
subject_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
archived_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
skipped_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
missing_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
missing_invoice_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
technical_error_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
staged_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
stats_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckSubject(Base):
|
||||
"""批次内一张销售 invoice 主体。"""
|
||||
|
||||
__tablename__ = "voucher_check_subjects"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"),
|
||||
Index("ix_voucher_check_subjects_invoice_no", "invoice_no"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
attributes_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckFileResult(Base):
|
||||
"""invoice × 文件规则 的单文件结果,是缺件统计与 Excel 的真相源。"""
|
||||
|
||||
__tablename__ = "voucher_check_file_results"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"run_id",
|
||||
"invoice_no",
|
||||
"rule_code",
|
||||
name="uq_voucher_check_file_results_run_invoice_rule",
|
||||
),
|
||||
Index("ix_voucher_check_file_results_status", "run_id", "status"),
|
||||
Index("ix_voucher_check_file_results_invoice", "invoice_no"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
subject_id: Mapped[Optional[int]] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
expected_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
matched_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
source_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
archive_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
archive_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||
archive_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(24), nullable=False)
|
||||
missing_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckNotification(Base):
|
||||
"""一个检核批次对应一条企微汇总通知审计。"""
|
||||
|
||||
__tablename__ = "voucher_check_notifications"
|
||||
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
)
|
||||
excel_filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
recipient_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
send_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
skip_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -3,7 +3,7 @@ backend/app/services/faq_cache.py
|
||||
|
||||
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
|
||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。
|
||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
@@ -66,6 +66,7 @@ class FaqCacheService:
|
||||
"""
|
||||
尝试为指定 Agent 命中全局 FAQ 缓存条目。
|
||||
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
|
||||
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
|
||||
@param query - 用户提问
|
||||
@param agent_id - 当前 Agent 主键
|
||||
@returns 命中的 QuickQuestion;未命中返回 None
|
||||
@@ -80,7 +81,6 @@ class FaqCacheService:
|
||||
QuickQuestion.user_id.is_(None),
|
||||
QuickQuestion.agent_id == agent_id,
|
||||
QuickQuestion.cache_enabled.is_(True),
|
||||
QuickQuestion.is_enabled.is_(True),
|
||||
QuickQuestion.answer.isnot(None),
|
||||
QuickQuestion.answer != "",
|
||||
QuickQuestion.stale_at.is_(None),
|
||||
|
||||
@@ -9,6 +9,7 @@ backend/app/services/schedule/queue_service.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -61,6 +62,7 @@ def _create_queued_run(
|
||||
*,
|
||||
trigger_type: str,
|
||||
triggered_by_user_id: int | None,
|
||||
api_request_json: dict[str, Any] | None = None,
|
||||
) -> tuple[ScheduleRun, int]:
|
||||
"""
|
||||
在当前事务创建 ScheduleRun 与对应通用 Job。
|
||||
@@ -69,6 +71,7 @@ def _create_queued_run(
|
||||
task: 已由调用方锁定的排程任务。
|
||||
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
|
||||
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
|
||||
api_request_json: 可选运行参数(如立账凭证 `run_options.mode=force_all`),须在入队前写入以免 worker 抢跑。
|
||||
|
||||
Returns:
|
||||
`(ScheduleRun, job_id)`;调用方负责提交事务。
|
||||
@@ -86,6 +89,7 @@ def _create_queued_run(
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
started_at=None,
|
||||
status="queued",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
@@ -112,6 +116,7 @@ def enqueue_manual_schedule_run(
|
||||
task_id: int,
|
||||
*,
|
||||
triggered_by_user_id: int | None,
|
||||
api_request_json: dict[str, Any] | None = None,
|
||||
) -> tuple[ScheduleRun, int, bool]:
|
||||
"""
|
||||
手动触发排程并写入 schedule 队列。
|
||||
@@ -119,6 +124,11 @@ def enqueue_manual_schedule_run(
|
||||
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
|
||||
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
|
||||
|
||||
Args:
|
||||
task_id: 排程任务主键。
|
||||
triggered_by_user_id: 触发人;系统触发可为空。
|
||||
api_request_json: 写入新 run 的请求快照;已有活动 run 时不会覆盖。
|
||||
|
||||
Returns:
|
||||
`(run, job_id, created)`;created=False 表示已有活动 run。
|
||||
"""
|
||||
@@ -151,6 +161,7 @@ def enqueue_manual_schedule_run(
|
||||
task,
|
||||
trigger_type="manual",
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.commit()
|
||||
return run, job_id, True
|
||||
|
||||
@@ -38,7 +38,7 @@ def _ensure_headers() -> None:
|
||||
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证检核排程。
|
||||
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
|
||||
核心逻辑:注册 Excel 表头后委托 runner;周批默认 incremental。
|
||||
"""
|
||||
_ensure_headers()
|
||||
return run_voucher_check_batch(task, run)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/__init__.py
|
||||
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
|
||||
依赖:各 adapter 模块。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.adapters.base import (
|
||||
AcquireAdapter,
|
||||
ArchiveAdapter,
|
||||
DirectoryScanAdapter,
|
||||
ScanOutcome,
|
||||
ScannedFile,
|
||||
SubjectAdapter,
|
||||
SubjectRow,
|
||||
)
|
||||
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
|
||||
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.adapters.hxjm_apa_subject import HxjmApaSubjectAdapter
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.adapters.registry import get_adapter, register_adapter, registered_adapter_names
|
||||
|
||||
register_adapter("hxjm_apa", HxjmApaSubjectAdapter)
|
||||
register_adapter("directory_scan", DmsDirectoryScanAdapter)
|
||||
register_adapter("erp_po_print", ErpPoPrintAdapter)
|
||||
register_adapter("oa_sales_release", OaSalesReleaseAdapter)
|
||||
register_adapter("dms_archive", DmsArchiveAdapter)
|
||||
|
||||
__all__ = [
|
||||
"AcquireAdapter",
|
||||
"ArchiveAdapter",
|
||||
"DirectoryScanAdapter",
|
||||
"DmsArchiveAdapter",
|
||||
"DmsDirectoryScanAdapter",
|
||||
"ErpPoPrintAdapter",
|
||||
"HxjmApaSubjectAdapter",
|
||||
"OaSalesReleaseAdapter",
|
||||
"ScanOutcome",
|
||||
"ScannedFile",
|
||||
"SubjectAdapter",
|
||||
"SubjectRow",
|
||||
"get_adapter",
|
||||
"register_adapter",
|
||||
"registered_adapter_names",
|
||||
]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/base.py
|
||||
|
||||
用途:立账凭证来源 Adapter 统一数据结构与协议。
|
||||
依赖:无。
|
||||
逻辑:引擎只消费这些类型;ERP/OA/DMS 细节留在各 Adapter 内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SubjectRow:
|
||||
"""应检 invoice 主体。"""
|
||||
|
||||
invoice_no: str
|
||||
invoice_date: date | None
|
||||
source_fingerprint: str
|
||||
attributes: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScannedFile:
|
||||
"""类型目录中命中的一个文件。"""
|
||||
|
||||
filename: str
|
||||
item_id: str | None = None
|
||||
folder_id: str | None = None
|
||||
path: str | None = None
|
||||
fingerprint: str | None = None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScanOutcome:
|
||||
"""一条文件规则对一张 invoice 的扫描结果。"""
|
||||
|
||||
status: str # matched / missing / technical_error
|
||||
file: ScannedFile | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
folder_id: str | None = None
|
||||
folder_path: str | None = None
|
||||
|
||||
|
||||
class SubjectAdapter(Protocol):
|
||||
"""获取期间内应检主体。"""
|
||||
|
||||
source_type: str
|
||||
|
||||
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
|
||||
"""
|
||||
拉取一个自然月的 invoice 清单。
|
||||
【AI 触发时机】周任务或强制重检需要本期主体时调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class DirectoryScanAdapter(Protocol):
|
||||
"""扫描文档库类型目录。"""
|
||||
|
||||
source_type: str
|
||||
|
||||
def scan(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
rule: dict[str, Any],
|
||||
) -> ScanOutcome:
|
||||
"""
|
||||
在对应类型目录中按命名模板匹配文件。
|
||||
【AI 触发时机】周任务对每张 invoice 的每条 directory_scan 规则调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class AcquireAdapter(Protocol):
|
||||
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
|
||||
|
||||
source_type: str
|
||||
wired: bool
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
获取并落入类型目录。
|
||||
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class ArchiveAdapter(Protocol):
|
||||
"""把已匹配文件复制到所有归档/{invoice}/。"""
|
||||
|
||||
wired: bool
|
||||
|
||||
def archive(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
file: ScannedFile,
|
||||
rule: dict[str, Any],
|
||||
) -> ScannedFile:
|
||||
"""
|
||||
复制到归档子目录;目标已有同名文件则跳过覆盖。
|
||||
【AI 触发时机】扫描命中且命名校验通过后调用。
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/dms_archive.py
|
||||
|
||||
用途:把类型目录中的命中文件复制到「所有归档/{invoice}/」。
|
||||
依赖:dms_client(SaveFolder + Copy);不调用 Move。
|
||||
逻辑:wired=True;目标目录已有同名文件则跳过并记 archived,复制失败记技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
|
||||
|
||||
class DmsArchiveAdapter:
|
||||
"""按票归档:建「所有归档/{invoice}/」并复制,同名跳过。"""
|
||||
|
||||
source_type = "dms_archive"
|
||||
wired = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._archive_root_ids: dict[str, str] = {}
|
||||
|
||||
def _archive_root_id(self, period_month: date) -> str:
|
||||
key = period_month.strftime("%Y-%m")
|
||||
if key not in self._archive_root_ids:
|
||||
self._archive_root_ids[key] = SalesDmsClient.ensure_month_archive_root(
|
||||
period_month=period_month
|
||||
)
|
||||
return self._archive_root_ids[key]
|
||||
|
||||
def archive(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
file: ScannedFile,
|
||||
rule: dict[str, Any],
|
||||
) -> ScannedFile:
|
||||
"""
|
||||
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
||||
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
|
||||
"""
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{invoice_no}/{file.filename}"
|
||||
source_item_id = str(file.item_id or "").strip()
|
||||
if not source_item_id:
|
||||
raise ServiceUnavailableError(
|
||||
"命中文件缺少文档库条目 ID,无法复制",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"adapter": self.source_type, "rule": rule.get("code")},
|
||||
)
|
||||
archive_root_id = self._archive_root_id(period_month)
|
||||
dest_folder_id = SalesDmsClient.ensure_folder(
|
||||
parent_folder_id=archive_root_id,
|
||||
leaf_name=str(invoice_no).strip(),
|
||||
)
|
||||
dest_row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id=source_item_id,
|
||||
dest_folder_id=dest_folder_id,
|
||||
leaf_name=file.filename,
|
||||
)
|
||||
return ScannedFile(
|
||||
filename=file.filename,
|
||||
item_id=str(dest_row.get("ID") or "").strip() or None,
|
||||
folder_id=dest_folder_id,
|
||||
path=archive_path,
|
||||
fingerprint=file.fingerprint,
|
||||
extra={
|
||||
"skipped_same_name": skipped,
|
||||
"source_item_id": source_item_id,
|
||||
"dest_version_id": dest_row.get("VersionID"),
|
||||
"rule": rule.get("code"),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/dms_directory_scan.py
|
||||
|
||||
用途:扫描销售开票附件/{年}/{月}/{类型目录} 并按命名模板匹配 invoice。
|
||||
依赖:dms_client、filename_match、fingerprint。
|
||||
逻辑:目录不存在视为该规则缺件;登录/Page 失败视为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScanOutcome, ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.filename_match import first_match
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
class DmsDirectoryScanAdapter:
|
||||
"""文档库类型目录扫描 Adapter。"""
|
||||
|
||||
source_type = "directory_scan"
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._month_folder_ids: dict[str, str | None] = {}
|
||||
self._type_folder_ids: dict[str, str | None] = {}
|
||||
self._type_files: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
def _period_key(self, period_month: date) -> str:
|
||||
return period_month.strftime("%Y-%m")
|
||||
|
||||
def _month_folder_id(self, period_month: date) -> str | None:
|
||||
key = self._period_key(period_month)
|
||||
if key not in self._month_folder_ids:
|
||||
_year_id, month_id = SalesDmsClient.resolve_period_folder(period_month=period_month)
|
||||
self._month_folder_ids[key] = month_id
|
||||
return self._month_folder_ids[key]
|
||||
|
||||
def _type_folder_id(self, period_month: date, type_folder: str) -> str | None:
|
||||
cache_key = f"{self._period_key(period_month)}/{type_folder}"
|
||||
if cache_key not in self._type_folder_ids:
|
||||
month_id = self._month_folder_id(period_month)
|
||||
if not month_id:
|
||||
self._type_folder_ids[cache_key] = None
|
||||
else:
|
||||
self._type_folder_ids[cache_key] = SalesDmsClient.find_child_folder(
|
||||
parent_folder_id=month_id,
|
||||
leaf_name=type_folder,
|
||||
)
|
||||
return self._type_folder_ids[cache_key]
|
||||
|
||||
def scan(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
rule: dict[str, Any],
|
||||
) -> ScanOutcome:
|
||||
"""
|
||||
在类型目录中匹配当前 invoice 的文件。
|
||||
核心逻辑:缓存月目录与类型目录列表,避免每票重复 Page。
|
||||
"""
|
||||
type_folder = str(rule.get("type_folder") or "").strip()
|
||||
template = str(rule.get("filename_template") or "").strip()
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
|
||||
try:
|
||||
folder_id = self._type_folder_id(period_month, type_folder)
|
||||
if not folder_id:
|
||||
return ScanOutcome(
|
||||
status="missing",
|
||||
folder_path=folder_path,
|
||||
)
|
||||
cache_key = folder_id
|
||||
if cache_key not in self._type_files:
|
||||
self._type_files[cache_key] = SalesDmsClient.list_files(folder_id=folder_id)
|
||||
rows = self._type_files[cache_key]
|
||||
names = [str(row.get("LeafName") or "").strip() for row in rows]
|
||||
hit = first_match(names, template=template, invoice_no=invoice_no)
|
||||
if hit is None:
|
||||
return ScanOutcome(status="missing", folder_id=folder_id, folder_path=folder_path)
|
||||
row = next((item for item in rows if str(item.get("LeafName") or "").strip() == hit.filename), {})
|
||||
item_id = str((row or {}).get("ID") or "") or None
|
||||
version_id = str((row or {}).get("VersionID") or "")
|
||||
fingerprint = build_material_fingerprint(
|
||||
[(f"{hit.filename}|{item_id or ''}|{version_id}", 0, 0)]
|
||||
)
|
||||
return ScanOutcome(
|
||||
status="matched",
|
||||
folder_id=folder_id,
|
||||
folder_path=folder_path,
|
||||
file=ScannedFile(
|
||||
filename=hit.filename,
|
||||
item_id=item_id,
|
||||
folder_id=folder_id,
|
||||
path=str((row or {}).get("Path") or folder_path),
|
||||
fingerprint=fingerprint,
|
||||
extra={"version_id": (row or {}).get("VersionID")},
|
||||
),
|
||||
)
|
||||
except ServiceUnavailableError as exc:
|
||||
return ScanOutcome(
|
||||
status="technical_error",
|
||||
folder_path=folder_path,
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/erp_po_print.py
|
||||
|
||||
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
|
||||
|
||||
class ErpPoPrintAdapter:
|
||||
"""PO 打印占位;未接线时禁止生成假 PDF。"""
|
||||
|
||||
source_type = "erp_po_print"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按 invoice 反查 PO 并打印到类型目录。
|
||||
【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"ERP PO 打印尚未接线",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
"period": period_month.isoformat(),
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/hxjm_apa_subject.py
|
||||
|
||||
用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。
|
||||
依赖:erp_repository.fetch_month_invoices、fingerprint。
|
||||
逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.services.voucher_check.adapters.base import SubjectRow
|
||||
from app.services.voucher_check.erp_repository import fetch_month_invoices
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
class HxjmApaSubjectAdapter:
|
||||
"""HXJM apa08/apa09 主体 Adapter。"""
|
||||
|
||||
source_type = "hxjm_apa"
|
||||
|
||||
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
|
||||
"""
|
||||
查询上月发票号集合并生成主体指纹。
|
||||
核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。
|
||||
|
||||
Args:
|
||||
period_month: 检核月首日,由 runner 预先算好。
|
||||
config: 含 ERP 连接的运行配置。
|
||||
|
||||
Returns:
|
||||
SubjectRow 列表。
|
||||
"""
|
||||
actual_period, rows = fetch_month_invoices(config)
|
||||
if actual_period != period_month:
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
raise ServiceUnavailableError(
|
||||
"ERP 期间与批次期间不一致",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={
|
||||
"expected": period_month.isoformat(),
|
||||
"actual": actual_period.isoformat(),
|
||||
},
|
||||
)
|
||||
subjects: list[SubjectRow] = []
|
||||
for row in rows:
|
||||
fingerprint = build_material_fingerprint(
|
||||
[(row.invoice_no, 0, int((row.invoice_date or period_month).toordinal()))]
|
||||
)
|
||||
subjects.append(
|
||||
SubjectRow(
|
||||
invoice_no=row.invoice_no,
|
||||
invoice_date=row.invoice_date,
|
||||
source_fingerprint=fingerprint,
|
||||
attributes={"scope_code": getattr(config, "scope_code", "HXJM")},
|
||||
)
|
||||
)
|
||||
return subjects
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/oa_sales_release.py
|
||||
|
||||
用途:OA 销货放行单模拟页面打印的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:一期规则已定但页面自动化未实现;周任务不调用,只扫描「销货单」目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
|
||||
|
||||
class OaSalesReleaseAdapter:
|
||||
"""销货放行单打印占位;未接线时禁止生成假 PDF。"""
|
||||
|
||||
source_type = "oa_sales_release"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按上月/归档/HXJM/发票号非空过滤后逐条打印。
|
||||
【AI 触发时机】仅当独立「抓取销货放行单」任务上线后调用。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"OA 销货放行单打印尚未接线",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
"period": period_month.isoformat(),
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/registry.py
|
||||
|
||||
用途:按 source_type / adapter 名解析已注册 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:模块 import 时 register;引擎禁止使用未登记的 source_type。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
_REGISTRY: dict[str, Callable[[], Any]] = {}
|
||||
|
||||
|
||||
def register_adapter(name: str, factory: Callable[[], Any]) -> None:
|
||||
"""登记 Adapter 工厂。同名后注册覆盖,便于测试注入。"""
|
||||
key = str(name or "").strip()
|
||||
if not key:
|
||||
raise ValidationError("Adapter 名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
_REGISTRY[key] = factory
|
||||
|
||||
|
||||
def get_adapter(name: str) -> Any:
|
||||
"""
|
||||
按名称构造 Adapter。
|
||||
核心逻辑:未注册则配置失败,避免引擎落到未知来源。
|
||||
"""
|
||||
key = str(name or "").strip()
|
||||
factory = _REGISTRY.get(key)
|
||||
if factory is None:
|
||||
raise ValidationError(
|
||||
f"未注册的 Adapter: {key}",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"adapter": key},
|
||||
)
|
||||
return factory()
|
||||
|
||||
|
||||
def registered_adapter_names() -> tuple[str, ...]:
|
||||
"""返回已登记名称,供测试断言。"""
|
||||
return tuple(sorted(_REGISTRY))
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/aggregator.py
|
||||
|
||||
用途:按单文件结果计算缺件双口径、invoice 行 Excel 值与批次状态。
|
||||
依赖:无 IO。
|
||||
逻辑:缺件文件数计 missing 条数;缺件 invoice 数对 missing 去重;技术失败/跳过/待归档不计缺件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
EXCEL_PRESENT = "有"
|
||||
EXCEL_MISSING = "缺件"
|
||||
EXCEL_PENDING = "未检核"
|
||||
INVOICE_COMPLETE = "完整"
|
||||
INVOICE_MISSING = "缺件"
|
||||
INVOICE_PENDING = "待处理"
|
||||
|
||||
_MISSING = "missing"
|
||||
_ARCHIVED = "archived"
|
||||
_SKIPPED = "skipped"
|
||||
_TECH = "technical_error"
|
||||
_STAGED = "staged"
|
||||
|
||||
|
||||
def excel_cell_for_rule(statuses: list[str]) -> str:
|
||||
"""一条规则在 Excel 中的单元格:缺件优先于有,其余为未检核。"""
|
||||
if any(status == _MISSING for status in statuses):
|
||||
return EXCEL_MISSING
|
||||
if statuses and all(status == _ARCHIVED for status in statuses):
|
||||
return EXCEL_PRESENT
|
||||
return EXCEL_PENDING
|
||||
|
||||
|
||||
def invoice_conclusion(cells: list[str]) -> str:
|
||||
"""invoice 行总体状态。"""
|
||||
if cells and all(cell == EXCEL_PRESENT for cell in cells):
|
||||
return INVOICE_COMPLETE
|
||||
if any(cell == EXCEL_MISSING for cell in cells):
|
||||
return INVOICE_MISSING
|
||||
return INVOICE_PENDING
|
||||
|
||||
|
||||
def aggregate_file_results(
|
||||
results: list[dict[str, Any]],
|
||||
*,
|
||||
rules: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
聚合单文件结果。
|
||||
核心逻辑:只认 status 字段;同一 invoice 多条缺件文件计多份、invoice 只计一次。
|
||||
"""
|
||||
missing_files = [row for row in results if row.get("status") == _MISSING]
|
||||
missing_invoices = {str(row.get("invoice_no") or "") for row in missing_files}
|
||||
missing_invoices.discard("")
|
||||
by_type: dict[str, dict[str, Any]] = {}
|
||||
for rule in rules:
|
||||
code = str(rule.get("code") or "")
|
||||
type_rows = [row for row in results if row.get("rule_code") == code]
|
||||
type_missing = [row for row in type_rows if row.get("status") == _MISSING]
|
||||
by_type[code] = {
|
||||
"rule_code": code,
|
||||
"rule_name": rule.get("name") or code,
|
||||
"missing_file_count": len(type_missing),
|
||||
"missing_invoice_count": len({str(row.get("invoice_no") or "") for row in type_missing} - {""}),
|
||||
}
|
||||
|
||||
invoices: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for row in results:
|
||||
invoices[str(row.get("invoice_no") or "")].append(row)
|
||||
|
||||
excel_rows: list[dict[str, Any]] = []
|
||||
for invoice_no, rows in invoices.items():
|
||||
if not invoice_no:
|
||||
continue
|
||||
cells: dict[str, str] = {}
|
||||
ordered_cells: list[str] = []
|
||||
for rule in rules:
|
||||
code = str(rule.get("code") or "")
|
||||
cell = excel_cell_for_rule(
|
||||
[str(item.get("status") or "") for item in rows if item.get("rule_code") == code]
|
||||
)
|
||||
cells[code] = cell
|
||||
ordered_cells.append(cell)
|
||||
excel_rows.append(
|
||||
{
|
||||
"invoice_no": invoice_no,
|
||||
"invoice_date": next((item.get("invoice_date") for item in rows if item.get("invoice_date")), None),
|
||||
"cells": cells,
|
||||
"status": invoice_conclusion(ordered_cells),
|
||||
}
|
||||
)
|
||||
excel_rows.sort(key=lambda item: str(item["invoice_no"]))
|
||||
|
||||
batch_status = "completed"
|
||||
if missing_files:
|
||||
batch_status = "missing"
|
||||
elif any(row.get("status") == _TECH for row in results):
|
||||
batch_status = "technical_failed"
|
||||
|
||||
return {
|
||||
"subject_count": len([key for key in invoices if key]),
|
||||
"archived_file_count": sum(1 for row in results if row.get("status") == _ARCHIVED),
|
||||
"skipped_file_count": sum(1 for row in results if row.get("status") == _SKIPPED),
|
||||
"missing_file_count": len(missing_files),
|
||||
"missing_invoice_count": len(missing_invoices),
|
||||
"technical_error_count": sum(1 for row in results if row.get("status") == _TECH),
|
||||
"staged_file_count": sum(1 for row in results if row.get("status") == _STAGED),
|
||||
"by_file_type": by_type,
|
||||
"excel_rows": excel_rows,
|
||||
"batch_status": batch_status,
|
||||
}
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/config.py
|
||||
|
||||
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。
|
||||
依赖:Flask current_app.config、core.errors.ValidationError。
|
||||
逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。
|
||||
逻辑:runner / share_scanner / erp_repository / 新引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,13 +38,14 @@ DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [
|
||||
]
|
||||
|
||||
DEFAULT_JOB_PARAMS: dict[str, Any] = {
|
||||
"profile_code": "sales",
|
||||
"scope_code": "HXJM",
|
||||
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"required_files": DEFAULT_REQUIRED_FILES,
|
||||
"filename_case_sensitive": True,
|
||||
"notify_missing_enabled": True,
|
||||
"notify_failure_enabled": True,
|
||||
"same_day_dedup_enabled": True,
|
||||
"same_day_dedup_enabled": False,
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +79,20 @@ class VoucherCheckConfig:
|
||||
erp_timeout_seconds: int = 30
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoucherCheckEngineConfig:
|
||||
"""销售一期引擎运行配置:ERP + 通知开关,不再依赖共享盘。"""
|
||||
|
||||
scope_code: str
|
||||
profile_code: str
|
||||
notify_missing_enabled: bool
|
||||
notify_failure_enabled: bool
|
||||
erp_dsn: str
|
||||
erp_username: str
|
||||
erp_password: str
|
||||
erp_timeout_seconds: int = 30
|
||||
|
||||
|
||||
def _config_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
|
||||
return ValidationError(
|
||||
message,
|
||||
@@ -168,6 +183,36 @@ def validate_directory_template(template: str) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _erp_settings() -> tuple[str, str, str, int]:
|
||||
"""读取 ERP 只读连接;密码只来自环境/配置,不写日志。"""
|
||||
cfg = current_app.config if has_app_context() else {}
|
||||
erp_dsn = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_DSN")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_DSN")
|
||||
or cfg.get("ERP_DB_DSN")
|
||||
or os.getenv("ERP_DB_DSN")
|
||||
or ""
|
||||
).strip()
|
||||
erp_username = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_USERNAME")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_USERNAME")
|
||||
or ""
|
||||
).strip()
|
||||
erp_password = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_PASSWORD")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_PASSWORD")
|
||||
or ""
|
||||
)
|
||||
if not erp_dsn or not erp_username:
|
||||
raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
|
||||
timeout = int(
|
||||
cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
|
||||
or 30
|
||||
)
|
||||
return erp_dsn, erp_username, erp_password, max(1, timeout)
|
||||
|
||||
|
||||
def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig:
|
||||
"""
|
||||
合并 env 与 job_params,返回校验后的检核配置。
|
||||
@@ -207,31 +252,7 @@ def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> Vouch
|
||||
if not local_root and not share_unc:
|
||||
raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC")
|
||||
|
||||
erp_dsn = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_DSN")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_DSN")
|
||||
or cfg.get("ERP_DB_DSN")
|
||||
or os.getenv("ERP_DB_DSN")
|
||||
or ""
|
||||
).strip()
|
||||
erp_username = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_USERNAME")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_USERNAME")
|
||||
or ""
|
||||
).strip()
|
||||
erp_password = str(
|
||||
cfg.get("VOUCHER_CHECK_ERP_PASSWORD")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_PASSWORD")
|
||||
or ""
|
||||
)
|
||||
if not erp_dsn or not erp_username:
|
||||
raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
|
||||
|
||||
timeout = int(
|
||||
cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
|
||||
or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
|
||||
or 30
|
||||
)
|
||||
erp_dsn, erp_username, erp_password, timeout = _erp_settings()
|
||||
|
||||
return VoucherCheckConfig(
|
||||
scope_code=scope_code,
|
||||
@@ -251,6 +272,31 @@ def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> Vouch
|
||||
)
|
||||
|
||||
|
||||
def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheckEngineConfig:
|
||||
"""
|
||||
加载销售一期引擎配置。
|
||||
核心逻辑:不要求共享盘;DMS 根目录由 SalesDmsClient.ensure_configured 在 runner 中校验。
|
||||
"""
|
||||
params = dict(DEFAULT_JOB_PARAMS)
|
||||
if isinstance(job_params, dict):
|
||||
params.update({k: v for k, v in job_params.items() if v is not None})
|
||||
scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM"
|
||||
if scope_code != "HXJM":
|
||||
raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code})
|
||||
profile_code = str(params.get("profile_code") or "sales").strip() or "sales"
|
||||
erp_dsn, erp_username, erp_password, timeout = _erp_settings()
|
||||
return VoucherCheckEngineConfig(
|
||||
scope_code=scope_code,
|
||||
profile_code=profile_code,
|
||||
notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True),
|
||||
notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True),
|
||||
erp_dsn=erp_dsn,
|
||||
erp_username=erp_username,
|
||||
erp_password=erp_password,
|
||||
erp_timeout_seconds=timeout,
|
||||
)
|
||||
|
||||
|
||||
def resolve_share_root(config: VoucherCheckConfig) -> str:
|
||||
"""
|
||||
解析实际扫描根路径。
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/dms_client.py
|
||||
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
|
||||
_LOCK = threading.Lock()
|
||||
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
||||
|
||||
ARCHIVE_ROOT_LEAF = "所有归档"
|
||||
|
||||
|
||||
def _extract_item_id(payload: dict[str, Any]) -> str:
|
||||
"""
|
||||
从 DMS SaveFolder / Copy 响应中取出条目 ID。
|
||||
核心逻辑:现网 Data 可能是对象或字符串;缺字段时返回空串,由调用方再 Page 回查。
|
||||
"""
|
||||
data = payload.get("Data")
|
||||
if isinstance(data, str) and data.strip():
|
||||
return data.strip()
|
||||
if not isinstance(data, dict):
|
||||
return ""
|
||||
for key in ("ID", "ItemID", "FolderID"):
|
||||
value = str(data.get(key) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
nested = data.get("Item") or data.get("Folder") or {}
|
||||
if isinstance(nested, dict):
|
||||
return str(nested.get("ID") or "").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _is_name_conflict(message: str) -> bool:
|
||||
"""判断 DMS 返回是否为同名/已存在冲突,便于按「同名跳过」回收。"""
|
||||
text = str(message or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
lowered = text.lower()
|
||||
return any(
|
||||
needle in text
|
||||
for needle in ("已存在", "同名", "重复名称", "名称重复")
|
||||
) or any(
|
||||
needle in lowered
|
||||
for needle in ("already exist", "already exists", "duplicate name")
|
||||
)
|
||||
|
||||
|
||||
class SalesDmsClient:
|
||||
"""销售开票附件 DMS 客户端;不把账号密码返回给 API。"""
|
||||
|
||||
@classmethod
|
||||
def _cfg(cls, key: str, fallback: str = "") -> str:
|
||||
value = current_app.config.get(key) or fallback
|
||||
return str(value or "").strip()
|
||||
|
||||
@classmethod
|
||||
def base_url(cls) -> str:
|
||||
return (cls._cfg("VOUCHER_CHECK_DMS_BASE_URL") or cls._cfg("CONTRACT_DMS_BASE_URL")).rstrip("/")
|
||||
|
||||
@classmethod
|
||||
def library_id(cls) -> str:
|
||||
return cls._cfg("VOUCHER_CHECK_DMS_LIBRARY_ID") or cls._cfg("CONTRACT_DMS_LIBRARY_ID")
|
||||
|
||||
@classmethod
|
||||
def root_folder_id(cls) -> str:
|
||||
return cls._cfg("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID")
|
||||
|
||||
@classmethod
|
||||
def username(cls) -> str:
|
||||
return cls._cfg("VOUCHER_CHECK_DMS_USERNAME") or cls._cfg("CONTRACT_DMS_USERNAME")
|
||||
|
||||
@classmethod
|
||||
def password(cls) -> str:
|
||||
return str(
|
||||
current_app.config.get("VOUCHER_CHECK_DMS_PASSWORD")
|
||||
or current_app.config.get("CONTRACT_DMS_PASSWORD")
|
||||
or ""
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_configured(cls) -> bool:
|
||||
"""判断销售 DMS 基址、账号、文档库 ID 和销售根目录是否齐全。"""
|
||||
return bool(cls.base_url() and cls.username() and cls.password() and cls.library_id() and cls.root_folder_id())
|
||||
|
||||
@classmethod
|
||||
def ensure_configured(cls) -> None:
|
||||
"""配置缺失时在批次开始前失败,避免空扫被当成业务缺件。"""
|
||||
if not cls.is_configured():
|
||||
raise ValidationError(
|
||||
"未配置销售开票附件文档库根目录",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"missing": "VOUCHER_CHECK_DMS_ROOT_FOLDER_ID"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _session(cls, *, refresh: bool = False) -> requests.Session:
|
||||
"""登录 DMS 并缓存会话。"""
|
||||
with _LOCK:
|
||||
session = _CACHE.get("session")
|
||||
if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200:
|
||||
return session
|
||||
session = requests.Session()
|
||||
try:
|
||||
response = session.post(
|
||||
f"{cls.base_url()}/Login/_api/Login",
|
||||
json={"LoginName": cls.username(), "Pwd": cls.password()},
|
||||
timeout=20,
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except requests.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"文档库登录失败",
|
||||
code="VOUCHER_CHECK.DMS_UNAVAILABLE",
|
||||
) from exc
|
||||
if int(payload.get("Code") or 0) != 0:
|
||||
raise ServiceUnavailableError(
|
||||
payload.get("Msg") or "文档库登录失败",
|
||||
code="VOUCHER_CHECK.DMS_UNAVAILABLE",
|
||||
)
|
||||
_CACHE.update({"session": session, "created_at": time.time()})
|
||||
return session
|
||||
|
||||
@classmethod
|
||||
def _post_json(
|
||||
cls,
|
||||
path: str,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
timeout: int = 30,
|
||||
failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE",
|
||||
failure_message: str = "文档库请求失败",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
POST JSON 到现网 DMS,并统一处理 401 刷新与 Code!=0。
|
||||
核心逻辑:路径相对基址;失败抛 ServiceUnavailableError,不把凭据写入异常。
|
||||
"""
|
||||
url = f"{cls.base_url()}{path}"
|
||||
try:
|
||||
session = cls._session()
|
||||
response = session.post(url, json=payload, timeout=timeout)
|
||||
if response.status_code in {401, 403}:
|
||||
session = cls._session(refresh=True)
|
||||
response = session.post(url, json=payload, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
raise ServiceUnavailableError(failure_message, code=failure_code) from exc
|
||||
if int(data.get("Code") or 0) != 0:
|
||||
raise ServiceUnavailableError(
|
||||
data.get("Msg") or failure_message,
|
||||
code=failure_code,
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
|
||||
"""
|
||||
查询一个父目录下的条目。
|
||||
核心逻辑:POST Item/Page,按页累加直到本页不足 Size 或达到 Total;避免「所有归档」超过 200 个子目录时漏建/漏跳过。
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
page_size = 200
|
||||
index = 1
|
||||
while index <= 50:
|
||||
payload = {
|
||||
"LibraryID": cls.library_id(),
|
||||
"ParentFolderID": parent_folder_id,
|
||||
"Keywords": "",
|
||||
"Page": {"Size": page_size, "Index": index},
|
||||
"Total": 0,
|
||||
"Recursion": recursion,
|
||||
"OrderBy": [],
|
||||
"FieldQuery": [],
|
||||
"LeafName": leaf_name,
|
||||
}
|
||||
data = cls._post_json("/Api/_api/APS/Public/Item/Page", payload, timeout=30)
|
||||
section = data.get("Data") or {}
|
||||
batch = section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or []
|
||||
items.extend(batch)
|
||||
total = int(section.get("Total") or 0)
|
||||
if len(batch) < page_size:
|
||||
break
|
||||
if total and len(items) >= total:
|
||||
break
|
||||
index += 1
|
||||
return items
|
||||
|
||||
@classmethod
|
||||
def find_child_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str | None:
|
||||
"""在父目录下按 LeafName 找文件夹 ID,找不到返回 None。"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not wanted:
|
||||
return None
|
||||
for row in cls.page(parent_folder_id=parent_folder_id, recursion=False):
|
||||
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted:
|
||||
folder_id = str(row.get("ID") or "").strip()
|
||||
if folder_id:
|
||||
return folder_id
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
|
||||
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not wanted:
|
||||
return None
|
||||
for row in cls.list_files(folder_id=parent_folder_id):
|
||||
if str(row.get("LeafName") or "").strip() == wanted:
|
||||
return row
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
|
||||
"""
|
||||
解析销售开票附件/{yyyy}/{MM} 的 FolderID。
|
||||
核心逻辑:从销售根逐级找年、月目录;缺层返回 (None, None),由扫描记缺件而非技术失败。
|
||||
"""
|
||||
root = cls.root_folder_id()
|
||||
year_name = f"{period_month.year:04d}"
|
||||
month_name = f"{period_month.month:02d}"
|
||||
year_id = cls.find_child_folder(parent_folder_id=root, leaf_name=year_name)
|
||||
if not year_id:
|
||||
return None, None
|
||||
month_id = cls.find_child_folder(parent_folder_id=year_id, leaf_name=month_name)
|
||||
return year_id, month_id
|
||||
|
||||
@classmethod
|
||||
def list_files(cls, *, folder_id: str) -> list[dict[str, Any]]:
|
||||
"""列出目录下的非文件夹条目。"""
|
||||
rows = cls.page(parent_folder_id=folder_id, recursion=False)
|
||||
return [row for row in rows if not row.get("IsFolder")]
|
||||
|
||||
@classmethod
|
||||
def ensure_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str:
|
||||
"""
|
||||
确保父目录下存在指定 LeafName 的文件夹;没有则 SaveFolder。
|
||||
核心逻辑:先 Page 查找;已存在直接返回。创建时若接口报同名,再查一次当作成功。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not wanted:
|
||||
raise ValidationError("文件夹名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing
|
||||
try:
|
||||
payload = cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/SaveFolder",
|
||||
{
|
||||
"ID": "",
|
||||
"LibraryID": cls.library_id(),
|
||||
"ParentFolderID": parent_folder_id,
|
||||
"LeafName": wanted,
|
||||
"FieldValues": [],
|
||||
},
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库创建文件夹失败",
|
||||
)
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing
|
||||
if _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing
|
||||
raise
|
||||
created_id = _extract_item_id(payload)
|
||||
if created_id:
|
||||
return created_id
|
||||
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing
|
||||
raise ServiceUnavailableError(
|
||||
"创建文件夹后未能解析 FolderID",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def ensure_month_archive_root(cls, *, period_month: date) -> str:
|
||||
"""
|
||||
确保销售开票附件/{yyyy}/{MM}/所有归档 存在并返回 FolderID。
|
||||
核心逻辑:月目录必须已存在(扫描命中才归档);缺月目录视为技术失败,不降级为缺件。
|
||||
"""
|
||||
_year_id, month_id = cls.resolve_period_folder(period_month=period_month)
|
||||
if not month_id:
|
||||
raise ServiceUnavailableError(
|
||||
"销售开票附件年/月目录不存在,无法创建归档文件夹",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
)
|
||||
return cls.ensure_folder(parent_folder_id=month_id, leaf_name=ARCHIVE_ROOT_LEAF)
|
||||
|
||||
@classmethod
|
||||
def ensure_invoice_archive_folder(cls, *, period_month: date, invoice_no: str) -> str:
|
||||
"""
|
||||
确保所有归档/{invoice}/ 存在并返回 FolderID。
|
||||
核心逻辑:先保证「所有归档」,再按发票号建子目录。
|
||||
"""
|
||||
invoice = str(invoice_no or "").strip()
|
||||
if not invoice:
|
||||
raise ValidationError("归档发票号不能为空", code="VOUCHER_CHECK.INVOICE_REQUIRED")
|
||||
archive_root_id = cls.ensure_month_archive_root(period_month=period_month)
|
||||
return cls.ensure_folder(parent_folder_id=archive_root_id, leaf_name=invoice)
|
||||
|
||||
@classmethod
|
||||
def copy_items(cls, *, item_ids: list[str], dest_folder_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
把文档库条目复制到目标文件夹(不移动原件)。
|
||||
核心逻辑:POST Item/Copy;ItemID 为数组,与现网前端 CopyFileFolder 一致。
|
||||
"""
|
||||
ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()]
|
||||
dest = str(dest_folder_id or "").strip()
|
||||
if not ids:
|
||||
raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not dest:
|
||||
raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/Copy",
|
||||
{"ItemID": ids, "ParentFolderID": dest},
|
||||
timeout=60,
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库复制文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def copy_file_skip_same_name(
|
||||
cls,
|
||||
*,
|
||||
source_item_id: str,
|
||||
dest_folder_id: str,
|
||||
leaf_name: str,
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||||
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
|
||||
|
||||
Returns:
|
||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
source = str(source_item_id or "").strip()
|
||||
dest = str(dest_folder_id or "").strip()
|
||||
if not source:
|
||||
raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not dest:
|
||||
raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not wanted:
|
||||
raise ValidationError("复制文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
|
||||
try:
|
||||
cls.copy_items(item_ids=[source], dest_folder_id=dest)
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
if _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
raise
|
||||
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if not dest_row:
|
||||
raise ServiceUnavailableError(
|
||||
"复制成功但目标目录未找到同名文件",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
return dest_row, False
|
||||
@@ -0,0 +1,182 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/engine_persistence.py
|
||||
|
||||
用途:新引擎批次、主体、单文件结果与通知审计的写入。
|
||||
依赖:models.voucher_check 新表。
|
||||
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckNotification,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckSubject,
|
||||
)
|
||||
|
||||
|
||||
def create_run(
|
||||
*,
|
||||
schedule_run_id: int | None,
|
||||
run_no: str,
|
||||
profile_code: str,
|
||||
profile_version: str,
|
||||
profile_snapshot: dict[str, Any],
|
||||
period_month: date,
|
||||
mode: str,
|
||||
started_at: datetime,
|
||||
) -> VoucherCheckRun:
|
||||
"""创建 running 状态的检核批次。"""
|
||||
run = VoucherCheckRun(
|
||||
schedule_run_id=schedule_run_id,
|
||||
run_no=run_no,
|
||||
profile_code=profile_code,
|
||||
profile_version=profile_version,
|
||||
profile_snapshot_json=profile_snapshot,
|
||||
period_month=period_month,
|
||||
mode=mode,
|
||||
status="running",
|
||||
started_at=started_at,
|
||||
created_at=started_at,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def persist_engine_results(
|
||||
*,
|
||||
run: VoucherCheckRun,
|
||||
subjects: list[dict[str, Any]],
|
||||
file_results: list[dict[str, Any]],
|
||||
stats: dict[str, Any],
|
||||
now: datetime | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入主体与单文件结果,并固化批次统计快照。
|
||||
核心逻辑:file_results 是缺件/Excel 真相源;列表查询不再重算。
|
||||
"""
|
||||
ts = now or datetime.utcnow()
|
||||
subject_ids: dict[str, int] = {}
|
||||
for item in subjects:
|
||||
invoice_no = str(item["invoice_no"]).strip()
|
||||
row = VoucherCheckSubject(
|
||||
run_id=run.id,
|
||||
invoice_no=invoice_no,
|
||||
invoice_date=item.get("invoice_date"),
|
||||
source_fingerprint=item.get("source_fingerprint"),
|
||||
attributes_json=item.get("attributes") or {},
|
||||
created_at=ts,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
subject_ids[invoice_no] = row.id
|
||||
|
||||
for item in file_results:
|
||||
invoice_no = str(item["invoice_no"]).strip()
|
||||
db.session.add(
|
||||
VoucherCheckFileResult(
|
||||
run_id=run.id,
|
||||
subject_id=subject_ids.get(invoice_no),
|
||||
invoice_no=invoice_no,
|
||||
rule_code=str(item["rule_code"]),
|
||||
rule_name=str(item.get("rule_name") or item["rule_code"]),
|
||||
source_type=str(item.get("source_type") or "directory_scan"),
|
||||
expected_name=item.get("expected_name"),
|
||||
matched_name=item.get("matched_name"),
|
||||
source_folder_id=item.get("source_folder_id"),
|
||||
source_item_id=item.get("source_item_id"),
|
||||
archive_folder_id=item.get("archive_folder_id"),
|
||||
archive_item_id=item.get("archive_item_id"),
|
||||
source_path=item.get("source_path"),
|
||||
archive_path=item.get("archive_path"),
|
||||
status=str(item["status"]),
|
||||
missing_reason=item.get("missing_reason"),
|
||||
error_code=item.get("error_code"),
|
||||
error_message=item.get("error_message"),
|
||||
source_fingerprint=item.get("source_fingerprint"),
|
||||
checked_at=item.get("checked_at") or ts,
|
||||
created_at=ts,
|
||||
)
|
||||
)
|
||||
|
||||
run.subject_count = int(stats.get("subject_count") or 0)
|
||||
run.archived_file_count = int(stats.get("archived_file_count") or 0)
|
||||
run.skipped_file_count = int(stats.get("skipped_file_count") or 0)
|
||||
run.missing_file_count = int(stats.get("missing_file_count") or 0)
|
||||
run.missing_invoice_count = int(stats.get("missing_invoice_count") or 0)
|
||||
run.technical_error_count = int(stats.get("technical_error_count") or 0)
|
||||
run.staged_file_count = int(stats.get("staged_file_count") or 0)
|
||||
run.stats_json = {
|
||||
"by_file_type": stats.get("by_file_type") or {},
|
||||
"batch_status": stats.get("batch_status"),
|
||||
}
|
||||
run.status = str(stats.get("batch_status") or "completed")
|
||||
run.finished_at = ts
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def persist_notification(
|
||||
*,
|
||||
run_id: int,
|
||||
excel_filename: str | None,
|
||||
recipient_user_ids: list[int],
|
||||
send_status: str,
|
||||
skip_reason: str | None,
|
||||
summary: dict[str, Any],
|
||||
sent_at: datetime | None,
|
||||
) -> VoucherCheckNotification:
|
||||
"""写入或覆盖本批次通知审计(一个 run 一条)。"""
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotification)
|
||||
.filter_by(run_id=run_id)
|
||||
.one_or_none()
|
||||
)
|
||||
if row is None:
|
||||
row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow())
|
||||
db.session.add(row)
|
||||
row.excel_filename = excel_filename
|
||||
row.recipient_user_ids_json = recipient_user_ids
|
||||
row.send_status = send_status
|
||||
row.skip_reason = skip_reason
|
||||
row.summary_json = summary
|
||||
row.sent_at = sent_at
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def load_previous_archived_fingerprints(
|
||||
*,
|
||||
profile_code: str,
|
||||
period_month: date,
|
||||
exclude_run_id: int | None = None,
|
||||
) -> dict[tuple[str, str], str]:
|
||||
"""
|
||||
读取同 Profile+期间已归档文件的最新指纹,供增量跳过。
|
||||
核心逻辑:按 file_results.id 倒序,每个 invoice+rule 只留一条 archived。
|
||||
"""
|
||||
query = (
|
||||
db.session.query(VoucherCheckFileResult, VoucherCheckRun)
|
||||
.join(VoucherCheckRun, VoucherCheckFileResult.run_id == VoucherCheckRun.id)
|
||||
.filter(
|
||||
VoucherCheckRun.profile_code == profile_code,
|
||||
VoucherCheckRun.period_month == period_month,
|
||||
VoucherCheckFileResult.status == "archived",
|
||||
)
|
||||
.order_by(VoucherCheckFileResult.id.desc())
|
||||
)
|
||||
if exclude_run_id:
|
||||
query = query.filter(VoucherCheckFileResult.run_id != exclude_run_id)
|
||||
found: dict[tuple[str, str], str] = {}
|
||||
for result, _run in query.all():
|
||||
key = (result.invoice_no, result.rule_code)
|
||||
if key in found:
|
||||
continue
|
||||
if result.source_fingerprint:
|
||||
found[key] = result.source_fingerprint
|
||||
return found
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/erp_repository.py
|
||||
|
||||
用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。
|
||||
用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。
|
||||
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
|
||||
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
|
||||
"""
|
||||
@@ -31,7 +31,7 @@ SELECT DISTINCT
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpInvoiceRow:
|
||||
"""ERP 当月发票行。"""
|
||||
"""ERP 发票行。"""
|
||||
|
||||
invoice_no: str
|
||||
invoice_date: date | None
|
||||
@@ -60,13 +60,32 @@ def current_period_bounds(now: datetime | None = None) -> tuple[date, date, date
|
||||
return period_month, next_month, period_start, next_start
|
||||
|
||||
|
||||
def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
|
||||
"""
|
||||
按 Asia/Shanghai 计算上一个自然月起止。
|
||||
核心逻辑:周二跑批检核上个月;跨年时 1 月回退到上年 12 月。
|
||||
|
||||
Returns:
|
||||
(period_month_first, current_month_first, period_start_dt, next_period_start_dt)
|
||||
其中 next_period_start 为当前月 1 日,即上月结束边界。
|
||||
"""
|
||||
current_month, _next_month, _current_start, _next_start = current_period_bounds(now)
|
||||
if current_month.month == 1:
|
||||
period_month = date(current_month.year - 1, 12, 1)
|
||||
else:
|
||||
period_month = date(current_month.year, current_month.month - 1, 1)
|
||||
period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ)
|
||||
next_start = datetime(current_month.year, current_month.month, 1, 0, 0, 0, tzinfo=_TZ)
|
||||
return period_month, current_month, period_start, next_start
|
||||
|
||||
|
||||
def fetch_month_invoices(
|
||||
config: VoucherCheckConfig,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[date, list[ErpInvoiceRow]]:
|
||||
"""
|
||||
查询当前自然月发票清单。
|
||||
查询上一个自然月发票清单。
|
||||
|
||||
Args:
|
||||
config: 含 Oracle DSN/账号的检核配置。
|
||||
@@ -78,7 +97,7 @@ def fetch_month_invoices(
|
||||
Raises:
|
||||
ServiceUnavailableError: Oracle 不可用。
|
||||
"""
|
||||
period_month, _next_month, period_start, next_start = current_period_bounds(now)
|
||||
period_month, _current_month, period_start, next_start = previous_period_bounds(now)
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/excel_rows.py
|
||||
|
||||
用途:把批次明细转换为通用 Excel 导出行与表头。
|
||||
依赖:无。
|
||||
逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。
|
||||
用途:把按 invoice 聚合的检核结果转为排程 Excel 行与表头。
|
||||
依赖:aggregator 单元格文案。
|
||||
逻辑:一行一张 invoice;六类必检列为有/缺件/未检核;资料所属期间与执行时间单独成列以兼容现有排程导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,82 +12,57 @@ from typing import Any
|
||||
|
||||
VOUCHER_CHECK_HEADER_ORDER = [
|
||||
"period",
|
||||
"scope_code",
|
||||
"executed_at",
|
||||
"invoice_no",
|
||||
"invoice_date",
|
||||
"result",
|
||||
"folder_exists",
|
||||
"folder_path",
|
||||
"matched_files",
|
||||
"missing_materials",
|
||||
"material_fingerprint",
|
||||
"checked_at",
|
||||
"error_code",
|
||||
"error_message",
|
||||
"po_order",
|
||||
"customs_pack",
|
||||
"sales_release",
|
||||
"tax_invoice",
|
||||
"customs_declaration",
|
||||
"bill_of_lading",
|
||||
"status",
|
||||
]
|
||||
|
||||
VOUCHER_CHECK_HEADER_LABELS = {
|
||||
"period": "检核月份",
|
||||
"scope_code": "账套",
|
||||
"invoice_no": "发票号",
|
||||
"invoice_date": "发票日期",
|
||||
"result": "结论",
|
||||
"folder_exists": "发票目录是否存在",
|
||||
"folder_path": "共享盘相对路径",
|
||||
"matched_files": "已找到材料",
|
||||
"missing_materials": "缺失材料",
|
||||
"material_fingerprint": "目录元数据指纹",
|
||||
"checked_at": "实际检核时间",
|
||||
"error_code": "技术错误码",
|
||||
"error_message": "技术错误摘要",
|
||||
"period": "资料所属期间",
|
||||
"executed_at": "执行时间",
|
||||
"invoice_no": "invoice",
|
||||
"po_order": "PO订单",
|
||||
"customs_pack": "报关资料",
|
||||
"sales_release": "销货放行申请单",
|
||||
"tax_invoice": "发票",
|
||||
"customs_declaration": "报关单",
|
||||
"bill_of_lading": "提单",
|
||||
"status": "状态",
|
||||
}
|
||||
|
||||
_RESULT_LABELS = {
|
||||
"complete": "齐全",
|
||||
"missing": "缺资料",
|
||||
"skipped": "跳过",
|
||||
"technical_error": "技术异常",
|
||||
}
|
||||
_RULE_COLUMNS = (
|
||||
"po_order",
|
||||
"customs_pack",
|
||||
"sales_release",
|
||||
"tax_invoice",
|
||||
"customs_declaration",
|
||||
"bill_of_lading",
|
||||
)
|
||||
|
||||
|
||||
def _fmt_matched(matched: dict[str, Any] | None) -> str:
|
||||
if not matched:
|
||||
return ""
|
||||
return "; ".join(f"{k}={v}" for k, v in matched.items())
|
||||
|
||||
|
||||
def _fmt_missing(missing: list[dict[str, Any]] | None) -> str:
|
||||
if not missing:
|
||||
return ""
|
||||
parts = []
|
||||
for item in missing:
|
||||
name = item.get("name") or item.get("code") or ""
|
||||
code = item.get("code") or ""
|
||||
parts.append(f"{name}({code})" if code and name != code else str(name or code))
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def to_excel_detail_row(item: dict[str, Any], *, period: str, scope_code: str) -> dict[str, Any]:
|
||||
def to_excel_invoice_row(
|
||||
item: dict[str, Any],
|
||||
*,
|
||||
period: str,
|
||||
executed_at: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将内存结果行转为 Excel details 行。
|
||||
将聚合后的 invoice 行转为排程 Excel details。
|
||||
核心逻辑:cells 按 rule_code 取值;缺列填未检核。
|
||||
"""
|
||||
result = str(item.get("result") or "")
|
||||
checked_at = item.get("checked_at")
|
||||
invoice_date = item.get("invoice_date")
|
||||
return {
|
||||
cells = item.get("cells") or {}
|
||||
row = {
|
||||
"period": period,
|
||||
"scope_code": scope_code,
|
||||
"executed_at": executed_at,
|
||||
"invoice_no": item.get("invoice_no"),
|
||||
"invoice_date": invoice_date.isoformat() if hasattr(invoice_date, "isoformat") else invoice_date,
|
||||
"result": _RESULT_LABELS.get(result, result),
|
||||
"folder_exists": "是" if item.get("folder_exists") else "否",
|
||||
"folder_path": item.get("folder_path") or "",
|
||||
"matched_files": _fmt_matched(item.get("matched_files")),
|
||||
"missing_materials": _fmt_missing(item.get("missing_materials")),
|
||||
"material_fingerprint": item.get("material_fingerprint") or "",
|
||||
"checked_at": checked_at.isoformat(sep=" ", timespec="seconds")
|
||||
if hasattr(checked_at, "isoformat")
|
||||
else (checked_at or ""),
|
||||
"error_code": item.get("error_code") or "",
|
||||
"error_message": item.get("error_message") or "",
|
||||
"status": item.get("status") or "",
|
||||
}
|
||||
for code in _RULE_COLUMNS:
|
||||
row[code] = cells.get(code) or "未检核"
|
||||
return row
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/filename_match.py
|
||||
|
||||
用途:按 Profile 命名模板匹配文档库文件名,并校验文件名中的 invoice。
|
||||
依赖:标准库 re。
|
||||
逻辑:{invoice} 替换为当前票号;其余 {token} 视为一段非路径字符;禁止路径穿越。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
_PLACEHOLDER_RE = re.compile(r"\{([^{}]+)\}")
|
||||
_UNSAFE_RE = re.compile(r"[/\\\x00]|(\.\.)")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FilenameMatch:
|
||||
"""单次文件名命中。"""
|
||||
|
||||
filename: str
|
||||
groups: dict[str, str]
|
||||
|
||||
|
||||
def compile_filename_pattern(template: str, *, invoice_no: str) -> re.Pattern[str]:
|
||||
"""
|
||||
把命名模板编译为整名匹配正则。
|
||||
核心逻辑:先替换 invoice,再把剩余占位符变成捕获组,字面量全部转义。
|
||||
|
||||
Args:
|
||||
template: 如 `{invoice}-{order_no}.pdf`。
|
||||
invoice_no: 当前发票号,禁止含路径字符。
|
||||
|
||||
Returns:
|
||||
锚定的正则。
|
||||
|
||||
Raises:
|
||||
ValueError: 模板或发票号非法。
|
||||
"""
|
||||
invoice = str(invoice_no or "").strip()
|
||||
if not invoice or _UNSAFE_RE.search(invoice):
|
||||
raise ValueError("invoice_no 非法")
|
||||
text = str(template or "").strip()
|
||||
if not text or _UNSAFE_RE.search(_PLACEHOLDER_RE.sub("", text)):
|
||||
raise ValueError("filename_template 非法")
|
||||
|
||||
parts: list[str] = []
|
||||
cursor = 0
|
||||
for match in _PLACEHOLDER_RE.finditer(text):
|
||||
parts.append(re.escape(text[cursor : match.start()]))
|
||||
name = match.group(1)
|
||||
if name in {"invoice", "invoice号"}:
|
||||
parts.append(re.escape(invoice))
|
||||
else:
|
||||
parts.append(rf"(?P<{re.escape(name)}>[^/\\]+)")
|
||||
cursor = match.end()
|
||||
parts.append(re.escape(text[cursor:]))
|
||||
return re.compile(r"^" + "".join(parts) + r"$")
|
||||
|
||||
|
||||
def match_filename(filename: str, *, template: str, invoice_no: str) -> FilenameMatch | None:
|
||||
"""
|
||||
判断文件名是否属于该 invoice 的规则。
|
||||
核心逻辑:整名匹配;命中后要求文件名包含 invoice 原文。
|
||||
"""
|
||||
name = str(filename or "").strip()
|
||||
if not name:
|
||||
return None
|
||||
try:
|
||||
pattern = compile_filename_pattern(template, invoice_no=invoice_no)
|
||||
except ValueError:
|
||||
return None
|
||||
matched = pattern.match(name)
|
||||
if not matched:
|
||||
return None
|
||||
invoice = str(invoice_no).strip()
|
||||
if invoice not in name:
|
||||
return None
|
||||
return FilenameMatch(filename=name, groups=matched.groupdict())
|
||||
|
||||
|
||||
def first_match(filenames: list[str], *, template: str, invoice_no: str) -> FilenameMatch | None:
|
||||
"""在文件名列表中返回第一条命中,保持目录返回顺序。"""
|
||||
for name in filenames:
|
||||
hit = match_filename(name, template=template, invoice_no=invoice_no)
|
||||
if hit is not None:
|
||||
return hit
|
||||
return None
|
||||
@@ -1,15 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notification.py
|
||||
|
||||
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
|
||||
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
|
||||
用途:立账凭证检核批次级企微汇总与技术失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -17,7 +17,7 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.voucher_check.persistence import mark_missing_notified
|
||||
from app.services.voucher_check.engine_persistence import persist_notification
|
||||
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
@@ -30,85 +30,115 @@ def _recipient_users(task: ScheduleTask) -> list[User]:
|
||||
return [u for u in users if u.wecom_userid]
|
||||
|
||||
|
||||
def _today_shanghai(now: datetime | None = None) -> date:
|
||||
base = now or datetime.now(_TZ)
|
||||
if base.tzinfo is None:
|
||||
base = base.replace(tzinfo=_TZ)
|
||||
else:
|
||||
base = base.astimezone(_TZ)
|
||||
return base.date()
|
||||
|
||||
|
||||
def send_missing_notifications(
|
||||
def send_batch_missing_summary(
|
||||
*,
|
||||
task: ScheduleTask,
|
||||
run: ScheduleRun,
|
||||
scope_code: str,
|
||||
period_month: date,
|
||||
missing_items: list[dict[str, Any]],
|
||||
same_day_dedup: bool,
|
||||
schedule_run: ScheduleRun,
|
||||
engine_run_id: int,
|
||||
profile_code: str,
|
||||
period_month: str,
|
||||
stats: dict[str, Any],
|
||||
excel_filename: str | None,
|
||||
enabled: bool,
|
||||
) -> int:
|
||||
) -> str:
|
||||
"""
|
||||
合并发送缺资料 textcard。
|
||||
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
|
||||
发送本批缺件汇总 textcard。
|
||||
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
|
||||
|
||||
Returns:
|
||||
本次实际通知的发票数。
|
||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||
"""
|
||||
if not enabled or not missing_items:
|
||||
return 0
|
||||
missing_files = int(stats.get("missing_file_count") or 0)
|
||||
missing_invoices = int(stats.get("missing_invoice_count") or 0)
|
||||
summary = {
|
||||
"profile_code": profile_code,
|
||||
"period": period_month,
|
||||
"subject_count": int(stats.get("subject_count") or 0),
|
||||
"missing_file_count": missing_files,
|
||||
"missing_invoice_count": missing_invoices,
|
||||
"run_no": schedule_run.run_no,
|
||||
}
|
||||
recipient_ids = [int(u.id) for u in _recipient_users(task)]
|
||||
|
||||
if not enabled:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
send_status="skipped_disabled",
|
||||
skip_reason="notify_missing_enabled=false",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_disabled"
|
||||
|
||||
if missing_files <= 0:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
send_status="skipped_no_missing",
|
||||
skip_reason="本批无缺件",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_no_missing"
|
||||
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
return 0
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
send_status="skipped_disabled",
|
||||
skip_reason="WECOM_NOTIFY_ENABLED=false",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_disabled"
|
||||
|
||||
users = _recipient_users(task)
|
||||
if not users:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=[],
|
||||
send_status="skipped_no_recipients",
|
||||
skip_reason="未配置企业微信接收人",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_no_recipients"
|
||||
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState
|
||||
from app.services.wecom_notify import (
|
||||
_build_jump_url,
|
||||
_create_audit,
|
||||
send_wecom_textcard_message,
|
||||
)
|
||||
|
||||
today = _today_shanghai()
|
||||
invoice_nos = [str(i["invoice_no"]).strip() for i in missing_items]
|
||||
states = (
|
||||
db.session.query(VoucherCheckInvoiceState)
|
||||
.filter(
|
||||
VoucherCheckInvoiceState.scope_code == scope_code,
|
||||
VoucherCheckInvoiceState.period_month == period_month,
|
||||
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
|
||||
)
|
||||
.all()
|
||||
type_stats = stats.get("by_file_type") or {}
|
||||
top_missing = sorted(
|
||||
(
|
||||
(item.get("rule_name") or key, int(item.get("missing_file_count") or 0))
|
||||
for key, item in type_stats.items()
|
||||
if isinstance(item, dict)
|
||||
),
|
||||
key=lambda pair: pair[1],
|
||||
reverse=True,
|
||||
)
|
||||
state_map = {s.invoice_no: s for s in states}
|
||||
to_notify: list[dict[str, Any]] = []
|
||||
for item in missing_items:
|
||||
inv = str(item["invoice_no"]).strip()
|
||||
state = state_map.get(inv)
|
||||
if same_day_dedup and state and state.last_missing_notified_on == today:
|
||||
continue
|
||||
to_notify.append(item)
|
||||
if not to_notify:
|
||||
return 0
|
||||
|
||||
users = _recipient_users(task)
|
||||
if not users:
|
||||
current_app.logger.warning(
|
||||
"[voucher-check] missing notify skipped: no wecom recipients run_id=%s",
|
||||
run.id,
|
||||
)
|
||||
return 0
|
||||
|
||||
sample = "、".join(i["invoice_no"] for i in to_notify[:8])
|
||||
if len(to_notify) > 8:
|
||||
sample += "…"
|
||||
period = period_month.strftime("%Y-%m")
|
||||
title = f"立账凭证缺资料: {task.name}"
|
||||
top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4]
|
||||
title = f"立账凭证缺件汇总: {task.name}"
|
||||
description = (
|
||||
f"批次 {run.run_no}\n"
|
||||
f"检核月份 {period}\n"
|
||||
f"缺资料 {len(to_notify)} 张\n"
|
||||
f"示例:{sample}\n"
|
||||
f"完整清单请查看工作台检核记录或 Excel。"
|
||||
f"业务方 {profile_code}\n"
|
||||
f"资料所属期间 {period_month}\n"
|
||||
f"批次 {schedule_run.run_no}\n"
|
||||
f"主体 {int(stats.get('subject_count') or 0)} 张\n"
|
||||
f"缺件文件 {missing_files} / 缺件 invoice {missing_invoices}\n"
|
||||
f"主要缺失:{'、'.join(top_missing) or '—'}\n"
|
||||
f"明细以工作台 Excel 为准。"
|
||||
)
|
||||
ok_any = False
|
||||
for user in users:
|
||||
@@ -116,7 +146,7 @@ def send_missing_notifications(
|
||||
jump_url = _build_jump_url(
|
||||
"/workspace/accounting-voucher-check",
|
||||
trace_id,
|
||||
{"task_id": task.id, "run_id": run.id},
|
||||
{"task_id": task.id, "run_id": schedule_run.id},
|
||||
)
|
||||
try:
|
||||
audit = _create_audit("voucher_check_missing", user, title, description, trace_id)
|
||||
@@ -130,20 +160,22 @@ def send_missing_notifications(
|
||||
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
"[voucher-check] missing notify failed user=%s err=%s",
|
||||
"[voucher-check] batch notify failed user=%s err=%s",
|
||||
user.id,
|
||||
exc,
|
||||
)
|
||||
if ok_any:
|
||||
mark_missing_notified(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_nos=[str(i["invoice_no"]).strip() for i in to_notify],
|
||||
notified_on=today,
|
||||
)
|
||||
db.session.commit()
|
||||
return len(to_notify)
|
||||
return 0
|
||||
status = "sent" if ok_any else "failed"
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
send_status=status,
|
||||
skip_reason=None if ok_any else "企业微信发送失败",
|
||||
summary=summary,
|
||||
sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None,
|
||||
)
|
||||
db.session.commit()
|
||||
return status
|
||||
|
||||
|
||||
def send_failure_alert(
|
||||
@@ -155,7 +187,7 @@ def send_failure_alert(
|
||||
error_message: str,
|
||||
enabled: bool,
|
||||
) -> None:
|
||||
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
|
||||
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
|
||||
if not enabled:
|
||||
return
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
@@ -178,7 +210,7 @@ def send_failure_alert(
|
||||
f"错误码:{error_code}\n"
|
||||
f"摘要:{(error_message or '')[:200]}\n"
|
||||
f"run_id={run.id}\n"
|
||||
f"请检查 Oracle 连接与共享盘挂载/健康标记。"
|
||||
f"请检查 Oracle 与文档库连接。"
|
||||
)
|
||||
for user in users:
|
||||
trace_id = uuid.uuid4().hex
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/profile_loader.py
|
||||
|
||||
用途:加载销售 Profile 并确保数据库中有对应已发布快照。
|
||||
依赖:profiles 目录、models.VoucherCheckProfile。
|
||||
逻辑:批次绑定 definition_json 快照;运行中不以表热更新覆盖已开始的批次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.voucher_check import VoucherCheckProfile
|
||||
from app.services.voucher_check.profiles import PROFILE_CATALOG
|
||||
|
||||
|
||||
def load_profile_definition(profile_code: str = "sales") -> dict[str, Any]:
|
||||
"""
|
||||
读取内置 Profile 定义的深拷贝。
|
||||
核心逻辑:未知 profile_code 在批次开始前失败。
|
||||
"""
|
||||
code = str(profile_code or "sales").strip() or "sales"
|
||||
definition = PROFILE_CATALOG.get(code)
|
||||
if not definition:
|
||||
raise ValidationError(
|
||||
f"未知 Profile: {code}",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"profile_code": code},
|
||||
)
|
||||
snapshot = copy.deepcopy(definition)
|
||||
if not snapshot.get("file_rules"):
|
||||
raise ValidationError("Profile 缺少 file_rules", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return snapshot
|
||||
|
||||
|
||||
def ensure_published_profile(profile_code: str = "sales") -> VoucherCheckProfile:
|
||||
"""
|
||||
幂等写入已发布 Profile 行,供审计;批次仍使用内存快照。
|
||||
"""
|
||||
snapshot = load_profile_definition(profile_code)
|
||||
code = str(snapshot["profile_code"])
|
||||
version = str(snapshot["profile_version"])
|
||||
row = (
|
||||
db.session.query(VoucherCheckProfile)
|
||||
.filter_by(profile_code=code, version=version)
|
||||
.one_or_none()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if row is None:
|
||||
row = VoucherCheckProfile(
|
||||
profile_code=code,
|
||||
version=version,
|
||||
definition_json=snapshot,
|
||||
status="published",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
if row.status != "published" or row.definition_json != snapshot:
|
||||
row.definition_json = snapshot
|
||||
row.status = "published"
|
||||
row.updated_at = now
|
||||
db.session.flush()
|
||||
return row
|
||||
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/profiles/__init__.py
|
||||
|
||||
用途:业务方 Profile 包入口。
|
||||
依赖:sales 销售一期定义。
|
||||
逻辑:profile_loader 按 profile_code 加载;新增业务方在此登记。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE, SALES_PROFILE_CODE, SALES_PROFILE_VERSION
|
||||
|
||||
PROFILE_CATALOG = {
|
||||
SALES_PROFILE_CODE: SALES_PROFILE,
|
||||
}
|
||||
|
||||
__all__ = ["PROFILE_CATALOG", "SALES_PROFILE", "SALES_PROFILE_CODE", "SALES_PROFILE_VERSION"]
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/profiles/sales.py
|
||||
|
||||
用途:销售一期 Profile 定义(六类必检文件、类型目录、命名模板)。
|
||||
依赖:无外部 IO;由 profile_loader 发布快照。
|
||||
逻辑:周任务扫描 source_type=directory_scan;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
SALES_PROFILE_CODE = "sales"
|
||||
SALES_PROFILE_VERSION = "v1"
|
||||
|
||||
SALES_PROFILE: dict[str, Any] = {
|
||||
"profile_code": SALES_PROFILE_CODE,
|
||||
"profile_version": SALES_PROFILE_VERSION,
|
||||
"scope_code": "HXJM",
|
||||
"subject_adapter": "hxjm_apa",
|
||||
"dms": {
|
||||
"year_folder_template": "{yyyy}",
|
||||
"month_folder_template": "{MM}",
|
||||
"archive_folder": "所有归档",
|
||||
},
|
||||
"file_rules": [
|
||||
{
|
||||
"code": "po_order",
|
||||
"name": "PO订单",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": "erp_po_print",
|
||||
"type_folder": "PO订单",
|
||||
"filename_template": "{invoice}-{order_no}.pdf",
|
||||
},
|
||||
{
|
||||
"code": "customs_pack",
|
||||
"name": "报关资料",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": None,
|
||||
"type_folder": "报关资料",
|
||||
"filename_template": "{invoice}.pdf",
|
||||
},
|
||||
{
|
||||
"code": "sales_release",
|
||||
"name": "销货放行申请单",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": "oa_sales_release",
|
||||
"type_folder": "销货单",
|
||||
"filename_template": "{invoice}-{delivery_no}.pdf",
|
||||
},
|
||||
{
|
||||
"code": "tax_invoice",
|
||||
"name": "发票",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": None,
|
||||
"type_folder": "发票",
|
||||
"filename_template": "{invoice}-{tax_invoice_no}.pdf",
|
||||
},
|
||||
{
|
||||
"code": "customs_declaration",
|
||||
"name": "报关单",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": None,
|
||||
"type_folder": "报关单",
|
||||
"filename_template": "{invoice}-{customs_no}.pdf",
|
||||
},
|
||||
{
|
||||
"code": "bill_of_lading",
|
||||
"name": "提单",
|
||||
"required": True,
|
||||
"source_type": "directory_scan",
|
||||
"acquire_adapter": None,
|
||||
"type_folder": "提单",
|
||||
"filename_template": "{invoice}-提单.pdf",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def required_file_rules(definition: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回必检文件规则列表。
|
||||
核心逻辑:过滤 required=true,保持 Profile 声明顺序供 Excel 动态列使用。
|
||||
"""
|
||||
payload = definition or SALES_PROFILE
|
||||
rules = payload.get("file_rules") or []
|
||||
return [rule for rule in rules if isinstance(rule, dict) and rule.get("required", True)]
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/query_service.py
|
||||
|
||||
用途:查询批次明细、当月缺资料与单票最新状态。
|
||||
依赖:models.voucher_check、ScheduleRun。
|
||||
逻辑:Tool API 与工作台 API 调用;不触发扫描。
|
||||
用途:查询检核批次列表、批次明细、兼容旧状态表,以及工作台强制重检入队。
|
||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
|
||||
逻辑:优先读新引擎表;无引擎批次时回退旧 run_items / invoice_states;强制重检写入 run_options.mode=force_all。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,10 +11,16 @@ from __future__ import annotations
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
from app.services.voucher_check.erp_repository import current_period_bounds
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckInvoiceState,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckRunItem,
|
||||
)
|
||||
from app.services.voucher_check.aggregator import aggregate_file_results
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
|
||||
|
||||
def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]:
|
||||
@@ -63,9 +69,9 @@ def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]:
|
||||
|
||||
|
||||
def parse_period_month(raw: str | None) -> date:
|
||||
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。"""
|
||||
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。"""
|
||||
if not raw:
|
||||
period_month, *_ = current_period_bounds()
|
||||
period_month, *_ = previous_period_bounds()
|
||||
return period_month
|
||||
text = str(raw).strip()
|
||||
try:
|
||||
@@ -113,6 +119,111 @@ def list_missing_states(
|
||||
}
|
||||
|
||||
|
||||
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 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]:
|
||||
"""工作台任务列表:按执行时间倒序返回引擎批次快照。"""
|
||||
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())
|
||||
total = q.count()
|
||||
rows = (
|
||||
q.order_by(VoucherCheckRun.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total": total,
|
||||
"items": [_serialize_engine_run(row) for row in rows],
|
||||
}
|
||||
|
||||
|
||||
def _engine_invoice_items(engine_run: VoucherCheckRun, *, result: str | None = None) -> list[dict[str, Any]]:
|
||||
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")
|
||||
if result and mapped_status != result:
|
||||
continue
|
||||
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,
|
||||
"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
|
||||
|
||||
|
||||
def list_run_items(
|
||||
*,
|
||||
run_id: int,
|
||||
@@ -120,12 +231,30 @@ def list_run_items(
|
||||
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 not None:
|
||||
items = _engine_invoice_items(engine_run, result=str(result).strip() if result else None)
|
||||
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,
|
||||
}
|
||||
q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id)
|
||||
if result:
|
||||
q = q.filter(VoucherCheckRunItem.result == str(result).strip())
|
||||
@@ -218,3 +347,41 @@ def list_states(
|
||||
"total": total,
|
||||
"items": [_serialize_state(r) for r in rows],
|
||||
}
|
||||
|
||||
|
||||
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.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",
|
||||
)
|
||||
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,
|
||||
}
|
||||
@@ -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,8 @@ def _update_progress(
|
||||
|
||||
def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证检核批次。
|
||||
核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。
|
||||
执行立账凭证周批次。
|
||||
核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。
|
||||
|
||||
Returns:
|
||||
ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs)
|
||||
@@ -87,9 +94,13 @@ 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()
|
||||
|
||||
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 +112,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 +135,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 +145,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 +355,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,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。
|
||||
用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批默认任务会改成周二。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,8 +24,8 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
|
||||
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check"
|
||||
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * *"
|
||||
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(日批)"
|
||||
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * 2"
|
||||
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(周批)"
|
||||
|
||||
_HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
|
||||
@@ -56,6 +56,17 @@ def ensure_default_voucher_check_schedule(
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.cron_expr == "0 6 * * *":
|
||||
existing.cron_expr = DEFAULT_VOUCHER_CHECK_CRON
|
||||
if existing.name == "立账凭证检核(日批)":
|
||||
existing.name = DEFAULT_VOUCHER_CHECK_NAME
|
||||
existing.next_run_at = compute_next_run_at(
|
||||
DEFAULT_VOUCHER_CHECK_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or existing.next_run_at
|
||||
existing.updated_at = datetime.utcnow()
|
||||
if commit:
|
||||
sess.commit()
|
||||
return existing
|
||||
|
||||
owner = (
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py
|
||||
|
||||
用途:新增立账凭证检核引擎表(Profile/批次/主体/单文件结果/通知),并把默认排程改为每周二。
|
||||
依赖:Alembic revision n8f9a0b1c2d3;旧 voucher_check_invoice_states / run_items 保留只读。
|
||||
逻辑:建五张新表;仅当默认任务仍是日批 cron 时改为周二 06:00。
|
||||
|
||||
Revision ID: vc1a2b3c4d5e
|
||||
Revises: n8f9a0b1c2d3
|
||||
Create Date: 2026-09-04 10:30:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "vc1a2b3c4d5e"
|
||||
down_revision = "n8f9a0b1c2d3"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
|
||||
_OLD_CRON = "0 6 * * *"
|
||||
_NEW_CRON = "0 6 * * 2"
|
||||
_TZ_NAME = "Asia/Shanghai"
|
||||
|
||||
|
||||
def _compute_next_run_at_utc_naive() -> datetime:
|
||||
try:
|
||||
from croniter import croniter
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
tz = ZoneInfo(_TZ_NAME)
|
||||
base = datetime.now(tz)
|
||||
next_local = croniter(_NEW_CRON, base).get_next(datetime)
|
||||
if next_local.tzinfo is None:
|
||||
next_local = next_local.replace(tzinfo=tz)
|
||||
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
except Exception:
|
||||
tz = timezone(timedelta(hours=8))
|
||||
now_local = datetime.now(tz)
|
||||
next_local = now_local.replace(hour=6, minute=0, second=0, microsecond=0)
|
||||
while next_local <= now_local or next_local.weekday() != 1:
|
||||
next_local = next_local + timedelta(days=1)
|
||||
next_local = next_local.replace(hour=6, minute=0, second=0, microsecond=0)
|
||||
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"voucher_check_profiles",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column("profile_code", sa.String(length=32), nullable=False),
|
||||
sa.Column("version", sa.String(length=32), nullable=False),
|
||||
sa.Column("definition_json", sa.JSON(), nullable=False),
|
||||
sa.Column("status", sa.String(length=24), nullable=False, server_default="published"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"),
|
||||
)
|
||||
op.create_index("ix_voucher_check_profiles_status", "voucher_check_profiles", ["status"])
|
||||
|
||||
op.create_table(
|
||||
"voucher_check_runs",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column(
|
||||
"schedule_run_id",
|
||||
sa.BigInteger(),
|
||||
sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("run_no", sa.String(length=64), nullable=False),
|
||||
sa.Column("profile_code", sa.String(length=32), nullable=False),
|
||||
sa.Column("profile_version", sa.String(length=32), nullable=False),
|
||||
sa.Column("profile_snapshot_json", sa.JSON(), nullable=False),
|
||||
sa.Column("period_month", sa.Date(), nullable=False),
|
||||
sa.Column("mode", sa.String(length=24), nullable=False, server_default="incremental"),
|
||||
sa.Column("status", sa.String(length=24), nullable=False, server_default="running"),
|
||||
sa.Column("subject_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("archived_file_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("skipped_file_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("missing_file_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("missing_invoice_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("technical_error_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("staged_file_count", sa.BigInteger(), nullable=False, server_default="0"),
|
||||
sa.Column("stats_json", sa.JSON(), nullable=True),
|
||||
sa.Column("started_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("finished_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
)
|
||||
op.create_index("ix_voucher_check_runs_schedule_run_id", "voucher_check_runs", ["schedule_run_id"])
|
||||
op.create_index(
|
||||
"ix_voucher_check_runs_period_profile",
|
||||
"voucher_check_runs",
|
||||
["period_month", "profile_code"],
|
||||
)
|
||||
op.create_index("ix_voucher_check_runs_status", "voucher_check_runs", ["status"])
|
||||
op.create_index("ix_voucher_check_runs_finished_at", "voucher_check_runs", ["finished_at"])
|
||||
|
||||
op.create_table(
|
||||
"voucher_check_subjects",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column(
|
||||
"run_id",
|
||||
sa.BigInteger(),
|
||||
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("invoice_no", sa.String(length=128), nullable=False),
|
||||
sa.Column("invoice_date", sa.Date(), nullable=True),
|
||||
sa.Column("source_fingerprint", sa.String(length=64), nullable=True),
|
||||
sa.Column("attributes_json", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"),
|
||||
)
|
||||
op.create_index("ix_voucher_check_subjects_run_id", "voucher_check_subjects", ["run_id"])
|
||||
op.create_index("ix_voucher_check_subjects_invoice_no", "voucher_check_subjects", ["invoice_no"])
|
||||
|
||||
op.create_table(
|
||||
"voucher_check_file_results",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column(
|
||||
"run_id",
|
||||
sa.BigInteger(),
|
||||
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"subject_id",
|
||||
sa.BigInteger(),
|
||||
sa.ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("invoice_no", sa.String(length=128), nullable=False),
|
||||
sa.Column("rule_code", sa.String(length=64), nullable=False),
|
||||
sa.Column("rule_name", sa.String(length=128), nullable=False),
|
||||
sa.Column("source_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("expected_name", sa.String(length=512), nullable=True),
|
||||
sa.Column("matched_name", sa.String(length=512), nullable=True),
|
||||
sa.Column("source_folder_id", sa.String(length=64), nullable=True),
|
||||
sa.Column("source_item_id", sa.String(length=64), nullable=True),
|
||||
sa.Column("archive_folder_id", sa.String(length=64), nullable=True),
|
||||
sa.Column("archive_item_id", sa.String(length=64), nullable=True),
|
||||
sa.Column("source_path", sa.String(length=1024), nullable=True),
|
||||
sa.Column("archive_path", sa.String(length=1024), nullable=True),
|
||||
sa.Column("status", sa.String(length=24), nullable=False),
|
||||
sa.Column("missing_reason", sa.String(length=255), nullable=True),
|
||||
sa.Column("error_code", sa.String(length=64), nullable=True),
|
||||
sa.Column("error_message", sa.Text(), nullable=True),
|
||||
sa.Column("source_fingerprint", sa.String(length=64), nullable=True),
|
||||
sa.Column("checked_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
"run_id",
|
||||
"invoice_no",
|
||||
"rule_code",
|
||||
name="uq_voucher_check_file_results_run_invoice_rule",
|
||||
),
|
||||
)
|
||||
op.create_index("ix_voucher_check_file_results_run_id", "voucher_check_file_results", ["run_id"])
|
||||
op.create_index(
|
||||
"ix_voucher_check_file_results_status",
|
||||
"voucher_check_file_results",
|
||||
["run_id", "status"],
|
||||
)
|
||||
op.create_index("ix_voucher_check_file_results_invoice", "voucher_check_file_results", ["invoice_no"])
|
||||
|
||||
op.create_table(
|
||||
"voucher_check_notifications",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
|
||||
sa.Column(
|
||||
"run_id",
|
||||
sa.BigInteger(),
|
||||
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("excel_filename", sa.String(length=255), nullable=True),
|
||||
sa.Column("recipient_user_ids_json", sa.JSON(), nullable=True),
|
||||
sa.Column("send_status", sa.String(length=32), nullable=False),
|
||||
sa.Column("skip_reason", sa.String(length=255), nullable=True),
|
||||
sa.Column("summary_json", sa.JSON(), nullable=True),
|
||||
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("run_id", name="uq_voucher_check_notifications_run_id"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_voucher_check_notifications_status",
|
||||
"voucher_check_notifications",
|
||||
["send_status"],
|
||||
)
|
||||
|
||||
conn = op.get_bind()
|
||||
conn.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE schedule_tasks
|
||||
SET cron_expr = :new_cron,
|
||||
name = CASE
|
||||
WHEN name = '立账凭证检核(日批)' THEN '立账凭证检核(周批)'
|
||||
ELSE name
|
||||
END,
|
||||
next_run_at = :next_run,
|
||||
updated_at = :now
|
||||
WHERE schedule_no = :sno
|
||||
AND cron_expr = :old_cron
|
||||
"""
|
||||
),
|
||||
{
|
||||
"new_cron": _NEW_CRON,
|
||||
"next_run": _compute_next_run_at_utc_naive(),
|
||||
"now": datetime.utcnow(),
|
||||
"sno": _SCHEDULE_NO,
|
||||
"old_cron": _OLD_CRON,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_voucher_check_notifications_status", table_name="voucher_check_notifications")
|
||||
op.drop_table("voucher_check_notifications")
|
||||
op.drop_index("ix_voucher_check_file_results_invoice", table_name="voucher_check_file_results")
|
||||
op.drop_index("ix_voucher_check_file_results_status", table_name="voucher_check_file_results")
|
||||
op.drop_index("ix_voucher_check_file_results_run_id", table_name="voucher_check_file_results")
|
||||
op.drop_table("voucher_check_file_results")
|
||||
op.drop_index("ix_voucher_check_subjects_invoice_no", table_name="voucher_check_subjects")
|
||||
op.drop_index("ix_voucher_check_subjects_run_id", table_name="voucher_check_subjects")
|
||||
op.drop_table("voucher_check_subjects")
|
||||
op.drop_index("ix_voucher_check_runs_finished_at", table_name="voucher_check_runs")
|
||||
op.drop_index("ix_voucher_check_runs_status", table_name="voucher_check_runs")
|
||||
op.drop_index("ix_voucher_check_runs_period_profile", table_name="voucher_check_runs")
|
||||
op.drop_index("ix_voucher_check_runs_schedule_run_id", table_name="voucher_check_runs")
|
||||
op.drop_table("voucher_check_runs")
|
||||
op.drop_index("ix_voucher_check_profiles_status", table_name="voucher_check_profiles")
|
||||
op.drop_table("voucher_check_profiles")
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/tests/test_faq_cache.py
|
||||
|
||||
用途:FAQ 缓存在线匹配规则。
|
||||
逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import Agent, QuickQuestion
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
|
||||
|
||||
def _create_agent() -> Agent:
|
||||
"""写入测试 Agent,供 FAQ 条目关联。"""
|
||||
agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache')
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
return agent
|
||||
|
||||
|
||||
def _create_faq(agent_id: int, **overrides) -> QuickQuestion:
|
||||
"""写入一条全局 FAQ,默认启用缓存且有标准答案。"""
|
||||
payload = {
|
||||
'user_id': None,
|
||||
'agent_id': agent_id,
|
||||
'title': '公司的企业文化',
|
||||
'question': '公司的企业文化',
|
||||
'answer': '客户满意、员工乐意、经营得意',
|
||||
'aliases': ['企业文化'],
|
||||
'cache_enabled': True,
|
||||
'is_enabled': True,
|
||||
}
|
||||
payload.update(overrides)
|
||||
faq = QuickQuestion(**payload)
|
||||
db.session.add(faq)
|
||||
db.session.commit()
|
||||
return faq
|
||||
|
||||
|
||||
def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app):
|
||||
"""关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。"""
|
||||
with app.app_context():
|
||||
agent = _create_agent()
|
||||
_create_faq(agent.id, is_enabled=False)
|
||||
|
||||
hit = FaqCacheService.try_match('公司的企业文化', agent.id)
|
||||
alias_hit = FaqCacheService.try_match('企业文化', agent.id)
|
||||
|
||||
assert hit is not None
|
||||
assert hit.answer == '客户满意、员工乐意、经营得意'
|
||||
assert alias_hit is not None
|
||||
assert alias_hit.id == hit.id
|
||||
|
||||
|
||||
def test_try_match_skips_when_cache_disabled(app):
|
||||
"""仅在首页展示、未启用缓存时,提问仍应回退 Dify。"""
|
||||
with app.app_context():
|
||||
agent = _create_agent()
|
||||
_create_faq(agent.id, cache_enabled=False, is_enabled=True)
|
||||
|
||||
assert FaqCacheService.try_match('公司的企业文化', agent.id) is None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_dms_archive.py
|
||||
|
||||
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
||||
依赖:pytest;不连文档库。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
|
||||
from app.services.voucher_check.dms_client import (
|
||||
SalesDmsClient,
|
||||
_extract_item_id,
|
||||
_is_name_conflict,
|
||||
)
|
||||
|
||||
|
||||
def test_extract_item_id_from_nested_data():
|
||||
assert _extract_item_id({"Data": {"ID": "folder-1"}}) == "folder-1"
|
||||
assert _extract_item_id({"Data": "folder-2"}) == "folder-2"
|
||||
assert _extract_item_id({"Data": {"Item": {"ID": "folder-3"}}}) == "folder-3"
|
||||
assert _extract_item_id({"Data": {}}) == ""
|
||||
|
||||
|
||||
def test_name_conflict_detects_same_name_messages():
|
||||
assert _is_name_conflict("文件夹已存在")
|
||||
assert _is_name_conflict("同名文件")
|
||||
assert _is_name_conflict("The name already exists")
|
||||
assert _is_name_conflict("网络超时") is False
|
||||
|
||||
|
||||
def test_ensure_folder_returns_existing_without_save(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: "folder-1")
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", lambda *_args, **_kwargs: calls.append(1) or {})
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "folder-1"
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_ensure_folder_creates_when_missing(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"_post_json",
|
||||
lambda path, payload, **_kwargs: {"Code": 0, "Data": {"ID": "new-folder"}},
|
||||
)
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
||||
|
||||
|
||||
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"find_child_file",
|
||||
lambda **_kwargs: {"ID": "dest-1", "LeafName": "INV001.pdf"},
|
||||
)
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "dest-1"
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_copy_when_dest_has_no_same_name(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
copied: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "dest-2"
|
||||
assert copied == [{"item_ids": ["src-1"], "dest_folder_id": "inv-folder"}]
|
||||
|
||||
|
||||
def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_items",
|
||||
lambda **_kwargs: (_ for _ in ()).throw(
|
||||
ServiceUnavailableError("目标已存在同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED")
|
||||
),
|
||||
)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "dest-3"
|
||||
|
||||
|
||||
def test_archive_adapter_is_wired_and_skips_same_name(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_month_archive_root", lambda **_kwargs: "archive-root")
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_folder", lambda **_kwargs: "inv-folder")
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_file_skip_same_name",
|
||||
lambda **_kwargs: ({"ID": "dest-9", "LeafName": "INV001-PO9.pdf"}, True),
|
||||
)
|
||||
adapter = DmsArchiveAdapter()
|
||||
assert adapter.wired is True
|
||||
archived = adapter.archive(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
file=ScannedFile(filename="INV001-PO9.pdf", item_id="src-9", fingerprint="fp1"),
|
||||
rule={"code": "po_order"},
|
||||
)
|
||||
assert archived.item_id == "dest-9"
|
||||
assert archived.folder_id == "inv-folder"
|
||||
assert archived.extra["skipped_same_name"] is True
|
||||
assert archived.path == "销售开票附件/2026/08/所有归档/INV001/INV001-PO9.pdf"
|
||||
|
||||
|
||||
def test_archive_adapter_missing_source_id_is_technical():
|
||||
adapter = DmsArchiveAdapter()
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
adapter.archive(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
file=ScannedFile(filename="INV001.pdf"),
|
||||
rule={"code": "tax_invoice"},
|
||||
)
|
||||
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
|
||||
|
||||
|
||||
def test_month_archive_root_missing_month_is_technical(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "resolve_period_folder", lambda **_kwargs: (None, None))
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
SalesDmsClient.ensure_month_archive_root(period_month=date(2026, 8, 1))
|
||||
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
|
||||
|
||||
|
||||
def test_page_walks_until_short_batch(monkeypatch):
|
||||
"""「所有归档」超过一页时必须翻页,否则同名跳过会漏检已有发票目录。"""
|
||||
calls = {"n": 0}
|
||||
|
||||
def post(_path, payload, **_kwargs):
|
||||
calls["n"] += 1
|
||||
index = payload["Page"]["Index"]
|
||||
if index == 1:
|
||||
return {
|
||||
"Code": 0,
|
||||
"Data": {"Items": [{"ID": "a", "IsFolder": True, "LeafName": "x"}] * 200, "Total": 201},
|
||||
}
|
||||
return {
|
||||
"Code": 0,
|
||||
"Data": {"Items": [{"ID": "b", "IsFolder": True, "LeafName": "y"}], "Total": 201},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
|
||||
rows = SalesDmsClient.page(parent_folder_id="archive-root")
|
||||
assert len(rows) == 201
|
||||
assert calls["n"] == 2
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_engine_profile_and_scan.py
|
||||
|
||||
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
|
||||
依赖:pytest;不连 Oracle / 文档库。
|
||||
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
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.filename_match import first_match, match_filename
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
|
||||
|
||||
|
||||
def test_previous_period_bounds_from_early_september():
|
||||
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
|
||||
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, current_month, period_start, next_start = previous_period_bounds(now)
|
||||
assert period_month.isoformat() == "2026-08-01"
|
||||
assert current_month.isoformat() == "2026-09-01"
|
||||
assert period_start.isoformat().startswith("2026-08-01T00:00:00")
|
||||
assert next_start.isoformat().startswith("2026-09-01T00:00:00")
|
||||
|
||||
|
||||
def test_previous_period_bounds_january_cross_year():
|
||||
now = datetime(2026, 1, 6, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, current_month, _, _ = previous_period_bounds(now)
|
||||
assert period_month.isoformat() == "2025-12-01"
|
||||
assert current_month.isoformat() == "2026-01-01"
|
||||
|
||||
|
||||
def test_filename_templates_match_sales_rules():
|
||||
assert match_filename("INV001-PO9.pdf", template="{invoice}-{order_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001.pdf", template="{invoice}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-DN8.pdf", template="{invoice}-{delivery_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-TAX1.pdf", template="{invoice}-{tax_invoice_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-CD2.pdf", template="{invoice}-{customs_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-提单.pdf", template="{invoice}-提单.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV002.pdf", template="{invoice}.pdf", invoice_no="INV001") is None
|
||||
assert first_match(["other.pdf", "INV001-提单.pdf"], template="{invoice}-提单.pdf", invoice_no="INV001")
|
||||
|
||||
|
||||
def test_aggregator_dual_missing_metrics():
|
||||
"""同一 invoice 缺两类文件:缺件文件=2,缺件 invoice=1。"""
|
||||
rules = required_file_rules(SALES_PROFILE)
|
||||
results = [
|
||||
{"invoice_no": "A", "rule_code": "po_order", "status": "missing"},
|
||||
{"invoice_no": "A", "rule_code": "customs_pack", "status": "missing"},
|
||||
{"invoice_no": "A", "rule_code": "sales_release", "status": "staged"},
|
||||
{"invoice_no": "A", "rule_code": "tax_invoice", "status": "archived"},
|
||||
{"invoice_no": "A", "rule_code": "customs_declaration", "status": "archived"},
|
||||
{"invoice_no": "A", "rule_code": "bill_of_lading", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "po_order", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "customs_pack", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "sales_release", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "tax_invoice", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "customs_declaration", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "bill_of_lading", "status": "archived"},
|
||||
]
|
||||
stats = aggregate_file_results(results, rules=rules)
|
||||
assert stats["missing_file_count"] == 2
|
||||
assert stats["missing_invoice_count"] == 1
|
||||
by_invoice = {row["invoice_no"]: row for row in stats["excel_rows"]}
|
||||
assert by_invoice["A"]["status"] == "缺件"
|
||||
assert by_invoice["B"]["status"] == "完整"
|
||||
assert by_invoice["A"]["cells"]["po_order"] == "缺件"
|
||||
assert by_invoice["A"]["cells"]["sales_release"] == "未检核"
|
||||
assert by_invoice["B"]["cells"]["po_order"] == "有"
|
||||
|
||||
|
||||
def test_po_and_oa_adapters_are_placeholders():
|
||||
with pytest.raises(ServiceUnavailableError) as po_exc:
|
||||
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert po_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
with pytest.raises(ServiceUnavailableError) as oa_exc:
|
||||
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert oa_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
assert ErpPoPrintAdapter.wired is False
|
||||
assert OaSalesReleaseAdapter.wired is False
|
||||
|
||||
|
||||
def test_directory_scan_matches_cached_listing(monkeypatch):
|
||||
adapter = DmsDirectoryScanAdapter()
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.resolve_period_folder",
|
||||
lambda **kwargs: ("year-id", "month-id"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.find_child_folder",
|
||||
lambda **kwargs: "type-id",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.list_files",
|
||||
lambda **kwargs: [
|
||||
{"LeafName": "INV001-PO9.pdf", "ID": "item-1", "IsFolder": False, "Path": "销售开票附件/2026/08/PO订单/INV001-PO9.pdf", "VersionID": "v1"},
|
||||
{"LeafName": "OTHER.pdf", "ID": "item-2", "IsFolder": False},
|
||||
],
|
||||
)
|
||||
hit = adapter.scan(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
|
||||
)
|
||||
assert hit.status == "matched"
|
||||
assert hit.file is not None
|
||||
assert hit.file.filename == "INV001-PO9.pdf"
|
||||
|
||||
missed = adapter.scan(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV999",
|
||||
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
|
||||
)
|
||||
assert missed.status == "missing"
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_force_recheck.py
|
||||
|
||||
用途:工作台强制重检入队(force_all)与并发冲突。
|
||||
依赖:pytest、Flask client;不执行真实周任务。
|
||||
逻辑:POST /api/workspace/accounting-voucher-check/runs 写入 run_options.mode=force_all;已有 queued 时 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
|
||||
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
|
||||
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 test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers):
|
||||
"""工作台按钮入队后,ScheduleRun 必须带 force_all,供 runner 跳过增量。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
assert task.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO
|
||||
assert task.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
|
||||
|
||||
first = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert first.status_code == 200
|
||||
data = parse_api_data(first.get_json())
|
||||
assert data["mode"] == "force_all"
|
||||
assert data["status"] == "queued"
|
||||
assert data["run_no"]
|
||||
|
||||
with app.app_context():
|
||||
run = db.session.get(ScheduleRun, data["schedule_run_id"])
|
||||
assert run is not None
|
||||
options = (run.api_request_json or {}).get("run_options") or {}
|
||||
assert options.get("mode") == "force_all"
|
||||
|
||||
second = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert second.status_code == 409
|
||||
error = parse_api_error(second.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.RUN_IN_PROGRESS"
|
||||
|
||||
|
||||
def test_workspace_force_recheck_rejects_non_admin_and_invalid_mode(app, client, admin_headers, user_headers):
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_ensure_user(username="user", role="user")
|
||||
ensure_default_voucher_check_schedule(commit=True)
|
||||
|
||||
forbidden = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=user_headers,
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
invalid = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "incremental"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
error = parse_api_error(invalid.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
Reference in new issue
Block a user