feat(shipping-notice): 增加发货通知建单幂等性支持及内容哈希校验

This commit is contained in:
hugo committed 2026-07-14 00:28:52 +08:00
1 parent 0a9bd6415d
commit 143e054d86
39 files changed
+1750 -80

No files matched your search

+1 -1
View File
@@ -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)})
@@ -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)
+9 -1
View File
@@ -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)
@@ -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)
@@ -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
@@ -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"})
@@ -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,
}
@@ -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,
@@ -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")
+99
View File
@@ -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
+96 -1
View File
@@ -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
+242 -26
View File
@@ -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"