diff --git a/.env.shared b/.env.shared index 41ee113e..c509e996 100644 --- a/.env.shared +++ b/.env.shared @@ -53,6 +53,7 @@ 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 + CONTRACT_PAYMENT_ENABLED=true CONTRACT_PAYMENT_OA_BASE_URL=http://192.168.100.221:8888 CONTRACT_PAYMENT_OA_USERNAME=AIuser @@ -73,6 +74,17 @@ CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD=bm CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD=zz CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD=jfl +# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*) +# VOUCHER_CHECK_ERP_DSN= +# VOUCHER_CHECK_ERP_USERNAME= +# VOUCHER_CHECK_ERP_PASSWORD= + +VOUCHER_CHECK_DMS_BASE_URL=http://192.168.8.158:8071 +VOUCHER_CHECK_DMS_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8 +VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=727c3683-dcdb-4d62-a5b1-b164224162bc +VOUCHER_CHECK_DMS_USERNAME=AIuser +VOUCHER_CHECK_DMS_PASSWORD=123456 + # chat回答的评分与评论 FEEDBACK_ENABLED=true diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 833424c4..bcf4d5e7 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -41,7 +41,7 @@ def register_blueprints(app: Flask) -> None: workspace_shipping_notice_bp, workspace_voucher_check_bp, ) - from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp + from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp from app.api.files import files_bp from app.api.procurement_contract_tools import procurement_contract_bp from app.api.contract_payment import contract_payment_bp @@ -66,7 +66,6 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') app.register_blueprint(file_check_bp, url_prefix='/api/file-check') - app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check') app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context') app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') app.register_blueprint(speech_bp, url_prefix='/api/speech') diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py index dde84dcb..d05d0a1e 100644 --- a/backend/app/api/tools/__init__.py +++ b/backend/app/api/tools/__init__.py @@ -2,11 +2,10 @@ backend/app/api/tools/__init__.py 用途:Dify HTTP Tool API Blueprint 聚合。 -逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。 +逻辑:re-export shipping_notice、file_check、maintenance tools。 """ from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401 from app.api.tools.file_check import file_check_bp # noqa: F401 from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401 -from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401 -__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp'] +__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp'] diff --git a/backend/app/api/tools/voucher_check.py b/backend/app/api/tools/voucher_check.py deleted file mode 100644 index f06e6f84..00000000 --- a/backend/app/api/tools/voucher_check.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -backend/app/api/tools/voucher_check.py - -用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。 -依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。 -逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。 -""" - -from __future__ import annotations - -from flask import Blueprint, jsonify, request - -from app.core.errors import AppError -from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE -from app.services.integration_tool_auth import require_integration_tool_auth -from app.services.voucher_check import query_service -from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec - -voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__) - - -@voucher_check_tools_bp.before_request -def _verify_tool_access(): - """openapi.json 免鉴权,其余端点校验 Tool API Key。""" - if request.path.endswith("/openapi.json"): - return None - require_integration_tool_auth() - return None - - -def _tool_error(exc: AppError): - """将 AppError 映射为 Tool 非 envelope 错误体。""" - code = str(exc.code or "").lower().replace(".", "_") - message = str(exc.message or "").strip() - # 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支 - if message in {"missing_auth", "invalid_auth"}: - code = message - return jsonify({ - "ok": False, - "error_code": code, - "message": message or code, - "details": exc.details or {}, - }), exc.http_status - - -@voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"]) -def voucher_check_openapi_spec(): - """ - 返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。 - 【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。 - """ - return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) - - -@voucher_check_tools_bp.route("/tools/tasks//missing", methods=["GET"]) -def tool_list_missing(task_id: int): - """ - 查询当前月或指定月缺资料票。 - 【AI 触发时机】:用户说「查询缺资料发票」时调用。 - """ - try: - data = query_service.list_missing_states( - task_id=task_id, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - limit=request.args.get("limit", default=200, type=int) or 200, - ) - return jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) - - -@voucher_check_tools_bp.route("/tools/runs//items", methods=["GET"]) -def tool_list_run_items(run_id: int): - """ - 查询批次明细,可按 result 过滤。 - 【AI 触发时机】:用户查询某批次结果明细时调用。 - """ - try: - data = query_service.list_run_items( - run_id=run_id, - result=request.args.get("result"), - 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 jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) - - -@voucher_check_tools_bp.route("/tools/invoices//latest", methods=["GET"]) -def tool_invoice_latest(invoice_no: str): - """ - 查询指定发票最新状态。 - 【AI 触发时机】:用户询问某张发票检核结论时调用。 - """ - try: - data = query_service.get_invoice_latest( - invoice_no=invoice_no, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - ) - return jsonify({"ok": True, **data}) - except AppError as exc: - return _tool_error(exc) diff --git a/backend/app/api/workspace/voucher_check.py b/backend/app/api/workspace/voucher_check.py index 4a471c7e..4a5e8d96 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。 +逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;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,11 +25,55 @@ 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): """ 分页查看批次明细。 - 核心逻辑:委托 query_service.list_run_items,可按 result 过滤。 + 核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。 """ _require_user() data = query_service.list_run_items( @@ -41,30 +85,17 @@ def workspace_voucher_run_items(run_id: int): return ok(data) -@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"]) -def workspace_voucher_states(): +@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"]) +def workspace_voucher_notifications(): """ - 按月份、状态、发票号筛选最新状态。 + 分页查看企微缺件汇总发送记录。 + 核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。 """ _require_user() - data = query_service.list_states( - scope_code=str(request.args.get("scope_code") or "HXJM"), + data = query_service.list_notifications( period=request.args.get("period"), - status=request.args.get("status"), - invoice_no=request.args.get("invoice_no"), + send_status=request.args.get("send_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/states/", methods=["GET"]) -def workspace_voucher_state_detail(invoice_no: str): - """查看单票最近状态和历史批次快照。""" - _require_user() - data = query_service.get_invoice_latest( - invoice_no=invoice_no, - scope_code=str(request.args.get("scope_code") or "HXJM"), - period=request.args.get("period"), - ) - return ok(data) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 3cb2c071..dd00dbcb 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -216,8 +216,8 @@ class Config: # 统一改用通用 ERP 连接变量(ERP_DB_DSN / ERP_USERNAME / ERP_PASSWORD / ERP_TIMEOUT_SECONDS,已并入 env.shared), # 并保留模块级 CONTRACT_PAYMENT_ERP_* 覆盖与旧回退(VOUCHER_CHECK_ERP_*)兼容。 CONTRACT_PAYMENT_ERP_DSN = os.getenv('CONTRACT_PAYMENT_ERP_DSN') or os.getenv('ERP_DB_DSN', '') - CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') or os.getenv('VOUCHER_CHECK_ERP_USERNAME', '') - CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') or os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '') + CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') + CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30') CONTRACT_DMS_BASE_URL = os.getenv('CONTRACT_DMS_BASE_URL', '').strip().rstrip('/') CONTRACT_DMS_USERNAME = os.getenv('CONTRACT_DMS_USERNAME', '') @@ -652,17 +652,26 @@ 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) - 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( - 'VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH', - '.hxops-share-ready', - ).strip() or '.hxops-share-ready' + # 立账凭证检核:ERP 只读 + 销售开票附件文档库根目录(密码仅 env) VOUCHER_CHECK_ERP_DSN = os.getenv('VOUCHER_CHECK_ERP_DSN') or os.getenv('ERP_DB_DSN', '') - 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_ERP_USERNAME = ( + os.getenv('VOUCHER_CHECK_ERP_USERNAME') + or os.getenv('ERP_USERNAME') + or os.getenv('CONTRACT_PAYMENT_ERP_USERNAME', '') + ).strip() + VOUCHER_CHECK_ERP_PASSWORD = ( + os.getenv('VOUCHER_CHECK_ERP_PASSWORD') + or os.getenv('ERP_PASSWORD') + or os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD', '') + ) + VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int( + os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS') or os.getenv('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 b56c0043..c31278ec 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -209,7 +209,13 @@ from app.models.integration_connector import ( ) 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, + VoucherCheckNotification, + VoucherCheckProfile, + VoucherCheckRun, + VoucherCheckSubject, +) from app.models.contract_payment import ( ContractPaymentAlert, ContractPaymentAlertBatch, @@ -393,8 +399,11 @@ __all__ = [ 'ShippingInventoryCandidateSource', 'ShippingInventoryCandidateLine', '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..01a3b757 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(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。 依赖:models.base.Base、schedule_runs。 -逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。 +逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。 """ from __future__ import annotations @@ -13,7 +13,6 @@ from typing import Optional from sqlalchemy import ( BigInteger, - Boolean, Date, DateTime, ForeignKey, @@ -28,41 +27,20 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class VoucherCheckInvoiceState(Base): - """账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。""" +class VoucherCheckProfile(Base): + """已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。""" - __tablename__ = "voucher_check_invoice_states" + __tablename__ = "voucher_check_profiles" __table_args__ = ( - UniqueConstraint( - "scope_code", - "period_month", - "invoice_no", - name="uq_voucher_check_invoice_states_scope_period_invoice", - ), - Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"), - Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"), - Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"), + 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) - scope_code: Mapped[str] = mapped_column(String(32), nullable=False) - period_month: Mapped[date] = mapped_column(Date, nullable=False) - invoice_no: Mapped[str] = mapped_column(String(128), nullable=False) - invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - status: Mapped[str] = mapped_column(String(24), nullable=False) - folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) - material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - last_actual_run_id: Mapped[Optional[int]] = mapped_column( - BigInteger, - ForeignKey("schedule_runs.id", ondelete="SET NULL"), - nullable=True, - ) - last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, nullable=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, @@ -72,43 +50,131 @@ class VoucherCheckInvoiceState(Base): ) -class VoucherCheckRunItem(Base): - """单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。""" +class VoucherCheckRun(Base): + """一次检核批次;列表统计取本表快照,不在查询时重算单文件结果。""" - __tablename__ = "voucher_check_run_items" + __tablename__ = "voucher_check_runs" __table_args__ = ( - UniqueConstraint( - "schedule_run_id", - "invoice_no", - name="uq_voucher_check_run_items_run_invoice", - ), - Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"), - Index("ix_voucher_check_run_items_period_result", "period_month", "result"), + 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[int] = mapped_column( + schedule_run_id: Mapped[Optional[int]] = mapped_column( BigInteger, - ForeignKey("schedule_runs.id", ondelete="CASCADE"), + 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_state_id: Mapped[Optional[int]] = mapped_column( - BigInteger, - ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"), - nullable=True, - ) - scope_code: Mapped[str] = mapped_column(String(32), nullable=False) - period_month: Mapped[date] = mapped_column(Date, nullable=False) invoice_no: Mapped[str] = mapped_column(String(128), nullable=False) invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - result: Mapped[str] = mapped_column(String(24), nullable=False) - folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) - material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, 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/job_registry.py b/backend/app/services/schedule/job_registry.py index 480e1ddc..91935478 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -144,7 +144,7 @@ def _register_builtin_platform_jobs() -> None: run_contract_payment_alert_schedule, run_contract_payment_sync_schedule, ) - from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES + from app.services.voucher_check.config import DEFAULT_JOB_PARAMS from app.services.schedule.contract_payment_job import ( run_contract_payment_alert_schedule, run_contract_payment_sync_schedule, @@ -339,7 +339,7 @@ def _register_builtin_platform_jobs() -> None: label="立账凭证检核", label_key="admin.schedule.form.platformJobAccountingVoucherCheck", handler=run_voucher_check_schedule, - description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。", + description="每周二检核上一个自然月的销售开票附件,扫描文档库类型目录并按 invoice 归档。", description_key="admin.schedule.form.accountingVoucherCheckHint", category="finance", params_schema=( @@ -353,30 +353,12 @@ def _register_builtin_platform_jobs() -> None: "options": [{"value": "HXJM", "label": "HXJM"}], }, { - "key": "directory_template", + "key": "profile_code", "type": "text", - "label": "目录模板", - "label_key": "admin.schedule.form.voucherCheckDirTemplate", + "label": "业务方 Profile", + "label_key": "admin.schedule.form.voucherCheckProfile", "required": True, - "default": "{root}/{YYYY}/{MM}/{invoice_no}", - "help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}", - "help_key": "admin.schedule.form.voucherCheckDirTemplateHelp", - }, - { - "key": "required_files", - "type": "json", - "label": "必检材料", - "label_key": "admin.schedule.form.voucherCheckRequiredFiles", - "required": True, - "default": DEFAULT_REQUIRED_FILES, - }, - { - "key": "filename_case_sensitive", - "type": "boolean", - "label": "文件名区分大小写", - "label_key": "admin.schedule.form.voucherCheckCaseSensitive", - "required": True, - "default": True, + "default": "sales", }, { "key": "notify_missing_enabled", @@ -394,14 +376,6 @@ def _register_builtin_platform_jobs() -> None: "required": False, "default": True, }, - { - "key": "same_day_dedup_enabled", - "type": "boolean", - "label": "同票同日去重", - "label_key": "admin.schedule.form.voucherCheckSameDayDedup", - "required": False, - "default": True, - }, ), defaults=dict(DEFAULT_JOB_PARAMS), )) diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index 43f58fe1..ac008c0e 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -4,11 +4,14 @@ backend/app/services/schedule/queue_service.py 用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。 依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。 逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。 + domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入 + business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。 """ from __future__ import annotations from datetime import datetime +from typing import Any from flask import current_app @@ -28,6 +31,86 @@ from app.services.schedule.freight_receipt_rpa_finalize import ( from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive _worker_initialized = False +_BUSINESS_REF_SLUG_MAX = 80 + + +def _schedule_job_slug(task: ScheduleTask) -> str: + """ + 从排程任务生成写入 jobs.business_ref 的业务短码。 + + 核心逻辑:优先 platform_api_path(如 accounting-voucher-check);无 path 时用 untagged。 + 冒号替换为连字符,避免破坏 `schedule_run:{id}:{slug}` 三段格式。 + + Args: + task: 排程任务。 + + Returns: + 最长 80 字符的 slug。 + """ + from app.services.schedule import normalize_platform_api_path + + slug = normalize_platform_api_path(getattr(task, "platform_api_path", None)) or "untagged" + slug = slug.replace(":", "-").replace("/", "-") + return slug[:_BUSINESS_REF_SLUG_MAX] + + +def _schedule_task_label(task: ScheduleTask) -> str: + """ + jobs.message 与 worker 日志用的任务显示名。 + + 核心逻辑:优先中文 name(如「立账凭证检核」);否则回落到 platform_api_path。 + + Args: + task: 排程任务。 + + Returns: + 非空显示名。 + """ + name = str(getattr(task, "name", None) or "").strip() + if name: + return name + slug = _schedule_job_slug(task) + return slug if slug != "untagged" else "未命名排程" + + +def schedule_job_business_ref(run_id: int, task: ScheduleTask) -> str: + """ + 生成 schedule Job 的 business_ref。 + + 格式:`schedule_run:{run_id}:{platform_api_path}`,便于在 jobs 表区分立账凭证检核等任务。 + 仍保留 run_id,取消/回收可按前缀精确匹配,避免 `schedule_run:1` 误伤 `schedule_run:13`。 + + Args: + run_id: ScheduleRun 主键。 + task: 排程任务。 + + Returns: + 长度不超过 128 的 business_ref。 + """ + return f"schedule_run:{int(run_id)}:{_schedule_job_slug(task)}" + + +def query_jobs_for_schedule_run(run_id: int): + """ + 按 ScheduleRun 主键查找对应通用 Job。 + + 核心逻辑:兼容旧格式 `schedule_run:{id}` 与新格式 `schedule_run:{id}:{path}`。 + 新格式必须带 `id` 后的冒号,避免 run_id=1 匹配到 10/11/13。 + + Args: + run_id: ScheduleRun 主键。 + + Returns: + 已过滤 domain/job_type/business_ref 的 Query;调用方可继续按 status 收窄。 + """ + run_id = int(run_id) + legacy = f"schedule_run:{run_id}" + prefix = f"schedule_run:{run_id}:" + return db.session.query(Job).filter( + Job.domain == "schedule", + Job.job_type == JobType.SCHEDULE_RUN.value, + db.or_(Job.business_ref == legacy, Job.business_ref.startswith(prefix)), + ) def _active_run(task_id: int) -> ScheduleRun | None: @@ -61,14 +144,19 @@ 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。 + 核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run; + 业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。 + Args: 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,22 +174,29 @@ 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() + task_label = _schedule_task_label(task) + platform_path = str(getattr(task, "platform_api_path", None) or "").strip() job_id = enqueue( JobType.SCHEDULE_RUN, { "schedule_task_id": task.id, "schedule_run_id": run.id, + "schedule_no": task.schedule_no, + "run_no": run.run_no, + "task_name": task_label, + "platform_api_path": platform_path, "trigger_type": normalized_trigger, "triggered_by_user_id": triggered_by_user_id, }, domain="schedule", - business_ref=f"schedule_run:{run.id}", + business_ref=schedule_job_business_ref(run.id, task), created_by_id=triggered_by_user_id, max_attempts=3, - message="排程等待后台执行", + message=f"{task_label}等待后台执行", dedupe_active=False, commit=False, ) @@ -112,6 +207,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 +215,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。 """ @@ -135,13 +236,8 @@ def enqueue_manual_schedule_run( active = _active_run(task.id) if active is not None: job = ( - db.session.query(Job) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.status.in_(("queued", "running")), - Job.business_ref == f"schedule_run:{active.id}", - ) + query_jobs_for_schedule_run(active.id) + .filter(Job.status.in_(("queued", "running"))) .order_by(Job.id.asc()) .first() ) @@ -151,6 +247,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 @@ -242,13 +339,9 @@ def prepare_schedule_queue() -> int: if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run): continue active_job = ( - db.session.query(Job.id) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.business_ref == f"schedule_run:{run.id}", - Job.status.in_(("queued", "running")), - ) + query_jobs_for_schedule_run(run.id) + .filter(Job.status.in_(("queued", "running"))) + .with_entities(Job.id) .first() ) if active_job is None: @@ -308,11 +401,13 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N if task is None: finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除") return None + task_label = _schedule_task_label(task) + platform_path = str(getattr(task, "platform_api_path", None) or "").strip() or "untagged" if run.status in {"success", "failed", "partial_failed"}: finish_job( job_id, - result={"schedule_run_id": run.id, "status": run.status}, - message="排程已处于终态", + result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path}, + message=f"{task_label}已处于终态", ) return run @@ -323,6 +418,14 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N run.started_at = run.started_at or datetime.utcnow() run.error_message = None db.session.commit() + logger.info( + "[schedule-run] start name=%s path=%s run_no=%s run_id=%s job_id=%s", + task_label, + platform_path, + run.run_no, + run.id, + job_id, + ) result_run = run_task_now( task, trigger_type=run.trigger_type, @@ -331,8 +434,12 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N ) finish_job( job_id, - result={"schedule_run_id": result_run.id, "status": result_run.status}, - message="排程执行完成", + result={ + "schedule_run_id": result_run.id, + "status": result_run.status, + "platform_api_path": platform_path, + }, + message=f"{task_label}执行完成", ) return result_run except Exception as exc: @@ -355,5 +462,11 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N retryable=True, owned_attempt=owned_attempt, ) - logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id) + logger.exception( + "[schedule-run] failed name=%s path=%s run_id=%s job_id=%s", + task_label, + platform_path, + run_id, + job_id, + ) return run diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 44cfb59b..8ceab5b4 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -5,7 +5,8 @@ backend/app/services/schedule/scheduler_service.py 依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。 逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task; job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path - 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler。 + 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler; + handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。 """ from __future__ import annotations @@ -43,20 +44,16 @@ def request_cancel_run(run_id: int) -> None: 持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。 核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过 - ScheduleRun 状态/存在性复检停止可中断的长循环。 + ScheduleRun 状态/存在性复检停止可中断的长循环。business_ref 兼容 + `schedule_run:{id}` 与 `schedule_run:{id}:{platform_api_path}`。 """ - from app.jobs.types import JobType from app.models import Job + from app.services.schedule.queue_service import query_jobs_for_schedule_run now = datetime.utcnow() jobs = ( - db.session.query(Job) - .filter( - Job.domain == "schedule", - Job.job_type == JobType.SCHEDULE_RUN.value, - Job.business_ref == f"schedule_run:{int(run_id)}", - Job.status.in_(("queued", "running")), - ) + query_jobs_for_schedule_run(run_id) + .filter(Job.status.in_(("queued", "running"))) .all() ) for job in jobs: @@ -493,6 +490,12 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun: + """ + 立即执行一条排程并写入 ScheduleRun 终态。 + + 核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success; + 该路径原先只写库不打日志,worker 汇总行看不到失败原因。 + """ recover_stale_awaiting_rpa_schedule_runs(task) recover_stale_receipt_rpa_schedule_runs(task) @@ -527,8 +530,16 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: executor = resolve_schedule_executor(task) total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run) except Exception as exc: - total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)] + total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 1, 0, [], [str(exc)] step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}] + if current_app: + current_app.logger.exception( + "[schedule-run] executor failed name=%s path=%s run_no=%s error=%s", + task.name, + task.platform_api_path, + run.run_no, + exc, + ) try: db.session.refresh(run) @@ -563,9 +574,18 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: duration_ms = int((time.time() - start_ts) * 1000) if current_app: + error_preview = "; ".join(str(item) for item in (errors or [])[:3]) current_app.logger.info( - "[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d", - run.run_no, total_count, success_count, failed_count, skipped_count, len(errors), + "[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d error=%s", + task.name, + task.platform_api_path, + run.run_no, + total_count, + success_count, + failed_count, + skipped_count, + len(errors or []), + error_preview or "-", ) if total_count == 0 and not errors: status = "success" 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/__init__.py b/backend/app/services/voucher_check/__init__.py index a303a55d..699c8411 100644 --- a/backend/app/services/voucher_check/__init__.py +++ b/backend/app/services/voucher_check/__init__.py @@ -3,7 +3,7 @@ backend/app/services/voucher_check/__init__.py 用途:立账凭证检核领域服务包入口。 依赖:config / runner / query_service 等子模块。 -逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。 +逻辑:platform Job 与工作台 API 从此包调用 runner 与查询能力。 """ from app.services.voucher_check.runner import run_voucher_check_batch 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..1f8a62e2 100644 --- a/backend/app/services/voucher_check/config.py +++ b/backend/app/services/voucher_check/config.py @@ -1,16 +1,15 @@ """ backend/app/services/voucher_check/config.py -用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。 +用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。 依赖:Flask current_app.config、core.errors.ValidationError。 -逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。 +逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID; + ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。 """ from __future__ import annotations -import json import os -import re from dataclasses import dataclass from typing import Any @@ -18,60 +17,22 @@ from flask import has_app_context, current_app from app.core.errors import ValidationError -_ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"} -_TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}") -_UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)") - -DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [ - { - "code": "price_check_sheet", - "name": "核价单", - "required": True, - "accepted_filenames": ["核价单.pdf"], - }, - { - "code": "purchase_order", - "name": "采购单", - "required": True, - "accepted_filenames": ["采购单.pdf"], - }, -] - 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, } @dataclass(frozen=True) -class RequiredFileRule: - """单条必检材料规则。""" - - code: str - name: str - required: bool - accepted_filenames: tuple[str, ...] - - -@dataclass(frozen=True) -class VoucherCheckConfig: - """运行期检核配置快照。""" +class VoucherCheckEngineConfig: + """销售一期引擎运行配置:ERP + 通知开关。""" scope_code: str - directory_template: str - required_files: tuple[RequiredFileRule, ...] - filename_case_sensitive: bool + profile_code: str notify_missing_enabled: bool notify_failure_enabled: bool - same_day_dedup_enabled: bool - local_root: str - share_unc: str - healthcheck_relative_path: str erp_dsn: str erp_username: str erp_password: str @@ -99,114 +60,13 @@ def _as_bool(value: Any, default: bool) -> bool: return default -def _parse_required_files(raw: Any) -> list[RequiredFileRule]: - if raw is None: - raw = DEFAULT_REQUIRED_FILES - if isinstance(raw, str): - try: - raw = json.loads(raw) - except json.JSONDecodeError as exc: - raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc - if not isinstance(raw, list) or not raw: - raise _config_invalid("required_files 至少包含一个必检项") - - rules: list[RequiredFileRule] = [] - for idx, item in enumerate(raw): - if not isinstance(item, dict): - raise _config_invalid(f"required_files[{idx}] 必须为对象") - code = str(item.get("code") or "").strip() - name = str(item.get("name") or code).strip() - accepted = item.get("accepted_filenames") or [] - if not code: - raise _config_invalid(f"required_files[{idx}].code 不能为空") - if not isinstance(accepted, list) or not accepted: - raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空") - filenames: list[str] = [] - for fname in accepted: - text = str(fname or "").strip() - if not text: - raise _config_invalid(f"required_files[{idx}] 存在空文件名") - if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text): - raise _config_invalid( - f"required_files[{idx}] 文件名禁止通配/路径字符: {text}", - ) - filenames.append(text) - rules.append( - RequiredFileRule( - code=code, - name=name or code, - required=_as_bool(item.get("required"), True), - accepted_filenames=tuple(filenames), - ) - ) - if not any(r.required for r in rules): - raise _config_invalid("required_files 至少包含一个 required=true 项") - return rules - - -def validate_directory_template(template: str) -> str: +def _erp_settings() -> tuple[str, str, str, int]: """ - 校验目录模板占位符。 - 核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。 + 读取 ERP 只读连接;密码只来自环境/配置,不写日志。 + + 核心逻辑:VOUCHER_CHECK_ERP_* 优先,其次通用 ERP_*,再回退合同付款同一套只读账号。 """ - text = str(template or "").strip().replace("\\", "/") - if not text: - raise _config_invalid("directory_template 不能为空") - tokens = _TEMPLATE_TOKEN_RE.findall(text) - unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS}) - if unknown: - raise _config_invalid( - "directory_template 含非法占位符", - details={"unknown": unknown}, - ) - missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens)) - if missing: - raise _config_invalid( - "directory_template 缺少必要占位符", - details={"missing": missing}, - ) - return text - - -def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig: - """ - 合并 env 与 job_params,返回校验后的检核配置。 - 核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。 - """ - 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}) - - template = validate_directory_template( - str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"]) - ) - required_files = _parse_required_files(params.get("required_files")) - cfg = current_app.config if has_app_context() else {} - local_root = str( - cfg.get("VOUCHER_CHECK_LOCAL_ROOT") - or os.getenv("VOUCHER_CHECK_LOCAL_ROOT") - or "" - ).strip() - share_unc = str( - cfg.get("VOUCHER_CHECK_SHARE_UNC") - or os.getenv("VOUCHER_CHECK_SHARE_UNC") - or "" - ).strip() - healthcheck = str( - cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") - or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH") - or ".hxops-share-ready" - ).strip() or ".hxops-share-ready" - - # 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT - 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") @@ -217,46 +77,53 @@ def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> Vouch erp_username = str( cfg.get("VOUCHER_CHECK_ERP_USERNAME") or os.getenv("VOUCHER_CHECK_ERP_USERNAME") + or cfg.get("ERP_USERNAME") + or os.getenv("ERP_USERNAME") + or cfg.get("CONTRACT_PAYMENT_ERP_USERNAME") + or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME") or "" ).strip() erp_password = str( cfg.get("VOUCHER_CHECK_ERP_PASSWORD") or os.getenv("VOUCHER_CHECK_ERP_PASSWORD") + or cfg.get("ERP_PASSWORD") + or os.getenv("ERP_PASSWORD") + or cfg.get("CONTRACT_PAYMENT_ERP_PASSWORD") + or os.getenv("CONTRACT_PAYMENT_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 cfg.get("ERP_TIMEOUT_SECONDS") + or os.getenv("ERP_TIMEOUT_SECONDS") or 30 ) + return erp_dsn, erp_username, erp_password, max(1, timeout) - return VoucherCheckConfig( + +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, - directory_template=template, - required_files=tuple(required_files), - filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True), + 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), - same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True), - local_root=local_root, - share_unc=share_unc, - healthcheck_relative_path=healthcheck, erp_dsn=erp_dsn, erp_username=erp_username, erp_password=erp_password, - erp_timeout_seconds=max(1, timeout), + erp_timeout_seconds=timeout, ) - - -def resolve_share_root(config: VoucherCheckConfig) -> str: - """ - 解析实际扫描根路径。 - 核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。 - """ - root = (config.local_root or config.share_unc or "").strip() - if not root: - raise _config_invalid("共享盘根路径为空") - return root 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..b78dd52f --- /dev/null +++ b/backend/app/services/voucher_check/dms_client.py @@ -0,0 +1,402 @@ +""" +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: + """ + 配置缺失时在批次开始前失败,并返回可操作的缺失项。 + 核心逻辑:避免把空扫当成业务缺件;同时不能将任意凭据值写入错误响应。 + """ + missing = [ + key + for key, value in ( + ("VOUCHER_CHECK_DMS_BASE_URL", cls.base_url()), + ("VOUCHER_CHECK_DMS_LIBRARY_ID", cls.library_id()), + ("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID", cls.root_folder_id()), + ("VOUCHER_CHECK_DMS_USERNAME", cls.username()), + ("VOUCHER_CHECK_DMS_PASSWORD", cls.password()), + ) + if not value + ] + if missing: + raise ValidationError( + "销售开票附件文档库配置不完整", + code="VOUCHER_CHECK.CONFIG_INVALID", + details={"missing": missing}, + ) + + @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..2155075d 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。 """ @@ -13,7 +13,7 @@ from datetime import date, datetime from zoneinfo import ZoneInfo from app.core.errors import ServiceUnavailableError -from app.services.voucher_check.config import VoucherCheckConfig +from app.services.voucher_check.config import VoucherCheckEngineConfig _TZ = ZoneInfo("Asia/Shanghai") @@ -31,7 +31,7 @@ SELECT DISTINCT @dataclass(frozen=True) class ErpInvoiceRow: - """ERP 当月发票行。""" + """ERP 发票行。""" invoice_no: str invoice_date: date | None @@ -40,7 +40,7 @@ class ErpInvoiceRow: def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]: """ 按 Asia/Shanghai 计算当前自然月起止。 - 核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。 + 核心逻辑:不用 Oracle SYSDATE,作为 previous_period_bounds 的基准。 Returns: (period_month_first, next_month_first, period_start_dt, next_period_start_dt) @@ -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, + config: VoucherCheckEngineConfig, *, 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/fingerprint.py b/backend/app/services/voucher_check/fingerprint.py index 02b0f568..05a45c55 100644 --- a/backend/app/services/voucher_check/fingerprint.py +++ b/backend/app/services/voucher_check/fingerprint.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/fingerprint.py -用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。 +用途:根据文件名与元数据生成稳定 SHA-256 指纹。 依赖:标准库 hashlib / json。 -逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。 +逻辑:DMS 目录扫描与 HXJM 主体 Adapter 调用,供增量跳过比对。 """ from __future__ import annotations 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/openapi_base.json b/backend/app/services/voucher_check/openapi_base.json deleted file mode 100644 index 372a97c4..00000000 --- a/backend/app/services/voucher_check/openapi_base.json +++ /dev/null @@ -1,316 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "HXOPS Accounting Voucher Check Tool API", - "description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://127.0.0.1:5052", - "description": "HXOPS_TOOLS_API_BASE" - } - ], - "security": [ - { - "BearerAuth": [] - }, - { - "IntegrationKey": [] - } - ], - "paths": { - "/api/accounting-voucher-check/tools/tasks/{task_id}/missing": { - "get": { - "operationId": "list_voucher_missing", - "summary": "查询缺资料发票(最新状态)", - "description": "按账套与月份查询 status=missing 的发票;默认当前自然月。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "task_id", - "in": "path", - "required": true, - "schema": { "type": "integer", "example": 12 }, - "description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { "type": "string", "example": "2026-08" }, - "description": "检核月份 YYYY-MM;缺省为当前自然月" - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { "type": "string", "default": "HXJM", "example": "HXJM" } - }, - { - "name": "limit", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 200, "minimum": 1, "maximum": 1000 } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/MissingListResponse" } - } - } - }, - "400": { "$ref": "#/components/responses/BadRequest" }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - }, - "/api/accounting-voucher-check/tools/runs/{run_id}/items": { - "get": { - "operationId": "list_voucher_run_items", - "summary": "查询批次发票明细", - "description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "run_id", - "in": "path", - "required": true, - "schema": { "type": "integer", "example": 1001 } - }, - { - "name": "result", - "in": "query", - "required": false, - "schema": { - "type": "string", - "enum": ["complete", "missing", "skipped", "technical_error"], - "example": "missing" - } - }, - { - "name": "page", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 1, "minimum": 1 } - }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/RunItemsResponse" } - } - } - }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "404": { "$ref": "#/components/responses/NotFound" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - }, - "/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": { - "get": { - "operationId": "get_voucher_invoice_latest", - "summary": "查询指定发票最新检核状态", - "description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。", - "tags": ["Accounting Voucher Check"], - "parameters": [ - { - "name": "invoice_no", - "in": "path", - "required": true, - "schema": { "type": "string", "example": "INV-20260803001" }, - "description": "发票号(apa08 原值)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { "type": "string", "example": "2026-08" } - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { "type": "string", "default": "HXJM" } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/InvoiceLatestResponse" } - } - } - }, - "400": { "$ref": "#/components/responses/BadRequest" }, - "401": { "$ref": "#/components/responses/Unauthorized" }, - "404": { "$ref": "#/components/responses/NotFound" }, - "503": { "$ref": "#/components/responses/MissingAuth" } - } - } - } - }, - "components": { - "securitySchemes": { - "BearerAuth": { - "type": "http", - "scheme": "bearer", - "description": "Authorization: Bearer " - }, - "IntegrationKey": { - "type": "apiKey", - "in": "header", - "name": "X-Integration-Key", - "description": "与 Bearer 二选一" - } - }, - "schemas": { - "MissingMaterial": { - "type": "object", - "properties": { - "code": { "type": "string", "example": "price_check_sheet" }, - "name": { "type": "string", "example": "核价单" } - } - }, - "InvoiceState": { - "type": "object", - "properties": { - "id": { "type": "integer" }, - "scope_code": { "type": "string" }, - "period_month": { "type": "string", "nullable": true }, - "invoice_no": { "type": "string" }, - "invoice_date": { "type": "string", "nullable": true }, - "status": { "type": "string", "enum": ["complete", "missing"] }, - "folder_path": { "type": "string", "nullable": true }, - "folder_exists": { "type": "boolean" }, - "matched_files": { "type": "object", "additionalProperties": { "type": "string" } }, - "missing_materials": { - "type": "array", - "items": { "$ref": "#/components/schemas/MissingMaterial" } - }, - "last_checked_at": { "type": "string", "nullable": true } - } - }, - "MissingListResponse": { - "type": "object", - "required": ["ok", "items", "count"], - "properties": { - "ok": { "type": "boolean", "example": true }, - "task_id": { "type": "integer", "nullable": true }, - "scope_code": { "type": "string" }, - "period": { "type": "string", "example": "2026-08" }, - "count": { "type": "integer" }, - "items": { - "type": "array", - "items": { "$ref": "#/components/schemas/InvoiceState" } - } - } - }, - "RunItem": { - "type": "object", - "properties": { - "id": { "type": "integer" }, - "schedule_run_id": { "type": "integer" }, - "invoice_no": { "type": "string" }, - "result": { - "type": "string", - "enum": ["complete", "missing", "skipped", "technical_error"] - }, - "folder_path": { "type": "string", "nullable": true }, - "matched_files": { "type": "object", "additionalProperties": { "type": "string" } }, - "missing_materials": { - "type": "array", - "items": { "$ref": "#/components/schemas/MissingMaterial" } - }, - "error_code": { "type": "string", "nullable": true }, - "error_message": { "type": "string", "nullable": true } - } - }, - "RunItemsResponse": { - "type": "object", - "required": ["ok", "items", "total"], - "properties": { - "ok": { "type": "boolean" }, - "run_id": { "type": "integer" }, - "run_no": { "type": "string" }, - "page": { "type": "integer" }, - "page_size": { "type": "integer" }, - "total": { "type": "integer" }, - "items": { - "type": "array", - "items": { "$ref": "#/components/schemas/RunItem" } - } - } - }, - "InvoiceLatestResponse": { - "type": "object", - "required": ["ok", "state"], - "properties": { - "ok": { "type": "boolean" }, - "state": { "$ref": "#/components/schemas/InvoiceState" }, - "recent_run_items": { - "type": "array", - "items": { "$ref": "#/components/schemas/RunItem" } - } - } - }, - "ToolError": { - "type": "object", - "properties": { - "ok": { "type": "boolean", "example": false }, - "error_code": { "type": "string" }, - "message": { "type": "string" }, - "details": { "type": "object" } - } - } - }, - "responses": { - "BadRequest": { - "description": "参数错误", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "Unauthorized": { - "description": "鉴权失败", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "NotFound": { - "description": "资源不存在", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - }, - "MissingAuth": { - "description": "服务端未配置 Tool API Key", - "content": { - "application/json": { - "schema": { "$ref": "#/components/schemas/ToolError" } - } - } - } - } - } -} diff --git a/backend/app/services/voucher_check/openapi_spec.py b/backend/app/services/voucher_check/openapi_spec.py deleted file mode 100644 index ce8f976f..00000000 --- a/backend/app/services/voucher_check/openapi_spec.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -backend/app/services/voucher_check/openapi_spec.py - -用途:构建立账凭证检核 Chatflow 查询 Tool 的 OpenAPI 3.0 规范。 -依赖:openapi_base.json。 -逻辑:GET /api/accounting-voucher-check/tools/openapi.json 调用本模块;Dify URL 导入。 -""" - -from __future__ import annotations - -import copy -import json -from pathlib import Path -from typing import Any - -_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json") - - -def _load_base_spec() -> dict[str, Any]: - with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp: - return json.load(fp) - - -def build_voucher_check_openapi_spec(base_url: str) -> dict[str, Any]: - """ - 构建立账凭证检核 Tool OpenAPI。 - 核心逻辑:深拷贝静态规格,并将 servers[0].url 替换为当前 HXOPS_TOOLS_API_BASE。 - """ - spec = copy.deepcopy(_load_base_spec()) - base = str(base_url or "").strip().rstrip("/") - servers = spec.get("servers") - if base and isinstance(servers, list) and servers: - servers[0]["url"] = base - servers[0]["description"] = "HXOPS_TOOLS_API_BASE" - return spec diff --git a/backend/app/services/voucher_check/persistence.py b/backend/app/services/voucher_check/persistence.py deleted file mode 100644 index 74e75271..00000000 --- a/backend/app/services/voucher_check/persistence.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -backend/app/services/voucher_check/persistence.py - -用途:立账凭证检核单票状态与批次明细的事务写入。 -依赖:models.voucher_check、ScheduleRun、SQLAlchemy session。 -逻辑:runner 阶段 B 调用;skipped 只更新 last_seen_erp_at;批次级失败不进入本模块。 -""" - -from __future__ import annotations - -from datetime import date, datetime -from typing import Any - -from app import db -from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem - - -def persist_batch_results( - *, - schedule_run_id: int, - scope_code: str, - period_month: date, - items: list[dict[str, Any]], - now: datetime | None = None, -) -> None: - """ - 单事务写入批次明细并 upsert 最新状态。 - 核心逻辑:先写 run_items;非 skipped/technical_error 再 upsert states; - skipped 仅刷新 last_seen_erp_at。 - - Args: - schedule_run_id: ScheduleRun.id - scope_code: 账套 - period_month: 当月首日 - items: 内存中的结果行(含 result / fingerprint / missing 等) - now: 可选时钟 - """ - ts = now or datetime.utcnow() - for item in items: - invoice_no = str(item["invoice_no"]).strip() - result = str(item["result"]) - run_item = VoucherCheckRunItem( - schedule_run_id=schedule_run_id, - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - invoice_date=item.get("invoice_date"), - result=result, - folder_path=item.get("folder_path"), - folder_exists=bool(item.get("folder_exists")), - material_fingerprint=item.get("material_fingerprint"), - matched_files_json=item.get("matched_files") or {}, - missing_materials_json=item.get("missing_materials") or [], - error_code=item.get("error_code"), - error_message=item.get("error_message"), - checked_at=item.get("checked_at"), - created_at=ts, - ) - db.session.add(run_item) - - state = ( - db.session.query(VoucherCheckInvoiceState) - .filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - ) - .one_or_none() - ) - if state is None: - state = VoucherCheckInvoiceState( - scope_code=scope_code, - period_month=period_month, - invoice_no=invoice_no, - created_at=ts, - ) - db.session.add(state) - - state.last_seen_erp_at = ts - state.invoice_date = item.get("invoice_date") or state.invoice_date - state.updated_at = ts - - if result == "skipped": - # 跳过:不改写齐全结论与实际扫描时间 - continue - if result == "technical_error": - continue - - state.status = "complete" if result == "complete" else "missing" - state.folder_path = item.get("folder_path") - state.folder_exists = bool(item.get("folder_exists")) - state.material_fingerprint = item.get("material_fingerprint") - state.matched_files_json = item.get("matched_files") or {} - state.missing_materials_json = item.get("missing_materials") or [] - state.last_actual_run_id = schedule_run_id - state.last_checked_at = item.get("checked_at") or ts - - db.session.flush() - run_item.invoice_state_id = state.id - - db.session.flush() - - -def mark_missing_notified( - *, - scope_code: str, - period_month: date, - invoice_nos: list[str], - notified_on: date, -) -> None: - """发送缺资料通知成功后更新同票同日节流字段。""" - if not invoice_nos: - return - states = ( - db.session.query(VoucherCheckInvoiceState) - .filter( - VoucherCheckInvoiceState.scope_code == scope_code, - VoucherCheckInvoiceState.period_month == period_month, - VoucherCheckInvoiceState.invoice_no.in_(invoice_nos), - ) - .all() - ) - for state in states: - state.last_missing_notified_on = notified_on - state.updated_at = datetime.utcnow() - db.session.flush() 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..4219013a 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。 +逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。 """ from __future__ import annotations @@ -11,61 +11,21 @@ from __future__ import annotations from datetime import date, datetime from typing import Any -from app.core.errors import 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 - - -def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]: - return { - "id": state.id, - "scope_code": state.scope_code, - "period_month": state.period_month.isoformat() if state.period_month else None, - "invoice_no": state.invoice_no, - "invoice_date": state.invoice_date.isoformat() if state.invoice_date else None, - "status": state.status, - "folder_path": state.folder_path, - "folder_exists": state.folder_exists, - "material_fingerprint": state.material_fingerprint, - "matched_files": state.matched_files_json or {}, - "missing_materials": state.missing_materials_json or [], - "last_actual_run_id": state.last_actual_run_id, - "last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None, - "last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None, - "last_missing_notified_on": ( - state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None - ), - "updated_at": state.updated_at.isoformat() if state.updated_at else None, - } - - -def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]: - return { - "id": item.id, - "schedule_run_id": item.schedule_run_id, - "invoice_state_id": item.invoice_state_id, - "scope_code": item.scope_code, - "period_month": item.period_month.isoformat() if item.period_month else None, - "invoice_no": item.invoice_no, - "invoice_date": item.invoice_date.isoformat() if item.invoice_date else None, - "result": item.result, - "folder_path": item.folder_path, - "folder_exists": item.folder_exists, - "material_fingerprint": item.material_fingerprint, - "matched_files": item.matched_files_json or {}, - "missing_materials": item.missing_materials_json or [], - "error_code": item.error_code, - "error_message": item.error_message, - "checked_at": item.checked_at.isoformat() if item.checked_at else None, - "created_at": item.created_at.isoformat() if item.created_at else None, - } +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ScheduleRun, ScheduleTask, User +from app.models.voucher_check import ( + VoucherCheckFileResult, + VoucherCheckNotification, + VoucherCheckRun, +) +from app.services.voucher_check.aggregator import aggregate_file_results +from app.services.voucher_check.erp_repository import previous_period_bounds 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: @@ -81,38 +41,191 @@ def parse_period_month(raw: str | None) -> date: ) from exc -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 _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]: + """ + 序列化尚未创建引擎批次的立账凭证排程记录。 + 核心逻辑:配置或外部依赖在引擎建批前失败时,仍须在工作台展示失败原因, + 避免用户只能看到空列表而无法判断强制重检是否已执行。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + voucher_summary = summary.get("voucher_check") if isinstance(summary.get("voucher_check"), dict) else {} + period_month, *_ = previous_period_bounds() + return { + "id": run.id, + "schedule_run_id": run.id, + "run_no": run.run_no, + "profile_code": str(voucher_summary.get("profile_code") or "sales"), + "period_month": str(voucher_summary.get("period") or period_month.strftime("%Y-%m")), + "mode": str(voucher_summary.get("mode") or "incremental"), + # 工作台按引擎状态筛选;排程在建批前失败统一映射为技术失败。 + "status": "technical_failed", + "subject_count": int(run.total_count or 0), + "archived_file_count": 0, + "missing_file_count": 0, + "missing_invoice_count": 0, + "technical_error_count": 1 if run.status == "failed" else 0, + "staged_file_count": 0, + "skipped_file_count": int(run.skipped_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, + "error_message": run.error_message, + } + + +def list_runs( *, - task_id: int | None = None, - scope_code: str = "HXJM", period: str | None = None, - limit: int = 200, + profile_code: str | None = None, + status: str | None = None, + page: int = 1, + page_size: int = 50, ) -> dict[str, Any]: """ - 查询指定月份缺资料票(最新状态表)。 - task_id 预留与排程绑定校验,本期仅用于响应回显。 + 工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。 + 核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在 + create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。 """ - period_month = parse_period_month(period) - limit = max(1, min(int(limit or 200), 1000)) - q = ( - VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, - status="missing", + 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()) + engine_rows = q.order_by(VoucherCheckRun.id.desc()).all() + engine_schedule_run_ids = {row.schedule_run_id for row in engine_rows if row.schedule_run_id} + fallback_query = ( + ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id) + .filter( + ScheduleTask.platform_api_path == "accounting-voucher-check", + ScheduleRun.status == "failed", ) - .order_by(VoucherCheckInvoiceState.invoice_no.asc()) - .limit(limit) ) - items = [_serialize_state(s) for s in q.all()] + if status and str(status).strip() != "technical_failed": + fallback_rows: list[ScheduleRun] = [] + else: + fallback_rows = fallback_query.order_by(ScheduleRun.id.desc()).all() + fallback_rows = [ + row + for row in fallback_rows + if row.id not in engine_schedule_run_ids + and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m")) + ] + merged = [_serialize_engine_run(row) for row in engine_rows] + merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows) + merged.sort(key=lambda row: row.get("finished_at") or row.get("started_at") or "", reverse=True) + total = len(merged) + rows = merged[(page - 1) * page_size : page * page_size] return { - "task_id": task_id, - "scope_code": scope_code, - "period": period_month.strftime("%Y-%m"), - "count": len(items), - "items": items, + "page": page, + "page_size": page_size, + "total": total, + "items": rows, } +def _serialize_file_type_rows(aggregated: dict[str, Any]) -> list[dict[str, Any]]: + """ + 将聚合器的 by_file_type 转成工作台「按文件类型」表格行。 + 核心逻辑:缺失占比 = 该类型缺件 invoice 数 / 本批主体总数。 + """ + subject_count = int(aggregated.get("subject_count") or 0) + by_type = aggregated.get("by_file_type") or {} + rows: list[dict[str, Any]] = [] + for item in by_type.values(): + if not isinstance(item, dict): + continue + missing_invoices = int(item.get("missing_invoice_count") or 0) + ratio = (missing_invoices / subject_count) if subject_count else 0.0 + rows.append( + { + "rule_code": item.get("rule_code"), + "rule_name": item.get("rule_name"), + "missing_file_count": int(item.get("missing_file_count") or 0), + "missing_invoice_count": missing_invoices, + "missing_ratio": round(ratio, 4), + } + ) + return rows + + +def _engine_invoice_items(engine_run: VoucherCheckRun) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """ + 将单文件结果聚合成 invoice 行,并返回同一批的类型汇总。 + 核心逻辑:按 invoice 汇总缺件材料;类型汇总来自聚合器,不受 invoice 行筛选影响。 + """ + 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") + 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, + "missing_count": len(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, aggregated + + def list_run_items( *, run_id: int, @@ -120,101 +233,202 @@ 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)) - q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id) - if result: - q = q.filter(VoucherCheckRunItem.result == str(result).strip()) - total = q.count() - rows = ( - q.order_by(VoucherCheckRunItem.invoice_no.asc()) - .offset((page - 1) * page_size) - .limit(page_size) - .all() + engine_run = ( + VoucherCheckRun.query.filter_by(schedule_run_id=run_id) + .order_by(VoucherCheckRun.id.desc()) + .first() ) + if engine_run is None: + return { + "run_id": run_id, + "run_no": run.run_no, + "page": page, + "page_size": page_size, + "total": 0, + "items": [], + "subject_count": 0, + "by_file_type": [], + } + items, aggregated = _engine_invoice_items(engine_run) + result_filter = str(result).strip() if result else "" + if result_filter: + items = [row for row in items if row.get("result") == result_filter] + 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": [_serialize_run_item(r) for r in rows], + "items": sliced, + "subject_count": int(aggregated.get("subject_count") or 0), + "by_file_type": _serialize_file_type_rows(aggregated), } -def get_invoice_latest( +def list_notifications( *, - invoice_no: str, - scope_code: str = "HXJM", period: str | None = None, -) -> dict[str, Any]: - """查询单票最新状态及近期批次快照。""" - inv = str(invoice_no or "").strip() - if not inv: - raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED") - period_month = parse_period_month(period) - state = ( - VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=inv, - ).one_or_none() - ) - if not state: - raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND") - history = ( - VoucherCheckRunItem.query.filter_by( - scope_code=scope_code, - period_month=period_month, - invoice_no=inv, - ) - .order_by(VoucherCheckRunItem.id.desc()) - .limit(20) - .all() - ) - return { - "state": _serialize_state(state), - "recent_run_items": [_serialize_run_item(h) for h in history], - } - - -def list_states( - *, - scope_code: str = "HXJM", - period: str | None = None, - status: str | None = None, - invoice_no: str | None = None, + send_status: str | None = None, page: int = 1, page_size: int = 50, ) -> dict[str, Any]: - """工作台:按月/状态/发票号筛选最新状态。""" - period_month = parse_period_month(period) + """ + 分页查询企微缺件汇总发送记录。 + 核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。 + """ page = max(1, int(page or 1)) page_size = max(1, min(int(page_size or 50), 200)) - q = VoucherCheckInvoiceState.query.filter_by( - scope_code=scope_code, - period_month=period_month, + q = VoucherCheckNotification.query.join( + VoucherCheckRun, + VoucherCheckNotification.run_id == VoucherCheckRun.id, ) - if status: - q = q.filter(VoucherCheckInvoiceState.status == str(status).strip()) - if invoice_no: - q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%")) + if period: + q = q.filter(VoucherCheckRun.period_month == parse_period_month(period)) + status_filter = str(send_status or "").strip() + if status_filter: + q = q.filter(VoucherCheckNotification.send_status == status_filter) total = q.count() rows = ( - q.order_by(VoucherCheckInvoiceState.invoice_no.asc()) + q.order_by(VoucherCheckNotification.id.desc()) .offset((page - 1) * page_size) .limit(page_size) .all() ) + engine_runs = { + run.id: run + for run in VoucherCheckRun.query.filter( + VoucherCheckRun.id.in_([row.run_id for row in rows] or [0]) + ).all() + } + schedule_ids = [ + engine_runs[row.run_id].schedule_run_id + for row in rows + if row.run_id in engine_runs and engine_runs[row.run_id].schedule_run_id + ] + schedule_map = { + item.id: item + for item in ScheduleRun.query.filter(ScheduleRun.id.in_(schedule_ids or [0])).all() + } + recipient_ids: set[int] = set() + for row in rows: + for raw in row.recipient_user_ids_json or []: + try: + recipient_ids.add(int(raw)) + except (TypeError, ValueError): + continue + users = { + user.id: user + for user in (User.query.filter(User.id.in_(recipient_ids)).all() if recipient_ids else []) + } + items: list[dict[str, Any]] = [] + for row in rows: + engine_run = engine_runs.get(row.run_id) + summary = row.summary_json if isinstance(row.summary_json, dict) else {} + names: list[str] = [] + for raw in row.recipient_user_ids_json or []: + try: + user = users.get(int(raw)) + except (TypeError, ValueError): + user = None + if user: + names.append(str(user.real_name or user.username or user.id)) + schedule_run_id = engine_run.schedule_run_id if engine_run else None + schedule_run = schedule_map.get(schedule_run_id) if schedule_run_id else None + items.append( + { + "id": row.id, + "run_id": row.run_id, + "schedule_run_id": schedule_run_id, + "run_no": ( + (engine_run.run_no if engine_run else None) + or summary.get("run_no") + or (schedule_run.run_no if schedule_run else None) + ), + "period_month": ( + engine_run.period_month.strftime("%Y-%m") + if engine_run and engine_run.period_month + else summary.get("period") + ), + "subject_count": int( + (engine_run.subject_count if engine_run else None) or summary.get("subject_count") or 0 + ), + "missing_file_count": int( + (engine_run.missing_file_count if engine_run else None) + or summary.get("missing_file_count") + or 0 + ), + "missing_invoice_count": int( + (engine_run.missing_invoice_count if engine_run else None) + or summary.get("missing_invoice_count") + or 0 + ), + "send_status": row.send_status, + "skip_reason": row.skip_reason, + "excel_filename": row.excel_filename or (schedule_run.excel_file_name if schedule_run else None), + "has_excel": bool(schedule_run and schedule_run.excel_file_name), + "recipient_names": names, + "sent_at": row.sent_at.isoformat() if row.sent_at else None, + "created_at": row.created_at.isoformat() if row.created_at else None, + } + ) return { - "scope_code": scope_code, - "period": period_month.strftime("%Y-%m"), "page": page, "page_size": page_size, "total": total, - "items": [_serialize_state(r) for r in rows], + "items": items, + } + + +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.config import load_engine_config + from app.services.voucher_check.dms_client import SalesDmsClient + from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition + 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", + ) + # [STEP 1] 入队前完成不依赖外部 IO 的配置预校验,避免 worker 失败后页面空白。 + 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() + 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..9d99991d 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,9 @@ def _update_progress( def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ - 执行立账凭证检核批次。 - 核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。 + 执行立账凭证周批次。 + 核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。 + 启动日志带 path=accounting-voucher-check,便于在全是 schedule 的 worker 输出中识别本任务。 Returns: ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs) @@ -87,9 +95,19 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe options = _extract_run_options(run) mode = options["mode"] single_invoice = options["invoice_no"] + now = datetime.utcnow() + current_app.logger.info( + "[voucher-check] start name=%s path=accounting-voucher-check run_no=%s mode=%s", + getattr(task, "name", None) or "立账凭证检核", + run.run_no, + mode, + ) try: - config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {}) + config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {}) + profile = load_profile_definition(config.profile_code) + ensure_published_profile(config.profile_code) + SalesDmsClient.ensure_configured() except AppError as exc: send_failure_alert( task=task, @@ -101,10 +119,15 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe ) raise - # [STEP 1] 拉取 ERP 当月发票清单 - _update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证") + rules = required_file_rules(profile) + period_month, _current, _start, _end = previous_period_bounds() + period = period_month.strftime("%Y-%m") + + # [STEP 1] 拉取上月销售 invoice 清单 + _update_progress(run, step="fetch_erp", label="拉取上月销售 invoice") try: - period_month, invoices = fetch_month_invoices(config) + subject_adapter = get_adapter(str(profile.get("subject_adapter") or "hxjm_apa")) + subjects = subject_adapter.fetch(period_month=period_month, config=config) except ServiceUnavailableError as exc: send_failure_alert( task=task, @@ -119,7 +142,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe { "step": "fetch_erp", "status": "success", - "detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")}, + "detail": {"count": len(subjects), "period": period}, } ) @@ -129,169 +152,200 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe "single 模式必须提供 invoice_no", code="VOUCHER_CHECK.INVOICE_REQUIRED", ) - invoices = [row for row in invoices if row.invoice_no == single_invoice] - if not invoices: + subjects = [row for row in subjects if row.invoice_no == single_invoice] + if not subjects: raise NotFoundError( - "指定发票不在当前月 ERP 集合", + "指定发票不在上一个月 ERP 集合", code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD", ) - # [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing) - _update_progress(run, step="share_health", label="检查共享盘可用性") - try: - root = ensure_share_healthy(config) - except ServiceUnavailableError as exc: - send_failure_alert( - task=task, - run=run, - stage="share_health", - error_code=exc.code, - error_message=exc.message, - enabled=config.notify_failure_enabled, - ) - raise - step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}}) - - # [STEP 3] 读取历史状态,供增量判定 - existing_states = ( - db.session.query(VoucherCheckInvoiceState) - .filter_by(scope_code=config.scope_code, period_month=period_month) - .all() + engine_run = create_run( + schedule_run_id=run.id, + run_no=str(run.run_no or f"VC-{run.id}"), + profile_code=str(profile["profile_code"]), + profile_version=str(profile["profile_version"]), + profile_snapshot=profile, + period_month=period_month, + mode=mode, + started_at=now, ) - state_map = {s.invoice_no: s for s in existing_states} + db.session.commit() - results: list[dict[str, Any]] = [] - complete_count = 0 - missing_count = 0 - skipped_count = 0 - technical_error_count = 0 - now = datetime.utcnow() + scan_adapter = get_adapter("directory_scan") + archive_adapter = get_adapter("dms_archive") force = mode in {"force_all", "single"} + previous_fp = {} if force else load_previous_archived_fingerprints( + profile_code=str(profile["profile_code"]), + period_month=period_month, + exclude_run_id=engine_run.id, + ) - # [STEP 4] 逐票扫描 / 指纹比对 + # [STEP 2] 扫描六类类型目录(不调用 PO/OA 打印 Adapter) _update_progress( run, - step="scan_share", - label="扫描共享盘文件名", + step="scan_dms", + label="扫描销售开票附件类型目录", processed=0, voucher_summary={ "scope_code": config.scope_code, - "period": period_month.strftime("%Y-%m"), + "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": 0, - "missing_count": 0, - "scan_count": 0, - "skipped_count": 0, + "subject_count": len(subjects), + "missing_file_count": 0, + "missing_invoice_count": 0, + "skipped_file_count": 0, "technical_error_count": 0, + "complete_invoice_count": 0, }, ) - for idx, row in enumerate(invoices, start=1): - hist = state_map.get(row.invoice_no) - scan = scan_invoice_folder( - config, - root=root, - period_month=period_month, - invoice_no=row.invoice_no, - ) - - # 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹) - can_skip = ( - not force - and hist is not None - and hist.status == "complete" - and hist.material_fingerprint - and scan.result == "complete" - and scan.material_fingerprint == hist.material_fingerprint - ) - if can_skip: - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": "skipped", - "folder_path": scan.folder_path, - "folder_exists": scan.folder_exists, - "material_fingerprint": scan.material_fingerprint, - "matched_files": scan.matched_files, - "missing_materials": [], - "checked_at": None, - } - skipped_count += 1 - elif scan.result == "technical_error": - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": "technical_error", - "folder_path": scan.folder_path, - "folder_exists": False, - "material_fingerprint": None, - "matched_files": {}, - "missing_materials": [], - "error_code": scan.error_code, - "error_message": scan.error_message, + file_results: list[dict[str, Any]] = [] + yyyy = f"{period_month.year:04d}" + mm = f"{period_month.month:02d}" + for idx, subject in enumerate(subjects, start=1): + for rule in rules: + rule_code = str(rule["code"]) + expected = str(rule.get("filename_template") or "").replace("{invoice}", subject.invoice_no) + prev_key = (subject.invoice_no, rule_code) + outcome = scan_adapter.scan( + period_month=period_month, + invoice_no=subject.invoice_no, + rule=rule, + ) + result: dict[str, Any] = { + "invoice_no": subject.invoice_no, + "invoice_date": subject.invoice_date, + "rule_code": rule_code, + "rule_name": rule.get("name") or rule_code, + "source_type": "directory_scan", + "expected_name": expected, + "source_folder_id": outcome.folder_id, + "source_path": outcome.folder_path, "checked_at": now, } - technical_error_count += 1 - else: - item = { - "invoice_no": row.invoice_no, - "invoice_date": row.invoice_date, - "result": scan.result, - "folder_path": scan.folder_path, - "folder_exists": scan.folder_exists, - "material_fingerprint": scan.material_fingerprint, - "matched_files": scan.matched_files, - "missing_materials": scan.missing_materials, - "checked_at": now, - } - if scan.result == "complete": - complete_count += 1 + if ( + not force + and outcome.status == "matched" + and outcome.file + and outcome.file.fingerprint + and previous_fp.get(prev_key) == outcome.file.fingerprint + ): + result.update( + { + "status": "skipped", + "matched_name": outcome.file.filename, + "source_item_id": outcome.file.item_id, + "source_fingerprint": outcome.file.fingerprint, + } + ) + elif outcome.status == "technical_error": + result.update( + { + "status": "technical_error", + "error_code": outcome.error_code, + "error_message": outcome.error_message, + } + ) + elif outcome.status != "matched" or outcome.file is None: + result.update( + { + "status": "missing", + "missing_reason": "类型目录未找到匹配文件", + } + ) else: - missing_count += 1 - results.append(item) + scanned = outcome.file + result.update( + { + "matched_name": scanned.filename, + "source_item_id": scanned.item_id, + "source_fingerprint": scanned.fingerprint, + } + ) + archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{subject.invoice_no}/{scanned.filename}" + result["archive_path"] = archive_path + if getattr(archive_adapter, "wired", False): + try: + archived = archive_adapter.archive( + period_month=period_month, + invoice_no=subject.invoice_no, + file=scanned, + rule=rule, + ) + extra = archived.extra or {} + result.update( + { + "status": "archived", + "archive_item_id": archived.item_id, + "archive_folder_id": archived.folder_id, + "archive_skipped_same_name": bool(extra.get("skipped_same_name")), + } + ) + except ServiceUnavailableError as exc: + result.update( + { + "status": "technical_error", + "error_code": exc.code, + "error_message": exc.message, + } + ) + else: + result["status"] = "staged" + file_results.append(result) - if idx % 20 == 0 or idx == len(invoices): - scan_count = complete_count + missing_count + technical_error_count + if idx % 20 == 0 or idx == len(subjects): + preview = aggregate_file_results(file_results, rules=rules) _update_progress( run, - step="scan_share", - label="扫描共享盘文件名", + step="scan_dms", + label="扫描销售开票附件类型目录", processed=idx, voucher_summary={ "scope_code": config.scope_code, - "period": period_month.strftime("%Y-%m"), + "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": complete_count, - "missing_count": missing_count, - "scan_count": scan_count, - "skipped_count": skipped_count, - "technical_error_count": technical_error_count, + "subject_count": len(subjects), + "missing_file_count": preview["missing_file_count"], + "missing_invoice_count": preview["missing_invoice_count"], + "skipped_file_count": preview["skipped_file_count"], + "technical_error_count": preview["technical_error_count"], + "complete_invoice_count": sum( + 1 for row in preview["excel_rows"] if row["status"] == "完整" + ), }, ) + stats = aggregate_file_results(file_results, rules=rules) step_logs.append( { - "step": "scan_share", + "step": "scan_dms", "status": "success", "detail": { - "complete": complete_count, - "missing": missing_count, - "skipped": skipped_count, - "technical_error": technical_error_count, + "missing_files": stats["missing_file_count"], + "missing_invoices": stats["missing_invoice_count"], + "staged": stats["staged_file_count"], + "skipped": stats["skipped_file_count"], + "technical_error": stats["technical_error_count"], }, } ) - # [STEP 5] 事务落库 + # [STEP 3] 落库单文件结果 _update_progress(run, step="persist", label="写入检核记录") try: - persist_batch_results( - schedule_run_id=run.id, - scope_code=config.scope_code, - period_month=period_month, - items=results, + persist_engine_results( + run=engine_run, + subjects=[ + { + "invoice_no": row.invoice_no, + "invoice_date": row.invoice_date, + "source_fingerprint": row.source_fingerprint, + "attributes": row.attributes, + } + for row in subjects + ], + file_results=file_results, + stats=stats, now=now, ) db.session.commit() @@ -308,58 +362,62 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe ) raise - # [STEP 6] 缺资料通知 - missing_items = [r for r in results if r["result"] == "missing"] - notified = send_missing_notifications( + excel_filename = f"voucher_check_{profile['profile_code']}_{period}_{run.run_no}.xlsx" + executed_at = now.strftime("%Y-%m-%d %H:%M:%S") + details = [ + to_excel_invoice_row(item, period=period, executed_at=executed_at) + for item in stats["excel_rows"] + ] + + # [STEP 4] 每批一条企微汇总 + notify_status = send_batch_missing_summary( task=task, - run=run, - scope_code=config.scope_code, - period_month=period_month, - missing_items=missing_items, - same_day_dedup=config.same_day_dedup_enabled, + schedule_run=run, + engine_run_id=engine_run.id, + profile_code=str(profile["profile_code"]), + period_month=period, + stats=stats, + excel_filename=excel_filename, enabled=config.notify_missing_enabled, ) step_logs.append( { "step": "notify", "status": "success", - "detail": {"missing": len(missing_items), "notified": notified}, + "detail": {"send_status": notify_status, "missing_files": stats["missing_file_count"]}, } ) - period = period_month.strftime("%Y-%m") - scan_count = complete_count + missing_count + technical_error_count + complete_invoices = sum(1 for row in stats["excel_rows"] if row["status"] == "完整") voucher_summary = { "scope_code": config.scope_code, "period": period, "mode": mode, - "total_count": len(invoices), - "complete_count": complete_count, - "missing_count": missing_count, - "scan_count": scan_count, - "skipped_count": skipped_count, - "technical_error_count": technical_error_count, - "missing_notification_count": notified, + "engine_run_id": engine_run.id, + "subject_count": stats["subject_count"], + "missing_file_count": stats["missing_file_count"], + "missing_invoice_count": stats["missing_invoice_count"], + "skipped_file_count": stats["skipped_file_count"], + "technical_error_count": stats["technical_error_count"], + "staged_file_count": stats["staged_file_count"], + "complete_invoice_count": complete_invoices, + "notify_status": notify_status, } _update_progress( run, step="done", label="检核完成", - processed=len(invoices), + processed=len(subjects), voucher_summary=voucher_summary, ) - details = [ - to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results - ] - # success_count = complete + missing(业务成功);failed_count 仅技术异常 - success_count = complete_count + missing_count - total_count = len(invoices) + success_count = stats["subject_count"] + failed_count = 1 if stats["batch_status"] == "technical_failed" and stats["missing_file_count"] == 0 else 0 return ( - total_count, + stats["subject_count"], success_count, - technical_error_count, - skipped_count, + failed_count, + stats["skipped_file_count"], details, errors, step_logs, diff --git a/backend/app/services/voucher_check/schedule_seed.py b/backend/app/services/voucher_check/schedule_seed.py index 936c3d75..500b4a52 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 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。 """ from __future__ import annotations @@ -14,6 +14,7 @@ from typing import Any from sqlalchemy import event from sqlalchemy.orm import Session +from sqlalchemy.orm.attributes import flag_modified from app import db from app.models import ScheduleTask, User @@ -24,20 +25,40 @@ _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" +def _normalize_existing_job_params(raw: Any) -> tuple[dict[str, Any], bool]: + """ + 把已有排程的 job_params 收成当前 schema。 + 核心逻辑:保留 DEFAULT_JOB_PARAMS 与 _advanced;丢掉共享盘时代的未知字段。 + """ + from app.services.schedule.job_params import ADVANCED_PARAMS_KEY + + current = dict(raw) if isinstance(raw, dict) else {} + cleaned: dict[str, Any] = {} + for key, default in DEFAULT_JOB_PARAMS.items(): + value = current.get(key) + cleaned[key] = default if value is None else value + advanced = current.get(ADVANCED_PARAMS_KEY) + if isinstance(advanced, dict): + cleaned[ADVANCED_PARAMS_KEY] = advanced + return cleaned, current != cleaned + + def ensure_default_voucher_check_schedule( *, commit: bool = True, session: Any | None = None, ) -> ScheduleTask | None: """ - 幂等确保默认立账凭证检核日批排程存在。 + 幂等确保默认立账凭证检核周批排程存在。 + 核心逻辑:已存在任务会把日批 cron 改成周二,并剥离 schema 外的旧 job_params, + 避免 worker 执行前校验 unknown params 整批失败。 Args: commit: 是否立即提交。 @@ -56,6 +77,29 @@ def ensure_default_voucher_check_schedule( .first() ) if existing is not None: + changed = False + 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 + changed = True + cleaned_params, params_changed = _normalize_existing_job_params(existing.job_params) + if params_changed: + existing.job_params = cleaned_params + flag_modified(existing, "job_params") + changed = True + _LOGGER.info( + "stripped legacy accounting-voucher-check job_params id=%s", + existing.id, + ) + if changed: + existing.updated_at = datetime.utcnow() + if commit: + sess.commit() return existing owner = ( diff --git a/backend/app/services/voucher_check/share_scanner.py b/backend/app/services/voucher_check/share_scanner.py deleted file mode 100644 index 020e1d13..00000000 --- a/backend/app/services/voucher_check/share_scanner.py +++ /dev/null @@ -1,273 +0,0 @@ -""" -backend/app/services/voucher_check/share_scanner.py - -用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。 -依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。 -逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。 -""" - -from __future__ import annotations - -import os -from dataclasses import dataclass, field -from datetime import date -from pathlib import Path - -from app.core.errors import ServiceUnavailableError, ValidationError -from app.services.voucher_check.config import ( - RequiredFileRule, - VoucherCheckConfig, - resolve_share_root, -) -from app.services.voucher_check.fingerprint import build_material_fingerprint - - -@dataclass -class FileMeta: - """直接子文件元数据。""" - - name: str - size: int - mtime_ns: int - - -@dataclass -class InvoiceScanResult: - """单票扫描结果。""" - - invoice_no: str - folder_path: str - absolute_path: str - folder_exists: bool - material_fingerprint: str | None - matched_files: dict[str, str] = field(default_factory=dict) - missing_materials: list[dict[str, str]] = field(default_factory=list) - result: str = "missing" # complete / missing / technical_error - error_code: str | None = None - error_message: str | None = None - - -def ensure_share_healthy(config: VoucherCheckConfig) -> str: - """ - 校验共享盘根目录可用。 - 核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。 - - Returns: - 解析后的绝对根路径。 - """ - root = resolve_share_root(config) - root_path = Path(root) - try: - if not root_path.exists() or not root_path.is_dir(): - raise ServiceUnavailableError( - "共享盘根目录不可用", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - # [STEP 1] 轻量枚举证明 I/O 可用 - with os.scandir(root_path) as it: - _ = next(it, None) - root_path.stat() - # [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件 - marker = (root_path / config.healthcheck_relative_path).resolve() - if not str(marker).startswith(str(root_path.resolve())): - raise ServiceUnavailableError( - "共享盘健康标记路径非法", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - if not marker.is_file(): - raise ServiceUnavailableError( - "共享盘健康标记文件缺失", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - ) - except ServiceUnavailableError: - raise - except OSError as exc: - raise ServiceUnavailableError( - "共享盘健康检查失败", - code="VOUCHER_CHECK.SHARE_UNAVAILABLE", - details={"error_type": type(exc).__name__}, - ) from exc - return str(root_path) - - -def _render_invoice_relative_path( - template: str, - *, - year: str, - month: str, - invoice_no: str, -) -> str: - """渲染相对业务路径(不含 root 实际值,报告用)。""" - rendered = ( - template.replace("{root}", "vouche") - .replace("{YYYY}", year) - .replace("{MM}", month) - .replace("{invoice_no}", invoice_no) - ) - return rendered.strip("/").replace("\\", "/") - - -def build_invoice_absolute_path( - config: VoucherCheckConfig, - *, - root: str, - period_month: date, - invoice_no: str, -) -> tuple[str, str]: - """ - 构造单票绝对路径与相对业务路径。 - 核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。 - """ - year = f"{period_month.year:04d}" - month = f"{period_month.month:02d}" - invoice = str(invoice_no or "").strip() - if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice: - raise ValidationError( - "发票号含非法路径字符", - code="VOUCHER_CHECK.INVOICE_PATH_INVALID", - details={"invoice_no": invoice_no}, - ) - - relative = _render_invoice_relative_path( - config.directory_template, - year=year, - month=month, - invoice_no=invoice, - ) - # 实际落盘:用真实 root 替换模板中的 {root} - absolute_template = ( - config.directory_template.replace("{root}", root.rstrip("/\\")) - .replace("{YYYY}", year) - .replace("{MM}", month) - .replace("{invoice_no}", invoice) - ) - absolute = str(Path(absolute_template)) - resolved_root = Path(root).resolve() - resolved_abs = Path(absolute).resolve() - try: - resolved_abs.relative_to(resolved_root) - except ValueError as exc: - raise ValidationError( - "发票目录逃逸共享根", - code="VOUCHER_CHECK.INVOICE_PATH_INVALID", - details={"invoice_no": invoice}, - ) from exc - return absolute, relative - - -def list_direct_files(folder: Path) -> list[FileMeta]: - """枚举发票目录直接子文件(忽略子目录与非普通文件)。""" - files: list[FileMeta] = [] - if not folder.is_dir(): - return files - with os.scandir(folder) as it: - for entry in it: - try: - if not entry.is_file(follow_symlinks=False): - continue - stat = entry.stat(follow_symlinks=False) - files.append( - FileMeta( - name=entry.name, - size=int(stat.st_size), - mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))), - ) - ) - except OSError: - continue - return files - - -def match_required_files( - files: list[FileMeta], - rules: tuple[RequiredFileRule, ...], - *, - case_sensitive: bool, -) -> tuple[dict[str, str], list[dict[str, str]]]: - """ - 按完整文件名精确匹配必检材料。 - 核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。 - """ - if case_sensitive: - available = {f.name: f.name for f in files} - else: - available = {f.name.lower(): f.name for f in files} - - matched: dict[str, str] = {} - missing: list[dict[str, str]] = [] - for rule in rules: - if not rule.required: - continue - hit: str | None = None - for candidate in rule.accepted_filenames: - key = candidate if case_sensitive else candidate.lower() - if key in available: - hit = available[key] - break - if hit: - matched[rule.code] = hit - else: - missing.append({"code": rule.code, "name": rule.name}) - return matched, missing - - -def scan_invoice_folder( - config: VoucherCheckConfig, - *, - root: str, - period_month: date, - invoice_no: str, -) -> InvoiceScanResult: - """ - 扫描单票目录并判定齐全/缺资料。 - 核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。 - """ - try: - absolute, relative = build_invoice_absolute_path( - config, - root=root, - period_month=period_month, - invoice_no=invoice_no, - ) - except ValidationError as exc: - return InvoiceScanResult( - invoice_no=str(invoice_no or "").strip(), - folder_path="", - absolute_path="", - folder_exists=False, - material_fingerprint=None, - result="technical_error", - error_code=exc.code, - error_message=exc.message, - ) - - folder = Path(absolute) - if not folder.exists() or not folder.is_dir(): - missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required] - return InvoiceScanResult( - invoice_no=str(invoice_no).strip(), - folder_path=relative, - absolute_path=absolute, - folder_exists=False, - material_fingerprint=None, - missing_materials=missing, - result="missing", - ) - - files = list_direct_files(folder) - fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files]) - matched, missing = match_required_files( - files, - config.required_files, - case_sensitive=config.filename_case_sensitive, - ) - return InvoiceScanResult( - invoice_no=str(invoice_no).strip(), - folder_path=relative, - absolute_path=absolute, - folder_exists=True, - material_fingerprint=fingerprint, - matched_files=matched, - missing_materials=missing, - result="complete" if not missing else "missing", - ) diff --git a/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py b/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py new file mode 100644 index 00000000..daa7c41a --- /dev/null +++ b/backend/migrations/versions/na0b1c2d3e4f5_merge_voucher_engine_and_dev_heads.py @@ -0,0 +1,30 @@ +"""合并立账凭证引擎表与 dev 集成连接器两条 Alembic 头。 + +Revision ID: na0b1c2d3e4f5 +Revises: n9a0b1c2d3e4, vc1a2b3c4d5e +Create Date: 2026-09-07 14:25:00.000000 + +用途:将 ``invoice-check`` 的 ``vc1a2b3c4d5e``(立账凭证引擎表)与 + ``dev`` 的 ``n9a0b1c2d3e4``(集成连接器 / 合同付款 head 合并)收成单一升级路径, + 避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。 +依赖:``n9a0b1c2d3e4``、``vc1a2b3c4d5e``。 +逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。 +""" + +from alembic import op # noqa: F401 - Alembic migration module contract + + +revision = "na0b1c2d3e4f5" +down_revision = ("n9a0b1c2d3e4", "vc1a2b3c4d5e") +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """合并立账凭证引擎 head 与 dev 集成连接器 head,不执行数据库结构变更。""" + pass + + +def downgrade() -> None: + """撤销合并节点;不会回滚两个父分支的业务变更。""" + pass 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/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py b/backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py new file mode 100644 index 00000000..0ed705e8 --- /dev/null +++ b/backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py @@ -0,0 +1,133 @@ +""" +backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py + +用途:删除旧共享盘方案的 voucher_check_invoice_states / voucher_check_run_items。 +依赖:Alembic revision na0b1c2d3e4f5。 +逻辑:先删 run_items(外键指向 states),再删 states;引擎表不受影响。 + +Revision ID: vc2b3c4d5e6f +Revises: na0b1c2d3e4f5 +Create Date: 2026-09-08 09:20:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "vc2b3c4d5e6f" +down_revision = "na0b1c2d3e4f5" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """删除旧一票一状态表;检核结果以 voucher_check_file_results 为准。""" + op.drop_index("ix_voucher_check_run_items_period_result", table_name="voucher_check_run_items") + op.drop_index("ix_voucher_check_run_items_run_result", table_name="voucher_check_run_items") + op.drop_index("ix_voucher_check_run_items_schedule_run_id", table_name="voucher_check_run_items") + op.drop_table("voucher_check_run_items") + op.drop_index("ix_voucher_check_invoice_states_notified_on", table_name="voucher_check_invoice_states") + op.drop_index("ix_voucher_check_invoice_states_invoice_no", table_name="voucher_check_invoice_states") + op.drop_index("ix_voucher_check_invoice_states_period_status", table_name="voucher_check_invoice_states") + op.drop_table("voucher_check_invoice_states") + + +def downgrade() -> None: + """回建旧表结构,不恢复历史数据。""" + op.create_table( + "voucher_check_invoice_states", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column("scope_code", sa.String(length=32), nullable=False), + sa.Column("period_month", sa.Date(), nullable=False), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("invoice_date", sa.Date(), nullable=True), + sa.Column("status", sa.String(length=24), nullable=False), + sa.Column("folder_path", sa.String(length=1024), nullable=True), + sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")), + sa.Column("material_fingerprint", sa.String(length=64), nullable=True), + sa.Column("matched_files_json", sa.JSON(), nullable=True), + sa.Column("missing_materials_json", sa.JSON(), nullable=True), + sa.Column( + "last_actual_run_id", + sa.BigInteger(), + sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("last_checked_at", sa.DateTime(), nullable=True), + sa.Column("last_seen_erp_at", sa.DateTime(), nullable=True), + sa.Column("last_missing_notified_on", sa.Date(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint( + "scope_code", + "period_month", + "invoice_no", + name="uq_voucher_check_invoice_states_scope_period_invoice", + ), + ) + op.create_index( + "ix_voucher_check_invoice_states_period_status", + "voucher_check_invoice_states", + ["period_month", "status"], + ) + op.create_index( + "ix_voucher_check_invoice_states_invoice_no", + "voucher_check_invoice_states", + ["invoice_no"], + ) + op.create_index( + "ix_voucher_check_invoice_states_notified_on", + "voucher_check_invoice_states", + ["last_missing_notified_on"], + ) + op.create_table( + "voucher_check_run_items", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "schedule_run_id", + sa.BigInteger(), + sa.ForeignKey("schedule_runs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column( + "invoice_state_id", + sa.BigInteger(), + sa.ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"), + nullable=True, + ), + sa.Column("scope_code", sa.String(length=32), nullable=False), + sa.Column("period_month", sa.Date(), nullable=False), + sa.Column("invoice_no", sa.String(length=128), nullable=False), + sa.Column("invoice_date", sa.Date(), nullable=True), + sa.Column("result", sa.String(length=24), nullable=False), + sa.Column("folder_path", sa.String(length=1024), nullable=True), + sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")), + sa.Column("material_fingerprint", sa.String(length=64), nullable=True), + sa.Column("matched_files_json", sa.JSON(), nullable=True), + sa.Column("missing_materials_json", sa.JSON(), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("checked_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.UniqueConstraint( + "schedule_run_id", + "invoice_no", + name="uq_voucher_check_run_items_run_invoice", + ), + ) + op.create_index( + "ix_voucher_check_run_items_schedule_run_id", + "voucher_check_run_items", + ["schedule_run_id"], + ) + op.create_index( + "ix_voucher_check_run_items_run_result", + "voucher_check_run_items", + ["schedule_run_id", "result"], + ) + op.create_index( + "ix_voucher_check_run_items_period_result", + "voucher_check_run_items", + ["period_month", "result"], + ) diff --git a/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py b/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py new file mode 100644 index 00000000..c3138889 --- /dev/null +++ b/backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py @@ -0,0 +1,146 @@ +""" +backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py + +用途:清掉立账凭证检核排程里共享盘时代的 job_params,避免 worker 报 unknown params。 +依赖:Alembic revision vc2b3c4d5e6f;schedule_tasks 已存在。 +逻辑:保留 scope_code / profile_code / 通知开关 / _advanced;日批 cron 改为周二。 + +Revision ID: vc3d4e5f6a7b +Revises: vc2b3c4d5e6f +Create Date: 2026-09-08 10:10:00.000000 +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "vc3d4e5f6a7b" +down_revision = "vc2b3c4d5e6f" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK" +_WEEKLY_CRON = "0 6 * * 2" +_WEEKLY_NAME = "立账凭证检核(周批)" +_DAILY_CRON = "0 6 * * *" +_DAILY_NAME = "立账凭证检核(日批)" +_TZ_NAME = "Asia/Shanghai" + +_DEFAULTS = { + "profile_code": "sales", + "scope_code": "HXJM", + "notify_missing_enabled": True, + "notify_failure_enabled": True, +} + + +def _as_dict(raw) -> dict: + """把 JSON 列读成 dict;驱动可能返回 dict 或字符串。""" + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + if isinstance(raw, str): + text = raw.strip() + if not text: + return {} + loaded = json.loads(text) + return dict(loaded) if isinstance(loaded, dict) else {} + return {} + + +def _clean_job_params(raw) -> dict: + """只保留当前 schema 字段,丢掉 directory_template / required_files 等旧键。""" + current = _as_dict(raw) + cleaned = {} + for key, default in _DEFAULTS.items(): + value = current.get(key) + cleaned[key] = default if value is None else value + advanced = current.get("_advanced") + if isinstance(advanced, dict): + cleaned["_advanced"] = advanced + return cleaned + + +def _next_weekly_run_utc_naive() -> datetime: + """计算下一个周二 06:00 Asia/Shanghai,写入 naive UTC。""" + try: + from croniter import croniter + from zoneinfo import ZoneInfo + + tz = ZoneInfo(_TZ_NAME) + next_local = croniter(_WEEKLY_CRON, datetime.now(tz)).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) + days = (1 - now_local.weekday()) % 7 + next_local = (now_local + timedelta(days=days)).replace( + hour=6, minute=0, second=0, microsecond=0 + ) + if next_local <= now_local: + next_local = next_local + timedelta(days=7) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> None: + """清洗 accounting-voucher-check 排程参数;无任务时跳过。""" + conn = op.get_bind() + rows = conn.execute( + sa.text( + """ + SELECT id, job_params, cron_expr, name + FROM schedule_tasks + WHERE schedule_no = :sno + OR platform_api_path = 'accounting-voucher-check' + """ + ), + {"sno": _SCHEDULE_NO}, + ).mappings().all() + now = datetime.utcnow() + next_run = _next_weekly_run_utc_naive() + for row in rows: + cleaned = _clean_job_params(row["job_params"]) + cron_expr = row["cron_expr"] + name = row["name"] + next_run_at = None + if cron_expr == _DAILY_CRON: + cron_expr = _WEEKLY_CRON + next_run_at = next_run + if name == _DAILY_NAME: + name = _WEEKLY_NAME + conn.execute( + sa.text( + """ + UPDATE schedule_tasks + SET job_params = CAST(:job_params AS JSONB), + cron_expr = :cron_expr, + name = :name, + next_run_at = COALESCE(:next_run_at, next_run_at), + updated_at = :now + WHERE id = :id + """ + ).bindparams( + sa.bindparam("job_params", type_=sa.String()), + sa.bindparam("next_run_at", type_=sa.DateTime(), required=False), + ), + { + "id": int(row["id"]), + "job_params": json.dumps(cleaned, ensure_ascii=False), + "cron_expr": cron_expr, + "name": name, + "now": now, + "next_run_at": next_run_at, + }, + ) + + +def downgrade() -> None: + """旧共享盘字段无法无损恢复,downgrade 为空操作。""" + return diff --git a/backend/scripts/export_voucher_check_openapi.py b/backend/scripts/export_voucher_check_openapi.py deleted file mode 100644 index da8c97ce..00000000 --- a/backend/scripts/export_voucher_check_openapi.py +++ /dev/null @@ -1,39 +0,0 @@ -""" -backend/scripts/export_voucher_check_openapi.py - -用途:导出立账凭证检核 Tool OpenAPI 到 docs/openapi,供 Dify 粘贴/对比。 -依赖:voucher_check.openapi_spec。 -逻辑:仓库静态 JSON 使用占位地址;各环境请用 URL 导入 GET .../openapi.json。 -""" - -from __future__ import annotations - -import json -import os -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -# 不经 app 包导入,避免导出脚本依赖本机 Flask venv -_SPEC_PATH = ROOT / "backend" / "app" / "services" / "voucher_check" / "openapi_base.json" - - -def main() -> None: - base = ( - os.getenv("HXOPS_TOOLS_API_BASE") - or os.getenv("PUBLIC_BASE_URL") - or "http://127.0.0.1:5052" - ).rstrip("/") - spec = json.loads(_SPEC_PATH.read_text(encoding="utf-8")) - if isinstance(spec.get("servers"), list) and spec["servers"]: - spec["servers"][0]["url"] = base - spec["servers"][0]["description"] = "HXOPS_TOOLS_API_BASE" - out_dir = ROOT / "docs" / "openapi" - out_dir.mkdir(parents=True, exist_ok=True) - json_path = out_dir / "accounting_voucher_check_tools_openapi.json" - json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(f"Wrote {json_path}") - print(f"Import URL: {base}/api/accounting-voucher-check/tools/openapi.json") - - -if __name__ == "__main__": - main() diff --git a/backend/tests/jobs/test_schedule_queue.py b/backend/tests/jobs/test_schedule_queue.py index acb22d02..61377698 100644 --- a/backend/tests/jobs/test_schedule_queue.py +++ b/backend/tests/jobs/test_schedule_queue.py @@ -1,7 +1,7 @@ """ backend/tests/jobs/test_schedule_queue.py -用途:验证排程迁出 Web 后的手动入队、Cron 扫描与 Job handler 状态闭环。 +用途:验证排程迁出 Web 后的手动入队、Cron 扫描、Job 业务身份字段与 handler 状态闭环。 依赖:通用 app fixture、models.Job/ScheduleRun/ScheduleTask、schedule.queue_service。 逻辑:只替换真正的排程执行器,不启动后台线程,断言 API/worker 之间的数据契约。 """ @@ -16,8 +16,16 @@ from app.models import Job, ScheduleRun, ScheduleTask, User from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run -def _create_task(*, due: bool = False) -> ScheduleTask: - """创建测试用户与排程;due=True 时令 next_run_at 已到期。""" +def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask: + """ + 创建测试用户与排程。 + 核心逻辑:due=True 时令 next_run_at 已到期;可指定 platform_api_path 覆盖默认 data_pipeline。 + + Args: + due: 是否立即到期,供 Cron 扫描测试。 + platform_api_path: 平台任务 key;有值时 schedule_type 改为 platform_job。 + name: 排程显示名,写入 jobs.message。 + """ suffix = str(datetime.utcnow().timestamp()).replace(".", "-") user = User( username=f"schedule-owner-{suffix}", @@ -30,8 +38,9 @@ def _create_task(*, due: bool = False) -> ScheduleTask: db.session.flush() task = ScheduleTask( schedule_no=f"SCH-TEST-{datetime.utcnow().timestamp()}", - name="schedule queue test", - schedule_type="data_pipeline", + name=name, + schedule_type="platform_job" if platform_api_path else "data_pipeline", + platform_api_path=platform_api_path, owner_user_id=user.id, cron_expr="0 3 * * *", schedule_timezone="Asia/Shanghai", @@ -57,6 +66,8 @@ def test_manual_schedule_run_creates_queued_job(app): assert job.domain == "schedule" assert job.job_type == JobType.SCHEDULE_RUN.value assert job.payload_json["schedule_run_id"] == run.id + assert job.business_ref == f"schedule_run:{run.id}:untagged" + assert job.message == "schedule queue test等待后台执行" def test_due_schedule_scan_is_idempotent(app): @@ -101,3 +112,51 @@ def test_schedule_handler_finishes_generic_job(app, monkeypatch): db.session.expire_all() assert db.session.get(ScheduleRun, run.id).status == "success" assert db.session.get(Job, job_id).status == "success" + + +def test_schedule_job_identity_uses_platform_api_path(app): + """关键断言:立账凭证等平台任务在 jobs 表用 business_ref/payload 区分,不改 job_type。""" + from app.services.schedule.queue_service import query_jobs_for_schedule_run + from app.services.schedule.scheduler_service import request_cancel_run + + with app.app_context(): + task = _create_task(platform_api_path="accounting-voucher-check", name="立账凭证检核") + run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + job = db.session.get(Job, job_id) + + assert created is True + assert job.domain == "schedule" + assert job.job_type == JobType.SCHEDULE_RUN.value + assert job.business_ref == f"schedule_run:{run.id}:accounting-voucher-check" + assert job.payload_json["platform_api_path"] == "accounting-voucher-check" + assert job.payload_json["task_name"] == "立账凭证检核" + assert job.payload_json["schedule_no"] == task.schedule_no + assert job.message == "立账凭证检核等待后台执行" + assert query_jobs_for_schedule_run(run.id).filter(Job.status == "queued").one().id == job_id + + request_cancel_run(run.id) + db.session.commit() + db.session.expire_all() + cancelled = db.session.get(Job, job_id) + assert cancelled.status == "cancelled" + + +def test_query_jobs_for_schedule_run_matches_legacy_business_ref(app): + """关键断言:取消/回收仍能命中升级前 `schedule_run:{id}` 旧格式。""" + from app.services.schedule.queue_service import query_jobs_for_schedule_run + from app.services.schedule.scheduler_service import request_cancel_run + + with app.app_context(): + task = _create_task() + run, job_id, _created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + job = db.session.get(Job, job_id) + job.business_ref = f"schedule_run:{run.id}" + db.session.commit() + + found = query_jobs_for_schedule_run(run.id).one() + assert found.id == job_id + + request_cancel_run(run.id) + db.session.commit() + db.session.expire_all() + assert db.session.get(Job, job_id).status == "cancelled" 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/test_schedule_run_executor_error.py b/backend/tests/test_schedule_run_executor_error.py new file mode 100644 index 00000000..d5da36e1 --- /dev/null +++ b/backend/tests/test_schedule_run_executor_error.py @@ -0,0 +1,43 @@ +""" +backend/tests/test_schedule_run_executor_error.py + +用途:排程 handler 抛错时 ScheduleRun 必须记 failed,不能因 failed_count=0 标成 success。 +依赖:scheduler_service.run_task_now、ScheduleTask/ScheduleRun。 +逻辑:monkeypatch executor 抛出配置错误,断言 status=failed 且 error_message 保留原文。 +""" + +from __future__ import annotations + +from app import db +from app.models import ScheduleRun, ScheduleTask, User +from app.services.schedule.scheduler_service import run_task_now + + +def test_run_task_now_marks_executor_exception_as_failed(app, monkeypatch): + """handler 抛 RuntimeError 时,批次状态应为 failed 且 failed_count=1。""" + def _boom(_task: ScheduleTask, _run: ScheduleRun): + raise RuntimeError("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME") + + monkeypatch.setattr( + "app.services.schedule.scheduler_service.resolve_schedule_executor", + lambda _task: _boom, + ) + with app.app_context(): + user = User(username="sched-exec-err", email="sched-exec-err@example.com") + db.session.add(user) + db.session.flush() + task = ScheduleTask( + schedule_no="SCH-TEST-EXECUTOR-ERROR", + name="executor error fixture", + schedule_type="platform_job", + platform_api_path="accounting-voucher-check", + owner_user_id=user.id, + cron_expr="0 6 * * 2", + enabled=True, + ) + db.session.add(task) + db.session.commit() + result = run_task_now(task, trigger_type="manual", triggered_by_user_id=user.id) + assert result.status == "failed" + assert result.failed_count == 1 + assert "VOUCHER_CHECK_ERP" in (result.error_message or "") 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..1a40fcf8 --- /dev/null +++ b/backend/tests/voucher_check/test_engine_profile_and_scan.py @@ -0,0 +1,127 @@ +""" +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"] == "有" + assert stats["by_file_type"]["po_order"]["missing_file_count"] == 1 + assert stats["by_file_type"]["po_order"]["missing_invoice_count"] == 1 + assert stats["by_file_type"]["tax_invoice"]["missing_file_count"] == 0 + + +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_erp_settings.py b/backend/tests/voucher_check/test_erp_settings.py new file mode 100644 index 00000000..ead9c5d1 --- /dev/null +++ b/backend/tests/voucher_check/test_erp_settings.py @@ -0,0 +1,29 @@ +""" +backend/tests/voucher_check/test_erp_settings.py + +用途:立账凭证 ERP 凭据回退到通用 ERP_* / 合同付款同一套只读账号。 +依赖:voucher_check.config._erp_settings、Flask app。 +逻辑:清空 VOUCHER_CHECK_ERP_USERNAME 后仍能从 CONTRACT_PAYMENT_ERP_* 读到账号。 +""" + +from __future__ import annotations + +from app.services.voucher_check.config import _erp_settings + + +def test_erp_settings_falls_back_to_contract_payment_credentials(app): + """未单独配 VOUCHER_CHECK_ERP_USERNAME 时,应复用合同付款已有的只读账号。""" + with app.app_context(): + app.config["VOUCHER_CHECK_ERP_DSN"] = "" + app.config["VOUCHER_CHECK_ERP_USERNAME"] = "" + app.config["VOUCHER_CHECK_ERP_PASSWORD"] = "" + app.config["ERP_DB_DSN"] = "192.168.8.24:1521/topprod" + app.config["ERP_USERNAME"] = "" + app.config["ERP_PASSWORD"] = "" + app.config["CONTRACT_PAYMENT_ERP_USERNAME"] = "hxjm_ro" + app.config["CONTRACT_PAYMENT_ERP_PASSWORD"] = "secret-from-contract-payment" + dsn, username, password, timeout = _erp_settings() + assert dsn == "192.168.8.24:1521/topprod" + assert username == "hxjm_ro" + assert password == "secret-from-contract-payment" + assert timeout >= 1 diff --git a/backend/tests/voucher_check/test_share_and_fingerprint.py b/backend/tests/voucher_check/test_share_and_fingerprint.py deleted file mode 100644 index 43ee3b13..00000000 --- a/backend/tests/voucher_check/test_share_and_fingerprint.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -backend/tests/voucher_check/test_share_and_fingerprint.py - -用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。 -依赖:pytest、临时目录、voucher_check 领域模块。 -逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。 -""" - -from __future__ import annotations - -from datetime import date -from pathlib import Path - -import pytest - -from app.core.errors import ValidationError -from app.services.voucher_check.config import ( - RequiredFileRule, - validate_directory_template, -) -from app.services.voucher_check.fingerprint import build_material_fingerprint -from app.services.voucher_check.share_scanner import ( - FileMeta, - match_required_files, - scan_invoice_folder, -) - - -def test_directory_template_rejects_unknown_placeholder(): - with pytest.raises(ValidationError) as exc: - validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}") - assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID" - - -def test_exact_filename_match_and_zero_byte_counts(): - rules = ( - RequiredFileRule( - code="price_check_sheet", - name="核价单", - required=True, - accepted_filenames=("核价单.pdf",), - ), - RequiredFileRule( - code="purchase_order", - name="采购单", - required=True, - accepted_filenames=("采购单.pdf",), - ), - ) - files = [ - FileMeta(name="核价单.pdf", size=0, mtime_ns=1), - FileMeta(name="采购单.pdf", size=10, mtime_ns=2), - ] - matched, missing = match_required_files(files, rules, case_sensitive=True) - assert matched["price_check_sheet"] == "核价单.pdf" - assert matched["purchase_order"] == "采购单.pdf" - assert missing == [] - - -def test_subdir_same_name_does_not_count(tmp_path: Path): - """直接子文件才命中;子目录内同名文件不算。""" - from app.services.voucher_check.config import VoucherCheckConfig - - root = tmp_path / "vouche" - inv_dir = root / "2026" / "08" / "INV001" - inv_dir.mkdir(parents=True) - nested = inv_dir / "nested" - nested.mkdir() - (nested / "核价单.pdf").write_bytes(b"x") - (inv_dir / "采购单.pdf").write_bytes(b"y") - - cfg = VoucherCheckConfig( - scope_code="HXJM", - directory_template="{root}/{YYYY}/{MM}/{invoice_no}", - required_files=( - RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)), - RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)), - ), - filename_case_sensitive=True, - notify_missing_enabled=False, - notify_failure_enabled=False, - same_day_dedup_enabled=False, - local_root=str(root), - share_unc="", - healthcheck_relative_path=".hxops-share-ready", - erp_dsn="x", - erp_username="u", - erp_password="p", - ) - result = scan_invoice_folder( - cfg, - root=str(root), - period_month=date(2026, 8, 1), - invoice_no="INV001", - ) - assert result.result == "missing" - assert any(m["code"] == "price_check_sheet" for m in result.missing_materials) - assert result.matched_files.get("purchase_order") == "采购单.pdf" - - -def test_fingerprint_stable_and_changes_on_mtime(): - a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)]) - b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)]) - assert a == b - c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)]) - assert a != c diff --git a/backend/tests/voucher_check/test_tool_auth_and_openapi.py b/backend/tests/voucher_check/test_tool_auth_and_openapi.py deleted file mode 100644 index a0def318..00000000 --- a/backend/tests/voucher_check/test_tool_auth_and_openapi.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -backend/tests/voucher_check/test_tool_auth_and_openapi.py - -用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。 -依赖:pytest、openapi_base.json。 -逻辑:直接读 JSON,校验 operationId 与 securitySchemes。 -""" - -from __future__ import annotations - -import json -from pathlib import Path - -_SPEC = ( - Path(__file__).resolve().parents[2] - / "app" - / "services" - / "voucher_check" - / "openapi_base.json" -) - - -def test_openapi_base_contains_expected_operations(): - spec = json.loads(_SPEC.read_text(encoding="utf-8")) - paths = spec["paths"] - assert ( - paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"] - == "list_voucher_missing" - ) - assert ( - paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"] - == "list_voucher_run_items" - ) - assert ( - paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"] - == "get_voucher_invoice_latest" - ) - assert "BearerAuth" in spec["components"]["securitySchemes"] - assert "IntegrationKey" in spec["components"]["securitySchemes"] - - -def test_docs_openapi_export_in_sync(): - docs = ( - Path(__file__).resolve().parents[3] - / "docs" - / "openapi" - / "accounting_voucher_check_tools_openapi.json" - ) - assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py" - exported = json.loads(docs.read_text(encoding="utf-8")) - base = json.loads(_SPEC.read_text(encoding="utf-8")) - assert exported["paths"].keys() == base["paths"].keys() 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..16c707ba --- /dev/null +++ b/backend/tests/voucher_check/test_workspace_force_recheck.py @@ -0,0 +1,203 @@ +""" +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.core.errors import ValidationError +from app.services.voucher_check.dms_client import SalesDmsClient +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 _stub_force_run_preflight(monkeypatch) -> None: + """隔离配置预校验,只验证工作台入队和失败可见性契约。""" + monkeypatch.setattr( + "app.services.voucher_check.config.load_engine_config", + lambda _params: type("Config", (), {"profile_code": "sales"})(), + ) + monkeypatch.setattr( + "app.services.voucher_check.profile_loader.load_profile_definition", + lambda _code: {"profile_code": "sales"}, + ) + monkeypatch.setattr( + "app.services.voucher_check.profile_loader.ensure_published_profile", + lambda _code: None, + ) + monkeypatch.setattr("app.services.voucher_check.dms_client.SalesDmsClient.ensure_configured", lambda: None) + + +def test_dms_preflight_reports_missing_keys_without_secret_values(app, monkeypatch): + """DMS 配置缺失时要指出变量名,且不在错误内容中泄露凭据值。""" + with app.app_context(): + monkeypatch.setattr(SalesDmsClient, "base_url", classmethod(lambda _cls: "https://dms.example")) + monkeypatch.setattr(SalesDmsClient, "library_id", classmethod(lambda _cls: "library-id")) + monkeypatch.setattr(SalesDmsClient, "root_folder_id", classmethod(lambda _cls: "folder-id")) + monkeypatch.setattr(SalesDmsClient, "username", classmethod(lambda _cls: "")) + monkeypatch.setattr(SalesDmsClient, "password", classmethod(lambda _cls: "")) + try: + SalesDmsClient.ensure_configured() + except ValidationError as exc: + assert exc.code == "VOUCHER_CHECK.CONFIG_INVALID" + assert exc.details["missing"] == ["VOUCHER_CHECK_DMS_USERNAME", "VOUCHER_CHECK_DMS_PASSWORD"] + else: + raise AssertionError("expected missing DMS configuration to fail") + + +def test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers, monkeypatch): + """工作台按钮入队后,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 + _stub_force_run_preflight(monkeypatch) + + 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, monkeypatch): + with app.app_context(): + _ensure_user(username="admin", role="admin") + _ensure_user(username="user", role="user") + ensure_default_voucher_check_schedule(commit=True) + _stub_force_run_preflight(monkeypatch) + + 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" + + +def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, admin_headers): + """配置校验在建引擎批次前失败时,页面仍应展示技术失败与原因。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + run = ScheduleRun( + schedule_task_id=task.id, + run_no="RUN-PREENGINE-FAILED", + trigger_type="manual", + status="failed", + total_count=0, + success_count=0, + failed_count=1, + error_message="未配置销售开票附件文档库根目录", + response_summary_json={"voucher_check": {"period": "2026-08"}}, + ) + db.session.add(run) + db.session.commit() + + response = client.get( + "/api/workspace/accounting-voucher-check/runs?period=2026-08&status=technical_failed", + headers=admin_headers, + ) + assert response.status_code == 200 + payload = parse_api_data(response.get_json()) + assert payload["total"] == 1 + item = payload["items"][0] + # 关键断言:前端列表读取的 run 数据保留失败原因,而非呈现为“暂无检核批次”。 + assert item["run_no"] == "RUN-PREENGINE-FAILED" + assert item["status"] == "technical_failed" + assert item["error_message"] == "未配置销售开票附件文档库根目录" + + +def test_seed_strips_legacy_share_job_params(app): + """已有排程若仍带共享盘旧字段,启动/入队种子必须剥掉,否则 worker 会 unknown params。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + task.job_params = { + "scope_code": "HXJM", + "profile_code": "sales", + "notify_missing_enabled": True, + "notify_failure_enabled": True, + "directory_template": "{root}/{YYYY}/{MM}/{invoice_no}", + "dir_template": "{root}/{YYYY}/{MM}/{invoice_no}", + "required_files": ["核价单.pdf", "采购单.pdf"], + "filename_case_sensitive": True, + "case_sensitive": False, + "same_day_dedup_enabled": True, + "same_day_dedup": True, + } + db.session.commit() + + refreshed = ensure_default_voucher_check_schedule(commit=True) + params = refreshed.job_params if isinstance(refreshed.job_params, dict) else {} + assert "directory_template" not in params + assert "dir_template" not in params + assert "required_files" not in params + assert "filename_case_sensitive" not in params + assert "case_sensitive" not in params + assert "same_day_dedup_enabled" not in params + assert "same_day_dedup" not in params + assert params["scope_code"] == "HXJM" + assert params["profile_code"] == "sales" diff --git a/backend/tests/voucher_check/test_workspace_notifications.py b/backend/tests/voucher_check/test_workspace_notifications.py new file mode 100644 index 00000000..14746518 --- /dev/null +++ b/backend/tests/voucher_check/test_workspace_notifications.py @@ -0,0 +1,144 @@ +""" +backend/tests/voucher_check/test_workspace_notifications.py + +用途:工作台企微发送记录列表 API。 +依赖:pytest、Flask client;不发送真实企微。 +逻辑:GET /api/workspace/accounting-voucher-check/notifications 读 voucher_check_notifications, + 回填接收人姓名与 has_excel,并可按期间、发送状态筛选。 +""" + +from __future__ import annotations + +from datetime import date, datetime + +from tests.conftest import parse_api_data + +from app import db +from app.models import ScheduleRun, User +from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun +from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule + + +def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> User: + """测试用户幂等创建。""" + user = db.session.query(User).filter_by(username=username).first() + if user: + user.role = role + user.status = "active" + if real_name: + user.real_name = real_name + db.session.commit() + return user + user = User( + username=username, + email=f"{username}@example.com", + role=role, + status="active", + real_name=real_name, + ) + user.set_password("test") + db.session.add(user) + db.session.commit() + return user + + +def test_workspace_lists_wecom_notifications(app, client, user_headers): + """企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。""" + with app.app_context(): + _ensure_user(username="admin", role="admin") + recipient = _ensure_user(username="user", role="user", real_name="Zhang San") + task = ensure_default_voucher_check_schedule(commit=True) + assert task is not None + schedule_run = ScheduleRun( + schedule_task_id=task.id, + run_no="RUN-VC-NOTIFY-1", + trigger_type="cron", + status="success", + excel_file_name="voucher-check-2026-08.xlsx", + excel_file_size=12, + excel_file_data=b"xlsx-bytes", + ) + db.session.add(schedule_run) + db.session.flush() + engine_run = VoucherCheckRun( + id=1, + schedule_run_id=schedule_run.id, + run_no="VC-202608-001", + profile_code="sales", + profile_version="1", + profile_snapshot_json={"profile_code": "sales"}, + period_month=date(2026, 8, 1), + mode="incremental", + status="missing", + subject_count=10, + missing_file_count=4, + missing_invoice_count=2, + ) + db.session.add(engine_run) + db.session.flush() + db.session.add( + VoucherCheckNotification( + id=1, + run_id=engine_run.id, + excel_filename="voucher-check-2026-08.xlsx", + recipient_user_ids_json=[recipient.id], + send_status="sent", + skip_reason=None, + summary_json={"period": "2026-08", "subject_count": 10}, + sent_at=datetime(2026, 9, 1, 6, 10, 0), + ) + ) + skipped_run = VoucherCheckRun( + id=2, + run_no="VC-202607-001", + profile_code="sales", + profile_version="1", + profile_snapshot_json={"profile_code": "sales"}, + period_month=date(2026, 7, 1), + mode="incremental", + status="completed", + subject_count=8, + missing_file_count=0, + missing_invoice_count=0, + ) + db.session.add(skipped_run) + db.session.flush() + db.session.add( + VoucherCheckNotification( + id=2, + run_id=skipped_run.id, + send_status="skipped_no_missing", + skip_reason="本批无缺件", + summary_json={"period": "2026-07"}, + ) + ) + db.session.commit() + + listed = client.get( + "/api/workspace/accounting-voucher-check/notifications", + headers=user_headers, + ) + assert listed.status_code == 200 + payload = parse_api_data(listed.get_json()) + assert payload["total"] >= 2 + sent = next(item for item in payload["items"] if item["run_no"] == "VC-202608-001") + # 关键断言:工作台汇总列表能看到发送状态、接收人姓名和 Excel 入口。 + assert sent["send_status"] == "sent" + assert sent["missing_invoice_count"] == 2 + assert sent["missing_file_count"] == 4 + assert sent["recipient_names"] == ["Zhang San"] + assert sent["has_excel"] is True + assert sent["schedule_run_id"] + + filtered = client.get( + "/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing", + headers=user_headers, + ) + assert filtered.status_code == 200 + filtered_payload = parse_api_data(filtered.get_json()) + assert filtered_payload["total"] == 1 + item = filtered_payload["items"][0] + assert item["run_no"] == "VC-202607-001" + assert item["send_status"] == "skipped_no_missing" + assert item["skip_reason"] == "本批无缺件" + assert item["has_excel"] is False diff --git a/backend/worker.py b/backend/worker.py index d26886f4..470cd720 100644 --- a/backend/worker.py +++ b/backend/worker.py @@ -4,6 +4,7 @@ backend/worker.py 用途:统一后台 worker 入口(方案 D)。 依赖:app.create_app、app.jobs.runner、app.jobs.handlers。 逻辑:--queues kb,shipping,contract,schedule;经 jobs.runner 统一 poll → dispatch。 + 启动诊断按队列打印,避免 schedule worker 误刷合同付款预警 ERP 配置。 """ from __future__ import annotations @@ -55,6 +56,35 @@ def _resolve_config_name() -> str: return mapping.get(env_name, 'production') +def _log_queue_startup_diagnostics(logger: logging.Logger, app, queue_names: list[str]) -> None: + """ + 按实际消费队列打印启动诊断,避免 schedule worker 刷出合同付款预警配置造成误判。 + + 核心逻辑:contract 队列才打印合同付款 ERP 就绪状态;schedule 队列说明 jobs 表身份字段。 + 只标记配置是否就绪,不输出密码或连接串。 + + Args: + logger: worker logger。 + app: Flask 应用,读取 config。 + queue_names: 本次启动消费的队列名。 + """ + if 'contract' in queue_names: + erp_dsn = str(app.config.get('CONTRACT_PAYMENT_ERP_DSN') or '').strip() + erp_user = str(app.config.get('CONTRACT_PAYMENT_ERP_USERNAME') or '').strip() + erp_pwd = str(app.config.get('CONTRACT_PAYMENT_ERP_PASSWORD') or '') + logger.info( + '合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s', + '✓就绪' if erp_dsn else '✗缺失', + '✓就绪' if erp_user else '✗缺失', + '✓就绪' if erp_pwd else '✗缺失', + ) + if 'schedule' in queue_names: + logger.info( + 'schedule 队列身份:domain/job_type 固定为 schedule/schedule_run;' + '立账凭证检核看 business_ref 后缀 accounting-voucher-check 或 payload.platform_api_path' + ) + + def main( *, queues: list[str] | None = None, @@ -75,16 +105,7 @@ def main( app = create_app(resolved_config) queue_names = queues or ['kb'] - # 启动期诊断:确认合同付款 ERP 回查的运行时配置状态(只标记是否就绪,不输出密码)。 - _erp_dsn = str(app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip() - _erp_user = str(app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip() - _erp_pwd = str(app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "") - logger.info( - "合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s", - "✓就绪" if _erp_dsn else "✗缺失", - "✓就绪" if _erp_user else "✗缺失", - "✓就绪" if _erp_pwd else "✗缺失", - ) + _log_queue_startup_diagnostics(logger, app, queue_names) if queue_names == ['schedule'] and not bool(app.config.get('SCHEDULE_WORKER_ENABLED', True)): logger.info('Schedule worker disabled by SCHEDULE_WORKER_ENABLED=false') diff --git a/docker-compose.yml b/docker-compose.yml index 6a4a6692..d6a9b598 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -61,10 +61,7 @@ services: # 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC - FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-} - FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-} - # 立账凭证检核:容器必须读 LOCAL_ROOT,不能依赖 UNC - - VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-} - - VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-} - - VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready} + # 立账凭证检核:ERP 只读;文档库走 DMS 环境变量 - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} @@ -81,9 +78,6 @@ services: # test/prod 的 FIXED_ASSET_HISTORY_LOCAL_ROOT 分别指向对应路径;未使用的一侧为空目录无影响。 - /mnt/hxops-fixed-asset-history-test:/mnt/hxops-fixed-asset-history-test:ro - /mnt/hxops-fixed-asset-history-prod:/mnt/hxops-fixed-asset-history-prod:ro - # 立账凭证检核共享盘:宿主机 CIFS 挂载后再 bind 只读进容器 - - /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro - - /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro # 货代发货通知 RPA:分别挂载 test/prod Worker 的共享数据目录 - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data @@ -180,10 +174,7 @@ services: - SHIPPING_NOTICE_STORAGE_ROOT=${SHIPPING_NOTICE_STORAGE_ROOT:-/app/data/shipping_notice} - FREIGHT_INVENTORY_DROP_DIR=${FREIGHT_INVENTORY_DROP_DIR:-/app/data/shipping_notice/freight_rpa/inventory_drop} - FREIGHT_RPA_INVENTORY_TRIGGER_DIR=${FREIGHT_RPA_INVENTORY_TRIGGER_DIR:-/app/data/shipping_notice/freight_rpa/inventory_triggers} - # 立账凭证检核:日批在 schedule-worker 内执行,必须与 backend 同挂载 - - VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-} - - VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-} - - VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready} + # 立账凭证检核:周批在 schedule-worker 内执行 - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} @@ -192,8 +183,6 @@ services: volumes: - ./oracle_client:/app/oracle_client:ro - hxops_runtime_data:/app/data - - /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro - - /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro # 库存 RPA trigger 由 schedule-worker 写入,必须与 backend 同挂 CIFS,否则 Windows Worker 看不到 - /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data - /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data 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 4059e32f..4273b57f 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -210,14 +210,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 打印仍待接线。不做 Chatflow;查询走工作台 API。 +- 权威需求见 [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..d0997668 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -1,18 +1,16 @@ # 立账凭证检核(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) | - -| **销售一期需求说明** | 产品、业务、测试 | [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 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。ERP PO / OA 销货放行打印仍待接线。 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..f8e92b11 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.9 +> 更新时间:2026-09-08 > 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置 +> +> 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。 ## 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,69 @@ | 任务列表字段 | 批次号、业务方、资料所属期间、执行时间、主体总数、已归档数、缺件文件数、缺件 `invoice` 数、状态 | | 状态 | 缺件、已完成、技术失败、待配置 | | 操作 | 查看详情;进入该批次的执行记录,并可查看企业微信通知附件 Excel | -| 任务入口 | 支持新建任务、强制重检;强制重检仍只针对上一个自然月 | +| 任务入口 | 支持新建任务、强制重检(仅上一个月);企微接收人从系统用户多选,可复用排程通知人选择器 | + +### 3.5 企业微信发送记录 + +工作台同一入口用 Tab 切换「检核任务」与「企微发送记录」。发送记录以 `voucher_check_notifications` 为真相源,每批一条缺件汇总(已发送 / 失败 / 无缺件未发送 / 未配置接收人 / 通知关闭)。 + +| 区域 | 内容 | +| -------- | --------------------------------------------------------------------------------------------- | +| 筛选条件 | 资料所属期间、发送状态 | +| 列表字段 | 批次号、资料所属期间、invoice 总数、invoice 缺件数、缺件文件数、发送状态、未发送原因、接收人、发送时间、Excel | +| 操作 | 有附件时可下载该批 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 +136,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 +213,7 @@ flowchart TD | 聚合 | 一个检核批次发送一条汇总通知;不在企业微信中逐票展开缺失明细 | | 内容 | 业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型、Excel 下载入口 | | 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 | -| 接收人 | 待业务确认;未配置接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | +| 接收人 | 业务可暂不指定具体人;**必须提供配置界面**,从 HXOPS 系统用户中多选(须已绑定企微 userid)。可复用管理后台排程任务的通知人选择器。未配置任何接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | | 技术失败 | 不作为缺件通知;按技术告警规则单独处理 | ## 7. 企业微信通知附件 Excel @@ -168,285 +232,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 deleted file mode 100644 index d9015899..00000000 --- a/docs/features/accounting-voucher-check/dify-chatflow-draft.md +++ /dev/null @@ -1,196 +0,0 @@ -# 立账凭证检核 — Dify Chatflow 编排草稿 - -> **状态**:草稿(待 Dify 画布落地) -> **前提**:HXOPS Tool / 工作台 API 已就绪;本文件只约定意图 → Tool 映射与节点配置,不参与文件是否齐全的判定。 -> **参考**:文件检核 Chatflow 手册 [../file-check/technical.md](../file-check/technical.md) 第二部分;技术设计 [technical-design.md](technical-design.md) §12。 - ---- - -## 1. 设计原则 - -1. Dify **只做**意图识别、调 Tool、组织自然语言回复。 -2. **禁止**让 LLM 判断「文件在不在」或读取共享盘/附件内容。 -3. 启动检核复用现有 `POST /api/file-check/tools/tasks/run`,通过顶层 `mode` / `invoice_no` 区分模式(Dify 友好;亦兼容嵌套 `run_options`)。 -4. 缺资料/单票查询走 `/api/accounting-voucher-check/tools/*`。 -5. 进度卡仍走工作台 file-check 轮询链路(`ChatToolRun` 绑定 + `progress_metrics`)。 - ---- - -## 2. 意图清单 - -| 意图 code | 示例话术 | Tool | 关键参数 | -| --- | --- | --- | --- | -| `run_incremental` | 执行今日立账凭证检核 | `run_file_check` | 顶层 `mode=incremental` | -| `run_force_all` | 重新检核当月全部 | `run_file_check` | 顶层 `mode=force_all` | -| `run_single` | 检核发票 INV-xxx | `run_file_check` | 顶层 `mode=single` + `invoice_no` | -| `query_latest` | 查询最新检核结果 | `get_latest_file_check_run` | `task_id` | -| `query_run` | 查询批次 xxx | `get_file_check_run` | `run_id` | -| `query_missing` | 查询缺资料发票 | `list_voucher_missing` | `task_id`,可选 `period` | -| `query_invoice` | 发票 INV-xxx 检核结果 | `get_voucher_invoice_latest` | `invoice_no` | -| `capability` | 你能做什么 | (无 Tool) | 固定能力说明文案 | -| `fallback` | 无法识别 | (无 Tool) | 引导上述话术 | - ---- - -## 3. Tool 注册(建议 OpenAPI 操作) - -### 3.1 复用 file-check(已有) - -| operationId(建议) | Method / Path | 说明 | -| --- | --- | --- | -| `run_file_check` | `POST /api/file-check/tools/tasks/run` | Body 增加顶层 `mode` / `invoice_no`(兼容 `run_options`) | -| `get_file_check_run` | `GET /api/file-check/tools/runs/{run_id}` | 查批次 | -| `get_latest_file_check_run` | `GET /api/file-check/tools/tasks/{task_id}/latest-run` | 最新批次 | -| `download_file_check_excel` | `GET /api/file-check/tools/runs/{run_id}/excel` | Excel(可选,前端也可下) | - -> **Dify 注意**:部分版本对 OpenAPI **嵌套 object**(`run_options`)不展示输入框。请绑定顶层 `mode`、`invoice_no`。改完 OpenAPI 后须在 Dify **重新导入/更新** file-check 工具包。 - -`RunCheckRequest`(Dify 推荐写法): - -```json -{ - "task_id": 12, - "hxops_turn_id": "{{#ctx.hxops_turn_id#}}", - "conversation_id": "{{#sys.conversation_id#}}", - "user_message": "{{#sys.query#}}", - "mode": "incremental", - "invoice_no": null -} -``` - -### 3.2 本域新增(HXOPS 已实现,可 URL 导入) - -| operationId | Method / Path | 说明 | -| --- | --- | --- | -| `list_voucher_missing` | `GET /api/accounting-voucher-check/tools/tasks/{task_id}/missing` | Query: `period`, `limit` | -| `list_voucher_run_items` | `GET /api/accounting-voucher-check/tools/runs/{run_id}/items` | Query: `result`, `page` | -| `get_voucher_invoice_latest` | `GET /api/accounting-voucher-check/tools/invoices/{invoice_no}/latest` | Query: `period` | - -**Dify 导入**: - -```text -GET {HXOPS_TOOLS_API_BASE}/api/accounting-voucher-check/tools/openapi.json -``` - -鉴权与 file-check **同一密钥**:`FILE_CHECK_TOOL_API_KEY` 或 `INTEGRATION_API_KEY`(Bearer / `X-Integration-Key`)。`openapi.json` 本身无需鉴权。 - ---- - -## 4. 画布节点建议顺序 - -```text -开始 - → 解析运行态上下文(agent_runtime_context:task_id / hxops_turn_id) - → 意图识别 LLM(输出 intent + invoice_no?) - → 意图分支 - ├─ run_* → HTTP Tool 启动检核 → 回复「已启动,请看进度卡」 - ├─ query_latest → latest-run Tool → 摘要回复(齐全/缺资料/跳过) - ├─ query_missing→ missing Tool → 列表摘要 + 引导打开工作台记录 - ├─ query_invoice→ invoice latest Tool → 单票结论卡文案 - ├─ capability → 固定能力说明 - └─ fallback → 引导话术 - → 结束 -``` - -要点: - -- `task_id` 必须来自 **Agent 绑定的 `bound_schedule_task_id` / runtime refs**,禁止让用户随口编造或 LLM 瞎填。 -- `hxops_turn_id` 必传,保证进度卡能绑到本轮助手消息。 -- 启动成功后**不要**在 Chatflow 里同步轮询到结束;进度由前端 `ToolRunProgressCard` 负责。 - ---- - -## 5. 意图识别 Prompt 草稿 - -```text -你是「立账凭证检核」助手的意图分类器。只输出 JSON,不要解释。 - -可选 intent: -- run_incremental:执行今日/当月增量检核 -- run_force_all:重新检核当月全部(不跳过) -- run_single:检核指定发票(需抽取 invoice_no) -- query_latest:查最新检核结果 -- query_run:查指定批次(若用户给出 run_no/run_id,放入 run_ref) -- query_missing:查缺资料发票 -- query_invoice:查某发票最近结论(需 invoice_no) -- capability:询问能力 -- fallback:其它 - -规则: -1. 本助手只做「共享盘必检材料是否存在」,不核对金额/供应商,不回写 ERP。 -2. 无法确定发票号时,run_single / query_invoice 不要猜,改用 fallback 并追问。 -3. invoice_no 保持用户原文(仅去首尾空白),不要改写。 - -输出 schema: -{ - "intent": "...", - "invoice_no": null, - "run_ref": null, - "period": null -} -``` - -`[PARAM_TUNING]` 建议 Temperature ≤ 0.2,避免发散意图。 - ---- - -## 6. 回复文案要点(Answer 节点) - -| 场景 | 回复应包含 | -| --- | --- | -| 启动成功 | 已启动、批次号、提示查看进度卡(当月总数/待检/跳过/齐全/缺资料) | -| `check_running` | 已有任务执行中,请稍候或查最新结果 | -| 最新结果 | 月份、齐全/缺资料/跳过计数;有 Excel 则提示下载 | -| 缺资料列表 | 票数 + 前几张发票号 + 缺项;引导 `/workspace/accounting-voucher-check` | -| 单票 | 齐全或缺资料 + 缺项名;目录相对路径(勿暴露宿主机绝对路径) | -| 能力说明 | 明确「只查文件在不在」「不读内容」「不回写 ERP」 | -| 共享盘/ERP 失败 | 转述错误码友好文案,提示联系运维检查挂载/Oracle | - ---- - -## 7. Agent Registry 配置(HXOPS 侧) - -落地 Chatflow 时同步: - -| 项 | 建议值 | -| --- | --- | -| Agent 名称 | 立账凭证检核 | -| `bound_schedule_task_id` | `SCH-ACCOUNTING-VOUCHER-CHECK` 对应 id | -| `capabilities.task_progress` | `true` | -| Dify app | 本 Chatflow 应用 | -| 知识库同步 | 关闭(任务级 `kb_sync_enabled=false`) | - -进度展示:服务端已写 `progress_metrics`(齐全/缺资料等),前端进度卡自动切换,无需 RoHS 八格文案。 - ---- - -## 8. 联调检查单(Chatflow) - -- [ ] 话术「执行今日立账凭证检核」→ `mode=incremental`,进度卡出现 -- [ ] 「重新检核当月全部」→ `force_all`,完成后 `skipped_count=0` -- [ ] 「检核发票 {真实 apa08}」→ `single`,可跳过历史不影响 -- [ ] 「查询缺资料发票」→ missing Tool,列表与工作台一致 -- [ ] 运行中重复启动 → `check_running`,不双开批次 -- [ ] LLM 未被要求/未尝试判断文件内容 - ---- - -## 9. 与文件检核 Chatflow 的差异(编排时勿混) - -| 点 | 文件检核 | 立账凭证检核 | -| --- | --- | --- | -| 队列 | SRM 未检核 | ERP 当月发票清单 | -| 判定 | Dify Workflow/字段规则 | **仅 HXOPS 文件名存在性** | -| 启动 Body | 通常无 mode | **须传顶层 `mode`(单票再加 `invoice_no`)** | -| 历史知识库检索 | 有 | **无**(默认不入 KB) | -| 进度格 | 合格/不合格/人工 | 齐全/缺资料/跳过 | - ---- - -## 10. 落地待办(给编排同学) - -1. 在 Dify 新建独立 Chatflow(勿直接改 RoHS 画布)。 -2. 导入/配置上述 HTTP Tools(file-check + accounting-voucher-check)。 -3. 按 §4 搭意图分支与 Prompt。 -4. HXOPS 注册 Agent 并绑定排程任务。 -5. 用 §8 联调;通过后把本文状态改为「已落地」,并链到正式导出 OpenAPI(若另出 voucher OpenAPI 文件)。 diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index 9141466a..0b7fd610 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -1,8 +1,10 @@ -# 立账凭证检核 — 迁移与部署验收清单 +# 立账凭证检核 — 部署验收清单 -> 适用环境:dev / test / prod -> 前置文档:[technical.md](technical.md) · [technical-design.md](technical-design.md) -> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通日批/手动触发并看到进度与记录。 +> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `apa_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。 +> +> 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。 +> +> 适用环境:dev / test / prod ## 0. 变更摘要(上线前确认) @@ -10,27 +12,29 @@ | --- | --- | | Job key | `accounting-voucher-check` | | 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` | -| Cron | `0 6 * * *`(Asia/Shanghai) | -| 必检材料(暂定) | `核价单.pdf`、`采购单.pdf` | -| 迁移 revision | `a0b1c2d3e4f5` | +| Cron | `0 6 * * 2`(Asia/Shanghai,每周二 06:00) | +| 检核期间 | 上一个自然月 | +| 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 | +| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` | +| 已删除旧表 | `voucher_check_invoice_states`、`voucher_check_run_items`(revision `vc2b3c4d5e6f`) | +| 旧 job_params 清洗 | revision `vc3d4e5f6a7b`:去掉共享盘字段;启动种子同样幂等剥离 | | 工作台入口 | `/workspace/accounting-voucher-check` | --- ## 1. 数据库迁移 -- [ ] 备份目标库(至少 `schedule_tasks` / 相关 schema) +- [ ] 备份目标库 - [ ] 后端目录执行: ```bash cd backend -# 激活对应环境 venv flask db upgrade ``` -- [ ] 确认表存在: - - `voucher_check_invoice_states` - - `voucher_check_run_items` +- [ ] 确认引擎表存在:`voucher_check_profiles`、`voucher_check_runs`、`voucher_check_subjects`、`voucher_check_file_results`、`voucher_check_notifications` +- [ ] 确认旧表已删除:`voucher_check_invoice_states`、`voucher_check_run_items` +- [ ] 确认排程 `job_params` 仅含 `profile_code` / `scope_code` / 两个通知开关(无 `directory_template` / `required_files`) - [ ] 确认种子排程存在(有用户时): ```sql @@ -41,124 +45,112 @@ SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at ``` - [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建) -- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含必检材料 JSON +- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含 `profile_code=sales`、`scope_code=HXJM` --- ## 2. 环境变量 -写入 `.env.`(密码勿提交仓库): +写入 `.env.`(密码勿提交仓库)。文档库登录可复用 `CONTRACT_DMS_*`;销售开票附件根目录必须单独配置: ```bash -# 共享盘(Linux/容器必须 LOCAL_ROOT) -VOUCHER_CHECK_SHARE_UNC=\\192.168.100.230\ai_file\vouche -VOUCHER_CHECK_LOCAL_ROOT=/mnt/hxops-voucher-check-test # prod 换 prod 路径 -VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=.hxops-share-ready - -# Oracle(只读;DSN 可复用 ERP_DB_DSN) +# Oracle(只读;未单独配置 VOUCHER_CHECK_ERP_* 时复用 ERP_DB_DSN / ERP_USERNAME,再回退 CONTRACT_PAYMENT_ERP_*) VOUCHER_CHECK_ERP_DSN=${ERP_DB_DSN} VOUCHER_CHECK_ERP_USERNAME= VOUCHER_CHECK_ERP_PASSWORD= VOUCHER_CHECK_ERP_TIMEOUT_SECONDS=30 + +# 文档库(LibraryID 与合同相同;只单独配销售根 FolderID) +VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= +# 如需覆盖合同 DMS 登录: +# VOUCHER_CHECK_DMS_BASE_URL= +# VOUCHER_CHECK_DMS_LIBRARY_ID= +# VOUCHER_CHECK_DMS_USERNAME= +# VOUCHER_CHECK_DMS_PASSWORD= ``` 检查: -- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_*` +- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*` - [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中 +- [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除) --- -## 3. 共享盘挂载(当前阻塞项) +## 3. 排程与通知配置 -对齐固资履历思路:宿主机 CIFS → bind 进容器只读。 - -示意(路径按环境替换): - -```bash -# 宿主机 -sudo mkdir -p /mnt/hxops-voucher-check-test -# 使用只读 SMB 账号挂载 ai_file 或 vouche 子路径到 LOCAL_ROOT - -# 健康标记(根目录下) -sudo touch /mnt/hxops-voucher-check-test/.hxops-share-ready - -# 容器内验收 -docker exec hxops-backend test -f /mnt/hxops-voucher-check-test/.hxops-share-ready -docker exec hxops-schedule-worker test -f /mnt/hxops-voucher-check-test/.hxops-share-ready - -# 抽查当月目录(示例) -docker exec hxops-backend ls "/mnt/hxops-voucher-check-test/$(date +%Y)/$(date +%m)" | head -``` - -- [ ] backend 与 schedule-worker 均可读健康标记 -- [ ] 用真实 `apa08`(含 `+` 等特殊字符)抽查子目录名一致 -- [ ] Compose 已挂载 `/mnt/hxops-voucher-check-test|prod`(见根目录 `docker-compose.yml`) -- [ ] recreate backend + schedule-worker 使 env/volume 生效 - -> 未挂载或缺少健康标记时:批次应 **整批 failed**,且不写入业务「缺资料」单票状态。 - ---- - -## 4. 排程与通知配置 - -- [ ] 管理后台打开任务「立账凭证检核(日批)」 -- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * *` +- [ ] 管理后台打开任务「立账凭证检核(周批)」 +- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * 2` - [ ] `kb_sync_enabled=false`(本域不需要进知识库) -- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户 -- [ ] `job_params.required_files` 确认为核价单/采购单(或业务最终定稿) +- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户;未配置则不发 +- [ ] `job_params.profile_code=sales`,`scope_code=HXJM` --- -## 5. 功能冒烟 +## 4. 功能冒烟 -### 5.1 管理台手动跑一批(共享盘可用后) +### 4.1 管理台手动跑一批 - [ ] 「立即执行」创建 `ScheduleRun` -- [ ] `response_summary_json.voucher_check` 含 `complete_count` / `missing_count` / `skipped_count` -- [ ] Excel 可下载,表头含发票号/结论/缺失材料 -- [ ] `failed_count` **不含**缺资料票(仅技术异常) +- [ ] `response_summary_json.voucher_check` 含缺件文件数 / 缺件 invoice 数 +- [ ] Excel 可下载,以 invoice 为行、文件类型为列 +- [ ] 技术失败不计入缺件 -### 5.2 增量跳过 +### 4.2 增量与强制重检 -- [ ] 第一次跑后,第二次对未变更齐全票:`skipped_count > 0` -- [ ] 强制语义(会话/Tool `mode=force_all`):跳过为 0 +- [ ] 第一次跑后,第二次对未变更齐全票:跳过数 > 0 +- [ ] 工作台「强制重检上月」:`mode=force_all`,跳过为 0 +- [ ] 仅管理员可触发强制重检 -### 5.3 共享盘故障 - -- [ ] 临时移除健康标记或卸载挂载 -- [ ] 再跑:批次 `failed`,不产生批量 missing 状态覆盖 -- [ ] 企微失败告警到达(若开启) - -### 5.4 工作台记录页 +### 4.3 工作台记录页 - [ ] 打开 `/workspace/accounting-voucher-check` -- [ ] 可按月/状态/发票号筛选 -- [ ] 缺资料票的缺失材料列非空 +- [ ] 「检核任务」可按月/状态筛选,分页可用 +- [ ] 「企微发送记录」可按月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口 +- [ ] 「查看详情」进入 `/workspace/accounting-voucher-check/runs/:runId`(`runId` 为 ScheduleRun.id) -### 5.5 Tool API(可用 curl / Postman) +### 4.4 文档库 / ERP 故障 -```bash -# 启动(增量)— 复用 file-check -POST /api/file-check/tools/tasks/run -{ "task_id": , "run_options": { "mode": "incremental" }, "hxops_turn_id": "..." } +- [ ] DMS 或 ERP 不可用时批次 `failed`,不得把空结果批量判为缺件 +- [ ] 企微失败告警到达(若开启) -# 缺资料查询 -GET /api/accounting-voucher-check/tools/tasks//missing +--- -# 批次明细 -GET /api/accounting-voucher-check/tools/runs//items?result=missing +## 5. 在 jobs 表识别立账凭证检核 + +平台排程(含立账凭证)仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**,这是 worker 认领约定,不要按这两列区分业务。 + +升级后新入队的 Job: + +| 列 | 立账凭证检核示例 | +| --- | --- | +| `business_ref` | `schedule_run:{id}:accounting-voucher-check` | +| `payload_json.platform_api_path` | `accounting-voucher-check` | +| `payload_json.task_name` | `立账凭证检核` | +| `message` | `立账凭证检核等待后台执行` | + +```sql +SELECT id, status, business_ref, message, payload_json + FROM jobs + WHERE domain = 'schedule' + AND job_type = 'schedule_run' + AND ( + business_ref LIKE '%:accounting-voucher-check' + OR payload_json->>'platform_api_path' = 'accounting-voucher-check' + ) + ORDER BY id DESC + LIMIT 20; ``` -- [ ] 上述接口返回符合约定(Tool 非 envelope / 工作台 envelope) +Worker 日志关键字:`[voucher-check]` 或 `[schedule-run] name=立账凭证检核 path=accounting-voucher-check`。 --- ## 6. 回滚要点 -- [ ] 代码回滚后:可 `flask db downgrade` 到上一 revision(会删本域两表 + 种子 `schedule_no`) -- [ ] **勿**在有生产检核数据时贸然 downgrade;优先停用任务 `enabled=false` -- [ ] 共享盘挂载可保留,不影响其它服务 +- [ ] **勿**在有生产检核数据时贸然 `flask db downgrade`(会回建空的旧表,不恢复历史数据) +- [ ] 优先停用任务 `enabled=false` +- [ ] 旧共享盘挂载与 `VOUCHER_CHECK_SHARE_*` 已不再使用,可从宿主机/Compose 移除 --- @@ -167,6 +159,6 @@ GET /api/accounting-voucher-check/tools/runs//items?result=missing | 角色 | 确认项 | 签名/日期 | | --- | --- | --- | | 研发 | 迁移 + Job 注册 + 冒烟 | | -| 运维 | env + 挂载 + 双容器可读 | | -| 业务 | 必检文件名 + 通知接收人 | | -| 测试 | T1–T12 关键场景抽样 | | +| 运维 | env + DMS/ERP 连通 | | +| 业务 | 类型目录 + 通知接收人 | | +| 测试 | 周批 / 强制重检 / 企微记录抽样 | | diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index a2c789f9..28b841c7 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.3 +> 更新时间:2026-09-08 +> 状态:销售一期引擎已落地;ERP PO / OA 打印仍待接线 > 需求基线:[demand.md](demand.md) +> +> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。 ## 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[文件规则] @@ -53,23 +55,23 @@ business_profiles/ 生产配置应存放于数据库或受控配置中心,以上目录仅表示逻辑结构;发布后的 Profile 必须生成不可变快照并绑定批次。 -| 配置项 | 说明 | -| -------------------------------------- | ------------------------------------------------------------------------ | -| `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | -| `subject_adapter` | 获取本期 `invoice` 主体清单的 Adapter 和参数 | -| `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | -| `notification` | 企业微信接收人、启用开关、模板、去重策略 | -| `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | +| 配置项 | 说明 | +| -------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | +| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `apa_file`(`apa08`/`apa09`),期间为上一个月 | +| `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | +| `notification` | 企业微信接收人、启用开关、模板、去重策略 | +| `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | ### 3.2 Adapter 契约 -| Adapter | 责任 | 统一输出 | -| -------------------------- | -------------------------------- | -------------------------------- | -| `subject_adapter` | 获取期间内应检主体及关联信息 | `invoice`、主体属性、来源指纹 | -| `erp_print_adapter` | 查询业务单据并打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `oa_report_adapter` | 按 OA 报表条件查询、逐条打印 PDF | 文件临时路径、关联字段、来源指纹 | -| `directory_scan_adapter` | 扫描目录并匹配命名模板 | 匹配文件、扫描路径、来源指纹 | -| `cloud_drive_adapter` | 按接口检索和下载文件 | 文件临时路径、关联字段、来源指纹 | +| Adapter | 责任 | 统一输出 | +| -------------------------- | ----------------------------------------------------------------- | -------------------------------- | +| `subject_adapter` | 获取期间内应检主体及关联信息 | `invoice`、主体属性、来源指纹 | +| `erp_print_adapter` | 查询业务单据并打印 PDF | 文件临时路径、关联字段、来源指纹 | +| `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` 已由迁移 `vc2b3c4d5e6f` 删除,不得再恢复为写入目标。 + ## 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 | +| Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` | -### 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 脱敏 | +- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。 +- 不得再写入 `voucher_check_invoice_states` / `voucher_check_run_items`。 +- 部署与冒烟见 [ops-checklist.md](ops-checklist.md)。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index 502e839b..9fdaefa2 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、任务和前端影响 @@ -498,11 +488,11 @@ backend/app/domains/document_check/ 迁移顺序: 1. 先建立 Profile Schema、Adapter 契约和单文件数据模型。 -2. 将现有销售共享盘扫描逻辑封装为 `directory_scan` Adapter。 +2. 销售文档扫描走 `dms_directory_scan` Adapter(文档库类型目录),不再封装旧共享盘扫描。 3. 将销售 invoice 主体加载和 OA/ERP 获取逻辑分别封装为 Loader/Adapter。 -4. 保留旧 `voucher_check` API 兼容层,内部调用通用引擎。 +4. 工作台 API 只读引擎表;已删除 Chatflow Tool 与旧 states 接口。 5. 完成销售回归后增加采购 Profile 和采购专用 Adapter。 -6. 最后清理只服务旧模型的单票状态、单一共享根配置和重复接口。 +6. 已清理只服务旧模型的单票状态、单一共享根配置和重复接口。 ## 12. 测试与验收 @@ -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/features/hr/AI知识库对接HR系统.md b/docs/features/hr-system/AI知识库对接HR系统.md similarity index 100% rename from docs/features/hr/AI知识库对接HR系统.md rename to docs/features/hr-system/AI知识库对接HR系统.md diff --git a/docs/funclist.md b/docs/funclist.md index abe5bc72..f5c716d3 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -212,22 +212,13 @@ ### 立账凭证检核(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 销货放行单打印仅占位 | +| 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` | +| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 | +| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;「强制重检上月」;`/runs`、`/notifications` 只读引擎表 | ### 采购合同审查 diff --git a/docs/openapi/accounting_voucher_check_tools_openapi.json b/docs/openapi/accounting_voucher_check_tools_openapi.json deleted file mode 100644 index 67a7eea2..00000000 --- a/docs/openapi/accounting_voucher_check_tools_openapi.json +++ /dev/null @@ -1,518 +0,0 @@ -{ - "openapi": "3.0.3", - "info": { - "title": "HXOPS Accounting Voucher Check Tool API", - "description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。", - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://127.0.0.1:5052", - "description": "HXOPS_TOOLS_API_BASE" - } - ], - "security": [ - { - "BearerAuth": [] - }, - { - "IntegrationKey": [] - } - ], - "paths": { - "/api/accounting-voucher-check/tools/tasks/{task_id}/missing": { - "get": { - "operationId": "list_voucher_missing", - "summary": "查询缺资料发票(最新状态)", - "description": "按账套与月份查询 status=missing 的发票;默认当前自然月。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "task_id", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "example": 12 - }, - "description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { - "type": "string", - "example": "2026-08" - }, - "description": "检核月份 YYYY-MM;缺省为当前自然月" - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { - "type": "string", - "default": "HXJM", - "example": "HXJM" - } - }, - { - "name": "limit", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 200, - "minimum": 1, - "maximum": 1000 - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MissingListResponse" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - }, - "/api/accounting-voucher-check/tools/runs/{run_id}/items": { - "get": { - "operationId": "list_voucher_run_items", - "summary": "查询批次发票明细", - "description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "run_id", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "example": 1001 - } - }, - { - "name": "result", - "in": "query", - "required": false, - "schema": { - "type": "string", - "enum": [ - "complete", - "missing", - "skipped", - "technical_error" - ], - "example": "missing" - } - }, - { - "name": "page", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 1, - "minimum": 1 - } - }, - { - "name": "page_size", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "default": 50, - "minimum": 1, - "maximum": 200 - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RunItemsResponse" - } - } - } - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - }, - "/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": { - "get": { - "operationId": "get_voucher_invoice_latest", - "summary": "查询指定发票最新检核状态", - "description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。", - "tags": [ - "Accounting Voucher Check" - ], - "parameters": [ - { - "name": "invoice_no", - "in": "path", - "required": true, - "schema": { - "type": "string", - "example": "INV-20260803001" - }, - "description": "发票号(apa08 原值)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { - "type": "string", - "example": "2026-08" - } - }, - { - "name": "scope_code", - "in": "query", - "required": false, - "schema": { - "type": "string", - "default": "HXJM" - } - } - ], - "responses": { - "200": { - "description": "成功", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InvoiceLatestResponse" - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "503": { - "$ref": "#/components/responses/MissingAuth" - } - } - } - } - }, - "components": { - "securitySchemes": { - "BearerAuth": { - "type": "http", - "scheme": "bearer", - "description": "Authorization: Bearer " - }, - "IntegrationKey": { - "type": "apiKey", - "in": "header", - "name": "X-Integration-Key", - "description": "与 Bearer 二选一" - } - }, - "schemas": { - "MissingMaterial": { - "type": "object", - "properties": { - "code": { - "type": "string", - "example": "price_check_sheet" - }, - "name": { - "type": "string", - "example": "核价单" - } - } - }, - "InvoiceState": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "scope_code": { - "type": "string" - }, - "period_month": { - "type": "string", - "nullable": true - }, - "invoice_no": { - "type": "string" - }, - "invoice_date": { - "type": "string", - "nullable": true - }, - "status": { - "type": "string", - "enum": [ - "complete", - "missing" - ] - }, - "folder_path": { - "type": "string", - "nullable": true - }, - "folder_exists": { - "type": "boolean" - }, - "matched_files": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "missing_materials": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MissingMaterial" - } - }, - "last_checked_at": { - "type": "string", - "nullable": true - } - } - }, - "MissingListResponse": { - "type": "object", - "required": [ - "ok", - "items", - "count" - ], - "properties": { - "ok": { - "type": "boolean", - "example": true - }, - "task_id": { - "type": "integer", - "nullable": true - }, - "scope_code": { - "type": "string" - }, - "period": { - "type": "string", - "example": "2026-08" - }, - "count": { - "type": "integer" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/InvoiceState" - } - } - } - }, - "RunItem": { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "schedule_run_id": { - "type": "integer" - }, - "invoice_no": { - "type": "string" - }, - "result": { - "type": "string", - "enum": [ - "complete", - "missing", - "skipped", - "technical_error" - ] - }, - "folder_path": { - "type": "string", - "nullable": true - }, - "matched_files": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "missing_materials": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MissingMaterial" - } - }, - "error_code": { - "type": "string", - "nullable": true - }, - "error_message": { - "type": "string", - "nullable": true - } - } - }, - "RunItemsResponse": { - "type": "object", - "required": [ - "ok", - "items", - "total" - ], - "properties": { - "ok": { - "type": "boolean" - }, - "run_id": { - "type": "integer" - }, - "run_no": { - "type": "string" - }, - "page": { - "type": "integer" - }, - "page_size": { - "type": "integer" - }, - "total": { - "type": "integer" - }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RunItem" - } - } - } - }, - "InvoiceLatestResponse": { - "type": "object", - "required": [ - "ok", - "state" - ], - "properties": { - "ok": { - "type": "boolean" - }, - "state": { - "$ref": "#/components/schemas/InvoiceState" - }, - "recent_run_items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RunItem" - } - } - } - }, - "ToolError": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "example": false - }, - "error_code": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": { - "type": "object" - } - } - } - }, - "responses": { - "BadRequest": { - "description": "参数错误", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "Unauthorized": { - "description": "鉴权失败", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "NotFound": { - "description": "资源不存在", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - }, - "MissingAuth": { - "description": "服务端未配置 Tool API Key", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ToolError" - } - } - } - } - } - } -} diff --git a/docs/tec.md b/docs/tec.md index 4055c0a1..31e3a82e 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。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 - 详细业务需求见 [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/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index c16134d0..153bc89b 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -2,7 +2,7 @@ * app/router/routes/workspace.routes.ts * 工作台路由表:/workspace 布局壳 + 各业务子页面懒加载。 * 依赖:vue-router、contract-payment 权限常量;meta.title 存 i18n key(workspace.*),由 guards 解析为 document.title。 - * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款子路由用 requiresFeaturePermission 而非 requiresAdmin。 + * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款子路由用 requiresFeaturePermission 而非 requiresAdmin;立账凭证明细为 accounting-voucher-check/runs/:runId。 */ import type { RouteRecordRaw } from 'vue-router'; import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants'; @@ -84,6 +84,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: () => import('@/features/workspace/pages/AccountingVoucherCheckPage.vue'), meta: { title: 'workspace.nav.accountingVoucherCheck', requiresAdmin: true }, }, + { + path: 'accounting-voucher-check/runs/:runId', + name: 'workspace-accounting-voucher-check-detail', + component: () => import('@/features/workspace/pages/AccountingVoucherCheckDetailPage.vue'), + meta: { title: 'workspace.voucherCheck.detailTitle', requiresAdmin: true }, + }, { path: 'contract-payment', name: 'workspace-contract-payment', 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。 */