From f615e56bb940b273e5e1b0655472ae50f4dfd0b8 Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 5 Aug 2026 14:49:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(agent):=20=E7=AB=8B=E8=B4=A6=E5=87=AD?= =?UTF-8?q?=E8=AF=81=E6=A3=80=E6=A0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit f9e2fb5efc1ec7bf4f6e52e08dd3591b4e77edd9) --- backend/app/__init__.py | 9 + backend/app/api/__init__.py | 5 +- backend/app/api/file_check_tools.py | 65 ++- backend/app/api/tools/__init__.py | 5 +- backend/app/api/tools/voucher_check.py | 105 ++++ backend/app/api/workspace/__init__.py | 4 +- backend/app/api/workspace/file_check.py | 59 +- backend/app/api/workspace/voucher_check.py | 70 +++ backend/app/core/config/settings.py | 12 + backend/app/models/__init__.py | 5 +- backend/app/models/voucher_check.py | 114 ++++ .../file_check_tools/openapi_base.json | 30 +- backend/app/services/integration_tool_auth.py | 44 ++ backend/app/services/schedule/__init__.py | 3 + backend/app/services/schedule/job_registry.py | 75 ++- .../services/schedule/scheduler_service.py | 11 + .../services/schedule/voucher_check_job.py | 44 ++ .../app/services/voucher_check/__init__.py | 11 + backend/app/services/voucher_check/config.py | 262 +++++++++ .../services/voucher_check/erp_repository.py | 146 +++++ .../app/services/voucher_check/excel_rows.py | 93 ++++ .../app/services/voucher_check/fingerprint.py | 34 ++ .../services/voucher_check/notification.py | 205 +++++++ .../services/voucher_check/openapi_base.json | 316 +++++++++++ .../services/voucher_check/openapi_spec.py | 35 ++ .../app/services/voucher_check/persistence.py | 126 +++++ .../services/voucher_check/query_service.py | 220 ++++++++ backend/app/services/voucher_check/runner.py | 366 +++++++++++++ .../services/voucher_check/schedule_seed.py | 149 +++++ .../services/voucher_check/share_scanner.py | 273 +++++++++ .../a0b1c2d3e4f5_add_voucher_check_tables.py | 235 ++++++++ .../scripts/export_voucher_check_openapi.py | 39 ++ backend/tests/voucher_check/__init__.py | 1 + .../test_period_and_incremental.py | 30 + .../test_share_and_fingerprint.py | 106 ++++ .../test_tool_auth_and_openapi.py | 52 ++ docker-compose.yml | 19 + docs/demand.md | 3 +- .../accounting-voucher-check/README.md | 11 +- .../dify-chatflow-draft.md | 196 +++++++ .../accounting-voucher-check/ops-checklist.md | 172 ++++++ .../technical-design.md | 62 +-- .../accounting-voucher-check/technical.md | 22 +- docs/funclist.md | 7 +- ...ccounting_voucher_check_tools_openapi.json | 518 ++++++++++++++++++ docs/openapi/file_check_tools_openapi.json | 55 +- .../src/app/router/routes/workspace.routes.ts | 6 + .../chat/components/ToolRunProgressCard.vue | 39 +- .../chat/types/tool-run-progress.types.ts | 7 + .../workspace/api/voucherCheck.api.ts | 91 +++ .../workspace/components/WorkspaceSidebar.vue | 3 +- .../features/workspace/constants/routes.ts | 2 + .../pages/AccountingVoucherCheckPage.vue | 13 + .../views/AccountingVoucherCheckView.vue | 255 +++++++++ frontend/src/locales/en/admin.json | 12 +- frontend/src/locales/en/chat.json | 7 + frontend/src/locales/en/errors.json | 10 +- frontend/src/locales/en/workspace.json | 30 +- frontend/src/locales/th/admin.json | 12 +- frontend/src/locales/th/chat.json | 7 + frontend/src/locales/th/errors.json | 10 +- frontend/src/locales/th/workspace.json | 30 +- frontend/src/locales/zh-CN/admin.json | 12 +- frontend/src/locales/zh-CN/chat.json | 7 + frontend/src/locales/zh-CN/errors.json | 10 +- frontend/src/locales/zh-CN/workspace.json | 30 +- frontend/src/locales/zh-TW/admin.json | 12 +- frontend/src/locales/zh-TW/chat.json | 7 + frontend/src/locales/zh-TW/errors.json | 10 +- frontend/src/locales/zh-TW/workspace.json | 30 +- 70 files changed, 4968 insertions(+), 108 deletions(-) create mode 100644 backend/app/api/tools/voucher_check.py create mode 100644 backend/app/api/workspace/voucher_check.py create mode 100644 backend/app/models/voucher_check.py create mode 100644 backend/app/services/integration_tool_auth.py create mode 100644 backend/app/services/schedule/voucher_check_job.py create mode 100644 backend/app/services/voucher_check/__init__.py create mode 100644 backend/app/services/voucher_check/config.py create mode 100644 backend/app/services/voucher_check/erp_repository.py create mode 100644 backend/app/services/voucher_check/excel_rows.py create mode 100644 backend/app/services/voucher_check/fingerprint.py create mode 100644 backend/app/services/voucher_check/notification.py create mode 100644 backend/app/services/voucher_check/openapi_base.json create mode 100644 backend/app/services/voucher_check/openapi_spec.py create mode 100644 backend/app/services/voucher_check/persistence.py create mode 100644 backend/app/services/voucher_check/query_service.py create mode 100644 backend/app/services/voucher_check/runner.py create mode 100644 backend/app/services/voucher_check/schedule_seed.py create mode 100644 backend/app/services/voucher_check/share_scanner.py create mode 100644 backend/migrations/versions/a0b1c2d3e4f5_add_voucher_check_tables.py create mode 100644 backend/scripts/export_voucher_check_openapi.py create mode 100644 backend/tests/voucher_check/__init__.py create mode 100644 backend/tests/voucher_check/test_period_and_incremental.py create mode 100644 backend/tests/voucher_check/test_share_and_fingerprint.py create mode 100644 backend/tests/voucher_check/test_tool_auth_and_openapi.py create mode 100644 docs/features/accounting-voucher-check/dify-chatflow-draft.md create mode 100644 docs/features/accounting-voucher-check/ops-checklist.md create mode 100644 docs/openapi/accounting_voucher_check_tools_openapi.json create mode 100644 frontend/src/features/workspace/api/voucherCheck.api.ts create mode 100644 frontend/src/features/workspace/pages/AccountingVoucherCheckPage.vue create mode 100644 frontend/src/features/workspace/views/AccountingVoucherCheckView.vue diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 47bd2823..a22512fa 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -73,6 +73,15 @@ def create_app(config_name='default'): ensure_default_file_asset_cleanup_schedule() except Exception as exc: # pragma: no cover - 表未就绪时容忍 logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc) + try: + from app.services.voucher_check.schedule_seed import ( + ensure_default_voucher_check_schedule, + register_voucher_check_schedule_hooks, + ) + register_voucher_check_schedule_hooks() + ensure_default_voucher_check_schedule() + except Exception as exc: # pragma: no cover - 表未就绪时容忍 + logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc) from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService FixedAssetsSnapshotService.start_worker(app) diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 02afc046..dd5d73df 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -39,8 +39,9 @@ def register_blueprints(app: Flask) -> None: workspace_file_check_bp, workspace_schedule_bp, workspace_shipping_notice_bp, + workspace_voucher_check_bp, ) - from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp + from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp from app.api.files import files_bp from app.api.procurement_contract_tools import procurement_contract_bp @@ -57,10 +58,12 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace') app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_voucher_check_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') 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/file_check_tools.py b/backend/app/api/file_check_tools.py index f14336d1..c90a8387 100644 --- a/backend/app/api/file_check_tools.py +++ b/backend/app/api/file_check_tools.py @@ -1,9 +1,9 @@ """ backend/app/api/file_check_tools.py -用途:文件检核 Chatflow 显式 HTTP Tool API。 +用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。 依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。 -逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。 +逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。 """ from __future__ import annotations @@ -74,7 +74,7 @@ def _require_tool_auth() -> None: """ 校验 Tool API 访问权限。 - 核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。 + 核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。 """ # [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key if request.path.endswith("/excel"): @@ -84,26 +84,10 @@ def _require_tool_auth() -> None: return raise UnauthorizedError("invalid_auth") - # [STEP 2] Dify / RPA 服务端调用 - configured = str( - current_app.config.get("FILE_CHECK_TOOL_API_KEY") - or current_app.config.get("INTEGRATION_API_KEY") - or "" - ).strip() - if not configured: - raise ServiceUnavailableError( - "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", - code="missing_auth", - ) + # [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥) + from app.services.integration_tool_auth import require_integration_tool_auth - bearer = str(request.headers.get("Authorization") or "").strip() - api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" - integration_key = str(request.headers.get("X-Integration-Key") or "").strip() - if configured in {api_token, integration_key}: - return - if not api_token and not integration_key: - raise UnauthorizedError("missing_auth") - raise UnauthorizedError("invalid_auth") + require_integration_tool_auth() def _tool_error_code(exc: AppError) -> str: @@ -382,7 +366,17 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None: @file_check_bp.route("/tools/tasks/run", methods=["POST"]) def run_file_check(): - """立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。""" + """ + 立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。 + + 核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到 + ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。 + + Body 关键字段(立账凭证检核): + mode: incremental | force_all | single + invoice_no: mode=single 时发票号 + run_options: 可选嵌套对象,与顶层字段合并(顶层优先) + """ perf_started = time.perf_counter() data = _prepare_bind_payload(request.get_json(silent=True) or {}) task = _resolve_check_task(data) @@ -428,16 +422,33 @@ def run_file_check(): ) return jsonify(no_data_response) + # [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示), + # 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。 + raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {} + run_options = {} + mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower() + if mode in {"incremental", "force_all", "single"}: + run_options["mode"] = mode + invoice_no = data.get("invoice_no") + if invoice_no is None or not str(invoice_no).strip(): + invoice_no = raw_options.get("invoice_no") + if invoice_no is not None and str(invoice_no).strip(): + run_options["invoice_no"] = str(invoice_no).strip() + + api_request_json = { + "trigger_source": data.get("trigger_source") or "dify_chatflow", + "conversation_id": data.get("conversation_id"), + } + if run_options: + api_request_json["run_options"] = run_options + run = ScheduleRun( run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type="dify_chatflow", started_at=datetime.utcnow(), status="running", - api_request_json={ - "trigger_source": data.get("trigger_source") or "dify_chatflow", - "conversation_id": data.get("conversation_id"), - }, + api_request_json=api_request_json, ) db.session.add(run) db.session.commit() diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py index 38316390..dde84dcb 100644 --- a/backend/app/api/tools/__init__.py +++ b/backend/app/api/tools/__init__.py @@ -2,10 +2,11 @@ backend/app/api/tools/__init__.py 用途:Dify HTTP Tool API Blueprint 聚合。 -逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。 +逻辑:re-export shipping_notice、file_check、maintenance、voucher_check 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'] +__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp'] diff --git a/backend/app/api/tools/voucher_check.py b/backend/app/api/tools/voucher_check.py new file mode 100644 index 00000000..f06e6f84 --- /dev/null +++ b/backend/app/api/tools/voucher_check.py @@ -0,0 +1,105 @@ +""" +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/__init__.py b/backend/app/api/workspace/__init__.py index 1b6a4307..5043fec3 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -1,7 +1,7 @@ """ backend/app/api/workspace/__init__.py -用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。 +用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、voucher_check、announcements)。 依赖:workspace 各子模块 blueprint。 逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。 """ @@ -9,10 +9,12 @@ from app.api.workspace.announcements import workspace_announcements_bp from app.api.workspace.file_check import workspace_file_check_bp from app.api.workspace.schedule import workspace_schedule_bp from app.api.workspace.shipping_notice import workspace_shipping_notice_bp +from app.api.workspace.voucher_check import workspace_voucher_check_bp __all__ = [ 'workspace_announcements_bp', 'workspace_file_check_bp', 'workspace_schedule_bp', 'workspace_shipping_notice_bp', + 'workspace_voucher_check_bp', ] diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py index 2a6e47e1..8e2c9427 100644 --- a/backend/app/api/workspace/file_check.py +++ b/backend/app/api/workspace/file_check.py @@ -57,6 +57,31 @@ def serialize_current_step(payload: dict) -> dict | None: return None return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)} +def serialize_progress_metrics(payload: dict) -> list[dict] | None: + """ + 序列化领域自定义进度指标(如立账凭证检核的齐全/缺资料)。 + 核心逻辑:读取 response_summary_json.progress_metrics;非法则返回 None 以回退旧八格。 + """ + response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {} + metrics = response_summary.get('progress_metrics') + if not isinstance(metrics, list) or not metrics: + return None + out: list[dict] = [] + for item in metrics: + if not isinstance(item, dict): + continue + key = str(item.get('key') or '').strip() + if not key: + continue + out.append({ + 'key': key, + 'label_key': str(item.get('label_key') or ''), + 'label': str(item.get('label') or ''), + 'value': int(item.get('value') or 0), + }) + return out or None + + def _serialize_progress_run(run: ScheduleRun) -> dict: payload = serialize_run(run) total = int(payload.get('total_count') or 0) @@ -66,7 +91,39 @@ def _serialize_progress_run(run: ScheduleRun) -> dict: processed = success + failed + skipped percent = int(round(processed / total * 100)) if total > 0 else 0 percent = max(0, min(percent, 100)) - return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}} + return { + 'run_id': payload['id'], + 'run_no': payload['run_no'], + 'task_id': payload['schedule_task_id'], + 'title': payload.get('schedule_name') or '', + 'status': payload['status'], + 'total_count': total, + 'processed_count': processed, + 'success_count': success, + 'failed_count': failed, + 'skipped_count': skipped, + 'judgement': serialize_file_judgement(payload), + 'progress_metrics': serialize_progress_metrics(payload), + 'current_step': serialize_current_step(payload), + 'progress_percent': percent, + 'started_at': payload.get('started_at'), + 'finished_at': payload.get('finished_at'), + 'duration_ms': payload.get('duration_ms'), + 'error_message': payload.get('error_message'), + 'excel': { + 'file_name': payload.get('excel_file_name'), + 'file_size': payload.get('excel_file_size'), + 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None, + }, + 'knowledge_base': { + 'sync_status': payload.get('kb_sync_status'), + 'group_id': payload.get('kb_group_id'), + 'document_id': payload.get('kb_document_id'), + 'document_version_id': payload.get('kb_document_version_id'), + 'sync_job_id': payload.get('kb_sync_job_id'), + 'error_message': payload.get('kb_sync_error'), + }, + } @workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET']) def workspace_file_check_run_for_log(): diff --git a/backend/app/api/workspace/voucher_check.py b/backend/app/api/workspace/voucher_check.py new file mode 100644 index 00000000..4a471c7e --- /dev/null +++ b/backend/app/api/workspace/voucher_check.py @@ -0,0 +1,70 @@ +""" +backend/app/api/workspace/voucher_check.py + +用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。 +依赖:auth.jwt、response_utils envelope、voucher_check.query_service。 +逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。 +""" + +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.response import ok +from app.services.voucher_check import query_service + +workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__) + + +def _require_user(): + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +@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 过滤。 + """ + _require_user() + 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 ok(data) + + +@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"]) +def workspace_voucher_states(): + """ + 按月份、状态、发票号筛选最新状态。 + """ + _require_user() + data = query_service.list_states( + scope_code=str(request.args.get("scope_code") or "HXJM"), + period=request.args.get("period"), + status=request.args.get("status"), + invoice_no=request.args.get("invoice_no"), + 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 0e7e61d4..6e31dcc6 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -416,6 +416,18 @@ 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' + 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') + # MinIO 配置 MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000') MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin') diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 784a148e..60218ecd 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -2,7 +2,7 @@ backend/app/models/__init__.py 用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。 -依赖:models/* 子模块、app.extensions.db(经 base.Base)。 +依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。 逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。 """ @@ -32,6 +32,7 @@ from app.models.shipping import ( ) from app.models.training import TrainingRecord from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig +from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit __all__ = [ @@ -86,4 +87,6 @@ __all__ = [ 'MaintenanceDevice', 'MaintenanceRecord', 'MaintenanceAuditLog', + 'VoucherCheckInvoiceState', + 'VoucherCheckRunItem', ] diff --git a/backend/app/models/voucher_check.py b/backend/app/models/voucher_check.py new file mode 100644 index 00000000..7de44eb6 --- /dev/null +++ b/backend/app/models/voucher_check.py @@ -0,0 +1,114 @@ +""" +backend/app/models/voucher_check.py + +用途:立账凭证检核单票最新状态与批次明细 ORM。 +依赖:models.base.Base、schedule_runs。 +逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from typing import Optional + +from sqlalchemy import ( + BigInteger, + Boolean, + Date, + DateTime, + ForeignKey, + Index, + JSON, + String, + Text, + UniqueConstraint, +) +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class VoucherCheckInvoiceState(Base): + """账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。""" + + __tablename__ = "voucher_check_invoice_states" + __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"), + ) + + 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) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, + default=datetime.utcnow, + onupdate=datetime.utcnow, + nullable=False, + ) + + +class VoucherCheckRunItem(Base): + """单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。""" + + __tablename__ = "voucher_check_run_items" + __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"), + ) + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + schedule_run_id: Mapped[int] = mapped_column( + BigInteger, + ForeignKey("schedule_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) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/services/file_check_tools/openapi_base.json b/backend/app/services/file_check_tools/openapi_base.json index 4222cc60..5b9471e5 100644 --- a/backend/app/services/file_check_tools/openapi_base.json +++ b/backend/app/services/file_check_tools/openapi_base.json @@ -560,12 +560,40 @@ "type": "string", "nullable": true, "description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入" + }, + "mode": { + "type": "string", + "nullable": true, + "enum": ["incremental", "force_all", "single"], + "description": "【Dify 推荐】运行模式(立账凭证检核读取;文件检核忽略)。incremental=增量 / force_all=全量 / single=单发票;单发票时须同时填 invoice_no" + }, + "invoice_no": { + "type": "string", + "nullable": true, + "description": "【Dify 推荐】mode=single 时必填的发票号;来自意图识别.invoice_no" + }, + "run_options": { + "type": "object", + "nullable": true, + "description": "可选嵌套写法(部分 Dify 版本不展示对象字段;优先用顶层 mode/invoice_no)。mode=incremental|force_all|single;single 时须带 invoice_no", + "properties": { + "mode": { + "type": "string", + "enum": ["incremental", "force_all", "single"], + "default": "incremental" + }, + "invoice_no": { + "type": "string", + "nullable": true, + "description": "mode=single 时必填的发票号" + } + } } }, "required": [ "task_id" ], - "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底" + "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);立账凭证检核用顶层 mode/invoice_no(Dify 友好)或嵌套 run_options" }, "RunCheckSuccessResponse": { "type": "object", diff --git a/backend/app/services/integration_tool_auth.py b/backend/app/services/integration_tool_auth.py new file mode 100644 index 00000000..fbf31ede --- /dev/null +++ b/backend/app/services/integration_tool_auth.py @@ -0,0 +1,44 @@ +""" +backend/app/services/integration_tool_auth.py + +用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。 +依赖:Flask current_app、core.errors。 +逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用; + 密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。 +""" + +from __future__ import annotations + +from flask import current_app, request + +from app.core.errors import ServiceUnavailableError, UnauthorizedError + + +def require_integration_tool_auth() -> None: + """ + 校验 Tool API 访问权限。 + 核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。 + + Raises: + ServiceUnavailableError: 服务端未配置密钥。 + UnauthorizedError: 缺少或错误的凭证。 + """ + configured = str( + current_app.config.get("FILE_CHECK_TOOL_API_KEY") + or current_app.config.get("INTEGRATION_API_KEY") + or "" + ).strip() + if not configured: + raise ServiceUnavailableError( + "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", + code="missing_auth", + ) + + bearer = str(request.headers.get("Authorization") or "").strip() + api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" + integration_key = str(request.headers.get("X-Integration-Key") or "").strip() + if configured in {api_token, integration_key}: + return + if not api_token and not integration_key: + raise UnauthorizedError("missing_auth") + raise UnauthorizedError("invalid_auth") diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index 20cc2f51..acfe0645 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -81,7 +81,10 @@ def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> Schedu from app.services.schedule.job_registry import run_platform_job key = normalize_platform_api_path(task.platform_api_path) + # [STEP 1] 合并而非覆盖:保留会话触发写入的 run_options 等字段 + existing = run.api_request_json if isinstance(run.api_request_json, dict) else {} payload = { + **existing, "run_no": run.run_no, "schedule_task_id": task.id, "schedule_name": task.name, diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index 0757a47b..97f34172 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -2,7 +2,7 @@ backend/app/services/schedule/job_registry.py 用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。 -依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、job_params(执行前校验)。 +依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。 逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key; api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。 """ @@ -132,6 +132,8 @@ def _register_builtin_platform_jobs() -> None: from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule + from app.services.schedule.voucher_check_job import run_voucher_check_schedule + from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES register_platform_job(PlatformJobDefinition( key="shipping-inventory-rpa", @@ -200,6 +202,77 @@ def _register_builtin_platform_jobs() -> None: description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。", category="files", )) + register_platform_job(PlatformJobDefinition( + key="accounting-voucher-check", + label="立账凭证检核", + label_key="admin.schedule.form.platformJobAccountingVoucherCheck", + handler=run_voucher_check_schedule, + description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。", + description_key="admin.schedule.form.accountingVoucherCheckHint", + category="finance", + params_schema=( + { + "key": "scope_code", + "type": "select", + "label": "账套", + "label_key": "admin.schedule.form.voucherCheckScope", + "required": True, + "default": "HXJM", + "options": [{"value": "HXJM", "label": "HXJM"}], + }, + { + "key": "directory_template", + "type": "text", + "label": "目录模板", + "label_key": "admin.schedule.form.voucherCheckDirTemplate", + "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, + }, + { + "key": "notify_missing_enabled", + "type": "boolean", + "label": "缺资料通知", + "label_key": "admin.schedule.form.voucherCheckNotifyMissing", + "required": False, + "default": True, + }, + { + "key": "notify_failure_enabled", + "type": "boolean", + "label": "失败告警", + "label_key": "admin.schedule.form.voucherCheckNotifyFailure", + "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), + )) _register_builtin_platform_jobs() diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 9c6e97fa..cf72c362 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -142,6 +142,11 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: + """ + 排程完成后的通用企微通知。 + 核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核), + 则跳过以免与领域缺件/失败告警重复。 + """ from app.services.wecom_notify import ( upload_wecom_temp_media, send_wecom_file_message, @@ -151,6 +156,12 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: _get_enabled_events, ) + # 领域自行管理通知时跳过通用完成通知,避免重复刷屏 + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if summary.get('domain_notification_managed'): + run.wecom_notify_error = 'domain_notification_managed' + return + if not current_app.config.get('WECOM_NOTIFY_ENABLED', True): run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false' return diff --git a/backend/app/services/schedule/voucher_check_job.py b/backend/app/services/schedule/voucher_check_job.py new file mode 100644 index 00000000..758f1be5 --- /dev/null +++ b/backend/app/services/schedule/voucher_check_job.py @@ -0,0 +1,44 @@ +""" +backend/app/services/schedule/voucher_check_job.py + +用途:立账凭证检核 platform_job 薄封装。 +依赖:voucher_check.runner、excel_rows 表头注册。 +逻辑:job_registry 注册 accounting-voucher-check 后由 schedule worker / 会话触发调用。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.schedule import register_schedule_header +from app.services.voucher_check.excel_rows import ( + VOUCHER_CHECK_HEADER_LABELS, + VOUCHER_CHECK_HEADER_ORDER, +) +from app.services.voucher_check.runner import run_voucher_check_batch + +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + +_HEADERS_REGISTERED = False + + +def _ensure_headers() -> None: + global _HEADERS_REGISTERED + if _HEADERS_REGISTERED: + return + register_schedule_header( + "accounting-voucher-check", + VOUCHER_CHECK_HEADER_ORDER, + VOUCHER_CHECK_HEADER_LABELS, + ) + _HEADERS_REGISTERED = True + + +def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 执行立账凭证检核排程。 + 核心逻辑:注册 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 new file mode 100644 index 00000000..a303a55d --- /dev/null +++ b/backend/app/services/voucher_check/__init__.py @@ -0,0 +1,11 @@ +""" +backend/app/services/voucher_check/__init__.py + +用途:立账凭证检核领域服务包入口。 +依赖:config / runner / query_service 等子模块。 +逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。 +""" + +from app.services.voucher_check.runner import run_voucher_check_batch + +__all__ = ["run_voucher_check_batch"] diff --git a/backend/app/services/voucher_check/config.py b/backend/app/services/voucher_check/config.py new file mode 100644 index 00000000..c22fc367 --- /dev/null +++ b/backend/app/services/voucher_check/config.py @@ -0,0 +1,262 @@ +""" +backend/app/services/voucher_check/config.py + +用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。 +依赖:Flask current_app.config、core.errors.ValidationError。 +逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。 +""" + +from __future__ import annotations + +import json +import os +import re +from dataclasses import dataclass +from typing import Any + +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] = { + "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: + """运行期检核配置快照。""" + + scope_code: str + directory_template: str + required_files: tuple[RequiredFileRule, ...] + filename_case_sensitive: bool + 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 + erp_timeout_seconds: int = 30 + + +def _config_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError: + return ValidationError( + message, + code="VOUCHER_CHECK.CONFIG_INVALID", + details=details or {}, + ) + + +def _as_bool(value: Any, default: bool) -> bool: + if value is None: + return default + if isinstance(value, bool): + return value + text = str(value).strip().lower() + if text in {"1", "true", "yes", "on"}: + return True + if text in {"0", "false", "no", "off"}: + return False + 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: + """ + 校验目录模板占位符。 + 核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。 + """ + 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") + or cfg.get("ERP_DB_DSN") + or os.getenv("ERP_DB_DSN") + or "" + ).strip() + erp_username = str( + cfg.get("VOUCHER_CHECK_ERP_USERNAME") + or os.getenv("VOUCHER_CHECK_ERP_USERNAME") + or "" + ).strip() + erp_password = str( + cfg.get("VOUCHER_CHECK_ERP_PASSWORD") + or os.getenv("VOUCHER_CHECK_ERP_PASSWORD") + or "" + ) + if not erp_dsn or not erp_username: + raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME") + + timeout = int( + cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") + or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS") + or 30 + ) + + return VoucherCheckConfig( + scope_code=scope_code, + directory_template=template, + required_files=tuple(required_files), + filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True), + 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), + ) + + +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/erp_repository.py b/backend/app/services/voucher_check/erp_repository.py new file mode 100644 index 00000000..b4e922db --- /dev/null +++ b/backend/app/services/voucher_check/erp_repository.py @@ -0,0 +1,146 @@ +""" +backend/app/services/voucher_check/erp_repository.py + +用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。 +依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。 +逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.config import VoucherCheckConfig + +_TZ = ZoneInfo("Asia/Shanghai") + +_INVOICE_SQL = """ +SELECT DISTINCT + TRIM(apa08) AS invoice_no, + TRUNC(apa09) AS invoice_date + FROM apa_file + WHERE apa09 >= :period_start + AND apa09 < :next_period_start + AND TRIM(apa08) IS NOT NULL + ORDER BY TRUNC(apa09), TRIM(apa08) +""" + + +@dataclass(frozen=True) +class ErpInvoiceRow: + """ERP 当月发票行。""" + + invoice_no: str + invoice_date: date | None + + +def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]: + """ + 按 Asia/Shanghai 计算当前自然月起止。 + 核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。 + + Returns: + (period_month_first, next_month_first, period_start_dt, next_period_start_dt) + """ + base = now.astimezone(_TZ) if now and now.tzinfo else (now or datetime.now(_TZ)) + if base.tzinfo is None: + base = base.replace(tzinfo=_TZ) + else: + base = base.astimezone(_TZ) + period_month = date(base.year, base.month, 1) + if base.month == 12: + next_month = date(base.year + 1, 1, 1) + else: + next_month = date(base.year, base.month + 1, 1) + period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ) + next_start = datetime(next_month.year, next_month.month, 1, 0, 0, 0, tzinfo=_TZ) + return period_month, next_month, period_start, next_start + + +def fetch_month_invoices( + config: VoucherCheckConfig, + *, + now: datetime | None = None, +) -> tuple[date, list[ErpInvoiceRow]]: + """ + 查询当前自然月发票清单。 + + Args: + config: 含 Oracle DSN/账号的检核配置。 + now: 可选时钟(测试注入)。 + + Returns: + (period_month, invoices) + + Raises: + ServiceUnavailableError: Oracle 不可用。 + """ + period_month, _next_month, period_start, next_start = current_period_bounds(now) + try: + import oracledb + except ImportError as exc: + raise ServiceUnavailableError( + "Oracle 驱动不可用", + code="VOUCHER_CHECK.ERP_UNAVAILABLE", + ) from exc + + from flask import current_app + from app.services.text2sql import Text2SQLService + + connection = None + try: + Text2SQLService._init_oracle_client(oracledb) + connection = oracledb.connect( + user=config.erp_username, + password=config.erp_password, + dsn=config.erp_dsn, + ) + connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000 + cursor = connection.cursor() + cursor.execute( + _INVOICE_SQL, + { + "period_start": period_start.replace(tzinfo=None), + "next_period_start": next_start.replace(tzinfo=None), + }, + ) + rows: list[ErpInvoiceRow] = [] + seen: set[str] = set() + for raw_no, raw_date in cursor: + invoice_no = str(raw_no or "").strip() + if not invoice_no or invoice_no in seen: + continue + seen.add(invoice_no) + invoice_date: date | None = None + if raw_date is not None: + if isinstance(raw_date, datetime): + invoice_date = raw_date.date() + elif isinstance(raw_date, date): + invoice_date = raw_date + rows.append(ErpInvoiceRow(invoice_no=invoice_no, invoice_date=invoice_date)) + return period_month, rows + except ServiceUnavailableError: + raise + except Exception as exc: + try: + current_app.logger.error( + "[voucher-check] ERP query failed dsn=%s error_type=%s", + config.erp_dsn, + type(exc).__name__, + ) + except Exception: + pass + raise ServiceUnavailableError( + "Oracle 查询失败", + code="VOUCHER_CHECK.ERP_UNAVAILABLE", + details={"error_type": type(exc).__name__}, + ) from exc + finally: + if connection is not None: + try: + connection.close() + except Exception: + pass diff --git a/backend/app/services/voucher_check/excel_rows.py b/backend/app/services/voucher_check/excel_rows.py new file mode 100644 index 00000000..a690c1d6 --- /dev/null +++ b/backend/app/services/voucher_check/excel_rows.py @@ -0,0 +1,93 @@ +""" +backend/app/services/voucher_check/excel_rows.py + +用途:把批次明细转换为通用 Excel 导出行与表头。 +依赖:无。 +逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。 +""" + +from __future__ import annotations + +from typing import Any + +VOUCHER_CHECK_HEADER_ORDER = [ + "period", + "scope_code", + "invoice_no", + "invoice_date", + "result", + "folder_exists", + "folder_path", + "matched_files", + "missing_materials", + "material_fingerprint", + "checked_at", + "error_code", + "error_message", +] + +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": "技术错误摘要", +} + +_RESULT_LABELS = { + "complete": "齐全", + "missing": "缺资料", + "skipped": "跳过", + "technical_error": "技术异常", +} + + +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]: + """ + 将内存结果行转为 Excel details 行。 + """ + result = str(item.get("result") or "") + checked_at = item.get("checked_at") + invoice_date = item.get("invoice_date") + return { + "period": period, + "scope_code": scope_code, + "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 "", + } diff --git a/backend/app/services/voucher_check/fingerprint.py b/backend/app/services/voucher_check/fingerprint.py new file mode 100644 index 00000000..02b0f568 --- /dev/null +++ b/backend/app/services/voucher_check/fingerprint.py @@ -0,0 +1,34 @@ +""" +backend/app/services/voucher_check/fingerprint.py + +用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。 +依赖:标准库 hashlib / json。 +逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。 +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Iterable, Sequence + + +def build_material_fingerprint( + entries: Sequence[tuple[str, int, int]] | Iterable[tuple[str, int, int]], +) -> str: + """ + 对直接子文件元数据生成 SHA-256。 + 核心逻辑:按文件名排序后序列化为 UTF-8 JSON,再哈希;不读取文件内容。 + + Args: + entries: (filename, size, mtime_ns) 列表。 + + Returns: + 64 位十六进制 SHA-256;无文件时对空数组哈希。 + """ + normalized = sorted( + [(str(name), int(size), int(mtime_ns)) for name, size, mtime_ns in entries], + key=lambda item: item[0], + ) + payload = json.dumps(normalized, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(payload).hexdigest() diff --git a/backend/app/services/voucher_check/notification.py b/backend/app/services/voucher_check/notification.py new file mode 100644 index 00000000..10255011 --- /dev/null +++ b/backend/app/services/voucher_check/notification.py @@ -0,0 +1,205 @@ +""" +backend/app/services/voucher_check/notification.py + +用途:立账凭证检核缺资料企微 textcard 与批次失败告警。 +依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。 +逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。 +""" + +from __future__ import annotations + +import uuid +from datetime import date, datetime +from typing import Any +from zoneinfo import ZoneInfo + +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 + +_TZ = ZoneInfo("Asia/Shanghai") + + +def _recipient_users(task: ScheduleTask) -> list[User]: + user_ids = task.notify_user_ids_json or [] + if not user_ids: + return [] + users = db.session.query(User).filter(User.id.in_(user_ids)).all() + 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( + *, + task: ScheduleTask, + run: ScheduleRun, + scope_code: str, + period_month: date, + missing_items: list[dict[str, Any]], + same_day_dedup: bool, + enabled: bool, +) -> int: + """ + 合并发送缺资料 textcard。 + 核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。 + + Returns: + 本次实际通知的发票数。 + """ + if not enabled or not missing_items: + return 0 + if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): + return 0 + + 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() + ) + 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}" + description = ( + f"批次 {run.run_no}\n" + f"检核月份 {period}\n" + f"缺资料 {len(to_notify)} 张\n" + f"示例:{sample}\n" + f"完整清单请查看工作台检核记录或 Excel。" + ) + ok_any = False + for user in users: + trace_id = uuid.uuid4().hex + jump_url = _build_jump_url( + "/workspace/accounting-voucher-check", + trace_id, + {"task_id": task.id, "run_id": run.id}, + ) + try: + audit = _create_audit("voucher_check_missing", user, title, description, trace_id) + audit.jump_url = jump_url + data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url) + if data.get("errcode") == 0: + audit.status = "sent" + ok_any = True + else: + audit.error_code = str(data.get("errcode")) + 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", + 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 + + +def send_failure_alert( + *, + task: ScheduleTask, + run: ScheduleRun, + stage: str, + error_code: str, + error_message: str, + enabled: bool, +) -> None: + """批次级失败告警(共享盘/Oracle/业务配置异常)。""" + if not enabled: + return + if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): + return + + from app.services.wecom_notify import ( + _build_jump_url, + _create_audit, + send_wecom_textcard_message, + ) + + users = _recipient_users(task) + if not users: + return + + title = f"立账凭证检核失败: {task.name}" + description = ( + f"批次 {run.run_no}\n" + f"失败阶段:{stage}\n" + f"错误码:{error_code}\n" + f"摘要:{(error_message or '')[:200]}\n" + f"run_id={run.id}\n" + f"请检查 Oracle 连接与共享盘挂载/健康标记。" + ) + for user in users: + trace_id = uuid.uuid4().hex + jump_url = _build_jump_url( + "/admin/schedules", + trace_id, + {"task_id": task.id, "run_id": run.id}, + ) + try: + audit = _create_audit("voucher_check_failure", user, title, description, trace_id) + audit.jump_url = jump_url + data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url) + if data.get("errcode") == 0: + audit.status = "sent" + else: + audit.error_code = str(data.get("errcode")) + audit.error_message = str(data.get("errmsg", "unknown"))[:255] + except Exception as exc: + current_app.logger.warning( + "[voucher-check] failure alert failed user=%s err=%s", + user.id, + exc, + ) + db.session.commit() diff --git a/backend/app/services/voucher_check/openapi_base.json b/backend/app/services/voucher_check/openapi_base.json new file mode 100644 index 00000000..372a97c4 --- /dev/null +++ b/backend/app/services/voucher_check/openapi_base.json @@ -0,0 +1,316 @@ +{ + "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 new file mode 100644 index 00000000..ce8f976f --- /dev/null +++ b/backend/app/services/voucher_check/openapi_spec.py @@ -0,0 +1,35 @@ +""" +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 new file mode 100644 index 00000000..74e75271 --- /dev/null +++ b/backend/app/services/voucher_check/persistence.py @@ -0,0 +1,126 @@ +""" +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/query_service.py b/backend/app/services/voucher_check/query_service.py new file mode 100644 index 00000000..61eefc70 --- /dev/null +++ b/backend/app/services/voucher_check/query_service.py @@ -0,0 +1,220 @@ +""" +backend/app/services/voucher_check/query_service.py + +用途:查询批次明细、当月缺资料与单票最新状态。 +依赖:models.voucher_check、ScheduleRun。 +逻辑:Tool API 与工作台 API 调用;不触发扫描。 +""" + +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, + } + + +def parse_period_month(raw: str | None) -> date: + """解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。""" + if not raw: + period_month, *_ = current_period_bounds() + return period_month + text = str(raw).strip() + try: + if len(text) == 7: + dt = datetime.strptime(text, "%Y-%m") + else: + dt = datetime.strptime(text[:10], "%Y-%m-%d") + return date(dt.year, dt.month, 1) + except ValueError as exc: + raise ValidationError( + "period 格式须为 YYYY-MM", + code="VOUCHER_CHECK.CONFIG_INVALID", + ) from exc + + +def list_missing_states( + *, + task_id: int | None = None, + scope_code: str = "HXJM", + period: str | None = None, + limit: int = 200, +) -> dict[str, Any]: + """ + 查询指定月份缺资料票(最新状态表)。 + task_id 预留与排程绑定校验,本期仅用于响应回显。 + """ + 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", + ) + .order_by(VoucherCheckInvoiceState.invoice_no.asc()) + .limit(limit) + ) + items = [_serialize_state(s) for s in q.all()] + return { + "task_id": task_id, + "scope_code": scope_code, + "period": period_month.strftime("%Y-%m"), + "count": len(items), + "items": items, + } + + +def list_run_items( + *, + run_id: int, + result: str | None = None, + page: int = 1, + page_size: int = 50, +) -> dict[str, Any]: + """分页查询批次明细。""" + 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() + ) + return { + "run_id": run_id, + "run_no": run.run_no, + "page": page, + "page_size": page_size, + "total": total, + "items": [_serialize_run_item(r) for r in rows], + } + + +def get_invoice_latest( + *, + 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, + page: int = 1, + page_size: int = 50, +) -> dict[str, Any]: + """工作台:按月/状态/发票号筛选最新状态。""" + period_month = parse_period_month(period) + 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, + ) + 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()}%")) + total = q.count() + rows = ( + q.order_by(VoucherCheckInvoiceState.invoice_no.asc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + 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], + } diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py new file mode 100644 index 00000000..dcdbbe9d --- /dev/null +++ b/backend/app/services/voucher_check/runner.py @@ -0,0 +1,366 @@ +""" +backend/app/services/voucher_check/runner.py + +用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。 +依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。 +逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +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 + +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + + +def _extract_run_options(run: ScheduleRun) -> dict[str, Any]: + payload = run.api_request_json if isinstance(run.api_request_json, dict) else {} + options = payload.get("run_options") + if not isinstance(options, dict): + options = {} + mode = str(options.get("mode") or "incremental").strip().lower() + if mode not in {"incremental", "force_all", "single"}: + mode = "incremental" + invoice_no = options.get("invoice_no") + invoice_no = str(invoice_no).strip() if invoice_no else None + return {"mode": mode, "invoice_no": invoice_no} + + +def _update_progress( + run: ScheduleRun, + *, + step: str, + label: str, + processed: int = 0, + voucher_summary: dict[str, Any] | None = None, +) -> None: + summary = dict(run.response_summary_json or {}) + summary["current_step"] = { + "step": step, + "label": label, + "processed_count": processed, + } + 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), + "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)}, + ] + summary["domain_notification_managed"] = True + run.response_summary_json = summary + db.session.commit() + + +def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 执行立账凭证检核批次。 + 核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。 + + Returns: + ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs) + """ + step_logs: list[dict[str, Any]] = [] + errors: list[str] = [] + options = _extract_run_options(run) + mode = options["mode"] + single_invoice = options["invoice_no"] + + try: + config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {}) + except AppError as exc: + send_failure_alert( + task=task, + run=run, + stage="config", + error_code=exc.code, + error_message=exc.message, + enabled=True, + ) + raise + + # [STEP 1] 拉取 ERP 当月发票清单 + _update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证") + try: + period_month, invoices = fetch_month_invoices(config) + except ServiceUnavailableError as exc: + send_failure_alert( + task=task, + run=run, + stage="fetch_erp", + error_code=exc.code, + error_message=exc.message, + enabled=config.notify_failure_enabled, + ) + raise + step_logs.append( + { + "step": "fetch_erp", + "status": "success", + "detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")}, + } + ) + + if mode == "single": + if not single_invoice: + raise ValidationError( + "single 模式必须提供 invoice_no", + code="VOUCHER_CHECK.INVOICE_REQUIRED", + ) + invoices = [row for row in invoices if row.invoice_no == single_invoice] + if not invoices: + raise NotFoundError( + "指定发票不在当前月 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() + ) + state_map = {s.invoice_no: s for s in existing_states} + + results: list[dict[str, Any]] = [] + complete_count = 0 + missing_count = 0 + skipped_count = 0 + technical_error_count = 0 + now = datetime.utcnow() + force = mode in {"force_all", "single"} + + # [STEP 4] 逐票扫描 / 指纹比对 + _update_progress( + run, + step="scan_share", + label="扫描共享盘文件名", + processed=0, + voucher_summary={ + "scope_code": config.scope_code, + "period": period_month.strftime("%Y-%m"), + "mode": mode, + "total_count": len(invoices), + "complete_count": 0, + "missing_count": 0, + "scan_count": 0, + "skipped_count": 0, + "technical_error_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, + "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 + else: + missing_count += 1 + results.append(item) + + if idx % 20 == 0 or idx == len(invoices): + scan_count = complete_count + missing_count + technical_error_count + _update_progress( + run, + step="scan_share", + label="扫描共享盘文件名", + processed=idx, + voucher_summary={ + "scope_code": config.scope_code, + "period": period_month.strftime("%Y-%m"), + "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, + }, + ) + + step_logs.append( + { + "step": "scan_share", + "status": "success", + "detail": { + "complete": complete_count, + "missing": missing_count, + "skipped": skipped_count, + "technical_error": technical_error_count, + }, + } + ) + + # [STEP 5] 事务落库 + _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, + now=now, + ) + db.session.commit() + except Exception as exc: + db.session.rollback() + current_app.logger.error("[voucher-check] persist failed run_id=%s: %s", run.id, exc, exc_info=True) + send_failure_alert( + task=task, + run=run, + stage="persist", + error_code="VOUCHER_CHECK.PERSIST_FAILED", + error_message=str(exc), + enabled=config.notify_failure_enabled, + ) + raise + + # [STEP 6] 缺资料通知 + missing_items = [r for r in results if r["result"] == "missing"] + notified = send_missing_notifications( + 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, + enabled=config.notify_missing_enabled, + ) + step_logs.append( + { + "step": "notify", + "status": "success", + "detail": {"missing": len(missing_items), "notified": notified}, + } + ) + + period = period_month.strftime("%Y-%m") + scan_count = complete_count + missing_count + technical_error_count + 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, + } + _update_progress( + run, + step="done", + label="检核完成", + processed=len(invoices), + 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) + return ( + total_count, + success_count, + technical_error_count, + skipped_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 new file mode 100644 index 00000000..936c3d75 --- /dev/null +++ b/backend/app/services/voucher_check/schedule_seed.py @@ -0,0 +1,149 @@ +""" +backend/app/services/voucher_check/schedule_seed.py + +用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。 +依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。 +逻辑:迁移种子 + create_app / User after_commit 幂等补建。 +""" + +from __future__ import annotations + +import logging +from datetime import datetime +from typing import Any + +from sqlalchemy import event +from sqlalchemy.orm import Session + +from app import db +from app.models import ScheduleTask, User +from app.services.schedule.timezone_util import compute_next_run_at +from app.services.voucher_check.config import DEFAULT_JOB_PARAMS + +_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 = "立账凭证检核(日批)" + +_HOOKS_REGISTERED = False +_SESSION_INFO_KEY = "_seed_voucher_check_schedule" + + +def ensure_default_voucher_check_schedule( + *, + commit: bool = True, + session: Any | None = None, +) -> ScheduleTask | None: + """ + 幂等确保默认立账凭证检核日批排程存在。 + + Args: + commit: 是否立即提交。 + session: 可选独立 Session。 + + Returns: + 新建或已存在的 ScheduleTask;尚无用户时返回 None。 + """ + sess = session if session is not None else db.session + existing = ( + sess.query(ScheduleTask) + .filter( + (ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO) + | (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH) + ) + .first() + ) + if existing is not None: + return existing + + owner = ( + sess.query(User) + .filter(User.role == "admin") + .order_by(User.id.asc()) + .first() + ) + if owner is None: + owner = sess.query(User).order_by(User.id.asc()).first() + if owner is None: + _LOGGER.info("skip seed accounting-voucher-check schedule: no users yet") + return None + + now = datetime.utcnow() + next_run = compute_next_run_at( + DEFAULT_VOUCHER_CHECK_CRON, + timezone_name="Asia/Shanghai", + ) or now + + task = ScheduleTask( + schedule_no=DEFAULT_VOUCHER_CHECK_SCHEDULE_NO, + name=DEFAULT_VOUCHER_CHECK_NAME, + schedule_type="platform_job", + owner_user_id=int(owner.id), + cron_expr=DEFAULT_VOUCHER_CHECK_CRON, + schedule_timezone="Asia/Shanghai", + wait_seconds=0, + platform_api_path=DEFAULT_VOUCHER_CHECK_PLATFORM_PATH, + job_params=dict(DEFAULT_JOB_PARAMS), + kb_sync_enabled=False, + notify_user_ids_json=[], + notify_enabled=True, + enabled=True, + next_run_at=next_run, + created_by=int(owner.id), + updated_by=int(owner.id), + created_at=now, + updated_at=now, + ) + sess.add(task) + if commit: + try: + sess.commit() + except Exception: + sess.rollback() + existing = ( + sess.query(ScheduleTask) + .filter( + (ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO) + | (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH) + ) + .first() + ) + if existing is not None: + return existing + raise + else: + sess.flush() + _LOGGER.info("seeded accounting-voucher-check schedule id=%s", task.id) + return task + + +def register_voucher_check_schedule_hooks() -> None: + """注册 User after_commit 补建钩子(幂等)。""" + global _HOOKS_REGISTERED + if _HOOKS_REGISTERED: + return + + @event.listens_for(Session, "after_commit") + def _after_commit(session: Session) -> None: + if not session.info.get(_SESSION_INFO_KEY): + return + session.info[_SESSION_INFO_KEY] = False + try: + from sqlalchemy.orm import sessionmaker + + bind = session.get_bind() + factory = sessionmaker(bind=bind) + with factory() as new_sess: + ensure_default_voucher_check_schedule(commit=True, session=new_sess) + except Exception: + _LOGGER.exception("voucher-check schedule seed after_commit failed") + + @event.listens_for(User, "after_insert") + def _user_after_insert(mapper, connection, target) -> None: # noqa: ARG001 + sess = Session.object_session(target) + if sess is not None: + sess.info[_SESSION_INFO_KEY] = True + + _HOOKS_REGISTERED = True diff --git a/backend/app/services/voucher_check/share_scanner.py b/backend/app/services/voucher_check/share_scanner.py new file mode 100644 index 00000000..020e1d13 --- /dev/null +++ b/backend/app/services/voucher_check/share_scanner.py @@ -0,0 +1,273 @@ +""" +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/a0b1c2d3e4f5_add_voucher_check_tables.py b/backend/migrations/versions/a0b1c2d3e4f5_add_voucher_check_tables.py new file mode 100644 index 00000000..92ffce93 --- /dev/null +++ b/backend/migrations/versions/a0b1c2d3e4f5_add_voucher_check_tables.py @@ -0,0 +1,235 @@ +""" +backend/migrations/versions/a0b1c2d3e4f5_add_voucher_check_tables.py + +用途:新增立账凭证检核状态/明细表,并种子日批 ScheduleTask(06:00)。 +依赖:Alembic revision e5f7a9b1c3d4;schedule_runs / users 已存在。 +逻辑:建表 + 幂等插入 SCH-ACCOUNTING-VOUCHER-CHECK;无用户时跳过种子由应用钩子补建。 + +Revision ID: a0b1c2d3e4f5 +Revises: e5f7a9b1c3d4 +Create Date: 2026-08-05 10:50:00.000000 +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "a0b1c2d3e4f5" +down_revision = "e5f7a9b1c3d4" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK" +_CRON_EXPR = "0 6 * * *" +_TZ_NAME = "Asia/Shanghai" + +_DEFAULT_JOB_PARAMS = { + "scope_code": "HXJM", + "directory_template": "{root}/{YYYY}/{MM}/{invoice_no}", + "required_files": [ + { + "code": "price_check_sheet", + "name": "核价单", + "required": True, + "accepted_filenames": ["核价单.pdf"], + }, + { + "code": "purchase_order", + "name": "采购单", + "required": True, + "accepted_filenames": ["采购单.pdf"], + }, + ], + "filename_case_sensitive": True, + "notify_missing_enabled": True, + "notify_failure_enabled": True, + "same_day_dedup_enabled": True, +} + + +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(_CRON_EXPR, 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) + if next_local <= now_local: + next_local = next_local + timedelta(days=1) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> 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"], + ) + + conn = op.get_bind() + exists = conn.execute( + sa.text( + "SELECT 1 FROM schedule_tasks " + "WHERE schedule_no = :sno OR platform_api_path = 'accounting-voucher-check' " + "LIMIT 1" + ), + {"sno": _SCHEDULE_NO}, + ).first() + if exists: + return + + owner = conn.execute( + sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1") + ).first() + if owner is None: + owner = conn.execute(sa.text("SELECT id FROM users ORDER BY id ASC LIMIT 1")).first() + if owner is None: + return + + now = datetime.utcnow() + next_run = _compute_next_run_at_utc_naive() + conn.execute( + sa.text( + """ + INSERT INTO schedule_tasks ( + schedule_no, name, schedule_type, owner_user_id, + cron_expr, schedule_timezone, wait_seconds, + platform_api_path, job_params, + kb_sync_enabled, notify_enabled, + enabled, next_run_at, last_run_at, + created_by, updated_by, created_at, updated_at + ) VALUES ( + :schedule_no, :name, 'platform_job', :owner_user_id, + :cron_expr, 'Asia/Shanghai', 0, + 'accounting-voucher-check', CAST(:job_params AS JSONB), + false, true, + true, :next_run_at, NULL, + :owner_user_id, :owner_user_id, :now, :now + ) + """ + ).bindparams(sa.bindparam("job_params", type_=sa.String())), + { + "schedule_no": _SCHEDULE_NO, + "name": "立账凭证检核(日批)", + "owner_user_id": int(owner[0]), + "cron_expr": _CRON_EXPR, + "job_params": json.dumps(_DEFAULT_JOB_PARAMS, ensure_ascii=False), + "next_run_at": next_run, + "now": now, + }, + ) + + +def downgrade() -> None: + conn = op.get_bind() + conn.execute( + sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"), + {"sno": _SCHEDULE_NO}, + ) + 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") diff --git a/backend/scripts/export_voucher_check_openapi.py b/backend/scripts/export_voucher_check_openapi.py new file mode 100644 index 00000000..da8c97ce --- /dev/null +++ b/backend/scripts/export_voucher_check_openapi.py @@ -0,0 +1,39 @@ +""" +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/voucher_check/__init__.py b/backend/tests/voucher_check/__init__.py new file mode 100644 index 00000000..a2aafc16 --- /dev/null +++ b/backend/tests/voucher_check/__init__.py @@ -0,0 +1 @@ +"""backend/tests/voucher_check — 立账凭证检核单测包。""" diff --git a/backend/tests/voucher_check/test_period_and_incremental.py b/backend/tests/voucher_check/test_period_and_incremental.py new file mode 100644 index 00000000..bbd8295e --- /dev/null +++ b/backend/tests/voucher_check/test_period_and_incremental.py @@ -0,0 +1,30 @@ +""" +backend/tests/voucher_check/test_period_and_incremental.py + +用途:自然月边界与增量跳过决策相关单测。 +依赖:pytest、erp_repository.current_period_bounds。 +逻辑:固定时钟注入,验证 Asia/Shanghai 月初/下月边界。 +""" + +from __future__ import annotations + +from datetime import datetime +from zoneinfo import ZoneInfo + +from app.services.voucher_check.erp_repository import current_period_bounds + + +def test_current_period_bounds_shanghai_august(): + now = datetime(2026, 8, 15, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai")) + period_month, next_month, period_start, next_start = current_period_bounds(now) + assert period_month.isoformat() == "2026-08-01" + assert next_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_current_period_bounds_december_rollover(): + now = datetime(2026, 12, 31, 23, 30, 0, tzinfo=ZoneInfo("Asia/Shanghai")) + period_month, next_month, _, _ = current_period_bounds(now) + assert period_month.isoformat() == "2026-12-01" + assert next_month.isoformat() == "2027-01-01" diff --git a/backend/tests/voucher_check/test_share_and_fingerprint.py b/backend/tests/voucher_check/test_share_and_fingerprint.py new file mode 100644 index 00000000..43ee3b13 --- /dev/null +++ b/backend/tests/voucher_check/test_share_and_fingerprint.py @@ -0,0 +1,106 @@ +""" +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 new file mode 100644 index 00000000..a0def318 --- /dev/null +++ b/backend/tests/voucher_check/test_tool_auth_and_openapi.py @@ -0,0 +1,52 @@ +""" +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/docker-compose.yml b/docker-compose.yml index 46c0c741..1c92d4e0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -57,6 +57,13 @@ 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} + - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} + - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} + - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} # 允许容器访问宿主机服务 (如数据库) extra_hosts: - "host.docker.internal:host-gateway" @@ -70,6 +77,9 @@ 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 networks: - ai-platform @@ -159,11 +169,20 @@ 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} + - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} + - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} + - VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-} extra_hosts: - "host.docker.internal:host-gateway" 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 networks: - ai-platform diff --git a/docs/demand.md b/docs/demand.md index 0469b05d..0704f112 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -74,7 +74,8 @@ - **核心目标**:按当前自然月从 HXJM 套账 ERP `apa_file` 取得发票号清单,检查共享盘对应发票目录中的必检文件是否存在,输出齐全/缺资料结果。 - **数据口径**:`apa08` 为发票号且唯一,`apa09` 为发票日期;只检核当前自然月,不追溯月末补录的上月发票;红冲、作废、取消票据一期不纳入。 - **目录口径**:共享盘默认采用 `vouche/{YYYY}/{MM}/{invoice_no}/`,目录模板可配置以支持后续调整。 -- **判定边界**:严格按可配置文件名判断存在性;不读取文件内容、不校验文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 +- **判定边界**:严格按可配置文件名判断存在性;暂定必检「核价单.pdf」「采购单.pdf」;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 +- **实现状态**:一期 HXOPS 引擎/API/工作台已落地;日批 `0 6 * * *`;**Dify Chatflow 编排待完成**。 - **可靠性要求**:共享盘不可用、Oracle 查询失败或配置错误时,整批失败并告警,不得把整批票标记为缺资料;单票缺目录/缺文件才记为缺资料。 - **通知要求**:缺资料按固定接收人发送企业微信通知,并按同票同日节流。 - 技术规格见 [docs/features/accounting-voucher-check/technical.md](features/accounting-voucher-check/technical.md)。 diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index 9e7064cd..534a5f33 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -3,15 +3,20 @@ | 文档 | 读者 | 路径 | | --- | --- | --- | | **需求与规格手册** | 产品、业务、测试 | [technical.md](technical.md) | -| **技术设计** | 研发、Dify、运维、测试 | [technical-design.md](technical-design.md) | +| **技术设计** | 研发、运维、测试 | [technical-design.md](technical-design.md) | +| **迁移与部署验收清单** | 研发、运维、测试 | [ops-checklist.md](ops-checklist.md) | +| **Dify Chatflow 编排草稿** | 研发、Dify | [dify-chatflow-draft.md](dify-chatflow-draft.md) | +| **查询 Tool OpenAPI** | Dify | 在线 `GET /api/accounting-voucher-check/tools/openapi.json`;静态 [../../openapi/accounting_voucher_check_tools_openapi.json](../../openapi/accounting_voucher_check_tools_openapi.json) | | **交互原型** | 产品、业务、测试 | [../../prototype/accounting-voucher-check-prototype.html](../../prototype/accounting-voucher-check-prototype.html) | | **原型速览** | 产品、测试 | [../../prototype/accounting-voucher-check-prototype.md](../../prototype/accounting-voucher-check-prototype.md) | **定位**:以企业 AI 工作台**对话为主入口**,**日批为主、会话可手动触发**。 -**要解决的问题**:审计/复核时按发票号**快速确认共享盘配套资料在不在**(核价叫、采购单等)。 +**要解决的问题**:审计/复核时按发票号**快速确认共享盘配套资料在不在**(核价单、采购单等)。 **检核内容**:只做必检材料**存在性 / 齐全性**;**不核对**金额、供应商等与 ERP 是否吻合。ERP **仅用于**取当月发票号清单。 **其它**:单票状态落 **HXOPS 库**(齐全且材料未变更可跳过);缺资料推企微 textcard;**不回写 ERP、不要求 ERP 终审**。 **实现规格(technical Part2)**:共享盘默认目录 `vouche/{YYYY}/{MM}/{invoice_no}/`,目录模板可配置;日批按 `apa09` 取**当前自然月发票清单**,仅处理 HXJM 套账,再按可配置文件名检查文件是否存在。文件内容不读取、不使用 LLM;共享盘不可用时整批失败并告警。ERP 已可连;凭据仅 env。 -**状态**:业务需求、实现规格与技术设计已整理;默认必检文件为“核价叫.pdf”和“采购单.pdf”,文件名仍由配置维护。进入研发前仍需确认 `apa42` 作废码的有效值,以及 ERP 红冲、取消的实际字段和值。 +**状态**:一期后端/工作台已落地实现;默认必检文件暂定为「核价单.pdf」和「采购单.pdf」,文件名仍由配置维护。日批预置 Cron `0 6 * * *`(Asia/Shanghai)。**Dify Chatflow 编排待完成**(见编排草稿)。本期暂不识别或过滤红冲、取消、作废场景。 + +**运维入口**:上线/验收请先走 [ops-checklist.md](ops-checklist.md)。 diff --git a/docs/features/accounting-voucher-check/dify-chatflow-draft.md b/docs/features/accounting-voucher-check/dify-chatflow-draft.md new file mode 100644 index 00000000..d9015899 --- /dev/null +++ b/docs/features/accounting-voucher-check/dify-chatflow-draft.md @@ -0,0 +1,196 @@ +# 立账凭证检核 — 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 new file mode 100644 index 00000000..9141466a --- /dev/null +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -0,0 +1,172 @@ +# 立账凭证检核 — 迁移与部署验收清单 + +> 适用环境:dev / test / prod +> 前置文档:[technical.md](technical.md) · [technical-design.md](technical-design.md) +> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通日批/手动触发并看到进度与记录。 + +## 0. 变更摘要(上线前确认) + +| 项 | 值 | +| --- | --- | +| Job key | `accounting-voucher-check` | +| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` | +| Cron | `0 6 * * *`(Asia/Shanghai) | +| 必检材料(暂定) | `核价单.pdf`、`采购单.pdf` | +| 迁移 revision | `a0b1c2d3e4f5` | +| 工作台入口 | `/workspace/accounting-voucher-check` | + +--- + +## 1. 数据库迁移 + +- [ ] 备份目标库(至少 `schedule_tasks` / 相关 schema) +- [ ] 后端目录执行: + +```bash +cd backend +# 激活对应环境 venv +flask db upgrade +``` + +- [ ] 确认表存在: + - `voucher_check_invoice_states` + - `voucher_check_run_items` +- [ ] 确认种子排程存在(有用户时): + +```sql +SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at + FROM schedule_tasks + WHERE schedule_no = 'SCH-ACCOUNTING-VOUCHER-CHECK' + OR platform_api_path = 'accounting-voucher-check'; +``` + +- [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建) +- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含必检材料 JSON + +--- + +## 2. 环境变量 + +写入 `.env.`(密码勿提交仓库): + +```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) +VOUCHER_CHECK_ERP_DSN=${ERP_DB_DSN} +VOUCHER_CHECK_ERP_USERNAME= +VOUCHER_CHECK_ERP_PASSWORD= +VOUCHER_CHECK_ERP_TIMEOUT_SECONDS=30 +``` + +检查: + +- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_*` +- [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中 + +--- + +## 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 * * *` +- [ ] `kb_sync_enabled=false`(本域不需要进知识库) +- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户 +- [ ] `job_params.required_files` 确认为核价单/采购单(或业务最终定稿) + +--- + +## 5. 功能冒烟 + +### 5.1 管理台手动跑一批(共享盘可用后) + +- [ ] 「立即执行」创建 `ScheduleRun` +- [ ] `response_summary_json.voucher_check` 含 `complete_count` / `missing_count` / `skipped_count` +- [ ] Excel 可下载,表头含发票号/结论/缺失材料 +- [ ] `failed_count` **不含**缺资料票(仅技术异常) + +### 5.2 增量跳过 + +- [ ] 第一次跑后,第二次对未变更齐全票:`skipped_count > 0` +- [ ] 强制语义(会话/Tool `mode=force_all`):跳过为 0 + +### 5.3 共享盘故障 + +- [ ] 临时移除健康标记或卸载挂载 +- [ ] 再跑:批次 `failed`,不产生批量 missing 状态覆盖 +- [ ] 企微失败告警到达(若开启) + +### 5.4 工作台记录页 + +- [ ] 打开 `/workspace/accounting-voucher-check` +- [ ] 可按月/状态/发票号筛选 +- [ ] 缺资料票的缺失材料列非空 + +### 5.5 Tool API(可用 curl / Postman) + +```bash +# 启动(增量)— 复用 file-check +POST /api/file-check/tools/tasks/run +{ "task_id": , "run_options": { "mode": "incremental" }, "hxops_turn_id": "..." } + +# 缺资料查询 +GET /api/accounting-voucher-check/tools/tasks//missing + +# 批次明细 +GET /api/accounting-voucher-check/tools/runs//items?result=missing +``` + +- [ ] 上述接口返回符合约定(Tool 非 envelope / 工作台 envelope) + +--- + +## 6. 回滚要点 + +- [ ] 代码回滚后:可 `flask db downgrade` 到上一 revision(会删本域两表 + 种子 `schedule_no`) +- [ ] **勿**在有生产检核数据时贸然 downgrade;优先停用任务 `enabled=false` +- [ ] 共享盘挂载可保留,不影响其它服务 + +--- + +## 7. 验收签字栏(可选) + +| 角色 | 确认项 | 签名/日期 | +| --- | --- | --- | +| 研发 | 迁移 + Job 注册 + 冒烟 | | +| 运维 | env + 挂载 + 双容器可读 | | +| 业务 | 必检文件名 + 通知接收人 | | +| 测试 | T1–T12 关键场景抽样 | | diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index fcd7b569..72f8589e 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -2,9 +2,9 @@ > 文档版本:v1.0 > 更新时间:2026-08-05 -> 状态:待研发评审 +> 状态:一期代码已落地;Dify Chatflow 编排仍待完成 > 需求基线:[technical.md](technical.md) -> 适用范围:一期后端、排程、Dify Tool、进度卡、企微通知与部署 +> 适用范围:一期后端、排程、Tool API、进度卡、工作台记录页、企微通知与部署 ## 1. 设计结论 @@ -157,9 +157,9 @@ VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=.hxops-share-ready "required_files": [ { "code": "price_check_sheet", - "name": "核价叫", + "name": "核价单", "required": true, - "accepted_filenames": ["核价叫.pdf"] + "accepted_filenames": ["核价单.pdf"] }, { "code": "purchase_order", @@ -194,7 +194,7 @@ Job key:`accounting-voucher-check`。 | --- | --- | --- | --- | | `scope_code` | `select` | 是 | `HXJM` | | `directory_template` | `text` | 是 | `{root}/{YYYY}/{MM}/{invoice_no}` | -| `required_files` | `json` | 是 | 核价叫.pdf、采购单.pdf 示例 | +| `required_files` | `json` | 是 | 核价单.pdf、采购单.pdf 示例 | | `filename_case_sensitive` | `boolean` | 是 | `true` | | `notify_missing_enabled` | `boolean` | 否 | `true` | | `notify_failure_enabled` | `boolean` | 否 | `true` | @@ -294,26 +294,12 @@ SELECT DISTINCT WHERE apa09 >= :period_start AND apa09 < :next_period_start AND TRIM(apa08) IS NOT NULL - /* 红冲、作废、取消过滤条件 */ ORDER BY TRUNC(apa09), TRIM(apa08) ``` -### 7.3 ERP 状态过滤上线门槛 +### 7.3 ERP 状态过滤 -根据 `apa_file` 字段说明,目前可以确认: - -- `apa42` 是“作废码”,可作为作废过滤字段,但具体哪些值代表“已作废”仍需 ERP 管理员确认。 -- `apa00` 是“帐款性质”,其中 `21` 表示“折让”;字段说明没有证明 `21` 就等同于红冲,因此不能直接作为红冲过滤条件。 -- 字段说明未识别出“取消”对应的字段和值,不能在 SQL 中臆测。 - -正式连接真实 ERP 前必须由业务/ERP 管理员确认: - -- `apa42` 的有效值、空值语义及作废判断条件。 -- 红冲实际使用的字段和值;确认是否为折让、冲销关联或其他业务状态。 -- 取消实际使用的字段和值。 -- 是否还需要 `apa00` 进货发票类型(例如 `11`)、`apalegal` 所属法人或其他 HXJM 范围字段过滤。 - -实现中 SQL 标识符必须写在代码的允许列表中,状态值使用绑定参数;不得从环境变量直接拼接任意 SQL。未确认生产过滤口径时,生产任务保持禁用。 +本期不识别、不区分、也不排除红冲、取消、作废等状态。只按 `apa09` 的当前自然月范围查询 `apa08` 发票号,并按既定 HXJM 账套范围取数。后续若业务需要增加状态过滤,应通过新增配置和经过评审的字段白名单实现,不能在 SQL 中拼接任意字段或值。 ### 7.4 Oracle 连接 @@ -368,7 +354,7 @@ SELECT DISTINCT ```json { "code": "price_check_sheet", - "accepted_filenames": ["核价叫.pdf", "核价叫.PDF"] + "accepted_filenames": ["核价单.pdf", "核价单.PDF"] } ``` @@ -715,14 +701,13 @@ docker exec hxops-schedule-worker test -f /mnt/hxops-voucher-check-test/.hxops-s - backend 与 schedule-worker 均可访问共享盘。 - Oracle Client 和 HXJM 只读连接可用。 -- Cron 在 `Asia/Shanghai` 每日 09:00 触发。 +- Cron 在 `Asia/Shanghai` 每日 06:00 触发。 - 共享盘断开后批次失败且不产生批量缺件。 - 缺资料通知发送到固定接收人并同日去重。 ## 18. 实施顺序 -1. 确认 ERP `apa42` 作废码,以及红冲/取消状态字段和值。 -2. 新增模型与 Alembic 迁移。 +1. 新增模型与 Alembic 迁移。 3. 实现配置、Oracle Repository、扫描器和指纹。 4. 实现两阶段 runner 与平台 Job 注册。 5. 扩展通用启动 Tool 的 `run_options` 透传。 @@ -734,14 +719,19 @@ docker exec hxops-schedule-worker test -f /mnt/hxops-voucher-check-test/.hxops-s ## 19. 研发评审检查点 -- [ ] ERP `apa42` 作废码的有效值已确认。 -- [ ] ERP 红冲、取消对应字段和值已确认;未将 `apa00=21` 未经确认地当作红冲。 -- [ ] 必检材料及完整候选文件名已确认。 -- [ ] 共享根健康标记方案已由运维接受。 -- [ ] 缺资料业务结果不进入技术失败计数。 -- [ ] 共享盘不可用不会写单票 missing。 -- [ ] 两阶段事务保证批次级失败不污染最新状态。 -- [ ] backend 和 schedule-worker 均完成只读挂载。 -- [ ] 新表已配套 Alembic 迁移。 -- [ ] 新错误码和进度文案已补齐四语言。 -- [ ] 财务文件内容不会进入日志、MinIO、Dify 或知识库。 +- [ ] 本期 SQL 未增加红冲、取消、作废状态过滤;后续扩展须通过评审后的配置和字段白名单实现。 +- [x] 必检材料暂定「核价单.pdf」「采购单.pdf」(可配置)。 +- [ ] 共享根健康标记方案已由运维接受(当前共享盘尚未挂载)。 +- [x] 缺资料业务结果不进入技术失败计数。 +- [x] 共享盘不可用不会写单票 missing。 +- [x] 两阶段事务保证批次级失败不污染最新状态。 +- [x] backend 和 schedule-worker Compose 已增加只读挂载位(宿主机需完成 CIFS)。 +- [x] 新表已配套 Alembic 迁移。 +- [x] 新错误码和进度文案已补齐四语言。 +- [x] 财务文件内容不会进入日志、MinIO、Dify 或知识库。 + +## 20. 待完成 + +- [ ] **Dify Chatflow 编排**:见草稿 [dify-chatflow-draft.md](dify-chatflow-draft.md);意图映射到 Tool 后改状态为已落地。 +- [ ] 运维完成共享盘 CIFS → `VOUCHER_CHECK_LOCAL_ROOT`,并放置 `.hxops-share-ready`(验收清单 [ops-checklist.md](ops-checklist.md))。 +- [ ] 配置 `VOUCHER_CHECK_ERP_*` 与排程接收人 `notify_user_ids_json`。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index 33ea712a..53f64abd 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -269,7 +269,7 @@ flowchart TB | --- | --- | | 日批默认范围 | **每日检核 ERP 当前自然月全部立账凭证**;跨月后自动切换到新自然月,不追溯补录上月 | | 队列来源 | ERP `apa_file`:`apa08`=发票编号,`apa09`=发票日期;按 `apa09` 取当前自然月;仅处理 HXJM 套账 | -| 排除范围 | 红冲、作废、取消发票本期不纳入检核;具体过滤字段/条件在实现规格中配置 | +| 排除范围 | 本期不按红冲、作废、取消做额外过滤;符合当前自然月和 HXJM 范围的 ERP 发票记录全部纳入检核 | | 材料来源 | 共享根 `\\192.168.100.230\ai_file\vouche`;默认月目录模板 `{root}/{YYYY}/{MM}/{invoice_no}/`,模板可配置 | | 会话默认「今日检核」 | 与日批同一范围、同一增量引擎 | | 非默认范围 | 仅通过「指定发票」或后续扩展话术覆盖;一期不提供任意自定义 SQL 筛月 | @@ -348,9 +348,9 @@ flowchart TD | 占位项 | 默认值 | 状态 | | --- | --- | --- | -| 日批时间 | 每日 09:00 | 可配置 | +| 日批时间 | 每日 06:00(Asia/Shanghai) | 可配置 | | 范围 | 当月立账凭证 | **已钉死** | -| 必检材料 | 按文件名配置;默认包含核价叫、采购单,发票扫描件是否必检由配置决定 | 文件名可修改,不读内容 | +| 必检材料 | 按文件名配置;暂定「核价单.pdf」「采购单.pdf」,发票扫描件是否必检由配置决定 | 文件名可修改,不读内容 | | ERP 用途 | 仅取当前自然月**发票号清单** | HXJM 套账;表 `apa_file`(`apa08`/`apa09`);不做字段吻合 | | 结论枚举 | 齐全 / 缺资料 / 跳过;批次另有失败态 | 共享盘不可用为整批失败,不转为缺资料 | | 目录模板 | `{root}/{YYYY}/{MM}/{invoice_no}/` | 模板配置,后续可调整 | @@ -409,15 +409,15 @@ flowchart TD - 目录默认采用 `vouche/{YYYY}/{MM}/{invoice_no}/`,并通过目录模板配置支持后续调整。 - 发票号字段唯一;一期只处理 HXJM 套账。 - 只判断配置文件名是否存在,不读取文件内容,不使用 LLM 参与判定。 -- 红冲、作废、取消发票一期不纳入检核。 +- 红冲、作废、取消本期暂不单独识别或过滤;后续如需排除,再补充 ERP 字段和值配置。 - 月末补录不追溯处理,只检核当前自然月。 - 共享盘不可用时整批失败并告警,不生成缺资料结论。 - 企微先发送给固定接收人。 -#### 6.3 第二部分预留 +#### 6.3 第二部分预留 / 待完成 -正式开发启动后,于本文续写:Dify 编排、Tool API、单票状态表迁移、验证排错。 -环境变量与共享盘挂载见 **[第二部分:实现规格](#第二部分实现规格)**。 +- **Dify Chatflow 编排待完成**:HXOPS Tool/API(启动复用 file-check `run` + `run_options`,缺资料/明细查询走 `/api/accounting-voucher-check/tools/*`)已就绪;Chatflow 意图映射与正式部署手册另开。 +- 环境变量与共享盘挂载见 **[第二部分:实现规格](#第二部分实现规格)** 与 [technical-design.md](technical-design.md) §16。 #### 6.4 本期明确不做 @@ -461,8 +461,8 @@ VOUCHER_CHECK_ERP_USERNAME=hxjm VOUCHER_CHECK_ERP_PASSWORD=******** VOUCHER_CHECK_ERP_SCOPE=HXJM -VOUCHER_CHECK_REQUIRED_FILES_JSON=[{"code":"price_check","name":"核价叫","accepted_filenames":["核价叫.pdf"]},{"code":"purchase_order","name":"采购单","accepted_filenames":["采购单.pdf"]}] -VOUCHER_CHECK_NOTIFY_RECIPIENTS= +VOUCHER_CHECK_REQUIRED_FILES_JSON=[{"code":"price_check_sheet","name":"核价单","accepted_filenames":["核价单.pdf"]},{"code":"purchase_order","name":"采购单","accepted_filenames":["采购单.pdf"]}] +# 缺资料接收人走 ScheduleTask.notify_user_ids_json(管理后台配置) ``` Linux/Docker **必须**配 `LOCAL_ROOT`(对齐固资履历);开发机可临时用 UNC。 @@ -473,7 +473,8 @@ Linux/Docker **必须**配 `LOCAL_ROOT`(对齐固资履历);开发机可 ```text vouche/{YYYY}/{MM}/{invoice_no}/ - 核价叫.pdf + 核价单.pdf + 采购单.pdf (其它必检文件按配置) ``` @@ -504,7 +505,6 @@ SELECT DISTINCT TRIM(apa08) AS invoice_no, WHERE apa09 >= :period_start AND apa09 < :next_period_start AND TRIM(apa08) IS NOT NULL - -- 作废使用 apa42;具体值及红冲/取消过滤条件按 ERP 状态口径补充 ``` 连接:`oracledb` + Instant Client(同 Text2SQL/固资)。账号走 `VOUCHER_CHECK_ERP_*`。 diff --git a/docs/funclist.md b/docs/funclist.md index 08277a16..f1beb410 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -110,8 +110,11 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | 需求、规格与技术设计 | 已文档化 | [需求规格](features/accounting-voucher-check/technical.md) · [技术设计](features/accounting-voucher-check/technical-design.md);当前自然月从 ERP `apa_file` 取 `apa08`/`apa09`,仅处理 HXJM 套账 | -| 共享盘文件存在性检核 | 待开发 | 默认扫描 `vouche/{YYYY}/{MM}/{invoice_no}/`,按可配置文件名判断存在性,不读取文件内容、不使用 LLM | -| 增量批次与异常告警 | 待开发 | 齐全且目录元数据未变更可跳过;共享盘不可用时整批失败并告警,不生成缺资料结论 | +| 共享盘文件存在性检核 | 已实现 | 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 意图映射与部署手册另开 | ### 采购合同审查 diff --git a/docs/openapi/accounting_voucher_check_tools_openapi.json b/docs/openapi/accounting_voucher_check_tools_openapi.json new file mode 100644 index 00000000..67a7eea2 --- /dev/null +++ b/docs/openapi/accounting_voucher_check_tools_openapi.json @@ -0,0 +1,518 @@ +{ + "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/openapi/file_check_tools_openapi.json b/docs/openapi/file_check_tools_openapi.json index a176c6f2..9a03b288 100644 --- a/docs/openapi/file_check_tools_openapi.json +++ b/docs/openapi/file_check_tools_openapi.json @@ -7,7 +7,7 @@ }, "servers": [ { - "url": "http://192.168.100.192:8890", + "url": "http://127.0.0.1:5052", "description": "HXOPS_TOOLS_API_BASE" } ], @@ -560,12 +560,48 @@ "type": "string", "nullable": true, "description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入" + }, + "mode": { + "type": "string", + "nullable": true, + "enum": [ + "incremental", + "force_all", + "single" + ], + "description": "【Dify 推荐】运行模式(立账凭证检核读取;文件检核忽略)。incremental=增量 / force_all=全量 / single=单发票;单发票时须同时填 invoice_no" + }, + "invoice_no": { + "type": "string", + "nullable": true, + "description": "【Dify 推荐】mode=single 时必填的发票号;来自意图识别.invoice_no" + }, + "run_options": { + "type": "object", + "nullable": true, + "description": "可选嵌套写法(部分 Dify 版本不展示对象字段;优先用顶层 mode/invoice_no)。mode=incremental|force_all|single;single 时须带 invoice_no", + "properties": { + "mode": { + "type": "string", + "enum": [ + "incremental", + "force_all", + "single" + ], + "default": "incremental" + }, + "invoice_no": { + "type": "string", + "nullable": true, + "description": "mode=single 时必填的发票号" + } + } } }, "required": [ "task_id" ], - "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底" + "description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);立账凭证检核用顶层 mode/invoice_no(Dify 友好)或嵌套 run_options" }, "RunCheckSuccessResponse": { "type": "object", @@ -891,6 +927,21 @@ } } } + }, + "DataSourceUnavailable": { + "description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "example": { + "ok": false, + "error_code": "data_source_unavailable", + "message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动" + } + } + } } } } diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index f4cb5254..4d8a9ac4 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -55,6 +55,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: () => import('@/features/workspace/pages/ShippingNoticePage.vue'), meta: { title: 'workspace.nav.shippingNotice' }, }, + { + path: 'accounting-voucher-check', + name: 'workspace-accounting-voucher-check', + component: () => import('@/features/workspace/pages/AccountingVoucherCheckPage.vue'), + meta: { title: 'workspace.nav.accountingVoucherCheck' }, + }, { path: 'feedback', name: 'workspace-feedback', diff --git a/frontend/src/features/chat/components/ToolRunProgressCard.vue b/frontend/src/features/chat/components/ToolRunProgressCard.vue index ae5cb9ca..58c5e717 100644 --- a/frontend/src/features/chat/components/ToolRunProgressCard.vue +++ b/frontend/src/features/chat/components/ToolRunProgressCard.vue @@ -1,11 +1,11 @@ + + diff --git a/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue b/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue new file mode 100644 index 00000000..dfa5bf2e --- /dev/null +++ b/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue @@ -0,0 +1,255 @@ + + + diff --git a/frontend/src/locales/en/admin.json b/frontend/src/locales/en/admin.json index 8cbb2fa4..0e311775 100644 --- a/frontend/src/locales/en/admin.json +++ b/frontend/src/locales/en/admin.json @@ -1274,7 +1274,17 @@ "agentOptionId": " (ID: {id})", "difySystemPrompt": "Dify System Prompt", "difySystemPromptHint": "Available when a Dify Agent is enabled. Saved as system_prompt in the Workflow; LLM nodes must reference this variable.", - "difySystemPromptPlaceholder": "e.g. You are a material compliance assistant. Based on record test data, return JSON with dify_result (pass/fail/manual review) and dify_message." + "difySystemPromptPlaceholder": "e.g. You are a material compliance assistant. Based on record test data, return JSON with dify_result (pass/fail/manual review) and dify_message.", + "platformJobAccountingVoucherCheck": "Accounting voucher check", + "accountingVoucherCheckHint": "Fetch the current-month ERP invoice list and scan the share for required filenames (no file content reading).", + "voucherCheckScope": "Ledger scope", + "voucherCheckDirTemplate": "Directory template", + "voucherCheckDirTemplateHelp": "Only {root}/{YYYY}/{MM}/{invoice_no} placeholders are allowed", + "voucherCheckRequiredFiles": "Required materials", + "voucherCheckCaseSensitive": "Case-sensitive filenames", + "voucherCheckNotifyMissing": "Notify on missing materials", + "voucherCheckNotifyFailure": "Failure alert", + "voucherCheckSameDayDedup": "Same-invoice same-day dedup" }, "testRun": { "title": "Test run — {name}", diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 519021c3..4c608242 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -1407,5 +1407,12 @@ "tableHeaderSystem": "System field", "tableHeaderInventory": "Inventory column", "hints": "Notes:" + }, + "voucherCheck": { + "total": "Month total", + "scanned": "To scan", + "skipped": "Skipped", + "complete": "Complete", + "missing": "Missing" } } diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index 59d65ced..1545b4e8 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -69,6 +69,14 @@ "SHIPPING_NOTICE_REVISION_TARGET_INVALID": "The revision target task is invalid.", "SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "A later revision of this task already exists.", "SHIPPING_NOTICE_REVISION_CONFLICT": "A revision of this task already exists. Open the existing revision or re-check.", - "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "A reliable business fingerprint could not be generated; only file-hash dedupe applies." + "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "A reliable business fingerprint could not be generated; only file-hash dedupe applies.", + "VOUCHER_CHECK_CONFIG_INVALID": "Accounting voucher check configuration is invalid.", + "VOUCHER_CHECK_INVOICE_REQUIRED": "Invoice number is required.", + "VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "The invoice is not in the current-month ERP set.", + "VOUCHER_CHECK_INVOICE_PATH_INVALID": "Invoice number contains illegal path characters.", + "VOUCHER_CHECK_SHARE_UNAVAILABLE": "Shared folder is unavailable. Check the mount and health marker.", + "VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP (Oracle) is unavailable. Please try again later.", + "VOUCHER_CHECK_RUN_NOT_FOUND": "Voucher check run or invoice state was not found.", + "VOUCHER_CHECK_PERSIST_FAILED": "Failed to persist voucher check results." } } diff --git a/frontend/src/locales/en/workspace.json b/frontend/src/locales/en/workspace.json index 040db2b2..8cfe0837 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -104,7 +104,8 @@ "updates": "Recent Updates", "backToChat": "Back to Chat", "backShort": "Back", - "logout": "Logout" + "logout": "Logout", + "accountingVoucherCheck": "Voucher Check" }, "kb": { "accessDenied": "Administrator access is required to open the knowledge base." @@ -274,5 +275,32 @@ "casdoorNotMatchedContactAdmin": "Casdoor login succeeded, but no local account matched. Please contact the administrator.", "casdoorNotMatchedNeedLocalUser": "Casdoor login succeeded, but no local account matched. Ask the administrator to create a local user with the same username or email.", "localAccountDisabled": "This local account is disabled. Please contact the administrator." + }, + "voucherCheck": { + "title": "Accounting Voucher Check Records", + "subtitle": "View completeness of required voucher materials for the current calendar month. Existence check only — no amount or supplier matching.", + "period": "Period", + "status": "Status", + "statusAll": "All", + "statusComplete": "Complete", + "statusMissing": "Missing", + "statusSkipped": "Skipped", + "statusTechError": "Technical error", + "invoiceNo": "Invoice No.", + "invoiceDate": "Invoice Date", + "invoicePlaceholder": "Filter by invoice number", + "folder": "Share path", + "missing": "Missing materials", + "checkedAt": "Checked at", + "result": "Result", + "search": "Search", + "refresh": "Refresh", + "loading": "Loading…", + "empty": "No check records yet", + "loadFailed": "Failed to load voucher check records", + "totalCount": "{total} records", + "prevPage": "Previous", + "nextPage": "Next", + "runItemsTitle": "Run {runId} details" } } diff --git a/frontend/src/locales/th/admin.json b/frontend/src/locales/th/admin.json index 067a6eb7..5a0c54cd 100644 --- a/frontend/src/locales/th/admin.json +++ b/frontend/src/locales/th/admin.json @@ -1153,7 +1153,17 @@ "agentOptionId": " (ID: {id})", "difySystemPrompt": "Dify System Prompt", "difySystemPromptHint": "ใช้ได้เมื่อเปิดใช้ Dify Agent จะบันทึกเป็น system_prompt ใน Workflow; โหนด LLM ต้องอ้างอิงตัวแปรนี้", - "difySystemPromptPlaceholder": "เช่น คุณเป็นผู้ช่วยตรวจสอบความสอดคล้องของวัสดุ จากข้อมูล record ให้คืน JSON: dify_result (ผ่าน/ไม่ผ่าน/ตรวจด้วยมือ) และ dify_message" + "difySystemPromptPlaceholder": "เช่น คุณเป็นผู้ช่วยตรวจสอบความสอดคล้องของวัสดุ จากข้อมูล record ให้คืน JSON: dify_result (ผ่าน/ไม่ผ่าน/ตรวจด้วยมือ) และ dify_message", + "platformJobAccountingVoucherCheck": "ตรวจสอบเอกสารบัญชี", + "accountingVoucherCheckHint": "ดึงรายการใบแจ้งหนี้ ERP ของเดือนปัจจุบัน และสแกนไฟล์ที่ต้องมีบนแชร์ (ไม่อ่านเนื้อหาไฟล์)", + "voucherCheckScope": "ชุดบัญชี", + "voucherCheckDirTemplate": "เทมเพลตโฟลเดอร์", + "voucherCheckDirTemplateHelp": "อนุญาตเฉพาะ {root}/{YYYY}/{MM}/{invoice_no}", + "voucherCheckRequiredFiles": "เอกสารที่ต้องมี", + "voucherCheckCaseSensitive": "แยกตัวพิมพ์เล็ก/ใหญ่ในชื่อไฟล์", + "voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร", + "voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว", + "voucherCheckSameDayDedup": "ไม่แจ้งซ้ำใบเดียวกันในวันเดียวกัน" }, "status": { "all": "ทุกสถานะ", diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index 2e6e9840..2da0c573 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -1407,5 +1407,12 @@ "tableHeaderSystem": "ฟิลด์ระบบ", "tableHeaderInventory": "คอลัมน์สต็อก", "hints": "หมายเหตุ:" + }, + "voucherCheck": { + "total": "ทั้งหมดเดือนนี้", + "scanned": "รอดตรวจ", + "skipped": "ข้าม", + "complete": "ครบ", + "missing": "ขาดเอกสาร" } } diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index 0c44df23..1a15ff6e 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -69,6 +69,14 @@ "SHIPPING_NOTICE_REVISION_TARGET_INVALID": "งานเป้าหมายสำหรับการแก้ไขไม่ถูกต้อง", "SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "งานนี้มีเวอร์ชันแก้ไขถัดไปอยู่แล้ว", "SHIPPING_NOTICE_REVISION_CONFLICT": "งานเป้าหมายมีเวอร์ชันแก้ไขอยู่แล้ว กรุณาเปิดเวอร์ชันที่มีหรือตรวจสอบใหม่", - "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "สร้างลายนิ้วมือทางธุรกิจที่เชื่อถือได้ไม่ได้ จะใช้การตัดรายการซ้ำด้วยแฮชไฟล์เท่านั้น" + "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "สร้างลายนิ้วมือทางธุรกิจที่เชื่อถือได้ไม่ได้ จะใช้การตัดรายการซ้ำด้วยแฮชไฟล์เท่านั้น", + "VOUCHER_CHECK_CONFIG_INVALID": "การตั้งค่าการตรวจสอบเอกสารบัญชีไม่ถูกต้อง", + "VOUCHER_CHECK_INVOICE_REQUIRED": "ต้องระบุเลขที่ใบแจ้งหนี้", + "VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "ใบแจ้งหนี้ไม่อยู่ในชุด ERP ของเดือนปัจจุบัน", + "VOUCHER_CHECK_INVOICE_PATH_INVALID": "เลขที่ใบแจ้งหนี้มีอักขระเส้นทางที่ไม่ถูกต้อง", + "VOUCHER_CHECK_SHARE_UNAVAILABLE": "โฟลเดอร์แชร์ใช้ไม่ได้ โปรดตรวจสอบการเมานต์และไฟล์สุขภาพ", + "VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP (Oracle) ใช้ไม่ได้ โปรดลองใหม่ภายหลัง", + "VOUCHER_CHECK_RUN_NOT_FOUND": "ไม่พบรอบการตรวจหรือสถานะใบแจ้งหนี้", + "VOUCHER_CHECK_PERSIST_FAILED": "บันทึกผลการตรวจไม่สำเร็จ" } } diff --git a/frontend/src/locales/th/workspace.json b/frontend/src/locales/th/workspace.json index d343a1d1..a62e331e 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -100,7 +100,8 @@ "updates": "อัปเดตล่าสุด", "backToChat": "กลับไปแชท", "backShort": "กลับ", - "logout": "ออกจากระบบ" + "logout": "ออกจากระบบ", + "accountingVoucherCheck": "ตรวจเอกสารบัญชี" }, "kb": { "accessDenied": "ต้องมีสิทธิ์ผู้ดูแลระบบจึงจะเข้าถึงคลังความรู้ได้" @@ -211,5 +212,32 @@ "upload_failed": "อัปโหลดไปยังระบบขนส่งไม่สำเร็จ", "backend_orchestrator_task_finished": "งานเบื้องหลังเสร็จแล้ว" } + }, + "voucherCheck": { + "title": "บันทึกตรวจสอบเอกสารบัญชี", + "subtitle": "ดูสถานะครบ/ขาดเอกสารใบแจ้งหนี้ของเดือนปฏิทินปัจจุบัน ตรวจสอบเฉพาะการมีอยู่ของไฟล์ ไม่เทียบยอดหรือผู้ขาย", + "period": "เดือนที่ตรวจ", + "status": "สถานะ", + "statusAll": "ทั้งหมด", + "statusComplete": "ครบ", + "statusMissing": "ขาดเอกสาร", + "statusSkipped": "ข้าม", + "statusTechError": "ข้อผิดพลาดทางเทคนิค", + "invoiceNo": "เลขที่ใบแจ้งหนี้", + "invoiceDate": "วันที่ใบแจ้งหนี้", + "invoicePlaceholder": "กรองด้วยเลขที่ใบแจ้งหนี้", + "folder": "เส้นทางแชร์", + "missing": "เอกสารที่ขาด", + "checkedAt": "เวลาที่ตรวจ", + "result": "ผลลัพธ์", + "search": "ค้นหา", + "refresh": "รีเฟรช", + "loading": "กำลังโหลด…", + "empty": "ยังไม่มีบันทึกการตรวจ", + "loadFailed": "โหลดบันทึกตรวจสอบไม่สำเร็จ", + "totalCount": "ทั้งหมด {total} รายการ", + "prevPage": "ก่อนหน้า", + "nextPage": "ถัดไป", + "runItemsTitle": "รายละเอียดรอบ {runId}" } } diff --git a/frontend/src/locales/zh-CN/admin.json b/frontend/src/locales/zh-CN/admin.json index 33a8e9c5..663f4d5f 100644 --- a/frontend/src/locales/zh-CN/admin.json +++ b/frontend/src/locales/zh-CN/admin.json @@ -1253,7 +1253,17 @@ "agentOptionId": "(ID: {id})", "difySystemPrompt": "Dify System Prompt", "difySystemPromptHint": "仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。", - "difySystemPromptPlaceholder": "例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。" + "difySystemPromptPlaceholder": "例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。", + "platformJobAccountingVoucherCheck": "立账凭证检核", + "accountingVoucherCheckHint": "按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。", + "voucherCheckScope": "账套", + "voucherCheckDirTemplate": "目录模板", + "voucherCheckDirTemplateHelp": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}", + "voucherCheckRequiredFiles": "必检材料", + "voucherCheckCaseSensitive": "文件名区分大小写", + "voucherCheckNotifyMissing": "缺资料通知", + "voucherCheckNotifyFailure": "失败告警", + "voucherCheckSameDayDedup": "同票同日去重" }, "testRun": { "title": "测试执行 — {name}", diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index ff4fa259..55ecaab3 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -1407,5 +1407,12 @@ "tableHeaderSystem": "系统字段", "tableHeaderInventory": "库存列", "hints": "提示:" + }, + "voucherCheck": { + "total": "当月总数", + "scanned": "本次待检", + "skipped": "跳过", + "complete": "齐全", + "missing": "缺资料" } } diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index e0523325..1195005c 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -69,6 +69,14 @@ "SHIPPING_NOTICE_REVISION_TARGET_INVALID": "修订目标任务无效。", "SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "该任务已有后续修订版本。", "SHIPPING_NOTICE_REVISION_CONFLICT": "目标任务已有修订版本,请打开已有修订或重新检测。", - "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "无法生成可靠业务指纹,将仅按文件去重。" + "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "无法生成可靠业务指纹,将仅按文件去重。", + "VOUCHER_CHECK_CONFIG_INVALID": "立账凭证检核配置无效。", + "VOUCHER_CHECK_INVOICE_REQUIRED": "请提供发票号。", + "VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定发票不在当前月 ERP 集合中。", + "VOUCHER_CHECK_INVOICE_PATH_INVALID": "发票号含非法路径字符。", + "VOUCHER_CHECK_SHARE_UNAVAILABLE": "共享盘不可用,请检查挂载与健康标记。", + "VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP(Oracle)不可用,请稍后重试。", + "VOUCHER_CHECK_RUN_NOT_FOUND": "检核批次或发票状态不存在。", + "VOUCHER_CHECK_PERSIST_FAILED": "检核结果落库失败。" } } diff --git a/frontend/src/locales/zh-CN/workspace.json b/frontend/src/locales/zh-CN/workspace.json index fe2d61aa..bd581435 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -104,7 +104,8 @@ "updates": "最近更新", "backToChat": "返回聊天", "backShort": "返", - "logout": "退出登录" + "logout": "退出登录", + "accountingVoucherCheck": "立账凭证" }, "kb": { "accessDenied": "需要管理员权限才能访问知识库。" @@ -274,5 +275,32 @@ "casdoorNotMatchedContactAdmin": "Casdoor 登录成功,但未匹配到本地账号,请联系管理员。", "casdoorNotMatchedNeedLocalUser": "Casdoor 登录成功,但未匹配到本地账号。请让管理员在本地用户表创建同名 username 或相同 email 的账号。", "localAccountDisabled": "该本地账号已被禁用,请联系管理员启用后再登录。" + }, + "voucherCheck": { + "title": "立账凭证检核记录", + "subtitle": "按当前自然月查看发票材料齐全/缺资料状态;只判文件是否存在,不核对金额与供应商。", + "period": "检核月份", + "status": "状态", + "statusAll": "全部", + "statusComplete": "齐全", + "statusMissing": "缺资料", + "statusSkipped": "跳过", + "statusTechError": "技术异常", + "invoiceNo": "发票号", + "invoiceDate": "发票日期", + "invoicePlaceholder": "输入发票号筛选", + "folder": "共享盘路径", + "missing": "缺失材料", + "checkedAt": "检核时间", + "result": "结论", + "search": "查询", + "refresh": "刷新", + "loading": "加载中…", + "empty": "暂无检核记录", + "loadFailed": "加载检核记录失败", + "totalCount": "共 {total} 条", + "prevPage": "上一页", + "nextPage": "下一页", + "runItemsTitle": "批次 {runId} 明细" } } diff --git a/frontend/src/locales/zh-TW/admin.json b/frontend/src/locales/zh-TW/admin.json index 76583a3e..3caf4846 100644 --- a/frontend/src/locales/zh-TW/admin.json +++ b/frontend/src/locales/zh-TW/admin.json @@ -1153,7 +1153,17 @@ "agentOptionId": "(ID: {id})", "difySystemPrompt": "Dify System Prompt", "difySystemPromptHint": "僅在啟用 Dify Agent 時可配置。保存後將作為 system_prompt 傳入 Workflow;編排中 LLM 節點需引用該變數。", - "difySystemPromptPlaceholder": "例如:你是物料合規判定助手。根據 record 中的檢測資料判定是否合格,僅返回 JSON:dify_result(合格/不合格/人工判定)與 dify_message。" + "difySystemPromptPlaceholder": "例如:你是物料合規判定助手。根據 record 中的檢測資料判定是否合格,僅返回 JSON:dify_result(合格/不合格/人工判定)與 dify_message。", + "platformJobAccountingVoucherCheck": "立帳憑證檢核", + "accountingVoucherCheckHint": "依當前自然月拉取 ERP 發票清單,掃描共用磁碟必檢材料是否存在(不讀檔案內容)。", + "voucherCheckScope": "帳套", + "voucherCheckDirTemplate": "目錄範本", + "voucherCheckDirTemplateHelp": "僅允許 {root}/{YYYY}/{MM}/{invoice_no}", + "voucherCheckRequiredFiles": "必檢材料", + "voucherCheckCaseSensitive": "檔名區分大小寫", + "voucherCheckNotifyMissing": "缺資料通知", + "voucherCheckNotifyFailure": "失敗告警", + "voucherCheckSameDayDedup": "同票同日去重" }, "status": { "all": "全部狀態", diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index 1edafe09..f3f62fea 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -1407,5 +1407,12 @@ "tableHeaderSystem": "系統欄位", "tableHeaderInventory": "庫存欄", "hints": "提示:" + }, + "voucherCheck": { + "total": "當月總數", + "scanned": "本次待檢", + "skipped": "跳過", + "complete": "齊全", + "missing": "缺資料" } } diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index 904b0512..e9101460 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -69,6 +69,14 @@ "SHIPPING_NOTICE_REVISION_TARGET_INVALID": "修訂目標任務無效。", "SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "該任務已有後續修訂版本。", "SHIPPING_NOTICE_REVISION_CONFLICT": "目標任務已有修訂版本,請打開已有修訂或重新檢測。", - "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "無法產生可靠業務指紋,將僅按檔案去重。" + "SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "無法產生可靠業務指紋,將僅按檔案去重。", + "VOUCHER_CHECK_CONFIG_INVALID": "立帳憑證檢核設定無效。", + "VOUCHER_CHECK_INVOICE_REQUIRED": "請提供發票號。", + "VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定發票不在當前月 ERP 集合中。", + "VOUCHER_CHECK_INVOICE_PATH_INVALID": "發票號含非法路徑字元。", + "VOUCHER_CHECK_SHARE_UNAVAILABLE": "共用磁碟不可用,請檢查掛載與健康標記。", + "VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP(Oracle)不可用,請稍後重試。", + "VOUCHER_CHECK_RUN_NOT_FOUND": "檢核批次或發票狀態不存在。", + "VOUCHER_CHECK_PERSIST_FAILED": "檢核結果寫入失敗。" } } diff --git a/frontend/src/locales/zh-TW/workspace.json b/frontend/src/locales/zh-TW/workspace.json index ace7f781..3971b891 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -104,7 +104,8 @@ "updates": "最近更新", "backToChat": "返回聊天", "backShort": "返", - "logout": "退出登錄" + "logout": "退出登錄", + "accountingVoucherCheck": "立帳憑證" }, "kb": { "accessDenied": "需要管理員權限才能存取知識庫。" @@ -274,5 +275,32 @@ "casdoorNotMatchedContactAdmin": "Casdoor 登錄成功,但未匹配到本地賬號,請聯繫管理員。", "casdoorNotMatchedNeedLocalUser": "Casdoor 登錄成功,但未匹配到本地賬號。請讓管理員在本地用戶表建立同名 username 或相同 email 的賬號。", "localAccountDisabled": "該本地賬號已被禁用,請聯繫管理員啟用後再登錄。" + }, + "voucherCheck": { + "title": "立帳憑證檢核紀錄", + "subtitle": "依當前自然月查看發票材料齊全/缺資料狀態;只判斷檔案是否存在,不核對金額與供應商。", + "period": "檢核月份", + "status": "狀態", + "statusAll": "全部", + "statusComplete": "齊全", + "statusMissing": "缺資料", + "statusSkipped": "跳過", + "statusTechError": "技術異常", + "invoiceNo": "發票號", + "invoiceDate": "發票日期", + "invoicePlaceholder": "輸入發票號篩選", + "folder": "共用磁碟路徑", + "missing": "缺失材料", + "checkedAt": "檢核時間", + "result": "結論", + "search": "查詢", + "refresh": "重新整理", + "loading": "載入中…", + "empty": "暫無檢核紀錄", + "loadFailed": "載入檢核紀錄失敗", + "totalCount": "共 {total} 筆", + "prevPage": "上一頁", + "nextPage": "下一頁", + "runItemsTitle": "批次 {runId} 明細" } }