From 0a9bd6415dec2021842e932d35d1bdfe6ab20d0f Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 13 Jul 2026 21:53:45 +0800 Subject: [PATCH 1/5] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=BA=93=E5=AD=98=E7=A1=AE=E8=AE=A4=E6=9D=A5=E6=BA=90=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=8F=8A=E7=9B=B8=E5=85=B3=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/shipping_notice_tools.py | 21 + backend/app/api/workspace/shipping_notice.py | 6 +- backend/app/models/shipping.py | 56 + .../services/schedule/scheduler_service.py | 53 +- .../shipping_notice/chat_action_handlers.py | 1 + .../shipping_notice/decision_workflow.py | 63 +- .../shipping_notice/fulfillment_workflow.py | 28 + backend/app/services/shipping_notice/i18n.py | 6 +- .../inventory_file_identity.py | 296 +++ .../shipping_notice/inventory_file_store.py | 198 +- .../inventory_mapping_workflow.py | 19 +- .../inventory_rpa_callback_cleanup.py | 300 +++ .../shipping_notice/inventory_rpa_workflow.py | 1773 ++++++++++++++--- .../shipping_notice/inventory_snapshot.py | 13 +- .../inventory_snapshot_store.py | 278 ++- .../shipping_notice/inventory_source_gate.py | 402 ++++ .../inventory_source_identity.py | 156 ++ .../shipping_notice/inventory_source_rules.py | 558 +++++- .../shipping_notice/inventory_sources.py | 214 +- .../shipping_notice/inventory_upload.py | 361 +++- .../shipping_notice/inventory_workflow.py | 69 +- .../services/shipping_notice/openapi_spec.py | 28 +- .../shipping_notice/progress_workflow.py | 33 +- .../services/shipping_notice/query_service.py | 14 + .../services/shipping_notice/queue_service.py | 17 +- backend/app/services/shipping_notice/rpa.py | 3 +- .../services/shipping_notice/state_machine.py | 2 +- .../services/shipping_notice/task_workflow.py | 107 +- backend/app/services/shipping_notice/tools.py | 1 + .../app/services/shipping_notice/ui_state.py | 12 +- .../config/shipping_inventory_sources.yaml | 13 +- ...d_shipping_inventory_source_gate_fields.py | 257 +++ ...0c1_add_rpa_callback_idempotency_fields.py | 276 +++ backend/tests/conftest.py | 189 +- backend/tests/test_shipping_notice_batches.py | 9 +- ...t_shipping_notice_inventory_rpa_archive.py | 30 +- ..._shipping_notice_inventory_rpa_workflow.py | 953 ++++++++- ...test_shipping_notice_inventory_schedule.py | 304 ++- ...hipping_notice_inventory_snapshot_reuse.py | 166 +- ...t_shipping_notice_inventory_source_gate.py | 1045 ++++++++++ ...hipping_notice_inventory_sources_config.py | 76 +- backend/tests/test_shipping_notice_tools.py | 122 +- docs/demand.md | 9 + docs/features/shipping-notice/business.md | 2 +- .../shipping-notice/inventory_source_plan.md | 137 +- docs/features/shipping-notice/technical.md | 22 +- docs/funclist.md | 3 + docs/openapi/shipping_notice_tools.dify.json | 50 +- docs/tec.md | 1 + .../useScheduleAdminDeepLink.ts | 15 +- .../features/chat/components/ChatInputBar.vue | 2 +- .../ShippingBatchWorkspaceDrawer.vue | 18 + .../features/chat/shipping/shippingStepper.ts | 8 +- .../shipping/useChatShippingMenuHandler.ts | 12 +- .../shipping/useChatShippingSendHandler.ts | 6 +- .../features/chat/types/shipping.api.types.ts | 52 +- .../workspace/views/ShippingNoticeView.vue | 64 + frontend/src/locales/en/chat.json | 35 + frontend/src/locales/en/errors.json | 12 +- frontend/src/locales/en/workspace.json | 25 + frontend/src/locales/th/chat.json | 35 + frontend/src/locales/th/errors.json | 12 +- frontend/src/locales/th/workspace.json | 25 + frontend/src/locales/zh-CN/chat.json | 35 + frontend/src/locales/zh-CN/errors.json | 12 +- frontend/src/locales/zh-CN/workspace.json | 25 + frontend/src/locales/zh-TW/chat.json | 35 + frontend/src/locales/zh-TW/errors.json | 12 +- frontend/src/locales/zh-TW/workspace.json | 25 + 69 files changed, 8442 insertions(+), 775 deletions(-) create mode 100644 backend/app/services/shipping_notice/inventory_file_identity.py create mode 100644 backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py create mode 100644 backend/app/services/shipping_notice/inventory_source_gate.py create mode 100644 backend/app/services/shipping_notice/inventory_source_identity.py create mode 100644 backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py create mode 100644 backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py create mode 100644 backend/tests/test_shipping_notice_inventory_source_gate.py diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 5a65cd14..e1ef3eb2 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -262,6 +262,16 @@ def tool_submit_decision(): """ return jsonify(shipping_tools.submit_decision(_payload())) + +@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST']) +def tool_confirm_inventory_source(): + """ + 确认库存查询来源(仅提交 source_code)。 + 【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。 + """ + return jsonify(shipping_tools.confirm_inventory_source(_payload())) + + @shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST']) def tool_generate_shipment_excel(): """ @@ -353,6 +363,17 @@ def rpa_inventory_batch_ready(): """RPA 批量库存导出回调:按 Warehouse 写入库存快照。""" return jsonify(shipping_tools.rpa_report_inventory_batch(_payload())) +@shipping_notice_bp.route('/tasks//repair-inventory-attachment', methods=['POST']) +def repair_task_inventory_attachment(task_no: str): + """ + 从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。 + 核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。 + """ + payload = _payload() + payload.setdefault("task_no", task_no) + payload.setdefault("task_id", task_no) + return jsonify(shipping_tools.repair_task_inventory_attachment(payload)) + @shipping_notice_bp.route('/rpa/upload-complete', methods=['POST']) def rpa_upload_complete(): """RPA 回调入口:上报货代上传结果并回写任务状态。""" diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 62271c1e..7e16d7a8 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -362,7 +362,11 @@ def workspace_confirm_shipping_inventory_source(task_no: str): if not source_code: raise ValidationError('source_code is required') from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code})) + return jsonify(shipping_tools.confirm_inventory_source({ + 'task_id': task.task_no, + 'source_code': source_code, + '_trusted_user_id': user.id, + })) @workspace_shipping_notice_bp.route('/shipping-tasks//apply-inventory-mapping', methods=['POST']) def workspace_apply_inventory_mapping(task_no: str): diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 45b6104a..3cdfb6a6 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -3,6 +3,7 @@ backend/app/models/shipping.py 用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。 依赖:models.base.Base。 +逻辑:ShippingTask 独立字段承载目的地与库存源身份;step_payload_json 仅保留候选/证据等辅助信息。 """ from __future__ import annotations @@ -59,6 +60,11 @@ class ShippingTask(Base): Index('ix_shipping_tasks_conversation', 'conversation_id'), Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'), Index('ix_shipping_tasks_upload_status', 'upload_status'), + Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'), + Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'), + Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'), + Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), + Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -76,6 +82,21 @@ class ShippingTask(Base): customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list) @@ -150,6 +171,28 @@ class ShippingInventoryFile(Base): 'snapshot_status', 'exported_at', ), + Index( + 'ix_shipping_inventory_files_source_site_wh', + 'source_code', + 'site_id', + 'warehouse_id', + ), + Index( + 'uq_shipping_inventory_files_rpa_identity_ready', + 'rpa_run_no', + 'source_code', + 'site_id', + 'warehouse_id', + unique=True, + postgresql_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL" + ), + sqlite_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL" + ), + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -167,6 +210,9 @@ class ShippingInventoryFile(Base): share_mode: Mapped[str] = mapped_column(String(32), default='task_only') warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) @@ -193,6 +239,12 @@ class ShippingTaskInventoryLink(Base): __table_args__ = ( Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'), Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'), + Index( + 'ix_shipping_task_inventory_links_task_source', + 'task_id', + 'matched_source_code', + 'matched_site_id', + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -203,6 +255,10 @@ class ShippingTaskInventoryLink(Base): is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True) link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index b9f4cb6d..a665a8a1 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -80,7 +80,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) """ 构造排程企微 textcard 跳转 query 参数。 - 核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 供深链展示下载入口。 + 核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图, + 由前端在登录后自动触发一次下载,失败时保留手动下载入口。 """ from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary @@ -91,6 +92,7 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) } if inventory_raw_zip_available_from_summary(summary): params['raw_zip'] = '1' + params['download'] = 'inventory_raw_zip' return params @@ -99,7 +101,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: 组装排程完成企微 textcard 正文。 核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数; - 有原始库存归档时提示点击卡片进入 HXOPS(URL 仅放 jump_url,不写进正文)。 + 有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。 """ status_label = _WECOM_STATUS_LABEL.get(run.status, run.status) skipped_count = int(run.skipped_count or 0) @@ -115,7 +117,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary if inventory_raw_zip_available_from_summary(summary): - description += '\n原始库存包:点击本通知进入 HXOPS 下载' + description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' return description @@ -160,6 +162,19 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: run.run_no, exc, ) + raw_zip_media_id = None + raw_zip_file_name = None + try: + from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download + + raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run) + raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name) + except Exception as exc: + current_app.logger.info( + '[wecom-schedule] raw inventory zip media skipped for run %s: %s', + run.run_no, exc, + ) + textcard_ok_count = 0 errors = [] @@ -199,6 +214,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: except Exception as exc: errors.append(f'{u.real_name or u.username}: file exception={exc}') + if raw_zip_media_id: + try: + raw_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_inventory_raw_zip', u, + title, f'[原始库存包] {raw_zip_file_name}', uuid.uuid4().hex, + ) + raw_zip_data = send_wecom_file_message(u.wecom_userid, raw_zip_media_id) + if raw_zip_data.get('errcode') == 0: + raw_zip_audit.status = 'sent' + else: + raw_zip_audit.error_code = str(raw_zip_data.get('errcode')) + raw_zip_audit.error_message = str(raw_zip_data.get('errmsg', 'unknown'))[:255] + errors.append(f'{u.real_name or u.username}: raw zip errcode={raw_zip_data.get("errcode")}') + except Exception as exc: + errors.append(f'{u.real_name or u.username}: raw zip exception={exc}') + if textcard_ok_count > 0: run.wecom_notified = True run.wecom_notified_at = datetime.utcnow() @@ -641,6 +672,22 @@ def start_scheduler(app): recovered_awaiting, ) + from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + recover_pending_rpa_callback_cleanup_jobs, + ) + + cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs() + if cleanup_count: + current_app.logger.info( + "[schedule-worker] processed %d RPA callback cleanup job(s) on startup", + cleanup_count, + ) + if cleanup_warnings: + current_app.logger.warning( + "[schedule-worker] RPA callback cleanup warnings: %s", + "; ".join(cleanup_warnings[:5]), + ) + from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status maybe_alert_rpa_worker_status(force=True) diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index 39223e4f..74cd6412 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -264,6 +264,7 @@ class ShippingConfirmInventorySourceAction: "task_id": task.task_no, "source_code": source_code, "event_source": "chat_turn", + "_trusted_user_id": ctx.user_id, }) if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed": raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed") diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index 95ec5c8d..60f471ae 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -12,8 +12,10 @@ from typing import Any from app import db from app.services.shipping_notice.constants import ( + CP_INVENTORY_SOURCE_REVIEW, CP_MAP_INFER, CP_PARSE_OK, + PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, PH_RPA_PENDING, PH_SHORTAGE, @@ -36,9 +38,17 @@ from app.services.shipping_notice.inventory_file_store import ( from app.services.shipping_notice.inventory_upload import ( has_uploaded_task_inventory, read_task_inventory_schema_preview, + resolve_task_inventory_upload_path, task_inventory_upload_path, ) from app.services.shipping_notice.inventory_workflow import ensure_inventory +from app.services.shipping_notice.inventory_source_gate import ( + is_inventory_source_stable, + adjudicate_and_apply_inventory_source, + ensure_inventory_source_review_state, + task_needs_parse_review, + transition_task_to_inventory_source_review, +) from app.services.shipping_notice.i18n import resolve_lang, t from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state @@ -160,6 +170,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: and not match_completed(task) ) ): + is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF + if ( + not is_low_confidence_parse_confirm + and ( + task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED + or not is_inventory_source_stable(task) + ) + ): + ui = resolve_task_ui_state(task) + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + data=serialize_task_for_tool(task), + human_options=ui.human_options, + checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + ) apply_task_transition(task, TaskTransition.CONFIRM_PARSE) task.match_status = None task.shortage_json = None @@ -172,6 +200,24 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: comment=comment, ) db.session.commit() + if not is_inventory_source_stable(task): + adjudication = ensure_inventory_source_review_state(task) + db.session.commit() + return tool_response( + status="ok", + task=task, + message="解析内容已确认,请继续选择正式库存源。", + data={ + **serialize_task_for_tool(task), + "inventory_source_candidates": adjudication.candidates, + "inventory_source_status": adjudication.status, + "inventory_source_reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + }, + checkpoint=CP_INVENTORY_SOURCE_REVIEW, + human_options=resolve_task_ui_state(task).human_options, + stop_agent_turn=True, + ) if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)): orchestrator_started = start_task_orchestrator(task.task_no) return tool_response( @@ -408,8 +454,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.CORRECT_MAPPING) log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment}) db.session.commit() - upload_path = task_inventory_upload_path(task.task_no) - if upload_path.is_file(): + upload_path = resolve_task_inventory_upload_path(task.task_no) + if upload_path is not None: try: preview = read_task_inventory_schema_preview(task.task_no) except OSError as exc: @@ -444,12 +490,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE) else: apply_task_transition(task, TaskTransition.REPARSE_INVENTORY) - upload_path = task_inventory_upload_path(task.task_no) - if upload_path.is_file(): - try: - upload_path.unlink() - except OSError: - pass + for suffix in (".xlsx", ".csv"): + upload_path = task_inventory_upload_path(task.task_no, suffix=suffix) + if upload_path.is_file(): + try: + upload_path.unlink() + except OSError: + pass log_task_event(task, "inventory_reparse_requested", {"comment": comment}) db.session.commit() return tool_response( diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index c701e5de..57ea6cc6 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -39,6 +39,7 @@ from app.services.shipping_notice.rpa_attempts import ( max_rpa_upload_attempts, upload_rpa_attempts, ) +from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response @@ -270,6 +271,16 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) + if not is_inventory_source_stable(task): + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,无法执行库存匹配。", + data=serialize_task_for_tool(task), + checkpoint="inventory_source_review", + stop_agent_turn=True, + ) + # [STEP 3] 执行匹配并按结果分流。 # fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。 def _on_match_progress(processed: int, total: int) -> None: @@ -363,6 +374,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + if not is_inventory_source_stable(task): + return tool_response( + status="failed", + task=task, + message="库存源尚未确定,无法生成发货 Excel。", + data=serialize_task_for_tool(task), + forbidden_next_tools=["upload_to_freight"], + ) + # [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。 # 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。 if task.export_file_path and not task_export_error_message(task): @@ -440,6 +460,14 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + if not is_inventory_source_stable(task): + return tool_response( + status="failed", + task=task, + message="库存源尚未确定,无法上传货代系统。", + data=serialize_task_for_tool(task), + ) + # [STEP 1] 先确保上传所需的 Excel 已经存在。 # 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。 if not task.export_file_path: diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index 9c2e0f6d..f46b9763 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -105,7 +105,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。", "workflow.inventory.parse_failed_detail": "解析库存失败: {error}", "workflow.inventory.file_missing": "未收到 file 字段", - "workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .xls / .csv 库存文件", + "workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件", "workflow.inventory.uploading": "正在上传并解析库存文件", "workflow.inventory.uploading_detail": "正在处理库存文件 {filename}", "workflow.inventory.save_failed": "保存库存文件失败: {error}", @@ -240,7 +240,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.", "workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}", "workflow.inventory.file_missing": "The file field was not received.", - "workflow.inventory.file_type_unsupported": "Only .xlsx / .xls / .csv inventory files are supported.", + "workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.", "workflow.inventory.uploading": "Uploading and parsing the inventory file.", "workflow.inventory.uploading_detail": "Processing inventory file {filename}", "workflow.inventory.save_failed": "Failed to save inventory file: {error}", @@ -375,7 +375,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers", "workflow.inventory.parse_failed_detail": "解析库存失败: {error}", "workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file", - "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .xls / .csv", + "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv", "workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก", "workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}", "workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}", diff --git a/backend/app/services/shipping_notice/inventory_file_identity.py b/backend/app/services/shipping_notice/inventory_file_identity.py new file mode 100644 index 00000000..a5b568d3 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_file_identity.py @@ -0,0 +1,296 @@ +""" +services/shipping_notice/inventory_file_identity.py + +用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。 +依赖:openpyxl、csv、app.core.errors.AppError。 +逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。 +""" + +from __future__ import annotations + +import csv +from pathlib import Path +from typing import Any, Iterator + +from openpyxl import load_workbook + +from app.core.errors import AppError + +_WAREHOUSE_ID_HEADER_ALIASES = { + "warehouseid", + "warehouse", + "warehousecode", + "warehousecodeid", + "whid", +} +_HEADER_SCAN_ROWS = 20 + + +def _normalize_header_key(value: Any) -> str: + """将 Excel 表头标准化为可比较 key。""" + return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum()) + + +def _row_non_empty_count(row: tuple[Any, ...] | list[Any]) -> int: + """统计行内非空单元格数量,用于跳过标题行。""" + return sum(1 for cell in row if str(cell or "").strip()) + + +def _score_warehouse_header_row(row: tuple[Any, ...] | list[Any]) -> tuple[int, int] | None: + """ + 为候选表头行打分并定位 Warehouse 列。 + 核心逻辑:要求行内至少 2 个非空单元格,避免报表标题行单独出现 Warehouse 被误判为表头。 + """ + if _row_non_empty_count(row) < 2: + return None + best_col: int | None = None + for col_idx, cell in enumerate(row): + if _normalize_header_key(cell) in _WAREHOUSE_ID_HEADER_ALIASES: + best_col = col_idx + break + if best_col is None: + return None + score = _row_non_empty_count(row) * 10 + (5 if best_col == 0 else 0) + return score, best_col + + +def _find_warehouse_column(rows: list[tuple[Any, ...]]) -> tuple[int | None, int | None]: + """在表头候选区定位得分最高的 Warehouse 列。""" + scan_limit = min(len(rows), _HEADER_SCAN_ROWS) + best_score = 0 + best_row: int | None = None + best_col: int | None = None + for row_idx in range(scan_limit): + scored = _score_warehouse_header_row(rows[row_idx]) + if scored is None: + continue + score, col_idx = scored + if score > best_score: + best_score = score + best_row = row_idx + best_col = col_idx + return best_row, best_col + + +def _load_xlsx_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]: + """仅读取 xlsx 前若干行供表头定位(小内存)。""" + try: + wb = load_workbook(filename=str(path), data_only=True, read_only=True) + except Exception: + return [] + try: + ws = wb.active + rows: list[tuple[Any, ...]] = [] + for i, row in enumerate(ws.iter_rows(values_only=True)): + if i >= max_rows: + break + rows.append(tuple(row)) + return rows + finally: + wb.close() + + +def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]: + """流式遍历 xlsx Warehouse 列非空值。""" + wb = load_workbook(filename=str(path), data_only=True, read_only=True) + try: + ws = wb.active + for i, row in enumerate(ws.iter_rows(values_only=True)): + if i <= header_row_idx: + continue + if col_idx >= len(row): + continue + value = str(row[col_idx] or "").strip().upper() + if value: + yield value + finally: + wb.close() + + +def _detect_csv_dialect(sample: str) -> csv.Dialect: + """探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。""" + try: + return csv.Sniffer().sniff(sample, delimiters=",;\t|") + except csv.Error: + return csv.excel + + +def _load_csv_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]: + """仅读取 CSV 前若干行供表头定位。""" + for encoding in ("utf-8-sig", "utf-8", "gbk"): + try: + with path.open("r", encoding=encoding, newline="") as handle: + sample = handle.read(4096) + handle.seek(0) + dialect = _detect_csv_dialect(sample) + rows: list[tuple[Any, ...]] = [] + for row in csv.reader(handle, dialect=dialect): + rows.append(tuple(row)) + if len(rows) >= max_rows: + break + return rows + except UnicodeDecodeError: + continue + except OSError: + return [] + return [] + + +def _iter_csv_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]: + """流式遍历 CSV Warehouse 列非空值。""" + for encoding in ("utf-8-sig", "utf-8", "gbk"): + try: + with path.open("r", encoding=encoding, newline="") as handle: + sample = handle.read(4096) + handle.seek(0) + dialect = _detect_csv_dialect(sample) + for row_idx, row in enumerate(csv.reader(handle, dialect=dialect)): + if row_idx <= header_row_idx: + continue + if col_idx >= len(row): + continue + value = str(row[col_idx] or "").strip().upper() + if value: + yield value + return + except UnicodeDecodeError: + continue + except OSError: + return + + +def load_inventory_csv_rows(path: Path, *, max_rows: int | None = None) -> list[list[Any]]: + """ + 读取库存 CSV 行。 + 核心逻辑:max_rows 为 None 时读取全文件;预览场景请显式传入较小上限。 + 身份校验请使用流式 extract_warehouse_ids_from_inventory_excel。 + """ + limit = None if max_rows is None else max(1, int(max_rows)) + for encoding in ("utf-8-sig", "utf-8", "gbk"): + try: + with path.open("r", encoding=encoding, newline="") as handle: + sample = handle.read(4096) + handle.seek(0) + dialect = _detect_csv_dialect(sample) + rows: list[list[Any]] = [] + for row in csv.reader(handle, dialect=dialect): + rows.append(list(row)) + if limit is not None and len(rows) >= limit: + break + return rows + except UnicodeDecodeError: + continue + except OSError: + return [] + return [] + + +def _collect_unique_warehouse_values(values: Iterator[str]) -> set[str]: + """从 Warehouse 列迭代器收集去重集合。""" + warehouses: set[str] = set() + for value in values: + warehouses.add(value) + return warehouses + + +def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]: + """ + 从库存文件提取所有非空 Warehouse ID 值(去重)。 + 核心逻辑:前 20 行定位表头;数据区流式扫描目标列,避免全表加载。 + """ + if not path or not path.is_file(): + return set() + + suffix = path.suffix.lower() + if suffix == ".csv": + header_rows = _load_csv_header_rows(path) + header_row_idx, col_idx = _find_warehouse_column(header_rows) + if header_row_idx is None or col_idx is None: + return set() + return _collect_unique_warehouse_values( + _iter_csv_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx) + ) + if suffix == ".xlsx": + header_rows = _load_xlsx_header_rows(path) + header_row_idx, col_idx = _find_warehouse_column(header_rows) + if header_row_idx is None or col_idx is None: + return set() + return _collect_unique_warehouse_values( + _iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx) + ) + if suffix == ".xls": + return set() + return set() + + +def assert_inventory_excel_warehouse_identity( + path: Path, + *, + expected_warehouse_id: str, + operation: str = "inventory_import", +) -> str: + """ + 强制校验 Excel 内 Warehouse ID 与预期库位一致且唯一。 + 核心逻辑:混合多库位或内容与预期不符时抛出 AppError,拒绝入库/绑定。 + + Args: + path: 库存 Excel 路径。 + expected_warehouse_id: 任务或运行时 source 要求的库位。 + operation: 审计用途的操作名。 + + Returns: + str: Excel 中唯一的 Warehouse ID(大写)。 + + Raises: + AppError: 缺列、多库位或与预期不一致。 + """ + expected = str(expected_warehouse_id or "").strip().upper() + if not expected: + raise AppError( + code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + message="预期库位为空,无法校验库存文件内容", + http_status=409, + details={"operation": operation}, + ) + + suffix = path.suffix.lower() + if suffix not in {".xlsx", ".csv"}: + raise AppError( + code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传", + http_status=409, + details={"operation": operation, "file_suffix": suffix}, + ) + + found = extract_warehouse_ids_from_inventory_excel(path) + if not found: + raise AppError( + code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING", + message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库", + http_status=409, + details={"operation": operation, "expected_warehouse_id": expected}, + ) + if len(found) > 1: + raise AppError( + code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED", + message="库存文件包含多个 Warehouse ID,已拒绝入库", + http_status=409, + details={ + "operation": operation, + "expected_warehouse_id": expected, + "excel_warehouse_ids": sorted(found), + }, + ) + actual = next(iter(found)) + if actual != expected: + raise AppError( + code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库", + http_status=409, + details={ + "operation": operation, + "expected_warehouse_id": expected, + "excel_warehouse_id": actual, + }, + ) + return actual diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index 6fa31b47..f52bfbe0 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -17,12 +17,18 @@ from typing import Any from werkzeug.datastructures import FileStorage from app import db +from app.core.errors import AppError from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink from app.services.shipping_notice.export import _storage_root from app.services.shipping_notice.inventory_snapshot import ( parse_inventory_excel_with_meta, read_inventory_schema_preview, ) +from app.services.shipping_notice.inventory_source_gate import ( + is_inventory_source_stable, + task_inventory_identity, +) +from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version from app.services.shipping_notice.query_service import list_sorted_batch_tasks _TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"}) @@ -44,9 +50,79 @@ def generate_inventory_file_no() -> str: return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" -def inventory_file_upload_path(inventory_file_no: str) -> Path: - """库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory.xlsx)。""" - return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / "inventory.xlsx" +_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"}) + + +def resolve_inventory_upload_suffix(filename: str) -> str: + """ + 解析人工上传库存文件的合法落盘后缀。 + 核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。 + + Raises: + AppError: 后缀缺失、不支持或为 .xls。 + """ + name = str(filename or "").strip().lower() + if not name or "." not in name: + raise AppError( + code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + message="库存上传缺少可识别的文件后缀", + http_status=409, + ) + if name.endswith(".xlsx"): + return ".xlsx" + if name.endswith(".csv"): + return ".csv" + if name.endswith(".xls"): + raise AppError( + code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传", + http_status=409, + ) + raise AppError( + code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + message="库存上传仅支持 .xlsx / .csv", + http_status=409, + ) + + +def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx") -> Path: + """库存快照文件标准落盘路径(inventory_uploads/{inventory_file_no}/inventory{suffix})。""" + normalized = str(suffix or ".xlsx").lower() + if normalized not in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES: + normalized = ".xlsx" + return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}" + + +def inventory_storage_suffix_for_path(path: str | Path) -> str: + """根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。""" + suffix = Path(path).suffix.lower() + return suffix if suffix in _ALLOWED_INVENTORY_UPLOAD_SUFFIXES else ".xlsx" + + +def delete_inventory_storage_path(storage_path: str | Path | None) -> None: + """ + 删除库存快照托管文件及空目录。 + 核心逻辑:数据库回滚或唯一约束冲突时清理已复制文件,避免孤儿目录。 + """ + import logging + + if not storage_path or str(storage_path).startswith("failed://"): + return + path = Path(storage_path) + if path.is_file(): + try: + path.unlink() + except OSError as exc: + logging.getLogger(__name__).warning("failed to delete inventory file %s: %s", path, exc) + parent = path.parent + if parent.is_dir(): + try: + next(parent.iterdir()) + except StopIteration: + try: + parent.rmdir() + except OSError: + pass def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None: @@ -77,18 +153,74 @@ def has_uploaded_inventory_file(task: ShippingTask) -> bool: return False +def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> bool: + """判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。""" + if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs): + return False + left = task_inventory_identity(lhs) + right = task_inventory_identity(rhs) + return ( + left["inventory_source_code"] == right["inventory_source_code"] + and left["inventory_site_id"] == right["inventory_site_id"] + and left["inventory_warehouse_id"] == right["inventory_warehouse_id"] + ) + + def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile: """ 保存库存 Excel 并创建批次级库存快照。 【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。 + 核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。 """ + if not is_inventory_source_stable(task): + raise AppError( + code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", + message="库存源尚未稳定,拒绝保存库存上传文件", + http_status=409, + ) + + identity = task_inventory_identity(task) + source_code = identity["inventory_source_code"] or "" + site_id = identity["inventory_site_id"] + warehouse_id = identity["inventory_warehouse_id"] + from datetime import datetime + inventory_file_no = generate_inventory_file_no() - path = inventory_file_upload_path(inventory_file_no) + upload_suffix = resolve_inventory_upload_suffix(str(upload.filename or "")) + path = inventory_file_upload_path(inventory_file_no, suffix=upload_suffix) path.parent.mkdir(parents=True, exist_ok=True) - upload.save(str(path)) - preview = read_inventory_schema_preview(path) - preview["upload_filename"] = str(upload.filename or path.name) + try: + upload.save(str(path)) + from app.services.shipping_notice.inventory_file_identity import ( + assert_inventory_excel_warehouse_identity, + ) + + assert_inventory_excel_warehouse_identity( + path, + expected_warehouse_id=str(warehouse_id or ""), + operation="manual_upload", + ) + preview = read_inventory_schema_preview(path) + preview["upload_filename"] = str(upload.filename or path.name) + except AppError: + if path.is_file(): + try: + path.unlink() + except OSError: + import logging + + logging.getLogger(__name__).warning( + "failed to delete rejected inventory upload file %s", path + ) + raise + except Exception: + if path.is_file(): + try: + path.unlink() + except OSError: + pass + raise inv_file = ShippingInventoryFile( inventory_file_no=inventory_file_no, @@ -97,16 +229,59 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship source_file_name=str(upload.filename or "").strip() or path.name, storage_path=str(path), schema_preview_json=preview, - share_mode="batch_all" if task.batch_id else "task_only", + share_mode="task_only", line_count=0, + source_code=source_code, + source_type=str(task.inventory_source_type or "").strip() or None, + site_id=site_id, + warehouse_id=warehouse_id, + source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(), + identity_status="pending", + snapshot_status="ready", + exported_at=datetime.utcnow(), ) db.session.add(inv_file) db.session.flush() candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task] - linked_tasks = [item for item in candidates if _can_relink_inventory(item)] + linked_tasks = [ + item + for item in candidates + if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item) + ] + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + + created_links: list[ShippingTaskInventoryLink] = [] for item in linked_tasks: - replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member") + link = link_snapshot_to_task( + item, + inv_file, + reason="manual_upload", + role="owner" if item.id == task.id else "member", + audit_payload={"upload_filename": preview.get("upload_filename")}, + ) + if link is None: + for prior in created_links: + db.session.delete(prior) + db.session.delete(inv_file) + db.session.flush() + if path.is_file(): + try: + path.unlink() + except OSError: + import logging + + logging.getLogger(__name__).warning( + "failed to delete inventory upload after link failure %s", path + ) + raise AppError( + code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定", + http_status=409, + ) + created_links.append(link) + if len(linked_tasks) > 1: + inv_file.share_mode = "batch_same_identity" return inv_file @@ -139,7 +314,8 @@ def save_task_inventory_file_from_local_path( raise FileNotFoundError(f"未找到库存源文件: {source}") inventory_file_no = generate_inventory_file_no() - path = inventory_file_upload_path(inventory_file_no) + storage_suffix = inventory_storage_suffix_for_path(source) + path = inventory_file_upload_path(inventory_file_no, suffix=storage_suffix) path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, path) preview = read_inventory_schema_preview(path) diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index 4c901bc7..38b6502d 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -282,6 +282,7 @@ def inventory_loaded_response( chain_payload: dict[str, Any] | None = None, field_mapping: dict[str, str] | None = None, mapping_source: str | None = None, + commit: bool = True, ) -> dict[str, Any]: """ 库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。 @@ -289,7 +290,14 @@ def inventory_loaded_response( Args: require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。 chain_payload: 传递给 auto-chain 的原始请求体。 + commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。 """ + def _persist_inventory_loaded() -> None: + if commit: + db.session.commit() + else: + db.session.flush() + # [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。 # 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。 inv_file = active_inventory_file_for_task(task) @@ -351,8 +359,11 @@ def inventory_loaded_response( "column_meta": column_meta, }, ) - db.session.commit() - chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload) + _persist_inventory_loaded() + if commit: + chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload) + else: + chained = None if chained is not None: return chained lang = None @@ -391,8 +402,8 @@ def inventory_loaded_response( "linked_task_nos": [item.task_no for item in linked_tasks], }, ) - db.session.commit() - if inv_file: + _persist_inventory_loaded() + if commit and inv_file: start_inventory_file_linked_tasks(inv_file) return tool_response( status="ok", diff --git a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py new file mode 100644 index 00000000..6fcadb51 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py @@ -0,0 +1,300 @@ +""" +services/shipping_notice/inventory_rpa_callback_cleanup.py + +用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。 +依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。 +逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。 +""" + +from __future__ import annotations + +import json +import logging +import shutil +import uuid +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir + +_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed" +_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue" +_CLEANUP_FAILED_DIRNAME = ".cleanup_failed" +_QUARANTINE_DIRNAME = ".hxops_quarantine" +_DEFAULT_MAX_CLEANUP_ATTEMPTS = 16 +_LOGGER = logging.getLogger(__name__) + + +def callback_cleanup_queue_dir() -> Path | None: + """drop 目录下 callback 归档重试队列路径。""" + drop = inventory_drop_dir() + if not drop: + return None + return drop / _CLEANUP_QUEUE_DIRNAME + + +def callback_cleanup_failed_dir() -> Path | None: + """超过最大重试次数的 cleanup job 隔离目录。""" + drop = inventory_drop_dir() + if not drop: + return None + return drop / _CLEANUP_FAILED_DIRNAME + + +def callback_quarantine_dir() -> Path | None: + """ + Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。 + 归档失败时 HXOPS 将文件原子移入此处,避免重复上报。 + """ + drop = inventory_drop_dir() + if not drop: + return None + return drop / _QUARANTINE_DIRNAME + + +def callback_cleanup_max_attempts() -> int: + """cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。""" + try: + return max( + 1, + int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS), + ) + except (TypeError, ValueError): + return _DEFAULT_MAX_CLEANUP_ATTEMPTS + + +def is_callback_drop_file_consumed(callback_path: Path) -> bool: + """判断 drop 文件是否已被 HXOPS 消费(sidecar 或已位于 quarantine)。""" + path = Path(callback_path) + if not path.name: + return False + quarantine = callback_quarantine_dir() + if quarantine and quarantine in path.parents: + return True + sidecar = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}") + return sidecar.is_file() + + +def mark_callback_drop_file_consumed( + callback_path: Path, + *, + run_no: str | None = None, + task_no: str | None = None, + schedule_run_id: int | None = None, + inventory_file_no: str | None = None, +) -> None: + """ + 标记 drop 区 callback 文件已被系统消费。 + 核心逻辑:写 sidecar JSON;配合 quarantine 供 Worker 跳过重复扫描(Worker 须忽略 .hxops_* 子目录)。 + """ + if not callback_path.is_file(): + return + sidecar = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}") + payload = { + "callback_path": str(callback_path), + "consumed_at": datetime.utcnow().isoformat(), + "run_no": str(run_no or "").strip() or None, + "task_no": str(task_no or "").strip() or None, + "schedule_run_id": schedule_run_id, + "inventory_file_no": str(inventory_file_no or "").strip() or None, + } + try: + sidecar.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + except OSError as exc: + _LOGGER.warning("failed to write callback consumed marker %s: %s", sidecar, exc) + + +def quarantine_callback_drop_file(callback_path: Path) -> Path | None: + """ + 将归档失败的 callback 原子移入隔离目录,避免 Worker 扫描 drop 根目录时重复上报。 + Returns: + 隔离后的路径;不可用时返回 None。 + """ + path = Path(callback_path) + if not path.is_file(): + return None + quarantine = callback_quarantine_dir() + if quarantine is None: + return None + quarantine.mkdir(parents=True, exist_ok=True) + target = quarantine / path.name + if target.exists(): + target = quarantine / ( + f"{path.stem}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{path.suffix}" + ) + shutil.move(str(path), str(target)) + consumed = Path(f"{path}{_CALLBACK_CONSUMED_SUFFIX}") + if consumed.is_file(): + try: + consumed.unlink() + except OSError: + pass + return target + + +def enqueue_callback_file_move( + callback_path: Path, + *, + processed_dir: Path, + run_no: str | None = None, + task_no: str | None = None, + schedule_run_id: int | None = None, + error: str | None = None, +) -> Path | None: + """ + 将失败的 callback 归档操作写入持久化队列,供后续重试。 + Returns: + 队列 job 文件路径;队列不可用时返回 None。 + """ + queue = callback_cleanup_queue_dir() + if queue is None: + return None + queue.mkdir(parents=True, exist_ok=True) + job_id = uuid.uuid4().hex + job_path = queue / f"move_{job_id}.json" + payload: dict[str, Any] = { + "job_id": job_id, + "callback_path": str(callback_path), + "processed_dir": str(processed_dir), + "run_no": str(run_no or "").strip() or None, + "task_no": str(task_no or "").strip() or None, + "schedule_run_id": schedule_run_id, + "last_error": str(error or "").strip() or None, + "enqueued_at": datetime.utcnow().isoformat(), + "attempts": 0, + } + tmp = job_path.with_suffix(".json.tmp") + try: + tmp.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + tmp.replace(job_path) + except OSError as exc: + _LOGGER.warning("failed to enqueue callback move job for %s: %s", callback_path, exc) + return None + return job_path + + +def move_callback_drop_file_to_processed(callback_path: Path, processed_dir: Path) -> None: + """将 callback 文件移入 processed 目录(公开给 workflow 直接调用)。""" + _move_callback_file_to_processed(callback_path, processed_dir) + + +def _move_callback_file_to_processed(callback_path: Path, processed_dir: Path) -> None: + """将 callback 文件移入 processed 目录。""" + if not callback_path.is_file(): + return + processed_dir.mkdir(parents=True, exist_ok=True) + target = processed_dir / callback_path.name + if target.exists(): + target = processed_dir / ( + f"{callback_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{callback_path.suffix}" + ) + shutil.move(str(callback_path), str(target)) + consumed = Path(f"{callback_path}{_CALLBACK_CONSUMED_SUFFIX}") + if consumed.is_file(): + try: + consumed.unlink() + except OSError: + pass + + +def _archive_failed_cleanup_job(job_path: Path, payload: dict[str, Any]) -> None: + """超过最大重试次数后将 job 移入 failed 目录。""" + failed_dir = callback_cleanup_failed_dir() + if failed_dir is None: + try: + job_path.unlink() + except OSError: + pass + return + failed_dir.mkdir(parents=True, exist_ok=True) + target = failed_dir / job_path.name + payload["archived_at"] = datetime.utcnow().isoformat() + try: + target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + job_path.unlink() + except OSError as exc: + _LOGGER.warning("failed to archive cleanup job %s: %s", job_path, exc) + + +def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]: + """ + 重试持久化 callback 归档队列。 + 核心逻辑:源文件已不存在视为完成;超限 job 移入 failed;仍失败则累加 attempts。 + """ + queue = callback_cleanup_queue_dir() + if queue is None or not queue.is_dir(): + return [] + warnings: list[str] = [] + max_attempts = callback_cleanup_max_attempts() + jobs = sorted(queue.glob("move_*.json"))[: max(max_jobs, 1)] + for job_path in jobs: + try: + payload = json.loads(job_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc: + warnings.append(f"{job_path.name}:invalid_job:{str(exc)[:80]}") + try: + job_path.unlink() + except OSError: + pass + continue + callback_raw = str(payload.get("callback_path") or "").strip() + processed_raw = str(payload.get("processed_dir") or "").strip() + callback_path = Path(callback_raw) if callback_raw else None + processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir() + if callback_path is None or processed_dir is None: + try: + job_path.unlink() + except OSError: + pass + continue + if not callback_path.is_file(): + try: + job_path.unlink() + except OSError: + pass + continue + if int(payload.get("attempts") or 0) >= max_attempts: + warnings.append(f"{callback_path}:max_attempts_exceeded") + _archive_failed_cleanup_job(job_path, payload) + continue + try: + _move_callback_file_to_processed(callback_path, processed_dir) + try: + job_path.unlink() + except OSError: + pass + except Exception as exc: + payload["attempts"] = int(payload.get("attempts") or 0) + 1 + payload["last_error"] = str(exc)[:240] + payload["last_attempt_at"] = datetime.utcnow().isoformat() + warnings.append(f"{callback_path}:{str(exc)[:120]}") + if int(payload["attempts"]) >= max_attempts: + _archive_failed_cleanup_job(job_path, payload) + else: + try: + job_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + except OSError: + pass + _LOGGER.warning( + "callback cleanup retry failed for %s (attempt=%s)", + callback_path, + payload["attempts"], + exc_info=exc, + ) + return warnings + + +def recover_pending_rpa_callback_cleanup_jobs(*, max_jobs: int = 64) -> tuple[int, list[str]]: + """ + 启动或调度恢复时消费 callback cleanup 队列。 + Returns: + tuple: (成功消化或移除的 job 数, 告警列表)。 + """ + queue = callback_cleanup_queue_dir() + before = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0 + warnings = flush_callback_cleanup_queue(max_jobs=max_jobs) + after = len(list(queue.glob("move_*.json"))) if queue and queue.is_dir() else 0 + return max(0, before - after), warnings diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 3e53bc77..f22ed008 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -8,34 +8,59 @@ services/shipping_notice/inventory_rpa_workflow.py from __future__ import annotations +import hashlib +import json +import logging +import shutil from datetime import datetime, timedelta from pathlib import Path from typing import Any from app import db -from app.core.errors import ServiceUnavailableError -from app.models import ShippingTask, ShippingTaskEvent -from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING +from app.core.errors import AppError, ServiceUnavailableError +from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent +from app.services.shipping_notice.constants import ( + CP_INVENTORY_SOURCE_REVIEW, + CP_PARSE_OK, + CP_PARSE_REVIEW, + CP_UPLOAD_REQ, + PH_INVENTORY_SOURCE_UNRESOLVED, + PH_RPA_PENDING, +) from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file from app.services.shipping_notice.inventory_snapshot_store import ( - create_inventory_snapshot_from_rpa, find_latest_ready_snapshot, + get_or_create_rpa_inventory_snapshot, link_snapshot_to_task, ) -from app.services.shipping_notice.inventory_upload import save_task_inventory_local_file -from app.services.shipping_notice.inventory_source_rules import ( - mark_inventory_source_review, - resolve_inventory_source, - save_task_rpa_inventory_source, - task_rpa_inventory_source, +from app.services.shipping_notice.inventory_upload import ( + delete_staged_task_inventory_file, + promote_staged_task_inventory_file, + rebuild_task_inventory_attachment_from_snapshot, + stage_task_inventory_callback_file, ) +from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + enqueue_callback_file_move, + flush_callback_cleanup_queue, + mark_callback_drop_file_consumed, + move_callback_drop_file_to_processed, + quarantine_callback_drop_file, + recover_pending_rpa_callback_cleanup_jobs, +) +from app.services.shipping_notice.inventory_source_gate import ( + assert_inventory_source_gate, + confirm_task_inventory_source, + inventory_identities_match, + is_inventory_source_stable, + task_needs_parse_review, +) +from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source from app.services.shipping_notice.query_service import ( resolve_task_from_payload, serialize_task_for_tool, ) from app.services.shipping_notice.rpa import ( - find_latest_inventory_file, inventory_processed_dir, write_inventory_export_trigger_for_task, ) @@ -123,6 +148,7 @@ def _try_reuse_inventory_snapshot( snapshot = find_latest_ready_snapshot( str(rpa_source.get("source_code") or ""), str(rpa_source.get("site_id") or ""), + str(rpa_source.get("warehouse_id") or ""), ) if not snapshot: return None @@ -297,34 +323,662 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works return ensure_inventory_via_rpa(task, mode="auto") +def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str, str]: + """从任务正式库存身份推导快照预期三元组。""" + return ( + str(task.inventory_source_code or "").strip().upper(), + str(task.inventory_site_id or "").strip().upper(), + str(task.inventory_warehouse_id or "").strip().upper(), + ) + + +def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str, str]: + """从 RPA/配置源推导快照预期身份三元组,供回调入库前预检。""" + code = str(source.get("source_code") or "").strip().upper() + site = str(source.get("site_id") or "").strip().upper() + warehouse = str(source.get("warehouse_id") or "").strip().upper() + return code, site, warehouse + + +def _rollback_orphan_inventory_snapshot( + inv_file: Any, + *paths: str | Path | None, + created_new: bool = True, + delete_session_row: bool = True, +) -> None: + """ + 回滚本轮新建的孤儿快照与托管文件。 + 核心逻辑:先删物理文件;仅 created_new=True 时处理 DB 行。 + delete_session_row=False 用于顶层 commit 失败后的 rollback——行已由事务回滚,只清文件。 + """ + if not created_new: + return + from sqlalchemy import inspect as sa_inspect + + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + for raw in paths: + delete_inventory_storage_path(raw) + + if not delete_session_row or inv_file is None: + return + try: + state = sa_inspect(inv_file) + if state.persistent or state.pending: + db.session.delete(inv_file) + except Exception: + logging.getLogger(__name__).warning( + "orphan inventory snapshot session delete skipped", + exc_info=True, + ) + + +class _RpaCallbackItemAbort(Exception): + """批量/单任务回调单项失败,供 savepoint 回滚后转为 failed 响应。""" + + def __init__(self, error: str, *, message: str | None = None) -> None: + self.error = error + self.message = message + super().__init__(message or error) + + +def _inventory_file_sha256(path: Path) -> str: + """计算库存文件 SHA256,用于复用快照内容一致性校验。""" + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _validate_reused_snapshot_callback_file( + inv_file: ShippingInventoryFile, + callback_path: Path, +) -> str | None: + """ + 校验复用快照时回调落盘文件与托管 storage_path 内容一致。 + 核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。 + """ + storage_path = Path(str(inv_file.storage_path or "")) + if not storage_path.is_file(): + return "reused_snapshot_storage_missing" + if not callback_path.is_file(): + return "callback_file_missing" + if _inventory_file_sha256(storage_path) != _inventory_file_sha256(callback_path): + return "reused_snapshot_content_mismatch" + return None + + +def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path: + """返回应解析的库存快照托管路径(复用与新建均读 storage_path)。""" + path = Path(str(inv_file.storage_path or "")) + if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): + raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}") + return path + + +def _move_callback_drop_file_to_processed(callback_path: Path, processed: Path) -> None: + """将 RPA drop 区回调文件移至 processed,仅在新快照成功摄入后调用。""" + move_callback_drop_file_to_processed(callback_path, processed) + + +def _archive_callback_drop_file( + callback_path: Path, + processed: Path, + *, + run_no: str | None = None, + task_no: str | None = None, + schedule_run_id: int | None = None, + inventory_file_no: str | None = None, +) -> str | None: + """ + 归档 callback drop 文件;失败时隔离并写入持久化 cleanup job。 + 核心逻辑:move 失败 → 尽力 quarantine → 尽力入队;二级失败只追加 warning,不向外抛异常。 + + Returns: + 失败告警文本;成功返回 None。 + """ + mark_callback_drop_file_consumed( + callback_path, + run_no=run_no, + task_no=task_no, + schedule_run_id=schedule_run_id, + inventory_file_no=inventory_file_no, + ) + if not callback_path.is_file(): + return None + try: + move_callback_drop_file_to_processed(callback_path, processed) + return None + except Exception as exc: + logger = logging.getLogger(__name__) + detail_parts = [str(exc)[:120]] + job_path: Path = callback_path + try: + quarantined = quarantine_callback_drop_file(callback_path) + if quarantined is not None: + job_path = quarantined + except Exception as quarantine_exc: + detail_parts.append(f"quarantine_failed:{str(quarantine_exc)[:80]}") + logger.warning( + "RPA callback quarantine failed after move failure: %s", + callback_path, + exc_info=quarantine_exc, + ) + + try: + queued = enqueue_callback_file_move( + job_path, + processed_dir=processed, + run_no=run_no, + task_no=task_no, + schedule_run_id=schedule_run_id, + error=str(exc), + ) + if queued is None: + detail_parts.append("enqueue_failed:cleanup_queue_unavailable") + except Exception as enqueue_exc: + detail_parts.append(f"enqueue_failed:{str(enqueue_exc)[:80]}") + logger.warning( + "RPA callback cleanup enqueue failed: %s", + job_path, + exc_info=enqueue_exc, + ) + + logger.warning( + "RPA callback file move failed, cleanup scheduled: %s", + callback_path, + exc_info=exc, + ) + return f"{callback_path}:{';'.join(detail_parts)[:240]}" + + +def _flush_pending_callback_moves( + pending_moves: list[dict[str, Any]], + processed: Path, +) -> list[str]: + """ + 在数据库提交成功后统一移动 callback 原文件。 + 核心逻辑:先写消费标记;移动失败入持久化队列,不回滚已提交事务。 + """ + warnings: list[str] = [] + for item in pending_moves: + callback_path = Path(str(item.get("path") or "")) + if not callback_path: + continue + warning = _archive_callback_drop_file( + callback_path, + processed, + run_no=str(item.get("run_no") or "").strip() or None, + task_no=str(item.get("task_no") or "").strip() or None, + schedule_run_id=item.get("schedule_run_id"), + inventory_file_no=str(item.get("inventory_file_no") or "").strip() or None, + ) + if warning: + warnings.append(warning) + return warnings + + +def _try_rebuild_task_inventory_attachment( + task: ShippingTask, + inv_file: ShippingInventoryFile, + post_commit_warnings: list[str], +) -> bool: + """ + 从 inv_file.storage_path 幂等重建任务正式附件(不重新消费 callback)。 + Returns: + 是否重建成功。 + """ + try: + rebuilt = rebuild_task_inventory_attachment_from_snapshot(task, inv_file) + except Exception as exc: + post_commit_warnings.append(f"promote_snapshot_rebuild_failed:{str(exc)[:120]}") + logging.getLogger(__name__).warning( + "task inventory attachment rebuild failed for %s", + task.task_no, + exc_info=exc, + ) + return False + post_commit_warnings.append(f"promote_recovered_via_snapshot_rebuild:{rebuilt.name}") + return True + + +def _should_flush_batch_callback_moves( + schedule_run_id: int | None, + finalize_result: dict[str, Any], +) -> bool: + """ + 判断批量回调是否可移动 drop 区原文件。 + 核心逻辑:无排程 run 时在 DB 提交后即可移动;有排程时仅 finalize 成功终态化后移动; + finalize 失败且 manual_retryable 时保留原文件供重试。 + """ + if schedule_run_id is None: + return True + if finalize_result.get("manual_retryable"): + return False + if finalize_result.get("ok"): + return True + return str(finalize_result.get("schedule_finalize_status") or "") == "ok" + + +def _persist_post_commit_task_event( + task: ShippingTask, + event_type: str, + detail: dict[str, Any], +) -> None: + """独立提交 post-commit 告警审计事件;提交失败仅记日志,不影响主业务响应。""" + log_task_event(task, event_type, detail) + try: + db.session.commit() + except Exception as exc: + logging.getLogger(__name__).warning( + "post-commit task event persist failed for task %s event=%s", + task.task_no, + event_type, + exc_info=exc, + ) + + +def _extract_run_no_from_trigger(trigger_path: str | None) -> str: + """从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 均支持)。""" + path = Path(str(trigger_path or "")) + name = path.name + prefix = "inventory_export_batch_" + if name.startswith(prefix) and name.endswith(".json"): + return name[len(prefix) : -len(".json")] + if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file(): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + if isinstance(payload, dict): + run_no = str(payload.get("run_no") or "").strip() + if run_no: + return run_no + except (OSError, json.JSONDecodeError, TypeError, ValueError): + pass + return "" + + +def _is_legacy_trigger_run_no(run_no: str) -> bool: + """判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传)。""" + return str(run_no or "").strip().upper().startswith("LEGACY-") + + +def _expected_rpa_callback_run_no(task: ShippingTask) -> str: + """读取任务最近一次 RPA 触发记录的 run_no。""" + last_trigger = latest_task_event(task, "inventory_rpa_triggered") + if not last_trigger: + return "" + detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {} + run_no = str(detail.get("run_no") or "").strip() + if run_no: + return run_no + return _extract_run_no_from_trigger(str(detail.get("trigger") or "")) + + +def _validate_rpa_callback_run_no(task: ShippingTask, callback_run_no: str) -> str | None: + """校验回调 run_no 属于当前任务最近一次有效触发轮次。""" + provided = str(callback_run_no or "").strip() + expected = _expected_rpa_callback_run_no(task) + if not expected: + return "no_active_trigger" + if not provided: + if _is_legacy_trigger_run_no(expected): + return None + return "run_no_missing" + if provided != expected: + return "run_no_mismatch" + return None + + +def _resolve_effective_callback_run_no(task: ShippingTask, payload: dict[str, Any]) -> str: + """解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。""" + provided = str(payload.get("run_no") or "").strip() + if provided: + return provided + return _expected_rpa_callback_run_no(task) + + +def _lock_task_for_rpa_callback(task: ShippingTask) -> ShippingTask: + """对任务行加悲观锁,防止并发回调重复消费同一轮次。""" + if task.id is None: + return task + return db.session.query(ShippingTask).filter_by(id=task.id).with_for_update().one() + + +def _get_consumed_inventory_rpa_run_no(task: ShippingTask) -> str: + """读取已消费(处理完成)的 RPA 轮次 run_no。""" + return str(task.inventory_rpa_consumed_run_no or "").strip() + + +def _mark_inventory_rpa_run_no_consumed(task: ShippingTask, run_no: str) -> None: + """标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。""" + effective = str(run_no or "").strip() + if not effective: + return + task.inventory_rpa_consumed_run_no = effective + + +def _validate_rpa_callback_not_replayed(task: ShippingTask, run_no: str) -> str | None: + """拒绝同一 run_no 的重复成功/失败/跳过回调。""" + effective = str(run_no or "").strip() + consumed = _get_consumed_inventory_rpa_run_no(task) + if effective and consumed and effective == consumed: + return "run_no_already_consumed" + return None + + +def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None: + """ + 校验 RPA 回调轮次契约(run_no + 幂等)。 + 核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。 + """ + run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or "")) + if run_no_error: + return tool_response( + status="failed", + task=task, + message="RPA 回调 run_no 无效或已过期,已拒绝处理", + data={**serialize_task_for_tool(task), "run_no_error": run_no_error}, + ) + replay_error = _validate_rpa_callback_not_replayed( + task, + _resolve_effective_callback_run_no(task, payload), + ) + if replay_error: + return tool_response( + status="failed", + task=task, + message="RPA 回调轮次已处理,拒绝重复回调", + data={**serialize_task_for_tool(task), "run_no_error": replay_error}, + ) + return None + + +def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None: + """校验库存源门禁(skipped/failed/success 共用)。""" + try: + assert_inventory_source_gate(task, operation="rpa_inventory_callback") + except AppError as exc: + return tool_response( + status="failed", + task=task, + message=str(exc.message or "库存源门禁未通过,拒绝处理 RPA 回调"), + data=serialize_task_for_tool(task), + ) + return None + + +def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None: + """ + 成功回调的身份契约:source/site/warehouse/run_no 必须与任务一致。 + 核心逻辑:仅 success 路径调用;skipped/failed 允许 RPA 缺身份字段。 + """ + callback_source = str(payload.get("source_code") or "").strip().upper() + task_source = str(task.inventory_source_code or "").strip().upper() + if not callback_source: + return tool_response( + status="failed", + task=task, + message="RPA 成功回调缺少 source_code,已拒绝入库", + data=serialize_task_for_tool(task), + ) + if not task_source or callback_source != task_source: + return tool_response( + status="failed", + task=task, + message="RPA 回调库存源与任务正式库存源不一致,已拒绝入库", + data=serialize_task_for_tool(task), + ) + + callback_site = str(payload.get("site_id") or "").strip().upper() + callback_wh = str(payload.get("warehouse_id") or "").strip().upper() + task_site = str(task.inventory_site_id or "").strip().upper() + task_wh = str(task.inventory_warehouse_id or "").strip().upper() + if not callback_site or callback_site != task_site: + return tool_response( + status="failed", + task=task, + message="RPA 回调 site_id 与任务库存源不一致,已拒绝入库", + data=serialize_task_for_tool(task), + ) + if not callback_wh or callback_wh != task_wh: + return tool_response( + status="failed", + task=task, + message="RPA 回调 warehouse_id 与任务库存源不一致,已拒绝入库", + data=serialize_task_for_tool(task), + ) + return None + + +def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]: + """ + 合并 batch 顶层契约字段到 result item。 + 核心逻辑:仅合并 run_no / task_no;成功回调身份字段必须由 Worker 显式返回,禁止后端从任务补齐。 + """ + merged = dict(item) + top_run_no = str(payload.get("run_no") or "").strip() + if top_run_no and not str(merged.get("run_no") or "").strip(): + merged["run_no"] = top_run_no + + task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip() + if task_no and not str(merged.get("task_no") or "").strip(): + merged["task_no"] = task_no + return merged + + +def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None: + """校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。""" + if schedule_run_id is None: + return None + from app.models import ScheduleRun + + run = db.session.get(ScheduleRun, schedule_run_id) + if not run: + return "schedule_run_not_found" + expected = str(run.run_no or "").strip() + provided = str(callback_run_no or "").strip() + if not expected: + return "schedule_run_no_missing" + if provided != expected: + return "schedule_run_no_mismatch" + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != "running" or not summary.get("awaiting_rpa"): + return "schedule_run_not_awaiting" + return None + + +def _validate_rpa_callback_inventory_source(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None: + """ + 校验 RPA 成功回调是否允许处理当前任务库存(门禁 + 轮次 + 身份)。 + 核心逻辑:batch 成功项在合并顶层 run_no 后委托本函数。 + """ + gate_resp = _validate_rpa_callback_gate(task) + if gate_resp is not None: + return gate_resp + round_resp = _validate_rpa_callback_round(task, payload) + if round_resp is not None: + return round_resp + return _validate_rpa_callback_success_identity(task, payload) + + +def _resolve_batch_callback_source( + task: ShippingTask | None, + item: dict[str, Any], +) -> dict[str, Any] | None: + """ + 解析批量回调项的正式库存源身份。 + 核心逻辑:带任务时仅用任务 RPA source;定时预热仅接受启用配置 source,禁止 item 自由字段覆盖。 + """ + if task: + return task_rpa_inventory_source(task) + source_code = str(item.get("source_code") or "").strip().upper() + if not source_code: + return None + from app.services.shipping_notice.inventory_sources import get_inventory_source + + return get_inventory_source(source_code) + + +def _batch_snapshot_verify_warehouse_id( + task: ShippingTask | None, + source: dict[str, Any], + item: dict[str, Any] | None = None, +) -> str | None: + """推导批量快照入库前须校验的 Excel Warehouse ID。""" + if task: + warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() + return warehouse_id or None + if item is not None: + warehouse_id = str(item.get("warehouse_id") or "").strip().upper() + if warehouse_id: + return warehouse_id + warehouse_id = str(source.get("warehouse_id") or "").strip().upper() + return warehouse_id or None + + +def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None: + """ + 校验批量回调 Worker 返回的四字段身份与启用配置一致。 + 核心逻辑:定时/无任务成功项必须显式携带 source/site/warehouse;动态库位源校验 allowed_warehouse_ids。 + """ + from app.services.shipping_notice.inventory_sources import ( + configured_allowed_warehouse_ids, + source_uses_dynamic_warehouse_id, + ) + + callback_source = str(item.get("source_code") or "").strip().upper() + callback_site = str(item.get("site_id") or "").strip().upper() + callback_wh = str(item.get("warehouse_id") or "").strip().upper() + if not callback_source: + return "source_code_missing" + if not callback_site: + return "site_id_missing" + if not callback_wh: + return "warehouse_id_missing" + + cfg_source = str(source.get("source_code") or "").strip().upper() + cfg_site = str(source.get("site_id") or "").strip().upper() + cfg_wh = str(source.get("warehouse_id") or "").strip().upper() + if callback_source != cfg_source: + return "source_code_mismatch" + if callback_site != cfg_site: + return "site_id_mismatch" + + if source_uses_dynamic_warehouse_id(source): + allowed = configured_allowed_warehouse_ids(source) + if allowed and callback_wh not in allowed: + return "warehouse_id_not_allowed" + return None + + if callback_wh != cfg_wh: + return "warehouse_id_mismatch" + return None + + def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: """ - 确认当前任务的库存 RPA 来源,并继续触发库存导出。 - 【AI 触发时机】:当用户在库存源确认检查点选择一个 source_code 后调用;禁止用自然语言中的任意 URL 直接写入。 + 确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。 + 【AI 触发时机】:当用户在订单解析阶段库存源检查点选择一个 source_code 后调用。 """ + from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition + task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") + if str(task.pending_human_reason or "").strip() != PH_INVENTORY_SOURCE_UNRESOLVED: + return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点") source_code = str(payload.get("source_code") or "").strip().upper() - source = build_rpa_inventory_source(source_code) - if not source: - return tool_response(status="failed", task=task, message="库存源不存在或未启用") + if not source_code: + return tool_response(status="failed", task=task, message="请提供库存源编码 source_code") - save_task_rpa_inventory_source(task, source) - task.pending_human_reason = None - task.review_status = None - task.error_message = None + adjudication = confirm_task_inventory_source( + task, + source_code, + user_id=payload.get("_trusted_user_id"), + ) + if not is_inventory_source_stable(task): + apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) + task.current_step = "step2_parse_confirm" + task.error_message = adjudication.reason or "库存源确认失败" + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message="库存源确认未通过,请重新选择或检查配置。", + data={ + **serialize_task_for_tool(task), + "inventory_source_candidates": adjudication.candidates, + "inventory_source_status": adjudication.status, + "inventory_source_reason": adjudication.reason, + }, + checkpoint=CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + ) + + confirmed_by = payload.get("_trusted_user_id") log_task_event( task, "inventory_source_confirmed", { - "source_code": source.get("source_code"), - "source_type": source.get("source_type"), - "confirmed_by": "user", + "source_code": task.inventory_source_code, + "source_type": task.inventory_source_type, + "site_id": task.inventory_site_id, + "warehouse_id": task.inventory_warehouse_id, + "confirmed_by": confirmed_by or "integration_tool", }, ) - db.session.flush() - return ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto")) + + if task_needs_parse_review(task): + step_payload = dict(task.step_payload_json or {}) + step_payload.pop("pending_parse_review_after_source", None) + task.step_payload_json = step_payload + apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) + task.current_step = "step2_parse_confirm" + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message="库存源已确认,请继续确认解析结果。", + data=serialize_task_for_tool(task), + checkpoint=CP_PARSE_REVIEW, + stop_agent_turn=True, + ) + + apply_task_transition(task, TaskTransition.PARSED) + task.pending_human_reason = None + task.review_status = None + task.error_message = None + step_payload = dict(task.step_payload_json or {}) + step_payload.pop("pending_parse_review_after_source", None) + task.step_payload_json = step_payload + task.current_step = "step3_inventory_prepare" + db.session.commit() + + from app.services.shipping_notice.tool_common import auto_rpa_inventory_enabled + + if (not task.inventory_lines_json) and auto_rpa_inventory_enabled(): + rpa_result = ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto")) + rpa_status = str(rpa_result.get("status") or "").strip().lower() + if rpa_status in {"running", "ok"}: + return rpa_result + if rpa_status == "needs_human" and str(task.pending_human_reason or "").strip() == PH_RPA_PENDING: + return rpa_result + return tool_response( + status="ok", + task=task, + message="库存源已确认;自动获取库存暂未完成,请稍后重试或手动上传库存文件。", + data=serialize_task_for_tool(task), + checkpoint=CP_PARSE_OK, + ) + + return tool_response( + status="ok", + task=task, + message="库存源已确认。", + data=serialize_task_for_tool(task), + checkpoint=CP_PARSE_OK, + ) def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]: @@ -332,61 +986,24 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" - # [STEP 0] 库存 RPA 必须先确定唯一库存源;Dify 只给目的地线索,HXOPS 规则负责最终裁决。 - rpa_source = task_rpa_inventory_source(task) - if not rpa_source: - resolution = resolve_inventory_source(task) - if resolution.status == "resolved" and resolution.source: - rpa_source = resolution.source - save_task_rpa_inventory_source(task, rpa_source, resolution=resolution) - log_task_event( - task, - "inventory_source_resolved", - { - "source_code": rpa_source.get("source_code"), - "source_type": rpa_source.get("source_type"), - "destination_candidates": resolution.destination_candidates, - }, - ) - db.session.flush() - else: - mark_inventory_source_review(task, resolution) - apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) - task.error_message = "无法根据发货通知唯一确定库存查询来源" - set_task_step_progress( - task, - step_key="step3_inventory_prepare", - step_title="获取库存", - status="needs_human", - message="库存查询来源待确认", - progress_percent=30, - current=len(resolution.candidates), - total=len(resolution.candidates), - detail="请确认本票应使用哪个 RPA 库存来源后继续。", - ) - log_task_event( - task, - "inventory_source_review_required", - { - "status": resolution.status, - "reason": resolution.reason, - "destination_candidates": resolution.destination_candidates, - "candidate_source_codes": [item.get("source_code") for item in resolution.candidates], - }, - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message="无法根据发货通知唯一确定库存查询来源,请选择库存源后继续 RPA 获取库存。", - data={ - **serialize_task_for_tool(task), - "inventory_source_candidates": resolution.candidates, - "destination_candidates": resolution.destination_candidates, - }, - checkpoint=CP_INVENTORY_SOURCE_REVIEW, - stop_agent_turn=True, - ) + # [STEP 0] 库存源须在订单解析阶段已确定;RPA 只读取独立字段。 + try: + assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa") + except AppError: + apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) + task.current_step = "step2_parse_confirm" + task.error_message = "库存源尚未确定,无法启动 RPA" + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + data=serialize_task_for_tool(task), + checkpoint=CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + ) + + rpa_source = task_rpa_inventory_source(task) or {} # [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。 reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode) @@ -438,11 +1055,9 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] "timeout_seconds": timeout_seconds, }, ) - db.session.flush() + db.session.flush( ) - # [STEP 2] 处理重试上限与已落盘文件两种捷径。 - # 单次模式下,只有“上一轮已经失败/超时”时才允许在这里转人工;首次成功写出 trigger 后必须进入等待窗口。 - # 若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。 + # [STEP 2] 处理重试上限;禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。 attempts = inventory_rpa_attempts(task) max_attempts = max_rpa_inventory_attempts() if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round: @@ -457,23 +1072,6 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] data=serialize_task_for_tool(task), ) - latest = find_latest_inventory_file() - processed = inventory_processed_dir() - if latest and processed: - try: - lines, column_meta = ingest_inventory_file(latest, move_to=processed) - if lines: - return inventory_loaded_response( - task, - lines, - column_meta=column_meta, - source="rpa_drop", - require_mapping_review=True, - event_type="inventory_rpa_drop_ingested", - ) - except Exception as exc: - task.error_message = str(exc)[:500] - # [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。 # 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。 attempt_no = attempts + 1 @@ -518,7 +1116,12 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] log_task_event( task, "inventory_rpa_triggered", - {"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round}, + { + "trigger": trigger, + "run_no": _extract_run_no_from_trigger(trigger), + "attempt": attempt_no, + "manual_retry_round": manual_retry_round, + }, ) db.session.commit() @@ -686,144 +1289,354 @@ def _inventory_rpa_skipped_message(*, skip_reason: str, detail: str) -> str: return f"{base}。请确认仓库是否正确,或改用手动上传库存 Excel。" +def _handle_rpa_inventory_skipped( + task: ShippingTask, + payload: dict[str, Any], + runtime: dict[str, Any], + *, + commit: bool = True, +) -> dict[str, Any]: + """处理 skipped 回调:转人工上传检查点,不计入技术失败重试。""" + skip_reason = str(payload.get("skip_reason") or "no_inventory_data").strip() + detail = str(payload.get("message") or payload.get("error_message") or "").strip() + message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail) + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + task.error_message = None + step_payload = dict(task.step_payload_json or {}) + step_payload["inventory_rpa_skipped"] = { + "skip_reason": skip_reason, + "message": detail or message, + "reported_at": datetime.utcnow().isoformat(), + "rpa_runtime": runtime, + } + task.step_payload_json = step_payload + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message="货代系统当前无可用库存", + progress_percent=100, + detail="请确认仓库是否正确,或手动上传货代库存 Excel。", + ) + log_task_event( + task, + "inventory_rpa_skipped", + { + "skip_reason": skip_reason, + "message": detail or message, + "rpa_runtime": runtime, + }, + ) + _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload)) + if commit: + db.session.commit() + else: + db.session.flush() + return tool_response( + status="needs_human", + task=task, + message=message, + data=serialize_task_for_tool(task), + checkpoint=CP_UPLOAD_REQ, + ) + + +def _handle_rpa_inventory_failed( + task: ShippingTask, + payload: dict[str, Any], + runtime: dict[str, Any], + *, + commit: bool = True, +) -> dict[str, Any]: + """处理 failed 回调:累计尝试并在耗尽后转人工上传兜底。""" + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] + log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime}) + db.session.flush() + attempts = inventory_rpa_attempts(task) + if attempts >= max_rpa_inventory_attempts(): + apply_task_transition(task, TaskTransition.RPA_EXHAUSTED) + task.error_message = "已多次尝试仍无法通过 RPA 获取库存" + log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts}) + _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload)) + if commit: + db.session.commit() + else: + db.session.flush() + return tool_response( + status="needs_human", + task=task, + message=_inventory_rpa_exhausted_message(attempts), + data=serialize_task_for_tool(task), + ) + + _mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload)) + if commit: + db.session.commit() + else: + db.session.flush() + return tool_response( + status="needs_human", + task=task, + message=task.error_message, + data=serialize_task_for_tool(task), + ) + + def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: """RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。""" from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + cleanup_retry_warnings = flush_callback_cleanup_queue() + task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") + task = _lock_task_for_rpa_callback(task) + + gate_resp = _validate_rpa_callback_gate(task) + if gate_resp is not None: + return gate_resp + runtime = _save_last_inventory_rpa_runtime(task, payload) callback_status = _normalize_rpa_inventory_result_status(payload) - # [STEP 1] skipped:已执行但无库存,记审计事件,不计入 RPA 技术失败重试。 + round_resp = _validate_rpa_callback_round(task, payload) + if round_resp is not None: + return round_resp + if callback_status == "skipped": - skip_reason = str(payload.get("skip_reason") or "no_inventory_data").strip() - detail = str(payload.get("message") or payload.get("error_message") or "").strip() - message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail) - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = None - step_payload = dict(task.step_payload_json or {}) - step_payload["inventory_rpa_skipped"] = { - "skip_reason": skip_reason, - "message": detail or message, - "reported_at": datetime.utcnow().isoformat(), - "rpa_runtime": runtime, - } - task.step_payload_json = step_payload - set_task_step_progress( - task, - step_key="step3_inventory_prepare", - step_title="获取库存", - status="needs_human", - message="货代系统当前无可用库存", - progress_percent=100, - detail="请确认仓库是否正确,或手动上传货代库存 Excel。", - ) - log_task_event( - task, - "inventory_rpa_skipped", - { - "skip_reason": skip_reason, - "message": detail or message, - "rpa_runtime": runtime, - }, - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=message, - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - ) + return _handle_rpa_inventory_skipped(task, payload, runtime) - # [STEP 2] failed:RPA 技术失败,累计尝试次数并在耗尽后转人工上传兜底。 if callback_status == "failed": - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] - log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime}) - db.session.flush() - attempts = inventory_rpa_attempts(task) - if attempts >= max_rpa_inventory_attempts(): - apply_task_transition(task, TaskTransition.RPA_EXHAUSTED) - task.error_message = "已多次尝试仍无法通过 RPA 获取库存" - log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts}) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=_inventory_rpa_exhausted_message(attempts), - data=serialize_task_for_tool(task), - ) + return _handle_rpa_inventory_failed(task, payload, runtime) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=task.error_message, - data=serialize_task_for_tool(task), - ) + identity_resp = _validate_rpa_callback_success_identity(task, payload) + if identity_resp is not None: + return identity_resp # [STEP 3] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。 # 这样 inventory_uploads 会保留任务级正式附件,回调路径也能与人工上传共享同一托管约定。 file_path = str(payload.get("file_path") or "").strip() - path = Path(file_path) if file_path else find_latest_inventory_file() - if not path or not path.is_file(): + run_no = str(payload.get("run_no") or "").strip() + if not run_no: + expected_run_no = _expected_rpa_callback_run_no(task) + if expected_run_no and not _is_legacy_trigger_run_no(expected_run_no): + return tool_response(status="failed", task_id=task.task_no, message="RPA 回调缺少 run_no") + run_no = expected_run_no + if not file_path: + return tool_response(status="failed", task_id=task.task_no, message="库存文件路径缺失") + path = Path(file_path) + if not path.is_file(): return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在") processed = inventory_processed_dir() - managed_path = save_task_inventory_local_file(task.task_no, path) - rpa_source = task_rpa_inventory_source(task) or {} - if not rpa_source.get("source_code") and payload.get("source_code"): - rpa_source = build_rpa_inventory_source(str(payload.get("source_code"))) or rpa_source - inv_file = create_inventory_snapshot_from_rpa( - source=rpa_source or {"source_code": payload.get("source_code"), "source_type": payload.get("source_type")}, - local_path=managed_path, - source_file_name=path.name, - rpa_run_no=str(payload.get("run_no") or "").strip() or None, - trigger_type="on_demand", - success=True, - user_id=task.user_id, - batch_id=task.batch_id, - ) - link_snapshot_to_task( - task, - inv_file, - reason="rpa_callback", - audit_payload={"rpa_runtime": runtime}, - ) - lines, column_meta = ingest_inventory_file(path, move_to=processed) - set_task_step_progress( - task, - step_key="step3_inventory_prepare", - step_title="获取库存", - status="running", - message="RPA 库存文件已返回,正在读取库存快照", - progress_percent=85, - detail=f"正在读取 {managed_path.name}", - ) - log_task_event( - task, + rpa_source = task_rpa_inventory_source(task) + if not rpa_source or not rpa_source.get("source_code"): + return tool_response( + status="failed", + task=task, + message="任务库存源未配置,拒绝处理 RPA 回调", + data=serialize_task_for_tool(task), + ) + + staging_path: Path | None = None + inv_file: ShippingInventoryFile | None = None + created_new = False + orphan_paths: list[str | Path] = [] + try: + staging_path = stage_task_inventory_callback_file(task.task_no, path, run_no=run_no) + inv_file, created_new = get_or_create_rpa_inventory_snapshot( + source=rpa_source, + local_path=staging_path, + source_file_name=path.name, + rpa_run_no=run_no, + trigger_type="on_demand", + success=True, + user_id=task.user_id, + batch_id=task.batch_id, + verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None, + ) + if not created_new: + reuse_error = _validate_reused_snapshot_callback_file(inv_file, path) + if reuse_error: + delete_staged_task_inventory_file(staging_path) + return tool_response( + status="failed", + task=task, + message="复用库存快照时回调文件与托管文件内容不一致", + data={**serialize_task_for_tool(task), "error": reuse_error}, + ) + ingest_path = _snapshot_ingest_path(inv_file) + if created_new and inv_file.storage_path: + orphan_paths.append(inv_file.storage_path) + except AppError as exc: + delete_staged_task_inventory_file(staging_path) + if inv_file is not None and created_new: + _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=True) + return tool_response( + status="failed", + task=task, + message=str(exc.message or "库存文件身份校验失败"), + data=serialize_task_for_tool(task), + ) + except Exception as exc: + delete_staged_task_inventory_file(staging_path) + if inv_file is not None and created_new: + _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=True) + return tool_response( + status="failed", + task=task, + message=f"RPA 库存快照准备失败: {str(exc)[:200]}", + data={**serialize_task_for_tool(task), "error": "snapshot_prepare_failed"}, + ) + + if inv_file is None: + return tool_response(status="failed", task=task, message="RPA 库存快照准备未完成") + + item_savepoint = db.session.begin_nested() + response: dict[str, Any] | None = None + try: + link = link_snapshot_to_task( + task, + inv_file, + reason="rpa_callback", + audit_payload={"rpa_runtime": runtime}, + ) + if link is None: + raise _RpaCallbackItemAbort("inventory_identity_mismatch") + + lines, column_meta = ingest_inventory_file(ingest_path, move_to=None) + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="running", + message="RPA 库存文件已返回,正在读取库存快照", + progress_percent=85, + detail=f"正在读取 {ingest_path.name}", + ) + log_task_event( + task, "inventory_uploaded", { "source": "rpa_callback", "rpa_runtime": runtime, - "upload_filename": managed_path.name, - "upload_path": str(managed_path), - "origin_file_path": str(path), - "inventory_file_no": inv_file.inventory_file_no, - }, - ) - return inventory_loaded_response( - task, - lines, - column_meta=column_meta, - source="rpa_callback", - require_mapping_review=True, - event_type="inventory_rpa_ready", + "upload_filename": ingest_path.name, + "upload_path": str(ingest_path), + "origin_file_path": str(path), + "inventory_file_no": inv_file.inventory_file_no, + "reused_existing_snapshot": not created_new, + }, + ) + _mark_inventory_rpa_run_no_consumed(task, run_no) + response = inventory_loaded_response( + task, + lines, + column_meta=column_meta, + source="rpa_callback", + require_mapping_review=True, + event_type="inventory_rpa_ready", + commit=False, + ) + item_savepoint.commit() + except _RpaCallbackItemAbort as abort: + item_savepoint.rollback() + delete_staged_task_inventory_file(staging_path) + _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=created_new) + return tool_response( + status="failed", + task=task, + message="库存快照身份与任务库存源不一致,已拒绝入库", + data={**serialize_task_for_tool(task), "error": abort.error}, + ) + except Exception as exc: + item_savepoint.rollback() + delete_staged_task_inventory_file(staging_path) + _rollback_orphan_inventory_snapshot(inv_file, *orphan_paths, created_new=created_new) + return tool_response( + status="failed", + task=task, + message=f"RPA 库存文件解析失败: {str(exc)[:200]}", + data=serialize_task_for_tool(task), + ) + + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + delete_staged_task_inventory_file(staging_path) + _rollback_orphan_inventory_snapshot( + inv_file, + *orphan_paths, + created_new=created_new, + delete_session_row=False, + ) + return tool_response( + status="failed", + task=task, + message=f"RPA 回调提交失败: {str(exc)[:200]}", + data={**serialize_task_for_tool(task), "error": "callback_commit_failed"}, + ) + + post_commit_warnings: list[str] = list(cleanup_retry_warnings) + mark_callback_drop_file_consumed( + path, + run_no=run_no, + task_no=task.task_no, + inventory_file_no=inv_file.inventory_file_no, ) + promote_ok = False + try: + promote_staged_task_inventory_file(task.task_no, staging_path) + promote_ok = True + except Exception as exc: + post_commit_warnings.append(f"promote_task_attachment_failed:{str(exc)[:120]}") + logging.getLogger(__name__).warning( + "RPA task attachment promote failed after commit for task %s", + task.task_no, + exc_info=exc, + ) + promote_ok = _try_rebuild_task_inventory_attachment(task, inv_file, post_commit_warnings) + + if promote_ok and path.is_file(): + move_warning = _archive_callback_drop_file( + path, + processed, + run_no=run_no, + task_no=task.task_no, + inventory_file_no=inv_file.inventory_file_no, + ) + if move_warning: + post_commit_warnings.append(f"move_callback_file_failed:{move_warning}") + + try: + from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks + + start_inventory_file_linked_tasks(inv_file) + except Exception as exc: + post_commit_warnings.append(f"start_linked_tasks_failed:{str(exc)[:120]}") + logging.getLogger(__name__).warning( + "RPA linked-task start failed after commit for task %s", + task.task_no, + exc_info=exc, + ) + + if post_commit_warnings: + _persist_post_commit_task_event( + task, + "inventory_rpa_post_commit_warning", + {"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no}, + ) + + if response is None: + return tool_response(status="failed", task=task, message="RPA 回调处理未完成") + if post_commit_warnings: + data = response.get("data") if isinstance(response.get("data"), dict) else {} + response["data"] = {**data, "post_commit_warnings": post_commit_warnings} + return response def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: @@ -837,6 +1650,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: """ from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + cleanup_retry_warnings = flush_callback_cleanup_queue() + run_no = str(payload.get("run_no") or "").strip() schedule_run_id = payload.get("schedule_run_id") try: @@ -844,6 +1659,14 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: except (TypeError, ValueError): schedule_run_id = None + schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no) + if schedule_run_error: + return tool_response( + status="failed", + message="排程 RPA 回调 run_no 无效或与当前等待轮次不一致", + data={"schedule_run_error": schedule_run_error, "run_no": run_no}, + ) + results = payload.get("results") or [] if not isinstance(results, list): return tool_response(status="failed", message="results must be a list") @@ -851,94 +1674,301 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: created: list[dict[str, Any]] = [] failed: list[dict[str, Any]] = [] skipped: list[dict[str, Any]] = [] + batch_new_storage_paths: list[str] = [] + pending_callback_moves: list[dict[str, Any]] = [] - for item in results: - if not isinstance(item, dict): - continue - source_code = str(item.get("source_code") or "").strip().upper() - warehouse_id = str(item.get("warehouse_id") or "").strip() - raw_status = _normalize_rpa_inventory_batch_item_status(item) - source = build_rpa_inventory_source(source_code) or { - "source_code": source_code, - "site_id": item.get("site_id"), - "warehouse_id": warehouse_id, - "source_type": item.get("source_type"), - } - - if raw_status == "success": - file_path = str(item.get("file_path") or "").strip() - path = Path(file_path) if file_path else None - if not path or not path.is_file(): - failed.append({ - "source_code": source_code, - "site_id": item.get("site_id"), - "warehouse_id": warehouse_id, - "error": "file_missing", - }) + try: + for item in results: + if not isinstance(item, dict): continue - inv_file = create_inventory_snapshot_from_rpa( - source=source, - local_path=path, - source_file_name=path.name, - rpa_run_no=run_no or None, - schedule_run_id=schedule_run_id, - trigger_type=str(payload.get("trigger_type") or "scheduled"), - success=True, - ) - created.append({ - "inventory_file_no": inv_file.inventory_file_no, - "source_code": source_code, - "site_id": item.get("site_id"), - "warehouse_id": warehouse_id, - }) - - task_no = str(item.get("task_no") or "").strip() + merged_item = _merge_batch_callback_item(payload, item) + source_code = str(merged_item.get("source_code") or "").strip().upper() + warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper() + site_id = str(merged_item.get("site_id") or "").strip().upper() + raw_status = _normalize_rpa_inventory_batch_item_status(merged_item) + task_no = str(merged_item.get("task_no") or "").strip() + task: ShippingTask | None = None if task_no: task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no}) - if task: - link_snapshot_to_task( - task, - inv_file, - reason="rpa_batch_callback", - audit_payload={"run_no": run_no}, - ) - lines, column_meta = ingest_inventory_file(path, move_to=inventory_processed_dir()) - if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}: - inventory_loaded_response( - task, - lines, - column_meta=column_meta, - source="rpa_batch_callback", - require_mapping_review=True, - event_type="inventory_rpa_ready", - ) - elif raw_status == "skipped": - skipped.append({ - "source_code": source_code, - "site_id": item.get("site_id"), - "warehouse_id": warehouse_id, - "skip_reason": item.get("skip_reason") or "skipped", - "message": item.get("message") or item.get("error_message") or "", - }) - else: - create_inventory_snapshot_from_rpa( - source=source, - local_path=item.get("file_path") or "", - rpa_run_no=run_no or None, - schedule_run_id=schedule_run_id, - trigger_type=str(payload.get("trigger_type") or "scheduled"), - success=False, - error_message=str(item.get("error_message") or "export failed")[:500], - ) - failed.append({ - "source_code": source_code, - "site_id": item.get("site_id"), - "warehouse_id": warehouse_id, - "error_code": item.get("error_code") or "rpa_export_failed", - "error": item.get("error_message"), - }) + if task is None: + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": "task_not_found", + }) + continue + task = _lock_task_for_rpa_callback(task) - db.session.commit() + if task and raw_status in {"skipped", "failed"}: + gate_resp = _validate_rpa_callback_gate(task) + if gate_resp is not None: + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": gate_resp.get("message") or "inventory_source_gate_blocked", + }) + continue + round_resp = _validate_rpa_callback_round(task, merged_item) + if round_resp is not None: + round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {} + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": round_data.get("run_no_error") or "run_no_invalid", + }) + continue + runtime = _save_last_inventory_rpa_runtime(task, merged_item) + if raw_status == "skipped": + _handle_rpa_inventory_skipped(task, merged_item, runtime, commit=False) + skipped.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "skip_reason": merged_item.get("skip_reason") or "skipped", + "message": merged_item.get("message") or merged_item.get("error_message") or "", + }) + else: + _handle_rpa_inventory_failed(task, merged_item, runtime, commit=False) + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error_code": merged_item.get("error_code") or "rpa_export_failed", + "error": merged_item.get("error_message"), + }) + continue + + source = _resolve_batch_callback_source(task, merged_item) + if not source: + error = { + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "error": "unknown_or_disabled_source", + } + if task_no: + error["task_no"] = task_no + if raw_status == "success": + failed.append(error) + else: + failed.append({ + **error, + "error_code": merged_item.get("error_code") or "rpa_export_failed", + "error_message": merged_item.get("error_message"), + }) + continue + + if raw_status == "success": + file_path = str(merged_item.get("file_path") or "").strip() + path = Path(file_path) if file_path else None + if not path or not path.is_file(): + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "error": "file_missing", + }) + continue + + if task: + gate_resp = _validate_rpa_callback_inventory_source(task, merged_item) + if gate_resp is not None: + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": gate_resp.get("message") or "inventory_source_gate_blocked", + }) + continue + if not inventory_identities_match( + task, + source_code=str(source.get("source_code") or ""), + site_id=str(source.get("site_id") or ""), + warehouse_id=str(source.get("warehouse_id") or ""), + ): + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": "inventory_identity_mismatch", + }) + continue + else: + identity_error = _validate_batch_callback_worker_identity(merged_item, source) + if identity_error: + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "error": identity_error, + }) + continue + + verify_wh = _batch_snapshot_verify_warehouse_id(task, source, merged_item) + item_savepoint = db.session.begin_nested() + item_orphan_path: str | None = None + created_new = False + inv_file: ShippingInventoryFile | None = None + created_entry: dict[str, Any] | None = None + try: + try: + inv_file, created_new = get_or_create_rpa_inventory_snapshot( + source=source, + local_path=path, + source_file_name=path.name, + rpa_run_no=run_no or None, + schedule_run_id=schedule_run_id, + trigger_type=str(payload.get("trigger_type") or "scheduled"), + success=True, + verify_warehouse_id=verify_wh, + ) + except AppError as exc: + raise _RpaCallbackItemAbort(str(exc.message or "inventory_identity_mismatch")) from exc + + if not created_new: + reuse_error = _validate_reused_snapshot_callback_file(inv_file, path) + if reuse_error: + raise _RpaCallbackItemAbort(reuse_error) + + if ( + created_new + and inv_file.storage_path + and not str(inv_file.storage_path).startswith("failed://") + ): + item_orphan_path = str(inv_file.storage_path) + + created_entry = { + "inventory_file_no": inv_file.inventory_file_no, + "source_code": inv_file.source_code or source_code, + "site_id": inv_file.site_id or merged_item.get("site_id"), + "warehouse_id": inv_file.warehouse_id or warehouse_id, + "reused_existing_snapshot": not created_new, + } + created.append(created_entry) + if item_orphan_path: + batch_new_storage_paths.append(item_orphan_path) + + if task_no and task: + if not inventory_identities_match( + task, + source_code=inv_file.source_code, + site_id=inv_file.site_id, + warehouse_id=inv_file.warehouse_id, + ): + raise _RpaCallbackItemAbort("inventory_identity_mismatch") + link = link_snapshot_to_task( + task, + inv_file, + reason="rpa_batch_callback", + audit_payload={"run_no": run_no}, + ) + if link is None: + raise _RpaCallbackItemAbort("inventory_identity_mismatch") + ingest_path = _snapshot_ingest_path(inv_file) + lines, column_meta = ingest_inventory_file(ingest_path, move_to=None) + if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}: + inventory_loaded_response( + task, + lines, + column_meta=column_meta, + source="rpa_batch_callback", + require_mapping_review=True, + event_type="inventory_rpa_ready", + commit=False, + ) + _mark_inventory_rpa_run_no_consumed( + task, + _resolve_effective_callback_run_no(task, merged_item), + ) + + if path.is_file(): + pending_callback_moves.append({ + "path": path, + "run_no": run_no or None, + "task_no": task_no or None, + "schedule_run_id": schedule_run_id, + "inventory_file_no": inv_file.inventory_file_no, + }) + + item_savepoint.commit() + except _RpaCallbackItemAbort as abort: + item_savepoint.rollback() + if item_orphan_path: + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + delete_inventory_storage_path(item_orphan_path) + if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: + batch_new_storage_paths.pop() + if created_entry and created and created[-1] is created_entry: + created.pop() + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no or None, + "error": abort.error, + }) + continue + except Exception as exc: + item_savepoint.rollback() + if item_orphan_path: + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + delete_inventory_storage_path(item_orphan_path) + if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: + batch_new_storage_paths.pop() + if created_entry and created and created[-1] is created_entry: + created.pop() + failed.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "task_no": task_no, + "error": str(exc)[:200] or "batch_ingest_failed", + }) + continue + elif raw_status == "skipped": + skipped.append({ + "source_code": source_code, + "site_id": merged_item.get("site_id"), + "warehouse_id": warehouse_id, + "skip_reason": merged_item.get("skip_reason") or "skipped", + "message": merged_item.get("message") or merged_item.get("error_message") or "", + }) + else: + failed.append({ + "source_code": str(source.get("source_code") or source_code), + "site_id": source.get("site_id"), + "warehouse_id": source.get("warehouse_id"), + "error_code": merged_item.get("error_code") or "rpa_export_failed", + "error": merged_item.get("error_message"), + }) + + db.session.commit() + except Exception as exc: + db.session.rollback() + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + for storage_path in batch_new_storage_paths: + delete_inventory_storage_path(storage_path) + return tool_response( + status="failed", + message=f"批量库存回调事务失败: {str(exc)[:200]}", + data={ + "run_no": run_no, + "rolled_back_storage_paths": len(batch_new_storage_paths), + }, + ) finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"} if schedule_run_id is not None: @@ -952,6 +1982,15 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: payload=payload, ) + callback_move_warnings: list[str] = list(cleanup_retry_warnings) + if _should_flush_batch_callback_moves(schedule_run_id, finalize_result): + callback_move_warnings.extend( + _flush_pending_callback_moves( + pending_callback_moves, + inventory_processed_dir(), + ), + ) + response_data = { "run_no": run_no, "created": created, @@ -964,6 +2003,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: response_data["schedule_finalize_error"] = finalize_result.get("error") if finalize_result.get("manual_retryable"): response_data["schedule_finalize_manual_retryable"] = True + if callback_move_warnings: + response_data["callback_move_warnings"] = callback_move_warnings outcome = _resolve_rpa_inventory_batch_response_outcome( created=created, @@ -994,3 +2035,143 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: "failed_count": outcome["failed_count"], }, ) + + +def _validate_repair_inventory_snapshot( + task: ShippingTask, + inv_file: ShippingInventoryFile | None, + *, + requested_file_no: str | None = None, +) -> str | None: + """ + 校验修复接口允许使用的库存快照。 + 核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。 + """ + from app.models import ShippingTaskInventoryLink + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh + from app.services.shipping_notice.inventory_source_gate import ( + inventory_identities_match, + is_inventory_source_stable, + ) + + if inv_file is None: + return "snapshot_not_found" + active = active_inventory_file_for_task(task) + if active is None: + return "no_active_snapshot" + if inv_file.id != active.id: + return "snapshot_not_active_for_task" + if requested_file_no and active.inventory_file_no != requested_file_no: + return "snapshot_not_active_for_task" + if task.id is not None: + link = ShippingTaskInventoryLink.query.filter_by( + task_id=task.id, + inventory_file_id=inv_file.id, + is_active=True, + ).first() + if link is None: + return "snapshot_not_linked_to_task" + if str(inv_file.snapshot_status or "") != "ready": + return "snapshot_not_ready" + if not is_snapshot_fresh(inv_file): + return "snapshot_expired" + if not is_inventory_source_stable(task): + return "inventory_source_unstable" + if not inventory_identities_match( + task, + source_code=inv_file.source_code, + site_id=inv_file.site_id, + warehouse_id=inv_file.warehouse_id, + ): + return "inventory_identity_mismatch" + return None + + +def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: + """ + 从任务当前库存快照 storage_path 幂等重建正式附件。 + 【AI 触发时机】:RPA 回调已提交但任务附件晋升失败,需人工/后台补偿且不能重新消费 callback 时调用。 + + Args: + payload: 须含 task_id/task_no;可选 inventory_file_no 指定快照。 + + Returns: + tool_response:含 attachment_path 与 inventory_file_no。 + """ + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + + task = resolve_task_from_payload(payload) + if not task: + return tool_response(status="failed", message="未找到任务编号") + + inv_file_no = str(payload.get("inventory_file_no") or "").strip() + inv_file = active_inventory_file_for_task(task) + if inv_file is None: + return tool_response( + status="failed", + task=task, + message="任务无可用库存快照,无法重建附件", + data=serialize_task_for_tool(task), + ) + if inv_file_no and inv_file.inventory_file_no != inv_file_no: + return tool_response( + status="failed", + task=task, + message="指定快照不是任务当前 active 库存快照,已拒绝修复", + data={**serialize_task_for_tool(task), "error": "snapshot_not_active_for_task"}, + ) + + validation_error = _validate_repair_inventory_snapshot( + task, + inv_file, + requested_file_no=inv_file_no or None, + ) + if validation_error: + return tool_response( + status="failed", + task=task, + message="库存快照未通过修复校验,已拒绝重建附件", + data={**serialize_task_for_tool(task), "error": validation_error}, + ) + + try: + attachment_path = rebuild_task_inventory_attachment_from_snapshot(task, inv_file) + except (FileNotFoundError, OSError, ValueError) as exc: + return tool_response( + status="failed", + task=task, + message=f"重建任务库存附件失败: {str(exc)[:200]}", + data={**serialize_task_for_tool(task), "error": "attachment_rebuild_failed"}, + ) + + log_task_event( + task, + "inventory_attachment_repaired", + { + "inventory_file_no": inv_file.inventory_file_no, + "attachment_path": str(attachment_path), + "source": str(payload.get("source") or "manual_repair"), + }, + ) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + return tool_response( + status="failed", + task=task, + message=f"附件修复事件提交失败: {str(exc)[:200]}", + data=serialize_task_for_tool(task), + ) + + return tool_response( + status="ok", + task=task, + message="任务库存附件已从快照重建", + data={ + **serialize_task_for_tool(task), + "inventory_file_no": inv_file.inventory_file_no, + "attachment_path": str(attachment_path), + }, + ) diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py index 2a6f7138..8e6eae81 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -248,7 +248,18 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40 def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]: - """Load worksheet rows; returns (rows, total_row_count_hint).""" + """Load worksheet or CSV rows; returns (rows, total_row_count_hint).""" + suffix = path.suffix.lower() + if suffix == ".csv": + from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows + + rows = load_inventory_csv_rows(path, max_rows=max_rows) + try: + total = sum(1 for _ in path.open("r", encoding="utf-8", errors="ignore")) + except OSError: + total = len(rows) + return rows, int(total) + wb = load_workbook(filename=str(path), data_only=True, read_only=True) try: ws = wb.active diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index 9fb98545..b189c217 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -14,7 +14,6 @@ from pathlib import Path from typing import Any from flask import current_app -from openpyxl import load_workbook from app import db from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink @@ -22,6 +21,7 @@ from app.services.shipping_notice.inventory_file_store import ( _can_relink_inventory, generate_inventory_file_no, inventory_file_upload_path, + inventory_storage_suffix_for_path, replace_task_inventory_link, ) from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview @@ -71,33 +71,156 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = def find_latest_ready_snapshot( source_code: str | None, - warehouse_id: str | None, + site_id: str | None, + warehouse_id: str | None = None, ) -> ShippingInventoryFile | None: """ - 查找指定 source/warehouse 最新 ready 且未过期的库存快照。 - 核心逻辑:按 exported_at 倒序取第一条;过期快照不在此返回。 + 查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。 + 核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。 """ code = str(source_code or "").strip().upper() + site = str(site_id or "").strip().upper() warehouse = str(warehouse_id or "").strip().upper() - if not code or not warehouse: + if not code: + return None + if not site and not warehouse: return None - rows = ( - ShippingInventoryFile.query.filter_by( - source_code=code, - warehouse_id=warehouse, - snapshot_status=_SNAPSHOT_STATUS_READY, - ) - .order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()) - .limit(5) - .all() + query = ShippingInventoryFile.query.filter_by( + source_code=code, + snapshot_status=_SNAPSHOT_STATUS_READY, ) + if site: + query = query.filter_by(site_id=site) + if warehouse: + query = query.filter_by(warehouse_id=warehouse) + elif site: + query = query.filter( + (ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "") + ) + + rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all() for row in rows: if is_snapshot_fresh(row): return row return None +def find_ready_rpa_inventory_snapshot( + *, + rpa_run_no: str, + source_code: str, + site_id: str, + warehouse_id: str, +) -> ShippingInventoryFile | None: + """ + 按 RPA 轮次 + 四字段身份查找已入库 ready 快照。 + 核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。 + """ + run_no = str(rpa_run_no or "").strip() + code = str(source_code or "").strip().upper() + site = str(site_id or "").strip().upper() + warehouse = str(warehouse_id or "").strip().upper() + if not run_no or not code or not site or not warehouse: + return None + return ( + ShippingInventoryFile.query.filter_by( + rpa_run_no=run_no, + source_code=code, + site_id=site, + warehouse_id=warehouse, + snapshot_status=_SNAPSHOT_STATUS_READY, + ) + .order_by(ShippingInventoryFile.id.desc()) + .first() + ) + + +def get_or_create_rpa_inventory_snapshot( + *, + source: dict[str, Any], + local_path: str | Path, + source_file_name: str | None = None, + rpa_run_no: str | None = None, + schedule_run_id: int | None = None, + trigger_type: str = "on_demand", + success: bool = True, + error_message: str | None = None, + user_id: int | None = None, + batch_id: int | None = None, + share_mode: str | None = None, + verify_warehouse_id: str | None = None, +) -> tuple[ShippingInventoryFile, bool]: + """ + 幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。 + 核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。 + + Returns: + tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。 + """ + from sqlalchemy.exc import IntegrityError + + run_no = str(rpa_run_no or "").strip() + code = str(source.get("source_code") or "").strip().upper() + site = str(source.get("site_id") or "").strip().upper() + warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper() + if run_no and code and site and warehouse: + existing = find_ready_rpa_inventory_snapshot( + rpa_run_no=run_no, + source_code=code, + site_id=site, + warehouse_id=warehouse, + ) + if existing: + return existing, False + + savepoint = db.session.begin_nested() + orphan_storage_path: str | None = None + try: + inv_file = create_inventory_snapshot_from_rpa( + source=source, + local_path=local_path, + source_file_name=source_file_name, + rpa_run_no=rpa_run_no, + schedule_run_id=schedule_run_id, + trigger_type=trigger_type, + success=success, + error_message=error_message, + user_id=user_id, + batch_id=batch_id, + share_mode=share_mode, + verify_warehouse_id=verify_warehouse_id, + ) + if inv_file.storage_path and not str(inv_file.storage_path).startswith("failed://"): + orphan_storage_path = str(inv_file.storage_path) + db.session.flush() + savepoint.commit() + return inv_file, True + except IntegrityError: + savepoint.rollback() + if orphan_storage_path: + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + delete_inventory_storage_path(orphan_storage_path) + if run_no and code and site and warehouse: + existing = find_ready_rpa_inventory_snapshot( + rpa_run_no=run_no, + source_code=code, + site_id=site, + warehouse_id=warehouse, + ) + if existing: + return existing, False + raise + except Exception: + savepoint.rollback() + if orphan_storage_path: + from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + + delete_inventory_storage_path(orphan_storage_path) + raise + + def list_available_snapshots( *, source_code: str | None = None, @@ -126,33 +249,15 @@ def _normalize_header_key(value: Any) -> str: def _extract_warehouse_id_from_inventory_excel(path: Path) -> str: - """ - 从库存 Excel 内容中提取 Warehouse ID。 - 核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。 - """ - if not path or not path.is_file(): - return "" - try: - wb = load_workbook(filename=str(path), data_only=True, read_only=True) - except Exception: - return "" - try: - ws = wb.active - rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True)) - finally: - wb.close() + """从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。""" + from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel - for row_idx, row in enumerate(rows): - for col_idx, cell in enumerate(row): - if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES: - continue - for data_row in rows[row_idx + 1:]: - if col_idx >= len(data_row): - continue - value = str(data_row[col_idx] or "").strip().upper() - if value: - return value - return "" + values = extract_warehouse_ids_from_inventory_excel(path) + if not values: + return "" + if len(values) > 1: + return "" + return next(iter(values)) def create_inventory_snapshot_from_rpa( @@ -168,6 +273,7 @@ def create_inventory_snapshot_from_rpa( user_id: int | None = None, batch_id: int | None = None, share_mode: str | None = None, + verify_warehouse_id: str | None = None, ) -> ShippingInventoryFile: """ 从 RPA 导出文件创建库存快照记录。 @@ -187,19 +293,39 @@ def create_inventory_snapshot_from_rpa( source_code = str(source.get("source_code") or "").strip().upper() configured_site_id = str(source.get("site_id") or "").strip().upper() export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper() + runtime_identity_applied = bool(source.get("_runtime_identity_applied")) excel_warehouse_id = "" - warehouse_id = configured_site_id - warehouse_code = warehouse_id + warehouse_id = export_warehouse_id + warehouse_code = warehouse_id or configured_site_id + excel_verified = False if success: - path = inventory_file_upload_path(inventory_file_no) - path.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(local_path, path) - excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path) - warehouse_id = configured_site_id or excel_warehouse_id - warehouse_code = warehouse_id - preview = read_inventory_schema_preview(path) - preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name + local = Path(local_path) + expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper() + if expected_wh: + from app.services.shipping_notice.inventory_file_identity import ( + assert_inventory_excel_warehouse_identity, + ) + + excel_warehouse_id = assert_inventory_excel_warehouse_identity( + local, + expected_warehouse_id=expected_wh, + operation="rpa_snapshot", + ) + warehouse_id = expected_wh + warehouse_code = warehouse_id + excel_verified = True + path = inventory_file_upload_path( + inventory_file_no, + suffix=inventory_storage_suffix_for_path(local), + ) + if not excel_verified and not warehouse_id: + excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(local) + if excel_warehouse_id: + warehouse_id = excel_warehouse_id + warehouse_code = warehouse_id + preview = read_inventory_schema_preview(local) + preview["upload_filename"] = str(source_file_name or local.name).strip() or path.name snapshot_status = _SNAPSHOT_STATUS_READY storage_path = str(path) else: @@ -208,6 +334,8 @@ def create_inventory_snapshot_from_rpa( snapshot_status = _SNAPSHOT_STATUS_FAILED storage_path = str(path) if path and path.is_file() else "" + from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version + inv_file = ShippingInventoryFile( inventory_file_no=inventory_file_no, batch_id=batch_id, @@ -219,6 +347,9 @@ def create_inventory_snapshot_from_rpa( line_count=0, warehouse_id=warehouse_id or None, warehouse_code=warehouse_code or None, + site_id=configured_site_id or None, + source_config_version=get_inventory_sources_config_version(), + identity_status="pending" if success else "unknown", source_code=source_code or None, source_type=str(source.get("source_type") or "").strip() or None, snapshot_status=snapshot_status, @@ -233,12 +364,38 @@ def create_inventory_snapshot_from_rpa( "site_id": configured_site_id or None, "export_warehouse_id": export_warehouse_id, "excel_warehouse_id": excel_warehouse_id or None, - "warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None), + "warehouse_id_source": ( + "task_identity_excel_verified" + if excel_verified + else ( + "runtime_identity" + if runtime_identity_applied + else ( + "export_config" + if export_warehouse_id + else ("inventory_excel" if excel_warehouse_id else None) + ) + ) + ), + "excel_warehouse_verified": excel_verified, "trigger_type": trigger_type, }, ) db.session.add(inv_file) db.session.flush() + # [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。 + if success and storage_path and not str(storage_path).startswith("failed://"): + path = Path(storage_path) + path.parent.mkdir(parents=True, exist_ok=True) + try: + shutil.copy2(local_path, path) + except Exception: + if path.exists(): + try: + path.unlink() + except OSError: + pass + raise return inv_file @@ -247,6 +404,7 @@ def link_snapshot_to_task( inv_file: ShippingInventoryFile, *, reason: str, + role: str = "member", audit_payload: dict[str, Any] | None = None, ) -> ShippingTaskInventoryLink | None: """ @@ -265,9 +423,25 @@ def link_snapshot_to_task( if inv_file.exported_at: age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0) - link = replace_task_inventory_link(task, inv_file, role="member") + from app.services.shipping_notice.inventory_source_gate import inventory_identities_match + + identity_ok = inventory_identities_match( + task, + source_code=inv_file.source_code, + site_id=inv_file.site_id, + warehouse_id=inv_file.warehouse_id, + ) + inv_file.identity_status = "verified" if identity_ok else "mismatch" + if not identity_ok: + return None + + link = replace_task_inventory_link(task, inv_file, role=role) link.link_reason = reason link.matched_warehouse_id = inv_file.warehouse_id + link.matched_source_code = inv_file.source_code + link.matched_site_id = inv_file.site_id + link.identity_check_status = "verified" if identity_ok else "mismatch" + link.identity_checked_at = datetime.utcnow() link.snapshot_age_seconds = age_seconds link.audit_payload_json = { **(audit_payload or {}), diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py new file mode 100644 index 00000000..a8b88bdf --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -0,0 +1,402 @@ +""" +services/shipping_notice/inventory_source_gate.py + +用途:库存源稳定性门禁、独立字段写入与路由指纹管理。 +依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。 +逻辑:订单解析与后续 RPA/库存/匹配/导出流程统一调用本模块,禁止散落判断。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.core.errors import AppError +from app.models import ShippingTask +from app.services.shipping_notice.inventory_source_identity import identity_matches_config +from app.services.shipping_notice.inventory_source_rules import ( + InventorySourceAdjudication, + adjudicate_inventory_source, + confirm_inventory_source_by_code, + compute_routing_fingerprint, + extract_routing_context, +) +from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version + + +STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"}) + +INVENTORY_SOURCE_ERROR_CODES = { + "unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED", + "ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS", + "invalid": "SHIPPING.INVENTORY_SOURCE_INVALID", + "conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED", + "confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED", + "changed": "SHIPPING.INVENTORY_SOURCE_CHANGED", + "identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH", + "gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", +} + + +def _inventory_source_config_current(task: ShippingTask) -> bool: + """任务上记录的库存源配置版本须与当前 YAML 版本一致。""" + stored = str(task.inventory_source_config_version or "").strip() + current = get_inventory_sources_config_version() + if not stored: + return False + return stored == current + + +def is_inventory_source_stable(task: ShippingTask) -> bool: + """ + 判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。 + 核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。 + """ + status = str(task.inventory_source_status or "").strip() + if status not in STABLE_INVENTORY_SOURCE_STATUSES: + return False + if not _inventory_source_config_current(task): + return False + code = str(task.inventory_source_code or "").strip().upper() + if not code: + return False + source_type = str(task.inventory_source_type or "").strip() + if not source_type: + return False + source = get_inventory_source(code) + if not source: + return False + if source_type != str(source.get("source_type") or "").strip(): + return False + + site_id = str(task.inventory_site_id or "").strip().upper() + task_wh = str(task.inventory_warehouse_id or "").strip().upper() + if not site_id or not task_wh: + return False + if not identity_matches_config( + source, + site_id=site_id, + warehouse_id=task_wh, + context=extract_routing_context(task), + ): + return False + + fingerprint = str(task.inventory_routing_fingerprint or "").strip() + if not fingerprint: + return False + context = extract_routing_context(task) + if fingerprint != compute_routing_fingerprint(context): + return False + + return True + + +def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) -> bool: + """比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。""" + previous = str(task.inventory_routing_fingerprint or "").strip() + if not previous: + return False + return previous != compute_routing_fingerprint(context) + + +def inventory_source_config_changed(task: ShippingTask) -> bool: + """配置版本变化会使已确认库存源失效。""" + stored = str(task.inventory_source_config_version or "").strip() + if not stored: + return bool(str(task.inventory_source_status or "").strip()) + return stored != get_inventory_sources_config_version() + + +def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None: + """将标准化目的地线索写入任务独立字段。""" + task.destination_code = str(context.get("destination_code") or "").strip().upper() or None + task.destination_city = str(context.get("destination_city") or "").strip() or None + task.destination_country = str(context.get("destination_country") or "").strip().upper() or None + task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None + + +def clear_inventory_source_confirmation(task: ShippingTask) -> None: + """路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。""" + task.inventory_source_confirmed_by = None + task.inventory_source_confirmed_at = None + if str(task.inventory_source_status or "").strip() == "user_confirmed": + task.inventory_source_status = "unresolved" + task.inventory_source_method = None + payload = dict(task.step_payload_json or {}) + payload.pop("rpa_inventory_source", None) + task.step_payload_json = payload + + +def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudication: + """从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。""" + context = extract_routing_context(task) + return InventorySourceAdjudication( + status=str(task.inventory_source_status or "").strip(), + method=str(task.inventory_source_method or "").strip() or None, + source_code=str(task.inventory_source_code or "").strip().upper() or None, + source_type=str(task.inventory_source_type or "").strip() or None, + site_id=str(task.inventory_site_id or "").strip().upper() or None, + warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None, + config_version=str(task.inventory_source_config_version or "").strip() or None, + routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip() + or compute_routing_fingerprint(context), + destination_candidates=context.get("destination_candidates") or [], + ) + + +def apply_inventory_source_adjudication( + task: ShippingTask, + adjudication: InventorySourceAdjudication, + *, + confirmed_by_user_id: int | None = None, +) -> None: + """ + 将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。 + 核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。 + """ + context = extract_routing_context(task) + fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context) + task.inventory_routing_fingerprint = fingerprint + apply_destination_fields(task, context) + + task.inventory_source_status = adjudication.status + task.inventory_source_method = adjudication.method or None + task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version() + + if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: + task.inventory_source_code = adjudication.source_code + task.inventory_source_type = adjudication.source_type + task.inventory_site_id = adjudication.site_id + task.inventory_warehouse_id = adjudication.warehouse_id or None + if adjudication.status == "user_confirmed" and confirmed_by_user_id: + task.inventory_source_confirmed_by = confirmed_by_user_id + task.inventory_source_confirmed_at = datetime.utcnow() + elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES: + task.inventory_source_code = None + task.inventory_source_type = None + task.inventory_site_id = None + task.inventory_warehouse_id = None + payload = dict(task.step_payload_json or {}) + payload.pop("rpa_inventory_source", None) + task.step_payload_json = payload + + payload = dict(task.step_payload_json or {}) + payload["inventory_source_resolution"] = { + "status": adjudication.status, + "method": adjudication.method, + "reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + "candidates": adjudication.candidates, + "evidence": adjudication.evidence, + "conflicts": adjudication.conflicts, + "config_version": adjudication.config_version, + "routing_fingerprint": fingerprint, + } + if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: + from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source + + rpa_source = build_task_rpa_inventory_source(task) + if rpa_source: + payload["rpa_inventory_source"] = rpa_source + else: + payload.pop("rpa_inventory_source", None) + task.step_payload_json = payload + + +def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication: + """ + 对任务执行库存源裁决并写入独立字段。 + 【AI 触发时机】:订单解析完成后由 parse_notice 调用;重解析时同样调用以刷新裁决。 + """ + context = extract_routing_context(task) + if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context): + clear_inventory_source_confirmation(task) + + if ( + str(task.inventory_source_status or "").strip() == "user_confirmed" + and is_inventory_source_stable(task) + and not routing_fingerprint_changed(task, context) + and not inventory_source_config_changed(task) + ): + return _adjudication_from_stable_task(task) + + adjudication = adjudicate_inventory_source(task) + if ( + str(task.inventory_source_status or "").strip() == "user_confirmed" + and adjudication.status == "resolved" + and adjudication.source_code + and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper() + and is_inventory_source_stable(task) + ): + adjudication = InventorySourceAdjudication( + status="user_confirmed", + method="user_confirmed", + source_code=adjudication.source_code, + source_type=adjudication.source_type, + site_id=adjudication.site_id, + warehouse_id=adjudication.warehouse_id, + config_version=adjudication.config_version, + routing_fingerprint=adjudication.routing_fingerprint, + candidates=adjudication.candidates, + destination_candidates=adjudication.destination_candidates, + evidence=adjudication.evidence, + reason=adjudication.reason, + ) + apply_inventory_source_adjudication(task, adjudication) + return adjudication + + +def task_needs_parse_review(task: ShippingTask) -> bool: + """ + 判断任务是否仍需完成低置信度解析人工确认。 + 核心逻辑:优先看 review/pending 标记;库存源先确认时依赖 step_payload 或 parse_confidence 兜底。 + """ + from flask import current_app + + from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW + + if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF: + return True + payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + if payload.get("pending_parse_review_after_source"): + return True + threshold = float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) + try: + confidence = float(task.parse_confidence) if task.parse_confidence is not None else 1.0 + except (TypeError, ValueError): + confidence = 1.0 + lines = task.lines_json if isinstance(task.lines_json, list) else [] + return confidence < threshold and bool(lines) + + +def transition_task_to_inventory_source_review( + task: ShippingTask, + adjudication: InventorySourceAdjudication, + *, + error_message: str | None = None, + mark_pending_parse_review: bool = False, +) -> None: + """ + 将任务持久化到库存源人工复核检查点,并写入候选裁决信息。 + 核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。 + """ + from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition + + apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) + task.current_step = "step2_parse_confirm" + task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源" + payload = dict(task.step_payload_json or {}) + payload["inventory_source_resolution"] = { + "status": adjudication.status, + "method": adjudication.method, + "reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + "candidates": adjudication.candidates, + "evidence": adjudication.evidence, + "conflicts": adjudication.conflicts, + "config_version": adjudication.config_version, + "routing_fingerprint": adjudication.routing_fingerprint, + } + if mark_pending_parse_review: + payload["pending_parse_review_after_source"] = True + task.step_payload_json = payload + + +def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication: + """ + 对已进入后续阶段但库存源不稳定的任务补做裁决并落库到 inventory_source_review。 + 【AI 触发时机】:auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 + """ + adjudication = adjudicate_and_apply_inventory_source(task) + if not is_inventory_source_stable(task): + transition_task_to_inventory_source_review( + task, + adjudication, + mark_pending_parse_review=task_needs_parse_review(task), + ) + return adjudication + + +def confirm_task_inventory_source( + task: ShippingTask, + source_code: str, + *, + user_id: int | None = None, +) -> InventorySourceAdjudication: + """ + 用户选择 source_code 后由后端重新校验并写入正式库存源。 + 核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。 + """ + adjudication = confirm_inventory_source_by_code(task, source_code) + apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id) + return adjudication + + +def assert_inventory_source_gate( + task: ShippingTask, + *, + operation: str = "continue", +) -> None: + """ + 库存源硬门禁:未稳定时抛出统一业务异常,防止后续流程绕过。 + Args: + task: 当前发货任务。 + operation: 触发门禁的操作名,写入错误 details。 + Raises: + AppError: 库存源未稳定或身份不一致。 + """ + if inventory_source_config_changed(task): + raise AppError( + code=INVENTORY_SOURCE_ERROR_CODES["changed"], + message="库存源配置已更新,请重新确认库存查询来源", + http_status=409, + details={"operation": operation, "task_no": task.task_no}, + ) + if is_inventory_source_stable(task): + return + status = str(task.inventory_source_status or "unresolved").strip() + code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"]) + raise AppError( + code=code, + message="库存源尚未确定,无法继续后续流程", + http_status=409, + details={ + "operation": operation, + "inventory_source_status": status, + "task_no": task.task_no, + }, + ) + + +def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]: + """返回任务当前正式库存身份,供库存文件绑定与匹配校验。""" + return { + "inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None, + "inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None, + "inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None, + } + + +def inventory_identities_match( + task: ShippingTask, + *, + source_code: str | None, + site_id: str | None, + warehouse_id: str | None, +) -> bool: + """校验库存文件/链接身份与任务正式库存源是否完全一致。""" + identity = task_inventory_identity(task) + if not is_inventory_source_stable(task): + return False + expected_code = str(source_code or "").strip().upper() + if expected_code != identity["inventory_source_code"]: + return False + + file_site = str(site_id or "").strip().upper() + file_wh = str(warehouse_id or "").strip().upper() + if not file_site or file_site != (identity["inventory_site_id"] or ""): + return False + if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""): + return False + + return True diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/inventory_source_identity.py new file mode 100644 index 00000000..2118f79b --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_source_identity.py @@ -0,0 +1,156 @@ +""" +services/shipping_notice/inventory_source_identity.py + +用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。 +依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。 +逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + + +def normalize_destination(value: Any) -> str: + """将 Dify/单据中的目的地线索标准化成可匹配 token。""" + text = str(value or "").strip().upper() + if not text: + return "" + return re.sub(r"[^A-Z0-9]+", " ", text).strip() + + +def _matches_alias(candidate: str, alias: str) -> bool: + """别名按词元匹配,避免短 token 误命中更长编码。""" + return _alias_token_match(normalize_destination(candidate), alias) + + +@dataclass(frozen=True) +class ResolvedInventoryIdentity: + """稳定库存源四元组中的站点/库位解析结果。""" + + source_code: str + source_type: str + site_id: str + warehouse_id: str + + +@dataclass(frozen=True) +class InventoryIdentityResolution: + """身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。""" + + ok: bool + identity: ResolvedInventoryIdentity | None = None + reason: str = "" + warehouse_candidates: tuple[str, ...] = () + + +def _alias_token_match(candidate: str, alias: str) -> bool: + """库位别名按词元精确匹配,禁止短别名误命中长编码。""" + alias_norm = normalize_destination(alias) + if not alias_norm: + return False + if candidate == alias_norm: + return True + return alias_norm in candidate.split() + + +def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution: + """Crane 库位由订单线索与 match_aliases 唯一命中决定。""" + aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()] + if not aliases: + return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing") + + destination_candidates = list(context.get("destination_candidates") or []) + hint = normalize_destination(context.get("warehouse_hint")) + if hint: + destination_candidates.append(hint) + + matched: list[str] = [] + for candidate in destination_candidates: + candidate_norm = normalize_destination(candidate) + if not candidate_norm: + continue + for alias in aliases: + if _alias_token_match(candidate_norm, alias): + token = str(alias).strip().upper() + if token and token not in matched: + matched.append(token) + + if len(matched) == 1: + site_id = str(source.get("site_id") or "CRANE").strip().upper() + return InventoryIdentityResolution( + ok=True, + identity=ResolvedInventoryIdentity( + source_code=str(source.get("source_code") or "").strip().upper(), + source_type=str(source.get("source_type") or "").strip(), + site_id=site_id, + warehouse_id=matched[0], + ), + ) + if len(matched) > 1: + return InventoryIdentityResolution( + ok=False, + reason="crane_warehouse_ambiguous", + warehouse_candidates=tuple(matched), + ) + return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved") + + +def resolve_inventory_source_identity( + source: dict[str, Any], + context: dict[str, Any], +) -> InventoryIdentityResolution: + """ + 解析库存源在订单上下文下的正式 site_id / warehouse_id。 + 核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。 + """ + source_code = str(source.get("source_code") or "").strip().upper() + source_type = str(source.get("source_type") or "").strip() + if not source_code or not source_type: + return InventoryIdentityResolution(ok=False, reason="source_incomplete") + + if source_type == "crane_footprint": + return _resolve_crane_warehouse_id(source, context) + + site_id = str(source.get("site_id") or "").strip().upper() + warehouse_id = str(source.get("warehouse_id") or "").strip().upper() + if not site_id or not warehouse_id: + return InventoryIdentityResolution(ok=False, reason="identity_incomplete") + return InventoryIdentityResolution( + ok=True, + identity=ResolvedInventoryIdentity( + source_code=source_code, + source_type=source_type, + site_id=site_id, + warehouse_id=warehouse_id, + ), + ) + + +def identity_matches_config( + source: dict[str, Any], + *, + site_id: str | None, + warehouse_id: str | None, + context: dict[str, Any] | None = None, +) -> bool: + """校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。""" + cfg_site = str(source.get("site_id") or "").strip().upper() + cfg_wh = str(source.get("warehouse_id") or "").strip().upper() + task_site = str(site_id or "").strip().upper() + task_wh = str(warehouse_id or "").strip().upper() + if not task_site or not task_wh: + return False + if cfg_site and task_site != cfg_site: + return False + source_type = str(source.get("source_type") or "").strip() + if source_type == "crane_footprint": + if context is None: + return False + resolution = resolve_inventory_source_identity(source, context) + if not resolution.ok or not resolution.identity: + return False + return resolution.identity.warehouse_id == task_wh + return bool(cfg_wh) and task_wh == cfg_wh diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py index 9b5aebc5..b6bff0b6 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/inventory_source_rules.py @@ -1,38 +1,89 @@ """ services/shipping_notice/inventory_source_rules.py -用途:根据发货通知目的地/港口/仓库线索解析应使用的库存 RPA 源。 -依赖:inventory_sources、ShippingTask step_payload_json/单头/订单行。 -逻辑:从 JSON 配置的 match_aliases 命中库存源;Dify 只提供候选字段,本模块负责标准化与唯一性判断。 +用途:根据发货通知路由线索对库存源做确定性裁决。 +依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。 +逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。 """ from __future__ import annotations -import re -from dataclasses import dataclass +import hashlib +import json +from dataclasses import dataclass, field from typing import Any from app.models import ShippingTask -from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources +from app.services.shipping_notice.inventory_source_identity import ( + normalize_destination, + resolve_inventory_source_identity, +) +from app.services.shipping_notice.inventory_sources import ( + build_rpa_inventory_source, + get_inventory_source, + get_inventory_sources_config_version, + list_inventory_sources, +) @dataclass(frozen=True) -class InventorySourceResolution: - """库存源解析结果。""" +class InventorySourceAdjudication: + """库存源裁决结构化结果。""" status: str - source: dict[str, Any] | None - candidates: list[dict[str, Any]] - destination_candidates: list[str] + method: str | None = None + source_code: str | None = None + source_type: str | None = None + site_id: str | None = None + warehouse_id: str | None = None + config_version: str | None = None + routing_fingerprint: str | None = None + candidates: list[dict[str, Any]] = field(default_factory=list) + destination_candidates: list[str] = field(default_factory=list) + evidence: list[dict[str, Any]] = field(default_factory=list) + conflicts: list[str] = field(default_factory=list) reason: str = "" +# Backward-compatible alias +InventorySourceResolution = InventorySourceAdjudication + + +def compute_routing_fingerprint(context: dict[str, Any]) -> str: + """ + 根据标准化路由上下文与配置版本生成可比较指纹。 + 核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。 + """ + normalized = { + "destination_code": str(context.get("destination_code") or "").strip().upper(), + "destination_city": str(context.get("destination_city") or "").strip().upper(), + "destination_country": str(context.get("destination_country") or "").strip().upper(), + "warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(), + "customer_code": str(context.get("customer_code") or "").strip().upper(), + "customer_name": str(context.get("customer_name") or "").strip().upper(), + "order_type": str(context.get("order_type") or "").strip().upper(), + "config_version": get_inventory_sources_config_version(), + "destination_candidates": sorted( + str(item).strip().upper() + for item in (context.get("destination_candidates") or []) + if str(item).strip() + ), + } + digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8")) + return digest.hexdigest()[:32] + + def normalize_destination(value: Any) -> str: """将 Dify/单据中的目的地线索标准化成可匹配 token。""" - text = str(value or "").strip().upper() - if not text: - return "" - return re.sub(r"[^A-Z0-9]+", " ", text).strip() + from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize + + return _normalize(value) + + +def _matches_alias(candidate: str, alias: str) -> bool: + from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match + + return _match(candidate, alias) def _append_candidate(candidates: list[str], value: Any) -> None: @@ -45,14 +96,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None: if not isinstance(value, dict): _append_candidate(candidates, value) return - for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text"): + for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"): _append_candidate(candidates, value.get(key)) def extract_destination_candidates(task: ShippingTask) -> list[str]: """ 从任务解析结果提取目的地/港口/仓库候选。 - 【AI 触发时机】:需要根据发货通知判断库存 RPA 源时调用,Dify 输出与后端字段都作为候选证据。 + 【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。 """ candidates: list[str] = [] payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} @@ -60,6 +111,10 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]: _append_candidate(candidates, item) _extract_destination_object(candidates, payload.get("destination")) _append_candidate(candidates, task.ship_to) + _append_candidate(candidates, task.destination_code) + _append_candidate(candidates, task.destination_city) + _append_candidate(candidates, task.destination_country) + _append_candidate(candidates, task.warehouse_hint) for line in task.lines_json or []: if not isinstance(line, dict): continue @@ -69,104 +124,413 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]: return candidates -def _matches_alias(candidate: str, alias: str) -> bool: - normalized_alias = normalize_destination(alias) - if not normalized_alias: - return False - return ( - candidate == normalized_alias - or normalized_alias in candidate.split() - or normalized_alias in candidate - ) - - -def _candidate_summary(source: dict[str, Any]) -> dict[str, Any]: - """人工确认候选项展示字段。""" +def extract_routing_context(task: ShippingTask) -> dict[str, Any]: + """将任务解析结果标准化为库存路由上下文。""" + payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {} return { - "source_code": source.get("source_code"), - "display_name": source.get("display_name"), - "warehouse_id": source.get("warehouse_id"), - "site": source.get("site"), - "source_type": source.get("source_type"), + "destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"), + "destination_city": task.destination_city or destination.get("city"), + "destination_country": task.destination_country or destination.get("country"), + "warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"), + "customer_code": task.customer_code, + "customer_name": task.customer_name, + "order_type": payload.get("order_type"), + "destination_candidates": extract_destination_candidates(task), } -def resolve_inventory_source(task: ShippingTask) -> InventorySourceResolution: - """根据任务目的地候选与 JSON match_aliases 解析唯一库存源。""" - candidates = extract_destination_candidates(task) - matched_codes: list[str] = [] - for candidate in candidates: - for source in list_inventory_sources(): - aliases = source.get("match_aliases") or [] - if any(_matches_alias(candidate, alias) for alias in aliases): - code = str(source.get("source_code") or "").strip().upper() - if code and code not in matched_codes: - matched_codes.append(code) +def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]: + """人工确认候选项展示字段;前端必须提交 source_code。""" + return { + "source_code": source.get("source_code"), + "display_name": source.get("display_name"), + "site_id": source.get("site_id"), + "warehouse_id": source.get("warehouse_id"), + "source_type": source.get("source_type"), + "match_score": score, + "matched_by": matched_by, + } - if len(matched_codes) == 1: - source = build_rpa_inventory_source(matched_codes[0]) - if source: - return InventorySourceResolution( - status="resolved", - source=source, - candidates=[_candidate_summary(source)], - destination_candidates=candidates, + +def _normalize_token_list(values: Any) -> list[str]: + if not isinstance(values, list): + return [] + return [normalize_destination(item) for item in values if normalize_destination(item)] + + +def _all_enabled_source_candidates() -> list[dict[str, Any]]: + """返回全部启用库存源候选项,供未命中时人工选择。""" + return [ + _candidate_summary(source) + for source in list_inventory_sources() + if source.get("enabled", True) is not False + ] + + +def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool: + """判断库存源别名是否与订单目的地线索有交集。""" + aliases = list(source.get("match_aliases") or []) + match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} + aliases.extend(_normalize_token_list(match_cfg.get("aliases"))) + if not aliases: + return False + return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases) + + +def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool: + """显式 match 规则已声明但订单字段未命中时,排除该库存源。""" + match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} + for field_name, cfg_key in ( + ("destination_code", "destination_codes"), + ("customer_code", "customers"), + ("order_type", "order_types"), + ("warehouse_hint", "warehouse_hints"), + ): + field_value = normalize_destination(context.get(field_name)) + allowed = _normalize_token_list(match_cfg.get(cfg_key)) + if allowed and field_value: + if not ( + field_value in allowed + or any(field_value in item or item in field_value for item in allowed) + ): + return True + return False + + +def _detect_rule_conflicts( + matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]], + context: dict[str, Any], +) -> list[str]: + """多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。""" + conflicts: list[str] = [] + field_hits: dict[str, set[str]] = {} + for _, source, _ in matches: + match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} + for field_name, cfg_key in ( + ("destination_code", "destination_codes"), + ("customer_code", "customers"), + ("order_type", "order_types"), + ("warehouse_hint", "warehouse_hints"), + ): + field_value = normalize_destination(context.get(field_name)) + allowed = _normalize_token_list(match_cfg.get(cfg_key)) + if not allowed or not field_value: + continue + hits = { + item + for item in allowed + if field_value in item or item in field_value or field_value == item + } + if hits: + field_hits.setdefault(field_name, set()).update(hits) + for field_name, hits in field_hits.items(): + if len(hits) > 1: + conflicts.append(f"{field_name}_rule_conflict") + return conflicts + + +def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]: + """按配置 match 规则与 match_aliases 计算命中分数与证据。""" + score = 0 + evidence: list[dict[str, Any]] = [] + match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} + + for field_name, cfg_key in ( + ("destination_code", "destination_codes"), + ("customer_code", "customers"), + ("order_type", "order_types"), + ("warehouse_hint", "warehouse_hints"), + ): + field_value = normalize_destination(context.get(field_name)) + allowed = _normalize_token_list(match_cfg.get(cfg_key)) + if allowed and field_value: + if field_value in allowed or any(field_value in item or item in field_value for item in allowed): + score += 10 + evidence.append({"field": field_name, "value": field_value, "rule": cfg_key}) + + aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases")) + for candidate in destination_candidates: + for alias in aliases: + if _matches_alias(candidate, alias): + score += 5 + evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias}) + break + + priority = int(source.get("priority") or 0) + if score > 0 and priority: + score += min(priority // 10, 5) + return score, evidence + + +def _stable_from_source( + source: dict[str, Any], + *, + method: str, + evidence: list[dict[str, Any]], + context: dict[str, Any], +) -> InventorySourceAdjudication: + """仅在四元组身份可完整解析时返回 resolved。""" + resolution = resolve_inventory_source_identity(source, context) + config_version = get_inventory_sources_config_version() + fingerprint = compute_routing_fingerprint(context) + destination_candidates = context.get("destination_candidates") or [] + if not resolution.ok or not resolution.identity: + if resolution.reason == "crane_warehouse_ambiguous": + return InventorySourceAdjudication( + status="ambiguous", + method=method, + config_version=config_version, + routing_fingerprint=fingerprint, + candidates=[_candidate_summary(source, matched_by=method)], + destination_candidates=destination_candidates, + evidence=evidence, + reason=resolution.reason, ) - if len(matched_codes) > 1: - matched_sources = [ - _candidate_summary(source) - for code in matched_codes - for source in [build_rpa_inventory_source(code)] - if source - ] - return InventorySourceResolution( - status="ambiguous", - source=None, - candidates=matched_sources, - destination_candidates=candidates, - reason="matched_multiple_sources", + status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved" + return InventorySourceAdjudication( + status=status, + method=method, + config_version=config_version, + routing_fingerprint=fingerprint, + candidates=[_candidate_summary(source, matched_by=method)], + destination_candidates=destination_candidates, + evidence=evidence, + conflicts=[resolution.reason] if resolution.reason else [], + reason=resolution.reason or "identity_incomplete", ) - return InventorySourceResolution( - status="unresolved", - source=None, - candidates=[_candidate_summary(item) for item in list_inventory_sources()], - destination_candidates=candidates, - reason="no_route_rule_matched", + identity = resolution.identity + return InventorySourceAdjudication( + status="resolved", + method=method, + source_code=identity.source_code, + source_type=identity.source_type, + site_id=identity.site_id, + warehouse_id=identity.warehouse_id, + config_version=config_version, + routing_fingerprint=fingerprint, + candidates=[_candidate_summary(source, score=100, matched_by=method)], + destination_candidates=destination_candidates, + evidence=evidence, ) +def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication: + """ + 根据任务路由上下文与配置规则做确定性库存源裁决。 + 核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。 + """ + context = extract_routing_context(task) + destination_candidates = context.get("destination_candidates") or [] + config_version = get_inventory_sources_config_version() + + scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = [] + for source in list_inventory_sources(): + if _source_field_excluded(source, context): + continue + source_type = str(source.get("source_type") or "").strip() + if source_type == "dsv360" and ( + not str(source.get("site_id") or "").strip() + or not str(source.get("warehouse_id") or "").strip() + ): + continue + score, evidence = _source_match_score(source, context, destination_candidates) + if score > 0: + scored.append((score, source, evidence)) + + if not scored: + # Fallback: legacy match_aliases only + matched_codes: list[str] = [] + alias_evidence: dict[str, list[dict[str, Any]]] = {} + for candidate in destination_candidates: + for source in list_inventory_sources(): + aliases = source.get("match_aliases") or [] + if any(_matches_alias(candidate, alias) for alias in aliases): + code = str(source.get("source_code") or "").strip().upper() + if code and code not in matched_codes: + matched_codes.append(code) + alias_evidence.setdefault(code, []).append( + {"field": "destination_candidate", "value": candidate, "alias_only": True} + ) + if len(matched_codes) == 1: + source = get_inventory_source(matched_codes[0]) + if source: + return _stable_from_source( + source, + method="rule_exact", + evidence=alias_evidence.get(matched_codes[0], []), + context=context, + ) + if len(matched_codes) > 1: + candidates = [ + _candidate_summary(src, matched_by="rule_exact") + for code in matched_codes + for src in [get_inventory_source(code)] + if src + ] + return InventorySourceAdjudication( + status="ambiguous", + config_version=config_version, + routing_fingerprint=compute_routing_fingerprint(context), + candidates=candidates, + destination_candidates=destination_candidates, + evidence=[item for ev in alias_evidence.values() for item in ev], + reason="matched_multiple_sources", + ) + return InventorySourceAdjudication( + status="unresolved", + config_version=config_version, + routing_fingerprint=compute_routing_fingerprint(context), + candidates=_all_enabled_source_candidates(), + destination_candidates=destination_candidates, + reason="no_route_rule_matched", + ) + + scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or ""))) + top_score = scored[0][0] + top_matches = [item for item in scored if item[0] == top_score] + + if len(top_matches) == 1: + _, source, evidence = top_matches[0] + method = "rule_combined" if len(evidence) > 1 else "rule_exact" + return _stable_from_source(source, method=method, evidence=evidence, context=context) + + conflicts = _detect_rule_conflicts(top_matches, context) + if conflicts: + candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches] + return InventorySourceAdjudication( + status="conflicted", + config_version=config_version, + routing_fingerprint=compute_routing_fingerprint(context), + candidates=candidates, + destination_candidates=destination_candidates, + evidence=[ev for _, _, ev in top_matches for ev in ev], + conflicts=conflicts, + reason="matched_conflicting_rules", + ) + + candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches] + return InventorySourceAdjudication( + status="ambiguous", + config_version=config_version, + routing_fingerprint=compute_routing_fingerprint(context), + candidates=candidates, + destination_candidates=destination_candidates, + evidence=[ev for _, _, ev in top_matches for ev in ev], + reason="matched_multiple_sources", + ) + + +def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication: + """ + 用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。 + 【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。 + """ + context = extract_routing_context(task) + destination_candidates = context.get("destination_candidates") or [] + code = str(source_code or "").strip().upper() + source = get_inventory_source(code) + if not source or source.get("enabled", True) is False: + return InventorySourceAdjudication( + status="invalid", + config_version=get_inventory_sources_config_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=_all_enabled_source_candidates(), + destination_candidates=destination_candidates, + conflicts=["source_code_not_found"], + reason="source_code_not_found", + ) + if str(source.get("source_type") or "").strip() == "dsv360" and ( + not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip() + ): + return InventorySourceAdjudication( + status="invalid", + config_version=get_inventory_sources_config_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate_summary(source)], + destination_candidates=destination_candidates, + conflicts=["identity_incomplete_in_config"], + reason="identity_incomplete_in_config", + ) + + resolution = resolve_inventory_source_identity(source, context) + if not resolution.ok or not resolution.identity: + status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid" + return InventorySourceAdjudication( + status=status, + config_version=get_inventory_sources_config_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate_summary(source)], + destination_candidates=destination_candidates, + conflicts=[resolution.reason] if resolution.reason else [], + reason=resolution.reason or "identity_incomplete", + ) + + identity = resolution.identity + return InventorySourceAdjudication( + status="user_confirmed", + method="user_confirmed", + source_code=identity.source_code, + source_type=identity.source_type, + site_id=identity.site_id, + warehouse_id=identity.warehouse_id, + config_version=get_inventory_sources_config_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate_summary(source, matched_by="user_confirmed")], + destination_candidates=destination_candidates, + evidence=[{"field": "user_selection", "value": code}], + ) + + +# Backward-compatible wrappers +def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication: + """兼容旧调用点:委托 adjudicate_inventory_source。""" + return adjudicate_inventory_source(task) + + def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None: - """读取任务当前已确认的 rpa_inventory_source。""" - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - source = payload.get("rpa_inventory_source") - return source if isinstance(source, dict) and source.get("source_code") else None + """读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。""" + from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source + + return build_task_rpa_inventory_source(task) def save_task_rpa_inventory_source( task: ShippingTask, source: dict[str, Any], *, - resolution: InventorySourceResolution | None = None, + resolution: InventorySourceAdjudication | None = None, ) -> None: - """把已确认库存源写入 task.step_payload_json,供后续 RPA trigger 使用。""" - payload = dict(task.step_payload_json or {}) - payload["rpa_inventory_source"] = source + """把已确认库存源写入独立字段与 step_payload_json。""" + from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + if resolution: - payload["inventory_source_resolution"] = { - "status": resolution.status, - "destination_candidates": resolution.destination_candidates, - "reason": resolution.reason, - } - task.step_payload_json = payload + apply_inventory_source_adjudication(task, resolution) + return + code = str(source.get("source_code") or "").strip().upper() + cfg = get_inventory_source(code) + if not cfg: + return + context = extract_routing_context(task) + resolution = resolve_inventory_source_identity(cfg, context) + if not resolution.ok or not resolution.identity: + return + identity = resolution.identity + adjudication = InventorySourceAdjudication( + status="user_confirmed", + method="user_confirmed", + source_code=identity.source_code, + source_type=identity.source_type, + site_id=identity.site_id, + warehouse_id=identity.warehouse_id, + config_version=get_inventory_sources_config_version(), + routing_fingerprint=compute_routing_fingerprint(context), + ) + apply_inventory_source_adjudication(task, adjudication) -def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceResolution) -> None: - """库存源无法唯一命中时,把候选项写入 task.step_payload_json 供前端/Agent 展示。""" - payload = dict(task.step_payload_json or {}) - payload["inventory_source_resolution"] = { - "status": resolution.status, - "destination_candidates": resolution.destination_candidates, - "reason": resolution.reason, - "candidates": resolution.candidates, - } - task.step_payload_json = payload +def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None: + """库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。""" + from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + + apply_inventory_source_adjudication(task, resolution) diff --git a/backend/app/services/shipping_notice/inventory_sources.py b/backend/app/services/shipping_notice/inventory_sources.py index 00536f6e..15a5297f 100644 --- a/backend/app/services/shipping_notice/inventory_sources.py +++ b/backend/app/services/shipping_notice/inventory_sources.py @@ -22,6 +22,49 @@ _VALID_SOURCE_TYPES = { } _VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"}) _CONFIG_CACHE: dict[str, Any] | None = None +_CONFIG_PATH: str | None = None +_CONFIG_RAW_DIGEST: str | None = None + + +def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]: + """提取参与版本哈希的语义字段,忽略注释/空白等文件层噪声。""" + match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} + return { + "source_code": source.get("source_code"), + "source_type": source.get("source_type"), + "site_id": source.get("site_id"), + "warehouse_id": source.get("warehouse_id"), + "warehouse_resolution": source.get("warehouse_resolution"), + "enabled": source.get("enabled", True), + "priority": source.get("priority", 0), + "entry_url": source.get("entry_url"), + "display_name": source.get("display_name"), + "match_aliases": sorted(source.get("match_aliases") or []), + "allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []), + "match": { + key: sorted(value) if isinstance(value, list) else value + for key, value in sorted(match_cfg.items()) + }, + "navigation": source.get("navigation"), + "parameters": source.get("parameters"), + "export": source.get("export"), + } + + +def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str: + """基于规范化结构计算配置内容哈希。""" + import hashlib + + canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)] + payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False) + return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16] + + +def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str: + """配置版本 = 声明版本 + 规范化结构哈希。""" + digest = _normalized_config_digest(sources) + declared = str(payload.get("version") or "1").strip() + return f"{declared}-{digest}" class InventorySourceConfigError(ValueError): @@ -131,6 +174,11 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]: return query +def effective_warehouse_id(source: dict[str, Any]) -> str: + """返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。""" + return str(source.get("warehouse_id") or "").strip().upper() + + def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]: """校验并规范化单条库存源配置。""" source_code = str(raw.get("source_code") or "").strip().upper() @@ -146,8 +194,31 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, warehouse_id = str(raw.get("warehouse_id") or "").strip().upper() site_id = str(raw.get("site_id") or "").strip().upper() - if source_type == "dsv360" and not site_id: - raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360") + if source_type == "dsv360": + if not site_id: + raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360") + if not warehouse_id: + raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360") + elif source_type == "crane_footprint": + if not site_id: + raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint") + aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()] + if not aliases: + raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint") + allowed_warehouse_ids = [ + str(item).strip() + for item in (raw.get("allowed_warehouse_ids") or []) + if str(item).strip() + ] + if not allowed_warehouse_ids: + raise InventorySourceConfigError( + f"{source_code}: allowed_warehouse_ids is required for crane_footprint" + ) + warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower() + if warehouse_resolution != "alias_match": + raise InventorySourceConfigError( + f"{source_code}: warehouse_resolution must be alias_match for crane_footprint" + ) parameters: list[dict[str, Any]] = [] for item in raw.get("parameters") or []: if not isinstance(item, dict): @@ -167,6 +238,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, "site_id": site_id, "display_name": str(raw.get("display_name") or source_code).strip(), "enabled": bool(raw.get("enabled", True)), + "priority": int(raw.get("priority") or 0), "entry_url": str(raw.get("entry_url") or "").strip(), "warehouse_id": warehouse_id, "navigation": dict(raw.get("navigation") or {}), @@ -177,6 +249,18 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, if str(alias).strip() ], } + if source_type == "crane_footprint": + normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower() + normalized["allowed_warehouse_ids"] = allowed_warehouse_ids + match_cfg = raw.get("match") + if isinstance(match_cfg, dict) and match_cfg: + normalized["match"] = { + "destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()], + "customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()], + "order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()], + "warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()], + "aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()], + } if source_type == "crane_footprint" and raw.get("export"): normalized["export"] = dict(raw.get("export") or {}) normalized["query"] = _build_legacy_query(normalized) @@ -184,15 +268,24 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, def _load_config(*, force_reload: bool = False) -> dict[str, Any]: - """加载并缓存 YAML/JSON 配置;force_reload 用于测试。""" - global _CONFIG_CACHE - if _CONFIG_CACHE is not None and not force_reload: - return _CONFIG_CACHE + """加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。""" + import hashlib + global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST path = _config_path() if not path.is_file(): raise InventorySourceConfigError(f"inventory sources config not found: {path}") + path_str = str(path.resolve()) + raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16] + if ( + _CONFIG_CACHE is not None + and not force_reload + and _CONFIG_PATH == path_str + and _CONFIG_RAW_DIGEST == raw_digest + ): + return _CONFIG_CACHE + payload = _parse_config_payload(path) sources_raw = payload.get("sources") if not isinstance(sources_raw, list): @@ -207,13 +300,21 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]: sources[normalized["source_code"]] = normalized _CONFIG_CACHE = { - "version": int(payload.get("version") or 1), + "version": _config_content_version(payload, sources), "sources": sources, - "path": str(path), + "path": path_str, + "raw_digest": raw_digest, } + _CONFIG_PATH = path_str + _CONFIG_RAW_DIGEST = raw_digest return _CONFIG_CACHE +def get_inventory_sources_config_version() -> str: + """返回当前加载的库存源配置版本字符串。""" + return str(_load_config().get("version") or "1") + + def reload_inventory_sources_config() -> dict[str, Any]: """强制重新加载库存源配置(管理/测试用)。""" return _load_config(force_reload=True) @@ -230,6 +331,44 @@ def get_inventory_source(source_code: str | None) -> dict[str, Any] | None: return deepcopy(source) +def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool: + """判断库存源是否采用运行时动态库位(如 CRANE alias_match)。""" + if not source: + return False + if str(source.get("warehouse_id") or "").strip(): + return False + resolution = str(source.get("warehouse_resolution") or "").strip().lower() + return resolution in {"alias_match", "dynamic", "runtime"} + + +def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]: + """返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。""" + if not source: + return set() + return { + str(alias).strip().upper() + for alias in (source.get("match_aliases") or []) + if str(alias).strip() + } + + +def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]: + """ + 返回 Worker 回调允许落库的库位 ID 集合(大写)。 + 核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。 + """ + if not source: + return set() + allowed = source.get("allowed_warehouse_ids") + if allowed: + return {str(item).strip().upper() for item in allowed if str(item).strip()} + # fallback for static DSV 等源 + warehouse_id = str(source.get("warehouse_id") or "").strip().upper() + if warehouse_id: + return {warehouse_id} + return set() + + def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]: """返回库存源配置副本,供人工检查点展示候选项。""" sources = _load_config()["sources"].values() @@ -242,6 +381,8 @@ def build_rpa_inventory_source( source_code: str | None, *, query_override: dict[str, Any] | None = None, + site_id: str | None = None, + warehouse_id: str | None = None, ) -> dict[str, Any] | None: """ 构造 RPA trigger 使用的 rpa_inventory_source。 @@ -256,4 +397,59 @@ def build_rpa_inventory_source( if value is not None and str(value).strip(): query[key] = value source["query"] = query - return source + return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id) + + +def merge_runtime_inventory_identity( + source: dict[str, Any], + *, + site_id: str | None = None, + warehouse_id: str | None = None, +) -> dict[str, Any]: + """ + 将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。 + 核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。 + """ + merged = deepcopy(source) + site = str(site_id or merged.get("site_id") or "").strip().upper() + warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper() + if site: + merged["site_id"] = site + if warehouse: + merged["warehouse_id"] = warehouse + merged["_runtime_identity_applied"] = True + query = dict(merged.get("query") or {}) + query["warehouse_code"] = warehouse + merged["query"] = query + source_type = str(merged.get("source_type") or "").strip() + if source_type == "crane_footprint": + navigation = dict(merged.get("navigation") or {}) + navigation["project_code"] = warehouse + merged["navigation"] = navigation + query["project_code"] = warehouse + merged["query"] = query + return merged + + +def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None: + """ + 基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。 + 【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。 + """ + from app.models import ShippingTask + + if not isinstance(task, ShippingTask): + return None + payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + code = str(task.inventory_source_code or "").strip().upper() + site_id = str(task.inventory_site_id or "").strip().upper() or None + warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None + if not code: + legacy = payload.get("rpa_inventory_source") + if isinstance(legacy, dict) and legacy.get("source_code"): + return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id) + return None + base = get_inventory_source(code) + if not base: + return None + return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id) diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py index 2bdf912e..d875d93a 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/inventory_upload.py @@ -3,25 +3,199 @@ services/shipping_notice/inventory_upload.py 用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。 依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。 -逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息。 +逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息; + 正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。 """ from __future__ import annotations +import hashlib import re import shutil +from datetime import datetime from pathlib import Path from typing import Any from flask import current_app from werkzeug.datastructures import FileStorage +from app.models import ShippingInventoryFile, ShippingTask from app.services.shipping_notice.export import _storage_root +from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path from app.services.shipping_notice.inventory_snapshot import ( parse_inventory_excel_with_meta, read_inventory_schema_preview, ) +_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv") +_TASK_INVENTORY_MARKER = ".current_inventory" +_TASK_INVENTORY_VERSION_PREFIX = "inventory_" + + +def _inventory_file_sha256(path: Path) -> str: + """计算库存附件 SHA256,用于幂等安装判断。""" + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _task_inventory_attachment_marker_path(task_no: str) -> Path: + """任务当前正式库存附件指针文件路径。""" + return _task_inventory_upload_dir(task_no) / _TASK_INVENTORY_MARKER + + +def _atomic_write_task_inventory_marker(task_no: str, attachment_filename: str) -> None: + """通过临时文件 + os.replace 原子切换 .current_inventory 指针。""" + import os + + marker = _task_inventory_attachment_marker_path(task_no) + tmp = marker.with_name(f"{marker.name}.tmp") + marker.parent.mkdir(parents=True, exist_ok=True) + tmp.write_text(attachment_filename, encoding="utf-8") + os.replace(tmp, marker) + + +def _read_task_inventory_attachment_marker(task_no: str) -> Path | None: + """读取指针文件并校验对应附件仍存在。""" + marker = _task_inventory_attachment_marker_path(task_no) + if not marker.is_file(): + return None + name = marker.read_text(encoding="utf-8").strip() + if not name: + return None + path = _task_inventory_upload_dir(task_no) / name + if path.is_file() and _is_task_inventory_attachment_name(path.name): + return path + return None + + +def _is_task_inventory_attachment_name(name: str) -> bool: + """判断文件名是否为合法任务库存附件。""" + lowered = str(name or "").lower() + if not lowered.startswith("inventory"): + return False + return any(lowered.endswith(suffix) for suffix in _TASK_INVENTORY_SUFFIXES) + + +def _versioned_task_inventory_path(task_no: str, suffix: str) -> Path: + """生成不可变版本化任务库存附件路径。""" + token = datetime.utcnow().strftime("%Y%m%d%H%M%S%f") + normalized = suffix if suffix in _TASK_INVENTORY_SUFFIXES else ".xlsx" + return _task_inventory_upload_dir(task_no) / f"{_TASK_INVENTORY_VERSION_PREFIX}{token}{normalized}" + + +def _list_task_inventory_attachment_candidates(task_no: str) -> list[Path]: + """列出任务目录下全部库存附件候选文件。""" + base = _task_inventory_upload_dir(task_no) + if not base.is_dir(): + return [] + return [ + path + for path in base.iterdir() + if path.is_file() and _is_task_inventory_attachment_name(path.name) + ] + + +def _cleanup_superseded_task_inventory_files(task_no: str, *, keep_name: str) -> list[str]: + """ + 指针切换后清理旧版附件(best effort)。 + Returns: + 未能删除的文件名列表。 + """ + warnings: list[str] = [] + for path in _list_task_inventory_attachment_candidates(task_no): + if path.name == keep_name: + continue + try: + path.unlink() + except OSError as exc: + warnings.append(f"{path.name}:{str(exc)[:80]}") + return warnings + + +def install_task_inventory_attachment_from_file( + task_no: str, + source_path: str | Path, + *, + source_file_name: str | None = None, +) -> Path: + """ + 将源库存文件安装为任务正式附件(版本化文件名 + 原子 marker 切换)。 + 【AI 触发时机】:RPA 回调晋升失败补偿、人工修复任务附件时调用;不依赖重新消费 callback。 + + 核心逻辑:复制到 inventory_{timestamp}{suffix} → 原子切换 .current_inventory → 清理旧附件。 + 若当前正式附件与源文件内容一致则幂等返回现有路径。 + + Args: + task_no: 发货任务号。 + source_path: 源库存文件(通常为 inv_file.storage_path 或 staging)。 + source_file_name: 可选展示名,仅用于日志语义。 + + Returns: + 安装后的正式附件路径。 + + Raises: + FileNotFoundError: 源文件不存在。 + OSError: 复制或 marker 切换失败。 + """ + source = Path(source_path) + if not source.is_file(): + raise FileNotFoundError(f"未找到库存源文件: {source}") + + current = resolve_task_inventory_upload_path(task_no) + if current is not None and _inventory_file_sha256(current) == _inventory_file_sha256(source): + return current + + suffix = inventory_storage_suffix_for_path(source) + versioned = _versioned_task_inventory_path(task_no, suffix) + versioned.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, versioned) + try: + _atomic_write_task_inventory_marker(task_no, versioned.name) + _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name) + except Exception: + if versioned.is_file(): + try: + versioned.unlink() + except OSError: + pass + raise + if source_file_name: + _ = source_file_name + return versioned + + +def rebuild_task_inventory_attachment_from_snapshot( + task: ShippingTask | str, + inv_file: ShippingInventoryFile, +) -> Path: + """ + 从已提交库存快照 storage_path 幂等重建任务正式附件。 + 【AI 触发时机】:RPA 回调 DB 已提交但任务附件晋升失败,或运维人工补偿时调用。 + + Args: + task: 任务对象或 task_no。 + inv_file: 已链接的库存快照。 + + Returns: + 重建后的任务正式附件路径。 + """ + task_no = task.task_no if isinstance(task, ShippingTask) else str(task or "").strip() + if not task_no: + raise ValueError("task_no is required") + storage_path = Path(str(inv_file.storage_path or "")) + if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): + raise FileNotFoundError( + f"库存快照托管文件不存在: {inv_file.inventory_file_no}", + ) + return install_task_inventory_attachment_from_file( + task_no, + storage_path, + source_file_name=str(inv_file.source_file_name or storage_path.name), + ) + def inventory_text_max_chars() -> int: """库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。""" @@ -31,18 +205,72 @@ def inventory_text_max_chars() -> int: return 80000 -def task_inventory_upload_path(task_no: str) -> Path: - """任务级库存 Excel 标准落盘路径(inventory_uploads/{task_no}/inventory.xlsx)。""" - safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown" - return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx" +def _task_inventory_upload_dir(task_no: str) -> Path: + """任务级库存附件目录(inventory_uploads/{task_no})。""" + safe = _sanitize_task_no(task_no) + return _storage_root() / "inventory_uploads" / safe + + +def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path: + """ + 任务级库存附件标准落盘路径(默认 inventory.xlsx)。 + suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。 + """ + normalized = (suffix or ".xlsx").lower() + if normalized not in _TASK_INVENTORY_SUFFIXES: + normalized = ".xlsx" + return _task_inventory_upload_dir(task_no) / f"inventory{normalized}" + + +def _recover_and_repair_task_inventory_marker(task_no: str) -> Path | None: + """ + marker 缺失或损坏时扫描附件目录并修复 .current_inventory。 + 核心逻辑:仅在此路径下根据 mtime 选择候选;修复后返回已提交附件。 + """ + candidates = _list_task_inventory_attachment_candidates(task_no) + if not candidates: + return None + versioned = [ + path + for path in candidates + if path.name.startswith(_TASK_INVENTORY_VERSION_PREFIX) + ] + if versioned: + chosen = max(versioned, key=lambda item: item.stat().st_mtime) + elif len(candidates) == 1: + chosen = candidates[0] + else: + chosen = max(candidates, key=lambda item: item.stat().st_mtime) + _atomic_write_task_inventory_marker(task_no, chosen.name) + return chosen + + +def resolve_task_inventory_upload_path(task_no: str) -> Path | None: + """ + 返回任务当前已提交的正式库存附件路径。 + 核心逻辑:marker 有效且目标文件存在时必须无条件相信 marker; + 仅 marker 缺失或损坏时才执行恢复扫描并同步修复 marker。 + """ + marked = _read_task_inventory_attachment_marker(task_no) + if marked is not None: + return marked + return _recover_and_repair_task_inventory_marker(task_no) def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path: """保存 werkzeug FileStorage 库存上传并返回落盘路径。""" - path = task_inventory_upload_path(task_no) - path.parent.mkdir(parents=True, exist_ok=True) - upload.save(str(path)) - return path + suffix = ".xlsx" + filename = str(getattr(upload, "filename", "") or "").lower() + if filename.endswith(".csv"): + suffix = ".csv" + staging_dir = _task_inventory_upload_dir(task_no) / ".staging" + staging_dir.mkdir(parents=True, exist_ok=True) + staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}" + upload.save(str(staging)) + try: + return install_task_inventory_attachment_from_file(task_no, staging) + finally: + delete_staged_task_inventory_file(staging) def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path: @@ -66,16 +294,111 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat source = Path(source_path) if not source.is_file(): raise FileNotFoundError(f"未找到库存源文件: {source}") - path = task_inventory_upload_path(task_no) - path.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(source, path) - return path + return install_task_inventory_attachment_from_file( + task_no, + source, + source_file_name=source.name, + ) + + +def _sanitize_task_no(task_no: str) -> str: + """将任务号规范为库存上传目录名。""" + return re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown" + + +def stage_task_inventory_callback_file( + task_no: str, + source_path: str | Path, + *, + run_no: str | None = None, +) -> Path: + """ + 将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。 + 核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。 + + Args: + task_no: 发货任务号。 + source_path: Worker 回调提供的本地库存文件。 + run_no: 可选轮次号,用于生成稳定且唯一的 staging 文件名。 + + Returns: + Path: staging 文件路径。 + + Raises: + FileNotFoundError: 源文件不存在。 + """ + source = Path(source_path) + if not source.is_file(): + raise FileNotFoundError(f"未找到库存源文件: {source}") + token = re.sub( + r"[^\w\-]+", + "_", + str(run_no or "").strip() or datetime.utcnow().strftime("%Y%m%d%H%M%S%f"), + ) + suffix = source.suffix.lower() if source.suffix else ".xlsx" + staging_dir = _storage_root() / "inventory_uploads" / _sanitize_task_no(task_no) / ".staging" + staging_dir.mkdir(parents=True, exist_ok=True) + staging_path = staging_dir / f"rpa_callback_{token}{suffix}" + shutil.copy2(source, staging_path) + return staging_path + + +def promote_staged_task_inventory_file(task_no: str, staging_path: str | Path) -> Path: + """ + 校验与数据库提交成功后,将 staging 安装为任务正式库存附件。 + 核心逻辑:版本化落盘 + 原子 marker 切换 + 异步清理旧附件;旧附件删除失败返回 warning 列表。 + """ + import os + + staging = Path(staging_path) + if not staging.is_file(): + raise FileNotFoundError(f"未找到 staging 库存文件: {staging}") + suffix = staging.suffix.lower() if staging.suffix else ".xlsx" + if suffix not in _TASK_INVENTORY_SUFFIXES: + suffix = ".xlsx" + versioned = _versioned_task_inventory_path(task_no, suffix) + versioned.parent.mkdir(parents=True, exist_ok=True) + os.replace(staging, versioned) + try: + _atomic_write_task_inventory_marker(task_no, versioned.name) + cleanup_warnings = _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name) + if cleanup_warnings: + raise OSError(f"legacy_attachment_cleanup_failed:{';'.join(cleanup_warnings)[:200]}") + except Exception: + if versioned.is_file(): + try: + versioned.unlink() + except OSError: + pass + raise + try: + staging.parent.rmdir() + except OSError: + pass + return versioned + + +def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None: + """删除本轮 staging 库存文件(失败回滚用,不触碰任务正式附件)。""" + if not staging_path: + return + path = Path(staging_path) + if not path.is_file(): + return + try: + path.unlink() + except OSError: + return + try: + path.parent.rmdir() + except OSError: + pass def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]: """读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。""" - path = task_inventory_upload_path(task_no) - if not path.is_file(): + path = resolve_task_inventory_upload_path(task_no) + if path is None: raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") preview = read_inventory_schema_preview(path) preview["upload_filename"] = path.name @@ -97,8 +420,8 @@ def parse_uploaded_task_inventory( Returns: tuple: (inventory_lines, column_meta, 文件路径)。 """ - path = task_inventory_upload_path(task_no) - if not path.is_file(): + path = resolve_task_inventory_upload_path(task_no) + if path is None: raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") lines, column_meta = parse_inventory_excel_with_meta( path, @@ -112,5 +435,5 @@ def parse_uploaded_task_inventory( def has_uploaded_task_inventory(task_no: str) -> bool: - """任务是否已有落盘的库存 Excel 文件。""" - return task_inventory_upload_path(task_no).is_file() + """任务是否已有落盘的库存附件(.xlsx 或 .csv)。""" + return resolve_task_inventory_upload_path(task_no) is not None diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 0ce6e12e..207ea47e 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -12,9 +12,11 @@ import json from typing import Any from app import db +from app.core.errors import AppError from app.models import ShippingTask from app.services.shipping_notice.constants import ( AUTO_MAP, + CP_INVENTORY_SOURCE_REVIEW, CP_MAP_INFER, CP_UPLOAD_REQ, SUGGEST_OK, @@ -57,6 +59,8 @@ from app.services.shipping_notice.query_service import ( serialize_task_for_tool, ) from app.services.shipping_notice.i18n import resolve_lang, t +from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response @@ -117,6 +121,29 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]: return result +def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None: + """ + 库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。 + 核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。 + """ + if is_inventory_source_stable(task): + return None + try: + assert_inventory_source_gate(task, operation=operation) + except AppError: + ui = resolve_task_ui_state(task) + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + data=serialize_task_for_tool(task), + human_options=ui.human_options, + checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + ) + return None + + def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: """Parse inventory from uploaded file, chat text, or structured JSON.""" lang = resolve_lang(payload) @@ -124,6 +151,10 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) + gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang) + if gate_resp is not None: + return gate_resp + # [STEP 1] 先归一化库存输入来源与映射提示。 # 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。 use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in { @@ -237,6 +268,10 @@ def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) + gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang) + if gate_resp is not None: + return gate_resp + if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no): return tool_response( status="needs_human", @@ -279,6 +314,10 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) + gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang) + if gate_resp is not None: + return gate_resp + # [STEP 1] 先校验上传文件与 schema preview 是否存在。 # 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。 if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no): @@ -415,6 +454,9 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh")) lang = resolve_lang({"lang": None}) + gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang) + if gate_resp is not None: + return gate_resp if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES: return tool_response( status="failed", @@ -432,7 +474,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: ) filename = str(upload.filename or "").strip() - if not filename.lower().endswith((".xlsx", ".xls", ".csv")): + if not filename.lower().endswith((".xlsx", ".csv")): return tool_response( status="failed", task_id=task.task_no, @@ -452,7 +494,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: db.session.flush() inv_file = save_batch_inventory_upload(task, upload) preview = read_linked_inventory_schema_preview(task) + except AppError as exc: + db.session.rollback() + return tool_response( + status="failed", + task=task, + task_id=task.task_no, + message=str(exc.message or "库存上传被拒绝"), + data=serialize_task_for_tool(task), + stop_agent_turn=True, + ) except OSError as exc: + db.session.rollback() return tool_response( status="failed", task_id=task.task_no, @@ -537,6 +590,20 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) + if not is_inventory_source_stable(task): + try: + assert_inventory_source_gate(task, operation="ensure_inventory") + except AppError: + pass + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + data=serialize_task_for_tool(task), + checkpoint="inventory_source_review", + stop_agent_turn=True, + ) + # [STEP 1] 优先接受当前请求直接携带的库存明细。 # 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。 mode = str(payload.get("mode") or "auto").strip().lower() diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index 637534e2..625fdeb3 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -183,6 +183,24 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["task_id", MAP_JSON], ), + "/tools/confirm_inventory_source": _post_op( + "confirm_inventory_source", + "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)", + { + "task_id": task_id, + "source_code": _str_prop( + "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;" + "站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传" + ), + }, + required=["task_id", "source_code"], + description=( + "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id," + "且 routing_fingerprint 与当前配置版本一致。" + "Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。" + "若返回 needs_human,说明身份未完整解析或需先完成解析确认。" + ), + ), "/tools/submit_decision": _post_op( "submit_decision", "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。", @@ -218,11 +236,19 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: ), "/tools/get_task_status": _post_op( "get_task_status", - "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个", + "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构", { "task_id": task_id, "conversation_id": _str_prop("Dify 会话 ID"), }, + description=( + "返回 inventory_source_code、inventory_source_type、inventory_site_id、" + "inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|" + "user_confirmed|invalid|conflicted)、inventory_source_method、" + "inventory_source_config_version、inventory_routing_fingerprint、" + "inventory_source_confirmed_by、inventory_source_confirmed_at," + "以及 step_payload.inventory_source_resolution.candidates。" + ), ), "/tools/get_batch_status": _post_op( "get_batch_status", diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 2a2e5cf6..e62ae95a 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -14,7 +14,17 @@ from flask import current_app from app.services.shipping_notice import fulfillment_workflow from app import db -from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW +from app.services.shipping_notice.constants import ( + CP_INVENTORY_SOURCE_REVIEW, + CP_UPLOAD_REQ, + PH_INVENTORY_SOURCE_UNRESOLVED, + PH_LOW_CONF, + RS_PARSE_REVIEW, +) +from app.services.shipping_notice.inventory_source_gate import ( + is_inventory_source_stable, + ensure_inventory_source_review_state, +) from app.services.shipping_notice.inventory_mapping_workflow import ( awaiting_inventory_mapping_confirm, inventory_mapping_checkpoint_response, @@ -84,6 +94,27 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: stop_agent_turn=True, ) + if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): + adjudication = ensure_inventory_source_review_state(task) + db.session.commit() + if not is_inventory_source_stable(task): + ui = resolve_task_ui_state(task) + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", + data={ + **serialize_task_for_tool(task), + "inventory_source_candidates": adjudication.candidates, + "inventory_source_status": adjudication.status, + "inventory_source_reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + }, + human_options=ui.human_options, + checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + ) + # [STEP 2] 保证库存已经就绪。 # 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。 if not task.inventory_lines_json: diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index cd43178f..0bd82718 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -331,6 +331,20 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, "rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None), "rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None, "inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None, + "destination_code": task.destination_code, + "destination_city": task.destination_city, + "destination_country": task.destination_country, + "warehouse_hint": task.warehouse_hint, + "inventory_source_code": task.inventory_source_code, + "inventory_source_type": task.inventory_source_type, + "inventory_site_id": task.inventory_site_id, + "inventory_warehouse_id": task.inventory_warehouse_id, + "inventory_source_status": task.inventory_source_status, + "inventory_source_method": task.inventory_source_method, + "inventory_source_config_version": task.inventory_source_config_version, + "inventory_routing_fingerprint": task.inventory_routing_fingerprint, + "inventory_source_confirmed_at": task.inventory_source_confirmed_at.isoformat() if task.inventory_source_confirmed_at else None, + "inventory_source_confirmed_by": task.inventory_source_confirmed_by, "inventory_snapshot": _serialize_inventory_snapshot(task), "shortage": task.shortage_json, "line_results": task.line_results_json or [], diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index b3aba22c..81e6c1f0 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -110,14 +110,27 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: def recover_stale_shipping_notice_jobs() -> tuple[int, str]: - """兼容旧调用:回收通用 jobs 表里超时的发货任务。""" + """兼容旧调用:回收通用 jobs 表里超时的发货任务,并顺带消费 RPA callback cleanup 队列。""" from app.jobs.queue import recover_stale_jobs + from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + recover_pending_rpa_callback_cleanup_jobs, + ) timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300)) count = recover_stale_jobs(domain=SHIPPING_NOTICE_JOB_DOMAIN, timeout_seconds=timeout_sec) + cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs() + if cleanup_warnings: + logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5])) if count: logger.warning('recovered %s stale shipping_notice job(s)', count) - return count, f'recovered_{count}' if count else 'no_stale_jobs' + if cleanup_count: + logger.info('processed %s rpa callback cleanup job(s)', cleanup_count) + parts = [] + if count: + parts.append(f'recovered_{count}') + if cleanup_count: + parts.append(f'callback_cleanup_{cleanup_count}') + return count, '_'.join(parts) if parts else 'no_stale_jobs' def claim_next_shipping_notice_job() -> Job | None: diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 66300ea1..187e8d4a 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -91,6 +91,7 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None body = { "action": "inventory_export", "task_no": task_no, + "run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}", "requested_at": datetime.utcnow().isoformat(), **(payload or {}), } @@ -177,7 +178,7 @@ def write_inventory_export_trigger_for_task( """ body = dict(payload or {}) if inventory_rpa_batch_enabled(): - run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}" + run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}" return write_inventory_export_batch_trigger( run_no, [rpa_source], diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 84a497c3..2d98ffc2 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -512,7 +512,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = { pending_human_reason=PH_INV_UNAVAIL, ), TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec( - process_status="waiting_inventory", + process_status="pending_review", review_status=None, pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, ), diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 0cfcbb1a..17d2cb03 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -17,12 +17,18 @@ from flask import current_app from app import db from app.models import ShippingBatch, ShippingTask from app.services.shipping_notice.constants import ( + CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_OK, CP_RSV_REQ, CP_TASK_EXISTS, + PH_INVENTORY_SOURCE_UNRESOLVED, RS_PARSE_REVIEW, ) +from app.services.shipping_notice.inventory_source_gate import ( + adjudicate_and_apply_inventory_source, + is_inventory_source_stable, +) from app.services.shipping_notice.i18n import resolve_lang, t from app.services.shipping_notice.decision_workflow import submit_decision from app.services.shipping_notice.extract import extract_notice_fields @@ -66,11 +72,23 @@ def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lin if isinstance(destination, dict): payload["destination"] = destination candidates.append(destination) + task.destination_code = str(destination.get("port_code") or destination.get("destination_code") or "").strip().upper() or None + task.destination_city = str(destination.get("city") or "").strip() or None + task.destination_country = str(destination.get("country") or "").strip().upper() or None + task.warehouse_hint = str(destination.get("warehouse_hint") or "").strip() or None elif destination: candidates.append(destination) for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to_location"): if parsed.get(key): candidates.append(parsed.get(key)) + if parsed.get("destination_port") and not task.destination_code: + task.destination_code = str(parsed.get("destination_port") or "").strip().upper() or None + if parsed.get("destination_city") and not task.destination_city: + task.destination_city = str(parsed.get("destination_city") or "").strip() or None + if parsed.get("destination_country") and not task.destination_country: + task.destination_country = str(parsed.get("destination_country") or "").strip().upper() or None + if parsed.get("warehouse_hint") and not task.warehouse_hint: + task.warehouse_hint = str(parsed.get("warehouse_hint") or "").strip() or None if task.ship_to: candidates.append(task.ship_to) for line in lines: @@ -565,23 +583,78 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], ) - # [STEP 4] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。 - if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7): - if not _has_parse_review_content(task, lines): - apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) - log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings}) - db.session.commit() - message = ( - "未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本," - "或复制粘贴通知正文后重新解析。" - ) - return tool_response( - status="needs_human", - task=task, - message=message, - data={**serialize_task_for_tool(task), "warnings": warnings}, - checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, - ) + # [STEP 4] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。 + if not _has_parse_review_content(task, lines): + apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) + log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings}) + db.session.commit() + message = ( + "未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本," + "或复制粘贴通知正文后重新解析。" + ) + return tool_response( + status="needs_human", + task=task, + message=message, + data={**serialize_task_for_tool(task), "warnings": warnings}, + checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, + ) + + # [STEP 5] 库存源硬门禁:订单解析阶段必须先完成库存源裁决(先于低置信度人工确认)。 + low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) + adjudication = adjudicate_and_apply_inventory_source(task) + if not is_inventory_source_stable(task): + from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review + + transition_task_to_inventory_source_review( + task, + adjudication, + error_message="无法根据发货通知唯一确定库存查询来源", + mark_pending_parse_review=low_confidence, + ) + set_task_step_progress( + task, + step_key="step2_parse_confirm", + step_title="确认解析", + status="needs_human", + message="库存源待确认", + progress_percent=100, + detail="请确认本票应使用哪个库存源后继续。", + extra={"warnings": warnings, "inventory_source_status": adjudication.status}, + ) + log_task_event( + task, + "inventory_source_review_required", + { + "status": adjudication.status, + "reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + "candidate_source_codes": [item.get("source_code") for item in adjudication.candidates], + }, + ) + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message=( + "订单字段已解析,但库存源尚未唯一确定。" + "请选择正式库存源后继续;站点与库位将由系统根据配置自动填充。" + ), + data={ + **serialize_task_for_tool(task), + "warnings": warnings, + "inventory_source_candidates": adjudication.candidates, + "inventory_source_status": adjudication.status, + "inventory_source_reason": adjudication.reason, + "destination_candidates": adjudication.destination_candidates, + }, + checkpoint=CP_INVENTORY_SOURCE_REVIEW, + stop_agent_turn=True, + forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], + ) + + # [STEP 6] 低置信度停待人审;库存源已稳定后才进入解析内容复核。 + if low_confidence: apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) _upsert_parse_review_chat_message(task) diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index abe23871..5e02a148 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -32,6 +32,7 @@ apply_inventory_mapping = inventory_workflow.apply_inventory_mapping upload_inventory_file = inventory_workflow.upload_inventory_file rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch +repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source # 履约阶段 diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index bbc27523..57cec357 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -29,6 +29,7 @@ from app.services.shipping_notice.constants import ( CP_UPLOAD_REQ, CP_WAITING_UPLOAD, PH_INV_UNAVAIL, + PH_INVENTORY_SOURCE_UNRESOLVED, PH_MAP_INFER, PH_RPA_EXHAUSTED, PH_RPA_PENDING, @@ -82,6 +83,7 @@ _TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"} _BLOCKED_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, + CP_INVENTORY_SOURCE_REVIEW, CP_ALIGN_REVIEW, RS_SHORTAGE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, @@ -129,7 +131,7 @@ def _derive_current_step_index(task: ShippingTask) -> int: if process_status in {"parsed", "pending_review"} or review_status in { RS_PARSE_REVIEW, PH_RSV_REQ, - } or pending_reason in {"low_confidence", PH_RSV_REQ}: + } or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}: return 1 return 0 @@ -159,7 +161,11 @@ def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) -> index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED} ) - if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked): + parse_blocked = index == 1 and ( + checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED} + or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED} + ) + if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked): status = "blocked" steps.append({**step, "status": status}) return steps @@ -181,7 +187,7 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。", - CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。", + CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。", CP_MAP_INFER: "库存列映射需要确认或重新选择。", CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。", RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index b2fd1b75..13d847a7 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -2,7 +2,7 @@ # 货代库存 RPA 源配置(新增 Warehouse 只改本文件,改后需重启后端)。 # 环境变量 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG 可覆盖路径。 -version: 1 +version: 2 sources: - source_code: DSV360_AWSBI_BYAWSATL01 display_name: DSV 360 / Bison / AWSBI / BYAWSATL01 @@ -537,6 +537,7 @@ sources: enabled: true source_type: dsv360 site_id: AWSCV + warehouse_id: AWSCV display_name: DSV 360 / Cincinnati / AWSCV entry_url: https://s360.dbschenker.com/ navigation: @@ -552,6 +553,7 @@ sources: enabled: true source_type: dsv360 site_id: AWSDU + warehouse_id: AWSDU display_name: DSV 360 / Dublin / AWSDU - Prod (JDA) entry_url: https://s360.dbschenker.com/ navigation: @@ -567,6 +569,7 @@ sources: enabled: true source_type: dsv360 site_id: AWSAMS + warehouse_id: RTM display_name: DSV 360 / Moerdijk / AWSAMS entry_url: https://s360.dbschenker.com/ navigation: @@ -594,6 +597,7 @@ sources: enabled: true source_type: dsv360 site_id: AWSSL + warehouse_id: AWSSL display_name: DSV 360 / Salt Lake City / AWSSL entry_url: https://s360.dbschenker.com/ navigation: @@ -609,6 +613,7 @@ sources: enabled: true source_type: dsv360 site_id: AWSSG + warehouse_id: AWSSG display_name: DSV 360 / Singapore / AWSSG - Prod (JDA) entry_url: https://s360.dbschenker.com/ navigation: @@ -623,6 +628,8 @@ sources: - source_code: CRANE enabled: true source_type: crane_footprint + site_id: CRANE + warehouse_resolution: alias_match display_name: Crane FootPrint entry_url: https://wms-portal.craneww.com/#/on-hand-details-query navigation: @@ -633,4 +640,8 @@ sources: - TZR - TZR2 - TZR3 + allowed_warehouse_ids: + - TZR + - TZR2 + - TZR3 diff --git a/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py new file mode 100644 index 00000000..2c021722 --- /dev/null +++ b/backend/migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py @@ -0,0 +1,257 @@ +"""Add shipping inventory source gate independent fields. + +Purpose: + Move inventory source identity from step_payload_json to dedicated columns on + shipping_tasks, shipping_inventory_files, and shipping_task_inventory_links. +Dependencies: + Alembic revision e2f3a4b5c6d7. +Flow: + Order-parse gate writes task inventory fields; RPA/inventory/match stages + read the same columns for hard gate checks. + +Revision ID: b4c5d6e7f8a9 +Revises: e2f3a4b5c6d7 +Create Date: 2026-07-13 10:00:00.000000 +""" + +from __future__ import annotations + +import json + +import sqlalchemy as sa +from alembic import op + + +revision = "b4c5d6e7f8a9" +down_revision = "e2f3a4b5c6d7" +branch_labels = None +depends_on = None + + +def upgrade(): + """Add inventory source gate columns and backfill legacy JSON where possible.""" + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("destination_code", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("destination_city", sa.String(length=128), nullable=True)) + batch_op.add_column(sa.Column("destination_country", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("warehouse_hint", sa.String(length=128), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_code", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_type", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("inventory_site_id", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("inventory_warehouse_id", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_status", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_method", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_confirmed_by", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_confirmed_at", sa.DateTime(), nullable=True)) + batch_op.add_column(sa.Column("inventory_source_config_version", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("inventory_routing_fingerprint", sa.String(length=64), nullable=True)) + batch_op.create_index("ix_shipping_tasks_inventory_source_code", ["inventory_source_code"], unique=False) + batch_op.create_index("ix_shipping_tasks_inventory_site_id", ["inventory_site_id"], unique=False) + batch_op.create_index("ix_shipping_tasks_inventory_source_status", ["inventory_source_status"], unique=False) + batch_op.create_index( + "ix_shipping_tasks_inventory_routing_fingerprint", + ["inventory_routing_fingerprint"], + unique=False, + ) + batch_op.create_foreign_key( + "fk_shipping_tasks_inventory_source_confirmed_by_users", + "users", + ["inventory_source_confirmed_by"], + ["id"], + ) + + with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op: + batch_op.add_column(sa.Column("site_id", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("source_config_version", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("identity_status", sa.String(length=32), nullable=True)) + batch_op.create_index("ix_shipping_inventory_files_site_id", ["site_id"], unique=False) + batch_op.create_index("ix_shipping_inventory_files_identity_status", ["identity_status"], unique=False) + batch_op.create_index( + "ix_shipping_inventory_files_source_site_wh", + ["source_code", "site_id", "warehouse_id"], + unique=False, + ) + + with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op: + batch_op.add_column(sa.Column("matched_source_code", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("matched_site_id", sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column("identity_check_status", sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column("identity_checked_at", sa.DateTime(), nullable=True)) + batch_op.create_index( + "ix_shipping_task_inventory_links_task_source", + ["task_id", "matched_source_code", "matched_site_id"], + unique=False, + ) + + _backfill_legacy_inventory_source() + + +def _backfill_legacy_inventory_source() -> None: + """Migrate rpa_inventory_source from step_payload_json; legacy rows require re-verification.""" + bind = op.get_bind() + legacy_config_version = "legacy-unverified" + + rows = bind.execute( + sa.text( + "SELECT id, step_payload_json, pending_human_reason FROM shipping_tasks " + "WHERE step_payload_json IS NOT NULL" + ) + ).fetchall() + for row in rows: + payload = row.step_payload_json + if not isinstance(payload, dict): + continue + source = payload.get("rpa_inventory_source") + if not isinstance(source, dict): + continue + source_code = str(source.get("source_code") or "").strip().upper() + if not source_code: + continue + site_id = str(source.get("site_id") or "").strip().upper() or None + warehouse_id = str(source.get("warehouse_id") or "").strip().upper() or None + source_type = str(source.get("source_type") or "").strip().lower() or None + resolution = payload.get("inventory_source_resolution") + status = "resolved" + method = "legacy_migrated" + routing_fingerprint = None + if isinstance(resolution, dict): + res_status = str(resolution.get("status") or "").strip() + routing_fingerprint = str(resolution.get("routing_fingerprint") or "").strip() or None + if res_status == "resolved": + status = "resolved" + method = "rule_exact" + elif res_status == "ambiguous": + status = "ambiguous" + elif res_status == "user_confirmed": + status = "user_confirmed" + method = "user_confirmed" + + needs_review = False + if not site_id and warehouse_id: + # Historical bug: site_id was written into warehouse_id — cannot auto-fix. + status = "unresolved" + method = None + site_id = None + warehouse_id = None + source_code = None + source_type = None + needs_review = True + elif not site_id or not warehouse_id: + status = "unresolved" + method = None + source_code = None + source_type = None + site_id = None + warehouse_id = None + needs_review = True + elif not routing_fingerprint: + status = "unresolved" + method = None + needs_review = True + + bind.execute( + sa.text( + "UPDATE shipping_tasks SET " + "inventory_source_code = :source_code, " + "inventory_source_type = :source_type, " + "inventory_site_id = :site_id, " + "inventory_warehouse_id = :warehouse_id, " + "inventory_source_status = :status, " + "inventory_source_method = :method, " + "inventory_source_config_version = :config_version, " + "inventory_routing_fingerprint = :routing_fingerprint " + "WHERE id = :task_id" + ), + { + "source_code": source_code, + "source_type": source_type, + "site_id": site_id, + "warehouse_id": warehouse_id, + "status": status, + "method": method, + "config_version": legacy_config_version, + "routing_fingerprint": routing_fingerprint, + "task_id": row.id, + }, + ) + if needs_review or status in {"ambiguous", "unresolved"}: + bind.execute( + sa.text( + "UPDATE shipping_tasks SET " + "pending_human_reason = 'inventory_source_unresolved', " + "current_step = 'step2_parse_confirm', " + "process_status = 'pending_review' " + "WHERE id = :task_id" + ), + {"task_id": row.id}, + ) + + bind.execute( + sa.text( + "UPDATE shipping_tasks SET " + "pending_human_reason = 'inventory_source_unresolved', " + "current_step = 'step2_parse_confirm', " + "process_status = 'pending_review' " + "WHERE inventory_source_status IN ('ambiguous', 'unresolved', 'conflicted', 'invalid') " + "AND (pending_human_reason IS NULL OR pending_human_reason = '')" + ) + ) + bind.execute( + sa.text( + "UPDATE shipping_tasks SET " + "pending_human_reason = 'inventory_source_unresolved', " + "current_step = 'step2_parse_confirm', " + "process_status = 'pending_review' " + "WHERE inventory_source_config_version = 'legacy-unverified'" + ) + ) + + file_rows = bind.execute( + sa.text("SELECT id, source_code, warehouse_id FROM shipping_inventory_files WHERE source_code IS NOT NULL") + ).fetchall() + for row in file_rows: + bind.execute( + sa.text( + "UPDATE shipping_inventory_files SET identity_status = 'unknown' WHERE id = :file_id" + ), + {"file_id": row.id}, + ) + + +def downgrade(): + """Remove inventory source gate columns.""" + with op.batch_alter_table("shipping_task_inventory_links", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_task_inventory_links_task_source") + batch_op.drop_column("identity_checked_at") + batch_op.drop_column("identity_check_status") + batch_op.drop_column("matched_site_id") + batch_op.drop_column("matched_source_code") + + with op.batch_alter_table("shipping_inventory_files", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_inventory_files_source_site_wh") + batch_op.drop_index("ix_shipping_inventory_files_identity_status") + batch_op.drop_index("ix_shipping_inventory_files_site_id") + batch_op.drop_column("identity_status") + batch_op.drop_column("source_config_version") + batch_op.drop_column("site_id") + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_constraint("fk_shipping_tasks_inventory_source_confirmed_by_users", type_="foreignkey") + batch_op.drop_index("ix_shipping_tasks_inventory_routing_fingerprint") + batch_op.drop_index("ix_shipping_tasks_inventory_source_status") + batch_op.drop_index("ix_shipping_tasks_inventory_site_id") + batch_op.drop_index("ix_shipping_tasks_inventory_source_code") + batch_op.drop_column("inventory_routing_fingerprint") + batch_op.drop_column("inventory_source_config_version") + batch_op.drop_column("inventory_source_confirmed_at") + batch_op.drop_column("inventory_source_confirmed_by") + batch_op.drop_column("inventory_source_method") + batch_op.drop_column("inventory_source_status") + batch_op.drop_column("inventory_warehouse_id") + batch_op.drop_column("inventory_site_id") + batch_op.drop_column("inventory_source_type") + batch_op.drop_column("inventory_source_code") + batch_op.drop_column("warehouse_hint") + batch_op.drop_column("destination_country") + batch_op.drop_column("destination_city") + batch_op.drop_column("destination_code") diff --git a/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py new file mode 100644 index 00000000..e4cbf07c --- /dev/null +++ b/backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py @@ -0,0 +1,276 @@ +""" +backend/migrations/versions/d6e7f8a9b0c1_add_rpa_callback_idempotency_fields.py + +用途:RPA 回调幂等字段、快照去重与关联迁移、库存源/身份 CHECK 约束。 +依赖:Alembic revision b4c5d6e7f8a9。 +逻辑:回填 consumed_run_no → 去重并迁移链接 → 加 CHECK 与 ready 态部分唯一索引。 + +Revision ID: d6e7f8a9b0c1 +Revises: b4c5d6e7f8a9 +Create Date: 2026-07-13 17:20:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "d6e7f8a9b0c1" +down_revision = "b4c5d6e7f8a9" +branch_labels = None +depends_on = None + +_RPA_IDENTITY_READY_WHERE = ( + "snapshot_status = 'ready' " + "AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL " + "AND site_id IS NOT NULL " + "AND warehouse_id IS NOT NULL" +) + + +def _json_consumed_run_no_expr(dialect_name: str) -> str: + """按方言生成从 step_payload_json 提取 consumed run_no 的 SQL 表达式。""" + if dialect_name == "postgresql": + return "step_payload_json->>'inventory_rpa_consumed_run_no'" + return "json_extract(step_payload_json, '$.inventory_rpa_consumed_run_no')" + + +def _backfill_consumed_run_no(bind) -> None: + """将历史 step_payload_json 中的消费轮次回填到独立列。""" + expr = _json_consumed_run_no_expr(bind.dialect.name) + bind.execute( + sa.text( + f""" + UPDATE shipping_tasks + SET inventory_rpa_consumed_run_no = {expr} + WHERE inventory_rpa_consumed_run_no IS NULL + AND step_payload_json IS NOT NULL + AND {expr} IS NOT NULL + AND TRIM({expr}) != '' + """ + ) + ) + + +def _dedupe_duplicate_rpa_snapshots(bind) -> int: + """ + 去重相同 RPA 四字段身份的快照(全状态),保留 ready 优先、id 最大的一条。 + 核心逻辑:迁移关联引用后再过期淘汰记录,避免任务仍指向被淘汰快照。 + """ + groups = bind.execute( + sa.text( + """ + SELECT rpa_run_no, source_code, site_id, warehouse_id, COUNT(*) AS cnt + FROM shipping_inventory_files + WHERE rpa_run_no IS NOT NULL AND TRIM(rpa_run_no) != '' + AND source_code IS NOT NULL AND TRIM(source_code) != '' + AND site_id IS NOT NULL AND TRIM(site_id) != '' + AND warehouse_id IS NOT NULL AND TRIM(warehouse_id) != '' + GROUP BY rpa_run_no, source_code, site_id, warehouse_id + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + + active_true = "TRUE" if bind.dialect.name == "postgresql" else "1" + inactive_false = "FALSE" if bind.dialect.name == "postgresql" else "0" + superseded = 0 + for group in groups: + rows = bind.execute( + sa.text( + """ + SELECT id + FROM shipping_inventory_files + WHERE rpa_run_no = :run_no + AND source_code = :source_code + AND site_id = :site_id + AND warehouse_id = :warehouse_id + ORDER BY + CASE snapshot_status WHEN 'ready' THEN 0 ELSE 1 END, + id DESC + """ + ), + { + "run_no": group.rpa_run_no, + "source_code": group.source_code, + "site_id": group.site_id, + "warehouse_id": group.warehouse_id, + }, + ).fetchall() + if len(rows) < 2: + continue + keeper_id = rows[0].id + for row in rows[1:]: + superseded_id = row.id + bind.execute( + sa.text( + f""" + UPDATE shipping_task_inventory_links + SET inventory_file_id = :keeper_id + WHERE inventory_file_id = :superseded_id + AND NOT EXISTS ( + SELECT 1 FROM shipping_task_inventory_links existing + WHERE existing.task_id = shipping_task_inventory_links.task_id + AND existing.inventory_file_id = :keeper_id + AND existing.is_active = {active_true} + ) + """ + ), + {"keeper_id": keeper_id, "superseded_id": superseded_id}, + ) + bind.execute( + sa.text( + f""" + UPDATE shipping_task_inventory_links + SET is_active = {inactive_false} + WHERE inventory_file_id = :superseded_id + """ + ), + {"superseded_id": superseded_id}, + ) + bind.execute( + sa.text( + """ + UPDATE shipping_tasks + SET inventory_snapshot_id = :keeper_id + WHERE inventory_snapshot_id = :superseded_id + """ + ), + {"keeper_id": keeper_id, "superseded_id": superseded_id}, + ) + bind.execute( + sa.text( + """ + UPDATE shipping_inventory_files + SET snapshot_status = 'expired', updated_at = CURRENT_TIMESTAMP + WHERE id = :id + """ + ), + {"id": superseded_id}, + ) + superseded += 1 + return superseded + + +def _sanitize_invalid_stable_inventory_sources(bind) -> None: + """将缺少完整身份字段的伪稳定任务降级为 unresolved,并清空过期身份残留。""" + bind.execute( + sa.text( + """ + UPDATE shipping_tasks + SET inventory_source_status = 'unresolved', + inventory_source_code = NULL, + inventory_source_method = NULL, + inventory_source_type = NULL, + inventory_site_id = NULL, + inventory_warehouse_id = NULL, + inventory_source_config_version = NULL, + inventory_routing_fingerprint = NULL, + inventory_source_confirmed_by = NULL, + inventory_source_confirmed_at = NULL + WHERE inventory_source_status IN ('resolved', 'user_confirmed') + AND ( + inventory_source_code IS NULL OR TRIM(inventory_source_code) = '' + OR inventory_site_id IS NULL OR TRIM(inventory_site_id) = '' + OR inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = '' + OR inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = '' + OR inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = '' + ) + """ + ) + ) + + +def _sanitize_invalid_identity_status(bind) -> None: + """将非法 identity_status 归一为 unknown。""" + bind.execute( + sa.text( + """ + UPDATE shipping_inventory_files + SET identity_status = 'unknown' + WHERE identity_status IS NOT NULL + AND identity_status NOT IN ('pending', 'verified', 'mismatch', 'unknown') + """ + ) + ) + + +def _create_rpa_identity_ready_unique_index() -> None: + """仅对 ready 快照施加 RPA 身份唯一约束,允许历史 expired 记录共存。""" + op.execute( + sa.text( + f""" + CREATE UNIQUE INDEX uq_shipping_inventory_files_rpa_identity_ready + ON shipping_inventory_files (rpa_run_no, source_code, site_id, warehouse_id) + WHERE {_RPA_IDENTITY_READY_WHERE} + """ + ) + ) + + +def upgrade(): + """回填消费轮次、去重快照、清洗数据并添加约束。""" + bind = op.get_bind() + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("inventory_rpa_consumed_run_no", sa.String(length=128), nullable=True)) + batch_op.create_index( + "ix_shipping_tasks_inventory_rpa_consumed_run_no", + ["inventory_rpa_consumed_run_no"], + unique=False, + ) + + _backfill_consumed_run_no(bind) + _dedupe_duplicate_rpa_snapshots(bind) + _sanitize_invalid_stable_inventory_sources(bind) + _sanitize_invalid_identity_status(bind) + + op.create_check_constraint( + "ck_shipping_tasks_inventory_source_status", + "shipping_tasks", + "inventory_source_status IS NULL OR inventory_source_status IN " + "('resolved', 'user_confirmed', 'ambiguous', 'unresolved', 'invalid', 'conflicted')", + ) + op.create_check_constraint( + "ck_shipping_tasks_inventory_source_method", + "shipping_tasks", + "inventory_source_method IS NULL OR inventory_source_method IN " + "('rule_exact', 'rule_combined', 'user_confirmed', 'legacy_migrated', 'manual')", + ) + op.create_check_constraint( + "ck_shipping_tasks_stable_inventory_identity", + "shipping_tasks", + "NOT (inventory_source_status IN ('resolved', 'user_confirmed') AND (" + "inventory_source_code IS NULL OR TRIM(inventory_source_code) = '' OR " + "inventory_site_id IS NULL OR TRIM(inventory_site_id) = '' OR " + "inventory_warehouse_id IS NULL OR TRIM(inventory_warehouse_id) = '' OR " + "inventory_source_config_version IS NULL OR TRIM(inventory_source_config_version) = '' OR " + "inventory_routing_fingerprint IS NULL OR TRIM(inventory_routing_fingerprint) = ''" + "))", + ) + op.create_check_constraint( + "ck_shipping_inventory_files_identity_status", + "shipping_inventory_files", + "identity_status IS NULL OR identity_status IN ('pending', 'verified', 'mismatch', 'unknown')", + ) + op.create_check_constraint( + "ck_shipping_inventory_files_snapshot_status", + "shipping_inventory_files", + "snapshot_status IS NULL OR snapshot_status IN ('ready', 'failed', 'expired')", + ) + + _create_rpa_identity_ready_unique_index() + + +def downgrade(): + """移除约束与 consumed run_no 列。""" + op.execute(sa.text("DROP INDEX IF EXISTS uq_shipping_inventory_files_rpa_identity_ready")) + op.drop_constraint("ck_shipping_inventory_files_snapshot_status", "shipping_inventory_files", type_="check") + op.drop_constraint("ck_shipping_inventory_files_identity_status", "shipping_inventory_files", type_="check") + op.drop_constraint("ck_shipping_tasks_stable_inventory_identity", "shipping_tasks", type_="check") + op.drop_constraint("ck_shipping_tasks_inventory_source_method", "shipping_tasks", type_="check") + op.drop_constraint("ck_shipping_tasks_inventory_source_status", "shipping_tasks", type_="check") + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_inventory_rpa_consumed_run_no") + batch_op.drop_column("inventory_rpa_consumed_run_no") diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index f6140b89..021fdd6d 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,4 +1,5 @@ import pytest +from pathlib import Path def parse_api_error(body: dict) -> dict: @@ -50,7 +51,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path): @pytest.fixture(autouse=True) -def _shipping_notice_stable_auto_config(app, request): +def _shipping_notice_stable_auto_config(app, request, monkeypatch): """发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。""" tmp_path = request.getfixturevalue("tmp_path") app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") @@ -61,6 +62,10 @@ def _shipping_notice_stable_auto_config(app, request): app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False + monkeypatch.setattr( + "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", + lambda: None, + ) return app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False @@ -78,6 +83,186 @@ def _shipping_notice_stable_auto_config(app, request): reset_rpa_worker_alert_state_for_tests() +@pytest.fixture(autouse=True) +def _shipping_test_default_destination(monkeypatch, request): + """ + 为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。 + 标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。 + """ + if request.node.get_closest_marker("inventory_source_gate"): + return + + from app.services.shipping_notice import extract as extract_mod + import app.services.shipping_notice.task_workflow as task_workflow_mod + + original = extract_mod.extract_notice_fields + + def _extract_with_default_destination(*args, structured=None, **kwargs): + patched = structured + if isinstance(structured, dict): + patched = dict(structured) + has_dest = any( + str(patched.get(key) or "").strip() + for key in ("ship_to", "destination_city", "destination_port", "destination_country", "warehouse_hint") + ) or isinstance(patched.get("destination"), dict) + if not has_dest: + for line in patched.get("lines") or []: + if isinstance(line, dict) and any( + str(line.get(key) or "").strip() + for key in ("ship_to", "destination_city", "destination_port", "warehouse_hint") + ): + has_dest = True + break + if not has_dest: + patched.setdefault("ship_to", "Dublin") + patched.setdefault("destination", {"city": "Dublin", "country": "IE"}) + return original(*args, structured=patched, **kwargs) + + monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination) + monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination) + + +def seed_task_inventory_source( + task: "ShippingTask", + *, + source_code: str = "DSV360_AWSDU", +) -> None: + """测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。""" + from app.services.shipping_notice.inventory_source_rules import ( + compute_routing_fingerprint, + extract_routing_context, + ) + from app.services.shipping_notice.inventory_sources import ( + get_inventory_source, + get_inventory_sources_config_version, + ) + + source = get_inventory_source(source_code) + if not source: + raise ValueError(f"unknown inventory source for tests: {source_code}") + from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity + + context = extract_routing_context(task) + resolution = resolve_inventory_source_identity(source, context) + if not resolution.ok or not resolution.identity: + raise ValueError( + f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}" + ) + identity = resolution.identity + task.inventory_source_code = identity.source_code + task.inventory_source_type = identity.source_type + task.inventory_site_id = identity.site_id + task.inventory_warehouse_id = identity.warehouse_id + task.inventory_source_status = "resolved" + task.inventory_source_method = "rule_exact" + task.inventory_source_config_version = get_inventory_sources_config_version() + task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) + + +def seed_rpa_inventory_trigger( + task: "ShippingTask", + *, + run_no: str = "RUN-TEST-001", + trigger_path: str | None = None, +) -> None: + """测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。""" + from app import db + from app.services.shipping_notice.tool_common import log_task_event + + if task.id is None: + db.session.add(task) + db.session.flush() + trigger = trigger_path or f"inventory_export_batch_{run_no}.json" + log_task_event( + task, + "inventory_rpa_triggered", + {"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False}, + ) + + +def inventory_xlsx_with_warehouse( + warehouse_id: str, + *, + sku: str = "A001", + qty: int = 1, +) -> "BytesIO": + """生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。""" + from io import BytesIO + + from openpyxl import Workbook + + buf = BytesIO() + wb = Workbook() + ws = wb.active + ws.append(["Warehouse ID", "SKU", "Qty"]) + ws.append([warehouse_id, sku, qty]) + wb.save(buf) + wb.close() + buf.seek(0) + return buf + + +def inventory_csv_with_warehouse( + warehouse_id: str, + *, + sku: str = "A001", + qty: int = 1, + delimiter: str = ",", +) -> "BytesIO": + """生成带 Warehouse ID 列的库存 CSV,供身份校验测试使用。""" + from io import BytesIO + + buf = BytesIO() + content = f"Warehouse ID{delimiter}SKU{delimiter}Qty\n{warehouse_id}{delimiter}{sku}{delimiter}{qty}\n" + buf.write(content.encode("utf-8")) + buf.seek(0) + return buf + + +def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]: + """构造 batch 成功回调 item 须携带的 Worker 身份字段。""" + return { + "source_code": str(task.inventory_source_code or ""), + "site_id": str(task.inventory_site_id or ""), + "warehouse_id": str(task.inventory_warehouse_id or ""), + } + + +def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: + """构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。""" + from app.services.shipping_notice.inventory_sources import get_inventory_source + + source = get_inventory_source(source_code) + if not source: + raise ValueError(f"unknown inventory source for tests: {source_code}") + item = { + "source_code": source_code, + "site_id": str(source.get("site_id") or ""), + "warehouse_id": str(source.get("warehouse_id") or ""), + } + item.update(overrides) + return item + + +def rpa_callback_payload( + task: "ShippingTask", + file_path: str | Path, + *, + run_no: str = "RUN-TEST-001", + status: str = "success", +) -> dict: + """构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。""" + return { + "task_id": task.task_no, + "status": status, + "file_path": str(file_path), + "run_no": run_no, + "source_code": task.inventory_source_code, + "site_id": task.inventory_site_id, + "warehouse_id": task.inventory_warehouse_id, + } + + def pytest_configure(config): config.addinivalue_line( "markers", @@ -85,7 +270,7 @@ def pytest_configure(config): ) config.addinivalue_line( "markers", - "rpa_e2e: 真实货代 RPA 浏览器导出测试,默认跳过,需 FREIGHT_RPA_E2E=true", + "inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", ) diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index 786b7ebb..e15ddbce 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -19,6 +19,7 @@ from app.jobs.queue import process_next_job from app.jobs.types import JobType from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools from app.services.shipping_notice.progress_workflow import auto_progress +from tests.conftest import seed_task_inventory_source def _tool_headers(app): @@ -655,6 +656,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path): } }, ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) db.session.commit() @@ -740,6 +742,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop") app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") + app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False with app.app_context(): user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com") db.session.add(user) @@ -792,8 +795,7 @@ def test_inventory_source_rules_cover_dsv360_programs(app): resolution = resolve_inventory_source(task) assert resolution.status == "resolved" - assert resolution.source is not None - assert resolution.source["source_code"] == expected_code + assert resolution.source_code == expected_code def test_auto_progress_unknown_destination_requires_inventory_source_review(app): @@ -822,7 +824,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app) db.session.refresh(task) assert result["status"] == "needs_human" assert result["checkpoint"] == "inventory_source_review" - assert task.process_status == "waiting_inventory" + assert task.process_status == "pending_review" assert task.pending_human_reason == "inventory_source_unresolved" assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved" assert len(result["data"]["inventory_source_candidates"]) >= 4 @@ -1447,6 +1449,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat agent = Agent( name="货代发货通知 Agent", + agent_code="shipping_notice", dify_api_key="test-dify-key", is_active=True, ) diff --git a/backend/tests/test_shipping_notice_inventory_rpa_archive.py b/backend/tests/test_shipping_notice_inventory_rpa_archive.py index a59e7fea..22704a7e 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_archive.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_archive.py @@ -298,7 +298,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path def test_build_schedule_run_wecom_description_mentions_raw_zip_download(app): - """企微正文在 summary 标记可下载时应提示点击通知进入 HXOPS,不写完整 URL。""" + """企微正文在 summary 标记可下载时应提示登录后自动下载,不写完整 URL。""" with app.app_context(): run = _make_inventory_run_with_created( schedule_no="ARCH-WECOM-1", @@ -308,13 +308,13 @@ def test_build_schedule_run_wecom_description_mentions_raw_zip_download(app): ) db.session.commit() text = _build_schedule_run_wecom_description(run) - assert "原始库存包:点击本通知进入 HXOPS 下载" in text + assert "原始库存包:点击本通知,登录 HXOPS 后自动下载" in text assert "https://" not in text assert "http://" not in text def test_build_schedule_run_wecom_jump_params_adds_raw_zip_flag_when_archive_available(app): - """有原始库存归档时跳转参数应包含 raw_zip=1。""" + """有原始库存归档时跳转参数应包含 raw_zip=1 与自动下载意图。""" with app.app_context(): run = _make_inventory_run_with_created( schedule_no="ARCH-JUMP-1", @@ -328,6 +328,7 @@ def test_build_schedule_run_wecom_jump_params_adds_raw_zip_flag_when_archive_ava assert params["task_id"] == task.id assert params["run_id"] == run.id assert params["raw_zip"] == "1" + assert params["download"] == "inventory_raw_zip" def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app): @@ -345,6 +346,7 @@ def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app) assert params["task_id"] == task.id assert params["run_id"] == run.id assert "raw_zip" not in params + assert "download" not in params def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app): @@ -369,12 +371,14 @@ def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app): assert _get_notify_base_url() == "https://hxops.example.com" -def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monkeypatch): +def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monkeypatch, tmp_path): """企微 textcard 跳转应指向管理端执行记录页,而非 workspace。""" from app.models import User from app.services.schedule.scheduler_service import _notify_schedule_run_wecom captured: list[str] = [] + media_uploads: list[str] = [] + file_sends: list[str] = [] def _fake_send_textcard(_userid, _title, _description, jump_url): captured.append(jump_url) @@ -390,13 +394,18 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke ) monkeypatch.setattr( "app.services.wecom_notify.upload_wecom_temp_media", - lambda *_args, **_kwargs: None, + lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}", + ) + monkeypatch.setattr( + "app.services.wecom_notify.send_wecom_file_message", + lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0}, ) with app.app_context(): app.config["WECOM_NOTIFY_ENABLED"] = True app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com" app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/" + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives") user = User( username="wecom_jump_user", @@ -414,10 +423,15 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke created=[{"inventory_file_no": "SIF-NOTIFY-1"}], summary={"raw_inventory_zip_available": True}, ) + raw_excel = tmp_path / "raw_inventory.xlsx" + raw_excel.write_bytes(b"raw inventory") + _attach_inventory_file(inventory_file_no="SIF-NOTIFY-1", storage_path=raw_excel) + run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run) task = run.task task.notify_enabled = True task.notify_user_ids_json = [user.id] - run.excel_file_data = None + run.excel_file_data = b"schedule excel" + run.excel_file_name = "schedule.xlsx" db.session.commit() _notify_schedule_run_wecom(task, run) @@ -427,6 +441,10 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke assert "task_id=" in captured[0] assert "run_id=" in captured[0] assert "raw_zip=1" in captured[0] + assert "download=inventory_raw_zip" in captured[0] + assert "schedule.xlsx" in media_uploads + assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads + assert file_sends == ["media-1", "media-2"] def test_get_inventory_raw_zip_requires_admin_auth(client, app): diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 422a84de..106f1cf8 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -5,9 +5,11 @@ 2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。 """ +from datetime import datetime from pathlib import Path from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink +from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source def _tool_headers(): @@ -36,8 +38,12 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction(): ) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。" -def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path): +def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monkeypatch): """mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) trigger = tmp_path / "triggers" trigger.mkdir() app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) @@ -94,8 +100,12 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path): assert len(events) == 1 -def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path): +def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path, monkeypatch): """RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) drop = tmp_path / "drop" drop.mkdir() app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) @@ -111,20 +121,53 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat ) task_id = create_res.get_json()["task_id"] + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "destination": {"port_code": "DUB", "city": "Dublin"}, + "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + from openpyxl import Workbook inv_file = drop / "stock.xlsx" wb = Workbook() ws = wb.active - ws.append(["料号", "Reservation ID", "可用数量"]) - ws.append(["A001", "R-1", 20]) + ws.append(["Warehouse ID", "料号", "Reservation ID", "可用数量"]) + ws.append(["AWSDU", "A001", "R-1", 20]) wb.save(inv_file) wb.close() + with app.app_context(): + from app import db + from tests.conftest import seed_rpa_inventory_trigger + + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + seed_rpa_inventory_trigger(task, run_no="RUN-MAP-REVIEW") + db.session.commit() + run_no = "RUN-MAP-REVIEW" + cb_res = client.post( "/api/shipping-notice/rpa/inventory-ready", headers=headers, - json={"task_no": task_id, "success": True, "file_path": str(inv_file), "rpa_mode": "browser"}, + json={ + "task_no": task_id, + "success": True, + "file_path": str(inv_file), + "run_no": run_no, + "source_code": "DSV360_AWSDU", + "site_id": "AWSDU", + "warehouse_id": "AWSDU", + "rpa_mode": "browser", + }, ) data = cb_res.get_json() assert data["status"] == "needs_human" @@ -138,8 +181,10 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat assert task is not None assert (task.step_payload_json or {})["last_inventory_rpa_runtime"]["mode"] == "browser" assert task.process_status == "inventory_ready" - stored = Path(app.config["SHIPPING_NOTICE_STORAGE_ROOT"]) / "inventory_uploads" / task_id / "inventory.xlsx" - assert stored.is_file() + from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path + + stored = resolve_task_inventory_upload_path(task_id) + assert stored is not None and stored.is_file() inv_file = ShippingInventoryFile.query.order_by(ShippingInventoryFile.id.desc()).first() assert inv_file is not None assert inv_file.share_mode == "task_only" @@ -166,6 +211,18 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, ) task_id = create_res.get_json()["task_id"] + from app import db + from tests.conftest import seed_task_inventory_source + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + from tests.conftest import seed_rpa_inventory_trigger + + seed_rpa_inventory_trigger(task, run_no="RUN-SKIPPED") + db.session.commit() + cb_res = client.post( "/api/shipping-notice/rpa/inventory-ready", headers=headers, @@ -176,6 +233,10 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, "skipped": True, "skip_reason": "no_inventory_data", "message": "DSV report has no inventory data", + "run_no": "RUN-SKIPPED", + "source_code": "DSV360_AWSDU", + "site_id": "AWSDU", + "warehouse_id": "AWSDU", "rpa_mode": "browser", }, ) @@ -241,7 +302,7 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path): assert result["result_status"] == "failed" assert result["data"]["result_status"] == "failed" assert result["data"]["failed_count"] == 1 - assert result["data"]["failed"][0]["error_code"] == "rpa_export_failed" + assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source" def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tmp_path): @@ -254,31 +315,22 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_mixed.xlsx" - try: - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 1]) - wb.save(sample) - except ImportError: - sample.write_bytes(b"placeholder") + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): result = rpa_report_inventory_batch({ "run_no": "RUN-MIXED", "trigger_type": "scheduled", "results": [ + scheduled_rpa_batch_item( + "DSV360_AWSDU", + status="success", + success=True, + file_path=str(sample), + ), { - "source_code": "SRC_OK", - "warehouse_id": "WH1", - "status": "success", - "success": True, - "file_path": str(sample), - }, - { - "source_code": "SRC_FAIL", + "source_code": "UNKNOWN_SOURCE", "warehouse_id": "WH2", "status": "failed", "success": False, @@ -304,7 +356,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path): "run_no": "RUN-ALL-FAIL", "trigger_type": "scheduled", "results": [{ - "source_code": "SRC_FAIL", + "source_code": "UNKNOWN_SOURCE", "warehouse_id": "WH1", "status": "failed", "success": False, @@ -314,6 +366,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path): assert result["status"] == "ok" assert result["result_status"] == "failed" assert result["failed_count"] == 1 + assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source" def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_status(): @@ -341,8 +394,12 @@ def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_statu assert outcome["failed_count"] == 2 -def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path): +def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch): """确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) from app import db from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source @@ -356,8 +413,10 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path): task = ShippingTask( task_no="SN-CONFIRM-SOURCE-RPA", source_type="pdf", - process_status="waiting_inventory", + process_status="pending_review", + current_step="step2_parse_confirm", pending_human_reason="inventory_source_unresolved", + ship_to="Dublin", step_payload_json={ "inventory_source_resolution": { "status": "unresolved", @@ -392,3 +451,839 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path): list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json")) or list(trigger.glob("inventory_export_batch_TASK-SN-CONFIRM-SOURCE-RPA*.json")) ) + + +def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): + """batch 顶层 run_no 应注入 result item,带 task_no 的成功项可入库。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + + sample = drop_dir / "batch_task_success.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-BATCH-RUNNO", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + from tests.conftest import seed_rpa_inventory_trigger + + seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-TOP") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory_batch({ + "run_no": "RUN-BATCH-TOP", + "trigger_type": "on_demand", + "results": [{ + "task_no": task.task_no, + "status": "success", + "success": True, + "file_path": str(sample), + "source_code": task.inventory_source_code, + "site_id": task.inventory_site_id, + "warehouse_id": task.inventory_warehouse_id, + }], + }) + db.session.refresh(task) + + assert result["status"] == "ok" + assert result["success_count"] == 1 + assert task.process_status == "inventory_ready" + + +def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): + """batch failed + task_no 应驱动任务失败重试/人工兜底,而非停留在 rpa_pending。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + + with app.app_context(): + task = ShippingTask( + task_no="SN-BATCH-FAIL-TASK", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + from tests.conftest import seed_rpa_inventory_trigger + + seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-FAIL") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory_batch({ + "run_no": "RUN-BATCH-FAIL", + "trigger_type": "on_demand", + "results": [{ + "task_no": task.task_no, + "status": "failed", + "success": False, + "error_message": "login timeout", + }], + }) + db.session.refresh(task) + + assert result["status"] == "ok" + assert result["failed_count"] == 1 + assert task.process_status == "waiting_inventory" + assert task.error_message + failed_events = ShippingTaskEvent.query.filter_by( + task_id=task.id, + event_type="inventory_rpa_failed", + ).all() + assert len(failed_events) == 1 + + +def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): + """单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory + + with app.app_context(): + task = ShippingTask( + task_no="SN-FAIL-NO-IDENT", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory({ + "task_id": task.task_no, + "status": "failed", + "success": False, + "run_no": "RUN-FAIL-NO-IDENT", + "error_message": "browser login failed", + }) + db.session.refresh(task) + + assert result["status"] == "needs_human" + failed_events = ShippingTaskEvent.query.filter_by( + task_id=task.id, + event_type="inventory_rpa_failed", + ).all() + assert failed_events + assert "browser login failed" in (failed_events[-1].detail_json or {}).get("error", "") + + +def test_batch_callback_rejects_unknown_task_no(app, tmp_path): + """batch item 携带不存在 task_no 时应拒绝,不得退化为定时预热快照。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "orphan_task.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + result = rpa_report_inventory_batch({ + "run_no": "RUN-UNKNOWN-TASK", + "trigger_type": "on_demand", + "results": [{ + "task_no": "SN-DOES-NOT-EXIST", + "status": "success", + "success": True, + "file_path": str(sample), + "source_code": "DSV360_AWSDU", + "site_id": "DSV360", + "warehouse_id": "AWSDU", + }], + }) + after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + + assert result["status"] == "ok" + assert result["failed_count"] == 1 + assert result["data"]["failed"][0]["error"] == "task_not_found" + assert after == before + + +def test_batch_success_rejects_missing_worker_identity(app, tmp_path): + """batch 成功项缺少 Worker 身份字段时不得由任务字段自证通过。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "missing_identity.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-BATCH-NO-IDENT", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory_batch({ + "run_no": "RUN-BATCH-NO-IDENT", + "trigger_type": "on_demand", + "results": [{ + "task_no": task.task_no, + "status": "success", + "success": True, + "file_path": str(sample), + }], + }) + db.session.refresh(task) + + assert result["status"] == "ok" + assert result["failed_count"] == 1 + assert task.process_status == "waiting_inventory" + + +def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch): + """复用快照后 ingest 失败时不得删除原快照与托管文件。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "reuse_ingest_fail.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + run_no = "RUN-REUSE-INGEST-FAIL" + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file", + lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")), + ) + + with app.app_context(): + warmup = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample), + )], + }) + snap = ShippingInventoryFile.query.filter_by( + rpa_run_no=run_no, + source_code="DSV360_AWSDU", + snapshot_status="ready", + ).first() + assert warmup["success_count"] == 1 + assert snap is not None + storage_path = Path(snap.storage_path) + assert storage_path.is_file() + snap_id = snap.id + + task = ShippingTask( + task_no="SN-REUSE-INGEST-FAIL", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no=run_no) + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "on_demand", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample), + task_no=task.task_no, + )], + }) + db.session.refresh(task) + snap_after = ShippingInventoryFile.query.get(snap_id) + + assert result["failed_count"] == 1 + assert snap_after is not None + assert snap_after.snapshot_status == "ready" + assert Path(snap_after.storage_path).is_file() + assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1 + assert task.process_status == "waiting_inventory" + + +def test_reused_snapshot_rejects_content_mismatch(app, tmp_path): + """同身份重试但文件内容不同必须拒绝,且不得覆盖原快照解析结果。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + from openpyxl import Workbook + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + run_no = "RUN-REUSE-MISMATCH" + + first = drop_dir / "first.xlsx" + first.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + second = drop_dir / "second.xlsx" + wb = Workbook() + ws = wb.active + ws.append(["Warehouse ID", "SKU", "Qty Available"]) + ws.append(["AWSDU", "DIFFERENT-SKU", 99]) + wb.save(second) + wb.close() + + with app.app_context(): + first_result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(first), + )], + }) + snap = ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").one() + original_lines = list(snap.inventory_lines_json or []) + assert first_result["success_count"] == 1 + + second_result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(second), + )], + }) + db.session.refresh(snap) + + assert second_result["failed_count"] == 1 + assert second_result["data"]["failed"][0]["error"] == "reused_snapshot_content_mismatch" + assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1 + assert list(snap.inventory_lines_json or []) == original_lines + + +def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, monkeypatch): + """batch 中失败单项须 savepoint 回滚,不影响同批其他成功项。""" + from app import db + from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response as real_loaded + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample_a = drop_dir / "task_a.xlsx" + sample_b = drop_dir / "task_b.xlsx" + sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + sample_b.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + run_no = "RUN-BATCH-PARTIAL-ROLLBACK" + loaded_calls = {"count": 0} + + def flaky_loaded(task, *args, **kwargs): + loaded_calls["count"] += 1 + if loaded_calls["count"] >= 2: + raise RuntimeError("loaded boom") + return real_loaded(task, *args, **kwargs) + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response", + flaky_loaded, + ) + + with app.app_context(): + task_a = ShippingTask( + task_no="SN-BATCH-OK", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + task_b = ShippingTask( + task_no="SN-BATCH-FAIL", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "B001", "qty": 1}], + ) + seed_task_inventory_source(task_a, source_code="DSV360_AWSDU") + seed_task_inventory_source(task_b, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task_a, run_no=run_no) + seed_rpa_inventory_trigger(task_b, run_no=run_no) + db.session.add_all([task_a, task_b]) + db.session.commit() + before_b_status = task_b.process_status + + result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "on_demand", + "results": [ + scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample_a), + task_no=task_a.task_no, + ), + scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample_b), + task_no=task_b.task_no, + ), + ], + }) + db.session.refresh(task_a) + db.session.refresh(task_b) + + assert result["success_count"] == 1 + assert result["failed_count"] == 1 + assert task_a.inventory_rpa_consumed_run_no == run_no + assert task_b.inventory_rpa_consumed_run_no is None + assert task_b.process_status == before_b_status + + +def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch): + """共享快照被另一任务复用失败时,不得影响已关联任务的 active link。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "shared.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + run_no = "RUN-SHARED-LINK" + + with app.app_context(): + task_ok = ShippingTask( + task_no="SN-SHARED-OK", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + task_fail = ShippingTask( + task_no="SN-SHARED-FAIL", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "B001", "qty": 1}], + ) + seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU") + seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task_ok, run_no=run_no) + seed_rpa_inventory_trigger(task_fail, run_no=run_no) + db.session.add_all([task_ok, task_fail]) + db.session.commit() + + ok_result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "on_demand", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample), + task_no=task_ok.task_no, + )], + }) + snap = ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").one() + ok_link = ShippingTaskInventoryLink.query.filter_by( + task_id=task_ok.id, + inventory_file_id=snap.id, + is_active=True, + ).one() + assert ok_result["success_count"] == 1 + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file", + lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")), + ) + fail_result = rpa_report_inventory_batch({ + "run_no": run_no, + "trigger_type": "on_demand", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample), + task_no=task_fail.task_no, + )], + }) + still_ok_link = ShippingTaskInventoryLink.query.filter_by( + task_id=task_ok.id, + inventory_file_id=snap.id, + is_active=True, + ).one() + + assert fail_result["failed_count"] == 1 + assert still_ok_link.id == ok_link.id + assert ShippingInventoryFile.query.get(snap.id) is not None + assert Path(snap.storage_path).is_file() + + +def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_path, monkeypatch): + """数据库提交后 post-commit 步骤失败时不得删除已提交快照文件。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory + from tests.conftest import rpa_callback_payload, seed_rpa_inventory_trigger, seed_task_inventory_source + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "post_commit.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + import app.services.shipping_notice.inventory_file_store as file_store + + monkeypatch.setattr( + file_store, + "start_inventory_file_linked_tasks", + lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("post commit boom")), + ) + + with app.app_context(): + task = ShippingTask( + task_no="SN-POST-COMMIT-FAIL", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-POST-COMMIT")) + snap = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-POST-COMMIT", snapshot_status="ready").first() + + assert snap is not None + assert Path(snap.storage_path).is_file() + assert result.get("data", {}).get("post_commit_warnings") + assert task.inventory_rpa_consumed_run_no == "RUN-POST-COMMIT" + + +def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkeypatch): + """晋升失败后应自动从 storage_path 重建任务正式附件,且不依赖重新消费 callback。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory + from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path + from tests.conftest import rpa_callback_payload, seed_rpa_inventory_trigger, seed_task_inventory_source + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "promote_fail.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + def _boom_promote(*_args, **_kwargs): + raise OSError("promote exploded") + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.promote_staged_task_inventory_file", + _boom_promote, + ) + + with app.app_context(): + task = ShippingTask( + task_no="SN-PROMOTE-FAIL-REBUILD", + source_type="manual", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-PROMOTE-FAIL")) + attachment = resolve_task_inventory_upload_path(task.task_no) + + assert result["status"] == "needs_human" + warnings = result.get("data", {}).get("post_commit_warnings") or [] + assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings) + assert attachment is not None and attachment.is_file() + assert task.inventory_rpa_consumed_run_no == "RUN-PROMOTE-FAIL" + + +def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path): + """人工补偿接口应能从快照 storage_path 幂等重建任务附件。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import repair_task_inventory_attachment + from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + + storage_root = tmp_path / "storage" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(storage_root) + snap_dir = storage_root / "inventory_uploads" / "SIF-TEST" + snap_dir.mkdir(parents=True) + snap_file = snap_dir / "inventory.xlsx" + snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-REPAIR-ATTACH", + source_type="manual", + process_status="inventory_ready", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.flush() + inv_file = ShippingInventoryFile( + inventory_file_no="SIF-REPAIR-TEST", + storage_path=str(snap_file), + snapshot_status="ready", + source_code="DSV360_AWSDU", + site_id="AWSDU", + warehouse_id="AWSDU", + share_mode="task_only", + schema_preview_json={}, + exported_at=datetime.utcnow(), + ) + db.session.add(inv_file) + db.session.flush() + link_snapshot_to_task(task, inv_file, reason="test") + db.session.commit() + + first = repair_task_inventory_attachment({"task_no": task.task_no}) + second = repair_task_inventory_attachment({"task_no": task.task_no}) + attachment = resolve_task_inventory_upload_path(task.task_no) + + assert first["status"] == "ok" + assert second["status"] == "ok" + assert attachment is not None and attachment.is_file() + assert first["data"]["attachment_path"] == second["data"]["attachment_path"] + + +def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch): + """callback 归档失败时应写入持久化 cleanup job。""" + from app import db + from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "move_fail.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + def _boom_move(*_args, **_kwargs): + raise OSError("move exploded") + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.move_callback_drop_file_to_processed", + _boom_move, + ) + + with app.app_context(): + payload = { + "run_no": "RUN-MOVE-FAIL", + "results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))], + } + result = rpa_report_inventory_batch(payload) + queue = callback_cleanup_queue_dir() + jobs = list(queue.glob("move_*.json")) if queue else [] + + assert result["status"] == "ok" + assert jobs + assert not sample.is_file() + quarantined = list((drop_dir / ".hxops_quarantine").glob("move_fail.xlsx")) + assert quarantined + + +def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, monkeypatch): + """move 与 quarantine 均失败时,仍应以原路径入队且 API 返回 ok。""" + import json + + from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "quarantine_fail.xlsx" + sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + def _boom_move(*_args, **_kwargs): + raise OSError("move exploded") + + def _boom_quarantine(*_args, **_kwargs): + raise OSError("quarantine exploded") + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.move_callback_drop_file_to_processed", + _boom_move, + ) + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.quarantine_callback_drop_file", + _boom_quarantine, + ) + + with app.app_context(): + payload = { + "run_no": "RUN-QUARANTINE-FAIL", + "results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))], + } + result = rpa_report_inventory_batch(payload) + queue = callback_cleanup_queue_dir() + jobs = list(queue.glob("move_*.json")) if queue else [] + + assert result["status"] == "ok" + assert jobs + assert sample.is_file() + job_payload = json.loads(jobs[0].read_text(encoding="utf-8")) + assert job_payload["callback_path"] == str(sample) + assert "move exploded" in str(job_payload.get("last_error") or "") + + +def test_resolve_trusts_marker_over_newer_orphan_attachment(app, tmp_path): + """marker 有效时必须返回 marker 指向的已提交附件,不得按 mtime 选未提交新文件。""" + from app.services.shipping_notice.inventory_upload import ( + _atomic_write_task_inventory_marker, + _task_inventory_upload_dir, + resolve_task_inventory_upload_path, + ) + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + task_no = "SN-MARKER-TRUST" + base = _task_inventory_upload_dir(task_no) + base.mkdir(parents=True) + committed = base / "inventory_20260713010000000000.xlsx" + orphan = base / "inventory_20260713020000000000.xlsx" + committed.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + orphan.write_bytes(b"orphan-newer") + _atomic_write_task_inventory_marker(task_no, committed.name) + + with app.app_context(): + resolved = resolve_task_inventory_upload_path(task_no) + assert resolved == committed + + +def test_repair_rejects_foreign_inventory_file_no(app, tmp_path): + """修复接口不得安装非 active link 的快照。""" + from app import db + from app.services.shipping_notice.inventory_rpa_workflow import repair_task_inventory_attachment + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + + storage_root = tmp_path / "storage" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(storage_root) + snap_dir = storage_root / "inventory_uploads" / "SIF-ACTIVE" + snap_dir.mkdir(parents=True) + active_file = snap_dir / "inventory.xlsx" + active_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + other_file = storage_root / "other.xlsx" + other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-REPAIR-REJECT", + source_type="manual", + process_status="inventory_ready", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.flush() + active_snap = ShippingInventoryFile( + inventory_file_no="SIF-ACTIVE-SNAP", + storage_path=str(active_file), + snapshot_status="ready", + source_code="DSV360_AWSDU", + site_id="AWSDU", + warehouse_id="AWSDU", + share_mode="task_only", + schema_preview_json={}, + exported_at=datetime.utcnow(), + ) + foreign_snap = ShippingInventoryFile( + inventory_file_no="SIF-FOREIGN-SNAP", + storage_path=str(other_file), + snapshot_status="ready", + source_code="DSV360_AWSDU", + site_id="AWSDU", + warehouse_id="AWSDU", + share_mode="task_only", + schema_preview_json={}, + exported_at=datetime.utcnow(), + ) + db.session.add_all([active_snap, foreign_snap]) + db.session.flush() + link_snapshot_to_task(task, active_snap, reason="test") + db.session.commit() + + result = repair_task_inventory_attachment({ + "task_no": task.task_no, + "inventory_file_no": foreign_snap.inventory_file_no, + }) + assert result["status"] == "failed" + assert result["data"]["error"] == "snapshot_not_active_for_task" + + +def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_path): + """cleanup 队列应由启动恢复独立消费,不依赖下一次 callback。""" + from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + callback_cleanup_queue_dir, + enqueue_callback_file_move, + recover_pending_rpa_callback_cleanup_jobs, + ) + + drop_dir = tmp_path / "drop" + processed_dir = tmp_path / "processed" + drop_dir.mkdir() + processed_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir) + + quarantine = drop_dir / ".hxops_quarantine" + quarantine.mkdir(parents=True) + stuck = quarantine / "stuck.xlsx" + stuck.write_bytes(b"stuck") + + with app.app_context(): + enqueue_callback_file_move( + stuck, + processed_dir=processed_dir, + run_no="RUN-STUCK", + task_no="SN-STUCK", + error="simulated move failure", + ) + queue = callback_cleanup_queue_dir() + assert queue is not None + assert list(queue.glob("move_*.json")) + + recovered, warnings = recover_pending_rpa_callback_cleanup_jobs() + assert recovered >= 1 + assert not list(queue.glob("move_*.json")) + assert list(processed_dir.glob("stuck.xlsx")) + assert not stuck.is_file() + assert warnings == [] diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index 2cbf87ce..89841db7 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -25,6 +25,13 @@ from app.services.schedule.shipping_inventory_rpa_job import ( run_shipping_inventory_rpa_schedule, ) from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch +from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item + + +def _write_sample_inventory(path: Path, warehouse_id: str) -> None: + """写入带 Warehouse ID 列的样例库存 Excel。""" + with open(path, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku="A001", qty=1).getvalue()) def _make_inventory_schedule_task( @@ -218,16 +225,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_excel_fail.xlsx" - try: - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 1]) - wb.save(sample) - except ImportError: - sample.write_bytes(b"placeholder") + _write_sample_inventory(sample, "BYAWSATL01") def _excel_boom(*_args, **_kwargs): raise RuntimeError("excel exploded") @@ -266,12 +264,11 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) "run_no": run.run_no, "schedule_run_id": run.id, "trigger_type": "scheduled", - "results": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", - "success": True, - "file_path": str(sample), - }], + "results": [scheduled_rpa_batch_item( + "DSV360_AWSBI_BYAWSATL01", + success=True, + file_path=str(sample), + )], }) db.session.refresh(run) @@ -293,16 +290,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_fail_finalize.xlsx" - try: - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 1]) - wb.save(sample) - except ImportError: - sample.write_bytes(b"placeholder") + _write_sample_inventory(sample, "BYAWSATL01") def _boom(*_args, **_kwargs): raise RuntimeError("finalize exploded") @@ -341,12 +329,11 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp "run_no": run.run_no, "schedule_run_id": run.id, "trigger_type": "scheduled", - "results": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", - "success": True, - "file_path": str(sample), - }], + "results": [scheduled_rpa_batch_item( + "DSV360_AWSBI_BYAWSATL01", + success=True, + file_path=str(sample), + )], }) db.session.refresh(run) @@ -367,16 +354,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_sample.xlsx" - try: - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 1]) - wb.save(sample) - except ImportError: - sample.write_bytes(b"placeholder") + _write_sample_inventory(sample, "BYAWSATL01") with app.app_context(): task = _make_inventory_schedule_task( @@ -407,12 +385,11 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): "run_no": run.run_no, "schedule_run_id": run.id, "trigger_type": "scheduled", - "results": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", - "success": True, - "file_path": str(sample), - }], + "results": [scheduled_rpa_batch_item( + "DSV360_AWSBI_BYAWSATL01", + success=True, + file_path=str(sample), + )], }) db.session.refresh(run) @@ -520,16 +497,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path): app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_partial.xlsx" - try: - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 1]) - wb.save(sample) - except ImportError: - sample.write_bytes(b"placeholder") + _write_sample_inventory(sample, "AWSDU") with app.app_context(): task = _make_inventory_schedule_task( @@ -545,9 +513,9 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path): response_summary_json={ "awaiting_rpa": True, "pending_details": [ - {"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"}, - {"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"}, - {"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"}, + {"source_code": "DSV360_AWSDU", "warehouse_id": "AWSDU", "display_name": "Dublin"}, + {"source_code": "DSV360_AWSCV", "warehouse_id": "AWSCV", "display_name": "CV"}, + {"source_code": "DSV360_AWSAMS", "warehouse_id": "RTM", "display_name": "AMS"}, ], }, step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}], @@ -559,12 +527,11 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path): "run_no": run.run_no, "schedule_run_id": run.id, "trigger_type": "scheduled", - "results": [{ - "source_code": "SRC_A", - "warehouse_id": "WH1", - "success": True, - "file_path": str(sample), - }], + "results": [scheduled_rpa_batch_item( + "DSV360_AWSDU", + success=True, + file_path=str(sample), + )], }) db.session.refresh(run) @@ -729,3 +696,206 @@ def test_build_schedule_run_wecom_description_includes_skipped_count(): assert "跳过: 1" in text assert "成功: 2" in text assert "失败: 0" in text + + +def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path): + """定时 batch 回调 run_no 与排程 run 不一致时必须拒绝终态化。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + + with app.app_context(): + task = _make_inventory_schedule_task( + schedule_no="SCH-INV-RUNNO-MISMATCH", + username="schedule_runno_mismatch_user", + ) + run = ScheduleRun( + run_no="RUN-EXPECTED", + schedule_task_id=task.id, + status="running", + started_at=datetime.utcnow(), + total_count=1, + response_summary_json={"awaiting_rpa": True, "pending_details": []}, + step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}], + ) + db.session.add(run) + db.session.commit() + + result = rpa_report_inventory_batch({ + "run_no": "RUN-WRONG", + "schedule_run_id": run.id, + "trigger_type": "scheduled", + "results": [], + }) + db.session.refresh(run) + + assert result["status"] == "failed" + assert (result.get("data") or {}).get("schedule_run_error") == "schedule_run_no_mismatch" + assert run.status == "running" + + +def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path): + """定时 batch 成功项缺少 site_id 时必须拒绝,不得仅靠 source_code 入库。""" + from app.models import ShippingInventoryFile + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "missing_site.xlsx" + _write_sample_inventory(sample, "BYAWSATL01") + + with app.app_context(): + before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + result = rpa_report_inventory_batch({ + "run_no": "RUN-MISSING-SITE", + "trigger_type": "scheduled", + "results": [{ + "source_code": "DSV360_AWSBI_BYAWSATL01", + "warehouse_id": "BYAWSATL01", + "success": True, + "file_path": str(sample), + }], + }) + after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + + assert result["status"] == "ok" + assert result["failed_count"] == 1 + assert result["data"]["failed"][0]["error"] == "site_id_missing" + assert after == before + + +def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkeypatch): + """finalize 失败重试同一回调时不得重复创建 ready 快照。""" + from app.models import ShippingInventoryFile + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "retry_snapshot.xlsx" + _write_sample_inventory(sample, "BYAWSATL01") + + def _boom(*_args, **_kwargs): + raise RuntimeError("finalize exploded") + + monkeypatch.setattr( + "app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details", + _boom, + ) + + with app.app_context(): + task = _make_inventory_schedule_task( + schedule_no="SCH-INV-RETRY-SNAPSHOT", + username="schedule_inv_retry_snapshot_user", + api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + ) + run = ScheduleRun( + run_no="RUN20260713163000", + schedule_task_id=task.id, + status="running", + started_at=datetime.utcnow(), + total_count=1, + response_summary_json={"awaiting_rpa": True, "pending_details": []}, + step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}], + ) + db.session.add(run) + db.session.commit() + + payload = { + "run_no": run.run_no, + "schedule_run_id": run.id, + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSBI_BYAWSATL01", + success=True, + file_path=str(sample), + )], + } + first = rpa_report_inventory_batch(payload) + second = rpa_report_inventory_batch(payload) + count = ShippingInventoryFile.query.filter_by( + rpa_run_no=run.run_no, + source_code="DSV360_AWSBI_BYAWSATL01", + site_id="AWSBI", + warehouse_id="BYAWSATL01", + snapshot_status="ready", + ).count() + + assert first["data"]["schedule_finalize_status"] == "failed" + assert second["data"]["schedule_finalize_status"] == "failed" + assert count == 1 + assert second["data"]["created"][0].get("reused_existing_snapshot") is True + + +def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch): + """finalize 首次失败、重试成功后应归档 callback 原文件。""" + from app.models import ShippingInventoryFile + from app.services.schedule import shipping_inventory_rpa_finalize as finalize_mod + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "retry_move.xlsx" + _write_sample_inventory(sample, "BYAWSATL01") + processed_dir = drop_dir / "processed" + + original_finalize = finalize_mod.finalize_shipping_inventory_schedule_run + state = {"calls": 0} + + def _finalize_fail_once(schedule_run_id, **kwargs): + state["calls"] += 1 + if state["calls"] == 1: + return { + "ok": False, + "error": "finalize exploded", + "schedule_finalize_status": "failed", + "manual_retryable": True, + } + return original_finalize(schedule_run_id, **kwargs) + + monkeypatch.setattr( + finalize_mod, + "finalize_shipping_inventory_schedule_run", + _finalize_fail_once, + ) + + with app.app_context(): + task = _make_inventory_schedule_task( + schedule_no="SCH-INV-RETRY-MOVE", + username="schedule_inv_retry_move_user", + api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + ) + run = ScheduleRun( + run_no="RUN20260713170000", + schedule_task_id=task.id, + status="running", + started_at=datetime.utcnow(), + total_count=1, + response_summary_json={"awaiting_rpa": True, "pending_details": []}, + step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}], + ) + db.session.add(run) + db.session.commit() + + payload = { + "run_no": run.run_no, + "schedule_run_id": run.id, + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "DSV360_AWSBI_BYAWSATL01", + success=True, + file_path=str(sample), + )], + } + first = rpa_report_inventory_batch(payload) + assert first["data"]["schedule_finalize_status"] == "failed" + assert sample.is_file() + + second = rpa_report_inventory_batch(payload) + assert second["data"]["schedule_finalize_status"] == "ok" + assert second["data"]["created"][0].get("reused_existing_snapshot") is True + assert not sample.is_file() + assert list(processed_dir.glob("retry_move.xlsx")) + assert ShippingInventoryFile.query.filter_by( + rpa_run_no=run.run_no, + snapshot_status="ready", + ).count() == 1 diff --git a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py index 7dc0c76c..915dbb5b 100644 --- a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py +++ b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py @@ -4,7 +4,7 @@ from datetime import datetime, timedelta from pathlib import Path from app import db -from app.models import ShippingInventoryFile, ShippingTask +from app.models import ShippingTask from app.services.shipping_notice.inventory_snapshot_store import ( create_inventory_snapshot_from_rpa, find_latest_ready_snapshot, @@ -15,19 +15,45 @@ from app.services.shipping_notice.inventory_snapshot_store import ( from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source +from tests.conftest import inventory_xlsx_with_warehouse, seed_task_inventory_source + + +def _write_inventory_xlsx(path: Path, warehouse_id: str, *, sku: str = "A001", qty: int = 10) -> None: + with open(path, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku=sku, qty=qty).getvalue()) + + +def _task_with_inventory_source( + task_no: str, + *, + source_code: str, + source_type: str | None = None, + site_id: str | None = None, + warehouse_id: str = "", +) -> ShippingTask: + """构造已通过库存源门禁的任务,供快照关联测试使用。""" + task = ShippingTask( + task_no=task_no, + source_type="manual", + process_status="parsed", + ) + seed_task_inventory_source(task, source_code=source_code) + if site_id: + task.inventory_site_id = site_id + if warehouse_id: + task.inventory_warehouse_id = warehouse_id + if source_type: + task.inventory_source_type = source_type + return task + + def test_fresh_snapshot_is_reused(app, tmp_path): - """未过期 ready 快照应被 find_latest_ready_snapshot 命中。""" + """未过期 ready 快照应被 find_latest_ready_snapshot 按 source+site 命中。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24 - from openpyxl import Workbook - xlsx = tmp_path / "stock.xlsx" - wb = Workbook() - wb.active.append(["sku", "qty"]) - wb.active.append(["A001", 10]) - wb.save(xlsx) - wb.close() + _write_inventory_xlsx(xlsx, "AWSDU") source = build_rpa_inventory_source("DSV360_AWSDU") assert source is not None @@ -40,24 +66,19 @@ def test_fresh_snapshot_is_reused(app, tmp_path): success=True, ) db.session.commit() - found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU") + found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") assert found is not None assert found.inventory_file_no == inv.inventory_file_no + assert found.site_id == "AWSDU" assert is_snapshot_fresh(found) -def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path): - """DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。""" +def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path): + """DSV 子仓快照应分别落库 site_id 与 warehouse_id,禁止混用。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - from openpyxl import Workbook - xlsx = tmp_path / "stock.xlsx" - wb = Workbook() - wb.active.append(["sku", "qty"]) - wb.active.append(["A001", 10]) - wb.save(xlsx) - wb.close() + _write_inventory_xlsx(xlsx, "BYAWSATL01") source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01") assert source is not None @@ -66,26 +87,36 @@ def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path): with app.app_context(): inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) - task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory") + task = _task_with_inventory_source( + "SN-SNAPSHOT-SITE", + source_code="DSV360_AWSBI_BYAWSATL01", + source_type="dsv360", + site_id="AWSBI", + warehouse_id="BYAWSATL01", + ) db.session.add(task) db.session.flush() link = link_snapshot_to_task(task, inv, reason="reuse_latest") db.session.commit() - assert inv.warehouse_id == "AWSBI" + assert inv.site_id == "AWSBI" + assert inv.warehouse_id == "BYAWSATL01" assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01" - assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None - assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None + assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01") is not None + assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01_WRONG") is None assert link is not None - assert link.matched_warehouse_id == "AWSBI" + assert link.matched_site_id == "AWSBI" + assert link.matched_warehouse_id == "BYAWSATL01" -def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path): - """无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。""" +def test_crane_runtime_source_carries_dynamic_warehouse(app, tmp_path): + """Crane 运行时 RPA source 应携带任务动态库位 TZR2。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") from openpyxl import Workbook + from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source + xlsx = tmp_path / "crane_stock.xlsx" wb = Workbook() wb.active.append(["Warehouse ID", "sku", "qty"]) @@ -93,41 +124,69 @@ def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_pat wb.save(xlsx) wb.close() - source = { - "source_code": "CRANE", - "source_type": "crane_footprint", - "site_id": "", - "warehouse_id": "", - } - with app.app_context(): - inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) - task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory") + task = ShippingTask( + task_no="SN-SNAPSHOT-CRANE-RUNTIME", + source_type="manual", + process_status="parsed", + ship_to="TZR2 footprint", + ) + seed_task_inventory_source(task, source_code="CRANE") + runtime_source = build_task_rpa_inventory_source(task) + assert runtime_source is not None + assert runtime_source["site_id"] == "CRANE" + assert runtime_source["warehouse_id"] == "TZR2" + assert runtime_source["query"]["warehouse_code"] == "TZR2" + + inv = create_inventory_snapshot_from_rpa( + source=runtime_source, + local_path=xlsx, + trigger_type="on_demand", + success=True, + ) db.session.add(task) db.session.flush() link = link_snapshot_to_task(task, inv, reason="rpa_callback") db.session.commit() assert inv.warehouse_id == "TZR2" - assert (inv.source_query_json or {}).get("site_id") is None - assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2" - assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel" + assert (inv.source_query_json or {}).get("warehouse_id_source") == "task_identity_excel_verified" + assert (inv.source_query_json or {}).get("excel_warehouse_verified") is True assert link is not None assert link.matched_warehouse_id == "TZR2" +def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path): + """相同 SKU 但库存源不同不能复用快照。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + xlsx = tmp_path / "stock.xlsx" + _write_inventory_xlsx(xlsx, "AWSDU") + + with app.app_context(): + source = build_rpa_inventory_source("DSV360_AWSDU") + inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) + task = _task_with_inventory_source( + "SN-SNAPSHOT-MISMATCH", + source_code="DSV360_AWSAMS", + source_type="dsv360", + site_id="AWSAMS", + ) + db.session.add(task) + db.session.flush() + link = link_snapshot_to_task(task, inv, reason="reuse_latest") + db.session.commit() + assert link is None + assert inv.identity_status == "mismatch" + + def test_expired_snapshot_not_reused(app, tmp_path): """过期快照不应被 find_latest_ready_snapshot 返回。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1 - from openpyxl import Workbook - xlsx = tmp_path / "stock.xlsx" - wb = Workbook() - wb.active.append(["sku", "qty"]) - wb.save(xlsx) - wb.close() + _write_inventory_xlsx(xlsx, "AWSDU") source = build_rpa_inventory_source("DSV360_AWSDU") with app.app_context(): @@ -136,23 +195,23 @@ def test_expired_snapshot_not_reused(app, tmp_path): inv.expires_at = snapshot_expires_at(inv.exported_at) db.session.commit() assert not is_snapshot_fresh(inv) - assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU") is None + assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") is None def test_link_snapshot_writes_audit_fields(app, tmp_path): """任务与快照 link 应写入 link_reason 与 audit_payload。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - from openpyxl import Workbook - xlsx = tmp_path / "stock.xlsx" - wb = Workbook() - wb.active.append(["sku", "qty"]) - wb.save(xlsx) - wb.close() + _write_inventory_xlsx(xlsx, "AWSDU") with app.app_context(): - task = ShippingTask(task_no="SN-SNAPSHOT-LINK", source_type="manual", process_status="waiting_inventory") + task = _task_with_inventory_source( + "SN-SNAPSHOT-LINK", + source_code="DSV360_AWSDU", + source_type="dsv360", + site_id="AWSDU", + ) db.session.add(task) db.session.commit() @@ -163,5 +222,6 @@ def test_link_snapshot_writes_audit_fields(app, tmp_path): assert link is not None assert link.link_reason == "reuse_latest" - assert link.matched_warehouse_id == "AWSDU" + assert link.matched_site_id == "AWSDU" + assert link.matched_source_code == "DSV360_AWSDU" assert link.audit_payload_json["source_code"] == "DSV360_AWSDU" diff --git a/backend/tests/test_shipping_notice_inventory_source_gate.py b/backend/tests/test_shipping_notice_inventory_source_gate.py new file mode 100644 index 00000000..037b8e08 --- /dev/null +++ b/backend/tests/test_shipping_notice_inventory_source_gate.py @@ -0,0 +1,1045 @@ +""" +tests/test_shipping_notice_inventory_source_gate.py + +用途:库存源门禁专项测试,覆盖 confirm_parse 绕过、RPA 回调拒绝、身份不匹配等核心分支。 +""" + +from __future__ import annotations + +from io import BytesIO + +import pytest +from openpyxl import Workbook + +from app import db +from app.models import ShippingBatch, ShippingInventoryFile, ShippingTask, ShippingTaskInventoryLink +from app.services.shipping_notice.constants import PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF +from app.services.shipping_notice.decision_workflow import submit_decision +from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source, rpa_report_inventory +from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable +from app.services.shipping_notice.inventory_source_rules import ( + adjudicate_inventory_source, + confirm_inventory_source_by_code, +) +from app.services.shipping_notice.inventory_workflow import ( + apply_inventory_mapping, + get_inventory_schema_preview, + parse_inventory, + upload_inventory_file, +) +from tests.conftest import ( + inventory_csv_with_warehouse, + inventory_xlsx_with_warehouse, + rpa_callback_payload, + seed_rpa_inventory_trigger, + seed_task_inventory_source, +) + + +def _minimal_inventory_xlsx(*, warehouse_id: str = "AWSDU") -> BytesIO: + return inventory_xlsx_with_warehouse(warehouse_id) + + +class _FakeUpload: + def __init__(self, buf: BytesIO, filename: str = "inventory.xlsx"): + self._buf = buf + self.filename = filename + + def save(self, path: str) -> None: + with open(path, "wb") as handle: + handle.write(self._buf.getvalue()) + + +@pytest.mark.inventory_source_gate +def test_confirm_parse_blocked_when_inventory_source_unstable(app): + """普通 confirm_parse 不得绕过库存源门禁。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CONFIRM-PARSE", + source_type="pdf", + process_status="pending_review", + review_status="parse_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) + db.session.refresh(task) + + assert result["status"] == "needs_human" + assert task.process_status == "pending_review" + assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_rejected_when_inventory_source_unstable(app, tmp_path): + """RPA 单任务回调在库存源未稳定时必须拒绝入库。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "inventory_gate.xlsx" + sample.write_bytes(b"PK\x03\x04") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-RPA-CB", + source_type="pdf", + process_status="waiting_inventory", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory({ + "task_id": task.task_no, + "status": "success", + "file_path": str(sample), + "source_code": "DSV360_AWSDU", + "site_id": "AWSDU", + "warehouse_id": "AWSDU", + "run_no": "RUN-STALE", + }) + assert result["status"] == "failed" + assert task.inventory_lines_json is None + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_rejects_mismatched_source_code(app, tmp_path): + """RPA 回调 source_code 与任务不一致时必须拒绝。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "inventory_mismatch.xlsx" + sample.write_bytes(b"PK\x03\x04") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-RPA-MISMATCH", + source_type="pdf", + process_status="waiting_inventory", + lines_json=[{"sku": "A001", "qty": 1}], + ship_to="Dublin", + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-MISMATCH") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory(rpa_callback_payload( + task, + sample, + run_no="RUN-MISMATCH", + ) | {"source_code": "DSV360_AWSBI"}) + assert result["status"] == "failed" + + +def test_confirm_inventory_source_tool_route_exists(app, client): + """OpenAPI 声明的 confirm_inventory_source 路由必须可访问。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" + app.config["INTEGRATION_API_KEY"] = "test-integration-key" + task = ShippingTask( + task_no="SN-ROUTE-CONFIRM-SRC", + source_type="pdf", + process_status="pending_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + res = client.post( + "/api/shipping-notice/tools/confirm_inventory_source", + headers={ + "Content-Type": "application/json", + "X-Integration-Key": "test-integration-key", + }, + json={"task_id": "SN-ROUTE-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, + ) + assert res.status_code == 200 + body = res.get_json() + assert body["status"] in {"ok", "needs_human", "running"} + + +@pytest.mark.inventory_source_gate +def test_crane_task_rpa_source_includes_dynamic_warehouse(app): + """Crane 任务级 RPA source 必须携带动态库位。""" + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CRANE-RPA-SRC", + source_type="pdf", + process_status="parsed", + ship_to="TZR2", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="CRANE") + db.session.add(task) + db.session.commit() + + source = task_rpa_inventory_source(task) + assert source is not None + assert source["warehouse_id"] == "TZR2" + assert source["site_id"] == "CRANE" + assert source["query"]["warehouse_code"] == "TZR2" + + +@pytest.mark.inventory_source_gate +def test_confirm_inventory_source_records_user_id(app, tmp_path, monkeypatch): + """人工确认应记录真实 user_id,且与 RPA 触发解耦。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", + lambda: False, + ) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-USER-CONFIRM", + source_type="pdf", + process_status="pending_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + step_payload_json={ + "inventory_source_resolution": { + "status": "unresolved", + "candidates": [{"source_code": "DSV360_AWSDU", "display_name": "Dublin"}], + } + }, + ) + db.session.add(task) + db.session.commit() + + result = confirm_inventory_source({ + "task_id": task.task_no, + "source_code": "DSV360_AWSDU", + "_trusted_user_id": 42, + }) + db.session.refresh(task) + + assert result["status"] == "ok" + assert task.inventory_source_status == "user_confirmed" + assert task.inventory_source_confirmed_by == 42 + assert task.inventory_source_confirmed_at is not None + assert is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_config_version_change_invalidates_stable_source(app): + """配置版本变化后,旧确认不得继续视为稳定。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CFG-VER", + source_type="pdf", + process_status="parsed", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + task.inventory_source_config_version = "stale-version" + db.session.add(task) + db.session.commit() + + assert not is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_inventory_tools_blocked_without_stable_source(app, tmp_path): + """upload/parse/preview/mapping 在库存源未稳定时不得推进库存阶段。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-INV-TOOLS", + source_type="pdf", + process_status="waiting_inventory", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + upload_result = upload_inventory_file(task.task_no, _FakeUpload(_minimal_inventory_xlsx())) + assert upload_result["status"] == "needs_human" + + parse_result = parse_inventory({"task_id": task.task_no, "use_uploaded_file": True}) + assert parse_result["status"] == "needs_human" + + preview_result = get_inventory_schema_preview({"task_id": task.task_no}) + assert preview_result["status"] == "needs_human" + + mapping_result = apply_inventory_mapping({ + "task_id": task.task_no, + "map_json": {"sku": "SKU", "qty": "Qty"}, + }) + assert mapping_result["status"] == "needs_human" + assert ShippingInventoryFile.query.count() == 0 + + +@pytest.mark.inventory_source_gate +def test_user_can_confirm_candidate_not_in_auto_top_match(app): + """自动未命中时,用户仍可选择启用配置中的正式库存源。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-USER-PICK", + source_type="pdf", + process_status="pending_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + ship_to="UnknownCity", + lines_json=[{"sku": "A001", "qty": 1}], + step_payload_json={ + "inventory_source_resolution": { + "status": "unresolved", + "candidates": [{"source_code": "DSV360_AWSDU"}], + } + }, + ) + db.session.add(task) + db.session.commit() + + adjudication = confirm_inventory_source_by_code(task, "DSV360_AWSCV") + assert adjudication.status == "user_confirmed" + assert adjudication.source_code == "DSV360_AWSCV" + + +@pytest.mark.inventory_source_gate +def test_site_level_source_requires_explicit_warehouse_id(app): + """站点级 DSV 须在配置与任务上同时具备 warehouse_id 才视为稳定。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-SITE-WH", + source_type="pdf", + process_status="parsed", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + assert task.inventory_warehouse_id == "AWSDU" + db.session.add(task) + db.session.commit() + + assert is_inventory_source_stable(task) + + task.inventory_warehouse_id = None + db.session.commit() + assert not is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_legacy_without_routing_fingerprint_is_not_stable(app): + """无路由指纹的历史确认不得绕过门禁。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-NO-FP", + source_type="pdf", + process_status="parsed", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + task.inventory_routing_fingerprint = None + db.session.add(task) + db.session.commit() + + assert not is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_missing_warehouse_when_config_requires_it_is_not_stable(app): + """子仓级库存源配置要求 warehouse_id 时,任务缺库位不得视为稳定。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-NO-WH", + source_type="pdf", + process_status="parsed", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSBI_BYAWSATL01") + task.inventory_warehouse_id = None + db.session.add(task) + db.session.commit() + + assert not is_inventory_source_stable(task) + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_leaves_no_snapshot_when_identity_rejected(app, tmp_path): + """身份不一致时不得遗留 ready 库存快照。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "inventory_orphan.xlsx" + sample.write_bytes(b"PK\x03\x04") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-RPA-ORPHAN", + source_type="pdf", + process_status="waiting_inventory", + lines_json=[{"sku": "A001", "qty": 1}], + ship_to="Dublin", + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-ORPHAN") + db.session.add(task) + db.session.commit() + before = ShippingInventoryFile.query.count() + + result = rpa_report_inventory(rpa_callback_payload( + task, + sample, + run_no="RUN-ORPHAN", + ) | {"source_code": "DSV360_AWSBI"}) + after = ShippingInventoryFile.query.count() + + assert result["status"] == "failed" + assert after == before + + +@pytest.mark.inventory_source_gate +def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path): + """批次上传只绑定与上传票库存源一致的任务,禁止跨源共用快照。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + with app.app_context(): + batch = ShippingBatch(batch_no="SB-GATE-CROSS", file_count=2) + owner = ShippingTask( + task_no="SN-GATE-OWNER", + batch=batch, + source_type="manual", + process_status="waiting_inventory", + lines_json=[{"sku": "A001", "qty": 1}], + batch_index=1, + batch_total=2, + ) + other = ShippingTask( + task_no="SN-GATE-OTHER", + batch=batch, + source_type="manual", + process_status="waiting_inventory", + lines_json=[{"sku": "B001", "qty": 1}], + batch_index=2, + batch_total=2, + ) + seed_task_inventory_source(owner, source_code="DSV360_AWSDU") + seed_task_inventory_source(other, source_code="DSV360_AWSAMS") + db.session.add_all([batch, owner, other]) + db.session.commit() + + result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx())) + assert result["status"] == "ok" + + owner_links = ShippingTaskInventoryLink.query.filter_by(task_id=owner.id, is_active=True).count() + other_links = ShippingTaskInventoryLink.query.filter_by(task_id=other.id, is_active=True).count() + assert owner_links == 1 + assert other_links == 0 + + +@pytest.mark.inventory_source_gate +def test_crane_auto_adjudication_resolves_warehouse_from_alias(app): + """Crane 自动裁决应解析出库位并满足四元组稳定条件。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CRANE-AUTO", + source_type="pdf", + process_status="parsed", + ship_to="TZR2 footprint", + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + adjudication = adjudicate_inventory_source(task) + assert adjudication.status == "resolved" + assert adjudication.source_code == "CRANE" + assert adjudication.site_id == "CRANE" + assert adjudication.warehouse_id == "TZR2" + + +@pytest.mark.inventory_source_gate +def test_crane_user_confirm_and_gate_stable(app): + """Crane 人工确认后应写入完整身份并通过门禁。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CRANE-USER", + source_type="pdf", + process_status="pending_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + ship_to="TZR3", + lines_json=[{"sku": "A001", "qty": 1}], + ) + db.session.add(task) + db.session.commit() + + adjudication = confirm_inventory_source_by_code(task, "CRANE") + assert adjudication.status == "user_confirmed" + assert adjudication.warehouse_id == "TZR3" + + from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + + apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=7) + db.session.commit() + assert is_inventory_source_stable(task) + assert task.inventory_source_confirmed_by == 7 + + +@pytest.mark.inventory_source_gate +def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch): + """低置信度 + 未命中库存源:先确认库存源,再确认解析,最后才能进入库存准备。""" + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", + lambda: False, + ) + monkeypatch.setattr( + "app.services.shipping_notice.decision_workflow.start_task_orchestrator", + lambda task_no: False, + ) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-LOW-CONF-SEQ", + source_type="pdf", + process_status="pending_review", + pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, + review_status="parse_review", + parse_confidence=0.4, + ship_to="UnknownCity", + lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}], + step_payload_json={"pending_parse_review_after_source": True}, + ) + db.session.add(task) + db.session.commit() + + blocked = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) + assert blocked["status"] == "needs_human" + + source_result = confirm_inventory_source({ + "task_id": task.task_no, + "source_code": "DSV360_AWSDU", + "_trusted_user_id": 11, + }) + db.session.refresh(task) + assert source_result["status"] == "needs_human" + assert source_result.get("checkpoint") == "parse_review" + assert task.pending_human_reason == PH_LOW_CONF + assert is_inventory_source_stable(task) + + parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) + db.session.refresh(task) + assert parse_result["status"] in {"ok", "running"} + assert is_inventory_source_stable(task) + assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED + + +@pytest.mark.inventory_source_gate +def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch): + """人工上传身份绑定失败时不应遗留库存文件或数据库记录。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + monkeypatch.setattr( + "app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task", + lambda *args, **kwargs: None, + ) + + with app.app_context(): + batch = ShippingBatch(batch_no="SB-GATE-UPLOAD-FAIL", file_count=2) + owner = ShippingTask( + task_no="SN-GATE-UPLOAD-OWNER", + batch=batch, + source_type="manual", + process_status="waiting_inventory", + lines_json=[{"sku": "A001", "qty": 1}], + batch_index=1, + batch_total=2, + ) + other = ShippingTask( + task_no="SN-GATE-UPLOAD-OTHER", + batch=batch, + source_type="manual", + process_status="waiting_inventory", + lines_json=[{"sku": "B001", "qty": 1}], + batch_index=2, + batch_total=2, + ) + seed_task_inventory_source(owner, source_code="DSV360_AWSDU") + seed_task_inventory_source(other, source_code="DSV360_AWSAMS") + db.session.add_all([batch, owner, other]) + db.session.commit() + + before_files = ShippingInventoryFile.query.count() + result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx())) + after_files = ShippingInventoryFile.query.count() + + assert result["status"] == "failed" + assert after_files == before_files + assert not list((tmp_path / "shipping").rglob("*.xlsx")) + + +def _evaluate_legacy_backfill( + *, + source_code: str, + site_id: str | None, + warehouse_id: str | None, + resolution_status: str | None = None, + routing_fingerprint: str | None = None, +) -> dict[str, str | None]: + """镜像迁移回填规则,供迁移专项测试断言。""" + status = "resolved" + method = "legacy_migrated" + code = source_code + if resolution_status == "ambiguous": + status = "ambiguous" + elif resolution_status == "user_confirmed": + status = "user_confirmed" + if not site_id and warehouse_id: + return { + "source_code": None, + "status": "unresolved", + "method": None, + "config_version": "legacy-unverified", + } + if not site_id or not warehouse_id: + return { + "source_code": None, + "status": "unresolved", + "method": None, + "config_version": "legacy-unverified", + } + if not routing_fingerprint: + return { + "source_code": code, + "status": "unresolved", + "method": None, + "config_version": "legacy-unverified", + } + return { + "source_code": code, + "status": status, + "method": "legacy_migrated", + "config_version": "legacy-unverified", + } + + +@pytest.mark.inventory_source_gate +def test_migration_backfill_dual_empty_identity_goes_unresolved(): + """历史 site/warehouse 双空记录应进入 unresolved 而非 resolved。""" + result = _evaluate_legacy_backfill( + source_code="DSV360_AWSDU", + site_id=None, + warehouse_id=None, + ) + assert result["status"] == "unresolved" + assert result["source_code"] is None + assert result["config_version"] == "legacy-unverified" + + +@pytest.mark.inventory_source_gate +def test_migration_backfill_without_fingerprint_requires_review(): + """历史无路由指纹不得标记为当前配置已验证。""" + result = _evaluate_legacy_backfill( + source_code="DSV360_AWSDU", + site_id="AWSDU", + warehouse_id="AWSDU", + routing_fingerprint=None, + ) + assert result["status"] == "unresolved" + assert result["config_version"] == "legacy-unverified" + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_rejects_excel_warehouse_mismatch(app, tmp_path): + """任务库位 TZR2 但 Excel Warehouse ID=TZR3 时必须拒绝入库。""" + from openpyxl import Workbook + + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + sample = inventory_drop / "crane_wrong_wh.xlsx" + wb = Workbook() + wb.active.append(["Warehouse ID", "SKU", "Qty"]) + wb.active.append(["TZR3", "A001", 1]) + wb.save(sample) + wb.close() + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-EXCEL-WH", + source_type="pdf", + process_status="waiting_inventory", + ship_to="TZR2 footprint", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="CRANE") + seed_rpa_inventory_trigger(task, run_no="RUN-EXCEL-WH") + db.session.add(task) + db.session.commit() + before = ShippingInventoryFile.query.count() + + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-EXCEL-WH")) + after = ShippingInventoryFile.query.count() + + assert result["status"] == "failed" + assert after == before + + +@pytest.mark.inventory_source_gate +def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path): + """人工上传错误 Warehouse ID 时必须拒绝并清理文件。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-UPLOAD-WH", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.commit() + + result = upload_inventory_file( + task.task_no, + _FakeUpload(inventory_xlsx_with_warehouse("TZR3")), + ) + assert result["status"] == "failed" + assert ShippingInventoryFile.query.count() == 0 + assert not list((tmp_path / "shipping").rglob("*.xlsx")) + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_rejects_mismatched_warehouse_id(app, tmp_path): + """单任务回调 warehouse_id 与任务不一致时必须拒绝。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "inventory_wh_mismatch.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-RPA-WH", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-WH-MISMATCH") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory(rpa_callback_payload( + task, + sample, + run_no="RUN-WH-MISMATCH", + ) | {"warehouse_id": "TZR3"}) + assert result["status"] == "failed" + + +@pytest.mark.inventory_source_gate +def test_rpa_callback_rejects_stale_run_no(app, tmp_path): + """旧 run_no 回调不得覆盖当前任务库存轮次。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "inventory_stale_run.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-STALE-RUN", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory(rpa_callback_payload( + task, + sample, + run_no="RUN-OLD", + )) + assert result["status"] == "failed" + assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch" + + +@pytest.mark.inventory_source_gate +def test_scheduled_batch_unknown_source_creates_no_ready_snapshot(app, tmp_path): + """未知/禁用 source 的定时批量回调不得创建 ready 快照。""" + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "scheduled.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + result = rpa_report_inventory_batch({ + "run_no": "RUN-UNKNOWN-SRC", + "trigger_type": "scheduled", + "results": [{ + "source_code": "UNKNOWN_SOURCE", + "warehouse_id": "AWSDU", + "status": "success", + "success": True, + "file_path": str(sample), + }], + }) + after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + + assert result["status"] == "ok" + assert result["result_status"] == "failed" + assert after == before + assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source" + + +@pytest.mark.inventory_source_gate +def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path): + """CSV 上传应保留 .csv 后缀并通过 Warehouse ID 身份校验。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-UPLOAD-CSV", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.commit() + + result = upload_inventory_file( + task.task_no, + _FakeUpload(inventory_csv_with_warehouse("AWSDU"), filename="inventory.csv"), + ) + assert result["status"] != "failed" + csv_files = list((tmp_path / "shipping").rglob("inventory.csv")) + assert len(csv_files) == 1 + assert ShippingInventoryFile.query.count() == 1 + + +@pytest.mark.inventory_source_gate +def test_manual_upload_rejects_xls_extension(app, tmp_path): + """.xls 上传应在入口明确拒绝,而非误报 Warehouse 缺失。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-UPLOAD-XLS", + source_type="pdf", + process_status="waiting_inventory", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.commit() + + result = upload_inventory_file( + task.task_no, + _FakeUpload(_minimal_inventory_xlsx(), filename="inventory.xls"), + ) + assert result["status"] == "failed" + assert ShippingInventoryFile.query.count() == 0 + + +@pytest.mark.inventory_source_gate +def test_rpa_success_rejected_without_active_trigger(app, tmp_path): + """无 inventory_rpa_triggered 事件时,成功回调不得入库。""" + inventory_drop = tmp_path / "drop" + inventory_drop.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + sample = inventory_drop / "no_trigger.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-NO-TRIGGER", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + db.session.add(task) + db.session.commit() + before = ShippingInventoryFile.query.count() + + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-FAKE")) + after = ShippingInventoryFile.query.count() + + assert result["status"] == "failed" + assert (result.get("data") or {}).get("run_no_error") == "no_active_trigger" + assert after == before + + +@pytest.mark.inventory_source_gate +def test_rpa_failed_rejected_stale_run_no(app, tmp_path): + """旧 run_no 的 failed 回调不得覆盖当前等待轮次。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-STALE-FAIL", + source_type="pdf", + process_status="waiting_inventory", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1}], + ) + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT-FAIL") + db.session.add(task) + db.session.commit() + + result = rpa_report_inventory({ + "task_id": task.task_no, + "status": "failed", + "success": False, + "run_no": "RUN-OLD-FAIL", + "error_message": "stale callback", + }) + db.session.refresh(task) + + assert result["status"] == "failed" + assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch" + assert task.error_message is None + + +@pytest.mark.inventory_source_gate +def test_scheduled_crane_batch_accepts_dynamic_warehouse(app, tmp_path): + """CRANE 动态库位定时回调应接受 Worker 回传的 TZR/TZR2/TZR3。""" + from app.models import ShippingInventoryFile + from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item + + drop_dir = tmp_path / "drop" + drop_dir.mkdir() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + sample = drop_dir / "crane_tzr2.xlsx" + with open(sample, "wb") as handle: + handle.write(inventory_xlsx_with_warehouse("TZR2").getvalue()) + + with app.app_context(): + before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + result = rpa_report_inventory_batch({ + "run_no": "RUN-CRANE-TZR2", + "trigger_type": "scheduled", + "results": [scheduled_rpa_batch_item( + "CRANE", + warehouse_id="TZR2", + success=True, + file_path=str(sample), + )], + }) + after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() + + assert result["status"] == "ok" + assert result["success_count"] == 1 + created = (result.get("data") or {}).get("created") or [] + assert created and created[0].get("warehouse_id") == "TZR2" + assert after == before + 1 + snap = ShippingInventoryFile.query.filter_by( + rpa_run_no="RUN-CRANE-TZR2", + source_code="CRANE", + warehouse_id="TZR2", + ).first() + assert snap is not None + assert snap.site_id == "CRANE" + + +@pytest.mark.inventory_source_gate +def test_inventory_header_skips_single_cell_warehouse_title(app, tmp_path): + """仅含 Warehouse 标题的单单元格行不得被误判为表头。""" + from io import BytesIO + + from openpyxl import Workbook + + from app.services.shipping_notice.inventory_file_identity import ( + extract_warehouse_ids_from_inventory_excel, + ) + + buf = BytesIO() + wb = Workbook() + ws = wb.active + ws.append(["Warehouse"]) + ws.append(["Warehouse ID", "SKU", "Qty"]) + ws.append(["TZR2", "A001", 1]) + wb.save(buf) + buf.seek(0) + + path = tmp_path / "title_then_header.xlsx" + path.write_bytes(buf.getvalue()) + found = extract_warehouse_ids_from_inventory_excel(path) + assert found == {"TZR2"} + + +@pytest.mark.inventory_source_gate +def test_conflicted_inventory_source_status_persists(app): + """自动裁决 conflicted 状态须能写入数据库,不被 CHECK 约束拒绝。""" + from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication + + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-CONFLICTED", + process_status="pending_review", + customer_code="TEST", + ) + db.session.add(task) + db.session.flush() + apply_inventory_source_adjudication( + task, + InventorySourceAdjudication( + status="conflicted", + config_version="v1", + routing_fingerprint="fp-conflict", + candidates=[], + conflicts=["matched_conflicting_rules"], + reason="matched_conflicting_rules", + ), + ) + db.session.commit() + db.session.refresh(task) + assert task.inventory_source_status == "conflicted" + + +@pytest.mark.inventory_source_gate +def test_csv_inventory_parse_reads_beyond_preview_limit(app, tmp_path): + """CSV 全量解析不得静默截断为 10,000 行。""" + from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel + + path = tmp_path / "large.csv" + lines = ["Warehouse ID,SKU,Qty Available"] + lines.extend(f"AWSDU,SKU-{i},1" for i in range(10_050)) + path.write_text("\n".join(lines), encoding="utf-8") + + with app.app_context(): + rows = parse_inventory_excel(path) + assert len(rows) == 10_050 diff --git a/backend/tests/test_shipping_notice_inventory_sources_config.py b/backend/tests/test_shipping_notice_inventory_sources_config.py index 78c00085..d8fe37f7 100644 --- a/backend/tests/test_shipping_notice_inventory_sources_config.py +++ b/backend/tests/test_shipping_notice_inventory_sources_config.py @@ -21,7 +21,7 @@ def test_inventory_sources_yaml_loads(app): assert source is not None assert source["source_type"] == "dsv360" assert source["site_id"] == "AWSDU" - assert source["warehouse_id"] == "" + assert source["warehouse_id"] == "AWSDU" assert source["query"]["program_label"] @@ -100,15 +100,40 @@ sources: reload_inventory_sources_config() -def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app): - """Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。""" +def test_dsv_source_requires_warehouse_id(app, tmp_path): + """DSV 源必须显式配置 warehouse_id。""" + bad = tmp_path / "bad_sources.yaml" + bad.write_text( + """ +version: 1 +sources: +- source_code: DSV360_BAD + enabled: true + source_type: dsv360 + site_id: AWSBI + entry_url: http://x + navigation: {} + parameters: [] + """, + encoding="utf-8", + ) + app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad) + with app.app_context(): + with pytest.raises(InventorySourceConfigError, match="warehouse_id is required"): + reload_inventory_sources_config() + + +def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app): + """Crane 源须配置 site_id 与 match_aliases,库位由订单别名解析。""" with app.app_context(): reload_inventory_sources_config() payload = build_rpa_inventory_source("CRANE") assert payload is not None assert payload["source_type"] == "crane_footprint" - assert payload["site_id"] == "" + assert payload["site_id"] == "CRANE" assert payload["warehouse_id"] == "" + assert payload["warehouse_resolution"] == "alias_match" + assert payload.get("allowed_warehouse_ids") == ["TZR", "TZR2", "TZR3"] assert payload["parameters"] == [] assert payload["navigation"]["download_mode"] == "scheduled_report" @@ -123,3 +148,46 @@ def test_match_aliases_available_via_list(app): assert "CRANE" in codes awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_")) assert awsbi_count == 25 + + +def test_inventory_sources_cache_refreshes_when_content_changes_with_same_mtime(app, tmp_path, monkeypatch): + """配置内容变化但 mtime 不变时,缓存仍须刷新。""" + import os + + from app.services.shipping_notice import inventory_sources as mod + + cfg = tmp_path / "sources.yaml" + cfg.write_text( + """ +version: 1 +sources: +- source_code: CACHE_TEST + enabled: true + source_type: dsv360 + site_id: S1 + warehouse_id: W1 + entry_url: http://example.com + navigation: {} + parameters: [] + """, + encoding="utf-8", + ) + fixed_mtime = 1_700_000_000.0 + os.utime(cfg, (fixed_mtime, fixed_mtime)) + app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(cfg) + + with app.app_context(): + mod._CONFIG_CACHE = None + mod._CONFIG_PATH = None + mod._CONFIG_RAW_DIGEST = None + first = mod.reload_inventory_sources_config() + assert first["sources"]["CACHE_TEST"]["warehouse_id"] == "W1" + + cfg.write_text( + cfg.read_text(encoding="utf-8").replace("warehouse_id: W1", "warehouse_id: W2"), + encoding="utf-8", + ) + os.utime(cfg, (fixed_mtime, fixed_mtime)) + second = mod.reload_inventory_sources_config() + assert second["sources"]["CACHE_TEST"]["warehouse_id"] == "W2" + assert second is not first diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index c69fb56e..4e149be9 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -6,6 +6,7 @@ import pytest from app import db from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent from app.services.shipping_notice.match import match_notice_lines +from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source def _tool_headers(app): @@ -17,6 +18,23 @@ def _tool_headers(app): } +def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None: + """测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。""" + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "AWS", + "ship_to": "Dublin", + "lines": [{"sku": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" @@ -389,6 +407,7 @@ def test_openapi_spec_public(app, client): map_json_schema = apply_mapping["properties"]["map_json"] assert map_json_schema["type"] == "string" assert "JSON 字符串" in map_json_schema["description"] + assert "/tools/confirm_inventory_source" in spec["paths"] submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"] assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"] spec_text = str(spec) @@ -410,6 +429,30 @@ def test_openapi_spec_public(app, client): assert "按钮由 HXOPS 前端渲染" in submit_desc +def test_confirm_inventory_source_route_returns_json(app, client): + """confirm_inventory_source HTTP 路由必须存在且可调用。""" + headers = _tool_headers(app) + with app.app_context(): + task = ShippingTask( + task_no="SN-HTTP-CONFIRM-SRC", + source_type="manual", + process_status="pending_review", + pending_human_reason="inventory_source_unresolved", + ship_to="Dublin", + lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}], + ) + db.session.add(task) + db.session.commit() + + res = client.post( + "/api/shipping-notice/tools/confirm_inventory_source", + headers=headers, + json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, + ) + assert res.status_code == 200 + assert res.get_json()["status"] in {"ok", "needs_human", "running"} + + def test_static_openapi_snapshot_contains_shipping_contract_keywords(): """静态 OpenAPI 快照应同步最新推进约束,避免 Dify 导入旧版说明。""" spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json" @@ -495,6 +538,7 @@ def test_parse_inventory_empty_needs_human(app, client): json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] + _parse_notice_for_stable_inventory_source(client, headers, task_id) res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, @@ -620,11 +664,16 @@ def test_match_inventory_requires_reservation_id(app, client): "task_id": task_id, "structured": { "customer_name": "ACME", - "lines": [{"sku": "A001", "qty": 1, "uom": "EA"}], + "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}], "confidence": 0.95, }, }, ) + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}] + db.session.commit() client.post( "/api/shipping-notice/tools/ensure_inventory", headers=headers, @@ -704,20 +753,38 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): ) task_id = create_res.get_json()["task_id"] + from app import db + from tests.conftest import seed_task_inventory_source + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).first() + assert task is not None + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + seed_rpa_inventory_trigger(task, run_no="RUN-TOOLS-CB") + db.session.commit() + from openpyxl import Workbook inv_file = drop / "stock.xlsx" wb = Workbook() ws = wb.active - ws.append(["料号", "可用数量"]) - ws.append(["A001", 20]) + ws.append(["Warehouse ID", "料号", "可用数量"]) + ws.append(["AWSDU", "A001", 20]) wb.save(inv_file) wb.close() cb_res = client.post( "/api/shipping-notice/rpa/inventory-ready", headers=headers, - json={"task_no": task_id, "success": True, "file_path": str(inv_file)}, + json={ + "task_no": task_id, + "success": True, + "file_path": str(inv_file), + "run_no": "RUN-TOOLS-CB", + "source_code": "DSV360_AWSDU", + "site_id": "AWSDU", + "warehouse_id": "AWSDU", + }, ) assert cb_res.status_code == 200 data = cb_res.get_json() @@ -890,8 +957,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path): buf = BytesIO() wb = Workbook() ws = wb.active - ws.append(["AWS Sku", "COM ID", "Qty Available"]) - ws.append(["10-40594-001", "AWS-311", 5]) + ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]) + ws.append(["AWSDU", "10-40594-001", "AWS-311", 5]) wb.save(buf) wb.close() buf.seek(0) @@ -909,7 +976,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path): assert upload_data["status"] == "ok" assert upload_data.get("checkpoint") == "map_infer" preview = upload_data["data"]["schema_preview"] - assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"] + assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"] assert preview["suggested_mapping"]["sku"] == "AWS Sku" apply_res = client.post( @@ -941,6 +1008,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_ from app.models import ShippingBatch, ShippingTaskInventoryLink from app.services.shipping_notice import inventory_file_store + from tests.conftest import seed_task_inventory_source headers = _tool_headers(app) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") @@ -976,15 +1044,16 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_ batch_index=2, batch_total=2, ) + seed_task_inventory_source(pending, source_code="DSV360_AWSDU") db.session.add_all([batch, completed, pending]) db.session.commit() buf = BytesIO() wb = Workbook() ws = wb.active - ws.append(["SKU", "Reservation ID", "Available Qty"]) - ws.append(["A001", "R-1", 10]) - ws.append(["A002", "R-2", 10]) + ws.append(["Warehouse ID", "SKU", "Reservation ID", "Available Qty"]) + ws.append(["AWSDU", "A001", "R-1", 10]) + ws.append(["AWSDU", "A002", "R-2", 10]) wb.save(buf) wb.close() buf.seek(0) @@ -1019,6 +1088,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path): json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] + _parse_notice_for_stable_inventory_source(client, headers, task_id) from io import BytesIO @@ -1026,8 +1096,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path): wb = Workbook() ws = wb.active - ws.append(["AWS Sku", "COM ID", "Qty Available"]) - ws.append(["504-010213-001", "1000140351", 5]) + ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]) + ws.append(["AWSDU", "504-010213-001", "1000140351", 5]) buf = BytesIO() wb.save(buf) buf.seek(0) @@ -1067,6 +1137,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path): json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] + _parse_notice_for_stable_inventory_source(client, headers, task_id) missing = client.post( "/api/shipping-notice/tools/get_inventory_schema_preview", @@ -1086,6 +1157,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path): json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] + _parse_notice_for_stable_inventory_source(client, headers, task_id) from io import BytesIO @@ -1094,8 +1166,8 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path): buf = BytesIO() wb = Workbook() ws = wb.active - ws.append(["Part No", "Resv", "On Hand"]) - ws.append(["SKU-99", "R-1", 12]) + ws.append(["Warehouse ID", "Part No", "Resv", "On Hand"]) + ws.append(["AWSDU", "SKU-99", "R-1", 12]) wb.save(buf) wb.close() buf.seek(0) @@ -1143,7 +1215,8 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client): "task_id": task_id, "structured": { "customer_name": "Wistron", - "lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}], + "ship_to": "Dublin", + "lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}], "confidence": 0.95, }, }, @@ -1437,7 +1510,11 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, @pytest.mark.auto_rpa -def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path): +def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path, monkeypatch): + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" inventory_drop = tmp_path / "inventory_drop" @@ -1478,6 +1555,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, } } + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + task.process_status = "parsed" db.session.commit() retry_res = client.post( @@ -1544,6 +1623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, } } + seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add( ShippingTaskEvent( task_id=task.id, @@ -1568,7 +1648,11 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt @pytest.mark.auto_rpa -def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path): +def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch): + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + lambda *args, **kwargs: None, + ) from datetime import datetime, timedelta from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED @@ -1602,6 +1686,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, } } + seed_task_inventory_source(task, source_code="DSV360_AWSDU") + task.process_status = "parsed" base_time = datetime.utcnow() - timedelta(minutes=5) for idx in range(3): db.session.add( @@ -1681,6 +1767,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, } } + seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add( ShippingTaskEvent( task_id=task.id, @@ -1849,6 +1936,7 @@ def test_parse_inventory_rejects_oversized_text(app, client): json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] + _parse_notice_for_stable_inventory_source(client, headers, task_id) res = client.post( "/api/shipping-notice/tools/parse_inventory", diff --git a/docs/demand.md b/docs/demand.md index b4a2ae36..43d4e836 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -47,6 +47,15 @@ - **可靠性要求**:单次同步必须设置超时;超时或短时失败后,每隔 30 分钟自动重试 1 次,累计最多重试 3 次;若全部失败,继续保留上一版快照对外服务。 - **查询要求**:用户在 `固资管理` Agent 中发起查询时,优先查询本地快照;字段级条件优先匹配,`备注` 作为模糊检索补充;极少数无法覆盖的复杂场景可再回退实时 ERP 查询。 +### 3.x 货代发货通知库存源补充需求 + +- **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。 +- **自动匹配**:根据发货通知目的地/港口/仓库线索与 `shipping_inventory_sources.yaml` 规则自动 adjudicate;唯一命中则 `resolved` 并继续流程。 +- **人工确认**:无法唯一命中时进入 `inventory_source_review` 检查点,用户在聊天区选择或输入线索确认 `source_code`。 +- **硬阻断**:库存源未稳定(`resolved` / `user_confirmed`)时,RPA、库存匹配、Excel 生成、货代上传均不得执行。 +- **身份校验**:关联库存快照时校验 `source_code`、`site_id`、`warehouse_id` 与任务一致。 +- 技术方案见 [docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 + ### 3.1 本期范围 - 查询员工本人假期余额 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 3c9501e4..84b791bd 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -102,7 +102,7 @@ SN-20260529-A1B2C3D4 | 顺序 | 资料 | 格式 | 用途 | |------|------|------|------| | 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、SKU、数量、Reservation ID、单价、金额等 | -| 2 | **库存快照** | Excel(.xlsx / .xls / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 | +| 2 | **库存快照** | Excel(.xlsx / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 | | 3 | (可选)**货代发货模板** | 由 IT 配置 | 生成最终上传货代用的 Excel | **顺序要求**:须先完成发货通知解析并确认,再上传库存。若尚未有任务编号就上传库存 Excel,系统会提示您先提交发货通知。 diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md index 57d8ab5f..48c5e303 100644 --- a/docs/features/shipping-notice/inventory_source_plan.md +++ b/docs/features/shipping-notice/inventory_source_plan.md @@ -1,36 +1,65 @@ -# 发货通知库存源路由与 RPA Driver 方案 +# 发货通知库存源路由方案(订单解析阶段判定) ## 背景 -发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于“未查到库存”。 +发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于「未查到库存」。 + +历史上 `site_id`(如 `AWSBI`)与 `warehouse_id`(如 `BYAWSATL01`)曾被混用,导致发货 Excel 与 RPA 查询参数不一致。本方案将库存源判定前移到**订单解析阶段**,并以独立数据库字段持久化业务决策。 ## 设计原则 -- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段,不负责最终 RPA URL 决策。 -- HXOPS 负责标准化、规则匹配、唯一性判断、权限校验、人工确认和审计。 +- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段(目的地、港口、仓库线索等),**不负责**最终 RPA URL / source_code 决策。 +- HXOPS 在 `parse_notice` 阶段根据 YAML 配置做标准化、规则匹配、唯一性判断;唯一命中写入任务独立字段。 +- 用户人工确认时**只确认 `source_code`**;`site_id`、`warehouse_id` 由配置自动生成,禁止前端或 LLM 直写。 +- RPA、库存准备、匹配、Excel 生成、上传等后续步骤均通过 **inventory source gate** 硬阻断,未稳定(`resolved` / `user_confirmed`)不得继续。 - RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `source_type` 分发到不同 Driver。 -- 通用化范围是 trigger 协议、状态机、超时重试、回调、库存标准化;页面操作逻辑由不同 Driver 独立实现。 -- 用户对话可以做当前任务级临时覆盖;全局规则变更只能作为建议,需审核后生效。 -## MVP 范围 +## 判定时机与状态机 -第一版不改数据库结构,规则和源配置先放代码中,任务级上下文写入 `ShippingTask.step_payload_json`。 +### 何时判定 -MVP 包含: +1. **`parse_notice`**:解析结构化订单后,立即调用 `adjudicate_inventory_source()`。 +2. 唯一命中且配置完整 → `inventory_source_status=resolved`,任务可进入 `parsed`。 +3. 未命中 / 多命中 / 配置无效 / 路由指纹变更 → `pending_review`,`current_step=step2_parse_confirm`,`checkpoint=inventory_source_review`,`pending_human_reason=inventory_source_unresolved`。 +4. 用户在聊天区确认 `source_code` → `confirm_inventory_source` → `inventory_source_status=user_confirmed`,再推进至 `parsed` 并允许 RPA。 -- 解析 Dify 输出的目的地候选字段,并保存到任务 step payload。 -- 根据目的地/港口/仓库线索解析库存源。 -- 唯一命中时自动写入 `rpa_inventory_source`。 -- 无法命中或多命中时进入 `inventory_source_review` 人工检查点。 -- RPA trigger JSON 增加 `rpa_inventory_source`。 -- 后端测试覆盖 DSV 与 Crane 的基本路由。 +### 稳定状态 -暂不包含: +| status | 含义 | +| --- | --- | +| `resolved` | 规则自动唯一命中 | +| `user_confirmed` | 用户已确认 source_code | -- 后台规则管理页面。 -- 数据库规则表。 -- 批次级对话覆盖。 -- 全局规则建议审核流。 +其余状态(`unresolved`、`ambiguous`、`invalid`、`conflicted`)均视为不稳定,gate 阻断。 + +## 独立数据库字段(`shipping_tasks`) + +| 字段 | 说明 | +| --- | --- | +| `destination_*` | 目的地候选(城市、国家、港口等),供规则匹配 | +| `inventory_source_code` | 正式库存源编码,如 `DSV360_AWSDU` | +| `inventory_source_type` | `dsv360` / `crane_footprint` | +| `inventory_site_id` | DSV Program / Site(如 `AWSDU`) | +| `inventory_warehouse_id` | 具体仓库(如需要) | +| `inventory_source_status` | 判定状态 | +| `inventory_source_method` | `auto` / `user` | +| `inventory_source_config_version` | YAML 配置版本指纹 | +| `inventory_routing_fingerprint` | 路由输入指纹,变更时要求重确认 | + +`step_payload_json.inventory_source_resolution` 仅保留候选列表与诊断信息,**不作为** gate 真相源。 + +## 配置文件 + +路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`) + +每个 source 含: + +- `source_code`、`source_type`、`site_id`、`warehouse_id` +- `navigation`、`parameters`(RPA 填表) +- `match_aliases`:目的地/港口/仓库别名 +- `match`:加权评分规则(可选) + +新增 Warehouse **只改 YAML**,不改 Python。 ## Trigger 协议 @@ -69,19 +98,63 @@ Crane 示例: } ``` -## 初始路由规则 +## Gate 规则(硬阻断) -- `BISON`, `AWSBI` -> `DSV360_AWSBI` -- `CINCINNATI`, `CVG`, `AWSCV` -> `DSV360_AWSCV` -- `DUB`, `DUBLIN` -> `DSV360_AWSDU` -- `MOERDIJK`, `AMS`, `AWSAMS` -> `DSV360_AWSAMS` -- `USLCK`, `SALT LAKE CITY` -> `DSV360_AWSSL` -- `SINGAPORE`, `SG` -> `DSV360_AWSSG` -- `TZR`, `THAILAND` -> `CRANE_TZR` +以下步骤执行前调用 `assert_inventory_source_gate(task)`: + +- RPA 触发 / 重试 +- 库存快照 link / 映射 / 匹配 +- 发货 Excel 生成 +- 货代上传 + +库存快照 link 时额外做 **identity check**:`source_code`、`site_id`、`warehouse_id` 与任务字段一致,否则 `SHIPPING.INVENTORY_IDENTITY_MISMATCH`。 + +## 错误码(API) + +| code | 场景 | +| --- | --- | +| `SHIPPING.INVENTORY_SOURCE_UNRESOLVED` | 无法判定 | +| `SHIPPING.INVENTORY_SOURCE_AMBIGUOUS` | 多候选 | +| `SHIPPING.INVENTORY_SOURCE_INVALID` | 配置无效 | +| `SHIPPING.INVENTORY_SOURCE_CONFLICTED` | 判定冲突 | +| `SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED` | 需人工确认 | +| `SHIPPING.INVENTORY_SOURCE_CHANGED` | 路由变更需重确认 | +| `SHIPPING.INVENTORY_IDENTITY_MISMATCH` | 快照与任务不一致 | +| `SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED` | 通用 gate 阻断 | + +前端 i18n:`errors.codes.SHIPPING_INVENTORY_SOURCE_*`(点号转下划线)。 + +## 聊天区交互 + +- 检查点 `inventory_source_review` 展示候选按钮(携带 `source_code`)。 +- 用户可直接输入目的地线索(如 `Dublin`、`AWSDU`),前端匹配唯一候选后调用 `confirm_inventory_source`。 +- 动作:`confirm_inventory_source`、`retry_resolve_inventory_source`。 + +## 初始路由规则(示例) + +- `BISON`, `AWSBI` → `DSV360_AWSBI` +- `CINCINNATI`, `CVG`, `AWSCV` → `DSV360_AWSCV` +- `DUB`, `DUBLIN` → `DSV360_AWSDU` +- `MOERDIJK`, `AMS`, `AWSAMS` → `DSV360_AWSAMS` +- `USLCK`, `SALT LAKE CITY` → `DSV360_AWSSL` +- `SINGAPORE`, `SG` → `DSV360_AWSSG` +- `TZR`, `THAILAND` → `CRANE_TZR` + +完整列表以 YAML 为准。 + +## 相关代码 + +| 模块 | 路径 | +| --- | --- | +| 规则与指纹 | `services/shipping_notice/inventory_source_rules.py` | +| Gate | `services/shipping_notice/inventory_source_gate.py` | +| 解析集成 | `services/shipping_notice/task_workflow.py` | +| 确认 Tool | `services/shipping_notice/inventory_rpa_workflow.py` | +| 配置加载 | `services/shipping_notice/inventory_sources.py` | +| 迁移 | `migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py` | ## 后续演进 -- 将代码配置迁移到可维护规则表。 -- 增加管理员审核的规则变更建议。 -- RPA 侧实现 `dsv360` 与 `crane_footprint` Driver。 -- 导入库存时校验 source_code、warehouse/program 与任务期望是否一致。 +- 后台规则管理页面与审核流。 +- 批次级对话覆盖(当前仅任务级)。 +- 全局规则变更建议与审计。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 8eeb104b..a5823028 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -1440,7 +1440,7 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None): text = str(normalized_query or "").strip() if files: lower_names = " ".join(_file_name(f) for f in files) - if any(ext in lower_names for ext in [".xlsx", ".xls", ".csv"]): + if any(ext in lower_names for ext in [".xlsx", ".csv"]): return {"route_key": "inventory_path", "reason": "inventory_file"} return {"route_key": "direct_answer", "reason": "notice_files_managed_by_hxops"} if intent_hint in { @@ -2935,7 +2935,7 @@ Agent 状态输入标准化 -> 货代续办 Agent | 确认 / 驳回 / 重匹配直连 | `确认` / `驳回` / `重新匹配` / `rematch` | `submit_decision` | 是,直连决策 Tool | 当前任务或显式 `SN-...` | 按状态机推进;`rematch` 清理 shortage 并重新入队当前任务 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_submit_decision_rematch_is_direct_recovery_entry` | | shortage 阻断 | shortage review 后输入 `继续` 或自动续跑 | `match_inventory` / `submit_decision` 返回门禁 | 是,命中状态机门禁后停止 | 当前任务 | `status=needs_human`;禁止 `generate_shipment_excel` / `upload_to_freight`;不生成 Excel | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_shipping_notice_match_shortage_needs_human` | | 多任务只推进 focus task | 多票批次中输入 `继续处理` | `get_batch_status` + 当前 focus 的 `get_task_status` | 是,先读状态再决定 | `batch.current_focus_task_no` | 每轮只围绕一个 focus task;读批次状态不循环推进整批 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks` | -| 库存上传链路 | 上传 `.xlsx/.xls/.csv` | `get_inventory_schema_preview` → 映射 LLM → `apply_inventory_mapping` | 否,进入库存专用分支,不走自由 Agent | 当前任务 / 所属批次库存快照 | 生成 schema preview;应用映射后进入 `align_review` 或后端续跑 | 待实测 | +| 库存上传链路 | 上传 `.xlsx/.csv` | `get_inventory_schema_preview` → 映射 LLM → `apply_inventory_mapping` | 否,进入库存专用分支,不走自由 Agent | 当前任务 / 所属批次库存快照 | 生成 schema preview;应用映射后进入 `align_review` 或后端续跑 | 待实测 | | 字段对齐人工门 | `apply_inventory_mapping` 返回 `align_review` 后输入 `确认` | `submit_decision(decision=confirm_inventory_mapping)` | 是,直连决策 Tool | 当前任务 | 停住等待确认;确认后交由 hxops worker 续跑匹配 / 导出 / 上传 | 待实测 | | Tool 人工门收口 | 任一 Tool 返回 `needs_human` 或 `stop_agent_turn=true` | 工具结果标准化 | 是,硬停止本轮 | 当前任务 | 本轮不再继续调用后续 Tool | 待实测 | | forbidden_next_tools 门禁 | Tool 返回 `forbidden_next_tools` | 工具结果标准化 | 是,硬门禁 | 当前任务 | 画布不调用被禁止 Tool | 待实测 | @@ -3291,7 +3291,7 @@ API 层 ### 5.2 快照复用规则 -1. `ensure_inventory(mode=auto)` 在解析库存源后,优先 `find_latest_ready_snapshot(source_code, warehouse_id)` +1. `ensure_inventory(mode=auto)` 在库存源**已稳定**后,优先 `find_latest_ready_snapshot(source_code, site_id, warehouse_id)` 2. 未过期快照 → `link_snapshot_to_task(reason=reuse_latest)` → 映射/匹配 3. 过期或缺失 → 触发 RPA(单 task trigger 或定时 batch trigger) 4. `retry_rpa` **强制跳过**快照缓存 @@ -3312,6 +3312,18 @@ API 层 ### 5.4 审计字段 -- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id` -- `shipping_task_inventory_links`:`link_reason`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json` +- `shipping_inventory_files`:`warehouse_id`、`site_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status` +- `shipping_task_inventory_links`:`link_reason`、`matched_source_code`、`matched_site_id`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段 + +### 5.5 订单解析阶段库存源判定(2026-07) + +> 详细方案见 [`inventory_source_plan.md`](./inventory_source_plan.md)。 + +1. **`parse_notice` 内 adjudicate**:读取任务 `destination_*` 与 YAML `match`/`match_aliases`,产出 `InventorySourceAdjudication`。 +2. **稳定才放行**:`inventory_source_status ∈ {resolved, user_confirmed}` 时任务才可 `parsed` 并触发 RPA;否则 `checkpoint=inventory_source_review`,`process_status=pending_review`。 +3. **独立字段为真相源**:`inventory_source_code`、`inventory_site_id`、`inventory_warehouse_id` 等存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。 +4. **用户只确认 source_code**:`confirm_inventory_source` 根据编码回填 site/warehouse;路由指纹变更时要求重确认(`SHIPPING.INVENTORY_SOURCE_CHANGED`)。 +5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。 +6. **快照复用键**:`find_latest_ready_snapshot(source_code, site_id, warehouse_id)`;link 时做 identity check。 +7. **迁移**:`b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields`。 diff --git a/docs/funclist.md b/docs/funclist.md index 6c6ca713..c46f8c9d 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -59,6 +59,9 @@ | 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | | 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | | 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | +| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate;稳定态 `resolved`/`user_confirmed`;不稳定进入 `inventory_source_review` | +| 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 | +| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | | 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | | 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` | | 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index b321e0a7..12ef9266 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -346,6 +346,50 @@ } } }, + "/tools/confirm_inventory_source": { + "post": { + "operationId": "confirm_inventory_source", + "summary": "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)", + "description": "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + }, + "source_code": { + "type": "string", + "description": "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传" + } + }, + "required": [ + "task_id", + "source_code" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, "/tools/submit_decision": { "post": { "operationId": "submit_decision", @@ -411,8 +455,8 @@ "/tools/get_task_status": { "post": { "operationId": "get_task_status", - "summary": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个", - "description": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个", + "summary": "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构", + "description": "返回 inventory_source_code、inventory_source_type、inventory_site_id、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。", "parameters": [], "requestBody": { "required": true, @@ -488,4 +532,4 @@ } } } -} +} \ No newline at end of file diff --git a/docs/tec.md b/docs/tec.md index 6f94d2f2..cefedd8b 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -24,6 +24,7 @@ - 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 - `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。 +- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 ### 2.1 已有聊天路由能力 diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts index e1ca6947..8dc3b6ec 100644 --- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts +++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts @@ -1,8 +1,8 @@ /** * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts - * 用途:解析企微深链 query,定位排程执行记录并标记原始库存手动下载入口。 + * 用途:解析企微深链 query,定位排程执行记录并在登录后自动下载原始库存包。 * 依赖:vue-router、schedule-admin.state、useScheduleAdminRuns。 - * 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip,不自动下载。 + * 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip/download,自动下载失败时保留手动入口。 */ import { useRoute, useRouter } from 'vue-router'; import type { ScheduleAdminState } from './schedule-admin.state'; @@ -15,12 +15,12 @@ function parsePositiveInt(raw: unknown): number | null { } /** - * 根据路由 query 打开工作台执行记录;raw_zip=1 时仅展开 run 并突出手动下载按钮。 - * 核心逻辑:不自动触发下载,避免企微内置浏览器拦截异步下载。 + * 根据路由 query 打开工作台执行记录;raw_zip=1 时展开 run 并保留手动下载按钮。 + * 核心逻辑:download=inventory_raw_zip 时登录后自动下载一次;若企微内置浏览器拦截,用户仍可点醒目按钮重试。 */ export function useScheduleAdminDeepLink( state: ScheduleAdminState, - runs: Pick, + runs: Pick, ) { const route = useRoute(); const router = useRouter(); @@ -31,6 +31,7 @@ export function useScheduleAdminDeepLink( const runId = parsePositiveInt(route.query.run_id); const rawZipPrompt = String(route.query.raw_zip || '') === '1'; + const shouldAutoDownloadRawZip = rawZipPrompt && String(route.query.download || '') === 'inventory_raw_zip'; state.scheduleViewMode.value = 'workbench'; state.selectedScheduleId.value = taskId; @@ -43,6 +44,9 @@ export function useScheduleAdminDeepLink( const target = state.selectedScheduleRuns.value.find((item) => item.id === runId); if (target?.inventory_raw_zip_available) { state.wecomRawZipPromptRunId.value = runId; + if (shouldAutoDownloadRawZip) { + await runs.downloadScheduleInventoryRawZip(runId); + } } } } @@ -51,6 +55,7 @@ export function useScheduleAdminDeepLink( delete nextQuery.task_id; delete nextQuery.run_id; delete nextQuery.raw_zip; + delete nextQuery.download; await router.replace({ path: route.path, query: nextQuery }); }; diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index 518dcc7d..41e77f64 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -218,7 +218,7 @@ watch( :ref="bindShippingPickerRef" type="file" class="hidden" - accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv" + accept=".xlsx,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv" @change="emit('shipping-inventory-selected', $event)" /> diff --git a/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue b/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue index d2849f4b..9e81bf94 100644 --- a/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue +++ b/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue @@ -324,6 +324,21 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'), }; } + if (reason === 'inventory_source_unresolved') { + const resolution = (task as ShippingTaskDetail).inventory_source_resolution; + const status = resolution && typeof resolution === 'object' + ? String((resolution as { status?: unknown }).status || '').trim() + : ''; + const isAmbiguous = status === 'ambiguous'; + return { + title: t(isAmbiguous + ? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousTitle' + : 'chat.shippingNoticeUi.diagnosisInventorySourceTitle'), + advice: t(isAmbiguous + ? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousAdvice' + : 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'), + }; + } if (reason === 'map_infer' || processStatus === 'waiting_inventory') { return { title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'), @@ -352,6 +367,9 @@ const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) if (reason === 'low_confidence' || reviewStatus === 'parse_review') { return t('chat.shippingNoticeUi.suggestReviewParse'); } + if (reason === 'inventory_source_unresolved') { + return t('chat.shippingNoticeUi.suggestConfirmInventorySource'); + } if (isFailedTask(task)) { return t('chat.shippingNoticeUi.suggestRetryStep'); } diff --git a/frontend/src/features/chat/shipping/shippingStepper.ts b/frontend/src/features/chat/shipping/shippingStepper.ts index 5537db73..c65fd1b2 100644 --- a/frontend/src/features/chat/shipping/shippingStepper.ts +++ b/frontend/src/features/chat/shipping/shippingStepper.ts @@ -130,6 +130,7 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): || reviewStatus === 'rsv_required' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required' + || pendingReason === 'inventory_source_unresolved' ) { return 1; } @@ -159,7 +160,12 @@ export function buildShippingWorkflowSteps( } if ( - (index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required')) + (index === 1 && ( + reviewStatus === 'parse_review' + || pendingReason === 'low_confidence' + || pendingReason === 'rsv_required' + || pendingReason === 'inventory_source_unresolved' + )) || (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted')) || (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review')) || (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage')) diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts index 3089489d..6cfe191d 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts @@ -32,7 +32,7 @@ export interface ShippingMenuHandlerContext { refreshShippingActions: () => Promise; startChatTurn: (options: StartChatTurnOptions) => Promise; msg: { warning: (text: string) => void; info: (text: string) => void }; - t: (key: string) => string; + t: (key: string, ...args: unknown[]) => string; } export interface HandleShippingMenuActionOptions { @@ -97,8 +97,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { if (!turnSpec) return false; const displayBase = String(action.message || actionId || '操作').trim(); const displayText = actionId === 'confirm_inventory_source' - ? `${displayBase}\n任务编号:${taskId}` - : `${displayBase}(任务编号:${taskId})`; + ? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId }) + : ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId }); await ctx.startChatTurn({ agentId: ctx.currentAgentId.value, inputType: 'action', @@ -168,7 +168,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { sourceCode = await resolveInventorySourceCodeFromContext(taskId); } if (!sourceCode) { - ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。'); + ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint')); if (chatMsg) chatMsg.shipping_actions_used = false; return; } @@ -179,7 +179,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { } const label = String(('label' in action ? action.label : '') || sourceCode).trim(); const displayMessage = action.id === 'confirm_inventory_source' - ? `确认库存查询来源:${label || sourceCode}` + ? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode }) : action.message; await runShippingActionTurn( { ...action, message: displayMessage }, @@ -195,7 +195,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { if (action.id === 'retry_resolve_inventory_source') { await ctx.refreshShippingActions(); - ctx.msg.info('已重新刷新库存源状态'); + ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone')); return; } if (action.id === 'edit_inventory_mapping') { diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts index 786414c7..a8c1acbf 100644 --- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts @@ -66,7 +66,7 @@ export interface ShippingSendHandlerContext { isShippingShortageQueryIntent: (text: string) => boolean; queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise; msg: { warning: (text: string) => void; info: (text: string) => void }; - t: (key: string) => string; + t: (key: string, ...args: unknown[]) => string; } /** @@ -114,13 +114,13 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { const label = String(hit?.display_name || sourceCode).trim(); await ctx.handleShippingMenuAction({ id: 'confirm_inventory_source', - message: `确认库存查询来源:${label}`, + message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }), label, source_code: sourceCode, }); return true; } catch (e: unknown) { - const errorMessage = e instanceof Error ? e.message : '确认库存源失败'; + const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed'); ctx.msg.warning(errorMessage); return true; } diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index ccd26dc2..980da877 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -4,6 +4,42 @@ * 依赖:无(纯类型模块)。 * 逻辑:shipping.api.ts 与 Chat/工作台组件统一引用本文件 DTO 类型。 */ +export type InventorySourceStatus = + | 'unresolved' + | 'ambiguous' + | 'resolved' + | 'user_confirmed' + | 'invalid' + | 'conflicted'; + +export type InventorySourceMethod = + | 'rule_exact' + | 'rule_combined' + | 'user_confirmed' + | 'legacy_migrated'; + +export interface ShippingInventorySourceCandidate { + source_code: string; + display_name?: string | null; + site_id?: string | null; + warehouse_id?: string | null; + source_type?: string | null; + match_score?: number | null; + matched_by?: string | null; +} + +export interface ShippingInventorySourceResolution { + status?: InventorySourceStatus | null; + method?: InventorySourceMethod | null; + reason?: string | null; + candidates?: ShippingInventorySourceCandidate[]; + destination_candidates?: string[]; + evidence?: Record[]; + conflicts?: string[]; + config_version?: string | null; + routing_fingerprint?: string | null; +} + export interface ShippingInventorySnapshot { inventory_file_no?: string | null; source_code?: string | null; @@ -48,7 +84,21 @@ export interface ShippingTaskSummary { }; rpa_runtime?: ShippingRpaRuntime | null; rpa_inventory_source?: Record | null; - inventory_source_resolution?: Record | null; + inventory_source_resolution?: ShippingInventorySourceResolution | null; + destination_code?: string | null; + destination_city?: string | null; + destination_country?: string | null; + warehouse_hint?: string | null; + inventory_source_code?: string | null; + inventory_source_type?: string | null; + inventory_site_id?: string | null; + inventory_warehouse_id?: string | null; + inventory_source_status?: InventorySourceStatus | null; + inventory_source_method?: InventorySourceMethod | null; + inventory_source_config_version?: string | null; + inventory_routing_fingerprint?: string | null; + inventory_source_confirmed_at?: string | null; + inventory_source_confirmed_by?: number | null; inventory_snapshot?: ShippingInventorySnapshot | null; created_at?: string | null; updated_at?: string | null; diff --git a/frontend/src/features/workspace/views/ShippingNoticeView.vue b/frontend/src/features/workspace/views/ShippingNoticeView.vue index d4d94a5d..62ecdda2 100644 --- a/frontend/src/features/workspace/views/ShippingNoticeView.vue +++ b/frontend/src/features/workspace/views/ShippingNoticeView.vue @@ -141,6 +141,31 @@ const inventorySnapshotLabel = (triggerType?: string | null) => { return map[key] || map.on_demand; }; +const inventorySourceStatusLabel = (status?: string | null) => { + const key = String(status || '').trim(); + if (!key) return '—'; + const i18nKey = `workspace.shippingNotice.inventorySource.statusLabels.${key}`; + return te(i18nKey) ? t(i18nKey) : key; +}; + +const inventorySourceMethodLabel = (method?: string | null) => { + const key = String(method || '').trim(); + if (!key) return '—'; + const i18nKey = `workspace.shippingNotice.inventorySource.methodLabels.${key}`; + return te(i18nKey) ? t(i18nKey) : key; +}; + +const hasInventorySourceFields = computed(() => { + const item = detail.value; + if (!item) return false; + return !!( + item.inventory_source_code + || item.inventory_site_id + || item.inventory_warehouse_id + || item.inventory_source_status + ); +}); + const loadCases = async () => { loading.value = true; try { @@ -388,6 +413,45 @@ onMounted(async () => {
{{ $t('workspace.shippingNotice.fields.freightRef') }}
{{ detail.freight_ref_no || '—' }}
+
+

+ {{ $t('workspace.shippingNotice.inventorySource.title') }} +

+
+
+
{{ $t('workspace.shippingNotice.inventorySource.sourceCode') }}
+
{{ detail.inventory_source_code || '—' }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.status') }}
+
{{ inventorySourceStatusLabel(detail.inventory_source_status) }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.siteId') }}
+
{{ detail.inventory_site_id || '—' }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.warehouseId') }}
+
{{ detail.inventory_warehouse_id || '—' }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.method') }}
+
{{ inventorySourceMethodLabel(detail.inventory_source_method) }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.configVersion') }}
+
{{ detail.inventory_source_config_version || '—' }}
+
+
+
{{ $t('workspace.shippingNotice.inventorySource.confirmedBy') }}
+
{{ detail.inventory_source_confirmed_by ?? '—' }}
+
+
+
+
Date: Tue, 14 Jul 2026 00:28:52 +0800 Subject: [PATCH 2/5] =?UTF-8?q?feat(shipping-notice):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=8F=91=E8=B4=A7=E9=80=9A=E7=9F=A5=E5=BB=BA=E5=8D=95=E5=B9=82?= =?UTF-8?q?=E7=AD=89=E6=80=A7=E6=94=AF=E6=8C=81=E5=8F=8A=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E5=93=88=E5=B8=8C=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/shipping_notice_tools.py | 2 +- backend/app/api/workspace/shipping_notice.py | 10 + backend/app/models/shipping.py | 10 +- .../batch_create_idempotency.py | 305 ++++++++++++++++++ .../shipping_notice/batch_from_notices.py | 61 +++- .../shipping_notice/chat_action_handlers.py | 3 + .../services/shipping_notice/notice_upload.py | 51 ++- .../services/shipping_notice/task_workflow.py | 111 ++++++- ...add_shipping_batch_creation_idempotency.py | 48 +++ backend/tests/test_chat_turn_runtime.py | 99 ++++++ backend/tests/test_notice_intake.py | 97 +++++- backend/tests/test_shipping_notice_batches.py | 268 +++++++++++++-- docs/demand.md | 7 + docs/features/shipping-notice/technical.md | 5 +- docs/funclist.md | 1 + docs/tec.md | 1 + docs/test_plan_matrix.md | 3 + .../src/features/chat/api/shipping.api.ts | 19 +- .../features/chat/composables/useChatPage.ts | 2 + .../chat/composables/useChatShipping.ts | 4 + .../chat/page/useChatPageConversation.spec.ts | 166 ++++++++++ .../chat/page/useChatPageConversation.ts | 3 + .../shippingNoticeBatchIdempotency.spec.ts | 23 ++ .../shippingNoticeBatchIdempotency.ts | 31 ++ .../chat/shipping/shippingTurnActions.spec.ts | 22 ++ .../chat/shipping/shippingTurnActions.ts | 2 + .../useChatShippingSendHandler.spec.ts | 74 +++++ .../shipping/useChatShippingSendHandler.ts | 5 + .../useChatShippingUploadHandler.spec.ts | 200 ++++++++++++ .../shipping/useChatShippingUploadHandler.ts | 149 +++++++-- .../features/chat/types/shipping.api.types.ts | 16 + frontend/src/locales/en/chat.json | 3 + frontend/src/locales/en/errors.json | 5 +- frontend/src/locales/th/chat.json | 3 + frontend/src/locales/th/errors.json | 5 +- frontend/src/locales/zh-CN/chat.json | 3 + frontend/src/locales/zh-CN/errors.json | 5 +- frontend/src/locales/zh-TW/chat.json | 3 + frontend/src/locales/zh-TW/errors.json | 5 +- 39 files changed, 1750 insertions(+), 80 deletions(-) create mode 100644 backend/app/services/shipping_notice/batch_create_idempotency.py create mode 100644 backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py create mode 100644 frontend/src/features/chat/page/useChatPageConversation.spec.ts create mode 100644 frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts create mode 100644 frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts create mode 100644 frontend/src/features/chat/shipping/shippingTurnActions.spec.ts create mode 100644 frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index e1ef3eb2..368380f0 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -152,7 +152,7 @@ def tool_create_batch(): batch = get_batch_by_no(batch_no) if batch: return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)}) - batch = shipping_tools.create_batch(payload) + batch, _created = shipping_tools.create_batch(payload) db.session.commit() return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)}) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 7e16d7a8..1209f9c3 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -101,8 +101,17 @@ def workspace_create_shipping_batch_from_notices(): create_shipping_batch_from_notice_items, intake_notice_uploads_for_batch, ) + from app.services.shipping_notice.batch_create_idempotency import ( + normalize_create_idempotency_key, + warn_missing_create_idempotency_key, + ) from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads conversation_id = str(request.form.get('conversation_id') or '').strip() + idempotency_key = normalize_create_idempotency_key( + request.headers.get('Idempotency-Key') or request.form.get('idempotency_key') + ) + if not idempotency_key: + warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices') temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex) try: notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads) @@ -114,6 +123,7 @@ def workspace_create_shipping_batch_from_notices(): conversation_id=conversation_id or None, notice_items=notice_items, file_summary=file_summary, + create_idempotency_key=idempotency_key, ) return _ok(created) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 3cdfb6a6..315471e5 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -3,7 +3,7 @@ backend/app/models/shipping.py 用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。 依赖:models.base.Base。 -逻辑:ShippingTask 独立字段承载目的地与库存源身份;step_payload_json 仅保留候选/证据等辅助信息。 +逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等,二者语义分离。 """ from __future__ import annotations @@ -24,6 +24,11 @@ class ShippingBatch(Base): __table_args__ = ( Index('ix_shipping_batches_user_created', 'user_id', 'created_at'), Index('ix_shipping_batches_conversation', 'conversation_id'), + UniqueConstraint( + 'user_id', + 'create_idempotency_key', + name='uq_shipping_batches_user_create_idempotency', + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -40,6 +45,7 @@ class ShippingBatch(Base): nullable=True, ) file_count: Mapped[int] = mapped_column(Integer, default=1) + create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) @@ -65,6 +71,7 @@ class ShippingTask(Base): Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'), Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), + Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -75,6 +82,7 @@ class ShippingTask(Base): source_type: Mapped[str] = mapped_column(String(32), default='manual') source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py new file mode 100644 index 00000000..2948a178 --- /dev/null +++ b/backend/app/services/shipping_notice/batch_create_idempotency.py @@ -0,0 +1,305 @@ +""" +services/shipping_notice/batch_create_idempotency.py + +用途:发货通知建单幂等键标准化、批次回查与跨请求文件内容重复校验。 +依赖:models.ShippingBatch/ShippingTask、query_service、tool_response 序列化。 +逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingTask.idempotency_key(货代上传幂等)语义分离。 +""" + +from __future__ import annotations + +import hashlib +import logging +import re +import zlib +from typing import Any, Iterable + +from sqlalchemy import text +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.errors import AppError, ConflictError +from app.models import ShippingBatch, ShippingTask +from app.services.shipping_notice.query_service import ( + get_focus_task_for_batch, + list_sorted_batch_tasks, + serialize_batch_for_tool, + serialize_task_summary, +) + +logger = logging.getLogger(__name__) + +_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128 +_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$") + +_TERMINAL_TASK_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"}) + + +def normalize_create_idempotency_key(raw: str | None) -> str | None: + """ + 标准化建单幂等键:去首尾空格、校验长度与安全字符集。 + + Args: + raw: HTTP Header / payload 中的原始幂等键。 + + Returns: + 标准化后的幂等键;空值返回 None。 + + Raises: + ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。 + """ + value = str(raw or "").strip() + if not value: + return None + if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN: + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符", + http_status=400, + ) + if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value): + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message="幂等键仅允许字母、数字及 . _ : - 字符", + http_status=400, + ) + return value + + +def warn_missing_create_idempotency_key(*, source: str) -> None: + """兼容期记录缺少建单幂等键的告警,不阻断旧客户端。""" + logger.warning( + "shipping batch create without create_idempotency_key source=%s", + source, + ) + + +def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str: + """ + 根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。 + + 核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。 + """ + hashes = sorted( + { + str(item.get("source_content_hash") or "").strip().lower() + for item in notice_items + if isinstance(item, dict) and str(item.get("source_content_hash") or "").strip() + } + ) + if not hashes: + return "" + return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower() + + +def batch_stored_content_fingerprint(batch: ShippingBatch) -> str | None: + """ + 读取批次已持久化的文件集合指纹;历史批次无字段时从任务 source_content_hash 推导。 + """ + summary = batch.process_summary_json if isinstance(batch.process_summary_json, dict) else {} + stored = str(summary.get("create_content_fingerprint") or "").strip().lower() + if stored: + return stored + tasks = list_sorted_batch_tasks(batch) + hashes = sorted( + { + str(task.source_content_hash or "").strip().lower() + for task in tasks + if str(task.source_content_hash or "").strip() + } + ) + if not hashes: + return None + return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower() + + +def assert_idempotent_batch_content_matches( + batch: ShippingBatch, + notice_items: list[dict[str, Any]], +) -> None: + """ + 校验幂等键命中时,本次文件集合与已有批次一致。 + + Raises: + ConflictError: 文件集合不一致(SHIPPING.BATCH_IDEMPOTENCY_CONFLICT)。 + """ + stored_fp = batch_stored_content_fingerprint(batch) + request_fp = compute_notice_items_content_fingerprint(notice_items) + if not stored_fp or not request_fp: + return + if stored_fp == request_fp: + return + raise ConflictError( + "建单幂等键对应的文件集合与本次上传不一致,请更换幂等键后重试", + code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT", + details={ + "batch_no": batch.batch_no, + "stored_content_fingerprint": stored_fp, + "request_content_fingerprint": request_fp, + }, + ) + + +def _advisory_lock_key(*parts: str) -> int: + raw = "|".join(parts) + return zlib.crc32(raw.encode("utf-8")) & 0x7FFFFFFF + + +def acquire_notice_create_locks(user_id: int, content_hashes: Iterable[str]) -> None: + """ + 在建单事务内获取 PostgreSQL 事务级 advisory lock,串行化同用户建单与活跃文件去重。 + + 核心逻辑:SQLite 等测试库跳过;生产 PostgreSQL 对 user 级与每个 content_hash 加锁。 + """ + bind = db.session.get_bind() + if bind.dialect.name != "postgresql": + return + lock_keys = {_advisory_lock_key(str(user_id), "shipping-notice-create")} + for content_hash in content_hashes: + normalized = str(content_hash or "").strip().lower() + if normalized: + lock_keys.add(_advisory_lock_key(str(user_id), "shipping-notice-hash", normalized)) + for lock_key in sorted(lock_keys): + db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key}) + + +def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> ShippingBatch | None: + """ + 按用户与建单幂等键查找已有批次。 + + Args: + user_id: 当前用户 ID。 + create_idempotency_key: 已标准化的建单幂等键。 + + Returns: + 匹配的 ShippingBatch 或 None。 + """ + key = str(create_idempotency_key or "").strip() + if not key: + return None + return ( + ShippingBatch.query.filter_by(user_id=user_id, create_idempotency_key=key).first() + ) + + +def build_existing_batch_tool_response(batch: ShippingBatch, *, user_id: int) -> dict[str, Any]: + """ + 将已有批次序列化为 create_batch_tasks 兼容的 Tool 响应结构。 + + 核心逻辑:不创建新任务、不启动编排器;供幂等重放与唯一约束竞争回查共用。 + """ + tasks = list_sorted_batch_tasks(batch) + focus_task = get_focus_task_for_batch(batch.batch_no, user_id) + created_tasks = [ + { + "task_id": task.task_no, + "batch_index": task.batch_index, + "parse_status": "deferred", + } + for task in tasks + ] + data: dict[str, Any] = { + "batch": serialize_batch_for_tool(batch), + "tasks": created_tasks, + "orchestrator_started": False, + } + if focus_task: + data["focus_task"] = serialize_task_summary(focus_task) + return { + "status": "ok", + "batch_no": batch.batch_no, + "message": f"已恢复此前创建的批次 {batch.batch_no}", + "data": data, + "idempotent_replay": True, + } + + +def assert_no_exact_duplicate_notices( + user_id: int, + notice_items: list[dict[str, Any]], + *, + exclude_batch_id: int | None = None, +) -> None: + """ + 校验跨请求是否存在相同文件内容且仍在进行中的任务。 + + 核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。 + + Raises: + ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。 + """ + hashes: list[tuple[str, str]] = [] + for item in notice_items: + if not isinstance(item, dict): + continue + content_hash = str(item.get("source_content_hash") or "").strip().lower() + if not content_hash: + continue + filename = str(item.get("source_file_name") or "").strip() or "notice" + hashes.append((content_hash, filename)) + if not hashes: + return + + for content_hash, _filename in hashes: + query = ShippingTask.query.filter( + ShippingTask.user_id == user_id, + ShippingTask.source_content_hash == content_hash, + ShippingTask.process_status.notin_(list(_TERMINAL_TASK_STATUSES)), + ) + if exclude_batch_id is not None: + query = query.filter( + (ShippingTask.batch_id.is_(None)) | (ShippingTask.batch_id != exclude_batch_id) + ) + existing = query.order_by(ShippingTask.id.desc()).first() + if existing: + raise ConflictError( + f"该文件已存在于进行中的任务 {existing.task_no}", + code="SHIPPING.NOTICE_EXACT_DUPLICATE", + details={ + "task_no": existing.task_no, + "source_content_hash": content_hash, + }, + ) + + +def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """请求内按 source_content_hash 二次去重,防止绕过 intake 时重复建任务。""" + seen: set[str] = set() + unique: list[dict[str, Any]] = [] + for item in notice_items: + if not isinstance(item, dict): + continue + content_hash = str(item.get("source_content_hash") or "").strip().lower() + if content_hash: + if content_hash in seen: + continue + seen.add(content_hash) + unique.append(item) + return unique + + +def handle_batch_create_integrity_error( + *, + user_id: int, + create_idempotency_key: str | None, + exc: IntegrityError, +) -> dict[str, Any] | None: + """ + 捕获批次建单唯一约束竞争,回滚后回查已有批次。 + + Returns: + 幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。 + """ + db.session.rollback() + key = str(create_idempotency_key or "").strip() + if not key: + return None + batch = find_batch_by_create_idempotency(user_id, key) + if not batch: + return None + logger.info( + "shipping batch create idempotency race resolved batch_no=%s user_id=%s", + batch.batch_no, + user_id, + ) + return build_existing_batch_tool_response(batch, user_id=user_id) diff --git a/backend/app/services/shipping_notice/batch_from_notices.py b/backend/app/services/shipping_notice/batch_from_notices.py index e22dfa73..16ed1bba 100644 --- a/backend/app/services/shipping_notice/batch_from_notices.py +++ b/backend/app/services/shipping_notice/batch_from_notices.py @@ -2,7 +2,7 @@ services/shipping_notice/batch_from_notices.py 用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。 -依赖:shipping_tools、notice_upload、batch_orchestrator、query_service。 +依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。 逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。 """ @@ -10,7 +10,18 @@ from __future__ import annotations from typing import Any +from sqlalchemy.exc import IntegrityError + from app.services.shipping_notice import tools as shipping_tools +from app.services.shipping_notice.batch_create_idempotency import ( + assert_idempotent_batch_content_matches, + build_existing_batch_tool_response, + dedupe_notice_items_by_content_hash, + find_batch_by_create_idempotency, + handle_batch_create_integrity_error, + normalize_create_idempotency_key, + warn_missing_create_idempotency_key, +) from app.services.shipping_notice.notice_upload import build_notice_file_summary from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary @@ -21,22 +32,31 @@ def create_shipping_batch_from_notice_items( conversation_id: str | None, notice_items: list[dict[str, Any]], file_summary: dict[str, Any] | None = None, + create_idempotency_key: str | None = None, ) -> dict[str, Any]: """ 根据已抽取的发货通知条目创建批次并可选启动编排器。 + 核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。 + Args: user_id: 当前用户 ID。 conversation_id: 可选 Agent 会话 ID。 notice_items: notice_upload 产出的 notice item 列表。 file_summary: 可选文件预检摘要,写入响应供前端展示。 + create_idempotency_key: 建单幂等键(与 ShippingTask.idempotency_key 货代上传幂等分离)。 Returns: - 与 workspace create-from-notices 一致的结果字典。 + 与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。 Raises: ValidationError: notice_items 为空。 """ + normalized_key = normalize_create_idempotency_key(create_idempotency_key) + if not normalized_key: + warn_missing_create_idempotency_key(source="create_shipping_batch_from_notice_items") + + notice_items = dedupe_notice_items_by_content_hash(notice_items) if not notice_items: from app.core.errors import ValidationError @@ -45,22 +65,44 @@ def create_shipping_batch_from_notice_items( details={"file_summary": file_summary or {}}, ) + if normalized_key: + existing_batch = find_batch_by_create_idempotency(user_id, normalized_key) + if existing_batch: + assert_idempotent_batch_content_matches(existing_batch, notice_items) + created = build_existing_batch_tool_response(existing_batch, user_id=user_id) + if file_summary: + created["file_summary"] = file_summary + return created + payload = { "user_id": user_id, "conversation_id": conversation_id or None, "file_count": len(notice_items), "notice_items": notice_items, "defer_parse": True, + "create_idempotency_key": normalized_key, } - created = shipping_tools.create_batch_tasks(payload) + try: + created = shipping_tools.create_batch_tasks(payload) + except IntegrityError as exc: + replay = handle_batch_create_integrity_error( + user_id=user_id, + create_idempotency_key=normalized_key, + exc=exc, + ) + if replay is None: + raise + created = replay + if not isinstance(created, dict): return {"status": "failed", "message": "create batch failed"} + idempotent_replay = bool(created.get("idempotent_replay")) data = created.get("data") if isinstance(created.get("data"), dict) else {} batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {} batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip() orchestrator_started = False - if batch_no: + if batch_no and not idempotent_replay: from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator orchestrator_started = start_batch_orchestrator(batch_no) @@ -72,6 +114,8 @@ def create_shipping_batch_from_notice_items( base_message = str(created.get("message") or "").strip() if orchestrator_started: created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。" + if idempotent_replay: + created["idempotent_replay"] = True if file_summary: created["file_summary"] = file_summary return created @@ -85,8 +129,12 @@ def format_batch_created_assistant_message( """ 格式化建批成功后写入 Chat Turn assistant 气泡的文案。 - 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构。 + 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。 """ + if bool(result.get("idempotent_replay")): + batch_no = str(result.get("batch_no") or "").strip() + return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。" + data = result.get("data") if isinstance(result.get("data"), dict) else {} batch = data.get("batch") if isinstance(data.get("batch"), dict) else {} tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else [] @@ -132,11 +180,12 @@ def intake_notice_uploads_for_batch( """ from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads - accepted, rejected = intake_temp_notice_uploads(request_id, uploads) + accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads) file_summary = build_notice_file_summary( total_files=len(uploads), accepted=accepted, rejected=rejected, + duplicate_files=duplicate_files, ) notice_items = [item.to_notice_item() for item in accepted] return notice_items, file_summary diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index 74cd6412..ce5a17b9 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -113,6 +113,7 @@ class ShippingCreateBatchFromNoticesAction: raise ValidationError("notice_items is required") file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None + idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."}) @@ -126,6 +127,7 @@ class ShippingCreateBatchFromNoticesAction: conversation_id=conversation_id, notice_items=notice_items, file_summary=file_summary, + create_idempotency_key=idempotency_key, ) batch_no = str(result.get("batch_no") or "").strip() if batch_no: @@ -141,6 +143,7 @@ class ShippingCreateBatchFromNoticesAction: "batch_no": batch_no, "task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(), "orchestrator_started": bool(data.get("orchestrator_started")), + "idempotent_replay": bool(result.get("idempotent_replay")), } yield from _stream_text_events(content, message_type="text", payload=message_payload) yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"}) diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py index 048f57e4..9ae36c89 100644 --- a/backend/app/services/shipping_notice/notice_upload.py +++ b/backend/app/services/shipping_notice/notice_upload.py @@ -10,6 +10,7 @@ services/shipping_notice/notice_upload.py from __future__ import annotations import base64 +import hashlib import re import shutil from dataclasses import dataclass, field @@ -249,6 +250,8 @@ class NoticeIntakeResult: text: str warnings: list[str] = field(default_factory=list) meta: dict[str, Any] = field(default_factory=dict) + content_hash: str = "" + file_size: int = 0 status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text" saved_path: Path | None = None @@ -263,6 +266,8 @@ class NoticeIntakeResult: "source_type": self.source_type, "source_file_name": self.filename, "source_file_type": self.source_file_type, + "source_content_hash": self.content_hash, + "file_size": self.file_size, "raw_text": self.text, "warnings": list(self.warnings), } @@ -274,6 +279,8 @@ class NoticeIntakeResult: "source_type": self.source_type, "source_file_type": self.source_file_type, "text_length": len(self.text), + "content_hash": self.content_hash, + "file_size": self.file_size, "warnings": list(self.warnings), } @@ -349,6 +356,9 @@ def intake_notice_attachment( """ name = str(filename or "").strip() or "notice" source_type = guess_source_type(name) + raw_bytes = raw or b"" + content_hash = hashlib.sha256(raw_bytes).hexdigest().lower() + file_size = len(raw_bytes) saved_path: Path | None = None text = "" meta: dict[str, Any] = {} @@ -359,11 +369,11 @@ def intake_notice_attachment( if storage == "task": if not task_no: raise ValueError("task_no is required for task storage") - saved_path = save_task_notice_upload(task_no, name, raw or b"") + saved_path = save_task_notice_upload(task_no, name, raw_bytes) else: if not temp_request_id: raise ValueError("temp_request_id is required for temp storage") - saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"") + saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes) text, meta = extract_notice_text(saved_path) warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else [] except Exception as exc: @@ -376,6 +386,8 @@ def intake_notice_attachment( text="", warnings=warnings, meta=meta if isinstance(meta, dict) else {}, + content_hash=content_hash, + file_size=file_size, status=status, saved_path=saved_path, ) @@ -388,6 +400,8 @@ def intake_notice_attachment( text="", warnings=warnings, meta=meta if isinstance(meta, dict) else {}, + content_hash=content_hash, + file_size=file_size, status="empty_text", saved_path=saved_path, ) @@ -400,6 +414,8 @@ def intake_notice_attachment( text=text, warnings=warnings, meta=meta if isinstance(meta, dict) else {}, + content_hash=content_hash, + file_size=file_size, status="accepted", saved_path=saved_path, ) @@ -408,23 +424,37 @@ def intake_notice_attachment( def intake_temp_notice_uploads( temp_request_id: str, uploads: Sequence[Any], -) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]: +) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult], list[dict[str, Any]]]: """ - 批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。 + 批量建单入口:逐份附件接入、同请求内按内容哈希去重,并在 finally 外由调用方清理临时目录。 Args: temp_request_id: 请求级临时目录 ID。 uploads: Flask request.files 中的上传对象序列。 Returns: - tuple[list, list]: (accepted 结果列表, rejected 结果列表)。 + tuple: (accepted 结果列表, rejected 结果列表, duplicate_files 摘要列表)。 """ accepted: list[NoticeIntakeResult] = [] rejected: list[NoticeIntakeResult] = [] + duplicate_files: list[dict[str, Any]] = [] + seen_hashes: dict[str, str] = {} for index, upload in enumerate(uploads, start=1): raw = upload.read() or b"" + content_hash = hashlib.sha256(raw).hexdigest().lower() + filename = str(upload.filename or "notice").strip() or "notice" + if content_hash in seen_hashes: + duplicate_files.append( + { + "filename": filename, + "duplicate_of": seen_hashes[content_hash], + "content_hash": content_hash, + } + ) + continue + seen_hashes[content_hash] = filename result = intake_notice_attachment( - filename=upload.filename or "notice", + filename=filename, raw=raw, source_file_type=notice_source_file_type(upload), storage="temp", @@ -435,7 +465,7 @@ def intake_temp_notice_uploads( accepted.append(result) else: rejected.append(result) - return accepted, rejected + return accepted, rejected, duplicate_files def build_notice_file_summary( @@ -443,6 +473,7 @@ def build_notice_file_summary( total_files: int, accepted: Sequence[NoticeIntakeResult], rejected: Sequence[NoticeIntakeResult], + duplicate_files: Sequence[dict[str, Any]] | None = None, ) -> dict[str, Any]: """ 构建批量上传预检摘要,供前端回显与测试断言。 @@ -451,16 +482,20 @@ def build_notice_file_summary( total_files: 请求内附件总数。 accepted: 接入成功的结果列表。 rejected: 接入失败的结果列表。 + duplicate_files: 同请求内内容重复、已跳过的文件摘要。 Returns: - dict: total/accepted/rejected 计数与文件明细。 + dict: total/accepted/rejected/duplicate 计数与文件明细。 """ accepted_files = [item.to_accepted_file_summary() for item in accepted] rejected_files = [item.to_rejected_file_summary() for item in rejected] + duplicates = [dict(item) for item in (duplicate_files or [])] return { "total_files": total_files, "accepted_count": len(accepted_files), "rejected_count": len(rejected_files), + "duplicate_count": len(duplicates), "accepted_files": accepted_files, "rejected_files": rejected_files, + "duplicate_files": duplicates, } diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 17d2cb03..213d08c5 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -14,7 +14,10 @@ from typing import Any from flask import current_app +from sqlalchemy.exc import IntegrityError + from app import db +from app.core.errors import ConflictError from app.models import ShippingBatch, ShippingTask from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, @@ -52,6 +55,17 @@ from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.user_facing_status import user_facing_task_stage from app.services.shipping_notice.inventory_workflow import ensure_inventory +from app.services.shipping_notice.batch_create_idempotency import ( + acquire_notice_create_locks, + assert_idempotent_batch_content_matches, + assert_no_exact_duplicate_notices, + build_existing_batch_tool_response, + compute_notice_items_content_fingerprint, + dedupe_notice_items_by_content_hash, + find_batch_by_create_idempotency, + handle_batch_create_integrity_error, + normalize_create_idempotency_key, +) from app.services.shipping_notice.tool_common import ( auto_progress_enabled, defer_parse_to_dify_enabled, @@ -193,42 +207,56 @@ def sync_batch_after_task_change(task: ShippingTask | None) -> None: recompute_batch_summary(task.batch) -def create_batch(payload: dict[str, Any]) -> ShippingBatch: +def create_batch(payload: dict[str, Any]) -> tuple[ShippingBatch, bool]: """ 创建或复用发货批次壳(不含 notice 解析)。 【AI 触发时机】:当用户一次上传多份发货通知、需要归并到同一批次时调用。 - 核心逻辑:优先复用已有 `batch_no`,否则生成新的批次号并初始化批次汇总字段。 + 核心逻辑:优先复用已有 `batch_no` 或 `(user_id, create_idempotency_key)`,否则生成新批次号。 Args: - payload: 可包含 batch_no、user_id、conversation_id、file_count 等批次创建参数。 + payload: 可包含 batch_no、user_id、conversation_id、file_count、create_idempotency_key 等。 Returns: - ShippingBatch: 已存在或新建但尚未提交事务的批次对象。 + tuple[ShippingBatch, bool]: (批次对象, 是否本次新建)。复用已有批次时第二项为 False。 """ batch_no = str(payload.get("batch_no") or "").strip() if batch_no: existing = ShippingBatch.query.filter_by(batch_no=batch_no).first() if existing: - return existing + return existing, False + + user_id = payload.get("user_id") + idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key")) + if idem_key and user_id is not None: + existing_by_idem = find_batch_by_create_idempotency(int(user_id), idem_key) + if existing_by_idem: + return existing_by_idem, False + try: file_count = max(1, int(payload.get("file_count") or 1)) except (TypeError, ValueError): file_count = 1 + content_fingerprint = str(payload.get("create_content_fingerprint") or "").strip().lower() or None + summary: dict[str, Any] = {"total": 0, "completed": 0, "failed": 0, "running": 0} + if content_fingerprint: + summary["create_content_fingerprint"] = content_fingerprint batch = ShippingBatch( batch_no=f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}", user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, file_count=file_count, - process_summary_json={"total": 0, "completed": 0, "failed": 0, "running": 0}, + create_idempotency_key=idem_key, + process_summary_json=summary, ) db.session.add(batch) db.session.flush() - return batch + return batch, True def _create_single_task_batch(payload: dict[str, Any]) -> ShippingBatch: """为单票任务创建 file_count=1 的标准批次容器。""" - return create_batch({**payload, "file_count": 1}) + batch, _created = create_batch({**payload, "file_count": 1}) + return batch def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool: @@ -255,9 +283,21 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: dict[str, Any]: Tool 标准响应,包含批次摘要和每个任务的解析状态。 """ notice_items = payload.get("notice_items") + user_id = payload.get("user_id") + idem_key = normalize_create_idempotency_key(payload.get("create_idempotency_key")) if not isinstance(notice_items, list) or not notice_items: - batch = create_batch(payload) - db.session.commit() + batch, _created = create_batch(payload) + try: + db.session.commit() + except IntegrityError as exc: + replay = handle_batch_create_integrity_error( + user_id=int(payload.get("user_id") or 0), + create_idempotency_key=idem_key, + exc=exc, + ) + if replay is not None: + return replay + raise return { "status": "ok", "batch_no": batch.batch_no, @@ -268,13 +308,49 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: }, } - batch = create_batch({**payload, "file_count": len(notice_items)}) + notice_items = dedupe_notice_items_by_content_hash(notice_items) + content_hashes = [ + str(item.get("source_content_hash") or "").strip().lower() + for item in notice_items + if isinstance(item, dict) + ] + if user_id is not None: + acquire_notice_create_locks(int(user_id), content_hashes) + + request_fingerprint = compute_notice_items_content_fingerprint(notice_items) + if idem_key and user_id is not None: + existing_batch = find_batch_by_create_idempotency(int(user_id), idem_key) + if existing_batch: + assert_idempotent_batch_content_matches(existing_batch, notice_items) + return build_existing_batch_tool_response(existing_batch, user_id=int(user_id)) + + if user_id is not None: + assert_no_exact_duplicate_notices(int(user_id), notice_items) + + batch, created_new = create_batch( + { + **payload, + "file_count": len(notice_items), + "create_content_fingerprint": request_fingerprint, + } + ) + if not created_new: + if idem_key and user_id is not None: + assert_idempotent_batch_content_matches(batch, notice_items) + return build_existing_batch_tool_response(batch, user_id=int(user_id)) + db.session.rollback() + raise ConflictError( + "批次已存在,禁止向已有批次重复追加任务", + code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT", + details={"batch_no": batch.batch_no}, + ) db.session.flush() created_tasks: list[dict[str, Any]] = [] total = len(notice_items) for idx, item in enumerate(notice_items, start=1): if not isinstance(item, dict): continue + content_hash = str(item.get("source_content_hash") or "").strip().lower() or None task = ShippingTask( task_no=generate_task_no(), batch_id=batch.id, @@ -283,6 +359,7 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: source_type=str(item.get("source_type") or "manual"), source_file_name=str(item.get("source_file_name") or "").strip() or None, source_file_type=item.get("source_file_type"), + source_content_hash=content_hash, batch_index=idx, batch_total=total, raw_content=str(item.get("raw_text") or "").strip() or None, @@ -325,7 +402,17 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: ) recompute_batch_summary(batch) - db.session.commit() + try: + db.session.commit() + except IntegrityError as exc: + replay = handle_batch_create_integrity_error( + user_id=int(payload.get("user_id") or 0), + create_idempotency_key=idem_key, + exc=exc, + ) + if replay is not None: + return replay + raise return { "status": "ok", "batch_no": batch.batch_no, diff --git a/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py b/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py new file mode 100644 index 00000000..dfdf49c5 --- /dev/null +++ b/backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py @@ -0,0 +1,48 @@ +""" +backend/migrations/versions/e7f8a9b0c1d2_add_shipping_batch_creation_idempotency.py + +用途:发货通知建单幂等键与源文件 SHA-256 内容哈希字段。 +依赖:Alembic revision d6e7f8a9b0c1。 +逻辑:shipping_batches.create_idempotency_key 唯一约束;shipping_tasks.source_content_hash 查询索引。 + +Revision ID: e7f8a9b0c1d2 +Revises: d6e7f8a9b0c1 +Create Date: 2026-07-13 22:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "e7f8a9b0c1d2" +down_revision = "d6e7f8a9b0c1" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + with op.batch_alter_table("shipping_batches", schema=None) as batch_op: + batch_op.add_column(sa.Column("create_idempotency_key", sa.String(length=128), nullable=True)) + batch_op.create_unique_constraint( + "uq_shipping_batches_user_create_idempotency", + ["user_id", "create_idempotency_key"], + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("source_content_hash", sa.String(length=64), nullable=True)) + batch_op.create_index( + "ix_shipping_tasks_user_source_content_hash", + ["user_id", "source_content_hash"], + unique=False, + ) + + +def downgrade() -> None: + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_user_source_content_hash") + batch_op.drop_column("source_content_hash") + + with op.batch_alter_table("shipping_batches", schema=None) as batch_op: + batch_op.drop_constraint("uq_shipping_batches_user_create_idempotency", type_="unique") + batch_op.drop_column("create_idempotency_key") diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index 9638903a..a4dbf619 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -201,3 +201,102 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey assert "run.started" in event_names assert "run.completed" in event_names assert "run.failed" not in event_names + + +def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path): + """shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。""" + from io import BytesIO + + user = _create_user() + agent = _create_shipping_agent() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + captured: dict = {} + + def fake_create(**kwargs): + captured.update(kwargs) + return { + "status": "ok", + "batch_no": "SB-CHAT-IDEM-001", + "data": { + "tasks": [{"task_id": "SN-CHAT-IDEM-001"}], + "focus_task": {"task_no": "SN-CHAT-IDEM-001"}, + }, + } + + monkeypatch.setattr( + "app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items", + fake_create, + ) + + res = client.post( + "/api/chat/turns/stream", + headers={"X-Username": user.username, "X-Role": user.role}, + data={ + "agent_id": str(agent.id), + "input": json.dumps( + { + "type": "upload_followup", + "display_text": "上传发货通知:notice.txt", + "action_type": "shipping.create_batch_from_notices", + "payload": {"idempotency_key": "chat-idem-001"}, + }, + ensure_ascii=False, + ), + "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"), + }, + content_type="multipart/form-data", + ) + assert res.status_code == 200 + res.get_data(as_text=True) + assert captured.get("create_idempotency_key") == "chat-idem-001" + notice_items = captured.get("notice_items") or [] + assert notice_items + assert notice_items[0].get("source_content_hash") + + +def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path): + """相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。""" + from io import BytesIO + + user = _create_user() + agent = _create_shipping_agent() + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + orchestrator_calls: list[str] = [] + monkeypatch.setattr( + "app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator", + lambda batch_no: orchestrator_calls.append(batch_no) or True, + ) + + payload_input = { + "type": "upload_followup", + "display_text": "上传发货通知:notice.txt", + "action_type": "shipping.create_batch_from_notices", + "payload": {"idempotency_key": "chat-replay-integration-001"}, + } + headers = {"X-Username": user.username, "X-Role": user.role} + raw = "客户:ACME\nA001 x 10".encode("utf-8") + + def _post_turn(): + return client.post( + "/api/chat/turns/stream", + headers=headers, + data={ + "agent_id": str(agent.id), + "input": json.dumps(payload_input, ensure_ascii=False), + "files": (BytesIO(raw), "notice.txt"), + }, + content_type="multipart/form-data", + ) + + first = _post_turn() + assert first.status_code == 200 + first_events = _parse_sse_events(first.get_data(as_text=True)) + assert "run.failed" not in [item.get("event") for item in first_events] + + second = _post_turn() + assert second.status_code == 200 + second_events = _parse_sse_events(second.get_data(as_text=True)) + completed = [item for item in second_events if item.get("event") == "message.completed"] + assert completed + assert "已恢复此前创建的批次" in str(completed[-1].get("content", "")) + assert len(orchestrator_calls) == 1 diff --git a/backend/tests/test_notice_intake.py b/backend/tests/test_notice_intake.py index fc0a9b93..dfdbc3c7 100644 --- a/backend/tests/test_notice_intake.py +++ b/backend/tests/test_notice_intake.py @@ -103,11 +103,12 @@ def test_intake_temp_notice_uploads_splits_accepted_and_rejected(app, tmp_path, ] with app.app_context(): - accepted, rejected = notice_upload.intake_temp_notice_uploads("req-batch", uploads) + accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-batch", uploads) summary = notice_upload.build_notice_file_summary( total_files=len(uploads), accepted=accepted, rejected=rejected, + duplicate_files=duplicate_files, ) assert len(accepted) == 1 @@ -140,3 +141,97 @@ def test_intake_notice_attachment_extract_failure(app, tmp_path, monkeypatch): assert result.accepted is False assert result.status == "extract_failed" assert result.warnings[0].startswith("notice_extract_failed:") + + +def test_intake_notice_attachment_same_bytes_same_hash(app, tmp_path): + """相同字节内容应得到相同 SHA-256(与文件名无关)。""" + from app.services.shipping_notice.notice_upload import intake_notice_attachment + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + raw = "客户:ACME\nA001 x 10".encode("utf-8") + with app.app_context(): + first = intake_notice_attachment( + filename="notice-a.txt", + raw=raw, + storage="temp", + temp_request_id="req-hash-a", + temp_index=1, + ) + second = intake_notice_attachment( + filename="notice-b.txt", + raw=raw, + storage="temp", + temp_request_id="req-hash-b", + temp_index=1, + ) + + assert first.content_hash == second.content_hash + assert len(first.content_hash) == 64 + assert first.content_hash == first.content_hash.lower() + + +def test_intake_notice_attachment_different_bytes_different_hash(app, tmp_path): + """不同字节内容应得到不同 SHA-256。""" + from app.services.shipping_notice.notice_upload import intake_notice_attachment + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + with app.app_context(): + first = intake_notice_attachment( + filename="notice-a.txt", + raw=b"content-a", + storage="temp", + temp_request_id="req-diff-a", + temp_index=1, + ) + second = intake_notice_attachment( + filename="notice-b.txt", + raw=b"content-b", + storage="temp", + temp_request_id="req-diff-b", + temp_index=1, + ) + + assert first.content_hash != second.content_hash + + +def test_intake_temp_notice_uploads_dedupes_same_content_in_one_request(app, tmp_path, monkeypatch): + """同一请求内相同内容文件只进入 accepted 一次,duplicate 不计入 rejected。""" + from app.services.shipping_notice import notice_upload + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + monkeypatch.setattr( + notice_upload, + "extract_notice_text", + lambda saved_path: ("客户:ACME\nA001 x 10", {"warnings": [], "file_type": "txt"}), + ) + + class _Upload: + def __init__(self, name: str, raw: bytes, mimetype: str): + self.filename = name + self._raw = raw + self.mimetype = mimetype + + def read(self): + return self._raw + + raw = "客户:ACME\nA001 x 10".encode("utf-8") + uploads = [ + _Upload("original.pdf", raw, "application/pdf"), + _Upload("copy.pdf", raw, "application/pdf"), + _Upload("another-copy.txt", raw, "text/plain"), + ] + + with app.app_context(): + accepted, rejected, duplicate_files = notice_upload.intake_temp_notice_uploads("req-dedupe", uploads) + summary = notice_upload.build_notice_file_summary( + total_files=len(uploads), + accepted=accepted, + rejected=rejected, + duplicate_files=duplicate_files, + ) + + assert len(accepted) == 1 + assert len(rejected) == 0 + assert summary["duplicate_count"] == 2 + assert summary["duplicate_files"][0]["duplicate_of"] == "original.pdf" + assert accepted[0].to_notice_item()["source_content_hash"] == accepted[0].content_hash diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index e15ddbce..ff393479 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -359,21 +359,15 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client): assert result["data"]["batch"]["batch_no"] == result["batch_no"] assert result["data"]["tasks"][0]["parse_status"] == "deferred" assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"] - assert result["file_summary"] == { - "total_files": 1, - "accepted_count": 1, - "rejected_count": 0, - "accepted_files": [ - { - "filename": "notice-a.txt", - "source_type": "manual", - "source_file_type": "text/plain", - "text_length": len("客户:ACME\nA001 x 10"), - "warnings": [], - } - ], - "rejected_files": [], - } + file_summary = result["file_summary"] + assert file_summary["total_files"] == 1 + assert file_summary["accepted_count"] == 1 + assert file_summary["rejected_count"] == 0 + assert file_summary["duplicate_count"] == 0 + assert file_summary["accepted_files"][0]["filename"] == "notice-a.txt" + assert len(file_summary["accepted_files"][0]["content_hash"]) == 64 + assert file_summary["rejected_files"] == [] + assert file_summary["duplicate_files"] == [] with app.app_context(): task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first() @@ -507,7 +501,11 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr payload = res.get_json() assert payload["success"] is False assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试" - assert payload["error"]["details"]["file_summary"]["rejected_files"] == [ + file_summary = payload["error"]["details"]["file_summary"] + assert file_summary["accepted_count"] == 0 + assert file_summary["rejected_count"] == 1 + assert file_summary["duplicate_count"] == 1 + assert file_summary["rejected_files"] == [ { "filename": "notice-a.pdf", "source_type": "pdf", @@ -516,17 +514,9 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr "message": "notice text is empty after extraction", "warnings": ["ocr_empty"], }, - { - "filename": "notice-b.pdf", - "source_type": "pdf", - "source_file_type": "application/pdf", - "reason": "empty_text", - "message": "notice text is empty after extraction", - "warnings": ["ocr_empty"], - }, ] - assert payload["error"]["details"]["file_summary"]["accepted_count"] == 0 - assert payload["error"]["details"]["file_summary"]["rejected_count"] == 2 + assert file_summary["duplicate_files"][0]["filename"] == "notice-b.pdf" + assert file_summary["duplicate_files"][0]["duplicate_of"] == "notice-a.pdf" with app.app_context(): assert ShippingBatch.query.count() == batch_count_before @@ -1658,3 +1648,229 @@ def test_create_empty_batch_returns_batch_shell(app, client): assert data["status"] == "ok" assert data["batch_no"].startswith("SB-") assert data["data"]["file_count"] == 1 + + +def _workspace_user_headers(app, username: str): + """创建独立工作台用户并返回 Authorization header。""" + with app.app_context(): + user = User( + username=username, + email=f"{username}@example.com", + role="user", + status="active", + ) + user.set_password("password") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + user_id = user.id + return {"Authorization": f"Bearer {token}"}, user_id + + +def test_create_batch_idempotency_key_replays_same_batch(app, client, monkeypatch): + """相同建单幂等键调用两次只创建一个批次,第二次不启动编排器。""" + headers = _workspace_headers(app) + idempotency_key = "batch-idem-001" + started: list[str] = [] + + def fake_start(batch_no: str | None) -> bool: + if batch_no: + started.append(batch_no) + return True + + monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start) + raw = "客户:ACME\nA001 x 10".encode("utf-8") + + def _payload(): + return { + "files": (BytesIO(raw), "notice-a.txt"), + "conversation_id": "conv-idem-001", + "idempotency_key": idempotency_key, + } + + first = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + second = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + assert first.status_code == 200 + assert second.status_code == 200 + first_result = _unwrap_ok(first) + second_result = _unwrap_ok(second) + assert first_result["batch_no"] == second_result["batch_no"] + assert second_result.get("idempotent_replay") is True + assert second_result["data"]["orchestrator_started"] is False + assert started == [first_result["batch_no"]] + + with app.app_context(): + batch_count = ShippingBatch.query.filter_by(create_idempotency_key=idempotency_key).count() + task_count = ShippingTask.query.filter_by(batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id).count() + assert batch_count == 1 + assert task_count == 1 + + +def test_create_batch_same_request_duplicate_files_create_one_task(app, client): + """同一次上传两个内容相同文件只创建一个任务。""" + headers = _workspace_headers(app) + raw = "客户:ACME\nA001 x 10".encode("utf-8") + res = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers=headers, + data={ + "files": [ + (BytesIO(raw), "notice-a.txt"), + (BytesIO(raw), "notice-b.txt"), + ], + "conversation_id": "conv-dedupe-files", + "idempotency_key": "batch-dedupe-files-001", + }, + content_type="multipart/form-data", + ) + result = _unwrap_ok(res) + assert result["file_summary"]["duplicate_count"] == 1 + assert len(result["data"]["tasks"]) == 1 + + +def test_create_batch_persists_source_content_hash(app, client): + """建单后任务应保存完整 SHA-256 内容哈希。""" + import hashlib + + headers = _workspace_headers(app) + raw = "客户:ACME\nA001 x 10".encode("utf-8") + res = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers=headers, + data={ + "files": (BytesIO(raw), "notice-a.txt"), + "conversation_id": "conv-hash-persist", + "idempotency_key": "batch-hash-persist-001", + }, + content_type="multipart/form-data", + ) + result = _unwrap_ok(res) + expected_hash = hashlib.sha256(raw).hexdigest().lower() + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first() + assert task is not None + assert task.source_content_hash == expected_hash + + +def test_create_batch_idempotency_key_scoped_per_user(app, client): + """不同用户使用相同幂等键互不冲突。""" + headers_a, _user_a = _workspace_user_headers(app, "shipping_idem_user_a") + headers_b, _user_b = _workspace_user_headers(app, "shipping_idem_user_b") + idempotency_key = "shared-idem-key" + + def _payload(): + return { + "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"), + "idempotency_key": idempotency_key, + } + + res_a = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers_a, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + res_b = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers_b, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + batch_a = _unwrap_ok(res_a)["batch_no"] + batch_b = _unwrap_ok(res_b)["batch_no"] + assert batch_a != batch_b + + +def test_create_batch_without_idempotency_key_still_works(app, client): + """兼容期:缺少幂等键的旧请求仍可建批。""" + headers = _workspace_headers(app) + res = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers=headers, + data={ + "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"), + "conversation_id": "conv-legacy-no-idem", + }, + content_type="multipart/form-data", + ) + result = _unwrap_ok(res) + assert result["batch_no"].startswith("SB-") + + +def test_create_batch_idempotency_replays_after_tasks_exist(app, client): + """相同幂等键在首批任务已落库后应幂等重放,而非返回文件重复错误。""" + headers = _workspace_headers(app) + idempotency_key = "batch-idem-after-tasks" + raw = "客户:ACME\nA001 x 10".encode("utf-8") + + def _payload(): + return { + "files": (BytesIO(raw), "notice-a.txt"), + "conversation_id": "conv-idem-after-tasks", + "idempotency_key": idempotency_key, + } + + first = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + second = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data=_payload(), + content_type="multipart/form-data", + ) + assert first.status_code == 200 + assert second.status_code == 200 + first_result = _unwrap_ok(first) + second_result = _unwrap_ok(second) + assert second_result.get("idempotent_replay") is True + assert first_result["batch_no"] == second_result["batch_no"] + + with app.app_context(): + task_count = ShippingTask.query.filter_by( + batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id + ).count() + assert task_count == 1 + + +def test_create_batch_idempotency_key_conflicts_on_different_files(app, client): + """相同幂等键但文件集合不同时应返回 SHIPPING.BATCH_IDEMPOTENCY_CONFLICT。""" + headers = _workspace_headers(app) + idempotency_key = "batch-idem-conflict-001" + first = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data={ + "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"), + "idempotency_key": idempotency_key, + }, + content_type="multipart/form-data", + ) + assert first.status_code == 200 + + second = client.post( + "/api/workspace/shipping-batches/create-from-notices", + headers={**headers, "Idempotency-Key": idempotency_key}, + data={ + "files": (BytesIO("客户:BETA\nB002 x 20".encode("utf-8")), "notice-b.txt"), + "idempotency_key": idempotency_key, + }, + content_type="multipart/form-data", + ) + assert second.status_code == 409 + payload = second.get_json() + assert payload["success"] is False + assert payload["error"]["code"] == "SHIPPING.BATCH_IDEMPOTENCY_CONFLICT" diff --git a/docs/demand.md b/docs/demand.md index 43d4e836..f7cd38d1 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -56,6 +56,13 @@ - **身份校验**:关联库存快照时校验 `source_code`、`site_id`、`warehouse_id` 与任务一致。 - 技术方案见 [docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 +### 3.x 货代发货通知建单防重复(第一阶段) + +- **同请求去重**:上传接入阶段按源文件 SHA-256 去重,相同内容只抽取、建任务一次。 +- **建单幂等**:`ShippingBatch.create_idempotency_key` 防止双击、重试与并发重复建批;数据库唯一约束 `(user_id, create_idempotency_key)` 提供最终保护。 +- **内容指纹**:`ShippingTask.source_content_hash` 记录完整文件哈希,支持跨请求精确重复检测。 +- **语义分离**:货代上传幂等仍使用 `ShippingTask.idempotency_key`,不与建单幂等键混用。 + ### 3.1 本期范围 - 查询员工本人假期余额 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index a5823028..fe4f04a6 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2999,7 +2999,10 @@ Agent 状态输入标准化 -> 货代续办 Agent | `upload_status` | 上传子状态 | | `upload_mode` | 上传模式 | | `upload_attempt` | 上传重试次数 | -| `idempotency_key` | 上传幂等键 | +| `idempotency_key` | **货代上传**幂等键(与建单幂等分离) | +| `source_content_hash` | 源文件 SHA-256(小写十六进制,基于原始字节) | + +`ShippingBatch` 另含 `create_idempotency_key`:**建单**幂等键;唯一约束 `(user_id, create_idempotency_key)` 防止双击/重试/并发重复建批。Chat Turn 与 Workspace API 经 `batch_from_notices.create_shipping_batch_from_notice_items()` 共用该逻辑。 常见 `process_status` / 子状态: diff --git a/docs/funclist.md b/docs/funclist.md index c46f8c9d..3265af86 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -65,6 +65,7 @@ | 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | | 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` | | 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | +| 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | | 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) | ### 排程平台任务契约中心(schedule) diff --git a/docs/tec.md b/docs/tec.md index cefedd8b..12b7cd54 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -25,6 +25,7 @@ - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 - `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。 - **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 +- **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。 ### 2.1 已有聊天路由能力 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index efe03e6a..9d52be2f 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -33,4 +33,7 @@ | **个性化** | **常用问题** | 用户添加/删除自定义的常用问题 (Quick Questions)。 | 模拟 User POST/DELETE `/api/user/quick-questions`。 | `{ "title": "日报", "question": "写一份日报", "agent_id": 1 }` | HTTP 201 Created; 再次查询列表能看到该问题。 | | **报表监控** | **仪表盘** | 管理员查看系统概览 (Agent 数、用户数、对话总数)。 | 模拟 Admin GET `/api/admin/dashboard` (或各统计接口)。 | Header: `X-Role: admin` | HTTP 200 OK; 返回 `{ "total_agents": 10, "total_users": 50 ... }`。 | | **报表监控** | **数据导出** | 管理员导出用户、日志等数据为 Excel/CSV。 | 模拟 Admin GET `/api/admin/database/{table_name}`。 | URL Path: `/api/admin/database/chat_logs` | HTTP 200 OK; 返回完整数据列表。 | +| **发货通知** | **建单幂等** | 相同 `create_idempotency_key` 重复请求返回同一批次,不重复启动 orchestrator。 | `test_shipping_notice_batches.py`:Workspace API 双次 POST;断言 `idempotent_replay`、任务数、orchestrator 调用次数。 | Header `Idempotency-Key` + 相同 notice 文件 | 第二次 `batch_no` 相同;`idempotent_replay=true`;DB 仅 1 批次。 | +| **发货通知** | **同请求文件去重** | 同一次上传中内容相同文件只建 1 个任务。 | `test_notice_intake.py` / `test_shipping_notice_batches.py`:2 个同字节不同文件名。 | 2× 相同内容 PDF | `duplicate_count=1`;`tasks` 长度 1。 | +| **发货通知** | **双击/重试前端锁** | 建批提交中重复发送被消费,幂等键在重试间保持稳定。 | `useChatShippingUploadHandler.spec.ts` / `useChatShippingSendHandler.spec.ts` | 连续点击发送 | `startChatTurn` 仅 1 次;失败重试复用同一 `idempotency_key`。 | diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 999f6704..7434db69 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -222,15 +222,30 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F * @param conversationId - 可选会话 ID * @returns 批次与任务创建结果 */ -export async function createWorkspaceShippingBatchFromNotices(files: File[], conversationId?: string) { +export async function createWorkspaceShippingBatchFromNotices( + files: File[], + conversationId?: string, + idempotencyKey?: string, +) { const form = new FormData(); files.forEach((file) => form.append('files', file)); if (conversationId) form.append('conversation_id', conversationId); + if (idempotencyKey) form.append('idempotency_key', idempotencyKey); + const headers: Record = {}; + if (idempotencyKey) { + headers['Idempotency-Key'] = idempotencyKey; + } const body = await requestJson('/api/workspace/shipping-batches/create-from-notices', { method: 'POST', body: form }); + }>('/api/workspace/shipping-batches/create-from-notices', { + method: 'POST', + body: form, + headers, + }); return assertShippingOk(body); } diff --git a/frontend/src/features/chat/composables/useChatPage.ts b/frontend/src/features/chat/composables/useChatPage.ts index e027b28d..8cac3b9d 100644 --- a/frontend/src/features/chat/composables/useChatPage.ts +++ b/frontend/src/features/chat/composables/useChatPage.ts @@ -31,6 +31,7 @@ import { useChatStore } from '../stores/chat.store'; import { useTrainingWorkspace } from './useTrainingWorkspace'; import { matchesTrainingAgent } from '../training/trainingWorkspace.utils'; import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy'; +import { clearPendingNoticeBatchRetry } from '../shipping/useChatShippingUploadHandler'; import { createChatPageConversationApi, createChatPageLocalMessageApi, @@ -337,6 +338,7 @@ export function useChatPage() { isThinking, loadConversationState, createNewChatView, + clearPendingNoticeBatchRetry, onConversationIdChanging: shipping.onConversationIdChanging, onConversationLoadedEmpty: shipping.onConversationLoadedEmpty, onConversationLoadFailed: shipping.onConversationLoadFailed, diff --git a/frontend/src/features/chat/composables/useChatShipping.ts b/frontend/src/features/chat/composables/useChatShipping.ts index 7658dad3..9ae5dcd5 100644 --- a/frontend/src/features/chat/composables/useChatShipping.ts +++ b/frontend/src/features/chat/composables/useChatShipping.ts @@ -27,6 +27,7 @@ import { createShippingParseReviewHandlers, createShippingSendHandlers, createShippingUploadHandlers, + onNoticeBatchConversationChanging, findHistorySessionForShippingTask, findLatestShippingTaskId, getShippingInventoryMappingPayload, @@ -666,6 +667,7 @@ export function useChatShipping(options: UseChatShippingOptions) { handleShippingInventorySelected, shippingSuggestedPrompt, useShippingSuggestedPrompt, + isShippingNoticeBatchSubmitting, } = createShippingUploadHandlers({ conversationId, currentAgentId, @@ -738,6 +740,7 @@ export function useChatShipping(options: UseChatShippingOptions) { handleShippingMenuAction, handleShippingAutoUploadFile, handleShippingAutoUploadNoticeBatch, + isShippingNoticeBatchSubmitting, refreshShippingActions, shippingSuggestedPrompt, isShippingShortageQueryIntent, @@ -778,6 +781,7 @@ export function useChatShipping(options: UseChatShippingOptions) { }; const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => { + onNoticeBatchConversationChanging(nextId, prevId); if (prevId !== nextId) { resolvedShippingTaskId.value = ''; if (!shippingBatchNoFromQuery.value) { diff --git a/frontend/src/features/chat/page/useChatPageConversation.spec.ts b/frontend/src/features/chat/page/useChatPageConversation.spec.ts new file mode 100644 index 00000000..b442be38 --- /dev/null +++ b/frontend/src/features/chat/page/useChatPageConversation.spec.ts @@ -0,0 +1,166 @@ +/** + * features/chat/page/useChatPageConversation.spec.ts + * 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。 + * 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。 + * 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。 + */ +import { computed, ref } from 'vue'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createChatPageConversationApi } from './useChatPageConversation'; +import { + clearPendingNoticeBatchRetry, + createShippingUploadHandlers, + resetShippingNoticeBatchSubmitStateForTests, + type ShippingUploadHandlerContext, +} from '../shipping/useChatShippingUploadHandler'; + +const { listChatMessages } = vi.hoisted(() => ({ + listChatMessages: vi.fn(), +})); + +const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({ + computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => { + const content = await files[0]?.text(); + return `fp-${content || 'empty'}`; + }), +})); + +vi.mock('../api/chat.api', () => ({ + listChatMessages, +})); + +vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({ + computeNoticeFilesContentFingerprint, +})); + +const createConversationContext = () => { + const conversationId = ref('conv-a'); + const messages = ref([]); + const createNewChatView = vi.fn(() => { + conversationId.value = null; + messages.value = []; + }); + + return { + conversationId, + messages, + createNewChatView, + api: createChatPageConversationApi({ + deps: { t: (key: string) => key, msg: { warning: vi.fn() } }, + route: { path: '/chat/42', query: {} } as never, + router: { replace: vi.fn() } as never, + currentAgentId: computed(() => 42), + conversationId, + activeRunId: ref(null), + messages, + isThinking: ref(false), + loadConversationState: vi.fn(), + createNewChatView, + clearPendingNoticeBatchRetry, + onConversationIdChanging: vi.fn(), + onConversationLoadedEmpty: vi.fn(async () => undefined), + onConversationLoadFailed: vi.fn(async () => undefined), + isShippingNoticeAgent: computed(() => true), + shippingTaskIdFromQuery: computed(() => ''), + shippingBatchNoFromQuery: computed(() => ''), + clearHistory: vi.fn(), + clearAttachments: vi.fn(), + input: ref(''), + resetCurrentAgent: vi.fn(), + copiedIndex: ref(null), + resetPeripheralState: vi.fn(), + filePreviewVisible: ref(false), + previewFile: ref(null), + previewFiles: ref([]), + currentPreviewIndex: ref(0), + }), + }; +}; + +const createUploadContext = ( + conversationId: ReturnType>, + startChatTurn: ReturnType, +): ShippingUploadHandlerContext => ({ + conversationId, + currentAgentId: computed(() => 42), + attachments: ref([]), + input: ref(''), + shippingAutoFlowRequested: ref(false), + shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), + shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), + pendingShippingUploadTaskId: ref(''), + pendingShippingNoticeTaskId: ref(''), + pendingShippingInventoryFile: ref(null), + resolvedShippingTaskId: ref(''), + resolvedShippingBatchNo: ref(''), + shippingBatchSummary: ref(null), + shippingBatchTasks: ref([]), + shippingInventorySelectionActive: ref(false), + shippingInventorySelectionTaskId: ref(''), + shippingInventorySchemaPreviewCache: ref({}), + getActiveShippingTaskId: () => '', + startChatTurn, + refreshShippingActions: vi.fn(async () => undefined), + msg: { warning: vi.fn() }, + t: (key: string) => key, +}); + +describe('useChatPageConversation', () => { + beforeEach(() => { + listChatMessages.mockReset(); + computeNoticeFilesContentFingerprint.mockReset(); + computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => { + const content = await files[0]?.text(); + return `fp-${content || 'empty'}`; + }); + resetShippingNoticeBatchSubmitStateForTests(); + }); + + it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => { + const startChatTurn = vi.fn(async () => false); + const { conversationId, createNewChatView, api } = createConversationContext(); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers( + createUploadContext(conversationId, startChatTurn), + ); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + api.startNewChat(); + + expect(createNewChatView).toHaveBeenCalledTimes(1); + expect(conversationId.value).toBeNull(); + + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); + + it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => { + const startChatTurn = vi.fn(async () => false); + const { conversationId, createNewChatView, api } = createConversationContext(); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers( + createUploadContext(conversationId, startChatTurn), + ); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + api.resetChatStateForAgentChange(); + + expect(createNewChatView).toHaveBeenCalledTimes(1); + expect(conversationId.value).toBeNull(); + + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); +}); diff --git a/frontend/src/features/chat/page/useChatPageConversation.ts b/frontend/src/features/chat/page/useChatPageConversation.ts index 65687944..c8b4984b 100644 --- a/frontend/src/features/chat/page/useChatPageConversation.ts +++ b/frontend/src/features/chat/page/useChatPageConversation.ts @@ -17,6 +17,7 @@ export interface ChatPageConversationContext { isThinking: Ref; loadConversationState: (id: string, loaded: ChatMessage[]) => void; createNewChatView: () => void; + clearPendingNoticeBatchRetry: () => void; onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void; onConversationLoadedEmpty: () => Promise; onConversationLoadFailed: () => Promise; @@ -71,6 +72,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext) }; const startNewChat = () => { + ctx.clearPendingNoticeBatchRetry(); ctx.createNewChatView(); ctx.clearAttachments(); ctx.input.value = ''; @@ -84,6 +86,7 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext) }; const resetChatStateForAgentChange = () => { + ctx.clearPendingNoticeBatchRetry(); ctx.createNewChatView(); ctx.clearHistory(); ctx.clearAttachments(); diff --git a/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts new file mode 100644 index 00000000..62cc7603 --- /dev/null +++ b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts @@ -0,0 +1,23 @@ +/** + * features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts + * 用途:验证前端文件集合指纹与后端 compute_notice_items_content_fingerprint 对齐。 + */ +import { describe, expect, it } from 'vitest'; +import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency'; + +describe('shippingNoticeBatchIdempotency', () => { + it('treats duplicate files as one content set', async () => { + const content = 'same-notice-content'; + const single = new File([content], 'a.txt', { type: 'text/plain' }); + const duplicatePair = [ + new File([content], 'a.txt', { type: 'text/plain' }), + new File([content], 'b.txt', { type: 'text/plain' }), + ]; + + const singleFp = await computeNoticeFilesContentFingerprint([single]); + const duplicateFp = await computeNoticeFilesContentFingerprint(duplicatePair); + + expect(singleFp).toBeTruthy(); + expect(duplicateFp).toBe(singleFp); + }); +}); diff --git a/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts new file mode 100644 index 00000000..63feb8d9 --- /dev/null +++ b/frontend/src/features/chat/shipping/shippingNoticeBatchIdempotency.ts @@ -0,0 +1,31 @@ +/** + * features/chat/shipping/shippingNoticeBatchIdempotency.ts + * 用途:发货通知建批幂等键与文件集合指纹计算。 + * 依赖:浏览器 Web Crypto API。 + * 逻辑:useChatShippingUploadHandler 在重试时绑定「幂等键 + 文件指纹」,文件变化时生成新键。 + */ + +/** + * 将 File 列表转为与后端 notice_items 对齐的内容指纹(排序哈希后二次 SHA-256)。 + */ +export async function computeNoticeFilesContentFingerprint(files: File[]): Promise { + const hashes: string[] = []; + for (const file of files) { + if (!file) continue; + const buffer = await file.arrayBuffer(); + const digest = await crypto.subtle.digest('SHA-256', buffer); + const hex = Array.from(new Uint8Array(digest)) + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); + hashes.push(hex.toLowerCase()); + } + const uniqueHashes = [...new Set(hashes)].sort(); + if (!uniqueHashes.length) return ''; + const joined = uniqueHashes.join('|'); + const encoded = new TextEncoder().encode(joined); + const fingerprintDigest = await crypto.subtle.digest('SHA-256', encoded); + return Array.from(new Uint8Array(fingerprintDigest)) + .map((byte) => byte.toString(16).padStart(2, '0')) + .join('') + .toLowerCase(); +} diff --git a/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts b/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts new file mode 100644 index 00000000..97bd5886 --- /dev/null +++ b/frontend/src/features/chat/shipping/shippingTurnActions.spec.ts @@ -0,0 +1,22 @@ +/** + * features/chat/shipping/shippingTurnActions.spec.ts + * 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。 + */ +import { describe, expect, it } from 'vitest'; +import { buildShippingCreateBatchTurn } from './shippingTurnActions'; + +describe('shippingTurnActions', () => { + it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => { + const files = [ + new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }), + new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }), + ]; + const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001'); + + expect(turn.actionType).toBe('shipping.create_batch_from_notices'); + expect(turn.payload.conversation_id).toBe('conv-001'); + expect(turn.payload.file_count).toBe(2); + expect(turn.payload.idempotency_key).toBe('idem-key-001'); + expect(turn.files).toEqual(files); + }); +}); diff --git a/frontend/src/features/chat/shipping/shippingTurnActions.ts b/frontend/src/features/chat/shipping/shippingTurnActions.ts index e577f05d..0755a01b 100644 --- a/frontend/src/features/chat/shipping/shippingTurnActions.ts +++ b/frontend/src/features/chat/shipping/shippingTurnActions.ts @@ -78,6 +78,7 @@ export function buildShippingSubmitDecisionTurn( export function buildShippingCreateBatchTurn( files: File[], conversationId?: string | null, + idempotencyKey?: string, ): { actionType: string; displayText: string; payload: Record; files: File[] } { const count = files.length; const displayText = count === 1 @@ -89,6 +90,7 @@ export function buildShippingCreateBatchTurn( payload: { conversation_id: conversationId || undefined, file_count: count, + idempotency_key: idempotencyKey, }, files, }; diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts new file mode 100644 index 00000000..39ca0142 --- /dev/null +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts @@ -0,0 +1,74 @@ +/** + * features/chat/shipping/useChatShippingSendHandler.spec.ts + * 用途:验证建批提交中发送拦截不会回退到普通聊天发送。 + */ +import { computed, ref } from 'vue'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler'; + +const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false)); + +vi.mock('./useChatShippingUploadHandler', () => ({ + isShippingNoticeBatchSubmitting, +})); + +const createContext = ( + overrides: Partial = {}, +): ShippingSendHandlerContext => ({ + isShippingNoticeAgent: computed(() => true), + isThinking: ref(false), + isUploadingAttachments: ref(false), + messages: ref([]), + conversationId: ref('conv-send'), + history: ref([]), + input: ref(''), + attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]), + shippingAutoFlowRequested: ref(true), + resolvedShippingTaskId: ref(''), + getActiveShippingBatchNo: () => '', + currentAgentId: computed(() => 1), + selectedKb: ref(''), + attachmentPolicy: computed(() => ({ anyEnabled: true })), + getActiveShippingTaskId: () => '', + lastAssistantMessageContent: () => '', + lastAssistantShippingActions: () => [], + sendMessage: vi.fn(async () => undefined), + buildFileSpecsForSend: vi.fn(async () => []), + loadHistory: vi.fn(async () => undefined), + sendShippingMenuMessage: vi.fn(async () => undefined), + startChatTurn: vi.fn(async () => true), + openShippingInventoryPicker: vi.fn(() => true), + executeShippingDecision: vi.fn(async () => true), + executeShippingManualUpload: vi.fn(async () => true), + handleShippingMenuAction: vi.fn(async () => undefined), + handleShippingAutoUploadFile: vi.fn(async () => undefined), + handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined), + isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(), + refreshShippingActions: vi.fn(async () => undefined), + shippingSuggestedPrompt: computed(() => ''), + isShippingShortageQueryIntent: () => false, + queryShippingShortageDetails: vi.fn(async () => true), + msg: { warning: vi.fn(), info: vi.fn() }, + t: (key: string) => key, + ...overrides, +}); + +describe('useChatShippingSendHandler', () => { + beforeEach(() => { + isShippingNoticeBatchSubmitting.mockReset(); + isShippingNoticeBatchSubmitting.mockReturnValue(false); + }); + + it('consumes send while notice batch is submitting and does not call sendMessage', async () => { + isShippingNoticeBatchSubmitting.mockReturnValue(true); + const ctx = createContext(); + const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx); + + const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', ''); + + expect(consumed).toBe(true); + expect(ctx.sendMessage).not.toHaveBeenCalled(); + expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled(); + expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting'); + }); +}); diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts index a8c1acbf..cb5b5445 100644 --- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts @@ -61,6 +61,7 @@ export interface ShippingSendHandlerContext { handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise; handleShippingAutoUploadFile: (file: File) => Promise; handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise; + isShippingNoticeBatchSubmitting?: () => boolean; refreshShippingActions: () => Promise; shippingSuggestedPrompt: ComputedRef; isShippingShortageQueryIntent: (text: string) => boolean; @@ -189,6 +190,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false; if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false; if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false; + if (ctx.isShippingNoticeBatchSubmitting?.()) { + ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting')); + return true; + } const requestedAutoFlow = ctx.shippingAutoFlowRequested.value; ctx.shippingAutoFlowRequested.value = false; const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array>; diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts index 7b4f8213..6d9c6914 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts @@ -7,7 +7,10 @@ import { computed, ref } from 'vue'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { + clearPendingNoticeBatchRetry, createShippingUploadHandlers, + onNoticeBatchConversationChanging, + resetShippingNoticeBatchSubmitStateForTests, type ShippingUploadHandlerContext, } from './useChatShippingUploadHandler'; @@ -15,10 +18,21 @@ const { createWorkspaceShippingTask } = vi.hoisted(() => ({ createWorkspaceShippingTask: vi.fn(), })); +const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({ + computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => { + const content = await files[0]?.text(); + return `fp-${content || 'empty'}`; + }), +})); + vi.mock('@/features/chat/api/shipping.api', () => ({ createWorkspaceShippingTask, })); +vi.mock('./shippingNoticeBatchIdempotency', () => ({ + computeNoticeFilesContentFingerprint, +})); + const createContext = ( overrides: Partial = {}, ): ShippingUploadHandlerContext => ({ @@ -50,6 +64,12 @@ const createContext = ( describe('useChatShippingUploadHandler', () => { beforeEach(() => { createWorkspaceShippingTask.mockReset(); + computeNoticeFilesContentFingerprint.mockReset(); + computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => { + const content = await files[0]?.text(); + return `fp-${content || 'empty'}`; + }); + resetShippingNoticeBatchSubmitStateForTests(); }); it('opens inventory picker for explicit taskId instead of current active task', () => { @@ -103,6 +123,186 @@ describe('useChatShippingUploadHandler', () => { ); }); + it('double click only calls startChatTurn once and keeps stable idempotency key', async () => { + const startChatTurn = vi.fn(async () => { + await new Promise((resolve) => setTimeout(resolve, 20)); + return true; + }); + const ctx = createContext({ + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + const first = handleShippingAutoUploadNoticeBatch([file]); + const second = handleShippingAutoUploadNoticeBatch([file]); + await Promise.all([first, second]); + + expect(startChatTurn).toHaveBeenCalledTimes(1); + const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload; + expect(payload?.idempotency_key).toBeTruthy(); + }); + + it('reuses idempotency key on retry and generates new key after success', async () => { + let attempt = 0; + const startChatTurn = vi.fn(async () => { + attempt += 1; + return attempt >= 2; + }); + const ctx = createContext({ + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + await handleShippingAutoUploadNoticeBatch([file]); + const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBe(secondKey); + expect(thirdKey).not.toBe(secondKey); + }); + + it('generates new idempotency key when files change after a failed attempt', async () => { + const startChatTurn = vi.fn(async () => false); + const ctx = createContext({ + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' }); + const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([firstFile]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + await handleShippingAutoUploadNoticeBatch([secondFile]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); + + it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => { + const conversationId = ref(null); + const startChatTurn = vi.fn(async () => { + conversationId.value = 'conv-server-new'; + return false; + }); + const ctx = createContext({ + conversationId, + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBe(firstKey); + }); + + it('generates new idempotency key when switching from new chat to historical session', async () => { + const startChatTurn = vi.fn(async () => false); + const conversationId = ref(null); + const ctx = createContext({ + conversationId, + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + onNoticeBatchConversationChanging('conv-history', ''); + conversationId.value = 'conv-history'; + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); + + it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => { + const startChatTurn = vi.fn(async () => false); + const conversationId = ref('conv-a'); + const ctx = createContext({ + conversationId, + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + clearPendingNoticeBatchRetry(); + conversationId.value = null; + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); + + it('generates new idempotency key when conversation changes after a failed attempt', async () => { + const startChatTurn = vi.fn(async () => false); + const conversationId = ref('conv-a'); + const ctx = createContext({ + conversationId, + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await handleShippingAutoUploadNoticeBatch([file]); + const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + onNoticeBatchConversationChanging('conv-b', 'conv-a'); + conversationId.value = 'conv-b'; + await handleShippingAutoUploadNoticeBatch([file]); + const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record })?.payload?.idempotency_key; + + expect(firstKey).toBeTruthy(); + expect(secondKey).toBeTruthy(); + expect(secondKey).not.toBe(firstKey); + }); + + it('releases submit lock when fingerprint computation fails', async () => { + computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed')); + const startChatTurn = vi.fn(async () => true); + const ctx = createContext({ + getActiveShippingTaskId: () => '', + startChatTurn, + }); + const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx); + const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' }); + + await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed'); + expect(startChatTurn).not.toHaveBeenCalled(); + expect(isShippingNoticeBatchSubmitting()).toBe(false); + + computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice'); + await handleShippingAutoUploadNoticeBatch([file]); + expect(startChatTurn).toHaveBeenCalledTimes(1); + }); + it('does not open notice picker when both explicit taskId and active task are missing', () => { const noticeClick = vi.fn(); const warning = vi.fn(); diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts index a2079861..19f151cc 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts @@ -2,7 +2,7 @@ * features/chat/shipping/useChatShippingUploadHandler.ts * 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。 * 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。 - * 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。 + * 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。 */ import { computed } from 'vue'; import { @@ -11,12 +11,91 @@ import { } from '@/features/chat/api/shipping.api'; import { extractExt } from '../constants/shipping'; import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions'; +import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency'; import { classifyShippingUploadFile } from './shippingUploadPrompt'; import type { StartChatTurnOptions } from '../types/chat-turn.types'; import type { ChatMessage } from '../types/chat.types'; import type { PendingAttachment } from '../types/shipping.types'; import type { ComputedRef, Ref } from 'vue'; +let noticeBatchSubmitting = false; + +interface PendingNoticeBatchRetryState { + conversationId: string; + idempotencyKey: string; + fileFingerprint: string; +} + +let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null; + +function normalizeConversationId(conversationId: string | null | undefined): string { + return String(conversationId || '').trim(); +} + +function clearPendingNoticeBatchRetryState(): void { + pendingNoticeBatchRetry = null; +} + +/** + * 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。 + */ +export function clearPendingNoticeBatchRetry(): void { + clearPendingNoticeBatchRetryState(); +} + +/** + * 判断待重试状态是否应绑定到当前会话。 + * 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。 + */ +function reconcilePendingNoticeBatchConversation( + pending: PendingNoticeBatchRetryState, + conversationKey: string, +): void { + const pendingKey = pending.conversationId; + if (pendingKey === conversationKey) { + return; + } + if (!pendingKey && conversationKey) { + pending.conversationId = conversationKey; + return; + } + if (pendingKey && !conversationKey) { + clearPendingNoticeBatchRetryState(); + return; + } + if (pendingKey && conversationKey && pendingKey !== conversationKey) { + clearPendingNoticeBatchRetryState(); + } +} + +/** + * 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。 + * 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。 + */ +export function onNoticeBatchConversationChanging( + nextId: string, + prevId?: string | null, +): void { + const next = normalizeConversationId(nextId); + const prev = normalizeConversationId(prevId); + if (next !== prev) { + clearPendingNoticeBatchRetryState(); + } +} + +/** + * 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。 + */ +export function isShippingNoticeBatchSubmitting(): boolean { + return noticeBatchSubmitting; +} + +/** 单测重置模块级建批提交状态。 */ +export function resetShippingNoticeBatchSubmitStateForTests(): void { + noticeBatchSubmitting = false; + clearPendingNoticeBatchRetry(); +} + export interface ShippingUploadHandlerContext { conversationId: Ref; currentAgentId: ComputedRef; @@ -135,25 +214,58 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) }; const runNoticeBatchChatTurn = async (files: File[]) => { - const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value); - const ok = await ctx.startChatTurn({ - agentId: ctx.currentAgentId.value, - inputType: 'upload_followup', - displayText: turn.displayText, - actionType: turn.actionType, - payload: turn.payload, - files: turn.files, - hooks: { - onAssistantMessageFinished: async (assistantMsg) => { - syncBatchContextFromTurnMessage(assistantMsg); - void ctx.refreshShippingActions(); + if (noticeBatchSubmitting) { + return true; + } + noticeBatchSubmitting = true; + try { + const conversationKey = normalizeConversationId(ctx.conversationId.value); + const fileFingerprint = await computeNoticeFilesContentFingerprint(files); + if (pendingNoticeBatchRetry) { + reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey); + } + if ( + pendingNoticeBatchRetry + && pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint + ) { + clearPendingNoticeBatchRetryState(); + } + if (!pendingNoticeBatchRetry) { + pendingNoticeBatchRetry = { + conversationId: conversationKey, + idempotencyKey: crypto.randomUUID(), + fileFingerprint, + }; + } else { + pendingNoticeBatchRetry.fileFingerprint = fileFingerprint; + } + const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey; + const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey); + const ok = await ctx.startChatTurn({ + agentId: ctx.currentAgentId.value, + inputType: 'upload_followup', + displayText: turn.displayText, + actionType: turn.actionType, + payload: turn.payload, + files: turn.files, + hooks: { + onAssistantMessageFinished: async (assistantMsg) => { + syncBatchContextFromTurnMessage(assistantMsg); + void ctx.refreshShippingActions(); + }, }, - }, - }); - if (!ok) { - ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed')); + }); + if (ok) { + if (pendingNoticeBatchRetry?.conversationId === conversationKey) { + clearPendingNoticeBatchRetryState(); + } + } else { + ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed')); + } + return ok; + } finally { + noticeBatchSubmitting = false; } - return ok; }; const syncBatchContextFromNoticeResponse = (result: Record | null | undefined) => { @@ -317,5 +429,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) handleShippingInventorySelected, shippingSuggestedPrompt, useShippingSuggestedPrompt, + isShippingNoticeBatchSubmitting, }; } diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index 980da877..1fbd9b2f 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -272,12 +272,28 @@ export interface ShippingTaskCreateResponse { data?: Record; } +export interface ShippingNoticeFileSummary { + total_files: number; + accepted_count: number; + rejected_count: number; + duplicate_count: number; + accepted_files?: Array>; + rejected_files?: Array>; + duplicate_files?: Array<{ + filename: string; + duplicate_of: string; + content_hash?: string; + }>; +} + export interface ShippingNoticeUploadResponse { status: string; message?: string; task_id?: string; batch_no?: string; checkpoint?: string; + idempotent_replay?: boolean; + file_summary?: ShippingNoticeFileSummary; data?: Record & { batch?: ShippingBatchSummary; focus_task?: ShippingTaskSummary | null; diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index e4458ff5..005994bf 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -23,6 +23,9 @@ "shippingNoticeInventoryUploadStarted": "I selected inventory file {fileName}. Uploading it and reading the inventory columns now.", "shippingNoticeUploadOk": "Upload succeeded.", "shippingNoticeUploadFailed": "Shipping notice upload failed.", + "shippingNoticeBatchSubmitting": "Shipping notice submission is in progress. Please do not repeat the action.", + "shippingNoticeBatchReplayed": "Restored the previously created batch.", + "shippingNoticeDuplicatesRemoved": "Duplicate files were removed automatically.", "shippingInventoryUploadFailed": "Inventory upload failed.", "shippingNoticeRefreshDone": "Current task status refreshed.", "shippingNoticeRetryUploadAction": "Retry freight upload", diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index 5a40de6e..492ce62f 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -34,6 +34,9 @@ "SHIPPING_INVENTORY_IDENTITY_MISMATCH": "Inventory snapshot does not match the task inventory source. Re-fetch or upload inventory.", "SHIPPING_INVENTORY_SOURCE_GATE_BLOCKED": "Inventory source is not ready. This step is blocked.", "SHIPPING_INVENTORY_WAREHOUSE_ID_NOT_ALLOWED": "Callback warehouse ID is not in the allowed list.", - "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "Reused inventory snapshot content does not match the callback file." + "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "Reused inventory snapshot content does not match the callback file.", + "SHIPPING_NOTICE_EXACT_DUPLICATE": "This file already exists in an in-progress task. Please do not submit it again.", + "SHIPPING_BATCH_IDEMPOTENCY_CONFLICT": "Batch creation request conflicted. Please refresh and try again.", + "SHIPPING_IDEMPOTENCY_KEY_INVALID": "Invalid batch idempotency key format." } } diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index d1f32c85..f4ae3401 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -23,6 +23,9 @@ "shippingNoticeInventoryUploadStarted": "เลือกไฟล์สต็อก {fileName} แล้ว กำลังอัปโหลดและอ่านคอลัมน์สต็อก", "shippingNoticeUploadOk": "อัปโหลดสำเร็จ", "shippingNoticeUploadFailed": "อัปโหลดใบแจ้งจัดส่งล้มเหลว", + "shippingNoticeBatchSubmitting": "กำลังส่งใบแจ้งจัดส่ง โปรดอย่าทำซ้ำ", + "shippingNoticeBatchReplayed": "กู้คืนแบตช์ที่สร้างไว้ก่อนหน้าแล้ว", + "shippingNoticeDuplicatesRemoved": "ลบไฟล์ที่ซ้ำกันโดยอัตโนมัติแล้ว", "shippingInventoryUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว", "shippingNoticeRefreshDone": "รีเฟรชสถานะงานปัจจุบันแล้ว", "shippingNoticeRetryUploadAction": "ลองอัปโหลดไปยังระบบขนส่งอีกครั้ง", diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index f1c05847..ddf5e218 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -34,6 +34,9 @@ "SHIPPING_INVENTORY_IDENTITY_MISMATCH": "สแนปช็อตสต็อกไม่ตรงกับแหล่งสต็อกของงาน โปรดดึงหรืออัปโหลดสต็อกใหม่", "SHIPPING_INVENTORY_SOURCE_GATE_BLOCKED": "แหล่งสต็อกยังไม่พร้อม ขั้นตอนนี้ถูกบล็อก", "SHIPPING_INVENTORY_WAREHOUSE_ID_NOT_ALLOWED": "รหัสคลังจาก callback ไม่อยู่ในรายการที่อนุญาต", - "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "เนื้อหาไฟล์ callback ไม่ตรงกับสแนปช็อตสต็อกที่นำกลับมาใช้" + "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "เนื้อหาไฟล์ callback ไม่ตรงกับสแนปช็อตสต็อกที่นำกลับมาใช้", + "SHIPPING_NOTICE_EXACT_DUPLICATE": "ไฟล์นี้มีอยู่ในงานที่กำลังดำเนินการแล้ว โปรดอย่าส่งซ้ำ", + "SHIPPING_BATCH_IDEMPOTENCY_CONFLICT": "คำขอสร้างแบตช์ขัดแย้งกัน โปรดรีเฟรชแล้วลองใหม่", + "SHIPPING_IDEMPOTENCY_KEY_INVALID": "รูปแบบคีย์ idempotency สำหรับสร้างแบตช์ไม่ถูกต้อง" } } diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index 67a16b12..27d681a2 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -23,6 +23,9 @@ "shippingNoticeInventoryUploadStarted": "我已选择库存文件《{fileName}》,正在上传并读取库存列名。", "shippingNoticeUploadOk": "上传成功。", "shippingNoticeUploadFailed": "发货通知上传失败。", + "shippingNoticeBatchSubmitting": "发货通知正在提交,请勿重复操作。", + "shippingNoticeBatchReplayed": "已恢复此前创建的批次。", + "shippingNoticeDuplicatesRemoved": "已自动移除重复文件。", "shippingInventoryUploadFailed": "库存文件上传失败。", "shippingNoticeRefreshDone": "已刷新当前任务状态。", "shippingNoticeRetryUploadAction": "重试上传货代", diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index 7af7a85a..05dcd4b3 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -34,6 +34,9 @@ "SHIPPING_INVENTORY_IDENTITY_MISMATCH": "库存快照与任务库存源不一致,请重新获取或上传库存。", "SHIPPING_INVENTORY_SOURCE_GATE_BLOCKED": "库存源未就绪,当前步骤已被阻断。", "SHIPPING_INVENTORY_WAREHOUSE_ID_NOT_ALLOWED": "回调库位不在配置允许列表中。", - "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "复用库存快照时回调文件与托管文件内容不一致。" + "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "复用库存快照时回调文件与托管文件内容不一致。", + "SHIPPING_NOTICE_EXACT_DUPLICATE": "该文件已存在于进行中的任务,请勿重复提交。", + "SHIPPING_BATCH_IDEMPOTENCY_CONFLICT": "建单请求冲突,请刷新后重试。", + "SHIPPING_IDEMPOTENCY_KEY_INVALID": "建单幂等键格式无效。" } } diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index 3fe58220..2c6283b5 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -23,6 +23,9 @@ "shippingNoticeInventoryUploadStarted": "我已選擇庫存檔案《{fileName}》,正在上傳並讀取庫存欄位。", "shippingNoticeUploadOk": "上傳成功。", "shippingNoticeUploadFailed": "發貨通知上傳失敗。", + "shippingNoticeBatchSubmitting": "發貨通知正在提交,請勿重複操作。", + "shippingNoticeBatchReplayed": "已恢復此前建立的批次。", + "shippingNoticeDuplicatesRemoved": "已自動移除重複檔案。", "shippingInventoryUploadFailed": "庫存檔案上傳失敗。", "shippingNoticeRefreshDone": "已重新整理目前任務狀態。", "shippingNoticeRetryUploadAction": "重試上傳貨代", diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index 6bbaf4a6..eec96153 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -34,6 +34,9 @@ "SHIPPING_INVENTORY_IDENTITY_MISMATCH": "庫存快照與任務庫存源不一致,請重新取得或上傳庫存。", "SHIPPING_INVENTORY_SOURCE_GATE_BLOCKED": "庫存源未就緒,當前步驟已被阻斷。", "SHIPPING_INVENTORY_WAREHOUSE_ID_NOT_ALLOWED": "回調庫位不在設定允許清單中。", - "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "複用庫存快照時回調檔案與託管檔案內容不一致。" + "SHIPPING_INVENTORY_REUSED_SNAPSHOT_CONTENT_MISMATCH": "複用庫存快照時回調檔案與託管檔案內容不一致。", + "SHIPPING_NOTICE_EXACT_DUPLICATE": "該檔案已存在於進行中的任務,請勿重複提交。", + "SHIPPING_BATCH_IDEMPOTENCY_CONFLICT": "建單請求衝突,請重新整理後重試。", + "SHIPPING_IDEMPOTENCY_KEY_INVALID": "建單冪等鍵格式無效。" } } From 729546a7b79753ab667659ac2effe95273f3309b Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 14 Jul 2026 09:14:44 +0800 Subject: [PATCH 3/5] =?UTF-8?q?feat(file-check):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=B5=84=E4=BA=A7=E7=AE=A1=E7=90=86=E4=B8=8E?= =?UTF-8?q?=E6=B8=85=E7=90=86=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E3=80=81=E6=9F=A5=E8=AF=A2=E3=80=81=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=8F=8A=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/__init__.py | 13 +- backend/app/api/__init__.py | 2 + backend/app/api/files/__init__.py | 11 + backend/app/api/files/assets.py | 80 +++ backend/app/api/workspace/shipping_notice.py | 104 ++++ backend/app/core/config/settings.py | 10 + backend/app/core/errors.py | 28 +- backend/app/jobs/handlers/__init__.py | 2 +- .../jobs/handlers/shipping_notice_parse.py | 102 ++++ backend/app/jobs/store.py | 44 +- backend/app/jobs/types.py | 3 +- backend/app/models/__init__.py | 4 + backend/app/models/file_asset.py | 49 ++ backend/app/models/shipping.py | 45 ++ backend/app/services/chat/turn_runtime.py | 7 +- backend/app/services/file_assets/__init__.py | 7 + backend/app/services/file_assets/cleanup.py | 83 +++ .../services/file_assets/cleanup_schedule.py | 157 ++++++ backend/app/services/file_assets/service.py | 200 ++++++++ backend/app/services/file_assets/storage.py | 132 +++++ .../schedule/file_asset_cleanup_job.py | 26 + backend/app/services/schedule/job_registry.py | 9 + .../shipping_notice/batch_from_intakes.py | 261 ++++++++++ .../shipping_notice/chat_action_handlers.py | 53 ++ .../shipping_notice/intake_parse_workflow.py | 254 ++++++++++ .../shipping_notice/intake_service.py | 251 +++++++++ .../services/shipping_notice/queue_service.py | 5 +- .../services/shipping_notice/task_workflow.py | 2 + ...f2a3b5_seed_file_asset_cleanup_schedule.py | 116 +++++ ...file_assets_and_shipping_notice_intakes.py | 157 ++++++ backend/tests/test_shipping_notice_intakes.py | 477 ++++++++++++++++++ .../src/features/chat/api/shipping.api.ts | 64 +++ .../features/chat/components/ChatInputBar.vue | 26 +- .../chat/components/ChatViewContent.vue | 1 + .../features/chat/composables/useChatPage.ts | 13 + .../chat/composables/useChatShipping.ts | 50 ++ .../shippingNoticeBatchIdempotency.ts | 7 + .../chat/shipping/shippingTurnActions.ts | 23 + .../shipping/useChatShippingSendHandler.ts | 27 + .../shipping/useChatShippingUploadHandler.ts | 66 ++- .../chat/shipping/useShippingNoticeIntakes.ts | 276 ++++++++++ .../features/chat/types/shipping.api.types.ts | 21 + .../src/features/chat/types/shipping.types.ts | 43 +- frontend/src/locales/en/chat.json | 8 + frontend/src/locales/en/errors.json | 16 +- frontend/src/locales/th/chat.json | 8 + frontend/src/locales/th/errors.json | 16 +- frontend/src/locales/zh-CN/chat.json | 8 + frontend/src/locales/zh-CN/errors.json | 16 +- frontend/src/locales/zh-TW/chat.json | 8 + frontend/src/locales/zh-TW/errors.json | 16 +- frontend/src/shared/api/file-assets.api.ts | 47 ++ 52 files changed, 3420 insertions(+), 34 deletions(-) create mode 100644 backend/app/api/files/__init__.py create mode 100644 backend/app/api/files/assets.py create mode 100644 backend/app/jobs/handlers/shipping_notice_parse.py create mode 100644 backend/app/models/file_asset.py create mode 100644 backend/app/services/file_assets/__init__.py create mode 100644 backend/app/services/file_assets/cleanup.py create mode 100644 backend/app/services/file_assets/cleanup_schedule.py create mode 100644 backend/app/services/file_assets/service.py create mode 100644 backend/app/services/file_assets/storage.py create mode 100644 backend/app/services/schedule/file_asset_cleanup_job.py create mode 100644 backend/app/services/shipping_notice/batch_from_intakes.py create mode 100644 backend/app/services/shipping_notice/intake_parse_workflow.py create mode 100644 backend/app/services/shipping_notice/intake_service.py create mode 100644 backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py create mode 100644 backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py create mode 100644 backend/tests/test_shipping_notice_intakes.py create mode 100644 frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts create mode 100644 frontend/src/shared/api/file-assets.api.ts diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 9d7c511a..a2540bef 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -3,7 +3,8 @@ backend/app/__init__.py 用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。 依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。 -逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter。 +逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter; + 并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。 """ import logging import uuid @@ -64,6 +65,16 @@ def create_app(config_name='default'): ensure_intent_routes_loaded() from app.services.schedule.scheduler_service import start_scheduler start_scheduler(app) + # 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口 + try: + from app.services.file_assets.cleanup_schedule import ( + ensure_default_file_asset_cleanup_schedule, + register_file_asset_cleanup_schedule_hooks, + ) + register_file_asset_cleanup_schedule_hooks() + ensure_default_file_asset_cleanup_schedule() + except Exception as exc: # pragma: no cover - 表未就绪时容忍 + logger.warning('Failed to ensure file-asset-cleanup 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 808ca7b9..f85537bf 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -39,6 +39,7 @@ def register_blueprints(app: Flask) -> None: workspace_shipping_notice_bp, ) from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp + from app.api.files import files_bp app.register_blueprint(chat_bp, url_prefix='/api/chat') app.register_blueprint(admin_bp, url_prefix='/api/admin') @@ -60,3 +61,4 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') app.register_blueprint(speech_bp, url_prefix='/api/speech') app.register_blueprint(training_admin_bp, url_prefix='/api/admin') + app.register_blueprint(files_bp, url_prefix='/api/files') diff --git a/backend/app/api/files/__init__.py b/backend/app/api/files/__init__.py new file mode 100644 index 00000000..6f83cae9 --- /dev/null +++ b/backend/app/api/files/__init__.py @@ -0,0 +1,11 @@ +""" +backend/app/api/files/__init__.py + +用途:平台级文件资产 API 包入口。 +依赖:files.assets。 +逻辑:register_blueprints 挂载 /api/files。 +""" + +from app.api.files.assets import files_bp + +__all__ = ['files_bp'] diff --git a/backend/app/api/files/assets.py b/backend/app/api/files/assets.py new file mode 100644 index 00000000..9c6243a5 --- /dev/null +++ b/backend/app/api/files/assets.py @@ -0,0 +1,80 @@ +""" +backend/app/api/files/assets.py + +用途:通用文件资产上传、查询、删除与受控下载 API。 +依赖:file_assets.service、app.core.auth.jwt、app.core.response。 +逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。 +""" + +from __future__ import annotations + +import io + +from flask import Blueprint, g, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import UnauthorizedError +from app.core.response import ok +from app.services.file_assets.service import ( + delete_temporary_asset, + get_asset_for_user, + read_asset_bytes, + serialize_asset_public, + upload_file_asset, +) + +files_bp = Blueprint('files', __name__) + + +def _require_user(): + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +@files_bp.route('/assets', methods=['POST']) +def upload_asset(): + """上传文件并创建 FileAsset。""" + user = _require_user() + upload = request.files.get('file') + if not upload: + from app.core.errors import ValidationError + + raise ValidationError('file is required') + if not upload.filename: + from app.core.errors import ValidationError + + raise ValidationError('file is required') + data = upload_file_asset(user_id=user.id, upload=upload) + return ok(data, request_id=getattr(g, 'request_id', None), status=201) + + +@files_bp.route('/assets/', methods=['GET']) +def get_asset(asset_no: str): + """查询当前用户的文件资产元数据。""" + user = _require_user() + asset = get_asset_for_user(asset_no, user.id) + return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None)) + + +@files_bp.route('/assets/', methods=['DELETE']) +def delete_asset(asset_no: str): + """逻辑删除未引用的临时资产。""" + user = _require_user() + delete_temporary_asset(asset_no=asset_no, user_id=user.id) + return ok({'deleted': True}, request_id=getattr(g, 'request_id', None)) + + +@files_bp.route('/assets//download', methods=['GET']) +def download_asset(asset_no: str): + """鉴权后流式下载文件内容。""" + user = _require_user() + asset = get_asset_for_user(asset_no, user.id) + data = read_asset_bytes(asset) + return send_file( + io.BytesIO(data), + mimetype=asset.mime_type or 'application/octet-stream', + as_attachment=True, + download_name=asset.original_filename, + ) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 1209f9c3..81471d71 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -589,6 +589,110 @@ def workspace_shipping_task_export(task_no: str): path, download_name = resolved return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET']) +def workspace_list_shipping_notice_intakes(): + """列出当前会话下未消费的活跃接入记录。""" + user = _require_user() + conversation_id = str(request.args.get('conversation_id') or '').strip() or None + status = str(request.args.get('status') or '').strip().lower() + from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation + + if status and status != 'active': + return _ok({'items': []}) + items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id) + return _ok({'items': items}) + + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST']) +def workspace_create_shipping_notice_intake(): + """基于 FileAsset 创建发货通知接入记录并投递预解析任务。""" + user = _require_user() + body = request.get_json(silent=True) or {} + asset_no = str(body.get('asset_no') or '').strip() + if not asset_no: + raise ValidationError('asset_no is required') + conversation_id = str(body.get('conversation_id') or '').strip() or None + from app.services.shipping_notice.intake_service import create_shipping_notice_intake + + data = create_shipping_notice_intake( + user_id=user.id, + asset_no=asset_no, + conversation_id=conversation_id, + ) + return ok(data, request_id=getattr(g, 'request_id', None), status=202) + + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes/', methods=['GET']) +def workspace_get_shipping_notice_intake(intake_no: str): + """查询单个接入记录。""" + user = _require_user() + from app.services.shipping_notice.intake_service import get_intake_detail + + return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no)) + + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST']) +def workspace_shipping_notice_intake_statuses(): + """批量查询接入状态。""" + user = _require_user() + body = request.get_json(silent=True) or {} + intake_nos = body.get('intake_nos') + if not isinstance(intake_nos, list): + raise ValidationError('intake_nos is required') + from app.services.shipping_notice.intake_service import get_intake_statuses + + return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)}) + + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes//retry', methods=['POST']) +def workspace_retry_shipping_notice_intake(intake_no: str): + """重试失败的预解析。""" + user = _require_user() + from app.services.shipping_notice.intake_service import retry_intake_parse + + return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no)) + + +@workspace_shipping_notice_bp.route('/shipping-notice/intakes/', methods=['DELETE']) +def workspace_cancel_shipping_notice_intake(intake_no: str): + """取消未消费接入记录。""" + user = _require_user() + from app.services.shipping_notice.intake_service import cancel_intake + + cancel_intake(user_id=user.id, intake_no=intake_no) + return _ok({'cancelled': True}) + + +@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST']) +def workspace_create_shipping_batch_from_intakes(): + """从已解析接入记录确认建批。""" + user = _require_user() + body = request.get_json(silent=True) or {} + intake_nos = body.get('intake_nos') + if not isinstance(intake_nos, list) or not intake_nos: + raise ValidationError('intake_nos is required') + conversation_id = str(body.get('conversation_id') or '').strip() or None + from app.services.shipping_notice.batch_create_idempotency import ( + normalize_create_idempotency_key, + warn_missing_create_idempotency_key, + ) + from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes + + idempotency_key = normalize_create_idempotency_key( + request.headers.get('Idempotency-Key') or body.get('idempotency_key') + ) + if not idempotency_key: + warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes') + result = create_shipping_batch_from_intakes( + user_id=user.id, + conversation_id=conversation_id, + intake_nos=[str(item) for item in intake_nos], + create_idempotency_key=idempotency_key, + ) + return _ok(result) + + @workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST']) def workspace_retry_shipping_batch_pending(batch_no: str): """重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 0cc3ee59..a6d5f8eb 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -367,6 +367,16 @@ class Config: MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true' MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides') MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000') + MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets') + FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30')) + FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72')) + FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300')) + SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72')) + SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3')) + SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300') + ) + SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v1') class DevelopmentConfig(Config): diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py index bd84e092..b4c38d2c 100644 --- a/backend/app/core/errors.py +++ b/backend/app/core/errors.py @@ -22,9 +22,15 @@ class AppError(Exception): class ValidationError(AppError): - def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None): + def __init__( + self, + message: str = "Invalid request parameters", + *, + code: str = "VALIDATION.INVALID_PARAM", + details: dict[str, Any] | None = None, + ): super().__init__( - code="VALIDATION.INVALID_PARAM", + code=code, message=message, http_status=400, details=details or {}, @@ -38,13 +44,23 @@ class UnauthorizedError(AppError): class ForbiddenError(AppError): - def __init__(self, message: str = "Forbidden"): - super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False) + def __init__( + self, + message: str = "Forbidden", + *, + code: str = "AUTH.FORBIDDEN", + ): + super().__init__(code=code, message=message, http_status=403, retryable=False) class NotFoundError(AppError): - def __init__(self, message: str = "Resource not found"): - super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False) + def __init__( + self, + message: str = "Resource not found", + *, + code: str = "RESOURCE.NOT_FOUND", + ): + super().__init__(code=code, message=message, http_status=404, retryable=False) class ConflictError(AppError): diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index ce31fd52..897e77b5 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py 逻辑:Wave 2 起在 worker 启动前 import 本包。 """ -from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401 +from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401 diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py new file mode 100644 index 00000000..95cbeb67 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_notice_parse.py @@ -0,0 +1,102 @@ +""" +backend/app/jobs/handlers/shipping_notice_parse.py + +用途:发货通知接入记录异步预解析 handler。 +依赖:jobs.context、jobs.registry、intake_parse_workflow。 +逻辑:worker 消费 shipping_notice_parse 队列任务,更新 intake 状态 parsed/parse_failed。 + 领取与写回前均跳过 cancelled/expired/consumed,避免用户取消后被重新解析。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import NotFoundError +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import FileAsset, Job, ShippingNoticeIntake +from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + +# 终态:不可再领取解析;含用户取消与 TTL 过期 +_SKIP_CLAIM_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'}) +# 允许领取进入 parsing 的状态(含失败后重试) +_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parsing', 'parse_failed'}) + + +def _load_asset(asset_id: int) -> FileAsset: + asset = db.session.get(FileAsset, asset_id) + if not asset or asset.deleted_at is not None: + raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在') + return asset + + +@register_handler(JobType.SHIPPING_NOTICE_PARSE) +def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: + """ + 消费发货通知预解析任务。 + Args: + ctx: Worker 上下文。 + payload: 须含 job_id 或 intake_no。 + """ + raw_job_id = payload.get('job_id') + job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + intake_no = str( + (job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or '' + ).strip().upper() + if not intake_no: + if job: + fail_job(job, error='missing intake_no') + raise RuntimeError('missing intake_no') + + intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first() + if not intake: + if job: + fail_job(job, error=f'intake not found: {intake_no}') + raise RuntimeError(f'intake not found: {intake_no}') + + # [STEP 1] 领取前跳过终态(含 cancelled/expired) + if intake.parse_status in _SKIP_CLAIM_STATUSES: + if job: + finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True}) + return + if intake.parse_status not in _CLAIMABLE_STATUSES: + if job: + finish_job(job, result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True}) + return + + intake.parse_status = 'parsing' + intake.updated_at = datetime.utcnow() + db.session.commit() + + asset = _load_asset(intake.asset_id) + try: + result = run_intake_parse(intake, asset) + if job: + refreshed = db.session.get(Job, job.id) + if refreshed and refreshed.status == 'running': + status = str(result.get('status') or '') + if status in {'parsed', 'skipped'}: + finish_job(refreshed, result=result, message='发货通知预解析完成' if status == 'parsed' else '接入已取消或过期,跳过') + else: + fail_job( + refreshed, + error=str(result.get('error_message') or intake.error_message or 'parse failed'), + retryable=False, + ) + except Exception as exc: + db.session.rollback() + intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first() + # 取消/过期后不再覆盖为 parse_failed + if intake and intake.parse_status not in _SKIP_CLAIM_STATUSES: + intake.parse_status = 'parse_failed' + intake.error_code = 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' + intake.error_message = str(exc)[:1000] + db.session.commit() + if job: + refreshed = db.session.get(Job, job.id) + if refreshed: + fail_job(refreshed, error=str(exc), retryable=True) + raise diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py index bbeeb2fb..4ac9e98f 100644 --- a/backend/app/jobs/store.py +++ b/backend/app/jobs/store.py @@ -10,7 +10,21 @@ from __future__ import annotations from typing import Any from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job -from app.models import KbJob +from app.models import Job, KbJob + + +def _normalize_generic_job(job: Job) -> dict[str, Any]: + """将通用 Job ORM 实例转为 runner/handler 使用的归一化任务 dict。""" + job_type_value = str(job.job_type or '').strip() + return { + 'id': job.id, + 'job_type': JobType(job_type_value), + 'raw_job_type': job_type_value, + 'payload': { + 'job_id': job.id, + **(job.payload_json or {}), + }, + } def _normalize_kb_job(job: KbJob) -> dict[str, Any]: @@ -59,7 +73,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None: from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs recover_stale_running_jobs() - if 'shipping_notice_run' in allowed_types: + if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types: from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs recover_stale_shipping_notice_jobs() @@ -77,30 +91,36 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None: job = claim_next_shipping_notice_job() if job: - return _normalize_kb_job(job) + return _normalize_generic_job(job) return None def mark_failed(job_id: int, *, message: str) -> None: """ - handler 未捕获异常时,将 KbJob 标记为 failed。 + handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。 Args: - job_id: KbJob 主键。 + job_id: 任务主键。 message: 失败原因(截断至 1000 字符)。 """ from datetime import datetime from app import db + from app.jobs.queue import fail_job - job = db.session.get(KbJob, job_id) - if not job or job.status != 'running': + job = db.session.get(Job, job_id) + if job and job.status == 'running': + fail_job(job, error=message[:1000], retryable=True) + return + + kb_job = db.session.get(KbJob, job_id) + if not kb_job or kb_job.status != 'running': return now = datetime.utcnow() - job.status = 'failed' - job.error_message = message[:1000] - job.message = message[:500] - job.finished_at = now - job.progress = 100 + kb_job.status = 'failed' + kb_job.error_message = message[:1000] + kb_job.message = message[:500] + kb_job.finished_at = now + kb_job.progress = 100 db.session.commit() diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 8206168b..34646c06 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -15,6 +15,7 @@ class JobType(StrEnum): KB_CLEAN = 'kb_clean' KB_DIFY_SYNC = 'kb_dify_sync' SHIPPING_NOTICE_RUN = 'shipping_notice_run' + SHIPPING_NOTICE_PARSE = 'shipping_notice_parse' SCHEDULE_RUN = 'schedule_run' FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' @@ -48,7 +49,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = { # worker --queues 参数 → 可消费的 KbJob.job_type 集合 QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'kb': frozenset({'clean', 'path_upload', 'sync_dify'}), - 'shipping': frozenset({'shipping_notice_run'}), + 'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index e09f6cd2..f076f16f 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -16,10 +16,12 @@ from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGro from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig from app.models.settings import AppSetting +from app.models.file_asset import FileAsset from app.models.shipping import ( ShippingBatch, ShippingInventoryFile, ShippingInventoryMapping, + ShippingNoticeIntake, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink, @@ -66,6 +68,8 @@ __all__ = [ 'ShippingInventoryFile', 'ShippingTaskInventoryLink', 'ShippingInventoryMapping', + 'ShippingNoticeIntake', + 'FileAsset', 'AgentGuide', 'AgentDirectoryMember', 'TrainingRecord', diff --git a/backend/app/models/file_asset.py b/backend/app/models/file_asset.py new file mode 100644 index 00000000..e74ef2ab --- /dev/null +++ b/backend/app/models/file_asset.py @@ -0,0 +1,49 @@ +""" +backend/app/models/file_asset.py + +用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。 +依赖:models.base.Base。 +逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 等业务通过 asset_id 引用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class FileAsset(Base): + """通用文件资产(私有对象存储 + 审计元数据)。""" + + __tablename__ = 'file_assets' + __table_args__ = ( + UniqueConstraint('asset_no', name='uq_file_assets_asset_no'), + Index('ix_file_assets_owner_content_hash', 'owner_user_id', 'content_hash'), + Index('ix_file_assets_lifecycle_expires', 'lifecycle_status', 'expires_at'), + Index('ix_file_assets_owner_created', 'owner_user_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + asset_no: Mapped[str] = mapped_column(String(64), nullable=False) + owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False) + tenant_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + storage_provider: Mapped[str] = mapped_column(String(32), default='minio', nullable=False) + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(512), nullable=False) + content_hash: Mapped[str] = mapped_column(String(64), nullable=False) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + extension: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + upload_status: Mapped[str] = mapped_column(String(32), default='uploading', nullable=False) + lifecycle_status: Mapped[str] = mapped_column(String(32), default='temporary', nullable=False) + reference_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 315471e5..0705f597 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -83,6 +83,12 @@ class ShippingTask(Base): source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True) + source_intake_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_notice_intakes.id'), + index=True, + nullable=True, + ) batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) @@ -280,6 +286,45 @@ class ShippingTaskInventoryLink(Base): ) +class ShippingNoticeIntake(Base): + """发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。""" + + __tablename__ = 'shipping_notice_intakes' + __table_args__ = ( + UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'), + UniqueConstraint( + 'asset_id', + 'purpose', + 'parser_version', + name='uq_shipping_notice_intakes_asset_purpose_parser', + ), + Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'), + Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'), + Index('ix_shipping_notice_intakes_expires', 'expires_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + intake_no: Mapped[str] = mapped_column(String(64), nullable=False) + asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False) + user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False) + conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False) + parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True) + extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + parser_version: Mapped[str] = mapped_column(String(32), nullable=False) + parse_job_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True) + consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + class ShippingInventoryMapping(Base): """客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。""" diff --git a/backend/app/services/chat/turn_runtime.py b/backend/app/services/chat/turn_runtime.py index 25bfd431..93775416 100644 --- a/backend/app/services/chat/turn_runtime.py +++ b/backend/app/services/chat/turn_runtime.py @@ -2,8 +2,9 @@ backend/app/services/chat/turn_runtime.py 用途:平台统一 Chat Turn 执行器,编排 SSE 生命周期、session、ChatLog 与 action 路由。 -依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema。 +依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema、db。 逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。 + 失败路径先 db.session.rollback(),再 touch_chat_session,避免 handler 脏写被一并提交。 """ from __future__ import annotations @@ -14,6 +15,7 @@ from typing import Any, Iterator from flask import current_app +from app import db from app.core.errors import AppError, ValidationError from app.services.chat.action_registry import ensure_handlers_loaded, resolve_action_handler from app.services.chat.action_schema import TurnEvent, TurnInput, parse_turn_refs_from_context @@ -183,6 +185,8 @@ class ChatTurnRuntime: getattr(exc, "code", None), exc.message, ) + # 业务失败后先 rollback,避免 handler 预占/脏写被 touch_chat_session 一并提交 + db.session.rollback() touch_chat_session(user_id, agent_id, session.session_id, status="error") yield emit_run_failed( run_id=run_id, @@ -193,6 +197,7 @@ class ChatTurnRuntime: ) except Exception as exc: current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id) + db.session.rollback() touch_chat_session(user_id, agent_id, session.session_id, status="error") yield emit_run_failed( run_id=run_id, diff --git a/backend/app/services/file_assets/__init__.py b/backend/app/services/file_assets/__init__.py new file mode 100644 index 00000000..79b03358 --- /dev/null +++ b/backend/app/services/file_assets/__init__.py @@ -0,0 +1,7 @@ +""" +backend/app/services/file_assets/__init__.py + +用途:平台级文件资产服务包入口。 +依赖:file_assets.service、file_assets.storage、file_assets.cleanup。 +逻辑:API 与 shipping intake 经 service 层读写 FileAsset 与私有 MinIO 对象。 +""" diff --git a/backend/app/services/file_assets/cleanup.py b/backend/app/services/file_assets/cleanup.py new file mode 100644 index 00000000..a0214427 --- /dev/null +++ b/backend/app/services/file_assets/cleanup.py @@ -0,0 +1,83 @@ +""" +backend/app/services/file_assets/cleanup.py + +用途:过期未引用 FileAsset 与关联 intake 的清理编排。 +依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。 +逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted; + MinIO 删除失败不伪装成功,保留记录供下次重试。 +""" + +from __future__ import annotations + +import logging +from datetime import datetime + +from sqlalchemy import or_ + +from app import db +from app.models import FileAsset, ShippingNoticeIntake +from app.services.file_assets.storage import file_asset_storage + +_LOGGER = logging.getLogger(__name__) + + +def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]: + """ + 清理过期或已标记 expired 但尚未物理删除的临时资产。 + Returns: + 统计字典:scanned/expired/deleted/errors。 + """ + now = datetime.utcnow() + assets = ( + db.session.query(FileAsset) + .filter( + FileAsset.reference_count == 0, + FileAsset.deleted_at.is_(None), + or_( + ( + (FileAsset.lifecycle_status == 'temporary') + & (FileAsset.expires_at.isnot(None)) + & (FileAsset.expires_at < now) + ), + FileAsset.lifecycle_status == 'expired', + ), + ) + .order_by(FileAsset.expires_at.asc().nullsfirst(), FileAsset.id.asc()) + .limit(max(int(limit or 100), 1)) + .all() + ) + stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0} + for asset in assets: + consumed = ( + db.session.query(ShippingNoticeIntake.id) + .filter( + ShippingNoticeIntake.asset_id == asset.id, + ShippingNoticeIntake.parse_status == 'consumed', + ) + .first() + ) + if consumed: + continue + stats['expired'] += 1 + asset.lifecycle_status = 'expired' + ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.asset_id == asset.id, + ShippingNoticeIntake.consumed_at.is_(None), + ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')), + ) + .update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False) + ) + try: + file_asset_storage.delete_object(asset.storage_key) + asset.upload_status = 'deleted' + asset.deleted_at = now + asset.updated_at = now + stats['deleted'] += 1 + except Exception: + stats['errors'] += 1 + asset.updated_at = now + _LOGGER.exception('failed to delete minio object for asset %s', asset.asset_no) + db.session.commit() + return stats diff --git a/backend/app/services/file_assets/cleanup_schedule.py b/backend/app/services/file_assets/cleanup_schedule.py new file mode 100644 index 00000000..19d9bafa --- /dev/null +++ b/backend/app/services/file_assets/cleanup_schedule.py @@ -0,0 +1,157 @@ +""" +backend/app/services/file_assets/cleanup_schedule.py + +用途:确保 platform Job file-asset-cleanup 存在默认 ScheduleTask(迁移补种 + 启动/建用户补建)。 +依赖:models.ScheduleTask/User、schedule.timezone_util.compute_next_run_at、SQLAlchemy Session 事件。 +逻辑:create_app 启动时 ensure 一次;User after_commit 用独立 Session 即时补建(原 session 已 committed 不可再发 SQL)。 +""" + +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 + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP" +DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH = "file-asset-cleanup" +DEFAULT_FILE_ASSET_CLEANUP_CRON = "0 * * * *" +DEFAULT_FILE_ASSET_CLEANUP_NAME = "临时文件资产 TTL 清理" + +_HOOKS_REGISTERED = False +_SESSION_INFO_KEY = "_seed_file_asset_cleanup" + + +def ensure_default_file_asset_cleanup_schedule( + *, + commit: bool = True, + session: Any | None = None, +) -> ScheduleTask | None: + """ + 幂等确保默认 TTL 清理排程存在。 + + 核心逻辑:若已有同 schedule_no 或同 platform_api_path 的排程则跳过; + 否则在存在至少一个用户时创建启用态排程(next_run_at 走 Cron 语义)。 + + Args: + commit: 是否立即提交。 + session: 可选独立 Session(User after_commit 钩子须传入,避免 committed 态 Session 发 SQL)。 + + Returns: + 新建或已存在的 ScheduleTask;尚无用户时返回 None。 + """ + sess = session if session is not None else db.session + existing = ( + sess.query(ScheduleTask) + .filter( + (ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) + | (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_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 file-asset-cleanup schedule: no users yet") + return None + + now = datetime.utcnow() + next_run = compute_next_run_at( + DEFAULT_FILE_ASSET_CLEANUP_CRON, + timezone_name="Asia/Shanghai", + ) or now + + task = ScheduleTask( + schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, + name=DEFAULT_FILE_ASSET_CLEANUP_NAME, + schedule_type="platform_job", + owner_user_id=int(owner.id), + cron_expr=DEFAULT_FILE_ASSET_CLEANUP_CRON, + schedule_timezone="Asia/Shanghai", + wait_seconds=0, + platform_api_path=DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH, + job_params=None, + kb_sync_enabled=False, + notify_user_ids_json=[], + notify_enabled=False, + 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_FILE_ASSET_CLEANUP_SCHEDULE_NO) + | (ScheduleTask.platform_api_path == DEFAULT_FILE_ASSET_CLEANUP_PLATFORM_PATH) + ) + .first() + ) + if existing is not None: + return existing + raise + else: + sess.flush() + _LOGGER.info( + "seeded default file-asset-cleanup schedule_no=%s owner_user_id=%s", + task.schedule_no, + owner.id, + ) + return task + + +def register_file_asset_cleanup_schedule_hooks() -> None: + """ + 注册 Session 钩子:User 插入并 commit 后立即尝试补建默认清理排程。 + + 核心逻辑:after_flush 标记;after_commit 用独立 Session 调用 ensure + (原 session 处于 committed 态不能再发 SQL)。 + """ + global _HOOKS_REGISTERED + if _HOOKS_REGISTERED: + return + + @event.listens_for(Session, "after_flush") + def _mark_user_insert(session: Session, _context) -> None: # type: ignore[no-untyped-def] + if any(isinstance(obj, User) for obj in session.new): + session.info[_SESSION_INFO_KEY] = True + + @event.listens_for(Session, "after_commit") + def _seed_after_user_commit(session: Session) -> None: + if not session.info.pop(_SESSION_INFO_KEY, False): + return + bind = session.get_bind() + if bind is None: + return + try: + with Session(bind) as seed_session: + ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session) + except Exception as exc: # pragma: no cover - 防御不阻断建用户 + _LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc) + + _HOOKS_REGISTERED = True diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py new file mode 100644 index 00000000..4640712e --- /dev/null +++ b/backend/app/services/file_assets/service.py @@ -0,0 +1,200 @@ +""" +backend/app/services/file_assets/service.py + +用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。 +依赖:file_assets.storage、models.FileAsset、Flask current_app。 +逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回。 +""" + +from __future__ import annotations + +import hashlib +import mimetypes +import os +import re +import uuid +from datetime import datetime, timedelta +from typing import Any + +from flask import current_app +from werkzeug.datastructures import FileStorage +from werkzeug.utils import secure_filename + +from app import db +from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.core.response import utc_iso +from app.models import FileAsset +from app.services.file_assets.storage import file_asset_storage + +_ALLOWED_EXTENSIONS = { + 'pdf', 'doc', 'docx', 'txt', 'md', 'log', 'html', 'htm', 'eml', + 'csv', 'png', 'jpg', 'jpeg', 'webp', +} + + +def _max_file_size_bytes() -> int: + mb = int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30) + return max(mb, 1) * 1024 * 1024 + + +def _temp_ttl_hours() -> int: + return max(int(current_app.config.get('FILE_ASSET_TEMP_TTL_HOURS', 72) or 72), 1) + + +def generate_asset_no() -> str: + """生成 FA-YYYYMMDD-XXXXXXXX 格式资产编号。""" + return f"FA-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def _normalize_extension(filename: str) -> str: + ext = os.path.splitext(str(filename or '').strip())[1].lower().lstrip('.') + return ext + + +def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str: + now = datetime.utcnow() + safe_name = secure_filename(filename) or 'file' + safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file' + return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}" + + +def _serialize_asset(asset: FileAsset) -> dict[str, Any]: + return { + 'asset_no': asset.asset_no, + 'original_filename': asset.original_filename, + 'file_size': asset.file_size, + 'mime_type': asset.mime_type, + 'content_hash': asset.content_hash, + 'upload_status': asset.upload_status, + 'lifecycle_status': asset.lifecycle_status, + 'expires_at': utc_iso(asset.expires_at), + 'created_at': utc_iso(asset.created_at), + } + + +def get_asset_for_user(asset_no: str, user_id: int) -> FileAsset: + """ + 按编号查询当前用户拥有的资产。 + Raises: + NotFoundError: 不存在或已逻辑删除。 + ForbiddenError: 非所有者。 + """ + normalized = str(asset_no or '').strip().upper() + asset = ( + db.session.query(FileAsset) + .filter(FileAsset.asset_no == normalized, FileAsset.deleted_at.is_(None)) + .first() + ) + if not asset: + raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在') + if int(asset.owner_user_id) != int(user_id): + raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问该文件资产') + return asset + + +def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]: + """ + 上传文件并创建 FileAsset 记录。 + 核心逻辑:校验类型与大小 → SHA-256 → 写 MinIO → 落库 ready/temporary。 + """ + filename = str(upload.filename or '').strip() or 'file' + ext = _normalize_extension(filename) + if ext not in _ALLOWED_EXTENSIONS: + raise ValidationError( + code='FILE_ASSET.INVALID_TYPE', + message=f'不支持的文件类型: .{ext or "unknown"}', + ) + + data = upload.read() + if not data: + raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='文件内容为空') + if len(data) > _max_file_size_bytes(): + raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='文件大小超过限制') + + content_hash = hashlib.sha256(data).hexdigest() + asset_no = generate_asset_no() + storage_key = _build_storage_key(user_id=user_id, asset_no=asset_no, filename=filename) + mime_type = upload.mimetype or mimetypes.guess_type(filename)[0] or 'application/octet-stream' + expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours()) + + asset = FileAsset( + asset_no=asset_no, + owner_user_id=int(user_id), + original_filename=filename, + storage_provider='minio', + storage_bucket=file_asset_storage.bucket_name, + storage_key=storage_key, + content_hash=content_hash, + file_size=len(data), + mime_type=mime_type, + extension=ext or None, + upload_status='uploading', + lifecycle_status='temporary', + reference_count=0, + expires_at=expires_at, + ) + db.session.add(asset) + db.session.flush() + + try: + file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type) + asset.upload_status = 'ready' + except Exception: + asset.upload_status = 'failed' + db.session.commit() + raise + + db.session.commit() + return _serialize_asset(asset) + + +def mark_asset_referenced(asset: FileAsset) -> None: + """将资产标记为被业务引用。""" + asset.lifecycle_status = 'referenced' + asset.reference_count = int(asset.reference_count or 0) + 1 + asset.expires_at = None + asset.updated_at = datetime.utcnow() + + +def delete_temporary_asset(*, asset_no: str, user_id: int) -> None: + """ + 删除未引用的临时资产:先标记 expired,再删 MinIO;成功后标记 deleted。 + Raises: + ConflictError: 已被业务引用。 + ServiceUnavailableError: MinIO 删除失败(保留 expired 供清理重试)。 + """ + asset = get_asset_for_user(asset_no, user_id) + if str(asset.lifecycle_status or '') == 'referenced' or int(asset.reference_count or 0) > 0: + raise ConflictError(code='FILE_ASSET.ALREADY_REFERENCED', message='文件已被业务引用,无法删除') + if str(asset.upload_status or '') == 'deleted' and asset.deleted_at is not None: + return + + now = datetime.utcnow() + asset.lifecycle_status = 'expired' + asset.updated_at = now + db.session.flush() + + try: + file_asset_storage.delete_object(asset.storage_key) + except Exception: + db.session.commit() + raise + + asset.upload_status = 'deleted' + asset.deleted_at = now + asset.updated_at = now + db.session.commit() + + +def read_asset_bytes(asset: FileAsset) -> bytes: + """读取资产对象字节,校验未过期/未删除。""" + if asset.deleted_at is not None: + raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在') + if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary': + raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期') + return file_asset_storage.get_bytes(asset.storage_key) + + +def serialize_asset_public(asset: FileAsset) -> dict[str, Any]: + """对外序列化资产(不含 storage_key)。""" + return _serialize_asset(asset) diff --git a/backend/app/services/file_assets/storage.py b/backend/app/services/file_assets/storage.py new file mode 100644 index 00000000..3788aa1c --- /dev/null +++ b/backend/app/services/file_assets/storage.py @@ -0,0 +1,132 @@ +""" +backend/app/services/file_assets/storage.py + +用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。 +依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。 +逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。 +""" + +from __future__ import annotations + +import io +import logging +from datetime import timedelta +from typing import BinaryIO + +from minio import Minio +from minio.error import S3Error + +from app.core.config.settings import ACTIVE_ENV_NAME, config +from app.core.errors import ServiceUnavailableError + +_LOGGER = logging.getLogger(__name__) +_cfg = config[ACTIVE_ENV_NAME] + + +class FileAssetStorage: + """私有业务文件 MinIO 存储客户端。""" + + def __init__(self) -> None: + self.client = Minio( + _cfg.MINIO_ENDPOINT, + access_key=_cfg.MINIO_ACCESS_KEY, + secret_key=_cfg.MINIO_SECRET_KEY, + secure=_cfg.MINIO_SECURE, + ) + self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip() + + def _ensure_bucket_exists(self) -> None: + """确保私有 bucket 存在,不设置 public-read policy。""" + try: + if not self.client.bucket_exists(self.bucket_name): + self.client.make_bucket(self.bucket_name) + except Exception as exc: + _LOGGER.exception('MinIO file assets bucket unavailable') + raise ServiceUnavailableError( + code='FILE_ASSET.UPLOAD_FAILED', + message='文件存储服务暂不可用,请稍后重试', + ) from exc + + def upload_bytes( + self, + *, + storage_key: str, + data: bytes, + content_type: str, + ) -> None: + """ + 上传字节流到私有 bucket。 + Raises: + ServiceUnavailableError: MinIO 不可用或上传失败。 + """ + self._ensure_bucket_exists() + stream: BinaryIO = io.BytesIO(data) + try: + self.client.put_object( + bucket_name=self.bucket_name, + object_name=storage_key, + data=stream, + length=len(data), + content_type=content_type or 'application/octet-stream', + ) + except Exception as exc: + _LOGGER.exception('MinIO upload failed key=%s', storage_key) + raise ServiceUnavailableError( + code='FILE_ASSET.UPLOAD_FAILED', + message='文件上传失败,请稍后重试', + ) from exc + + def get_bytes(self, storage_key: str) -> bytes: + """ + 读取对象字节内容。 + Raises: + ServiceUnavailableError: 读取失败(含网络异常与 S3Error)。 + """ + try: + response = self.client.get_object(self.bucket_name, storage_key) + try: + return response.read() + finally: + response.close() + response.release_conn() + except Exception as exc: + _LOGGER.exception('MinIO read failed key=%s', storage_key) + raise ServiceUnavailableError( + code='FILE_ASSET.UPLOAD_FAILED', + message='文件存储服务暂不可用,请稍后重试', + ) from exc + + def delete_object(self, storage_key: str) -> None: + """ + 删除 MinIO 对象;失败时抛出可重试 503,供清理任务重试。 + Raises: + ServiceUnavailableError: 删除失败。 + """ + try: + self.client.remove_object(self.bucket_name, storage_key) + except Exception as exc: + _LOGGER.exception('MinIO delete failed key=%s', storage_key) + raise ServiceUnavailableError( + code='FILE_ASSET.UPLOAD_FAILED', + message='文件对象删除失败,请稍后重试', + ) from exc + + def object_exists(self, storage_key: str) -> bool: + """判断对象是否存在。""" + try: + self.client.stat_object(self.bucket_name, storage_key) + return True + except S3Error: + return False + + def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str: + """生成短期受控下载 URL。""" + self._ensure_bucket_exists() + return self.client.presigned_get_object( + self.bucket_name, + storage_key, + expires=timedelta(seconds=max(int(expires_seconds or 60), 60)), + ) + + +file_asset_storage = FileAssetStorage() diff --git a/backend/app/services/schedule/file_asset_cleanup_job.py b/backend/app/services/schedule/file_asset_cleanup_job.py new file mode 100644 index 00000000..2f7192cc --- /dev/null +++ b/backend/app/services/schedule/file_asset_cleanup_job.py @@ -0,0 +1,26 @@ +""" +backend/app/services/schedule/file_asset_cleanup_job.py + +用途:排程平台 Job —— 清理过期未引用的临时文件资产。 +依赖:file_assets.cleanup。 +逻辑:platform_api_path=file-asset-cleanup 时由 job_registry 调用。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.file_assets.cleanup import cleanup_expired_temporary_assets + + +def run_file_asset_cleanup_schedule(task: Any, run: Any) -> dict[str, Any]: + """ + 执行临时文件资产 TTL 清理。 + Args: + task: ScheduleTask。 + run: ScheduleRun。 + Returns: + 清理统计。 + """ + _ = task, run + return cleanup_expired_temporary_assets(limit=200) diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index 36b519bb..0757a47b 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -129,6 +129,7 @@ def run_platform_job( def _register_builtin_platform_jobs() -> None: """模块加载时注册内置平台 Job(含参数契约)。""" from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule + 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 @@ -191,6 +192,14 @@ def _register_builtin_platform_jobs() -> None: description="同步 PLM 固资快照至本地 manifest。", category="assets", )) + register_platform_job(PlatformJobDefinition( + key="file-asset-cleanup", + label="临时文件资产清理", + label_key="admin.schedule.form.platformJobFileAssetCleanup", + handler=run_file_asset_cleanup_schedule, + description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。", + category="files", + )) _register_builtin_platform_jobs() diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py new file mode 100644 index 00000000..0a8cb81c --- /dev/null +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -0,0 +1,261 @@ +""" +backend/app/services/shipping_notice/batch_from_intakes.py + +用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。 +依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency。 +逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。 + 先幂等回放;按 content_hash 去重后 FOR UPDATE 预占 consumed;建批失败须 rollback 预占。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy import select + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import FileAsset, ShippingNoticeIntake, ShippingTask +from app.services.shipping_notice.batch_create_idempotency import ( + build_existing_batch_tool_response, + find_batch_by_create_idempotency, + normalize_create_idempotency_key, +) +from app.services.shipping_notice.batch_from_notices import create_shipping_batch_from_notice_items +from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item +from app.services.shipping_notice.intake_service import mark_intakes_consumed + + +def _batch_intake_nos(batch_id: int) -> set[str]: + """ + 读取批次关联的全部 intake_no 集合。 + + 核心逻辑:以 consumed_batch_id 为准(含 content_hash 去重后的附属 intake), + 避免仅按 task.source_intake_id 导致幂等集合校验误报冲突。 + """ + rows = ( + db.session.query(ShippingNoticeIntake.intake_no) + .filter(ShippingNoticeIntake.consumed_batch_id == int(batch_id)) + .all() + ) + return {str(row[0]).strip().upper() for row in rows if row and row[0]} + + +def _try_idempotent_replay( + *, + user_id: int, + create_idempotency_key: str | None, + intake_nos: list[str], +) -> dict[str, Any] | None: + """ + 按 user_id + create_idempotency_key 查找已有批次,并校验 intake 集合一致。 + Returns: + 幂等重放响应;无匹配批次时返回 None。 + """ + key = normalize_create_idempotency_key(create_idempotency_key) + if not key: + return None + existing = find_batch_by_create_idempotency(user_id, key) + if existing is None: + return None + expected = set(intake_nos) + actual = _batch_intake_nos(int(existing.id)) + if expected != actual: + raise ConflictError( + '建单幂等键对应批次的接入集合不一致', + code='SHIPPING.BATCH_IDEMPOTENCY_CONFLICT', + details={'batch_no': existing.batch_no, 'expected': sorted(expected), 'actual': sorted(actual)}, + ) + result = build_existing_batch_tool_response(existing, user_id=user_id) + result['idempotent_replay'] = True + return result + + +def _partition_intakes_by_content_hash( + ordered: list[tuple[ShippingNoticeIntake, FileAsset]], +) -> tuple[list[tuple[ShippingNoticeIntake, FileAsset]], dict[str, list[ShippingNoticeIntake]]]: + """ + 按 FileAsset.content_hash 去重,保留首次出现的 intake 用于建单。 + + Returns: + (primary_pairs, duplicates_by_hash):duplicates 不含 primary。 + """ + seen: set[str] = set() + primary: list[tuple[ShippingNoticeIntake, FileAsset]] = [] + duplicates_by_hash: dict[str, list[ShippingNoticeIntake]] = {} + for intake, asset in ordered: + content_hash = str(asset.content_hash or '').strip() + if not content_hash: + primary.append((intake, asset)) + continue + if content_hash in seen: + duplicates_by_hash.setdefault(content_hash, []).append(intake) + continue + seen.add(content_hash) + primary.append((intake, asset)) + return primary, duplicates_by_hash + + +def create_shipping_batch_from_intakes( + *, + user_id: int, + conversation_id: str | None, + intake_nos: list[str], + create_idempotency_key: str | None = None, +) -> dict[str, Any]: + """ + 根据已解析且未消费的 intake 列表创建批次。 + + 核心逻辑: + 1. 优先按建单幂等键回放(此时 intake 可能已 consumed); + 2. FOR UPDATE 锁定 intake,校验 parsed; + 3. 按 content_hash 去重后再预标记 consumed(仅 flush),再调用建批; + 4. 建批异常必须 rollback,避免 Chat Turn 后续 commit 把预占 consumed 落库; + 5. 建批成功后回填 batch/task,并把同 hash 附属 intake 一并关联到同一任务。 + """ + normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()] + if not normalized: + raise ValidationError('intake_nos is required') + + # [STEP 1] 幂等重放优先:相同 Idempotency-Key 在 intake 已消费后仍可恢复原批次 + replay = _try_idempotent_replay( + user_id=user_id, + create_idempotency_key=create_idempotency_key, + intake_nos=normalized, + ) + if replay is not None: + return replay + + # [STEP 2] 锁定并校验接入记录 + stmt = ( + select(ShippingNoticeIntake, FileAsset) + .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id) + .where( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .with_for_update() + ) + rows = list(db.session.execute(stmt).all()) + row_by_no = {intake.intake_no: (intake, asset) for intake, asset in rows} + if len(row_by_no) != len(set(normalized)): + raise ValidationError( + '部分接入记录不存在或无权访问', + code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', + ) + + # 锁后再查一次幂等键,覆盖 STEP1 与锁定之间的并发窗口 + replay = _try_idempotent_replay( + user_id=user_id, + create_idempotency_key=create_idempotency_key, + intake_nos=normalized, + ) + if replay is not None: + return replay + + ordered_pairs: list[tuple[ShippingNoticeIntake, FileAsset]] = [] + now = datetime.utcnow() + for intake_no in normalized: + intake, asset = row_by_no[intake_no] + if intake.consumed_at is not None or intake.parse_status == 'consumed': + raise ConflictError( + f'接入记录 {intake.intake_no} 已被消费', + code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', + ) + if intake.parse_status != 'parsed': + raise ConflictError( + f'接入记录 {intake.intake_no} 尚未解析完成', + code=( + 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' + if intake.parse_status in {'created', 'queued', 'parsing'} + else 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' + ), + ) + if intake.expires_at and intake.expires_at < now: + raise ConflictError( + '接入记录已过期', + code='SHIPPING_NOTICE.INTAKE_EXPIRED', + ) + ordered_pairs.append((intake, asset)) + + # [STEP 3] content_hash 去重:只消费真正用于建单的 primary intake + primary_pairs, duplicates_by_hash = _partition_intakes_by_content_hash(ordered_pairs) + primary_intakes = [intake for intake, _ in primary_pairs] + notice_items = [intake_to_notice_item(intake, asset) for intake, asset in primary_pairs] + + # [STEP 4] 预占消费状态(flush 不 commit),与后续 create_batch_tasks 同事务提交 + mark_intakes_consumed(intakes=primary_intakes, batch_id=None) + db.session.flush() + + try: + result = create_shipping_batch_from_notice_items( + user_id=user_id, + conversation_id=conversation_id, + notice_items=notice_items, + create_idempotency_key=create_idempotency_key, + ) + except Exception: + # [P0] 建批失败时丢弃预占 consumed,避免 Chat Turn 的 touch_chat_session commit 落脏状态 + db.session.rollback() + raise + + if bool(result.get('idempotent_replay')): + # create 路径返回重放时不会 commit;丢弃本事务内的预占 consumed,避免脏状态落库 + db.session.rollback() + return result + + data = result.get('data') if isinstance(result.get('data'), dict) else {} + batch = data.get('batch') if isinstance(data.get('batch'), dict) else {} + batch_no = str(result.get('batch_no') or batch.get('batch_no') or '').strip() + if not batch_no: + return result + + from app.services.shipping_notice.query_service import get_batch_for_user + + batch_obj = get_batch_for_user(batch_no, user_id) + if not batch_obj: + return result + + tasks = ( + db.session.query(ShippingTask) + .filter(ShippingTask.batch_id == batch_obj.id) + .order_by(ShippingTask.batch_index.asc(), ShippingTask.id.asc()) + .all() + ) + task_by_intake_id = { + int(task.source_intake_id): task + for task in tasks + if task.source_intake_id is not None + } + hash_to_task_id: dict[str, int] = {} + for intake, asset in primary_pairs: + task = task_by_intake_id.get(int(intake.id)) + if task is None: + continue + intake.consumed_batch_id = int(batch_obj.id) + intake.consumed_task_id = int(task.id) + intake.updated_at = datetime.utcnow() + content_hash = str(asset.content_hash or '').strip() + if content_hash: + hash_to_task_id[content_hash] = int(task.id) + + # [STEP 5] 同 hash 附属 intake 显式关联到同一任务,避免残留 parsed 且保证幂等集合一致 + duplicate_intakes: list[ShippingNoticeIntake] = [] + for content_hash, dups in duplicates_by_hash.items(): + task_id = hash_to_task_id.get(content_hash) + if task_id is None: + continue + for dup in dups: + duplicate_intakes.append(dup) + dup.consumed_batch_id = int(batch_obj.id) + dup.consumed_task_id = int(task_id) + if duplicate_intakes: + mark_intakes_consumed( + intakes=duplicate_intakes, + batch_id=int(batch_obj.id), + task_ids_by_intake={int(i.id): int(i.consumed_task_id) for i in duplicate_intakes if i.consumed_task_id}, + ) + + db.session.commit() + return result diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index ce5a17b9..871b5250 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -149,6 +149,58 @@ class ShippingCreateBatchFromNoticesAction: yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"}) +class ShippingCreateBatchFromIntakesAction: + """基于已解析接入记录确认建批(第二阶段主路径)。""" + + action_type = "shipping.create_batch_from_intakes" + + def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: + user_id = ctx.user_id + if user_id is None: + raise ValidationError("user context is required") + payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} + intake_nos = payload.get("intake_nos") + if not isinstance(intake_nos, list) or not intake_nos: + raise ValidationError("intake_nos is required") + # 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id + conversation_id = ( + _payload_str(payload, "conversation_id", "conversationId") + or str(getattr(ctx, "session_id", "") or "").strip() + or None + ) + idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None + + yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."}) + + from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes + from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message + + result = create_shipping_batch_from_intakes( + user_id=user_id, + conversation_id=conversation_id, + intake_nos=[str(item) for item in intake_nos], + create_idempotency_key=idempotency_key, + ) + batch_no = str(result.get("batch_no") or "").strip() + if batch_no: + batch_event = _shipping_batch_ui_state_event(batch_no, user_id) + if batch_event is not None: + yield batch_event + + file_count = len(intake_nos) + content = format_batch_created_assistant_message(result, file_count=file_count) + data = result.get("data") if isinstance(result.get("data"), dict) else {} + focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {} + message_payload = { + "batch_no": batch_no, + "task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(), + "orchestrator_started": bool(data.get("orchestrator_started")), + "idempotent_replay": bool(result.get("idempotent_replay")), + } + yield from _stream_text_events(content, message_type="text", payload=message_payload) + yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"}) + + class ShippingSubmitDecisionAction: """提交人工决策:confirm / reject / rematch / retry_rpa 等。""" @@ -307,6 +359,7 @@ class ShippingMarkManualUploadedAction: _HANDLERS = ( ShippingCreateBatchFromNoticesAction(), + ShippingCreateBatchFromIntakesAction(), ShippingSubmitDecisionAction(), ShippingGenerateExcelAction(), ShippingRetryUploadAction(), diff --git a/backend/app/services/shipping_notice/intake_parse_workflow.py b/backend/app/services/shipping_notice/intake_parse_workflow.py new file mode 100644 index 00000000..65d5bcc6 --- /dev/null +++ b/backend/app/services/shipping_notice/intake_parse_workflow.py @@ -0,0 +1,254 @@ +""" +backend/app/services/shipping_notice/intake_parse_workflow.py + +用途:发货通知接入记录的文本抽取与预解析编排。 +依赖:notice_upload、file_assets.service、models.ShippingNoticeIntake。 +逻辑:由 shipping_notice_parse Job handler 调用;不写 API 路由。 +""" + +from __future__ import annotations + +import tempfile +from pathlib import Path +from typing import Any + +from flask import current_app + +from sqlalchemy import update + +from app import db +from app.models import FileAsset, ShippingNoticeIntake +from app.services.file_assets.service import read_asset_bytes +from app.services.shipping_notice.notice_upload import ( + NoticeIntakeResult, + extract_notice_text, + guess_source_type, + truncate_notice_text, +) + + +def _parser_version() -> str: + return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip() + + +def extract_notice_from_asset(asset: FileAsset) -> NoticeIntakeResult: + """ + 从 FileAsset 下载并抽取发货通知文本。 + 核心逻辑:写入临时文件后复用 extract_notice_text,避免长期落盘到 notice_uploads。 + """ + raw = read_asset_bytes(asset) + filename = str(asset.original_filename or 'notice') + source_type = guess_source_type(filename) + suffix = Path(filename).suffix or '.bin' + with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: + tmp.write(raw) + tmp_path = Path(tmp.name) + try: + text, meta = extract_notice_text(tmp_path) + warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] + except Exception as exc: + return NoticeIntakeResult( + filename=filename, + source_type=source_type, + source_file_type=asset.mime_type, + text='', + warnings=[f'notice_extract_failed:{exc}'], + meta={}, + content_hash=str(asset.content_hash or ''), + file_size=int(asset.file_size or 0), + status='extract_failed', + saved_path=None, + ) + finally: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + + if not str(text or '').strip(): + return NoticeIntakeResult( + filename=filename, + source_type=source_type, + source_file_type=asset.mime_type, + text='', + warnings=warnings, + meta=meta if isinstance(meta, dict) else {}, + content_hash=str(asset.content_hash or ''), + file_size=int(asset.file_size or 0), + status='empty_text', + saved_path=None, + ) + + text, warnings = truncate_notice_text(text, warnings) + return NoticeIntakeResult( + filename=filename, + source_type=source_type, + source_file_type=asset.mime_type, + text=text, + warnings=warnings, + meta=meta if isinstance(meta, dict) else {}, + content_hash=str(asset.content_hash or ''), + file_size=int(asset.file_size or 0), + status='accepted', + saved_path=None, + ) + + +def intake_result_to_structured_summary(result: NoticeIntakeResult) -> dict[str, Any]: + """生成前端可展示的预解析摘要。""" + line_count = 0 + for line in str(result.text or '').splitlines(): + if line.strip(): + line_count += 1 + return { + 'filename': result.filename, + 'source_type': result.source_type, + 'text_length': len(result.text or ''), + 'line_count': line_count, + 'warnings': list(result.warnings), + 'parser_version': _parser_version(), + } + + +_ABORT_WRITE_STATUSES = frozenset({'cancelled', 'expired', 'consumed'}) + + +def _db_parse_status(intake_id: int) -> str | None: + """ + 绕过 Session 身份映射强制读库中的 parse_status。 + + 核心逻辑:expire 本地缓存后 refresh,避免抽取耗时窗口内他事务 cancel 后仍读到 parsing。 + """ + obj = db.session.get(ShippingNoticeIntake, int(intake_id)) + if obj is None: + return None + db.session.expire(obj) + db.session.refresh(obj) + return str(obj.parse_status or '') + + +def _commit_parse_result_if_writable( + *, + intake_id: int, + values: dict[str, Any], +) -> ShippingNoticeIntake | None: + """ + 条件更新解析结果:仅当库中状态仍非 cancelled/expired/consumed 时写回。 + + Returns: + 写成功后的 ORM 对象;被取消/过期/消费则返回 None。 + """ + # [STEP 1] 先强制刷新;若已终态则放弃 + status = _db_parse_status(intake_id) + if status is None or status in _ABORT_WRITE_STATUSES: + return None + + # [STEP 2] 原子 UPDATE,防止 refresh 与 commit 之间的竞态仍覆盖 cancelled + stmt = ( + update(ShippingNoticeIntake) + .where( + ShippingNoticeIntake.id == int(intake_id), + ShippingNoticeIntake.parse_status.notin_(tuple(_ABORT_WRITE_STATUSES)), + ) + .values(**values) + ) + result = db.session.execute(stmt) + if int(result.rowcount or 0) != 1: + db.session.rollback() + return None + db.session.commit() + return db.session.get(ShippingNoticeIntake, int(intake_id)) + + +def run_intake_parse(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]: + """ + 执行单条接入记录的预解析并更新 ORM 状态。 + + 核心逻辑:抽取文本后强制刷新并条件 UPDATE;抽取期间被取消则 status=skipped,不覆盖 cancelled。 + + Returns: + 解析结果摘要字典;若期间被取消/过期则 status=skipped。 + """ + result = extract_notice_from_asset(asset) + intake_id = int(intake.id) + intake_no = intake.intake_no + parser_version = _parser_version() + summary = intake_result_to_structured_summary(result) + warnings = list(result.warnings) + + if result.status == 'extract_failed': + fresh = _commit_parse_result_if_writable( + intake_id=intake_id, + values={ + 'parser_version': parser_version, + 'parse_status': 'parse_failed', + 'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED', + 'error_message': '; '.join(warnings)[:1000] or '文本抽取失败', + 'extracted_text': None, + 'structured_result_json': summary, + 'parse_warnings_json': warnings, + }, + ) + if fresh is None: + return { + 'status': 'skipped', + 'intake_no': intake_no, + 'parse_status': _db_parse_status(intake_id), + } + return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message} + + if result.status == 'empty_text': + fresh = _commit_parse_result_if_writable( + intake_id=intake_id, + values={ + 'parser_version': parser_version, + 'parse_status': 'parse_failed', + 'error_code': 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED', + 'error_message': '未提取到有效文本', + 'extracted_text': None, + 'structured_result_json': summary, + 'parse_warnings_json': warnings, + }, + ) + if fresh is None: + return { + 'status': 'skipped', + 'intake_no': intake_no, + 'parse_status': _db_parse_status(intake_id), + } + return {'status': 'parse_failed', 'intake_no': intake_no, 'error_message': fresh.error_message} + + fresh = _commit_parse_result_if_writable( + intake_id=intake_id, + values={ + 'parser_version': parser_version, + 'parse_status': 'parsed', + 'error_code': None, + 'error_message': None, + 'extracted_text': result.text, + 'structured_result_json': summary, + 'parse_warnings_json': warnings, + }, + ) + if fresh is None: + return { + 'status': 'skipped', + 'intake_no': intake_no, + 'parse_status': _db_parse_status(intake_id), + } + return {'status': 'parsed', 'intake_no': intake_no} + + +def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]: + """将已解析 intake 转为兼容 create_batch 的 notice_item。""" + return { + 'source_type': guess_source_type(asset.original_filename), + 'source_file_name': asset.original_filename, + 'source_file_type': asset.mime_type, + 'source_content_hash': asset.content_hash, + 'file_size': asset.file_size, + 'raw_text': intake.extracted_text or '', + 'warnings': list(intake.parse_warnings_json or []), + 'source_asset_id': asset.id, + 'source_intake_id': intake.id, + } diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py new file mode 100644 index 00000000..e68190d4 --- /dev/null +++ b/backend/app/services/shipping_notice/intake_service.py @@ -0,0 +1,251 @@ +""" +backend/app/services/shipping_notice/intake_service.py + +用途:发货通知接入记录(ShippingNoticeIntake)业务编排。 +依赖:file_assets.service、intake_parse_workflow、jobs.queue、models。 +逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime, timedelta +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.core.response import utc_iso +from app.jobs.queue import enqueue +from app.jobs.types import JobType +from app.models import FileAsset, ShippingNoticeIntake +from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced + +from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + +def _parser_version() -> str: + return str(current_app.config.get('SHIPPING_NOTICE_PARSER_VERSION', 'v1') or 'v1').strip() + + +def _intake_ttl_hours() -> int: + return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1) + + +def generate_intake_no() -> str: + """生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。""" + return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def serialize_intake(intake: ShippingNoticeIntake, *, asset: FileAsset | None = None) -> dict[str, Any]: + """对外序列化接入记录。""" + payload: dict[str, Any] = { + 'intake_no': intake.intake_no, + 'asset_no': asset.asset_no if asset else None, + 'conversation_id': intake.conversation_id, + 'parse_status': intake.parse_status, + 'parser_version': intake.parser_version, + 'parse_summary': intake.structured_result_json, + 'warnings': list(intake.parse_warnings_json or []), + 'error_code': intake.error_code, + 'error_message': intake.error_message, + 'expires_at': utc_iso(intake.expires_at), + 'consumed_at': utc_iso(intake.consumed_at), + 'created_at': utc_iso(intake.created_at), + 'updated_at': utc_iso(intake.updated_at), + } + if asset: + payload['original_filename'] = asset.original_filename + payload['file_size'] = asset.file_size + payload['content_hash'] = asset.content_hash + return payload + + +def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake: + """按编号查询当前用户的接入记录。""" + normalized = str(intake_no or '').strip().upper() + intake = ( + db.session.query(ShippingNoticeIntake) + .filter(ShippingNoticeIntake.intake_no == normalized) + .first() + ) + if not intake or int(intake.user_id) != int(user_id): + raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='接入记录不存在') + return intake + + +def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]: + """查询单个接入记录详情(含资产摘要)。""" + intake = get_intake_for_user(intake_no, user_id) + asset = db.session.get(FileAsset, intake.asset_id) + if not asset: + raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在') + return serialize_intake(intake, asset=asset) + + +def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset: + asset = db.session.get(FileAsset, intake.asset_id) + if not asset or asset.deleted_at is not None: + raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在') + return asset + + +def create_shipping_notice_intake( + *, + user_id: int, + asset_no: str, + conversation_id: str | None = None, +) -> dict[str, Any]: + """ + 基于已上传 FileAsset 创建接入记录并投递解析 Job。 + 核心逻辑:校验资产 ready → 复用同 parser 版本 intake → 入队 shipping_notice_parse。 + """ + asset = get_asset_for_user(asset_no, user_id) + if str(asset.upload_status or '') != 'ready': + raise ValidationError(code='FILE_ASSET.INVALID_STATUS', message='文件尚未上传完成') + if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary': + raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期') + + parser_version = _parser_version() + intake = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.asset_id == asset.id, + ShippingNoticeIntake.purpose == 'shipping_notice', + ShippingNoticeIntake.parser_version == parser_version, + ) + .first() + ) + if intake and intake.parse_status in {'parsed', 'consumed'}: + return serialize_intake(intake, asset=asset) + + if not intake: + intake = ShippingNoticeIntake( + intake_no=generate_intake_no(), + asset_id=asset.id, + user_id=int(user_id), + conversation_id=str(conversation_id or '').strip() or None, + purpose='shipping_notice', + parse_status='created', + parser_version=parser_version, + expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()), + ) + db.session.add(intake) + db.session.flush() + + if intake.parse_status in {'queued', 'parsing'}: + return serialize_intake(intake, asset=asset) + + intake.parse_status = 'queued' + intake.conversation_id = str(conversation_id or intake.conversation_id or '').strip() or None + intake.error_code = None + intake.error_message = None + intake.updated_at = datetime.utcnow() + + job_id = enqueue( + JobType.SHIPPING_NOTICE_PARSE, + {'intake_no': intake.intake_no}, + domain=SHIPPING_NOTICE_JOB_DOMAIN, + business_ref=intake.intake_no, + created_by_id=user_id, + message='等待预解析发货通知', + max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3), + ) + intake.parse_job_id = job_id + db.session.commit() + return serialize_intake(intake, asset=asset) + + +def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]: + """列出会话下未消费的活跃接入记录,供页面恢复。""" + query = db.session.query(ShippingNoticeIntake, FileAsset).join( + FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id + ).filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})), + ShippingNoticeIntake.consumed_at.is_(None), + ) + conv = str(conversation_id or '').strip() + if conv: + query = query.filter(ShippingNoticeIntake.conversation_id == conv) + rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all() + return [serialize_intake(intake, asset=asset) for intake, asset in rows] + + +def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]: + """批量查询接入状态。""" + normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()] + if not normalized: + return [] + rows = ( + db.session.query(ShippingNoticeIntake, FileAsset) + .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .all() + ) + return [serialize_intake(intake, asset=asset) for intake, asset in rows] + + +def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: + """重试 parse_failed 的接入记录。""" + intake = get_intake_for_user(intake_no, user_id) + if intake.parse_status not in {'parse_failed'}: + raise ConflictError( + code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', + message='当前状态不允许重试解析', + ) + asset = _load_asset_for_intake(intake) + intake.parse_status = 'queued' + intake.error_code = None + intake.error_message = None + job_id = enqueue( + JobType.SHIPPING_NOTICE_PARSE, + {'intake_no': intake.intake_no}, + domain=SHIPPING_NOTICE_JOB_DOMAIN, + business_ref=intake.intake_no, + created_by_id=user_id, + message='等待重试预解析发货通知', + max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3), + dedupe_active=False, + ) + intake.parse_job_id = job_id + db.session.commit() + return serialize_intake(intake, asset=asset) + + +def cancel_intake(*, user_id: int, intake_no: str) -> None: + """取消未消费的接入记录。""" + intake = get_intake_for_user(intake_no, user_id) + if intake.consumed_at is not None or intake.parse_status == 'consumed': + raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED', message='接入记录已被消费') + intake.parse_status = 'cancelled' + intake.updated_at = datetime.utcnow() + db.session.commit() + + +def mark_intakes_consumed( + *, + intakes: list[ShippingNoticeIntake], + batch_id: int | None, + task_ids_by_intake: dict[int, int] | None = None, +) -> None: + """ + 标记 intake 为 consumed 并增加资产引用计数。 + + 核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。 + """ + now = datetime.utcnow() + task_map = task_ids_by_intake or {} + for intake in intakes: + intake.parse_status = 'consumed' + intake.consumed_at = now + intake.consumed_batch_id = int(batch_id) if batch_id else None + intake.consumed_task_id = task_map.get(intake.id) + intake.updated_at = now + asset = db.session.get(FileAsset, intake.asset_id) + if asset: + mark_asset_referenced(asset) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 81e6c1f0..adabd0e6 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -134,12 +134,13 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: def claim_next_shipping_notice_job() -> Job | None: - """兼容旧调用:领取下一条发货通知通用任务。""" + """领取下一条发货通知通用任务(单票编排或预解析)。""" from app.jobs.queue import claim_next_job + from app.jobs.types import JobType return claim_next_job( domain=SHIPPING_NOTICE_JOB_DOMAIN, - job_types=[JobType.SHIPPING_NOTICE_RUN], + job_types=[JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE], ) diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 213d08c5..c6a44b03 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -360,6 +360,8 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: source_file_name=str(item.get("source_file_name") or "").strip() or None, source_file_type=item.get("source_file_type"), source_content_hash=content_hash, + source_asset_id=item.get("source_asset_id"), + source_intake_id=item.get("source_intake_id"), batch_index=idx, batch_total=total, raw_content=str(item.get("raw_text") or "").strip() or None, diff --git a/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py new file mode 100644 index 00000000..8e83f8fb --- /dev/null +++ b/backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py @@ -0,0 +1,116 @@ +""" +backend/migrations/versions/c9d0e1f2a3b5_seed_file_asset_cleanup_schedule.py + +用途:为平台 Job file-asset-cleanup 写入默认 ScheduleTask,使 TTL 清理按小时自动执行。 +依赖:Alembic revision f8a9b0c1d2e3;schedule_tasks / users 表已存在;croniter。 +逻辑:有用户则插入 SCH-FILE-ASSET-CLEANUP;无用户时跳过,由应用启动/建用户钩子补建。 + next_run_at 按 Cron「0 * * * *」在 Asia/Shanghai 计算下次整点(与 ensure_* 对齐)。 + downgrade 仅按本迁移固定 schedule_no 删除。 + +Revision ID: c9d0e1f2a3b5 +Revises: f8a9b0c1d2e3 +Create Date: 2026-07-14 08:55:00.000000 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import sqlalchemy as sa +from alembic import op + +revision = "c9d0e1f2a3b5" +down_revision = "f8a9b0c1d2e3" +branch_labels = None +depends_on = None + +_SCHEDULE_NO = "SCH-FILE-ASSET-CLEANUP" +_CRON_EXPR = "0 * * * *" +_TZ_NAME = "Asia/Shanghai" + + +def _compute_next_run_at_utc_naive() -> datetime: + """ + 按「0 * * * *」+ Asia/Shanghai 计算下次整点,返回 UTC naive。 + 与 app.services.schedule.timezone_util.compute_next_run_at 语义对齐。 + """ + 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: + # croniter/zoneinfo 不可用时退化:上海时区下一整点 + tz = timezone(timedelta(hours=8)) + now_local = datetime.now(tz) + next_local = now_local.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + return next_local.astimezone(timezone.utc).replace(tzinfo=None) + + +def upgrade() -> None: + conn = op.get_bind() + exists = conn.execute( + sa.text( + "SELECT 1 FROM schedule_tasks " + "WHERE schedule_no = :sno OR platform_api_path = 'file-asset-cleanup' " + "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: + # 空库无用户:留给 create_app / User after_commit 钩子补建 + 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, + 'file-asset-cleanup', NULL, + false, false, + true, :next_run_at, NULL, + :owner_user_id, :owner_user_id, :now, :now + ) + """ + ), + { + "schedule_no": _SCHEDULE_NO, + "name": "临时文件资产 TTL 清理", + "owner_user_id": int(owner[0]), + "cron_expr": _CRON_EXPR, + "next_run_at": next_run, + "now": now, + }, + ) + + +def downgrade() -> None: + """仅删除本迁移约定的 schedule_no,避免误删管理员手工创建的同路径排程。""" + conn = op.get_bind() + conn.execute( + sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"), + {"sno": _SCHEDULE_NO}, + ) diff --git a/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py new file mode 100644 index 00000000..f20fb8cf --- /dev/null +++ b/backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py @@ -0,0 +1,157 @@ +""" +backend/migrations/versions/f8a9b0c1d2e3_add_file_assets_and_shipping_notice_intakes.py + +用途:第二阶段通用文件资产、发货通知接入记录及任务溯源字段。 +依赖:Alembic revision e7f8a9b0c1d2。 +逻辑:创建 file_assets / shipping_notice_intakes;shipping_tasks 增加 source_asset_id/source_intake_id。 + +Revision ID: f8a9b0c1d2e3 +Revises: e7f8a9b0c1d2 +Create Date: 2026-07-14 00:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "f8a9b0c1d2e3" +down_revision = "e7f8a9b0c1d2" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "file_assets", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("asset_no", sa.String(length=64), nullable=False), + sa.Column("owner_user_id", sa.Integer(), nullable=False), + sa.Column("tenant_id", sa.String(length=64), nullable=True), + sa.Column("original_filename", sa.String(length=255), nullable=False), + sa.Column("storage_provider", sa.String(length=32), server_default="minio", nullable=False), + sa.Column("storage_bucket", sa.String(length=128), nullable=False), + sa.Column("storage_key", sa.String(length=512), nullable=False), + sa.Column("content_hash", sa.String(length=64), nullable=False), + sa.Column("file_size", sa.Integer(), nullable=False), + sa.Column("mime_type", sa.String(length=128), nullable=True), + sa.Column("extension", sa.String(length=32), nullable=True), + sa.Column("upload_status", sa.String(length=32), server_default="uploading", nullable=False), + sa.Column("lifecycle_status", sa.String(length=32), server_default="temporary", nullable=False), + sa.Column("reference_count", sa.Integer(), server_default="0", nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=True), + sa.Column("deleted_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["owner_user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("asset_no", name="uq_file_assets_asset_no"), + ) + op.create_index("ix_file_assets_owner_content_hash", "file_assets", ["owner_user_id", "content_hash"]) + op.create_index("ix_file_assets_lifecycle_expires", "file_assets", ["lifecycle_status", "expires_at"]) + op.create_index("ix_file_assets_owner_created", "file_assets", ["owner_user_id", "created_at"]) + op.create_index(op.f("ix_file_assets_owner_user_id"), "file_assets", ["owner_user_id"], unique=False) + + op.create_table( + "shipping_notice_intakes", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("intake_no", sa.String(length=64), nullable=False), + sa.Column("asset_id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("conversation_id", sa.String(length=100), nullable=True), + sa.Column("purpose", sa.String(length=32), server_default="shipping_notice", nullable=False), + sa.Column("parse_status", sa.String(length=32), server_default="created", nullable=False), + sa.Column("extracted_text", sa.Text(), nullable=True), + sa.Column("structured_result_json", sa.JSON(), nullable=True), + sa.Column("parse_warnings_json", sa.JSON(), nullable=True), + sa.Column("parser_version", sa.String(length=32), nullable=False), + sa.Column("parse_job_id", sa.Integer(), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("consumed_at", sa.DateTime(), nullable=True), + sa.Column("consumed_batch_id", sa.Integer(), nullable=True), + sa.Column("consumed_task_id", sa.Integer(), nullable=True), + sa.Column("expires_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + sa.Column("updated_at", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]), + sa.ForeignKeyConstraint(["consumed_batch_id"], ["shipping_batches.id"]), + sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]), + sa.ForeignKeyConstraint(["user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("intake_no", name="uq_shipping_notice_intakes_intake_no"), + sa.UniqueConstraint( + "asset_id", + "purpose", + "parser_version", + name="uq_shipping_notice_intakes_asset_purpose_parser", + ), + ) + op.create_index( + "ix_shipping_notice_intakes_user_conversation_created", + "shipping_notice_intakes", + ["user_id", "conversation_id", "created_at"], + ) + op.create_index( + "ix_shipping_notice_intakes_parse_status_created", + "shipping_notice_intakes", + ["parse_status", "created_at"], + ) + op.create_index("ix_shipping_notice_intakes_expires", "shipping_notice_intakes", ["expires_at"]) + op.create_index(op.f("ix_shipping_notice_intakes_asset_id"), "shipping_notice_intakes", ["asset_id"], unique=False) + op.create_index(op.f("ix_shipping_notice_intakes_user_id"), "shipping_notice_intakes", ["user_id"], unique=False) + op.create_index( + op.f("ix_shipping_notice_intakes_parse_status"), + "shipping_notice_intakes", + ["parse_status"], + unique=False, + ) + op.create_index( + op.f("ix_shipping_notice_intakes_parse_job_id"), + "shipping_notice_intakes", + ["parse_job_id"], + unique=False, + ) + + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.add_column(sa.Column("source_asset_id", sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column("source_intake_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + "fk_shipping_tasks_source_asset_id_file_assets", + "file_assets", + ["source_asset_id"], + ["id"], + ) + batch_op.create_foreign_key( + "fk_shipping_tasks_source_intake_id_shipping_notice_intakes", + "shipping_notice_intakes", + ["source_intake_id"], + ["id"], + ) + batch_op.create_index("ix_shipping_tasks_source_asset_id", ["source_asset_id"], unique=False) + batch_op.create_index("ix_shipping_tasks_source_intake_id", ["source_intake_id"], unique=False) + + +def downgrade() -> None: + with op.batch_alter_table("shipping_tasks", schema=None) as batch_op: + batch_op.drop_index("ix_shipping_tasks_source_intake_id") + batch_op.drop_index("ix_shipping_tasks_source_asset_id") + batch_op.drop_constraint("fk_shipping_tasks_source_intake_id_shipping_notice_intakes", type_="foreignkey") + batch_op.drop_constraint("fk_shipping_tasks_source_asset_id_file_assets", type_="foreignkey") + batch_op.drop_column("source_intake_id") + batch_op.drop_column("source_asset_id") + + op.drop_index(op.f("ix_shipping_notice_intakes_parse_job_id"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_parse_status"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_user_id"), table_name="shipping_notice_intakes") + op.drop_index(op.f("ix_shipping_notice_intakes_asset_id"), table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_expires", table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_parse_status_created", table_name="shipping_notice_intakes") + op.drop_index("ix_shipping_notice_intakes_user_conversation_created", table_name="shipping_notice_intakes") + op.drop_table("shipping_notice_intakes") + + op.drop_index(op.f("ix_file_assets_owner_user_id"), table_name="file_assets") + op.drop_index("ix_file_assets_owner_created", table_name="file_assets") + op.drop_index("ix_file_assets_lifecycle_expires", table_name="file_assets") + op.drop_index("ix_file_assets_owner_content_hash", table_name="file_assets") + op.drop_table("file_assets") diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py new file mode 100644 index 00000000..d7be1af9 --- /dev/null +++ b/backend/tests/test_shipping_notice_intakes.py @@ -0,0 +1,477 @@ +""" +backend/tests/test_shipping_notice_intakes.py + +用途:验证 FileAsset + ShippingNoticeIntake 创建、消费与幂等回放主路径。 +依赖:pytest、conftest app fixture、MinIO/建批路径 mock。 +逻辑:覆盖上传≠建单、parsed 才可建单、消费后幂等键可恢复、异常 kwargs 不抛 TypeError。 +""" + +from __future__ import annotations + +from datetime import datetime +from unittest.mock import patch + +import pytest +from werkzeug.datastructures import FileStorage +from io import BytesIO + +from app import db +from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask, User +from app.services.file_assets.service import upload_file_asset +from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes +from app.services.shipping_notice.intake_service import create_shipping_notice_intake + + +@pytest.fixture +def shipping_user(app): + with app.app_context(): + user = User(username='intake-user', email='intake@example.com', password_hash='x') + db.session.add(user) + db.session.commit() + yield user + + +def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage: + return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain') + + +def test_upload_file_asset_creates_ready_record(app, shipping_user): + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) + asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one() + assert asset.upload_status == 'ready' + assert asset.lifecycle_status == 'temporary' + assert asset.content_hash + assert 'storage_key' not in result + + +def test_create_intake_queues_parse_job(app, shipping_user): + with app.app_context(): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock: + intake_data = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=asset['asset_no'], + conversation_id='conv-intake-1', + ) + assert intake_data['parse_status'] == 'queued' + enqueue_mock.assert_called_once() + intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one() + assert intake.parse_job_id == 101 + + +def test_error_classes_accept_custom_code_kwargs(app): + """业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。""" + with app.app_context(): + err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在') + assert err.code == 'FILE_ASSET.NOT_FOUND' + err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问') + assert err2.code == 'FILE_ASSET.FORBIDDEN' + err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期') + assert err3.code == 'FILE_ASSET.EXPIRED' + + +def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'): + asset = FileAsset( + asset_no=f'FA-{intake_no}', + owner_user_id=user_id, + original_filename='notice.txt', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user_id}/test/{intake_no}.txt', + content_hash=hash_value, + file_size=12, + mime_type='text/plain', + upload_status='ready', + lifecycle_status='temporary', + reference_count=0, + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=intake_no, + asset_id=asset.id, + user_id=user_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v1', + extracted_text='SKU001 qty 10', + ) + db.session.add(intake) + db.session.commit() + return asset, intake + + +def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch): + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id) + + def _fake_create_batch_from_notice_items(**kwargs): + notice_items = kwargs['notice_items'] + batch = ShippingBatch( + batch_no='SB-TEST-0001', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + ) + db.session.add(batch) + db.session.flush() + item = notice_items[0] + task = ShippingTask( + task_no='SN-TEST-0001', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_content_hash=item.get('source_content_hash'), + source_asset_id=item.get('source_asset_id'), + source_intake_id=item.get('source_intake_id'), + raw_content=item.get('raw_text'), + process_status='created', + ) + db.session.add(task) + db.session.commit() + return { + 'status': 'ok', + 'batch_no': batch.batch_no, + 'data': { + 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, + 'tasks': [{'task_id': task.task_no}], + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create_batch_from_notice_items, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-intake-1', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-1', + ) + assert result['batch_no'] == 'SB-TEST-0001' + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'consumed' + assert refreshed.consumed_batch_id is not None + assert refreshed.consumed_task_id is not None + + task = db.session.query(ShippingTask).filter_by(task_no='SN-TEST-0001').one() + assert task.source_asset_id == asset.id + assert task.source_intake_id == intake.id + + asset_ref = db.session.get(FileAsset, asset.id) + assert asset_ref.lifecycle_status == 'referenced' + assert int(asset_ref.reference_count or 0) >= 1 + + +def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shipping_user, monkeypatch): + with app.app_context(): + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-REPLAY') + batch = ShippingBatch( + batch_no='SB-TEST-REPLAY', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key='idem-replay', + ) + db.session.add(batch) + db.session.flush() + task = ShippingTask( + task_no='SN-TEST-REPLAY', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_asset_id=asset.id, + source_intake_id=intake.id, + process_status='created', + ) + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.consumed_batch_id = batch.id + intake.consumed_task_id = None + db.session.add(task) + db.session.commit() + intake.consumed_task_id = task.id + db.session.commit() + + called = {'count': 0} + + def _should_not_create(**kwargs): + called['count'] += 1 + raise AssertionError('idempotent replay must not create again') + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _should_not_create, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-replay', + intake_nos=['SNI-TEST-REPLAY'], + create_idempotency_key='idem-replay', + ) + assert result.get('idempotent_replay') is True + assert result['batch_no'] == 'SB-TEST-REPLAY' + assert called['count'] == 0 + + +def test_queued_intake_cannot_create_batch(app, shipping_user): + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-QUEUED') + intake.parse_status = 'queued' + db.session.commit() + with pytest.raises(Exception) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id=None, + intake_nos=[intake.intake_no], + create_idempotency_key='idem-queued', + ) + assert 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' in str(getattr(excinfo.value, 'code', '')) or True + from app.core.errors import ConflictError + assert isinstance(excinfo.value, ConflictError) + assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' + + +def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch): + """建批业务异常后预占 consumed 须回滚,否则用户无法重试。""" + with app.app_context(): + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-ROLLBACK') + + def _raise_conflict(**kwargs): + raise ConflictError( + '精确重复通知', + code='SHIPPING.EXACT_DUPLICATE', + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _raise_conflict, + ) + + with pytest.raises(ConflictError) as excinfo: + create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-rollback', + intake_nos=[intake.intake_no], + create_idempotency_key='idem-rollback', + ) + assert excinfo.value.code == 'SHIPPING.EXACT_DUPLICATE' + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'parsed' + assert refreshed.consumed_at is None + assert refreshed.consumed_batch_id is None + + +def test_create_batch_dedupes_same_content_hash_intakes(app, shipping_user, monkeypatch): + """相同 content_hash 的多个 intake:只建一个任务,附属 intake 也关联到同一任务。""" + with app.app_context(): + asset1, intake1 = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-DEDUP-1', hash_value='same-hash-xx' + ) + asset2, intake2 = _seed_parsed_intake( + shipping_user.id, intake_no='SNI-DEDUP-2', hash_value='same-hash-xx' + ) + + def _fake_create(**kwargs): + notice_items = kwargs['notice_items'] + assert len(notice_items) == 1 + batch = ShippingBatch( + batch_no='SB-DEDUP-1', + user_id=shipping_user.id, + file_count=1, + create_idempotency_key=kwargs.get('create_idempotency_key'), + ) + db.session.add(batch) + db.session.flush() + item = notice_items[0] + task = ShippingTask( + task_no='SN-DEDUP-1', + batch_id=batch.id, + user_id=shipping_user.id, + source_type='manual', + source_content_hash=item.get('source_content_hash'), + source_asset_id=item.get('source_asset_id'), + source_intake_id=item.get('source_intake_id'), + raw_content=item.get('raw_text'), + process_status='created', + ) + db.session.add(task) + db.session.commit() + return { + 'status': 'ok', + 'batch_no': batch.batch_no, + 'data': { + 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, + 'tasks': [{'task_id': task.task_no}], + }, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', + _fake_create, + ) + + result = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-dedup', + intake_nos=[intake1.intake_no, intake2.intake_no], + create_idempotency_key='idem-dedup', + ) + assert result['batch_no'] == 'SB-DEDUP-1' + + r1 = db.session.get(ShippingNoticeIntake, intake1.id) + r2 = db.session.get(ShippingNoticeIntake, intake2.id) + assert r1.parse_status == 'consumed' + assert r2.parse_status == 'consumed' + assert r1.consumed_batch_id == r2.consumed_batch_id + assert r1.consumed_task_id == r2.consumed_task_id + assert r1.consumed_task_id is not None + + # 同键重放不应因「请求 2 个 intake / 任务只绑 1 个」而冲突 + replay = create_shipping_batch_from_intakes( + user_id=shipping_user.id, + conversation_id='conv-dedup', + intake_nos=[intake1.intake_no, intake2.intake_no], + create_idempotency_key='idem-dedup', + ) + assert replay.get('idempotent_replay') is True + + +def test_parse_worker_skips_cancelled_intake(app, shipping_user): + """已取消的 intake 不应被 worker 重新写回 parsed。""" + with app.app_context(): + import logging + + from app.jobs.context import JobContext + from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse + + _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-WORKER') + intake.parse_status = 'cancelled' + db.session.commit() + + ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) + run_shipping_notice_parse(ctx, {'intake_no': intake.intake_no}) + + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'cancelled' + + +def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch): + """抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。""" + with app.app_context(): + from sqlalchemy import text + + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + from app.services.shipping_notice.notice_upload import NoticeIntakeResult + + asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-RACE') + intake.parse_status = 'parsing' + db.session.commit() + + local = db.session.get(ShippingNoticeIntake, intake.id) + assert local.parse_status == 'parsing' + + # 他连接直接改库,模拟 cancel_intake 已提交;当前 Session 身份映射仍缓存 parsing + with db.engine.begin() as conn: + conn.execute( + text( + "UPDATE shipping_notice_intakes " + "SET parse_status = 'cancelled' WHERE id = :id" + ), + {'id': intake.id}, + ) + assert local.parse_status == 'parsing' + + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', + lambda _asset: NoticeIntakeResult( + filename='notice.txt', + source_type='manual', + source_file_type='text/plain', + text='SKU001 qty 10', + warnings=[], + meta={}, + content_hash=asset.content_hash, + file_size=12, + status='accepted', + saved_path=None, + ), + ) + + result = run_intake_parse(local, asset) + assert result['status'] == 'skipped' + + db.session.expire_all() + refreshed = db.session.get(ShippingNoticeIntake, intake.id) + assert refreshed.parse_status == 'cancelled' + + +def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user): + """有用户时可幂等补建默认 TTL 清理排程。""" + with app.app_context(): + from app.models import ScheduleTask + from app.services.file_assets.cleanup_schedule import ( + DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, + ensure_default_file_asset_cleanup_schedule, + ) + + first = ensure_default_file_asset_cleanup_schedule() + assert first is not None + assert first.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO + assert first.platform_api_path == 'file-asset-cleanup' + assert first.enabled is True + + second = ensure_default_file_asset_cleanup_schedule() + assert second is not None + assert second.id == first.id + count = ( + db.session.query(ScheduleTask) + .filter(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) + .count() + ) + assert count == 1 + + +def test_user_insert_hook_seeds_cleanup_schedule(app): + """首个用户 commit 后应立即补建清理排程,无需重启。""" + with app.app_context(): + from app.models import ScheduleTask, User + from app.services.file_assets.cleanup_schedule import ( + DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, + register_file_asset_cleanup_schedule_hooks, + ) + + register_file_asset_cleanup_schedule_hooks() + # 确保环境干净 + db.session.query(ScheduleTask).filter( + ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO + ).delete() + db.session.commit() + + user = User(username='seed-hook-user', email='seed-hook@example.com', password_hash='x') + db.session.add(user) + db.session.commit() + + task = ( + db.session.query(ScheduleTask) + .filter_by(schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) + .first() + ) + assert task is not None + assert task.platform_api_path == 'file-asset-cleanup' + assert task.enabled is True + assert task.next_run_at is not None + # Cron 整点:分钟应为 0(允许时区转换后的 UTC 分钟非 0,但应等于 compute_next_run_at 结果) + from app.services.schedule.timezone_util import compute_next_run_at + + expected = compute_next_run_at('0 * * * *', timezone_name='Asia/Shanghai') + assert expected is not None + # 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内 + assert abs((task.next_run_at - expected).total_seconds()) < 3700 diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 7434db69..68204310 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -15,6 +15,8 @@ import type { ShippingNoticeHeader, ShippingNoticeLine, ShippingNoticeUploadResponse, + ShippingNoticeIntakeResponse, + ShippingCreateBatchFromIntakesResponse, ShippingTaskCreateResponse, ShippingTaskDetail, ShippingTaskSummary, @@ -471,6 +473,66 @@ export async function generateWorkspaceShippingExcel(taskNo: string) { /** 发货通知 Agent 应用类型标识(运行时识别)。 */ export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'; +export const createShippingNoticeIntake = ( + assetNo: string, + conversationId?: string | null, +) => requestJson('/api/workspace/shipping-notice/intakes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + asset_no: assetNo, + conversation_id: conversationId || undefined, + }), +}); + +export const getShippingNoticeIntake = (intakeNo: string) => + requestJson(`/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`); + +export const getShippingNoticeIntakeStatuses = (intakeNos: string[]) => + requestJson<{ items: ShippingNoticeIntakeResponse[] }>('/api/workspace/shipping-notice/intakes/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ intake_nos: intakeNos }), + }); + +export const listActiveShippingNoticeIntakes = (conversationId?: string | null) => { + const sp = new URLSearchParams({ status: 'active' }); + if (conversationId) sp.set('conversation_id', conversationId); + return requestJson<{ items: ShippingNoticeIntakeResponse[] }>( + `/api/workspace/shipping-notice/intakes?${sp.toString()}`, + ); +}; + +export const retryShippingNoticeIntake = (intakeNo: string) => + requestJson( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}/retry`, + { method: 'POST' }, + ); + +export const cancelShippingNoticeIntake = (intakeNo: string) => + requestJson<{ cancelled: boolean }>( + `/api/workspace/shipping-notice/intakes/${encodeURIComponent(intakeNo)}`, + { method: 'DELETE' }, + ); + +export const createWorkspaceShippingBatchFromIntakes = ( + intakeNos: string[], + conversationId?: string | null, + idempotencyKey?: string, +) => + requestJson('/api/workspace/shipping-batches/create-from-intakes', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), + }, + body: JSON.stringify({ + intake_nos: intakeNos, + conversation_id: conversationId || undefined, + idempotency_key: idempotencyKey, + }), + }); + export type { ShippingBatchSummary, ShippingBatchUiState, @@ -485,6 +547,8 @@ export type { ShippingNoticeHeader, ShippingNoticeLine, ShippingNoticeUploadResponse, + ShippingNoticeIntakeResponse, + ShippingCreateBatchFromIntakesResponse, ShippingTaskCreateResponse, ShippingTaskDetail, ShippingTaskSummary, diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index 41e77f64..b243602f 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -5,6 +5,7 @@ */ + +