feat(shipping-notice): 新增订单行与字段冲突管理功能,支持字段冲突查询与解决
This commit is contained in:
1 parent
4fbaed2b4c
commit
9da0481fc3
74 files changed
+4861
-375
No files matched your search
@@ -151,8 +151,8 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
|
||||
assert rows[0]['source_type'] == 'VMI-FRA01'
|
||||
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
|
||||
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
|
||||
assert 'hub_code' not in rows[0]
|
||||
assert 'hub_code' not in rows[2]
|
||||
assert rows[0]['hub_code'] == 'FRA01'
|
||||
assert rows[2]['hub_code'] == 'DUB'
|
||||
|
||||
fused = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
@@ -168,7 +168,7 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
|
||||
assert not fused['conflicts']
|
||||
assert line['source_type'] == 'VMI-FRA01'
|
||||
assert line['customer_sku'] == 'TEMP-S000218922'
|
||||
assert 'hub_code' not in line
|
||||
assert line['hub_code'] == 'FRA01'
|
||||
|
||||
conflict = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
|
||||
@@ -419,7 +419,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
|
||||
batch_index=1,
|
||||
batch_total=2,
|
||||
)
|
||||
@@ -428,7 +428,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
lines_json=[{"sku": "B001", "qty": 1}],
|
||||
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
|
||||
batch_index=2,
|
||||
batch_total=2,
|
||||
)
|
||||
@@ -730,7 +730,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
|
||||
batch_index=1,
|
||||
batch_total=2,
|
||||
)
|
||||
@@ -739,7 +739,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
lines_json=[{"sku": "B001", "qty": 1}],
|
||||
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
|
||||
batch_index=2,
|
||||
batch_total=2,
|
||||
)
|
||||
@@ -877,7 +877,7 @@ def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path):
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
@@ -1000,7 +1000,7 @@ def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path):
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
@@ -1026,7 +1026,7 @@ def test_manual_upload_rejects_xls_extension(app, tmp_path):
|
||||
task_no="SN-GATE-UPLOAD-XLS",
|
||||
source_type="pdf",
|
||||
process_status="waiting_inventory",
|
||||
lines_json=[{"sku": "A001", "qty": 1}],
|
||||
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.add(task)
|
||||
|
||||
@@ -17,7 +17,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
"""
|
||||
校验订单行与库存连接器的字段边界。
|
||||
|
||||
核心逻辑:订单行保留可选 source_type 且不暴露 hub_code;任务状态说明使用
|
||||
核心逻辑:订单行保留可选 source_type 与独立 hub_code;任务状态说明使用
|
||||
inventory_connector_type,并拒绝旧 inventory_source_type 命名。
|
||||
|
||||
Args:
|
||||
@@ -30,8 +30,9 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
"application/json"
|
||||
]["schema"]["properties"]["orders"]["items"]
|
||||
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
|
||||
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type"}
|
||||
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type", "hub_code"}
|
||||
assert "可选订单路由线索" in line_properties["source_type"]["description"]
|
||||
assert "Hub" in line_properties["hub_code"]["description"] or "hub" in line_properties["hub_code"]["description"].lower()
|
||||
|
||||
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
|
||||
assert "inventory_connector_type" in status_description
|
||||
|
||||
@@ -36,6 +36,7 @@ from app.services.agent_registry.handlers.registry import get_handler
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
from app.services.chat.stream_relay import iter_handler_preface_sse
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
EXTRACTION_CONTRACT_VERSION,
|
||||
ORDER_EXTRACTION_FAILED_CODE,
|
||||
@@ -57,6 +58,20 @@ from app.services.shipping_notice.query_service import resolve_order_extraction_
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
|
||||
|
||||
def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it():
|
||||
"""Reservation 是逐行匹配键;部分行缺失时整单摘要必须保留流程门禁。"""
|
||||
assessment = assess_candidate_business_summary({
|
||||
'po_number': '4510038672',
|
||||
'lines': [
|
||||
{'sku': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
|
||||
{'sku': 'SKU-B', 'qty': 2},
|
||||
],
|
||||
})
|
||||
|
||||
assert assessment['can_create_task'] is True
|
||||
assert assessment['missing_process_fields'] == ['reservation_id']
|
||||
|
||||
|
||||
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
|
||||
"""
|
||||
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
|
||||
@@ -150,6 +165,16 @@ def _order(
|
||||
line = {'sku': sku, 'qty': qty}
|
||||
if include_process_fields:
|
||||
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin'})
|
||||
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},
|
||||
]
|
||||
if include_process_fields:
|
||||
evidence.append({
|
||||
'field': 'lines[0].reservation_id',
|
||||
'quote': 'R-100',
|
||||
'document_id': document_id,
|
||||
})
|
||||
return {
|
||||
'source_intake_no': intake_no,
|
||||
'primary_document_id': document_id,
|
||||
@@ -159,10 +184,7 @@ def _order(
|
||||
'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},
|
||||
],
|
||||
'evidence': evidence,
|
||||
'conflicts': [],
|
||||
}
|
||||
|
||||
@@ -211,7 +233,7 @@ def _add_extraction_intake(
|
||||
content_hash=f'order-extraction-document-{suffix.lower()}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'SKU SKU-{normalized} QTY 1',
|
||||
extracted_text=f'SKU SKU-{normalized} QTY 1 RSV R-100',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
@@ -1231,6 +1253,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
document.extracted_text = f"{document.extracted_text}\nReservation ID 1000140351"
|
||||
db.session.commit()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
@@ -1242,6 +1266,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
)
|
||||
order['lines'][0]['reservation_id'] = '1000140351'
|
||||
order['lines'][0]['source_type'] = 'DBS DUB'
|
||||
order['evidence'][-1]['quote'] = '1000140351'
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
@@ -1256,7 +1281,12 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
|
||||
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert candidate_line['source_type'] == 'DBS DUB'
|
||||
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA', 'reservation_id': '1000140351'}]
|
||||
# 通用字段对账会同时补空的 Source Type 等可选字段;Reservation 必须落库。
|
||||
assert existing.lines_json[0]['sku'] == 'P123456'
|
||||
assert existing.lines_json[0]['qty'] == 24
|
||||
assert existing.lines_json[0]['uom'] == 'EA'
|
||||
assert existing.lines_json[0]['reservation_id'] == '1000140351'
|
||||
assert existing.lines_json[0].get('source_type') == 'DBS DUB'
|
||||
assert existing.process_status == 'pending_review'
|
||||
assert existing.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (existing.step_payload_json or {})
|
||||
@@ -1266,7 +1296,73 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
event_type='reservation_backfilled_from_exact_file_candidate',
|
||||
).one()
|
||||
assert event.detail_json['updated_line_indexes'] == [0]
|
||||
assert event.detail_json['review_preserved'] is True
|
||||
|
||||
|
||||
def test_order_extraction_does_not_auto_create_with_unverified_reservation_evidence(app):
|
||||
"""关键匹配键没有当前 Intake 原文证据时,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})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
sku='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=True,
|
||||
)
|
||||
order['evidence'] = [
|
||||
item
|
||||
for item in order['evidence']
|
||||
if item['field'] != 'lines[0].reservation_id'
|
||||
]
|
||||
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
assert result['created_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
"""即使 LLM 未声明冲突,后端也必须用明确表格列证据阻断不一致的 Reservation。"""
|
||||
with app.app_context():
|
||||
user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
document.extracted_text = (
|
||||
"SKU\tReservation ID\tQty\n"
|
||||
"SKU-A\tR-200\t10\n"
|
||||
"LLM candidate quote R-100"
|
||||
)
|
||||
db.session.commit()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
sku='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=True,
|
||||
)
|
||||
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
assert result['created_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert candidate.conflicts_json[0]['reason'] == 'source_conflict'
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -1296,7 +1392,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
changed = backfill_exact_file_open_existing_reservations(
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
candidate=candidate,
|
||||
candidate_summary={
|
||||
@@ -1305,9 +1401,15 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
},
|
||||
duplicate_status='exact_file',
|
||||
duplicate_matches=[{'task_no': task.task_no}],
|
||||
verified_reservation_evidence=[{
|
||||
'line_index': 0,
|
||||
'reservation_id': '1000140351',
|
||||
'document_id': 1,
|
||||
'quote': '1000140351',
|
||||
}],
|
||||
)
|
||||
|
||||
assert changed is False
|
||||
assert outcome['status'] == 'skipped'
|
||||
assert 'reservation_id' not in task.lines_json[0]
|
||||
assert ShippingTaskEvent.query.filter_by(
|
||||
task_id=int(task.id),
|
||||
@@ -1369,16 +1471,216 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
if task.task_no.endswith('AMBIGUOUS-TARGET')
|
||||
else [{'task_no': task.task_no}]
|
||||
),
|
||||
verified_reservation_evidence=[{
|
||||
'line_index': 0,
|
||||
'reservation_id': '1000140351',
|
||||
'document_id': 1,
|
||||
'quote': '1000140351',
|
||||
}],
|
||||
)
|
||||
for task in tasks
|
||||
]
|
||||
|
||||
assert results == [False, False, False]
|
||||
assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped']
|
||||
assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD'
|
||||
assert all('reservation_id' not in line for line in tasks[1].lines_json)
|
||||
assert 'reservation_id' not in tasks[2].lines_json[0]
|
||||
|
||||
|
||||
def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app):
|
||||
"""目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
)
|
||||
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
candidate=candidate,
|
||||
candidate_summary={
|
||||
'po_number': '4510038672',
|
||||
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
},
|
||||
duplicate_status='exact_file',
|
||||
duplicate_matches=[{'task_no': task.task_no}],
|
||||
verified_reservation_evidence=[{
|
||||
'line_index': 0,
|
||||
'reservation_id': '1000140351',
|
||||
'document_id': 1,
|
||||
'quote': '1000140351',
|
||||
}],
|
||||
)
|
||||
|
||||
assert outcome['status'] == 'skipped'
|
||||
assert outcome['reason'] == 'target_already_complete'
|
||||
assert task.lines_json[0]['reservation_id'] == '1000140351'
|
||||
|
||||
|
||||
def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app):
|
||||
"""已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
batch = ShippingBatch(
|
||||
batch_no='SB-ORDER-RSV-UNSAFE-OPEN-001',
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
file_count=1,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-ORDER-RSV-UNSAFE-OPEN-001',
|
||||
batch=batch,
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='waiting_inventory',
|
||||
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351'
|
||||
db.session.commit()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510038672',
|
||||
sku='P123456',
|
||||
qty=24,
|
||||
include_process_fields=True,
|
||||
)
|
||||
order['lines'][0]['reservation_id'] = '1000140351'
|
||||
order['evidence'][-1]['quote'] = '1000140351'
|
||||
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
db.session.refresh(existing)
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert result['opened_existing_count'] == 1
|
||||
assert result['pending_count'] == 0
|
||||
assert candidate.consumed_task_id == int(existing.id)
|
||||
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}]
|
||||
assert existing.process_status == 'waiting_inventory'
|
||||
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
|
||||
|
||||
|
||||
def test_order_extraction_requires_verified_pair_after_reservation_adjudication(app, monkeypatch):
|
||||
"""裁决改写 Reservation 后,必须按 (line_index, 新值) 核验证据,不能只认行号。"""
|
||||
with app.app_context():
|
||||
user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
sku='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=True,
|
||||
)
|
||||
order['lines'][0]['reservation_id'] = '1000140351'
|
||||
order['evidence'][-1]['quote'] = '1000140351'
|
||||
|
||||
def _rewrite_reservation(summary, *, documents):
|
||||
rewritten = dict(summary)
|
||||
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
|
||||
if lines:
|
||||
lines[0]['reservation_id'] = '3000092917'
|
||||
rewritten['lines'] = lines
|
||||
return rewritten, []
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction.adjudicate_order_reservations',
|
||||
_rewrite_reservation,
|
||||
)
|
||||
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
assert result['created_count'] == 0
|
||||
assert result['opened_existing_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert candidate.selected is False
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app):
|
||||
"""exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
batch = ShippingBatch(
|
||||
batch_no='SB-ORDER-RSV-UNVERIFIED-001',
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
file_count=1,
|
||||
)
|
||||
existing = ShippingTask(
|
||||
task_no='SN-ORDER-RSV-UNVERIFIED-001',
|
||||
batch=batch,
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510038672',
|
||||
sku='P123456',
|
||||
qty=24,
|
||||
include_process_fields=True,
|
||||
)
|
||||
order['lines'][0]['reservation_id'] = '1000140351'
|
||||
order['evidence'] = [
|
||||
item for item in order['evidence'] if item['field'] != 'lines[0].reservation_id'
|
||||
]
|
||||
|
||||
result = submit_order_extraction({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert candidate.duplicate_resolution == 'open_existing'
|
||||
assert candidate.selected is False
|
||||
assert candidate.validation_status == 'needs_review'
|
||||
assert candidate.consumed_task_id is None
|
||||
assert result['opened_existing_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons']
|
||||
assert 'reservation_id' not in (existing.lines_json[0] or {})
|
||||
|
||||
|
||||
def test_submit_order_extraction_rejects_changed_document_snapshot(app):
|
||||
"""读取上下文后附件文本变化时,旧 LLM 结果不得覆盖新来源。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -716,22 +716,41 @@ def test_match_inventory_requires_reservation_id(app, client):
|
||||
assert task is not None
|
||||
task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
|
||||
db.session.commit()
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/ensure_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
ensure_inventory as ensure_inventory_service,
|
||||
parse_inventory as parse_inventory_service,
|
||||
upload_inventory_file as upload_inventory_file_service,
|
||||
)
|
||||
from io import BytesIO
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
direct_data = ensure_inventory_service({
|
||||
"task_id": task_id,
|
||||
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
|
||||
},
|
||||
)
|
||||
match_res = client.post(
|
||||
"/api/shipping-notice/tools/match_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": task_id},
|
||||
)
|
||||
data = match_res.get_json()
|
||||
assert data["status"] == "needs_human"
|
||||
assert data.get("checkpoint") == "rsv_req"
|
||||
})
|
||||
assert direct_data["status"] == "needs_human", direct_data
|
||||
assert direct_data.get("checkpoint") == "rsv_req"
|
||||
assert not task.inventory_lines_json
|
||||
|
||||
parse_data = parse_inventory_service({
|
||||
"task_id": task_id,
|
||||
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
|
||||
})
|
||||
assert parse_data["status"] == "needs_human"
|
||||
assert parse_data.get("checkpoint") == "rsv_req"
|
||||
assert not task.inventory_lines_json
|
||||
|
||||
upload_data = upload_inventory_file_service(
|
||||
task_id,
|
||||
FileStorage(stream=BytesIO(b"sku,qty\nA001,1"), filename="inventory.csv"),
|
||||
)
|
||||
assert upload_data["status"] == "needs_human"
|
||||
assert upload_data.get("checkpoint") == "rsv_req"
|
||||
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory as match_inventory_service
|
||||
match_data = match_inventory_service({"task_id": task_id})
|
||||
assert match_data["status"] == "needs_human"
|
||||
assert match_data.get("checkpoint") == "rsv_req"
|
||||
|
||||
|
||||
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_field_reconciliation.py
|
||||
|
||||
用途:验证通用字段对账、冲突落库/解决、版本冲突与下游门禁。
|
||||
依赖:Flask testing app、task_candidate_reconciliation、task_field_conflict_service、field_conflict_gate。
|
||||
逻辑:覆盖 Stage5 核心验收:空值自动补、双方不同落冲突、解决回写、409 版本、冲突阻断库存入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict
|
||||
from app.services.shipping_notice.task_candidate_reconciliation import (
|
||||
apply_candidate_reconciliation_plan,
|
||||
build_candidate_reconciliation_plan,
|
||||
reconcile_exact_file_open_existing,
|
||||
)
|
||||
from app.services.shipping_notice.task_field_conflict_service import resolve_field_conflict
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.task_line_store import replace_task_order_lines
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
|
||||
|
||||
def _task(**kwargs) -> ShippingTask:
|
||||
task = ShippingTask(
|
||||
task_no=kwargs.pop('task_no', 'SN-RECON-001'),
|
||||
source_type='manual',
|
||||
process_status=kwargs.pop('process_status', 'pending_review'),
|
||||
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
|
||||
po_number=kwargs.pop('po_number', 'PO-100'),
|
||||
lines_json=kwargs.pop('lines_json', [{'sku': 'A001', 'qty': 10}]),
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
**kwargs,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> SimpleNamespace:
|
||||
"""测试用 Candidate 替身:只需要 candidate_no 与 summary。"""
|
||||
return SimpleNamespace(
|
||||
candidate_no='SNC-RECON-001',
|
||||
summary_json={'po_number': po_number, 'lines': summary_lines},
|
||||
)
|
||||
|
||||
|
||||
def test_build_plan_fills_empty_and_conflicts_on_diff(app):
|
||||
"""空字段自动进入 fills;双方非空不同进入 conflicts。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[
|
||||
{'sku': 'A001', 'qty': 10, 'reservation_id': ''},
|
||||
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
|
||||
])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
candidate_summary={
|
||||
'lines': [
|
||||
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'hub_code': 'H1'},
|
||||
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
|
||||
]
|
||||
},
|
||||
verified_reservation_evidence=[
|
||||
{'line_index': 0, 'reservation_id': '3000092917'},
|
||||
{'line_index': 1, 'reservation_id': '3000000099'},
|
||||
],
|
||||
)
|
||||
assert plan['status'] == 'conflicted'
|
||||
assert any(item['field_name'] == 'reservation_id' and item['position'] == 1 for item in plan['conflicts'])
|
||||
assert any(item['field_name'] == 'reservation_id' and item['position'] == 0 for item in plan['fills'])
|
||||
|
||||
|
||||
def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
|
||||
"""冲突落库后库存门禁应阻断。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
candidate_summary=candidate.summary_json,
|
||||
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
|
||||
)
|
||||
result = apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
|
||||
db.session.commit()
|
||||
assert result['status'] == 'conflicted'
|
||||
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 1
|
||||
gate = field_conflict_gate_response(task, lang='zh')
|
||||
assert gate is not None
|
||||
assert gate['status'] == 'needs_human'
|
||||
|
||||
|
||||
def test_resolve_conflict_writes_line_and_is_idempotent(app):
|
||||
"""解决冲突回写订单行;同幂等键可重放。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
candidate_summary=candidate.summary_json,
|
||||
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
|
||||
)
|
||||
apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
|
||||
db.session.commit()
|
||||
conflict = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').one()
|
||||
|
||||
first = resolve_field_conflict(
|
||||
task=task,
|
||||
conflict_id=conflict.id,
|
||||
resolution='take_incoming',
|
||||
expected_conflict_version=conflict.conflict_version,
|
||||
expected_order_data_version=task.order_data_version,
|
||||
resolved_by_id=1,
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
assert first['idempotent_replay'] is False
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
assert task.lines_json[0]['reservation_id'] == '3000092917'
|
||||
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 0
|
||||
|
||||
replay = resolve_field_conflict(
|
||||
task=task,
|
||||
conflict_id=conflict.id,
|
||||
resolution='take_incoming',
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
assert replay['idempotent_replay'] is True
|
||||
|
||||
|
||||
def test_update_notice_line_version_mismatch(app):
|
||||
"""改单携带过期 order_data_version 不得覆盖。"""
|
||||
with app.app_context():
|
||||
task = _task(
|
||||
process_status='parsed',
|
||||
pending_human_reason=None,
|
||||
lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
db.session.commit()
|
||||
resp = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'hub_code': 'H9'},
|
||||
'expected_order_data_version': 1,
|
||||
})
|
||||
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
stale = int(task.order_data_version) - 1
|
||||
resp = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'hub_code': 'H8'},
|
||||
'expected_order_data_version': stale,
|
||||
})
|
||||
assert resp['status'] == 'failed'
|
||||
assert resp['data']['error_code'] == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
|
||||
|
||||
|
||||
def test_multiline_conflicts_persist_and_survive_line_replace(app):
|
||||
"""多行同字段冲突应分别落库,且双写重建订单行后不得被抹掉。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _task(lines_json=[
|
||||
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
|
||||
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
|
||||
])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([
|
||||
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
|
||||
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
|
||||
])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
candidate_summary=candidate.summary_json,
|
||||
verified_reservation_evidence=[
|
||||
{'line_index': 0, 'reservation_id': '3000092917'},
|
||||
{'line_index': 1, 'reservation_id': '3000092918'},
|
||||
],
|
||||
)
|
||||
assert plan['status'] == 'conflicted'
|
||||
assert len(plan['conflicts']) == 2
|
||||
apply_candidate_reconciliation_plan(task=task, candidate=candidate, plan=plan)
|
||||
db.session.commit()
|
||||
open_rows = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').all()
|
||||
assert len(open_rows) == 2
|
||||
assert {row.position for row in open_rows} == {0, 1}
|
||||
|
||||
# 再次双写重建行主键后,冲突审计仍在。
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
db.session.commit()
|
||||
open_rows = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').all()
|
||||
assert len(open_rows) == 2
|
||||
assert all(row.line_id is not None for row in open_rows)
|
||||
|
||||
|
||||
def test_reconcile_exact_file_open_existing_auto_fill(app):
|
||||
"""安全态 exact_file 可自动补空 Reservation。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'sku': 'A001', 'qty': 10}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
result = reconcile_exact_file_open_existing(
|
||||
task=task,
|
||||
candidate=candidate,
|
||||
candidate_summary=candidate.summary_json,
|
||||
duplicate_status='exact_file',
|
||||
duplicate_matches=[{'task_no': task.task_no}],
|
||||
verified_reservation_evidence=[{'line_index': 0, 'reservation_id': '3000092917'}],
|
||||
)
|
||||
db.session.commit()
|
||||
assert result['status'] == 'applied'
|
||||
assert task.lines_json[0]['reservation_id'] == '3000092917'
|
||||
@@ -0,0 +1,297 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_line_store.py
|
||||
|
||||
用途:验证订单行双写、历史回填、影子/表读与故障回滚。
|
||||
依赖:Flask testing app、ShippingTask/ShippingTaskLine、task_line_store、backfill 脚本函数。
|
||||
逻辑:覆盖双写原子性、未知字段 round-trip、dry-run/幂等回填、shadow 差异日志、table 读投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskLine
|
||||
from app.services.shipping_notice.task_line_store import (
|
||||
clear_task_order_lines,
|
||||
compare_task_order_line_projections,
|
||||
lines_checksum,
|
||||
read_task_order_lines,
|
||||
replace_task_order_lines,
|
||||
sync_task_order_lines_from_json,
|
||||
)
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
_BACKFILL_PATH = Path(__file__).resolve().parents[1] / 'scripts' / 'backfill_shipping_task_lines.py'
|
||||
_BACKFILL_SPEC = importlib.util.spec_from_file_location(
|
||||
'backfill_shipping_task_lines',
|
||||
_BACKFILL_PATH,
|
||||
)
|
||||
assert _BACKFILL_SPEC and _BACKFILL_SPEC.loader
|
||||
_BACKFILL_MODULE = importlib.util.module_from_spec(_BACKFILL_SPEC)
|
||||
_BACKFILL_SPEC.loader.exec_module(_BACKFILL_MODULE)
|
||||
backfill_shipping_task_lines = _BACKFILL_MODULE.backfill_shipping_task_lines
|
||||
|
||||
|
||||
def _make_task(*, task_no: str = 'SN-LINE-STORE-001', lines: list | None = None) -> ShippingTask:
|
||||
"""创建最小可落库任务,供双写测试复用。"""
|
||||
task = ShippingTask(
|
||||
task_no=task_no,
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=lines if lines is not None else [],
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def test_dual_write_replace_persists_json_and_table(app):
|
||||
"""dual 写模式应在同一事务内更新 lines_json 与规范表,并保留未知字段。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'json'
|
||||
task = _make_task()
|
||||
version_before = int(task.order_data_version)
|
||||
|
||||
written = replace_task_order_lines(
|
||||
task,
|
||||
[
|
||||
{
|
||||
'sku': 'A001',
|
||||
'qty': 10,
|
||||
'reservation_id': '3000092917',
|
||||
'hub_code': 'H1',
|
||||
'custom_note': 'keep-me',
|
||||
}
|
||||
],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert written[0]['sku'] == 'A001'
|
||||
assert task.lines_json[0]['custom_note'] == 'keep-me'
|
||||
assert int(task.order_data_version) == version_before + 1
|
||||
assert task.order_lines_migration_status == 'synced'
|
||||
|
||||
rows = ShippingTaskLine.query.filter_by(task_id=task.id).order_by(ShippingTaskLine.position).all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].sku == 'A001'
|
||||
assert rows[0].qty == Decimal('10')
|
||||
assert rows[0].reservation_id == '3000092917'
|
||||
assert rows[0].hub_code == 'H1'
|
||||
assert rows[0].extra_json == {'custom_note': 'keep-me'}
|
||||
assert compare_task_order_line_projections(task)['equal'] is True
|
||||
|
||||
|
||||
def test_dual_write_failure_rolls_back_both_sides(app):
|
||||
"""构造行失败时不得留下半写规范行或 JSON。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task(lines=[{'sku': 'OLD', 'qty': 1}])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValueError, match='invalid qty'):
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{'sku': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.rollback()
|
||||
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
|
||||
def test_clear_and_shadow_read(app, caplog):
|
||||
"""清空走 store;shadow 模式对外仍读 JSON,并在不一致时打 warning。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task()
|
||||
replace_task_order_lines(task, [{'sku': 'A001', 'qty': 2}], normalize=False)
|
||||
db.session.commit()
|
||||
|
||||
clear_task_order_lines(task)
|
||||
db.session.commit()
|
||||
assert task.lines_json == []
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
# 人为制造影子差异:只改 JSON,不改表。
|
||||
task.lines_json = [{'sku': 'SHADOW', 'qty': 9}]
|
||||
task.order_lines_migration_status = 'pending'
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
|
||||
with caplog.at_level('WARNING'):
|
||||
lines = read_task_order_lines(task)
|
||||
assert lines == [{'sku': 'SHADOW', 'qty': 9}]
|
||||
assert any('shadow mismatch' in message for message in caplog.messages)
|
||||
|
||||
|
||||
def test_sync_from_json_backfill_idempotent_and_dry_run(app):
|
||||
"""历史回填 dry-run 不落库;apply 幂等且不 bump order_data_version。"""
|
||||
with app.app_context():
|
||||
task = _make_task(
|
||||
task_no='SN-LINE-BACKFILL-001',
|
||||
lines=[
|
||||
{
|
||||
'sku': 'B002',
|
||||
'qty': '3.50',
|
||||
'source_type': 'HUB',
|
||||
'legacy_flag': True,
|
||||
}
|
||||
],
|
||||
)
|
||||
db.session.commit()
|
||||
version_before = int(task.order_data_version)
|
||||
|
||||
dry = sync_task_order_lines_from_json(task, dry_run=True)
|
||||
assert dry['status'] == 'synced'
|
||||
assert dry['reason'] == 'dry_run'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
applied = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
db.session.commit()
|
||||
assert applied['status'] == 'synced'
|
||||
assert int(task.order_data_version) == version_before
|
||||
assert task.order_lines_migration_status == 'synced'
|
||||
row = ShippingTaskLine.query.filter_by(task_id=task.id).one()
|
||||
assert row.qty == Decimal('3.50')
|
||||
assert row.extra_json == {'legacy_flag': True}
|
||||
|
||||
again = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
assert again['status'] == 'skipped'
|
||||
assert again['reason'] == 'already_synced'
|
||||
|
||||
|
||||
def test_sync_rejects_invalid_historical_line(app):
|
||||
"""非法历史行应返回 failed,并保留原 JSON / 空规范表。"""
|
||||
with app.app_context():
|
||||
task = _make_task(
|
||||
task_no='SN-LINE-BAD-001',
|
||||
lines=[{'sku': 'Z', 'qty': -1}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
assert result['status'] == 'failed'
|
||||
assert 'invalid qty' in str(result.get('reason') or '')
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
assert task.lines_json == [{'sku': 'Z', 'qty': -1}]
|
||||
|
||||
|
||||
def test_backfill_script_page_and_resume(app):
|
||||
"""回填脚本支持 dry-run、apply、按 after_id 续跑,失败任务隔离。"""
|
||||
with app.app_context():
|
||||
good = _make_task(task_no='SN-BF-GOOD', lines=[{'sku': 'G1', 'qty': 1}])
|
||||
bad = _make_task(task_no='SN-BF-BAD', lines=[{'sku': 'B1', 'qty': 0}])
|
||||
db.session.commit()
|
||||
|
||||
dry_summary = backfill_shipping_task_lines(dry_run=True, after_id=0, limit=50)
|
||||
assert dry_summary['scanned'] >= 2
|
||||
assert ShippingTaskLine.query.count() == 0
|
||||
|
||||
apply_summary = backfill_shipping_task_lines(dry_run=False, after_id=0, limit=50)
|
||||
assert apply_summary['synced'] >= 1
|
||||
assert apply_summary['failed'] >= 1
|
||||
assert any(item['task_no'] == 'SN-BF-BAD' for item in apply_summary['failures'])
|
||||
|
||||
good = db.session.get(ShippingTask, good.id)
|
||||
bad = db.session.get(ShippingTask, bad.id)
|
||||
assert good.order_lines_migration_status == 'synced'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=good.id).count() == 1
|
||||
assert ShippingTaskLine.query.filter_by(task_id=bad.id).count() == 0
|
||||
|
||||
resume = backfill_shipping_task_lines(dry_run=False, after_id=int(good.id), limit=50)
|
||||
assert all(item['task_id'] > good.id for item in resume['results'])
|
||||
|
||||
|
||||
def test_json_write_mode_skips_table(app):
|
||||
"""write=json 时只更新快照,不写规范表。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'json'
|
||||
task = _make_task(task_no='SN-JSON-ONLY')
|
||||
replace_task_order_lines(task, [{'sku': 'J1', 'qty': 4}], normalize=False)
|
||||
db.session.commit()
|
||||
assert task.lines_json[0]['sku'] == 'J1'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
assert task.order_lines_migration_status == 'pending'
|
||||
|
||||
|
||||
def test_table_read_mode_returns_canonical_projection(app):
|
||||
"""read=table 时以规范表投影为准,忽略仅存在于 JSON 的漂移。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
|
||||
task = _make_task(task_no='SN-TABLE-READ')
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 人为制造 JSON 漂移:table 读路径不得返回漂移值。
|
||||
task.lines_json = [{'sku': 'DRIFT', 'qty': 99}]
|
||||
db.session.commit()
|
||||
|
||||
lines = read_task_order_lines(task)
|
||||
assert lines == [{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
|
||||
comparison = compare_task_order_line_projections(task)
|
||||
assert comparison['equal'] is False
|
||||
assert comparison['table_count'] == 1
|
||||
|
||||
|
||||
def test_lines_checksum_stable_for_key_order(app):
|
||||
"""checksum 对 dict key 顺序稳定,供影子对账。"""
|
||||
left = [{'qty': 1, 'sku': 'A'}]
|
||||
right = [{'sku': 'A', 'qty': 1}]
|
||||
assert lines_checksum(left) == lines_checksum(right)
|
||||
|
||||
|
||||
def test_lines_checksum_normalizes_id_and_qty_types(app):
|
||||
"""checksum 忽略 reservation_id int/str 与 qty 1/1.0 的类型差异。"""
|
||||
left = [{'sku': 'A', 'qty': 1, 'reservation_id': 3000092917, 'hub_code': 12}]
|
||||
right = [{'sku': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'hub_code': '12'}]
|
||||
assert lines_checksum(left) == lines_checksum(right)
|
||||
|
||||
|
||||
def test_shadow_read_tolerates_unsaved_task(app):
|
||||
"""未落库任务(id=None)在 shadow/table 读路径不得抛 TypeError。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
|
||||
task = ShippingTask(
|
||||
task_no='SN-UNSAVED',
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=[{'sku': 'A001', 'qty': 1}],
|
||||
)
|
||||
assert read_task_order_lines(task) == [{'sku': 'A001', 'qty': 1}]
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
|
||||
assert read_task_order_lines(task) == []
|
||||
|
||||
|
||||
def test_replace_rolls_back_when_commit_fails_after_dual_write(app):
|
||||
"""提交阶段失败时,两侧变更应随事务回滚(故障注入)。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task(task_no='SN-FAULT-001', lines=[{'sku': 'OLD', 'qty': 1}])
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
|
||||
replace_task_order_lines(task, [{'sku': 'NEW', 'qty': 2}], normalize=False)
|
||||
with patch.object(db.session, 'commit', side_effect=RuntimeError('boom')):
|
||||
with pytest.raises(RuntimeError, match='boom'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
task = db.session.get(ShippingTask, task_id)
|
||||
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task_id).count() == 0
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_lines_migration.py
|
||||
|
||||
用途:验证规范订单行与冲突表迁移可升级/降级,以及模型级唯一与 qty 约束。
|
||||
依赖:Alembic Operations、SQLAlchemy、ShippingTaskLine 模型。
|
||||
逻辑:在最小 shipping_tasks/users 历史上执行 d5e6f7a8b9c0;再在 Flask app 内断言 ORM 约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict, ShippingTaskLine
|
||||
|
||||
|
||||
def _task_lines_pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建订单行迁移所需的最小历史表(含 connector 改名后的 shipping_tasks)。"""
|
||||
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('task_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('process_status', sa.String(length=32), nullable=False),
|
||||
sa.Column('lines_json', sa.JSON(), nullable=True),
|
||||
sa.Column('inventory_connector_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_shipping_task_lines_migration_upgrade_and_downgrade():
|
||||
"""d5e6f7a8b9c0 应建立规范行/冲突表与任务版本字段,并能完整回滚且不改 lines_json。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_task_lines_pre_migration_schema(engine)
|
||||
module = importlib.import_module(
|
||||
'migrations.versions.d5e6f7a8b9c0_shipping_task_lines_and_conflicts'
|
||||
)
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
original_op = module.op
|
||||
module.op = operations
|
||||
try:
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"INSERT INTO shipping_tasks "
|
||||
"(id, task_no, source_type, process_status, lines_json, created_at, updated_at) "
|
||||
"VALUES (1, 'SN-LINE-MIG-001', 'manual', 'parsed', :lines_json, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
),
|
||||
{'lines_json': '[{"sku":"A001","qty":1}]'},
|
||||
)
|
||||
module.upgrade()
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
assert {'shipping_task_lines', 'shipping_task_field_conflicts'} <= set(inspector.get_table_names())
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
assert {'order_data_version', 'order_lines_migration_status', 'lines_json'} <= task_columns
|
||||
|
||||
row = connection.execute(sa.text(
|
||||
"SELECT order_data_version, order_lines_migration_status, lines_json "
|
||||
"FROM shipping_tasks WHERE id = 1"
|
||||
)).one()
|
||||
assert row[0] == 1
|
||||
assert row[1] == 'pending'
|
||||
assert 'A001' in str(row[2])
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, 0, 'A001', 0, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, reservation_id, source_type, hub_code, "
|
||||
"extra_json, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, 0, 'A001', 1.5, '1000140351', 'DBS DUB', 'DUB1', "
|
||||
"'{\"legacy_note\":\"kept\"}', 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (2, 1, 0, 'B001', 2, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_field_conflicts "
|
||||
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_field_conflicts "
|
||||
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
|
||||
"VALUES (2, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
module.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_task_lines' not in inspector.get_table_names()
|
||||
assert 'shipping_task_field_conflicts' not in inspector.get_table_names()
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
assert 'order_data_version' not in task_columns
|
||||
assert 'order_lines_migration_status' not in task_columns
|
||||
assert 'lines_json' in task_columns
|
||||
preserved = connection.execute(sa.text(
|
||||
"SELECT lines_json FROM shipping_tasks WHERE id = 1"
|
||||
)).scalar()
|
||||
assert 'A001' in str(preserved)
|
||||
finally:
|
||||
module.op = original_op
|
||||
|
||||
|
||||
def test_shipping_task_line_orm_constraints_and_cascade(app):
|
||||
"""ORM 层应强制 qty>0、(task_id,position) 唯一,并在删除 Task 时级联清理行与冲突。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no='SN-LINE-ORM-001',
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=[{'sku': 'A001', 'qty': 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
line = ShippingTaskLine(
|
||||
task_id=int(task.id),
|
||||
position=0,
|
||||
sku='A001',
|
||||
qty=Decimal('1'),
|
||||
reservation_id='1000140351',
|
||||
source_type='DBS DUB',
|
||||
hub_code='DUB1',
|
||||
extra_json={'legacy_note': 'kept'},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
conflict = ShippingTaskFieldConflict(
|
||||
task_id=int(task.id),
|
||||
line_id=int(line.id),
|
||||
position=0,
|
||||
field_name='reservation_id',
|
||||
existing_value='1000140351',
|
||||
incoming_value='3000092917',
|
||||
status='open',
|
||||
)
|
||||
db.session.add(conflict)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.add(ShippingTaskLine(
|
||||
task_id=int(task.id),
|
||||
position=0,
|
||||
sku='B001',
|
||||
qty=Decimal('2'),
|
||||
))
|
||||
db.session.flush()
|
||||
db.session.rollback()
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no='SN-LINE-ORM-001').one()
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
assert ShippingTaskLine.query.count() == 0
|
||||
assert ShippingTaskFieldConflict.query.count() == 0
|
||||
@@ -0,0 +1,228 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_parsed_projection.py
|
||||
|
||||
用途:验证 Task Detail / Candidate brief 对订单解析结果与门禁的持久只读投影。
|
||||
依赖:内存数据库、ShippingTask / ShippingNoticeCandidate、query_service、document_candidate_persist。
|
||||
逻辑:构造带 step_payload 与 source_candidate 的任务,断言 DETAIL 顶层字段与 Candidate brief 暴露证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingTask
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.query_service import serialize_task_detail
|
||||
|
||||
|
||||
def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
"""Task Detail 必须稳定顶层返回 lines 门禁与来源 Candidate 证据投影。"""
|
||||
with app.app_context():
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-PARSED-PROJECTION-001',
|
||||
intake_id=1,
|
||||
primary_document_id=1,
|
||||
candidate_key='parsed-projection-1',
|
||||
missing_fields_json=['hub_code'],
|
||||
field_confidence_json={'sku': 0.95, 'qty': 0.9},
|
||||
evidence_json=[{
|
||||
'field': 'lines[0].reservation_id',
|
||||
'line_index': 0,
|
||||
'reservation_id': '1000140351',
|
||||
'quote': '1000140351',
|
||||
'document_id': 1,
|
||||
}],
|
||||
conflicts_json=[],
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingTask(
|
||||
task_no='SN-PARSED-PROJECTION-001',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
po_number='4510038672',
|
||||
source_candidate_id=int(candidate.id),
|
||||
lines_json=[{
|
||||
'sku': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'source_type': 'DBS DUB',
|
||||
'hub_code': 'DUB1',
|
||||
}],
|
||||
step_payload_json={
|
||||
'parse_validation': {
|
||||
'status': 'ready',
|
||||
'issues': [],
|
||||
'contract_version': 'shipping-line-v1',
|
||||
},
|
||||
'process_field_gate': {
|
||||
'status': 'ready',
|
||||
'missing_fields': [],
|
||||
'issues': [],
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
detail = serialize_task_detail(task)
|
||||
assert detail['lines'][0]['reservation_id'] == '1000140351'
|
||||
assert detail['lines'][0]['hub_code'] == 'DUB1'
|
||||
assert detail['parse_validation']['status'] == 'ready'
|
||||
assert detail['process_field_gate']['status'] == 'ready'
|
||||
assert detail['source_candidate']['candidate_no'] == 'SNC-PARSED-PROJECTION-001'
|
||||
assert detail['source_candidate']['missing_fields'] == ['hub_code']
|
||||
assert detail['source_candidate']['evidence'][0]['reservation_id'] == '1000140351'
|
||||
|
||||
|
||||
def test_serialize_candidate_brief_exposes_evidence_and_missing_fields(app):
|
||||
"""Candidate brief 必须暴露已落库的 evidence / missing_fields / field_confidence。"""
|
||||
with app.app_context():
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-BRIEF-EVIDENCE-001',
|
||||
intake_id=1,
|
||||
primary_document_id=1,
|
||||
candidate_key='brief-evidence-1',
|
||||
missing_fields_json=['reservation_id'],
|
||||
field_confidence_json={'sku': 0.88},
|
||||
evidence_json=[{'field': 'lines[0].sku', 'quote': 'SKU-A', 'document_id': 1}],
|
||||
conflicts_json=[{'field': 'reservation_id', 'reason': 'source_conflict'}],
|
||||
structured_result_json={'business_summary': {'po_number': 'PO-1', 'lines': []}},
|
||||
)
|
||||
brief = _serialize_candidate_brief(candidate)
|
||||
assert brief['missing_fields'] == ['reservation_id']
|
||||
assert brief['field_confidence']['sku'] == 0.88
|
||||
assert brief['evidence'][0]['quote'] == 'SKU-A'
|
||||
assert brief['conflicts'][0]['reason'] == 'source_conflict'
|
||||
|
||||
|
||||
def test_normalize_notice_line_keeps_hub_code_independent_of_source_type():
|
||||
"""Hub Code 不得折叠进 source_type;两者应同时保留。"""
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_line
|
||||
|
||||
line = normalize_notice_line({
|
||||
'sku': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'source_type': 'DBS DUB',
|
||||
'hub_code': 'DUB1',
|
||||
'Hub Code': 'SHOULD_NOT_OVERRIDE_EXPLICIT',
|
||||
})
|
||||
assert line is not None
|
||||
assert line['source_type'] == 'DBS DUB'
|
||||
assert line['hub_code'] == 'DUB1'
|
||||
|
||||
summary = normalize_candidate_business_summary({
|
||||
'po_number': '4510038672',
|
||||
'lines': [{
|
||||
'sku': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'source_type': 'VMI-FRA01',
|
||||
'hub_code': 'FRA01',
|
||||
}],
|
||||
})
|
||||
assert summary['lines'][0]['source_type'] == 'VMI-FRA01'
|
||||
assert summary['lines'][0]['hub_code'] == 'FRA01'
|
||||
|
||||
|
||||
def test_candidate_update_persists_hub_code_round_trip(app):
|
||||
"""Candidate 人工修订保存后,hub_code 必须仍在 business_summary 中。"""
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, User
|
||||
from app.services.shipping_notice.candidate_service import update_candidate
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='hub-code-user', email='hub-code@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name='Shipping Notice',
|
||||
agent_code='shipping_notice_hub_code',
|
||||
dify_app_id='shipping-hub-code-test',
|
||||
dify_api_key='test-key',
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
session = ChatSession(
|
||||
session_id='sess-hub-code',
|
||||
user_id=int(user.id),
|
||||
agent_id=int(agent.id),
|
||||
title='Hub code',
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no='FA-HUB-CODE-001',
|
||||
owner_user_id=int(user.id),
|
||||
original_filename='order.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user.id}/hub-code.pdf',
|
||||
content_hash='hash-hub-code',
|
||||
file_size=12,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add_all([session, asset])
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SI-HUB-CODE-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',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=int(intake.id),
|
||||
asset_id=int(asset.id),
|
||||
document_type='attachment',
|
||||
attachment_key='order.pdf',
|
||||
filename='order.pdf',
|
||||
content_hash='hash-hub-code-doc',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='SKU P123456 qty 24',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-HUB-CODE-001',
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key='hub-code-1',
|
||||
validation_status='needs_review',
|
||||
selected=True,
|
||||
structured_result_json={
|
||||
'business_summary': {
|
||||
'po_number': '4510038672',
|
||||
'lines': [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
|
||||
updated = update_candidate(
|
||||
user_id=int(user.id),
|
||||
candidate_no='SNC-HUB-CODE-001',
|
||||
business_summary={
|
||||
'po_number': '4510038672',
|
||||
'lines': [{
|
||||
'sku': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'source_type': 'DBS DUB',
|
||||
'hub_code': 'DUB1',
|
||||
'uom': 'EA',
|
||||
}],
|
||||
},
|
||||
)
|
||||
line = updated['business_summary']['lines'][0]
|
||||
assert line['source_type'] == 'DBS DUB'
|
||||
assert line['hub_code'] == 'DUB1'
|
||||
db.session.refresh(candidate)
|
||||
persisted = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert persisted['hub_code'] == 'DUB1'
|
||||
assert persisted['source_type'] == 'DBS DUB'
|
||||
Reference in new issue
Block a user