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

+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"