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": "建單冪等鍵格式無效。" } }