feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测
This commit is contained in:
1 parent
729546a7b7
commit
ceb49461e8
72 files changed
+14270
-460
No files matched your search
@@ -894,6 +894,43 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
|
||||
]
|
||||
|
||||
|
||||
def test_parse_stage_ui_state_lists_all_issues(app):
|
||||
"""文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。"""
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-PARSE-ISSUES-LIST",
|
||||
source_type="pdf",
|
||||
process_status="pending_review",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
error_message="无法根据发货通知唯一确定库存查询来源",
|
||||
parse_confidence=0.4,
|
||||
step_payload_json={
|
||||
"pending_parse_review_after_source": True,
|
||||
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
|
||||
"current_step_progress": {
|
||||
"extra": {
|
||||
"warnings": [
|
||||
"部分订单行缺少 Reservation ID,可能影响精确匹配。",
|
||||
"parse_fallback_heuristic",
|
||||
]
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
ui_state = build_task_ui_state(task)
|
||||
issues = ui_state["summary"]["issues"]
|
||||
|
||||
assert ui_state["checkpoint"] == "inventory_source_review"
|
||||
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
|
||||
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
|
||||
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
|
||||
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
|
||||
assert len(issues) == 4
|
||||
|
||||
|
||||
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
|
||||
"""任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。"""
|
||||
headers = _workspace_headers(app)
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_business_dedup.py
|
||||
|
||||
用途:第三阶段业务指纹、重复检测与决策门闩核心用例。
|
||||
依赖:pytest、business_fingerprint、duplicate_detection、batch_from_intakes。
|
||||
逻辑:覆盖指纹稳定性、阻断门闩、open_existing / create_revision 分流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingBatch,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
detect_duplicates_for_candidate,
|
||||
detect_duplicates_for_intake,
|
||||
)
|
||||
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dedup_user(app):
|
||||
with app.app_context():
|
||||
user = User(username='dedup-user', email='dedup@example.com', password_hash='x', role='user')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
yield user
|
||||
|
||||
|
||||
def _seed_parsed_intake(
|
||||
user_id: int,
|
||||
*,
|
||||
intake_no: str,
|
||||
hash_value: str,
|
||||
business_summary: dict,
|
||||
fingerprint: dict,
|
||||
):
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{intake_no}',
|
||||
owner_user_id=user_id,
|
||||
original_filename='notice.txt',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
|
||||
content_hash=hash_value,
|
||||
file_size=12,
|
||||
mime_type='text/plain',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=intake_no,
|
||||
asset_id=asset.id,
|
||||
user_id=user_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v1',
|
||||
extracted_text='SKU001 qty 10',
|
||||
structured_result_json={'business_summary': business_summary},
|
||||
business_fingerprint=fingerprint.get('fingerprint'),
|
||||
fingerprint_version=fingerprint.get('version'),
|
||||
fingerprint_strength=fingerprint.get('strength'),
|
||||
duplicate_status='none',
|
||||
duplicate_matches_json=[],
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
return asset, intake
|
||||
|
||||
|
||||
def test_fingerprint_stable_across_line_order():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
|
||||
'required_date': '2026-01-01',
|
||||
'lines': [
|
||||
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
|
||||
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
|
||||
],
|
||||
}
|
||||
swapped = {
|
||||
**base,
|
||||
'lines': [
|
||||
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
|
||||
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
|
||||
],
|
||||
}
|
||||
a = build_business_fingerprint(base)
|
||||
b = build_business_fingerprint(swapped)
|
||||
assert a['strength'] == 'medium'
|
||||
assert a['fingerprint'] == b['fingerprint']
|
||||
|
||||
|
||||
def test_fingerprint_changes_with_qty():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
|
||||
'required_date': '2026-01-01',
|
||||
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
|
||||
}
|
||||
changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
|
||||
assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
|
||||
|
||||
|
||||
def test_blocking_create_requires_resolution(app, dedup_user):
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-9',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-DEDUP-BLOCK',
|
||||
hash_value='hash-block-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
batch = ShippingBatch(batch_no='SB-DEDUP-OLD', user_id=dedup_user.id, file_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
existing = ShippingTask(
|
||||
task_no='SN-DEDUP-OLD',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
result = detect_duplicates_for_intake(intake=intake, asset=asset, business_summary=summary, fingerprint_result=fp)
|
||||
assert result['blocking'] is True
|
||||
assert result['status'] == 'same_active_task'
|
||||
|
||||
with pytest.raises(ConflictError) as excinfo:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-dedup',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-block',
|
||||
)
|
||||
assert excinfo.value.code == 'SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED'
|
||||
|
||||
|
||||
def test_open_existing_does_not_create_batch(app, dedup_user):
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-OPEN',
|
||||
'reservation_ids': ['1000140352'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-DEDUP-OPEN',
|
||||
hash_value='hash-open-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
batch = ShippingBatch(batch_no='SB-OPEN-OLD', user_id=dedup_user.id, file_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
existing = ShippingTask(
|
||||
task_no='SN-OPEN-OLD',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
# 模拟前端已决策:写入 resolution,避免 resolve 内 refresh 对 SQLite 时间敏感
|
||||
intake.duplicate_status = 'same_active_task'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': existing.process_status,
|
||||
'document_version': 1,
|
||||
'match_type': 'business_fingerprint',
|
||||
'matched_fields': ['customer_code', 'po_number'],
|
||||
'lifecycle': 'active',
|
||||
}
|
||||
]
|
||||
intake.duplicate_resolution = 'open_existing'
|
||||
intake.duplicate_target_task_no = existing.task_no
|
||||
intake.duplicate_resolved_by_id = dedup_user.id
|
||||
intake.duplicate_resolved_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items'
|
||||
) as create_mock:
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-open',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-open',
|
||||
)
|
||||
create_mock.assert_not_called()
|
||||
|
||||
assert result.get('batch_no') in (None, '')
|
||||
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
|
||||
assert refreshed.parse_status == 'consumed'
|
||||
assert refreshed.consumed_task_id == existing.id
|
||||
|
||||
|
||||
def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatch):
|
||||
"""create_revision 应写入 supersedes_task_id 与 document_version+1。"""
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-REV-1',
|
||||
'reservation_ids': ['12345678'],
|
||||
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-REV-1',
|
||||
hash_value='hash-rev-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-REV-BASE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
intake.duplicate_status = 'same_completed_task'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': 'uploaded',
|
||||
'document_version': 1,
|
||||
'match_type': 'business_fingerprint',
|
||||
'matched_fields': ['customer_code', 'po_number'],
|
||||
}
|
||||
]
|
||||
intake.duplicate_resolution = 'create_revision'
|
||||
intake.duplicate_target_task_no = existing.task_no
|
||||
intake.duplicate_resolved_by_id = dedup_user.id
|
||||
intake.duplicate_resolved_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
notice_items = kwargs['notice_items']
|
||||
item = notice_items[0]
|
||||
batch = ShippingBatch(
|
||||
batch_no='SB-REV-1',
|
||||
user_id=dedup_user.id,
|
||||
file_count=1,
|
||||
create_idempotency_key=kwargs.get('create_idempotency_key'),
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no='SN-REV-NEW',
|
||||
batch_id=batch.id,
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
source_content_hash=item.get('source_content_hash'),
|
||||
source_asset_id=item.get('source_asset_id'),
|
||||
source_intake_id=item.get('source_intake_id'),
|
||||
business_fingerprint=item.get('business_fingerprint'),
|
||||
fingerprint_version=item.get('fingerprint_version'),
|
||||
document_version=int(item.get('document_version') or 1),
|
||||
supersedes_task_id=item.get('supersedes_task_id'),
|
||||
duplicate_resolution_type=item.get('duplicate_resolution_type'),
|
||||
raw_content=item.get('raw_text'),
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'batch_no': batch.batch_no,
|
||||
'data': {
|
||||
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
|
||||
'tasks': [{'task_id': task.task_no}],
|
||||
'focus_task': {
|
||||
'task_no': task.task_no,
|
||||
'document_version': task.document_version,
|
||||
'duplicate_resolution_type': task.duplicate_resolution_type,
|
||||
'supersedes_task_no': existing.task_no,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
|
||||
_fake_create,
|
||||
)
|
||||
# 确保 detect 仍命中
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
|
||||
lambda **kwargs: {
|
||||
'status': 'same_completed_task',
|
||||
'blocking': True,
|
||||
'fingerprint': fp.get('fingerprint'),
|
||||
'fingerprint_version': fp.get('version'),
|
||||
'fingerprint_strength': fp.get('strength'),
|
||||
'matches': intake.duplicate_matches_json,
|
||||
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
|
||||
},
|
||||
)
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=dedup_user.id,
|
||||
conversation_id='conv-rev',
|
||||
intake_nos=[intake.intake_no],
|
||||
create_idempotency_key='idem-rev',
|
||||
)
|
||||
assert result['batch_no'] == 'SB-REV-1'
|
||||
created = db.session.query(ShippingTask).filter_by(task_no='SN-REV-NEW').one()
|
||||
assert created.supersedes_task_id == existing.id
|
||||
assert int(created.document_version) == 2
|
||||
assert created.duplicate_resolution_type == 'revision'
|
||||
|
||||
|
||||
def test_fingerprint_strong_with_customer_name_po_reservation():
|
||||
"""启发式常只有客户名:客户名 + PO + Reservation 应产出 strong 指纹。"""
|
||||
summary = {
|
||||
'customer_name': 'ACME',
|
||||
'customer_code': None,
|
||||
'po_number': 'PO-20260714',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
assert fp['strength'] == 'strong'
|
||||
assert fp['fingerprint']
|
||||
assert fp['components'].get('customer_name') == 'ACME'
|
||||
|
||||
|
||||
def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
"""pending_review 属活跃态:业务指纹命中应为 same_active_task 且 blocking。"""
|
||||
with app.app_context():
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': 'PO-PENDING',
|
||||
'reservation_ids': ['1000140399'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-PENDING-ACTIVE',
|
||||
hash_value='hash-pending-1',
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-PENDING-1',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
result = detect_duplicates_for_intake(
|
||||
intake=intake,
|
||||
asset=asset,
|
||||
business_summary=summary,
|
||||
fingerprint_result=fp,
|
||||
)
|
||||
assert result['status'] == 'same_active_task'
|
||||
assert result['blocking'] is True
|
||||
|
||||
|
||||
def test_assert_no_exact_duplicate_allows_revision_and_force(app, dedup_user):
|
||||
"""revision/force_create 可越过同 content_hash 的旧门闩;无决议仍阻断。"""
|
||||
from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices
|
||||
|
||||
with app.app_context():
|
||||
existing = ShippingTask(
|
||||
task_no='SN-HASH-GATE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
source_content_hash='samehashabc',
|
||||
process_status='pending_review',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
'duplicate_resolution_type': 'revision',
|
||||
}
|
||||
],
|
||||
)
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
'duplicate_resolution_type': 'force_create',
|
||||
}
|
||||
],
|
||||
)
|
||||
with pytest.raises(ConflictError) as excinfo:
|
||||
assert_no_exact_duplicate_notices(
|
||||
dedup_user.id,
|
||||
[
|
||||
{
|
||||
'source_content_hash': 'samehashabc',
|
||||
'source_file_name': 'same.xlsx',
|
||||
}
|
||||
],
|
||||
)
|
||||
assert excinfo.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
|
||||
|
||||
|
||||
def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
|
||||
"""API 投影:possible_duplicate 必须 blocking,供前端弹窗确认。"""
|
||||
from app.services.shipping_notice.intake_service import serialize_intake
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-POSSIBLE-1',
|
||||
hash_value='hash-possible-1',
|
||||
business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]},
|
||||
fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'},
|
||||
)
|
||||
intake.duplicate_status = 'possible_duplicate'
|
||||
intake.fingerprint_strength = 'weak'
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': 'SN-OLD',
|
||||
'process_status': 'waiting_inventory',
|
||||
'document_version': 1,
|
||||
'match_type': 'weak_fingerprint',
|
||||
'matched_fields': ['line_digest'],
|
||||
}
|
||||
]
|
||||
db.session.commit()
|
||||
payload = serialize_intake(intake, asset=asset)
|
||||
assert payload['duplicate']['status'] == 'possible_duplicate'
|
||||
assert payload['duplicate']['blocking'] is True
|
||||
assert 'force_create' in payload['duplicate']['allowed_actions']
|
||||
|
||||
|
||||
def test_task_summary_includes_version_chain(app, dedup_user):
|
||||
"""query_service SUMMARY 须暴露版本链与 duplicate 决策字段。"""
|
||||
from app.services.shipping_notice.query_service import TaskProjection, serialize_task
|
||||
|
||||
with app.app_context():
|
||||
base = ShippingTask(
|
||||
task_no='SN-VER-BASE',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(base)
|
||||
db.session.flush()
|
||||
rev = ShippingTask(
|
||||
task_no='SN-VER-REV',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
document_version=2,
|
||||
supersedes_task_id=base.id,
|
||||
duplicate_resolution_type='revision',
|
||||
duplicate_source_task_id=base.id,
|
||||
duplicate_override_reason=None,
|
||||
business_fingerprint='fp-x',
|
||||
fingerprint_version='shipping-v1',
|
||||
)
|
||||
db.session.add(rev)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task(rev, TaskProjection.SUMMARY)
|
||||
assert data['document_version'] == 2
|
||||
assert data['supersedes_task_no'] == 'SN-VER-BASE'
|
||||
assert data['duplicate_source_task_no'] == 'SN-VER-BASE'
|
||||
assert data['duplicate_resolution_type'] == 'revision'
|
||||
assert data['business_fingerprint'] == 'fp-x'
|
||||
|
||||
base_data = serialize_task(base, TaskProjection.SUMMARY)
|
||||
assert base_data['superseded_by_task_no'] == 'SN-VER-REV'
|
||||
|
||||
|
||||
def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
"""
|
||||
阶段二:同一邮件中候选 A 与已有任务重复时,仅 A 被阻断;B/C 仍可为 none。
|
||||
"""
|
||||
with app.app_context():
|
||||
existing_fp = build_business_fingerprint(
|
||||
{
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['1000140351'],
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-EXISTING-PO-A',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-other-file',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-STAGE2-DEDUP-EML',
|
||||
owner_user_id=dedup_user.id,
|
||||
original_filename='multi.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{dedup_user.id}/stage2.eml',
|
||||
content_hash='eml-parent-hash',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
asset_role='upload',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-STAGE2-DEDUP',
|
||||
asset_id=parent.id,
|
||||
user_id=dedup_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='multi',
|
||||
duplicate_status='unchecked',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
docs = []
|
||||
for idx, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
|
||||
doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key=f'att-00{idx}',
|
||||
document_type='attachment',
|
||||
filename=f'{po}.pdf',
|
||||
content_hash=f'pdf-hash-{po}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO {po}',
|
||||
)
|
||||
db.session.add(doc)
|
||||
docs.append(doc)
|
||||
db.session.flush()
|
||||
|
||||
results = []
|
||||
for doc, po in zip(docs, ('4510039227', '4510039228', '4510039229')):
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': po,
|
||||
'reservation_ids': ['1000140351'] if po == '4510039227' else [],
|
||||
'lines': [],
|
||||
}
|
||||
if po != '4510039227':
|
||||
summary['reservation_ids'] = [f'100014035{po[-1]}']
|
||||
fp = build_business_fingerprint(summary)
|
||||
dup = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
document=doc,
|
||||
business_summary=summary,
|
||||
fingerprint_result=fp,
|
||||
)
|
||||
cand = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-{po}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
po_number=po,
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
fingerprint_strength=fp.get('strength'),
|
||||
duplicate_status=str(dup.get('status') or 'none'),
|
||||
duplicate_matches_json=list(dup.get('matches') or []),
|
||||
selected=True,
|
||||
validation_status='pending',
|
||||
)
|
||||
db.session.add(cand)
|
||||
results.append(dup)
|
||||
db.session.commit()
|
||||
|
||||
assert results[0]['blocking'] is True
|
||||
assert results[0]['status'] in {'same_active_task', 'exact_file', 'possible_duplicate'}
|
||||
assert results[1]['blocking'] is False
|
||||
assert results[1]['status'] == 'none'
|
||||
assert results[2]['blocking'] is False
|
||||
assert results[2]['status'] == 'none'
|
||||
|
||||
refreshed = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter_by(intake_id=intake.id)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
assert refreshed[0].duplicate_status != 'none'
|
||||
assert refreshed[1].duplicate_status == 'none'
|
||||
assert refreshed[2].duplicate_status == 'none'
|
||||
|
||||
|
||||
def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
"""刷新重复检测须重写各 Candidate.duplicate_status,再聚合到 Intake。"""
|
||||
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||
|
||||
with app.app_context():
|
||||
existing_fp = build_business_fingerprint(
|
||||
{
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510099999',
|
||||
'reservation_ids': ['1000199999'],
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-REFRESH-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-refresh-other',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-REFRESH-DEDUP',
|
||||
owner_user_id=dedup_user.id,
|
||||
original_filename='refresh.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{dedup_user.id}/refresh.eml',
|
||||
content_hash='eml-refresh-hash',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
asset_role='upload',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-REFRESH-DEDUP',
|
||||
asset_id=parent.id,
|
||||
user_id=dedup_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='refresh',
|
||||
duplicate_status='none',
|
||||
structured_result_json={'business_summary': {'customer_code': 'C1'}},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510099999',
|
||||
'reservation_ids': ['1000199999'],
|
||||
'lines': [],
|
||||
}
|
||||
fp = build_business_fingerprint(summary)
|
||||
doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key='att-001',
|
||||
document_type='attachment',
|
||||
filename='dup.pdf',
|
||||
content_hash='pdf-refresh-1',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 4510099999',
|
||||
)
|
||||
db.session.add(doc)
|
||||
db.session.flush()
|
||||
cand = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-REFRESH-1',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
po_number='4510099999',
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
fingerprint_version=fp.get('version'),
|
||||
fingerprint_strength=fp.get('strength'),
|
||||
# 模拟解析后任务尚未存在时的旧结果;刷新时应变为阻断
|
||||
duplicate_status='none',
|
||||
duplicate_matches_json=[],
|
||||
selected=True,
|
||||
validation_status='pending',
|
||||
)
|
||||
db.session.add(cand)
|
||||
db.session.commit()
|
||||
|
||||
payload = refresh_intake_duplicate_detection(
|
||||
user_id=dedup_user.id,
|
||||
intake_no='SNI-REFRESH-DEDUP',
|
||||
)
|
||||
assert payload['duplicate']['blocking'] is True
|
||||
db.session.expire_all()
|
||||
cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
|
||||
assert cand2.duplicate_status != 'none'
|
||||
assert list(cand2.duplicate_matches_json or [])
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -495,7 +495,7 @@ def test_crane_user_confirm_and_gate_stable(app):
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
|
||||
"""低置信度 + 未命中库存源:先确认库存源,再确认解析,最后才能进入库存准备。"""
|
||||
"""低置信度 + 未命中库存源:先确认解析,再确认库存源,最后才能进入库存准备。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
@@ -514,6 +514,61 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
|
||||
task_no="SN-GATE-LOW-CONF-SEQ",
|
||||
source_type="pdf",
|
||||
process_status="pending_review",
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
review_status="parse_review",
|
||||
parse_confidence=0.4,
|
||||
ship_to="UnknownCity",
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
|
||||
inventory_source_status="unresolved",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"})
|
||||
db.session.refresh(task)
|
||||
assert parse_result["status"] in {"ok", "needs_human"}
|
||||
assert parse_result.get("checkpoint") == "inventory_source_review"
|
||||
assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
assert not is_inventory_source_stable(task)
|
||||
option_ids = parse_result.get("human_options") or [
|
||||
item.get("id") for item in (parse_result.get("action_buttons") or [])
|
||||
]
|
||||
assert "reparse" not in option_ids
|
||||
assert "confirm_inventory_source" in option_ids
|
||||
|
||||
source_result = confirm_inventory_source({
|
||||
"task_id": task.task_no,
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"_trusted_user_id": 11,
|
||||
})
|
||||
db.session.refresh(task)
|
||||
assert source_result["status"] in {"ok", "running"}
|
||||
assert is_inventory_source_stable(task)
|
||||
assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
assert task.pending_human_reason != PH_LOW_CONF
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch):
|
||||
"""存量任务:先库存源后解析的延后标记仍可走完兼容路径。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled",
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.decision_workflow.start_task_orchestrator",
|
||||
lambda task_no: False,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-GATE-LEGACY-PARSE-AFTER-SOURCE",
|
||||
source_type="pdf",
|
||||
process_status="pending_review",
|
||||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
review_status="parse_review",
|
||||
parse_confidence=0.4,
|
||||
@@ -545,6 +600,90 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
|
||||
assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(app, client):
|
||||
"""高置信度解析自动通过后,库存源未命中应直接进入 inventory_source_review。"""
|
||||
from tests.test_shipping_notice_tools import _tool_headers
|
||||
|
||||
headers = _tool_headers(app)
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
parse_res = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"ship_to": "Mystery Port",
|
||||
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
parse_data = parse_res.get_json()
|
||||
assert parse_data["status"] == "needs_human"
|
||||
assert parse_data.get("checkpoint") == "inventory_source_review"
|
||||
button_ids = [item.get("id") for item in (parse_data.get("action_buttons") or [])]
|
||||
assert "confirm_inventory_source" in button_ids
|
||||
assert "reparse" not in button_ids
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
assert not is_inventory_source_stable(task)
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app, client):
|
||||
"""低置信度 + 库存源未命中:应先进入 parse_review(含重新解析),而非抢先确认库存源。"""
|
||||
from app.services.shipping_notice.state_machine import human_options_for_task
|
||||
from tests.test_shipping_notice_tools import _tool_headers
|
||||
|
||||
headers = _tool_headers(app)
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
parse_res = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"ship_to": "Mystery Port",
|
||||
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
|
||||
"confidence": 0.4,
|
||||
},
|
||||
},
|
||||
)
|
||||
parse_data = parse_res.get_json()
|
||||
assert parse_data["status"] == "needs_human"
|
||||
assert parse_data.get("checkpoint") == "parse_review"
|
||||
assert "重新解析" in (parse_data.get("message") or "") or "置信度" in (parse_data.get("message") or "")
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == PH_LOW_CONF
|
||||
assert task.review_status == "parse_review"
|
||||
options = human_options_for_task(task) or []
|
||||
assert "reparse" in options
|
||||
assert "confirm" in options
|
||||
assert "confirm_inventory_source" not in options
|
||||
assert "解析确认通过后" in (parse_data.get("message") or "")
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
|
||||
"""人工上传身份绑定失败时不应遗留库存文件或数据库记录。"""
|
||||
|
||||
Reference in new issue
Block a user