From 63b997a7e401bb3b24ecc09d107be2e6919794f3 Mon Sep 17 00:00:00 2001 From: sophie Date: Mon, 7 Sep 2026 11:13:33 +0800 Subject: [PATCH 1/3] 1 --- .env.shared | 3 + backend/app/api/workspace/voucher_check.py | 50 +- backend/app/core/config/settings.py | 7 +- backend/app/models/__init__.py | 15 +- backend/app/models/content.py | 1 + backend/app/models/voucher_check.py | 157 +++++- backend/app/services/faq_cache.py | 4 +- .../app/services/schedule/queue_service.py | 11 + .../services/schedule/voucher_check_job.py | 2 +- .../voucher_check/adapters/__init__.py | 47 ++ .../services/voucher_check/adapters/base.py | 113 ++++ .../voucher_check/adapters/dms_archive.py | 81 +++ .../adapters/dms_directory_scan.py | 110 ++++ .../voucher_check/adapters/erp_po_print.py | 36 ++ .../adapters/hxjm_apa_subject.py | 61 +++ .../adapters/oa_sales_release.py | 36 ++ .../voucher_check/adapters/registry.py | 44 ++ .../app/services/voucher_check/aggregator.py | 114 ++++ backend/app/services/voucher_check/config.py | 100 +++- .../app/services/voucher_check/dms_client.py | 388 ++++++++++++++ .../voucher_check/engine_persistence.py | 182 +++++++ .../services/voucher_check/erp_repository.py | 27 +- .../app/services/voucher_check/excel_rows.py | 113 ++-- .../services/voucher_check/filename_match.py | 89 ++++ .../services/voucher_check/notification.py | 194 ++++--- .../services/voucher_check/profile_loader.py | 70 +++ .../voucher_check/profiles/__init__.py | 15 + .../services/voucher_check/profiles/sales.py | 92 ++++ .../services/voucher_check/query_service.py | 185 ++++++- backend/app/services/voucher_check/runner.py | 399 ++++++++------ .../services/voucher_check/schedule_seed.py | 19 +- ...b3c4d5e_add_voucher_check_engine_tables.py | 237 +++++++++ backend/tests/test_faq_cache.py | 60 +++ .../tests/voucher_check/test_dms_archive.py | 186 +++++++ .../test_engine_profile_and_scan.py | 124 +++++ .../test_workspace_force_recheck.py | 97 ++++ docs/convention/环境变量规则.md | 8 + docs/demand.md | 16 +- .../accounting-voucher-check/README.md | 23 +- .../accounting-voucher-check-prototype.html | 14 +- .../accounting-voucher-check-prototype.md | 4 +- .../accounting-voucher-check/demand.md | 448 +++++----------- .../dify-chatflow-draft.md | 3 +- .../accounting-voucher-check/ops-checklist.md | 9 +- .../technical-design.md | 495 ++---------------- .../accounting-voucher-check/technical.md | 70 ++- docs/features/faq/faq_cache_ops_manual.md | 3 +- docs/funclist.md | 24 +- docs/tec.md | 10 +- .../components/QuestionFormModal.vue | 16 +- .../workspace/api/voucherCheck.api.ts | 91 ++-- .../views/AccountingVoucherCheckView.vue | 166 ++++-- frontend/src/locales/en/admin.json | 3 +- frontend/src/locales/en/chat.json | 6 +- frontend/src/locales/en/errors.json | 8 +- frontend/src/locales/en/workspace.json | 37 +- frontend/src/locales/th/admin.json | 3 +- frontend/src/locales/th/chat.json | 6 +- frontend/src/locales/th/errors.json | 8 +- frontend/src/locales/th/workspace.json | 35 +- frontend/src/locales/zh-CN/admin.json | 3 +- frontend/src/locales/zh-CN/chat.json | 8 +- frontend/src/locales/zh-CN/errors.json | 8 +- frontend/src/locales/zh-CN/workspace.json | 41 +- frontend/src/locales/zh-TW/admin.json | 3 +- frontend/src/locales/zh-TW/chat.json | 8 +- frontend/src/locales/zh-TW/errors.json | 8 +- frontend/src/locales/zh-TW/workspace.json | 39 +- 68 files changed, 3680 insertions(+), 1413 deletions(-) create mode 100644 backend/app/services/voucher_check/adapters/__init__.py create mode 100644 backend/app/services/voucher_check/adapters/base.py create mode 100644 backend/app/services/voucher_check/adapters/dms_archive.py create mode 100644 backend/app/services/voucher_check/adapters/dms_directory_scan.py create mode 100644 backend/app/services/voucher_check/adapters/erp_po_print.py create mode 100644 backend/app/services/voucher_check/adapters/hxjm_apa_subject.py create mode 100644 backend/app/services/voucher_check/adapters/oa_sales_release.py create mode 100644 backend/app/services/voucher_check/adapters/registry.py create mode 100644 backend/app/services/voucher_check/aggregator.py create mode 100644 backend/app/services/voucher_check/dms_client.py create mode 100644 backend/app/services/voucher_check/engine_persistence.py create mode 100644 backend/app/services/voucher_check/filename_match.py create mode 100644 backend/app/services/voucher_check/profile_loader.py create mode 100644 backend/app/services/voucher_check/profiles/__init__.py create mode 100644 backend/app/services/voucher_check/profiles/sales.py create mode 100644 backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py create mode 100644 backend/tests/test_faq_cache.py create mode 100644 backend/tests/voucher_check/test_dms_archive.py create mode 100644 backend/tests/voucher_check/test_engine_profile_and_scan.py create mode 100644 backend/tests/voucher_check/test_workspace_force_recheck.py diff --git a/.env.shared b/.env.shared index 53728fc0..858709dd 100644 --- a/.env.shared +++ b/.env.shared @@ -53,6 +53,9 @@ CONTRACT_DMS_2026_FOLDER_ID=4e63b520-0da9-4731-a3dd-ec48f278dce0 CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE={year}年设备合同书 CONTRACT_DMS_TEMP_FOLDER_NAME=暂存 CONTRACT_DMS_LOOKUP_WINDOW_DAYS=30 + +# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*) +VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=727c3683-dcdb-4d62-a5b1-b164224162bc CONTRACT_PAYMENT_ENABLED=true CONTRACT_PAYMENT_OA_BASE_URL=http://192.168.100.221:8888 CONTRACT_PAYMENT_OA_USERNAME=AIuser diff --git a/backend/app/api/workspace/voucher_check.py b/backend/app/api/workspace/voucher_check.py index 4a471c7e..b08f6876 100644 --- a/backend/app/api/workspace/voucher_check.py +++ b/backend/app/api/workspace/voucher_check.py @@ -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//items", methods=["GET"]) def workspace_voucher_run_items(run_id: int): """ diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index d92d0d6f..9f30db55 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -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') diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index fc658988..22fcaa43 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/content.py b/backend/app/models/content.py index d794ed4b..c88dbe4c 100644 --- a/backend/app/models/content.py +++ b/backend/app/models/content.py @@ -34,6 +34,7 @@ class QuickQuestion(Base): """ 常用问题表 用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。 + is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。 """ __tablename__ = 'quick_questions' diff --git a/backend/app/models/voucher_check.py b/backend/app/models/voucher_check.py index 7de44eb6..1b215df7 100644 --- a/backend/app/models/voucher_check.py +++ b/backend/app/models/voucher_check.py @@ -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) diff --git a/backend/app/services/faq_cache.py b/backend/app/services/faq_cache.py index 2ff00f7e..032a6a32 100644 --- a/backend/app/services/faq_cache.py +++ b/backend/app/services/faq_cache.py @@ -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), diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index 43f58fe1..85e25b50 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -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 diff --git a/backend/app/services/schedule/voucher_check_job.py b/backend/app/services/schedule/voucher_check_job.py index 758f1be5..1b7a289a 100644 --- a/backend/app/services/schedule/voucher_check_job.py +++ b/backend/app/services/schedule/voucher_check_job.py @@ -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) diff --git a/backend/app/services/voucher_check/adapters/__init__.py b/backend/app/services/voucher_check/adapters/__init__.py new file mode 100644 index 00000000..9314e478 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/__init__.py @@ -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", +] diff --git a/backend/app/services/voucher_check/adapters/base.py b/backend/app/services/voucher_check/adapters/base.py new file mode 100644 index 00000000..a728e03a --- /dev/null +++ b/backend/app/services/voucher_check/adapters/base.py @@ -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 触发时机】扫描命中且命名校验通过后调用。 + """ + ... diff --git a/backend/app/services/voucher_check/adapters/dms_archive.py b/backend/app/services/voucher_check/adapters/dms_archive.py new file mode 100644 index 00000000..31f25d26 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/dms_archive.py @@ -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"), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/dms_directory_scan.py b/backend/app/services/voucher_check/adapters/dms_directory_scan.py new file mode 100644 index 00000000..2a3d4009 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/dms_directory_scan.py @@ -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, + ) diff --git a/backend/app/services/voucher_check/adapters/erp_po_print.py b/backend/app/services/voucher_check/adapters/erp_po_print.py new file mode 100644 index 00000000..32a4e968 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/erp_po_print.py @@ -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), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py new file mode 100644 index 00000000..23e8e265 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py @@ -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 diff --git a/backend/app/services/voucher_check/adapters/oa_sales_release.py b/backend/app/services/voucher_check/adapters/oa_sales_release.py new file mode 100644 index 00000000..16658713 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/oa_sales_release.py @@ -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), + }, + ) diff --git a/backend/app/services/voucher_check/adapters/registry.py b/backend/app/services/voucher_check/adapters/registry.py new file mode 100644 index 00000000..a845fed8 --- /dev/null +++ b/backend/app/services/voucher_check/adapters/registry.py @@ -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)) diff --git a/backend/app/services/voucher_check/aggregator.py b/backend/app/services/voucher_check/aggregator.py new file mode 100644 index 00000000..8714cc00 --- /dev/null +++ b/backend/app/services/voucher_check/aggregator.py @@ -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, + } diff --git a/backend/app/services/voucher_check/config.py b/backend/app/services/voucher_check/config.py index c22fc367..0e296dfb 100644 --- a/backend/app/services/voucher_check/config.py +++ b/backend/app/services/voucher_check/config.py @@ -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: """ 解析实际扫描根路径。 diff --git a/backend/app/services/voucher_check/dms_client.py b/backend/app/services/voucher_check/dms_client.py new file mode 100644 index 00000000..3842b01a --- /dev/null +++ b/backend/app/services/voucher_check/dms_client.py @@ -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 diff --git a/backend/app/services/voucher_check/engine_persistence.py b/backend/app/services/voucher_check/engine_persistence.py new file mode 100644 index 00000000..2cd6b1e0 --- /dev/null +++ b/backend/app/services/voucher_check/engine_persistence.py @@ -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 diff --git a/backend/app/services/voucher_check/erp_repository.py b/backend/app/services/voucher_check/erp_repository.py index b4e922db..8e74fbc6 100644 --- a/backend/app/services/voucher_check/erp_repository.py +++ b/backend/app/services/voucher_check/erp_repository.py @@ -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: diff --git a/backend/app/services/voucher_check/excel_rows.py b/backend/app/services/voucher_check/excel_rows.py index a690c1d6..a9aed91a 100644 --- a/backend/app/services/voucher_check/excel_rows.py +++ b/backend/app/services/voucher_check/excel_rows.py @@ -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 diff --git a/backend/app/services/voucher_check/filename_match.py b/backend/app/services/voucher_check/filename_match.py new file mode 100644 index 00000000..bef6af9b --- /dev/null +++ b/backend/app/services/voucher_check/filename_match.py @@ -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 diff --git a/backend/app/services/voucher_check/notification.py b/backend/app/services/voucher_check/notification.py index 10255011..da89c0eb 100644 --- a/backend/app/services/voucher_check/notification.py +++ b/backend/app/services/voucher_check/notification.py @@ -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 diff --git a/backend/app/services/voucher_check/profile_loader.py b/backend/app/services/voucher_check/profile_loader.py new file mode 100644 index 00000000..d5bb8038 --- /dev/null +++ b/backend/app/services/voucher_check/profile_loader.py @@ -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 diff --git a/backend/app/services/voucher_check/profiles/__init__.py b/backend/app/services/voucher_check/profiles/__init__.py new file mode 100644 index 00000000..2b173420 --- /dev/null +++ b/backend/app/services/voucher_check/profiles/__init__.py @@ -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"] diff --git a/backend/app/services/voucher_check/profiles/sales.py b/backend/app/services/voucher_check/profiles/sales.py new file mode 100644 index 00000000..0c24e95c --- /dev/null +++ b/backend/app/services/voucher_check/profiles/sales.py @@ -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)] diff --git a/backend/app/services/voucher_check/query_service.py b/backend/app/services/voucher_check/query_service.py index 61eefc70..f48d6832 100644 --- a/backend/app/services/voucher_check/query_service.py +++ b/backend/app/services/voucher_check/query_service.py @@ -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, + } diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py index dcdbbe9d..124f3fb2 100644 --- a/backend/app/services/voucher_check/runner.py +++ b/backend/app/services/voucher_check/runner.py @@ -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, diff --git a/backend/app/services/voucher_check/schedule_seed.py b/backend/app/services/voucher_check/schedule_seed.py index 936c3d75..0c6c9497 100644 --- a/backend/app/services/voucher_check/schedule_seed.py +++ b/backend/app/services/voucher_check/schedule_seed.py @@ -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 = ( diff --git a/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py b/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py new file mode 100644 index 00000000..1d3d8f1e --- /dev/null +++ b/backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py @@ -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") diff --git a/backend/tests/test_faq_cache.py b/backend/tests/test_faq_cache.py new file mode 100644 index 00000000..50e7713d --- /dev/null +++ b/backend/tests/test_faq_cache.py @@ -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 diff --git a/backend/tests/voucher_check/test_dms_archive.py b/backend/tests/voucher_check/test_dms_archive.py new file mode 100644 index 00000000..be40dd90 --- /dev/null +++ b/backend/tests/voucher_check/test_dms_archive.py @@ -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 diff --git a/backend/tests/voucher_check/test_engine_profile_and_scan.py b/backend/tests/voucher_check/test_engine_profile_and_scan.py new file mode 100644 index 00000000..1313e3df --- /dev/null +++ b/backend/tests/voucher_check/test_engine_profile_and_scan.py @@ -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" diff --git a/backend/tests/voucher_check/test_workspace_force_recheck.py b/backend/tests/voucher_check/test_workspace_force_recheck.py new file mode 100644 index 00000000..71694c9b --- /dev/null +++ b/backend/tests/voucher_check/test_workspace_force_recheck.py @@ -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" diff --git a/docs/convention/环境变量规则.md b/docs/convention/环境变量规则.md index 8cbc611a..10d78f9b 100644 --- a/docs/convention/环境变量规则.md +++ b/docs/convention/环境变量规则.md @@ -83,3 +83,11 @@ - `PROCUREMENT_CONTRACT_LLM_DIFY_BASE` `PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` 属于密钥;生产环境优先由 Jenkins/部署平台注入。当前优先通过 `PROCUREMENT_CONTRACT_LLM_AGENT_ID` 复用已配置的 Chatflow Agent,不在环境文件重复保存密钥。 + +## 8. 立账凭证检核文档库 + +三环境一致、非密钥的销售开票附件根目录放在 `.env.shared`: + +- `VOUCHER_CHECK_DMS_ROOT_FOLDER_ID` + +登录基址、LibraryID、账号默认复用 `CONTRACT_DMS_*`。如需覆盖再设 `VOUCHER_CHECK_DMS_BASE_URL` / `VOUCHER_CHECK_DMS_LIBRARY_ID` / `VOUCHER_CHECK_DMS_USERNAME` / `VOUCHER_CHECK_DMS_PASSWORD`(密码禁止写入仓库)。 diff --git a/docs/demand.md b/docs/demand.md index e7a7e706..d8d6e6a2 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -208,14 +208,14 @@ ### 3.x 立账凭证检核补充需求 - AI 工作台中的“立账凭证”入口及页面仅对 `role=admin` 用户开放;普通用户不展示入口,直接访问地址时返回工作台应用页。 -- **核心目标**:按当前自然月从 HXJM 套账 ERP `apa_file` 取得发票号清单,检查共享盘对应发票目录中的必检文件是否存在,输出齐全/缺资料结果。 -- **数据口径**:`apa08` 为发票号且唯一,`apa09` 为发票日期;只检核当前自然月,不追溯月末补录的上月发票;红冲、作废、取消票据一期不纳入。 -- **目录口径**:共享盘默认采用 `vouche/{YYYY}/{MM}/{invoice_no}/`,目录模板可配置以支持后续调整。 -- **判定边界**:严格按可配置文件名判断存在性;暂定必检「核价单.pdf」「采购单.pdf」;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 -- **实现状态**:一期 HXOPS 引擎/API/工作台已落地;日批 `0 6 * * *`;**Dify Chatflow 编排待完成**。 -- **可靠性要求**:共享盘不可用、Oracle 查询失败或配置错误时,整批失败并告警,不得把整批票标记为缺资料;单票缺目录/缺文件才记为缺资料。 -- **通知要求**:缺资料按固定接收人发送企业微信通知,并按同票同日节流。 -- 技术规格见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 +- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单沿用旧口径(HXJM `apa_file.apa08/apa09`);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 +- **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。 +- **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。 +- **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。 +- **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。 +- **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 +- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总迁移;PO/OA 打印仍待接线。Dify Chatflow 待按新口径重编。 +- 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 ### 3.x 货代发货通知库存源补充需求 diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index 84b55b9b..11b51935 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -1,18 +1,17 @@ # 立账凭证检核(accounting-voucher-check) -| 文档 | 读者 | 路径 | -| ---------------------------- | ---------------- | --------------------------------------------------------------- | -| | | | -| **需求说明** | 产品、业务、测试 | [demand.md](demand.md) | -| **历史需求与规格手册** | 研发、运维、测试 | [technical.md](technical.md)(旧版单共享盘方案,仅供历史实现参考) | +| 文档 | 读者 | 路径 | +| --- | --- | --- | +| **需求说明** | 产品、业务、测试 | [demand.md](demand.md) | +| **技术设计** | 研发 | [technical-design.md](technical-design.md) | +| **技术规格** | 研发、测试 | [technical.md](technical.md) | +| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) | +| **当前代码部署清单(旧实现)** | 运维、研发 | [ops-checklist.md](ops-checklist.md) | +| **Dify 编排草稿(旧引擎 Tool)** | 研发 | [dify-chatflow-draft.md](dify-chatflow-draft.md) | - -| **销售一期需求说明** | 产品、业务、测试 | [demand.md](demand.md) | -| **需求与规格手册** | 产品、业务、测试 | [technical.md](technical.md) | - -**定位**:以业务方 Profile 驱动的批量资料检核;每周增量处理上一个自然月,按 `invoice` 集中归档。 +**定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。 **要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。 **检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。 -**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数,提供按文件类型、按 `invoice` 的汇总和单文件明细;同一 `invoice` 的多个缺件合并为一条企业微信通知。 +**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。 -**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。旧版已实现代码与文档尚未按新版需求改造,实施前须以 [technical-design.md](technical-design.md) 的新版设计为准。 +**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。仓库内现有代码仍是旧实现(当前自然月共享盘文件名存在性),实施前须按 [technical-design.md](technical-design.md) 改造,不得按旧口径扩展。 diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html index f5dc97df..70874c6c 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.html @@ -46,16 +46,16 @@ const profiles = { sales: { name: '销售一期', enabled: true, - desc: '每周增量检核上一个自然月;以销售 invoice 为核心,从 ERP、OA 与固定目录获取文件并集中归档。', + desc: '每周增量检核上一个自然月;获取后写入销售开票附件/{年}/{月}/{类型目录}/,再按 invoice 归入所有归档。', metrics: [['6','必检文件规则'],['每周','执行频率'],['上月','检核范围']], note: '缺少任一必检文件时生成双维度汇总 Excel 并发送企业微信通知;通知接收人待业务确认。', rules: [ - ['PO订单','{invoice号}-{订单号}.pdf','erp','ERP 查询并打印','以 invoice 反查 PO','查询条件待补充','已确认'], - ['报关资料','{invoice号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['销货放行申请单','{invoice号}-{销货单号}.pdf','oa','OA 报表打印','OA 读取发票号和销货单号','上月 + 归档 + HXJM + 发票号非空','流程已确认'], - ['发票','{invoice号}-{发票号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['报关单','{invoice号}-{报关单号}.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'], - ['提单','{invoice号}-提单.pdf','dir','固定目录扫描','文件名含 invoice','路径待确认','待确认'] + ['PO订单','{invoice号}-{订单号}.pdf','erp','ERP 查询并打印','以 invoice 反查 PO','销售开票附件/{年}/{月}/PO订单/','已确认'], + ['报关资料','{invoice号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/报关资料/','已确认'], + ['销货放行申请单','{invoice号}-{销货单号}.pdf','oa','OA 报表打印','OA 读取发票号和销货单号','销售开票附件/{年}/{月}/销货单/','已确认'], + ['发票','{invoice号}-{发票号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/发票/','已确认'], + ['报关单','{invoice号}-{报关单号}.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/报关单/','已确认'], + ['提单','{invoice号}-提单.pdf','dir','固定目录扫描','文件名含 invoice','销售开票附件/{年}/{月}/提单/','已确认'] ], subjects: [ ['INV-202607-00128','已归档',[['PO订单','ERP 打印','archived'],['销货放行申请单','OA 打印','archived'],['报关资料','固定目录','archived'],['发票','固定目录','archived'],['报关单','固定目录','archived'],['提单','固定目录','archived']]], diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md index 8d080ee5..f3cbbbe2 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md @@ -15,8 +15,8 @@ ## 业务口径 -- 销售一期:每周增量检核上一个自然月,支持 ERP、OA 和固定目录来源,按 invoice 集中归档。 -- 销货放行申请单:OA 过滤上月、归档、HXJM、发票号码非空;关联字段不完整时直接跳过,不打印、不归档、不记录字段异常。 +- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `apa_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。 +- 销货放行申请单:一期模拟 OA 页面;后期换新接口。关联字段不完整时直接跳过。 - 采购二期:展示六类拟定文件规则;路径、主体来源和 Adapter 参数待确认,原型不执行采购检核。 - 批量缺件同时统计“缺件文件总数”和“缺件 `invoice` 数”;同一 `invoice` 缺多个文件时前者累计多个、后者只计一次。 - 统一 Excel 仅包含“检核结果”工作表:每行一个 `invoice`,直接展示各必检文件“有 / 缺件 / 未检核”和状态;全部文件均为“有”时状态为“完整”。 diff --git a/docs/features/accounting-voucher-check/demand.md b/docs/features/accounting-voucher-check/demand.md index 5091238f..3fea0a3f 100644 --- a/docs/features/accounting-voucher-check/demand.md +++ b/docs/features/accounting-voucher-check/demand.md @@ -1,8 +1,10 @@ # 立账凭证资料检核需求说明 -> 文档版本:v1.1 -> 更新时间:2026-08-18 +> 文档版本:v1.7 +> 更新时间:2026-09-04 > 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置 +> +> 本文是本期需求权威。仓库里现有「当前自然月 + 单一共享盘 + 固定文件名存在性」是旧实现,不得作为本期验收口径;旧实现部署见 [ops-checklist.md](ops-checklist.md)。 ## 1. 背景与目标 @@ -25,31 +27,33 @@ | 项目 | 规则 | | -------- | ----------------------------------------------------------------------------------------------------------------------- | -| 执行频率 | 每周执行一次 | +| 执行频率 | 每周二执行一次(默认 06:00,Asia/Shanghai) | | 检核期间 | 执行日的上一个自然月;例如 2026-08-18 执行,检核 2026-07 | -| 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核 | -| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体 | -| 归档单位 | 以 `invoice` 为目录单位,同一 `invoice` 的全部已获取文件放入同一归档目录 | +| 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核。归档目录已有同名文件时按「同名跳过」不覆盖 | +| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。工作台「强制重检上月」入队 `force_all` | +| 归档单位 | 文档库「所有归档」下以 `invoice` 为子目录;同一 `invoice` 的已获取文件集中存放。获取后先落入当月类型目录 | ### 3.2 Profile 驱动扩展 -| 配置项 | 说明 | -| ---------------- | ------------------------------------------------------------------------------------- | -| `profile_code` | 业务方标识,例如 `sales`、`procurement` | -| 主体来源 | 获取本期应检 `invoice` 清单的来源和关联字段 | -| 文件规则 | 文件类型、必检性、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时目录、归档模板 | -| 通知规则 | 缺件通知开关、接收人、通知模板与去重策略 | +| 配置项 | 说明 | +| ---------------- | ----------------------------------------------------------------------------------------- | +| `profile_code` | 业务方标识,例如 `sales`、`procurement` | +| 主体来源 | 获取本期应检 `invoice` 清单的来源和关联字段 | +| 文件规则 | 文件类型、必检性、命名模板、关联字段、来源 Adapter、查询/扫描条件、类型存放路径、归档模板 | +| 通知规则 | 缺件通知开关、接收人、通知模板与去重策略 | 新增业务方时优先新增或调整 Profile;只有新增外部系统或获取协议时才开发新的来源 Adapter。 +销售一期主体清单**沿用旧方案 ERP 口径**:HXJM 套账只读查询 `apa_file`,`apa08` 为发票号、`apa09` 为发票日期,发票号非空。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。 + ### 3.3 结果状态 -| 状态 | 含义 | 是否计入缺件 | -| -------- | ---------------------------------------- | ------------ | -| 已归档 | 文件已取得、校验关联并复制到目标归档目录 | 否 | -| 缺件 | 必检文件未找到或未成功取得 | 是 | -| 已跳过 | 增量规则判定无需本次重新处理 | 否 | -| 技术失败 | 登录、查询、打印、复制等系统异常 | 否;单独告警 | +| 状态 | 含义 | 是否计入缺件 | +| -------- | ----------------------------------------------------- | ------------ | +| 已归档 | 文件已取得、校验关联并复制到「所有归档/{invoice号}/」 | 否 | +| 缺件 | 必检文件未找到或未成功取得 | 是 | +| 已跳过 | 增量规则判定无需本次重新处理 | 否 | +| 技术失败 | 登录、查询、打印、复制等系统异常 | 否;单独告警 | ### 3.4 检核任务列表 @@ -62,34 +66,61 @@ | 任务列表字段 | 批次号、业务方、资料所属期间、执行时间、主体总数、已归档数、缺件文件数、缺件 `invoice` 数、状态 | | 状态 | 缺件、已完成、技术失败、待配置 | | 操作 | 查看详情;进入该批次的执行记录,并可查看企业微信通知附件 Excel | -| 任务入口 | 支持新建任务、强制重检;强制重检仍只针对上一个自然月 | +| 任务入口 | 支持新建任务、强制重检(仅上一个月);企微接收人从系统用户多选,可复用排程通知人选择器 | ## 4. 销售一期文件规则 -| 文件类型 | 命名方式 | 获取方式 | `invoice` 关联 | 扫描/查询条件 | 路径状态 | -| -------------- | ------------------------------ | -------------------------- | --------------------------- | ---------------------- | ------------------- | -| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | 以销售 `invoice` 反查 PO | ERP 具体查询字段待补充 | 临时/归档路径待确认 | -| 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | OA 列表读取发票号、销货单号 | 见 5.1 | 临时/归档路径待确认 | -| 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 报关单 | `{invoice号}-{报关单号}.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | -| 提单 | `{invoice号}-提单.pdf` | 固定目录扫描 | 文件名含 `invoice` | 扫描上月对应文件 | 扫描路径待确认 | +销售开票附件落在文档管理系统(文档库)中。不论从 ERP 打印、OA 打印还是固定目录扫描,**获取成功后都先写入当月类型存放目录**,再按发票号归档到「所有归档」。 -> 各路径确认前不得虚构实际目录。文件命名、路径和查询条件均由销售 Profile 配置。 +目录层级(与文档库现状一致): + +```text +文档库 / 销售开票附件 / {yyyy} / {MM} / + ├── PO订单/ + ├── 付款回单/ ← 库中已有,一期不检核 + ├── 发票/ + ├── 报关资料/ + ├── 送货单/ ← 库中已有,一期不检核 + ├── 销货单/ ← 销货放行申请单的类型存放目录 + ├── 报关单/ + ├── 提单/ + └── 所有归档/{invoice号}/ +``` + +`{yyyy}`、`{MM}` 为检核月份的四位年份与两位月份,例如 `2026/08`。 + +| 文件类型 | 命名方式 | 获取方式 | 存放路径 | `invoice` 关联 | 扫描/查询条件 | +| -------------- | ------------------------------ | -------------------------- | --------------------------------------------- | --------------------------- | ---------------------- | +| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | 以销售 `invoice` 反查 PO | **待确认**:查询字段、关联与打印方式 | +| 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关资料/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | OA 列表读取发票号、销货单号 | 见 5.1 | +| 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/发票/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 报关单 | `{invoice号}-{报关单号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | +| 提单 | `{invoice号}-提单.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/提单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | + +归档路径(六类文件共用,按发票号集中): + +```text +文档库/销售开票附件/{yyyy}/{MM}/所有归档/{invoice号}/ +``` + +> 固定目录扫描的来源即上表「存放路径」。ERP/OA 打印件写入同一类型目录后再归档。销售类型目录名已确认固定,不随现场习惯改名:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单`。文档库系统、接口与账号见 §5.4。 ## 5. 销售文件获取与归档 ### 5.1 销货放行申请单(OA) -| 步骤 | 操作与规则 | -| ---- | ------------------------------------------------------------------ | -| 1 | 在 OA 进入“报表 → 流程报表 → 自定义报表”,选择“销货放行单” | -| 2 | 过滤申请日期为检核期间(上一个自然月) | -| 3 | 过滤流程状态为“归档”、账套为 `HXJM`、发票号码不为空 | -| 4 | 从结果列表读取发票号和销货单号,以二者关联并生成文件名 | -| 5 | 对关联字段完整的每条申请单逐条打印并保存为 PDF | -| 6 | 关联字段不完整时直接丢弃该 OA 记录:不打印、不归档、不记录字段异常 | -| 7 | 校验后复制至对应 `invoice` 的归档目录 | +一期**只支持按页面模拟**完成下列步骤;不依赖尚未提供的 OA 打印 API。后续对接新 OA 接口时,过滤条件、命名和归档规则不变,仅替换 Adapter 实现。 + +| 步骤 | 操作与规则 | +| ---- | --------------------------------------------------------------------- | +| 1 | 在 OA 进入“报表 → 流程报表 → 自定义报表”,选择“销货放行单” | +| 2 | 过滤申请日期为检核期间(上一个自然月) | +| 3 | 过滤流程状态为“归档”、账套为 `HXJM`、发票号码不为空 | +| 4 | 从结果列表读取发票号和销货单号,以二者关联并生成文件名 | +| 5 | 对关联字段完整的每条申请单:一期按页面逐步模拟打开并打印/保存 PDF;预留切换新 OA 接口,接口就绪后不改过滤与命名规则 | +| 6 | 关联字段不完整时直接丢弃该 OA 记录:不打印、不归档、不记录字段异常 | +| 7 | 校验后先写入当月「销货单」存放目录,再复制到「所有归档/{invoice号}/」 | ```mermaid flowchart TD @@ -97,36 +128,61 @@ flowchart TD B --> C[读取发票号与销货单号] C --> D{关联字段完整?} D -- 否 --> E[直接丢弃,不记录字段异常] - D -- 是 --> F[逐条打印并保存 PDF] - F --> G[按 invoice 校验命名并归档] + D -- 是 --> F[一期模拟页面打印 PDF / 后期改走 OA 接口] + F --> G[写入销货单目录并归档到所有归档/invoice] ``` ### 5.2 PO 订单(ERP) -| 步骤 | 操作与规则 | -| ---- | ------------------------------------------------------------- | -| 1 | 以上月销售 `invoice` 清单为入口 | -| 2 | 在 ERP 查询并反查对应 PO 订单 | -| 3 | 每个 PO 订单打印并保存一个 PDF | -| 4 | 按 `invoice + 订单号` 命名,复制至对应 `invoice` 归档目录 | -| 5 | ERP 查询字段、过滤条件和具体路径待业务补充 | +| 步骤 | 操作与规则 | +| ---- | -------------------------------------------------------- | +| 1 | 以上月销售 `invoice` 清单为入口 | +| 2 | 在 ERP 查询并反查对应 PO 订单 | +| 3 | 每个 PO 订单打印并保存一个 PDF | +| 4 | 按 `invoice + 订单号` 命名,写入当月「PO订单」存放目录 | +| 5 | 再复制到「所有归档/{invoice号}/」 | +| 6 | **待确认**:ERP 查询字段、invoice 与 PO 关联、打印入口与 PDF 落盘方式 | -### 5.3 通用归档流程 +### 5.3 通用存放与归档流程 + +获取与归档分两步,都在文档库「销售开票附件」下完成: + +| 步骤 | 位置 | 规则 | +| ---------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| 1 类型存放 | `销售开票附件/{yyyy}/{MM}/{类型目录}/` | ERP/OA 打印或目录扫描的成功文件先落入对应类型目录,按上表命名 | +| 2 按票归档 | `销售开票附件/{yyyy}/{MM}/所有归档/{invoice号}/` | 校验 `invoice` 关联和命名后,将成功文件**复制**(不移动类型目录原件)到该发票子目录;同一 `invoice` 的多个文件必须集中在同一子目录,不同 `invoice` 不得混放。**重复文件策略:同名跳过**——目标目录已有相同 `LeafName` 时不覆盖、不报缺件,视为已归档 | ```mermaid flowchart TD A[每周任务启动] --> B[确定上一个自然月] B --> C[加载业务方 Profile 和本期 invoice 清单] C --> D[按文件规则调用来源 Adapter] - D --> E[获取或打印至临时目录] + D --> E[写入类型存放目录] E --> F[校验 invoice 关联和命名] - F --> G[建立 invoice 归档目录] - G --> H[复制文件并记录单文件结果] + F --> G[复制到所有归档/invoice号] + G --> H[记录单文件结果] H --> I[汇总缺件与技术失败] I --> J[生成统一 Excel 并发送通知] ``` -归档目录模板:`{归档根路径}/{yyyy}/{MM}/{invoice号}/`。同一 `invoice` 的多个文件必须集中在同一目录下。 +类型存放失败或归档复制失败属于技术失败,不可降级为缺件。固定目录扫描找不到文件记为缺件。 + +### 5.4 文档管理系统(已确认可复用) + +销售开票附件与采购合同附件使用**同一套文档管理系统**,不新造存储。 + +| 项 | 已确认内容 | +| --- | --- | +| 系统 | 文档管理系统(Web 文档库,路径形如 `文档库 > 销售开票附件 > {年} > {月}`) | +| 基址 | 复用现有 `CONTRACT_DMS_BASE_URL`(与合同付款文档库相同) | +| 登录接口 | `POST {基址}/Login/_api/Login`,body:`LoginName` / `Pwd` | +| 目录/文件查询 | `POST {基址}/Api/_api/APS/Public/Item/Page`(`LibraryID`、`ParentFolderID`、分页) | +| 建文件夹 | `POST {基址}/Api/_api/APS/Public/Item/SaveFolder`(`LibraryID`、`ParentFolderID`、`LeafName`、`FieldValues`) | +| 复制文件 | `POST {基址}/Api/_api/APS/Public/Item/Copy`(`ItemID` 数组、目标 `ParentFolderID`)。归档**禁止**使用 Move | +| 账号 | 复用现有 DMS 账号;用户名与密码只放环境变量/密钥注入,禁止写入代码、Profile JSON、Excel 或日志 | +| 库与目录 | 全公司只有一个文档库:`LibraryID` 与现网 `CONTRACT_DMS_LIBRARY_ID` 相同(`LibraryName` 为「文档库」)。「设备合同书」「销售开票附件」都是该库下的文件夹,**不要另配 LibraryID**。销售根目录单独配置 FolderID,**不得**复用合同根目录。现网销售根 FolderID 为 `727c3683-dcdb-4d62-a5b1-b164224162bc`(接口无 `FolderID` 字段,用条目 `ID` / `IDPath`) | + +下载、建文件夹、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;目标已有同名文件则跳过。仍不把凭据写入需求正文。 ## 6. 批量缺件汇总与企业微信通知 @@ -149,7 +205,7 @@ flowchart TD | 聚合 | 一个检核批次发送一条汇总通知;不在企业微信中逐票展开缺失明细 | | 内容 | 业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型、Excel 下载入口 | | 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 | -| 接收人 | 待业务确认;未配置接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | +| 接收人 | 业务可暂不指定具体人;**必须提供配置界面**,从 HXOPS 系统用户中多选(须已绑定企微 userid)。可复用管理后台排程任务的通知人选择器。未配置任何接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | | 技术失败 | 不作为缺件通知;按技术告警规则单独处理 | ## 7. 企业微信通知附件 Excel @@ -168,285 +224,23 @@ flowchart TD ## 8. 验收要点 -1. 每周任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 +1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 4. 企业微信每批仅发送一条缺件汇总通知,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 -6. 路径、ERP 查询条件等待确认项保持待确认,系统通过 Profile 配置承接,不能写死在通用逻辑中。 - ======= - -# 销售立账凭证检核一期需求说明 - -> 文档状态:需求梳理稿 -> -> 适用阶段:一期销售业务 -> -> 说明:本文用于确认业务范围、文件获取方式、归档规则和结果输出。各文件的具体扫描路径、目录名称、ERP 查询字段及自动化接口,待业务方继续补充后固化。 - -## 1. 需求概述 - -### 1.1 背景 - -立账凭证资料由不同业务方分别维护。不同业务方需要检核的文件数量、文件命名方式、获取方式和存放路径并不相同,因此不能继续按单一共享目录和固定文件清单进行扫描。 - -本期先建设销售业务的立账凭证资料检核流程,后续再扩展采购及其它业务方。 - -### 1.2 建设目标 - -| 目标 | 说明 | -| --------------- | ---------------------------------------------------------- | -| 周度增量检核 | 每周执行一次,仅处理上一个自然月内新增或发生变化的销售资料 | -| 多来源获取 | 支持 ERP、OA 和固定目录等不同文件来源 | -| 按 invoice 归档 | 同一 invoice 的相关文件集中放在同一归档目录 | -| 缺失可追踪 | 明确列出缺少的文件及查询、打印、复制失败原因 | -| 缺失通知 | 发现缺失文件后发送企业微信通知,提醒相关人员补齐资料 | -| 统一输出 | 将所有 invoice 和文件的处理结果汇总为一个 Excel | -| 可扩展 | 后续可以按业务方配置不同的文件清单和处理规则 | - -## 2. 业务范围 - -### 2.1 分期范围 - -| 阶段 | 业务方 | 范围 | -| ---- | ---------- | ---------------------------------------------------------------- | -| 一期 | 销售 | 检核销售立账凭证相关文件,获取并归档已找到的文件,输出统一 Excel | -| 二期 | 采购 | 待一期稳定后建设,文件清单和处理规则另行确认 | -| 后续 | 其它业务方 | 按业务方独立配置文件、路径和处理流程 | - -### 2.2 本期不包含 - -- 不处理采购及其它业务方的文件。 -- 不读取 PDF 或其它文件的业务内容。 -- 不校验金额、供应商、订单信息等字段是否一致。 -- 不使用 LLM 判断文件是否合格。 -- 不回写 ERP 或 OA 业务数据。 -- 不虚构尚未确认的扫描路径、目录名称和 ERP 查询字段。 - -## 3. 检核周期与处理范围 - -### 3.1 执行与检核口径 - -系统每周执行一次增量检核,检核范围始终为上一个自然月。每次执行只处理自上次成功执行后新增或发生变化的资料,避免重复处理已成功归档且未发生变化的文件。 - -| 执行时间 | 检核月份 | 执行方式 | -| ------------------ | ------------- | -------- | -| 2026 年 8 月任一周 | 2026 年 7 月 | 增量检核 | -| 2027 年 1 月任一周 | 2026 年 12 月 | 增量检核 | - -任务需要正确处理跨年场景,不能将执行所在月份误作为检核月份。进入新的自然月后,检核目标相应切换至新月份的上一个自然月。 - -### 3.2 检核主键 - -- 以销售 `invoice 号` 作为一组资料的核心关联标识。 -- 同一 invoice 下的 PO 订单、销货放行申请单、发票、报关资料、报关单和提单统一归档。 -- 一个 invoice 对应多个业务单号时,每个实际文件单独记录,但归档到同一 invoice 目录。 - -## 4. 销售文件配置总表 - -下表根据当前业务资料整理。标记为“待确认”的内容,在业务方补充抓取规则后更新。 - -| 文件类型 | 命名规则 | 获取/处理方式 | 扫描路径 | 扫描目录名称 | 归档路径 | invoice 关联方式 | 状态 | -| -------------- | -------------------------------- | --------------------------------------- | -------- | ------------------------------ | ---------------------------- | --------------------------------------- | ------------------------------------ | -| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 条件查询对应 PO,逐个打印并保存 PDF | 待确认 | `PO订单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 以上月 invoice 清单为入口,反查 PO 订单 | 获取方式已确认,查询条件待补充 | -| 报关资料 | `{invoice号}.pdf` | 从固定目录读取 | 待确认 | `报关资料/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表筛选后,逐条打印并保存 PDF | OA | `销货放行申请单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | OA 记录直接提供发票号和销货单号 | 获取流程已确认,打印及落盘细节待补充 | -| 发票 | `{invoice号}-{发票号}.pdf` | 从固定目录读取 | 待确认 | `销货单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 报关单 | `{invoice号}-{报关单号码}.pdf` | 从固定目录读取 | 待确认 | `报关单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | -| 提单 | `{invoice号}-提单.pdf` | 从固定目录读取 | 待确认 | `提单/{yyyy}/{MM}` | `{yyyy}/{MM}/{invoice号}/` | 文件名直接包含 invoice 号 | 命名及处理方式已确认,路径待补充 | - -> 说明:表中的 `{yyyy}`、`{MM}` 和 `{invoice号}` 为路径变量,分别表示检核月份的四位年份、两位月份和 invoice 号。实际归档根路径待确认。 - -## 5. 文件获取需求 - -### 5.1 OA 销货放行申请单 - -#### 5.1.1 OA 报表入口 - -```text -报表 → 流程报表 → 自定义报表 → 销货放行单 -``` - -#### 5.1.2 查询条件 - -| 条件 | 过滤要求 | 目的 | -| -------- | ------------ | --------------------------- | -| 申请日期 | 上一个自然月 | 限定本次月度检核范围 | -| 流程状态 | `归档` | 只处理已完成归档的流程 | -| 账套 | `HXJM` | 限定销售一期目标账套 | -| 发票号码 | 不为空 | 确保能够与 invoice 建立关联 | - -#### 5.1.3 处理流程 - -```mermaid -flowchart TD - A[进入 OA 自定义报表] --> B[选择销货放行单] - B --> C[设置申请日期为上月] - C --> D[流程状态=归档] - D --> E[账套=HXJM] - E --> F[发票号码不为空] - F --> G[获取过滤后的列表] - G --> H[读取发票号和销货单号] - H --> I{关联字段完整?} - I -->|否| J[跳过该条记录] - I -->|是| K[逐条打开申请单] - K --> L[打印并保存独立 PDF] - L --> M[按 invoice 号复制归档] - M --> N[汇总到 Excel] -``` - -#### 5.1.4 业务规则 - -- OA 过滤结果中的每一条申请单生成一个独立 PDF。 -- 发票号和销货单号直接从 OA 列表或申请单详情读取,不依赖 PDF OCR。 -- 文件名按 `{invoice号}-{销货单号}.pdf` 生成。 -- 发票号码为空的记录由 OA 查询条件排除,不进入打印流程。 -- 发票号或销货单号缺失时,直接跳过该条记录;不打印、不归档,也不记录字段异常。 -- 单条申请单打开、打印或保存失败时,继续处理其它申请单,并在 Excel 中记录失败原因。 - -### 5.2 ERP PO 订单 - -#### 5.2.1 处理流程 - -```mermaid -flowchart TD - A[获取上月销售 invoice 清单] --> B[按 invoice 查询 ERP] - B --> C{查询到 PO 订单?} - C -->|否| D[记录 PO 缺失] - C -->|是| E[获取 PO 订单号] - E --> F[逐个打开 PO 订单] - F --> G[打印并保存独立 PDF] - G --> H[按 invoice 号复制归档] - D --> I[汇总到 Excel] - H --> I -``` - -#### 5.2.2 业务规则 - -- 以上一个自然月的销售 invoice 清单作为 PO 查询入口。 -- 针对每个 invoice 在 ERP 中反查对应 PO 订单。 -- 每个 PO 订单生成一个独立 PDF。 -- 文件名按 `{invoice号}-{订单号}.pdf` 生成。 -- 一个 invoice 对应多个 PO 时,多个 PO 文件均归档到该 invoice 目录。 -- ERP 具体查询条件、字段名称、打印入口和登录方式待后续补充确认。 -- 查询无结果、订单字段缺失、打印失败或保存失败均需记录到统一 Excel。 - -## 6. 整体处理流程 - -```mermaid -flowchart TD - A[每周增量任务启动] --> B[确定上一个自然月] - B --> C[获取销售 invoice 清单] - C --> D[按文件类型执行独立获取规则] - D --> E{文件来源} - E -->|ERP| F[查询 PO 并打印 PDF] - E -->|OA| G[筛选销货放行单并逐条打印 PDF] - E -->|固定目录| H[按命名规则扫描文件] - F --> I[临时目录保存] - G --> I - H --> I - I --> J{文件名和 invoice 关联有效?} - J -->|否| K[记录获取或关联异常] - J -->|是| L[创建 invoice 归档目录] - L --> M[复制文件到归档目录] - M --> N{复制成功?} - N -->|否| O[记录复制失败] - N -->|是| P[记录文件成功] - K --> Q[汇总所有处理结果] - O --> Q - P --> Q - Q --> R[生成统一 Excel] -``` - -### 6.1 临时目录与归档目录 - -文件处理采用“先临时保存、后校验归档”的方式: - -1. ERP、OA 打印生成的文件先保存至本次任务的临时目录。 -2. 系统校验文件名、invoice 号和业务单号是否完整。 -3. 按下列规则创建 invoice 归档目录: - -```text -{归档根路径}/{yyyy}/{MM}/{invoice号}/ -``` - -4. 将获取成功的文件复制到对应 invoice 目录。 -5. 记录来源文件路径、归档文件路径和复制结果。 - -同一 invoice 的文件只能归档到该 invoice 对应目录,不同 invoice 之间不得混放。 - -### 6.2 异常处理 - -| 异常类型 | 处理方式 | 是否阻断其它数据 | -| -------------------- | -------------------------------------- | ----------------- | -| ERP 查询无 PO | 记录该 invoice 缺少 PO 订单 | 否 | -| OA 查询无销货放行单 | 记录该 invoice 缺少销货放行申请单 | 否 | -| 固定目录找不到文件 | 记录对应文件缺失 | 否 | -| 发票号或业务单号为空 | 记录关联字段异常,不归档无归属文件 | 否 | -| ERP/OA 查询接口失败 | 记录技术失败原因,按任务策略重试或补跑 | 其它 invoice 继续 | -| PDF 打印或保存失败 | 记录单文件失败 | 否 | -| 文件复制失败 | 记录来源路径和目标路径 | 否 | -| 归档根路径不可用 | 记录归档技术异常,并触发运维处理 | 由任务策略决定 | - -### 6.3 缺失文件企业微信通知 - -- 当任一 invoice 缺少应检文件时,系统需发送企业微信通知。 -- 通知内容至少包含检核月份、invoice 号、缺失文件类型、期望文件名和本次任务标识。 -- 企业微信通知用于提醒补齐资料,不替代统一 Excel 检核结果。 -- 单个 invoice 存在多个缺失文件时,应在同一条通知中汇总展示。 -- 通知接收人、通知频率和通知模板待业务方确认后配置。 - -## 7. 统一 Excel 结果 - -### 7.1 输出要求 - -- 每次周度增量任务生成一个统一 Excel。 -- Excel 同时包含成功、缺失、查询异常、打印异常和复制异常记录。 -- 记录粒度为“一个 invoice + 一种文件类型 + 一个实际文件”。 -- 一个 invoice 存在多个 PO 或多个销货放行申请单时,分别生成多行记录。 -- 缺失文件也必须生成记录,不能只输出成功文件。 - -### 7.2 建议字段 - -| 字段 | 说明 | -| ------------ | -------------------------------------------------- | -| 检核月份 | 上一个自然月,格式 `yyyy-MM` | -| 业务方 | 一期固定为销售 | -| invoice 号 | 资料归属的核心编号 | -| 文件类型 | PO 订单、报关资料、销货放行申请单等 | -| 业务单号 | 订单号、销货单号、报关单号码等 | -| 期望文件名 | 按规则生成的文件名或匹配规则 | -| 获取方式 | ERP、OA 或固定目录 | -| 查询条件摘要 | 实际使用的日期、状态、账套等条件 | -| 处理状态 | 成功、缺失、查询失败、打印失败、保存失败、复制失败 | -| 来源路径 | 原始文件或临时文件路径 | -| 归档路径 | 最终归档文件路径 | -| 错误原因 | 缺失或失败的具体说明 | -| 处理时间 | 文件处理完成时间 | - -## 8. 验收标准 - -| 编号 | 验收场景 | 验收要求 | -| ----- | ---------- | -------------------------------------------------------- | -| AC-01 | 月份计算 | 任务始终检核上一个自然月,跨年计算正确 | -| AC-02 | OA 过滤 | 只处理上月、归档、HXJM 且发票号码不为空的记录 | -| AC-03 | OA 关联 | 每条记录能够取得发票号和销货单号,并正确命名 PDF | -| AC-04 | ERP PO | 按 invoice 反查 PO,每个 PO 生成独立 PDF | -| AC-05 | 文件归档 | 同一 invoice 的文件全部进入同一目录,不同 invoice 不混放 | -| AC-06 | 异常继续 | 单个文件失败不影响其它文件和其它 invoice 继续处理 | -| AC-07 | 结果完整 | Excel 同时包含成功、缺失和失败记录 | -| AC-08 | 信息可追溯 | Excel 能够追溯来源路径、归档路径和失败原因 | +6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 反查与打印、OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 +7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。 ## 9. 待补充事项 -| 待确认项 | 负责补充内容 | -| ---------------------- | ---------------------------------------------------------- | -| 销售 invoice 清单来源 | ERP 查询入口、字段和筛选条件 | -| 各固定目录扫描路径 | 服务器/共享盘路径、访问方式和权限 | -| 各固定目录实际目录名称 | 年月目录层级及命名格式 | -| ERP PO 查询规则 | 查询字段、关联字段、账套和日期条件 | -| ERP 打印方式 | 页面入口、打印范围、分页和 PDF 保存方式 | -| OA 自动化细节 | 登录方式、分页方式、详情打开方式和打印接口 | -| 归档根路径 | 测试、生产环境的实际路径 | -| 重复执行规则 | 已归档文件的覆盖、跳过或版本保留策略 | -| 企业微信通知 | 缺失文件必须发送企业微信;待确认接收人、通知频率和通知模板 | +| 待确认项 | 当前结论 | 仍缺什么 | +| --- | --- | --- | +| 销售 invoice 清单 | **已确认**:HXJM `apa_file.apa08/apa09`,期间为上一个月 | 无 | +| ERP 反查 PO 并打印 | **待确认** | 查询字段、关联、打印入口、PDF 保存 | +| OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 | +| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy` | 无 | +| 企微接收人 | **已确认产品**:界面从系统用户多选;人可以后配 | 业务最终勾选哪些人 | +| 周任务 | **已确认**:每周二(默认 06:00 上海时区) | 无 | +| 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 | +| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 已有相同文件名则不覆盖,记已归档 | diff --git a/docs/features/accounting-voucher-check/dify-chatflow-draft.md b/docs/features/accounting-voucher-check/dify-chatflow-draft.md index d9015899..dd1eab8b 100644 --- a/docs/features/accounting-voucher-check/dify-chatflow-draft.md +++ b/docs/features/accounting-voucher-check/dify-chatflow-draft.md @@ -1,8 +1,9 @@ # 立账凭证检核 — Dify Chatflow 编排草稿 > **状态**:草稿(待 Dify 画布落地) +> **口径**:本文对应仓库内**旧引擎** Tool(当月共享盘存在性、`mode`/`invoice_no`)。销售一期按 Profile、上一个月、批次汇总通知改造后,须重编意图与 Tool,不得把本文当作新方案编排手册。 > **前提**:HXOPS Tool / 工作台 API 已就绪;本文件只约定意图 → Tool 映射与节点配置,不参与文件是否齐全的判定。 -> **参考**:文件检核 Chatflow 手册 [../file-check/technical.md](../file-check/technical.md) 第二部分;技术设计 [technical-design.md](technical-design.md) §12。 +> **参考**:文件检核 Chatflow 手册 [../file-check/technical.md](../file-check/technical.md) 第二部分;新方案设计 [technical-design.md](technical-design.md)。 --- diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index 9141466a..dee56e56 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -1,8 +1,11 @@ -# 立账凭证检核 — 迁移与部署验收清单 +# 立账凭证检核 — 当前代码(旧实现)部署验收清单 +> **不是**销售一期新需求的验收清单。本文只覆盖仓库内现有实现:当前自然月、HXJM `apa_file` 发票清单、共享盘固定文件名存在性(核价单/采购单)。 +> +> 产品需求与目标设计见 [demand.md](demand.md)、[technical-design.md](technical-design.md)。按新方案上线前须重写本文。 +> > 适用环境:dev / test / prod -> 前置文档:[technical.md](technical.md) · [technical-design.md](technical-design.md) -> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通日批/手动触发并看到进度与记录。 +> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通**旧实现**日批/手动触发并看到进度与记录。 ## 0. 变更摘要(上线前确认) diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index a2c789f9..4321baf5 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -1,9 +1,11 @@ # 立账凭证资料检核技术设计 -> 文档版本:v2.0 -> 更新时间:2026-08-18 -> 状态:目标设计,销售一期待实施;替代旧版“当月 + 单一共享盘 + 固定文件名”方案 +> 文档版本:v2.2 +> 更新时间:2026-09-04 +> 状态:目标设计,销售一期待实施 > 需求基线:[demand.md](demand.md) +> +> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。现有 `voucher_check` 代码见 §11,不得按旧口径扩展。 ## 1. 设计目标 @@ -13,7 +15,7 @@ | ------------ | ------------------------------------------------------------------------------------------------- | | 支持多业务方 | 新业务方优先新增 Profile,不在通用流程中增加销售/采购分支 | | 支持多来源 | 新文件来源通过 Adapter 接入,不将查询、打印、目录扫描逻辑写死在引擎中 | -| 支持周度增量 | 每周处理上一个自然月;以 `invoice + 文件规则` 的来源指纹和结果判断是否跳过 | +| 支持周度增量 | **每周二**处理上一个自然月;以 `invoice + 文件规则` 的来源指纹和结果判断是否跳过 | | 可审计 | 保存批次、单文件结果、归档结果、缺件汇总、通知状态与配置快照 | | 可汇总 | 明确区分缺件文件总数和缺件 `invoice` 数;通知 Excel 以 `invoice` 为行、以文件规则为动态状态列 | @@ -21,7 +23,7 @@ ```mermaid flowchart LR - Scheduler[周度排程 / 手动触发] --> Period[上月期间计算] + Scheduler[每周二排程 / 手动触发] --> Period[上月期间计算] Period --> Profile[加载已发布 Profile 快照] Profile --> Subjects[主体清单 Adapter] Profile --> Rules[文件规则] @@ -56,7 +58,7 @@ business_profiles/ | 配置项 | 说明 | | -------------------------------------- | ------------------------------------------------------------------------ | | `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | -| `subject_adapter` | 获取本期 `invoice` 主体清单的 Adapter 和参数 | +| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `apa_file`(`apa08`/`apa09`),期间为上一个月 | | `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | | `notification` | 企业微信接收人、启用开关、模板、去重策略 | | `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | @@ -67,8 +69,8 @@ business_profiles/ | -------------------------- | -------------------------------- | -------------------------------- | | `subject_adapter` | 获取期间内应检主体及关联信息 | `invoice`、主体属性、来源指纹 | | `erp_print_adapter` | 查询业务单据并打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `oa_report_adapter` | 按 OA 报表条件查询、逐条打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `directory_scan_adapter` | 扫描目录并匹配命名模板 | 匹配文件、扫描路径、来源指纹 | +| `oa_report_adapter` | 一期模拟 OA 页面查询并打印 PDF;预留新 OA 接口 | 文件临时路径、关联字段、来源指纹 | +| `directory_scan_adapter` | 扫描文档库类型目录并匹配命名模板(复用现网 DMS 登录与 Page 接口) | 匹配文件、扫描路径、来源指纹 | | `cloud_drive_adapter` | 按接口检索和下载文件 | 文件临时路径、关联字段、来源指纹 | Adapter 不负责归档、Excel 或通知;引擎不理解 ERP/OA 的具体页面、SQL、目录规则。 @@ -86,7 +88,7 @@ flowchart TD F -- 否 --> H[调用来源 Adapter 获取文件] H --> I[校验 invoice 关联、命名和必填字段] I --> J{成功取得文件?} - J -- 是 --> K[复制至 invoice 归档目录] + J -- 是 --> K[写入类型目录并复制到所有归档/invoice] J -- 否,业务未找到 --> L[写入缺件] J -- 否,技术异常 --> M[写入技术失败] K --> N[写入已归档] @@ -95,149 +97,6 @@ flowchart TD M --> O N --> O O --> P[生成 Excel 与企业微信通知] -======= -# 立账凭证检核通用引擎技术设计 - -> 文档版本:v2.0 -> -> 更新时间:2026-08-14 -> -> 状态:重构设计,待研发评审 -> -> 需求基线:[demand.md](demand.md) -> -> 技术规格:[technical.md](technical.md) - -## 1. 设计目标 - -当前 `voucher_check` 实现按“单一 HXJM 账套、单一共享根目录、固定文件名、invoice 一票一状态”组织,无法覆盖销售和采购的多来源、多文件、多实例场景。 - -本次改造建立通用 `document_check` 引擎: - -- 以 `profile_code` 隔离销售、采购及后续业务方。 -- 以 `DocumentRule` 描述每种文件的业务规则。 -- 以 `SourceAdapter` 封装 ERP、OA、固定目录和其它系统差异。 -- 以 `CheckItem` 保存一个主体下一个文件规则实例的结果。 -- 复用现有排程、异步批次、Excel 下载、权限和企业微信基础能力。 - -## 2. 总体组件 - -```mermaid -flowchart LR - Schedule[ScheduleTask / 手动API] --> RunService[CheckRunService] - RunService --> ProfileRegistry[ProfileRegistry] - RunService --> SubjectLoader[SubjectLoaderRegistry] - RunService --> RuleExecutor[RuleExecutor] - RuleExecutor --> AdapterRegistry[SourceAdapterRegistry] - AdapterRegistry --> Directory[DirectoryScanAdapter] - AdapterRegistry --> ERP[ErpQueryPrintAdapter] - AdapterRegistry --> OAReport[OAReportPrintAdapter] - AdapterRegistry --> OARelation[OARelationPrintAdapter] - AdapterRegistry --> Upload[UploadDirectoryAdapter] - AdapterRegistry --> Payment[PaymentDownloadAdapter] - RuleExecutor --> Archive[ArchiveService] - RuleExecutor --> Repository[CheckRepository] - Repository --> Excel[ExcelExporter] - Repository --> Notify[WeComNotificationService] -``` - -## 3. 代码目录 - -```text -backend/app/ -├── domains/document_check/ -│ ├── profiles/ -│ │ ├── registry.py -│ │ ├── schema.py -│ │ ├── loader.py -│ │ ├── sales.yaml -│ │ └── procurement.yaml -│ ├── engine/ -│ │ ├── context.py -│ │ ├── run_service.py -│ │ ├── incremental_service.py -│ │ ├── subject_loader.py -│ │ ├── rule_executor.py -│ │ └── result_aggregator.py -│ ├── sources/ -│ │ ├── base.py -│ │ ├── models.py -│ │ ├── registry.py -│ │ ├── directory_scan.py -│ │ ├── erp_query_print.py -│ │ ├── oa_report_print.py -│ │ ├── oa_relation_print.py -│ │ ├── upload_directory_scan.py -│ │ └── payment_download.py -│ ├── archive/ -│ │ ├── archive_service.py -│ │ ├── path_renderer.py -│ │ └── fingerprint.py -│ ├── persistence/ -│ │ ├── models.py -│ │ └── repository.py -│ ├── exporters/ -│ │ └── excel_exporter.py -│ └── notifications/ -│ └── wecom.py -├── api/ -│ ├── document_check.py -│ └── workspace_document_check.py -└── schedule/ - └── document_check_job.py - -frontend/src/features/document-check/ -├── api/document-check.api.ts -├── composables/useDocumentCheckRuns.ts -├── views/DocumentCheckPage.vue -├── components/CheckProgressCard.vue -├── components/CheckResultTable.vue -└── components/MissingFilesPanel.vue -``` - -## 4. Profile Schema - -Profile 建议首期使用仓库内版本化 YAML/JSON,避免在业务规则尚未稳定时直接引入复杂管理后台。后续可把同一 Schema 存入数据库。 - -```yaml -code: sales -name: 销售立账凭证 -version: 2026-08-14.1 -enabled: true -subject_loader: - type: erp_invoice - config: - scope_code: HXJM - date_field: invoice_date -period_policy: - type: previous_month -archive_policy: - root_env: DOCUMENT_CHECK_ARCHIVE_ROOT - template: "{root}/{YYYY}/{MM}/{invoice_no}/" -incremental_policy: - enabled: true - fingerprint_fields: [name, size, mtime_ns] - retry_statuses: [missing, query_failed, print_failed, copy_failed] -notification_policy: - missing_enabled: true - recipient_keys: [] - dedup_scope: invoice_period -documents: - - code: shipping_release - name: 销货放行申请单 - required: true - source_type: oa_report_print - source_config: - report_name: 销货放行单 - filters: - application_date: previous_month - process_status: 归档 - scope_code: HXJM - invoice_no: not_empty - filename_template: "{invoice_no}-{shipment_no}.pdf" - relation_keys: [invoice_no, shipment_no] - incomplete_relation_policy: skip ->>>>>>> Stashed changes ``` ### 4.1 增量判定 @@ -252,15 +111,18 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ## 5. 归档与结果模型 -### 5.1 归档规则 +### 5.1 存放与归档规则 -文件先放入临时目录,完成 `invoice` 关联、命名和文件完整性校验后,复制到: +销售开票附件在文档库中分两步落盘(路径以销售 Profile 配置,默认与文档库现状一致): ```text -{archive_root}/{yyyy}/{MM}/{invoice}/ +存放:文档库/销售开票附件/{yyyy}/{MM}/{类型目录}/ +归档:文档库/销售开票附件/{yyyy}/{MM}/所有归档/{invoice}/ ``` -同一 `invoice` 的所有成功资料必须集中在同一目录。复制失败属于技术失败,不可降级为缺件。 +类型目录与一期文件对应(**已确认固定,不改名**):`PO订单`、`报关资料`、`销货单`(销货放行申请单)、`发票`、`报关单`、`提单`。库中同级的 `付款回单`、`送货单` 一期不检核。 + +ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。 ### 5.2 建议持久化实体 @@ -274,6 +136,8 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 `voucher_check_file_results` 是缺件统计和 Excel 明细的真相源;不得仅保存 `invoice` 级结论,否则无法正确统计同一 `invoice` 的多个缺件。 +现有表 `voucher_check_invoice_states` / `voucher_check_run_items` 是旧实现的一票一状态模型,迁移时由上述单文件结果表替代,不得继续扩展旧表语义。 + ## 6. 批量缺件统计 ### 6.1 统计口径 @@ -294,7 +158,7 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ### 6.2 通知聚合 -通知以 `run_id` 聚合:一个检核批次仅生成一条企业微信汇总消息,展示业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数和主要缺失文件类型,并提供该批 Excel 下载入口。消息正文不得逐票展开全部 `invoice` 或缺失文件;完整清单由 Excel 和执行记录承载。未配置接收人时不发送空消息,保存未发送原因。技术失败进入独立运维告警,不混入缺件通知。 +通知以 `run_id` 聚合:一个检核批次仅生成一条企业微信汇总消息。接收人由任务配置界面从系统用户多选(须已绑定企微);未配置则不发送并记录原因。技术失败进入独立运维告警,不混入缺件通知。 ### 6.3 检核任务列表 @@ -337,18 +201,19 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 ## 9. 实施顺序 -1. 建立 Profile、文件规则、批次、单文件结果和通知审计模型,并提供销售 Profile 配置。 -2. 实现通用期间计算、增量决策、归档器、统计聚合器和 Excel 生成器。 -3. 接入销售主体、OA 销货放行申请单、ERP PO 和目录扫描 Adapter;路径/ERP 条件确认后发布。 -4. 接入企业微信通知和执行记录工作台。 -5. 采购通过新增 Profile 和 Adapter 参数接入;新来源系统再新增 Adapter。 +1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表。 +2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。 +3. **已预留**:`erp_po_print`、`oa_sales_release` Adapter,周任务不调用。 +4. 接入 ERP PO 打印与 OA 模拟页,作为独立抓取任务写入类型目录。 +5. 采购通过新增 Profile 和 Adapter 参数接入。 ## 10. 验收重点 - 一次批次中多个 `invoice` 缺件、且单个 `invoice` 缺多个文件时,两个缺件指标均正确。 - Excel 报告以“资料所属期间”筛选,顶部单独展示“执行时间”;每个 `invoice` 一行,动态文件列与 Profile 必检规则一致;所有文件列均为“有”时状态为“完整”。 - 企业微信每批发送一条汇总通知并提供 Excel 下载入口;完整 `invoice` 明细仅在 Excel 和执行记录中查看。 -- 周度任务仅处理上一个自然月;增量、强制重检和跨年期间计算正确。 +- 每周二任务仅处理上一个自然月;增量、强制重检和跨年期间计算正确。 +- 企微接收人可从系统用户配置;未配置不发空通知。 - 新增采购或其它业务方无需修改通用检核、汇总、Excel 和通知逻辑。 - Profile 加载后必须生成不可变快照,批次全程使用同一版本。 - `source_type` 必须在 Adapter Registry 注册。 @@ -356,297 +221,21 @@ OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状 - 配置错误在批次开始前失败,不产生批量业务缺失结果。 - 密码、Token、Cookie 不允许出现在 Profile 文件、数据库 JSON、Excel 或日志中。 -## 5. 核心接口 +## 11. 现有代码(旧实现)与迁移 -### 5.1 检核上下文 +当前 `backend/app/services/voucher_check/` 仍按旧模型运行,**不是**本期设计的实现: -```python -@dataclass(frozen=True) -class CheckContext: - profile_code: str - profile_version: str - period_month: date - run_id: int - mode: str - temp_root: Path - archive_root: Path -``` +| 旧实现 | 本期设计 | +| --- | --- | +| 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** | +| HXJM `apa_file.apa08/apa09` 拉发票清单 | **沿用该口径**,仅把期间改为上一个月 | +| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从 ERP/OA/固定目录**获取**,先写入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | +| 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 | +| 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel | -### 5.2 检核主体 +迁移约束: -```python -@dataclass(frozen=True) -class CheckSubject: - subject_type: str - subject_key: str - invoice_no: str | None - relation_values: dict[str, str] - source_metadata: dict[str, Any] -``` - -`relation_values` 用于保存 `shipment_no`、`po_no`、`delivery_no` 等业务关联字段;禁止把不同业务方字段硬编码到统一表列中。 - -### 5.3 来源 Adapter - -```python -class SourceAdapter(Protocol): - source_type: str - - def fetch( - self, - context: CheckContext, - rule: DocumentRule, - subject: CheckSubject, - ) -> list[ArtifactCandidate]: - """返回候选文件;不得写最终归档目录。""" -``` - -Adapter 返回的 `ArtifactCandidate`: - -```python -@dataclass(frozen=True) -class ArtifactCandidate: - artifact_key: str - filename: str | None - temporary_path: Path | None - source_path: str | None - relation_values: dict[str, str] - fingerprint: str | None - status: str - error_code: str | None = None - error_message: str | None = None -``` - -Adapter 只负责查询/下载/打印和返回候选文件;命名校验、归档、落库由通用引擎负责。 - -### 5.4 Profile Registry - -```python -class ProfileRegistry(Protocol): - def get(self, profile_code: str, version: str | None = None) -> ProfileSnapshot: - ... - - def list_enabled(self) -> list[ProfileSummary]: - ... -``` - -## 6. 执行编排 - -### 6.1 主流程 - -```python -def run_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - profile = profile_registry.get(run.profile_code) - context = build_context(profile, run) - subjects = subject_loader_registry.load(context, profile.subject_loader) - - for subject in subjects: - for rule in profile.documents: - if incremental_service.can_skip(context, subject, rule): - repository.save_skipped(context, subject, rule) - continue - candidates = adapter_registry.get(rule.source_type).fetch(context, rule, subject) - items = rule_executor.evaluate(context, subject, rule, candidates) - repository.save_items(items) - - archive_service.finalize(context) - excel_exporter.export(context) - notification_service.notify_missing(context) - return result_aggregator.to_schedule_result(context) -``` - -### 6.2 Adapter 结果统一化 - -| Adapter 状态 | 统一结果 | 说明 | -| ---------------------- | -------------------------------------- | --------------------------------------------- | -| 找到候选文件 | `found` | 尚未完成归档 | -| 找不到业务文件 | `missing` | 正常业务缺件 | -| 查询无记录 | `missing` | 由 Profile 指定是否为必缺 | -| 外部系统超时/登录失败 | `query_failed` | 技术失败,可重试 | -| 打印或保存 PDF 失败 | `print_failed` | 技术失败,可重试 | -| 文件名或关联字段不完整 | 由 `incomplete_relation_policy` 决定 | `skip` 不生成检核项;其它策略可记录处理失败 | -| 复制归档失败 | `copy_failed` | 保留源、目标和错误信息 | - -## 7. 持久化设计 - -建议新增或改造以下表。最终字段以模型评审和迁移脚本为准。 - -### 7.1 `document_check_profiles` - -| 字段 | 说明 | -| ------------------------------- | ------------------ | -| `code` | Profile 编码,唯一 | -| `name` | 业务方名称 | -| `version` | 配置版本 | -| `config_json` | 非敏感配置快照 | -| `enabled` | 是否启用 | -| `created_at` / `updated_at` | 审计时间 | - -### 7.2 `document_check_runs` - -| 字段 | 说明 | -| -------------------------------------- | ------------------------------------------- | -| `id` | 批次 ID | -| `profile_code` / `profile_version` | 本批次使用的 Profile | -| `period_month` | 检核月份 | -| `mode` | incremental / force_all / single | -| `status` | running / success / partial_failed / failed | -| `summary_json` | 统计和阶段信息 | -| `excel_file_*` | 复用现有下载字段或关联文件资产 | - -### 7.3 `document_check_subjects` - -保存本批次主体快照,避免外部系统后续变化导致历史结果无法解释。 - -### 7.4 `document_check_items` - -建议唯一约束: - -```text -(profile_code, period_month, subject_key, rule_code, artifact_key) -``` - -保存期望文件、来源类型、实际关联字段、状态、错误、指纹和最后成功批次。 - -### 7.5 `document_check_artifacts` - -保存来源、临时文件、归档文件和指纹。文件路径字段必须经过脱敏展示策略,避免把敏感 UNC 凭据写入前端或通知。 - -### 7.6 `document_check_notifications` - -保存 `dedup_key`、接收人、通知内容摘要、发送状态和失败原因,支撑每周增量重复通知控制。 - -## 8. 增量与幂等 - -### 8.1 跳过条件 - -只有同时满足以下条件才允许跳过: - -- 上次文件状态为 `archived`。 -- Profile 版本一致。 -- 文件规则版本或模板指纹一致。 -- 来源指纹一致。 -- 归档目标仍存在且指纹一致。 - -### 8.2 重试条件 - -以下状态每周自动重试: - -```text -missing / query_failed / print_failed / copy_failed / technical_error -``` - -缺件不阻断其它主体;批次只有在配置、数据库或核心基础设施故障时才进入批次失败。 - -### 8.3 外部操作幂等 - -- OA/ERP 打印前根据 `artifact_key` 检查当前批次临时文件,避免重复打印。 -- 归档目标相同指纹时直接复用。 -- 目标存在但指纹不同,按 Profile 的 `overwrite_policy` 处理:默认保留原文件并记录版本,禁止静默覆盖。 -- 同一批次并发启动使用现有 ScheduleRun 锁,同时 Profile 维度增加 running 检查。 - -## 9. API 与兼容层 - -### 9.1 新 API - -```text -POST /api/document-check/runs -GET /api/document-check/runs/{run_id} -GET /api/document-check/runs/{run_id}/items -GET /api/document-check/runs/{run_id}/excel -GET /api/document-check/missing -GET /api/document-check/profiles -``` - -启动请求: - -```json -{ - "profile_code": "sales", - "mode": "incremental", - "period": "2026-07" -} -``` - -### 9.2 错误契约 - -继续使用 `{success, data | error, request_id}` envelope;业务错误使用 `AppError` 子类。建议新增: - -| 错误码 | 含义 | -| -------------------------------------- | ----------------------------- | -| `DOCUMENT_CHECK.PROFILE_NOT_FOUND` | Profile 不存在或未启用 | -| `DOCUMENT_CHECK.PROFILE_INVALID` | Profile 校验失败 | -| `DOCUMENT_CHECK.ADAPTER_NOT_FOUND` | 来源 Adapter 未注册 | -| `DOCUMENT_CHECK.SOURCE_UNAVAILABLE` | 外部来源不可用 | -| `DOCUMENT_CHECK.ARCHIVE_UNAVAILABLE` | 归档路径不可用 | -| `DOCUMENT_CHECK.RUN_ALREADY_RUNNING` | 同 Profile 和期间已有运行批次 | - -新增错误码需要同步四语言 `locales/*/errors.json`。 - -### 9.3 旧接口兼容 - -现有 `/api/accounting-voucher-check/*` 和 `/api/file-check/tools/tasks/run` 在迁移期间保留: - -- 旧入口默认映射 `profile_code=sales`。 -- 旧的 `invoice_no` 参数映射为 `subject_key`。 -- 旧查询结果转换为通用 `CheckItem` 视图。 -- 销售迁移验证完成后,再评估下线旧接口。 - -## 10. 前端与通知 - -- 工作台页面改为读取 Profile 名称和 DocumentRule 元数据,不写死采购单、核价单等文件名称。 -- 结果表以 `document_type`、`status`、`business_no` 和 `archive_path` 为通用列。 -- 每周增量进度展示主体总数、文件规则总数、已处理、跳过、缺失和技术失败。 -- 企业微信缺件通知按 invoice 合并,接收人从 Profile 的通知配置解析;接收人待定时显示未发送原因。 -- 文件缺失和技术失败分开展示,不能把 OA 登录失败显示为缺件。 - -## 11. 测试设计 - -### 11.1 单元测试 - -- Profile Schema 校验、版本快照和非法模板。 -- Adapter Registry 注册、未知类型和参数校验。 -- 文件名、路径和关联字段渲染。 -- 多实例 `artifact_key` 生成和重复去重。 -- 增量跳过、失败重试、Profile 版本变化和归档指纹变化。 - -### 11.2 Adapter 合约测试 - -每个 Adapter 统一覆盖: - -- 成功返回候选文件。 -- 业务无记录返回 `missing`。 -- 外部系统异常返回明确技术状态。 -- 临时文件隔离和失败清理。 -- 重试不产生重复业务实例。 - -### 11.3 集成测试 - -- 销售 Profile 混合 OA、ERP 和固定目录来源。 -- 采购 Profile 混合固定目录、OA 关联和付款下载来源。 -- 同一 invoice 多个 PO/送货单归档不互相覆盖。 -- 一条文件缺失时其它文件继续处理并触发企业微信通知。 -- 接收人未配置时不调用发送接口但保留审计记录。 - -## 12. 实施顺序 - -1. 定义 Profile Schema、Adapter 契约和通用状态枚举。 -2. 新增通用 Profile/Adapter Registry 和配置校验。 -3. 新增单文件级数据模型及迁移脚本。 -4. 把现有共享盘扫描封装为 `directory_scan` Adapter。 -5. 建立销售 Profile,完成销售回归和旧接口兼容。 -6. 接入 OA/ERP Adapter,补齐销售打印流程。 -7. 建立采购 Profile,接入采购所需来源。 -8. 迁移 Excel、企业微信通知和工作台查询到通用 API。 -9. 运行新旧结果对比,确认无误后下线旧单票专用逻辑。 - -## 13. 风险与控制 - -| 风险 | 控制措施 | -| ---------------------------- | -------------------------------------------------- | -| Profile 配置错误导致大批缺件 | 启动前 Schema 校验、Profile 版本和小范围试运行 | -| OA/ERP 打印不稳定 | Adapter 超时、重试、临时目录和可恢复状态 | -| 多文件实例覆盖 | `artifact_key` 唯一键和默认不覆盖策略 | -| 缺件通知重复 | `dedup_key` 按 Profile、期间、invoice 和规则生成 | -| 旧接口改造影响现有 Agent | 保留兼容层,内部映射到销售 Profile | -| 敏感路径和账号泄露 | 凭据仅 env/secret,日志和 Excel 脱敏 | +- 旧入口 `/api/accounting-voucher-check/*` 与 `POST /api/file-check/tools/tasks/run` 在销售迁移期保留,内部映射 `profile_code=sales`。 +- 现有共享盘扫描可收成 `directory_scan` Adapter,不得继续作为唯一检核路径。 +- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。 +- 部署与冒烟清单 [ops-checklist.md](ops-checklist.md)、Chatflow 草稿 [dify-chatflow-draft.md](dify-chatflow-draft.md) 仅描述旧引擎,迁移后需重写。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index 502e839b..9816ad8f 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -1,24 +1,11 @@ -# 立账凭证检核 — 历史方案归档 - -> **已废弃**:本文记录旧版“当前自然月 + 单一共享盘 + 固定文件名”的实现方案,不再作为需求或技术设计依据。当前业务需求见 [demand.md](demand.md),新版技术设计见 [technical-design.md](technical-design.md)。 - # 立账凭证检核技术规格 ->>>>>>> Stashed changes ->>>>>>> ->>>>>> ->>>>> ->>>> ->>> ->> - -> 文档状态:重构设计基线 -> +> 文档状态:销售一期规格基线 > 适用范围:销售一期、采购二期及后续其它业务方 +> 需求基线:[demand.md](demand.md) +> 落地设计:[technical-design.md](technical-design.md) > -> 需求基线:[销售一期需求说明](demand.md) -> -> 本文描述通用实现目标。当前已有的单一共享盘实现仅作为迁移对象,不再作为新业务方扩展的结构基础。 +> 本文描述**新方案**通用实现目标。仓库内现有「当前自然月 + 单一共享盘 + 固定文件名」代码只是迁移对象,见 [ops-checklist.md](ops-checklist.md),不得作为新业务方扩展基础。 ## 1. 设计结论 @@ -105,7 +92,7 @@ Profile 是一个可版本化的业务方配置快照,至少包含: | `subject_loader` | 检核主体加载器,如 ERP invoice 清单、业务清单 | | `period_policy` | 上月周期和跨年计算规则 | | `documents` | 文件规则集合 | -| `archive_policy` | 归档根路径和目录模板 | +| `archive_policy` | 类型存放路径与「所有归档/{invoice}」模板 | | `incremental_policy` | 指纹、重试和跳过策略 | | `notification_policy` | 缺件通知开关、接收人和去重策略 | | `enabled` | 是否允许执行 | @@ -375,26 +362,29 @@ sequenceDiagram ## 8. 归档与文件安全 -默认归档模板: +默认存放与归档模板(销售文档库): ```text -{archive_root}/{YYYY}/{MM}/{invoice_no}/ +{dms_root}/销售开票附件/{YYYY}/{MM}/{类型目录}/ +{dms_root}/销售开票附件/{YYYY}/{MM}/所有归档/{invoice_no}/ ``` 要求: -- 所有生成或扫描的文件先进入任务隔离的临时目录,再校验关联字段和命名后归档。 -- 同一 invoice 的所有文件进入同一目录;不同 invoice 不得混放。 -- 复制采用幂等策略,目标文件相同指纹时跳过,指纹不同按 Profile 的覆盖策略处理。 +- ERP/OA 打印或目录扫描的成功文件先写入当月类型存放目录,再校验关联字段和命名后复制到「所有归档/{invoice_no}/」。 +- 同一 invoice 的所有文件进入同一归档子目录;不同 invoice 不得混放。 +- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。归档只 `Copy`、不 `Move`。 - `invoice_no`、业务单号和路径变量必须做路径穿越校验。 - 临时目录和日志不得输出密码、Token 或完整外部系统会话信息。 - 归档记录保存来源路径、临时路径、归档路径、指纹、Profile 版本和处理时间。 ## 9. Excel 与企业微信通知 -### 9.1 Excel +执行记录可按「一个 invoice + 一种文件类型 + 一个实际文件」保留明细。企业微信通知附件 Excel **不**使用该明细表结构,口径见 [demand.md](demand.md) §7:一张「检核结果」工作表,一行一个 `invoice`,按 Profile 动态展开「有 / 缺件 / 未检核」。 -一批次生成一个统一 Excel,记录粒度为“主体 + 文件规则 + 文件实例”: +### 9.1 执行记录字段(审计用,不是企微附件) + +一批次的执行记录粒度为“主体 + 文件规则 + 文件实例”: | 字段 | 说明 | | --------------------- | ---------------------------- | @@ -416,11 +406,11 @@ sequenceDiagram ### 9.2 缺件企业微信通知 -- 任一必检文件状态为 `missing` 时发送企业微信通知。 -- 同一 invoice 的多个缺件合并通知。 -- 通知至少包含业务方、检核月份、invoice 号、缺失文件和批次号。 -- 接收人、通知模板、发送频率和去重规则由 Profile 的 `notification_policy` 管理。 -- 当前业务接收人待定,未配置接收人时必须在批次日志和 Excel 中保留“未发送原因”。 +- 本批存在必检文件缺件时发送企业微信。 +- **一个检核批次只发一条汇总通知**,不在消息正文逐票展开缺失明细。 +- 通知至少包含业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型和本批 Excel 下载入口。 +- 完整 `invoice` 与缺失文件清单以企微附件 Excel 和执行记录为准。 +- 接收人、通知模板由 Profile 的 `notification_policy` 管理;未配置接收人时不发送空通知,并在批次日志和 Excel 中保留未发送原因。 - 技术失败使用独立失败告警,不应伪装成业务缺件。 ## 10. API、任务和前端影响 @@ -517,7 +507,7 @@ backend/app/domains/document_check/ - 固定目录命中、缺失、路径不可用和大小写规则。 - ERP/OA 查询成功、无结果、超时、登录失败和分页。 - ERP/OA 每个业务单生成独立 PDF,正确返回 invoice 和业务单关联字段。 -- Adapter 重试不产生重复归档文件。 +- Adapter 重试不产生重复归档文件:目标已有同名则跳过复制。 ### 12.3 增量与归档 @@ -528,21 +518,21 @@ backend/app/domains/document_check/ ### 12.4 结果与通知 -- Excel 同时包含成功、跳过、缺失和技术失败记录。 -- 同一 invoice 多个缺件合并企业微信通知。 -- 接收人未配置时不发送空通知,并记录明确原因。 +- 企微附件 Excel 一行一个 `invoice`,动态文件列为「有 / 缺件 / 未检核」;执行记录可另存单文件明细。 +- 同一批次多个 `invoice` 缺件、同一 `invoice` 缺多个文件时,缺件文件总数累计、缺件 `invoice` 数去重。 +- 企业微信每批一条汇总通知,提供 Excel 下载入口;接收人未配置时不发送空通知,并记录明确原因。 - 批次级技术故障不批量伪装成缺件。 ## 13. 待确认事项 | 事项 | 当前状态 | | -------------------------------- | ------------------------------------------------ | -| 销售各固定目录路径 | 待确认 | +| 销售开票附件文档库路径 | 已确认固定:`销售开票附件/{年}/{月}/{类型目录}`,类型目录为 `PO订单`/`报关资料`/`销货单`/`发票`/`报关单`/`提单`,归档 `所有归档/{invoice}` | | 采购各固定目录路径 | 待确认 | -| 销售 invoice 主体来源与 ERP 字段 | 待确认/需适配现有来源 | +| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `apa_file` `apa08`/`apa09`,期间上一个月 | | 采购 invoice 主体来源 | 待确认 | -| ERP PO 查询字段与打印方式 | 待确认 | -| OA 登录、报表分页和打印接口 | 待确认 | -| 归档根路径及重复文件策略 | 待确认 | -| 企业微信通知接收人、模板和频率 | 待确认 | +| ERP PO 查询字段与打印方式 | **待确认** | +| OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 | +| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy`;同名跳过 | +| 企业微信通知接收人、模板和频率 | 界面从系统用户多选;每周二;具体人选可后配 | | Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 | diff --git a/docs/features/faq/faq_cache_ops_manual.md b/docs/features/faq/faq_cache_ops_manual.md index 58d078c1..451b8792 100644 --- a/docs/features/faq/faq_cache_ops_manual.md +++ b/docs/features/faq/faq_cache_ops_manual.md @@ -64,7 +64,7 @@ flowchart TD A[用户发消息 chat.py] --> B{有附件?} B -->|是| Z[跳过 FAQ,走业务路由] B -->|否| C[FaqCacheService.try_match] - C --> D{agent 全局 FAQ
cache_enabled=true
is_enabled=true
stale_at 为空
未过期?} + C --> D{agent 全局 FAQ
cache_enabled=true
stale_at 为空
未过期?} D -->|否| E[未命中 → Dify 等] D -->|是| F{归一化问句匹配
question / title / aliases?} F -->|否| E @@ -283,6 +283,7 @@ FAQ_HOT_BAD_SCORE=2 | --- | --- | | 新建/编辑 | 填写 question、answer、aliases;开启「启用缓存」 | | 关闭缓存 | `cache_enabled=false` 后不再在线命中,但不删 ChatLog | +| 关闭前台展示 | `is_enabled=false` 后工作台首页不显示快捷入口,**不影响** FAQ 缓存命中 | | 设置过期 | `expires_at` 到期后 `try_match` 自动跳过 | | 查看命中 | 列表字段 `hit_count` | diff --git a/docs/funclist.md b/docs/funclist.md index 84dd399d..23c10842 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -198,22 +198,14 @@ ### 立账凭证检核(accounting-voucher-check) -| 功能项 | 状态 | 说明 | -| -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| | | | -| 需求、规格与技术设计 | 需求更新中 | [需求说明](features/accounting-voucher-check/demand.md) · [技术设计](features/accounting-voucher-check/technical-design.md);销售一期每周增量检核上月,按 Profile 从 ERP、OA、目录等来源获取并归档资料,采购二期待配置 | -| 共享盘文件存在性检核 | 已实现 | platform Job `accounting-voucher-check`;默认 `vouche/{YYYY}/{MM}/{invoice_no}/`;暂定必检「核价单.pdf」「采购单.pdf」;不读内容、不用 LLM | -| 增量批次与异常告警 | 已实现 | 齐全且目录元数据指纹未变更可跳过;共享盘不可用整批失败并告警;缺资料企微 textcard(同票同日节流) | -| 日批排程 | 已实现 | 预置 `SCH-ACCOUNTING-VOUCHER-CHECK`,Cron `0 6 * * *`(Asia/Shanghai) | -| Tool / 工作台查询 | 已实现 | 启动复用 `/api/file-check/tools/tasks/run` + `run_options`;查询 `/api/accounting-voucher-check/tools/*`;工作台 `/workspace/accounting-voucher-check` 仅管理员可见和访问 | -| Dify Chatflow 编排 | 待完成 | Tool API 已就绪,Chatflow 意图映射与部署手册另开 | - -| 销售一期需求、规格与技术设计 | 已文档化 | [销售一期需求](features/accounting-voucher-check/demand.md) · [技术规格](features/accounting-voucher-check/technical.md) · [技术设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个自然月 | -| 通用 Profile + Adapter 架构 | 待实施 | `document_check` 通用引擎加载销售、采购及后续业务方 Profile;文件规则决定来源、命名、路径和归档,Adapter 封装 ERP、OA、固定目录等差异 | -| 单一共享盘旧检核 | 已实现,待迁移 | platform Job `accounting-voucher-check`;当前月 `vouche/{YYYY}/{MM}/{invoice_no}/` 和固定必检文件的旧模型,仅作为销售 Profile 迁移参考 | -| 增量、归档与缺件通知 | 待重构 | 单文件级指纹和状态支持每周增量;同 invoice 集中归档;缺失必检文件发送企业微信,接收人待确认 | -| Tool / 工作台查询 | 已实现,待兼容迁移 | 现有 `/api/accounting-voucher-check/tools/*` 和工作台保留兼容;新通用 API 按 `profile_code` 提供批次和明细查询 | -| Dify Chatflow 编排 | 待完成 | 迁移后按 `profile_code` 发起和查询;旧 Tool 映射在销售迁移期保留 | +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月,按 Profile 从 ERP、OA、目录获取并归档 | +| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;ERP PO / OA 销货放行单打印仅占位 | +| 单一共享盘旧检核 | 已停用主路径 | 旧共享盘扫描保留模块但周任务不再调用;不得按核价单/采购单口径扩展 | +| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 | +| Tool / 工作台查询 | 实施中 | 工作台任务列表含「强制重检上月」;`/runs` 读新引擎批次;旧 states 查询保留兼容 | +| Dify Chatflow 编排 | 待完成 | 须按新口径(上月、Profile、批次汇总)编排;现有草稿仅对应旧引擎 Tool | ### 采购合同审查 diff --git a/docs/tec.md b/docs/tec.md index f3c79119..1774cd1b 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -215,10 +215,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 ### 2.x 立账凭证检核(accounting-voucher-check) - 前端路由 `/workspace/accounting-voucher-check` 标记 `requiresAdmin`,工作台侧栏按当前用户角色隐藏入口;全局路由守卫负责阻止非管理员直接访问。 -- 任务引擎从 Oracle `apa_file` 按 `apa09` 查询当前自然月 `apa08`,一期仅处理 HXJM 套账。 -- 共享盘默认路径为 `vouche/{YYYY}/{MM}/{invoice_no}/`,通过目录模板配置支持调整;必检文件名通过配置维护。 -- 扫描器只读取目录和文件元数据判断文件是否存在,不读取内容、不调用 LLM;齐全票可基于元数据指纹增量跳过。 -- 共享盘不可用时批次失败并告警,不生成缺资料结论;单票缺目录或缺必检文件才记缺资料。 +- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `apa_file`(`apa08`/`apa09`);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 +- **销售一期来源**:ERP 打印 PO(查询与打印方式待确认)、OA 销货放行单一期模拟页面(后期换新接口)、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 +- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。归档复制策略为同名跳过。 +- **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。 +- **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。 +- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。 - 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。 ### 2.x 货代发货通知批次库存能力 diff --git a/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue b/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue index e3f22929..31439e28 100644 --- a/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue +++ b/frontend/src/features/admin/modules/questions/components/QuestionFormModal.vue @@ -3,6 +3,7 @@ * 常用问题 / FAQ 缓存创建与编辑居中弹窗。 * 依赖:QuestionFormState、admin 通用 modal 样式。 * 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。 + * is_enabled 仅控制工作台首页入口;cache_enabled 单独控制聊天是否跳过 Dify。 */ diff --git a/frontend/src/features/admin/modules/wecom/pages/WecomSettingsPage.vue b/frontend/src/features/admin/modules/wecom/pages/WecomSettingsPage.vue index 0fde2862..53a262f5 100644 --- a/frontend/src/features/admin/modules/wecom/pages/WecomSettingsPage.vue +++ b/frontend/src/features/admin/modules/wecom/pages/WecomSettingsPage.vue @@ -2,11 +2,12 @@ /** * features/admin/modules/wecom/pages/WecomSettingsPage.vue * 企微系统配置、通知与集成复制。 + * 依赖:WECOM_ADMIN_KEY、lucide CircleHelp。 + * 逻辑:绑定概览卡片只在绑定管理页展示,本页仅编辑系统/通知配置。 */ import { inject } from 'vue'; import { useI18n } from 'vue-i18n'; import { CircleHelp } from 'lucide-vue-next'; -import WecomOverviewCards from '../components/WecomOverviewCards.vue'; import { WECOM_ADMIN_KEY } from '../wecom.context'; const { t } = useI18n(); @@ -28,8 +29,6 @@ const {