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