feat(shipping-notice): 增加发货通知建单幂等性支持及内容哈希校验
This commit is contained in:
1 parent
0a9bd6415d
commit
143e054d86
39 files changed
+1750
-80
No files matched your search
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user