From f615e56bb940b273e5e1b0655472ae50f4dfd0b8 Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 5 Aug 2026 14:49:59 +0800 Subject: [PATCH 1/3] =?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} 明細" } } From 59ff2dd9c731af747c1fc5f2abf4c79c8e57a209 Mon Sep 17 00:00:00 2001 From: "HTEWJ\\26070045" <2815434552@qq.com> Date: Thu, 6 Aug 2026 17:07:31 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(platform):=20=E6=B1=87=E6=80=BB?= =?UTF-8?q?=E7=9F=A5=E8=AF=86=E5=BA=93=E9=97=AE=E7=AD=94=E4=B8=8E=E5=9B=BE?= =?UTF-8?q?=E8=A1=A8=E5=B1=95=E7=A4=BA=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.shared | 3 +- backend/app/api/chat.py | 2361 +++++++++++++++++ backend/app/api/integration.py | 121 +- backend/app/services/dify.py | 49 + backend/app/services/hr_leave_sqlserver.py | 21 +- backend/app/services/integration_api.py | 52 +- .../knowledge_cleaning/dify_sync_service.py | 227 +- .../knowledge_cleaning/settings_service.py | 10 +- .../app/services/knowledge_cleaning/tasks.py | 3 + backend/edkb_system/controller.py | 18 + backend/tests/test_dify_sync_process_rule.py | 76 +- backend/tests/test_dify_token_usage.py | 10 + backend/tests/test_edkb_file_timeout.py | 8 + backend/tests/test_file_check_tools.py | 2 +- .../tests/test_hr_leave_sqlserver_support.py | 7 + .../tests/test_integration_source_fallback.py | 127 + backend/tests/test_kb_migration_flow.py | 8 +- docker-compose.yml | 12 + docs/demand.md | 1 + docs/funclist.md | 8 + docs/kb-excel-dify-chunking.md | 176 ++ docs/knowledge_base_runtime_deploy.md | 175 ++ frontend/package-lock.json | 1437 +++++----- .../components/messages/ChatMessageBubble.vue | 97 + .../chat/composables/useChatScroll.ts | 31 +- .../features/chat/leave/leaveIntent.test.ts | 6 + .../src/features/chat/leave/leaveIntent.ts | 4 + .../features/chat/page/useChatPageMarkdown.ts | 23 +- .../features/chat/utils/mermaidChart.test.ts | 28 + .../src/features/chat/utils/mermaidChart.ts | 71 + .../features/kb/utils/kb-workflow.utils.ts | 8 +- frontend/src/locales/en/auth.json | 2 +- frontend/src/locales/en/errors.json | 2 +- frontend/src/locales/th/auth.json | 2 +- frontend/src/locales/th/errors.json | 2 +- frontend/src/locales/zh-CN/auth.json | 2 +- frontend/src/locales/zh-CN/errors.json | 2 +- frontend/src/locales/zh-TW/auth.json | 2 +- frontend/src/locales/zh-TW/errors.json | 2 +- .../shared/components/FilePreviewModal.vue | 67 +- scripts/seed_fire_extinguisher_faq.py | 82 + 41 files changed, 4579 insertions(+), 766 deletions(-) create mode 100644 backend/app/api/chat.py create mode 100644 backend/tests/test_integration_source_fallback.py create mode 100644 docs/kb-excel-dify-chunking.md create mode 100644 docs/knowledge_base_runtime_deploy.md create mode 100644 frontend/src/features/chat/utils/mermaidChart.test.ts create mode 100644 frontend/src/features/chat/utils/mermaidChart.ts create mode 100644 scripts/seed_fire_extinguisher_faq.py diff --git a/.env.shared b/.env.shared index afc7ad36..6df54692 100644 --- a/.env.shared +++ b/.env.shared @@ -29,10 +29,11 @@ EDKB_SOFFICE_TIMEOUT_SEC=600 EDKB_WORD_TIMEOUT_SEC=300 # 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker EDKB_FILE_TIMEOUT_SEC=300 +EDKB_PDF_FILE_TIMEOUT_SEC=900 # Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC EDKB_WORD_FILE_TIMEOUT_SEC=420 # running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时 -KB_JOB_RUNNING_TIMEOUT_SECONDS=900 +KB_JOB_RUNNING_TIMEOUT_SECONDS=1200 # 采购合同全面审核:三环境一致的异步任务与输入保护参数 # 清洗产物目录由各环境相对 backend/ 根目录解析;容器部署可由 Compose 覆盖为 /app/data/procurement_contract diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py new file mode 100644 index 00000000..27c3f72f --- /dev/null +++ b/backend/app/api/chat.py @@ -0,0 +1,2361 @@ +""" +backend/app/api/chat.py + +用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。 +依赖:app.core.decorators、app.core.errors、services.dify、integrations。 +逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。 +""" +import io +import ipaddress +import mimetypes +import ntpath +import posixpath +import tempfile +import os +import subprocess +import uuid +import json +import time +from datetime import datetime +from urllib.parse import urlparse +import requests +from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context +from sqlalchemy import func, desc, or_, exists, and_ +from openpyxl import load_workbook +from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs +from app.services.dify import DifyService +from app.core.config.settings import Config +from app.services.integration_api import IntegrationApiService +from app.core.decorators import require_agent_permission +from app.models import Agent, ChatLog, ChatSession, Feedback +from app import db +from app.core.errors import ( + AppError, + ConflictError, + ForbiddenError, + NotFoundError, + ServiceUnavailableError, + UnauthorizedError, + ValidationError, + raise_for_status, +) +chat_bp = Blueprint('chat', __name__) + +SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' + + +PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip() + + +def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None: + """ + 构建聊天入口分发给领域 adapter 的提示字典。 + + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, + 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 + """ + task_id = str(shipping_task_id or '').strip() + batch_no = str(shipping_batch_no or '').strip() + if not task_id and not batch_no: + return None + return { + 'shipping_notice': { + 'task_id': task_id or None, + 'batch_no': batch_no or None, + } + } + + +def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool: + """ + 判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。 + + 核心逻辑: + - 仅对“固资管理”Agent 生效; + - 仅当用户本轮问题可脱离上一轮上下文独立完成时触发; + - 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。 + """ + from app.services.text2sql import Text2SQLService + + return Text2SQLService._should_reset_provider_conversation(query, agent_proxy) + +def _session_title_from_text(text: str) -> str: + value = str(text or '').strip() + if not value: + return '' + return value[:30] + ('...' if len(value) > 30 else '') + + +def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str: + """ + 将内部 Agent 编排提示转换成业务用户可见话术。 + + Args: + text: chat_logs.query 中保存的用户侧文本。 + agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。 + Returns: + 可直接展示在聊天历史里的用户问题。 + """ + value = str(text or '').strip() + if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE: + return value + import re + + task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I) + task_no = task_match.group(1).upper() if task_match else '' + if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value: + return f'继续处理当前发货任务 {task_no}'.strip() + return value + + +def _serialize_session(session: ChatSession) -> dict: + last_active = session.last_active_at or session.created_at + return { + 'id': session.id, + 'conversation_id': session.session_id, + 'title': session.title or '', + 'created_at': last_active.isoformat() if last_active else '', + 'status': session.status, + } + + +def _get_chat_session(user_id: int, agent_id: int, session_id: str | None): + session_key = str(session_id or '').strip() + if not session_key: + return None + return db.session.query(ChatSession).filter_by( + user_id=user_id, + agent_id=agent_id, + session_id=session_key, + ).first() + + +def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession): + match_ids = {session.session_id} + external_id = str(session.external_conversation_id or '').strip() + if external_id: + match_ids.add(external_id) + return db.session.query(ChatLog).filter( + ChatLog.user_id == user_id, + ChatLog.agent_id == agent_id, + or_( + ChatLog.session_id.in_(match_ids), + ChatLog.conversation_id.in_(match_ids), + ), + ).order_by(ChatLog.created_at.asc()).all() + + +def _ensure_chat_session( + user_id: int, + agent_id: int, + session_id: str | None, + title: str = '', + status: str = 'running', + external_conversation_id: str | None = None, +): + session_key = str(session_id or '').strip() + external_id = str(external_conversation_id or '').strip() or None + session = _get_chat_session(user_id, agent_id, session_key) + changed = False + if not session: + session = ChatSession( + session_id=session_key or uuid.uuid4().hex, + user_id=user_id, + agent_id=agent_id, + title=_session_title_from_text(title), + status=status, + external_conversation_id=external_id, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow(), + last_active_at=datetime.utcnow(), + ) + db.session.add(session) + db.session.commit() + return session + + if not session.title and title: + session.title = _session_title_from_text(title) + changed = True + if status and session.status != status: + session.status = status + changed = True + if external_id and session.external_conversation_id != external_id: + session.external_conversation_id = external_id + changed = True + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() + changed = True + if changed: + db.session.commit() + return session + + +def _update_chat_session( + user_id: int, + agent_id: int, + session_id: str, + *, + status: str | None = None, + external_conversation_id: str | None = None, + title: str | None = None, + touch: bool = False, +): + session = _get_chat_session(user_id, agent_id, session_id) + if not session: + return None + + changed = False + if title and not session.title: + session.title = _session_title_from_text(title) + changed = True + + external_id = str(external_conversation_id or '').strip() or None + if external_id and session.external_conversation_id != external_id: + session.external_conversation_id = external_id + changed = True + + if status and session.status != status: + session.status = status + changed = True + + if touch or changed: + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() + changed = True + + if changed: + db.session.commit() + return session + + +def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]: + """ + 统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。 + + Returns: + (path_kind, normalized_path) + - path_kind: 'windows' | 'posix' | '' + - normalized_path: 归一化后的绝对路径文本 + """ + raw_value = str(path_value or '').strip().strip('"') + if not raw_value: + return ('', '') + if raw_value.startswith('\\\\'): + normalized = raw_value.replace('/', '\\') + normalized = '\\\\' + normalized[2:].rstrip('\\') + return ('windows', normalized) + if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'): + normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\') + return ('windows', normalized) + if raw_value.startswith('/'): + normalized = posixpath.normpath(raw_value.replace('\\', '/')) + return ('posix', normalized.rstrip('/')) + return ('', '') + +def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool: + target_kind, normalized_target = _normalize_allowed_share_path(target_path) + root_kind, normalized_root = _normalize_allowed_share_path(root_path) + if not normalized_target or not normalized_root or target_kind != root_kind: + return False + if target_kind == 'windows': + target_lower = normalized_target.lower() + root_lower = normalized_root.lower() + return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\') + return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/') + +def _is_allowed_share_path(target_url: str) -> bool: + target_kind, normalized_target = _normalize_allowed_share_path(target_url) + if not normalized_target: + return False + history_share_root = '' + history_local_root = '' + if has_request_context(): + history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip() + history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip() + if not history_share_root: + history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip() + if not history_local_root: + history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip() + roots = [ + PLM_PREVIEW_SHARE_ROOT, + history_share_root, + history_local_root, + ] + return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots) + +def _is_allowed_preview_url(target_url: str) -> bool: + """ + 预览代理 URL 白名单校验。 + 仅允许: + 1) 配置中的集成服务主机; + 2) 本机地址; + 3) 私网 IP 或常见内网域名(.local/.lan)。 + """ + try: + if _is_allowed_share_path(target_url): + return True + parsed = urlparse(target_url) + if parsed.scheme not in ('http', 'https'): + return False + host = (parsed.hostname or '').strip().lower() + if not host: + return False + integration_base = (IntegrationApiService.get_base_url() or '').strip() + if integration_base: + integration_host = (urlparse(integration_base).hostname or '').strip().lower() + if integration_host and host == integration_host: + return True + + # 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP) + if has_request_context(): + req_host = (request.host.split(':')[0] or "").strip().lower() + if host == req_host: + return True + + if host in ("localhost", "127.0.0.1", "::1"): + return True + try: + ip = ipaddress.ip_address(host) + return ip.is_private or ip.is_loopback + except ValueError: + # 非 IP 主机:仅放行内网风格本地域名。 + return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com") + except Exception: + return False + +def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024): + """ + 从上游文件 URL 拉取二进制内容(供预览接口复用)。 + 核心逻辑:共享盘直读 / 固资图 / HTTP 拉取;integration kind=source 404 时回退 md → Dify 原文件 → 分段文本。 + 如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。 + 返回: (content_bytes, content_type, error_tuple) + 其中 error_tuple = (message, status_code);成功时为 None。 + """ + import base64 + import json + import time + import sqlalchemy as sa + from urllib.parse import parse_qs + if _is_allowed_share_path(file_url): + _path_kind, normalized_path = _normalize_allowed_share_path(file_url) + try: + if not os.path.isfile(normalized_path): + return (None, None, ('source file not found', 404)) + file_size = os.path.getsize(normalized_path) + if max_size is not None and file_size > max_size: + return (None, None, ('file too large for online preview', 413)) + with open(normalized_path, 'rb') as fh: + content = fh.read() + except OSError as exc: + current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc) + return (None, None, ('failed to read source file', 502)) + guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower() + if _extract_placeholder_text(content): + guessed_type = 'text/plain; charset=utf-8' + return (content, guessed_type, None) + try: + from app.services.fixed_asset_image import FixedAssetImageService + content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes( + file_url, + max_size=max_size, + ) + if content is not None or asset_image_err is not None: + return (content, content_type, asset_image_err) + except Exception as exc: + current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc) + headers = {} + base_url = IntegrationApiService.get_base_url() + api_key = IntegrationApiService.get_api_key() + + def _resolve_latest_integration_url(raw_url: str): + dataset_id = '' + remote_document_id = '' + try: + parsed = urlparse(raw_url) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if token: + parts = token.split('.') + if len(parts) >= 2: + payload_b64 = parts[1] + payload_b64 += '=' * (-len(payload_b64) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + dataset_id = str(payload_data.get('dataset_id') or '').strip() + remote_document_id = str(payload_data.get('remote_document_id') or '').strip() + except Exception: + pass + if not dataset_id or not remote_document_id: + try: + stmt = sa.text('CAST(retriever_resources AS TEXT) LIKE :url') + log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() + if log and log.retriever_resources: + for r in log.retriever_resources: + if not isinstance(r, dict): + continue + source_url = str(r.get('source_download_url') or '') + if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): + resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r) + dataset_id = dataset_id or str(resolved_dataset_id or '').strip() + remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip() + if dataset_id and remote_document_id: + break + except Exception as e: + current_app.logger.warning('[file-preview] failed to find IDs in ChatLog: %s', e) + if dataset_id and remote_document_id: + new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) + if new_info and new_info.get('source_download_url'): + current_app.logger.info('[file-preview] refreshed integration url for dataset=%s doc=%s', dataset_id, remote_document_id) + return new_info['source_download_url'] + return raw_url + + def _build_headers(raw_url: str): + next_headers = {} + + is_trusted = False + if base_url and raw_url.startswith(base_url): + is_trusted = True + elif _is_allowed_preview_url(raw_url): + is_trusted = True + else: + try: + parsed = urlparse(raw_url) + host = (parsed.hostname or "").strip().lower() + if has_request_context(): + req_host = (request.host.split(':')[0] or "").strip().lower() + if host == req_host: + is_trusted = True + if host in ("localhost", "127.0.0.1", "::1"): + is_trusted = True + except Exception: + pass + + current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}") + if is_trusted: + if api_key: + next_headers['X-Integration-Key'] = api_key + if has_request_context(): + auth_header = (request.headers.get('Authorization') or '').strip() + cookie_header = (request.headers.get('Cookie') or '').strip() + if auth_header: + next_headers['Authorization'] = auth_header + if cookie_header: + next_headers['Cookie'] = cookie_header + + return next_headers + + def _should_refresh_from_response(resp) -> bool: + ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower() + if resp.status_code == 401: + return True + if resp.status_code in (403, 404) and 'token=' in file_url: + return True + if ctype == 'application/json': + body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower() + if 'unauthorized' in body or '"error"' in body: + return True + return False + + def _retry_with_refreshed_url(raw_url: str): + refreshed_url = _resolve_latest_integration_url(raw_url) + if not refreshed_url or refreshed_url == raw_url: + return None, raw_url + retry_headers = _build_headers(refreshed_url) + try: + return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url + except requests.RequestException as e: + current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) + return None, refreshed_url + + if 'token=' in file_url: + try: + parsed = urlparse(file_url) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if token: + parts = token.split('.') + if len(parts) >= 2: + payload_b64 = parts[1] + payload_b64 += '=' * (-len(payload_b64) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + exp = payload_data.get('exp', 0) + if exp and exp < time.time() + 300: + file_url = _resolve_latest_integration_url(file_url) + except Exception as e: + current_app.logger.warning('[file-preview] failed to refresh expired integration token: %s', e) + headers = _build_headers(file_url) + try: + upstream = requests.get(file_url, headers=headers, timeout=(5, 20)) + except requests.RequestException as e: + current_app.logger.warning('[file-preview] upstream request failed: %s', e) + return (None, None, ('failed to fetch source file', 502)) + if 'token=' in file_url and _should_refresh_from_response(upstream): + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url + if upstream.status_code != 200: + if 'token=' in file_url: + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url + current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}") + if upstream.status_code == 404: + # [STEP] 源文件 404:先试 integration kind=md,再试 Dify 原文件/分段文本 + fallback = _fetch_preview_bytes_after_source_404(file_url, max_size=max_size) + if fallback[0] is not None or fallback[2] is not None: + return fallback + return None, None, ('source file not found', 404) + return None, None, (f'upstream returned status {upstream.status_code}', 502) + + content = upstream.content or b'' + if max_size is not None and len(content) > max_size: + return (None, None, ('file too large for online preview', 413)) + content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + if content_type == 'application/json': + body = content[:512].decode('utf-8', errors='ignore') + current_app.logger.warning('[file-preview] upstream returned json instead of binary url=%s body=%s', file_url, body) + return (None, None, ('upstream returned invalid preview payload', 502)) + return (content, content_type, None) + + +def _rewrite_integration_download_kind(file_url: str, kind: str) -> str: + """ + 将 integration download URL 的 kind 查询参数改写为目标值。 + @param file_url: 原始下载 URL + @param kind: 目标 kind(如 md) + @returns 改写后的 URL;无法识别时原样返回 + """ + from urllib.parse import parse_qs, urlencode, urlunparse + + raw = str(file_url or '').strip() + if not raw or '/api/integration/files/' not in raw: + return raw + parsed = urlparse(raw) + qs = parse_qs(parsed.query, keep_blank_values=True) + qs['kind'] = [str(kind)] + flat: dict = {} + for key, values in qs.items(): + flat[key] = values[0] if len(values) == 1 else values + new_query = urlencode(flat, doseq=True) + return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment)) + + +def _extract_integration_token_ids(file_url: str) -> tuple[str, str]: + """ + 从 integration 下载 URL 的 JWT token 中解析 dataset_id / remote_document_id。 + @returns (dataset_id, remote_document_id),失败时为空字符串 + """ + import base64 + from urllib.parse import parse_qs + + try: + parsed = urlparse(str(file_url or '')) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if not token: + return ('', '') + parts = token.split('.') + if len(parts) < 2: + return ('', '') + payload_b64 = parts[1] + '=' * (-len(parts[1]) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + dataset_id = str(payload_data.get('dataset_id') or '').strip() + remote_document_id = str(payload_data.get('remote_document_id') or '').strip() + return (dataset_id, remote_document_id) + except Exception: + return ('', '') + + +def _fetch_dify_source_bytes(dataset_id: str, remote_document_id: str, max_size: int | None): + """ + 从 Dify 拉取文档原始二进制(签名下载 URL)。 + 【AI 触发时机】本地 source 文件丢失、integration 404 时作为预览兜底。 + @returns (content, content_type, error_tuple) 与 _fetch_preview_source_bytes 一致 + """ + if not dataset_id or not remote_document_id: + return (None, None, None) + try: + info = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id) + source_url = str((info or {}).get('source_download_url') or '').strip() + if not source_url: + return (None, None, None) + upstream = requests.get(source_url, timeout=(5, 30)) + if upstream.status_code != 200: + current_app.logger.warning( + '[file-preview] dify source download status=%s dataset=%s doc=%s', + upstream.status_code, + dataset_id, + remote_document_id, + ) + return (None, None, None) + content = upstream.content or b'' + if max_size is not None and len(content) > max_size: + return (None, None, ('file too large for online preview', 413)) + content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + return (content, content_type or None, None) + except Exception as exc: + current_app.logger.warning( + '[file-preview] dify source download failed dataset=%s doc=%s err=%s', + dataset_id, + remote_document_id, + exc, + ) + return (None, None, None) + + +def _looks_like_text_document(content: bytes) -> bool: + """ + 判断内容是否可按文本/Markdown 预览,避免把 OLE/PDF 等二进制当文本导致乱码。 + 核心逻辑:识别常见二进制魔数;抽样解码后要求可打印字符占比足够高。 + """ + if not content: + return False + # [STEP 1] 排除 PDF / ZIP(OOXML) / OLE(旧版 Office) + if content.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')): + return False + sample = content[:4096] + if b'\x00' in sample: + return False + text = None + for enc in ('utf-8', 'utf-8-sig', 'gb18030'): + try: + text = sample.decode(enc) + break + except UnicodeDecodeError: + continue + if text is None: + return False + printable = sum(1 for ch in text if ch.isprintable() or ch in '\r\n\t') + return (printable / max(len(text), 1)) >= 0.85 + + +def _fetch_preview_bytes_after_source_404(file_url: str, max_size: int | None): + """ + 源文件 404 后的预览兜底链:integration md → Dify 原文件 → Dify 分段文本。 + """ + # [STEP 1] kind=source → kind=md(清洗稿,必须是可读文本) + if 'kind=source' in str(file_url or '') and '/api/integration/files/' in str(file_url or ''): + md_url = _rewrite_integration_download_kind(file_url, 'md') + if md_url and md_url != file_url: + try: + api_key = IntegrationApiService.get_api_key() + headers = {'X-Integration-Key': api_key} if api_key else {} + upstream = requests.get(md_url, headers=headers, timeout=(5, 20)) + if upstream.status_code == 200: + content = upstream.content or b'' + if max_size is not None and len(content) > max_size: + return (None, None, ('file too large for online preview', 413)) + content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + if content_type == 'application/json': + current_app.logger.warning('[file-preview] md fallback returned json url=%s', md_url) + elif not _looks_like_text_document(content): + current_app.logger.warning( + '[file-preview] md fallback ignored binary payload url=%s', + md_url, + ) + else: + current_app.logger.info('[file-preview] source 404 fallback to markdown url=%s', md_url) + return (content, content_type or 'text/markdown', None) + except requests.RequestException as exc: + current_app.logger.warning('[file-preview] markdown fallback failed: %s', exc) + + dataset_id, remote_document_id = _extract_integration_token_ids(file_url) + + # [STEP 2] Dify 原始文件下载 + dify_bytes = _fetch_dify_source_bytes(dataset_id, remote_document_id, max_size) + if dify_bytes[0] is not None: + current_app.logger.info( + '[file-preview] source 404 fallback to dify binary dataset=%s doc=%s', + dataset_id, + remote_document_id, + ) + return dify_bytes + if dify_bytes[2] is not None: + return dify_bytes + + # [STEP 3] Dify 分段文本(任意文档形态) + text = _fetch_dify_document_segments_text(dataset_id, remote_document_id) + if text: + current_app.logger.info( + '[file-preview] source 404 fallback to dify segments dataset=%s doc=%s', + dataset_id, + remote_document_id, + ) + return (text.encode('utf-8'), 'text/plain; charset=utf-8', None) + return (None, None, None) + + +def _extract_placeholder_text(content: bytes) -> str: + sample = content[:2048] + for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'): + try: + text = sample.decode(enc).replace('\x00', '').strip() + except Exception: + continue + if not text: + continue + lines = [line.strip() for line in text.splitlines() if line.strip()] + if not lines: + continue + first_line = lines[0][:160] + if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))): + return first_line + return '' + + + +def _fetch_dify_document_segments_text(dataset_id: str, remote_document_id: str) -> str | None: + """ + 拼接 Dify 文档全部分段文本,不限制 doc_form(供源文件丢失时的预览兜底)。 + """ + if not dataset_id or not remote_document_id: + return None + try: + from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService + service = KbDifySyncService() + segments_payload = service._request( + 'GET', + f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000', + ) + rows = [] + if isinstance(segments_payload, dict): + rows = segments_payload.get('data') or [] + elif isinstance(segments_payload, list): + rows = segments_payload + if not isinstance(rows, list) or not rows: + return None + ordered_rows = sorted( + [row for row in rows if isinstance(row, dict)], + key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')), + ) + parts: list[str] = [] + for row in ordered_rows: + text_part = str(row.get('content') or '').strip() + if text_part: + parts.append(text_part) + return '\n\n'.join(parts).strip() or None + except Exception as e: + current_app.logger.warning( + '[source-file-text] failed to fetch dify segments dataset=%s doc=%s err=%s', + dataset_id, + remote_document_id, + e, + ) + return None + +def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None: + """ + 对于 Dify 中以 text_model / txt 形式存储的文档, + 直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。 + """ + if not dataset_id or not remote_document_id: + return None + try: + from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService + service = KbDifySyncService() + document_payload = service.get_document( + dataset_id=str(dataset_id), + document_id=str(remote_document_id), + ) + if not isinstance(document_payload, dict): + return None + + upload_info = ( + ((document_payload.get('data_source_info') or {}).get('upload_file')) + if isinstance(document_payload.get('data_source_info'), dict) + else {} + ) or {} + source_ext = str(upload_info.get('extension') or '').strip().lower() + doc_form = str(document_payload.get('doc_form') or '').strip().lower() + mime_type = str(upload_info.get('mime_type') or '').strip().lower() + is_text_doc = ( + source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt') + or doc_form == 'text_model' + or mime_type.startswith('text/') + ) + if not is_text_doc: + return None + + return _fetch_dify_document_segments_text(dataset_id, remote_document_id) + except Exception as e: + current_app.logger.warning( + '[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s', + dataset_id, + remote_document_id, + e, + ) + return None + +def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF + """ + import shutil + temp_dir = tempfile.mkdtemp() + try: + input_path = os.path.join(temp_dir, f"input.{ext}") + with open(input_path, 'wb') as f: + f.write(content) + commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe'] + success = False + for cmd in commands: + try: + process = subprocess.run([cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) + if process.returncode == 0: + success = True + break + else: + current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}") + except (FileNotFoundError, subprocess.TimeoutExpired): + continue + if not success and os.name == 'nt': + app = None + doc_obj = None + pythoncom = None + try: + import win32com.client + import pythoncom + pythoncom.CoInitialize() + output_path = os.path.join(temp_dir, 'input.pdf') + if ext in ('doc', 'docx'): + try: + from pathlib import Path + from edkb_system.skills.word_bridge import convert_with_word + + convert_with_word(Path(input_path), Path(output_path), 17) + success = True + except Exception as word_bridge_exc: + current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc) + + if not success and ext in ('doc', 'docx'): + try: + # 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS + app = win32com.client.Dispatch("Word.Application") + except Exception: + app = win32com.client.Dispatch("KWPS.Application") + app.Visible = False + app.DisplayAlerts = False + input_abs = os.path.abspath(input_path) + output_abs = os.path.abspath(output_path) + try: + doc_obj = app.Documents.Open( + FileName=input_abs, + ConfirmConversions=False, + ReadOnly=True, + AddToRecentFiles=False, + Visible=False, + NoEncodingDialog=True, + OpenAndRepair=True, + ) + except TypeError: + doc_obj = app.Documents.Open(input_abs, ReadOnly=True) + + try: + # 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17) + doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF + except Exception: + doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF + success = True + elif ext in ('ppt', 'pptx'): + try: + app = win32com.client.Dispatch('KWPP.Application') + except Exception: + app = win32com.client.Dispatch('PowerPoint.Application') + app.Visible = False + try: + app.DisplayAlerts = False + except Exception: + pass + doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False) + doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF + success = True + elif ext in ('xls', 'xlsx'): + try: + app = win32com.client.Dispatch('KET.Application') + except Exception: + app = win32com.client.Dispatch('Excel.Application') + app.Visible = False + app.DisplayAlerts = False + doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True) + doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF + success = True + except ImportError: + current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Office COM API.') + except Exception as e: + current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}") + finally: + if doc_obj is not None: + try: + doc_obj.Close(False) + except Exception: + pass + if app is not None: + try: + app.Quit() + except Exception: + pass + if pythoncom is not None: + try: + pythoncom.CoUninitialize() + except Exception: + pass + + if not success: + raise Exception('Failed to convert document to PDF using LibreOffice or WPS/MS Office') + output_path = os.path.join(temp_dir, 'input.pdf') + if os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + else: + raise Exception("PDF output not found after conversion") + finally: + shutil.rmtree(temp_dir, ignore_errors=True) + + +def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。 + """ + normalized_ext = (ext or '').strip().lower() + if normalized_ext != 'xls': + return content + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, 'input.xls') + output_path = os.path.join(temp_dir, 'input.xlsx') + with open(input_path, 'wb') as f: + f.write(content) + commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe'] + errors = [] + for cmd in commands: + try: + process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60) + except (FileNotFoundError, subprocess.TimeoutExpired) as e: + errors.append(f'{cmd}: {e}') + continue + if process.returncode == 0 and os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + stderr = process.stderr.decode('utf-8', errors='ignore').strip() + errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}") + + allow_windows_excel_preview = ( + os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on') + ) + if allow_windows_excel_preview: + if _convert_excel_via_windows_office(input_path, output_path): + with open(output_path, 'rb') as f: + return f.read() + errors.append("windows-office: failed to convert xls via WPS/MS Excel") + else: + errors.append("windows-office: disabled for preview to avoid interactive Office dialogs") + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError(f"failed to convert xls to xlsx: {joined}") + + +def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool: + """ + 在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。 + LibreOffice 不存在时,给在线预览提供兜底转换能力。 + """ + if os.name != 'nt': + return False + try: + import pythoncom + import win32com.client + except ImportError: + current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.') + return False + app = None + workbook = None + pythoncom.CoInitialize() + try: + try: + app = win32com.client.Dispatch('KET.Application') + except Exception: + app = win32com.client.Dispatch('Excel.Application') + app.Visible = False + app.DisplayAlerts = False + workbook = app.Workbooks.Open(os.path.abspath(input_path)) + workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) + workbook.Close(False) + workbook = None + app.Quit() + app = None + return os.path.exists(output_path) + except Exception as exc: + current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc) + return False + finally: + try: + if workbook is not None: + workbook.Close(False) + except Exception: + pass + try: + if app is not None: + app.Quit() + except Exception: + pass + try: + pythoncom.CoUninitialize() + except Exception: + pass + +def _detect_excel_format(content: bytes, ext: str) -> str: + """ + 根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。 + - OLE 复合文档头: 老式 `.xls` + - ZIP 头: `.xlsx` + """ + normalized_ext = (ext or '').strip().lower() + head = content[:8] if content else b'' + if head.startswith(b'PK\x03\x04'): + return 'xlsx' + if head.startswith(b'\xd0\xcf\x11\xe0'): + return 'xls' + return normalized_ext + +def _load_excel_workbook(content: bytes, ext: str): + normalized_ext = _detect_excel_format(content, ext) + if normalized_ext == 'xls': + content = _convert_excel_to_xlsx(content, 'xls') + return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + +@chat_bp.route('/oa/employees', methods=['GET']) +@require_agent_permission +def get_oa_employees(): + """ + 获取 OA 系统中的员工列表(分页/搜索) + """ + keyword = request.args.get('keyword', '').strip() + try: + page = int(request.args.get('page', 1)) + page_size = int(request.args.get('page_size', 20)) + except ValueError: + page = 1 + page_size = 20 + try: + from app.services.oa_sqlserver import OASQLServerService + result = OASQLServerService.search_employees(keyword, page, page_size) + return jsonify(result) + except Exception as e: + current_app.logger.error(f'[OA-Employees] Query failed: {e}') + raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500) + +@chat_bp.route('/oa/resolve-names', methods=['GET']) +@require_agent_permission +def resolve_oa_names(): + dept_ids = request.args.get('department_ids', '').strip() + sub_ids = request.args.get('subcompany_ids', '').strip() + result = {} + try: + from app.services.oa_sqlserver import OASQLServerService + if dept_ids: + for did in dept_ids.split(','): + did = did.strip() + if did: + result[f'dept_{did}'] = OASQLServerService.get_department_name(did) + if sub_ids: + for sid in sub_ids.split(','): + sid = sid.strip() + if sid: + result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid) + except Exception as e: + current_app.logger.error(f'[OA-ResolveNames] Query failed: {e}') + return jsonify(result) + +@chat_bp.route('/sessions', methods=['GET']) +@require_agent_permission +def get_chat_sessions(): + """ + 获取当前用户与当前 Agent 的历史会话列表 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500) + + session_rows = db.session.query(ChatSession).filter( + ChatSession.user_id == user.id, + ChatSession.agent_id == agent.id, + or_( + ChatSession.status == 'running', + exists().where( + and_( + ChatLog.session_id == ChatSession.session_id, + ChatLog.user_id == user.id, + ChatLog.agent_id == agent.id, + ) + ), + ), + ).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all() + + sessions = [_serialize_session(item) for item in session_rows] + session_ids = {item['conversation_id'] for item in sessions} + + # 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。 + subquery = db.session.query( + ChatLog.conversation_id, + func.max(ChatLog.created_at).label('last_active') + ).filter( + ChatLog.user_id == user.id, + ChatLog.agent_id == agent.id, + ChatLog.session_id.is_(None), + ChatLog.conversation_id.isnot(None), + ChatLog.conversation_id != '', + ).group_by(ChatLog.conversation_id).subquery() + + legacy_rows = db.session.query( + subquery.c.conversation_id, + subquery.c.last_active, + ).order_by(desc(subquery.c.last_active)).limit(20).all() + + for row in legacy_rows: + if not row.conversation_id or row.conversation_id in session_ids: + continue + latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first() + title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip() + sessions.append({ + 'id': 0, + 'conversation_id': row.conversation_id, + 'title': title[:30] + ('...' if len(title) > 30 else '') if title else '', + 'created_at': row.last_active.isoformat(), + 'status': 'done', + }) + + sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True) + return jsonify(sessions[:20]) + +@chat_bp.route('/sessions', methods=['DELETE']) +@require_agent_permission +def delete_all_chat_sessions(): + """ + 删除当前用户与当前 Agent 的所有历史会话 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500) + chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all() + chat_log_ids = [log.id for log in chat_logs] + if chat_log_ids: + from app.models import GeneralFeedback + db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False) + db.session.commit() + + return jsonify({'status': 'ok'}) + +@chat_bp.route('/sessions/', methods=['DELETE']) +@require_agent_permission +def delete_chat_session(conversation_id): + """ + 删除指定的会话记录 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500) + + session = _get_chat_session(user.id, agent.id, conversation_id) + if session: + chat_logs = db.session.query(ChatLog).filter( + ChatLog.user_id == user.id, + ChatLog.agent_id == agent.id, + or_( + ChatLog.session_id == session.session_id, + ChatLog.conversation_id == session.external_conversation_id, + ) + ).all() + else: + chat_logs = db.session.query(ChatLog).filter_by( + user_id=user.id, + agent_id=agent.id, + conversation_id=conversation_id + ).all() + + chat_log_ids = [log.id for log in chat_logs] + if chat_log_ids: + from app.models import GeneralFeedback + db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) + if session: + db.session.delete(session) + db.session.commit() + + return jsonify({'status': 'ok'}) + +@chat_bp.route('/messages', methods=['GET']) +@require_agent_permission +def get_chat_messages(): + """ + 获取指定会话的消息记录 + """ + conversation_id = request.args.get('conversation_id') + if not conversation_id: + return jsonify([]) + + session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id) + if session: + logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session) + else: + logs = db.session.query(ChatLog).filter( + ChatLog.user_id == g.current_user.id, + ChatLog.agent_id == g.current_agent.id, + ChatLog.conversation_id == conversation_id, + ).order_by(ChatLog.created_at.asc()).all() + + messages = [] + agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic' + for log in logs: + if log.query: + messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)}) + if ( + not log.answer + and not log.message_type + and not log.payload + ): + continue + if ( + log.query + and log.answer == log.query + and (not log.message_type or log.message_type == 'text') + and not log.payload + ): + continue + assistant_msg = { + 'role': 'assistant', + 'content': DifyService._dedupe_exact_doubled_text(log.answer or ''), + 'chat_log_id': log.id, + 'retriever_resources': log.retriever_resources or [], + 'attribution_parts': log.attribution_parts or [], + } + if log.run_id: + assistant_msg['run_id'] = log.run_id + if log.message_type: + assistant_msg['type'] = log.message_type + if log.payload: + assistant_msg['payload'] = log.payload + messages.append(assistant_msg) + return jsonify(messages) + +@chat_bp.route('/messages/local', methods=['POST']) +@require_agent_permission +def save_local_message(): + """ + 保存前端本地生成的聊天记录(如表单、确认弹窗、提交结果等) + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500) + data = request.get_json() or {} + conversation_id = (data.get('conversation_id') or '').strip() + role = (data.get('role') or 'assistant').strip() + message_type = data.get('type') + content = data.get('content', '') + payload = data.get('payload') + user_query = data.get('query', '') + if role == 'user': + user_query = user_query or content + content = '' + else: + # 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。 + user_query = '' + + if not message_type: + raise ValidationError('type is required') + + title = user_query or content + external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None + session = _ensure_chat_session( + user.id, + agent.id, + conversation_id or None, + title=title, + status='done', + external_conversation_id=external_conversation_id, + ) + conversation_id = session.session_id + + # 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录 + # 这样能保证前端表单状态(例如已确认)被持久化 + local_id = payload.get('formId') if payload and isinstance(payload, dict) else None + chat_log = None + if local_id: + # 在 payload 中查找是否已存在相同 formId 的同类型消息 + # SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配 + logs = db.session.query(ChatLog).filter_by( + user_id=user.id, + agent_id=agent.id, + session_id=conversation_id, + message_type=message_type + ).order_by(ChatLog.created_at.desc()).limit(20).all() + + for log in logs: + if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id): + chat_log = log + break + if chat_log: + chat_log.content = content + chat_log.answer = content + chat_log.payload = payload + if user_query and (not chat_log.query): + chat_log.query = user_query + else: + chat_log = ChatLog( + user_id=user.id, + agent_id=agent.id, + conversation_id=session.external_conversation_id or conversation_id, + session_id=conversation_id, + query=user_query, + answer=content, + message_type=message_type, + payload=payload + ) + db.session.add(chat_log) + session.status = 'done' + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() + db.session.commit() + return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id}) + +@chat_bp.route('/query-preview/', methods=['GET']) +@require_agent_permission +def get_chat_query_preview(chat_log_id: int): + page = request.args.get('page', type=int) or 1 + page_size = request.args.get('page_size', type=int) or 100 + page = max(1, page) + page_size = max(1, min(200, page_size)) + + log = db.session.query(ChatLog).filter( + ChatLog.id == chat_log_id, + ChatLog.user_id == getattr(g.current_user, 'id', 0), + ChatLog.agent_id == getattr(g.current_agent, 'id', 0), + ).first() + if not log: + raise NotFoundError('query preview not found') + + payload = log.payload if isinstance(log.payload, dict) else {} + if payload.get('kind') != 'text2sql_result_preview': + raise ValidationError('current message does not support query preview') + + sql = str(payload.get('sql') or '').strip() + query = str(payload.get('query') or log.query or '').strip() + if not sql: + raise ValidationError('query preview sql is missing') + + from app.services.text2sql import Text2SQLService + total_count = payload.get('total_count') + try: + total_count = int(total_count) if total_count is not None else None + except (TypeError, ValueError): + total_count = None + + columns, rows, resolved_total = Text2SQLService.get_preview_page( + sql=sql, + query=query, + page=page, + page_size=page_size, + agent=g.current_agent, + total_count=total_count, + user_context=Text2SQLService._normalize_user_context(g.current_user), + ) + if columns == ["Error"]: + raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500) + + total = resolved_total if resolved_total is not None else len(rows) + return jsonify({ + 'columns': columns, + 'rows': [list(row) for row in rows], + 'page': page, + 'page_size': page_size, + 'total': total, + 'has_more': page * page_size < total, + 'query': query, + }) + + +@chat_bp.route('/asset-history/search', methods=['GET']) +@require_agent_permission +def search_asset_history_files(): + """ + 检索固定资产履历文件。 + + 用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。 + 约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。 + """ + asset_id = (request.args.get('asset_id') or '').strip() + asset_name = (request.args.get('asset_name') or '').strip() + limit = request.args.get('limit', type=int) or 20 + limit = max(1, min(limit, 50)) + + if not asset_id and not asset_name: + raise ValidationError('asset_id or asset_name is required') + + from app.services.fixed_asset_history import FixedAssetHistoryService + + if not FixedAssetHistoryService.is_enabled(): + raise ServiceUnavailableError('asset history share is not configured') + + items = FixedAssetHistoryService.search_history_files( + asset_id=asset_id, + asset_name=asset_name, + limit=limit, + ) + return jsonify({ + 'asset_id': asset_id, + 'asset_name': asset_name, + 'total': len(items), + 'items': items, + }) + + +@chat_bp.route('/asset-image/resolve', methods=['GET']) +@require_agent_permission +def resolve_asset_image_preview(): + """ + 解析固定资产图片预览链接。 + + 用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。 + 约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。 + """ + asset_id = (request.args.get('asset_id') or '').strip() + asset_name = (request.args.get('asset_name') or '').strip() + if not asset_id and not asset_name: + raise ValidationError('asset_id or asset_name is required') + + from app.services.fixed_asset_image import FixedAssetImageService + + result = FixedAssetImageService.resolve_images( + asset_id=asset_id, + asset_name=asset_name, + ) + return jsonify({ + 'asset_id': asset_id, + 'asset_name': asset_name, + 'item': result.get('item'), + 'items': result.get('items', []), + 'total': result.get('total', 0), + }) + + +@chat_bp.route('/completions', methods=['POST']) +@require_agent_permission +def chat_completions(): + """ + SSE 流式聊天接口 + 用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回 + 核心逻辑: + 1. 从请求体中读取 query / agent_id / conversation_id + 2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent + 3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送 + 传入参数: + 无(从 request.json 读取) + 返回值: + Flask Response 对象,mimetype=text/event-stream + """ + data = request.get_json() or {} + query = data.get('query') + display_query = str(data.get('display_query') or query or '').strip() + # 前端传入的 conversation_id 在 B2 里代表本地 session_id + conversation_id = data.get('conversation_id') + shipping_task_id = str(data.get('task_id') or '').strip() + shipping_batch_no = str(data.get('batch_no') or '').strip() + kb_type = data.get('kb_type', '企业知识库') + files = data.get('files') + request_id = uuid.uuid4().hex[:12] + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type) + if user is None or agent is None: + current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent)) + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500) + + from app.services.agent_registry.resolver import resolve_runtime_provider + + if resolve_runtime_provider(agent) == 'iframe': + raise ValidationError('Embedded iframe agents do not support chat completions') + + user_id = getattr(user, 'id', None) + agent_id = getattr(agent, 'id', None) + + from types import SimpleNamespace + from app.services.agent_directory import serialize_directory_members + + is_aggregate = bool(getattr(agent, 'is_aggregate', False)) + directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else [] + agent_proxy = SimpleNamespace( + id=agent_id, + name=getattr(agent, 'name', None), + type=getattr(agent, 'type', None), + dify_api_key=getattr(agent, 'dify_api_key', None), + api_base_url=getattr(agent, 'api_base_url', None), + extra_config=getattr(agent, 'extra_config', None) or {}, + agent_code=getattr(agent, 'agent_code', None), + runtime_provider=getattr(agent, 'runtime_provider', None), + conversation_mode=getattr(agent, 'conversation_mode', None), + dify_app_type=getattr(agent, 'dify_app_type', None), + capabilities=getattr(agent, 'capabilities', None), + bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None), + handler_config=getattr(agent, 'handler_config', None), + is_aggregate=is_aggregate, + directory_members=directory_members, + ) + user_proxy = SimpleNamespace( + id=user_id, + username=getattr(user, 'username', None), + employee_id=getattr(user, 'employee_id', None), + real_name=getattr(user, 'real_name', None), + role=getattr(user, 'role', None), + ) + + from app.services.dify import DifyService + + external_conversation_id = None + if conversation_id: + existing_session = _get_chat_session(user_id, agent_id, conversation_id) + if existing_session: + session = _ensure_chat_session( + user_id, + agent_id, + existing_session.session_id, + title=display_query, + status='running', + ) + external_conversation_id = session.external_conversation_id + if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy): + current_app.logger.info( + '[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s', + request_id, + session.session_id, + external_conversation_id, + query, + ) + session.external_conversation_id = None + session.updated_at = datetime.utcnow() + session.last_active_at = datetime.utcnow() + db.session.commit() + external_conversation_id = None + else: + session = _ensure_chat_session( + user_id, + agent_id, + conversation_id, + title=display_query, + status='running', + external_conversation_id=conversation_id, + ) + external_conversation_id = session.external_conversation_id + else: + session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running') + + normalized_files: list[dict] | None = None + if files is not None: + if not isinstance(files, list): + raise ValidationError('files must be a list') + normalized_files = [] + for item in files: + if not isinstance(item, dict): + continue + transfer_method = str(item.get('transfer_method') or '').strip() + ftype = str(item.get('type') or '').strip() + if transfer_method not in ('local_file', 'remote_url'): + continue + if ftype not in ('image', 'document', 'audio', 'video', 'custom'): + continue + if transfer_method == 'local_file': + upload_file_id = str(item.get('upload_file_id') or '').strip() + if not upload_file_id: + continue + normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id}) + else: + url = str(item.get('url') or '').strip() + if not url: + continue + normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url}) + if not normalized_files: + normalized_files = None + + from app.services.agent_registry.handlers.base import ChatStreamContext + + relay_stream_ctx = ChatStreamContext( + query=query, + display_query=display_query, + user=user_proxy, + agent=agent_proxy, + session=session, + external_conversation_id=external_conversation_id, + request_id=request_id, + normalized_files=normalized_files, + adapter_hints=_build_chat_adapter_hints( + shipping_task_id=shipping_task_id, + shipping_batch_no=shipping_batch_no, + ), + shipping_task_id=shipping_task_id, + shipping_batch_no=shipping_batch_no, + kb_type=kb_type, + ) + + from app.services.hr_leave_sqlserver import HRLeaveSQLServerService + from app.services.chat.router import try_fast_route + + leave_supported = HRLeaveSQLServerService.supports(query) + + fast_route = try_fast_route( + user=user_proxy, + agent=agent_proxy, + query=query, + agent_id=agent_id, + session_id=session.session_id, + external_conversation_id=external_conversation_id, + normalized_files=normalized_files, + kb_type=kb_type, + leave_supported=leave_supported, + ) + if fast_route is not None: + generator = fast_route.generator + elif leave_supported: + generator = DifyService.stream_chat( + query, + user_proxy.id, + agent_proxy, + external_conversation_id, + request_id=request_id, + session_id=session.session_id, + files=normalized_files, + inputs=build_chat_dify_inputs( + agent_proxy, + session_id=session.session_id, + request_id=request_id, + trigger_source="frontend_chat", + user_role=user_proxy.role, + adapter_hints=_build_chat_adapter_hints( + shipping_task_id=shipping_task_id, + shipping_batch_no=shipping_batch_no, + ), + ), + ) + else: + from app.services.chat.executors import stream_chat_via_executor + + generator = stream_chat_via_executor(relay_stream_ctx) + + def relay_stream(): + from app.services.chat_perf import chat_perf_enabled + + relay_started = time.perf_counter() + relay_first_chunk_at: float | None = None + created_event = { + 'event': 'session_created', + 'conversation_id': session.session_id, + 'provider_conversation_id': session.external_conversation_id, + 'session_status': session.status, + } + yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n" + + known_provider_conversation_id = session.external_conversation_id + known_status = session.status + emitted_handler_state_keys: set[str] = set() + + from app.services.chat.stream_relay import ( + iter_handler_preface_sse, + iter_handler_terminal_sse, + ) + + for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys): + yield preface_line + + try: + for chunk in generator: + if relay_first_chunk_at is None: + relay_first_chunk_at = time.perf_counter() + if not isinstance(chunk, str) or not chunk.startswith('data: '): + yield chunk + continue + + raw_payload = chunk[6:].strip() + try: + event_data = json.loads(raw_payload) + except Exception: + yield chunk + continue + + provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None + event_name = event_data.get('event') + should_touch = False + if provider_conversation_id and provider_conversation_id != known_provider_conversation_id: + known_provider_conversation_id = provider_conversation_id + should_touch = True + if event_name in ('message_end', 'workflow_finished'): + known_status = 'done' + should_touch = True + elif event_name == 'error': + known_status = 'error' + should_touch = True + + if should_touch: + updated_session = _update_chat_session( + user_id, + agent_id, + session.session_id, + status=known_status, + external_conversation_id=known_provider_conversation_id, + touch=True, + ) + if updated_session: + known_status = updated_session.status + + event_data['provider_conversation_id'] = provider_conversation_id + event_data['conversation_id'] = session.session_id + event_data['session_status'] = known_status + if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'): + relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None + relay_total_ms = int((time.perf_counter() - relay_started) * 1000) + current_app.logger.info( + '[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s', + request_id, + session.session_id, + relay_first_ms, + relay_total_ms, + event_name, + ) + event_data['hxops_relay'] = { + 'first_chunk_ms': relay_first_ms, + 'total_relay_ms': relay_total_ms, + } + yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n" + if event_name in ('message_end', 'workflow_finished'): + for terminal_line in iter_handler_terminal_sse( + relay_stream_ctx, + event_data, + emitted_keys=emitted_handler_state_keys, + ): + yield terminal_line + except Exception as exc: + current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id) + payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} + yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" + + # 返回 SSE 响应,mimetype 设为 text/event-stream + return Response( + stream_with_context( + relay_stream() + ), + mimetype='text/event-stream', + headers={ + 'Cache-Control': 'no-cache', + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Connection': 'keep-alive', + # 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输 + 'X-Accel-Buffering': 'no' + } + ) + + +@chat_bp.route('/files/upload', methods=['POST']) +@require_agent_permission +def upload_chat_file(): + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500) + if str(getattr(agent, 'type', '') or '').strip().lower() != 'api': + raise ValidationError('This agent does not support file upload') + if not getattr(agent, 'dify_api_key', None): + raise ValidationError('This agent does not support file upload') + + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + + from app.services.dify import DifyService + from app.core.config.settings import Config + + params = DifyService.get_app_parameters(agent, force_refresh=True) + file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {} + system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {} + + filename = str(getattr(upload, 'filename', '') or '').strip() + mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip() + detected_type, ext = DifyService.detect_file_type(filename, mimetype) + file_type = None + normalized_allowed_types = None + normalized_allowed_methods = None + normalized_allowed_exts = None + is_new_schema = False + if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list): + is_new_schema = True + normalized_allowed_types = set( + ( + str(v or '').strip().lower() + for v in (file_upload_cfg.get('allowed_file_types') or []) + if str(v or '').strip() + ) + ) + normalized_allowed_methods = set( + ( + str(v or '').strip().lower() + for v in (file_upload_cfg.get('allowed_file_upload_methods') or []) + if str(v or '').strip() + ) + ) + exts = [] + for v in (file_upload_cfg.get('allowed_file_extensions') or []): + s = str(v or '').strip() + if not s: + continue + if s.startswith('.'): + s = s[1:] + s = s.lower().strip() + if s: + exts.append(s) + normalized_allowed_exts = set(exts) if exts else None + + if detected_type: + file_type = detected_type + else: + if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)): + file_type = 'custom' + else: + custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None + if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)): + file_type = 'custom' + else: + raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})') + + def _effective_type_methods(target_type: str) -> set[str]: + if not isinstance(file_upload_cfg, dict): + return set(normalized_allowed_methods or set()) + cfg = file_upload_cfg.get(target_type) + transfer_methods = [] + if isinstance(cfg, dict): + transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or [] + if isinstance(transfer_methods, str): + transfer_methods = [transfer_methods] + if isinstance(transfer_methods, list) and len(transfer_methods) > 0: + return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip()) + return set(normalized_allowed_methods or set()) + + def _is_type_enabled_in_new_schema(target_type: str) -> bool: + if not (is_new_schema and normalized_allowed_types): + return False + if not isinstance(file_upload_cfg, dict): + return target_type in normalized_allowed_types + cfg = file_upload_cfg.get(target_type) + if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool): + if cfg.get('enabled') is False: + return False + if cfg.get('enabled') is True: + return True + return target_type in normalized_allowed_types + + if is_new_schema and normalized_allowed_types: + if not _is_type_enabled_in_new_schema(file_type): + raise ValidationError(f'File type not enabled: {file_type}') + type_methods = _effective_type_methods(file_type) + if 'local_file' not in type_methods: + raise ValidationError('local_file upload is not enabled') + if normalized_allowed_exts: + allowed_for_type = set() + for e in normalized_allowed_exts: + t, _ = DifyService.detect_file_type(f'file.{e}', None) + if t is None: + if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)): + allowed_for_type.add(e) + continue + if t == file_type: + allowed_for_type.add(e) + if allowed_for_type and (not ext or ext not in allowed_for_type): + raise ValidationError(f'Unsupported file extension: .{ext or ""}') + else: + # legacy schema checks + type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None + if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'): + raise ValidationError(f'File type not enabled: {file_type}') + transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or [] + if isinstance(transfer_methods, str): + transfer_methods = [transfer_methods] + if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)): + raise ValidationError('local_file upload is not enabled') + + def _mb_limit_for_type() -> float | None: + merged = {} + if isinstance(system_params, dict): + merged.update(system_params) + if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict): + merged.update(file_upload_cfg.get('fileUploadConfig') or {}) + if file_type == 'image': + return merged.get('image_file_size_limit') or merged.get('file_size_limit') + if file_type == 'audio': + return merged.get('audio_file_size_limit') or merged.get('file_size_limit') + if file_type == 'video': + return merged.get('video_file_size_limit') or merged.get('file_size_limit') + return merged.get('file_size_limit') + + size_limit_mb = _mb_limit_for_type() + if size_limit_mb is not None: + try: + import os + stream = getattr(upload, 'stream', None) + if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'): + cur = stream.tell() + stream.seek(0, os.SEEK_END) + size_bytes = stream.tell() + stream.seek(cur) + limit_bytes = int(float(size_limit_mb) * 1024 * 1024) + if size_bytes > limit_bytes: + raise ValidationError(f'File too large (limit {size_limit_mb}MB)') + except ValidationError: + raise + except Exception: + pass + + base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE + dify_url = DifyService._build_files_upload_url(base_url) + headers = {'Authorization': f'Bearer {agent.dify_api_key}'} + + try: + try: + upload.stream.seek(0) + except Exception: + pass + resp = requests.post( + dify_url, + headers=headers, + files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')}, + data={'user': str(getattr(user, 'id', 'system'))}, + timeout=(5, 300), + ) + except requests.RequestException as exc: + raise ServiceUnavailableError(f'Upload failed: {exc}') + + if not resp.ok: + body = (resp.text or '')[:1500] + header_snapshot = {} + try: + for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'): + v = resp.headers.get(k) or resp.headers.get(k.title()) + if v: + header_snapshot[k] = v + except Exception: + header_snapshot = {} + current_app.logger.warning( + '[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s', + resp.status_code, + dify_url, + header_snapshot, + body, + ) + raise AppError( + code='DIFY.UPLOAD_FAILED', + message='Upload failed', + http_status=502, + details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot}, + ) + + data = resp.json() if resp.content else {} + return jsonify({ + 'id': data.get('id'), + 'name': data.get('name') or filename, + 'size': data.get('size'), + 'extension': data.get('extension') or ext, + 'mime_type': data.get('mime_type') or mimetype, + 'type': file_type, + }) + + +@chat_bp.route('/feedback', methods=['POST']) +@require_agent_permission +def submit_feedback(): + """ + 提交对回答的评分与评论 + 用途:在对话结束后,由前端发送评分(1~5)和文字意见 + 核心逻辑: + 1. 从请求体中读取 score/comment/conversation_id + 2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog + 3. 为该 ChatLog 创建或更新 Feedback 记录 + """ + data = request.get_json() or {} + score = data.get('score') + comment = data.get('comment') or '' + conversation_id = data.get('conversation_id') + if not current_app.config.get('FEEDBACK_ENABLED', True): + raise ForbiddenError('feedback is disabled') + if score is None: + raise ValidationError('score is required') + try: + score_value = int(score) + except (TypeError, ValueError): + raise ValidationError('score must be an integer') + if score_value < 1 or score_value > 5: + raise ValidationError('score must be between 1 and 5') + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500) + chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id) + if conversation_id: + chat_logs_query = chat_logs_query.filter( + or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id) + ) + + # 取最新一条对话日志 + chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first() + if not chat_log: + raise NotFoundError('ChatLog not found') + if chat_log.feedback: + chat_log.feedback.score = score_value + chat_log.feedback.comment = comment + else: + fb = Feedback(chat_log_id=chat_log.id, score=score_value, comment=comment) + db.session.add(fb) + db.session.commit() + return jsonify({'status': 'ok'}) + +@chat_bp.route('/source-file', methods=['GET']) +@require_agent_permission +def resolve_source_file(): + """ + Resolve original source download URL by Dify dataset/document IDs. + """ + dataset_id = (request.args.get('dataset_id') or '').strip() + remote_document_id = (request.args.get('remote_document_id') or '').strip() + if not dataset_id or not remote_document_id: + current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args)) + raise ValidationError('dataset_id and remote_document_id are required') + payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) + if not payload: + raise NotFoundError('source file mapping not found') + + source_ext = str(payload.get('source_ext') or '').strip().lower() + source_download_url = payload.get('source_download_url') + + return jsonify({ + 'dataset_id': dataset_id, + 'remote_document_id': remote_document_id, + 'source_filename': payload.get('source_filename'), + 'source_ext': source_ext, + 'source_download_url': source_download_url, + 'download_url_expires_at': payload.get('download_url_expires_at'), + }) + + +@chat_bp.route('/source-file-text', methods=['GET']) +@require_agent_permission +def source_file_text(): + dataset_id = (request.args.get('dataset_id') or '').strip() + remote_document_id = (request.args.get('remote_document_id') or '').strip() + if not dataset_id or not remote_document_id: + raise ValidationError('dataset_id and remote_document_id are required') + + text = _fetch_dify_text_document(dataset_id, remote_document_id) + if not text: + raise NotFoundError('failed to resolve text source file') + + filename = f'{remote_document_id}.txt' + return Response( + text, + status=200, + mimetype='text/plain; charset=utf-8', + headers={ + 'Content-Disposition': f'inline; filename="{filename}"', + 'Cache-Control': 'no-store', + }, + ) + + +@chat_bp.route('/preview-excel', methods=['GET']) +@require_agent_permission +def preview_excel(): + """ + 内网 Excel 预览接口(简版可上线)。 + 说明: + - xlsx 直接解析; + - xls 先转为 xlsx 后再解析。 + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + raise ValidationError('url is required') + if not _is_allowed_preview_url(file_url): + raise ForbiddenError('url is not allowed for preview') + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + ext = url_path_ext or name_ext + if ext and ext not in ('xlsx', 'xls'): + raise_for_status(f'unsupported file extension: {ext}', 415) + try: + limit = int(request.args.get('limit', 100)) + except ValueError: + limit = 100 + limit = max(1, min(limit, 300)) + content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024) + if err: + msg, code = err + raise_for_status(msg, code) + + detected_ext = _detect_excel_format(content or b'', ext) + if detected_ext not in ('xlsx', 'xls'): + raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415) + + try: + wb = _load_excel_workbook(content, detected_ext) + except Exception as e: + current_app.logger.warning( + "[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r", + ext, + detected_ext, + len(content or b''), + name, + file_url, + e, + ) + details: dict = {} + if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev': + details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')} + raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details) + if not wb.sheetnames: + raise_for_status('workbook has no sheets', 422) + requested_sheet = (request.args.get('sheet') or '').strip() + sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0] + ws = wb[sheet_name] + rows = [] + for row in ws.iter_rows(values_only=True): + normalized = [] + for cell in row: + if cell is None: + normalized.append('') + elif isinstance(cell, (int, float, bool)): + normalized.append(cell) + else: + normalized.append(str(cell)) + rows.append(normalized) + if len(rows) >= limit: + break + max_cols = max((len(r) for r in rows), default=0) + for r in rows: + if len(r) < max_cols: + r.extend([''] * (max_cols - len(r))) + columns = [f'COL_{i + 1}' for i in range(max_cols)] + return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit}) + +@chat_bp.route('/preview-text', methods=['GET']) +@require_agent_permission +def preview_text(): + """ + 文本类文件预览接口(内网代理)。 + 支持:md/markdown/txt/csv/vtt/properties/html/htm + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + raise ValidationError('url is required') + if not _is_allowed_preview_url(file_url): + raise ForbiddenError('url is not allowed for preview') + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + explicit_ext = (request.args.get('ext') or '').strip().lower() + ext = explicit_ext or url_path_ext or name_ext + allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'} + if ext and ext not in allowed: + raise_for_status(f'unsupported text extension: {ext}', 415) + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) + if err: + msg, code = err + raise_for_status(msg, code) + text = None + for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'): + try: + text = content.decode(enc) + break + except Exception: + continue + if text is None: + raise_for_status('failed to decode text file', 422) + return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext}) + +def _guess_ext_from_content(content: bytes, default_ext: str) -> str: + """ + 根据文件内容(Magic Bytes)纠正可能的错误扩展名 + """ + import io + import zipfile + + if not content: + return default_ext + if content.startswith(b'%PDF-'): + return 'pdf' + if content.startswith(b'PK\x03\x04'): + # ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。 + try: + with zipfile.ZipFile(io.BytesIO(content)) as zf: + names = {name.lower() for name in zf.namelist()} + if any(name.startswith('word/') for name in names): + return 'docx' + if any(name.startswith('xl/') for name in names): + return 'xlsx' + if any(name.startswith('ppt/') for name in names): + return 'pptx' + except Exception: + pass + if default_ext == 'doc': + return 'docx' + if default_ext == 'xls': + return 'xlsx' + if default_ext == 'ppt': + return 'pptx' + if default_ext in ('docx', 'xlsx', 'pptx'): + return default_ext + return 'docx' + if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'): + # OLE 复合文件,通常是 doc, xls, ppt 等。 + if default_ext == 'docx': return 'doc' + if default_ext == 'xlsx': return 'xls' + if default_ext == 'pptx': return 'ppt' + if default_ext in ('doc', 'xls', 'ppt'): return default_ext + return 'doc' + return default_ext + +@chat_bp.route('/preview-file-raw', methods=['GET']) +@require_agent_permission +def preview_file_raw(): + """ + 二进制文件内网代理预览接口。 + 用途: + - 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址; + - 尽量使用 inline 响应头,避免强制下载。 + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + raise ValidationError('url is required') + if not _is_allowed_preview_url(file_url): + raise ForbiddenError('url is not allowed for preview') + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + original_ext = url_path_ext or name_ext + ext = original_ext + is_download = request.args.get('download') == '1' + max_size = None if is_download else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) + if err: + msg, code = err + raise_for_status(msg, code) + + # 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码 + real_ext = _guess_ext_from_content(content, ext) + # 仅当内容确实是文本时,才允许按 content_type 切到 md/txt(避免 .doc OLE 被当文本渲染乱码) + normalized_ct = (content_type or '').split(';')[0].strip().lower() + if _looks_like_text_document(content): + if 'markdown' in normalized_ct: + real_ext = 'md' + elif normalized_ct.startswith('text/') and original_ext in ( + 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', + ): + real_ext = 'txt' + elif real_ext in ('md', 'markdown', 'txt') and original_ext in ( + 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', + ): + # content_type/文件名声称是文本,但载荷是 Office 二进制:以魔数扩展名为准 + real_ext = _guess_ext_from_content(content, original_ext or ext) + if real_ext != ext: + current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}") + ext = real_ext + if name and '.' in name: + name = f"{name.rsplit('.', 1)[0]}.{ext}" + elif name: + name = f"{name}.{ext}" + # 回退文本预览时,避免仍带二进制 Content-Type 导致前端按 PDF 渲染 + if ext in ('md', 'markdown', 'txt') and _looks_like_text_document(content): + if not str(content_type or '').lower().startswith('text/'): + content_type = { + 'md': 'text/markdown; charset=utf-8', + 'markdown': 'text/markdown; charset=utf-8', + 'txt': 'text/plain; charset=utf-8', + }.get(ext) + elif ext in ('md', 'markdown', 'txt') and not _looks_like_text_document(content): + # 拒绝把二进制伪装成文本扩展名 + ext = _guess_ext_from_content(content, original_ext or 'bin') or (original_ext or 'bin') + content_type = None + + # 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。 + # 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染, + # 避免在服务端走旧版转换链路导致长时间卡住。 + needs_pdf_conversion = ( + request.args.get('download') != '1' + and ext in ('doc', 'ppt', 'pptx') + ) + if needs_pdf_conversion: + try: + content = _convert_office_to_pdf(content, ext) + ext = 'pdf' + content_type = 'application/pdf' + if name and '.' in name: + name = f"{name.rsplit('.', 1)[0]}.pdf" + elif name: + name = f"{name}.pdf" + except Exception as e: + current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e) + placeholder_text = _extract_placeholder_text(content) + if placeholder_text: + content = placeholder_text.encode('utf-8') + ext = 'txt' + content_type = 'text/plain; charset=utf-8' + if name and '.' in name: + name = f"{name.rsplit('.', 1)[0]}.txt" + elif name: + name = f"{name}.txt" + current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url) + else: + raise AppError( + code='VALIDATION.UNPROCESSABLE', + message='failed to convert office file for preview', + http_status=422, + ) + + fallback_types = { + 'pdf': 'application/pdf', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xls': 'application/vnd.ms-excel', + 'csv': 'text/csv', + 'txt': 'text/plain', + 'md': 'text/markdown', + 'markdown': 'text/markdown', + 'html': 'text/html', + 'htm': 'text/html', + } + if ext == 'pdf' and not content.startswith(b'%PDF-'): + placeholder_text = _extract_placeholder_text(content) + if placeholder_text: + content = placeholder_text.encode('utf-8') + content_type = 'text/plain; charset=utf-8' + current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url) + mime = content_type or fallback_types.get(ext) or 'application/octet-stream' + from urllib.parse import quote + filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}" + encoded_filename = quote(filename) + ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}" + disposition_type = 'attachment' if is_download else 'inline' + resp = Response(content, status=200, mimetype=mime) + resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}""" + resp.headers['Cache-Control'] = 'no-store' + resp.headers['X-Preview-Actual-Ext'] = ext or '' + resp.headers['X-Preview-Original-Ext'] = original_ext or '' + return resp + + +from app.api.chat_turns import register_chat_turn_routes + +register_chat_turn_routes(chat_bp) diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index 459b0e9c..3659582d 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -1,6 +1,9 @@ """ backend/app/api/integration.py -文件用途:知识库外部集成查询接口 + +用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。 +依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。 +逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。 """ from __future__ import annotations from pathlib import Path @@ -144,6 +147,12 @@ def _kb_storage_root() -> Path: return root def _resolve_storage_path(path_value: str | None) -> Path | None: + """ + 解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。 + 核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。 + @param path_value: 数据库中的路径字符串 + @returns 合法绝对 Path,越界或空则 None + """ if not path_value: return None raw_path = Path(str(path_value)) @@ -155,6 +164,45 @@ def _resolve_storage_path(path_value: str | None) -> Path | None: return None return candidate + +def _existing_storage_path(path_value: str | None) -> Path | None: + """ + 解析存储路径且要求文件真实存在。 + 核心逻辑:先 _resolve_storage_path,再校验 is_file。 + @returns 存在的 Path,否则 None + """ + path = _resolve_storage_path(path_value) + if path is None or not path.exists() or not path.is_file(): + return None + return path + + +def _markdown_storage_path(version: KbDocumentVersion) -> Path | None: + """ + 取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。 + 核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。 + """ + for path_value in (version.cleaned_file_path, version.cleaned_preview_path): + path = _existing_storage_path(path_value) + if path is None: + continue + try: + head = path.read_bytes()[:4096] + except OSError: + continue + if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')): + current_app.logger.warning( + '[integration] skip binary cleaned path version_id=%s path=%s', + version.id, + path, + ) + continue + if b'\x00' in head: + continue + return path + return None + + def _current_version(document: KbDocument) -> KbDocumentVersion | None: versions = list(getattr(document, 'versions', []) or []) if not versions: @@ -165,13 +213,40 @@ def _document_query(): return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False)) def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None): + """ + 序列化集成侧文档元数据与可下载 URL。 + 核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md), + 避免聊天预览拿到“库有映射、盘无文件”的死链。 + """ version = version or _current_version(document) if not version: abort(404, description='No current version found.') sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)) - source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) - markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None - return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}} + source_path = _existing_storage_path(version.source_file_path) + markdown_path = _markdown_storage_path(version) + markdown_download_url = ( + _build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None + ) + if source_path is not None: + source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) + source_filename = version.source_file_name + source_ext = version.source_file_ext + elif markdown_path is not None: + # [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览 + source_download_url = markdown_download_url + stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem + source_filename = f'{stem}.md' + source_ext = 'md' + current_app.logger.info( + '[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s', + document.id, + version.id, + ) + else: + source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) + source_filename = version.source_file_name + source_ext = version.source_file_ext + return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}} def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict: return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None} @@ -196,13 +271,31 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in return payload def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]: + """ + 解析下载目标路径与文件名。 + 核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。 + @param version: 文档版本 + @param kind: source | md + @returns (绝对路径, 下载文件名) + @raises NotFoundError: 源文件与清洗稿均不存在 + """ if kind == 'source': - path = _resolve_storage_path(version.source_file_path) - if path is None: - raise NotFoundError('File not found on disk.') - filename = version.source_file_name or f'document-{version.document_id}' - return (path, filename) - preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path) + path = _existing_storage_path(version.source_file_path) + if path is not None: + filename = version.source_file_name or f'document-{version.document_id}' + return (path, filename) + preferred = _markdown_storage_path(version) + if preferred is not None: + current_app.logger.warning( + '[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s', + version.document_id, + version.id, + preferred, + ) + filename = f'document-{version.document_id}-v{version.version_no}.md' + return (preferred, filename) + raise NotFoundError('File not found on disk.') + preferred = _markdown_storage_path(version) if not preferred: abort(409, description='Markdown not ready.') filename = f'document-{version.document_id}-v{version.version_no}.md' @@ -248,6 +341,10 @@ def list_files_for_knowledge_base(knowledge_base_id: int): @integration_bp.route('/dify-file', methods=['GET']) def get_file_detail_by_dify(): + """ + 按 Dify dataset/document 反查本地知识库文件元数据。 + 核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。 + """ remote_document_id = str(request.args.get('remote_document_id') or '').strip() dataset_id = str(request.args.get('dataset_id') or '').strip() or None if not remote_document_id: @@ -258,8 +355,10 @@ def get_file_detail_by_dify(): record = record_query.first() version = record.document_version if record else None document = version.document if version else None - if not document: + if not document or not version: raise NotFoundError('No local file mapping found for the given Dify document.') + if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None: + raise NotFoundError('No readable local file for the given Dify document.') return jsonify(_serialize_integration_document(document, version=version, sync_record=record)) @integration_bp.route('/dify-files/resolve', methods=['POST']) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index edf7e440..9dd74947 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -134,6 +134,38 @@ class DifyService: return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。" return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。" + @staticmethod + def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str: + """将 Dify HTTP 错误转换为可执行的用户提示。 + + AI 触发时机:Dify 在建立 SSE 流前直接返回非 2xx 响应时调用。 + 核心逻辑:优先识别知识检索常用的 rerank 插件授权失败,避免把上游 403 误报为网络超时; + 其余状态码则给出不泄露密钥和内部地址的通用排查方向。 + + Args: + status_code: Dify HTTP 响应状态码。 + raw_body: 已截断的 Dify 错误正文,仅用于分类,不向用户原样透传。 + agent_name: 当前智能体名称。 + + Returns: + 面向最终用户的安全错误提示。 + """ + text = str(raw_body or "") + lower = text.lower() + resolved_agent_name = str(agent_name or "").strip() or "当前智能体" + if "rerank" in lower and ("403" in lower or "forbidden" in lower): + return ( + f"{resolved_agent_name}的知识检索重排服务授权失败。" + "请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。" + ) + if status_code in (401, 403): + return f"{resolved_agent_name}暂时无法访问 Dify 服务,请联系管理员检查该应用的 API Key 与服务授权。" + if status_code == 404: + return f"{resolved_agent_name}的 Dify 应用地址或应用类型配置错误,请联系管理员检查 API Base URL。" + if status_code in (429, 502, 503, 504): + return f"{resolved_agent_name}的 Dify 服务暂时不可用或繁忙,请稍后重试。" + return f"{resolved_agent_name}暂时无法完成查询,请稍后重试;如持续失败请联系管理员检查 Dify 工作流。" + @staticmethod def _merge_stream_answer_text( streamed_text: str, @@ -1028,6 +1060,23 @@ class DifyService: if retryable and attempt < max_retries: time.sleep(attempt * 2) continue + if not response.ok: + message = DifyService._friendly_upstream_error_message( + response.status_code, + response.text[:2000], + getattr(agent, 'name', None), + ) + persist_stream_chat( + { + 'event': 'error', + 'conversation_id': normalized_conversation_id, + 'answer': f"[Error: {message}]", + 'metadata': {}, + }, + 'error', + ) + yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n" + return response.raise_for_status() yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n" diff --git a/backend/app/services/hr_leave_sqlserver.py b/backend/app/services/hr_leave_sqlserver.py index 6d869efe..5bc625b9 100644 --- a/backend/app/services/hr_leave_sqlserver.py +++ b/backend/app/services/hr_leave_sqlserver.py @@ -59,7 +59,7 @@ class HRLeaveSQLServerService: _PERSON_NAME_PATTERNS = ( r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)", r"(?P[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)", - r"(?P[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)", + r"(?P[\u4e00-\u9fa5]{2,4}?).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)", ) _PERSON_NAME_STOPWORDS = { "我的", @@ -92,6 +92,10 @@ class HRLeaveSQLServerService: "部门", } _OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期" + _SALARY_CONSULTATION_PATTERN = re.compile( + r"(?:请假|休假|年假|事假|病假).{0,12}(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)" + r"|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(?:请假|休假|年假|事假|病假)" + ) @classmethod def supports(cls, query: str) -> bool: @@ -104,6 +108,10 @@ class HRLeaveSQLServerService: text = (query or "").strip() if not text: return False + # [STEP 1] 薪资/扣款是制度计算问答,必须交给 FAQ/Dify,不能进入个人假期余额 SQL。 + # [PROMPT_UPDATE] 公式、适用条件和计薪口径由知识库原文负责,后端只做路由保护。 + if cls._SALARY_CONSULTATION_PATTERN.search(text): + return False if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS): return False if any(keyword in text for keyword in cls._PROCESS_KEYWORDS): @@ -129,10 +137,10 @@ class HRLeaveSQLServerService: text = (query or "").strip() if not text: return False - if any(keyword in text for keyword in cls._SELF_KEYWORDS): - return False if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS): return True + if any(keyword in text for keyword in cls._SELF_KEYWORDS): + return False return bool(cls._extract_candidate_person_names(text)) @classmethod @@ -170,10 +178,10 @@ class HRLeaveSQLServerService: text = (query or "").strip() if not text: return False - if any(keyword in text for keyword in cls._SELF_KEYWORDS): - return False if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS): return True + if any(keyword in text for keyword in cls._SELF_KEYWORDS): + return False self_identifiers = { str(getattr(user, "real_name", None) or "").strip(), str(getattr(user, "username", None) or "").strip(), @@ -181,7 +189,8 @@ class HRLeaveSQLServerService: } self_identifiers = {value for value in self_identifiers if value} for candidate in cls._extract_candidate_person_names(text): - if candidate not in self_identifiers: + normalized_candidate = candidate.rstrip("的") + if normalized_candidate not in self_identifiers: return True return False diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 3ecd4491..f9a836ac 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -1,5 +1,9 @@ """ -Integration API client for resolving original source-file download links. +backend/app/services/integration_api.py + +用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。 +依赖:Flask request/current_app、requests、Kb* 模型。 +逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。 """ from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Optional, Tuple @@ -223,8 +227,14 @@ class IntegrationApiService: @staticmethod def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]: + """ + 从本地 KbDifySyncRecord 反查可预览下载链接。 + 核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown; + 两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。 + """ if not has_app_context(): return None + from pathlib import Path from app import db from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument @@ -251,6 +261,30 @@ class IntegrationApiService: version = record.document_version document = version.document + def _existing(path_value: str | None): + if not path_value: + return None + raw = Path(str(path_value)) + root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve() + candidate = (raw if raw.is_absolute() else (root / raw)).resolve() + try: + candidate.relative_to(root) + except ValueError: + return None + if candidate.exists() and candidate.is_file(): + return candidate + return None + + source_path = _existing(version.source_file_path) + markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path) + if source_path is None and markdown_path is None: + current_app.logger.info( + '[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s', + document.id, + version.id, + ) + return None + base_url = IntegrationApiService._request_origin_url() if not base_url: explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/') @@ -276,15 +310,25 @@ class IntegrationApiService: } token = jwt.encode(payload, secret, algorithm='HS256') + if source_path is not None: + kind = 'source' + source_filename = version.source_file_name + source_ext = version.source_file_ext + else: + kind = 'md' + stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem + source_filename = f'{stem}.md' + source_ext = 'md' + source_download_url = ( f'{base_url}/api/integration/files/{document.id}/download' - f'?kind=source&version_id={version.id}&token={token}' + f'?kind={kind}&version_id={version.id}&token={token}' ) return { "source_download_url": source_download_url, - "source_filename": version.source_file_name, - "source_ext": version.source_file_ext, + "source_filename": source_filename, + "source_ext": source_ext, "download_url_expires_at": None, "version_id": version.id, "document_id": document.id, diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index 6110830f..7b365c5d 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -7,6 +7,7 @@ from __future__ import annotations from datetime import datetime import hashlib import re +import time from pathlib import Path import requests @@ -19,6 +20,8 @@ from app.services.knowledge_cleaning.settings_service import get_kb_dify_setting _EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'}) +_DIFY_INDEXING_SUCCEEDED = frozenset({'completed', 'completed_successfully', 'succeeded', 'success'}) +_DIFY_INDEXING_FAILED = frozenset({'error', 'failed', 'failure'}) def _decode_separator(value: str) -> str: @@ -65,6 +68,9 @@ class KbDifySyncService: self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50')) self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS')) self.timeout = 60 + # Dify create/update 仅表示已接收文本,索引仍在后台异步执行。 + self.indexing_wait_seconds = 60 + self.indexing_poll_seconds = 2 def _build_process_rule(self, source_ext: str | None = None) -> dict: ext = str(source_ext or '').strip().lower().lstrip('.') @@ -137,9 +143,9 @@ class KbDifySyncService: 'retrieval_model': { 'search_method': self.search_method, 'reranking_enable': False, - 'top_k': 3, - 'score_threshold_enabled': False, - 'score_threshold': None, + 'top_k': 5, + 'score_threshold_enabled': True, + 'score_threshold': 0.25, }, } return self._request('POST', '/datasets', json=payload) @@ -243,6 +249,54 @@ class KbDifySyncService: def get_document(self, *, dataset_id: str, document_id: str) -> dict: return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}') + def wait_for_document_indexing( + self, + *, + dataset_id: str, + document_id: str, + initial_payload: dict | None = None, + ) -> dict: + """ + 确认 Dify 异步索引的最终结果,禁止把“已受理”当作“已可检索”。 + + 核心逻辑:读取创建/更新响应或文档详情中的 indexing_status,直到 completed 或 error。 + 超时也按失败处理,避免工作台把仍未可检索的文件标为同步成功。 + + Args: + dataset_id: Dify Dataset ID,不能为空。 + document_id: Dify 文档 ID,不能为空。 + initial_payload: create/update 接口的原始响应,可减少一次详情请求。 + + Returns: + 含 indexing_status 和 Dify 文档详情的字典。 + + Raises: + KbDifySyncError: Dify 索引失败、状态缺失或在限定时间内未完成。 + """ + if not dataset_id or not document_id: + raise KbDifySyncError('Dify 文档索引校验缺少 dataset_id 或 document_id') + + payload = initial_payload or {} + deadline = time.monotonic() + self.indexing_wait_seconds + last_status = '' + while True: + document = payload.get('document') if isinstance(payload, dict) else None + document = document if isinstance(document, dict) else payload + document = document if isinstance(document, dict) else {} + status = str(document.get('indexing_status') or '').strip().lower() + error = str(document.get('error') or document.get('error_message') or '').strip() + last_status = status or last_status + if status in _DIFY_INDEXING_SUCCEEDED: + return {'indexing_status': status, 'document': document} + if status in _DIFY_INDEXING_FAILED: + raise KbDifySyncError(error or f'Dify 文档索引失败(状态:{status})') + if time.monotonic() >= deadline: + raise KbDifySyncError( + f'Dify 文档索引未在 {self.indexing_wait_seconds} 秒内完成(当前状态:{last_status or "unknown"}),请在 Dify 查看文档错误后重试' + ) + time.sleep(self.indexing_poll_seconds) + payload = self.get_document(dataset_id=dataset_id, document_id=document_id) + def delete_document(self, *, dataset_id: str, document_id: str) -> None: self._request( 'DELETE', @@ -274,9 +328,30 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]: def _is_remote_document_missing(error_text: str) -> bool: + """ + 判断同步记录指向的 Dify 远端文档是否已失效。 + + Dify 在不同版本中会对已删除或不可访问的文档返回 404/not_found, + 也可能返回 400 invalid_param 和 ``Document is not available``。两种结果都表示 + 不能继续 update-by-text,调用方必须新建远端文档并刷新本地映射。 + + Args: + error_text: Dify HTTP 异常转换后的完整错误文本。 + + Returns: + 远端文档已失效时返回 True;其他 API 错误返回 False,避免掩盖配置或网络问题。 + """ + normalized_error = str(error_text or '').lower() return ( - '404' in error_text - and ('Document not found' in error_text or '"code":"not_found"' in error_text) + ('404' in normalized_error and ( + 'document not found' in normalized_error + or '"code":"not_found"' in normalized_error + )) + or ( + '400' in normalized_error + and '"code":"invalid_param"' in normalized_error + and 'document is not available' in normalized_error + ) ) @@ -290,7 +365,90 @@ def _resolve_upload_name(version: KbDocumentVersion) -> str: return f'文档-{version.document_id}' +def _save_sync_record( + *, + version: KbDocumentVersion, + dataset_id: str, + dataset_name: str, + remote_document_id: str, + remote_document_name: str | None, + sync_hash: str, + synced_by_id: int | None, + status: str, + error_message: str | None, +) -> KbDifySyncRecord: + """ + 持久化本地到 Dify 的映射及最终索引结果。 + + 核心逻辑:同一版本和远端文档复用记录;成功与失败均保存, + 让工作台能展示 Dify 的真实索引状态和原因。 + + Args: + version: 已上传且归属有效分组的文档版本。 + dataset_id: Dify Dataset ID。 + remote_document_id: Dify 文档 ID。 + status: 本地同步状态,仅传 synced 或 failed。 + error_message: Dify 索引失败详情;成功时传 None。 + + Returns: + 已 flush 的 KbDifySyncRecord。 + """ + document = version.document + group = document.group + record = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_version_id == version.id, + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .first() + ) + if not record: + record = KbDifySyncRecord( + group_id=group.id, + document_id=document.id, + document_version_id=version.id, + dataset_id=dataset_id, + dataset_name=dataset_name, + remote_document_id=remote_document_id, + remote_document_name=remote_document_name, + status=status, + sync_hash=sync_hash, + error_message=error_message, + synced_by_id=synced_by_id, + synced_at=datetime.utcnow(), + ) + add_and_flush_with_sequence_retry(record, 'kb_dify_sync_records') + return record + + record.dataset_id = dataset_id + record.dataset_name = dataset_name + record.remote_document_name = remote_document_name + record.status = status + record.sync_hash = sync_hash + record.error_message = error_message + record.synced_by_id = synced_by_id + record.synced_at = datetime.utcnow() + return record + + def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict: + """ + 同步清洗后的知识库版本,并以 Dify 最终索引结果作为成功标准。 + + 核心逻辑:上传/更新文本后轮询 Dify 的 indexing_status;仅 completed 写入 synced, + error 时持久化失败原因并抛错,由调用任务将工作台同步步骤标红。 + + Args: + document_version_id: 当前待同步的 KbDocumentVersion 主键。 + synced_by_id: 发起同步的用户 ID,可为空(自动任务)。 + + Returns: + 含 Dify 映射与 indexing_status 的同步结果。 + + Raises: + KbDifySyncError: 本地文本、Dify API 或 Dify 索引失败。 + """ version = db.session.get(KbDocumentVersion, document_version_id) if not version or not version.document or not version.document.group: raise KbDifySyncError('文档版本或关联分组不存在') @@ -318,7 +476,13 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | remote_document_id = None remote_document_name = None upload_name = _resolve_upload_name(version) - if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash: + indexing_payload: dict | None = None + if ( + existing_record + and existing_record.dataset_id == dataset_id + and existing_record.sync_hash == sync_hash + and existing_record.status == 'synced' + ): try: payload = service.get_document( dataset_id=dataset_id, @@ -326,6 +490,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | ) remote_document_id = payload.get('id') or existing_record.remote_document_id remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name + indexing_payload = payload except KbDifySyncError as exc: if not _is_remote_document_missing(str(exc)): raise @@ -337,6 +502,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') remote_document_name = payload.get('document', {}).get('name') or upload_name + indexing_payload = payload elif existing_record and existing_record.dataset_id == dataset_id: try: payload = service.update_document_by_text( @@ -357,6 +523,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id remote_document_name = payload.get('document', {}).get('name') or upload_name + indexing_payload = payload else: payload = service.create_document_by_text( dataset_id=dataset_id, @@ -366,42 +533,43 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') remote_document_name = payload.get('document', {}).get('name') or upload_name + indexing_payload = payload if not remote_document_id: raise KbDifySyncError('Dify 未返回远端文档 ID') - record = ( - db.session.query(KbDifySyncRecord) - .filter( - KbDifySyncRecord.document_version_id == version.id, - KbDifySyncRecord.remote_document_id == remote_document_id, + try: + indexing_result = service.wait_for_document_indexing( + dataset_id=dataset_id, + document_id=remote_document_id, + initial_payload=indexing_payload, ) - .first() - ) - if not record: - record = KbDifySyncRecord( - group_id=group.id, - document_id=document.id, - document_version_id=version.id, + except KbDifySyncError as exc: + _save_sync_record( + version=version, dataset_id=dataset_id, dataset_name=dataset_name, remote_document_id=remote_document_id, remote_document_name=remote_document_name, - status='synced', sync_hash=sync_hash, synced_by_id=synced_by_id, + status='failed', + error_message=str(exc), ) - add_and_flush_with_sequence_retry(record, "kb_dify_sync_records") - else: - record.dataset_id = dataset_id - record.dataset_name = dataset_name - record.remote_document_name = remote_document_name - record.status = 'synced' - record.sync_hash = sync_hash - record.error_message = None - record.synced_by_id = synced_by_id + db.session.commit() + raise - record.synced_at = datetime.utcnow() + _save_sync_record( + version=version, + dataset_id=dataset_id, + dataset_name=dataset_name, + remote_document_id=remote_document_id, + remote_document_name=remote_document_name, + sync_hash=sync_hash, + synced_by_id=synced_by_id, + status='synced', + error_message=None, + ) db.session.commit() content_changed = previous_sync_hash != sync_hash @@ -438,6 +606,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | 'remote_document_id': remote_document_id, 'remote_document_name': remote_document_name, 'sync_hash': sync_hash, + 'indexing_status': indexing_result['indexing_status'], 'source_path': source_path, } diff --git a/backend/app/services/knowledge_cleaning/settings_service.py b/backend/app/services/knowledge_cleaning/settings_service.py index 9b2b128b..f64c24e5 100644 --- a/backend/app/services/knowledge_cleaning/settings_service.py +++ b/backend/app/services/knowledge_cleaning/settings_service.py @@ -18,14 +18,16 @@ SETTING_DEFAULTS = { 'DIFY_API_KEY': '', 'KB_DIFY_PERMISSION': 'only_me', 'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality', - 'KB_DIFY_SEARCH_METHOD': 'semantic_search', + # 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。 + 'KB_DIFY_SEARCH_METHOD': 'hybrid_search', 'KB_DIFY_DOC_FORM': 'text_model', - 'KB_DIFY_PROCESS_MODE': 'automatic', + # 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。 + 'KB_DIFY_PROCESS_MODE': 'custom', 'KB_DIFY_PROCESS_MODE_EXCEL': 'custom', 'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n', 'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n', - 'KB_DIFY_SEGMENT_MAX_TOKENS': '800', - 'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50', + 'KB_DIFY_SEGMENT_MAX_TOKENS': '600', + 'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100', 'KB_DIFY_REMOVE_URLS': 'false', } diff --git a/backend/app/services/knowledge_cleaning/tasks.py b/backend/app/services/knowledge_cleaning/tasks.py index 154f54c1..16fbd22e 100644 --- a/backend/app/services/knowledge_cleaning/tasks.py +++ b/backend/app/services/knowledge_cleaning/tasks.py @@ -622,6 +622,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]: result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id) except KbDifySyncError as exc: version.status = 'ready' + version.error_message = str(exc) job.status = 'failed' job.progress = 100 job.error_message = str(exc) @@ -632,6 +633,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]: return False, str(exc) except Exception as exc: version.status = 'ready' + version.error_message = f'同步到 Dify 时发生未预期错误:{exc}' job.status = 'failed' job.progress = 100 job.error_message = f'同步到 Dify 时发生未预期错误:{exc}' @@ -642,6 +644,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]: return False, str(exc) version.status = 'synced' + version.error_message = None job.status = 'success' job.progress = 100 job.message = '已同步到 Dify' diff --git a/backend/edkb_system/controller.py b/backend/edkb_system/controller.py index c12487e3..cb5df90b 100644 --- a/backend/edkb_system/controller.py +++ b/backend/edkb_system/controller.py @@ -243,6 +243,7 @@ def _normalize_path_for_match(p: Path | str) -> str: _WORD_TIMEOUT_EXTS = {".doc", ".docx"} +_PDF_TIMEOUT_EXTS = {".pdf"} # Excel/CSV are fast and in-process; skip spawn timeout wrapper (macOS/gevent safe). _FAST_PATH_EXTS = {".xlsx", ".xls", ".csv", ".txt", ".md"} @@ -257,6 +258,19 @@ def _parse_timeout_env(name: str, default: str = "0") -> int | None: def _file_timeout_sec(file_path: Path | None = None) -> int | None: + """ + 按源文件类型选择清洗子进程的最长运行时间。 + + 图文 PDF 的 OCR、版面恢复和分段通常显著慢于 Office 文档;若直接复用全局 + 时限,大型手册会在内容尚未产出时被误杀。PDF 可用独立环境变量延长时限, + 其他格式仍使用全局上限,避免异常任务无限占用 worker。 + + Args: + file_path: 待清洗源文件路径;仅使用其扩展名进行策略选择。 + + Returns: + 正整数秒数表示启用子进程时限;None 表示该格式不使用 spawn 时限包装。 + """ suffix = str(getattr(file_path, "suffix", "") or "").lower() if suffix in _FAST_PATH_EXTS: return None @@ -264,6 +278,10 @@ def _file_timeout_sec(file_path: Path | None = None) -> int | None: specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC") if specific: return specific + if suffix in _PDF_TIMEOUT_EXTS: + specific = _parse_timeout_env("EDKB_PDF_FILE_TIMEOUT_SEC") + if specific: + return specific return _parse_timeout_env("EDKB_FILE_TIMEOUT_SEC") diff --git a/backend/tests/test_dify_sync_process_rule.py b/backend/tests/test_dify_sync_process_rule.py index c86c6b62..0568dd8e 100644 --- a/backend/tests/test_dify_sync_process_rule.py +++ b/backend/tests/test_dify_sync_process_rule.py @@ -1,4 +1,4 @@ -"""Tests for Dify sync process_rule selection (Excel custom vs default automatic).""" +"""Tests for Dify sync process_rule selection (all document types preserve complete semantic blocks).""" from __future__ import annotations from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module @@ -10,14 +10,14 @@ def _make_service(monkeypatch, **overrides): 'DIFY_API_KEY': 'dataset-test-key', 'KB_DIFY_PERMISSION': 'only_me', 'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality', - 'KB_DIFY_SEARCH_METHOD': 'semantic_search', + 'KB_DIFY_SEARCH_METHOD': 'hybrid_search', 'KB_DIFY_DOC_FORM': 'text_model', - 'KB_DIFY_PROCESS_MODE': 'automatic', + 'KB_DIFY_PROCESS_MODE': 'custom', 'KB_DIFY_PROCESS_MODE_EXCEL': 'custom', 'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n', 'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n', - 'KB_DIFY_SEGMENT_MAX_TOKENS': '800', - 'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50', + 'KB_DIFY_SEGMENT_MAX_TOKENS': '600', + 'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100', 'KB_DIFY_REMOVE_URLS': 'false', } settings.update(overrides) @@ -31,15 +31,18 @@ def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch): assert rule['mode'] == 'custom' assert rule['rules']['segmentation']['separator'] == '\n\n' - assert rule['rules']['segmentation']['max_tokens'] == 800 - assert rule['rules']['segmentation']['chunk_overlap'] == 50 + # 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。 + assert rule['rules']['segmentation']['max_tokens'] == 600 + assert rule['rules']['segmentation']['chunk_overlap'] == 100 assert rule['rules']['pre_processing_rules'][1]['enabled'] is False -def test_build_process_rule_docx_defaults_to_automatic(monkeypatch): +def test_build_process_rule_docx_uses_custom_semantic_blocks(monkeypatch): service = _make_service(monkeypatch) rule = service._build_process_rule('docx') - assert rule == {'mode': 'automatic'} + # 断言制度类文档的标题、规则、例外条件保留在同一个检索片段中。 + assert rule['mode'] == 'custom' + assert rule['rules']['segmentation']['separator'] == '\n\n' def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch): @@ -65,7 +68,7 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch): process_rule = captured['json']['process_rule'] assert process_rule['mode'] == 'custom' assert process_rule['rules']['segmentation']['separator'] == '\n\n' - assert process_rule['rules']['segmentation']['max_tokens'] == 800 + assert process_rule['rules']['segmentation']['max_tokens'] == 600 def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch): @@ -78,6 +81,59 @@ def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch): assert remove_urls['enabled'] is True +def test_wait_for_document_indexing_rejects_dify_error(monkeypatch): + service = _make_service(monkeypatch) + + try: + service.wait_for_document_indexing( + dataset_id='dataset-001', + document_id='document-001', + initial_payload={ + 'document': { + 'id': 'document-001', + 'indexing_status': 'error', + 'error': 'embedding credential invalid', + }, + }, + ) + except dify_sync_module.KbDifySyncError as exc: + # 断言 Dify 的原始原因被保留,供工作台展示而不是误报同步成功。 + assert 'embedding credential invalid' in str(exc) + else: + raise AssertionError('Dify indexing error must fail the local sync') + + +def test_wait_for_document_indexing_accepts_completed_status(monkeypatch): + service = _make_service(monkeypatch) + result = service.wait_for_document_indexing( + dataset_id='dataset-001', + document_id='document-001', + initial_payload={'document': {'id': 'document-001', 'indexing_status': 'completed'}}, + ) + + # completed 是唯一可将本地同步记录写为 synced 的终态。 + assert result['indexing_status'] == 'completed' + + +def test_remote_document_not_available_is_recreated(monkeypatch): + """400 invalid_param 的不可用文档错误必须触发创建新远端文档的恢复流程。""" + error = ( + 'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text ' + 'failed: 400 {"code":"invalid_param","message":"Document is not available","status":400}' + ) + + # 断言该 Dify 版本特有的 400 响应不会被当成不可恢复的同步失败。 + assert dify_sync_module._is_remote_document_missing(error) is True + + +def test_remote_document_other_invalid_parameter_is_not_treated_as_missing(): + """非文档失效的参数错误仍应原样失败,避免错误地重复创建文档。""" + error = 'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text failed: 400 {"code":"invalid_param","message":"Invalid process rule","status":400}' + + # 断言只有精确的“文档不可用”语义才走自动恢复分支。 + assert dify_sync_module._is_remote_document_missing(error) is False + + def test_resolve_source_file_ext_from_filename(): class _Version: source_file_ext = None diff --git a/backend/tests/test_dify_token_usage.py b/backend/tests/test_dify_token_usage.py index 2b30f6c3..3ebe53c2 100644 --- a/backend/tests/test_dify_token_usage.py +++ b/backend/tests/test_dify_token_usage.py @@ -78,6 +78,16 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。' +def test_friendly_upstream_error_message_identifies_rerank_authorization_failure(): + """断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。""" + message = DifyService._friendly_upstream_error_message( + 400, + 'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank', + agent_name='通用入口', + ) + assert message == '通用入口的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。' + + def test_persist_stream_chat_record_uses_workflow_finished_tokens(app): """workflow_finished 首次落库应写入 data.total_tokens。""" with app.app_context(): diff --git a/backend/tests/test_edkb_file_timeout.py b/backend/tests/test_edkb_file_timeout.py index 0d5e2cfb..0304636d 100644 --- a/backend/tests/test_edkb_file_timeout.py +++ b/backend/tests/test_edkb_file_timeout.py @@ -18,6 +18,14 @@ def test_word_still_uses_word_timeout(monkeypatch): assert _file_timeout_sec(Path('manual.docx')) == 420 +def test_pdf_uses_dedicated_timeout_for_figure_rich_handbooks(monkeypatch): + monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '300') + monkeypatch.setenv('EDKB_PDF_FILE_TIMEOUT_SEC', '900') + + # 断言大型图文手册不会被通用 300 秒时限提前终止。 + assert _file_timeout_sec(Path('mechanical-design-handbook.pdf')) == 900 + + def test_other_formats_use_global_timeout(monkeypatch): monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180') assert _file_timeout_sec(Path('slides.pptx')) == 180 diff --git a/backend/tests/test_file_check_tools.py b/backend/tests/test_file_check_tools.py index 7c0bb94e..d8e3efbd 100644 --- a/backend/tests/test_file_check_tools.py +++ b/backend/tests/test_file_check_tools.py @@ -1527,7 +1527,7 @@ def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeyp monkeypatch.setattr( dify_sync_module.KbDifySyncService, 'create_document_by_text', - lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name}}, + lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name, 'indexing_status': 'completed'}}, ) with app.app_context(): diff --git a/backend/tests/test_hr_leave_sqlserver_support.py b/backend/tests/test_hr_leave_sqlserver_support.py index ed672487..8f01d6f6 100644 --- a/backend/tests/test_hr_leave_sqlserver_support.py +++ b/backend/tests/test_hr_leave_sqlserver_support.py @@ -16,6 +16,13 @@ def test_supports_rejects_leave_process_questions(): assert not HRLeaveSQLServerService.supports("年假制度是什么") +def test_supports_rejects_salary_calculation_questions(): + # 断言:制度扣薪问题必须走 FAQ/Dify,不能触发 HR 假期余额查询。 + assert not HRLeaveSQLServerService.supports("请病假怎么扣钱") + assert not HRLeaveSQLServerService.supports("请假扣多少薪资") + assert not HRLeaveSQLServerService.supports("请假扣款计算公式") + + def test_supports_other_person_leave_queries_for_guardrail(): assert HRLeaveSQLServerService.supports("张三还有多少假期") assert HRLeaveSQLServerService.supports("曹惠鹏还有多少假期") diff --git a/backend/tests/test_integration_source_fallback.py b/backend/tests/test_integration_source_fallback.py new file mode 100644 index 00000000..502f638f --- /dev/null +++ b/backend/tests/test_integration_source_fallback.py @@ -0,0 +1,127 @@ +""" +backend/tests/test_integration_source_fallback.py + +用途:验证源文件缺失时 integration 下载与序列化回退到清洗 Markdown。 +依赖:pytest、kb 模型与 integration 路由。 +逻辑:模拟磁盘无 source、有 cleaned md,断言 kind=source 仍可读且序列化返回 .md。 +""" +from __future__ import annotations + +from pathlib import Path + +from app import db +from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, User + + +def _configure(app, tmp_path: Path) -> Path: + root = tmp_path / 'kb-storage' + root.mkdir(parents=True, exist_ok=True) + app.config.update( + SECRET_KEY='test-secret-key-with-sufficient-length-123456', + KB_STORAGE_ROOT=str(root), + WECOM_PUBLIC_BASE_URL='https://ai.example.com', + INTEGRATION_API_KEY='test-integration-key', + INTEGRATION_API_MODE='local', + ) + return root + + +def _ensure_admin() -> User: + user = db.session.query(User).filter_by(username='admin').first() + if user: + return user + user = User(username='admin', email='admin@example.com', role='admin', status='active') + user.set_password('password123') + db.session.add(user) + db.session.commit() + return user + + +def _seed_doc_with_missing_source(root: Path) -> tuple[KbDocument, KbDocumentVersion]: + """创建文档:source_file_path 指向不存在文件,cleaned md 真实存在。""" + _ensure_admin() + group = KbGroup(name='fallback-group', description='t', is_active=True) + db.session.add(group) + db.session.flush() + + document = KbDocument( + group_id=group.id, + title='员工入职须知', + status='ready', + source_type='upload', + is_deleted=False, + ) + db.session.add(document) + db.session.flush() + + missing_source = root / 'docs' / 'missing-source.pdf' + cleaned = root / 'docs' / 'cleaned.md' + cleaned.parent.mkdir(parents=True, exist_ok=True) + cleaned.write_text('# 入职须知\n\n欢迎加入。', encoding='utf-8') + + version = KbDocumentVersion( + document_id=document.id, + version_no=1, + status='ready', + is_current=True, + source_file_name='员工入职须知.pdf', + source_file_path=str(missing_source), + source_file_ext='pdf', + source_file_size=12, + sha256='abc', + cleaned_file_path=str(cleaned), + ) + db.session.add(version) + db.session.flush() + + sync = KbDifySyncRecord( + group_id=group.id, + document_id=document.id, + document_version_id=version.id, + dataset_id='ds-fallback', + remote_document_id='remote-fallback', + status='synced', + ) + db.session.add(sync) + db.session.commit() + return document, version + + +def test_download_source_falls_back_to_markdown(app, client, tmp_path): + """断言:kind=source 时源文件不存在,仍返回清洗 Markdown 内容。""" + root = _configure(app, tmp_path) + with app.app_context(): + document, version = _seed_doc_with_missing_source(root) + document_id = document.id + version_id = version.id + + response = client.get( + f'/api/integration/files/{document_id}/download', + headers={'X-Integration-Key': 'test-integration-key'}, + query_string={'kind': 'source', 'version_id': version_id}, + ) + assert response.status_code == 200, response.get_data(as_text=True) + body = response.get_data(as_text=True) + assert '入职须知' in body + assert '欢迎加入' in body + + +def test_serialize_prefers_markdown_when_source_missing(app, client, tmp_path): + """断言:dify-file 在源文件缺失时返回 kind=md 与 .md 扩展名。""" + root = _configure(app, tmp_path) + with app.app_context(): + _seed_doc_with_missing_source(root) + + response = client.get( + '/api/integration/dify-file', + headers={'X-Integration-Key': 'test-integration-key'}, + query_string={ + 'dataset_id': 'ds-fallback', + 'remote_document_id': 'remote-fallback', + }, + ) + assert response.status_code == 200, response.get_json() + payload = response.get_json() + assert payload['source_ext'] == 'md' + assert str(payload['source_filename']).endswith('.md') + assert 'kind=md' in str(payload['source_download_url']) diff --git a/backend/tests/test_kb_migration_flow.py b/backend/tests/test_kb_migration_flow.py index 62aaa41d..cc3d7a0a 100644 --- a/backend/tests/test_kb_migration_flow.py +++ b/backend/tests/test_kb_migration_flow.py @@ -115,7 +115,7 @@ def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path): monkeypatch.setattr( dify_sync_module.KbDifySyncService, 'create_document_by_text', - lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}}, + lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_test_001', 'name': name, 'indexing_status': 'completed'}}, ) sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) @@ -159,7 +159,7 @@ def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_ monkeypatch.setattr( dify_sync_module.KbDifySyncService, 'create_document_by_text', - lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}}, + lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_integration_001', 'name': name, 'indexing_status': 'completed'}}, ) sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) @@ -232,7 +232,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke monkeypatch.setattr( dify_sync_module.KbDifySyncService, 'create_document_by_text', - lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}}, + lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_old_001', 'name': name, 'indexing_status': 'completed'}}, ) first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) @@ -252,7 +252,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke monkeypatch.setattr( dify_sync_module.KbDifySyncService, 'create_document_by_text', - lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}}, + lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_new_001', 'name': name, 'indexing_status': 'completed'}}, ) second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) diff --git a/docker-compose.yml b/docker-compose.yml index 1c92d4e0..9e154728 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -44,16 +44,22 @@ services: - KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker} - KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2} # kb-worker 自动回收长时间 running 的任务(秒) +<<<<<<< HEAD - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900} # 采购合同异步审核:清洗产物与任务/模型输入保护 - PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract} - PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600} - PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000} - PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160} +======= + - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-1200} +>>>>>>> e7ff6bc2 (fix(platform): 汇总知识库问答与图表展示修复) # LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测) - EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice} # LibreOffice 单次格式转换超时(秒) - EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600} + # 图文 PDF 可能包含 OCR/版面恢复;独立时限避免被通用清洗上限提前终止 + - EDKB_PDF_FILE_TIMEOUT_SEC=${EDKB_PDF_FILE_TIMEOUT_SEC:-900} # 固资履历:必须注入 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:-} @@ -116,16 +122,22 @@ services: - KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker} - KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2} # kb-worker 自动回收长时间 running 的任务(秒) +<<<<<<< HEAD - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900} # 采购合同异步审核:Worker 与后端必须指向同一持久化目录 - PROCUREMENT_CONTRACT_STORAGE_ROOT=${PROCUREMENT_CONTRACT_STORAGE_ROOT:-/app/data/procurement_contract} - PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS=${PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS:-600} - PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS=${PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS:-120000} - PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES=${PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES:-160} +======= + - KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-1200} +>>>>>>> e7ff6bc2 (fix(platform): 汇总知识库问答与图表展示修复) # LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测) - EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice} # LibreOffice 单次格式转换超时(秒) - EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600} + # 与 API 容器保持一致,确保 worker 实际读取到 PDF 专用清洗时限 + - EDKB_PDF_FILE_TIMEOUT_SEC=${EDKB_PDF_FILE_TIMEOUT_SEC:-900} extra_hosts: - "host.docker.internal:host-gateway" volumes: diff --git a/docs/demand.md b/docs/demand.md index 0704f112..e0d45089 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -132,6 +132,7 @@ - 员工在 `企业知识库` 或 `ERP知识库` 中,针对“我还有多少假期”“我的年假还有多少”等强意图问题,可以直接获取本人假期数据。 - 流程/制度类问题仍继续走知识库问答,不进入数据库强查询。 +- 薪资扣除、福利计算等制度计算问题(如“请假扣多少薪资”“请假如何扣薪”)不得触发请假申请表单,应优先检索知识库并返回权威计算公式及适用条件。 ### 5.2 申请类目标 diff --git a/docs/funclist.md b/docs/funclist.md index f1beb410..336d8d7a 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -1,5 +1,10 @@ # 智能HR请假管理功能清单 +## 知识库同步状态校验 + +- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。 +- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。 + ## 设备维保助手 | 功能项 | 状态 | 说明 | @@ -221,6 +226,8 @@ - 我要请明天下午假 - 帮我提一个请假单 +制度计算类问法(例如“请假扣多少薪资”“请假扣薪计算公式”)不属于申请意图,必须继续进入 FAQ/Dify 知识库问答,返回制度原文中的计算公式。 + #### 功能点 - 识别“申请类意图” @@ -441,6 +448,7 @@ - 如何请假 - 请假制度有哪些 - 年假规则是什么 +- 请假扣多少薪资 / 请假扣薪计算公式 ## 4. 数据源清单 diff --git a/docs/kb-excel-dify-chunking.md b/docs/kb-excel-dify-chunking.md new file mode 100644 index 00000000..79e12646 --- /dev/null +++ b/docs/kb-excel-dify-chunking.md @@ -0,0 +1,176 @@ +# 知识库 Excel/CSV 切块与 Dify 同步 + +> 说明 Excel/CSV 清洗成 Markdown 后如何与 Dify custom 分段配合,以及版本目录下调试产物路径。 + +--- + +## 1. 问题背景 + +知识库 Excel(如 RoHS/供应商排程宽表)经 edkb 清洗成 Markdown 后,同步 Dify 时若使用默认 `process_rule.mode=automatic`,宽表 pipe 行或长段落会被 Dify 按 token/标点切散,导致**同一数据行字段落入不同 segment**,Hit testing 检索时上下文不完整。 + +典型症状: + +- 问「某供应商编码 + 物料」命中片段只有半行字段; +- Dify 文档分段数远大于 Excel 数据行数,或一行被拆成多段。 + +--- + +## 2. 改造后数据流 + +```text +上传 xlsx/csv + → edkb loader_excel / loader_csv + → table_linearize(宽表行文本化 / 窄表 pipe 行 \n\n 分隔) + → document.md(写入 KB 版本目录) + → [可选] 04_chunks.jsonl / chunks/(调试,不传 Dify) + → sync_dify:create-by-text / update-by-text + → Dify process_rule.mode=custom(Excel/CSV 专用,separator=\n\n) +``` + +### table_linearize 输出规则(摘要) + +| 表类型 | 条件 | 输出格式 | +| --- | --- | --- | +| 条件/处理/责任表 | 表头含「条件」「处理」等关键词 | 每条 bullet 之间 `\n\n` | +| 窄表 | 列数 ≤ 8 | 表头块 + 每个数据行单独 `\| ... \|` 块,行间 `\n\n` | +| 宽表 | 列数 > 8 | `- 【行】列1=值1;列2=值2;...`,行间 `\n\n` | + +示例(宽表,与 RoHS 排程类文件一致): + +```markdown +## Sheet: result + +- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;... + +- 【行】供应商编码=VCCD00027;供应商名称=沃顿;... +``` + +--- + +## 3. 配置项(KB_DIFY_*) + +可通过 **环境变量** 或管理台 **AppSetting** 覆盖;读取入口:`get_kb_dify_settings()`。 + +| 键 | 默认值 | 含义 | +| --- | --- | --- | +| `KB_DIFY_PROCESS_MODE` | `custom` | 非 Excel/CSV 文档的 Dify 分段模式;按空行保留标题、规则和例外条件组成的完整知识单元 | +| `KB_DIFY_PROCESS_MODE_EXCEL` | `custom` | xlsx / xls / csv 专用分段模式 | +| `KB_DIFY_SEGMENT_SEPARATOR` | `\n\n`(env 写 `\\n\\n`) | custom 模式通用分隔符 | +| `KB_DIFY_SEGMENT_SEPARATOR_EXCEL` | `\n\n` | Excel/CSV custom 分隔符,与 table_linearize 对齐 | +| `KB_DIFY_SEGMENT_MAX_TOKENS` | `600` | custom 模式 max_tokens | +| `KB_DIFY_SEGMENT_CHUNK_OVERLAP` | `100` | custom 模式 chunk_overlap,保留相邻段落的必要上下文 | +| `KB_DIFY_REMOVE_URLS` | `false` | 映射 Dify `remove_urls_emails`;RoHS 等表含 PDF 链接,默认关闭 | + +`.env` 示例: + +```bash +KB_DIFY_PROCESS_MODE=automatic +KB_DIFY_PROCESS_MODE_EXCEL=custom +KB_DIFY_SEGMENT_SEPARATOR_EXCEL=\n\n +KB_DIFY_SEGMENT_MAX_TOKENS=800 +KB_DIFY_SEGMENT_CHUNK_OVERLAP=50 +KB_DIFY_REMOVE_URLS=false +``` + +--- + +## 4. 版本目录与调试文件 + +清洗完成后,单版本目录结构(相对 `backend/data/kb/` 或部署挂载路径): + +```text +group_XXXX/document_XXXXXX/vXXX/ + su_schedule_5.xlsx # 原始上传 + document.md # 清洗结果(sync_dify 读取此文件) + document_preview.md # 可选,含图片预览时 + 04_chunks.jsonl # 可选,edkb 切块调试(不传 Dify) + chunks/ + chunk_0000.md + chunk_0001.md + ... +``` + +- `document.md`:权威同步文本; +- `04_chunks.jsonl`:edkb export 阶段产物,一行一个 chunk JSON,便于与 Dify segment 列表对照; +- 若清洗失败回退占位,会出现 `*.preview.txt`(含 `clean_status=placeholder_success`),**不应**作为 Dify 同步源。 + +--- + +## 5. 手动验收(curl) + +对已有 dataset 创建文本文档,模拟 Excel custom 分段(需替换 `DATASET_ID`、`API_KEY`): + +```bash +curl -X POST "http:///v1/datasets//document/create-by-text" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{ + "name": "excel-chunk-test.md", + "text": "## Sheet: result\n\n- 【行】列1=a;列2=b。\n\n- 【行】列1=c;列2=d。", + "indexing_technique": "high_quality", + "doc_form": "text_model", + "process_rule": { + "mode": "custom", + "rules": { + "pre_processing_rules": [ + {"id": "remove_extra_spaces", "enabled": true}, + {"id": "remove_urls_emails", "enabled": false} + ], + "segmentation": { + "separator": "\n\n", + "max_tokens": 800, + "chunk_overlap": 50 + } + } + } + }' +``` + +--- + +## 6. 对比 Dify 分段与本地 jsonl + +1. 打开 Dify 知识库 → 该文档 → **分段列表**,记录 segment 数量与首段内容; +2. 打开版本目录 `04_chunks.jsonl`,统计非空行数:`wc -l 04_chunks.jsonl`; +3. 宽表场景:segment 数应接近 **数据行数**(每行一条 `【行】` bullet,经 `\n\n` 切开); +4. 在 Dify **Hit testing** 用表中存在的「供应商编码 + 物料名称」提问,应命中包含完整行字段的片段。 + +--- + +## 7. 回滚 + +| 层级 | 做法 | +| --- | --- | +| Dify 分段 | 设 `KB_DIFY_PROCESS_MODE_EXCEL=automatic`,并对已有 Excel 文档 **重新 sync_dify** | +| 清洗格式 | git revert `table_linearize` 相关提交(document.md 格式恢复旧行为) | +| 调试文件 | 忽略 `04_chunks.jsonl`,不影响线上同步 | + +> **发版说明**:环境变量变更后,**已有 Excel 文档需触发重新 sync_dify** 才会应用新的 `process_rule`;仅重新清洗不会更新 Dify 远端分段规则。 + +--- + +## 8. 本地开发注意 + +- API 与 KB worker 须使用同一虚拟环境: + + ```bash + cd backend && source .venv/bin/activate + python run.py # 终端 1 + python worker_kb.py # 终端 2 + ``` + +- `.env.shared` 中 `EDKB_FILE_TIMEOUT_SEC` 对 Word 等慢格式启用 spawn 超时;**Excel/CSV 已在代码中豁免**,避免 macOS 本地 `Operation not permitted`。 +- 相关代码:`edkb_system/skills/table_linearize.py`、`app/services/knowledge_cleaning/dify_sync_service.py`、`edkb_adapter.py`。 + +--- + +## 9. 相关测试 + +```bash +cd backend && source .venv/bin/activate +python -m pytest tests/test_dify_sync_process_rule.py \ + tests/test_table_linearize.py \ + tests/test_kb_excel_cleaning.py \ + tests/test_edkb_adapter_chunks.py \ + tests/test_edkb_file_timeout.py -q +``` diff --git a/docs/knowledge_base_runtime_deploy.md b/docs/knowledge_base_runtime_deploy.md new file mode 100644 index 00000000..04a12b3c --- /dev/null +++ b/docs/knowledge_base_runtime_deploy.md @@ -0,0 +1,175 @@ +# 主平台知识库运行时部署说明 + +## 目标 + +将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。 + +当前主平台 `docker-compose.yml` 已接入: + +- `kb-redis` +- `hxops-backend` +- `hxops-kb-worker` +- `hxops-frontend` +- 共享卷 `hxops_runtime_data` + +## 容器职责 + +### `hxops-backend` + +- 提供主平台 API +- 提供知识库 API:`/api/kb/*` +- 提供集成 API:`/api/integration/*` +- 挂载知识库存储根目录到 `/app/data` + +### `hxops-kb-worker` + +- 轮询执行知识库 `clean` 任务 +- 复用后端镜像,避免维护第二套依赖 +- 与后端共享数据库、Redis、知识库存储卷 + +### `kb-redis` + +- 提供知识库异步任务所需 Redis +- 当前主要用于主平台知识库运行时接入与后续队列化扩展 + +## 关键环境变量 + +部署主平台知识库运行时时,至少确认以下变量: + +| 变量名 | 用途 | 建议值/说明 | +| --- | --- | --- | +| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 | +| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 | +| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` | +| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` | +| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` | +| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 | +| `KB_JOB_RUNNING_TIMEOUT_SECONDS` | running 任务超时回收 | 图文 PDF 建议 `1200`,必须大于 `EDKB_PDF_FILE_TIMEOUT_SEC` | +| `EDKB_SOFFICE_TIMEOUT_SEC` | LibreOffice 转换超时 | 默认 `120` | +| `EDKB_PDF_FILE_TIMEOUT_SEC` | 图文 PDF 清洗总超时 | 建议 `900`;应小于 `KB_JOB_RUNNING_TIMEOUT_SECONDS`,避免 PDF OCR/版面恢复被通用时限提前中止 | +| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` | +| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 | +| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 | +| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 | +| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 | +| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 | +| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` | +| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` | +| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 | +| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 | + +补充说明: + +- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。 +- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。 +- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。 +- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。 +- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。 +- OCR 依赖(OpenCV/RapidOCR)在 `backend/requirements-ocr.txt`,由 `backend/Dockerfile` 分步安装,避免同时下载 `opencv-python` 与 `opencv-python-headless` 两个大 wheel。 +- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。 +- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。 +- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。 + +## 启动步骤 + +### 1. 构建并启动 + +```bash +docker compose up -d --build +``` + +若使用私有镜像仓库,可先设置: + +```bash +$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine" +$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim" +$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine" +$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine" +$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple" +docker compose up -d --build +``` + +若需要同时启用内置 Redis,再改为: + +```bash +docker compose --profile kb-redis up -d --build +``` + +### 2. 执行数据库迁移 + +```bash +docker compose exec hxops-backend flask db upgrade +``` + +### 3. 检查服务状态 + +```bash +docker compose ps +``` + +预期: + +- `hxops-backend` 为 `Up` +- `hxops-kb-worker` 为 `Up`(与 backend 共用镜像;Jenkins/`deploy_compose.sh` 在后端变更时会一并重建) +- `hxops-frontend` 为 `Up` + +若启用了 `kb-redis` profile,则额外确认: + +- `kb-redis` 为 `Up` + +### 4. 检查 worker 日志 + +```bash +docker compose logs -f hxops-kb-worker +``` + +预期可见: + +```text +[kb-worker] started, poll_seconds=2.0 +``` + +## 端口与卷 + +当前主平台容器端口关系: + +- 宿主机 `5002` -> `hxops-backend:5000` +- 宿主机 `8890` -> `hxops-frontend:80` + +当前关键卷: + +- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录 +- `hxops_redis_data`:Redis 持久化数据 + +## 切换前检查 + +切换 `xinxin2` 运行时前,至少确认: + +1. 主平台已完成数据库迁移 +2. 主平台后台可正常打开知识库管理页 +3. 上传文件后会生成 `upload/clean` 任务 +4. `hxops-kb-worker` 能持续消费待执行任务 +5. Dify 设置已在主平台管理端保存并通过健康检查 +6. 聊天侧 `INTEGRATION_API_MODE=local` +7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名 + +## 切换后冒烟清单 + +建议按顺序验证: + +1. 登录主平台并进入知识库工作台 +2. 新建一个分组和一个文档条目 +3. 上传一个 `txt` 或 `md` 文件 +4. 确认任务状态从 `pending/running` 进入 `success` +5. 在文档详情里触发一次 Dify 同步 +6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射 +7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台 + +## 常见注意事项 + +- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。 +- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。 +- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。 +- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。 +- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。 +- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0d168b1b..5a1ef991 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -38,7 +38,7 @@ }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", - "resolved": "https://mirrors.tencent.com/npm/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "resolved": "https://registry.npmmirror.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", "license": "MIT", "engines": { @@ -49,30 +49,30 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.27.1", - "resolved": "https://mirrors.tencent.com/npm/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", - "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://mirrors.tencent.com/npm/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.29.0", - "resolved": "https://mirrors.tencent.com/npm/@babel/parser/-/parser-7.29.0.tgz", - "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", "license": "MIT", "dependencies": { - "@babel/types": "^7.29.0" + "@babel/types": "^7.29.7" }, "bin": { "parser": "bin/babel-parser.js" @@ -82,34 +82,34 @@ } }, "node_modules/@babel/types": { - "version": "7.29.0", - "resolved": "https://mirrors.tencent.com/npm/@babel/types/-/types-7.29.0.tgz", - "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@emnapi/core": { - "version": "1.8.1", - "resolved": "https://mirrors.tencent.com/npm/@emnapi/core/-/core-1.8.1.tgz", - "integrity": "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg==", + "version": "1.11.1", + "resolved": "https://registry.npmmirror.com/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.1.0", + "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.8.1", - "resolved": "https://mirrors.tencent.com/npm/@emnapi/runtime/-/runtime-1.8.1.tgz", - "integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==", + "version": "1.11.1", + "resolved": "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", "dev": true, "license": "MIT", "optional": true, @@ -118,9 +118,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.1.0", - "resolved": "https://mirrors.tencent.com/npm/@emnapi/wasi-threads/-/wasi-threads-1.1.0.tgz", - "integrity": "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==", + "version": "1.2.2", + "resolved": "https://registry.npmmirror.com/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", "dev": true, "license": "MIT", "optional": true, @@ -129,44 +129,61 @@ } }, "node_modules/@intlify/core-base": { - "version": "11.2.8", - "resolved": "https://mirrors.tencent.com/npm/@intlify/core-base/-/core-base-11.2.8.tgz", - "integrity": "sha512-nBq6Y1tVkjIUsLsdOjDSJj4AsjvD0UG3zsg9Fyc+OivwlA/oMHSKooUy9tpKj0HqZ+NWFifweHavdljlBLTwdA==", + "version": "11.4.7", + "resolved": "https://registry.npmmirror.com/@intlify/core-base/-/core-base-11.4.7.tgz", + "integrity": "sha512-MSB/sBKwEWJTILvQIhg2rnIcwPpLayo3wGwvVA+dJTNeUBD9GoqQgAaSOLdI9iOPDHCm9YoVnLqpfzza98MpkQ==", "license": "MIT", "dependencies": { - "@intlify/message-compiler": "11.2.8", - "@intlify/shared": "11.2.8" + "@intlify/devtools-types": "11.4.7", + "@intlify/message-compiler": "11.4.7", + "@intlify/shared": "11.4.7" }, "engines": { - "node": ">= 16" + "node": ">= 22" + }, + "funding": { + "url": "https://github.com/sponsors/kazupon" + } + }, + "node_modules/@intlify/devtools-types": { + "version": "11.4.7", + "resolved": "https://registry.npmmirror.com/@intlify/devtools-types/-/devtools-types-11.4.7.tgz", + "integrity": "sha512-GSz+J+hqH+AEpAHIYya6fSufS30OaMnG39HiZX7DmGKi3+aaLvassCfsXENEc4Wr4m68q2YP0QdMdB3D9UeAXg==", + "license": "MIT", + "dependencies": { + "@intlify/core-base": "11.4.7", + "@intlify/shared": "11.4.7" + }, + "engines": { + "node": ">= 22" }, "funding": { "url": "https://github.com/sponsors/kazupon" } }, "node_modules/@intlify/message-compiler": { - "version": "11.2.8", - "resolved": "https://mirrors.tencent.com/npm/@intlify/message-compiler/-/message-compiler-11.2.8.tgz", - "integrity": "sha512-A5n33doOjmHsBtCN421386cG1tWp5rpOjOYPNsnpjIJbQ4POF0QY2ezhZR9kr0boKwaHjbOifvyQvHj2UTrDFQ==", + "version": "11.4.7", + "resolved": "https://registry.npmmirror.com/@intlify/message-compiler/-/message-compiler-11.4.7.tgz", + "integrity": "sha512-bHxmh7n94N4N1evADeb7XTkc3jTw6Ki5biMFZVSX6Jmk+iehy8/maeH2XUsBI27rtKIK+Hzc6QnVAKggUwylKw==", "license": "MIT", "dependencies": { - "@intlify/shared": "11.2.8", + "@intlify/shared": "11.4.7", "source-map-js": "^1.0.2" }, "engines": { - "node": ">= 16" + "node": ">= 22" }, "funding": { "url": "https://github.com/sponsors/kazupon" } }, "node_modules/@intlify/shared": { - "version": "11.2.8", - "resolved": "https://mirrors.tencent.com/npm/@intlify/shared/-/shared-11.2.8.tgz", - "integrity": "sha512-l6e4NZyUgv8VyXXH4DbuucFOBmxLF56C/mqh2tvApbzl2Hrhi1aTDcuv5TKdxzfHYmpO3UB0Cz04fgDT9vszfw==", + "version": "11.4.7", + "resolved": "https://registry.npmmirror.com/@intlify/shared/-/shared-11.4.7.tgz", + "integrity": "sha512-OtjPZan3No2OZZFnMUiCVsXC6+j+XRwEywaFDk0AoayAbLuPesyDloXhJZLl9JUl5vHZeQUkYSbEA8VX+CWMjg==", "license": "MIT", "engines": { - "node": ">= 16" + "node": ">= 22" }, "funding": { "url": "https://github.com/sponsors/kazupon" @@ -174,7 +191,7 @@ }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", - "resolved": "https://mirrors.tencent.com/npm/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "license": "MIT", "dependencies": { @@ -184,7 +201,7 @@ }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", - "resolved": "https://mirrors.tencent.com/npm/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "license": "MIT", "engines": { @@ -193,13 +210,13 @@ }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", - "resolved": "https://mirrors.tencent.com/npm/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "license": "MIT" }, "node_modules/@jridgewell/trace-mapping": { "version": "0.3.31", - "resolved": "https://mirrors.tencent.com/npm/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "license": "MIT", "dependencies": { @@ -208,25 +225,27 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.1", - "resolved": "https://mirrors.tencent.com/npm/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", - "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", + "version": "1.1.6", + "resolved": "https://registry.npmmirror.com/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1", - "@tybys/wasm-util": "^0.10.1" + "@tybys/wasm-util": "^0.10.3" }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" } }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", - "resolved": "https://mirrors.tencent.com/npm/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "license": "MIT", "dependencies": { @@ -239,7 +258,7 @@ }, "node_modules/@nodelib/fs.stat": { "version": "2.0.5", - "resolved": "https://mirrors.tencent.com/npm/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "license": "MIT", "engines": { @@ -248,7 +267,7 @@ }, "node_modules/@nodelib/fs.walk": { "version": "1.2.8", - "resolved": "https://mirrors.tencent.com/npm/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "resolved": "https://registry.npmmirror.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "license": "MIT", "dependencies": { @@ -259,20 +278,10 @@ "node": ">= 8" } }, - "node_modules/@oxc-project/runtime": { - "version": "0.114.0", - "resolved": "https://mirrors.tencent.com/npm/@oxc-project/runtime/-/runtime-0.114.0.tgz", - "integrity": "sha512-mVGQvr/uFJGQ3hsvgQ1sJfh79t5owyZZZtw+VaH+WhtvsmtgjT6imznB9sz2Q67Q0/4obM9mOOtQscU4aJteSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, "node_modules/@oxc-project/types": { - "version": "0.114.0", - "resolved": "https://mirrors.tencent.com/npm/@oxc-project/types/-/types-0.114.0.tgz", - "integrity": "sha512-//nBfbzHQHvJs8oFIjv6coZ6uxQ4alLfiPe6D5vit6c4pmxATHHlVwgB1k+Hv4yoAMyncdxgRBF5K4BYWUCzvA==", + "version": "0.139.0", + "resolved": "https://registry.npmmirror.com/@oxc-project/types/-/types-0.139.0.tgz", + "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==", "dev": true, "license": "MIT", "funding": { @@ -280,9 +289,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.5.tgz", - "integrity": "sha512-zCEmUrt1bggwgBgeKLxNj217J1OrChrp3jJt24VK9jAharSTeVaHODNL+LpcQVhRz+FktYWfT9cjo5oZ99ZLpg==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz", + "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==", "cpu": [ "arm64" ], @@ -297,9 +306,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.5.tgz", - "integrity": "sha512-ZP9xb9lPAex36pvkNWCjSEJW/Gfdm9I3ssiqOFLmpZ/vosPXgpoGxCmh+dX1Qs+/bWQE6toNFXWWL8vYoKoK9Q==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz", + "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==", "cpu": [ "arm64" ], @@ -314,9 +323,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.5.tgz", - "integrity": "sha512-7IdrPunf6dp9mywMgTOKMMGDnMHQ6+h5gRl6LW8rhD8WK2kXX0IwzcM5Zc0B5J7xQs8QWOlKjv8BJsU/1CD3pg==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz", + "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==", "cpu": [ "x64" ], @@ -331,9 +340,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.5.tgz", - "integrity": "sha512-o/JCk+dL0IN68EBhZ4DqfsfvxPfMeoM6cJtxORC1YYoxGHZyth2Kb2maXDb4oddw2wu8iIbnYXYPEzBtAF5CAg==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz", + "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==", "cpu": [ "x64" ], @@ -348,9 +357,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.5.tgz", - "integrity": "sha512-IIBwTtA6VwxQLcEgq2mfrUgam7VvPZjhd/jxmeS1npM+edWsrrpRLHUdze+sk4rhb8/xpP3flemgcZXXUW6ukw==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz", + "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==", "cpu": [ "arm" ], @@ -365,13 +374,16 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.5.tgz", - "integrity": "sha512-KSol1De1spMZL+Xg7K5IBWXIvRWv7+pveaxFWXpezezAG7CS6ojzRjtCGCiLxQricutTAi/LkNWKMsd2wNhMKQ==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz", + "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -382,13 +394,56 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.5.tgz", - "integrity": "sha512-WFljyDkxtXRlWxMjxeegf7xMYXxUr8u7JdXlOEWKYgDqEgxUnSEsVDxBiNWQ1D5kQKwf8Wo4sVKEYPRhCdsjwA==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz", + "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz", + "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz", + "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -399,13 +454,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.5.tgz", - "integrity": "sha512-CUlplTujmbDWp2gamvrqVKi2Or8lmngXT1WxsizJfts7JrvfGhZObciaY/+CbdbS9qNnskvwMZNEhTPrn7b+WA==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz", + "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -416,13 +474,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.5.tgz", - "integrity": "sha512-wdf7g9NbVZCeAo2iGhsjJb7I8ZFfs6X8bumfrWg82VK+8P6AlLXwk48a1ASiJQDTS7Svq2xVzZg3sGO2aXpHRA==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz", + "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -433,9 +494,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.5.tgz", - "integrity": "sha512-0CWY7ubu12nhzz+tkpHjoG3IRSTlWYe0wrfJRf4qqjqQSGtAYgoL9kwzdvlhaFdZ5ffVeyYw9qLsChcjUMEloQ==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz", + "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==", "cpu": [ "arm64" ], @@ -450,9 +511,9 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.5.tgz", - "integrity": "sha512-LztXnGzv6t2u830mnZrFLRVqT/DPJ9DL4ZTz/y93rqUVkeHjMMYIYaFj+BUthiYxbVH9dH0SZYufETspKY/NhA==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz", + "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==", "cpu": [ "wasm32" ], @@ -460,16 +521,18 @@ "license": "MIT", "optional": true, "dependencies": { - "@napi-rs/wasm-runtime": "^1.1.1" + "@emnapi/core": "1.11.1", + "@emnapi/runtime": "1.11.1", + "@napi-rs/wasm-runtime": "^1.1.6" }, "engines": { - "node": ">=14.0.0" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.5.tgz", - "integrity": "sha512-jUct1XVeGtyjqJXEAfvdFa8xoigYZ2rge7nYEm70ppQxpfH9ze2fbIrpHmP2tNM2vL/F6Dd0CpXhpjPbC6bSxQ==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz", + "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==", "cpu": [ "arm64" ], @@ -483,23 +546,40 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz", + "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.2", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz", - "integrity": "sha512-izyXV/v+cHiRfozX62W9htOAvwMo4/bXKDrQ+vom1L1qRuexPock/7VZDAhnpHCLNejd3NJ6hiab+tO0D44Rgw==", + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, "license": "MIT" }, "node_modules/@standard-schema/spec": { "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "resolved": "https://registry.npmmirror.com/@standard-schema/spec/-/spec-1.1.0.tgz", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", "dev": true, "license": "MIT" }, "node_modules/@tailwindcss/forms": { "version": "0.5.11", - "resolved": "https://mirrors.tencent.com/npm/@tailwindcss/forms/-/forms-0.5.11.tgz", + "resolved": "https://registry.npmmirror.com/@tailwindcss/forms/-/forms-0.5.11.tgz", "integrity": "sha512-h9wegbZDPurxG22xZSoWtdzc41/OlNEUQERNqI/0fOwa2aVlWGu7C35E/x6LDyD3lgtztFSSjKZyuVM0hxhbgA==", "license": "MIT", "dependencies": { @@ -510,34 +590,21 @@ } }, "node_modules/@tailwindcss/typography": { - "version": "0.5.19", - "resolved": "https://mirrors.tencent.com/npm/@tailwindcss/typography/-/typography-0.5.19.tgz", - "integrity": "sha512-w31dd8HOx3k9vPtcQh5QHP9GwKcgbMp87j58qi6xgiBnFFtKEAgCWnDw4qUT8aHwkCp8bKvb/KGKWWHedP0AAg==", + "version": "0.5.20", + "resolved": "https://registry.npmmirror.com/@tailwindcss/typography/-/typography-0.5.20.tgz", + "integrity": "sha512-hwbzQuNUfcPvbegQFatVPl/MY/tcM9KLl963hQ5laJKPh81TEZ1+dNG9PirGvcaDBkp+BCshExAyKVPW91dozw==", "license": "MIT", "dependencies": { "postcss-selector-parser": "6.0.10" }, "peerDependencies": { - "tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1" - } - }, - "node_modules/@tailwindcss/typography/node_modules/postcss-selector-parser": { - "version": "6.0.10", - "resolved": "https://mirrors.tencent.com/npm/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", - "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" + "tailwindcss": ">=3.0.0 || >=4.0.0 || insiders" } }, "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://mirrors.tencent.com/npm/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "version": "0.10.3", + "resolved": "https://registry.npmmirror.com/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", + "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", "dev": true, "license": "MIT", "optional": true, @@ -547,7 +614,7 @@ }, "node_modules/@types/chai": { "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz", "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", "dev": true, "license": "MIT", @@ -558,56 +625,56 @@ }, "node_modules/@types/deep-eql": { "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz", "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", "dev": true, "license": "MIT" }, "node_modules/@types/estree": { "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz", "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "dev": true, "license": "MIT" }, "node_modules/@types/node": { - "version": "24.10.13", - "resolved": "https://mirrors.tencent.com/npm/@types/node/-/node-24.10.13.tgz", - "integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==", + "version": "24.13.3", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-24.13.3.tgz", + "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.16.0" + "undici-types": "~7.18.0" } }, "node_modules/@vitejs/plugin-vue": { - "version": "6.0.4", - "resolved": "https://mirrors.tencent.com/npm/@vitejs/plugin-vue/-/plugin-vue-6.0.4.tgz", - "integrity": "sha512-uM5iXipgYIn13UUQCZNdWkYk+sysBeA97d5mHsAoAt1u/wpN3+zxOmsVJWosuzX+IMGRzeYUNytztrYznboIkQ==", + "version": "6.0.8", + "resolved": "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-6.0.8.tgz", + "integrity": "sha512-0ZjgOg7oO6farnNGup7yvoM/YXZV84OZxHAwtflItNa/6zzQyVb5LNxyea3FEKEX2XlagIKzrlH7wwxkKgtiew==", "dev": true, "license": "MIT", "dependencies": { - "@rolldown/pluginutils": "1.0.0-rc.2" + "@rolldown/pluginutils": "^1.0.1" }, "engines": { "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25" } }, "node_modules/@vitest/expect": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.8.tgz", - "integrity": "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-4.1.10.tgz", + "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -616,13 +683,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.8.tgz", - "integrity": "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-4.1.10.tgz", + "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.8", + "@vitest/spy": "4.1.10", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -642,20 +709,10 @@ } } }, - "node_modules/@vitest/mocker/node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, "node_modules/@vitest/pretty-format": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.8.tgz", - "integrity": "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-4.1.10.tgz", + "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==", "dev": true, "license": "MIT", "dependencies": { @@ -666,13 +723,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.8.tgz", - "integrity": "sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-4.1.10.tgz", + "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.8", + "@vitest/utils": "4.1.10", "pathe": "^2.0.3" }, "funding": { @@ -680,14 +737,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.8.tgz", - "integrity": "sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-4.1.10.tgz", + "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/pretty-format": "4.1.10", + "@vitest/utils": "4.1.10", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -696,9 +753,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.8.tgz", - "integrity": "sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-4.1.10.tgz", + "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==", "dev": true, "license": "MIT", "funding": { @@ -706,13 +763,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.8.tgz", - "integrity": "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-4.1.10.tgz", + "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", + "@vitest/pretty-format": "4.1.10", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -722,7 +779,7 @@ }, "node_modules/@volar/language-core": { "version": "2.4.28", - "resolved": "https://mirrors.tencent.com/npm/@volar/language-core/-/language-core-2.4.28.tgz", + "resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.28.tgz", "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", "dev": true, "license": "MIT", @@ -732,14 +789,14 @@ }, "node_modules/@volar/source-map": { "version": "2.4.28", - "resolved": "https://mirrors.tencent.com/npm/@volar/source-map/-/source-map-2.4.28.tgz", + "resolved": "https://registry.npmmirror.com/@volar/source-map/-/source-map-2.4.28.tgz", "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", "dev": true, "license": "MIT" }, "node_modules/@volar/typescript": { "version": "2.4.28", - "resolved": "https://mirrors.tencent.com/npm/@volar/typescript/-/typescript-2.4.28.tgz", + "resolved": "https://registry.npmmirror.com/@volar/typescript/-/typescript-2.4.28.tgz", "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", "dev": true, "license": "MIT", @@ -751,7 +808,7 @@ }, "node_modules/@vue-office/docx": { "version": "1.6.3", - "resolved": "https://mirrors.tencent.com/npm/@vue-office/docx/-/docx-1.6.3.tgz", + "resolved": "https://registry.npmmirror.com/@vue-office/docx/-/docx-1.6.3.tgz", "integrity": "sha512-Cs+3CAaRBOWOiW4XAhTwwxJ0dy8cPIf6DqfNvYcD3YACiLwO4kuawLF2IAXxyijhbuOeoFsfvoVbOc16A/4bZA==", "hasInstallScript": true, "license": "MIT", @@ -768,7 +825,7 @@ }, "node_modules/@vue-office/excel": { "version": "1.7.14", - "resolved": "https://mirrors.tencent.com/npm/@vue-office/excel/-/excel-1.7.14.tgz", + "resolved": "https://registry.npmmirror.com/@vue-office/excel/-/excel-1.7.14.tgz", "integrity": "sha512-pVUgt+emDQUnW7q22CfnQ+jl43mM/7IFwYzOg7lwOwPEbiVB4K4qEQf+y/bc4xGXz75w1/e3Kz3G6wAafmFBFg==", "hasInstallScript": true, "license": "MIT", @@ -785,7 +842,7 @@ }, "node_modules/@vue-office/pdf": { "version": "1.6.5", - "resolved": "https://mirrors.tencent.com/npm/@vue-office/pdf/-/pdf-1.6.5.tgz", + "resolved": "https://registry.npmmirror.com/@vue-office/pdf/-/pdf-1.6.5.tgz", "integrity": "sha512-3BePzeA5wji2JoZGJhdlc3XEXs6gMcSnBXrBXlGGfhZHjNijxcHa9V5Ibm8dDKoEwPPsfg+kf4TGP9/2GBR8jQ==", "hasInstallScript": true, "license": "MIT", @@ -801,68 +858,83 @@ } }, "node_modules/@vue/compiler-core": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/compiler-core/-/compiler-core-3.5.28.tgz", - "integrity": "sha512-kviccYxTgoE8n6OCw96BNdYlBg2GOWfBuOW4Vqwrt7mSKWKwFVvI8egdTltqRgITGPsTFYtKYfxIG8ptX2PJHQ==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/compiler-core/-/compiler-core-3.5.40.tgz", + "integrity": "sha512-39E8IgOhTbVDnoJFMKc2DvYnypcZwUqgUhQkccva/0m6FUwtIKSGV7n1hpVmYcFaoRAwf9pBcwnKlCEsN63ZEQ==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.0", - "@vue/shared": "3.5.28", + "@babel/parser": "^7.29.7", + "@vue/shared": "3.5.40", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, + "node_modules/@vue/compiler-core/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, "node_modules/@vue/compiler-dom": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/compiler-dom/-/compiler-dom-3.5.28.tgz", - "integrity": "sha512-/1ZepxAb159jKR1btkefDP+J2xuWL5V3WtleRmxaT+K2Aqiek/Ab/+Ebrw2pPj0sdHO8ViAyyJWfhXXOP/+LQA==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/compiler-dom/-/compiler-dom-3.5.40.tgz", + "integrity": "sha512-pwkx4vqlqOspFstrcmzwkKLePVMD3PT65imRzLhanU2V1Fj4K13g6OXjanOyzw3aTAuRk84BOmY8f3rEHqPaVA==", "license": "MIT", "dependencies": { - "@vue/compiler-core": "3.5.28", - "@vue/shared": "3.5.28" + "@vue/compiler-core": "3.5.40", + "@vue/shared": "3.5.40" } }, "node_modules/@vue/compiler-sfc": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/compiler-sfc/-/compiler-sfc-3.5.28.tgz", - "integrity": "sha512-6TnKMiNkd6u6VeVDhZn/07KhEZuBSn43Wd2No5zaP5s3xm8IqFTHBj84HJah4UepSUJTro5SoqqlOY22FKY96g==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/compiler-sfc/-/compiler-sfc-3.5.40.tgz", + "integrity": "sha512-gIf497P4kpuALcvs5n3AEg1Vdn0pSY4XbjASIfHNYF1/MP3T2Mf2STERTubysBxCRxzJGJYtF/O7vwJrxFB3Vw==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.0", - "@vue/compiler-core": "3.5.28", - "@vue/compiler-dom": "3.5.28", - "@vue/compiler-ssr": "3.5.28", - "@vue/shared": "3.5.28", + "@babel/parser": "^7.29.7", + "@vue/compiler-core": "3.5.40", + "@vue/compiler-dom": "3.5.40", + "@vue/compiler-ssr": "3.5.40", + "@vue/shared": "3.5.40", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", - "postcss": "^8.5.6", + "postcss": "^8.5.19", "source-map-js": "^1.2.1" } }, + "node_modules/@vue/compiler-sfc/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, "node_modules/@vue/compiler-ssr": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/compiler-ssr/-/compiler-ssr-3.5.28.tgz", - "integrity": "sha512-JCq//9w1qmC6UGLWJX7RXzrGpKkroubey/ZFqTpvEIDJEKGgntuDMqkuWiZvzTzTA5h2qZvFBFHY7fAAa9475g==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/compiler-ssr/-/compiler-ssr-3.5.40.tgz", + "integrity": "sha512-rrE5xiXG663+vHCHa3J9p2z5OcBRjXmoqenprJxAFQxg5pSshzeBiCE6pu46axapRJ2Adk0YDA2BRZVjiHXnhg==", "license": "MIT", "dependencies": { - "@vue/compiler-dom": "3.5.28", - "@vue/shared": "3.5.28" + "@vue/compiler-dom": "3.5.40", + "@vue/shared": "3.5.40" } }, "node_modules/@vue/devtools-api": { - "version": "6.6.4", - "resolved": "https://mirrors.tencent.com/npm/@vue/devtools-api/-/devtools-api-6.6.4.tgz", - "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", - "license": "MIT" - }, - "node_modules/@vue/devtools-kit": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", - "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", + "version": "7.7.10", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-7.7.10.tgz", + "integrity": "sha512-KxtEpUOOpFz/qOGRrAwA36QF7DqIA+FXgCYit9mk9wjbaZt0sXOFz81ElOZtKA4HbWHUdwNjZHBFsFFyp5BZiA==", "license": "MIT", "dependencies": { - "@vue/devtools-shared": "^7.7.9", + "@vue/devtools-kit": "^7.7.10" + } + }, + "node_modules/@vue/devtools-kit": { + "version": "7.7.10", + "resolved": "https://registry.npmmirror.com/@vue/devtools-kit/-/devtools-kit-7.7.10.tgz", + "integrity": "sha512-3WNi2Kq4tbpVbmhml7RiphmAt0279oh3fKNeWMQIrltfX8Q91b4i5PL8DtyNKdwmcsGrV4fg+erwWOmD05CLIw==", + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^7.7.10", "birpc": "^2.3.0", "hookable": "^5.5.3", "mitt": "^3.0.1", @@ -872,83 +944,94 @@ } }, "node_modules/@vue/devtools-shared": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", - "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", + "version": "7.7.10", + "resolved": "https://registry.npmmirror.com/@vue/devtools-shared/-/devtools-shared-7.7.10.tgz", + "integrity": "sha512-wOPslzB8vTvpxwdaOcR2qAbwmuSP0L+rhpoC6Cf56V3Jip+HWb7PQQXOUPgBNQARpXsbQX/+mvi8kKucmBGRwQ==", "license": "MIT", "dependencies": { "rfdc": "^1.4.1" } }, "node_modules/@vue/language-core": { - "version": "3.2.5", - "resolved": "https://mirrors.tencent.com/npm/@vue/language-core/-/language-core-3.2.5.tgz", - "integrity": "sha512-d3OIxN/+KRedeM5wQ6H6NIpwS3P5gC9nmyaHgBk+rO6dIsjY+tOh4UlPpiZbAh3YtLdCGEX4M16RmsBqPmJV+g==", + "version": "3.3.7", + "resolved": "https://registry.npmmirror.com/@vue/language-core/-/language-core-3.3.7.tgz", + "integrity": "sha512-LzmkKinXAMMoh8Jfi/jMUSDUjuPdv8mynH5WJGKfXyZtDw3hQ6GBaoI6Bcnl/Xqlu32q/0Z6i/trp4VXykzyLw==", "dev": true, "license": "MIT", "dependencies": { "@volar/language-core": "2.4.28", "@vue/compiler-dom": "^3.5.0", "@vue/shared": "^3.5.0", - "alien-signals": "^3.0.0", + "alien-signals": "^3.2.1", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1", - "picomatch": "^4.0.2" + "picomatch": "^4.0.4" + } + }, + "node_modules/@vue/language-core/node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/@vue/reactivity": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/reactivity/-/reactivity-3.5.28.tgz", - "integrity": "sha512-gr5hEsxvn+RNyu9/9o1WtdYdwDjg5FgjUSBEkZWqgTKlo/fvwZ2+8W6AfKsc9YN2k/+iHYdS9vZYAhpi10kNaw==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.40.tgz", + "integrity": "sha512-B7ot9UlUZOi1zbq61/LvE88ZLTV8IlajTdiZTAEiDQgrnIMIZoPr9kGw0Zw46ObW62O9+H/Be3kMbfb7kYPQZA==", "license": "MIT", "dependencies": { - "@vue/shared": "3.5.28" + "@vue/shared": "3.5.40" } }, "node_modules/@vue/runtime-core": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/runtime-core/-/runtime-core-3.5.28.tgz", - "integrity": "sha512-POVHTdbgnrBBIpnbYU4y7pOMNlPn2QVxVzkvEA2pEgvzbelQq4ZOUxbp2oiyo+BOtiYlm8Q44wShHJoBvDPAjQ==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/runtime-core/-/runtime-core-3.5.40.tgz", + "integrity": "sha512-KAZLweuZ6uUJPK1PMSQPgBU5gCjgrrfjUhSglmU9NhH+Zjepa8cnwSydPWDWHDwOgY4g3VcZ+PljbiHlURNCbw==", "license": "MIT", "dependencies": { - "@vue/reactivity": "3.5.28", - "@vue/shared": "3.5.28" + "@vue/reactivity": "3.5.40", + "@vue/shared": "3.5.40" } }, "node_modules/@vue/runtime-dom": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/runtime-dom/-/runtime-dom-3.5.28.tgz", - "integrity": "sha512-4SXxSF8SXYMuhAIkT+eBRqOkWEfPu6nhccrzrkioA6l0boiq7sp18HCOov9qWJA5HML61kW8p/cB4MmBiG9dSA==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/runtime-dom/-/runtime-dom-3.5.40.tgz", + "integrity": "sha512-ZfrX8ssZQds900L9pr8AuK05ddnMsR4MPMZr8cPN9GoqoPWcXLhjvvbIA2SMv+7a97sJ1vv9pj/zxK0Cq/eEFQ==", "license": "MIT", "dependencies": { - "@vue/reactivity": "3.5.28", - "@vue/runtime-core": "3.5.28", - "@vue/shared": "3.5.28", + "@vue/reactivity": "3.5.40", + "@vue/runtime-core": "3.5.40", + "@vue/shared": "3.5.40", "csstype": "^3.2.3" } }, "node_modules/@vue/server-renderer": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/server-renderer/-/server-renderer-3.5.28.tgz", - "integrity": "sha512-pf+5ECKGj8fX95bNincbzJ6yp6nyzuLDhYZCeFxUNp8EBrQpPpQaLX3nNCp49+UbgbPun3CeVE+5CXVV1Xydfg==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/server-renderer/-/server-renderer-3.5.40.tgz", + "integrity": "sha512-XNJym9WpevhTVt1HuwOrCRJ5Q+9z4BjTMrDtjTrvx74SmUll8spNTw6whWJa9mEkO4PKn5TihI/bm/8ds2QVJw==", "license": "MIT", "dependencies": { - "@vue/compiler-ssr": "3.5.28", - "@vue/shared": "3.5.28" - }, - "peerDependencies": { - "vue": "3.5.28" + "@vue/compiler-ssr": "3.5.40", + "@vue/runtime-dom": "3.5.40", + "@vue/shared": "3.5.40" } }, "node_modules/@vue/shared": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/@vue/shared/-/shared-3.5.28.tgz", - "integrity": "sha512-cfWa1fCGBxrvaHRhvV3Is0MgmrbSCxYTXCSCau2I0a1Xw1N1pHAvkWCiXPRAqjvToILvguNyEwjevUqAuBQWvQ==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.40.tgz", + "integrity": "sha512-WxnBtruIqOoV3rA4jeKDWzrYI5h7Cp4+pjwDi8kWGHz+IslhiN+wguLVVhtv2l8VoU02rzDCVfDjgCl1lNpZVg==", "license": "MIT" }, "node_modules/@vue/tsconfig": { "version": "0.8.1", - "resolved": "https://mirrors.tencent.com/npm/@vue/tsconfig/-/tsconfig-0.8.1.tgz", + "resolved": "https://registry.npmmirror.com/@vue/tsconfig/-/tsconfig-0.8.1.tgz", "integrity": "sha512-aK7feIWPXFSUhsCP9PFqPyFOcz4ENkb8hZ2pneL6m2UjCkccvaOhC/5KCKluuBufvp2KzkbdA2W2pk20vLzu3g==", "dev": true, "license": "MIT", @@ -967,7 +1050,7 @@ }, "node_modules/adler-32": { "version": "1.3.1", - "resolved": "https://mirrors.tencent.com/npm/adler-32/-/adler-32-1.3.1.tgz", + "resolved": "https://registry.npmmirror.com/adler-32/-/adler-32-1.3.1.tgz", "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", "license": "Apache-2.0", "engines": { @@ -975,21 +1058,21 @@ } }, "node_modules/alien-signals": { - "version": "3.1.2", - "resolved": "https://mirrors.tencent.com/npm/alien-signals/-/alien-signals-3.1.2.tgz", - "integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==", + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/alien-signals/-/alien-signals-3.2.1.tgz", + "integrity": "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==", "dev": true, "license": "MIT" }, "node_modules/any-promise": { "version": "1.3.0", - "resolved": "https://mirrors.tencent.com/npm/any-promise/-/any-promise-1.3.0.tgz", + "resolved": "https://registry.npmmirror.com/any-promise/-/any-promise-1.3.0.tgz", "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", "license": "MIT" }, "node_modules/anymatch": { "version": "3.1.3", - "resolved": "https://mirrors.tencent.com/npm/anymatch/-/anymatch-3.1.3.tgz", + "resolved": "https://registry.npmmirror.com/anymatch/-/anymatch-3.1.3.tgz", "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", "license": "ISC", "dependencies": { @@ -1000,27 +1083,15 @@ "node": ">= 8" } }, - "node_modules/anymatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/arg": { "version": "5.0.2", - "resolved": "https://mirrors.tencent.com/npm/arg/-/arg-5.0.2.tgz", + "resolved": "https://registry.npmmirror.com/arg/-/arg-5.0.2.tgz", "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", "license": "MIT" }, "node_modules/assertion-error": { "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz", "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, "license": "MIT", @@ -1029,9 +1100,9 @@ } }, "node_modules/autoprefixer": { - "version": "10.4.24", - "resolved": "https://mirrors.tencent.com/npm/autoprefixer/-/autoprefixer-10.4.24.tgz", - "integrity": "sha512-uHZg7N9ULTVbutaIsDRoUkoS8/h3bdsmVJYZ5l3wv8Cp/6UIIoRDm90hZ+BwxUj/hGBEzLxdHNSKuFpn8WOyZw==", + "version": "10.5.4", + "resolved": "https://registry.npmmirror.com/autoprefixer/-/autoprefixer-10.5.4.tgz", + "integrity": "sha512-MaU0U/za7N3r6brxD4YB/l4NSrFzLPlANv6wEuQVaIPlD3L4W9rFcQPbL/EilY9BHhHvhfcz3gInDLrEtWT4EA==", "dev": true, "funding": [ { @@ -1049,8 +1120,8 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.28.1", - "caniuse-lite": "^1.0.30001766", + "browserslist": "^4.28.6", + "caniuse-lite": "^1.0.30001806", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" @@ -1066,9 +1137,9 @@ } }, "node_modules/baseline-browser-mapping": { - "version": "2.10.0", - "resolved": "https://mirrors.tencent.com/npm/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz", - "integrity": "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA==", + "version": "2.11.0", + "resolved": "https://registry.npmmirror.com/baseline-browser-mapping/-/baseline-browser-mapping-2.11.0.tgz", + "integrity": "sha512-oCu2wfipvX3AePSgmOuKkIywOu+8n9psz7hXYmk56ghpu3+7KzNIBopaOs4c9BrtdnTtW30unG9GTfHo7EwERQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -1080,7 +1151,7 @@ }, "node_modules/binary-extensions": { "version": "2.3.0", - "resolved": "https://mirrors.tencent.com/npm/binary-extensions/-/binary-extensions-2.3.0.tgz", + "resolved": "https://registry.npmmirror.com/binary-extensions/-/binary-extensions-2.3.0.tgz", "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", "license": "MIT", "engines": { @@ -1092,7 +1163,7 @@ }, "node_modules/birpc": { "version": "2.9.0", - "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz", + "resolved": "https://registry.npmmirror.com/birpc/-/birpc-2.9.0.tgz", "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==", "license": "MIT", "funding": { @@ -1101,7 +1172,7 @@ }, "node_modules/braces": { "version": "3.0.3", - "resolved": "https://mirrors.tencent.com/npm/braces/-/braces-3.0.3.tgz", + "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "license": "MIT", "dependencies": { @@ -1112,9 +1183,9 @@ } }, "node_modules/browserslist": { - "version": "4.28.1", - "resolved": "https://mirrors.tencent.com/npm/browserslist/-/browserslist-4.28.1.tgz", - "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "version": "4.28.7", + "resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.28.7.tgz", + "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", "dev": true, "funding": [ { @@ -1132,11 +1203,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.9.0", - "caniuse-lite": "^1.0.30001759", - "electron-to-chromium": "^1.5.263", - "node-releases": "^2.0.27", - "update-browserslist-db": "^1.2.0" + "baseline-browser-mapping": "^2.10.44", + "caniuse-lite": "^1.0.30001806", + "electron-to-chromium": "^1.5.393", + "node-releases": "^2.0.51", + "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" @@ -1147,7 +1218,7 @@ }, "node_modules/camelcase-css": { "version": "2.0.1", - "resolved": "https://mirrors.tencent.com/npm/camelcase-css/-/camelcase-css-2.0.1.tgz", + "resolved": "https://registry.npmmirror.com/camelcase-css/-/camelcase-css-2.0.1.tgz", "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", "license": "MIT", "engines": { @@ -1155,9 +1226,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001772", - "resolved": "https://mirrors.tencent.com/npm/caniuse-lite/-/caniuse-lite-1.0.30001772.tgz", - "integrity": "sha512-mIwLZICj+ntVTw4BT2zfp+yu/AqV6GMKfJVJMx3MwPxs+uk/uj2GLl2dH8LQbjiLDX66amCga5nKFyDgRR43kg==", + "version": "1.0.30001806", + "resolved": "https://registry.npmmirror.com/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", + "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", "dev": true, "funding": [ { @@ -1177,7 +1248,7 @@ }, "node_modules/cfb": { "version": "1.2.2", - "resolved": "https://mirrors.tencent.com/npm/cfb/-/cfb-1.2.2.tgz", + "resolved": "https://registry.npmmirror.com/cfb/-/cfb-1.2.2.tgz", "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", "license": "Apache-2.0", "dependencies": { @@ -1190,7 +1261,7 @@ }, "node_modules/chai": { "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "resolved": "https://registry.npmmirror.com/chai/-/chai-6.2.2.tgz", "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", "dev": true, "license": "MIT", @@ -1200,7 +1271,7 @@ }, "node_modules/chokidar": { "version": "3.6.0", - "resolved": "https://mirrors.tencent.com/npm/chokidar/-/chokidar-3.6.0.tgz", + "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz", "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "license": "MIT", "dependencies": { @@ -1224,7 +1295,7 @@ }, "node_modules/chokidar/node_modules/glob-parent": { "version": "5.1.2", - "resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-5.1.2.tgz", + "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "license": "ISC", "dependencies": { @@ -1236,7 +1307,7 @@ }, "node_modules/codepage": { "version": "1.15.0", - "resolved": "https://mirrors.tencent.com/npm/codepage/-/codepage-1.15.0.tgz", + "resolved": "https://registry.npmmirror.com/codepage/-/codepage-1.15.0.tgz", "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", "license": "Apache-2.0", "engines": { @@ -1245,7 +1316,7 @@ }, "node_modules/commander": { "version": "4.1.1", - "resolved": "https://mirrors.tencent.com/npm/commander/-/commander-4.1.1.tgz", + "resolved": "https://registry.npmmirror.com/commander/-/commander-4.1.1.tgz", "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", "license": "MIT", "engines": { @@ -1254,14 +1325,14 @@ }, "node_modules/convert-source-map": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/convert-source-map/-/convert-source-map-2.0.0.tgz", "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true, "license": "MIT" }, "node_modules/copy-anything": { "version": "4.0.5", - "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz", + "resolved": "https://registry.npmmirror.com/copy-anything/-/copy-anything-4.0.5.tgz", "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", "license": "MIT", "dependencies": { @@ -1276,7 +1347,7 @@ }, "node_modules/crc-32": { "version": "1.2.2", - "resolved": "https://mirrors.tencent.com/npm/crc-32/-/crc-32-1.2.2.tgz", + "resolved": "https://registry.npmmirror.com/crc-32/-/crc-32-1.2.2.tgz", "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", "license": "Apache-2.0", "bin": { @@ -1287,12 +1358,12 @@ } }, "node_modules/cron-parser": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-5.5.0.tgz", - "integrity": "sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==", + "version": "5.6.2", + "resolved": "https://registry.npmmirror.com/cron-parser/-/cron-parser-5.6.2.tgz", + "integrity": "sha512-yJ/G1LVir6CnlkLI40CsampPLKl1SprGGlUagWtGJxewytRVYezv5xVyzzbT+Pvzx+VIRvZVF7/a0eEMTxdnTA==", "license": "MIT", "dependencies": { - "luxon": "^3.7.1" + "luxon": "^3.7.2" }, "engines": { "node": ">=18" @@ -1300,7 +1371,7 @@ }, "node_modules/cssesc": { "version": "3.0.0", - "resolved": "https://mirrors.tencent.com/npm/cssesc/-/cssesc-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz", "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", "license": "MIT", "bin": { @@ -1312,13 +1383,13 @@ }, "node_modules/csstype": { "version": "3.2.3", - "resolved": "https://mirrors.tencent.com/npm/csstype/-/csstype-3.2.3.tgz", + "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, "node_modules/detect-libc": { "version": "2.1.2", - "resolved": "https://mirrors.tencent.com/npm/detect-libc/-/detect-libc-2.1.2.tgz", + "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, "license": "Apache-2.0", @@ -1328,26 +1399,26 @@ }, "node_modules/didyoumean": { "version": "1.2.2", - "resolved": "https://mirrors.tencent.com/npm/didyoumean/-/didyoumean-1.2.2.tgz", + "resolved": "https://registry.npmmirror.com/didyoumean/-/didyoumean-1.2.2.tgz", "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", "license": "Apache-2.0" }, "node_modules/dlv": { "version": "1.1.3", - "resolved": "https://mirrors.tencent.com/npm/dlv/-/dlv-1.1.3.tgz", + "resolved": "https://registry.npmmirror.com/dlv/-/dlv-1.1.3.tgz", "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.302", - "resolved": "https://mirrors.tencent.com/npm/electron-to-chromium/-/electron-to-chromium-1.5.302.tgz", - "integrity": "sha512-sM6HAN2LyK82IyPBpznDRqlTQAtuSaO+ShzFiWTvoMJLHyZ+Y39r8VMfHzwbU8MVBzQ4Wdn85+wlZl2TLGIlwg==", + "version": "1.5.395", + "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.395.tgz", + "integrity": "sha512-7zt9Aw+SrmxLWLN0zhaTWZQiCdryLVrYTq5R7iZakLvi2UQPYMMsROYV/2qVCzMeCiSXHwKOU+sZ4zOVVlrtKA==", "dev": true, "license": "ISC" }, "node_modules/entities": { "version": "7.0.1", - "resolved": "https://mirrors.tencent.com/npm/entities/-/entities-7.0.1.tgz", + "resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", "license": "BSD-2-Clause", "engines": { @@ -1357,16 +1428,25 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", - "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-2.3.1.tgz", + "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==", "dev": true, "license": "MIT" }, "node_modules/escalade": { "version": "3.2.0", - "resolved": "https://mirrors.tencent.com/npm/escalade/-/escalade-3.2.0.tgz", + "resolved": "https://registry.npmmirror.com/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "dev": true, "license": "MIT", @@ -1375,15 +1455,19 @@ } }, "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://mirrors.tencent.com/npm/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "license": "MIT" + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } }, "node_modules/expect-type": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", - "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", "dev": true, "license": "Apache-2.0", "engines": { @@ -1392,7 +1476,7 @@ }, "node_modules/fast-glob": { "version": "3.3.3", - "resolved": "https://mirrors.tencent.com/npm/fast-glob/-/fast-glob-3.3.3.tgz", + "resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz", "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", "license": "MIT", "dependencies": { @@ -1408,7 +1492,7 @@ }, "node_modules/fast-glob/node_modules/glob-parent": { "version": "5.1.2", - "resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-5.1.2.tgz", + "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "license": "ISC", "dependencies": { @@ -1420,33 +1504,16 @@ }, "node_modules/fastq": { "version": "1.20.1", - "resolved": "https://mirrors.tencent.com/npm/fastq/-/fastq-1.20.1.tgz", + "resolved": "https://registry.npmmirror.com/fastq/-/fastq-1.20.1.tgz", "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", "license": "ISC", "dependencies": { "reusify": "^1.0.4" } }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://mirrors.tencent.com/npm/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, "node_modules/fill-range": { "version": "7.1.1", - "resolved": "https://mirrors.tencent.com/npm/fill-range/-/fill-range-7.1.1.tgz", + "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "license": "MIT", "dependencies": { @@ -1458,7 +1525,7 @@ }, "node_modules/frac": { "version": "1.1.2", - "resolved": "https://mirrors.tencent.com/npm/frac/-/frac-1.1.2.tgz", + "resolved": "https://registry.npmmirror.com/frac/-/frac-1.1.2.tgz", "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", "license": "Apache-2.0", "engines": { @@ -1467,7 +1534,7 @@ }, "node_modules/fraction.js": { "version": "5.3.4", - "resolved": "https://mirrors.tencent.com/npm/fraction.js/-/fraction.js-5.3.4.tgz", + "resolved": "https://registry.npmmirror.com/fraction.js/-/fraction.js-5.3.4.tgz", "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", "dev": true, "license": "MIT", @@ -1481,7 +1548,7 @@ }, "node_modules/fsevents": { "version": "2.3.3", - "resolved": "https://mirrors.tencent.com/npm/fsevents/-/fsevents-2.3.3.tgz", + "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "hasInstallScript": true, "license": "MIT", @@ -1495,7 +1562,7 @@ }, "node_modules/function-bind": { "version": "1.1.2", - "resolved": "https://mirrors.tencent.com/npm/function-bind/-/function-bind-1.1.2.tgz", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", "license": "MIT", "funding": { @@ -1504,7 +1571,7 @@ }, "node_modules/glob-parent": { "version": "6.0.2", - "resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-6.0.2.tgz", + "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-6.0.2.tgz", "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", "license": "ISC", "dependencies": { @@ -1515,9 +1582,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://mirrors.tencent.com/npm/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -1528,7 +1595,7 @@ }, "node_modules/highlight.js": { "version": "11.11.1", - "resolved": "https://mirrors.tencent.com/npm/highlight.js/-/highlight.js-11.11.1.tgz", + "resolved": "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.11.1.tgz", "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==", "license": "BSD-3-Clause", "engines": { @@ -1537,13 +1604,13 @@ }, "node_modules/hookable": { "version": "5.5.3", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", + "resolved": "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", "license": "MIT" }, "node_modules/is-binary-path": { "version": "2.1.0", - "resolved": "https://mirrors.tencent.com/npm/is-binary-path/-/is-binary-path-2.1.0.tgz", + "resolved": "https://registry.npmmirror.com/is-binary-path/-/is-binary-path-2.1.0.tgz", "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "license": "MIT", "dependencies": { @@ -1554,12 +1621,12 @@ } }, "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://mirrors.tencent.com/npm/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "version": "2.16.2", + "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", "license": "MIT", "dependencies": { - "hasown": "^2.0.2" + "hasown": "^2.0.3" }, "engines": { "node": ">= 0.4" @@ -1570,7 +1637,7 @@ }, "node_modules/is-extglob": { "version": "2.1.1", - "resolved": "https://mirrors.tencent.com/npm/is-extglob/-/is-extglob-2.1.1.tgz", + "resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "license": "MIT", "engines": { @@ -1579,7 +1646,7 @@ }, "node_modules/is-glob": { "version": "4.0.3", - "resolved": "https://mirrors.tencent.com/npm/is-glob/-/is-glob-4.0.3.tgz", + "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "license": "MIT", "dependencies": { @@ -1591,7 +1658,7 @@ }, "node_modules/is-number": { "version": "7.0.0", - "resolved": "https://mirrors.tencent.com/npm/is-number/-/is-number-7.0.0.tgz", + "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "license": "MIT", "engines": { @@ -1600,7 +1667,7 @@ }, "node_modules/is-what": { "version": "5.5.0", - "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz", + "resolved": "https://registry.npmmirror.com/is-what/-/is-what-5.5.0.tgz", "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", "license": "MIT", "engines": { @@ -1612,7 +1679,7 @@ }, "node_modules/jiti": { "version": "1.21.7", - "resolved": "https://mirrors.tencent.com/npm/jiti/-/jiti-1.21.7.tgz", + "resolved": "https://registry.npmmirror.com/jiti/-/jiti-1.21.7.tgz", "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", "license": "MIT", "bin": { @@ -1620,9 +1687,9 @@ } }, "node_modules/lightningcss": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss/-/lightningcss-1.31.1.tgz", - "integrity": "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", "dependencies": { @@ -1636,23 +1703,23 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "lightningcss-android-arm64": "1.31.1", - "lightningcss-darwin-arm64": "1.31.1", - "lightningcss-darwin-x64": "1.31.1", - "lightningcss-freebsd-x64": "1.31.1", - "lightningcss-linux-arm-gnueabihf": "1.31.1", - "lightningcss-linux-arm64-gnu": "1.31.1", - "lightningcss-linux-arm64-musl": "1.31.1", - "lightningcss-linux-x64-gnu": "1.31.1", - "lightningcss-linux-x64-musl": "1.31.1", - "lightningcss-win32-arm64-msvc": "1.31.1", - "lightningcss-win32-x64-msvc": "1.31.1" + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" } }, "node_modules/lightningcss-android-arm64": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-android-arm64/-/lightningcss-android-arm64-1.31.1.tgz", - "integrity": "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", "cpu": [ "arm64" ], @@ -1671,9 +1738,9 @@ } }, "node_modules/lightningcss-darwin-arm64": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.31.1.tgz", - "integrity": "sha512-02uTEqf3vIfNMq3h/z2cJfcOXnQ0GRwQrkmPafhueLb2h7mqEidiCzkE4gBMEH65abHRiQvhdcQ+aP0D0g67sg==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", "cpu": [ "arm64" ], @@ -1692,9 +1759,9 @@ } }, "node_modules/lightningcss-darwin-x64": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.31.1.tgz", - "integrity": "sha512-1ObhyoCY+tGxtsz1lSx5NXCj3nirk0Y0kB/g8B8DT+sSx4G9djitg9ejFnjb3gJNWo7qXH4DIy2SUHvpoFwfTA==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", "cpu": [ "x64" ], @@ -1713,9 +1780,9 @@ } }, "node_modules/lightningcss-freebsd-x64": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.31.1.tgz", - "integrity": "sha512-1RINmQKAItO6ISxYgPwszQE1BrsVU5aB45ho6O42mu96UiZBxEXsuQ7cJW4zs4CEodPUioj/QrXW1r9pLUM74A==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", "cpu": [ "x64" ], @@ -1734,9 +1801,9 @@ } }, "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.31.1.tgz", - "integrity": "sha512-OOCm2//MZJ87CdDK62rZIu+aw9gBv4azMJuA8/KB74wmfS3lnC4yoPHm0uXZ/dvNNHmnZnB8XLAZzObeG0nS1g==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", "cpu": [ "arm" ], @@ -1755,13 +1822,16 @@ } }, "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.31.1.tgz", - "integrity": "sha512-WKyLWztD71rTnou4xAD5kQT+982wvca7E6QoLpoawZ1gP9JM0GJj4Tp5jMUh9B3AitHbRZ2/H3W5xQmdEOUlLg==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1776,13 +1846,16 @@ } }, "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.31.1.tgz", - "integrity": "sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1797,13 +1870,16 @@ } }, "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.31.1.tgz", - "integrity": "sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1818,13 +1894,16 @@ } }, "node_modules/lightningcss-linux-x64-musl": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.31.1.tgz", - "integrity": "sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1839,9 +1918,9 @@ } }, "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.31.1.tgz", - "integrity": "sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", "cpu": [ "arm64" ], @@ -1860,9 +1939,9 @@ } }, "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.31.1", - "resolved": "https://mirrors.tencent.com/npm/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.31.1.tgz", - "integrity": "sha512-I9aiFrbd7oYHwlnQDqr1Roz+fTz61oDDJX7n9tYF9FJymH1cIN1DtKw3iYt6b8WZgEjoNwVSncwF4wx/ZedMhw==", + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", "cpu": [ "x64" ], @@ -1882,7 +1961,7 @@ }, "node_modules/lilconfig": { "version": "3.1.3", - "resolved": "https://mirrors.tencent.com/npm/lilconfig/-/lilconfig-3.1.3.tgz", + "resolved": "https://registry.npmmirror.com/lilconfig/-/lilconfig-3.1.3.tgz", "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", "license": "MIT", "engines": { @@ -1894,13 +1973,13 @@ }, "node_modules/lines-and-columns": { "version": "1.2.4", - "resolved": "https://mirrors.tencent.com/npm/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "resolved": "https://registry.npmmirror.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, "node_modules/lucide-vue-next": { "version": "0.575.0", - "resolved": "https://mirrors.tencent.com/npm/lucide-vue-next/-/lucide-vue-next-0.575.0.tgz", + "resolved": "https://registry.npmmirror.com/lucide-vue-next/-/lucide-vue-next-0.575.0.tgz", "integrity": "sha512-UHzA3cYMCgBLyGay5R9IQaidwV0NLocx7cIBnFt8vJ9Xhl6IM/oKD0fUhoCUuouFta15SX1rLXVoko9s3TzWMA==", "license": "ISC", "peerDependencies": { @@ -1909,7 +1988,7 @@ }, "node_modules/luxon": { "version": "3.7.2", - "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz", + "resolved": "https://registry.npmmirror.com/luxon/-/luxon-3.7.2.tgz", "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==", "license": "MIT", "engines": { @@ -1918,7 +1997,7 @@ }, "node_modules/magic-string": { "version": "0.30.21", - "resolved": "https://mirrors.tencent.com/npm/magic-string/-/magic-string-0.30.21.tgz", + "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", "license": "MIT", "dependencies": { @@ -1926,9 +2005,9 @@ } }, "node_modules/marked": { - "version": "17.0.3", - "resolved": "https://mirrors.tencent.com/npm/marked/-/marked-17.0.3.tgz", - "integrity": "sha512-jt1v2ObpyOKR8p4XaUJVk3YWRJ5n+i4+rjQopxvV32rSndTJXvIzuUdWWIy/1pFQMkQmvTXawzDNqOH/CUmx6A==", + "version": "17.0.6", + "resolved": "https://registry.npmmirror.com/marked/-/marked-17.0.6.tgz", + "integrity": "sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==", "license": "MIT", "bin": { "marked": "bin/marked.js" @@ -1939,7 +2018,7 @@ }, "node_modules/merge2": { "version": "1.4.1", - "resolved": "https://mirrors.tencent.com/npm/merge2/-/merge2-1.4.1.tgz", + "resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "license": "MIT", "engines": { @@ -1948,7 +2027,7 @@ }, "node_modules/micromatch": { "version": "4.0.8", - "resolved": "https://mirrors.tencent.com/npm/micromatch/-/micromatch-4.0.8.tgz", + "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "license": "MIT", "dependencies": { @@ -1959,21 +2038,9 @@ "node": ">=8.6" } }, - "node_modules/micromatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/mini-svg-data-uri": { "version": "1.4.4", - "resolved": "https://mirrors.tencent.com/npm/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz", + "resolved": "https://registry.npmmirror.com/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz", "integrity": "sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==", "license": "MIT", "bin": { @@ -1982,20 +2049,20 @@ }, "node_modules/mitt": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "resolved": "https://registry.npmmirror.com/mitt/-/mitt-3.0.1.tgz", "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", "license": "MIT" }, "node_modules/muggle-string": { "version": "0.4.1", - "resolved": "https://mirrors.tencent.com/npm/muggle-string/-/muggle-string-0.4.1.tgz", + "resolved": "https://registry.npmmirror.com/muggle-string/-/muggle-string-0.4.1.tgz", "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", "dev": true, "license": "MIT" }, "node_modules/mz": { "version": "2.7.0", - "resolved": "https://mirrors.tencent.com/npm/mz/-/mz-2.7.0.tgz", + "resolved": "https://registry.npmmirror.com/mz/-/mz-2.7.0.tgz", "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", "license": "MIT", "dependencies": { @@ -2005,9 +2072,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://mirrors.tencent.com/npm/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "version": "3.3.16", + "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.16.tgz", + "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", "funding": [ { "type": "github", @@ -2023,15 +2090,18 @@ } }, "node_modules/node-releases": { - "version": "2.0.27", - "resolved": "https://mirrors.tencent.com/npm/node-releases/-/node-releases-2.0.27.tgz", - "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "version": "2.0.51", + "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.51.tgz", + "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/normalize-path": { "version": "3.0.0", - "resolved": "https://mirrors.tencent.com/npm/normalize-path/-/normalize-path-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "license": "MIT", "engines": { @@ -2040,7 +2110,7 @@ }, "node_modules/object-assign": { "version": "4.1.1", - "resolved": "https://mirrors.tencent.com/npm/object-assign/-/object-assign-4.1.1.tgz", + "resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", "license": "MIT", "engines": { @@ -2049,7 +2119,7 @@ }, "node_modules/object-hash": { "version": "3.0.0", - "resolved": "https://mirrors.tencent.com/npm/object-hash/-/object-hash-3.0.0.tgz", + "resolved": "https://registry.npmmirror.com/object-hash/-/object-hash-3.0.0.tgz", "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", "license": "MIT", "engines": { @@ -2057,9 +2127,9 @@ } }, "node_modules/obug": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.2.tgz", - "integrity": "sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==", + "version": "2.1.4", + "resolved": "https://registry.npmmirror.com/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", "dev": true, "funding": [ "https://github.com/sponsors/sxzz", @@ -2072,43 +2142,43 @@ }, "node_modules/path-browserify": { "version": "1.0.1", - "resolved": "https://mirrors.tencent.com/npm/path-browserify/-/path-browserify-1.0.1.tgz", + "resolved": "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", "dev": true, "license": "MIT" }, "node_modules/path-parse": { "version": "1.0.7", - "resolved": "https://mirrors.tencent.com/npm/path-parse/-/path-parse-1.0.7.tgz", + "resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "license": "MIT" }, "node_modules/pathe": { "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "resolved": "https://registry.npmmirror.com/pathe/-/pathe-2.0.3.tgz", "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", "dev": true, "license": "MIT" }, "node_modules/perfect-debounce": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/perfect-debounce/-/perfect-debounce-1.0.0.tgz", "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", "license": "MIT" }, "node_modules/picocolors": { "version": "1.1.1", - "resolved": "https://mirrors.tencent.com/npm/picocolors/-/picocolors-1.1.1.tgz", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "version": "2.3.2", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "license": "MIT", "engines": { - "node": ">=12" + "node": ">=8.6" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" @@ -2116,7 +2186,7 @@ }, "node_modules/pify": { "version": "2.3.0", - "resolved": "https://mirrors.tencent.com/npm/pify/-/pify-2.3.0.tgz", + "resolved": "https://registry.npmmirror.com/pify/-/pify-2.3.0.tgz", "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", "license": "MIT", "engines": { @@ -2125,7 +2195,7 @@ }, "node_modules/pinia": { "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.4.tgz", + "resolved": "https://registry.npmmirror.com/pinia/-/pinia-3.0.4.tgz", "integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==", "license": "MIT", "dependencies": { @@ -2144,18 +2214,9 @@ } } }, - "node_modules/pinia/node_modules/@vue/devtools-api": { - "version": "7.7.9", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz", - "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", - "license": "MIT", - "dependencies": { - "@vue/devtools-kit": "^7.7.9" - } - }, "node_modules/pirates": { "version": "4.0.7", - "resolved": "https://mirrors.tencent.com/npm/pirates/-/pirates-4.0.7.tgz", + "resolved": "https://registry.npmmirror.com/pirates/-/pirates-4.0.7.tgz", "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", "license": "MIT", "engines": { @@ -2163,9 +2224,9 @@ } }, "node_modules/postcss": { - "version": "8.5.6", - "resolved": "https://mirrors.tencent.com/npm/postcss/-/postcss-8.5.6.tgz", - "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "version": "8.5.21", + "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.21.tgz", + "integrity": "sha512-v4sDNP3fdNiWMfabO7OwOQdOX8TiQSztKyT1Wj0w+j7LDallJThJRBBBmzVGyYj0crMh7jlV4zepPkiNu9UwDQ==", "funding": [ { "type": "opencollective", @@ -2182,7 +2243,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.11", + "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -2192,7 +2253,7 @@ }, "node_modules/postcss-import": { "version": "15.1.0", - "resolved": "https://mirrors.tencent.com/npm/postcss-import/-/postcss-import-15.1.0.tgz", + "resolved": "https://registry.npmmirror.com/postcss-import/-/postcss-import-15.1.0.tgz", "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", "license": "MIT", "dependencies": { @@ -2209,7 +2270,7 @@ }, "node_modules/postcss-js": { "version": "4.1.0", - "resolved": "https://mirrors.tencent.com/npm/postcss-js/-/postcss-js-4.1.0.tgz", + "resolved": "https://registry.npmmirror.com/postcss-js/-/postcss-js-4.1.0.tgz", "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", "funding": [ { @@ -2233,9 +2294,9 @@ } }, "node_modules/postcss-load-config": { - "version": "4.0.2", - "resolved": "https://mirrors.tencent.com/npm/postcss-load-config/-/postcss-load-config-4.0.2.tgz", - "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", "funding": [ { "type": "opencollective", @@ -2248,28 +2309,35 @@ ], "license": "MIT", "dependencies": { - "lilconfig": "^3.0.0", - "yaml": "^2.3.4" + "lilconfig": "^3.1.1" }, "engines": { - "node": ">= 14" + "node": ">= 18" }, "peerDependencies": { + "jiti": ">=1.21.0", "postcss": ">=8.0.9", - "ts-node": ">=9.0.0" + "tsx": "^4.8.1", + "yaml": "^2.4.2" }, "peerDependenciesMeta": { + "jiti": { + "optional": true + }, "postcss": { "optional": true }, - "ts-node": { + "tsx": { + "optional": true + }, + "yaml": { "optional": true } } }, "node_modules/postcss-nested": { "version": "6.2.0", - "resolved": "https://mirrors.tencent.com/npm/postcss-nested/-/postcss-nested-6.2.0.tgz", + "resolved": "https://registry.npmmirror.com/postcss-nested/-/postcss-nested-6.2.0.tgz", "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", "funding": [ { @@ -2292,10 +2360,23 @@ "postcss": "^8.2.14" } }, + "node_modules/postcss-nested/node_modules/postcss-selector-parser": { + "version": "6.1.4", + "resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", + "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/postcss-selector-parser": { - "version": "6.1.2", - "resolved": "https://mirrors.tencent.com/npm/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", - "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "version": "6.0.10", + "resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", + "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -2307,13 +2388,13 @@ }, "node_modules/postcss-value-parser": { "version": "4.2.0", - "resolved": "https://mirrors.tencent.com/npm/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "resolved": "https://registry.npmmirror.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, "node_modules/queue-microtask": { "version": "1.2.3", - "resolved": "https://mirrors.tencent.com/npm/queue-microtask/-/queue-microtask-1.2.3.tgz", + "resolved": "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "funding": [ { @@ -2333,7 +2414,7 @@ }, "node_modules/read-cache": { "version": "1.0.0", - "resolved": "https://mirrors.tencent.com/npm/read-cache/-/read-cache-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/read-cache/-/read-cache-1.0.0.tgz", "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", "license": "MIT", "dependencies": { @@ -2342,7 +2423,7 @@ }, "node_modules/readdirp": { "version": "3.6.0", - "resolved": "https://mirrors.tencent.com/npm/readdirp/-/readdirp-3.6.0.tgz", + "resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-3.6.0.tgz", "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "license": "MIT", "dependencies": { @@ -2352,24 +2433,13 @@ "node": ">=8.10.0" } }, - "node_modules/readdirp/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/resolve": { - "version": "1.22.11", - "resolved": "https://mirrors.tencent.com/npm/resolve/-/resolve-1.22.11.tgz", - "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "version": "1.22.12", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", "license": "MIT", "dependencies": { + "es-errors": "^1.3.0", "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" @@ -2386,7 +2456,7 @@ }, "node_modules/reusify": { "version": "1.1.0", - "resolved": "https://mirrors.tencent.com/npm/reusify/-/reusify-1.1.0.tgz", + "resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz", "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", "license": "MIT", "engines": { @@ -2396,19 +2466,19 @@ }, "node_modules/rfdc": { "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "resolved": "https://registry.npmmirror.com/rfdc/-/rfdc-1.4.1.tgz", "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", "license": "MIT" }, "node_modules/rolldown": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/rolldown/-/rolldown-1.0.0-rc.5.tgz", - "integrity": "sha512-0AdalTs6hNTioaCYIkAa7+xsmHBfU5hCNclZnM/lp7lGGDuUOb6N4BVNtwiomybbencDjq/waKjTImqiGCs5sw==", + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.1.5.tgz", + "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.114.0", - "@rolldown/pluginutils": "1.0.0-rc.5" + "@oxc-project/types": "=0.139.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { "rolldown": "bin/cli.mjs" @@ -2417,48 +2487,26 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.5", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.5", - "@rolldown/binding-darwin-x64": "1.0.0-rc.5", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.5", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.5", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.5", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.5", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.5", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.5", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.5", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.5", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.5", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.5" + "@rolldown/binding-android-arm64": "1.1.5", + "@rolldown/binding-darwin-arm64": "1.1.5", + "@rolldown/binding-darwin-x64": "1.1.5", + "@rolldown/binding-freebsd-x64": "1.1.5", + "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", + "@rolldown/binding-linux-arm64-gnu": "1.1.5", + "@rolldown/binding-linux-arm64-musl": "1.1.5", + "@rolldown/binding-linux-ppc64-gnu": "1.1.5", + "@rolldown/binding-linux-s390x-gnu": "1.1.5", + "@rolldown/binding-linux-x64-gnu": "1.1.5", + "@rolldown/binding-linux-x64-musl": "1.1.5", + "@rolldown/binding-openharmony-arm64": "1.1.5", + "@rolldown/binding-wasm32-wasi": "1.1.5", + "@rolldown/binding-win32-arm64-msvc": "1.1.5", + "@rolldown/binding-win32-x64-msvc": "1.1.5" } }, - "node_modules/rolldown/node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.5.tgz", - "integrity": "sha512-VQ8F9ld5gw29epjnVGdrx8ugiLTe8BMqmhDYy7nGbdeDo4HAt4bgdZvLbViEhg7DZyHLpiEUlO5/jPSUrIuxRQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/rolldown/node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.5", - "resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.5.tgz", - "integrity": "sha512-RxlLX/DPoarZ9PtxVrQgZhPoor987YtKQqCo5zkjX+0S0yLJ7Vv515Wk6+xtTL67VONKJKxETWZwuZjss2idYw==", - "dev": true, - "license": "MIT" - }, "node_modules/run-parallel": { "version": "1.2.0", - "resolved": "https://mirrors.tencent.com/npm/run-parallel/-/run-parallel-1.2.0.tgz", + "resolved": "https://registry.npmmirror.com/run-parallel/-/run-parallel-1.2.0.tgz", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "funding": [ { @@ -2481,14 +2529,14 @@ }, "node_modules/siginfo": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz", "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", "dev": true, "license": "ISC" }, "node_modules/source-map-js": { "version": "1.2.1", - "resolved": "https://mirrors.tencent.com/npm/source-map-js/-/source-map-js-1.2.1.tgz", + "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "license": "BSD-3-Clause", "engines": { @@ -2497,7 +2545,7 @@ }, "node_modules/speakingurl": { "version": "14.0.1", - "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz", + "resolved": "https://registry.npmmirror.com/speakingurl/-/speakingurl-14.0.1.tgz", "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", "license": "BSD-3-Clause", "engines": { @@ -2506,7 +2554,7 @@ }, "node_modules/ssf": { "version": "0.11.2", - "resolved": "https://mirrors.tencent.com/npm/ssf/-/ssf-0.11.2.tgz", + "resolved": "https://registry.npmmirror.com/ssf/-/ssf-0.11.2.tgz", "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", "license": "Apache-2.0", "dependencies": { @@ -2518,21 +2566,21 @@ }, "node_modules/stackback": { "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz", "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", "dev": true, "license": "MIT" }, "node_modules/std-env": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", - "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==", + "version": "4.2.0", + "resolved": "https://registry.npmmirror.com/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", "dev": true, "license": "MIT" }, "node_modules/sucrase": { "version": "3.35.1", - "resolved": "https://mirrors.tencent.com/npm/sucrase/-/sucrase-3.35.1.tgz", + "resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz", "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", "license": "MIT", "dependencies": { @@ -2554,7 +2602,7 @@ }, "node_modules/superjson": { "version": "2.2.6", - "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz", + "resolved": "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", "integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==", "license": "MIT", "dependencies": { @@ -2566,7 +2614,7 @@ }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", - "resolved": "https://mirrors.tencent.com/npm/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "license": "MIT", "engines": { @@ -2577,9 +2625,9 @@ } }, "node_modules/tailwindcss": { - "version": "3.4.17", - "resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz", - "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", + "version": "3.4.19", + "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-3.4.19.tgz", + "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", "license": "MIT", "dependencies": { "@alloc/quick-lru": "^5.2.0", @@ -2590,7 +2638,7 @@ "fast-glob": "^3.3.2", "glob-parent": "^6.0.2", "is-glob": "^4.0.3", - "jiti": "^1.21.6", + "jiti": "^1.21.7", "lilconfig": "^3.1.3", "micromatch": "^4.0.8", "normalize-path": "^3.0.0", @@ -2599,7 +2647,7 @@ "postcss": "^8.4.47", "postcss-import": "^15.1.0", "postcss-js": "^4.0.1", - "postcss-load-config": "^4.0.2", + "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", "postcss-nested": "^6.2.0", "postcss-selector-parser": "^6.1.2", "resolve": "^1.22.8", @@ -2613,9 +2661,22 @@ "node": ">=14.0.0" } }, + "node_modules/tailwindcss/node_modules/postcss-selector-parser": { + "version": "6.1.4", + "resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", + "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/thenify": { "version": "3.3.1", - "resolved": "https://mirrors.tencent.com/npm/thenify/-/thenify-3.3.1.tgz", + "resolved": "https://registry.npmmirror.com/thenify/-/thenify-3.3.1.tgz", "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", "license": "MIT", "dependencies": { @@ -2624,7 +2685,7 @@ }, "node_modules/thenify-all": { "version": "1.6.0", - "resolved": "https://mirrors.tencent.com/npm/thenify-all/-/thenify-all-1.6.0.tgz", + "resolved": "https://registry.npmmirror.com/thenify-all/-/thenify-all-1.6.0.tgz", "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", "license": "MIT", "dependencies": { @@ -2636,14 +2697,14 @@ }, "node_modules/tinybench": { "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-2.9.0.tgz", "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", "dev": true, "license": "MIT" }, "node_modules/tinyexec": { "version": "1.2.4", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", + "resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-1.2.4.tgz", "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", "dev": true, "license": "MIT", @@ -2652,13 +2713,13 @@ } }, "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://mirrors.tencent.com/npm/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "version": "0.2.17", + "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "license": "MIT", "dependencies": { "fdir": "^6.5.0", - "picomatch": "^4.0.3" + "picomatch": "^4.0.4" }, "engines": { "node": ">=12.0.0" @@ -2667,9 +2728,38 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/tinyrainbow": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/tinyrainbow/-/tinyrainbow-3.1.0.tgz", "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", "dev": true, "license": "MIT", @@ -2679,7 +2769,7 @@ }, "node_modules/to-regex-range": { "version": "5.0.1", - "resolved": "https://mirrors.tencent.com/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", + "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "license": "MIT", "dependencies": { @@ -2691,13 +2781,13 @@ }, "node_modules/ts-interface-checker": { "version": "0.1.13", - "resolved": "https://mirrors.tencent.com/npm/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "resolved": "https://registry.npmmirror.com/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", "license": "Apache-2.0" }, "node_modules/tslib": { "version": "2.8.1", - "resolved": "https://mirrors.tencent.com/npm/tslib/-/tslib-2.8.1.tgz", + "resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, "license": "0BSD", @@ -2705,7 +2795,7 @@ }, "node_modules/typescript": { "version": "5.9.3", - "resolved": "https://mirrors.tencent.com/npm/typescript/-/typescript-5.9.3.tgz", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", @@ -2718,15 +2808,15 @@ } }, "node_modules/undici-types": { - "version": "7.16.0", - "resolved": "https://mirrors.tencent.com/npm/undici-types/-/undici-types-7.16.0.tgz", - "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "version": "7.18.2", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", "dev": true, "license": "MIT" }, "node_modules/update-browserslist-db": { "version": "1.2.3", - "resolved": "https://mirrors.tencent.com/npm/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "resolved": "https://registry.npmmirror.com/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ @@ -2757,23 +2847,22 @@ }, "node_modules/util-deprecate": { "version": "1.0.2", - "resolved": "https://mirrors.tencent.com/npm/util-deprecate/-/util-deprecate-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, "node_modules/vite": { - "version": "8.0.0-beta.15", - "resolved": "https://mirrors.tencent.com/npm/vite/-/vite-8.0.0-beta.15.tgz", - "integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==", + "version": "8.1.5", + "resolved": "https://registry.npmmirror.com/vite/-/vite-8.1.5.tgz", + "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/runtime": "0.114.0", - "lightningcss": "^1.31.1", - "picomatch": "^4.0.3", - "postcss": "^8.5.6", - "rolldown": "1.0.0-rc.5", - "tinyglobby": "^0.2.15" + "lightningcss": "^1.32.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.17", + "rolldown": "~1.1.5", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" @@ -2789,8 +2878,8 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.0.0-alpha.31", - "esbuild": "^0.27.0", + "@vitejs/devtools": "^0.3.0", + "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", @@ -2840,20 +2929,33 @@ } } }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/vitest": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.8.tgz", - "integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==", + "version": "4.1.10", + "resolved": "https://registry.npmmirror.com/vitest/-/vitest-4.1.10.tgz", + "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.8", - "@vitest/mocker": "4.1.8", - "@vitest/pretty-format": "4.1.8", - "@vitest/runner": "4.1.8", - "@vitest/snapshot": "4.1.8", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/expect": "4.1.10", + "@vitest/mocker": "4.1.10", + "@vitest/pretty-format": "4.1.10", + "@vitest/runner": "4.1.10", + "@vitest/snapshot": "4.1.10", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -2881,12 +2983,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.8", - "@vitest/browser-preview": "4.1.8", - "@vitest/browser-webdriverio": "4.1.8", - "@vitest/coverage-istanbul": "4.1.8", - "@vitest/coverage-v8": "4.1.8", - "@vitest/ui": "4.1.8", + "@vitest/browser-playwright": "4.1.10", + "@vitest/browser-preview": "4.1.10", + "@vitest/browser-webdriverio": "4.1.10", + "@vitest/coverage-istanbul": "4.1.10", + "@vitest/coverage-v8": "4.1.10", + "@vitest/ui": "4.1.10", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" @@ -2930,24 +3032,37 @@ } } }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/vscode-uri": { "version": "3.1.0", - "resolved": "https://mirrors.tencent.com/npm/vscode-uri/-/vscode-uri-3.1.0.tgz", + "resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.1.0.tgz", "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", "dev": true, "license": "MIT" }, "node_modules/vue": { - "version": "3.5.28", - "resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz", - "integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==", + "version": "3.5.40", + "resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.40.tgz", + "integrity": "sha512-+8PJ4SJXdn/cHGImF4CKdxlWHIN5Dkt7DoufRREM6h6uVCx2m7QxgcEQmmzyOK8A9mcafg7sFbJFYsdFVubTig==", "license": "MIT", "dependencies": { - "@vue/compiler-dom": "3.5.28", - "@vue/compiler-sfc": "3.5.28", - "@vue/runtime-dom": "3.5.28", - "@vue/server-renderer": "3.5.28", - "@vue/shared": "3.5.28" + "@vue/compiler-dom": "3.5.40", + "@vue/compiler-sfc": "3.5.40", + "@vue/runtime-dom": "3.5.40", + "@vue/server-renderer": "3.5.40", + "@vue/shared": "3.5.40" }, "peerDependencies": { "typescript": "*" @@ -2960,7 +3075,7 @@ }, "node_modules/vue-demi": { "version": "0.14.10", - "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz", + "resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.14.10.tgz", "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", "hasInstallScript": true, "license": "MIT", @@ -2986,17 +3101,18 @@ } }, "node_modules/vue-i18n": { - "version": "11.2.8", - "resolved": "https://mirrors.tencent.com/npm/vue-i18n/-/vue-i18n-11.2.8.tgz", - "integrity": "sha512-vJ123v/PXCZntd6Qj5Jumy7UBmIuE92VrtdX+AXr+1WzdBHojiBxnAxdfctUFL+/JIN+VQH4BhsfTtiGsvVObg==", + "version": "11.4.7", + "resolved": "https://registry.npmmirror.com/vue-i18n/-/vue-i18n-11.4.7.tgz", + "integrity": "sha512-j6RyshdPPzqLiMAUpnpvZGFPM+rRoWi14Sl5yTsquvoW0/56DWyvhAj2o9TO2YXGvb6teg8T0xrYO9jR3urvdw==", "license": "MIT", "dependencies": { - "@intlify/core-base": "11.2.8", - "@intlify/shared": "11.2.8", + "@intlify/core-base": "11.4.7", + "@intlify/devtools-types": "11.4.7", + "@intlify/shared": "11.4.7", "@vue/devtools-api": "^6.5.0" }, "engines": { - "node": ">= 16" + "node": ">= 22" }, "funding": { "url": "https://github.com/sponsors/kazupon" @@ -3005,9 +3121,15 @@ "vue": "^3.0.0" } }, + "node_modules/vue-i18n/node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, "node_modules/vue-router": { "version": "4.6.4", - "resolved": "https://mirrors.tencent.com/npm/vue-router/-/vue-router-4.6.4.tgz", + "resolved": "https://registry.npmmirror.com/vue-router/-/vue-router-4.6.4.tgz", "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", "license": "MIT", "dependencies": { @@ -3020,15 +3142,21 @@ "vue": "^3.5.0" } }, + "node_modules/vue-router/node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, "node_modules/vue-tsc": { - "version": "3.2.5", - "resolved": "https://mirrors.tencent.com/npm/vue-tsc/-/vue-tsc-3.2.5.tgz", - "integrity": "sha512-/htfTCMluQ+P2FISGAooul8kO4JMheOTCbCy4M6dYnYYjqLe3BExZudAua6MSIKSFYQtFOYAll7XobYwcpokGA==", + "version": "3.3.7", + "resolved": "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-3.3.7.tgz", + "integrity": "sha512-+C+rgD49wAQ5bUTl2sp5a8Bzg4YoldMNXM+g7CFe604MYcQ8PrZPMQhIjJSzKXtPBCa+C5ayMipqjbA7splekQ==", "dev": true, "license": "MIT", "dependencies": { "@volar/typescript": "2.4.28", - "@vue/language-core": "3.2.5" + "@vue/language-core": "3.3.7" }, "bin": { "vue-tsc": "bin/vue-tsc.js" @@ -3039,7 +3167,7 @@ }, "node_modules/why-is-node-running": { "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz", "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", "dev": true, "license": "MIT", @@ -3056,7 +3184,7 @@ }, "node_modules/wmf": { "version": "1.0.2", - "resolved": "https://mirrors.tencent.com/npm/wmf/-/wmf-1.0.2.tgz", + "resolved": "https://registry.npmmirror.com/wmf/-/wmf-1.0.2.tgz", "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", "license": "Apache-2.0", "engines": { @@ -3065,7 +3193,7 @@ }, "node_modules/word": { "version": "0.3.0", - "resolved": "https://mirrors.tencent.com/npm/word/-/word-0.3.0.tgz", + "resolved": "https://registry.npmmirror.com/word/-/word-0.3.0.tgz", "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", "license": "Apache-2.0", "engines": { @@ -3074,7 +3202,7 @@ }, "node_modules/xlsx": { "version": "0.18.5", - "resolved": "https://mirrors.tencent.com/npm/xlsx/-/xlsx-0.18.5.tgz", + "resolved": "https://registry.npmmirror.com/xlsx/-/xlsx-0.18.5.tgz", "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", "license": "Apache-2.0", "dependencies": { @@ -3092,21 +3220,6 @@ "engines": { "node": ">=0.8" } - }, - "node_modules/yaml": { - "version": "2.8.2", - "resolved": "https://mirrors.tencent.com/npm/yaml/-/yaml-2.8.2.tgz", - "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==", - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } } } } diff --git a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue index 68f20c36..61e833a7 100644 --- a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue +++ b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue @@ -5,8 +5,12 @@ * 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。 */