feat(shipping-notice): 增强发货通知候选管理功能,支持候选选择、重复检测与业务摘要修订
This commit is contained in:
1 parent
70f684b94a
commit
b595e157e9
83 files changed
+5857
-200
No files matched your search
@@ -10,7 +10,10 @@ from app import db
|
||||
from app.models import Agent, User
|
||||
from app.services.chat.action_schema import TurnInput
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice.chat_action_handlers import ShippingGenerateExcelAction
|
||||
from app.services.shipping_notice.chat_action_handlers import (
|
||||
ShippingCreateBatchFromIntakesAction,
|
||||
ShippingGenerateExcelAction,
|
||||
)
|
||||
|
||||
|
||||
def _create_task(user_id: int) -> str:
|
||||
@@ -76,3 +79,62 @@ def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
|
||||
assert "message.completed" in event_names
|
||||
completed = next(item for item in events if item.event == "message.completed")
|
||||
assert "Excel 已生成" in str(completed.data.get("content") or "")
|
||||
|
||||
|
||||
def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypatch):
|
||||
"""Chat Turn Candidate 建批必须把选择集合透传后端,且不得引用未定义局部变量。"""
|
||||
user = User(username="candidate_handler", email="candidate-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
description="t",
|
||||
dify_api_key="k",
|
||||
api_base_url="http://example.com",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": None,
|
||||
"message": "已打开已有任务,未创建新批次",
|
||||
"opened_existing": [{"candidate_no": "SNC-1", "task_no": "SN-EXISTING"}],
|
||||
"data": {"focus_task": {"task_no": "SN-EXISTING"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_intakes",
|
||||
_fake_create,
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-candidate",
|
||||
run_id="turn-candidate",
|
||||
session_id="sess-candidate",
|
||||
request_id="req-candidate",
|
||||
user=user,
|
||||
agent=agent,
|
||||
input=TurnInput(
|
||||
type="action",
|
||||
display_text="确认两个订单",
|
||||
action_type="shipping.create_batch_from_intakes",
|
||||
payload={
|
||||
"intake_nos": ["SNI-1"],
|
||||
"candidate_nos": ["SNC-1", "SNC-2"],
|
||||
"idempotency_key": "idem-candidate-handler",
|
||||
},
|
||||
),
|
||||
refs={},
|
||||
)
|
||||
|
||||
events = list(ShippingCreateBatchFromIntakesAction().stream(ctx))
|
||||
|
||||
assert captured["intake_nos"] == ["SNI-1"]
|
||||
assert captured["candidate_nos"] == ["SNC-1", "SNC-2"]
|
||||
assert captured["conversation_id"] == "sess-candidate"
|
||||
assert any(event.event == "message.completed" for event in events)
|
||||
@@ -909,6 +909,19 @@ def test_parse_stage_ui_state_lists_all_issues(app):
|
||||
step_payload_json={
|
||||
"pending_parse_review_after_source": True,
|
||||
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
|
||||
"parse_validation": {
|
||||
"status": "needs_review",
|
||||
"issues": [
|
||||
{
|
||||
"line_index": 0,
|
||||
"sku": "A001",
|
||||
"field": "reservation_id",
|
||||
"reason": "invalid_format",
|
||||
"severity": "blocking",
|
||||
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
|
||||
}
|
||||
],
|
||||
},
|
||||
"current_step_progress": {
|
||||
"extra": {
|
||||
"warnings": [
|
||||
@@ -927,8 +940,9 @@ def test_parse_stage_ui_state_lists_all_issues(app):
|
||||
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
|
||||
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
|
||||
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
|
||||
assert "第 1 行 SKU A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
|
||||
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
|
||||
assert len(issues) == 4
|
||||
assert len(issues) == 5
|
||||
|
||||
|
||||
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
|
||||
|
||||
@@ -25,8 +25,12 @@ from app.models import (
|
||||
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.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
apply_duplicate_result_to_candidate,
|
||||
detect_duplicates_for_candidate,
|
||||
detect_duplicates_for_intake,
|
||||
)
|
||||
@@ -86,6 +90,26 @@ def _seed_parsed_intake(
|
||||
return asset, intake
|
||||
|
||||
|
||||
def test_business_fingerprint_ignores_internal_hex_reservation_id():
|
||||
"""内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。"""
|
||||
summary = {
|
||||
'customer_name': 'ACME',
|
||||
'reservation_ids': ['1f1a682dfdc446a393415dee93eb36ce'],
|
||||
'lines': [
|
||||
{
|
||||
'sku': 'A001',
|
||||
'qty': 1,
|
||||
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
fingerprint = build_business_fingerprint(summary)
|
||||
|
||||
assert fingerprint['strength'] == 'weak'
|
||||
assert 'reservation_ids' not in fingerprint['components']
|
||||
|
||||
|
||||
def test_fingerprint_stable_across_line_order():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
@@ -616,6 +640,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
candidate_no=f'SNC-{po}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
candidate_key=f'test:SNC-{po}',
|
||||
po_number=po,
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
@@ -725,6 +750,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
candidate_no='SNC-REFRESH-1',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
candidate_key='test:SNC-REFRESH-1',
|
||||
po_number='4510099999',
|
||||
structured_result_json={'business_summary': summary},
|
||||
business_fingerprint=fp.get('fingerprint'),
|
||||
@@ -748,3 +774,98 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
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 [])
|
||||
|
||||
|
||||
def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(app, dedup_user):
|
||||
"""身份相同且内容相同应判重复内容;数量变化应判修订。"""
|
||||
with app.app_context():
|
||||
base = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['2000485916'],
|
||||
'lines': [
|
||||
{
|
||||
'reservation_id': '2000485916',
|
||||
'sku': '504-006043-001',
|
||||
'qty': 30,
|
||||
'uom': 'EA',
|
||||
}
|
||||
],
|
||||
}
|
||||
identity = build_business_fingerprint(base)
|
||||
content = build_content_fingerprint(base)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-CONTENT-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=identity['fingerprint'],
|
||||
fingerprint_version=identity['version'],
|
||||
content_fingerprint=content['fingerprint'],
|
||||
content_fingerprint_version=content['version'],
|
||||
)
|
||||
db.session.add(existing)
|
||||
parent, intake = _seed_parsed_intake(
|
||||
dedup_user.id,
|
||||
intake_no='SNI-CONTENT-CHECK',
|
||||
hash_value='content-parent-hash',
|
||||
business_summary=base,
|
||||
fingerprint=identity,
|
||||
)
|
||||
doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key='att-content',
|
||||
document_type='attachment',
|
||||
filename='4510039227.pdf',
|
||||
content_hash='different-file-hash',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(doc)
|
||||
db.session.commit()
|
||||
|
||||
same = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
document=doc,
|
||||
business_summary=base,
|
||||
fingerprint_result=identity,
|
||||
content_fingerprint_result=content,
|
||||
)
|
||||
changed = {**base, 'lines': [{**base['lines'][0], 'qty': 25}]}
|
||||
revision = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
document=doc,
|
||||
business_summary=changed,
|
||||
fingerprint_result=identity,
|
||||
content_fingerprint_result=build_content_fingerprint(changed),
|
||||
)
|
||||
assert same['status'] == 'same_business_content'
|
||||
assert revision['status'] == 'possible_revision'
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-CONTENT-WRITEBACK',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
candidate_key='test:SNC-CONTENT-WRITEBACK',
|
||||
structured_result_json={'business_summary': changed},
|
||||
content_fingerprint=content['fingerprint'],
|
||||
content_fingerprint_version=content['version'],
|
||||
)
|
||||
db.session.add(candidate)
|
||||
apply_duplicate_result_to_candidate(candidate, revision)
|
||||
assert candidate.content_fingerprint == revision['content_fingerprint']
|
||||
assert candidate.content_fingerprint != content['fingerprint']
|
||||
|
||||
hub_changed = {
|
||||
**base,
|
||||
'lines': [{**base['lines'][0], 'hub_code': 'DUB'}],
|
||||
}
|
||||
assert build_content_fingerprint(hub_changed)['fingerprint'] != content['fingerprint']
|
||||
|
||||
header_date_changed = {**base, 'required_date': '2026-07-20'}
|
||||
assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint']
|
||||
|
||||
allocation_changed = {
|
||||
**base,
|
||||
'lines': [{**base['lines'][0], 'allocation_id': 'ALLOC-2'}],
|
||||
}
|
||||
assert build_content_fingerprint(allocation_changed)['fingerprint'] != content['fingerprint']
|
||||
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_candidate_migration.py
|
||||
|
||||
用途:独立验证 Candidate 内容指纹及订单抽取状态迁移可执行 upgrade/downgrade,不依赖历史全量迁移链。
|
||||
依赖:Alembic MigrationContext、SQLAlchemy、d9e0f1a2b3c4/e0f1a2b3c4d5 迁移模块。
|
||||
逻辑:构造前一版本最小 SQLite schema,执行迁移并检查字段/约束,再验证安全回滚与多订单降级保护。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_candidate_content_fingerprint_migration_upgrade_and_downgrade():
|
||||
"""本次迁移应能独立增加并完整移除内容指纹与 Candidate 决策审计字段。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_tasks',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('user_id', sa.Integer(), nullable=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_candidates',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('candidate_no', sa.String(64), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.d9e0f1a2b3c4_candidate_content_fingerprint'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
original_op = migration.op
|
||||
migration.op = operations
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
candidate_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
|
||||
}
|
||||
assert {'content_fingerprint', 'content_fingerprint_version'} <= task_columns
|
||||
assert {
|
||||
'content_fingerprint',
|
||||
'content_fingerprint_version',
|
||||
'duplicate_resolved_by_id',
|
||||
'duplicate_resolved_at',
|
||||
} <= candidate_columns
|
||||
assert 'ix_shipping_tasks_user_content_fingerprint' in {
|
||||
index['name'] for index in inspector.get_indexes('shipping_tasks')
|
||||
}
|
||||
assert 'fk_shipping_notice_candidates_duplicate_resolved_by_id' in {
|
||||
foreign_key['name']
|
||||
for foreign_key in inspector.get_foreign_keys('shipping_notice_candidates')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
candidate_columns = {
|
||||
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
|
||||
}
|
||||
assert 'content_fingerprint' not in task_columns
|
||||
assert 'content_fingerprint_version' not in task_columns
|
||||
assert 'content_fingerprint' not in candidate_columns
|
||||
assert 'duplicate_resolved_by_id' not in candidate_columns
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_notice_intakes',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_documents',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_candidates',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('candidate_no', sa.String(64), nullable=False),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.Column('primary_document_id', sa.Integer(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'intake_id',
|
||||
'primary_document_id',
|
||||
name='uq_shipping_notice_candidates_intake_primary_document',
|
||||
),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_order_extraction_state_migration_upgrade_and_downgrade():
|
||||
"""e0f1 迁移应增加抽取状态、多订单键并可在单候选场景完整降级。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_order_extraction_pre_migration_schema(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_candidates "
|
||||
"(id, candidate_no, intake_id, primary_document_id) VALUES (1, 'SNC-1', 10, 20)"
|
||||
))
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
original_op = migration.op
|
||||
migration.op = operations
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
intake_columns = {column['name'] for column in inspector.get_columns('shipping_notice_intakes')}
|
||||
document_columns = {column['name'] for column in inspector.get_columns('shipping_notice_documents')}
|
||||
candidate_columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
|
||||
assert {'order_extraction_status', 'order_extraction_version'} <= intake_columns
|
||||
assert {'order_extraction_status', 'order_extraction_result_json'} <= document_columns
|
||||
assert {'candidate_key', 'source_order_index', 'evidence_json'} <= candidate_columns
|
||||
row = connection.execute(sa.text(
|
||||
"SELECT candidate_key FROM shipping_notice_candidates WHERE id = 1"
|
||||
)).one()
|
||||
assert row.candidate_key == 'legacy:1'
|
||||
assert 'uq_shipping_notice_candidates_intake_key' in {
|
||||
item['name'] for item in inspector.get_unique_constraints('shipping_notice_candidates')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'order_extraction_status' not in {
|
||||
column['name'] for column in inspector.get_columns('shipping_notice_intakes')
|
||||
}
|
||||
assert 'candidate_key' not in {
|
||||
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
|
||||
}
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_order_extraction_state_migration_rejects_unsafe_multi_candidate_downgrade():
|
||||
"""同一 Document 已产生多个 Candidate 时,降级必须明确失败而不是丢数据。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_order_extraction_pre_migration_schema(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
original_op = migration.op
|
||||
migration.op = operations
|
||||
try:
|
||||
migration.upgrade()
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_candidates "
|
||||
"(candidate_no, intake_id, primary_document_id, candidate_key) VALUES "
|
||||
"('SNC-A', 1, 2, 'a'), ('SNC-B', 1, 2, 'b')"
|
||||
))
|
||||
with pytest.raises(RuntimeError, match='multiple candidates'):
|
||||
migration.downgrade()
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -2,7 +2,12 @@ from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
|
||||
from app.services.shipping_notice.order_candidate_builder import (
|
||||
build_email_order_index,
|
||||
merge_attachment_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.notice_lines import (
|
||||
adjudicate_notice_lines,
|
||||
normalize_notice_line,
|
||||
parse_notice_table_rows,
|
||||
parse_notice_table_text,
|
||||
@@ -129,6 +134,71 @@ def test_extract_notice_text_reads_xfa_pdf_datasets():
|
||||
assert "EINDT=2026-06-23" in text
|
||||
|
||||
|
||||
def test_email_body_order_index_and_attachment_fusion_by_po():
|
||||
"""截图型邮件正文应解析三条订单,并按 PO 将正文分配字段融合到对应附件候选。"""
|
||||
body = """
|
||||
allocation_id\tReservation N.r\tsource type\tAllocated HHPN\tAllocated APN\tAllocated QTY\tMPN\tHub Code\tPO
|
||||
S-ENC-FOBU260702-286\t2000485916\tVMI-FRA01\tTEMP-S000218922\t504-006043-001\t30\tD4-A08AR12000001\tFRA01\t4510039227
|
||||
S-BRA-FOBU260702-187\t2000485915\tVMI-FRA01\tTEMP-S000196207\t504-006076-001\t60\tD4-AR1200115A1\tFRA01\t4510039228
|
||||
S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD4-A08AR12000001\tDUB\t4510039229
|
||||
"""
|
||||
rows = build_email_order_index(body)
|
||||
assert len(rows) == 3
|
||||
assert rows[0]['po_number'] == '4510039227'
|
||||
assert rows[0]['reservation_id'] == '2000485916'
|
||||
assert rows[0]['sku'] == '504-006043-001'
|
||||
assert rows[0]['qty'] == 30
|
||||
assert rows[0]['source_type'] == 'VMI-FRA01'
|
||||
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
|
||||
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
|
||||
assert rows[0]['hub_code'] == 'FRA01'
|
||||
assert rows[2]['hub_code'] == 'DUB'
|
||||
|
||||
fused = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['2000485916'],
|
||||
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30, 'uom': 'EA'}],
|
||||
},
|
||||
filename='4510039227.pdf',
|
||||
body_rows=rows,
|
||||
)
|
||||
line = fused['business_summary']['lines'][0]
|
||||
assert fused['validation_status'] == 'ready'
|
||||
assert not fused['conflicts']
|
||||
assert line['source_type'] == 'VMI-FRA01'
|
||||
assert line['customer_sku'] == 'TEMP-S000218922'
|
||||
assert line['hub_code'] == 'FRA01'
|
||||
|
||||
conflict = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['2000485916'],
|
||||
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 20, 'uom': 'EA'}],
|
||||
},
|
||||
filename='4510039227.pdf',
|
||||
body_rows=rows,
|
||||
)
|
||||
assert conflict['validation_status'] == 'needs_review'
|
||||
assert conflict['conflicts'][0]['field'] == 'qty'
|
||||
|
||||
multi_line = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
'po_number': '4510039227',
|
||||
'reservation_ids': ['OTHER', '2000485916'],
|
||||
'lines': [
|
||||
{'reservation_id': 'OTHER', 'sku': 'OTHER-SKU', 'qty': 5},
|
||||
{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30},
|
||||
],
|
||||
},
|
||||
filename='4510039227.pdf',
|
||||
body_rows=rows,
|
||||
)
|
||||
assert multi_line['validation_status'] == 'ready'
|
||||
assert 'source_type' not in multi_line['business_summary']['lines'][0]
|
||||
assert multi_line['business_summary']['lines'][1]['source_type'] == 'VMI-FRA01'
|
||||
|
||||
|
||||
def test_extract_eml_with_three_pdf_attachments(tmp_path):
|
||||
"""带 3 个 PDF 附件的 EML:attachment_count=3,且各附件独立抽到文本。"""
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
@@ -634,6 +704,29 @@ def test_extract_eml_html_table_keeps_row_boundaries(tmp_path):
|
||||
assert "4510039227\t30" in body.replace(" ", "")
|
||||
|
||||
|
||||
def test_extract_eml_html_table_preserves_empty_cells(tmp_path):
|
||||
"""HTML 表格空单元格必须保留列占位,避免不同邮件模板的尾部业务字段整体错位。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text
|
||||
|
||||
html = (
|
||||
"<table>"
|
||||
"<tr><th>SKU</th><th>Parent allocation ID</th><th>External reservation ID</th></tr>"
|
||||
"<tr><td>A001</td><td></td><td>AWS-311</td></tr>"
|
||||
"</table>"
|
||||
)
|
||||
msg = EmailMessage()
|
||||
msg.set_content(html, subtype="html")
|
||||
path = tmp_path / "html-empty-cell.eml"
|
||||
path.write_bytes(msg.as_bytes())
|
||||
|
||||
_, meta = extract_notice_text(path)
|
||||
body = meta["email"]["body_text"].replace(" ", "")
|
||||
|
||||
assert "A001\t\tAWS-311" in body
|
||||
|
||||
|
||||
def test_extract_eml_nested_eml_file_respects_depth(tmp_path):
|
||||
"""嵌套 .eml 文件附件须共享深度/限额,不得重置 depth=0 无限展开。"""
|
||||
from email.message import EmailMessage
|
||||
@@ -1134,6 +1227,76 @@ def test_extract_reservation_id_from_pr_number():
|
||||
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
|
||||
|
||||
|
||||
def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evidence():
|
||||
"""明确 TSV 列关系与唯一 MPN 关联时,应把 32 位内部 ID 纠正为 External Reservation ID。"""
|
||||
raw_text = (
|
||||
"Allocated APN\tMPN\tAllocated QTY\tCommodity group ID\tExternal reservation ID\n"
|
||||
"504-006055-001\tD4-A08AR12000002\t10\t"
|
||||
"1f1a682dfdc446a393415dee93eb36ce\t3000092917"
|
||||
)
|
||||
lines = [
|
||||
{
|
||||
"sku": "TEMP-S000218929/D4-A08AR12000002",
|
||||
"vendor_part_number": "D4-A08AR12000002",
|
||||
"qty": 10,
|
||||
"uom": "EA",
|
||||
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "3000092917"
|
||||
assert issues == [
|
||||
{
|
||||
"line_index": 0,
|
||||
"sku": "TEMP-S000218929/D4-A08AR12000002",
|
||||
"field": "reservation_id",
|
||||
"reason": "value_corrected",
|
||||
"severity": "info",
|
||||
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
|
||||
"resolved_value": "3000092917",
|
||||
"resolution_basis": "email_table.External reservation ID",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_flattened_text_does_not_guess_external_reservation_id():
|
||||
"""纯文本缺少列边界时不得因附近存在数字而自动修正 Reservation ID。"""
|
||||
raw_text = (
|
||||
"Commodity group ID External reservation ID "
|
||||
"1f1a682dfdc446a393415dee93eb36ce 3000092917"
|
||||
)
|
||||
lines = [
|
||||
{
|
||||
"sku": "TEMP-S000218929/D4-A08AR12000002",
|
||||
"qty": 10,
|
||||
"uom": "EA",
|
||||
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
|
||||
}
|
||||
]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
|
||||
assert status == "needs_review"
|
||||
assert "reservation_id" not in adjudicated[0]
|
||||
assert issues[0]["reason"] == "invalid_format"
|
||||
assert issues[0]["severity"] == "blocking"
|
||||
|
||||
|
||||
def test_adjudication_supports_non_numeric_reservation_templates():
|
||||
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
|
||||
raw_text = "AWS Sku\tReservation Order\tQty\nA001\tAWS-311\t2"
|
||||
lines = [{"sku": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "AWS-311"
|
||||
assert issues[0]["reason"] == "value_corrected"
|
||||
|
||||
|
||||
def test_wistron_po_table_with_pr_number_in_document():
|
||||
text = """
|
||||
Vendor: HOXIN
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
"""
|
||||
tests/test_shipping_notice_field_alignment_summary.py
|
||||
|
||||
用途:验证库存字段对齐摘要的固定结构、多语言中文文案与警告合并行为。
|
||||
依赖:shipping_notice.field_alignment_summary。
|
||||
逻辑:构造字段映射预览并断言聊天区展示内容符合结构化按钮交互契约。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
|
||||
|
||||
|
||||
def test_format_field_alignment_summary_single_block():
|
||||
"""字段对齐摘要应展示映射证据,并提示用户使用结构化按钮继续。"""
|
||||
field_alignment = {
|
||||
"match_rule": "按 AWS Sku + Reservation Order 汇总 Qty Available 与订单 qty 比对。",
|
||||
"match_rule_source": "llm",
|
||||
@@ -39,10 +48,12 @@ def test_format_field_alignment_summary_single_block():
|
||||
assert "订单样例:" in text
|
||||
assert "预订单号 1000140351" in text
|
||||
assert "料号 504-010213-001" in text
|
||||
assert "回复「确认」进入匹配" in text
|
||||
assert "请核对字段对齐后使用下方按钮继续" in text
|
||||
assert "回复「确认」进入匹配" not in text
|
||||
|
||||
|
||||
def test_format_field_alignment_summary_includes_warnings():
|
||||
"""调用方警告与字段对齐警告都应合并展示。"""
|
||||
text = format_field_alignment_summary(
|
||||
task_no="SN-1",
|
||||
field_alignment={
|
||||
|
||||
@@ -29,6 +29,10 @@ from app.models import (
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -44,6 +48,538 @@ def _make_upload(content: bytes = b'customer order line', filename: str = 'notic
|
||||
return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
|
||||
|
||||
|
||||
def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
"""Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。"""
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='candidate-owner', email='candidate-owner@example.com', password_hash='x')
|
||||
other = User(username='candidate-other', email='candidate-other@example.com', password_hash='x')
|
||||
db.session.add_all([owner, other])
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-CANDIDATE-API-001',
|
||||
owner_user_id=owner.id,
|
||||
original_filename='order-7001.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{owner.id}/order-7001.pdf',
|
||||
content_hash='candidate-api-content-hash',
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-CANDIDATE-API-001',
|
||||
asset_id=asset.id,
|
||||
user_id=owner.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key='attachment-1',
|
||||
filename='order-7001.pdf',
|
||||
content_hash=asset.content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-CANDIDATE-EXISTING-001',
|
||||
user_id=owner.id,
|
||||
source_content_hash=asset.content_hash,
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add_all([document, existing])
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-CANDIDATE-API-001',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='test:SNC-CANDIDATE-API-001',
|
||||
po_number='7001',
|
||||
structured_result_json={
|
||||
'business_summary': {
|
||||
'po_number': '7001',
|
||||
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 1}],
|
||||
},
|
||||
},
|
||||
validation_status='needs_review',
|
||||
conflicts_json=[{'field': 'qty'}],
|
||||
selected=True,
|
||||
duplicate_resolution='open_existing',
|
||||
duplicate_target_task_no=existing.task_no,
|
||||
duplicate_resolved_by_id=owner.id,
|
||||
duplicate_resolved_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
|
||||
|
||||
patch_response = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
|
||||
json={
|
||||
'selected': False,
|
||||
'business_summary': {
|
||||
'po_number': '7001',
|
||||
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 2}],
|
||||
},
|
||||
},
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert patch_response.status_code == 200
|
||||
patched = patch_response.get_json()['data']
|
||||
assert patched['selected'] is False
|
||||
assert patched['validation_status'] == 'ready'
|
||||
assert patched['conflicts'] == []
|
||||
assert patched['content_fingerprint']
|
||||
assert patched['duplicate_resolution'] is None
|
||||
|
||||
forbidden = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
|
||||
json={'selected': True},
|
||||
headers=other_headers,
|
||||
)
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
refresh = client.post(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-refresh',
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert refresh.status_code == 200
|
||||
refreshed = refresh.get_json()['data']
|
||||
assert refreshed['duplicate']['status'] == 'exact_file'
|
||||
assert 'open_existing' in refreshed['duplicate']['allowed_actions']
|
||||
|
||||
resolution = client.post(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-resolution',
|
||||
json={'action': 'open_existing', 'target_task_no': 'SN-CANDIDATE-EXISTING-001'},
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert resolution.status_code == 200
|
||||
assert resolution.get_json()['data']['duplicate_resolution']['action'] == 'open_existing'
|
||||
|
||||
with app.app_context():
|
||||
row = db.session.query(ShippingNoticeCandidate).filter_by(
|
||||
candidate_no='SNC-CANDIDATE-API-001',
|
||||
).one()
|
||||
row.consumed_task_id = db.session.query(ShippingTask).filter_by(
|
||||
task_no='SN-CANDIDATE-EXISTING-001',
|
||||
).one().id
|
||||
db.session.commit()
|
||||
|
||||
consumed = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
|
||||
json={'selected': True},
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert consumed.status_code == 409
|
||||
|
||||
|
||||
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
|
||||
"""人工修订不得以空摘要或无效 SKU/Qty 绕过 Candidate 审核门禁。"""
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-CANDIDATE-VALIDATION',
|
||||
owner_user_id=user.id,
|
||||
original_filename='invalid-order.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user.id}/invalid-order.pdf',
|
||||
content_hash='candidate-validation-hash',
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-CANDIDATE-VALIDATION',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key='invalid-order',
|
||||
filename='invalid-order.pdf',
|
||||
content_hash=asset.content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-CANDIDATE-VALIDATION',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='test:SNC-CANDIDATE-VALIDATION',
|
||||
structured_result_json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 1}]}},
|
||||
validation_status='needs_review',
|
||||
selected=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
|
||||
|
||||
empty = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
|
||||
json={'business_summary': {}},
|
||||
headers=headers,
|
||||
)
|
||||
assert empty.status_code == 400
|
||||
assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
|
||||
|
||||
invalid_qty = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
|
||||
json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 0}]}},
|
||||
headers=headers,
|
||||
)
|
||||
assert invalid_qty.status_code == 400
|
||||
|
||||
invalid_reservation = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
|
||||
json={
|
||||
'business_summary': {
|
||||
'lines': [
|
||||
{
|
||||
'sku': 'SKU-1',
|
||||
'qty': 1,
|
||||
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert invalid_reservation.status_code == 400
|
||||
assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
|
||||
|
||||
invalid_selected = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
|
||||
json={'selected': 'false'},
|
||||
headers=headers,
|
||||
)
|
||||
assert invalid_selected.status_code == 400
|
||||
|
||||
null_summary = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
|
||||
json={'business_summary': None},
|
||||
headers=headers,
|
||||
)
|
||||
assert null_summary.status_code == 400
|
||||
|
||||
|
||||
def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app, shipping_user):
|
||||
"""Candidate 建批必须继承附件完整性/过期门禁,并要求传入集合等于服务端已选集合。"""
|
||||
with app.app_context():
|
||||
parent = FileAsset(
|
||||
asset_no='FA-CANDIDATE-GATE',
|
||||
owner_user_id=shipping_user.id,
|
||||
original_filename='gate.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{shipping_user.id}/gate.eml',
|
||||
content_hash='candidate-gate-parent',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-CANDIDATE-GATE',
|
||||
asset_id=parent.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
structured_result_json={
|
||||
'attachment_count': 1,
|
||||
'attachments': [{'parse_status': 'failed', 'filename': 'gate.pdf'}],
|
||||
},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidates = []
|
||||
for index in (1, 2):
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'gate-{index}',
|
||||
filename=f'gate-{index}.pdf',
|
||||
content_hash=f'candidate-gate-{index}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
summary = {'po_number': f'PO-{index}', 'lines': [{'sku': f'SKU-{index}', 'qty': index}]}
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-CANDIDATE-GATE-{index}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key=f'test:SNC-CANDIDATE-GATE-{index}',
|
||||
structured_result_json={'business_summary': summary},
|
||||
validation_status='ready',
|
||||
conflicts_json=[],
|
||||
selected=True,
|
||||
duplicate_status='none',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
candidates.append(candidate)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as incomplete:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-gate',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=[candidate.candidate_no for candidate in candidates],
|
||||
)
|
||||
assert incomplete.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
|
||||
db.session.rollback()
|
||||
|
||||
intake.structured_result_json = {'attachment_count': 0, 'attachments': []}
|
||||
intake.expires_at = datetime(2020, 1, 1)
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as expired:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-gate',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=[candidate.candidate_no for candidate in candidates],
|
||||
)
|
||||
assert expired.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED'
|
||||
db.session.rollback()
|
||||
|
||||
intake.expires_at = None
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as changed:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-gate',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=[candidates[0].candidate_no],
|
||||
)
|
||||
assert changed.value.code == 'SHIPPING_NOTICE.CANDIDATE_SELECTION_CHANGED'
|
||||
|
||||
for candidate in candidates:
|
||||
candidate.selected = False
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as none_selected:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-gate',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=None,
|
||||
)
|
||||
assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED'
|
||||
|
||||
|
||||
def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user):
|
||||
"""v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。"""
|
||||
with app.app_context():
|
||||
asset = FileAsset(
|
||||
asset_no='FA-CANDIDATE-MISSING',
|
||||
owner_user_id=shipping_user.id,
|
||||
original_filename='missing-candidates.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{shipping_user.id}/missing-candidates.eml',
|
||||
content_hash='candidate-missing-hash',
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-CANDIDATE-MISSING',
|
||||
asset_id=asset.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
structured_result_json={'attachment_count': 0, 'attachments': []},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as missing:
|
||||
create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-missing-candidate',
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
assert missing.value.code == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
|
||||
assert db.session.query(ShippingTask).filter_by(source_intake_id=intake.id).count() == 0
|
||||
|
||||
|
||||
def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping_user, monkeypatch):
|
||||
"""一封邮件的三个已审核 Candidate 应创建一个批次和三个独立 Task,并支持幂等重放。"""
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
with app.app_context():
|
||||
parent = FileAsset(
|
||||
asset_no='FA-CANDIDATE-BATCH',
|
||||
owner_user_id=shipping_user.id,
|
||||
original_filename='three-orders.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{shipping_user.id}/three-orders.eml',
|
||||
content_hash='eml-three-orders',
|
||||
file_size=1000,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-CANDIDATE-BATCH',
|
||||
asset_id=parent.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='three orders',
|
||||
structured_result_json={
|
||||
'attachment_count': 3,
|
||||
'attachment_registered_count': 3,
|
||||
'attachments': [
|
||||
{'filename': f'{po}.pdf', 'parse_status': 'parsed'}
|
||||
for po in ('4510039227', '4510039228', '4510039229')
|
||||
],
|
||||
},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
candidate_nos = []
|
||||
hashes = []
|
||||
for index, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
|
||||
attachment = FileAsset(
|
||||
asset_no=f'FA-CAND-{index}',
|
||||
owner_user_id=shipping_user.id,
|
||||
parent_asset_id=parent.id,
|
||||
asset_role='derived_attachment',
|
||||
source_attachment_key=f'att-{index}',
|
||||
original_filename=f'{po}.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{shipping_user.id}/{po}.pdf',
|
||||
content_hash=f'pdf-hash-{po}',
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='referenced',
|
||||
)
|
||||
db.session.add(attachment)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=attachment.id,
|
||||
attachment_key=f'att-{index}',
|
||||
document_type='attachment',
|
||||
filename=f'{po}.pdf',
|
||||
content_hash=attachment.content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO Number: {po} SKU-{index} x {index}',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
summary = {
|
||||
'customer_code': 'C1',
|
||||
'po_number': po,
|
||||
'reservation_ids': [f'20004859{index:02d}'],
|
||||
'lines': [
|
||||
{
|
||||
'reservation_id': f'20004859{index:02d}',
|
||||
'sku': f'SKU-{index}',
|
||||
'qty': index,
|
||||
'uom': 'EA',
|
||||
}
|
||||
],
|
||||
}
|
||||
identity = build_business_fingerprint(summary)
|
||||
content = build_content_fingerprint(summary)
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-CAND-BATCH-{index}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key=f'test:SNC-CAND-BATCH-{index}',
|
||||
po_number=po,
|
||||
structured_result_json={'business_summary': summary},
|
||||
validation_status='ready',
|
||||
conflicts_json=[],
|
||||
selected=True,
|
||||
business_fingerprint=identity['fingerprint'],
|
||||
fingerprint_version=identity['version'],
|
||||
fingerprint_strength=identity['strength'],
|
||||
content_fingerprint=content['fingerprint'],
|
||||
content_fingerprint_version=content['version'],
|
||||
duplicate_status='none',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
candidate_nos.append(candidate.candidate_no)
|
||||
hashes.append(attachment.content_hash)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator',
|
||||
lambda _batch_no: False,
|
||||
)
|
||||
first = create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-candidate-batch',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=candidate_nos,
|
||||
create_idempotency_key='candidate-batch-idem',
|
||||
)
|
||||
assert first['batch_no']
|
||||
batch = db.session.query(ShippingBatch).filter_by(batch_no=first['batch_no']).one()
|
||||
tasks = db.session.query(ShippingTask).filter_by(batch_id=batch.id).order_by(ShippingTask.id).all()
|
||||
assert len(tasks) == 3
|
||||
assert {task.source_content_hash for task in tasks} == set(hashes)
|
||||
assert all(task.source_candidate_id for task in tasks)
|
||||
assert len({task.source_candidate_id for task in tasks}) == 3
|
||||
|
||||
replay = create_shipping_batch_from_intakes(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id='conv-candidate-batch',
|
||||
intake_nos=[intake.intake_no],
|
||||
candidate_nos=candidate_nos,
|
||||
create_idempotency_key='candidate-batch-idem',
|
||||
)
|
||||
assert replay['idempotent_replay'] is True
|
||||
assert replay['batch_no'] == first['batch_no']
|
||||
|
||||
|
||||
def test_upload_file_asset_creates_ready_record(app, shipping_user):
|
||||
with app.app_context():
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
@@ -2740,12 +3276,12 @@ def _minimal_pdf_bytes(marker: str) -> bytes:
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
|
||||
def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candidates(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""
|
||||
阶段二验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document + 3 Candidate;
|
||||
正文订单表不额外生成第 4 候选;各 PDF 独立 FileAsset;重试不膨胀。
|
||||
上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document;
|
||||
点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。
|
||||
"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
@@ -2845,14 +3381,13 @@ def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
|
||||
assert len(pdf_docs) == 3
|
||||
assert all(d.classification == 'order_notice' for d in pdf_docs)
|
||||
assert all(d.asset_id for d in pdf_docs)
|
||||
assert len(cands) == 3
|
||||
assert all(c.primary_document_id != body_docs[0].id for c in cands)
|
||||
assert len(cands) == 0
|
||||
assert len(children) == 3
|
||||
assert len({c.content_hash for c in children}) == 3
|
||||
|
||||
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
|
||||
assert detail['document_count'] == 4
|
||||
assert detail['candidate_count'] == 3
|
||||
assert detail['candidate_count'] == 0
|
||||
|
||||
intake2 = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
@@ -2871,7 +3406,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
|
||||
.id
|
||||
)
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 3
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
|
||||
assert (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
|
||||
@@ -3002,10 +3537,10 @@ def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
|
||||
assert retried['parse_status'] == 'queued'
|
||||
|
||||
|
||||
def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
|
||||
def test_upload_preprocess_does_not_invoke_candidate_dedup(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""Candidate 重复检测异常仅 SAVEPOINT 回滚:Document/Candidate 保留,去重为 unchecked。"""
|
||||
"""上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
@@ -3055,16 +3590,17 @@ def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parsed'
|
||||
assert result.get('duplicate_status') == 'unchecked'
|
||||
assert result.get('candidate_count') == 0
|
||||
assert result.get('order_extraction_status') == 'not_started'
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
|
||||
intake_no='SNI-DEDUP-SAVEPOINT'
|
||||
).one()
|
||||
assert refreshed.parse_status == 'parsed'
|
||||
assert refreshed.duplicate_status == 'unchecked'
|
||||
assert refreshed.order_extraction_status == 'not_started'
|
||||
assert refreshed.duplicate_matches_json in (None, [])
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=refreshed.id).count() >= 1
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() >= 1
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() == 0
|
||||
|
||||
|
||||
def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
|
||||
|
||||
@@ -67,6 +67,17 @@ def test_parse_aws_inventory_headers(app):
|
||||
assert lines[1]["odm_id"] == "16754797"
|
||||
|
||||
|
||||
def test_parse_inventory_drops_internal_hex_reservation_id(app):
|
||||
"""库存快照可保留 SKU/数量,但内部 hex 不得写入 Reservation ID 字段。"""
|
||||
with app.app_context():
|
||||
lines = parse_inventory_rows(
|
||||
["AWS Sku", "COM ID", "Qty Available"],
|
||||
[["A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
|
||||
)
|
||||
|
||||
assert lines == [{"sku": "A001", "available_qty": 2.0}]
|
||||
|
||||
|
||||
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
|
||||
with app.app_context():
|
||||
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_order_extraction.py
|
||||
|
||||
用途:验证点击发送后的 Dify 完整订单抽取、订单级 Candidate、自动建单和安全门禁。
|
||||
依赖:agent_runtime_context builder、order_extraction、Shipping Notice 模型与 pytest Flask fixture。
|
||||
逻辑:构造一封已预处理邮件及单个附件,模拟 Chatflow 读取快照并提交多个 orders[],断言部分成功、幂等与来源漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
EXTRACTION_CONTRACT_VERSION,
|
||||
get_order_extraction_context,
|
||||
submit_order_extraction,
|
||||
)
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
|
||||
|
||||
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
|
||||
"""
|
||||
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
|
||||
|
||||
Returns:
|
||||
用户、会话、Intake、Document 与序列化 agent_runtime_context。
|
||||
"""
|
||||
user = User(username='order-extraction-user', email='order-extraction@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name='Shipping Notice',
|
||||
agent_code='shipping_notice',
|
||||
dify_app_id='shipping-order-extraction-test',
|
||||
dify_api_key='test-key',
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
session = ChatSession(
|
||||
session_id='shipping-order-extraction-session',
|
||||
user_id=int(user.id),
|
||||
agent_id=int(agent.id),
|
||||
title='Order extraction',
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no='FA-ORDER-EXTRACTION-001',
|
||||
owner_user_id=int(user.id),
|
||||
original_filename='orders.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user.id}/orders.eml',
|
||||
content_hash='order-extraction-parent-hash',
|
||||
file_size=256,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add_all([session, asset])
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-ORDER-EXTRACTION-001',
|
||||
asset_id=int(asset.id),
|
||||
user_id=int(user.id),
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
order_extraction_status='not_started',
|
||||
structured_result_json={'rule_hints': {'attachment_count': 1}},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=int(intake.id),
|
||||
asset_id=int(asset.id),
|
||||
document_type='attachment',
|
||||
attachment_key='orders.pdf',
|
||||
filename='orders.pdf',
|
||||
content_hash='order-extraction-document-hash',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=(
|
||||
'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n'
|
||||
'PO 4510000002 SKU SKU-B QTY 20'
|
||||
),
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
context = build_agent_runtime_context(
|
||||
agent_code='shipping_notice',
|
||||
session_id=session.session_id,
|
||||
request_id='req-order-extraction-001',
|
||||
refs={
|
||||
'capability': 'order_extraction',
|
||||
'contract_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'intake_nos': json.dumps([intake.intake_no], separators=(',', ':')),
|
||||
'run_purpose': 'order_extraction',
|
||||
},
|
||||
)
|
||||
return user, session, intake, document, serialize_for_dify(context)
|
||||
|
||||
|
||||
def _order(
|
||||
*,
|
||||
intake_no: str,
|
||||
document_id: int,
|
||||
po_number: str,
|
||||
sku: str,
|
||||
qty: int,
|
||||
confidence: float = 0.99,
|
||||
include_process_fields: bool,
|
||||
) -> dict:
|
||||
"""构造符合 Chatflow v1 契约的单个订单结果。"""
|
||||
line = {'sku': sku, 'qty': qty}
|
||||
if include_process_fields:
|
||||
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin', 'hub_code': 'DUB'})
|
||||
return {
|
||||
'source_intake_no': intake_no,
|
||||
'primary_document_id': document_id,
|
||||
'candidate_key_hint': po_number,
|
||||
'classification': 'shipping_request',
|
||||
'classification_confidence': confidence,
|
||||
'field_confidence': {'sku': confidence, 'qty': confidence},
|
||||
'po_number': po_number,
|
||||
'lines': [line],
|
||||
'evidence': [
|
||||
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
|
||||
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
|
||||
|
||||
def test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay(app):
|
||||
"""一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
|
||||
# 断言读取 Tool 返回不可变快照,并把 Intake 绑定到当前会话。
|
||||
assert context_result['status'] == 'ok'
|
||||
assert context_result['intake_nos'] == [intake.intake_no]
|
||||
assert context_result['documents'][0]['document_id'] == document.id
|
||||
snapshot = context_result['input_snapshot_hash']
|
||||
|
||||
payload = {
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': snapshot,
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [
|
||||
_order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
sku='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=False,
|
||||
),
|
||||
_order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000002',
|
||||
sku='SKU-B',
|
||||
qty=20,
|
||||
confidence=0.60,
|
||||
include_process_fields=True,
|
||||
),
|
||||
],
|
||||
}
|
||||
result = submit_order_extraction(payload)
|
||||
|
||||
# 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。
|
||||
assert result['auto_created_count'] == 1
|
||||
assert result['pending_count'] == 1
|
||||
assert result['batch_no']
|
||||
candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all()
|
||||
assert len(candidates) == 2
|
||||
assert len({item.candidate_key for item in candidates}) == 2
|
||||
tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all()
|
||||
assert len(tasks) == 1
|
||||
task = tasks[0]
|
||||
assert task.process_status == 'pending_review'
|
||||
assert task.pending_human_reason == 'rsv_req'
|
||||
assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == [
|
||||
'hub_code',
|
||||
'reservation_id',
|
||||
'source_type',
|
||||
]
|
||||
db.session.refresh(intake)
|
||||
assert intake.parse_status == 'parsed'
|
||||
assert intake.order_extraction_status == 'partially_completed'
|
||||
db.session.refresh(document)
|
||||
assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2
|
||||
|
||||
# 断言后台或自然语言“继续”无法绕过字段门禁进入库存流程。
|
||||
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
|
||||
progress = auto_progress({'task_id': task.task_no})
|
||||
assert progress['status'] == 'needs_human'
|
||||
assert progress['checkpoint'] == 'rsv_req'
|
||||
assert 'ensure_inventory' in progress['forbidden_next_tools']
|
||||
|
||||
replay = submit_order_extraction(payload)
|
||||
assert replay['idempotent_replay'] is True
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
|
||||
|
||||
edit_result = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {
|
||||
'reservation_id': 'R-100',
|
||||
'source_type': 'AWS Dublin',
|
||||
'hub_code': 'DUB',
|
||||
},
|
||||
'comment': '用户通过自然对话补齐流程字段',
|
||||
})
|
||||
db.session.refresh(task)
|
||||
# 断言既有行更新 Tool 可完成自然对话补字段,并清除旧流程字段门禁。
|
||||
assert edit_result['status'] == 'ok'
|
||||
assert task.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (task.step_payload_json or {})
|
||||
assert task.lines_json[0]['reservation_id'] == 'R-100'
|
||||
assert task.lines_json[0]['source_type'] == 'AWS Dublin'
|
||||
assert task.lines_json[0]['hub_code'] == 'DUB'
|
||||
assert session.user_id == user.id
|
||||
|
||||
|
||||
def test_submit_order_extraction_rejects_changed_document_snapshot(app):
|
||||
"""读取上下文后附件文本变化时,旧 LLM 结果不得覆盖新来源。"""
|
||||
with app.app_context():
|
||||
_user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
document.extracted_text = f'{document.extracted_text}\nCHANGED'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [],
|
||||
})
|
||||
|
||||
# 断言来源漂移使用稳定错误码,要求 Dify 重新读取上下文而不是重放旧结果。
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED'
|
||||
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0
|
||||
@@ -1,5 +1,9 @@
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
from app.services.shipping_notice.reservation_id import normalize_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
is_valid_reservation_id,
|
||||
normalize_reservation_id,
|
||||
validated_reservation_id,
|
||||
)
|
||||
|
||||
|
||||
def test_match_numeric_reservation_id():
|
||||
@@ -13,3 +17,13 @@ def test_match_numeric_reservation_id():
|
||||
|
||||
def test_normalize_reservation_id_string():
|
||||
assert normalize_reservation_id("1000140351") == "1000140351"
|
||||
|
||||
|
||||
def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids():
|
||||
"""硬契约应拒绝内部 hex 主键,同时兼容已有字母型业务 Reservation ID。"""
|
||||
assert not is_valid_reservation_id("1f1a682dfdc446a393415dee93eb36ce")
|
||||
assert validated_reservation_id("1f1a682dfdc446a393415dee93eb36ce") == ""
|
||||
assert is_valid_reservation_id("3000092917")
|
||||
assert is_valid_reservation_id("AWS-311")
|
||||
assert is_valid_reservation_id("R-1")
|
||||
assert not is_valid_reservation_id("AWS-311", numeric_only=True)
|
||||
@@ -121,7 +121,14 @@ def test_shipping_notice_tool_flow(app, client):
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
|
||||
"lines": [{
|
||||
"sku": "A001",
|
||||
"reservation_id": "R-1",
|
||||
"qty": 10,
|
||||
"uom": "EA",
|
||||
"source_type": "AWS Dublin",
|
||||
"hub_code": "DUB",
|
||||
}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
@@ -1297,6 +1304,132 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
|
||||
assert task.match_status is None
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_parse_notice_blocks_invalid_nonempty_reservation_id(app, client, monkeypatch):
|
||||
"""非空内部 hex ID 仍应被后端硬闸门阻断,并在 step_payload 留存解析问题。"""
|
||||
import app.services.shipping_notice.task_workflow as task_workflow
|
||||
|
||||
monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda task_no: True)
|
||||
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,
|
||||
"raw_text": "Commodity group ID External reservation ID 1f1a682dfdc446a393415dee93eb36ce 3000092917",
|
||||
"structured": {
|
||||
"lines": [
|
||||
{
|
||||
"sku": "TEMP-S000218929/D4-A08AR12000002",
|
||||
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
|
||||
"qty": 10,
|
||||
"uom": "EA",
|
||||
}
|
||||
],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
data = parse_res.get_json()
|
||||
assert data["status"] == "needs_human"
|
||||
assert data["checkpoint"] == "rsv_req"
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert "reservation_id" not in task.lines_json[0]
|
||||
validation = (task.step_payload_json or {})["parse_validation"]
|
||||
assert validation["status"] == "needs_review"
|
||||
assert validation["issues"][0]["reason"] == "invalid_format"
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_human_edit_revalidates_reservation_and_blocks_stale_confirm(app, client, monkeypatch):
|
||||
"""人工修订应重算硬契约;非法值不能确认,改成合法字母型业务 ID 后清除阻断。"""
|
||||
import app.services.shipping_notice.decision_workflow as decision_workflow
|
||||
|
||||
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", lambda task_no: True)
|
||||
headers = _tool_headers(app)
|
||||
task_id = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
).get_json()["task_id"]
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
|
||||
"confidence": 0.4,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
invalid_edit = client.post(
|
||||
"/api/shipping-notice/tools/update_notice_line",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "f" * 32}},
|
||||
)
|
||||
assert invalid_edit.get_json()["status"] == "ok"
|
||||
blocked = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "confirm_parse"},
|
||||
).get_json()
|
||||
assert blocked["status"] == "needs_human"
|
||||
assert blocked["data"]["parse_validation"]["issues"][0]["reason"] == "invalid_format"
|
||||
|
||||
valid_edit = client.post(
|
||||
"/api/shipping-notice/tools/update_notice_line",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "AWS-311"}},
|
||||
)
|
||||
assert valid_edit.get_json()["status"] == "ok"
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
validation = (task.step_payload_json or {})["parse_validation"]
|
||||
assert validation["status"] == "ready"
|
||||
assert validation["issues"] == []
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(app, client):
|
||||
"""两个值格式都合法时,原文列证据冲突仍必须进入 parse_review,不能靠高置信度自动通过。"""
|
||||
headers = _tool_headers(app)
|
||||
task_id = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
).get_json()["task_id"]
|
||||
raw_text = "AWS Sku\tReservation ID\tQty\nA001\t3000092917\t2"
|
||||
|
||||
result = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"raw_text": raw_text,
|
||||
"structured": {
|
||||
"lines": [{"sku": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
).get_json()
|
||||
|
||||
assert result["status"] == "needs_human"
|
||||
assert result["checkpoint"] == "parse_review"
|
||||
assert result["data"]["parse_validation"]["issues"][0]["reason"] == "source_conflict"
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
Reference in new issue
Block a user