test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。
|
||||
依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。
|
||||
逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_resolution_service import (
|
||||
confirm_customer_resolution,
|
||||
customer_resolution_facts,
|
||||
)
|
||||
|
||||
|
||||
def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]:
|
||||
"""构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。"""
|
||||
user = User(username='resolution-user', email='resolution@example.com', role='user')
|
||||
customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active')
|
||||
db.session.add_all([user, customer])
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='resolution-test', candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id)
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='shadow-v2',
|
||||
status=status,
|
||||
evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 'a' * 64}},
|
||||
identity_rule_set_checksum='a' * 64,
|
||||
top_customer_id=customer.id,
|
||||
top_score=100,
|
||||
)
|
||||
db.session.add_all([task, resolution])
|
||||
db.session.commit()
|
||||
return task, resolution, customer
|
||||
|
||||
|
||||
def test_non_bill_to_evidence_can_confirm_customer(app):
|
||||
"""关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。"""
|
||||
with app.app_context():
|
||||
task, resolution, customer = _task_with_resolution()
|
||||
|
||||
confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual')
|
||||
db.session.commit()
|
||||
facts = customer_resolution_facts(task)
|
||||
|
||||
assert facts['status'] == 'confirmed'
|
||||
assert facts['customer_id'] == customer.id
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
# 关键断言:确认不篡改规则证据及其 checksum。
|
||||
assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}]
|
||||
assert resolution.identity_rule_set_checksum == 'a' * 64
|
||||
|
||||
|
||||
def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app):
|
||||
"""关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。"""
|
||||
with app.app_context():
|
||||
task, _resolution, _customer = _task_with_resolution(status='unique_candidate')
|
||||
|
||||
facts = customer_resolution_facts(task)
|
||||
|
||||
assert facts['status'] == 'unique_candidate'
|
||||
assert facts['customer_id'] is None
|
||||
@@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
# 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。
|
||||
case = _fake_case(status='confirmed', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'_project_case_formal_gate_summary',
|
||||
|
||||
@@ -238,8 +238,10 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa
|
||||
phase='queued',
|
||||
schema_version_id=1,
|
||||
attempt_count=0,
|
||||
reparse_source=None,
|
||||
superseding_run=None,
|
||||
reparse_source=None,
|
||||
reparse_of_run_id=None,
|
||||
superseded_by_run_id=None,
|
||||
superseding_run=None,
|
||||
reparse_reason=None,
|
||||
superseded_at=None,
|
||||
result_json=None,
|
||||
|
||||
@@ -80,6 +80,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
|
||||
run_id=10,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
stream_id=100,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=1,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
|
||||
@@ -103,6 +104,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
|
||||
return_value={'status': 'queued', 'job_id': 1201,
|
||||
'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'},
|
||||
) as ensure_mock:
|
||||
RC_Mock.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=1)]
|
||||
RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=1),
|
||||
]
|
||||
@@ -136,6 +138,7 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app)
|
||||
run_id=20,
|
||||
run=SimpleNamespace(id=20, run_no='SNER-20'),
|
||||
owner_user_id=1,
|
||||
stream_id=200,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=3,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
|
||||
@@ -172,6 +175,7 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None,
|
||||
document_id=300, candidate_id=30, run_id=30,
|
||||
run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1,
|
||||
stream_id=300,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=2,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'},
|
||||
@@ -232,34 +236,26 @@ def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(a
|
||||
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
|
||||
candidate = SimpleNamespace(id=31)
|
||||
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
|
||||
extraction = SimpleNamespace(id=101)
|
||||
shadow_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
|
||||
)
|
||||
match_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
|
||||
)
|
||||
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
|
||||
coord,
|
||||
'ShippingCustomerShadowResolution',
|
||||
shadow_model,
|
||||
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
|
||||
coord,
|
||||
'_resolve_extraction_for_case',
|
||||
return_value=extraction,
|
||||
), patch.object(
|
||||
coord,
|
||||
'ShippingOrderCustomerMatch',
|
||||
match_model,
|
||||
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
|
||||
'confirm_customer_resolution',
|
||||
autospec=True,
|
||||
) as confirm_mock, patch.object(
|
||||
coord,
|
||||
'record_fulfillment_audit',
|
||||
):
|
||||
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
|
||||
|
||||
assert status == 'auto_confirmed'
|
||||
assert metadata == {'customer_id': 5555, 'extraction_id': 101}
|
||||
assert confirm_mock.call_args.kwargs['commit'] is False
|
||||
assert metadata == {'customer_id': 5555, 'extraction_id': None}
|
||||
assert confirm_mock.call_args.kwargs['method'] == 'auto_rule'
|
||||
|
||||
|
||||
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
|
||||
@@ -313,6 +309,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
run_id=42,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
stream_id=420,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=8,
|
||||
header_values_json={},
|
||||
@@ -331,6 +328,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'waiting_manual_validation'},
|
||||
):
|
||||
review_case.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=42)]
|
||||
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=42),
|
||||
]
|
||||
@@ -465,6 +463,26 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app):
|
||||
) is True
|
||||
|
||||
|
||||
def test_contract_06_legacy_unexpected_stp_failure_allows_general_retry(app):
|
||||
"""修复前落库的技术异常不能继续阻止普通 STP 重试。"""
|
||||
from app.services.shipping_notice import reconciliation_service as rs
|
||||
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-P1-06-TECH', status='ready', confirmed_task_id=None,
|
||||
document_id=601, run=SimpleNamespace(run_no='SNER-P1-06-TECH'),
|
||||
)
|
||||
with patch.object(rs, 'Job') as Job:
|
||||
Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace(
|
||||
id=61, status='failed',
|
||||
result_json={
|
||||
'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
},
|
||||
)
|
||||
rs.assert_case_not_blocked_manual(case_no='SORC-P1-06-TECH', case=case)
|
||||
|
||||
|
||||
def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
"""合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。"""
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
@@ -482,11 +500,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
) as sess_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches',
|
||||
) as refresh_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match',
|
||||
) as confirm_mock:
|
||||
):
|
||||
# Shadow = unique_candidate 但是 resolved=false。
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution',
|
||||
@@ -501,19 +515,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate',
|
||||
) as Cand, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch',
|
||||
) as CM, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction',
|
||||
) as EX:
|
||||
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
|
||||
CM.query.filter_by.return_value.first.return_value = None
|
||||
EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700)
|
||||
# 执行投影(纯读)
|
||||
out = project_review_case_customer_resolution(case)
|
||||
|
||||
# 7A:GET 路径不允许 confirm / validate / commit
|
||||
confirm_mock.assert_not_called()
|
||||
refresh_mock.assert_not_called()
|
||||
sess_mock.commit.assert_not_called()
|
||||
# 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认)
|
||||
assert out.get('resolved') is False
|
||||
|
||||
@@ -15,7 +15,7 @@ from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
@@ -28,9 +28,9 @@ from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_t
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask:
|
||||
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
|
||||
task = ShippingNotice(task_no='APX-P0-3-001')
|
||||
task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
@@ -101,7 +101,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=formal,
|
||||
through_gate_code='task_creation',
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
task.active_process_execution_id = formal.id
|
||||
@@ -148,6 +148,65 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
|
||||
|
||||
|
||||
def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
"""[断言] Worker 真实执行失败(failed + job_id 非空)的门禁:auto_progress 不得自动重试,
|
||||
必须等待用户在当前 Gate 显式恢复;首次投递通道(无失败 Attempt)不受影响(由
|
||||
test_formal_execution_queues_one_gate_attempt_job 锁定)。"""
|
||||
import uuid as _uuid
|
||||
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
# Worker 已真实执行并失败:failed Attempt 持有非空 job_id
|
||||
failed_job = Job(
|
||||
domain='shipping_notice', job_type='shipping_process_gate',
|
||||
status='failed', business_ref='apx-p03-failed-gate-job',
|
||||
)
|
||||
db.session.add(failed_job)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGateAttempt(
|
||||
gate_id=int(gate.id),
|
||||
attempt_no=1,
|
||||
status='failed',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-poll',
|
||||
idempotency_key=f'test-failed-worker-attempt:{_uuid.uuid4().hex}',
|
||||
job_id=int(failed_job.id),
|
||||
))
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'retry_inventory_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
# 同步事实是本用例之外的职责;固定复现“同步后仍为可重试阻断”的当前 Gate。
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
):
|
||||
result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
# 没有新的 ProcessGate Job 被创建(仅存量失败 Job)
|
||||
assert Job.query.filter(
|
||||
Job.job_type == 'shipping_process_gate',
|
||||
Job.id != int(failed_job.id),
|
||||
).count() == 0
|
||||
# Attempt 数量不变:只有种子失败行,未被自动重派
|
||||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -183,3 +242,90 @@ def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
assert result['retry_of_job_id'] is None
|
||||
|
||||
|
||||
def test_derived_fulfillment_status_uses_line_match_facts_for_order_task():
|
||||
"""OT 履约状态必须从行级 Match 事实推导,不再读取已删除的 Notice JSON 投影。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_bridge import _derived_fulfillment_status
|
||||
|
||||
task = SimpleNamespace(id=1)
|
||||
with patch(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
return_value=True,
|
||||
), patch(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.ShippingOrderTask',
|
||||
SimpleNamespace,
|
||||
):
|
||||
assert _derived_fulfillment_status(task) == 'matched'
|
||||
|
||||
|
||||
def test_auto_retry_blocked_only_for_non_user_trigger():
|
||||
"""Bug 修复:[禁止自动重试] 仅拦非用户显式触发 / 无定向 gate 的自动推进。
|
||||
|
||||
核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试,
|
||||
用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进
|
||||
(如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching')
|
||||
应绕过,否则点"重新匹配库存"报"无待处理 Gate"。
|
||||
"""
|
||||
from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked
|
||||
|
||||
assert _auto_retry_blocked('auto', True) is True
|
||||
assert _auto_retry_blocked('system_requeue', True) is True
|
||||
assert _auto_retry_blocked('worker_takeover', True) is True
|
||||
assert _auto_retry_blocked('user_retry', True) is False
|
||||
assert _auto_retry_blocked('user_manual', True) is False
|
||||
assert _auto_retry_blocked('user_retry', False) is False
|
||||
assert _auto_retry_blocked('auto', False) is False
|
||||
# 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False
|
||||
assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False
|
||||
|
||||
|
||||
def test_retry_inventory_matching_fulfillable_passes():
|
||||
"""Bug 修复:已可履约订单的"重新匹配库存"应通过,不把 match_inventory 内部的
|
||||
run_task_auto_progress "无待处理 Gate"(status='completed')误判为失败。
|
||||
|
||||
核心逻辑:_handle_retry_inventory_matching 只在 needs_human+shortage 时 return passed;
|
||||
对 match_status='fulfillable' + response.status='completed' 会落 _tool_outcome 判为
|
||||
blocked_retryable,把"无待处理 Gate"记作 error_summary。修复:fulfillable 直接 passed。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_executor as ex
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
class _Task:
|
||||
id = 1
|
||||
task_no = 'OT-X'
|
||||
order_snapshot_id = 1
|
||||
|
||||
class _Execution:
|
||||
task_id = 1
|
||||
|
||||
class _Gate:
|
||||
gate_code = 'inventory_matching'
|
||||
|
||||
class _OT:
|
||||
query = MagicMock(get=MagicMock(return_value=_Task()))
|
||||
|
||||
with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={
|
||||
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None,
|
||||
}), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \
|
||||
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \
|
||||
patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}):
|
||||
result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1})
|
||||
assert result['outcome'] == 'passed'
|
||||
|
||||
|
||||
@@ -128,6 +128,9 @@ def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monke
|
||||
conflicts_json=[{
|
||||
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
# 派生/已解决字段的历史 evidence_missing 由写路径 _discard_resolved_worker_field_conflicts
|
||||
# 在投影到 Candidate 前丢弃;资格 Gate 只按冻结字段配置判断证据缺失是否可选。
|
||||
'field_config': {'required': False, 'auto_create_key_field': False},
|
||||
}],
|
||||
structured_result_json={
|
||||
'customer': {'resolution_status': 'user_confirmed'},
|
||||
|
||||
@@ -23,7 +23,6 @@ def test_legacy_fulfillment_chat_actions_are_not_registered():
|
||||
"shipping.retry_upload",
|
||||
"shipping.match_inventory",
|
||||
"shipping.confirm_inventory_source",
|
||||
"shipping.submit_decision",
|
||||
"shipping.mark_manual_uploaded",
|
||||
}.isdisjoint(action_types)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import Agent, ChatSession, ShippingNotice, User
|
||||
from app.models import Agent, ChatSession, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability
|
||||
|
||||
|
||||
@@ -18,10 +18,10 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app):
|
||||
agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True)
|
||||
db.session.add_all([user, agent]); db.session.flush()
|
||||
session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id)
|
||||
own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test')
|
||||
other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test')
|
||||
own = ShippingOrderTask(task_no='SN-CAP-OWN', user_id=user.id, source_type=None)
|
||||
other = ShippingOrderTask(task_no='SN-CAP-OTHER', user_id=user.id, source_type=None)
|
||||
db.session.add_all([session, own, other]); db.session.commit()
|
||||
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None)
|
||||
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no)
|
||||
assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id
|
||||
with pytest.raises(ForbiddenError):
|
||||
require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no)
|
||||
|
||||
@@ -186,7 +186,7 @@ def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(),
|
||||
row_reconstruction_mode='adaptive_record_columns',
|
||||
)
|
||||
# Both layouts must yield a complete logical record despite their different visual-band counts.
|
||||
# 两种视觉排版均可从明确的 ``@ + 纯数字`` 预约号段还原完整逻辑明细。
|
||||
assert compact[0].fields == {
|
||||
'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS',
|
||||
'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48',
|
||||
@@ -870,6 +870,22 @@ def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign(
|
||||
assert rows[0].fields['reservation_id'] == '3000097059'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_accept_reservation_with_text_suffix_truncated():
|
||||
"""预约号框内含文本后缀时可截断为纯数字写入(生产行为)。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)],
|
||||
[('898.72', 80), ('898.72', 165)], [('3000097059(PENROSE)', 115)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
|
||||
line_layouts=_adaptive_layouts(),
|
||||
row_reconstruction_mode='adaptive_record_columns',
|
||||
)
|
||||
|
||||
# 允许将带文本后缀的预约号截断为纯数字(生产已实现)。
|
||||
assert rows[0].fields['reservation_id'] == '3000097059'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
|
||||
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
@@ -974,6 +990,70 @@ def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor():
|
||||
}]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_clamps_a_shifted_wide_field_frame_to_the_page_top():
|
||||
"""锚点上移把宽字段框推过页顶时,截断框仍须读取页面内的有效字符。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('1', 10), ('PART-A', 60)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .25, 'y1': .80}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '1', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_honors_deleted_marker_exclusion_authorization():
|
||||
"""dynamic 模式绕过普通排除过滤时,仍须使用配置排除区授权删除标记。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
|
||||
],
|
||||
}],
|
||||
exclusion_regions=[{'x0': .3, 'y0': .3, 'x1': .8, 'y1': .5}],
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields['customer_po_line_no'] for row in rows] == ['00020']
|
||||
|
||||
|
||||
def test_dynamic_x_columns_ignores_unconfigured_deleted_marker():
|
||||
"""dynamic 模式没有删除标记排除授权时,不得擅自删除上一条明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
|
||||
],
|
||||
}],
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields['customer_po_line_no'] for row in rows] == ['00010', '00020']
|
||||
|
||||
|
||||
def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor():
|
||||
"""固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
@@ -1145,6 +1225,114 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b
|
||||
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_keep_main_row_fields_and_skip_description_wrap_for_part_number():
|
||||
"""主视觉行同时含日期金额时,描述折行不得占用内部料号视觉位置。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130), ('08/28/2026', 260),
|
||||
('941.76', 320), ('37670.40', 365)],
|
||||
[('BUSBAR', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
[('Revision:A0', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
{'field_code': 'requested_receipt_date', 'region': {'x0': .65, 'y0': .2, 'x1': .78, 'y1': .3}},
|
||||
{'field_code': 'unit_price', 'region': {'x0': .79, 'y0': .2, 'x1': .88, 'y1': .3}},
|
||||
{'field_code': 'line_amount_with_tax', 'region': {'x0': .88, 'y0': .2, 'x1': 1, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]}],
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'requested_receipt_date', 'scope': 'line', 'value_type': 'date'},
|
||||
{'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
|
||||
{'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal'},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields == {
|
||||
'customer_po_line_no': '10', 'qty': '40', 'customer_part_number': 'RK-00410-001B',
|
||||
'requested_receipt_date': '08/28/2026', 'unit_price': '941.76',
|
||||
'line_amount_with_tax': '37670.40', 'part_number': 'D4-A08AR12000002',
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row_reconstruction_mode', [
|
||||
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
|
||||
])
|
||||
def test_two_subrow_layout_rescans_description_wrap_before_part_number(row_reconstruction_mode):
|
||||
"""真实 ZT 两子行布局中,描述折行不能占用内部料号的固定续行。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
|
||||
[('BUSBAR', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
]},
|
||||
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]},
|
||||
],
|
||||
row_reconstruction_mode=row_reconstruction_mode,
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row_reconstruction_mode', [
|
||||
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
|
||||
])
|
||||
def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(row_reconstruction_mode):
|
||||
"""真实 ZT 两子行布局中,含数字和标点的描述折行也不能占用内部料号续行。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
|
||||
[('48U AR1.2', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
]},
|
||||
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]},
|
||||
],
|
||||
row_reconstruction_mode=row_reconstruction_mode,
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
|
||||
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_auto_resolution.py
|
||||
|
||||
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
@@ -11,7 +11,6 @@ from copy import deepcopy
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCustomer,
|
||||
@@ -28,19 +27,17 @@ from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_RESOLUTION_VERSION,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
resolve_auto_customer_from_shadow,
|
||||
try_auto_confirm_task_customer,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
|
||||
@@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment",
|
||||
customer_resolution_status="pending",
|
||||
task = ShippingOrderTask(
|
||||
task_no=f"OT-AUTO-{user.id}", user_id=user.id,
|
||||
candidate_id=candidate.id, source_type="eml",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None:
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
|
||||
def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None:
|
||||
"""断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。"""
|
||||
assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app):
|
||||
"""开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
@@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
|
||||
assert result["status"] == "auto_confirmed"
|
||||
assert result["rule_version"] == AUTO_RESOLUTION_VERSION
|
||||
assert task.customer_resolution_status == "confirmed"
|
||||
assert task.customer_resolution_method == "auto_rule"
|
||||
assert task.customer_id == customer.id
|
||||
assert task.business_no.startswith("WYC")
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
|
||||
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
|
||||
assert event.detail_json['rule_set']['checksum']
|
||||
assert event.detail_json['evidence'][0]['definition_id']
|
||||
assert event.detail_json['evidence'][0]['evidence_id']
|
||||
source = event.detail_json['evidence'][0]['source']
|
||||
assert source['field_value_id'] and source['decision_id'] and source['extraction_id']
|
||||
assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id']
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert shadow.status == "confirmed"
|
||||
assert shadow.confirmation_method == "auto_rule"
|
||||
assert shadow.confirmed_customer_id == customer.id
|
||||
assert shadow.evidence_json[0]['definition_id']
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert result['business_no'] is None
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
assert metrics["auto_confirmed_count"] == 1
|
||||
assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed"
|
||||
assert metrics["recent_events"][0]["task_no"] == task.task_no
|
||||
|
||||
|
||||
def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
@@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
|
||||
disabled = try_auto_confirm_task_customer(task)
|
||||
assert disabled["status"] == "disabled"
|
||||
assert task.business_no is None
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
_allow_auto_confirmation(app)
|
||||
unmatched = try_auto_confirm_task_customer(task)
|
||||
assert unmatched["status"] == "unmatched"
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
@@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
assert result["status"] == "ambiguous"
|
||||
assert len(result["candidate_customer_ids"]) == 2
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
@@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
|
||||
persisted_task = db.session.get(ShippingNotice, task_id)
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
assert persisted_task.customer_id is None
|
||||
assert persisted_task.business_no is None
|
||||
persisted_task = db.session.get(ShippingOrderTask, task_id)
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
|
||||
|
||||
|
||||
@@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
|
||||
assert result["status"] == "insufficient_labeled_samples"
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
@@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
status='approved', auto_match_allowed=True,
|
||||
))
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
original_source = shadow.evidence_json[0]['source']
|
||||
field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id'])
|
||||
decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id'])
|
||||
@@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
|
||||
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
@@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
task = _seed_candidate_task(sender='buyer@gmail.com')
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.resolution_context_json = {}
|
||||
db.session.commit()
|
||||
missing = resolve_auto_customer_from_shadow(task)
|
||||
@@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app):
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code='WYC', value='buyer@wyc.example.com')
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['normalized_value'] = 'attacker@example.com'
|
||||
shadow.evidence_json = evidence
|
||||
db.session.commit()
|
||||
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
shadow.evidence_json = []
|
||||
context = deepcopy(shadow.resolution_context_json)
|
||||
@@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
db.session.add(truth)
|
||||
db.session.flush()
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.manual_customer_id = truth.id
|
||||
db.session.commit()
|
||||
|
||||
@@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
assert result["status"] == "insufficient_accuracy"
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 1
|
||||
assert result["quality_gate"]["accuracy"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
|
||||
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
|
||||
def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None:
|
||||
"""把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。"""
|
||||
shadow.order_schema_version_id = new_version.id
|
||||
# JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['source']['order_schema_version_id'] = new_version.id
|
||||
shadow.evidence_json = evidence
|
||||
extraction = db.session.get(
|
||||
ShippingOrderExtraction, evidence[0]['source']['extraction_id'],
|
||||
)
|
||||
extraction.schema_version_id = new_version.id
|
||||
|
||||
|
||||
def test_schema_republish_with_same_semantics_still_auto_confirms(app):
|
||||
"""Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
|
||||
db.session.add_all([wrong, correct])
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
}]},
|
||||
checksum='f' * 64,
|
||||
)
|
||||
db.session.add(new_version)
|
||||
db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V1", document_version=1,
|
||||
source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV",
|
||||
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
|
||||
match_status="fulfillable", line_results_json=[{"sku": "A"}],
|
||||
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
|
||||
)
|
||||
db.session.add(first)
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
db.session.commit()
|
||||
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = first.business_no
|
||||
|
||||
result = correct_numbered_task_customer(
|
||||
first,
|
||||
customer_id=correct.id,
|
||||
reason="自动识别客户错误",
|
||||
actor_id=None,
|
||||
)
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
replacement = db.session.get(ShippingNotice, result["new_notice_id"])
|
||||
assert first.business_no == old_business_no
|
||||
assert first.lifecycle_status == "voided"
|
||||
assert replacement.supersedes_task_id == first.id
|
||||
assert replacement.business_no.startswith("NEW")
|
||||
assert replacement.business_no != old_business_no
|
||||
assert replacement.customer_resolution_method == "admin_correction"
|
||||
assert replacement.inventory_source_status is None
|
||||
assert replacement.inventory_lines_json is None
|
||||
assert replacement.export_file_path is None
|
||||
assert replacement.source_type == "manual"
|
||||
assert get_task_by_ref(old_business_no).id == first.id
|
||||
assert get_task_by_ref(replacement.business_no).id == replacement.id
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["corrected_task_count"] == 2
|
||||
assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no
|
||||
assert result['status'] == 'unique_strong_match'
|
||||
assert result['customer_id'] is not None
|
||||
|
||||
|
||||
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app):
|
||||
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。"""
|
||||
def test_schema_republish_changes_semantics_never_auto_confirms(app):
|
||||
"""Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CORRECTION-BLOCK",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True,
|
||||
'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。
|
||||
}]},
|
||||
checksum='e' * 64,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.add(new_version)
|
||||
db.session.flush()
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
db.session.commit()
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None)
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
|
||||
db.session.rollback()
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
task.upload_status = "uploaded"
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
|
||||
db.session.rollback()
|
||||
assert db.session.query(ShippingNotice).count() == 1
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert result['customer_id'] is None
|
||||
@@ -1,146 +1,147 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_identity_gate.py
|
||||
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
|
||||
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
|
||||
逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。
|
||||
依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。
|
||||
逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断;
|
||||
确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
confirm_task_customer,
|
||||
customer_identity_is_confirmed,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
_validate_rpa_callback_gate,
|
||||
ensure_inventory_via_rpa,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.task_workflow import retry_task
|
||||
|
||||
|
||||
def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
|
||||
"""创建待确认任务、启用客户和任务用户。"""
|
||||
def _seed_task(*, confirmed: bool = False) -> tuple[ShippingOrderTask, ShippingNotice, ShippingCustomer, User]:
|
||||
"""创建待确认订单任务(OT)、关联 Notice、启用客户、候选与影子识别结果。"""
|
||||
sequence = db.session.query(User).count()
|
||||
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
|
||||
short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}'
|
||||
customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active')
|
||||
db.session.add_all([user, customer])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f'SN-GATE-{user.id}', user_id=user.id,
|
||||
customer_resolution_status='pending' if customer_pending else None,
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-GATE-{user.id}', asset_id=user.id, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-GATE-{user.id}', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key=f'gate-{user.id}', candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=f'OT-GATE-{user.id}', user_id=user.id, status='ready',
|
||||
current_step='customer_review', candidate_id=candidate.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
# OT 的客户确认事实由 ShippingCustomerShadowResolution 承载(不再落 Notice/OT 列)。
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='test.v1',
|
||||
status='confirmed' if confirmed else 'unique_candidate',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
|
||||
identity_rule_set_checksum='t' * 64,
|
||||
)
|
||||
if confirmed:
|
||||
resolution.confirmed_customer_id = customer.id
|
||||
resolution.confirmation_method = 'manual'
|
||||
db.session.add(resolution)
|
||||
|
||||
notice = ShippingNotice(task_no=f'SN-GATE-{user.id}', user_id=user.id, source_type='manual', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
return task, customer, user
|
||||
|
||||
|
||||
def _assert_customer_gate_response(result: dict) -> None:
|
||||
"""断言 Tool 入口返回统一客户检查点。"""
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['checkpoint'] == 'customer_review'
|
||||
assert 'human_options' not in result
|
||||
return task, notice, customer, user
|
||||
|
||||
|
||||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
"""未确认客户时所有库存与履约公共入口都必须在副作用前停止。"""
|
||||
"""未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。"""
|
||||
with app.app_context():
|
||||
task, _customer, _user = _seed_task()
|
||||
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
|
||||
|
||||
results = [
|
||||
auto_progress({'task_id': task.task_no}),
|
||||
ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}),
|
||||
upload_inventory_file(
|
||||
task.task_no,
|
||||
FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'),
|
||||
),
|
||||
ensure_inventory_via_rpa(task, mode='auto'),
|
||||
match_inventory({'task_id': task.task_no}),
|
||||
generate_excel({'task_id': task.task_no}),
|
||||
task, _notice, _customer, _user = _seed_task()
|
||||
operations = [
|
||||
'auto_progress',
|
||||
'ensure_inventory',
|
||||
'upload_inventory_file',
|
||||
'ensure_inventory_via_rpa',
|
||||
'match_inventory',
|
||||
'generate_excel',
|
||||
'upload_to_freight',
|
||||
]
|
||||
for result in results:
|
||||
_assert_customer_gate_response(result)
|
||||
|
||||
# upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。
|
||||
upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})
|
||||
_assert_customer_gate_response(upload)
|
||||
|
||||
callback = _validate_rpa_callback_gate(task)
|
||||
assert callback is not None
|
||||
assert callback['status'] == 'failed'
|
||||
for operation in operations:
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
assert_customer_identity_gate(task, operation=operation)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
db.session.refresh(task)
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.upload_status is None
|
||||
assert customer_identity_is_confirmed(task) is False
|
||||
|
||||
|
||||
def test_pending_customer_blocks_retry_before_clearing_review_state(app):
|
||||
"""重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。"""
|
||||
with app.app_context():
|
||||
task, _customer, _user = _seed_task()
|
||||
task, _notice, _customer, _user = _seed_task()
|
||||
task.pending_human_reason = 'customer_unconfirmed'
|
||||
task.error_message = '标准客户尚未确认'
|
||||
db.session.commit()
|
||||
|
||||
result = retry_task({'task_id': task.task_no})
|
||||
|
||||
_assert_customer_gate_response(result)
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
assert_customer_identity_gate(task, operation='retry_task')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
db.session.refresh(task)
|
||||
assert task.pending_human_reason == 'customer_unconfirmed'
|
||||
assert task.error_message == '标准客户尚未确认'
|
||||
|
||||
|
||||
def test_confirm_customer_does_not_assign_notice_number_before_excel(app):
|
||||
"""客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。"""
|
||||
"""客户确认只固化客户事实;正式单号只能由首个 Excel 生成时分配。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
revision = ShippingNotice(
|
||||
task_no='SN-GATE-REV', user_id=user.id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
|
||||
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
db.session.refresh(revision)
|
||||
assert updated.customer_resolution_status == 'confirmed'
|
||||
assert revision.customer_resolution_status == 'pending'
|
||||
assert updated.customer_resolution_method == 'manual'
|
||||
assert updated.customer_id == customer.id
|
||||
assert updated.customer_name_snapshot == customer.standard_name
|
||||
assert updated.customer_short_code_snapshot == customer.short_code
|
||||
assert updated.business_no is None
|
||||
assert updated.business_date is None
|
||||
assert updated.business_sequence_value is None
|
||||
db.session.refresh(updated)
|
||||
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.status == 'confirmed'
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
assert resolution.confirmation_method == 'manual'
|
||||
assert customer_identity_is_confirmed(updated) is True
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0
|
||||
# OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。
|
||||
assert getattr(updated, 'business_no', None) is None
|
||||
|
||||
|
||||
def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch):
|
||||
"""PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。"""
|
||||
def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch):
|
||||
"""PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
original_query = db.session.query
|
||||
lock_arguments: list[dict] = []
|
||||
|
||||
class NoticeQuerySpy:
|
||||
class OrderTaskQuerySpy:
|
||||
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
|
||||
|
||||
def __init__(self, query):
|
||||
@@ -160,21 +161,21 @@ def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app,
|
||||
|
||||
def traced_query(*entities, **kwargs):
|
||||
query = original_query(*entities, **kwargs)
|
||||
if len(entities) == 1 and entities[0] is ShippingNotice:
|
||||
return NoticeQuerySpy(query)
|
||||
if len(entities) == 1 and entities[0] is ShippingOrderTask:
|
||||
return OrderTaskQuerySpy(query)
|
||||
return query
|
||||
|
||||
monkeypatch.setattr(db.session, 'query', traced_query)
|
||||
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
|
||||
assert lock_arguments == [{'of': ShippingNotice}]
|
||||
assert lock_arguments == [{'of': ShippingOrderTask}]
|
||||
|
||||
|
||||
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
customer.status = 'inactive'
|
||||
db.session.commit()
|
||||
@@ -182,7 +183,7 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
assert_customer_identity_gate(task, operation='match_inventory')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False)
|
||||
unconfirmed, _unconfirmed_notice, _other_customer, _other_user = _seed_task()
|
||||
with pytest.raises(AppError) as unconfirmed_error:
|
||||
assert_customer_identity_gate(unconfirmed, operation='match_inventory')
|
||||
assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
@@ -190,10 +191,10 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
|
||||
|
||||
def test_workspace_customer_search_and_confirmation_api(app, client):
|
||||
"""业务用户只能确认自己的任务,确认响应返回正式业务编号。"""
|
||||
"""业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, notice, customer, user = _seed_task()
|
||||
other_user = User(username='gate-other-user', email='gate-other@example.com', role='user')
|
||||
db.session.add(other_user)
|
||||
db.session.commit()
|
||||
@@ -218,9 +219,14 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
|
||||
envelope = confirm_response.get_json()
|
||||
assert envelope['success'] is True
|
||||
payload = envelope['data']
|
||||
assert payload['customer_resolution_status'] == 'confirmed'
|
||||
assert payload['customer_id'] == customer_id
|
||||
assert payload['business_no'].startswith(short_code)
|
||||
# 新契约:确认只固化客户事实,业务编号仍由 Excel 阶段分配。
|
||||
assert payload.get('business_no') is None
|
||||
|
||||
with app.app_context():
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.status == 'confirmed'
|
||||
assert resolution.confirmed_customer_id == customer_id
|
||||
|
||||
other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'}
|
||||
forbidden_response = client.post(
|
||||
|
||||
@@ -294,3 +294,36 @@ def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||||
report = get_shadow_quality_report()
|
||||
assert labeled['is_correct'] is True
|
||||
assert report['labeled_count'] == 1 and report['accuracy'] == 1.0
|
||||
|
||||
|
||||
def test_field_code_resolution_preferred_over_drifted_snapshot_uuid(app):
|
||||
"""字段绑定以 field_code 语义键为主:快照 UUID 漂移到新字段时仍按同 code 命中。"""
|
||||
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
|
||||
|
||||
with app.app_context():
|
||||
field, version = _published_field(code='bill_to_customer')
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
definition = {
|
||||
'context_field_id': 'obsolete-uuid-no-longer-present', # 快照 UUID 已漂移,不在当前解析结果中。
|
||||
'field_config': {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'},
|
||||
}
|
||||
header_values = {str(field.id): {'value': 'buyer@example.com'}}
|
||||
assert _resolved_context_field_id(definition, extraction, header_values) == field.id
|
||||
|
||||
|
||||
def test_field_code_resolution_falls_back_to_snapshot_uuid_for_legacy_snapshot(app):
|
||||
"""旧快照缺少 field_config.field_code 时,仍按快照 UUID 直配命中,保持向后兼容。"""
|
||||
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
|
||||
|
||||
with app.app_context():
|
||||
field, _version = _published_field(code='bill_to_customer')
|
||||
definition = {
|
||||
'context_field_id': field.id,
|
||||
'field_config': {}, # 旧快照无 field_code,只能回退到 UUID 直配。
|
||||
}
|
||||
header_values = {str(field.id): {'value': 'buyer@example.com'}}
|
||||
assert _resolved_context_field_id(definition, None, header_values) == field.id
|
||||
@@ -229,7 +229,11 @@ def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it():
|
||||
|
||||
|
||||
def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。"""
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。
|
||||
|
||||
aws_part_number 不属于订单 Schema 的表格明细字段(见 test_shipping_order_schema.py
|
||||
的标准资产断言),因此 AWS SKU 列必须保持未映射,不能形成内部/AWS 料号字段候选。
|
||||
"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>',
|
||||
@@ -239,10 +243,10 @@ def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == ['mapped', 'mapped', 'unmapped', 'mapped']
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1',
|
||||
'aws_part_number': 'AWS-1',
|
||||
'qty': 2,
|
||||
}
|
||||
|
||||
@@ -280,11 +284,15 @@ def test_customer_material_without_internal_part_is_not_build_complete():
|
||||
|
||||
|
||||
def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed():
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。"""
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。
|
||||
|
||||
line_no 已由系统按单据顺序生成(见 order_schema.field_rules),不再参与表格明细映射;
|
||||
改用仍属于表格明细字段的 customer_po_line_no 验证同一污染防护规则。
|
||||
"""
|
||||
result = _map(
|
||||
'<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('line_no', ['Item No']),
|
||||
_field('customer_po_line_no', ['Item No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
@@ -21,8 +21,11 @@ from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
|
||||
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
COORDINATE_EVIDENCE_REF_KEY,
|
||||
schedule_layout_version,
|
||||
)
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot
|
||||
|
||||
|
||||
def _assert_layout_job_diagnostics_contract(result: dict) -> None:
|
||||
@@ -69,7 +72,10 @@ def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
|
||||
return_value=_snapshot(marker='worker'),
|
||||
return_value={
|
||||
**_snapshot(marker='worker'),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
},
|
||||
):
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
@@ -87,13 +93,16 @@ def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
assert job.result_json['status'] == 'ready'
|
||||
assert job.result_json['provider_status'] == 'ready'
|
||||
assert job.message == '文档版面解析完成'
|
||||
# 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
_assert_layout_job_diagnostics_contract(job.result_json)
|
||||
assert 'timings' not in version.payload_json
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
|
||||
"""表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。"""
|
||||
"""表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
document, version, job = _running_layout_job(app)
|
||||
@@ -132,13 +141,14 @@ def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
|
||||
assert job.message == '文档版面解析完成'
|
||||
assert version.payload_json['tables'] == snapshot['tables']
|
||||
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in version.payload_json['coordinate_evidence']
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
|
||||
|
||||
|
||||
def test_layout_job_failure_requeues_version_and_clears_lease(app):
|
||||
"""可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。"""
|
||||
def test_layout_job_failure_fails_version_and_clears_lease(app):
|
||||
"""不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。"""
|
||||
with app.app_context():
|
||||
_document_row, version, job = _running_layout_job(app)
|
||||
with patch(
|
||||
@@ -153,8 +163,9 @@ def test_layout_job_failure_requeues_version_and_clears_lease(app):
|
||||
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(job)
|
||||
assert job.status == 'queued'
|
||||
assert version.status == 'queued'
|
||||
# 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。
|
||||
assert job.status == 'failed'
|
||||
assert version.status == 'failed'
|
||||
assert version.lease_token is None
|
||||
assert job.error_message == LAYOUT_JOB_ERROR
|
||||
|
||||
@@ -207,7 +218,7 @@ def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
|
||||
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'page_glyphs': {'1': [{'text': 'x'}]},
|
||||
},
|
||||
'issues': [],
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
COORDINATE_EVIDENCE_REF_KEY,
|
||||
canonical_layout_payload,
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
@@ -76,6 +77,19 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _externalizable_evidence() -> dict:
|
||||
"""构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。
|
||||
|
||||
生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被
|
||||
``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除,
|
||||
改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。
|
||||
"""
|
||||
return {
|
||||
'pages': {'1': {'width': 100, 'height': 200}},
|
||||
'page_glyphs': {'1': [{'text': 'x'}]},
|
||||
}
|
||||
|
||||
|
||||
def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
"""相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。"""
|
||||
with app.app_context():
|
||||
@@ -207,7 +221,12 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
ready = record_inline_layout_snapshot(document, _snapshot())
|
||||
# PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。
|
||||
ready = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json
|
||||
reused = schedule_layout_version(document)
|
||||
forced = schedule_layout_version(document, force=True)
|
||||
db.session.commit()
|
||||
@@ -227,7 +246,10 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
ready = record_inline_layout_snapshot(original, _snapshot())
|
||||
ready = record_inline_layout_snapshot(original, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
@@ -256,12 +278,15 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
|
||||
|
||||
|
||||
def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
"""ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。"""
|
||||
"""ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
# 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref),
|
||||
# 缺页坐标由正式识别按需从原 PDF 恢复。
|
||||
incomplete = record_inline_layout_snapshot(original, {
|
||||
**_snapshot(), 'coordinate_evidence': {'tables': {}},
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id,
|
||||
@@ -325,8 +350,9 @@ def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkey
|
||||
'backend': 'pipeline',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}},
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset);
|
||||
# datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}},
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
@@ -483,7 +509,7 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
|
||||
|
||||
|
||||
def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app):
|
||||
"""PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。"""
|
||||
"""PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
@@ -521,23 +547,27 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
|
||||
assert document.current_layout_version_id == pending.id
|
||||
assert pending.payload_json['tables'] == snapshot['tables']
|
||||
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in pending.payload_json['coordinate_evidence']
|
||||
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
|
||||
assert pending.payload_json['matching_features']['version'] == 'v1'
|
||||
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2]
|
||||
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。
|
||||
assert 'coordinate_evidence' not in pending.payload_json
|
||||
ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY]
|
||||
assert ref['asset_no']
|
||||
assert ref['checksum']
|
||||
assert ref['size'] > 0
|
||||
assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1'
|
||||
# 模板结构保留,无需把外置证据当作容量压缩问题。
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json
|
||||
assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json
|
||||
|
||||
|
||||
def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app):
|
||||
"""普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。"""
|
||||
def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app):
|
||||
"""普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
snapshot = {
|
||||
**_snapshot(marker='inline-compacted'),
|
||||
**_snapshot(marker='inline-externalized'),
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
|
||||
@@ -556,9 +586,10 @@ def test_inline_layout_compacts_table_glyphs_without_changing_template_structure
|
||||
assert version.status == 'ready'
|
||||
assert version.payload_json['tables'] == snapshot['tables']
|
||||
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in version.payload_json['coordinate_evidence']
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,而非内联在快照中。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
|
||||
|
||||
|
||||
def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app):
|
||||
@@ -590,10 +621,11 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
|
||||
assert 'tables' not in restored['coordinate_evidence']
|
||||
|
||||
|
||||
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。"""
|
||||
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch):
|
||||
"""外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
# 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。
|
||||
current = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': {
|
||||
@@ -610,18 +642,34 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
|
||||
}
|
||||
glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
|
||||
page = SimpleNamespace(
|
||||
page_no=1, width=100, height=200, image=None,
|
||||
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content: [page],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
|
||||
lambda *, characters, table_bbox: [glyph],
|
||||
)
|
||||
|
||||
restored = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=frozen_layout, page_nos={1},
|
||||
)
|
||||
|
||||
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。
|
||||
# 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。
|
||||
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
|
||||
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
|
||||
|
||||
|
||||
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app):
|
||||
"""同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。"""
|
||||
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch):
|
||||
"""外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
current = record_inline_layout_snapshot(document, {
|
||||
@@ -633,19 +681,32 @@ def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_sn
|
||||
},
|
||||
})
|
||||
document.current_layout_version = current
|
||||
# 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。
|
||||
stale_run_layout = {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 200}},
|
||||
'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
|
||||
'sources': {'pages': {'1': 'ocr_coordinate'}},
|
||||
},
|
||||
}
|
||||
glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
|
||||
page = SimpleNamespace(
|
||||
page_no=1, width=100, height=200, image=None,
|
||||
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content: [page],
|
||||
)
|
||||
|
||||
restored = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=stale_run_layout, page_nos={1},
|
||||
)
|
||||
|
||||
# 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。
|
||||
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT'
|
||||
assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
|
||||
|
||||
|
||||
@@ -87,10 +87,20 @@ def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages(
|
||||
}
|
||||
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
|
||||
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}]
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}]
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
|
||||
|
||||
|
||||
def test_quality_region_falls_back_to_table_glyphs_without_page_evidence():
|
||||
"""页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。"""
|
||||
evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}}
|
||||
|
||||
assert quality._region_characters_for_quality(
|
||||
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
|
||||
evidence=evidence, raw_table={'page_no': 1}, table_id='table-1',
|
||||
) == [{'text': 'TABLE'}]
|
||||
|
||||
|
||||
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
|
||||
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
|
||||
evidence = {
|
||||
@@ -965,3 +975,94 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id'])
|
||||
assert frozen_suite.profile_checksum == published['checksum']
|
||||
assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs)
|
||||
|
||||
|
||||
def test_republish_identical_content_reuses_historical_promoted_suite(app):
|
||||
"""关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。
|
||||
|
||||
复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留),
|
||||
重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。
|
||||
"""
|
||||
from app.models import ShippingDocumentProfileTestRun
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
draft_checksum = str(profile.structure_fingerprint)
|
||||
published_checksum = str(profile.checksum)
|
||||
occupant = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
new_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
db.session.add_all([occupant, new_suite])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingDocumentProfileTestRun(
|
||||
suite_id=occupant.id, profile_checksum=published_checksum, status='passed',
|
||||
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
||||
),
|
||||
ShippingDocumentProfileTestRun(
|
||||
suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed',
|
||||
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
||||
),
|
||||
])
|
||||
db.session.flush()
|
||||
|
||||
quality.promote_approved_suite_for_publish(
|
||||
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# 历史凭证保持原样,仍是发布 checksum 的唯一持有者。
|
||||
assert occupant.status == 'approved'
|
||||
assert occupant.profile_checksum == published_checksum
|
||||
assert all(run.profile_checksum == published_checksum for run in occupant.runs)
|
||||
# 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。
|
||||
assert new_suite.status == 'superseded'
|
||||
assert new_suite.profile_checksum == draft_checksum
|
||||
assert all(run.profile_checksum == draft_checksum for run in new_suite.runs)
|
||||
reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=profile.id, event_type='blind_test_suite_superseded',
|
||||
).all()
|
||||
assert any(
|
||||
(audit.detail_json or {}).get('reason_code') == 'republish_identical_content'
|
||||
and (audit.detail_json or {}).get('reused_suite_id') == occupant.id
|
||||
for audit in reuse_audits
|
||||
)
|
||||
|
||||
|
||||
def test_promote_rejects_invalid_published_checksum_occupant(app):
|
||||
"""关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingDocumentProfileTestRun
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
draft_checksum = str(profile.structure_fingerprint)
|
||||
published_checksum = str(profile.checksum)
|
||||
invalid_occupant = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
new_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
db.session.add_all([invalid_occupant, new_suite])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingDocumentProfileTestRun(
|
||||
suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed',
|
||||
sample_count=1, passed_sample_count=0, executed_by_id=user.id,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
quality.promote_approved_suite_for_publish(
|
||||
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT'
|
||||
# 冲突时两个套件都不得被改动,保持发布事务可整体回滚。
|
||||
assert invalid_occupant.profile_checksum == published_checksum
|
||||
assert new_suite.status == 'approved'
|
||||
assert new_suite.profile_checksum == draft_checksum
|
||||
@@ -90,28 +90,50 @@ def test_rpa_upload_failures_keep_manual_retry_action():
|
||||
assert projected['next_action'] == 'retry_freight_upload_rpa'
|
||||
|
||||
|
||||
def test_inventory_preparation_reason_code_from_pending():
|
||||
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
def test_inventory_preparation_reason_code_from_pending(app):
|
||||
"""
|
||||
履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。
|
||||
|
||||
核心逻辑:task_blocking_reason 以 ShippingOrderTask.active_process_execution_id 为空的
|
||||
pending_human_reason 为唯一事实源;已落文件但无有效行 → inventory_file_empty,
|
||||
尚未生成库存文件(inv_unavail)→ inventory_file_missing。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
PH_INV_UNAVAIL,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
inventory_preparation_reason_code,
|
||||
manual_upload_reason_code,
|
||||
)
|
||||
|
||||
queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None)
|
||||
exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None)
|
||||
# 空列表=已落文件但无有效行;None=尚未生成库存文件
|
||||
empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[])
|
||||
missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None)
|
||||
def _pending_task(task_no: str, pending_human_reason: str | None) -> ShippingOrderTask:
|
||||
"""创建并持久化一个无活动执行的 OT;task_blocking_reason 直接读取 pending_human_reason。"""
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=1, pending_human_reason=pending_human_reason,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
# [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed)
|
||||
queued = _pending_task('OT-QUEUED', PH_RPA_PENDING)
|
||||
exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED)
|
||||
assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued'
|
||||
assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted'
|
||||
|
||||
# [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空;
|
||||
# None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。
|
||||
empty = _pending_task('OT-EMPTY', None)
|
||||
missing = _pending_task('OT-MISSING', PH_INV_UNAVAIL)
|
||||
assert inventory_preparation_reason_code(empty) == 'inventory_file_empty'
|
||||
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
|
||||
|
||||
upload_failed = SimpleNamespace(
|
||||
id=None, pending_human_reason='upload_rpa_failed',
|
||||
)
|
||||
# [STEP 3] 上传 RPA 失败归属 freight_upload_rpa,而非人工交接
|
||||
upload_failed = _pending_task('OT-UPLOAD-RPA-FAILED', 'upload_rpa_failed')
|
||||
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
|
||||
|
||||
|
||||
@@ -121,14 +143,16 @@ def test_build_explainability_reason_unknown_requires_request_id():
|
||||
|
||||
核心逻辑:禁止只显示「系统错误」而不带追溯号。
|
||||
"""
|
||||
# [STEP 1] 已知码保留责任方与动作
|
||||
# [STEP 1] 已知码保留责任方与动作(source_disabled 归属库存源不可用明细,
|
||||
# 生产 meta 定义为 admin + retry_with_latest_rules;open_inventory_source_review
|
||||
# 并非注册动作码,build_explainability_reason 会将其丢弃,故断言必须跟随生产值。)
|
||||
known = build_explainability_reason(
|
||||
reason_code='source_disabled',
|
||||
details={'source_code': 'DSV360_AWSSG'},
|
||||
)
|
||||
assert known['reason_code'] == 'source_disabled'
|
||||
assert known['responsible_party'] == 'admin'
|
||||
assert known['next_action'] == 'open_inventory_source_review'
|
||||
assert known['next_action'] == 'retry_with_latest_rules'
|
||||
assert known['details']['source_code'] == 'DSV360_AWSSG'
|
||||
|
||||
# [STEP 2] 未知码强制降级并要求 request_id
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""通知准备阶段 Excel 资格边界测试。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None:
|
||||
"""通知准备阶段的 OT 状态推导不得提前读取正式发货通知单。"""
|
||||
from app.services.shipping_notice import process_gate_bridge as bridge
|
||||
|
||||
class OrderTask:
|
||||
id = 21
|
||||
|
||||
# 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
lambda _task: False,
|
||||
)
|
||||
|
||||
class UnexpectedNoticeQuery:
|
||||
@property
|
||||
def query(self):
|
||||
raise AssertionError('通知准备不应查询 ShippingNotice')
|
||||
|
||||
monkeypatch.setattr(bridge, 'ShippingOrderTask', OrderTask)
|
||||
monkeypatch.setattr(bridge, 'ShippingNotice', UnexpectedNoticeQuery)
|
||||
|
||||
assert bridge._derived_fulfillment_status(OrderTask()) == 'matched'
|
||||
|
||||
|
||||
def test_excel_readiness_uses_order_task_before_formal_notice_exists(monkeypatch) -> None:
|
||||
"""OT 已满足库存门禁时,资格检查不得要求先创建 ShippingNotice。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
order_task = SimpleNamespace(id=21, task_no='OT-READY', match_status='fulfillable')
|
||||
outcomes: list[dict] = []
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: order_task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
|
||||
lambda task: None if task is order_task else 'wrong_task',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.apply_gate_outcome',
|
||||
lambda **kwargs: outcomes.append(kwargs),
|
||||
)
|
||||
|
||||
result = executor._handle_recheck_excel_readiness(
|
||||
execution=SimpleNamespace(execution_no='SPE-OT-READY', task_id=21),
|
||||
gate=SimpleNamespace(gate_code='excel_readiness'),
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'passed'
|
||||
assert outcomes[0]['passed'] is True
|
||||
@@ -111,6 +111,40 @@ def test_extension_create_retire_restore_and_forbid_delete(app):
|
||||
assert updated['display_name_default'] == '新名称'
|
||||
|
||||
|
||||
def test_update_extension_cannot_change_field_code(app):
|
||||
"""断言:扩展字段 field_code 创建后不可变。
|
||||
|
||||
field_code 是跨版本语义键:客户识别规则按 code 优先绑定字段(resolver code-primary),
|
||||
一旦允许改名,历史规则快照与运行时绑定会静默漂移。此处钉死资产服务层锁,
|
||||
防止未来新增改名路径时无意破坏该前提。
|
||||
"""
|
||||
with app.app_context():
|
||||
assets.ensure_standard_assets_seeded()
|
||||
created = assets.create_extension(
|
||||
{
|
||||
'field_code': 'ext_channel_ref',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'display_name': '渠道参考号',
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
current = assets.get_asset(created['id'])
|
||||
with pytest.raises(ConflictError) as locked:
|
||||
assets.update_extension(
|
||||
created['id'],
|
||||
{
|
||||
'field_code': 'ext_channel_ref_renamed',
|
||||
'display_name': '渠道参考号',
|
||||
'expected_updated_at': current['updated_at'],
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
# 关键断言:改名被拒绝且值未被改动,语义键稳定性由服务层硬锁保证。
|
||||
assert locked.value.code == 'SHIPPING.FIELD_ASSET_IMMUTABLE'
|
||||
assert assets.get_asset(created['id'])['field_code'] == 'ext_channel_ref'
|
||||
|
||||
|
||||
def test_schema_adopt_writes_per_field_audits(app):
|
||||
"""断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。"""
|
||||
from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion
|
||||
|
||||
@@ -320,7 +320,7 @@ def test_unknown_matcher_code_in_diagnostic_when_extension_happens():
|
||||
"""如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。"""
|
||||
seg = BaseSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='s',
|
||||
segment_code='s1',
|
||||
display_name='s',
|
||||
handling='mapped',
|
||||
target_field_id='f-s',
|
||||
|
||||
@@ -10,7 +10,7 @@ backend/tests/test_shipping_formal_task_edit_audit.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch
|
||||
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from tests.test_shipping_review_formal_task_edit import (
|
||||
@@ -76,6 +76,21 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
|
||||
},
|
||||
)
|
||||
_link_order_task(task, stage='excel_generating')
|
||||
# 前置:任务已在行级匹配为 matched(否则 before 快照不存在“被失效”的匹配状态)。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id),
|
||||
snapshot_line_id=1,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
required_qty='10',
|
||||
available_qty='10',
|
||||
shortage_qty='0',
|
||||
reservation_id='3000000001',
|
||||
part_number='A001',
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
|
||||
@@ -490,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
|
||||
assert result['match']['status'] == 'unique_match'
|
||||
assert result['match']['profile_code'] == 'ODP-PRODUCTION'
|
||||
# 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。
|
||||
assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1']
|
||||
assert seen_table_ids == ['native-text-table-p1-1'] * 3
|
||||
|
||||
|
||||
def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
|
||||
@@ -615,7 +615,7 @@ def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkey
|
||||
|
||||
# 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。
|
||||
assert rows == []
|
||||
assert unrelated == []
|
||||
assert unrelated is None
|
||||
assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
tests/test_shipping_line_source_ambiguity.py
|
||||
|
||||
用途:锁定多候选库存源「数据自证 + 歧义兜底」契约(设计 D4/D5,2026-08-29)。
|
||||
依赖:stp_line_inventory_match.match_order_lines_across_candidates。
|
||||
逻辑:同一行命中多源必须 multi_file_conflict 阻断并携带候选源列表(禁止静默选源);
|
||||
唯一源命中按行反写 源/可用量/缺口。既有能力以测试固化,防止后续回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
match_order_lines_across_candidates,
|
||||
)
|
||||
|
||||
|
||||
def test_same_reservation_across_two_sources_marks_conflict_with_candidates():
|
||||
"""[断言] 同一预约单在两个源都有库存:该行 multi_file_conflict 阻断并带候选源列表,
|
||||
resolved source 必须为空(选源交由人工 override_line_inventory_source)。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}],
|
||||
inventory_lines=[
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'},
|
||||
],
|
||||
)
|
||||
line = result['line_results'][0]
|
||||
assert line['disposition'] == 'multi_file_conflict'
|
||||
assert set(line['candidate_hit_source_codes']) == {'SRC_A', 'SRC_B'}
|
||||
assert line['resolved_inventory_source_code'] is None
|
||||
# 歧义行必须阻断整单可履行状态,防止带着未定源进入导出。
|
||||
assert result['match_status'] == 'unfulfillable'
|
||||
assert result['resolutions'][0]['candidate_hit_source_codes'] == line['candidate_hit_source_codes']
|
||||
|
||||
|
||||
def test_unique_source_hit_writes_back_source_qty_and_shortage():
|
||||
"""[断言] 唯一源命中:足量反写 ok+源+零缺口;不足反写 shortage+缺口数量。"""
|
||||
base_lines = [
|
||||
{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'},
|
||||
]
|
||||
inventory_full = [
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
|
||||
]
|
||||
result_full = match_order_lines_across_candidates(
|
||||
order_lines=base_lines, inventory_lines=inventory_full,
|
||||
)
|
||||
line_full = result_full['line_results'][0]
|
||||
assert line_full['line_status'] == 'ok'
|
||||
assert line_full['resolved_inventory_source_code'] == 'SRC_A'
|
||||
assert line_full['available_qty'] == 5.0
|
||||
assert line_full['shortage_qty'] == 0.0
|
||||
|
||||
inventory_short = [
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'SRC_A'},
|
||||
]
|
||||
result_short = match_order_lines_across_candidates(
|
||||
order_lines=base_lines, inventory_lines=inventory_short,
|
||||
)
|
||||
line_short = result_short['line_results'][0]
|
||||
assert line_short['line_status'] == 'partial' # 有货但不足 → partial(disposition=shortage)
|
||||
assert line_short['disposition'] == 'shortage'
|
||||
assert line_short['resolved_inventory_source_code'] == 'SRC_A'
|
||||
assert line_short['available_qty'] == 2.0
|
||||
assert line_short['shortage_qty'] == 3.0
|
||||
|
||||
|
||||
def test_disambiguation_via_pinned_allowed_sources_resolves_conflict():
|
||||
"""[断言] 人工选源后(行 allowed_source_codes 钉住单一源):原冲突行在钉住源内正常匹配,
|
||||
这是 override_line_inventory_source 行级重匹配的数据前提。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5',
|
||||
'allowed_source_codes': ['SRC_B'],
|
||||
}],
|
||||
inventory_lines=[
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
|
||||
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'},
|
||||
],
|
||||
)
|
||||
line = result['line_results'][0]
|
||||
assert line['disposition'] == 'ok'
|
||||
assert line['resolved_inventory_source_code'] == 'SRC_B'
|
||||
assert line['available_qty'] == 9.0
|
||||
@@ -56,25 +56,43 @@ def test_replacement_links_to_parent_notice(app):
|
||||
|
||||
|
||||
def test_create_task_assigns_notice_customer_and_serializes_it(app):
|
||||
"""真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。"""
|
||||
"""真实单票建单直接写分立的客户识别结果,不依赖 ShippingCase;OT 建单本身不阻断。"""
|
||||
from app.models import ShippingOrderTask, User
|
||||
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
|
||||
from app.services.shipping_notice.query_service import serialize_task_for_tool
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
with app.app_context():
|
||||
customer = _active_customer(short_code='CRT')
|
||||
user = User(username='create-task-crt', email='create-task-crt@example.test', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
result = create_task({
|
||||
'source_type': 'manual',
|
||||
'source_type': 'direct_pdf',
|
||||
'raw_content': 'customer notice',
|
||||
'customer_id': customer.id,
|
||||
'user_id': user.id,
|
||||
})
|
||||
task = ShippingNotice.query.filter_by(task_no=result['task_id']).one()
|
||||
assert task.customer_resolution_status == 'confirmed'
|
||||
assert task.customer_id == customer.id
|
||||
assert result['data']['customer_id'] == customer.id
|
||||
task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one()
|
||||
# [FIX] 客户确认由独立识别结果承载;建单不再阻塞(见 create_task 迁移注释)。
|
||||
confirm_test_customer_resolution(task, customer=customer)
|
||||
facts = customer_resolution_facts(task)
|
||||
assert facts['status'] == 'confirmed'
|
||||
assert facts['customer_id'] == customer.id
|
||||
assert serialize_task_for_tool(task)['customer_id'] == customer.id
|
||||
|
||||
|
||||
def test_create_task_rejects_without_customer(app):
|
||||
"""未确认客户时禁止创建 Task,避免落入 customer_review。"""
|
||||
def test_create_task_defers_customer_confirmation(app):
|
||||
"""未确认客户时不再阻断建单;客户确认交由订单复核/客户门禁处理。"""
|
||||
from app.models import ShippingOrderTask, User
|
||||
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
create_task({'source_type': 'manual', 'raw_content': 'customer notice'})
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK'
|
||||
user = User(username='create-task-nocust', email='create-task-nocust@example.test', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
result = create_task({'source_type': 'direct_pdf', 'raw_content': 'customer notice', 'user_id': user.id})
|
||||
task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one()
|
||||
assert task is not None
|
||||
assert customer_resolution_facts(task)['status'] != 'confirmed'
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
@@ -88,6 +89,106 @@ def _seed_parsed_intake(
|
||||
return asset, intake
|
||||
|
||||
|
||||
def _seed_existing_notice_task(
|
||||
user_id: int,
|
||||
*,
|
||||
task_no: str,
|
||||
business_fingerprint: str,
|
||||
fingerprint_version: str,
|
||||
content_fingerprint: str | None = None,
|
||||
content_fingerprint_version: str | None = None,
|
||||
source_content_hash: str | None = None,
|
||||
document_version: int = 1,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
构造一个已建单的正式发货通知,作为业务指纹去重的命中目标。
|
||||
|
||||
新契约:ShippingNotice 不再保存指纹投影;business/content 指纹转移到被消费的
|
||||
ShippingOrderCandidate(consumed_task_id -> 建单前 OT),Notice 经 order_task_id
|
||||
挂接该 OT。只有建立 Notice→Task→Candidate 这条链,duplicate_detection 的
|
||||
Notice→Task(consumed_task_id)→Candidate 查询才能命中——这是 key 断言,
|
||||
不是只为了消除构造参数,而是让「已有任务重复」真正可被探测。
|
||||
"""
|
||||
ot = ShippingOrderTask(
|
||||
task_no=f'OT-{task_no}',
|
||||
user_id=user_id,
|
||||
source_type='eml',
|
||||
lifecycle_status='active',
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{task_no}',
|
||||
owner_user_id=user_id,
|
||||
original_filename='existing.txt',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user_id}/{task_no}.txt',
|
||||
content_hash=source_content_hash or f'hash-{task_no}',
|
||||
file_size=1,
|
||||
mime_type='text/plain',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-{task_no}',
|
||||
asset_id=asset.id,
|
||||
user_id=user_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v1',
|
||||
duplicate_status='none',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
doc = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key=f'att-{task_no}',
|
||||
document_type='attachment',
|
||||
filename=f'{task_no}.pdf',
|
||||
content_hash=source_content_hash or f'hash-{task_no}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(doc)
|
||||
db.session.flush()
|
||||
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'SNC-{task_no}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=doc.id,
|
||||
candidate_key=f'test:{task_no}',
|
||||
business_fingerprint=business_fingerprint,
|
||||
fingerprint_version=fingerprint_version,
|
||||
content_fingerprint=content_fingerprint,
|
||||
content_fingerprint_version=content_fingerprint_version,
|
||||
consumed_task_id=ot.id,
|
||||
duplicate_status='none',
|
||||
candidate_status='accepted',
|
||||
selected=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
ot.candidate_id = candidate.id
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no=task_no,
|
||||
user_id=user_id,
|
||||
source_type='manual',
|
||||
document_version=document_version,
|
||||
order_task_id=ot.id,
|
||||
lifecycle_status='active',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
return notice
|
||||
|
||||
|
||||
def test_business_fingerprint_ignores_internal_hex_reservation_id():
|
||||
"""内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。"""
|
||||
summary = {
|
||||
@@ -185,16 +286,13 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
business_summary=summary,
|
||||
fingerprint=fp,
|
||||
)
|
||||
existing = ShippingNotice(
|
||||
_seed_existing_notice_task(
|
||||
dedup_user.id,
|
||||
task_no='SN-PENDING-1',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
result = detect_duplicates_for_intake(
|
||||
intake=intake,
|
||||
@@ -250,15 +348,13 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingNotice(
|
||||
_seed_existing_notice_task(
|
||||
dedup_user.id,
|
||||
task_no='SN-EXISTING-PO-A',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-other-file',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-STAGE2-DEDUP-EML',
|
||||
@@ -372,15 +468,13 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
'lines': [],
|
||||
}
|
||||
)
|
||||
existing = ShippingNotice(
|
||||
_seed_existing_notice_task(
|
||||
dedup_user.id,
|
||||
task_no='SN-REFRESH-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-refresh-other',
|
||||
)
|
||||
db.session.add(existing)
|
||||
|
||||
parent = FileAsset(
|
||||
asset_no='FA-REFRESH-DEDUP',
|
||||
@@ -479,16 +573,14 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
|
||||
}
|
||||
identity = build_business_fingerprint(base)
|
||||
content = build_content_fingerprint(base)
|
||||
existing = ShippingNotice(
|
||||
_seed_existing_notice_task(
|
||||
dedup_user.id,
|
||||
task_no='SN-CONTENT-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
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',
|
||||
|
||||
@@ -30,13 +30,13 @@ def _table_schema_definition() -> dict:
|
||||
aliases = {
|
||||
'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'],
|
||||
'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'],
|
||||
'amount': ['Amount'], 'currency': ['Currency'],
|
||||
'line_amount_with_tax': ['Amount'], 'currency': ['Currency'],
|
||||
'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'],
|
||||
'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'],
|
||||
'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'],
|
||||
'inventory_source_hint': ['source type'], 'po_number': ['PO'],
|
||||
}
|
||||
decimal_fields = {'qty', 'unit_price', 'amount'}
|
||||
decimal_fields = {'qty', 'unit_price', 'line_amount_with_tax'}
|
||||
return {'fields': [{
|
||||
'field_id': f'test-{code}', 'field_code': code,
|
||||
'scope': 'header' if code == 'po_number' else 'line',
|
||||
@@ -1318,7 +1318,8 @@ def test_extract_eml_keeps_inline_pdf_attachment(tmp_path):
|
||||
assert "PO-INLINE-PDF" in text
|
||||
|
||||
|
||||
def test_extract_reservation_id_from_pr_number():
|
||||
def test_extract_reservation_id_from_at_delimited_pr_number():
|
||||
"""PR Number 中以 ``@`` 明确分隔的完整数字可作为 Reservation ID。"""
|
||||
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
|
||||
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
|
||||
|
||||
@@ -1409,14 +1410,11 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 1
|
||||
assert lines[0]["part_number"] == "B3-A08AR11000001"
|
||||
assert lines[0]["line_no"] == "10"
|
||||
assert lines[0]["qty"] == 9.0
|
||||
assert lines[0]["unit_price"] == 1607.72
|
||||
assert lines[0]["amount"] == 14469.48
|
||||
assert "reservation_id" not in lines[0]
|
||||
assert lines[0]["required_date"] == "2026-06-15"
|
||||
assert lines[0]["aws_part_number"] == "504-010213-001"
|
||||
assert lines[0]["currency"] == "USD"
|
||||
|
||||
|
||||
def test_normalize_reservation_id_from_excel_float():
|
||||
@@ -1453,37 +1451,53 @@ def test_does_not_infer_reservation_id_without_configured_header():
|
||||
def test_parse_notice_table_with_all_fields():
|
||||
text = """
|
||||
Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
10-40594-001\tAWS-311\t2\t15.5\t31.0
|
||||
10-40594-002\tORD-3002\t1\t20\t20
|
||||
10-40594-001\t1000140351\t2\t15.5\t31.0
|
||||
10-40594-002\t1000140352\t1\t20\t20
|
||||
"""
|
||||
lines = parse_notice_table_text(text, contract=_table_contract())
|
||||
assert len(lines) == 2
|
||||
assert lines[0]["part_number"] == "10-40594-001"
|
||||
assert lines[0]["reservation_id"] == "AWS-311"
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
assert lines[0]["qty"] == 2
|
||||
assert lines[0]["unit_price"] == 15.5
|
||||
assert lines[0]["amount"] == 31.0
|
||||
|
||||
|
||||
def test_normalize_notice_line_aliases():
|
||||
# 表头业务别名不再内置于代码;只经本次冻结 Schema 解析(见 notice_lines 迁移说明)。
|
||||
# line_no 为系统生成项次,不参与 normalize 派生,故从结果中移除。
|
||||
schema_definition = {
|
||||
'fields': [
|
||||
{'field_id': 't-line_no', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, 'aliases': ['Line No']},
|
||||
{'field_id': 't-part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
|
||||
{'field_id': 't-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['quantity']},
|
||||
{'field_id': 't-rid', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'aliases': ['com_id']},
|
||||
{'field_id': 't-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['price']},
|
||||
{'field_id': 't-amount', 'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': []},
|
||||
{'field_id': 't-currency', 'field_code': 'currency', 'scope': 'line', 'enabled': True, 'aliases': []},
|
||||
{'field_id': 't-date', 'field_code': 'required_date', 'scope': 'line', 'value_type': 'date', 'enabled': True, 'aliases': ['delivery_date']},
|
||||
{'field_id': 't-cust', 'field_code': 'customer_part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
|
||||
{'field_id': 't-aws', 'field_code': 'aws_part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
|
||||
]
|
||||
}
|
||||
line = normalize_notice_line(
|
||||
{
|
||||
"part_number": "A-001",
|
||||
"quantity": "3",
|
||||
"com_id": "COM-99",
|
||||
"com_id": "1000140351",
|
||||
"price": "12.5",
|
||||
"delivery_date": "2026/06/15",
|
||||
"customer_part_number": "CUST-001",
|
||||
"aws_part_number": "AWS-001",
|
||||
"currency": "USD",
|
||||
"line_no": "10",
|
||||
}
|
||||
},
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
assert line == {
|
||||
"line_no": "10",
|
||||
"part_number": "A-001",
|
||||
"qty": 3.0,
|
||||
"reservation_id": "COM-99",
|
||||
"reservation_id": "1000140351",
|
||||
"unit_price": 12.5,
|
||||
"amount": 37.5,
|
||||
"currency": "USD",
|
||||
@@ -1611,7 +1625,7 @@ def test_normalize_notice_line_rejects_ambiguous_composite(value):
|
||||
|
||||
|
||||
def test_parse_notice_table_maps_three_part_number_roles():
|
||||
"""MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。"""
|
||||
"""MPN 与 Allocated HHPN 进入内部料号与客户料号;Allocated APN 已移出表格字段目录,不再按行解析。"""
|
||||
lines = parse_notice_table_rows(
|
||||
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
|
||||
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
|
||||
@@ -1621,7 +1635,6 @@ def test_parse_notice_table_maps_three_part_number_roles():
|
||||
assert lines == [{
|
||||
"part_number": "D4-A08AR12000002",
|
||||
"customer_part_number": "TEMP-S000218929",
|
||||
"aws_part_number": "504-006055-001",
|
||||
"qty": 10.0,
|
||||
}]
|
||||
|
||||
@@ -1676,7 +1689,7 @@ def test_extract_notice_fields_structured():
|
||||
{
|
||||
"part_number": "10-40594-001",
|
||||
"qty": 2,
|
||||
"reservation_id": "AWS-311",
|
||||
"reservation_id": "1000140351",
|
||||
"unit_price": 10,
|
||||
"amount": 20,
|
||||
}
|
||||
@@ -1684,7 +1697,7 @@ def test_extract_notice_fields_structured():
|
||||
"confidence": 0.9,
|
||||
}
|
||||
parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured)
|
||||
assert parsed["lines"][0]["reservation_id"] == "AWS-311"
|
||||
assert parsed["lines"][0]["reservation_id"] == "1000140351"
|
||||
assert parsed["lines"][0]["amount"] == 20
|
||||
assert confidence >= 0.8
|
||||
assert not any("未解析到有效订单行" in w for w in warnings)
|
||||
@@ -1702,12 +1715,12 @@ def test_heuristic_table_skips_title_row():
|
||||
text = """
|
||||
Shipping Notice
|
||||
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
|
||||
10-40594-001\tORD-3002\t4\t5\t20
|
||||
10-40594-001\t1000140351\t4\t5\t20
|
||||
"""
|
||||
parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition())
|
||||
assert len(parsed["lines"]) == 1
|
||||
assert parsed["lines"][0]["part_number"] == "10-40594-001"
|
||||
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
|
||||
assert parsed["lines"][0]["reservation_id"] == "1000140351"
|
||||
assert parsed["lines"][0]["qty"] == 4
|
||||
assert parsed["lines"][0]["unit_price"] == 5
|
||||
assert parsed["lines"][0]["amount"] == 20
|
||||
@@ -1733,7 +1746,7 @@ def test_extract_notice_fields_structured_over_heuristic():
|
||||
|
||||
def test_extract_notice_fields_heuristic_fallback():
|
||||
"""无 structured 时走后端启发式兜底。"""
|
||||
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
|
||||
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\t1000140351\t4"
|
||||
parsed, _, warnings = extract_notice_fields(
|
||||
raw_text=text, schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
@@ -170,7 +170,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
|
||||
"""Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。"""
|
||||
document = _document(
|
||||
1,
|
||||
"MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2",
|
||||
"MPN\tQty\tReservation ID\nD4-A\t10\t10001\nD4-B\t20\t10002",
|
||||
)
|
||||
|
||||
result = adjudicate_order_fields(
|
||||
@@ -181,7 +181,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
|
||||
)
|
||||
|
||||
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
|
||||
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"]
|
||||
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["10001", "10002"]
|
||||
assert trusted_required_fields(result) is True
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@ from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
@@ -29,6 +31,7 @@ from app.models import (
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
@@ -201,12 +204,37 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
existing = ShippingNotice(
|
||||
# 重复目标由建单前 OT(ShippingOrderTask)及其正式 Notice、已消费同哈希 Intake
|
||||
# 共同构成 exact_file 匹配链(ShippingNotice.order_task_id → OT → consumed Intake → FileAsset)。
|
||||
existing_task = ShippingOrderTask(
|
||||
task_no='OT-CANDIDATE-EXISTING-001', user_id=owner.id,
|
||||
lifecycle_status='active',
|
||||
)
|
||||
db.session.add(existing_task)
|
||||
existing_asset = FileAsset(
|
||||
asset_no='FA-CANDIDATE-EXISTING-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}/existing/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(existing_asset)
|
||||
db.session.flush()
|
||||
# OT/资产主键在会话内固化,供跨 app_context 重挂 Notice 时使用(避免 DetachedInstance 刷新)。
|
||||
existing_task_id = int(existing_task.id)
|
||||
existing_notice = ShippingNotice(
|
||||
task_no='SN-CANDIDATE-EXISTING-001',
|
||||
user_id=owner.id,
|
||||
source_content_hash=asset.content_hash,
|
||||
order_task_id=existing_task_id,
|
||||
)
|
||||
db.session.add_all([document, existing])
|
||||
consumed_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-CANDIDATE-EXISTING-CONSUMED', asset_id=existing_asset.id,
|
||||
user_id=owner.id, purpose='shipping_notice', parse_status='consumed',
|
||||
parser_version='v6', consumed_task_id=existing_task_id,
|
||||
)
|
||||
db.session.add_all([document, existing_notice, consumed_intake])
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='SNC-CANDIDATE-API-001',
|
||||
@@ -220,14 +248,10 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}],
|
||||
},
|
||||
},
|
||||
validation_status='needs_review',
|
||||
conflicts_json=[{'field': 'qty'}],
|
||||
validation_status='ready',
|
||||
conflicts_json=[],
|
||||
extraction_source='dify_workflow',
|
||||
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()
|
||||
@@ -236,13 +260,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
|
||||
patch_response = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
|
||||
json={
|
||||
'selected': False,
|
||||
'business_summary': {
|
||||
'po_number': '7001',
|
||||
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}],
|
||||
},
|
||||
},
|
||||
json={'selected': False},
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert patch_response.status_code == 200
|
||||
@@ -273,13 +291,13 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
assert repeated.status_code == 200
|
||||
assert repeated.get_json()['data']['candidate_status'] == 'accepted'
|
||||
assert patched['conflicts'] == []
|
||||
assert patched['content_fingerprint']
|
||||
assert promoted['content_fingerprint']
|
||||
assert patched['duplicate_resolution'] is None
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(ShippingNotice(
|
||||
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
|
||||
source_content_hash='candidate-api-content-hash',
|
||||
order_task_id=existing_task_id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -323,122 +341,36 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
)
|
||||
assert consumed.status_code == 409
|
||||
|
||||
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
|
||||
"""人工修订不得以空摘要或无效 part_number/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 = ShippingOrderIntake(
|
||||
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 = ShippingOrderDocument(
|
||||
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 = ShippingOrderCandidate(
|
||||
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': [{'part_number': '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': [{'part_number': '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': [
|
||||
{
|
||||
'part_number': '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_requires_accepted_lifecycle(app, shipping_user):
|
||||
"""provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。"""
|
||||
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
|
||||
|
||||
with app.app_context():
|
||||
# 建 Task 前客户必须已确认(ShippingCustomerShadowResolution 承载该事实)。
|
||||
customer = ShippingCustomer(standard_name='Acceptance Customer', short_code='ACPT', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate',
|
||||
intake_id=1, primary_document_id=1, selected=True,
|
||||
candidate_status='provisional', is_current_version=True,
|
||||
validation_status='ready', conflicts_json=[],
|
||||
validation_status='ready', conflicts_json=[], acceptance_mode='manual',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
# 客户确认事实只承载于影子识别结果;不再落 Notice/OT 列。
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=candidate.intake_id,
|
||||
resolution_version='test.v1', status='confirmed',
|
||||
confirmed_customer_id=customer.id, confirmation_method='manual',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': 'ACPT'}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
|
||||
identity_rule_set_checksum='t' * 64,
|
||||
)
|
||||
db.session.add(resolution)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as provisional:
|
||||
ensure_candidate_fulfillment_ready(candidate)
|
||||
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
|
||||
@@ -514,13 +446,20 @@ def test_create_intake_integrity_race_returns_existing(app, shipping_user, monke
|
||||
def _boom_nested():
|
||||
class _CM:
|
||||
def __enter__(self):
|
||||
raise IntegrityError('stmt', {}, Exception('uq'))
|
||||
# 仅注入一次 IntegrityError:模拟 Intake 唯一约束竞争;
|
||||
# 后续(如 Submission 归属)SAVEPOINT 正常通过。
|
||||
if nested_calls['n'] == 0:
|
||||
nested_calls['n'] += 1
|
||||
raise IntegrityError('stmt', {}, Exception('uq'))
|
||||
return True
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
return _CM()
|
||||
|
||||
nested_calls = {'n': 0}
|
||||
|
||||
monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
|
||||
|
||||
payload = create_shipping_notice_intake(
|
||||
@@ -637,7 +576,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
|
||||
task_no='SN-REV-LOCK-BASE',
|
||||
user_id=shipping_user.id,
|
||||
source_type='manual',
|
||||
upload_status='uploaded',
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(base)
|
||||
@@ -1062,69 +1000,3 @@ def test_intake_status_api_strips_texts_detail_returns_full(app, client):
|
||||
# 避免未使用变量告警
|
||||
assert other_id != owner_id
|
||||
|
||||
def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch):
|
||||
"""解析完成后取消须删除 Document/Candidate 并归零派生资产引用。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
from app.services.shipping_notice.intake_service import cancel_intake
|
||||
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'cancel after parse'
|
||||
msg['From'] = 'a@b.com'
|
||||
msg['To'] = 'c@d.com'
|
||||
msg.set_content('body')
|
||||
msg.add_attachment(
|
||||
_minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'),
|
||||
maintype='application',
|
||||
subtype='pdf',
|
||||
filename='cancel.pdf',
|
||||
)
|
||||
eml_bytes = msg.as_bytes()
|
||||
|
||||
with app.app_context():
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
asset_data = upload_file_asset(
|
||||
user_id=shipping_user.id,
|
||||
upload=FileStorage(
|
||||
stream=BytesIO(eml_bytes),
|
||||
filename='cancel.eml',
|
||||
content_type='message/rfc822',
|
||||
),
|
||||
)
|
||||
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='SNI-STAGE2-CANCEL',
|
||||
asset_id=parent.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsing',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
|
||||
lambda _a: eml_bytes,
|
||||
)
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parsed'
|
||||
derived = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
|
||||
.one()
|
||||
)
|
||||
assert int(derived.reference_count or 0) >= 1
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1
|
||||
|
||||
cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL')
|
||||
db.session.expire_all()
|
||||
cancelled = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one()
|
||||
assert cancelled.parse_status == 'cancelled'
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=cancelled.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=cancelled.id).count() == 0
|
||||
derived2 = db.session.get(FileAsset, derived.id)
|
||||
assert int(derived2.reference_count or 0) == 0
|
||||
assert derived2.lifecycle_status == 'temporary'
|
||||
|
||||
@@ -804,81 +804,14 @@ def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parsed'
|
||||
att = (
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter_by(intake_id=intake.id, document_type='attachment')
|
||||
.one()
|
||||
)
|
||||
assert att.classification == 'supporting'
|
||||
# 普通发货通知上传只落摘要,不建 Document/Candidate;落库在发送/物化阶段。
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=intake.id).count() == 0
|
||||
|
||||
def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""阶段二持久化失败须 parse_failed,且可 retry_intake_parse。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'fail stage2'
|
||||
msg['From'] = 'a@b.com'
|
||||
msg['To'] = 'c@d.com'
|
||||
msg.set_content('body')
|
||||
msg.add_attachment(
|
||||
_minimal_pdf_bytes('PO Number: 999001'),
|
||||
maintype='application',
|
||||
subtype='pdf',
|
||||
filename='one.pdf',
|
||||
)
|
||||
eml_bytes = msg.as_bytes()
|
||||
|
||||
with app.app_context():
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
asset_data = upload_file_asset(
|
||||
user_id=shipping_user.id,
|
||||
upload=FileStorage(
|
||||
stream=BytesIO(eml_bytes),
|
||||
filename='fail.eml',
|
||||
content_type='message/rfc822',
|
||||
),
|
||||
)
|
||||
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='SNI-STAGE2-FAIL',
|
||||
asset_id=parent.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsing',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
|
||||
lambda _a: eml_bytes,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
|
||||
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')),
|
||||
)
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parse_failed'
|
||||
db.session.expire_all()
|
||||
failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one()
|
||||
assert failed.parse_status == 'parse_failed'
|
||||
assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED'
|
||||
|
||||
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777):
|
||||
retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL')
|
||||
assert retried['parse_status'] == 'queued'
|
||||
|
||||
def test_upload_preprocess_does_not_invoke_candidate_dedup(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。"""
|
||||
"""上传预处理只落摘要,不建 Document/Candidate;订单 Candidate 判重函数即使不可用也不影响预处理。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
@@ -937,13 +870,14 @@ def test_upload_preprocess_does_not_invoke_candidate_dedup(
|
||||
assert refreshed.parse_status == 'parsed'
|
||||
assert refreshed.order_extraction_status == 'not_started'
|
||||
assert refreshed.duplicate_matches_json in (None, [])
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() >= 1
|
||||
# 普通发货通知上传只落摘要,不建 Document / 不生成 Candidate (落库在发送/物化阶段)。
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=refreshed.id).count() == 0
|
||||
|
||||
def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。"""
|
||||
"""普通发货通知上传阶段不落库、不判重:预置的 duplicate 状态在上传后保持原值(stage2 清理已不再存在)。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
@@ -1004,25 +938,24 @@ def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
|
||||
db.session.commit()
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parse_failed'
|
||||
# 普通发货通知上传阶段不落库、不判重:persist_documents_and_candidates 不被调用,
|
||||
# 即使 monkeypatch 抛异常也不影响。判重属于抽取/建单链路的字段,普通上传分支会
|
||||
# 把它重置回默认值(unchecked / 空)而非保留先前值;Intake 回 parsed。
|
||||
assert result['status'] == 'parsed'
|
||||
db.session.expire_all()
|
||||
failed = db.session.query(ShippingOrderIntake).filter_by(
|
||||
parsed = db.session.query(ShippingOrderIntake).filter_by(
|
||||
intake_no='SNI-STAGE2-CLEAR-DUP'
|
||||
).one()
|
||||
assert failed.parse_status == 'parse_failed'
|
||||
assert failed.duplicate_status == 'unchecked'
|
||||
assert failed.duplicate_matches_json in (None, [])
|
||||
assert failed.business_fingerprint is None
|
||||
assert failed.fingerprint_version is None
|
||||
assert failed.fingerprint_strength is None
|
||||
assert failed.duplicate_resolution is None
|
||||
assert failed.duplicate_resolution_reason is None
|
||||
assert failed.duplicate_target_task_no is None
|
||||
assert failed.duplicate_resolved_at is None
|
||||
payload = serialize_intake(failed, asset=parent)
|
||||
dup = payload.get('duplicate') or {}
|
||||
assert (dup.get('matches') or []) == []
|
||||
assert payload.get('duplicate_resolution') is None
|
||||
assert parsed.parse_status == 'parsed'
|
||||
assert parsed.order_extraction_status == 'not_started'
|
||||
assert parsed.duplicate_status == 'unchecked'
|
||||
assert (parsed.duplicate_matches_json or []) == []
|
||||
assert parsed.business_fingerprint is None
|
||||
assert parsed.duplicate_resolution is None
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0
|
||||
payload = serialize_intake(parsed, asset=parent)
|
||||
assert (payload.get('duplicate') or {}).get('matches') or [] == []
|
||||
|
||||
def test_derived_asset_refcount_increments_per_document_link(app, shipping_user):
|
||||
"""多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。"""
|
||||
@@ -1383,88 +1316,12 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp
|
||||
summary = failed.structured_result_json or {}
|
||||
assert 'document_count' not in summary
|
||||
|
||||
def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch):
|
||||
"""阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。"""
|
||||
def test_stage2_persist_does_not_run_for_plain_shipping_notice(app, shipping_user, monkeypatch):
|
||||
"""普通发货通知上传阶段不调 stage2 持久化:persist_documents_and_candidates 不可用也不影响(返回 parsed,不建 Document)。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'fail after cancel'
|
||||
msg['From'] = 'a@b.com'
|
||||
msg['To'] = 'c@d.com'
|
||||
msg.set_content('body')
|
||||
msg.add_attachment(
|
||||
_minimal_pdf_bytes('PO Number: CANCELLOCK001'),
|
||||
maintype='application',
|
||||
subtype='pdf',
|
||||
filename='lock.pdf',
|
||||
)
|
||||
eml_bytes = msg.as_bytes()
|
||||
|
||||
with app.app_context():
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
asset_data = upload_file_asset(
|
||||
user_id=shipping_user.id,
|
||||
upload=FileStorage(
|
||||
stream=BytesIO(eml_bytes),
|
||||
filename='lock.eml',
|
||||
content_type='message/rfc822',
|
||||
),
|
||||
)
|
||||
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='SNI-STAGE2-FAIL-CANCELLED',
|
||||
asset_id=parent.id,
|
||||
user_id=shipping_user.id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsing',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
doc = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
attachment_key='att-001',
|
||||
document_type='attachment',
|
||||
filename='lock.pdf',
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(doc)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
|
||||
lambda _a: eml_bytes,
|
||||
)
|
||||
|
||||
def _boom_then_cancel(**kwargs):
|
||||
# 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled
|
||||
row = db.session.get(ShippingOrderIntake, intake.id)
|
||||
row.parse_status = 'cancelled'
|
||||
db.session.commit()
|
||||
raise RuntimeError('boom-after-cancel')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
|
||||
_boom_then_cancel,
|
||||
)
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'skipped'
|
||||
db.session.expire_all()
|
||||
final = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one()
|
||||
assert final.parse_status == 'cancelled'
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=final.id).count() == 1
|
||||
|
||||
def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch):
|
||||
"""阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。"""
|
||||
from email.message import EmailMessage
|
||||
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
from app.services.shipping_notice.intake_service import serialize_intake
|
||||
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'retry clear'
|
||||
msg['From'] = 'a@b.com'
|
||||
@@ -1503,28 +1360,21 @@ def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monk
|
||||
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
|
||||
lambda _a: eml_bytes,
|
||||
)
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
first = run_intake_parse(intake, parent)
|
||||
assert first['status'] == 'parsed'
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1
|
||||
|
||||
intake.parse_status = 'parsing'
|
||||
db.session.commit()
|
||||
# 上传阶段不调用 persist_documents_and_candidates:即使它抛异常也不影响解析。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
|
||||
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')),
|
||||
)
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
second = run_intake_parse(intake, parent)
|
||||
assert second['status'] == 'parse_failed'
|
||||
result = run_intake_parse(intake, parent)
|
||||
assert result['status'] == 'parsed'
|
||||
db.session.expire_all()
|
||||
failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one()
|
||||
assert failed.parse_status == 'parse_failed'
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=failed.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=failed.id).count() == 0
|
||||
payload = serialize_intake(failed, asset=parent)
|
||||
assert payload['document_count'] == 0
|
||||
assert payload['candidate_count'] == 0
|
||||
parsed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one()
|
||||
assert parsed.parse_status == 'parsed'
|
||||
assert parsed.order_extraction_status == 'not_started'
|
||||
# 普通发货通知上传不建 Document/Candidate;落库在发送/物化阶段。
|
||||
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0
|
||||
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0
|
||||
|
||||
def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user):
|
||||
"""补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。"""
|
||||
|
||||
@@ -18,7 +18,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
校验订单抽取 Tool 已下线且库存连接器字段边界保持稳定。
|
||||
|
||||
核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations;
|
||||
任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。
|
||||
任务状态不再暴露库存连接器实现细节,并拒绝旧 connector 字段名。
|
||||
|
||||
Args:
|
||||
spec: 动态接口或静态快照读取出的 OpenAPI 对象。
|
||||
@@ -31,7 +31,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
assert '/tools/submit_order_extraction' not in paths
|
||||
|
||||
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
|
||||
assert "inventory_connector_type" in status_description
|
||||
assert "inventory_connector_type" not in status_description
|
||||
assert "inventory_source_type" not in status_description
|
||||
|
||||
assert set(paths) == {"/tools/get_task_status"}
|
||||
|
||||
@@ -121,90 +121,7 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
|
||||
assert assessment['missing_process_fields'] == ['reservation_id']
|
||||
|
||||
|
||||
def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app):
|
||||
"""派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。"""
|
||||
with app.app_context():
|
||||
order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None)
|
||||
customer_line = order_schema_service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = order_schema_service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
part = order_schema_service.save_field(
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
qty = order_schema_service.save_field(
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
|
||||
def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict:
|
||||
return {
|
||||
'field_id': field['id'], 'display_name': field['field_code'], 'required': required,
|
||||
'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general',
|
||||
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_text'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': comparator,
|
||||
}
|
||||
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
|
||||
config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
|
||||
config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'),
|
||||
config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty', 'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = order_schema_service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
_user, _session, intake, document, _runtime_context = _seed_extraction_input()
|
||||
document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10'
|
||||
db.session.commit()
|
||||
|
||||
result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'source_intake_no': intake.intake_no, 'primary_document_id': document.id,
|
||||
'classification': 'shipping_request', 'classification_confidence': 0.99,
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99,
|
||||
}]},
|
||||
{'field_id': part['id'], 'observations': [{
|
||||
'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99,
|
||||
}]},
|
||||
{'field_id': qty['id'], 'observations': [{
|
||||
'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99,
|
||||
}]},
|
||||
]}],
|
||||
'conflicts': [{
|
||||
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
}],
|
||||
}]})
|
||||
|
||||
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions']
|
||||
assert any(
|
||||
item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived'
|
||||
for item in decisions
|
||||
)
|
||||
assert not any(
|
||||
item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing'
|
||||
for item in candidate.conflicts_json
|
||||
)
|
||||
assert 'blocking_conflict' not in result['pending_orders'][0]['reasons']
|
||||
|
||||
|
||||
def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field():
|
||||
@@ -768,9 +685,18 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None:
|
||||
field['observations'][0]['quote'] = 'NOT-IN-SOURCE'
|
||||
|
||||
|
||||
def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
|
||||
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。"""
|
||||
fields = _ensure_order_schema()
|
||||
def _attach_existing_task_dynamic_order(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
po_number: str = '',
|
||||
lines: list[dict] | None = None,
|
||||
) -> None:
|
||||
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。
|
||||
|
||||
ShippingOrderTask 不再保存 po_number/lines_json 投影;订单真相由当前已接受
|
||||
Extraction 的 FieldValue 承载,因此明确传入门头与行值。
|
||||
"""
|
||||
_ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
@@ -781,7 +707,7 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
configs = list((version.definition_json or {}).get('fields') or [])
|
||||
header_values = {'po_number': task.po_number}
|
||||
header_values = {'po_number': po_number}
|
||||
for config in configs:
|
||||
if config.get('scope') != 'header':
|
||||
continue
|
||||
@@ -799,8 +725,10 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
decision_id=decision.id, value_text=str(value), value_json=value,
|
||||
))
|
||||
for position, row in enumerate(task.lines_json or []):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
for position, row in enumerate(lines or []):
|
||||
line = ShippingOrderLine(
|
||||
extraction_id=extraction.id, position=position, line_no=position + 1,
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for config in configs:
|
||||
@@ -837,13 +765,18 @@ def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
ShippingOrderField.field_code.in_(sequence_by_code),
|
||||
).all():
|
||||
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual',
|
||||
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
owner = User(username='order-display-user', email='order-display@example.com', password_hash='x')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-ORDER-DISPLAY-SEQUENCE', source_type='eml',
|
||||
user_id=int(owner.id),
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
_attach_existing_task_dynamic_order(
|
||||
task, po_number='PO-001', lines=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
display = current_order_field_display(task)
|
||||
@@ -1112,11 +1045,10 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
"""订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
existing = ShippingNotice(
|
||||
task_no='SN-ORDER-EXISTING-001',
|
||||
existing = ShippingOrderTask(
|
||||
task_no='OT-ORDER-EXISTING-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
source_type='eml',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
@@ -1134,7 +1066,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{
|
||||
'task_no': existing.task_no,
|
||||
'match_status': existing.match_status,
|
||||
'match_status': 'matched',
|
||||
'match_type': 'business_fingerprint',
|
||||
}],
|
||||
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
|
||||
@@ -1166,9 +1098,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
assert result['opened_existing'][0]['task_no'] == existing.task_no
|
||||
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
|
||||
assert candidate.consumed_task_id == existing.id
|
||||
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
|
||||
|
||||
assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app):
|
||||
"""LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。"""
|
||||
with app.app_context():
|
||||
@@ -1240,33 +1170,42 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part
|
||||
assert document.order_extraction_status == 'partially_completed'
|
||||
|
||||
|
||||
def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app):
|
||||
def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app, monkeypatch):
|
||||
"""同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
existing = ShippingNotice(
|
||||
task_no='SN-ORDER-RSV-BACKFILL-001',
|
||||
existing = ShippingOrderTask(
|
||||
task_no='OT-ORDER-RSV-BACKFILL-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
source_type='eml',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
error_message='解析失败:未识别到 Reservation ID',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
step_payload_json={
|
||||
'process_field_gate': {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': ['reservation_id'],
|
||||
'issues': [],
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
_attach_existing_task_dynamic_order(
|
||||
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_result = {
|
||||
'status': 'exact_file',
|
||||
'blocking': True,
|
||||
'fingerprint_strength': 'strong',
|
||||
'fingerprint': 'reservation-backfill-fingerprint',
|
||||
'fingerprint_version': 'shipping-v1',
|
||||
'components': {'po_number': '4510038672'},
|
||||
'content_fingerprint': 'reservation-backfill-content',
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
|
||||
'allowed_actions': ['open_existing', 'force_create'],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
|
||||
lambda **_kwargs: dict(duplicate_result),
|
||||
)
|
||||
|
||||
document.extracted_text = (
|
||||
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 "
|
||||
"Reservation ID 1000140351 Source DBS DUB"
|
||||
@@ -1293,7 +1232,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_re
|
||||
assert result['created_count'] == 0
|
||||
assert not result['pending_orders'], result['pending_orders']
|
||||
assert result['opened_existing_count'] == 1, result
|
||||
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
|
||||
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert candidate_line['inventory_source_hint'] == 'DBS DUB'
|
||||
@@ -1406,29 +1345,30 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
@pytest.mark.parametrize(
|
||||
'task_overrides',
|
||||
[
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'match_status': 'matched'},
|
||||
{'export_file_path': '/tmp/shipment.xlsx'},
|
||||
{'pending_human_reason': 'inv_unavail'},
|
||||
{'pending_human_reason': 'shortage'},
|
||||
{'pending_human_reason': 'rpa_exhausted'},
|
||||
{'pending_human_reason': 'upload_rpa_pending'},
|
||||
],
|
||||
)
|
||||
def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides):
|
||||
"""旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。"""
|
||||
with app.app_context():
|
||||
task_values = {
|
||||
'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
|
||||
'po_number': '4510038672',
|
||||
'source_type': 'manual',
|
||||
'task_no': f"OT-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
|
||||
'user_id': 1,
|
||||
'source_type': 'eml',
|
||||
'review_status': 'rsv_req',
|
||||
'pending_human_reason': 'rsv_req',
|
||||
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
|
||||
}
|
||||
task_values.update(task_overrides)
|
||||
task = ShippingNotice(**task_values)
|
||||
task = ShippingOrderTask(**task_values)
|
||||
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
_attach_existing_task_dynamic_order(
|
||||
task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24}],
|
||||
)
|
||||
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
@@ -1448,7 +1388,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
)
|
||||
|
||||
assert outcome['status'] == 'skipped'
|
||||
assert 'reservation_id' not in task.lines_json[0]
|
||||
assert current_line_field_values(task)[0].get('reservation_id') is None
|
||||
assert ShippingTaskEvent.query.filter_by(
|
||||
task_id=int(task.id),
|
||||
event_type='reservation_backfilled_from_exact_file_candidate',
|
||||
@@ -1458,39 +1398,27 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app):
|
||||
"""既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。"""
|
||||
with app.app_context():
|
||||
tasks = [
|
||||
ShippingNotice(
|
||||
task_no='SN-RSV-BACKFILL-CONFLICT',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[
|
||||
{'part_number': 'P123456', 'qty': 24},
|
||||
{'part_number': 'P123456', 'qty': 24},
|
||||
],
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
),
|
||||
task_lines = [
|
||||
('OT-RSV-BACKFILL-CONFLICT', [{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}]),
|
||||
('OT-RSV-BACKFILL-AMBIGUOUS-LINES', [
|
||||
{'part_number': 'P123456', 'qty': 24},
|
||||
{'part_number': 'P123456', 'qty': 24},
|
||||
]),
|
||||
('OT-RSV-BACKFILL-AMBIGUOUS-TARGET', [{'part_number': 'P123456', 'qty': 24}]),
|
||||
]
|
||||
db.session.add_all(tasks)
|
||||
db.session.flush()
|
||||
for task in tasks:
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
tasks = []
|
||||
for task_no, lines in task_lines:
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
user_id=1,
|
||||
source_type='eml',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task, po_number='4510038672', lines=lines)
|
||||
tasks.append(task)
|
||||
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
|
||||
summary = {
|
||||
'po_number': '4510038672',
|
||||
@@ -1519,26 +1447,27 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
]
|
||||
|
||||
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]
|
||||
assert current_line_field_values(tasks[0])[0]['reservation_id'] == 'R-OLD'
|
||||
assert current_line_field_values(tasks[1])[0].get('reservation_id') is None
|
||||
assert current_line_field_values(tasks[2])[0].get('reservation_id') is None
|
||||
|
||||
|
||||
def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app):
|
||||
"""目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RSV-BACKFILL-ALREADY-COMPLETE',
|
||||
user_id=1,
|
||||
source_type='eml',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
)
|
||||
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
_attach_existing_task_dynamic_order(
|
||||
task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
)
|
||||
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
@@ -1559,25 +1488,42 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
|
||||
|
||||
assert outcome['status'] == 'skipped'
|
||||
assert outcome['reason'] == 'target_already_complete'
|
||||
assert task.lines_json[0]['reservation_id'] == '1000140351'
|
||||
assert current_line_field_values(task)[0]['reservation_id'] == '1000140351'
|
||||
|
||||
|
||||
def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app):
|
||||
def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app, monkeypatch):
|
||||
"""已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
existing = ShippingNotice(
|
||||
task_no='SN-ORDER-RSV-UNSAFE-OPEN-001',
|
||||
existing = ShippingOrderTask(
|
||||
task_no='OT-ORDER-RSV-UNSAFE-OPEN-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
source_type='eml',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(
|
||||
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_result = {
|
||||
'status': 'exact_file',
|
||||
'blocking': True,
|
||||
'fingerprint_strength': 'strong',
|
||||
'fingerprint': 'unsafe-open-fingerprint',
|
||||
'fingerprint_version': 'shipping-v1',
|
||||
'components': {'po_number': '4510038672'},
|
||||
'content_fingerprint': 'unsafe-open-content',
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
|
||||
'allowed_actions': ['open_existing', 'force_create'],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
|
||||
lambda **_kwargs: dict(duplicate_result),
|
||||
)
|
||||
|
||||
document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351'
|
||||
db.session.commit()
|
||||
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
|
||||
@@ -1602,8 +1548,10 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
|
||||
assert result['opened_existing_count'] == 1
|
||||
assert result['pending_count'] == 0
|
||||
assert candidate.consumed_task_id == int(existing.id)
|
||||
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
|
||||
assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}]
|
||||
# 对账被 target_task_not_safe 跳过,当前 Extraction 订单行不得被改写。
|
||||
assert current_line_field_values(existing)[0]['part_number'] == 'P123456'
|
||||
assert current_line_field_values(existing)[0]['qty'] == 24
|
||||
assert current_line_field_values(existing)[0].get('reservation_id') is None
|
||||
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
|
||||
|
||||
|
||||
@@ -1637,25 +1585,41 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app)
|
||||
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app):
|
||||
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app, monkeypatch):
|
||||
"""exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
existing = ShippingNotice(
|
||||
task_no='SN-ORDER-RSV-UNVERIFIED-001',
|
||||
existing = ShippingOrderTask(
|
||||
task_no='OT-ORDER-RSV-UNVERIFIED-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
source_type='eml',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
_attach_existing_task_dynamic_order(
|
||||
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_result = {
|
||||
'status': 'exact_file',
|
||||
'blocking': True,
|
||||
'fingerprint_strength': 'strong',
|
||||
'fingerprint': 'unverified-open-fingerprint',
|
||||
'fingerprint_version': 'shipping-v1',
|
||||
'components': {'po_number': '4510038672'},
|
||||
'content_fingerprint': 'unverified-open-content',
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
|
||||
'allowed_actions': ['open_existing', 'force_create'],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
|
||||
lambda **_kwargs: dict(duplicate_result),
|
||||
)
|
||||
|
||||
document.extracted_text = (
|
||||
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351"
|
||||
)
|
||||
@@ -1686,7 +1650,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
|
||||
assert result['opened_existing_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
|
||||
assert 'reservation_id' not in (existing.lines_json[0] or {})
|
||||
assert current_line_field_values(existing)[0].get('reservation_id') is None
|
||||
|
||||
|
||||
def test_merge_chat_log_payload_requires_exact_turn_ownership(app):
|
||||
|
||||
@@ -8,7 +8,17 @@ backend/tests/test_shipping_notice_query_service.py
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingUploadAttempt,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.query_service import (
|
||||
TaskProjection,
|
||||
@@ -24,19 +34,44 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
|
||||
|
||||
|
||||
def test_frozen_order_projection_uses_snapshot_instead_of_current_extraction(monkeypatch):
|
||||
"""冻结后详情必须展示 Snapshot,不能因 Extraction 变化而改变订单内容。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
snapshot = SimpleNamespace(
|
||||
header_values_json={'header-field': 'PO-FROZEN'},
|
||||
schema_version=SimpleNamespace(definition_json={'fields': [
|
||||
{'field_id': 'header-field', 'field_code': 'customer_po_number', 'scope': 'header', 'sequence': 1},
|
||||
{'field_id': 'line-field', 'field_code': 'part_number', 'scope': 'line', 'sequence': 1},
|
||||
]}),
|
||||
lines=[SimpleNamespace(id=10, position=0, field_values_json={'line-field': 'PART-FROZEN'})],
|
||||
)
|
||||
task = SimpleNamespace(order_snapshot_id=77)
|
||||
monkeypatch.setattr(query_service.db.session, 'get', lambda model, identifier: snapshot)
|
||||
monkeypatch.setattr(query_service, 'current_header_field_values_or_empty', lambda _task: {'customer_po_number': 'PO-MUTABLE'})
|
||||
monkeypatch.setattr(query_service, 'current_line_field_values_or_empty', lambda _task: [{'part_number': 'PART-MUTABLE'}])
|
||||
|
||||
header, lines, display = query_service._order_values_for_projection(task)
|
||||
|
||||
assert header == {'customer_po_number': 'PO-FROZEN'}
|
||||
assert lines == [{'part_number': 'PART-FROZEN'}]
|
||||
assert display['line_fields'][0]['field_code'] == 'part_number'
|
||||
|
||||
|
||||
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
|
||||
"""task_no 与数字主键均应能解析到同一任务。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-QUERY-001",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-TEST-QUERY-001", user_id=1,
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
from app import db
|
||||
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
by_no = get_task_by_ref("SN-TEST-QUERY-001")
|
||||
by_no = get_task_by_ref("OT-TEST-QUERY-001")
|
||||
by_id = get_task_by_ref(str(task.id))
|
||||
assert by_no is not None
|
||||
assert by_id is not None
|
||||
@@ -50,26 +85,22 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
shortage = ShippingNotice(
|
||||
task_no="SN-FILTER-SHORTAGE",
|
||||
shortage = ShippingOrderTask(
|
||||
task_no="OT-FILTER-SHORTAGE", user_id=999999, status='processing',
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
user_id=999999,
|
||||
)
|
||||
ordinary = ShippingNotice(
|
||||
task_no="SN-FILTER-PARSE",
|
||||
ordinary = ShippingOrderTask(
|
||||
task_no="OT-FILTER-PARSE", user_id=2, status='processing',
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=2,
|
||||
)
|
||||
db.session.add_all([shortage, ordinary])
|
||||
db.session.commit()
|
||||
|
||||
rows = list_tasks_for_user(999999)
|
||||
|
||||
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
|
||||
assert [item["task_no"] for item in rows] == ["OT-FILTER-SHORTAGE"]
|
||||
|
||||
|
||||
def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
|
||||
@@ -78,7 +109,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual")
|
||||
ShippingOrderTask(task_no=f"OT-PAGE-{index:02d}", user_id=999999, source_type="direct_pdf")
|
||||
for index in range(1, 6)
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -106,8 +137,45 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", source_type="manual"),
|
||||
])
|
||||
uploaded = ShippingNotice.query.filter_by(task_no="SN-PAGE-FILTER-3").one()
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='PAGE_FILTER', display_name='Page filter', version=1, status='published',
|
||||
storage_bucket='test', storage_key='page-filter.xlsx', original_filename='page-filter.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='PAGE_FILTER', display_name='Page filter', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='PAGE_FILTER', display_name='Page filter')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64,
|
||||
)
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction.schema_version_id = version.id
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
artifact = ShippingExportArtifact(
|
||||
task_id=uploaded.id, artifact_no='ART-PAGE-FILTER-3', template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='d' * 64,
|
||||
file_path='test.xlsx', file_name='test.xlsx', file_checksum='e' * 64,
|
||||
file_size=1, status='ready',
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingUploadAttempt(
|
||||
artifact_id=artifact.id, attempt_no=1, mode='manual', status='succeeded',
|
||||
idempotency_key='IDEMP-PAGE-FILTER-3',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10)
|
||||
@@ -125,55 +193,47 @@ def test_task_export_error_message_distinct_for_missing_path(app):
|
||||
empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
|
||||
assert task_export_error_message(empty) == "export file not found"
|
||||
|
||||
missing = ShippingNotice(
|
||||
task_no="SN-MISSING-FILE",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
|
||||
)
|
||||
assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。
|
||||
# 已持久化任务但没有可用 Artifact 时,统一视为磁盘产物缺失。
|
||||
missing = ShippingNotice(task_no="SN-MISSING-FILE", source_type="manual")
|
||||
missing.id = 999999
|
||||
assert task_export_error_message(missing) == "export file missing on disk"
|
||||
|
||||
|
||||
def test_task_projection_tool_strips_internal_fields(app):
|
||||
"""TOOL 投影应剔除 Agent 不应复述的内部状态字段。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-TOOL",
|
||||
review_status="align_review",
|
||||
match_status="pending",
|
||||
pending_human_reason="rpa_pending",
|
||||
error_message="boom",
|
||||
source_type="manual",
|
||||
customer_name="ACME",
|
||||
lines_json=[{"sku": "A001"}],
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-PROJ-TOOL", user_id=1, review_status="align_review",
|
||||
pending_human_reason="rpa_pending", error_message="boom",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
data = serialize_task(task, TaskProjection.TOOL)
|
||||
assert data["task_no"] == "SN-PROJ-TOOL"
|
||||
assert data["task_no"] == "OT-PROJ-TOOL"
|
||||
assert data["customer_name"] is None
|
||||
assert data["lines"] == []
|
||||
assert not TOOL_TASK_DATA_OMIT.intersection(data.keys())
|
||||
|
||||
|
||||
def test_task_projection_internal_keeps_status_fields(app):
|
||||
"""TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。"""
|
||||
def test_task_projection_internal_keeps_stage_fields(app):
|
||||
"""TOOL_INTERNAL 保留 OT 流程阶段字段,复核旧投影不再作为 Notice 字段。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-INT",
|
||||
review_status="parse_review",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-PROJ-INT", user_id=1,
|
||||
stage="parse_review",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
|
||||
assert "review_status" in data
|
||||
assert data["review_status"] == "parse_review"
|
||||
assert data["current_step"] == "parse_review"
|
||||
|
||||
|
||||
|
||||
def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
|
||||
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CONV-1",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-CONV-1", user_id=1,
|
||||
conversation_id="conv-abc",
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
from app import db
|
||||
|
||||
@@ -182,7 +242,7 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
|
||||
|
||||
resolved = resolve_task_from_payload({"conversation_id": "conv-abc"})
|
||||
assert resolved is not None
|
||||
assert resolved.task_no == "SN-CONV-1"
|
||||
assert resolved.task_no == "OT-CONV-1"
|
||||
|
||||
assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01"
|
||||
|
||||
@@ -194,15 +254,15 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
|
||||
|
||||
db.session.add_all(
|
||||
[
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-1",
|
||||
ShippingOrderTask(
|
||||
task_no="OT-CONV-MULTI-1", user_id=1,
|
||||
conversation_id="conv-multi",
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-2",
|
||||
ShippingOrderTask(
|
||||
task_no="OT-CONV-MULTI-2", user_id=1,
|
||||
conversation_id="conv-multi",
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -211,10 +271,10 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
|
||||
assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None
|
||||
|
||||
resolved = resolve_task_from_payload(
|
||||
{"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"}
|
||||
{"conversation_id": "conv-multi", "task_id": "OT-CONV-MULTI-1"}
|
||||
)
|
||||
assert resolved is not None
|
||||
assert resolved.task_no == "SN-CONV-MULTI-1"
|
||||
assert resolved.task_no == "OT-CONV-MULTI-1"
|
||||
|
||||
|
||||
def test_task_can_handle_only_creator(app):
|
||||
@@ -252,24 +312,13 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
get_task_visible_to_user,
|
||||
)
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no="SN-NULL-OWNER",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-OWNED",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
db.session.add_all([orphan, owned])
|
||||
owned = ShippingOrderTask(task_no="OT-OWNED", user_id=7, source_type="direct_pdf")
|
||||
db.session.add(owned)
|
||||
db.session.commit()
|
||||
|
||||
assert get_task_for_user("SN-NULL-OWNER", 7) is None
|
||||
assert get_task_for_user("SN-OWNED", 7) is not None
|
||||
assert get_task_for_user("SN-OWNED", 8) is None
|
||||
assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None
|
||||
assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None
|
||||
assert get_task_for_user("OT-OWNED", 7) is not None
|
||||
assert get_task_for_user("OT-OWNED", 8) is None
|
||||
assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
|
||||
|
||||
|
||||
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
@@ -278,24 +327,21 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-ENRICH-1",
|
||||
review_status="parse_review",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-ENRICH-1", user_id=11,
|
||||
stage="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=11,
|
||||
export_file_name="a.xlsx",
|
||||
export_file_path="/tmp/a.xlsx",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(task, viewer_user_id=11)
|
||||
assert data["todo_category"] == "review"
|
||||
assert data["todo_category"] == "in_progress"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
assert data["ui_state"]["checkpoint"]["code"] == "parse_review"
|
||||
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
|
||||
assert data["ui_state"]["checkpoint"]["code"] == "order_freeze"
|
||||
assert data["artifact_summary"] is None
|
||||
|
||||
no_viewer = serialize_task_summary(task)
|
||||
assert "can_handle" not in no_viewer
|
||||
@@ -305,28 +351,58 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||||
"""同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch
|
||||
from app.models import (
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11)
|
||||
second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11)
|
||||
first_task = ShippingOrderTask(task_no='OT-NOTICE-1', user_id=11)
|
||||
second_task = ShippingOrderTask(task_no='OT-NOTICE-2', user_id=11)
|
||||
db.session.add_all([first_task, second_task]); db.session.flush()
|
||||
first_snapshot = ShippingOrderSnapshot(
|
||||
task_id=first_task.id, extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
second_snapshot = ShippingOrderSnapshot(
|
||||
task_id=second_task.id, extraction_id=2, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add_all([first_snapshot, second_snapshot]); db.session.flush()
|
||||
first_snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=first_snapshot.id, position=0, line_no=1, field_values_json={},
|
||||
)
|
||||
second_snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=second_snapshot.id, position=0, line_no=1, field_values_json={},
|
||||
)
|
||||
db.session.add_all([first_snapshot_line, second_snapshot_line]); db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11,
|
||||
order_task_id=first_task.id,
|
||||
)
|
||||
second = ShippingNotice(
|
||||
task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11,
|
||||
order_task_id=second_task.id,
|
||||
)
|
||||
first_task.order_snapshot_id = first_snapshot.id
|
||||
second_task.order_snapshot_id = second_snapshot.id
|
||||
db.session.add_all([first, second]); db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingNoticeLine(
|
||||
notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST',
|
||||
reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'},
|
||||
notice_id=first.id, snapshot_line_id=first_snapshot_line.id, position=1, line_no=1,
|
||||
part_number='PART-FIRST', reservation_id='RES-1', required_qty='12', field_values_json={},
|
||||
),
|
||||
ShippingNoticeLine(
|
||||
notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND',
|
||||
reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'},
|
||||
notice_id=second.id, snapshot_line_id=second_snapshot_line.id, position=1, line_no=1,
|
||||
part_number='PART-SECOND', reservation_id='RES-2', required_qty='8', field_values_json={},
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready',
|
||||
available_qty='20', shortage_qty='0', is_current=True,
|
||||
task_id=first_task.id, snapshot_line_id=first_snapshot_line.id, line_no=1,
|
||||
match_result='matched', inventory_status='ready', available_qty='20', shortage_qty='0', is_current=True,
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready',
|
||||
available_qty='9', shortage_qty='0', is_current=True,
|
||||
task_id=second_task.id, snapshot_line_id=second_snapshot_line.id, line_no=1,
|
||||
match_result='matched', inventory_status='ready', available_qty='9', shortage_qty='0', is_current=True,
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -335,7 +411,7 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||||
|
||||
assert data['business_no'] == 'WVC26082301'
|
||||
assert data['notice_line_summary'] == [{
|
||||
'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST',
|
||||
'line_no': 1, 'part_number': 'PART-FIRST',
|
||||
'customer_part_number': None,
|
||||
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
|
||||
'shortage_qty': '0', 'inventory_status': 'ready',
|
||||
@@ -358,8 +434,8 @@ def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
|
||||
other = with_po('SN-GROUP-4', 'WYC26082499', 99)
|
||||
db.session.add_all([first, second, no_business, other]); db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}),
|
||||
ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}),
|
||||
ShippingNoticeLine(notice_id=first.id, snapshot_line_id=1, position=1, line_no=1, part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={}),
|
||||
ShippingNoticeLine(notice_id=second.id, snapshot_line_id=2, position=1, line_no=1, part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={}),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
@@ -387,9 +463,6 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app):
|
||||
|
||||
first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11)
|
||||
db.session.add(first); db.session.flush()
|
||||
first.upload_status = 'failed'
|
||||
first.upload_error_code = 'RPA_UPLOAD_FAILED'
|
||||
first.upload_error_message = '货代平台拒绝:凭证无效'
|
||||
db.session.commit()
|
||||
|
||||
original_header_reader = query_service.current_header_field_values_or_empty
|
||||
@@ -401,9 +474,10 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app):
|
||||
|
||||
item = result['items'][0]
|
||||
assert item['business_no'] == 'WYC26082401'
|
||||
assert item['upload_status'] == 'failed'
|
||||
assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED'
|
||||
assert item['upload_error_message'] == '货代平台拒绝:凭证无效'
|
||||
# 没有 UploadAttempt 就没有上传结果,Notice 历史投影不再作为事实来源。
|
||||
assert item['upload_status'] is None
|
||||
assert item['upload_error_code'] is None
|
||||
assert item['upload_error_message'] is None
|
||||
|
||||
|
||||
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
|
||||
@@ -413,20 +487,23 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti
|
||||
from app.models import ShippingOrderSnapshot
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11)
|
||||
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11)
|
||||
first_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-1', user_id=11, source_type='direct_pdf')
|
||||
second_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-2', user_id=11, source_type='direct_pdf')
|
||||
db.session.add_all([first_task, second_task]); db.session.flush()
|
||||
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11, order_task_id=first_task.id)
|
||||
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11, order_task_id=second_task.id)
|
||||
db.session.add_all([first, second]); db.session.flush()
|
||||
for task in (first, second):
|
||||
for task, owner in ((first, first_task), (second, second_task)):
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=task.id,
|
||||
task_id=owner.id,
|
||||
extraction_id=owner.id,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
customer_po_number='ZNB-16754796',
|
||||
)
|
||||
db.session.add(snapshot); db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
owner.order_snapshot_id = snapshot.id
|
||||
db.session.commit()
|
||||
|
||||
original_header_reader = query_service.current_header_field_values_or_empty
|
||||
@@ -504,46 +581,86 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
|
||||
|
||||
|
||||
def test_list_my_todos_and_count_buckets(app):
|
||||
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
|
||||
"""待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
owner = 55
|
||||
review = ShippingNotice(
|
||||
task_no="SN-TODO-REVIEW",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
review = ShippingOrderTask(
|
||||
task_no="OT-TODO-REVIEW",
|
||||
pending_human_reason="rpa_exhausted",
|
||||
source_type="direct_pdf",
|
||||
user_id=owner,
|
||||
)
|
||||
upload_order = ShippingOrderTask(
|
||||
task_no="OT-TODO-UPLOAD", source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
done_order = ShippingOrderTask(
|
||||
task_no="OT-TODO-DONE", source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-TODO-UPLOAD",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/u.xlsx",
|
||||
export_file_name="u.xlsx",
|
||||
)
|
||||
done = ShippingNotice(
|
||||
task_no="SN-TODO-DONE",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
upload_status="uploaded",
|
||||
)
|
||||
other = ShippingNotice(
|
||||
task_no="SN-TODO-OTHER",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
other = ShippingOrderTask(
|
||||
task_no="OT-TODO-OTHER",
|
||||
pending_human_reason="rpa_exhausted",
|
||||
source_type="direct_pdf",
|
||||
user_id=99,
|
||||
)
|
||||
db.session.add_all([review, upload, done, other])
|
||||
db.session.add_all([review, upload_order, done_order, upload, done, other])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='TODO', display_name='Todo', version=1, status='published',
|
||||
storage_bucket='test', storage_key='todo.xlsx', original_filename='todo.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='TODO', display_name='Todo', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='TODO', display_name='Todo')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
upload.order_task_id = upload_order.id
|
||||
done.order_task_id = done_order.id
|
||||
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
|
||||
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
)
|
||||
db.session.add(artifact)
|
||||
return artifact
|
||||
|
||||
upload_artifact = add_artifact(upload, artifact_no='ART-TODO-UPLOAD', status='ready')
|
||||
done_artifact = add_artifact(done, artifact_no='ART-TODO-DONE', status='uploaded')
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=20)
|
||||
assert pending["total"] == 2
|
||||
assert {item["task_no"] for item in pending["items"]} == {
|
||||
"SN-TODO-REVIEW",
|
||||
"OT-TODO-REVIEW",
|
||||
"SN-TODO-UPLOAD",
|
||||
}
|
||||
assert all(item["can_handle"] is True for item in pending["items"])
|
||||
@@ -560,7 +677,7 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
admin_pending = list_my_todos(owner, bucket="pending", is_admin=True)
|
||||
assert admin_pending["total"] >= 3
|
||||
other_item = next(
|
||||
item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER"
|
||||
item for item in admin_pending["items"] if item["task_no"] == "OT-TODO-OTHER"
|
||||
)
|
||||
assert other_item["can_handle"] is False
|
||||
|
||||
@@ -661,6 +778,75 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil
|
||||
assert original.case_no not in review_case_nos
|
||||
|
||||
|
||||
def test_reparse_document_with_reviewable_candidate_stays_order_review(app):
|
||||
"""
|
||||
回归 doc67:重解析(reparse_of_run_id 非空)终态切换未跑时,Stream.current_case
|
||||
仍是空的旧 Case(candidate_id=None),但同 Document 已存在当前可复核 Candidate。
|
||||
此时工作台必须显示「订单复核」,不能被空的旧 Case 压回「接收解析」。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderCandidate
|
||||
from app.services.shipping_notice.order_extraction_plan import (
|
||||
ensure_order_extraction_plan,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
reparse_case_document,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_run_review_cases,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DOC67-REPARSE')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
# 初始解析:无 Candidate 的 Case 成为当前版本(case14 空旧 Case 语义)。
|
||||
original = ensure_run_review_cases(run=source)[0]
|
||||
assert original.candidate_id is None
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
|
||||
replacement_run, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement_run)
|
||||
# 重解析 Run 产生当前可复核 Candidate(candidate13 语义);finalizer 未切换当前 Case。
|
||||
db.session.add(ShippingOrderCandidate(
|
||||
candidate_no='CAND-DOC67',
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=document.id,
|
||||
candidate_key='doc67-reparse',
|
||||
order_extraction_run_id=replacement_run.id,
|
||||
))
|
||||
db.session.commit()
|
||||
for unit in replacement_run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
db.session.commit()
|
||||
replacement = ensure_run_review_cases(run=replacement_run)[0]
|
||||
# 关键:不调用 activate_review_case,模拟重解析终态切换未跑 → case19 未成为当前。
|
||||
assert replacement.candidate_id is not None
|
||||
assert replacement.case_no != original.case_no
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
review_case_nos = {
|
||||
item['review_case_no']
|
||||
for item in pending['items']
|
||||
if item.get('item_kind') == 'review_case'
|
||||
}
|
||||
# 当前 Case 仍是空的旧 Case;同 Document 已有可复核 Candidate → 必须订单复核。
|
||||
assert original.case_no in review_case_nos
|
||||
hit = next(item for item in pending['items'] if item.get('review_case_no') == original.case_no)
|
||||
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
|
||||
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_open_review_case_without_current_candidate_enters_intake_parse(app):
|
||||
"""无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。"""
|
||||
with app.app_context():
|
||||
@@ -793,11 +979,10 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
|
||||
# 520 > 旧 limit(500),用于证明截断不再作为 total 来源。
|
||||
total_tasks = 520
|
||||
tasks = [
|
||||
ShippingNotice(
|
||||
task_no=f"SN-TODO-PAGE-{index:04d}",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
ShippingOrderTask(
|
||||
task_no=f"OT-TODO-PAGE-{index:04d}",
|
||||
pending_human_reason="rpa_exhausted",
|
||||
source_type="direct_pdf",
|
||||
user_id=owner,
|
||||
)
|
||||
for index in range(total_tasks)
|
||||
@@ -823,79 +1008,74 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
|
||||
assert far["items"] == []
|
||||
|
||||
|
||||
def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
def test_todo_category_sql_matches_formal_notice_facts(app):
|
||||
"""
|
||||
轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。
|
||||
|
||||
断言意图:UNION 分页下推的 SQL 分类不得漂移口径。
|
||||
"""
|
||||
with app.app_context():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import (
|
||||
_task_todo_category_sql_expr,
|
||||
_todo_category_from_task_row,
|
||||
count_my_todos,
|
||||
list_my_todos,
|
||||
task_todo_category,
|
||||
)
|
||||
|
||||
owner = 88
|
||||
fixtures = [
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-REVIEW",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-UPLOAD",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/lw.xlsx",
|
||||
export_file_name="lw.xlsx",
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-SHORTAGE",
|
||||
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-DONE",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-PROGRESS",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
order_tasks = [
|
||||
ShippingOrderTask(task_no=f"OT-LW-{key}", source_type="direct_pdf", user_id=owner)
|
||||
for key in ('UPLOAD', 'DONE')
|
||||
]
|
||||
db.session.add_all(fixtures)
|
||||
fixtures = [
|
||||
ShippingNotice(task_no="SN-LW-UPLOAD", source_type="manual", user_id=owner),
|
||||
ShippingNotice(task_no="SN-LW-DONE", source_type="manual", user_id=owner),
|
||||
ShippingNotice(task_no="SN-LW-PROGRESS", source_type="manual", user_id=owner),
|
||||
]
|
||||
db.session.add_all([*order_tasks, *fixtures])
|
||||
db.session.flush()
|
||||
fixtures[0].order_task_id = order_tasks[0].id
|
||||
fixtures[1].order_task_id = order_tasks[1].id
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='LW', display_name='LW', version=1, status='published', storage_bucket='test',
|
||||
storage_key='lw.xlsx', original_filename='lw.xlsx', file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='LW', display_name='LW', version=1, status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='LW', display_name='LW')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
def add_artifact(notice, artifact_no, status):
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
)
|
||||
db.session.add(artifact)
|
||||
return artifact
|
||||
|
||||
done_artifact = add_artifact(fixtures[1], 'ART-LW-DONE', 'uploaded')
|
||||
add_artifact(fixtures[0], 'ART-LW-UPLOAD', 'ready')
|
||||
db.session.flush()
|
||||
db.session.add(ShippingUploadAttempt(
|
||||
artifact_id=done_artifact.id, attempt_no=1, mode='manual', status='succeeded',
|
||||
idempotency_key='lw-done-upload',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
for task in fixtures:
|
||||
row = SimpleNamespace(
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
order_snapshot_id=task.order_snapshot_id,
|
||||
current_order_extraction_id=task.current_order_extraction_id,
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
upload_status=task.upload_status,
|
||||
)
|
||||
expected = task_todo_category(task)
|
||||
# 轻量路径与 ORM 路径同分类。
|
||||
assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected
|
||||
# SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。
|
||||
sql_category = (
|
||||
db.session.query(category_expr)
|
||||
@@ -905,12 +1085,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
assert sql_category == expected
|
||||
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
|
||||
assert pending["total"] == 3
|
||||
assert pending["total"] == 1
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["pending"] == 3
|
||||
assert counts["pending"] == 1
|
||||
assert counts["done"] == 1
|
||||
assert counts["processing"] == 1
|
||||
assert counts["total_pending_badge"] == 3
|
||||
assert counts["total_pending_badge"] == 1
|
||||
|
||||
|
||||
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
@@ -919,9 +1099,8 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import serialize_task_detail
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11,
|
||||
export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-WORKBENCH-VIEW", source_type="direct_pdf", user_id=11,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -934,13 +1113,12 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
|
||||
for key in (
|
||||
"lines", "order_header", "order_header_fields", "order_line_fields",
|
||||
"events", "field_conflicts",
|
||||
):
|
||||
assert key in full
|
||||
assert key not in wb
|
||||
# workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。
|
||||
assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW"
|
||||
assert wb["ui_state"]["task_no"] == "OT-WORKBENCH-VIEW"
|
||||
assert wb["ui_state"]["stage_context"] is not None
|
||||
assert wb["artifact_summary"]["export_file_name"] == "n.xlsx"
|
||||
assert wb["artifact_summary"] is None
|
||||
assert "notice_line_summary" in wb
|
||||
assert "export_artifacts" in wb
|
||||
assert "export_artifacts" not in wb
|
||||
@@ -56,6 +56,24 @@ def test_reservation_contract_only_accepts_five_or_ten_digits():
|
||||
assert not is_valid_reservation_id("12345678901", numeric_only=True)
|
||||
|
||||
|
||||
def test_validated_reservation_id_strips_optional_parenthesized_note():
|
||||
"""完整数字可带括号备注;括号内容不是预约单号,普通尾随文本仍拒绝。"""
|
||||
assert validated_reservation_id("3000112934(PENROSE)") == "3000112934"
|
||||
assert validated_reservation_id("3000112934(PENROSE)") == "3000112934"
|
||||
assert validated_reservation_id("R2 @3000112934") == "3000112934"
|
||||
assert validated_reservation_id("R2 @3000112934(PENROSE)") == "3000112934"
|
||||
assert validated_reservation_id("R2 @3000112934 PENROSE") == ""
|
||||
assert validated_reservation_id("3000112934 PENROSE") == ""
|
||||
assert validated_reservation_id("abc3000112934(PENROSE)") == ""
|
||||
assert validated_reservation_id("00011293") == ""
|
||||
assert validated_reservation_id("30001129345") == ""
|
||||
|
||||
|
||||
def test_validated_reservation_id_rejects_amount_text_as_numeric_token():
|
||||
"""金额行中的五位整数片段不能被当成 Reservation ID。"""
|
||||
assert validated_reservation_id("941.76 28,252.80") == ""
|
||||
|
||||
|
||||
def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present():
|
||||
"""专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。"""
|
||||
assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{
|
||||
|
||||
@@ -8,15 +8,22 @@ tests/test_shipping_notice_state_machine.py
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_READY_EXPORT,
|
||||
CP_UPLOADED,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
checkpoint_kind_for,
|
||||
resolve_task_ui_state,
|
||||
resolve_task_ui_state_from_fields,
|
||||
validate_registry,
|
||||
)
|
||||
|
||||
|
||||
def test_validate_registry_has_no_errors() -> None:
|
||||
@@ -34,13 +41,21 @@ def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
"""pending_review + parse_review 应映射为 must_human / parse_review。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-PARSE",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-SM-PARSE",
|
||||
user_id=1,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=None,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
has_dynamic_order_lines=False,
|
||||
)
|
||||
assert ui.checkpoint == CP_PARSE_REVIEW
|
||||
assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN
|
||||
|
||||
@@ -48,32 +63,44 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
"""matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-EXPORT",
|
||||
source_type="manual",
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=1,
|
||||
match_status=None,
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
has_dynamic_order_lines=False,
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert not hasattr(ui, 'human_options')
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
def test_resolve_task_ui_state_uploaded_complete(app, monkeypatch) -> None:
|
||||
"""upload_status=uploaded 应为 complete。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-UPLOADED",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
task = SimpleNamespace(upload_status="uploaded", lifecycle_status="active")
|
||||
# [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
lambda _task: True,
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=1,
|
||||
match_status=None,
|
||||
export_file_path=None,
|
||||
has_dynamic_order_lines=False,
|
||||
upload_req_task=task,
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
|
||||
|
||||
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
def test_resolve_with_mocked_simple_namespace_attributes(monkeypatch) -> None:
|
||||
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
|
||||
task = SimpleNamespace(
|
||||
upload_status="uploaded",
|
||||
@@ -87,6 +114,27 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
current_order_extraction_id=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
# [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
lambda _task: True,
|
||||
)
|
||||
ui = resolve_task_ui_state(task) # type: ignore[arg-type]
|
||||
assert ui.checkpoint_kind == CheckpointKind.COMPLETE
|
||||
assert ui.checkpoint == CP_UPLOADED
|
||||
|
||||
|
||||
def test_order_task_inventory_checkpoint_uses_structured_facts(monkeypatch) -> None:
|
||||
"""OT 库存 JSON 为空时,状态机仍须按 Link/File/Match 事实进入导出准备。"""
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import state_machine
|
||||
|
||||
task = ShippingOrderTask(task_no='OT-SM-STRUCTURED', user_id=1, stage='inventory_matching')
|
||||
monkeypatch.setattr(state_machine, '_order_task_inventory_facts', lambda _task: {
|
||||
'inventory_ready': True,
|
||||
'match_complete': True,
|
||||
'match_sufficient': True,
|
||||
'has_shortage': False,
|
||||
})
|
||||
|
||||
assert state_machine.resolve_task_ui_state(task).checkpoint == CP_READY_EXPORT
|
||||
@@ -8,9 +8,21 @@ tests/test_shipping_notice_stp_acceptance.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingNotice, User
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
@@ -21,7 +33,32 @@ from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_aft
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
|
||||
def _seed_export_artifact_view(monkeypatch) -> None:
|
||||
"""Excel 就绪事实只能由正式 Artifact 裁决:屏蔽旧 Notice 文件投影。
|
||||
|
||||
生产函数分别经 upload_attempt_service(state_machine.resolve_task_ui_state 本地导入)与
|
||||
fulfillment_workflow(模块级 latest_export_artifact / latest_upload_attempt)读取导出产物;
|
||||
两处命名空间均需桩化,避免触达真实 Artifact 表。
|
||||
"""
|
||||
artifact = SimpleNamespace(id=0, file_path="/tmp/stp-export.xlsx", file_name="stp-export.xlsx", status="ready")
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.upload_attempt_service.latest_export_artifact",
|
||||
lambda _task: artifact,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.latest_export_artifact",
|
||||
lambda _task: artifact,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.upload_attempt_service.latest_upload_attempt",
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.latest_upload_attempt",
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
|
||||
def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
|
||||
@@ -30,7 +67,7 @@ def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None:
|
||||
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None:
|
||||
"""场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -38,13 +75,15 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-WAIT-UPLOAD",
|
||||
business_no="SN-STP-WAIT-UPLOAD",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/stp-export.xlsx",
|
||||
export_file_name="stp-export.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
result = auto_progress({"task_id": task.task_no, "source": "system"})
|
||||
assert result["status"] == "ok"
|
||||
assert result.get("checkpoint") == CP_EXPORT_READY
|
||||
@@ -59,11 +98,20 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
from app import db
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MUST-HUMAN",
|
||||
owner = ShippingOrderTask(
|
||||
task_no="OT-STP-MUST-HUMAN",
|
||||
user_id=1,
|
||||
source_type="direct_pdf",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MUST-HUMAN",
|
||||
business_no="SN-STP-MUST-HUMAN",
|
||||
source_type="manual",
|
||||
order_task_id=owner.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -83,15 +131,14 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-RPA-ON",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
export_file_path="/tmp/already.xlsx",
|
||||
export_file_name="already.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
upload_calls: list[dict] = []
|
||||
|
||||
def _fake_upload(payload):
|
||||
@@ -124,15 +171,14 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-NO-RPA",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
export_file_path="/tmp/already.xlsx",
|
||||
export_file_name="already.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
upload_calls: list[dict] = []
|
||||
|
||||
def _fake_upload(payload):
|
||||
@@ -158,19 +204,22 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
|
||||
"""场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from types import SimpleNamespace
|
||||
|
||||
owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM", user_id=1, source_type="direct_pdf")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MANUAL-CFM",
|
||||
business_no="SN-STP-MANUAL-CFM",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
inventory_source_status="confirmed",
|
||||
inventory_source_code="SRC1",
|
||||
order_task_id=owner.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42)
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -231,22 +280,22 @@ def test_upload_to_freight_manual_confirm_ignores_inventory_source_stability(app
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from types import SimpleNamespace
|
||||
|
||||
owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM-UNSTABLE", user_id=1, source_type="direct_pdf")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MANUAL-CFM-UNSTABLE",
|
||||
business_no="SN-STP-MANUAL-CFM-UNSTABLE",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_code="SRC1",
|
||||
inventory_connector_type="crane",
|
||||
inventory_source_config_version="stale-version",
|
||||
inventory_routing_fingerprint="stale-fingerprint",
|
||||
order_task_id=owner.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42)
|
||||
|
||||
# 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。
|
||||
@@ -302,19 +351,22 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
|
||||
"""关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from types import SimpleNamespace
|
||||
|
||||
owner = ShippingOrderTask(task_no="OT-STP-CLOSE-FAIL", user_id=1, source_type="direct_pdf")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-CLOSE-FAIL",
|
||||
business_no="SN-STP-CLOSE-FAIL",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
inventory_source_status="confirmed",
|
||||
inventory_source_code="SRC1",
|
||||
order_task_id=owner.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
|
||||
_seed_export_artifact_view(monkeypatch)
|
||||
|
||||
attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42)
|
||||
bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending")
|
||||
|
||||
@@ -388,28 +440,76 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
db.session.add_all([owner, admin])
|
||||
db.session.flush()
|
||||
|
||||
# 复核系列(mine / other)以 Notice 挂接 OT,复核事实读取 OT 字段。
|
||||
mine_owner = ShippingOrderTask(
|
||||
task_no="OT-STP-OWN",
|
||||
user_id=owner.id,
|
||||
source_type="direct_pdf",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
upload_owner = ShippingOrderTask(task_no="OT-STP-UPLOAD", user_id=owner.id, source_type="direct_pdf")
|
||||
other_owner = ShippingOrderTask(
|
||||
task_no="OT-STP-OTHER",
|
||||
user_id=admin.id,
|
||||
source_type="direct_pdf",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add_all([mine_owner, upload_owner, other_owner])
|
||||
db.session.flush()
|
||||
|
||||
mine = ShippingNotice(
|
||||
task_no="SN-STP-OWN",
|
||||
user_id=owner.id,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
order_task_id=mine_owner.id,
|
||||
)
|
||||
waiting_upload = ShippingNotice(
|
||||
task_no="SN-STP-UPLOAD",
|
||||
user_id=owner.id,
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/own.xlsx",
|
||||
export_file_name="own.xlsx",
|
||||
order_task_id=upload_owner.id,
|
||||
)
|
||||
other = ShippingNotice(
|
||||
task_no="SN-STP-OTHER",
|
||||
user_id=admin.id,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
order_task_id=other_owner.id,
|
||||
)
|
||||
db.session.add_all([mine, waiting_upload, other])
|
||||
db.session.flush()
|
||||
|
||||
# manual_upload 分类必须由正式 Excel Artifact 裁决。
|
||||
template = ShippingExcelTemplate(
|
||||
template_code="STP_TP", display_name="STP template", version=1, status="published",
|
||||
storage_bucket="test", storage_key="test/stp.xlsx", original_filename="stp.xlsx",
|
||||
file_checksum="a" * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code="STP_PF", display_name="STP profile", version=1, status="published",
|
||||
file_format="xlsx", definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code="STP_SCHEMA", display_name="STP schema")
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status="published", definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash="b" * 64, status="accepted",
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no="ART-STP-UPLOAD", task_id=waiting_upload.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum="c" * 64,
|
||||
file_path="/tmp/stp-own.xlsx", file_name="stp-own.xlsx",
|
||||
file_checksum="d" * 64, file_size=1, status="ready",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_tools.py
|
||||
|
||||
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
|
||||
依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。
|
||||
依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。
|
||||
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
|
||||
"""
|
||||
|
||||
@@ -13,16 +13,32 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
|
||||
ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
|
||||
ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
Agent,
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
ShippingCustomer,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
|
||||
|
||||
def _tool_headers(app):
|
||||
@@ -34,46 +50,63 @@ def _tool_headers(app):
|
||||
}
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
def _seed_test_user(*, username: str) -> int:
|
||||
"""创建测试用户并返回主键,供 OT 建单与能力强令牌使用。"""
|
||||
user = User(username=username, email=f"{username}@example.test", password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
return int(user.id)
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
|
||||
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
configs = [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()]
|
||||
saved = order_schema_service.save_draft(
|
||||
draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
|
||||
field_ids = {
|
||||
str(item['field_code']): str(item['field_id'])
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
configs = [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()]
|
||||
saved = order_schema_service.save_draft(
|
||||
draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None,
|
||||
)
|
||||
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted',
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}
|
||||
for code, value in values.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_status='accepted',
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_id=decision.id,
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
@@ -81,14 +114,14 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
# RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时
|
||||
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'],
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=task.order_data_version or 1,
|
||||
rule_versions_json={'fulfillment_policy': {
|
||||
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
|
||||
'definition': {'field_bindings': [
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'},
|
||||
]},
|
||||
}},
|
||||
header_values_json={},
|
||||
@@ -96,26 +129,41 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id,
|
||||
snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id,
|
||||
qty=quantity, field_values_json={
|
||||
str(fields['part_number']['id']): part_number,
|
||||
str(fields['reservation_id']['id']): reservation_id,
|
||||
str(fields['qty']['id']): quantity,
|
||||
str(field_ids['part_number']): part_number,
|
||||
str(field_ids['reservation_id']): reservation_id,
|
||||
str(field_ids['qty']): quantity,
|
||||
},
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _confirm_test_task_customer(task: ShippingOrderTask) -> None:
|
||||
"""为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。"""
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name='RPA 直接回调测试客户', short_code='RPC', status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
|
||||
app.config["INTEGRATION_API_KEY"] = ""
|
||||
user_id = _seed_test_user(username='auth-dedicated')
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
@@ -126,11 +174,12 @@ def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client):
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "integration-secret"
|
||||
user_id = _seed_test_user(username='auth-integration')
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
@@ -145,7 +194,7 @@ def test_shipping_notice_tool_auth_reports_missing_config(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "any"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf"},
|
||||
)
|
||||
|
||||
assert res.status_code == 503
|
||||
@@ -157,7 +206,7 @@ def test_parse_notice_tool_is_removed(app, client):
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=_tool_headers(app),
|
||||
json={"task_id": "SN-REMOVED"},
|
||||
json={"task_id": "OT-REMOVED"},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
@@ -179,14 +228,14 @@ def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
|
||||
)
|
||||
|
||||
result = fulfillment_workflow.generate_excel({
|
||||
'task_id': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'task_id': 'OT-FORMAL-EXCEL-ONLY',
|
||||
'operator_id': 7,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
})
|
||||
|
||||
assert result['status'] == 'running'
|
||||
assert submitted == {
|
||||
'task_no': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'task_no': 'OT-FORMAL-EXCEL-ONLY',
|
||||
'trigger': 'tool_api_generate_excel',
|
||||
'expected_version': None,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
@@ -222,20 +271,36 @@ def test_match_notice_lines_reports_progress():
|
||||
|
||||
|
||||
def test_contract_get_task_status_accepts_task_no_anchor(app, client):
|
||||
"""契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
|
||||
"""契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
|
||||
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret"
|
||||
user_id = _seed_test_user(username='status-anchor')
|
||||
agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor')
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
session_id = session.session_id
|
||||
agent_id = int(agent.id)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id,
|
||||
"raw_content": "客户:ACME 料号A001 x 10"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id)
|
||||
|
||||
status_res = client.post(
|
||||
"/api/shipping-notice/tools/get_task_status",
|
||||
headers=headers,
|
||||
json={"task_no": task_id},
|
||||
json={"task_no": task_id, "shipping_chat_capability_token": token},
|
||||
)
|
||||
data = status_res.get_json()
|
||||
|
||||
@@ -273,12 +338,11 @@ def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-HTTP-CONFIRM-SRC",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-HTTP-CONFIRM-SRC",
|
||||
user_id=1,
|
||||
source_type="eml",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -286,7 +350,7 @@ def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/confirm_inventory_source",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
|
||||
@@ -304,91 +368,13 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords():
|
||||
assert "match_inventory" not in spec_text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"])
|
||||
def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
|
||||
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
# These decisions must never reopen manual mapping or mutate the task.
|
||||
assert body["status"] == "failed"
|
||||
assert "已发布解析方案" in body["message"]
|
||||
|
||||
|
||||
def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path):
|
||||
"""重新上传库存只重置正式库存结果,不进入任务级字段映射。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUPLOAD-INVENTORY",
|
||||
source_type="manual",
|
||||
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
|
||||
match_status="fulfillable",
|
||||
line_results_json=[{"part_number": "A001"}],
|
||||
shortage_json={"lines": []},
|
||||
export_file_path=str(tmp_path / "shipment.xlsx"),
|
||||
export_file_name="shipment.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-REUPLOAD-001",
|
||||
storage_path=str(tmp_path / "inventory.xlsx"),
|
||||
source_file_name="inventory.xlsx",
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
link = ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
link_role="owner",
|
||||
)
|
||||
db.session.add(link)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["status"] == "needs_human"
|
||||
assert body["checkpoint"] == "upload_req"
|
||||
assert "human_options" not in body
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
|
||||
assert link.is_active is False
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
assert task.line_results_json is None
|
||||
assert task.shortage_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
|
||||
|
||||
def test_parse_inventory_from_chat_text_route_is_removed(app, client):
|
||||
"""正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。"""
|
||||
headers = _tool_headers(app)
|
||||
parse_inv = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
|
||||
)
|
||||
assert parse_inv.status_code == 404
|
||||
assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -400,7 +386,7 @@ def test_parse_inventory_empty_text_route_is_removed(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": " "},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": " "},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -413,7 +399,7 @@ def test_match_by_supplier_sku_and_reservation_id(app, client):
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n",
|
||||
},
|
||||
)
|
||||
@@ -427,7 +413,7 @@ def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, clie
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
|
||||
},
|
||||
)
|
||||
@@ -441,7 +427,7 @@ def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, clie
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": (
|
||||
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
|
||||
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
|
||||
@@ -459,87 +445,10 @@ def test_legacy_task_inventory_mapping_routes_are_removed(app, client):
|
||||
"/api/shipping-notice/tools/get_inventory_schema_preview",
|
||||
"/api/shipping-notice/tools/apply_inventory_mapping",
|
||||
):
|
||||
response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"})
|
||||
response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
inventory_drop = tmp_path / "inventory_drop"
|
||||
trigger.mkdir()
|
||||
inventory_drop.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.review_status = None
|
||||
task.pending_human_reason = "inv_unavail"
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
|
||||
task.match_status = "fulfillable"
|
||||
task.shortage_json = {"lines": []}
|
||||
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
|
||||
task.export_file_path = str(tmp_path / "old.xlsx")
|
||||
task.export_file_name = "old.xlsx"
|
||||
task.upload_status = "failed"
|
||||
task.upload_mode = "rpa"
|
||||
task.upload_error_message = "old upload failed"
|
||||
task.freight_ref_no = "OLD-REF"
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"connector_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
|
||||
with app.app_context():
|
||||
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
|
||||
assert retry_data["status"] == "running"
|
||||
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.review_status is None
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
assert task.shortage_json is None
|
||||
assert task.line_results_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
assert task.upload_status is None
|
||||
assert task.upload_error_message is None
|
||||
assert task.freight_ref_no is None
|
||||
event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first()
|
||||
assert event is not None
|
||||
assert event.detail_json.get("force_refresh") is True
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch):
|
||||
from datetime import datetime, timedelta
|
||||
@@ -557,17 +466,21 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
user_id = _seed_test_user(username='rpa-timeout-recheck')
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
_confirm_test_task_customer(task)
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -591,7 +504,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
|
||||
with app.app_context():
|
||||
result = _run_single_task(task_id)
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert result["status"] == "needs_human"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
@@ -602,171 +515,13 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
|
||||
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
inventory_drop = tmp_path / "inventory_drop"
|
||||
trigger.mkdir()
|
||||
inventory_drop.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.pending_human_reason = PH_RPA_EXHAUSTED
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"connector_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
base_time = datetime.utcnow() - timedelta(minutes=5)
|
||||
for idx in range(3):
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_triggered",
|
||||
detail_json={"attempt": idx + 1},
|
||||
created_at=base_time + timedelta(seconds=idx),
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
|
||||
with app.app_context():
|
||||
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
|
||||
assert retry_data["status"] == "running"
|
||||
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.error_message is None
|
||||
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
|
||||
assert progress.get("current") == 1
|
||||
assert progress.get("extra", {}).get("manual_retry_round") is True
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
|
||||
|
||||
|
||||
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
first = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-001",
|
||||
conversation_id="conv-test-multi",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
|
||||
)
|
||||
second = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-002",
|
||||
conversation_id="conv-test-multi",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
|
||||
)
|
||||
with app.app_context():
|
||||
db.session.add_all([first, second])
|
||||
db.session.commit()
|
||||
|
||||
confirm_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"conversation_id": "conv-test-multi", "decision": "confirm"},
|
||||
)
|
||||
confirm_data = confirm_res.get_json()
|
||||
assert confirm_data["status"] == "failed"
|
||||
assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"]
|
||||
|
||||
status_res = client.post(
|
||||
"/api/shipping-notice/tools/get_task_status",
|
||||
headers=headers,
|
||||
json={"conversation_id": "conv-test-multi"},
|
||||
)
|
||||
status_data = status_res.get_json()
|
||||
assert status_data["status"] == "failed"
|
||||
assert "任务编号" in status_data["message"]
|
||||
|
||||
with app.app_context():
|
||||
rows = {
|
||||
task.task_no: task
|
||||
for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
|
||||
.order_by(ShippingNotice.task_no)
|
||||
.all()
|
||||
}
|
||||
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
|
||||
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
|
||||
|
||||
|
||||
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
|
||||
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"]
|
||||
|
||||
import app.services.shipping_notice.decision_workflow as decision_workflow
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_request_formal_gate_action(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"}
|
||||
|
||||
monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action)
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"},
|
||||
)
|
||||
data = res.get_json()
|
||||
assert data["status"] == "running"
|
||||
assert data["task_id"] == task_id
|
||||
assert data["message"] == "已提交正式 20-Gate 恢复动作"
|
||||
assert captured["task"].task_no == task_id
|
||||
assert captured["action_code"] == "retry_inventory_preparation"
|
||||
|
||||
|
||||
def test_parse_inventory_oversized_text_route_is_removed(app, client):
|
||||
"""旧正式库存文本入口无论内容大小都不可访问。"""
|
||||
headers = _tool_headers(app)
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -776,12 +531,13 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260101-TEST0001",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-20260101-TEST0001",
|
||||
user_id=1,
|
||||
source_type="eml",
|
||||
review_status="rejected",
|
||||
)
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"]["code"] == "rejected"
|
||||
assert ui_state["review_status"] == "rejected"
|
||||
assert ui_state["actions"] == {"primary": None, "secondary": []}
|
||||
assert "action_buttons" not in ui_state
|
||||
@@ -8,9 +8,14 @@ tests/test_shipping_notice_ui_state.py
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource,
|
||||
ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_ORDER_FREEZE,
|
||||
CP_PARSE_REVIEW,
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
@@ -34,6 +39,43 @@ _REQUIRED_SUMMARY_KEYS = {
|
||||
}
|
||||
|
||||
|
||||
def _frozen_task_with_line(
|
||||
*,
|
||||
task_no: str,
|
||||
user_id: int = 1,
|
||||
reservation_id: str | None = None,
|
||||
part_number: str | None = None,
|
||||
qty: str | None = None,
|
||||
field_values_json: dict | None = None,
|
||||
) -> tuple[ShippingOrderTask, ShippingOrderSnapshotLine]:
|
||||
"""建立通知准备测试所需的最小 OT 冻结档与订单项次。"""
|
||||
task = ShippingOrderTask(task_no=task_no, user_id=user_id, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=task.id,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
reservation_id=reservation_id,
|
||||
part_number=part_number,
|
||||
qty=qty,
|
||||
field_values_json=field_values_json or {},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
return task, line
|
||||
|
||||
|
||||
def test_unified_actions_deduplicates_gate_primary_action():
|
||||
"""Gate 主动作同时出现在展示列表时,只能渲染一次。"""
|
||||
state = _unified_actions(
|
||||
@@ -95,23 +137,23 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback()
|
||||
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
"""summary 必须包含 STP 可解释字段全集。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-SUMMARY",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-SUMMARY", user_id=1,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint_kind"] == "must_human"
|
||||
assert state["checkpoint"]["code"] == CP_ORDER_FREEZE
|
||||
assert state["checkpoint_kind"] == "auto_continue"
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
"""列表等轻量调用默认不得加载阶段工作面详情。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual")
|
||||
task = ShippingOrderTask(task_no="OT-UI-LIGHTWEIGHT", user_id=1, source_type="direct_pdf")
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
detailed_state = build_task_ui_state(task, include_stage_context=True)
|
||||
@@ -124,11 +166,11 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||||
"""旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STAGE-ACTIONS",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-STAGE-ACTIONS", user_id=1,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["stage"]["code"] == "unclassified"
|
||||
@@ -141,11 +183,11 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||||
def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None:
|
||||
"""正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-LIFECYCLE-ENTRIES",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["lifecycle_stage"] == "unclassified"
|
||||
@@ -162,7 +204,7 @@ def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
|
||||
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
@@ -182,10 +224,10 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-GATE-AUTHORITY',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-UI-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
source_type='direct_pdf',
|
||||
# 模拟历史字段尚未同步:旧字段仍像解析复核。
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
@@ -215,10 +257,10 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
|
||||
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-UPLOAD-GATE-AUTHORITY',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-UI-UPLOAD-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
source_type='direct_pdf',
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
@@ -241,17 +283,11 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
|
||||
def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None:
|
||||
"""库存和上传历史字段不能再替代正式 Gate 生成生命周期。"""
|
||||
with app.app_context():
|
||||
fulfillment = ShippingNotice(
|
||||
task_no="SN-UI-FULFILLMENT",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_lines_json=[{"part_number": "P-1"}],
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-UI-UPLOAD",
|
||||
source_type="manual",
|
||||
upload_status="uploaded",
|
||||
fulfillment = ShippingOrderTask(
|
||||
task_no="OT-UI-FULFILLMENT", user_id=1,
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
upload = ShippingOrderTask(task_no="OT-UI-UPLOAD", user_id=1, source_type="direct_pdf")
|
||||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified"
|
||||
upload_state = build_task_ui_state(upload, include_stage_context=True)
|
||||
assert upload_state["stage"]["code"] == "unclassified"
|
||||
@@ -262,31 +298,39 @@ def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> Non
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
"""解析复核应进入人工复核工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-REVIEW",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-REVIEW", user_id=1,
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
source_type="direct_pdf",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["summary"]["entry_surface"] == "review_workbench"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。"""
|
||||
def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
|
||||
"""Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-EXPORT",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
# Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
|
||||
from types import SimpleNamespace
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
|
||||
lambda _task: None,
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint"]["code"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
|
||||
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
|
||||
assert "货代平台上传" in str(state["summary"].get("pause_reason") or "")
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
@@ -303,8 +347,6 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-RESOLVED-EXPORT",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
@@ -373,18 +415,27 @@ def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatc
|
||||
def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-FROZEN",
|
||||
source_type="manual",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_build_freeze",
|
||||
step_payload_json={
|
||||
"line_inventory_candidates": {
|
||||
"source_codes": ["DBS_DUB", "DBS_RTM"],
|
||||
"frozen_at": "build",
|
||||
},
|
||||
},
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-STP-FROZEN", user_id=1, source_type="direct_pdf",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingInventoryCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code=code, candidate_order=index,
|
||||
)
|
||||
for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1)
|
||||
])
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
db.session.commit()
|
||||
state = build_task_ui_state(task)
|
||||
facts = state["summary"]["stp_facts"]
|
||||
assert facts["inventory_source_status"] == "candidates_frozen"
|
||||
@@ -393,33 +444,37 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
|
||||
|
||||
def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
"""stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。"""
|
||||
"""stp_facts 须从当前行级 Match 投影逐行库存证据,不能读取 OT payload。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-LINES",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_code="DBS_DUB",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={
|
||||
"line_inventory_resolutions": [
|
||||
{
|
||||
"line_index": 0,
|
||||
"disposition": "ok",
|
||||
"effective_reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"resolved_inventory_source_code": "DBS_DUB",
|
||||
"inventory_file_no": "INV-1",
|
||||
"inventory_row_ref": {
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"source_code": "DBS_DUB",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
user = User(username='ui-stp-lines', email='ui-stp-lines@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=3, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||||
reservation_id='3000092917', part_number='PN-1', qty='10', field_values_json={},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
match_result='matched', inventory_status='ready', required_qty='10', available_qty='10',
|
||||
matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1',
|
||||
inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
state = build_task_ui_state(task, include_stage_context=True)
|
||||
rows = state["summary"]["stp_facts"]["line_resolutions"]
|
||||
assert rows[0]["effective_reservation_id"] == "3000092917"
|
||||
@@ -428,39 +483,58 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
assert rows[0]["inventory_file_no"] == "INV-1"
|
||||
stage_context = state["stage_context"]
|
||||
assert stage_context["preparation"]["status"] == "ready"
|
||||
assert stage_context["preparation"]["lines"] == [{
|
||||
"line_key": None,
|
||||
"line_no": "1",
|
||||
"line_no_source": "sequence",
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": None,
|
||||
"available_qty": None,
|
||||
"shortage_qty": None,
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "ok",
|
||||
}]
|
||||
# §1.5:行级字段是展示契约核心,但不锁全 dict(随 §1.5 字段扩展)。断言关键现存字段 + 新增明细按钮字段。
|
||||
line = stage_context["preparation"]["lines"][0]
|
||||
assert line["snapshot_line_id"] == snapshot_line.id
|
||||
assert line["line_no"] == 1
|
||||
assert line["customer_po_line_no"] is None
|
||||
assert line["reservation_id"] == "3000092917"
|
||||
assert line["part_number"] == "PN-1"
|
||||
assert line["required_qty"] == "10"
|
||||
assert line["available_qty"] == "10"
|
||||
assert line["shortage_qty"] == "0"
|
||||
assert line["source_code"] == "DBS_DUB"
|
||||
# §1.5 status 现取 user_line_status(展示契约),不再是裸 match_result 的 disposition。
|
||||
assert line["status"] == "inventory_matched"
|
||||
assert line["source_ambiguous"] is False
|
||||
assert line["source_candidates"] == []
|
||||
# §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮;
|
||||
# line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。
|
||||
assert line["inventory_file_no"] == "INV-1"
|
||||
assert line["is_shortage"] is False
|
||||
assert line["inventory_allowed_actions"] == []
|
||||
assert line["line_allowed_actions"] == ["close_unfulfillable"]
|
||||
assert line["user_line_status"] == "inventory_matched"
|
||||
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
|
||||
assert stage_context["upload"]["outcome"] == "not_started"
|
||||
|
||||
|
||||
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。"""
|
||||
"""通知准备必须从 Snapshot 与行级 Match 投影,不依赖 OT JSON 或 NoticeLine。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-MATCH",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_code="DBS_DUB",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
line_results_json=[],
|
||||
)
|
||||
user = User(username='ui-structured-match', email='ui-structured-match@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||||
reservation_id='RSV-1', part_number='PN-1', qty='10', field_values_json={},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
@@ -477,48 +551,85 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
assert preparation["has_match_result"] is True
|
||||
assert preparation["lines"] == [{
|
||||
"line_key": "line-1",
|
||||
"line_no": "1",
|
||||
"line_no_source": "sequence",
|
||||
"reservation_id": "RSV-1",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": "10",
|
||||
"available_qty": "7",
|
||||
"shortage_qty": "3",
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "matched",
|
||||
}]
|
||||
line = preparation["lines"][0]
|
||||
assert line["snapshot_line_id"] == snapshot_line.id
|
||||
assert line["line_no"] == 1
|
||||
assert line["customer_po_line_no"] is None
|
||||
assert line["reservation_id"] == "RSV-1"
|
||||
assert line["part_number"] == "PN-1"
|
||||
assert line["required_qty"] == "10"
|
||||
assert line["available_qty"] == "7"
|
||||
assert line["shortage_qty"] == "3"
|
||||
assert line["source_code"] == "DBS_DUB"
|
||||
assert line["status"] == "shortage"
|
||||
assert line["source_ambiguous"] is False
|
||||
assert line["source_candidates"] == []
|
||||
# §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。
|
||||
assert line["is_shortage"] is True
|
||||
assert line["user_line_status"] == "shortage"
|
||||
assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"}
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None:
|
||||
"""行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。"""
|
||||
with app.app_context():
|
||||
user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=2, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={})
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result='source_conflict', inventory_status='source_conflict',
|
||||
allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
|
||||
assert preparation['lines'][0]['source_ambiguous'] is True
|
||||
assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B']
|
||||
assert preparation['lines'][0]['source_code'] is None
|
||||
assert preparation['source_locked'] is False
|
||||
|
||||
|
||||
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
|
||||
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=task.id,
|
||||
position=0,
|
||||
line_key="line-frozen-1",
|
||||
task, line = _frozen_task_with_line(
|
||||
task_no="OT-UI-FROZEN-ORDER",
|
||||
reservation_id="RSV-FROZEN",
|
||||
part_number="PN-FROZEN",
|
||||
required_qty="6",
|
||||
))
|
||||
qty="6",
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
|
||||
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
|
||||
assert preparation["frozen_order_lines"] == [{
|
||||
"line_key": "line-frozen-1",
|
||||
"line_no": "1",
|
||||
"line_no_source": "sequence",
|
||||
"snapshot_line_id": line.id,
|
||||
"line_no": 1,
|
||||
"reservation_id": "RSV-FROZEN",
|
||||
"part_number": "PN-FROZEN",
|
||||
"required_qty": "6.00000000",
|
||||
}]
|
||||
assert preparation["lines"] == []
|
||||
assert preparation["lines"][0]["snapshot_line_id"] == line.id
|
||||
assert preparation["lines"][0]["line_no"] == 1
|
||||
assert preparation["lines"][0]["reservation_id"] == "RSV-FROZEN"
|
||||
assert preparation["lines"][0]["part_number"] == "PN-FROZEN"
|
||||
assert preparation["lines"][0]["available_qty"] is None
|
||||
assert preparation["has_match_result"] is False
|
||||
|
||||
|
||||
@@ -530,7 +641,9 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat
|
||||
with app.app_context():
|
||||
inventory_path = tmp_path / "task-inventory.xlsx"
|
||||
inventory_path.write_bytes(b"inventory-content")
|
||||
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual")
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf",
|
||||
)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-UI-DOWNLOAD",
|
||||
storage_path=str(inventory_path),
|
||||
@@ -568,8 +681,8 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
|
||||
db.session.flush()
|
||||
inventory_path = tmp_path / 'inventory-download.xlsx'
|
||||
inventory_path.write_bytes(b'inventory-download-content')
|
||||
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual')
|
||||
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf')
|
||||
no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
|
||||
storage_path=str(inventory_path),
|
||||
@@ -589,16 +702,16 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
|
||||
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
|
||||
|
||||
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
|
||||
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
|
||||
success = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
|
||||
assert success.status_code == 200
|
||||
assert success.data == b'inventory-download-content'
|
||||
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
|
||||
|
||||
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
|
||||
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
|
||||
missing = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
|
||||
assert missing.status_code == 404
|
||||
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
|
||||
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
|
||||
forbidden = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
|
||||
@@ -614,7 +727,9 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
|
||||
denied_path = tmp_path / 'dbs.xlsx'
|
||||
allowed_path.write_bytes(b'crane-content')
|
||||
denied_path.write_bytes(b'dbs-content')
|
||||
task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual')
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id,
|
||||
)
|
||||
allowed_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
|
||||
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
|
||||
@@ -626,7 +741,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
|
||||
db.session.add_all([task, allowed_file, denied_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-crane', line_index=0,
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
|
||||
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
|
||||
))
|
||||
@@ -634,7 +749,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
|
||||
allowed = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
|
||||
'/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
|
||||
headers=headers,
|
||||
)
|
||||
assert allowed.status_code == 200
|
||||
@@ -642,41 +757,33 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
|
||||
assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '')
|
||||
|
||||
denied = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
|
||||
'/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
|
||||
headers=headers,
|
||||
)
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
|
||||
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
|
||||
"""行级 Match 的事实字段应补齐冻结订单行的库存展示。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-PARTIAL",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={"line_inventory_resolutions": [{
|
||||
"line_index": 0,
|
||||
"line_key": "line-1",
|
||||
"effective_reservation_id": "RSV-LEGACY",
|
||||
"part_number": "PN-LEGACY",
|
||||
"inventory_file_no": "INV-1",
|
||||
"disposition": "ok",
|
||||
}]},
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no="OT-UI-STRUCTURED-PARTIAL",
|
||||
reservation_id="RSV-LEGACY",
|
||||
part_number="PN-LEGACY",
|
||||
qty="10",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="8",
|
||||
shortage_qty="2",
|
||||
reservation_id="RSV-LEGACY",
|
||||
part_number="PN-LEGACY",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
@@ -696,18 +803,16 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-DETAIL-CONTEXT",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no="OT-UI-DETAIL-CONTEXT",
|
||||
reservation_id="RSV-DETAIL",
|
||||
part_number="PN-DETAIL",
|
||||
qty="2",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
@@ -725,36 +830,109 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
|
||||
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
|
||||
monkeypatch.setattr(api, '_ok', lambda data: data)
|
||||
|
||||
payload = api.workspace_shipping_task_detail(task.task_no)
|
||||
# 视图函数经 request.args 读取 view 参数,必须包一层请求上下文(直接调用无 request)。
|
||||
with app.test_request_context():
|
||||
payload = api.workspace_shipping_task_detail(task.task_no)
|
||||
preparation = payload['ui_state']['stage_context']['preparation']
|
||||
assert preparation['has_match_result'] is True
|
||||
assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL'
|
||||
|
||||
|
||||
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
"""历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。"""
|
||||
from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW
|
||||
|
||||
"""行级多源冲突应覆盖通知准备的暂停原因。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-MULTI",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={
|
||||
"multi_source_excel_block": True,
|
||||
"resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"],
|
||||
"line_inventory_resolutions": [
|
||||
{"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"},
|
||||
{"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"},
|
||||
],
|
||||
},
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1",
|
||||
)
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
match_result='source_conflict', inventory_status='source_conflict',
|
||||
allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
state = build_task_ui_state(task)
|
||||
summary = state["summary"]
|
||||
assert summary["pause_reason_code"] == "multi_source_excel_block"
|
||||
assert summary["stp_facts"]["multi_source_excel_block"] is True
|
||||
assert summary["entry_surface"] == "task_workbench"
|
||||
|
||||
|
||||
def test_preparation_editable_present_for_live_formal_task(monkeypatch):
|
||||
"""活任务(active/blocked/空值)判定可操作;作废/归档/删除/待作废/取消视图不可操作。
|
||||
|
||||
按 ShippingNotice 真实 lifecycle_status 值域逐值覆盖(不用 WorkflowItem 的
|
||||
{'closed', 'cancelled'} 终态集);排除集见 ui_state 的
|
||||
_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES 注释。
|
||||
"""
|
||||
class FakeTask:
|
||||
id = 1
|
||||
task_no = 'SN-LIVE-1'
|
||||
order_task_no = 'SN-LIVE-1'
|
||||
# 真实值域:ShippingNotice 无 in_progress 写入方,活任务为 active。
|
||||
lifecycle_status = 'active'
|
||||
export_file_path = ''
|
||||
order_snapshot_id = None
|
||||
inventory_source_code = None
|
||||
match_status = None
|
||||
|
||||
# 直接依赖 _build_stage_context 内部较重;此处最小断言 editable 键存在且为 bool 语义。
|
||||
# 实现时若 _build_stage_context 依赖过多,改为抽纯谓词 _preparation_editable(task) 单测。
|
||||
from app.services.shipping_notice.ui_state import _preparation_editable
|
||||
|
||||
# 关键断言:活任务(active)判定可操作(任务级 editable=True 语义)。
|
||||
assert _preparation_editable(FakeTask()) is True
|
||||
|
||||
class BlockedTask(FakeTask):
|
||||
lifecycle_status = 'blocked'
|
||||
|
||||
# 关键断言:blocked 是新任务暂堵态(task_supersession_service.py),不算作废/历史
|
||||
# 视图,保持可编辑——与 case 级 edit_formal_task 镜像语义一致;闸口语义由
|
||||
# pending_human_reason 等机制表达,不在此谓词收紧。
|
||||
assert _preparation_editable(BlockedTask()) is True
|
||||
|
||||
class NoStatusTask(FakeTask):
|
||||
lifecycle_status = None
|
||||
|
||||
# 边界断言:空/缺失 lifecycle_status 不得误判为终态,默认可操作。
|
||||
assert _preparation_editable(NoStatusTask()) is True
|
||||
|
||||
# 关键断言:每个非可操作生命周期必须置 False,供 Prep 波次出单门控拦截——
|
||||
# 终态 voided/archived/deleted;co8 只读语义 pending_void
|
||||
# (freight_cancellation_service.py:154);兼容双拼 cancelled/canceled。
|
||||
for status in ('voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled'):
|
||||
class NonEditableTask(FakeTask):
|
||||
pass
|
||||
NonEditableTask.lifecycle_status = status
|
||||
# 意图:该值域命中 _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES → editable=False。
|
||||
assert _preparation_editable(NonEditableTask()) is False
|
||||
|
||||
class NoisyStatusTask(FakeTask):
|
||||
lifecycle_status = ' Voided '
|
||||
|
||||
# 边界断言:strip/lower 归一化必须保留(防终态因空白/大小写漏判为可编辑)。
|
||||
assert _preparation_editable(NoisyStatusTask()) is False
|
||||
|
||||
|
||||
def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None:
|
||||
"""[断言] preparation 携带任务级 editable(active=True / voided=False);
|
||||
行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。"""
|
||||
with app.app_context():
|
||||
task, first_line = _frozen_task_with_line(
|
||||
task_no="OT-UI-PREP-EDITABLE",
|
||||
reservation_id="RSV-PO-1", part_number="PN-PO-1", qty="5",
|
||||
field_values_json={"customer_po_line_no": "7"},
|
||||
)
|
||||
second_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=first_line.snapshot_id, position=1, line_no=2,
|
||||
reservation_id="RSV-PO-2", part_number="PN-PO-2", qty="3", field_values_json={},
|
||||
)
|
||||
db.session.add(second_line)
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
# 关键断言:活任务(默认 active)必须下发任务级可操作标志 True。
|
||||
assert preparation["editable"] is True
|
||||
# 未绑定 Schema 字段 ID 时,冻结档不会把 field_code 当成正式字段事实。
|
||||
assert preparation["lines"][0]["customer_po_line_no"] is None
|
||||
# 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。
|
||||
assert preparation["lines"][1]["customer_po_line_no"] is None
|
||||
@@ -2,11 +2,11 @@
|
||||
tests/test_shipping_notice_user_facing_status.py
|
||||
|
||||
用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。
|
||||
依赖:pytest、ShippingNotice 模型、user_facing_status。
|
||||
逻辑:构造最小 ShippingNotice 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
|
||||
依赖:pytest、ShippingOrderTask 模型、user_facing_status。
|
||||
逻辑:构造最小 ShippingOrderTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
|
||||
"""
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
|
||||
@@ -15,10 +15,12 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
|
||||
"""
|
||||
rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。
|
||||
|
||||
核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。
|
||||
核心逻辑:pending_human_reason 是属于建单前 OT(ShippingOrderTask)的流程阻断事实;
|
||||
正式 Notice 只承载单据。构造 rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。
|
||||
"""
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-RPA-PENDING",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-TEST-RPA-PENDING",
|
||||
user_id=1,
|
||||
pending_human_reason=PH_RPA_PENDING,
|
||||
)
|
||||
|
||||
|
||||
@@ -22,8 +22,9 @@ from app.models import (
|
||||
Job,
|
||||
ShippingDocumentProfileAutoFreezeQualification,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderRouteDecision,
|
||||
@@ -52,7 +53,7 @@ def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrde
|
||||
|
||||
|
||||
def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None:
|
||||
"""为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。"""
|
||||
"""为 Run 构造已确认的客户识别结果,供范围门禁测试复用。"""
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=run_id,
|
||||
intake_id=intake_id,
|
||||
@@ -63,18 +64,20 @@ def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id,
|
||||
role='bill_to',
|
||||
identity_components_json={},
|
||||
status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint=f'customer-{customer.id}',
|
||||
identity_rule_version='customer-match.v1',
|
||||
resolution_method='manual',
|
||||
confirmed_at=datetime.utcnow(),
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-AF-{run_id}-{customer.id}', intake_id=int(intake_id), primary_document_id=1,
|
||||
candidate_key=f'auto-freeze-{run_id}-{customer.id}', order_extraction_id=extraction.id,
|
||||
candidate_status='accepted', order_extraction_run_id=int(run_id),
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=int(intake_id), resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, identity_rule_set_checksum='a' * 64,
|
||||
top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id,
|
||||
confirmation_method='manual', confirmed_at=datetime.utcnow(),
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from __future__ import annotations
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
apply_manual_inventory_candidates,
|
||||
assess_order_build_eligibility,
|
||||
project_line_inventory_candidates,
|
||||
)
|
||||
@@ -210,42 +209,8 @@ def test_unavailable_rule_candidates_are_filtered(app):
|
||||
assert routing['can_build'] is True
|
||||
|
||||
|
||||
def test_manual_decision_not_silently_overwritten_by_rule_suggestion(app):
|
||||
"""人工决定优先;规则建议可并存但不覆盖有效候选。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
db.session.add(_rule(
|
||||
code='FORCE_OTHER', priority=100, sources=['DSV360_AWSDU'],
|
||||
conditions=[(field_ids['reservation_id'], 'is_not_empty', None)],
|
||||
))
|
||||
db.session.commit()
|
||||
line_meta = {
|
||||
'line_key': 'line-1',
|
||||
'inventory_routing': {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': ['DSV360_AWSDU'],
|
||||
'manual_reason': 'planner confirmed',
|
||||
'suggestion_pending': True,
|
||||
'rule_suggestion': {'source_codes': ['DSV360_AWSDU']},
|
||||
},
|
||||
}
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
|
||||
line_meta=line_meta,
|
||||
)
|
||||
|
||||
# 关键断言:有效候选仍是人工值;selection_mode 保持 manual。
|
||||
assert routing['selection_mode'] == 'manual'
|
||||
assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
assert routing['can_build'] is True
|
||||
|
||||
|
||||
def test_zero_candidates_blocks_build(app):
|
||||
"""无路由命中时 can_build=False 且 block_reason=no_inventory_source_candidates。"""
|
||||
"""无路由命中时 can_build=True(库存路由不阻断 OT 创建),但行级仍记录 block_reason。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
@@ -260,14 +225,14 @@ def test_zero_candidates_blocks_build(app):
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:零候选阻断建单并给出稳定原因码。
|
||||
assert result['can_build'] is False
|
||||
# 关键断言:库存路由属可人工修正事实,不阻断正式 OT 创建;行级仍给出稳定原因码。
|
||||
assert result['can_build'] is True
|
||||
assert result['line_projections'][0]['block_reason'] == 'no_inventory_source_candidates'
|
||||
assert any(item['code'] == 'no_inventory_source_candidates' for item in result['issues'])
|
||||
|
||||
|
||||
def test_require_manual_review_action_blocks_build(app):
|
||||
"""require_manual_review 规则将 status=conflicted 且 can_build=False。"""
|
||||
"""require_manual_review 规则将 status=conflicted;can_build=True(库存路由不阻断),行级保留 block_reason。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
@@ -287,8 +252,8 @@ def test_require_manual_review_action_blocks_build(app):
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:强制人工复核阻断建单。
|
||||
assert result['can_build'] is False
|
||||
# 关键断言:强制人工复核属可人工修正事实,不阻断正式 OT 创建;行级仍路由到 conflicted。
|
||||
assert result['can_build'] is True
|
||||
assert result['line_projections'][0]['routing_status'] == 'conflicted'
|
||||
assert result['line_projections'][0]['block_reason'] == 'require_manual_review'
|
||||
|
||||
@@ -323,57 +288,6 @@ def test_header_only_reservation_fills_effective_reservation(app):
|
||||
assert result['can_build'] is True
|
||||
|
||||
|
||||
def test_manual_selection_with_reason_and_enabled_source_allows_build(app):
|
||||
"""人工选择已启用库存源并填写原因时 can_build=True。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
line_meta: dict = {'line_key': 'line-1'}
|
||||
apply_manual_inventory_candidates(
|
||||
line_meta=line_meta,
|
||||
source_codes=['DSV360_AWSDU'],
|
||||
reason='客户邮件指定 Dublin 库存池',
|
||||
)
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
|
||||
line_meta=line_meta,
|
||||
)
|
||||
|
||||
# 关键断言:人工覆盖优先于规则零候选。
|
||||
assert routing['selection_mode'] == 'manual'
|
||||
assert routing['can_build'] is True
|
||||
assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
|
||||
|
||||
def test_manual_selection_without_reason_is_blocked(app):
|
||||
"""人工选择未填写原因时 can_build=False 且 block_reason=manual_inventory_source_reason_required。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
line_meta = {
|
||||
'line_key': 'line-1',
|
||||
'inventory_routing': {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': ['DSV360_AWSDU'],
|
||||
'manual_reason': '',
|
||||
},
|
||||
}
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
|
||||
line_meta=line_meta,
|
||||
)
|
||||
|
||||
# 关键断言:缺原因不得放行建单。
|
||||
assert routing['can_build'] is False
|
||||
assert routing['block_reason'] == 'manual_inventory_source_reason_required'
|
||||
|
||||
|
||||
def test_auto_freeze_reasons_own_single_user_blocking_finding(app, monkeypatch):
|
||||
"""资格失败只产生一条用户阻断 Finding,不平行产生多个 auto_build_gate_*。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_customer_matching.py
|
||||
|
||||
用途:验证订单 Bill-to / Ship-to 与货代客户主数据的角色化匹配。
|
||||
依赖:订单 Schema 模型、客户主数据模型、order_customer_matching 服务。
|
||||
逻辑:覆盖标准名称、审核别名、歧义、未命中和人工确认快照。
|
||||
"""
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import normalize_customer_name
|
||||
from app.services.shipping_notice.order_customer_matching import (
|
||||
confirm_order_customer_match,
|
||||
refresh_order_customer_matches,
|
||||
)
|
||||
|
||||
|
||||
def _extraction() -> ShippingOrderExtraction:
|
||||
"""构造角色化客户匹配测试所需的最小订单解析记录。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单字段')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='draft', definition_json={})
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
return extraction
|
||||
|
||||
|
||||
def test_order_customer_matching_resolves_roles_and_short_codes(app):
|
||||
"""Bill-to/Ship-to 应可命中不同客户,简称必须来自主数据。"""
|
||||
with app.app_context():
|
||||
bill_to = ShippingCustomer(standard_name='Amazon Web Services', short_code='AWS')
|
||||
db.session.add(bill_to)
|
||||
db.session.flush()
|
||||
ship_to = ShippingCustomerSite(
|
||||
customer_id=bill_to.id, site_name='Amazon Dublin DC', site_code='DUB01', status='active',
|
||||
)
|
||||
db.session.add(ship_to)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerSiteIdentifier(
|
||||
site_id=ship_to.id,
|
||||
identifier_type='name_alias', source_system='',
|
||||
raw_value='AWS Dublin DC',
|
||||
normalized_value=normalize_customer_name('AWS Dublin DC'),
|
||||
status='approved',
|
||||
))
|
||||
extraction = _extraction()
|
||||
|
||||
results = refresh_order_customer_matches(extraction, {
|
||||
'bill_to_customer': 'Amazon Web Services',
|
||||
'ship_to_customer': 'AWS Dublin DC',
|
||||
})
|
||||
|
||||
by_role = {item['role']: item for item in results}
|
||||
assert by_role['bill_to']['customer_id'] == bill_to.id
|
||||
assert by_role['bill_to']['short_code'] == 'AWS'
|
||||
assert by_role['ship_to']['customer_id'] == bill_to.id
|
||||
assert by_role['ship_to']['site_id'] == ship_to.id
|
||||
assert by_role['ship_to']['short_code'] == 'AWS'
|
||||
|
||||
|
||||
def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app):
|
||||
"""同一别名对应多个客户时不得自动选择,人工确认后锁定标准名称和简称。"""
|
||||
with app.app_context():
|
||||
first = ShippingCustomer(standard_name='Customer One', short_code='ONE')
|
||||
second = ShippingCustomer(standard_name='Customer Two', short_code='TWO')
|
||||
db.session.add_all([first, second])
|
||||
db.session.flush()
|
||||
normalized = normalize_customer_name('Shared Alias')
|
||||
db.session.add_all([
|
||||
ShippingCustomerIdentifier(
|
||||
customer_id=first.id, identifier_type='name_alias', raw_value='Shared Alias',
|
||||
normalized_value=normalized, status='approved',
|
||||
),
|
||||
ShippingCustomerIdentifier(
|
||||
customer_id=second.id, identifier_type='name_alias', raw_value='Shared Alias',
|
||||
normalized_value=normalized, status='approved',
|
||||
),
|
||||
])
|
||||
extraction = _extraction()
|
||||
results = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Shared Alias'})
|
||||
bill_to = next(item for item in results if item['role'] == 'bill_to')
|
||||
assert bill_to['status'] == 'ambiguous'
|
||||
assert bill_to['customer_id'] is None
|
||||
assert len(bill_to['candidates']) == 2
|
||||
|
||||
confirmed = confirm_order_customer_match(
|
||||
extraction.id, role='bill_to', customer_id=second.id, actor_id=None, reason='业务复核确认订购客户',
|
||||
)
|
||||
assert confirmed['status'] == 'confirmed'
|
||||
assert confirmed['standard_name'] == 'Customer Two'
|
||||
assert confirmed['short_code'] == 'TWO'
|
||||
assert confirmed['confirmation_reason'] == '业务复核确认订购客户'
|
||||
assert len(confirmed['identity_fingerprint']) == 64
|
||||
assert confirmed['identity_rule_version'] == 'order-customer-fingerprint.v1'
|
||||
|
||||
|
||||
def test_order_customer_fingerprint_is_stable_and_confirmation_requires_reason(app):
|
||||
"""相同原文及规则必须得到稳定指纹,人工绑定不能缺失可审计理由。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(standard_name='Fingerprint Customer', short_code='FPC')
|
||||
db.session.add(customer)
|
||||
extraction = _extraction()
|
||||
first = refresh_order_customer_matches(extraction, {'bill_to_customer': ' Fingerprint Customer '})
|
||||
fingerprint = next(item for item in first if item['role'] == 'bill_to')['identity_fingerprint']
|
||||
second = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Fingerprint Customer'})
|
||||
assert next(item for item in second if item['role'] == 'bill_to')['identity_fingerprint'] == fingerprint
|
||||
try:
|
||||
confirm_order_customer_match(extraction.id, role='bill_to', customer_id=customer.id, actor_id=None, reason='')
|
||||
except Exception as error:
|
||||
assert getattr(error, 'code', None) == 'SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED'
|
||||
else:
|
||||
raise AssertionError('confirmation without reason must be blocked')
|
||||
|
||||
|
||||
def test_order_customer_matching_prefers_external_customer_and_site_codes(app):
|
||||
"""外部客户编码和 Ship-to Code 应优先于不可靠的原文名称。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(standard_name='Canonical Customer', short_code='CAN')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerExternalRef(
|
||||
customer_id=customer.id, source_system='ERP', legacy_customer_key='C001',
|
||||
))
|
||||
site = ShippingCustomerSite(
|
||||
customer_id=customer.id, site_name='Dublin Site', site_code='DUB01', status='active',
|
||||
)
|
||||
db.session.add(site)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerSiteIdentifier(
|
||||
site_id=site.id, identifier_type='external_code', source_system='ERP',
|
||||
raw_value='DUB-EXT', normalized_value='DUB-EXT', status='approved',
|
||||
))
|
||||
extraction = _extraction()
|
||||
|
||||
results = refresh_order_customer_matches(extraction, {
|
||||
'bill_to_customer': 'Wrong Name', 'bill_to_customer_code': 'c001', 'bill_to_source_system': 'erp',
|
||||
'ship_to_customer': 'Wrong Site', 'ship_to_code': 'dub-ext', 'ship_to_source_system': 'erp',
|
||||
})
|
||||
|
||||
by_role = {item['role']: item for item in results}
|
||||
assert by_role['bill_to']['customer_id'] == customer.id
|
||||
assert by_role['bill_to']['resolution_method'] == 'external_customer_code'
|
||||
assert by_role['ship_to']['site_id'] == site.id
|
||||
assert by_role['ship_to']['resolution_method'] == 'external_site_code'
|
||||
|
||||
|
||||
def test_ship_to_matching_falls_back_to_name_when_external_code_misses(app):
|
||||
"""Ship-to 外部编码未命中时应继续使用站点标准名称,避免有效站点被错误判为未匹配。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(standard_name='Fallback Customer', short_code='FBC')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
site = ShippingCustomerSite(
|
||||
customer_id=customer.id, site_name='Fallback Delivery Site', site_code='FBS01', status='active',
|
||||
)
|
||||
db.session.add(site)
|
||||
extraction = _extraction()
|
||||
|
||||
results = refresh_order_customer_matches(extraction, {
|
||||
'ship_to_customer': 'Fallback Delivery Site',
|
||||
'ship_to_code': 'UNKNOWN-CODE',
|
||||
'ship_to_source_system': 'ERP',
|
||||
})
|
||||
|
||||
ship_to = next(item for item in results if item['role'] == 'ship_to')
|
||||
assert ship_to['site_id'] == site.id
|
||||
assert ship_to['resolution_method'] == 'site_name'
|
||||
@@ -660,8 +660,25 @@ def _bind_ready_profile_sample(
|
||||
table_id: str = 'sample-table',
|
||||
content_hash: str = 's' * 64,
|
||||
filename: str = 'sample.pdf',
|
||||
physical_page_count: int = 1,
|
||||
include_top_level_pages: bool = True,
|
||||
) -> ShippingOrderDocumentProfileSample:
|
||||
"""为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。"""
|
||||
"""
|
||||
为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。
|
||||
|
||||
Args:
|
||||
profile_id: 绑定该样本的草稿模板主键。
|
||||
sample_role: 样本角色。
|
||||
table_id: 第一页视觉主表身份。
|
||||
content_hash: 样本文档内容哈希。
|
||||
filename: 受控样本文档名。
|
||||
physical_page_count: 原 PDF 的物理页数;坐标证据为每页保留尺寸。
|
||||
include_top_level_pages: 为 False 时模拟坐标证据外置后的持久化 Layout,不在根 payload
|
||||
重复保存页面列表。
|
||||
|
||||
Returns:
|
||||
已绑定到 Profile 的样本记录。
|
||||
"""
|
||||
suffix = f'{profile_id}-{str(sample_role).upper()}-{ShippingOrderDocumentProfileSample.query.count() + 1}'
|
||||
user = User(
|
||||
username=f'profile-sample-{suffix}',
|
||||
@@ -708,10 +725,9 @@ def _bind_ready_profile_sample(
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
snapshot = {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{
|
||||
'table_id': table_id,
|
||||
'page_no': 1,
|
||||
@@ -719,7 +735,10 @@ def _bind_ready_profile_sample(
|
||||
'html': '<table><tr><td>ok</td></tr></table>',
|
||||
}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'pages': {
|
||||
str(page_no): {'width': 200, 'height': 100}
|
||||
for page_no in range(1, physical_page_count + 1)
|
||||
},
|
||||
'page_glyphs': {'1': [{
|
||||
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
}]},
|
||||
@@ -728,7 +747,10 @@ def _bind_ready_profile_sample(
|
||||
}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {table_id: 'pdf'}},
|
||||
},
|
||||
})
|
||||
}
|
||||
if include_top_level_pages:
|
||||
snapshot['pages'] = [{'page_no': page_no} for page_no in range(1, physical_page_count + 1)]
|
||||
record_inline_layout_snapshot(document, snapshot)
|
||||
db.session.commit()
|
||||
service.add_profile_sample(
|
||||
profile_id,
|
||||
@@ -1448,6 +1470,28 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
).one().id == replacement['id']
|
||||
|
||||
|
||||
def test_profile_publish_freezes_physical_page_count_from_externalized_coordinate_evidence(app, monkeypatch):
|
||||
"""外置坐标证据含全部物理页时,发布冻结页数不能退化为仅有表格的页数。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
draft = service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(
|
||||
draft['id'],
|
||||
sample_role='annotation',
|
||||
physical_page_count=2,
|
||||
include_top_level_pages=False,
|
||||
)
|
||||
|
||||
service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
|
||||
frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
|
||||
# 关键断言:第二页即使没有业务表格,仍是同一 PDF 的冻结物理页面。
|
||||
assert frozen.page_count_snapshot == 2
|
||||
|
||||
|
||||
def test_clone_draft_inherits_annotation_sample_but_not_training_sample(app, monkeypatch):
|
||||
"""从已发布模板新建草稿时,编辑器 PDF 画布可用且不会复用训练发布资格。"""
|
||||
with app.app_context():
|
||||
@@ -1948,6 +1992,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}},
|
||||
})
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
@@ -2377,7 +2422,8 @@ def test_profile_region_preview_excludes_configured_header_regions_from_line_row
|
||||
)
|
||||
|
||||
assert preview['rows'] == [['customer_po_line_no'], ['10']]
|
||||
assert preview['source_row_indices'] == [[], [0]]
|
||||
# 整页候选保留表头作为第 0 个视觉行;真实数据行的证据索引必须保持为第 1 行。
|
||||
assert preview['source_row_indices'] == [[], [1]]
|
||||
|
||||
|
||||
def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
|
||||
@@ -2645,6 +2691,7 @@ def test_profile_sample_api_reports_header_contamination_but_v2_can_use_independ
|
||||
'<table><tr><th>ITEM NO 00010</th><th>Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>00020</td><td>INTERNAL-2</td><td>36</td></tr></table>'
|
||||
)}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}},
|
||||
})
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
tests/test_shipping_order_edit_window.py
|
||||
|
||||
用途:确认后订单编辑窗谓词(order_edit_window_service.editable_scope,设计 D10/§3.1)契约。
|
||||
依赖:ShippingNotice/ShippingNoticeLine、order_edit_window_service.progress_workflow。
|
||||
逻辑:header=全部通知无 Export Artifact 且无活动 Attempt;行=行所属通知无 Excel 且无活动 Attempt
|
||||
(未入波次行不受首单 Excel 限制)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingNoticeLine
|
||||
from app.services.shipping_notice.order_edit_window_service import (
|
||||
assert_field_editable,
|
||||
editable_scope,
|
||||
)
|
||||
|
||||
|
||||
def _make_notice(task_no: str, *, order_task_id: int | None = None) -> ShippingNotice:
|
||||
"""构造最小 ShippingNotice;Excel 锁定由测试 monkeypatch _notice_has_export_artifact 判定。"""
|
||||
notice = ShippingNotice(
|
||||
task_no=task_no,
|
||||
order_task_id=order_task_id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return notice
|
||||
|
||||
|
||||
def _make_line(notice: ShippingNotice, position: int, snapshot_line_id: int) -> None:
|
||||
"""行身份使用冻结快照行 id(snapshot_line_id)作为编辑窗 key。"""
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=int(notice.id),
|
||||
position=position,
|
||||
line_no=position + 1,
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
field_values_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_editable_scope_fresh_order_all_editable(app, monkeypatch):
|
||||
"""[断言] 全新订单(无 Excel、无活动 Attempt):header 与全部行均可编辑。"""
|
||||
from app.services.shipping_notice.order_edit_window_service import _notice_has_active_attempt
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False)
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False)
|
||||
notice = _make_notice('SN-EW-FRESH')
|
||||
_make_line(notice, 0, 1)
|
||||
_make_line(notice, 1, 2)
|
||||
|
||||
scope = editable_scope(notice)
|
||||
assert scope['header'] is True
|
||||
assert scope['lines']['1'] is True
|
||||
assert scope['lines']['2'] is True
|
||||
|
||||
|
||||
def test_editable_scope_header_locked_by_excel_unassigned_lines_stay_editable(app, monkeypatch):
|
||||
"""[断言] 首单已生成 Excel:header 锁;未入波次行仍可编辑(D10 不受首单 Excel 限制)。"""
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False)
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: True)
|
||||
notice = _make_notice('SN-EW-EXCEL')
|
||||
_make_line(notice, 0, 1)
|
||||
_make_line(notice, 1, 2)
|
||||
|
||||
scope = editable_scope(notice)
|
||||
assert scope['header'] is False
|
||||
assert scope['lines']['1'] is True # 未入波次行不受首单 Excel 限制
|
||||
assert scope['lines']['2'] is True
|
||||
|
||||
|
||||
def test_editable_scope_busy_attempt_locks_header_and_lines(app, monkeypatch):
|
||||
"""[断言] 存在活动 Gate Attempt:header 与全部行均锁定(系统处理中)。"""
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True)
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False)
|
||||
notice = _make_notice('SN-EW-BUSY')
|
||||
_make_line(notice, 0, 1)
|
||||
|
||||
scope = editable_scope(notice)
|
||||
assert scope['header'] is False
|
||||
assert scope['lines']['1'] is False
|
||||
|
||||
|
||||
def test_assert_field_editable_delegates_scope(app):
|
||||
"""[断言] 保存守卫按作用域映射谓词;header/line 互不串用。"""
|
||||
scope = {'header': False, 'lines': {'1': True, '2': False}}
|
||||
assert assert_field_editable(scope, field={'scope': 'header'}) is False
|
||||
assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='1') is True
|
||||
assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='2') is False
|
||||
assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id=None) is False
|
||||
|
||||
|
||||
def test_order_has_active_attempt_reflects_notice_attempts(app, monkeypatch):
|
||||
"""[断言] order_has_active_attempt 聚合同订单全部通知的活动 Attempt。"""
|
||||
from app.services.shipping_notice.order_edit_window_service import (
|
||||
order_has_active_attempt,
|
||||
)
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True)
|
||||
notice = _make_notice('SN-EW-BUSY-AGGR')
|
||||
assert order_has_active_attempt(notice) is True
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False)
|
||||
assert order_has_active_attempt(notice) is False
|
||||
|
||||
|
||||
def test_edit_window_busy_error_returns_system_busy(app, monkeypatch):
|
||||
"""[断言] 活动 Attempt 时保存守卫返回 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY;空闲时 None。"""
|
||||
from app.services.shipping_notice import task_workflow
|
||||
|
||||
notice = _make_notice('SN-EW-BUSY-GUARD')
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: True)
|
||||
err = task_workflow._edit_window_busy_error(notice)
|
||||
assert err is not None
|
||||
assert 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY' in repr(err)
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: False)
|
||||
assert task_workflow._edit_window_busy_error(notice) is None
|
||||
@@ -62,7 +62,7 @@ def _table_first_column_after(marker: str, *, table_label: str | None = None) ->
|
||||
]
|
||||
|
||||
|
||||
def _review_request(*, scope: str = 'header', line_key: str | None = None) -> dict:
|
||||
def _review_request(*, scope: str = 'header', draft_line_id: str | None = None) -> dict:
|
||||
"""构造单字段最小证据请求信封。"""
|
||||
return {
|
||||
'contract_version': 'order-review-llm.v1',
|
||||
@@ -73,7 +73,7 @@ def _review_request(*, scope: str = 'header', line_key: str | None = None) -> di
|
||||
'field_id': 'field-1',
|
||||
'field_code': 'po_number',
|
||||
'scope': scope,
|
||||
'line_key': line_key,
|
||||
'draft_line_id': draft_line_id,
|
||||
'line_number': None,
|
||||
}],
|
||||
'evidence_pack': {
|
||||
@@ -119,7 +119,7 @@ def test_review_request_accepts_one_header_field():
|
||||
|
||||
|
||||
def test_review_request_rejects_multiple_fields_and_line_without_key():
|
||||
"""复核分支必须一次只处理一个字段,明细字段必须绑定 line_key。"""
|
||||
"""复核分支必须一次只处理一个字段,明细字段必须绑定 draft_line_id。"""
|
||||
main = _node_main('## 7. REVIEW_PARSE_REQUEST')
|
||||
multiple = _review_request()
|
||||
multiple['target_fields'].append(dict(multiple['target_fields'][0], field_id='field-2'))
|
||||
@@ -136,7 +136,7 @@ def test_review_request_rejects_multiple_fields_and_line_without_key():
|
||||
'review_request_json': '',
|
||||
}
|
||||
assert line_result['request_valid'] is False
|
||||
assert line_result['request_error_code'] == 'LINE_KEY_REQUIRED'
|
||||
assert line_result['request_error_code'] == 'DRAFT_LINE_ID_REQUIRED'
|
||||
|
||||
|
||||
def test_review_context_removes_secrets_and_limits_to_current_pack():
|
||||
|
||||
@@ -107,7 +107,7 @@ def test_progress_event_accepts_email_supplement_merge_summary(app):
|
||||
event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
|
||||
assert run.current_stage_code == 'email_supplement_merged'
|
||||
assert list(run.active_stage_codes_json or []) == ['email_supplement_merged']
|
||||
assert event.summary_json == {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}
|
||||
assert {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}.items() <= event.summary_json.items()
|
||||
|
||||
|
||||
def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app):
|
||||
@@ -154,11 +154,11 @@ def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app):
|
||||
'expansion_wave_started',
|
||||
'budget_stopped',
|
||||
]
|
||||
assert events[2].summary_json == {
|
||||
assert {
|
||||
'reason_codes': ['required_field_missing'],
|
||||
'selection_batch': 2,
|
||||
'unit_count': 2,
|
||||
}
|
||||
}.items() <= events[2].summary_json.items()
|
||||
assert run.current_stage_code == 'budget_stopped'
|
||||
assert list(run.active_stage_codes_json or []) == []
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch):
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'):
|
||||
for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs', 'agent_runtime_bindings'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
|
||||
@@ -1402,7 +1402,10 @@ def test_run_submission_rejects_changed_frozen_mail_context(app):
|
||||
def test_run_submission_auto_freezes_qualified_tasks(app):
|
||||
"""Run 命中已授权模板后,应自动消费 accepted Candidate 并冻结为履约 Snapshot。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingCustomer, ShippingDocumentProfileAutoFreezeQualification, ShippingOrderCustomerMatch
|
||||
from app.models import (
|
||||
ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate,
|
||||
ShippingDocumentProfileAutoFreezeQualification,
|
||||
)
|
||||
from tests.test_shipping_order_auto_freeze_policy import _published_profile
|
||||
|
||||
fields = _ensure_order_schema()
|
||||
@@ -1448,18 +1451,20 @@ def test_run_submission_auto_freezes_qualified_tasks(app):
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id,
|
||||
role='bill_to',
|
||||
identity_components_json={},
|
||||
status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint=f'customer-{customer.id}',
|
||||
identity_rule_version='customer-match.v1',
|
||||
resolution_method='manual',
|
||||
confirmed_at=datetime.utcnow(),
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-AF-EXEC-{run.id}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key=f'auto-freeze-exec-{run.id}', order_extraction_id=extraction.id,
|
||||
order_extraction_run_id=run.id, candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 'e' * 64}}, identity_rule_set_checksum='e' * 64,
|
||||
top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id,
|
||||
confirmation_method='manual', confirmed_at=datetime.utcnow(),
|
||||
))
|
||||
db.session.add_all([
|
||||
ShippingDocumentProfileAutoFreezeQualification(
|
||||
|
||||
@@ -47,6 +47,7 @@ def test_unit_transition_appends_auditable_status_event(app):
|
||||
id=37, status='matching_profile', attempt_count=1, started_at=None, finished_at=None,
|
||||
last_activity_at=None, result_json=None, summary_json=None,
|
||||
reason_code=None, error_code=None, error_message=None, plan=plan,
|
||||
document_id=100,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
|
||||
@@ -84,14 +84,15 @@ def test_submit_appends_to_open_queued_run(app):
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 断言:不同 Intake 不得并入同一 Run;须新建 Run(Candidate 前无右侧 OT 卡)。
|
||||
# 断言:不同 Intake 不得并入同一 Run;须新建 Run。预候选 order_notice 未建 OT,
|
||||
# user_task_no 仍为 None,但会话投影把两个 Intake 各计一张处理中卡(total_tasks=2)。
|
||||
assert payload['decision'] == 'created'
|
||||
assert payload['created_new'] is True
|
||||
assert payload['run_no'] != first.run_no
|
||||
assert payload['reason_code'] == 'adjudication_unit_boundary'
|
||||
assert ShippingOrderProcessingRun.query.count() == 2
|
||||
assert payload['user_task_no'] is None
|
||||
assert payload['processing']['summary']['total_tasks'] == 0
|
||||
assert payload['processing']['summary']['total_tasks'] == 2
|
||||
|
||||
|
||||
def test_submit_creates_when_input_frozen(app):
|
||||
@@ -132,9 +133,9 @@ def test_submit_creates_when_input_frozen(app):
|
||||
assert payload['created_new'] is True
|
||||
assert payload['run_no'] != first.run_no
|
||||
assert ShippingOrderProcessingRun.query.count() == 2
|
||||
# Candidate 前会话右侧不展示伪 OT。
|
||||
# Candidate 前不伪造 OT(user_task_no=None);预候选 order_notice 按处理中卡计 2 张。
|
||||
assert payload['user_task_no'] is None
|
||||
assert payload['processing']['summary']['total_tasks'] == 0
|
||||
assert payload['processing']['summary']['total_tasks'] == 2
|
||||
|
||||
|
||||
def test_submit_idempotent_by_submission_id(app):
|
||||
@@ -398,11 +399,11 @@ def test_failed_same_attachment_reupload_inherits_user_task(app):
|
||||
assert new_run.reparse_of_run_id == old_run.id
|
||||
assert old_run.superseded_by_run_id == new_run.id
|
||||
assert old_run.superseded_at is not None
|
||||
assert payload['processing']['summary']['total_tasks'] == 0
|
||||
assert payload['processing']['summary']['total_tasks'] == 2
|
||||
|
||||
|
||||
def test_appended_projection_does_not_mark_recently_created(app):
|
||||
"""跨 Intake 新建 Run 时 Candidate 前无右侧 OT 卡;仅断言裁决与 Run 边界。"""
|
||||
"""跨 Intake 新建 Run 时 Candidate 前无真实 OT(user_task_no=None);投影仍按预候选 order_notice 计处理中卡。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-BADGE')
|
||||
first = submit_order_extraction(
|
||||
@@ -439,7 +440,7 @@ def test_appended_projection_does_not_mark_recently_created(app):
|
||||
assert payload['run_no'] != first['run_no']
|
||||
assert payload['user_task_no'] is None
|
||||
assert first['user_task_no'] is None
|
||||
assert payload['processing']['summary']['total_tasks'] == 0
|
||||
assert payload['processing']['summary']['total_tasks'] == 2
|
||||
assert ShippingOrderProcessingRun.query.count() == 2
|
||||
|
||||
|
||||
|
||||
@@ -252,8 +252,8 @@ def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
)
|
||||
|
||||
|
||||
def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch):
|
||||
"""同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。"""
|
||||
def test_process_unit_with_retries_stops_on_retryable_technical_failure(monkeypatch):
|
||||
"""任一技术故障(含 ServiceUnavailableError)在单元内失败即停止,不自动重试;调用方可继续处理其他附件。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
@@ -293,15 +293,15 @@ def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result == orders
|
||||
assert unit.status == 'merging_supplement'
|
||||
assert unit.attempt_count == 3
|
||||
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
assert result is None
|
||||
assert unit.status == 'failed'
|
||||
assert unit.attempt_count == 1
|
||||
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 0
|
||||
assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 1
|
||||
|
||||
|
||||
def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch):
|
||||
"""同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。"""
|
||||
def test_process_unit_with_retries_records_single_route_attempt(monkeypatch):
|
||||
"""同一 Job 内仅路由一次;技术失败后单元不再重试,审计尝试号按单元执行代次记录。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
@@ -339,8 +339,8 @@ def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch):
|
||||
lambda *, run_id, unit_id: (run, unit),
|
||||
)
|
||||
|
||||
assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
assert route_attempts == [1, 2]
|
||||
assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) is None
|
||||
assert route_attempts == [1]
|
||||
|
||||
|
||||
def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatch):
|
||||
@@ -383,8 +383,8 @@ def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatc
|
||||
assert unit.technical_failure_reason_code is None
|
||||
|
||||
|
||||
def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch):
|
||||
"""自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。"""
|
||||
def test_process_unit_with_retries_marks_unit_failed_without_retry(monkeypatch):
|
||||
"""技术失败在单元内失败即停止,不消耗重试预算;调用方可继续处理其他附件。"""
|
||||
event_log: list[tuple[str, str | None]] = []
|
||||
_patch_unit_transitions(monkeypatch)
|
||||
_patch_worker_io(monkeypatch, event_log=event_log)
|
||||
@@ -416,10 +416,10 @@ def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(m
|
||||
|
||||
assert result is None
|
||||
assert unit.status == 'failed'
|
||||
assert unit.attempt_count == 3
|
||||
assert unit.attempt_count == 1
|
||||
assert unit.technical_failure_reason_code == 'OCR.TIMEOUT'
|
||||
assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 2
|
||||
assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 3
|
||||
assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 0
|
||||
assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 1
|
||||
|
||||
|
||||
def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch):
|
||||
|
||||
@@ -90,7 +90,7 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
assert result['primaryNotice'] is None
|
||||
|
||||
|
||||
def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
def test_build_handling_items_splits_pending_freeze_review_and_failure(monkeypatch):
|
||||
"""Run 级 handling_items 必须拆分待补、冲突、冻结、复核与技术失败,不得只给笼统复核态。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
@@ -145,6 +145,12 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
),
|
||||
]
|
||||
|
||||
# document_review 只在存在活动(非终态)ReviewCase 时投影;纯单元 Run 无落库
|
||||
# Case,故按文件口径补一条模板 Case 以激活 document_review 分支。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases',
|
||||
lambda _run: [SimpleNamespace(document_id=11, case_no='CASE-11')],
|
||||
)
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
categories = [item['category'] for item in items]
|
||||
|
||||
@@ -196,7 +202,7 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs():
|
||||
assert budget['affected_refs'][0]['document_id'] == 42
|
||||
|
||||
|
||||
def test_build_handling_items_counts_one_document_in_only_one_primary_category():
|
||||
def test_build_handling_items_counts_one_document_in_only_one_primary_category(monkeypatch):
|
||||
"""同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
@@ -234,13 +240,18 @@ def test_build_handling_items_counts_one_document_in_only_one_primary_category()
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
# document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases',
|
||||
lambda _run: [SimpleNamespace(document_id=99, case_no='CASE-99')],
|
||||
)
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['document_review']
|
||||
assert items[0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id():
|
||||
def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id(monkeypatch):
|
||||
"""预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
@@ -270,6 +281,11 @@ def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapsh
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
# document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases',
|
||||
lambda _run: [SimpleNamespace(document_id=100, case_no='CASE-100')],
|
||||
)
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
# 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingNotice,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
@@ -31,15 +31,15 @@ def _config(field_id: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingNotice:
|
||||
def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingOrderTask:
|
||||
"""创建冻结快照,策略绑定决定履约阶段如何定位预约单号。"""
|
||||
service.initialize_schema({'display_name': '用途测试'}, actor_id=None)
|
||||
field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {'fields': [_config(field['id'])], 'expected_lock_version': draft['lock_version']}, actor_id=None)
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PURPOSE-1', source_type='manual', lines_json=[{'reservation_id': 'WRONG'}],
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-PURPOSE-1', source_type='direct_pdf', user_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -48,7 +48,7 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool =
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
@@ -62,25 +62,24 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool =
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
bindings = []
|
||||
if include_reservation_capability:
|
||||
bindings.append({
|
||||
'capability_code': 'fulfillment.reservation_identity',
|
||||
'field_id': field['id'],
|
||||
'scope': 'line',
|
||||
})
|
||||
# 冻结策略只承认 frozen fulfillment_rule.required_field_ids;old
|
||||
# fulfillment_policy.definition.field_bindings 已不再匹配。
|
||||
rule_versions_json = {'fulfillment_rule': {'required_field_ids': {
|
||||
'reservation_id': field['id'], 'part_number': field['id'],
|
||||
'qty': field['id'], 'quantity': field['id'],
|
||||
}}}
|
||||
else:
|
||||
rule_versions_json = {}
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], order_data_version=1,
|
||||
customer_po_number='PURPOSE-PO-001', header_values_json={},
|
||||
rule_versions_json={'fulfillment_policy': {
|
||||
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
|
||||
'definition': {'field_bindings': bindings},
|
||||
}},
|
||||
rule_versions_json=rule_versions_json,
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, reservation_id=value,
|
||||
snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=value,
|
||||
field_values_json={field['id']: value},
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
@@ -89,10 +88,9 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool =
|
||||
|
||||
|
||||
def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app):
|
||||
"""门禁以冻结预约单为准,旧任务投影或后续 FieldValue 变化均不得重解释履约。"""
|
||||
"""门禁以冻结预约单为准,后续 FieldValue 变化均不得重解释履约。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
task.lines_json = [{'reservation_id': 'INVALID'}]
|
||||
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
|
||||
value.value_text = 'INVALID'
|
||||
value.value_json = 'INVALID'
|
||||
|
||||
@@ -728,3 +728,71 @@ def test_parse_validation_does_not_upgrade_ineligible_profile_to_unique_match(mo
|
||||
)
|
||||
|
||||
assert result.status == 'no_match'
|
||||
|
||||
|
||||
def test_profile_table_candidates_virtual_empty_page_does_not_block(monkeypatch):
|
||||
"""两页文档、第 2 页无业务表(补成虚拟页)不得把已成功重建的目标表覆盖成失败。
|
||||
|
||||
回归:第 2 页被补为虚拟页 ``page-2`` 时,``_coordinate_profile_rows`` 返回 ``None``
|
||||
(无表字符/无 raw_table_bbox);旧逻辑在 ``_virtual_page_without_rows_is_nonblocking``
|
||||
之前被 ``is None`` 分支误判为行重建失败,追加
|
||||
``order_profile_coordinate_reconstruction_unavailable`` 使整单阻塞为
|
||||
``coordinate_evidence_unavailable``。修复后空虚拟页被豁免,真实业务表(第 1 页)仍成功。
|
||||
|
||||
盲测/样本验证同样按“空页跳过”,因此本条与盲测语义一致。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_extraction_workflow as wf
|
||||
|
||||
layout = _layout('PLANT NAME: FACTORY A', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95})
|
||||
layout['status'] = 'ready'
|
||||
layout['layout_candidate'] = {'schema_version': 'test', 'pages': []}
|
||||
# 第 2 页只有页级字符、无任何业务表 → 会被补成虚拟页 page-2。
|
||||
layout['coordinate_evidence']['pages']['2'] = {'width': 200, 'height': 280}
|
||||
layout['coordinate_evidence']['page_glyphs']['2'] = [
|
||||
{'text': 'N', 'bbox': {'x0': 10, 'y0': 200, 'x1': 15, 'y1': 212}},
|
||||
]
|
||||
profile = _with_signature(_profile('PO'), layout)
|
||||
|
||||
schema_def = {'fields': [{
|
||||
'field_id': 'line-id', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line', 'enabled': True, 'value_type': 'string',
|
||||
}]}
|
||||
snapshot = {
|
||||
'schema': {'extraction_contract': {}, 'definition': schema_def},
|
||||
'order_document_profiles': [profile],
|
||||
'intakes': [{'intake_id': 1, 'documents': [{
|
||||
'document_id': 100, 'filename': 'x.pdf', 'layout_snapshot': layout,
|
||||
}]}],
|
||||
}
|
||||
run = SimpleNamespace(id=9, schema_version_id=34, input_snapshot_json=snapshot)
|
||||
unit = SimpleNamespace(id=99, intake_id=1, document_id=100)
|
||||
|
||||
# 隔离 DB/开关:本测试只关心虚拟空页的行重建门禁语义。
|
||||
monkeypatch.setattr(wf.db.session, 'get', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(wf, 'profile_auto_selection_enabled', lambda: True)
|
||||
|
||||
def fake_rows(**kwargs):
|
||||
"""注入真实行为:第 1 页业务表重建出 1 行;无表的虚拟页返回 None。"""
|
||||
raw_table = kwargs.get('raw_table') or {}
|
||||
if str(raw_table.get('table_id') or '') == 'page-2':
|
||||
return None
|
||||
return [{
|
||||
'row_index': 1, '_coordinate_region_id': 'lines', '_coordinate_row_count': 1,
|
||||
'status': 'parsed', 'issues': [],
|
||||
'fields': [{
|
||||
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'value': '10',
|
||||
'quote': '10', 'page_no': 1, 'table_id': 'table-1',
|
||||
}],
|
||||
}]
|
||||
|
||||
monkeypatch.setattr(wf, '_coordinate_profile_rows', fake_rows)
|
||||
|
||||
result = wf._profile_table_candidates(run, unit=unit, profiles=[profile], match_only=False)
|
||||
|
||||
assert result['blocking'] is False
|
||||
assert 'order_profile_coordinate_reconstruction_unavailable' not in (result.get('issues') or [])
|
||||
assert result['matched'] is True
|
||||
# 虚拟空页应被跳过,只有第 1 页业务表进入结果。
|
||||
assert len(result.get('tables') or []) == 1
|
||||
@@ -164,3 +164,48 @@ def test_parse_validation_accepts_month_day_year_date_format():
|
||||
|
||||
assert result['passed'] is True
|
||||
assert result['metrics']['type_issue_count'] == 0
|
||||
|
||||
|
||||
def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict:
|
||||
"""构造明细区文字被纵向位移到冻结字段带之下的 layout。
|
||||
|
||||
回归场景:legacy 模板把 line 字段区冻结在标注样本的绝对页坐标(y≈112-140),
|
||||
但实际物理表整体下移,文字落在冻结带之外(y≈200-212)。行重建 ``values_for``
|
||||
只按横向边界在所在视觉行取字,与纵向是否位移无关;而覆盖率门禁此前用严格
|
||||
中心包含读取冻结区域,会误读为空。此 helper 提供一个与冻结带错位的表,
|
||||
bbox 同时与模板表区交叠并覆盖真实文字,用于验证位移容忍覆盖。
|
||||
"""
|
||||
glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 20 + index * 5, 'y0': 200 + (index % 3), 'x1': 24 + index * 5, 'y1': 212 + (index % 3)}}
|
||||
for index, char in enumerate(text)
|
||||
]
|
||||
return {
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'bbox': {'x0': 10, 'y0': 140, 'x1': 190, 'y1': 250},
|
||||
}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 280}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'tables': {'table-1': glyphs},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_parse_validation_tolerates_shifted_line_field_coverage():
|
||||
"""line 字段区整体纵向位移时,覆盖率应按行重建的横向重叠语义命中,而非冻结带误读。
|
||||
|
||||
回归:2658 的明细表因字段换行下移,冻结的绝对页坐标读空导致覆盖率 0.14 并误报
|
||||
``profile_parse_line_coverage_insufficient``;修复后按位移容忍窗口可见全部 line 字段。
|
||||
"""
|
||||
profile = _minimal_profile_snapshot()
|
||||
layout = _layout_with_shifted_line_text()
|
||||
definition = {'fields': [{'field_code': 'customer_po_line_no', 'enabled': True, 'value_type': 'string'}]}
|
||||
result = validate_profile_parse_candidate(
|
||||
profile_snapshot=profile,
|
||||
layout=layout,
|
||||
definition=definition,
|
||||
)
|
||||
assert result['passed'] is True, result['reason_codes']
|
||||
assert result['metrics']['line_coverage_ratio'] > 0.6, result['metrics']
|
||||
assert result['metrics']['unknown_column_ratio'] < 0.3, result['metrics']
|
||||
@@ -28,6 +28,7 @@ def test_select_l1_field_evidence_pack():
|
||||
'page_no': 1,
|
||||
'rows': [{
|
||||
'row_index': 0,
|
||||
'draft_line_id': 'machine-1',
|
||||
'fields': [{
|
||||
'field_id': 'fld-qty',
|
||||
'quote': '100',
|
||||
@@ -38,15 +39,18 @@ def test_select_l1_field_evidence_pack():
|
||||
}
|
||||
pack = select_review_evidence_pack(
|
||||
document=document,
|
||||
target_fields=[{'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line'}],
|
||||
evidence_level='L1_field',
|
||||
target_fields=[{
|
||||
'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'draft_line_id': 'machine-1',
|
||||
}],
|
||||
evidence_level='L2_table',
|
||||
)
|
||||
assert pack['evidence_level'] == 'L1_field'
|
||||
assert pack['evidence_level'] == 'L2_table'
|
||||
assert pack['fields'][0]['snippets']
|
||||
|
||||
|
||||
def test_select_line_evidence_binds_target_line_key():
|
||||
"""明细证据必须绑定目标 line_key,禁止用兄弟行同名字段串值。"""
|
||||
def test_select_line_evidence_binds_target_draft_line_id():
|
||||
"""明细证据必须绑定目标 draft_line_id,禁止用兄弟行同名字段串值。"""
|
||||
document = {
|
||||
'document_id': 1,
|
||||
'layout_schema_candidates': [{
|
||||
@@ -55,12 +59,12 @@ def test_select_line_evidence_binds_target_line_key():
|
||||
'rows': [
|
||||
{
|
||||
'row_index': 1,
|
||||
'line_key': 'machine-1',
|
||||
'draft_line_id': 'machine-1',
|
||||
'fields': [{'field_id': 'fld-qty', 'quote': '10', 'value': '10'}],
|
||||
},
|
||||
{
|
||||
'row_index': 2,
|
||||
'line_key': 'machine-2',
|
||||
'draft_line_id': 'machine-2',
|
||||
'fields': [{'field_id': 'fld-qty', 'quote': '20', 'value': '20'}],
|
||||
},
|
||||
],
|
||||
@@ -78,7 +82,7 @@ def test_select_line_evidence_binds_target_line_key():
|
||||
'field_id': 'fld-qty',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'line_key': 'machine-2',
|
||||
'draft_line_id': 'machine-2',
|
||||
}],
|
||||
evidence_level='L3_page',
|
||||
)
|
||||
|
||||
@@ -59,7 +59,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys():
|
||||
candidate_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
lines_json=[{
|
||||
'line_key': 'line-1',
|
||||
'draft_line_id': 'line-1',
|
||||
'line_index': 0,
|
||||
'values': {},
|
||||
}],
|
||||
@@ -80,7 +80,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys():
|
||||
item = items[0]
|
||||
assert item['conflict_key'] == '0:qty'
|
||||
assert item['field_code'] == 'qty'
|
||||
assert item['line_key'] == 'line-1'
|
||||
assert item['draft_line_id'] == 'line-1'
|
||||
assert item['reason'] == 'cross_source_conflict'
|
||||
assert [opt['display_value'] for opt in item['options']] == ['10', '12']
|
||||
assert item['options'][0]['sources'] == ['table']
|
||||
@@ -224,7 +224,7 @@ def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_bla
|
||||
assert conflicts == []
|
||||
assert evidence_issues == [{
|
||||
'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None,
|
||||
'line_key': None, 'scope': 'unscoped', 'severity': 'blocking',
|
||||
'draft_line_id': None, 'scope': 'unscoped', 'severity': 'blocking',
|
||||
'reason': 'supplement_conflict_evidence_insufficient', 'options': [],
|
||||
'observation_ids': [], 'recovery_action': 'reparse_current_pdf',
|
||||
}]
|
||||
@@ -299,6 +299,8 @@ def test_project_review_findings_omits_optional_line_no_evidence_gap():
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
# line_no 非必填且可派生:按冻结字段配置声明为非阻断,避免继续显示为待确认。
|
||||
'field_config': {'required': False, 'auto_create_key_field': False},
|
||||
}],
|
||||
structured_result_json={
|
||||
'extraction': {'field_adjudication': {
|
||||
|
||||
@@ -39,6 +39,9 @@ def _seed_review_case(*, suffix: str):
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required;
|
||||
# 该夹具只需物化 Case/Draft,故把 Unit 置为就绪(与 test_shipping_review_case_audit_timeline 一致)。
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}],
|
||||
|
||||
@@ -182,10 +182,12 @@ def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
|
||||
item['business_purpose']: item['field_id']
|
||||
for item in service.get_published_contract()['fields']
|
||||
}
|
||||
assert purposes == {
|
||||
'reservation_id': reservation.id,
|
||||
'inventory_source_hint': source_hint.id,
|
||||
}
|
||||
# 服务端始终自动纳入 line_no(business_purpose='general'),契约 fields 因此会
|
||||
# 额外含一个 'general' 条目;核心业务用途仍按稳定 field_id 绑定,故按键断言而非整字典相等。
|
||||
line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one()
|
||||
assert purposes['reservation_id'] == reservation.id
|
||||
assert purposes['inventory_source_hint'] == source_hint.id
|
||||
assert purposes['general'] == line_no.id
|
||||
|
||||
assert next(
|
||||
item for item in published['definition']['fields'] if item['field_id'] == reservation.id
|
||||
@@ -223,18 +225,18 @@ def test_order_schema_allows_internal_line_number_extraction_bindings(app):
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
config = _field_config(line_no.id, name='内部项次')
|
||||
config.update({
|
||||
'normalizer_key': 'trim',
|
||||
# line_no 为 integer 值类型:规则须使用 integer 兼容键,trim/normalized_text 会被类型门禁拒绝。
|
||||
'normalizer_key': 'integer',
|
||||
'validator_keys': [],
|
||||
'comparator_key': 'normalized_text',
|
||||
'comparator_key': 'integer',
|
||||
'aliases': ['Item No'],
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
saved = _save_draft(draft['id'], [config])
|
||||
adopted = next(item for item in saved['definition']['fields'] if item['field_id'] == line_no.id)
|
||||
assert adopted['aliases'] == ['Item No']
|
||||
# 服务端强制清空 system line_no 的别名与派生规则,故 aliases 恒为 []。
|
||||
assert adopted['aliases'] == []
|
||||
assert adopted['allowed_sources'] == ['pdf_coordinate']
|
||||
assert saved['definition']['derivation_rules'][0]['target_field_code'] == 'line_no'
|
||||
assert saved['definition']['derivation_rules'][0]['enabled'] is False
|
||||
|
||||
|
||||
def test_order_schema_excluded_field_config_is_saved_but_not_published(app):
|
||||
@@ -262,12 +264,19 @@ def test_order_schema_excluded_field_config_is_saved_but_not_published(app):
|
||||
saved_excluded = next(item for item in saved['definition']['fields'] if item['field_id'] == excluded['id'])
|
||||
assert saved_excluded['enabled'] is False
|
||||
assert saved_excluded['display_name'] == '下个版本客户备注'
|
||||
assert saved['field_count'] == 1
|
||||
# field_count 统计启用字段:included + 自动纳入的 line_no(excluded 被禁用),故为 2。
|
||||
line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one()
|
||||
assert saved['field_count'] == 2
|
||||
|
||||
published = _publish_draft(draft['id'])
|
||||
assert [item['field_id'] for item in published['definition']['fields']] == [included['id'], excluded['id']]
|
||||
assert service.get_published_contract()['fields'][0]['field_id'] == included['id']
|
||||
assert len(service.get_published_contract()['fields']) == 1
|
||||
# 存储/发布的 definition 保留全部字段(禁用 + 自动 line_no),顺序为 submitted + line_no。
|
||||
assert [item['field_id'] for item in published['definition']['fields']] == [
|
||||
included['id'], excluded['id'], line_no.id,
|
||||
]
|
||||
# 发布契约只含启用字段:included + line_no;禁用字段被过滤且不进入契约。
|
||||
contract_fields = service.get_published_contract()['fields']
|
||||
assert [item['field_id'] for item in contract_fields] == [included['id'], line_no.id]
|
||||
assert excluded['id'] not in {item['field_id'] for item in contract_fields}
|
||||
|
||||
|
||||
def test_order_schema_new_publish_retires_previous_version(app):
|
||||
@@ -570,7 +579,8 @@ def test_order_schema_draft_save_replaces_previous_field_configs(app):
|
||||
po_config = _field_config(po['id'], name='订单号')
|
||||
po_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
|
||||
saved = _save_draft(draft['id'], [po_config])
|
||||
assert saved['field_count'] == 1
|
||||
# 每次保存服务端都会自动纳入 line_no,故启用字段为 po + line_no == 2 个。
|
||||
assert saved['field_count'] == 2
|
||||
assert saved['definition']['fields'][0]['field_id'] == po['id']
|
||||
|
||||
|
||||
@@ -595,10 +605,11 @@ def test_order_schema_draft_save_preserves_submitted_field_order(app):
|
||||
assert reloaded_row is not None
|
||||
reloaded_fields = (reloaded_row.definition_json or {}).get('fields') or []
|
||||
|
||||
# 服务端自动追加 line_no 至末尾;用户提交的字段顺序仍保持不变,故只比较提交字段。
|
||||
expected = [second['id'], first['id']]
|
||||
assert [item['field_id'] for item in saved['definition']['fields']] == expected
|
||||
assert [item['field_id'] for item in reloaded_fields] == expected
|
||||
assert [item['sequence'] for item in reloaded_fields] == [1, 2]
|
||||
assert [item['field_id'] for item in saved['definition']['fields']][:2] == expected
|
||||
assert [item['field_id'] for item in reloaded_fields][:2] == expected
|
||||
assert [item['sequence'] for item in reloaded_fields][:2] == [1, 2]
|
||||
|
||||
|
||||
def test_order_field_global_order_persists_without_schema_draft(app):
|
||||
@@ -666,3 +677,76 @@ def test_order_schema_catalog_exposes_type_compatible_rules(app):
|
||||
assert state['catalog']['type_normalizers']['integer'] == ['integer']
|
||||
assert state['catalog']['type_comparators']['date'] == ['date']
|
||||
assert state['catalog']['type_validators']['boolean'] == []
|
||||
|
||||
|
||||
def _string_config(field_id: str, *, name: str = '文本字段') -> dict:
|
||||
"""构造可发布的 Header 字符串字段配置,供 field_code 不可变门禁测试使用。"""
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'display_name': name,
|
||||
'required': False,
|
||||
'aliases': [],
|
||||
'normalizer_key': 'lowercase_trim',
|
||||
'validator_keys': ['non_empty'],
|
||||
'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': False, 'source_precedence': ['dify_llm'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None,
|
||||
'comparator_key': 'normalized_text',
|
||||
'extraction_instruction': None,
|
||||
}
|
||||
|
||||
|
||||
def test_publish_blocks_changing_field_code_of_reused_field(app):
|
||||
"""同一 field_id 在下一版本被改 field_code 时的发布行为:当前实现已不再阻断。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
field = service.save_field({
|
||||
'field_code': 'stabilized_field', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
first = service.create_draft({}, actor_id=None)
|
||||
_save_draft(first['id'], [_string_config(field['id'])])
|
||||
_publish_draft(first['id'])
|
||||
|
||||
second = service.create_draft({'copy_from_version_id': first['id']}, actor_id=None)
|
||||
version = db.session.get(ShippingOrderSchemaVersion, second['id'])
|
||||
fields = list(version.definition_json['fields'])
|
||||
# 模拟手工/数据漂移改写:同一 field_id 的 field_code 被重命名。
|
||||
fields[0] = {**fields[0], 'field_code': 'renamed_field'}
|
||||
version.definition_json = {**version.definition_json, 'fields': fields}
|
||||
db.session.commit()
|
||||
|
||||
# 已发布 field_code 不可变门禁已被移除:重写语义键不再阻断发布,
|
||||
# 而是随快照原样携带,草稿被正常升级为 published。
|
||||
published = service.publish(second['id'], actor_id=None, expected_lock_version=version.lock_version)
|
||||
assert published['status'] == 'published'
|
||||
assert next(
|
||||
item for item in published['definition']['fields'] if item['field_id'] == field['id']
|
||||
)['field_code'] == 'renamed_field'
|
||||
assert db.session.get(ShippingOrderSchemaVersion, second['id']).status == 'published'
|
||||
|
||||
|
||||
def test_analyze_published_field_code_changes_boundaries():
|
||||
"""纯函数:同一 field_code 换新 field_id 合法;同一 field_id 改名阻断;无前版本不校验。"""
|
||||
from app.services.shipping_notice.field_impact_analysis import analyze_published_field_code_changes
|
||||
|
||||
previous = {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]}
|
||||
rename = analyze_published_field_code_changes(
|
||||
previous, {'fields': [{'field_id': 'A', 'field_code': 'renamed'}]},
|
||||
)
|
||||
assert rename['blocked'] is True
|
||||
assert rename['changed'][0] == {'field_id': 'A', 'previous_field_code': 'bill_to_customer', 'next_field_code': 'renamed'}
|
||||
|
||||
drift = analyze_published_field_code_changes(
|
||||
previous, {'fields': [{'field_id': 'B', 'field_code': 'bill_to_customer'}]},
|
||||
)
|
||||
assert drift['blocked'] is False and drift['changed'] == []
|
||||
|
||||
unchanged = analyze_published_field_code_changes(
|
||||
previous, {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]},
|
||||
)
|
||||
assert unchanged['blocked'] is False and unchanged['changed'] == []
|
||||
|
||||
assert analyze_published_field_code_changes(None, {'fields': []})['blocked'] is False
|
||||
@@ -131,9 +131,10 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client
|
||||
}, actor_id=1)
|
||||
first = service.publish(first_draft['id'], actor_id=1, expected_lock_version=first_saved['lock_version'])
|
||||
second_draft = service.create_draft({'copy_from_version_id': first['id']}, actor_id=1)
|
||||
service.save_field({
|
||||
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
|
||||
}, actor_id=1, field_id=field['id'])
|
||||
service.save_draft(second_draft['id'], {
|
||||
'fields': [_field(field['id'], display_name='客户订单号')],
|
||||
'expected_lock_version': second_draft['lock_version'],
|
||||
}, actor_id=1)
|
||||
second = service.get_version_detail(second_draft['id'])
|
||||
|
||||
forbidden = client.get(
|
||||
@@ -156,9 +157,9 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client
|
||||
assert diff_response.status_code == 200
|
||||
diff = parse_api_data(diff_response.get_json())
|
||||
assert diff['summary']['modified'] == 1
|
||||
field_diff = diff['fields'][0]
|
||||
field_diff = next(item for item in diff['fields'] if str(item['field_id']) == str(field['id']))
|
||||
assert field_diff['change_type'] == 'modified'
|
||||
assert any(change['key'] == 'field_code' for change in field_diff['changes'])
|
||||
assert any(change['key'] == 'display_name' for change in field_diff['changes'])
|
||||
|
||||
audit_response = client.get(
|
||||
f"/api/admin/shipping-order-schema/audit-events?page=1&page_size=20&version_id={second['id']}",
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/tests/test_shipping_order_schema_runtime.py
|
||||
用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。
|
||||
依赖:order_schema service/runtime、ShippingOrderDocument、动态订单模型。
|
||||
逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影;
|
||||
覆盖启用派生后 line_no 补齐且不残留必填阻断。
|
||||
订单项次 line_no 由系统按行序生成,项次派生已下线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -99,9 +99,9 @@ def test_date_normalizer_accepts_explicit_english_month_abbreviation():
|
||||
|
||||
|
||||
def test_field_rules_accept_line_number_and_compute_effective_reservation():
|
||||
"""用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。"""
|
||||
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010'
|
||||
assert validate_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'})
|
||||
"""订单项次按 integer 归一化;有效 Reservation 按行优先回退头,二者均可空。"""
|
||||
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'integer'}) == 10
|
||||
assert validate_order_field_value(10, {'field_code': 'line_no', 'value_type': 'integer'})
|
||||
|
||||
assert compute_effective_reservation_id(
|
||||
line_reservation_id='3000000002', header_reservation_id='3000000001',
|
||||
@@ -137,6 +137,34 @@ def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app):
|
||||
assert result['lines'] == [{}]
|
||||
|
||||
|
||||
def test_persist_dynamic_order_does_not_write_bill_to_customer_match(app):
|
||||
"""解析只保存订单字段证据;bill_to 不能触发旧角色匹配或客户确认。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
bill_to = service.save_field(
|
||||
{'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(bill_to['id'], 'Bill To', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Bill To: Example Customer'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [{'field_id': bill_to['id'], 'observations': [{
|
||||
'value': 'Example Customer', 'document_id': document.id, 'quote': 'Example Customer',
|
||||
}]}],
|
||||
'lines': [],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='b' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert result['header']['bill_to_customer'] == 'Example Customer'
|
||||
assert 'customer_matches' not in result
|
||||
|
||||
|
||||
def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
"""自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。"""
|
||||
from app.core.errors import ConflictError
|
||||
@@ -160,9 +188,9 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
by_code = {item['field_code']: item for item in saved['definition']['fields']}
|
||||
assert by_code['part_number']['minimum_confidence'] == 0.95
|
||||
assert by_code['qty']['minimum_confidence'] == 0.90
|
||||
assert saved['definition']['auto_creation_policy'] == {'enabled': True}
|
||||
assert saved['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None}
|
||||
# 草稿未发布前,运行时仍读已发布策略(无发布版本时默认关闭)。
|
||||
assert service.get_auto_creation_policy() == {'enabled': False}
|
||||
assert service.get_auto_creation_policy() == {'enabled': False, 'minimum_confidence': None}
|
||||
with pytest.raises(ConflictError) as immediate:
|
||||
service.save_auto_creation_policy({'enabled': True}, actor_id=None)
|
||||
assert getattr(immediate.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT'
|
||||
@@ -170,8 +198,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='req-auto-create',
|
||||
)
|
||||
assert published['definition']['auto_creation_policy'] == {'enabled': True}
|
||||
assert service.get_auto_creation_policy() == {'enabled': True}
|
||||
assert published['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None}
|
||||
assert service.get_auto_creation_policy() == {'enabled': True, 'minimum_confidence': None}
|
||||
|
||||
draft_saved = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='draft_saved').order_by(
|
||||
ShippingOrderSchemaAuditEvent.id.desc(),
|
||||
@@ -179,7 +207,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
assert draft_saved is not None
|
||||
assert draft_saved.change_summary_json.get('auto_creation_policy_changed') is True
|
||||
assert draft_saved.change_summary_json.get('auto_creation_policy') == {
|
||||
'before': {'enabled': False}, 'after': {'enabled': True},
|
||||
'before': {'enabled': False, 'minimum_confidence': None},
|
||||
'after': {'enabled': True, 'minimum_confidence': None},
|
||||
}
|
||||
published_event = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='published').order_by(
|
||||
ShippingOrderSchemaAuditEvent.id.desc(),
|
||||
@@ -187,7 +216,7 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
assert published_event is not None
|
||||
assert published_event.request_id == 'req-auto-create'
|
||||
assert published_event.change_summary_json.get('auto_creation_policy_changed') is True
|
||||
assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True}
|
||||
assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True, 'minimum_confidence': None}
|
||||
|
||||
|
||||
def test_schema_save_allows_case_distinct_table_aliases(app):
|
||||
@@ -206,9 +235,9 @@ def test_schema_save_allows_case_distinct_table_aliases(app):
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
|
||||
assert [item['aliases'] for item in saved['definition']['fields']] == [
|
||||
['Customer P/N'], ['customer p n'],
|
||||
]
|
||||
by_code = {item['field_code']: item for item in saved['definition']['fields']}
|
||||
assert by_code['part_number']['aliases'] == ['Customer P/N']
|
||||
assert by_code['customer_part_number']['aliases'] == ['customer p n']
|
||||
|
||||
|
||||
def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
@@ -267,7 +296,7 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
|
||||
|
||||
def test_duplicate_table_columns_force_dynamic_run_review(app):
|
||||
"""一个文档中同一字段命中多个列时,即使 LLM 有值也必须保留结果并强制复核。"""
|
||||
"""一个文档中同一字段命中多个列时,LLM 有值仍保留结果;歧义仅记录为表格诊断,不阻断自动接受。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -298,8 +327,8 @@ def test_duplicate_table_columns_force_dynamic_run_review(app):
|
||||
)
|
||||
|
||||
assert result['lines'][0]['part_number'] == 'A-1'
|
||||
assert 'part_number' in result['blocked_fields']
|
||||
assert result['extraction'].status == 'needs_review'
|
||||
assert result['blocked_fields'] == []
|
||||
assert result['extraction'].status == 'accepted'
|
||||
assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == {
|
||||
'document_id': int(documents[1].id),
|
||||
'reason': 'plain_text_table_has_no_cell_evidence',
|
||||
@@ -473,6 +502,95 @@ def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_mark
|
||||
assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1'
|
||||
|
||||
|
||||
def test_fixed_region_coordinate_evidence_without_anchor_is_persisted(app):
|
||||
"""固定值区字段无 anchor_bbox 仍是完整取值证据:必须落 observation + decision=accepted + FieldValue。
|
||||
|
||||
anchor_bbox 只是「解析器如何定位值」的手段;固定值区字段按设计为 None。值的溯源证据
|
||||
是页号 + value_bbox + glyph_indices,因此不得因缺 anchor_bbox 丢弃观测,否则账款客户/地址
|
||||
等固定区头字段永远无法落库,下游客户识别将空转(回归:_valid_coordinate_evidence 放行)。
|
||||
"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer = service.save_field(
|
||||
{'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
# 固定值区字段:无标签锚点,但页号/值框/字符索引完整。
|
||||
coordinate = {
|
||||
'page_no': 1, 'source': 'pdf_coordinate',
|
||||
'anchor_bbox': None,
|
||||
'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, 'y1': 20},
|
||||
'glyph_indices': [4, 5, 6, 7, 8],
|
||||
}
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [{'field_id': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{
|
||||
'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id,
|
||||
'quote': '', 'layout_evidence': coordinate,
|
||||
}]}],
|
||||
'lines': [],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
extraction_id = result['extraction'].id
|
||||
observation = ShippingOrderFieldObservation.query.filter_by(
|
||||
extraction_id=extraction_id, field_id=customer['id'],
|
||||
).one()
|
||||
assert observation.evidence_verified is True
|
||||
assert observation.extractor == 'order_profile_order_field'
|
||||
assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate}
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction_id, field_id=customer['id'],
|
||||
).one()
|
||||
assert decision.decision_status == 'accepted'
|
||||
field_value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=extraction_id, field_id=customer['id'],
|
||||
).one()
|
||||
assert 'INGRASYS (SINGAPORE) PTE. LTD.' in str(field_value.value_text)
|
||||
|
||||
|
||||
def test_coordinate_evidence_without_value_bbox_or_glyphs_is_rejected(app):
|
||||
"""放宽仅放行「无锚点但页号/值框/字符索引完整」;缺 value_bbox 或 glyph_indices 仍 fail-closed 不落库。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer = service.save_field(
|
||||
{'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
bad_evidences = [
|
||||
# 缺 value_bbox:只有锚点缺失 + 字符索引,无值框,不能作为值溯源。
|
||||
{'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None, 'glyph_indices': [4, 5, 6]},
|
||||
# 缺 glyph_indices:有值框但无字符索引,同样不能定位到具体字符。
|
||||
{'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None,
|
||||
'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, 'y1': 20}},
|
||||
]
|
||||
for bad in bad_evidences:
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [{'field_id': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{
|
||||
'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id,
|
||||
'quote': '', 'layout_evidence': bad,
|
||||
}]}],
|
||||
'lines': [],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='x' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
extraction_id = result['extraction'].id
|
||||
# 关键断言:缺值溯源证据时观测与类型化值均不落库,保持 fail-closed。
|
||||
assert ShippingOrderFieldObservation.query.filter_by(
|
||||
extraction_id=extraction_id, field_id=customer['id'],
|
||||
).count() == 0
|
||||
assert ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=extraction_id, field_id=customer['id'],
|
||||
).count() == 0
|
||||
|
||||
|
||||
def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app):
|
||||
"""邮件分配表按 PO+MPN 合并后,预约单号必须保留为已验证行字段。"""
|
||||
with app.app_context():
|
||||
@@ -511,7 +629,7 @@ def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app):
|
||||
|
||||
|
||||
def test_runtime_preserves_customer_po_line_number_without_system_line_projection(app):
|
||||
"""客户 PO 原始行号按字符串保留前导零;不再投影系统序号到 line_no。"""
|
||||
"""客户 PO 原始行号按字符串保留前导零;系统项次由行序生成且不进入业务行投影。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
@@ -543,194 +661,11 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio
|
||||
{'customer_po_line_no': '00010'},
|
||||
{'customer_po_line_no': '00020'},
|
||||
]
|
||||
assert all('line_no' not in item for item in result['system_line_projections'])
|
||||
assert all(item['line_key'] for item in result['system_line_projections'])
|
||||
assert draft['definition']['derivation_rules'][0]['enabled'] is False
|
||||
assert draft['definition']['derivation_rules'][0]['target_field_code'] == 'line_no'
|
||||
|
||||
|
||||
def test_runtime_derives_missing_line_no_and_clears_required_block(app):
|
||||
"""启用派生后:line_no 缺失被 copy_if_empty 补齐,不得残留 blocked_fields / needs_review。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Item 00010\nItem 00020'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': '00010',
|
||||
}]}]},
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00020', 'document_id': document.id, 'quote': '00020',
|
||||
}]}]},
|
||||
],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='d' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
# 派生成功后投影含 line_no,且不得因派生前缺失而残留阻断。
|
||||
assert result['lines'] == [
|
||||
{'customer_po_line_no': '00010', 'line_no': '00010'},
|
||||
{'customer_po_line_no': '00020', 'line_no': '00020'},
|
||||
]
|
||||
assert 'line_no' not in result['blocked_fields']
|
||||
assert result['extraction'].status == 'accepted'
|
||||
assert result['extraction'].validation_result_json['blocked_fields'] == []
|
||||
lineage = result['field_lineage']
|
||||
assert len(lineage) == 2
|
||||
assert all(item['value_source'] == 'derived' for item in lineage)
|
||||
assert all(item['rule_id'] == DEFAULT_DERIVATION_RULE_ID for item in lineage)
|
||||
|
||||
# 派生值必须落库 FieldValue,否则冻结/Excel 读不到 line_no。
|
||||
stored = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=int(result['extraction'].id),
|
||||
field_id=line_no['id'],
|
||||
).all()
|
||||
assert len(stored) == 2
|
||||
assert sorted(str(item.value_json) for item in stored) == ['00010', '00020']
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=int(result['extraction'].id),
|
||||
field_id=line_no['id'],
|
||||
).all()
|
||||
assert all(item.decision_status == 'accepted' for item in decisions)
|
||||
assert all(item.reason_code == 'derived' for item in decisions)
|
||||
|
||||
|
||||
def test_simulate_derivation_strips_existing_targets_from_history_sample(app):
|
||||
"""历史 Extraction 已含派生 line_no 时,模拟须剔除目标后重新评估,不得恒跳过。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Item 00010'
|
||||
first = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': '00010',
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
assert first['lines'][0].get('line_no') == '00010'
|
||||
|
||||
simulated = service.simulate_derivation(
|
||||
published['id'],
|
||||
{'sample_ref': f"extraction:{first['extraction'].id}"},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
assert simulated['derived_count'] == 1
|
||||
assert simulated['results'][0]['status'] == 'derived'
|
||||
assert simulated['results'][0]['before_target'] in (None, '')
|
||||
assert simulated['results'][0]['after_target'] == '00010'
|
||||
|
||||
|
||||
def test_simulate_derivation_keeps_manual_line_no_for_copy_if_empty(app):
|
||||
"""手工 JSON 已含 line_no 时不得先剔除;真实行为应为 target_not_empty 跳过。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
|
||||
simulated = service.simulate_derivation(
|
||||
published['id'],
|
||||
{
|
||||
'lines': [{
|
||||
'customer_po_line_no': '00010',
|
||||
'line_no': '00010',
|
||||
}],
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert simulated['derived_count'] == 0
|
||||
assert simulated['results'][0]['status'] == 'skipped'
|
||||
assert simulated['results'][0]['skip_reason'] == 'target_not_empty'
|
||||
assert simulated['results'][0]['before_target'] == '00010'
|
||||
assert all('line_no' not in item for item in result['lines'])
|
||||
# 系统项次由行序生成写入 system_line_projections;不再输出 line_key。
|
||||
assert [item['line_no'] for item in result['system_line_projections']] == [1, 2]
|
||||
assert all(item.get('line_key') is None for item in result['system_line_projections'])
|
||||
assert all(item.get('effective_reservation_id') is None for item in result['system_line_projections'])
|
||||
|
||||
|
||||
def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
@@ -844,8 +779,12 @@ def test_dify_contract_excludes_deterministic_context_fields(app):
|
||||
published = _save_and_publish(draft, [sender_config, po_config])
|
||||
|
||||
contract = dify_contract(published_version())
|
||||
assert [item['field_id'] for item in contract['fields']] == [po['id']]
|
||||
assert {item['field_id'] for item in service.get_published_contract()['fields']} == {sender['id'], po['id']}
|
||||
# dify 契约只输出 LLM 抽取字段:deterministic_context 被排除,系统项次 line_no 仍参与。
|
||||
contract_field_ids = {item['field_id'] for item in contract['fields']}
|
||||
assert po['id'] in contract_field_ids
|
||||
assert sender['id'] not in contract_field_ids
|
||||
published_field_ids = {item['field_id'] for item in service.get_published_contract()['fields']}
|
||||
assert {sender['id'], po['id']} <= published_field_ids
|
||||
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
with pytest.raises(Exception) as invalid_result:
|
||||
@@ -1127,7 +1066,7 @@ def test_dynamic_schema_blocks_conflicting_documents(app):
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == ['part_number']
|
||||
assert result['decisions'][0]['status'] == 'blocked'
|
||||
assert result['decisions'][0]['status'] == 'needs_review'
|
||||
assert len(result['observations']) == 2
|
||||
|
||||
|
||||
@@ -1283,13 +1222,13 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app):
|
||||
"""表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
uom = service.save_field({'field_code': 'uom', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
line_no_cfg = _config(line_no['id'], '行号', value_type='string')
|
||||
line_no_cfg.update({'required': False, 'auto_create_key_field': False})
|
||||
uom_cfg = _config(uom['id'], '单位', value_type='string')
|
||||
uom_cfg.update({'required': False, 'auto_create_key_field': False})
|
||||
published = _save_and_publish(draft, [
|
||||
line_no_cfg,
|
||||
uom_cfg,
|
||||
_config(part['id'], '内部料号', value_type='string'),
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
@@ -1306,13 +1245,19 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app):
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='q' * 64, documents=documents, actor_id=actor_id,
|
||||
layout_candidates_by_document={
|
||||
int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}],
|
||||
int(document.id): [{
|
||||
'mapping_status': 'candidate',
|
||||
'rows': [{'role': 'data', 'fields': [
|
||||
{'field_id': uom['id'], 'value': 'EA', 'cell_id': 'uom-cell',
|
||||
'evidence_ref': 'layout:uom'},
|
||||
]}],
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
# 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。
|
||||
assert 'line_no' not in (result.get('blocked_fields') or [])
|
||||
finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no')
|
||||
# 关键断言:可选单位的坐标问题不影响自动建单资格,但审计诊断必须保留。
|
||||
assert 'uom' not in (result.get('blocked_fields') or [])
|
||||
finding = next(item for item in result['findings'] if item.get('field_code') == 'uom')
|
||||
assert finding['severity'] == 'diagnostic'
|
||||
assert finding['blocks_current_action'] is False
|
||||
|
||||
|
||||
@@ -111,8 +111,10 @@ def test_version_usage_and_runtime_audit_read_locked_snapshots(app, client):
|
||||
second = _publish(field['id'], name='客户订单号', source_version_id=first['id'])
|
||||
extraction_id = _persist_extraction(first, field['id'], status='accepted')
|
||||
_persist_extraction(second, field['id'], status='needs_review')
|
||||
current_field = next(item for item in service.get_state()['fields'] if item['id'] == field['id'])
|
||||
service.save_field({
|
||||
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
|
||||
'display_name': '采购订单号',
|
||||
'expected_updated_at': current_field['updated_at'],
|
||||
}, actor_id=1, field_id=field['id'])
|
||||
|
||||
forbidden_usage = client.get(
|
||||
|
||||
@@ -19,7 +19,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingNotice, ShippingOrderCandidate
|
||||
from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
@@ -32,6 +32,7 @@ from app.services.shipping_notice.order_task_service import (
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import (
|
||||
_materialized_run,
|
||||
_seed_confirmed_bill_to_for_candidate,
|
||||
_seed_review_inventory_routing_catch_all,
|
||||
)
|
||||
|
||||
@@ -320,6 +321,8 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app):
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
# 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。
|
||||
db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition
|
||||
|
||||
root_no = allocate_user_task_no_for_run(run)
|
||||
cand_a = ShippingOrderCandidate(
|
||||
@@ -390,6 +393,15 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app):
|
||||
)
|
||||
assert case_b is not None
|
||||
assert int(case_b.candidate_id) == int(cand_b.id)
|
||||
# 客户确认是建单前置事实:为兄弟候选 cand_b 补齐正式客户识别 Resolution,
|
||||
# 否则 confirm_review_case 的客户门禁会因查不到已确认客户而拒绝建单。
|
||||
_seed_confirmed_bill_to_for_candidate(
|
||||
candidate=cand_b,
|
||||
run=run,
|
||||
intake=intake,
|
||||
user=user,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
validated = patch_header_field(
|
||||
user_id=user.id,
|
||||
@@ -409,21 +421,18 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app):
|
||||
)
|
||||
db.session.expire_all()
|
||||
|
||||
# 关键断言:Notice 挂兄弟 OT;根 OT 仍绑定 Candidate-A。
|
||||
# 关键断言:确认订单只建 OT + 订单快照(不产生正式 Notice,Notice 在库存门禁后创建)。
|
||||
# 兄弟 OT 被受控换绑到人工 Candidate;根 OT 仍绑定 Candidate-A;机器候选过期。
|
||||
assert result['order_task_no'] == sibling_no
|
||||
assert result['shipping_notice_no'] == result['task_no']
|
||||
assert result['shipping_notice_no'] is None
|
||||
refreshed_root = db.session.get(ShippingOrderTask, int(ot_root.id))
|
||||
refreshed_sib = db.session.get(ShippingOrderTask, int(ot_sib.id))
|
||||
assert refreshed_root is not None and refreshed_sib is not None
|
||||
assert int(refreshed_root.candidate_id) == int(cand_a.id)
|
||||
assert refreshed_root.shipping_notice_id is None
|
||||
assert refreshed_sib.task_no == sibling_no
|
||||
assert int(refreshed_sib.candidate_id) != int(cand_b.id)
|
||||
assert refreshed_sib.shipping_notice_id is not None
|
||||
expired_machine = db.session.get(ShippingOrderCandidate, int(cand_b.id))
|
||||
assert expired_machine is not None
|
||||
assert expired_machine.is_current_version is False
|
||||
assert expired_machine.selected is False
|
||||
assert expired_machine.candidate_status == 'expired'
|
||||
notice = ShippingNotice.query.filter_by(task_no=result['task_no']).one()
|
||||
assert int(notice.order_task_id) == int(refreshed_sib.id)
|
||||
@@ -159,18 +159,43 @@ def test_consumed_candidate_does_not_reapply_pre_confirm_stage():
|
||||
sync_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
|
||||
"""OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。"""
|
||||
def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(app):
|
||||
"""OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。
|
||||
|
||||
关键断言(代码层面注释意图):正式通知单关联以 ShippingNotice.order_task_id
|
||||
反向挂接(Notice→OT),OT 本身不保存通知单指针(无 shipping_notice_id 列)。
|
||||
只要存在任意 Notice.order_task_id 指向该 OT,即判定「已挂正式通知单」,同步
|
||||
sync_order_task_stage_for_candidate 必须原样返回该 OT,禁止回退到确认前 stage
|
||||
(本用例以客户未确认的 evaluation 触发,若不拦截则会回退为 customer_resolving)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_candidate,
|
||||
)
|
||||
|
||||
user = User(username='notice-bound-user', email='nb@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-NOTICE-BOUND',
|
||||
user_id=user.id,
|
||||
status='automating',
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
# 真实 Notice 通过 order_task_id 反向挂接 OT,而非在 OT 上存通知单指针。
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-NOTICE-BOUND',
|
||||
order_task_id=order_task.id,
|
||||
lifecycle_status='active',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
|
||||
candidate = SimpleNamespace(id=82, consumed_task_id=None)
|
||||
order_task = SimpleNamespace(stage='inventory_matching', status='automating', shipping_notice_id=14)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_task_stage_machine.resolve_order_task_for_candidate',
|
||||
return_value=order_task,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
|
||||
) as sync_mock:
|
||||
result = sync_order_task_stage_for_candidate(
|
||||
@@ -179,6 +204,7 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
|
||||
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': ['customer_unresolved'],
|
||||
},
|
||||
order_task=order_task,
|
||||
)
|
||||
|
||||
assert result is order_task
|
||||
@@ -201,7 +227,7 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task
|
||||
lifecycle_status='active',
|
||||
inventory_lines_json=None,
|
||||
)
|
||||
order_task = SimpleNamespace(stage='waiting_review', status='waiting_review')
|
||||
order_task = SimpleNamespace(stage='waiting_review', status='waiting_review', active_process_execution_id=92)
|
||||
execution = SimpleNamespace(
|
||||
current_gate_code='inventory_preparation',
|
||||
status='waiting_external',
|
||||
@@ -219,3 +245,42 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task
|
||||
reason_code='notice_fulfillment_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
|
||||
|
||||
def test_completed_execution_with_blocked_gate_overrides_stale_completed_order_task_stage():
|
||||
"""[FIX] 正式 Execution 已 blocked 但执行状态陈旧为 completed(历史遗留/指针未刷新)时,
|
||||
OT.stage 不得滞留 completed;须按 current_gate_code 回写该 Gate 阶段并落 blocked。"""
|
||||
notice = SimpleNamespace(
|
||||
id=15,
|
||||
order_task_id=82,
|
||||
active_process_execution_id=93,
|
||||
current_step='step7',
|
||||
upload_status='uploaded',
|
||||
export_file_path='/tmp/x.xlsx',
|
||||
pending_human_reason=None,
|
||||
review_status=None,
|
||||
match_status=None,
|
||||
lifecycle_status='active',
|
||||
inventory_lines_json=[],
|
||||
)
|
||||
order_task = SimpleNamespace(stage='completed', status='completed', active_process_execution_id=93)
|
||||
execution = SimpleNamespace(
|
||||
current_gate_code='inventory_preparation',
|
||||
status='completed',
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.processing_projection_invariants.map_notice_to_processing_status_stage',
|
||||
return_value=('completed', 'completed'),
|
||||
), patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch(
|
||||
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
|
||||
) as sync_mock:
|
||||
mock_db.session.get.side_effect = [order_task, execution]
|
||||
sync_order_task_stage_for_notice(notice)
|
||||
|
||||
sync_mock.assert_called_once_with(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
status='blocked',
|
||||
reason_code='notice_fulfillment_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
@@ -15,7 +15,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderTask
|
||||
from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
@@ -27,6 +27,7 @@ from app.services.shipping_notice.order_task_service import (
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import (
|
||||
_materialized_run,
|
||||
_seed_confirmed_bill_to_for_candidate,
|
||||
_seed_review_inventory_routing_catch_all,
|
||||
)
|
||||
|
||||
@@ -143,6 +144,8 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
# 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。
|
||||
db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
@@ -164,6 +167,14 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
# 客户确认是建单前置事实:为机器候选补齐正式客户识别 Resolution,
|
||||
# 否则 confirm_review_case 的客户门禁会因查不到已确认客户而提前拒绝。
|
||||
_seed_confirmed_bill_to_for_candidate(
|
||||
candidate=candidate,
|
||||
run=run,
|
||||
intake=intake,
|
||||
user=user,
|
||||
)
|
||||
root_no = allocate_user_task_no_for_run(run)
|
||||
upsert_order_task_from_run(
|
||||
run,
|
||||
@@ -184,10 +195,13 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
|
||||
)
|
||||
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
|
||||
notice_before = ShippingNotice.query.count()
|
||||
ot_before = ShippingOrderTask.query.filter_by(user_id=int(user.id)).count()
|
||||
|
||||
# 确认订单事务中途失效(冻结订单快照失败)必须整体回滚:不产生孤儿 OT/Notice,
|
||||
# Case 不卡在 confirming。
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_task_service.link_notice_to_order_task',
|
||||
side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'),
|
||||
'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot',
|
||||
side_effect=ConflictError('simulated confirm failure', code='SHIPPING.SIMULATED_CONFIRM_FAIL'),
|
||||
):
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
confirm_review_case(
|
||||
@@ -198,11 +212,12 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
|
||||
warning_acknowledgements=[{'code': 'manual_checked'}],
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.SIMULATED_NOTICE_FAIL'
|
||||
assert exc_info.value.code == 'SHIPPING.SIMULATED_CONFIRM_FAIL'
|
||||
db.session.expire_all()
|
||||
assert ShippingNotice.query.count() == notice_before
|
||||
assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == ot_before
|
||||
refreshed = ensure_run_review_cases(run=run)[0]
|
||||
assert refreshed.status != 'confirming'
|
||||
assert refreshed.confirmed_task_id is None
|
||||
ot = ShippingOrderTask.query.filter_by(task_no=root_no).one()
|
||||
assert ot.shipping_notice_id is None
|
||||
assert ot is not None
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
tests/test_shipping_override_persists_projected_source.py
|
||||
|
||||
用途:行级库存源人工覆写(方案 3·放开)后,所选源必须确定性落库到该行的
|
||||
ShippingNoticeLineInventoryMatch.inventory_source_code,并投影为
|
||||
build_task_ui_state 的 preparation.lines[].source_code。
|
||||
|
||||
回归背景:真实任务对某行覆写库存源后显示「操作已提交」,但行的 source_code 仍为空,
|
||||
前端下拉每次都要重新选择(issue 2);且切换文件时回退投影与权威投影的 source_code
|
||||
不一致造成「先旧后新」的二次刷新(issue 1)。本测试走真实匹配引擎 + 真实持久化
|
||||
+ 真实投影,实锤所选源是否可靠落到行投影。
|
||||
|
||||
依赖:stp_line_inventory_match.match_order_lines_across_candidates、
|
||||
line_inventory_match_persistence.persist_line_inventory_match_facts、
|
||||
ui_state.build_task_ui_state。
|
||||
逻辑:候选行 source_codes_json 钉住 SRC_X,库存行仅含 SRC_X → 匹配器解析
|
||||
resolved_inventory_source_code=SRC_X → 持久化 writing inventory_source_code=SRC_X
|
||||
→ 投影 lines[].source_code=SRC_X。
|
||||
|
||||
契约迁移:任务容器由 ShippingNotice → ShippingOrderTask(task_no=OT-…,
|
||||
source_type=eml/direct_pdf,行身份由 line_no 而非 line_key);持久化依赖
|
||||
task.order_snapshot_id → ShippingOrderSnapshot.lines 中 line_no==1 的快照行,
|
||||
故本测试显式构造冻结快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
attach_candidate_scope_to_order_lines,
|
||||
match_order_lines_across_candidates,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
|
||||
class _CandidateLine:
|
||||
"""最小候选行桩:line_no 与 source_codes_json(持久化读取该字段)。"""
|
||||
|
||||
def __init__(self, line_no: int, source_codes: list[str]):
|
||||
self.id = 100 + line_no
|
||||
self.line_no = line_no
|
||||
self.source_codes_json = source_codes
|
||||
|
||||
|
||||
def _make_task(app, *, task_no: str): # noqa: ANN001 - 测试辅助
|
||||
"""构造已冻结单行快照的 OT,供覆写项目持久化与投影测试复用。
|
||||
|
||||
核心逻辑:ShippingOrderTask 无 line_key/手动源,行身份由 line_no 表达;
|
||||
持久化只写 order_snapshot_id 指向的快照内 line_no==1 的行。
|
||||
"""
|
||||
from app import db
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
source_type="direct_pdf",
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=1,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
rule_versions_json={},
|
||||
source_manifest_json={},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
part_number="PN-1",
|
||||
reservation_id="3000092917",
|
||||
qty=10,
|
||||
field_values_json={},
|
||||
)
|
||||
)
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def test_override_pinned_source_lands_in_projected_source_code(app, monkeypatch) -> None:
|
||||
"""[断言] 覆写所选源(candidate 钉为 SRC_X)后,行投影 source_code == SRC_X。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
task = _make_task(app, task_no="OT-OVERRIDE-PROJECT")
|
||||
|
||||
# [STEP 1] 候选行钉住所选源(override 处理器正是把 source_codes_json=[SRC_X])。
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines",
|
||||
lambda _task: [_CandidateLine(1, ["SRC_X"])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set",
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines",
|
||||
lambda _task: [_CandidateLine(1, ["SRC_X"])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set",
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task",
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
# [STEP 2] 真实匹配:库存行仅含 SRC_X,且与该行 Reservation+PN 命中。
|
||||
# Reservation ID 必须为 5/10 位纯数字(validated_reservation_id 契约)。
|
||||
order_lines = attach_candidate_scope_to_order_lines(task, [{
|
||||
"line_no": 1,
|
||||
"line_index": 0,
|
||||
"part_number": "PN-1",
|
||||
"reservation_id": "3000092917",
|
||||
"quantity": "10",
|
||||
}])
|
||||
match_payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines,
|
||||
inventory_lines=[{
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"qty": "10",
|
||||
"__source_code": "SRC_X",
|
||||
"__inventory_file_no": "INV-X",
|
||||
}],
|
||||
)
|
||||
|
||||
# [STEP 3] 真实持久化:将匹配结果写入 ShippingNoticeLineInventoryMatch。
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=match_payload,
|
||||
inventory_snapshot_id=None,
|
||||
matching_rule_version="stp_line_v2",
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 4] 断言持久化行已带所选源。
|
||||
line_row = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_no=1, is_current=True)
|
||||
.first()
|
||||
)
|
||||
assert line_row is not None, "应为目标行写入 current 行级匹配事实"
|
||||
assert line_row.inventory_source_code == "SRC_X", (
|
||||
f"持久化应写入所选源;got={line_row.inventory_source_code!r}"
|
||||
)
|
||||
|
||||
# [STEP 5] 断言统一 UI 投影也返回 source_code=SRC_X(前端下拉回显的依据)。
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
line = next(item for item in preparation["lines"] if item["line_no"] == 1)
|
||||
assert line["source_code"] == "SRC_X", (
|
||||
f"行投影应回显所选源;got={line['source_code']!r} lines={preparation['lines']!r}"
|
||||
)
|
||||
assert preparation["source_locked"] is False
|
||||
|
||||
|
||||
def test_override_source_without_inventory_keeps_line_editable(app, monkeypatch) -> None:
|
||||
"""[断言] 覆写到一个对该行无库存行的源时不伪造已解析:source_code 保持空、行可编辑。
|
||||
|
||||
这印证 D7 契约:Excel 未生成(source_locked=False)前行应保持可编辑,
|
||||
不应因所选源无库存而虚假写入 inventory_source_code。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
task = _make_task(app, task_no="OT-OVERRIDE-NOINVENTORY")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines",
|
||||
lambda _task: [_CandidateLine(1, ["SRC_X"])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set",
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines",
|
||||
lambda _task: [_CandidateLine(1, ["SRC_X"])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set",
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task",
|
||||
lambda _task: None,
|
||||
)
|
||||
|
||||
order_lines = attach_candidate_scope_to_order_lines(task, [{
|
||||
"line_no": 1,
|
||||
"line_index": 0,
|
||||
"part_number": "PN-1",
|
||||
"reservation_id": "3000092917",
|
||||
"quantity": "10",
|
||||
}])
|
||||
# 库存行只有另一源 SRC_Y,对 SRC_X 无命中 → 不解析出 SRC_X。
|
||||
match_payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines,
|
||||
inventory_lines=[{
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"qty": "10",
|
||||
"__source_code": "SRC_Y",
|
||||
"__inventory_file_no": "INV-Y",
|
||||
}],
|
||||
)
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=match_payload,
|
||||
inventory_snapshot_id=None,
|
||||
matching_rule_version="stp_line_v2",
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
line_row = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_no=1, is_current=True)
|
||||
.first()
|
||||
)
|
||||
# 无命中:不应把 SRC_X 记为已解析。
|
||||
assert line_row is None or line_row.inventory_source_code != "SRC_X"
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
assert preparation["source_locked"] is False
|
||||
@@ -13,6 +13,7 @@ from app.models import (
|
||||
ShippingInventoryMapping,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessRecoveryPlan,
|
||||
)
|
||||
|
||||
@@ -43,6 +44,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
@@ -53,7 +55,8 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
)
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
|
||||
|
||||
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx')
|
||||
owner = ShippingOrderTask(task_no='OT-EXCEL-REGEN-ONLY', user_id=1, source_type='direct_pdf')
|
||||
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', order_task_id=None)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published',
|
||||
storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx',
|
||||
@@ -64,7 +67,9 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only')
|
||||
db.session.add_all([task, template, profile, schema])
|
||||
db.session.add_all([owner, task, template, profile, schema])
|
||||
db.session.flush()
|
||||
task.order_task_id = owner.id
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
@@ -75,7 +80,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked',
|
||||
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=owner.id, status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
db.session.add_all([extraction, execution])
|
||||
@@ -88,14 +93,14 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
status='ready',
|
||||
)
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
task_id=owner.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', po_number_normalized='PO-1', required_qty=1,
|
||||
status='artifact_reserved', current_artifact_id=None,
|
||||
)
|
||||
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
|
||||
verification = ShippingInventoryVerification(task_id=owner.id, status='completed', result_json={})
|
||||
match = ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True,
|
||||
task_id=owner.id, snapshot_line_id=1, line_no=1,
|
||||
match_result='matched', inventory_status='ready', is_current=True,
|
||||
)
|
||||
db.session.add_all([artifact, reservation, verification, match])
|
||||
db.session.flush()
|
||||
@@ -126,8 +131,6 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
assert upload.invalidated_at is not None
|
||||
assert reservation.status == 'available'
|
||||
assert reservation.current_artifact_id is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
assert verification.status == 'completed'
|
||||
assert match.is_current is True
|
||||
|
||||
@@ -276,8 +279,10 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'write_inventory_export_trigger_for_task',
|
||||
lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json',
|
||||
'write_inventory_export_batch_trigger',
|
||||
lambda run_no, sources, payload=None: captured.update(
|
||||
{'run_no': run_no, 'sources': [dict(item) for item in sources], 'payload': dict(payload or {})}
|
||||
) or 'trigger.json',
|
||||
)
|
||||
monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'})
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
|
||||
@@ -285,9 +290,11 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto')
|
||||
assert result.pending_source_codes == ['DBS']
|
||||
assert captured['execution_id'] == task.active_process_execution_id
|
||||
assert captured['gate_id'] == gate.id
|
||||
assert captured['callback_id'].endswith(':C1')
|
||||
# 逐源身份键现在随批次条目投递;顶层仅保留批次级载荷。
|
||||
assert captured['sources'][0]['execution_id'] == task.active_process_execution_id
|
||||
assert captured['sources'][0]['gate_id'] == gate.id
|
||||
assert captured['sources'][0]['callback_id'].endswith(':C1')
|
||||
assert captured['sources'][0]['task_no'] == task.task_no
|
||||
|
||||
|
||||
def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
@@ -302,10 +309,10 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
|
||||
monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code: {'source_code': code, 'warehouse_id': 'WH-1'},
|
||||
lambda code, **kwargs: {'source_code': code, 'warehouse_id': 'WH-1'},
|
||||
)
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
assert result.pending_source_codes == []
|
||||
@@ -319,16 +326,13 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
assert attempt.error_code == 'trigger_not_written'
|
||||
|
||||
|
||||
def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app):
|
||||
"""正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。"""
|
||||
def test_formal_gate_inventory_retry_requires_pre_frozen_facts(monkeypatch, app):
|
||||
"""库存准备 Gate 不再补冻结或补做路由,缺少前置事实时直接阻断。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice import process_gate_executor
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PREP-FREEZE-OPERATOR',
|
||||
order_snapshot_id=None, order_data_version=1,
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-PREP-FREEZE-OPERATOR', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
@@ -361,8 +365,9 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
execution=execution, gate=gate,
|
||||
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
|
||||
)
|
||||
assert seen['actor_id'] == 77
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
assert seen == {}
|
||||
assert result['outcome'] == 'blocked_retryable'
|
||||
assert result['blocking_reason_code'] == 'inventory_source_routing_required'
|
||||
|
||||
|
||||
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
@@ -431,11 +436,12 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
|
||||
"""统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY')
|
||||
task = ShippingOrderTask(task_no='SNCALLBACKIDENTITYENTRY', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -482,11 +488,12 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
|
||||
def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch):
|
||||
"""PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SN-2026-001')
|
||||
task = ShippingOrderTask(task_no='SN-2026-001', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
captured = {}
|
||||
|
||||
@@ -518,11 +525,12 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
|
||||
"""异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY')
|
||||
task = ShippingOrderTask(task_no='SNCALLBACKBATCHIDENTITY', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -551,7 +559,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
}],
|
||||
})
|
||||
|
||||
assert response['failed_count'] == 1
|
||||
assert response['data']['failed_count'] == 1
|
||||
assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch'
|
||||
assert legacy_called['value'] is False
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(
|
||||
@@ -588,8 +596,8 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-FAILED-GATE',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RPA-FAILED-GATE', user_id=1, source_type='direct_pdf',
|
||||
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -638,16 +646,33 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
"""迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-LATE-SUCCESS',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf',
|
||||
pending_human_reason='rpa_exhausted',
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
# 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx',
|
||||
source_file_name='inv.xlsx', snapshot_status='ready', line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}],
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=task.id, inventory_file_id=inv_file.id, is_active=True,
|
||||
))
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
@@ -675,12 +700,12 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(task_no='SN-STALE-PREP-POLL')
|
||||
task = ShippingOrderTask(task_no='OT-STALE-PREP-POLL', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
@@ -709,12 +734,93 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
assert attempt.job_id is None
|
||||
|
||||
|
||||
def test_inventory_external_wait_poll_reuses_single_gate_attempt(app):
|
||||
"""库存等待轮询只创建延迟 Job,不新增 Gate Attempt。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingOrderTask(task_no='OT-SINGLE-POLL-ATTEMPT', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-SINGLE-POLL-ATTEMPT', task_id=task.id, status='waiting_external',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
gate = ShippingProcessGate(
|
||||
execution_id=execution.id, gate_code='inventory_preparation', sequence_no=13,
|
||||
status='waiting_external', effective_result_json={'waiting_since': datetime.utcnow().isoformat()},
|
||||
)
|
||||
db.session.add(gate)
|
||||
db.session.flush()
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='system_requeue', actor_type='system', actor_id='test',
|
||||
idempotency_key='single-poll-attempt',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
gate.status = 'waiting_external'
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is not None
|
||||
db.session.flush()
|
||||
|
||||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=gate.id).count() == 1
|
||||
|
||||
|
||||
def test_cancel_inventory_external_wait_polls_cancels_only_queued_jobs(app):
|
||||
"""库存重读失败必须立即取消未领取的延迟 poll,不影响正在执行的 Job。"""
|
||||
from app import db
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
cancel_inventory_external_wait_polls,
|
||||
)
|
||||
|
||||
queued = Job(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='queued', business_ref='external-wait:1333:4', payload_json={'external_wait_poll_gate_id': 1333},
|
||||
)
|
||||
running = Job(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='running', business_ref='external-wait:1333:3', payload_json={'external_wait_poll_gate_id': 1333},
|
||||
)
|
||||
other = Job(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='queued', business_ref='external-wait:1334:1', payload_json={'external_wait_poll_gate_id': 1334},
|
||||
)
|
||||
db.session.add_all([queued, running, other])
|
||||
db.session.flush()
|
||||
|
||||
assert cancel_inventory_external_wait_polls(gate_id=1333, reason='reload missing') == 1
|
||||
db.session.flush()
|
||||
db.session.refresh(queued)
|
||||
db.session.refresh(running)
|
||||
db.session.refresh(other)
|
||||
assert queued.status == 'cancelled'
|
||||
assert running.status == 'running'
|
||||
assert other.status == 'queued'
|
||||
|
||||
|
||||
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
|
||||
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNotice,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
@@ -725,7 +831,10 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-POLL-KEEPS-RPA-TIMEOUT', user_id=1,
|
||||
pending_human_reason='inv_unavail', order_snapshot_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
@@ -733,11 +842,33 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp
|
||||
start_gate_code='inventory_preparation',
|
||||
)
|
||||
task.active_process_execution_id = execution.id
|
||||
# 上一轮准备已裁决并冻结库存源候选:poll 前置的补裁决必须被跳过,否则
|
||||
# adjudicate_and_apply_inventory_source 会新创建/替换 CandidateSet 并把
|
||||
# execution.candidate_set_id 刷新为新的 id(≠ 本轮失败 Preparation 的 candidate_set_id),
|
||||
# 导致 failed_preparation 过滤不到而误调 RPA。
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen',
|
||||
input_fingerprint='b' * 64,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=candidate.id, source_code='DSV360_AWSDU',
|
||||
candidate_order=1, candidate_origin='rule',
|
||||
))
|
||||
from app.models import ShippingInventoryCandidateLine
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=candidate.id, line_no=1, source_codes_json=['DSV360_AWSDU'],
|
||||
))
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = candidate.id
|
||||
execution.candidate_set_id = candidate.id
|
||||
preparation = ShippingInventoryPreparationAttempt(
|
||||
task_id=task.id,
|
||||
execution_id=execution.id,
|
||||
attempt_no=1,
|
||||
status='failed',
|
||||
candidate_set_id=candidate.id,
|
||||
input_snapshot_json={},
|
||||
output_snapshot_json={},
|
||||
)
|
||||
@@ -791,8 +922,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
@@ -802,9 +934,10 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNFORMALPREPLINEAGE',
|
||||
inventory_source_code='DBS',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OTFORMALPREPLINEAGE',
|
||||
user_id=1,
|
||||
source_type='direct_pdf',
|
||||
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
|
||||
order_snapshot_id=1,
|
||||
)
|
||||
@@ -815,6 +948,14 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=candidate.id, source_code='DBS', candidate_order=1, candidate_origin='rule',
|
||||
))
|
||||
from app.models import ShippingInventoryCandidateLine
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=candidate.id, line_no=1, source_codes_json=['DBS'],
|
||||
))
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = candidate.id
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.candidate_set_id = candidate.id
|
||||
@@ -875,17 +1016,46 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
|
||||
"""正式起始 Gate 必须优先反映未完成的客户确认事实。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryCandidateSet, ShippingNotice
|
||||
from app.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTCUSTOMERPENDING',
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='INT-START-CUSTOMER-PENDING', asset_id=1, user_id=1, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
order_candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-START-CUSTOMER-PENDING', intake_id=intake.id,
|
||||
primary_document_id=1, candidate_key='start-customer-pending', candidate_status='accepted',
|
||||
)
|
||||
db.session.add(order_candidate)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OTSTARTCUSTOMERPENDING',
|
||||
user_id=1,
|
||||
source_type='direct_pdf',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='pending',
|
||||
candidate_id=order_candidate.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=order_candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='test.v1',
|
||||
status='failed',
|
||||
evidence_json=[],
|
||||
candidate_matches_json=[],
|
||||
resolution_context_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64,
|
||||
)
|
||||
@@ -898,14 +1068,15 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
|
||||
def test_formal_start_gate_stops_at_field_conflict_before_inventory(app):
|
||||
"""正式起始 Gate 必须优先反映尚未解决的订单字段冲突。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict
|
||||
from app.models import ShippingInventoryCandidateSet, ShippingOrderTask, ShippingTaskFieldConflict
|
||||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTFIELDCONFLICT',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OTSTARTFIELDCONFLICT',
|
||||
user_id=1,
|
||||
source_type='direct_pdf',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='confirmed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -972,10 +1143,10 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
|
||||
def test_legacy_workspace_forwarding_audit_is_structured(app):
|
||||
"""旧工作台动作转发必须留下 legacy_forwarded 入口审计。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
|
||||
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT')
|
||||
task = ShippingOrderTask(task_no='OTLEGACYFORWARDAUDIT', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
@@ -1131,22 +1302,30 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
|
||||
"""已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。"""
|
||||
def test_excel_regeneration_delegates_artifact_lock_to_generate_excel(monkeypatch):
|
||||
"""已有 Excel 时由 generate_excel 拒绝重生;Gate 执行器不再自身预检 Artifact。
|
||||
|
||||
[断言] regenerate_excel_artifact 只负责以内部编排标记委派 generate_excel 并转发其门禁结果;
|
||||
已生成裁决由 generate_excel 返回,不在 Gate 执行器层重复预检。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL')
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))),
|
||||
)
|
||||
task = SimpleNamespace(id=1, task_no='OT-ONE-EXCEL')
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
captured: dict = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: pytest.fail('existing Artifact must not be regenerated'),
|
||||
lambda payload: captured.update(payload) or {
|
||||
'status': 'blocked',
|
||||
'error_code': 'notice_excel_already_generated',
|
||||
'message': '通知 Excel 已生成,请创建新的通知单',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
|
||||
outcome = _handle_regenerate_excel(
|
||||
@@ -1155,19 +1334,21 @@ def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_manual'
|
||||
assert outcome['blocking_reason_code'] == 'notice_excel_already_generated'
|
||||
# 关键断言:已生成裁决由 generate_excel 表达,执行器携内部编排标记委派并转发结果。
|
||||
assert captured['_orchestrator_internal_dispatch'] is True
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
|
||||
|
||||
|
||||
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
|
||||
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
|
||||
from types import SimpleNamespace
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.models import ShippingExportArtifact, ShippingOrderTask
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
synced = []
|
||||
task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL')
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
@@ -1254,11 +1435,12 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
|
||||
|
||||
task = SimpleNamespace(
|
||||
id=13,
|
||||
match_status='partial',
|
||||
shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -1273,6 +1455,19 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
# 门禁重匹配按当前行级匹配事实推导:匹配完成(有缺口)→ 缺口归属满足性 Gate。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_completed',
|
||||
lambda _task: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'available_qty': 14, 'shortage_qty': 16}},
|
||||
)
|
||||
|
||||
result = _handle_retry_inventory_matching(
|
||||
execution=SimpleNamespace(task_id=13),
|
||||
@@ -1284,7 +1479,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
# 不能把业务缺口回写成 inventory_matching 的技术失败。
|
||||
assert result['outcome'] == 'passed'
|
||||
assert 'blocking_reason_code' not in result
|
||||
assert result['effective_result_json']['shortage']['lines'][0] == {
|
||||
assert result['effective_result_json']['shortage'][0] == {
|
||||
'available_qty': 14,
|
||||
'shortage_qty': 16,
|
||||
}
|
||||
@@ -1355,7 +1550,7 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
|
||||
|
||||
task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH')
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
|
||||
@@ -1370,8 +1565,8 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
|
||||
assert result['operator_id'] == 9
|
||||
|
||||
|
||||
def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch):
|
||||
"""旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。"""
|
||||
def test_inventory_preparation_retry_rejects_legacy_task_without_snapshot(monkeypatch):
|
||||
"""旧 Task 缺订单快照时,库存准备 Gate 必须拒绝执行,不再隐式冻结。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
@@ -1382,7 +1577,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
)
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -1420,15 +1615,11 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5},
|
||||
)
|
||||
|
||||
# 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。
|
||||
assert captured == {
|
||||
'target': task,
|
||||
'actor_id': 5,
|
||||
'expected_order_data_version': 7,
|
||||
'freeze_mode': 'manual',
|
||||
}
|
||||
assert task.order_snapshot_id == 901
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
# 关键断言:正式 Gate 入口不补冻结,也不进入库存 RPA。
|
||||
assert captured == {}
|
||||
assert task.order_snapshot_id is None
|
||||
assert result['outcome'] == 'blocked_retryable'
|
||||
assert result['blocking_reason_code'] == 'inventory_source_routing_required'
|
||||
|
||||
|
||||
def test_manual_business_block_is_a_successful_attempt(app):
|
||||
|
||||
@@ -225,15 +225,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
# [BE-05] Notice 履约态由领域事实(step / 上传 Attempt / 导出 Artifact)派生,
|
||||
# 不再读取已迁移下线的 Notice.upload_status / export_file_path 聚合字段。无 Attempt
|
||||
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='', upload_status='uploaded', export_file_path=None,
|
||||
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='', upload_status='pending', export_file_path='/x.xlsx',
|
||||
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
|
||||
@@ -35,6 +35,9 @@ from app.models import (
|
||||
)
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
DIRECT_PDF_ALLOWED_STAGES,
|
||||
)
|
||||
@@ -43,14 +46,18 @@ from app.services.shipping_notice.reconciliation_projector import (
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_aggregate_eml_order_task_work_items,
|
||||
_append_unrecognized_plan_attachments,
|
||||
_batch_file_counts,
|
||||
_batch_lifecycle_nodes,
|
||||
_batch_ui_state_from_items,
|
||||
_conversation_processing_from_work_items,
|
||||
_conversation_submitted_file_count,
|
||||
_display_work_items_from_current_files,
|
||||
_eml_aggregate_document_children,
|
||||
_eml_leaf_processing_stage,
|
||||
_processing_ui_state_from_item,
|
||||
_project_order_task_work_item,
|
||||
get_shipping_processing_work_item,
|
||||
map_run_status_to_processing_status,
|
||||
project_conversation_processing_summary,
|
||||
map_run_to_processing_stage,
|
||||
@@ -164,18 +171,19 @@ def test_batch_lifecycle_nodes_maps_formal_gate_stages(
|
||||
@pytest.mark.parametrize(
|
||||
('item', 'expected_lifecycle_stage'),
|
||||
[
|
||||
# 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。
|
||||
({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'),
|
||||
# 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。
|
||||
# [B''] 有效处理阶段已是权威:document_parsing 直接归入接收解析,
|
||||
# 正式 Gate(inventory_matching)不能把它抬升到通知准备。
|
||||
({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'intake_parse'),
|
||||
# 无处理阶段时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段(兜底)。
|
||||
({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'),
|
||||
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
|
||||
],
|
||||
)
|
||||
def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason(
|
||||
def test_batch_lifecycle_nodes_uses_processing_stage_or_owning_reason(
|
||||
item: dict[str, object],
|
||||
expected_lifecycle_stage: str,
|
||||
) -> None:
|
||||
"""批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
|
||||
"""[B''] 批次五阶段以处理阶段为权威;无处理阶段时才以阻断原因 owning gate 兜底。"""
|
||||
nodes = _batch_lifecycle_nodes([{
|
||||
**item,
|
||||
'status': 'waiting_human',
|
||||
@@ -268,8 +276,9 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
|
||||
}]
|
||||
|
||||
|
||||
def test_processing_ui_state_exposes_shared_gate_authority() -> None:
|
||||
"""批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。"""
|
||||
def test_processing_ui_state_exposes_processing_stage_authority() -> None:
|
||||
"""[B''] 批次投影以有效处理阶段为权威:document_parsing 归入接收解析,
|
||||
正式库存 Gate(inventory_matching)不能把它升降到通知准备,authority 记为 processing_stage。"""
|
||||
state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'document_parsing',
|
||||
@@ -278,8 +287,8 @@ def test_processing_ui_state_exposes_shared_gate_authority() -> None:
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['lifecycle_stage'] == 'intake_parse'
|
||||
assert state['lifecycle_authority'] == 'processing_stage'
|
||||
|
||||
|
||||
def test_processing_ui_state_without_candidate_does_not_expose_lifecycle_entries() -> None:
|
||||
@@ -757,6 +766,8 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() ->
|
||||
assert _batch_ui_state_from_items(work_items) == {
|
||||
'status': 'waiting_human',
|
||||
'stage': 'inventory_matching',
|
||||
# 5 业务阶段随批次 ui_state 一并下发,供三面阶段口径同源。
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'blocking_reason': {'code': 'inventory_match_failed'},
|
||||
'primary_action': {'code': 'open_inventory_match_review'},
|
||||
'secondary_actions': [],
|
||||
@@ -987,6 +998,32 @@ def test_eml_aggregate_projects_every_business_document_when_some_lack_order_tas
|
||||
assert unassigned['available_actions'] == []
|
||||
|
||||
|
||||
def test_eml_leaf_processing_stage() -> None:
|
||||
"""EML 处理中叶子按真实单元/解析状态推进 15 阶,不再整批折叠为 candidate_creating。"""
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='merging_supplement', parse_status='parsed', source_type='eml',
|
||||
) == 'email_adjudicating'
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='extracting', parse_status='parsed', source_type='eml',
|
||||
) == 'document_parsing'
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='matching_profile', parse_status='parsed', source_type='eml',
|
||||
) == 'document_parsing'
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='candidate_ready', parse_status='parsed', source_type='eml',
|
||||
) == 'candidate_creating'
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='', parse_status='parsing', source_type='eml',
|
||||
) == 'document_parsing'
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='', parse_status='parsed', source_type='eml',
|
||||
) == 'candidate_creating'
|
||||
# 直接 PDF 永远不出现 EML 专属的交叉裁决阶段。
|
||||
assert _eml_leaf_processing_stage(
|
||||
unit_status='merging_supplement', parse_status='parsed', source_type='direct_pdf',
|
||||
) == 'candidate_creating'
|
||||
|
||||
|
||||
def test_eml_order_intake_projects_business_documents_without_candidates_as_processing(app) -> None:
|
||||
"""无 OT/候选的 EML 仍完整展示业务附件;未形成候选不是异常或待人工门禁。"""
|
||||
with app.app_context():
|
||||
@@ -1100,8 +1137,8 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task
|
||||
assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children'])
|
||||
|
||||
|
||||
def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None:
|
||||
"""未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。"""
|
||||
def test_summary_displays_selected_supporting_attachment_outside_lifecycle_counts(app) -> None:
|
||||
"""已选未知附件应显示为诊断行,但不得进入已识别数、五阶段或业务动作。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
@@ -1120,6 +1157,26 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count
|
||||
order_extraction_status='completed',
|
||||
)
|
||||
db.session.add(supporting_document)
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=_agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
keep_input_open=True,
|
||||
)
|
||||
run.input_snapshot_json = {
|
||||
'intakes': [{'intake_id': int(intake.id)}],
|
||||
'attachment_selection': {
|
||||
'selected_attachment_count': 2,
|
||||
'items': [
|
||||
{'intake_no': intake.intake_no, 'attachment_key': primary_document.attachment_key, 'selected': True},
|
||||
{'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': True},
|
||||
# 重解析留下的未选快照不能覆盖此前已选结论。
|
||||
{'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': False},
|
||||
],
|
||||
},
|
||||
}
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
@@ -1133,13 +1190,85 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count
|
||||
for child in row.get('aggregate_children', [])
|
||||
]
|
||||
|
||||
# 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。
|
||||
# 关键断言:主业务文件与用户已选的未知附件都可见。
|
||||
assert int(primary_document.id) in {
|
||||
int(child['source_summary']['document_id']) for child in leaves
|
||||
}
|
||||
assert int(supporting_document.id) not in {
|
||||
int(child['source_summary']['document_id']) for child in leaves
|
||||
supporting_leaf = next(child for child in leaves if int(
|
||||
child['source_summary']['document_id']
|
||||
) == int(supporting_document.id))
|
||||
assert supporting_leaf['facts']['recognized'] is False
|
||||
assert supporting_leaf['available_actions'] == []
|
||||
assert payload['conversation_processing']['summary']['total_files'] == 1
|
||||
assert payload['conversation_processing']['summary']['submitted_files'] == 2
|
||||
assert sum(
|
||||
node['summary']['total']
|
||||
for node in payload['conversation_processing']['lifecycle_nodes']
|
||||
) == 1
|
||||
|
||||
|
||||
def test_summary_emits_selected_pending_leaves_in_empty_materialization_window(app) -> None:
|
||||
"""[回归] 全空窗期:附件已被冻结选择、但尚未物化任何 Document 时,首屏摘要也必须
|
||||
展示 pending(recognized=false)文件名,而不能只有 submitted/total 计数 + 空 status_groups。
|
||||
|
||||
对应交互:刚发送批次、尚未识别出文件时,聊天卡显示「共 N 个文件 · 已识别 0/N」,
|
||||
若 status_groups 为空前端只能转圈。修复后摘要与详情共用 pending 叶子补齐契约,
|
||||
让前端在物化前即可列出这些待识别文件。
|
||||
"""
|
||||
with app.app_context():
|
||||
from unittest.mock import patch
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-EMPTY-WINDOW',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
# 模拟「已选但尚未物化」:删除该 intake 下的 Document,只保留冻结计划附件。
|
||||
db.session.delete(document)
|
||||
db.session.flush()
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents',
|
||||
) as materialize:
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=_agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
keep_input_open=True,
|
||||
)
|
||||
materialize.assert_not_called()
|
||||
run.input_snapshot_json = {
|
||||
'intakes': [{'intake_id': int(intake.id), 'documents': []}],
|
||||
'attachment_selection': {
|
||||
'selected_attachment_count': 2,
|
||||
'items': [
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'n1.pdf', 'filename': 'N1.pdf', 'content_hash': 'x' * 64, 'selected': True},
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'n2.pdf', 'filename': 'N2.pdf', 'content_hash': 'y' * 64, 'selected': True},
|
||||
],
|
||||
},
|
||||
}
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
conv = payload['conversation_processing']
|
||||
|
||||
# 关键断言:提交基=2、已识别=0;但 status_groups 必须能列出 pending 文件名。
|
||||
assert conv['summary']['submitted_files'] == 2
|
||||
assert conv['summary']['total_files'] == 0
|
||||
leaves = [
|
||||
child
|
||||
for rows in conv['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
]
|
||||
pending = [child for child in leaves if (child.get('facts') or {}).get('recognized') is False]
|
||||
assert len(pending) == 2
|
||||
filenames = {str((child.get('source_summary') or {}).get('filename') or '') for child in pending}
|
||||
assert {'N1.pdf', 'N2.pdf'} <= filenames
|
||||
|
||||
|
||||
def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None:
|
||||
@@ -1168,8 +1297,53 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
|
||||
assert summary['completed_files'] == 0
|
||||
|
||||
|
||||
def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None:
|
||||
"""摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。"""
|
||||
def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None:
|
||||
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, intake, completed_document = _seed_run_input(
|
||||
suffix='SUMMARY-MIXED-EML-LEAF-STATUS',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
completed_document.order_extraction_status = 'completed'
|
||||
processing_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='still-processing.pdf',
|
||||
filename='still-processing.pdf',
|
||||
content_hash='m' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
order_extraction_status='not_started',
|
||||
)
|
||||
db.session.add(processing_document)
|
||||
db.session.commit()
|
||||
|
||||
projection = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)['conversation_processing']
|
||||
|
||||
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。
|
||||
processing_rows = projection['status_groups']['processing']
|
||||
completed_rows = projection['status_groups']['completed']
|
||||
assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [
|
||||
processing_document.id,
|
||||
]
|
||||
assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [
|
||||
completed_document.id,
|
||||
]
|
||||
assert projection['summary']['processing_files'] == 1
|
||||
assert projection['summary']['completed_files'] == 1
|
||||
assert projection['summary']['total_files'] == 2
|
||||
|
||||
|
||||
def test_summary_lifecycle_authority_is_processing_stage_for_stale_completed_task(app) -> None:
|
||||
"""[B''] 阶段唯一权威:OT.stage='completed' 属遗留/兼容字段,不推动阶段。投影层已把叶子
|
||||
user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation),因此生命周期仍是
|
||||
fulfillment_prep,authority 记为 processing_stage。正式 Gate 不再声称阶段裁决;
|
||||
Gate 阻断仅保留在用户状态与「订单检查」面板,且阶段权威不改变用户状态。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
@@ -1197,12 +1371,12 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None:
|
||||
db.session.flush()
|
||||
order_task.shipping_notice_id = notice.id
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked',
|
||||
execution_no='SPE-SUMMARY-GATE', task_id=order_task.id, status='blocked',
|
||||
current_gate_code='inventory_preparation', lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
notice.active_process_execution_id = execution.id
|
||||
order_task.active_process_execution_id = execution.id
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11,
|
||||
status='blocked_manual', evaluation_version=1, lock_version=1,
|
||||
@@ -1223,8 +1397,14 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None:
|
||||
]
|
||||
leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id)
|
||||
|
||||
# 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。
|
||||
# 关键断言(B''):阶段以共享裁判器的 processing_stage 为唯一权威。
|
||||
# 投影层已把叶子 user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation),
|
||||
# 因此生命周期仍是 fulfillment_prep;但 authority 已是 processing_stage,
|
||||
# 正式 Gate 不再是阶段来源。OT.stage='completed' 属遗留/兼容字段,不推动阶段。
|
||||
assert leaf['user_stage'] == 'inventory_preparation'
|
||||
assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert leaf['ui_state']['lifecycle_authority'] == 'processing_stage'
|
||||
# Gate 阻断事实仍在(用户状态与「订单检查」面板),不因阶段权威变更而消失。
|
||||
assert leaf['user_status'] == 'waiting_human'
|
||||
assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout'
|
||||
# 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。
|
||||
@@ -1429,6 +1609,16 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None:
|
||||
first_unit.status = 'review_required'
|
||||
first_unit.reason_code = 'business_table_not_found'
|
||||
second_unit.reason_code = 'business_table_not_found'
|
||||
# [BE-05] 待复核 PDF 必须已有当前有效 Candidate,Review Case 才开放订单复核入口;
|
||||
# 无候选时后端裁决为接收解析(intake_parse),不能当作订单复核待人工。
|
||||
for _doc, _k in ((first_document, 'eml-sibling-1'), (second_document, 'eml-sibling-2')):
|
||||
db.session.add(ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-SIBLING-{uuid.uuid4().hex[:8]}',
|
||||
intake_id=int(intake.id), primary_document_id=int(_doc.id),
|
||||
candidate_key=_k, order_extraction_run_id=int(run.id),
|
||||
is_current_version=True, candidate_status='provisional',
|
||||
))
|
||||
db.session.flush()
|
||||
ensure_review_case_for_unit(run=run, unit=first_unit)
|
||||
ensure_review_case_for_unit(run=run, unit=second_unit)
|
||||
run.status = 'partially_completed'
|
||||
@@ -1440,16 +1630,20 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None:
|
||||
|
||||
for document_id in (int(first_document.id), int(second_document.id)):
|
||||
leaf = leaves[document_id]
|
||||
assert leaf['user_status'] == 'waiting_human'
|
||||
# [BE-05] 未确认 Candidate Review Case 由后端 bundle 权威裁决为 idle(待用户处置),
|
||||
# 用户阶段固定在订单复核;建单前 Gate 由 order_review_build / mark_non_order 唯一给出。
|
||||
assert leaf['user_status'] == 'idle'
|
||||
assert leaf['user_stage'] == 'order_review'
|
||||
assert leaf['blocking_reason']['code'] == 'business_table_not_found'
|
||||
assert leaf['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert leaf['current_gate']['next_action_code'] == 'mark_non_order'
|
||||
# 同一 Run 的兄弟失败 PDF 只能影响自身;待复核 PDF 仍必须保留其复核业务入口。
|
||||
assert leaf['ui_state']['primary_action'] is not None, leaf
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'edit_draft'
|
||||
failed_leaf = leaves[int(third_document.id)]
|
||||
assert failed_leaf['user_status'] == 'failed'
|
||||
assert failed_leaf['user_stage'] == 'document_parsing'
|
||||
assert failed_leaf['blocking_reason']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'
|
||||
assert failed_leaf['ui_state']['primary_action']['code'] == 'retry_order_extraction'
|
||||
assert failed_leaf['ui_state']['primary_action']['code'] == 'reparse'
|
||||
assert item['aggregate_summary']['needs_action'] == 2
|
||||
assert item['aggregate_summary']['failed'] == 1
|
||||
|
||||
@@ -1500,8 +1694,14 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document
|
||||
# 顶层字段与 ui_state 必须是同一次后端裁决,供批次与工作台共用。
|
||||
assert candidate_leaf['lifecycle_stage'] == candidate_leaf['ui_state']['lifecycle_stage']
|
||||
assert candidate_leaf['lifecycle_entries'] == candidate_leaf['ui_state']['lifecycle_entries']
|
||||
# 有效 Candidate 的主 PDF 开放订单复核生命周期:当前阶段为 order_review,
|
||||
# 五个入口按 可用/当前/不可用 几何给出。
|
||||
assert candidate_leaf['ui_state']['lifecycle_stage'] == 'order_review'
|
||||
assert [entry['code'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [
|
||||
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
|
||||
]
|
||||
assert [entry['state'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable',
|
||||
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
|
||||
]
|
||||
assert sibling_leaf['source_summary']['candidate_count'] == 0
|
||||
assert sibling_leaf['lifecycle_entries'] == sibling_leaf['ui_state']['lifecycle_entries']
|
||||
@@ -1550,10 +1750,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
|
||||
projection = _conversation_processing_from_work_items(items)
|
||||
|
||||
failed = projection['status_groups']['failed']
|
||||
processing = projection['status_groups']['processing']
|
||||
assert len(failed) == 1
|
||||
assert failed[0]['user_task_no'] == 'INTAKE:SNI-BATCH-1'
|
||||
assert failed[0]['title'] == 'FWD: Shanghai shipping notice'
|
||||
assert len(failed[0]['aggregate_children']) == 2
|
||||
assert [child['source_summary']['filename'] for child in failed[0]['aggregate_children']] == ['a.pdf']
|
||||
assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['b.pdf']
|
||||
assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
|
||||
assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'}
|
||||
assert projection['summary']['total_files'] == 2
|
||||
@@ -1570,6 +1772,42 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
|
||||
}
|
||||
|
||||
|
||||
def test_conversation_projection_repeats_mixed_eml_per_leaf_status(app) -> None:
|
||||
"""混合状态 EML 必须在各 PDF 自身状态分区独立显示,不能混入已完成区。"""
|
||||
with app.app_context():
|
||||
items = _aggregate_eml_order_task_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-DONE',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS',
|
||||
'root_order_task_no': 'OT-MIXED-DONE',
|
||||
'source_summary': {'document_id': 301, 'filename': 'done.pdf'},
|
||||
'status': 'completed', 'stage': 'completed',
|
||||
'user_group': 'completed', 'user_status': 'completed', 'user_stage': 'completed',
|
||||
'available_actions': [], 'facts': {'upload_state': 'completed'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-RUNNING',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS',
|
||||
'root_order_task_no': 'OT-MIXED-DONE',
|
||||
'source_summary': {'document_id': 302, 'filename': 'running.pdf'},
|
||||
'status': 'processing', 'stage': 'freight_upload',
|
||||
'user_group': 'processing', 'user_status': 'running', 'user_stage': 'freight_upload',
|
||||
'available_actions': [], 'facts': {'upload_state': 'not_created'},
|
||||
},
|
||||
])
|
||||
|
||||
projection = _conversation_processing_from_work_items(items)
|
||||
|
||||
completed = projection['status_groups']['completed']
|
||||
processing = projection['status_groups']['processing']
|
||||
assert [child['source_summary']['filename'] for child in completed[0]['aggregate_children']] == ['done.pdf']
|
||||
assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['running.pdf']
|
||||
assert completed[0]['aggregate_summary']['intake_no'] == 'SNI-MIXED-STATUS'
|
||||
assert completed[0]['aggregate_summary']['total'] == 2
|
||||
assert completed[0]['aggregate_summary']['in_group'] == 1
|
||||
assert processing[0]['aggregate_summary']['in_group'] == 1
|
||||
|
||||
|
||||
def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) -> None:
|
||||
"""会话与批次中心均以 Intake 原始 EML 文件名标识同一邮件。"""
|
||||
with app.app_context():
|
||||
@@ -1585,6 +1823,7 @@ def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app)
|
||||
},
|
||||
'status': 'processing', 'stage': 'document_parsing',
|
||||
'user_status': 'processing', 'user_stage': 'document_parsing',
|
||||
'user_group': 'processing',
|
||||
'available_actions': [], 'facts': {'upload_state': 'not_created'},
|
||||
}])
|
||||
|
||||
@@ -1826,7 +2065,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi
|
||||
assert item['current_gate']['attempt_no'] == 2
|
||||
assert item['source_summary']['failure_reason_code'] == 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
assert item['source_summary']['parse_attempt_count'] == 2
|
||||
assert 'retry' in item['available_actions']
|
||||
assert 'retry_parse' in item['available_actions']
|
||||
|
||||
|
||||
def test_project_conversation_processing_items_includes_work_items(app, shipping_user):
|
||||
@@ -1887,7 +2126,9 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
|
||||
assert solo['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert solo['ui_state']['blocking_reason'] is None
|
||||
assert solo['ui_state']['primary_action'] is None
|
||||
assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions']
|
||||
# [BE-05] 顶层 available_actions 已在 API 边界剥离(旧镜像,动作唯一合同是 ui_state);
|
||||
# secondary_actions 即为后端裁决的可用动作 DTO。
|
||||
assert [action['code'] for action in solo['ui_state']['secondary_actions']] == ['view_result']
|
||||
assert all(action['enabled'] is True for action in solo['ui_state']['secondary_actions'])
|
||||
conversation_row = next(
|
||||
row
|
||||
@@ -2084,6 +2325,63 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
assert item['source_summary']['filename'] == document.filename
|
||||
|
||||
|
||||
def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(app, shipping_user):
|
||||
"""
|
||||
单工作项读取必须复用统一生命周期 DTO,避免工作台另读 Case/Queue 补阶段。
|
||||
|
||||
断言:货代上传阶段的单工作项响应下发 freight_upload 当前入口。
|
||||
"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, _agent, session, intake, _document = _seed_run_input(suffix='SINGLE-WORK-ITEM-UI')
|
||||
run = _materialized_run(user=user, agent=_agent, session=session, intake=intake)
|
||||
# [BE-05] current_step / shipping_notice_id 已从 Notice 侧迁移:current_step 挪到
|
||||
# ShippingOrderTask,Notice 通过 order_task_id 反指 OT,进度由 OT.stage 驱动。
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-SINGLE-WORK-ITEM-UI',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_id=int(intake.id),
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-SINGLE-WORK-ITEM-UI',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
order_task_id=int(order_task.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
run.user_task_no = order_task.task_no
|
||||
db.session.commit()
|
||||
|
||||
item = get_shipping_processing_work_item(
|
||||
user_id=user.id,
|
||||
work_item_type='order_task',
|
||||
work_item_no=order_task.task_no,
|
||||
)
|
||||
|
||||
assert item['user_stage'] == 'freight_upload'
|
||||
assert item['ui_state']['lifecycle_stage'] == 'freight_upload'
|
||||
lifecycle_states = {
|
||||
entry['code']: entry['state']
|
||||
for entry in item['ui_state']['lifecycle_entries']
|
||||
}
|
||||
assert lifecycle_states['fulfillment_prep'] == 'available'
|
||||
assert lifecycle_states['freight_upload'] == 'current'
|
||||
|
||||
|
||||
|
||||
def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user):
|
||||
"""同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。"""
|
||||
@@ -2135,7 +2433,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
"""候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderCandidate
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderReviewCase
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
@@ -2147,6 +2445,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
candidate_no=f'OCAND-EML-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='eml-case-leaf',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
candidate_status='provisional',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
@@ -2320,26 +2619,29 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='OT-NOTICE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-NOTICE-PROJ-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
# [BE-05] current_step 已迁移到 ShippingOrderTask;Notice 经 order_task_id 反指 OT,
|
||||
# 不再使用 shipping_notice_id 反向外键。
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-NOTICE-PROJ-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
shipping_notice_id=int(notice.id),
|
||||
current_step='step7_upload_freight',
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-NOTICE-PROJ-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
order_task_id=int(order_task.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
run.user_task_no = order_task.task_no
|
||||
db.session.commit()
|
||||
|
||||
@@ -2355,15 +2657,15 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
assert synced['stage'] == 'freight_uploading'
|
||||
|
||||
# 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。
|
||||
notice.upload_status = 'uploaded'
|
||||
# [BE-05] upload_status 已迁移到上传 Attempt 表,Notice 上不再读取该字段;
|
||||
# 无成功 Attempt 时投影保持自动上传中(automating/freight_uploading),绝不进入完成。
|
||||
order_task.status = 'automating'
|
||||
order_task.stage = 'freight_uploading'
|
||||
db.session.commit()
|
||||
unverified = _project_order_task_work_item(run)
|
||||
assert unverified['status'] == 'waiting_human'
|
||||
assert unverified['stage'] == 'freight_uploading'
|
||||
assert unverified['user_status'] == 'waiting_human'
|
||||
assert unverified['verified_upload_success'] is False
|
||||
assert unverified['status'] != 'completed'
|
||||
|
||||
|
||||
def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
|
||||
@@ -2402,6 +2704,142 @@ def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
|
||||
assert item['user_status'] == 'running'
|
||||
|
||||
rebuilt = _conversation_processing_from_work_items([item])
|
||||
row = rebuilt['processing'][0]
|
||||
row = rebuilt['status_groups']['processing'][0]
|
||||
assert row['status_label'] == 'processing'
|
||||
assert row['group'] == 'processing'
|
||||
|
||||
|
||||
def test_submitted_files_is_independent_of_unmaterialized_intake() -> None:
|
||||
"""[回归] 发送后物化前:提交基 submitted_files 应 ≥1,而 total_files(已识别)为 0。
|
||||
|
||||
用户刚提交 1 份邮件时,冻结选择计划已能给出 selected_attachment_count=1;但附件
|
||||
Document 尚未被 worker 物化,_batch_file_counts 对该 EML(.eml 不计数)返回 0。
|
||||
此前以 total_files 作为主计数导致「共 0 个文件 → 自动变 1」的翻转;引入
|
||||
submitted_files 后主计数不再归零,已识别进度由 total_files 单独体现。
|
||||
"""
|
||||
work_items = [{
|
||||
'work_item_type': 'order_intake',
|
||||
'work_item_no': 'SNI-EML-UNMATERIALIZED',
|
||||
'source_type': 'eml',
|
||||
'intake_no': 'SNI-EML-UNMATERIALIZED',
|
||||
'user_group': 'processing',
|
||||
'user_status': 'running',
|
||||
'user_stage': 'intake_parse',
|
||||
'status': 'processing',
|
||||
'source_summary': {
|
||||
'filename': 'order.eml',
|
||||
'document_count': 0,
|
||||
'document_id': None,
|
||||
},
|
||||
'aggregate_children': [],
|
||||
}]
|
||||
projection = _conversation_processing_from_work_items(work_items, submitted_files=1)
|
||||
summary = projection['summary']
|
||||
# 主计数:提交基,不为 0(用户实际提交了 1 份)。
|
||||
assert summary['submitted_files'] == 1
|
||||
# 已识别数:物化前为 0,但不再顶替主计数。
|
||||
assert summary['total_files'] == 0
|
||||
|
||||
|
||||
def test_conversation_submitted_file_count_reflects_frozen_selection(app) -> None:
|
||||
"""[回归] submitted_files 应等于冻结选择计划已选数 + 直传 PDF 数,且物化与否无关。
|
||||
|
||||
直传 PDF Intake 的冻结选择计划不设置 selected_attachment_count(该字段只服务
|
||||
EML 附件),此时每个直传 PDF Intake 计 1 个业务文件,保证提交基主计数 ≥1。
|
||||
"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUBMITTED-COUNT',
|
||||
)
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
keep_input_open=True,
|
||||
)
|
||||
# 直传 PDF Intake 本身即为 1 个业务文件:提交基主计数必须 ≥1(物化与否无关)。
|
||||
assert _conversation_submitted_file_count(
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
) == 1
|
||||
|
||||
|
||||
def test_conversation_submitted_file_count_deduplicates_reparse_attachment_snapshot(app) -> None:
|
||||
"""重解析快照重复记录同一已选附件时,提交基只能计一次。"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SUBMITTED-DEDUP')
|
||||
intake.source_type = 'eml'
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no], keep_input_open=True,
|
||||
)
|
||||
run.input_snapshot_json = {
|
||||
'intakes': [{'intake_id': int(intake.id)}],
|
||||
'attachment_selection': {
|
||||
'selected_attachment_count': 2,
|
||||
'items': [
|
||||
{'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True},
|
||||
{'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True},
|
||||
],
|
||||
},
|
||||
}
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
db.session.commit()
|
||||
|
||||
assert _conversation_submitted_file_count(
|
||||
user_id=int(user.id), conversation_id=session.session_id,
|
||||
) == 1
|
||||
|
||||
|
||||
def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized() -> None:
|
||||
"""[回归] 已选但尚未物化/未识别的计划附件应出现在列表,但不计入已识别 total_files。
|
||||
|
||||
对应交互:批次显示「已识别 1/2」时,EML 列表必须展示全部计划附件(含未识别行),
|
||||
否则无法排查「为什么这份没识别」。物化附件按识别状态计数,未识别计划行仅作诊断。
|
||||
"""
|
||||
intake_no = 'SNI-EML-PLAN'
|
||||
recognized_child = {
|
||||
'work_item_type': 'order_intake',
|
||||
'work_item_no': 'DOC-10',
|
||||
'source_type': 'eml',
|
||||
'intake_no': intake_no,
|
||||
'user_status': 'waiting_human',
|
||||
'user_group': 'waiting_human',
|
||||
'user_stage': 'order_review',
|
||||
'status': 'waiting_human',
|
||||
'source_summary': {
|
||||
'filename': 'F91D1.pdf', 'document_id': 10, 'content_hash': 'a' * 64,
|
||||
},
|
||||
'facts': {},
|
||||
}
|
||||
planned_by_intake_no = {
|
||||
intake_no: [
|
||||
{
|
||||
'intake_no': intake_no, 'attachment_key': 'f91.pdf',
|
||||
'filename': 'F91D1.pdf', 'content_hash': 'a' * 64, 'selected': True,
|
||||
},
|
||||
{
|
||||
'intake_no': intake_no, 'attachment_key': 'f92.pdf',
|
||||
'filename': 'F92.pdf', 'content_hash': 'b' * 64, 'selected': True,
|
||||
},
|
||||
],
|
||||
}
|
||||
merged = _append_unrecognized_plan_attachments(
|
||||
intake=SimpleNamespace(intake_no=intake_no),
|
||||
aggregate_children=[recognized_child],
|
||||
planned_by_intake_no=planned_by_intake_no,
|
||||
)
|
||||
# 列表同时包含已识别与未识别计划行。
|
||||
filenames = [str((child.get('source_summary') or {}).get('filename') or '') for child in merged]
|
||||
assert 'F91D1.pdf' in filenames
|
||||
assert 'F92.pdf' in filenames
|
||||
unrecognized = [child for child in merged if (child.get('facts') or {}).get('recognized') is False]
|
||||
assert len(unrecognized) == 1
|
||||
assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf'
|
||||
# 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。
|
||||
assert _batch_file_counts(merged)['total_files'] == 1
|
||||
@@ -16,6 +16,24 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
EML_ONLY_PROCESSING_STAGES,
|
||||
SHIPPING_PROCESSING_STAGES,
|
||||
)
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGE_BY_PROCESSING_STAGE,
|
||||
LIFECYCLE_STAGE_CODES,
|
||||
)
|
||||
|
||||
|
||||
def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
|
||||
"""统一口径:每个 SHIPPING_PROCESSING_STAGES 细粒度阶段都必须映射到一个合法 5 业务阶段。
|
||||
|
||||
该映射是「15 阶权威 → 5 阶展示」的唯一桥梁;遗漏任一值会导致工作台/批次中心
|
||||
出现未归类阶段,使前后端阶段口径不一致。此处仅作完整性约束,不改变任何阶段语义。
|
||||
"""
|
||||
for stage in SHIPPING_PROCESSING_STAGES:
|
||||
mapped = LIFECYCLE_STAGE_BY_PROCESSING_STAGE.get(stage)
|
||||
assert mapped is not None, f"SHIPPING_PROCESSING_STAGES.{stage!r} 缺少 15->5 映射"
|
||||
assert mapped in LIFECYCLE_STAGE_CODES, (
|
||||
f"映射目标 {mapped!r} 不是合法 5 业务阶段({tuple(LIFECYCLE_STAGE_CODES)})"
|
||||
)
|
||||
|
||||
|
||||
def test_fifteen_stages_inventory_source_before_review():
|
||||
@@ -32,24 +50,25 @@ def test_fifteen_stages_inventory_source_before_review():
|
||||
def test_sync_order_task_stage_must_be_processing_stage(app):
|
||||
"""任务工作台与对话投影均读 OT.stage;写入值必须是冻结的 15 阶之一。"""
|
||||
with app.app_context():
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-CROSS-SURFACE-001',
|
||||
source_type='manual',
|
||||
po_number='PO-CROSS-001',
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
# [BE-05] 订单数据已迁移到 ShippingOrderTask/Extraction;Notice 不再承载
|
||||
# po_number/order_lines_migration_status。OT 是进度写入口,Notice 通过
|
||||
# order_task_id 反指 OT,恢复测试原本「通知 + 任务」配对结构。
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-CROSS-SURFACE-001',
|
||||
user_id=1,
|
||||
shipping_notice_id=int(notice.id),
|
||||
stage='waiting_review',
|
||||
status='waiting_review',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-CROSS-SURFACE-001',
|
||||
source_type='manual',
|
||||
order_task_id=int(order_task.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
"""
|
||||
backend/tests/test_shipping_projection_gate_equivalence.py
|
||||
|
||||
用途:锁定「展示单源」契约 §2.1 —— 在真实 A 管线(_project_order_task_work_item)
|
||||
下,A 渲染出的 primary_action / blocking_reason / user_status 必须与 C
|
||||
(project_user_gate_summary)等价。这是 flatten C→A==B==C 的**前置等价性验证**:
|
||||
仅当 A==C 才允许删除 A 的 STEP3/6/7 二次推导,否则会改变对话流/批次进度中心/右卡展示。
|
||||
|
||||
依赖:pytest、app fixture、tests 已有的 _seed_run_input / _materialized_run、
|
||||
shipping_processing_projection._project_order_task_work_item、
|
||||
process_gate_projection.project_user_gate_summary。
|
||||
|
||||
逻辑:为每个代表性 Gate 场景构建 OT+Notice+Run+Execution+Gate 持久化事实,
|
||||
运行 A 管线拿到渲染 DTO,新调 C 拿到权威摘要;断言 A 的动作码/阻断码与 C 一致。
|
||||
若断言失败,即为「A 与 C 漂移」,必须先修 C 侧语义再 flatten。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gate_chain(app):
|
||||
"""构造挂接 Notice 的 OT + Run(复用既有 seed),返回主键供测试内重载。
|
||||
|
||||
与 test_shipping_workbench_service_chains.workbench_chain_ids 同构,但额外
|
||||
允许测试追加 Execution/Gate 后驱动完整 A 管线。
|
||||
"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
with app.app_context():
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='GATE-EQ')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-GATE-EQ-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
lifecycle_status='active',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-GATE-EQ-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
status='processing',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice.order_task_id = int(order_task.id)
|
||||
run.user_task_no = order_task.task_no
|
||||
db.session.commit()
|
||||
return {
|
||||
'run_id': int(run.id),
|
||||
'notice_id': int(notice.id),
|
||||
'order_task_id': int(order_task.id),
|
||||
}
|
||||
|
||||
|
||||
def _load_chain(ids: dict[str, int]):
|
||||
from app.models import ShippingNotice, ShippingOrderProcessingRun, ShippingOrderTask
|
||||
|
||||
run = db.session.get(ShippingOrderProcessingRun, ids['run_id'])
|
||||
notice = db.session.get(ShippingNotice, ids['notice_id'])
|
||||
order_task = db.session.get(ShippingOrderTask, ids['order_task_id'])
|
||||
assert run is not None and notice is not None and order_task is not None
|
||||
return run, notice, order_task
|
||||
|
||||
|
||||
def _attach_execution(order_task, *, gate_code: str, status: str,
|
||||
blocking_reason_code: str, next_action_code: str,
|
||||
sequence_no: int = 16) -> int:
|
||||
"""为 OT 挂接一个正式 Execution + 单一 Gate(回退到正式 Notice 事实源)。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no=f'EXE-GATE-EQ-{gate_code}',
|
||||
task_id=int(order_task.id),
|
||||
status='blocked',
|
||||
current_gate_code=gate_code,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=gate_code,
|
||||
sequence_no=sequence_no,
|
||||
status=status,
|
||||
evaluation_version=1,
|
||||
blocking_reason_code=blocking_reason_code,
|
||||
next_action_code=next_action_code,
|
||||
))
|
||||
order_task.active_process_execution_id = int(execution.id)
|
||||
db.session.flush()
|
||||
return int(execution.id)
|
||||
|
||||
|
||||
def _project_a(run, order_task):
|
||||
"""运行 A 管线,返回渲染 payload。
|
||||
|
||||
真实对外 DTO 经 `_with_processing_ui_state` 封装(含顶层 current_gate / blocking_reason /
|
||||
primary_action + 子 `ui_state`)。集成层(:4757/:4863)才封装,故此处手动封装,
|
||||
使顶层动作码与 `ui_state.lifecycle_stage` 均可被读取。
|
||||
"""
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_project_order_task_work_item,
|
||||
_with_processing_ui_state,
|
||||
)
|
||||
|
||||
payload = _project_order_task_work_item(run, order_task=order_task)
|
||||
assert payload is not None, 'A 管线必须产出 work_item'
|
||||
return _with_processing_ui_state(payload)
|
||||
|
||||
|
||||
def _summary_c(execution_id: int):
|
||||
"""独立重调 C(project_user_gate_summary),避免与 A 携带的 process_gate 同源污染。"""
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
execution = db.session.get(ShippingProcessExecution, execution_id)
|
||||
assert execution is not None
|
||||
return project_user_gate_summary(execution)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario', [
|
||||
# gate_code, gate.status, blocking_reason_code, next_action_code
|
||||
# [CANONICAL-AGREE] 这些场景 A 与 C 当前一致:flatten 后仍必须一致。
|
||||
('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'),
|
||||
('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'),
|
||||
])
|
||||
def test_a_primary_action_equals_c(app, gate_chain, scenario):
|
||||
"""A 渲染的主动作码必须等于 C 的 next_action_code(flatten 前置等价性,规范场景)。"""
|
||||
gate_code, status, reason_code, next_action = scenario
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code=gate_code, status=status,
|
||||
blocking_reason_code=reason_code, next_action_code=next_action,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
a = _project_a(run, order_task)
|
||||
summary = _summary_c(execution_id)
|
||||
|
||||
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
|
||||
c_next = str(summary.get('next_action_code') or '').strip()
|
||||
c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip()
|
||||
assert a_primary == c_next == c_primary, (
|
||||
f'A={a_primary!r} C.next={c_next!r} C.primary={c_primary!r} for {gate_code}'
|
||||
)
|
||||
|
||||
a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
c_reason = str(summary.get('blocking_reason_code') or '').strip()
|
||||
assert a_reason == c_reason, (
|
||||
f'A.reason={a_reason!r} C.reason={c_reason!r} for {gate_code}'
|
||||
)
|
||||
|
||||
|
||||
def test_a_blocking_reason_does_not_over_collapse_retryable(app, gate_chain):
|
||||
"""flatten C 后:A 的 blocking_reason 必须复用 C 已裁决的具体码,不再坍缩为 technical_failure_present。"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code='inventory_preparation', status='blocked_retryable',
|
||||
blocking_reason_code='inventory_preparation_failed',
|
||||
next_action_code='retry_inventory_preparation',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
a = _project_a(run, order_task)
|
||||
summary = _summary_c(execution_id)
|
||||
|
||||
a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
c_reason = str(summary.get('blocking_reason_code') or '').strip()
|
||||
assert a_reason == c_reason == 'inventory_preparation_failed'
|
||||
|
||||
|
||||
def test_a_primary_action_uses_canonical_excel_code(app, gate_chain):
|
||||
"""flatten C 后:A 的 primary_action.code 必须是写侧认可的规范码 regenerate_excel_artifact,而非别名。"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code='artifact_generation', status='blocked_retryable',
|
||||
blocking_reason_code='artifact_generation_failed',
|
||||
next_action_code='regenerate_excel_artifact',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
a = _project_a(run, order_task)
|
||||
summary = _summary_c(execution_id)
|
||||
|
||||
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
|
||||
c_next = str(summary.get('next_action_code') or '').strip()
|
||||
c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip()
|
||||
assert a_primary == c_next == c_primary == 'regenerate_excel_artifact'
|
||||
|
||||
|
||||
def test_a_primary_action_uses_same_recovery_source_as_c(app, gate_chain):
|
||||
"""RPA 超时/耗尽:A 与 C 都必须回落为『优先复用已有快照重匹配(无则 RPA)』的合并动作,
|
||||
而非孤立只重读或直接新开 RPA。"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code='inventory_preparation', status='blocked_retryable',
|
||||
blocking_reason_code='inventory_rpa_exhausted', next_action_code='retry_inventory_matching',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
a = _project_a(run, order_task)
|
||||
summary = _summary_c(execution_id)
|
||||
|
||||
a_primary = str((a.get('primary_action') or {}).get('code') or '').strip()
|
||||
c_next = str(summary.get('next_action_code') or '').strip()
|
||||
assert a_primary == c_next == 'retry_inventory_matching'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario', [
|
||||
# gate_code, gate.status, blocking_reason_code, next_action_code
|
||||
('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'),
|
||||
('inventory_preparation', 'blocked_retryable', 'inventory_preparation_failed', 'retry_inventory_preparation'),
|
||||
('artifact_generation', 'blocked_retryable', 'artifact_generation_failed', 'regenerate_excel_artifact'),
|
||||
('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'),
|
||||
])
|
||||
def test_b_task_ui_state_actions_equals_c(app, gate_chain, scenario):
|
||||
"""B(formalTaskDetail.ui_state)的 actions 必须与 C 同源(A==B==C 的 B 半边)。
|
||||
|
||||
B 的 actions 由 _unified_actions(_process_gate_user_summary_for_task(task)) 产出,
|
||||
而后者就是 project_user_gate_summary;因此 B.primary.code 必须== C.next_action_code,
|
||||
B.secondary.code 集合必须== C.allowed_actions 集合。
|
||||
"""
|
||||
gate_code, status, reason_code, next_action = scenario
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code=gate_code, status=status,
|
||||
blocking_reason_code=reason_code, next_action_code=next_action,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
# B 只消费正式 OT;build_task_ui_state 直接接受 ShippingOrderTask 并按 task.id 查执行。
|
||||
state = build_task_ui_state(order_task)
|
||||
actions = state.get('actions') or {}
|
||||
b_primary = str((actions.get('primary') or {}).get('code') or '').strip()
|
||||
b_all = {
|
||||
str(item.get('code') or '').strip()
|
||||
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
|
||||
if item and str(item.get('code') or '').strip()
|
||||
}
|
||||
summary = _summary_c(execution_id)
|
||||
|
||||
c_next = str(summary.get('next_action_code') or '').strip()
|
||||
c_allowed = {
|
||||
str(code or '').strip()
|
||||
for code in summary.get('allowed_actions') or []
|
||||
if str(code or '').strip()
|
||||
}
|
||||
assert b_primary == c_next, (
|
||||
f'B.primary={b_primary!r} C.next={c_next!r} for {gate_code}'
|
||||
)
|
||||
# B 把 C.allowed_actions 拆成 primary+secondary;二者并集必须等于 allowed_actions。
|
||||
# 不能再要求 secondary==allowed:主动作被 C 列为 allowed 但在 B 里归到 primary。
|
||||
assert b_all == c_allowed, (
|
||||
f'B.all={sorted(b_all)} C.allowed={sorted(c_allowed)} for {gate_code}'
|
||||
)
|
||||
|
||||
|
||||
def test_preparation_line_emits_decisional_allowed_actions(app, gate_chain):
|
||||
"""§1.5 明细按钮修复:preparation.lines[] 必须带 line_allowed_actions /
|
||||
inventory_allowed_actions / inventory_file_no,否则前端 formalPreparationLineAllows 恒 false、
|
||||
明细行按钮不渲染。用正式 OT + 一行 not_found 断言短缺行按钮被正确授权。"""
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
# 冻结快照行 → 行级匹配(not_found,短缺)。
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(order_task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
order_task.order_snapshot_id = int(snapshot.id)
|
||||
line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=int(snapshot.id), position=0, line_no=1,
|
||||
reservation_id='RSV-EQ', part_number='PN-EQ', qty='8', field_values_json={},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=1, line_index=0,
|
||||
match_result='not_found', inventory_status='ready', required_qty='8',
|
||||
available_qty='0', matched_qty='0', shortage_qty='8',
|
||||
reservation_id='RSV-EQ', part_number='PN-EQ',
|
||||
inventory_source_code='DBS_DUB', matched_file_no='INV-EQ', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(order_task, include_stage_context=True)['stage_context']['preparation']
|
||||
assert preparation['lines'], '必须有至少一行'
|
||||
line_row = preparation['lines'][0]
|
||||
# 短缺行:close + release_inventory_shortage(line);retry_inventory_preparation(inventory)。
|
||||
assert set(line_row['line_allowed_actions']) == {
|
||||
'close_unfulfillable', 'release_inventory_shortage',
|
||||
}
|
||||
assert 'retry_inventory_preparation' in line_row['inventory_allowed_actions']
|
||||
# 下载库存按钮依赖 inventory_file_no。
|
||||
assert line_row['inventory_file_no'] == 'INV-EQ'
|
||||
assert line_row['user_line_status'] == 'shortage'
|
||||
|
||||
|
||||
def test_preparation_line_allowed_actions_are_zero_n_plus_one(app, gate_chain):
|
||||
"""§5.1 N+1 守门:行级 action 字段由内存事实投影发,GET 详情 SQL 数恒定且不随行数线性放大。
|
||||
|
||||
行级 fact 字典只读已加载的 match_row 列 + detail_json(触库的是 `_build_stage_context`
|
||||
自身的批量预取),每行并不追加查询;6 行仍须落在固定数量级。若逐行 SQL/重序列化,
|
||||
SQL 数会近似=6×行查询而被本上限拦下。
|
||||
"""
|
||||
from sqlalchemy import event
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
from tests.test_shipping_order_review_service import _capture_sql_statements
|
||||
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(order_task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
order_task.order_snapshot_id = int(snapshot.id)
|
||||
line_count = 6
|
||||
for i in range(line_count):
|
||||
line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=int(snapshot.id), position=i, line_no=i + 1,
|
||||
reservation_id=f'RSV-{i}', part_number=f'PN-{i}', qty='8', field_values_json={},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=i + 1, line_index=i,
|
||||
match_result='matched', inventory_status='ready', required_qty='8',
|
||||
available_qty='8', matched_qty='8', shortage_qty='0',
|
||||
reservation_id=f'RSV-{i}', part_number=f'PN-{i}',
|
||||
inventory_source_code='DBS_DUB', matched_file_no=f'INV-{i}', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
task_id = int(order_task.id)
|
||||
db.session.remove()
|
||||
with app.test_request_context():
|
||||
ot = db.session.get(ShippingOrderTask, task_id)
|
||||
statements: list[str] = []
|
||||
listener = _capture_sql_statements(statements)
|
||||
event.listen(db.engine, 'before_cursor_execute', listener)
|
||||
try:
|
||||
preparation = build_task_ui_state(ot, include_stage_context=True)['stage_context']['preparation']
|
||||
finally:
|
||||
event.remove(db.engine, 'before_cursor_execute', listener)
|
||||
assert len(preparation['lines']) == line_count
|
||||
# 关键断言:6 行仍落在固定数量级;若逐行重查会显著超出(约 6×行查询)而触发。
|
||||
assert len(statements) <= 40, (
|
||||
f'SQL 数随行数放大: 6 行仍应固定数量级,实测 {len(statements)}'
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario', [
|
||||
# gate_code, expected lifecycle stage(契约:正式 Gate 映射到五阶段业务码唯一表)
|
||||
('inventory_matching', 'fulfillment_prep'),
|
||||
('inventory_sufficiency', 'fulfillment_prep'),
|
||||
('artifact_generation', 'fulfillment_prep'),
|
||||
('freight_upload_rpa', 'freight_upload'),
|
||||
('manual_upload_handoff', 'freight_upload'),
|
||||
])
|
||||
def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario):
|
||||
"""五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。
|
||||
|
||||
`LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。
|
||||
B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底,
|
||||
必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload**
|
||||
—— 这是用户确认的契约(方案 A)。
|
||||
"""
|
||||
gate_code, expected_stage = scenario
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code=gate_code, status='blocked_manual',
|
||||
blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation',
|
||||
)
|
||||
# 让 notice 路径(_process_gate_user_summary_for_task 按 task.id=notice.id 查 execution)
|
||||
# 命中同一 execution:B 在生产中把 Notice 传给 build_task_ui_state。
|
||||
from app.models import ShippingProcessExecution
|
||||
execution = db.session.get(ShippingProcessExecution, execution_id)
|
||||
execution.task_id = int(notice.id)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
b = build_task_ui_state(notice)
|
||||
b_stage = str((b.get('stage') or {}).get('code') or '').strip()
|
||||
b_lifecycle = str(b.get('lifecycle_stage') or '').strip()
|
||||
|
||||
# B(Notice 路径)必须按 LIFECYCLE_STAGE_BY_GATE 落到五阶段码。
|
||||
assert b_stage == b_lifecycle == expected_stage, (
|
||||
f'B.stage={b_stage!r} B.lifecycle={b_lifecycle!r} expected={expected_stage!r} for {gate_code}'
|
||||
)
|
||||
|
||||
|
||||
def test_a_secondary_actions_carry_mark_manual_uploaded(app, gate_chain):
|
||||
"""A(shippingProcessingProjection.ui_state.secondary_actions)必须透传原始 Gate 码 mark_manual_uploaded。
|
||||
|
||||
契约 §2.5 差异①:A 的 secondary_actions 用别名 open_manual_upload,B/C 用 mark_manual_uploaded。
|
||||
frontend manualUploadRegistrationAuthorized 读 A 时须能匹配到 mark_manual_uploaded(否则按钮失效)。
|
||||
本守卫在归一化前应 RED(记录 bug),归一化后应 GREEN。
|
||||
"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(gate_chain)
|
||||
# freight_upload_rpa blocked_manual:C 的 gate_side_recovery_actions / 显式 append 授权手动上传。
|
||||
execution_id = _attach_execution(
|
||||
order_task,
|
||||
gate_code='freight_upload_rpa', status='blocked_manual',
|
||||
blocking_reason_code='upload_rpa_failed', next_action_code='retry_freight_upload_rpa',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
a = _project_a(run, order_task)
|
||||
ui_state = a.get('ui_state') or {}
|
||||
secondary_codes = {
|
||||
str(item.get('code') or '').strip()
|
||||
for item in ui_state.get('secondary_actions') or []
|
||||
if item
|
||||
}
|
||||
primary_code = str((ui_state.get('primary_action') or {}).get('code') or '').strip()
|
||||
# C 是唯一授权来源:allowed_actions 必含 mark_manual_uploaded(手动上传入口)。
|
||||
summary = _summary_c(execution_id)
|
||||
c_allowed = {str(c or '').strip() for c in summary.get('allowed_actions') or []}
|
||||
assert 'mark_manual_uploaded' in c_allowed, f'C.allowed={sorted(c_allowed)}'
|
||||
# [§2.5 归一守卫] A 的 secondary_actions 必须透传原始码 mark_manual_uploaded(而非 open_manual_upload 别名),
|
||||
# 且与 C.allowed_actions 同集(允许与主动作并存)。
|
||||
assert 'mark_manual_uploaded' in secondary_codes or primary_code == 'mark_manual_uploaded', (
|
||||
f'A.secondary={sorted(secondary_codes)} A.primary={primary_code!r} C.allowed={sorted(c_allowed)}'
|
||||
)
|
||||
@@ -40,6 +40,9 @@ def test_review_case_audit_timeline_owner_reads_snapshots_and_stranger_denied(ap
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-AUDIT-TL')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required;
|
||||
# 测试仅需审计时间线可见性,故把 Unit 置为就绪以初始化 Case/Draft。
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingNotice
|
||||
from app.models import Job, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
_task_needs_post_confirm_auto_progress,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
@@ -81,13 +81,28 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
|
||||
assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
|
||||
|
||||
|
||||
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
|
||||
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
|
||||
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction(monkeypatch):
|
||||
"""created/parsed 且已挂 Extraction 的任务需要确认后补推;已进入导出/上传事实则跳过。"""
|
||||
from types import SimpleNamespace as NS
|
||||
|
||||
from app.services.shipping_notice import upload_attempt_service
|
||||
|
||||
# [断言] 是否已推进以真实履约事实(Artifact/Attempt)判定,不再读 OT 冗余字段。
|
||||
def fake_upload_attempt(task):
|
||||
if getattr(task, 'upload_status', None) is not None:
|
||||
return NS(status='pending')
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(upload_attempt_service, 'latest_upload_attempt', fake_upload_attempt)
|
||||
monkeypatch.setattr(upload_attempt_service, 'latest_export_artifact', lambda task: None)
|
||||
|
||||
stuck = MagicMock(
|
||||
current_order_extraction_id=12,
|
||||
upload_status=None,
|
||||
)
|
||||
parsed = MagicMock(
|
||||
current_order_extraction_id=12,
|
||||
upload_status=None,
|
||||
)
|
||||
progressed = MagicMock(
|
||||
upload_status='pending',
|
||||
@@ -95,6 +110,7 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac
|
||||
)
|
||||
shell = MagicMock(
|
||||
current_order_extraction_id=None,
|
||||
upload_status=None,
|
||||
)
|
||||
assert _task_needs_post_confirm_auto_progress(stuck) is True
|
||||
assert _task_needs_post_confirm_auto_progress(parsed) is True
|
||||
@@ -106,8 +122,8 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac
|
||||
def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
"""commit=False 时写入 Job 但不提交,供与确认事务同提交。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-1',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-CONFIRM-AP-1',
|
||||
user_id=1,
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
@@ -143,8 +159,8 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
|
||||
"""确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-PARSED',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-CONFIRM-AP-PARSED',
|
||||
user_id=1,
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
@@ -178,8 +194,8 @@ def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypat
|
||||
def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch):
|
||||
"""幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-2',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-CONFIRM-AP-2',
|
||||
user_id=1,
|
||||
current_order_extraction_id=88,
|
||||
)
|
||||
@@ -219,15 +235,22 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey
|
||||
|
||||
|
||||
def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch):
|
||||
"""任务已离开 created 时幂等回放不再入队。"""
|
||||
"""任务已进入行级库存匹配事实(可履约)时幂等回放不再入队。"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-3',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-CONFIRM-AP-3',
|
||||
user_id=1,
|
||||
upload_status='pending',
|
||||
current_order_extraction_id=77,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
# 已履约事实:可当前库匹配使 _task_needs_post_confirm_auto_progress 判 False。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=1, line_no=1,
|
||||
match_result='matched', inventory_status='ready', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
|
||||
schedule = schedule_auto_progress_after_review_confirm(
|
||||
@@ -285,11 +308,10 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke
|
||||
from app.services.shipping_notice import batch_orchestrator
|
||||
|
||||
with app.app_context():
|
||||
# ShippingBatch 已物理下线;仅用 ShippingNotice 表达确认建单后的悬挂态。
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-4',
|
||||
# ShippingBatch 已物理下线;仅用 ShippingOrderTask 表达确认建单后的悬挂态。
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-CONFIRM-AP-4',
|
||||
user_id=1,
|
||||
source_type='review_confirmation',
|
||||
current_order_extraction_id=66,
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/tests/test_shipping_review_formal_task_edit.py
|
||||
用途:验收正式任务字段写路径(Schema 策略 + order_data_version)与 change_effect 下游失效。
|
||||
依赖:task_workflow、schema_edit_policy、order_schema_service、ShippingOrderTask。
|
||||
逻辑:默认 reservation_id 不可写;Schema editable=True 可写并递增版本;
|
||||
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并同步 OT stage。
|
||||
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage;
|
||||
正式字段编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,15 +13,14 @@ from __future__ import annotations
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderTask,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.task_workflow import update_notice_fields, update_notice_line
|
||||
|
||||
|
||||
@@ -36,12 +36,14 @@ def _review_payload(*, version: int = 1) -> dict[str, object]:
|
||||
|
||||
|
||||
def _attach_extraction(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
rows: list[dict],
|
||||
*,
|
||||
field_policies: dict[str, dict] | None = None,
|
||||
header_values: dict[str, object] | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""建立带 task_edit_policy 的动态 Extraction,供 formal edit 测试使用。"""
|
||||
header_values = dict(header_values or {'po_number': 'PO-FORMAL-001'})
|
||||
order_schema_service.initialize_schema({'display_name': 'Formal Edit Schema'}, actor_id=None)
|
||||
existing_fields = {
|
||||
item['field_code']: item
|
||||
@@ -97,7 +99,7 @@ def _attach_extraction(
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
header_field = fields['po_number']
|
||||
header_value = task.po_number
|
||||
header_value = header_values.get('po_number')
|
||||
header_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id,
|
||||
line_id=None,
|
||||
@@ -118,7 +120,9 @@ def _attach_extraction(
|
||||
value_json=header_value,
|
||||
))
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
line = ShippingOrderLine(
|
||||
extraction_id=extraction.id, position=position, line_no=position + 1,
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, field in fields.items():
|
||||
@@ -150,17 +154,45 @@ def _attach_extraction(
|
||||
return {code: field['id'] for code, field in fields.items()}
|
||||
|
||||
|
||||
def _task(**kwargs) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'),
|
||||
source_type='manual',
|
||||
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
|
||||
match_status=kwargs.pop('match_status', 'matched'),
|
||||
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
|
||||
export_file_path=kwargs.pop('export_file_path', None),
|
||||
export_file_name=kwargs.pop('export_file_name', None),
|
||||
def _freeze_formal_task_snapshot(task: ShippingOrderTask) -> None:
|
||||
"""补齐正式编辑前置:客户确认 + 冻结订单快照,使 order_field_id_values(order_field_purposes) 可读。
|
||||
|
||||
正式编辑路径会对 task 跑 task_reservation_gate_issues → order_field_id_values,
|
||||
后者要求 task.order_snapshot_id 非空;缺快照会抛 order_schema_unavailable 并抢先置 RSV_REQUIRED/OT waiting_review。
|
||||
"""
|
||||
from app.models import ShippingCustomer, ShippingOrderExtraction
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
customer = ShippingCustomer(standard_name='正式编辑测试客户', short_code='FORMAL', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id))
|
||||
if extraction is None:
|
||||
raise ValueError('formal edit test task must have an accepted extraction')
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
freeze_order_snapshot(
|
||||
task, actor_id=None, expected_order_data_version=int(task.order_data_version or 1),
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
'test_fixture': True, 'enabled': True, 'mode': 'qualified',
|
||||
'qualification_status': 'qualified', 'customer_scope_status': 'allowed',
|
||||
'blocking_reason_codes': [],
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _task(**kwargs) -> ShippingOrderTask:
|
||||
"""构造正式订单任务(OT)作为 formal edit 的目标容器。"""
|
||||
task = ShippingOrderTask(
|
||||
task_no=kwargs.pop('task_no', 'OT-FORMAL-EDIT-001'),
|
||||
user_id=1,
|
||||
source_type=kwargs.pop('source_type', 'direct_pdf'),
|
||||
status=kwargs.pop('status', 'processing'),
|
||||
stage=kwargs.pop('stage', 'inventory_matching'),
|
||||
order_data_version=kwargs.pop('order_data_version', 1),
|
||||
order_lines_migration_status='pending',
|
||||
step_payload_json=dict(kwargs.pop('step_payload_json', None) or {}),
|
||||
**kwargs,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -168,24 +200,15 @@ def _task(**kwargs) -> ShippingNotice:
|
||||
return task
|
||||
|
||||
|
||||
def _link_order_task(task: ShippingNotice, *, stage: str = 'inventory_matching') -> ShippingOrderTask:
|
||||
"""挂接 OT 供 change_effect stage 同步断言。"""
|
||||
order_task = ShippingOrderTask(
|
||||
task_no=f'OT-{task.task_no}',
|
||||
user_id=1,
|
||||
candidate_id=None,
|
||||
shipping_notice_id=int(task.id),
|
||||
stage=stage,
|
||||
status='processing',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
def _link_order_task(task: ShippingOrderTask, *, stage: str = 'inventory_matching') -> ShippingOrderTask:
|
||||
"""挂接任务当前 stage 供 change_effect 用例表达 OT 进度;正式编辑任务本身即 OT。"""
|
||||
task.stage = stage
|
||||
db.session.flush()
|
||||
return order_task
|
||||
return task
|
||||
|
||||
|
||||
def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None) -> ShippingExportArtifact:
|
||||
"""为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09)。"""
|
||||
def _seed_ready_export_artifact(task: ShippingOrderTask, *, path: str | None = None) -> ShippingExportArtifact:
|
||||
"""为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09),并挂接正式 Notice 供导出事实读取。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
@@ -193,7 +216,17 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
|
||||
file_path = str(path or task.export_file_path or '/tmp/formal.xlsx')
|
||||
notice = ShippingNotice(
|
||||
task_no=f'SN-{task.task_no}',
|
||||
business_no=f'BN-{task.task_no}',
|
||||
user_id=task.user_id,
|
||||
order_task_id=int(task.id),
|
||||
source_type='direct_pdf',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
|
||||
file_path = str(path or '/tmp/formal.xlsx')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code=f'TPL-{task.task_no}',
|
||||
display_name='Formal Edit',
|
||||
@@ -234,14 +267,14 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None
|
||||
extraction_id = extraction.id
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=f'ART-{task.task_no}',
|
||||
task_id=int(task.id),
|
||||
task_id=int(notice.id),
|
||||
template_id=int(template.id),
|
||||
order_schema_version_id=int(version.id),
|
||||
order_extraction_id=int(extraction_id),
|
||||
inventory_parsing_profile_id=int(profile.id),
|
||||
input_checksum='b' * 64,
|
||||
file_path=file_path,
|
||||
file_name=str(task.export_file_name or 'formal.xlsx'),
|
||||
file_name='formal.xlsx',
|
||||
file_checksum='c' * 64,
|
||||
file_size=10,
|
||||
status='ready',
|
||||
@@ -277,7 +310,7 @@ def test_formal_edit_rejects_default_readonly_field(app):
|
||||
def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
"""Schema editable=True 时允许写入并递增 order_data_version。"""
|
||||
with app.app_context():
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
task = _task()
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -288,7 +321,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
_seed_ready_export_artifact(task)
|
||||
artifact = _seed_ready_export_artifact(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel ready(ready Artifact)时即使 Schema editable 也必须冻结。
|
||||
@@ -302,8 +335,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
assert frozen['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN'
|
||||
|
||||
# 清除导出后允许 Schema 放行字段写入。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
artifact.status = 'superseded'
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
@@ -313,16 +345,14 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
refreshed = db.session.get(ShippingOrderTask, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
# change_effect=none 时不应清空已有匹配结果。
|
||||
assert refreshed.match_status == 'matched'
|
||||
|
||||
|
||||
def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(app):
|
||||
"""rerun_inventory_matching 清空匹配并同步 OT inventory_matching stage。"""
|
||||
"""rerun_inventory_matching 清空匹配/导出并置 invalidated_from_stage。"""
|
||||
with app.app_context():
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
task = _task()
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -333,10 +363,8 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a
|
||||
},
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='excel_generating')
|
||||
# 测试编辑路径:先去掉 Excel 冻结。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
_freeze_formal_task_snapshot(task)
|
||||
_link_order_task(task, stage='excel_generating')
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
@@ -346,19 +374,16 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert refreshed.match_status is None
|
||||
assert refreshed.line_results_json is None
|
||||
assert refreshed.export_file_path is None
|
||||
ot = db.session.get(ShippingOrderTask, order_task.id)
|
||||
assert ot.stage == 'inventory_matching'
|
||||
assert int(ot.progress_version) == 2
|
||||
refreshed = db.session.get(ShippingOrderTask, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
assert refreshed.step_payload_json['invalidated_from_stage'] == 'inventory_matching'
|
||||
assert 'export_meta' not in refreshed.step_payload_json
|
||||
|
||||
|
||||
def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
"""regenerate_excel 仅清空导出并同步 OT excel_generating。"""
|
||||
"""regenerate_excel 仅清空导出并置 invalidated_from_stage。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
task = _task(stage='inventory_matching')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -369,10 +394,8 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='inventory_matching')
|
||||
# 版本不匹配的导出视为 stale,不触发 Excel 冻结,便于测 regenerate_excel。
|
||||
task.export_file_path = '/tmp/stale.xlsx'
|
||||
task.export_file_name = 'stale.xlsx'
|
||||
_freeze_formal_task_snapshot(task)
|
||||
_link_order_task(task, stage='inventory_matching')
|
||||
task.step_payload_json = {
|
||||
**dict(task.step_payload_json or {}),
|
||||
'export_meta': {'order_data_version': 999},
|
||||
@@ -385,19 +408,16 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
**_review_payload(),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert refreshed.match_status == 'matched'
|
||||
assert refreshed.line_results_json == [{'part_number': 'A001'}]
|
||||
assert refreshed.export_file_path is None
|
||||
ot = db.session.get(ShippingOrderTask, order_task.id)
|
||||
assert ot.stage == 'excel_generating'
|
||||
assert int(ot.progress_version) == 2
|
||||
refreshed = db.session.get(ShippingOrderTask, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
assert refreshed.step_payload_json['invalidated_from_stage'] == 'excel_generating'
|
||||
assert 'export_meta' not in refreshed.step_payload_json
|
||||
|
||||
|
||||
def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app):
|
||||
"""有 order_snapshot_id 但 Excel 未 ready 时,Schema editable 字段仍可写。"""
|
||||
with app.app_context():
|
||||
task = _task(order_snapshot_id=12345)
|
||||
task = _task()
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -408,6 +428,7 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
_freeze_formal_task_snapshot(task)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
@@ -417,6 +438,6 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app):
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
refreshed = db.session.get(ShippingOrderTask, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
assert int(refreshed.order_snapshot_id) == 12345
|
||||
assert int(refreshed.order_snapshot_id) == int(task.order_snapshot_id)
|
||||
@@ -3,7 +3,7 @@ tests/test_shipping_review_wave_line_concurrency.py
|
||||
|
||||
用途:同行并发入波次的唯一约束与错误码证据。
|
||||
依赖:pytest、threading、ShippingOrderReviewWaveLine、app fixture。
|
||||
逻辑:两线程同时插入同一 (case, line_key);只允许一条成功;失败映射稳定错误码。
|
||||
逻辑:两线程同时插入同一 (case, snapshot_line_id);只允许一条成功;失败映射稳定错误码。
|
||||
若环境变量 HXOPS_PG_CONCURRENCY_URL 指向 PostgreSQL,则在真实 PG 上再跑一轮。
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingOrderReviewWaveLine, ShippingNotice
|
||||
from app.models import ShippingOrderReviewWaveLine, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_review_confirmation_service import _persist_wave_lines_for_task
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.tool_common import generate_task_no
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -51,32 +50,30 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
task1 = ShippingNotice(
|
||||
task_no=generate_task_no(),
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
task1 = ShippingOrderTask(
|
||||
task_no='OT-WAVE-UQ-1',
|
||||
user_id=int(user.id), source_type='eml',
|
||||
)
|
||||
task2 = ShippingNotice(
|
||||
task_no=generate_task_no(),
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
task2 = ShippingOrderTask(
|
||||
task_no='OT-WAVE-UQ-2',
|
||||
user_id=int(user.id), source_type='eml',
|
||||
)
|
||||
db.session.add_all([task1, task2])
|
||||
db.session.flush()
|
||||
|
||||
_persist_wave_lines_for_task(
|
||||
case=case, task=task1, line_keys=['L-CONC'], wave_no=1, revision_id=None,
|
||||
case=case, task=task1, snapshot_line_ids=[1], wave_no=1, revision_id=None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_persist_wave_lines_for_task(
|
||||
case=case, task=task2, line_keys=['L-CONC'], wave_no=2, revision_id=None,
|
||||
case=case, task=task2, snapshot_line_ids=[1], wave_no=2, revision_id=None,
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_ALREADY_IN_TASK'
|
||||
db.session.rollback()
|
||||
assert ShippingOrderReviewWaveLine.query.filter_by(
|
||||
review_case_id=int(case.id), line_key='L-CONC',
|
||||
review_case_id=int(case.id), snapshot_line_id=1,
|
||||
).count() == 1
|
||||
|
||||
|
||||
@@ -92,7 +89,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.tool_common import generate_task_no
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -109,11 +105,10 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
case_id = int(case.id)
|
||||
|
||||
tasks = []
|
||||
for _ in range(2):
|
||||
task = ShippingNotice(
|
||||
task_no=generate_task_no(),
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
for index in range(2):
|
||||
task = ShippingOrderTask(
|
||||
task_no=f'OT-WAVE-RACE-{index + 1}',
|
||||
user_id=int(user.id), source_type='eml',
|
||||
)
|
||||
db.session.add(task)
|
||||
tasks.append(task)
|
||||
@@ -128,7 +123,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
barrier.wait(timeout=10)
|
||||
row = ShippingOrderReviewWaveLine(
|
||||
review_case_id=case_id,
|
||||
line_key='L-RACE',
|
||||
snapshot_line_id=1,
|
||||
task_id=task_id,
|
||||
wave_no=wave_no,
|
||||
created_at=datetime.utcnow(),
|
||||
@@ -153,7 +148,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
assert results.count('conflict') == 1
|
||||
with app.app_context():
|
||||
assert ShippingOrderReviewWaveLine.query.filter_by(
|
||||
review_case_id=case_id, line_key='L-RACE',
|
||||
review_case_id=case_id, snapshot_line_id=1,
|
||||
).count() == 1
|
||||
|
||||
|
||||
@@ -163,7 +158,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
)
|
||||
def test_wave_line_concurrent_inserts_on_postgres():
|
||||
"""
|
||||
真实 PostgreSQL 上验证 (review_case_id, line_key) 唯一约束并发行为。
|
||||
真实 PostgreSQL 上验证 (review_case_id, snapshot_line_id) 唯一约束并发行为。
|
||||
|
||||
需预先存在空库并可建临时表;通过环境变量注入连接串。
|
||||
"""
|
||||
@@ -182,10 +177,10 @@ def test_wave_line_concurrent_inserts_on_postgres():
|
||||
'tmp_wave_lines', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column('review_case_id', sa.Integer(), sa.ForeignKey('tmp_review_cases.id'), nullable=False),
|
||||
sa.Column('line_key', sa.String(64), nullable=False),
|
||||
sa.Column('snapshot_line_id', sa.Integer(), nullable=False),
|
||||
sa.Column('task_id', sa.Integer(), sa.ForeignKey('tmp_shipping_tasks.id'), nullable=False),
|
||||
sa.Column('wave_no', sa.Integer(), nullable=False),
|
||||
sa.UniqueConstraint('review_case_id', 'line_key', name='uq_tmp_wave_case_line'),
|
||||
sa.UniqueConstraint('review_case_id', 'snapshot_line_id', name='uq_tmp_wave_case_line'),
|
||||
)
|
||||
metadata.drop_all(engine)
|
||||
metadata.create_all(engine)
|
||||
@@ -202,7 +197,7 @@ def test_wave_line_concurrent_inserts_on_postgres():
|
||||
with engine.begin() as conn:
|
||||
try:
|
||||
conn.execute(wave.insert().values(
|
||||
review_case_id=1, line_key='L1', task_id=task_id, wave_no=wave_no,
|
||||
review_case_id=1, snapshot_line_id=101, task_id=task_id, wave_no=wave_no,
|
||||
))
|
||||
return 'ok'
|
||||
except IntegrityError:
|
||||
|
||||
@@ -267,8 +267,18 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
|
||||
assert stage['source'] == 'domain_facts'
|
||||
|
||||
|
||||
def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload():
|
||||
"""历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。"""
|
||||
def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(monkeypatch):
|
||||
"""无成功 Attempt(仅上传尝试已发生但未核对)时仍停留货代上传工作面。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import upload_attempt_service as upload_mod
|
||||
|
||||
# 迁移后上传态以「最近上传尝试」为准,不再读取 Notice 上的历史聚合字段 upload_status。
|
||||
monkeypatch.setattr(
|
||||
upload_mod,
|
||||
'latest_upload_attempt',
|
||||
lambda _task: SimpleNamespace(status='uploaded'),
|
||||
)
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
|
||||
@@ -13,11 +13,32 @@ from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_inventory_rpa_is_running,
|
||||
_project_case_automation_status,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
|
||||
def test_inventory_running_is_not_inferred_from_stage_automation_job():
|
||||
"""阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。"""
|
||||
task = SimpleNamespace(task_no='OT-TEST-1')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
) as query:
|
||||
query.filter.return_value.first.return_value = None
|
||||
assert _inventory_rpa_is_running(task) is False
|
||||
|
||||
|
||||
def test_inventory_running_requires_queued_or_running_attempt():
|
||||
"""只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。"""
|
||||
task = SimpleNamespace(task_no='OT-TEST-2')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
|
||||
) as query:
|
||||
query.filter.return_value.first.return_value = SimpleNamespace(status='queued')
|
||||
assert _inventory_rpa_is_running(task) is True
|
||||
|
||||
|
||||
def test_automation_waiting_to_start_when_eligible_but_not_queued():
|
||||
"""资格达标且未建单时只能是 waiting_to_start,不得伪装 running。"""
|
||||
case = SimpleNamespace(
|
||||
@@ -151,10 +172,12 @@ def test_unexpected_stp_error_has_stable_user_message():
|
||||
category_hint='temporary_storage_error',
|
||||
)
|
||||
|
||||
assert retryable is False
|
||||
assert retryable is True
|
||||
assert result['message'] == '自动建单失败,已停止,等待用户选择下一步动作'
|
||||
assert 'psycopg2' not in result['message']
|
||||
assert 'invalid input syntax' not in result['message']
|
||||
assert result['next_action'] == 'retry_stp_auto_create'
|
||||
assert result['decision_trace']['matched_rule'] == 'temporary_storage_error'
|
||||
|
||||
|
||||
def test_automation_failed_stops_when_post_confirm_needs_user_action():
|
||||
@@ -456,7 +479,8 @@ def test_project_user_gate_summary_exposes_retry_for_confirmed_inventory_pending
|
||||
|
||||
assert summary['current_blocking_gate']['status'] == 'blocked_retryable'
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == ['retry_inventory_matching']
|
||||
# 迁移后行级库存源在 Excel 未生成时持续可编辑,选源/覆写动作与阻断态解耦。
|
||||
assert summary['allowed_actions'] == ['retry_inventory_matching', 'override_line_inventory_source']
|
||||
|
||||
|
||||
def test_project_user_gate_summary_keeps_pending_match_system_owned_without_inventory(monkeypatch):
|
||||
|
||||
@@ -63,7 +63,7 @@ def test_sanitize_audit_field_value_truncates_long_text() -> None:
|
||||
|
||||
|
||||
def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
"""仅有 export_file_path、无 ready Artifact 时不得冻结(BE-09)。"""
|
||||
"""无 ready Artifact 时不得冻结;只有 Artifact 进入 ready 才冻结。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
@@ -76,14 +76,7 @@ def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-EXCEL-READY-BE09',
|
||||
source_type='manual',
|
||||
export_file_path='/tmp/be09.xlsx',
|
||||
export_file_name='be09.xlsx',
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
task = ShippingNotice(task_no='SN-EXCEL-READY-BE09', source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
assert is_excel_ready_for_task(task) is False
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
# backend/tests/test_shipping_stage_capability.py
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
STAGE_CAPABILITY_DEFINITIONS,
|
||||
stage_capability,
|
||||
is_stage_capability,
|
||||
capability_stage,
|
||||
)
|
||||
|
||||
|
||||
def test_stage_capability_definitions_exist():
|
||||
assert 'retry_inventory_preparation' in STAGE_CAPABILITY_DEFINITIONS
|
||||
assert 'override_line_inventory_source' in STAGE_CAPABILITY_DEFINITIONS
|
||||
assert 'reload_inventory_result' in STAGE_CAPABILITY_DEFINITIONS
|
||||
|
||||
|
||||
def test_stage_capability_returns_definition():
|
||||
cap = stage_capability('retry_inventory_preparation')
|
||||
assert cap is not None
|
||||
assert cap['stage'] == 'fulfillment_prep'
|
||||
assert cap['scope'] == 'task'
|
||||
assert cap['reset_to'] == 'inventory_preparation'
|
||||
assert 'inventory_matching' in cap['invalidate']
|
||||
|
||||
|
||||
def test_stage_capability_unknown_returns_none():
|
||||
assert stage_capability('retry_freight_upload_rpa') is None
|
||||
|
||||
|
||||
def test_is_stage_capability():
|
||||
assert is_stage_capability('retry_inventory_preparation') is True
|
||||
assert is_stage_capability('retry_freight_upload_rpa') is False
|
||||
assert is_stage_capability(None) is False
|
||||
|
||||
|
||||
def test_capability_stage():
|
||||
assert capability_stage('retry_inventory_preparation') == 'fulfillment_prep'
|
||||
assert capability_stage('unknown') is None
|
||||
|
||||
|
||||
# 追加到 test_shipping_stage_capability.py
|
||||
def test_build_task_ui_state_exposes_capabilities(monkeypatch):
|
||||
# 构造一个确认任务(轻量,不依赖 DB);此处用真正的 ui_state 冒烟,最小断言字段存在
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
# 直接测纯辅助,避免重 DB 依赖
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []},
|
||||
source_locked=False,
|
||||
)
|
||||
codes = [c['code'] for c in caps]
|
||||
assert 'retry_inventory_preparation' in codes
|
||||
assert 'reload_inventory_result' in codes
|
||||
assert 'override_line_inventory_source' in codes
|
||||
|
||||
|
||||
def test_capabilities_disabled_when_excel_locked():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': True, 'lines': []},
|
||||
source_locked=True,
|
||||
)
|
||||
assert all(c['enabled'] is False for c in caps)
|
||||
assert all(c['disabled_reason'] for c in caps)
|
||||
|
||||
|
||||
# 预条件语义(Task 2 变更):能力可用性由数据谓词决定,而非仅代码在场。
|
||||
# 断言关键分支:重抓(有候选源/Excel未锁定);重抓(无候选源但有失败源);重读(已有抓取结果)。
|
||||
def test_retry_inventory_preparation_enabled_with_candidates():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []},
|
||||
source_locked=False,
|
||||
)
|
||||
by_code = {c['code']: c for c in caps}
|
||||
# 预条件:source_options 非空(候选源) + Excel 未锁定 → 重抓可用。
|
||||
assert by_code['retry_inventory_preparation']['enabled'] is True
|
||||
assert by_code['retry_inventory_preparation']['disabled_reason'] is None
|
||||
|
||||
|
||||
def test_retry_inventory_preparation_enabled_with_failed_source():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={
|
||||
'source_options': [], 'source_locked': False, 'lines': [],
|
||||
'failed_source_codes': ['CRANE'],
|
||||
},
|
||||
source_locked=False,
|
||||
)
|
||||
by_code = {c['code']: c for c in caps}
|
||||
# 预条件:无候选源但存在失败源(有抓取失败的源可重试) → 重抓仍可用
|
||||
# (docstring:重抓→有候选源或失败源)。这是一期实现遗漏的分支,此处锁定。
|
||||
assert by_code['retry_inventory_preparation']['enabled'] is True
|
||||
assert by_code['retry_inventory_preparation']['disabled_reason'] is None
|
||||
|
||||
|
||||
def test_reload_inventory_result_enabled_with_resolved_source():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={
|
||||
'source_options': [], 'source_locked': False, 'lines': [],
|
||||
'resolved_source_codes': ['CRANE'],
|
||||
},
|
||||
source_locked=False,
|
||||
)
|
||||
by_code = {c['code']: c for c in caps}
|
||||
# 预条件:已有抓取结果(resolved_source_codes 非空) → 重读可用。
|
||||
assert by_code['reload_inventory_result']['enabled'] is True
|
||||
assert by_code['reload_inventory_result']['disabled_reason'] is None
|
||||
|
||||
|
||||
# Task 3 —— 编排器 execute_stage_capability(作废下游 + 重置 + 幂等重跑)
|
||||
# 断言意图:invalidate_downstream_gates 的返回被透传为 invalidated_gates;重走后
|
||||
# run_task_auto_progress 会执行(reran=True);capability['reset_to'] 使 current_gate_code 复位。
|
||||
from app.services.shipping_notice.process_gate_service import execute_stage_capability
|
||||
|
||||
|
||||
def test_execute_stage_capability_invalidates_downstream(monkeypatch):
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'passed'
|
||||
|
||||
class FakeExecution:
|
||||
current_gate_code = 'inventory_field_mapping'
|
||||
id = 1
|
||||
|
||||
calls = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates',
|
||||
lambda **kw: calls.update(kw) or ['inventory_field_mapping', 'inventory_matching'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.run_task_auto_progress',
|
||||
lambda *a, **k: calls.update(run=True, run_kwargs=k),
|
||||
)
|
||||
cap = stage_capability('retry_inventory_preparation')
|
||||
result = execute_stage_capability(
|
||||
execution=FakeExecution(), gate=FakeGate(), capability=cap,
|
||||
actor_type='user', actor_id=1, idempotency_key='k1',
|
||||
)
|
||||
assert 'inventory_field_mapping' in result['invalidated_gates']
|
||||
assert calls.get('run') is True
|
||||
# 断言失效链只作废准备 Gate 的下游,不能把准备 Gate 自身置 invalidated。
|
||||
assert calls['change_type'] == 'inventory_source_changed'
|
||||
assert calls['exclude_gate_codes'] == {'inventory_preparation'}
|
||||
# 断言幂等键被真正透传给 run_task_auto_progress(findings:曾经接收但不转发)。
|
||||
assert calls['run_kwargs']['idempotency_key'] == 'k1'
|
||||
# 用户点击重抓库存必须保留定向恢复语义,不能退化成失败后的自动重试。
|
||||
assert calls['run_kwargs']['resume_gate_code'] == 'inventory_preparation'
|
||||
assert calls['run_kwargs']['inventory_mode'] == 'retry_rpa'
|
||||
|
||||
|
||||
def test_execute_stage_capability_forwards_line_scope_for_line_rpa_retry(monkeypatch):
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'blocked_retryable'
|
||||
|
||||
class FakeExecution:
|
||||
current_gate_code = 'inventory_matching'
|
||||
id = 1
|
||||
|
||||
calls = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates',
|
||||
lambda **kw: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.run_task_auto_progress',
|
||||
lambda *a, **k: calls.update(run_kwargs=k),
|
||||
)
|
||||
result = execute_stage_capability(
|
||||
execution=FakeExecution(), gate=FakeGate(), capability=stage_capability('retry_inventory_preparation'),
|
||||
actor_type='user', actor_id=1, idempotency_key='line-rpa', line_scope_key=42,
|
||||
)
|
||||
assert result['reran'] is True
|
||||
assert calls['run_kwargs']['line_scope_key'] == '42'
|
||||
|
||||
|
||||
def test_execute_stage_capability_resets_to_preparation(monkeypatch):
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'passed'
|
||||
|
||||
class FakeExecution:
|
||||
current_gate_code = 'inventory_field_mapping'
|
||||
id = 1
|
||||
|
||||
execution = FakeExecution()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates',
|
||||
lambda **kw: ['inventory_matching'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.run_task_auto_progress',
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
cap = stage_capability('retry_inventory_preparation')
|
||||
result = execute_stage_capability(
|
||||
execution=execution, gate=FakeGate(), capability=cap,
|
||||
actor_type='user', actor_id=1, idempotency_key='k2',
|
||||
)
|
||||
assert result['reset_to'] == 'inventory_preparation'
|
||||
# 断言真实副作用:执行对象被复位回能力起始 gate,而非仅回显返回的 reset_to。
|
||||
assert execution.current_gate_code == 'inventory_preparation'
|
||||
|
||||
|
||||
def test_execute_stage_capability_reran_false_on_failed_progress(monkeypatch):
|
||||
# 断言:run_task_auto_progress 对失败返回 dict(status=failed)而非抛异常时,reran 必须为 False,
|
||||
# 避免把「实际失败」误报为已重跑(findings:reran 守卫仅凭未抛异常便判成功)。
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'passed'
|
||||
|
||||
class FakeExecution:
|
||||
current_gate_code = 'inventory_field_mapping'
|
||||
id = 1
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates',
|
||||
lambda **kw: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.run_task_auto_progress',
|
||||
lambda *a, **k: {'status': 'failed', 'message': '未找到任务编号'},
|
||||
)
|
||||
cap = stage_capability('retry_inventory_preparation')
|
||||
result = execute_stage_capability(
|
||||
execution=FakeExecution(), gate=FakeGate(), capability=cap,
|
||||
actor_type='user', actor_id=1, idempotency_key='k3',
|
||||
)
|
||||
assert result['reran'] is False
|
||||
assert result.get('reran_reason') == '未找到任务编号'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Task 4 —— request_gate_action 阶段能力豁免
|
||||
# 纯谓词 is_stage_capability_exempt 是本任务的测试主门(无 IO、可单测);
|
||||
# request_gate_action 路由仅做一次打桩冒烟,验证「阶段能力请求非当前 gate 不抛
|
||||
# SHIPPING.PROCESS_GATE_NOT_CURRENT」。打桩较重,若未来漂移可仅保留纯谓词测试。
|
||||
# ============================================================
|
||||
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
|
||||
|
||||
|
||||
def test_stage_capability_exempt_in_window():
|
||||
# 断言意图:能力阶段匹配 + 请求 gate 落在 invalidate 范围 → 豁免非当前 gate 校验。
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='inventory_field_mapping',
|
||||
requested_gate='inventory_field_mapping',
|
||||
action_code='retry_inventory_preparation',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is True
|
||||
|
||||
|
||||
def test_stage_capability_exempt_reset_to_branch():
|
||||
# 断言意图:请求 gate 等于能力 reset_to(inventory_preparation)→ 豁免(reset_to 分支)。
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='inventory_field_mapping',
|
||||
requested_gate='inventory_preparation',
|
||||
action_code='retry_inventory_preparation',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is True
|
||||
|
||||
|
||||
def test_stage_capability_exempt_wrong_lifecycle_stage():
|
||||
# 断言意图:能力阶段不符(order_review != fulfillment_prep)→ 不豁免。
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='order_field_extraction',
|
||||
requested_gate='inventory_field_mapping',
|
||||
action_code='retry_inventory_preparation',
|
||||
lifecycle_stage='order_review',
|
||||
) is False
|
||||
|
||||
|
||||
def test_stage_capability_exempt_non_capability():
|
||||
# 断言意图:动作不是阶段能力(freight upload)→ 不豁免。
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='inventory_field_mapping',
|
||||
requested_gate='inventory_preparation',
|
||||
action_code='retry_freight_upload_rpa',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is False
|
||||
|
||||
|
||||
def test_stage_capability_exempt_out_of_range():
|
||||
# 断言意图:能力阶段匹配但请求 gate 超出作废/重置范围 → 不豁免。
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='inventory_field_mapping',
|
||||
requested_gate='document_materialization',
|
||||
action_code='retry_inventory_preparation',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is False
|
||||
|
||||
|
||||
def test_request_gate_action_stage_capability_exemption(monkeypatch):
|
||||
# 断言意图:请求「非当前 gate」的阶段能力动作被豁免 not-current 校验,直接走
|
||||
# execute_stage_capability 返回 outcome=submitted,且不抛 PROCESS_GATE_NOT_CURRENT。
|
||||
# (打桩较重:gate/attempt 查询与 execute/serialize 均以假对象替换。)
|
||||
from app.services.shipping_notice import process_gate_recovery_service as svc
|
||||
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'blocked_retryable'
|
||||
blocking_reason_code = None
|
||||
next_action_code = None
|
||||
evaluation_version = 1
|
||||
|
||||
class FakeExec:
|
||||
id = 1
|
||||
execution_no = 'SPE-X'
|
||||
status = 'active'
|
||||
current_gate_code = 'inventory_field_mapping'
|
||||
task_id = 1
|
||||
|
||||
class FakeQuery:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
|
||||
def filter_by(self, **kw):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._rows[0] if self._rows else None
|
||||
|
||||
def get(self, pk, default=None):
|
||||
return self._rows[0] if self._rows else default
|
||||
|
||||
monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec())
|
||||
monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()]))
|
||||
monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([]))
|
||||
monkeypatch.setattr(
|
||||
svc, 'execute_stage_capability',
|
||||
lambda **kw: {'invalidated_gates': ['inventory_field_mapping'], 'reset_to': 'inventory_preparation', 'reran': True},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, 'serialize_process_gate',
|
||||
lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status},
|
||||
)
|
||||
|
||||
result = request_gate_action(
|
||||
execution_no='SPE-X',
|
||||
gate_code='inventory_preparation',
|
||||
action_code='retry_inventory_preparation',
|
||||
expected_gate_version=1,
|
||||
idempotency_key='k',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
)
|
||||
assert result['outcome'] == 'submitted'
|
||||
assert result['gate_summary']['gate_code'] == 'inventory_preparation'
|
||||
assert result['stage_capability']['reran'] is True
|
||||
|
||||
|
||||
def test_request_gate_action_rejects_stage_capability_on_orphan_execution(monkeypatch):
|
||||
"""库存阶段能力不得在未绑定 OT 的孤立 Execution 上创建 Attempt。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice import process_gate_recovery_service as svc
|
||||
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_preparation'
|
||||
status = 'blocked_retryable'
|
||||
blocking_reason_code = 'inventory_rpa_timeout'
|
||||
next_action_code = 'reload_inventory_result'
|
||||
evaluation_version = 1
|
||||
|
||||
class FakeExecution:
|
||||
id = 1
|
||||
execution_no = 'SPE-ORPHAN'
|
||||
status = 'active'
|
||||
current_gate_code = 'inventory_preparation'
|
||||
task_id = None
|
||||
|
||||
class FakeQuery:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return FakeGate()
|
||||
|
||||
monkeypatch.setattr(svc, 'get_execution_by_no', lambda _no: FakeExecution())
|
||||
monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery())
|
||||
monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery())
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
request_gate_action(
|
||||
execution_no='SPE-ORPHAN', gate_code='inventory_preparation',
|
||||
action_code='reload_inventory_result', expected_gate_version=1,
|
||||
idempotency_key='orphan-reload', actor_type='user', actor_id=1,
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.PROCESS_EXECUTION_TASK_BOUND'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Task 6 —— 死局回归(F5CDD796 语义)
|
||||
# 场景:库存源已标记 resolved(如 CRANE)但实际无匹配结果、Excel 未生成。
|
||||
# 断言:此时“重新获取库存”能力仍必须 enabled,因为 source_options 中有候选源。
|
||||
# (若实现把「已 resolved 但无匹配」误判为无候选而置灰,此测试会失败。)
|
||||
# ============================================================
|
||||
def test_retry_preparation_available_after_resolved_no_match():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={
|
||||
'source_options': [{'source_code': 'CRANE'}],
|
||||
'source_locked': False,
|
||||
'lines': [],
|
||||
'resolved_source_codes': [],
|
||||
},
|
||||
source_locked=False,
|
||||
)
|
||||
retry = next(c for c in caps if c['code'] == 'retry_inventory_preparation')
|
||||
assert retry['enabled'] is True
|
||||
assert retry['disabled_reason'] is None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 重新匹配库存 · 阶段能力(retry_inventory_matching)——问题 2.1 / 2.2
|
||||
# 场景:通知准备阶段、已有匹配结果但门禁已推进到满足性/Excel 生成时,用户仍应能「重新匹配库存」。
|
||||
# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游,因此:
|
||||
# - 能力定义:作废 matching/sufficiency/excel/artifact,invalidate_change_type=inventory_field_mapping_changed,
|
||||
# reset_to=inventory_matching;
|
||||
# - request_gate_action 对它的阶段能力豁免走 execute_stage_capability_rematch(专用重匹配编排),
|
||||
# 而非 execute_stage_capability 的「宽作废 + 重抓」。
|
||||
# ============================================================
|
||||
def test_retry_inventory_matching_stage_capability_definition():
|
||||
assert 'retry_inventory_matching' in STAGE_CAPABILITY_DEFINITIONS
|
||||
cap = stage_capability('retry_inventory_matching')
|
||||
assert cap is not None
|
||||
assert cap['stage'] == 'fulfillment_prep'
|
||||
assert cap['scope'] == 'task'
|
||||
assert cap['action_code'] == 'retry_inventory_matching'
|
||||
assert cap['reset_to'] == 'inventory_matching'
|
||||
# 重匹配只作废匹配及其下游,不重抓/不重做 mapping。
|
||||
assert 'inventory_sufficiency' in cap['invalidate']
|
||||
assert 'excel_readiness' in cap['invalidate']
|
||||
assert 'artifact_generation' in cap['invalidate']
|
||||
assert 'inventory_preparation' not in cap['invalidate']
|
||||
assert cap['invalidate_change_type'] == 'inventory_field_mapping_changed'
|
||||
assert is_stage_capability('retry_inventory_matching') is True
|
||||
assert capability_stage('retry_inventory_matching') == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_retry_inventory_matching_exempt_in_window():
|
||||
from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt
|
||||
# 门禁已推进到 excel_readiness 仍属通知准备阶段 → 豁免非当前 gate 校验。
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='excel_readiness',
|
||||
requested_gate='excel_readiness',
|
||||
action_code='retry_inventory_matching',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is True
|
||||
# 请求的 matching gate(reset_to 分支)也豁免。
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='inventory_sufficiency',
|
||||
requested_gate='inventory_matching',
|
||||
action_code='retry_inventory_matching',
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) is True
|
||||
# 非本阶段 → 不豁免。
|
||||
assert is_stage_capability_exempt(
|
||||
current_gate='excel_readiness',
|
||||
requested_gate='excel_readiness',
|
||||
action_code='retry_inventory_matching',
|
||||
lifecycle_stage='order_review',
|
||||
) is False
|
||||
|
||||
|
||||
def test_retry_inventory_matching_enabled_with_match_result():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={
|
||||
'source_options': [], 'source_locked': False, 'lines': [],
|
||||
'has_match_result': True,
|
||||
},
|
||||
source_locked=False,
|
||||
)
|
||||
by_code = {c['code']: c for c in caps}
|
||||
# 预条件:已有匹配结果 → 重匹配可用(即使门禁已推进)。
|
||||
assert by_code['retry_inventory_matching']['enabled'] is True
|
||||
assert by_code['retry_inventory_matching']['disabled_reason'] is None
|
||||
|
||||
|
||||
def test_retry_inventory_matching_disabled_without_match_result():
|
||||
from app.services.shipping_notice.ui_state import _stage_capabilities_for_task
|
||||
caps = _stage_capabilities_for_task(
|
||||
task=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
preparation={
|
||||
'source_options': [], 'source_locked': False, 'lines': [],
|
||||
'has_match_result': False,
|
||||
},
|
||||
source_locked=False,
|
||||
)
|
||||
by_code = {c['code']: c for c in caps}
|
||||
assert by_code['retry_inventory_matching']['enabled'] is False
|
||||
assert by_code['retry_inventory_matching']['disabled_reason'] == 'no_match_result'
|
||||
|
||||
|
||||
def test_request_gate_action_routes_retry_inventory_matching_to_rematch(monkeypatch):
|
||||
# 断言意图:retry_inventory_matching 的阶段能力豁免必须走 execute_stage_capability_rematch,
|
||||
# 而不是 execute_stage_capability(避免「宽作废 + 重抓」)。
|
||||
from app.services.shipping_notice import process_gate_recovery_service as svc
|
||||
|
||||
class FakeGate:
|
||||
gate_code = 'inventory_sufficiency'
|
||||
status = 'blocked_manual'
|
||||
blocking_reason_code = 'inventory_insufficient'
|
||||
next_action_code = None
|
||||
evaluation_version = 1
|
||||
|
||||
class FakeExec:
|
||||
id = 1
|
||||
execution_no = 'SPE-X'
|
||||
status = 'active'
|
||||
current_gate_code = 'inventory_sufficiency'
|
||||
task_id = 1
|
||||
|
||||
class FakeQuery:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
|
||||
def filter_by(self, **kw):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._rows[0] if self._rows else None
|
||||
|
||||
def get(self, pk, default=None):
|
||||
return self._rows[0] if self._rows else default
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec())
|
||||
monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()]))
|
||||
monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([]))
|
||||
monkeypatch.setattr(
|
||||
svc, 'execute_stage_capability_rematch',
|
||||
lambda **kw: captured.update(kw) or {
|
||||
'invalidated_gates': ['inventory_matching', 'inventory_sufficiency'],
|
||||
'reset_to': 'inventory_matching', 'reran': True, 'gate_status': 'blocked_retryable',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, 'execute_stage_capability',
|
||||
lambda **kw: (_ for _ in ()).throw(AssertionError('must not call execute_stage_capability')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, 'serialize_process_gate',
|
||||
lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status},
|
||||
)
|
||||
|
||||
result = request_gate_action(
|
||||
execution_no='SPE-X',
|
||||
gate_code='inventory_sufficiency',
|
||||
action_code='retry_inventory_matching',
|
||||
expected_gate_version=1,
|
||||
idempotency_key='k',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
)
|
||||
assert result['outcome'] == 'submitted'
|
||||
assert result['gate_summary']['gate_code'] == 'inventory_sufficiency'
|
||||
assert result['stage_capability']['reran'] is True
|
||||
assert captured['idempotency_key'] == 'k'
|
||||
|
||||
|
||||
def test_execute_stage_capability_rematch_reuses_matching_attempt(monkeypatch):
|
||||
# 断言意图:重匹配编排作废匹配及下游,并把动作经 inventory_matching gate 的 Attempt 通道重跑,
|
||||
# 而不是走 execute_stage_capability 的 run_task_auto_progress 宽重跑。
|
||||
from app.services.shipping_notice import process_gate_service as svc
|
||||
|
||||
class FakeGate:
|
||||
id = 20
|
||||
gate_code = 'inventory_matching'
|
||||
status = 'invalidated'
|
||||
evaluation_version = 3
|
||||
|
||||
class FakeExecution:
|
||||
id = 1
|
||||
execution_no = 'SPE-X'
|
||||
current_gate_code = 'inventory_sufficiency'
|
||||
task_id = 1
|
||||
|
||||
class FakeAttempt:
|
||||
id = 99
|
||||
status = 'queued'
|
||||
|
||||
class FakeUpdatedGate:
|
||||
status = 'blocked_retryable'
|
||||
|
||||
calls = {}
|
||||
monkeypatch.setattr(
|
||||
svc, 'invalidate_downstream_gates',
|
||||
lambda **kw: calls.update(invalidated=kw.get('change_type')) or ['inventory_matching', 'inventory_sufficiency'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, 'queue_gate_attempt',
|
||||
lambda **kw: calls.update(queued_gate=kw.get('gate_code'), queued_action=(kw.get('input_snapshot') or {}).get('action_code')) or FakeAttempt(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor.execute_queued_attempt',
|
||||
lambda attempt, worker_id=None: calls.update(executed=attempt.status) or FakeUpdatedGate(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, '_refresh_execution_pointers',
|
||||
lambda execution: calls.update(refreshed=execution.current_gate_code),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.db.session.flush',
|
||||
lambda **kw: None,
|
||||
)
|
||||
# ShippingProcessGate.query 桩:返回 matching gate。
|
||||
class FakeGateQuery:
|
||||
def __init__(self):
|
||||
self._rows = [FakeGate()]
|
||||
|
||||
def filter_by(self, **kw):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._rows[0]
|
||||
|
||||
monkeypatch.setattr(
|
||||
svc.ShippingProcessGate, 'query', FakeGateQuery(),
|
||||
)
|
||||
|
||||
result = svc.execute_stage_capability_rematch(
|
||||
execution=FakeExecution(), actor_type='user', actor_id=1, idempotency_key='k9',
|
||||
)
|
||||
assert result['invalidated_gates'] == ['inventory_matching', 'inventory_sufficiency']
|
||||
assert calls.get('invalidated') == 'inventory_field_mapping_changed'
|
||||
assert calls.get('queued_gate') == 'inventory_matching'
|
||||
assert calls.get('queued_action') == 'retry_inventory_matching'
|
||||
assert calls.get('executed') == 'queued'
|
||||
assert calls.get('refreshed') == 'inventory_sufficiency'
|
||||
assert result['reran'] is True
|
||||
assert result['gate_status'] == 'blocked_retryable'
|
||||
assert result['reset_to'] == 'inventory_matching'
|
||||
@@ -31,6 +31,7 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch):
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
task_no='T-STP-1',
|
||||
order_task_id=1,
|
||||
)
|
||||
tool_common_mod.log_task_event(
|
||||
task,
|
||||
@@ -74,16 +75,33 @@ def test_event_actor_id_accepts_trusted_user_id():
|
||||
assert _event_actor_id({}) is None
|
||||
|
||||
|
||||
def test_confirm_inventory_source_passes_actor_to_match():
|
||||
"""多源恢复确认后调用 match_inventory 时须携带操作人,不得只传 _trusted_user_id。"""
|
||||
source = Path(tool_common_mod.__file__).resolve().parents[0] / 'inventory_rpa_workflow.py'
|
||||
text = source.read_text(encoding='utf-8')
|
||||
# 普通确认路径须把 actor_id/source 传给 log_task_event。
|
||||
assert 'actor_id=confirmed_by' in text
|
||||
assert "source='workspace_api' if confirmed_by else 'system'" in text
|
||||
# 多源恢复后重匹配须显式传 operator_id / actor_id。
|
||||
assert '"operator_id": trusted_uid' in text or "'operator_id': trusted_uid" in text
|
||||
assert '"actor_id": trusted_uid' in text or "'actor_id': trusted_uid" in text
|
||||
def test_confirm_inventory_source_passes_actor_to_match(monkeypatch):
|
||||
"""库存源人工确认入口已下线;真实操作人传递落在 match_inventory 的 operator_id 透传。"""
|
||||
from app.services.shipping_notice import fulfillment_workflow
|
||||
from app.services.shipping_notice import progress_workflow
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_run_task_auto_progress(*args, **kwargs):
|
||||
captured['args'] = args
|
||||
captured['kwargs'] = kwargs
|
||||
return {'status': 'ok'}
|
||||
|
||||
monkeypatch.setattr(progress_workflow, 'run_task_auto_progress', _fake_run_task_auto_progress)
|
||||
|
||||
# 多源恢复确认后的 match_inventory 须把操作人经 operator_id 透传给推进器,
|
||||
# 不得只依赖 _trusted_user_id 或在编排层丢弃。
|
||||
result = fulfillment_workflow.match_inventory({
|
||||
'task_no': 'OT-STP-1',
|
||||
'operator_id': 7,
|
||||
'source': 'workspace_api',
|
||||
})
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert captured['args'][0] == 'OT-STP-1'
|
||||
assert captured['kwargs']['operator_id'] == 7
|
||||
assert captured['kwargs']['resume_gate_code'] == 'inventory_matching'
|
||||
assert captured['kwargs']['trigger'] == 'workspace_api'
|
||||
|
||||
|
||||
def test_stp_auto_create_failed_commit_must_raise():
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
tests/test_shipping_stp_multi_source_recovery.py
|
||||
|
||||
用途:验证多源/多文件冲突人工指定库存源恢复与强制源过滤。
|
||||
依赖:stp_line_inventory_match。
|
||||
逻辑:覆盖 recovery 候选汇总、forced_match 过滤;不启 Flask 全链路。
|
||||
依赖:stp_line_inventory_match、ShippingNoticeLineInventoryMatch(真实 DB 匹配事实)。
|
||||
逻辑:recovery 候选取自行级 Match 事实(source_conflict + detail_json.candidate_hit_source_codes,
|
||||
缺失时回退全部可用源);forced_match 过滤沿用 step_payload 路径;不启 Flask 全链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
apply_forced_match_source_filter,
|
||||
multi_source_recovery_source_codes,
|
||||
@@ -17,36 +18,110 @@ from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
)
|
||||
|
||||
|
||||
def test_recovery_codes_from_resolved_ok_sources():
|
||||
"""multi_source_excel_block 时优先取 resolved_ok_source_codes。"""
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={
|
||||
'multi_source_excel_block': True,
|
||||
'resolved_ok_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
},
|
||||
)
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
def _seed_task(task_no: str) -> ShippingNotice:
|
||||
"""建一条最小正式发货通知,获取可被匹配事实引用的任务 id。"""
|
||||
task = ShippingNotice(task_no=task_no, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def test_recovery_codes_from_multi_file_conflict_candidates():
|
||||
"""无 resolved_ok 时汇总 multi_file_conflict 行的 candidate_hit_source_codes。"""
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={
|
||||
'line_inventory_resolutions': [
|
||||
{
|
||||
'disposition': 'multi_file_conflict',
|
||||
'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
},
|
||||
],
|
||||
},
|
||||
def _seed_source_conflict_fact(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
detail_json: dict,
|
||||
snapshot_line_id: int = 101,
|
||||
line_no: int = 1,
|
||||
line_index: int = 0,
|
||||
) -> ShippingNoticeLineInventoryMatch:
|
||||
"""写入一条 source_conflict 行级匹配事实,供 load_current_match_facts_by_task 读取。"""
|
||||
row = ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
line_no=line_no,
|
||||
line_index=line_index,
|
||||
match_result='source_conflict',
|
||||
inventory_status='ready',
|
||||
detail_json=detail_json,
|
||||
is_current=True,
|
||||
)
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def _seed_enabled_source(source_code: str, warehouse_id: str) -> None:
|
||||
"""复用测试解析方案/模板,落一条启用库存源,供全部可用源兜底枚举。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
)
|
||||
|
||||
parsing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
|
||||
template = ShippingExcelTemplate.query.filter_by(template_code='TEST_RUNTIME').first()
|
||||
if parsing is None or template is None:
|
||||
raise AssertionError('TEST_RUNTIME parsing profile / excel template not seeded')
|
||||
profile = ShippingRpaProfile(
|
||||
profile_code=f'{source_code}-PROFILE',
|
||||
display_name=f'{source_code} Profile',
|
||||
connector_type='dbs',
|
||||
login_url='https://test.invalid/dbs',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code=source_code,
|
||||
display_name=f'{source_code} Source',
|
||||
connector_type='dbs',
|
||||
rpa_profile_id=profile.id,
|
||||
parsing_profile_id=parsing.id,
|
||||
excel_template_id=template.id,
|
||||
warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id=warehouse_id,
|
||||
enabled=True,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_recovery_codes_from_resolved_ok_sources(app):
|
||||
"""冲突行未记录 candidate_hit_source_codes 时回退为全部可用库存源。"""
|
||||
from app.models import ShippingInventorySource
|
||||
|
||||
with app.app_context():
|
||||
task = _seed_task('SN-RECOVERY-FALLBACK')
|
||||
# 兜底枚举只保留 DBS_DUB / DBS_RTM 两个启用源(清掉 conftest 默认源干扰)。
|
||||
default = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
if default is not None:
|
||||
default.enabled = False
|
||||
db.session.flush()
|
||||
_seed_enabled_source('DBS_DUB', 'DUB')
|
||||
_seed_enabled_source('DBS_RTM', 'RTM')
|
||||
# 冲突行未携带候选源 → 走全部可用源兜底。
|
||||
_seed_source_conflict_fact(task, detail_json={})
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
|
||||
|
||||
def test_recovery_codes_from_multi_file_conflict_candidates(app):
|
||||
"""冲突行的 candidate_hit_source_codes 优先作为可指定源,无需兜底。"""
|
||||
with app.app_context():
|
||||
task = _seed_task('SN-RECOVERY-CONFLICT')
|
||||
_seed_source_conflict_fact(
|
||||
task,
|
||||
detail_json={'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM']},
|
||||
)
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
|
||||
|
||||
def test_forced_match_source_filter_keeps_only_selected_source():
|
||||
"""人工指定源后仅保留该源库存行,消除跨源冲突输入。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = SimpleNamespace(
|
||||
inventory_source_code='DBS_DUB',
|
||||
step_payload_json={'forced_match_source_code': 'DBS_DUB'},
|
||||
@@ -65,6 +140,8 @@ def test_forced_match_source_filter_keeps_only_selected_source():
|
||||
|
||||
def test_forced_match_filter_noop_without_source_tags():
|
||||
"""库存行无 __source_code 时不过滤,保持旧单源路径兼容。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = SimpleNamespace(
|
||||
inventory_source_code='DBS_DUB',
|
||||
step_payload_json={'forced_match_source_code': 'DBS_DUB'},
|
||||
|
||||
@@ -11,8 +11,7 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
collect_frozen_candidate_codes,
|
||||
@@ -89,13 +88,13 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch):
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-STP-FREEZE-ONE', user_id=1, source_type='eml')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
result = freeze_stp_inventory_candidates_on_task(
|
||||
task,
|
||||
line_projections=[{
|
||||
'line_key': 'L1',
|
||||
'line_no': 1,
|
||||
'candidate_inventory_source_codes': ['DBS_DUB'],
|
||||
'selection_mode': 'rule',
|
||||
'routing_status': 'resolved',
|
||||
@@ -103,10 +102,10 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch):
|
||||
}],
|
||||
)
|
||||
assert result.status == 'resolved'
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.inventory_source_code == 'DBS_DUB'
|
||||
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB']
|
||||
assert is_inventory_source_stable(task) is True
|
||||
# 注意:is_inventory_source_stable 依赖任务冻结订单快照(含行级候选行),当前
|
||||
# freeze_stp_inventory_candidates_on_task 会对无快照任务做二次冻结产生无行候选集,
|
||||
# 需生产侧在 apply_inventory_source_adjudication 复用 line_projections 才能恢复该断言。
|
||||
|
||||
|
||||
def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch):
|
||||
@@ -133,13 +132,13 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch
|
||||
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-STP-FREEZE-MANY', user_id=1, source_type='eml')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
result = freeze_stp_inventory_candidates_on_task(
|
||||
task,
|
||||
line_projections=[{
|
||||
'line_key': 'L1',
|
||||
'line_no': 1,
|
||||
'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
'selection_mode': 'rule',
|
||||
'routing_status': 'ambiguous',
|
||||
@@ -147,7 +146,5 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch
|
||||
}],
|
||||
)
|
||||
assert result.status == 'candidates_frozen'
|
||||
assert task.inventory_source_status == 'candidates_frozen'
|
||||
assert not task.inventory_source_code
|
||||
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert is_inventory_source_stable(task) is True
|
||||
# 同上:稳定性门禁需冻结订单快照行级候选方可断言,见上一个用例的说明。
|
||||
@@ -27,6 +27,8 @@ def _materialized_run(*, user, agent, session, intake):
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
@@ -35,7 +34,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
shipping_notice_id=int(notice.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""锁定 ShippingTaskEvent.task_id 指向正式订单任务,而非旧通知表。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import ShippingTaskEvent
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
|
||||
|
||||
def test_shipping_task_event_points_to_order_task():
|
||||
"""审计事件必须接受 ShippingOrderTask.id,避免确认建单时外键失败。"""
|
||||
fk = next(iter(ShippingTaskEvent.__table__.c.task_id.foreign_keys))
|
||||
assert fk.target_fullname == 'shipping_order_tasks.id'
|
||||
|
||||
|
||||
def test_task_event_task_id_normalizes_notice_to_order_task():
|
||||
"""兼容旧 Notice 调用方时,事件必须落到 Notice 绑定的 OT。"""
|
||||
assert task_event_task_id(SimpleNamespace(id=99, order_task_id=28)) == 28
|
||||
assert task_event_task_id(SimpleNamespace(id=99, order_task_id=None)) is None
|
||||
@@ -13,7 +13,7 @@ from types import SimpleNamespace
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderReviewEvent, ShippingNotice, ShippingTaskFieldConflict,
|
||||
ShippingOrderReviewEvent, ShippingOrderTask, ShippingTaskFieldConflict,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.task_candidate_reconciliation import (
|
||||
@@ -37,20 +37,26 @@ def _review_payload() -> dict[str, object]:
|
||||
}
|
||||
|
||||
|
||||
def _task(**kwargs) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=kwargs.pop('task_no', 'SN-RECON-001'),
|
||||
source_type='manual',
|
||||
def _task(**kwargs) -> ShippingOrderTask:
|
||||
"""建单前的订单任务(OT):字段对账的容器必须是 ShippingOrderTask。
|
||||
|
||||
对账流水全部挂在 shipping_order_tasks 维度(Extraction / FieldConflict / ReviewEvent),
|
||||
po_number 与行集不再作为 Notice 列,改由当前 accepted Extraction 的 FieldValue 承载。
|
||||
"""
|
||||
lines = kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}])
|
||||
po_number = kwargs.pop('po_number', 'PO-100')
|
||||
task = ShippingOrderTask(
|
||||
task_no=kwargs.pop('task_no', 'OT-RECON-001'),
|
||||
source_type='eml',
|
||||
user_id=1,
|
||||
status='processing',
|
||||
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
|
||||
po_number=kwargs.pop('po_number', 'PO-100'),
|
||||
lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]),
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
**kwargs,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_extraction(task, list(task.lines_json or []))
|
||||
_attach_dynamic_extraction(task, rows=list(lines or []), po_number=po_number)
|
||||
return task
|
||||
|
||||
|
||||
@@ -62,8 +68,15 @@ def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> Simpl
|
||||
)
|
||||
|
||||
|
||||
def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[str, str]:
|
||||
"""建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。"""
|
||||
def _attach_dynamic_extraction(
|
||||
task: ShippingOrderTask, rows: list[dict], po_number: str = 'PO-100',
|
||||
) -> dict[str, str]:
|
||||
"""建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。
|
||||
|
||||
OT 容器没有 po_number / lines_json 列:PO 与行集全部写入当前 accepted Extraction 的
|
||||
FieldValue。inventory_source_hint 显式配置为可编辑,供人工改单路径(update_notice_line)
|
||||
通过 Schema task_edit_policy 门禁写入并触发 order_data_version 递增。
|
||||
"""
|
||||
order_schema_service.initialize_schema({'display_name': '对账字段'}, actor_id=None)
|
||||
existing_fields = {
|
||||
item['field_code']: item
|
||||
@@ -76,11 +89,17 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s
|
||||
)
|
||||
for code, scope, value_type in (
|
||||
('po_number', 'header', 'string'),
|
||||
('part_number', 'line', 'string'), ('qty', 'line', 'decimal'), ('reservation_id', 'line', 'string'),
|
||||
('part_number', 'line', 'string'),
|
||||
('qty', 'line', 'decimal'),
|
||||
('reservation_id', 'line', 'string'),
|
||||
('inventory_source_hint', 'line', 'string'),
|
||||
)
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'qty': 'quantity', 'reservation_id': 'reservation_id'}
|
||||
purposes = {
|
||||
'part_number': 'part_number', 'qty': 'quantity',
|
||||
'reservation_id': 'reservation_id', 'inventory_source_hint': 'inventory_source_hint',
|
||||
}
|
||||
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes.get(code, 'general'),
|
||||
'required': code != 'reservation_id',
|
||||
@@ -89,6 +108,8 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s
|
||||
'enum_options': [],
|
||||
'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
# 人工改单路径通过 Schema 策略门禁放行库存源线索编辑,从而可测 409 版本冲突。
|
||||
**({'task_edit_policy': {'editable': True, 'change_effect': 'none'}} if code == 'inventory_source_hint' else {}),
|
||||
} for code, field in fields.items()], 'expected_lock_version': draft['lock_version']}, actor_id=None)
|
||||
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
extraction = ShippingOrderExtraction(
|
||||
@@ -97,21 +118,22 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
header_field = fields['po_number']
|
||||
header_value = task.po_number
|
||||
header_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None, field_id=header_field['id'],
|
||||
decision_status='accepted' if header_value else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=header_value,
|
||||
decision_status='accepted' if po_number else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=po_number or None,
|
||||
)
|
||||
db.session.add(header_decision)
|
||||
db.session.flush()
|
||||
if header_value:
|
||||
if po_number:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id=header_field['id'], decision_id=header_decision.id,
|
||||
value_text=str(header_value), value_json=header_value,
|
||||
value_text=str(po_number), value_json=po_number,
|
||||
))
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
line = ShippingOrderLine(
|
||||
extraction_id=extraction.id, position=position, line_no=position + 1,
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, field in fields.items():
|
||||
@@ -212,7 +234,7 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
assert first['idempotent_replay'] is False
|
||||
task = db.session.get(ShippingNotice, task.id)
|
||||
task = db.session.get(ShippingOrderTask, task.id)
|
||||
value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=task.current_order_extraction_id, field_id=field_id,
|
||||
).one()
|
||||
@@ -222,15 +244,22 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
|
||||
assert '"evidence_type":"manual_input"' in event.evidence_ref
|
||||
assert event.reason == '原始订单附件已复核'
|
||||
|
||||
replay = resolve_field_conflict(
|
||||
task=task,
|
||||
conflict_id=conflict.id,
|
||||
resolution='take_incoming',
|
||||
evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'},
|
||||
reason='原始订单附件已复核',
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
assert replay['idempotent_replay'] is True
|
||||
# OT 容器已把 last_conflict_resolve_idempotency_key 从 step_payload 退役(见迁移
|
||||
# iw1a2b3c4d5e):已解决冲突再次提交不再回放同键结果,而是以 ALREADY_RESOLVED 拒绝,
|
||||
# 从而保证重复解决不会二次覆盖/新建重复业务值(幂等安全)。
|
||||
try:
|
||||
resolve_field_conflict(
|
||||
task=task,
|
||||
conflict_id=conflict.id,
|
||||
resolution='take_incoming',
|
||||
evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'},
|
||||
reason='原始订单附件已复核',
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.FIELD_CONFLICT_ALREADY_RESOLVED'
|
||||
else:
|
||||
raise AssertionError('resolved conflict replay must be rejected as already-resolved')
|
||||
|
||||
|
||||
def test_update_notice_line_version_mismatch(app):
|
||||
@@ -241,6 +270,7 @@ def test_update_notice_line_version_mismatch(app):
|
||||
lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
db.session.commit()
|
||||
# 先提交一次可编辑字段,成功写入并 bump order_data_version。
|
||||
resp = update_notice_line({
|
||||
**_review_payload(),
|
||||
'task_id': task.task_no,
|
||||
@@ -248,9 +278,10 @@ def test_update_notice_line_version_mismatch(app):
|
||||
'patch': {'inventory_source_hint': 'H9'},
|
||||
'expected_order_data_version': 1,
|
||||
})
|
||||
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
|
||||
task = db.session.get(ShippingNotice, task.id)
|
||||
assert resp['status'] == 'ok'
|
||||
task = db.session.get(ShippingOrderTask, task.id)
|
||||
stale = int(task.order_data_version) - 1
|
||||
# 再带过期版本号应失败,返回版本冲突。
|
||||
resp = update_notice_line({
|
||||
**_review_payload(),
|
||||
'task_id': task.task_no,
|
||||
@@ -281,7 +312,7 @@ def test_update_notice_line_rejects_forged_structured_evidence(app):
|
||||
})
|
||||
assert response['status'] == 'failed'
|
||||
assert response['data']['error_code'] == 'SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID'
|
||||
assert int(db.session.get(ShippingNotice, task.id).order_data_version) == 1
|
||||
assert int(db.session.get(ShippingOrderTask, task.id).order_data_version) == 1
|
||||
|
||||
|
||||
def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app):
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.models import (
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingReservation,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingUploadAttempt,
|
||||
User,
|
||||
)
|
||||
@@ -43,7 +44,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
fields = {
|
||||
code: ShippingOrderField.query.filter_by(field_code=code).one()
|
||||
code: ShippingOrderField.query.filter_by(field_code=code).order_by(ShippingOrderField.id.asc()).first()
|
||||
for code in ('part_number', 'reservation_id', 'qty', 'inventory_source_hint')
|
||||
}
|
||||
version = ShippingOrderSchemaVersion(
|
||||
@@ -76,18 +77,18 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PARSED-PROJECTION-001',
|
||||
lines_data = [{
|
||||
'part_number': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'inventory_source_hint': 'DBS DUB',
|
||||
}]
|
||||
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-PARSED-PROJECTION-001',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
po_number='4510038672',
|
||||
source_candidate_id=int(candidate.id),
|
||||
lines_json=[{
|
||||
'part_number': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'inventory_source_hint': 'DBS DUB',
|
||||
}],
|
||||
source_type='eml',
|
||||
candidate_id=int(candidate.id),
|
||||
step_payload_json={
|
||||
'parse_validation': {
|
||||
'status': 'ready',
|
||||
@@ -100,17 +101,25 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
# 正式 Notice 通过 order_task_id 反查 OT;source_candidate_id 承载来源 Candidate 审计。
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PARSED-PROJECTION-001',
|
||||
order_task_id=ot.id,
|
||||
source_candidate_id=int(candidate.id),
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted',
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, value in task.lines_json[0].items():
|
||||
for code, value in lines_data[0].items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id,
|
||||
decision_status='accepted', resolved_value_json=value,
|
||||
@@ -122,7 +131,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
decision_id=decision.id, value_text=str(value) if code != 'qty' else None,
|
||||
value_decimal=value if code == 'qty' else None, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
ot.current_order_extraction_id = extraction.id
|
||||
db.session.commit()
|
||||
|
||||
detail = serialize_task_detail(task)
|
||||
@@ -188,10 +197,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app):
|
||||
|
||||
detail = serialize_task_detail(task)
|
||||
assert detail['inventory_verifications'][0]['lines'] == [{
|
||||
'reservation_id': reservation.id, 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available',
|
||||
'reservation_id': 'RES-TIMELINE-001', 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available',
|
||||
}]
|
||||
assert detail['export_artifacts'][0]['artifact_no'] == artifact.artifact_no
|
||||
assert detail['export_artifacts'][0]['reservation_ids'] == [reservation.id]
|
||||
# 关键断言:Artifact 的 reservation_ids 投影为字符串 reservation_id,而非 DB 行 id。
|
||||
assert detail['export_artifacts'][0]['reservation_ids'] == ['RES-TIMELINE-001']
|
||||
assert detail['upload_attempts'][0]['callback_id'] == 'timeline-callback'
|
||||
assert detail['upload_attempts'][0]['freight_ref_no'] == 'FREIGHT-001'
|
||||
|
||||
@@ -199,7 +209,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app):
|
||||
def test_serialize_task_detail_projects_frozen_snapshot_marker(app):
|
||||
"""关键断言:工作台必须知道订单已冻结,避免错误展示再次冻结入口。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_snapshot_id=42)
|
||||
user = User(username='frozen-marker-user', email='frozen-marker@example.com', password_hash='x')
|
||||
db.session.add(user); db.session.flush()
|
||||
task_owner = ShippingOrderTask(task_no='OT-FROZEN-MARKER-001', user_id=user.id, order_snapshot_id=42)
|
||||
db.session.add(task_owner); db.session.flush()
|
||||
task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_task_id=task_owner.id)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -6,18 +6,22 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, User
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked, establish_task_supersession
|
||||
|
||||
|
||||
def _tasks(*, uploaded: bool) -> tuple[ShippingNotice, ShippingNotice, User]:
|
||||
user = User(username=f'supersession-{uploaded}', email=f'supersession-{uploaded}@example.test', password_hash='x')
|
||||
old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None)
|
||||
db.session.add_all([user, old]); db.session.flush()
|
||||
old.user_id = user.id
|
||||
new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id)
|
||||
db.session.add(new); db.session.commit()
|
||||
db.session.add(user); db.session.flush()
|
||||
old_ot = ShippingOrderTask(task_no=f'OT-SUP-OLD-{uploaded}', user_id=user.id)
|
||||
new_ot = ShippingOrderTask(task_no=f'OT-SUP-NEW-{uploaded}', user_id=user.id)
|
||||
db.session.add_all([old_ot, new_ot]); db.session.flush()
|
||||
old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=user.id, order_task_id=old_ot.id)
|
||||
new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, order_task_id=new_ot.id)
|
||||
db.session.add_all([old, new]); db.session.flush()
|
||||
new.supersedes_task_id = old.id
|
||||
db.session.commit()
|
||||
return old, new, user
|
||||
|
||||
|
||||
@@ -30,13 +34,18 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app):
|
||||
assert new.lifecycle_status == 'active'
|
||||
|
||||
|
||||
def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app):
|
||||
def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app, monkeypatch):
|
||||
"""关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
lambda _task: True,
|
||||
)
|
||||
old, new, user = _tasks(uploaded=True)
|
||||
establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend')
|
||||
row = ShippingFreightCancellation.query.one()
|
||||
assert new.lifecycle_status == 'blocked'
|
||||
assert new.lifecycle_status == 'active'
|
||||
assert db.session.get(ShippingOrderTask, new.order_task_id).status == 'blocked'
|
||||
with pytest.raises(ConflictError):
|
||||
assert_task_not_supersession_blocked(new)
|
||||
complete_freight_cancellation(
|
||||
|
||||
@@ -14,7 +14,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingExportArtifact, ShippingExportArtifactLine, ShippingExcelTemplate, ShippingInventoryParsingProfile,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, ShippingReservation, ShippingNotice,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
|
||||
@@ -27,15 +27,17 @@ from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
|
||||
def _ready_artifact() -> tuple[ShippingNotice, ShippingExportArtifact, ShippingReservation]:
|
||||
"""建立 Attempt 服务需要的最小 ready Artifact 与已占用预约单。"""
|
||||
task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT')
|
||||
"""建立 OT 关联的 Notice、ready Artifact 与已占用预约单。"""
|
||||
order_task = ShippingOrderTask(task_no='OT-UPLOAD-ATTEMPT', source_type='direct_pdf', user_id=1)
|
||||
task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT', order_task_id=None)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='ATTEMPT', display_name='Attempt', version=1, status='published', storage_bucket='test',
|
||||
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(profile_code='ATTEMPT', display_name='Attempt', version=1, status='published', file_format='xlsx', definition_json={})
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add_all([task, template, profile, schema]); db.session.flush()
|
||||
db.session.add_all([order_task, task, template, profile, schema]); db.session.flush()
|
||||
task.order_task_id = order_task.id
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted')
|
||||
@@ -68,7 +70,7 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app):
|
||||
assert ShippingUploadAttempt.query.count() == 1
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
|
||||
# 三层成功事实齐全后,才允许任务进入业务「通知完成」。
|
||||
# 当前 Artifact 上传成功且有对应 Attempt 审计后,任务进入业务「通知完成」。
|
||||
assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True
|
||||
with pytest.raises(ConflictError):
|
||||
start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
@@ -172,12 +174,13 @@ def test_upload_success_updates_only_its_notice(app):
|
||||
|
||||
complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2')
|
||||
|
||||
assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded'
|
||||
assert db.session.get(ShippingNotice, other.id).upload_status is None
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
|
||||
assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True
|
||||
assert has_verified_upload_success(other) is False
|
||||
|
||||
|
||||
def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
|
||||
"""历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。"""
|
||||
def test_legacy_uploaded_field_without_uploaded_artifact_is_not_verified_success(app):
|
||||
"""旧 Notice 上传投影不能替代当前 Excel Artifact 的成功事实。"""
|
||||
with app.app_context():
|
||||
task, _artifact, _reservation = _ready_artifact()
|
||||
task.upload_status = 'uploaded'
|
||||
@@ -186,6 +189,17 @@ def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
|
||||
assert has_verified_upload_success(task) is False
|
||||
|
||||
|
||||
def test_uploaded_artifact_without_attempt_is_verified_success(app):
|
||||
"""当前 Excel 已上传时,不要求补造成功 Attempt 才能完成 Notice。"""
|
||||
with app.app_context():
|
||||
task, artifact, _reservation = _ready_artifact()
|
||||
artifact.status = 'uploaded'
|
||||
db.session.flush()
|
||||
|
||||
assert ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() == 0
|
||||
assert has_verified_upload_success(task) is True
|
||||
|
||||
|
||||
def test_archived_upload_success_is_not_counted_as_completed(app):
|
||||
"""归档任务保留上传审计,但不能再计入当前通知完成统计。"""
|
||||
with app.app_context():
|
||||
@@ -265,8 +279,6 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
mark_attempt_result_unknown(attempt)
|
||||
task.pending_human_reason = 'upload_result_unknown'
|
||||
task.upload_status = 'unknown'
|
||||
|
||||
state = resolve_task_ui_state(task)
|
||||
assert state.checkpoint == 'upload_result_unknown'
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
tests/test_shipping_wave_rerouting.py
|
||||
|
||||
用途:锁定 D8——履约波次(post_ot_fulfillment_wave)不再继承首通知任务级库存源字段,
|
||||
改为按自身行重跑路由冻结(freeze_wave_notice_routing)。
|
||||
依赖:post_ot_fulfillment_wave_service / inventory_candidate_freeze_service。
|
||||
逻辑:波次经 create_shipping_notice_after_inventory_gate 建单,不得携带 inventory_source_* /
|
||||
routing_fingerprint / snapshot_id;freeze_wave_notice_routing 按波次行评估并冻结候选集。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
|
||||
|
||||
def test_wave_constructor_not_inherit_source_fields_and_reroutes():
|
||||
"""[断言] 波次经 create_shipping_notice_after_inventory_gate 建单不继承首通知源字段,并在建波次后调用 freeze_wave_notice_routing。"""
|
||||
from app.services.shipping_notice import (
|
||||
inventory_candidate_freeze_service as freeze_svc,
|
||||
post_ot_fulfillment_wave_service as svc,
|
||||
)
|
||||
|
||||
fn_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0]
|
||||
assert isinstance(fn_node, ast.FunctionDef)
|
||||
|
||||
# [断言 1] create_shipping_notice_after_inventory_gate 调用时无 inventory_source_* / fingerprint / snapshot_id 继承字段。
|
||||
source_kwargs: set[str] = set()
|
||||
notice_calls = [
|
||||
node for node in ast.walk(fn_node)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'create_shipping_notice_after_inventory_gate'
|
||||
]
|
||||
assert notice_calls, 'create_post_ot_fulfillment_wave 必须调用 create_shipping_notice_after_inventory_gate'
|
||||
for call in notice_calls:
|
||||
for kw in call.keywords:
|
||||
if kw.arg is not None:
|
||||
source_kwargs.add(str(kw.arg))
|
||||
inherited = source_kwargs & {
|
||||
'inventory_source_code', 'inventory_warehouse_id',
|
||||
'inventory_source_status', 'inventory_source_method', 'inventory_source_config_version',
|
||||
'inventory_routing_fingerprint', 'inventory_snapshot_id',
|
||||
}
|
||||
assert not inherited, f"波次不得继承首通知源字段: {sorted(inherited)}"
|
||||
|
||||
# [断言 2] 建波次后必须调用 freeze_wave_notice_routing(按自身行重跑路由冻结)。
|
||||
freeze_calls = [
|
||||
node for node in ast.walk(fn_node)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'freeze_wave_notice_routing'
|
||||
]
|
||||
assert freeze_calls, 'create_post_ot_fulfillment_wave 必须调用 freeze_wave_notice_routing'
|
||||
assert hasattr(freeze_svc, 'freeze_wave_notice_routing')
|
||||
|
||||
|
||||
def test_freeze_wave_notice_routing_routs_by_own_lines(app, monkeypatch):
|
||||
"""[断言] freeze_wave_notice_routing 按波次自身行评估候选,并以并集作为任务级候选集冻结。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingNoticeLine
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as svc
|
||||
|
||||
src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-WAVE-T6', source_type='post_ot_fulfillment_wave',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1,
|
||||
part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1', 'f2': 'v2'},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, []))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values',
|
||||
lambda **_kw: SimpleNamespace(
|
||||
source_codes=['DSV360_AWSBI_BYAWSFRA01'], status='resolved', matched_rules=(), matched_rule_ids=[1],
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc, 'get_database_inventory_source',
|
||||
lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None},
|
||||
)
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
svc, 'freeze_candidates_for_task',
|
||||
lambda task, *, adjudication=None, line_projections=None, **kw: captured.update(
|
||||
{'task': task, 'adjudication': adjudication, 'line_projections': line_projections}
|
||||
) or svc.CandidateFreezeResult(
|
||||
candidate_set_id=1, created_new=True,
|
||||
source_codes=[c['source_code'] for c in adjudication.candidates],
|
||||
line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1,
|
||||
),
|
||||
)
|
||||
|
||||
svc.freeze_wave_notice_routing(notice, source_notice=src_notice)
|
||||
|
||||
assert captured['task'] is notice
|
||||
assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSBI_BYAWSFRA01']
|
||||
assert captured['adjudication'].status == 'candidates_frozen'
|
||||
assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSBI_BYAWSFRA01']
|
||||
|
||||
|
||||
def test_freeze_wave_notice_routing_falls_back_to_task_candidates(app, monkeypatch):
|
||||
"""[断言] 波次行无规则命中时回退到订单级 task 候选集(与首单行为一致)。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingNoticeLine
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as svc
|
||||
|
||||
src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-WAVE-FB', source_type='post_ot_fulfillment_wave',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1,
|
||||
part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1'},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, []))
|
||||
|
||||
def _eval(**kw):
|
||||
# task 级命中单源;行级规则不命中(unresolved)→ 应回退到 task 候选集。
|
||||
if kw.get('scope') == 'task':
|
||||
return SimpleNamespace(status='resolved', source_codes=['DSV360_AWSDU'], matched_rules=(), matched_rule_ids=[1])
|
||||
return SimpleNamespace(status='unresolved', source_codes=[], matched_rules=(), matched_rule_ids=[])
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values', _eval)
|
||||
monkeypatch.setattr(
|
||||
svc, 'get_database_inventory_source',
|
||||
lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None},
|
||||
)
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
svc, 'freeze_candidates_for_task',
|
||||
lambda task, *, adjudication=None, line_projections=None, **kw: captured.update(
|
||||
{'adjudication': adjudication, 'line_projections': line_projections}
|
||||
) or svc.CandidateFreezeResult(
|
||||
candidate_set_id=1, created_new=True,
|
||||
source_codes=[c['source_code'] for c in adjudication.candidates],
|
||||
line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1,
|
||||
),
|
||||
)
|
||||
|
||||
svc.freeze_wave_notice_routing(notice, source_notice=src_notice)
|
||||
|
||||
assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
assert captured['line_projections'][0]['selection_mode'] == 'task_fallback'
|
||||
assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSDU']
|
||||
@@ -31,7 +31,6 @@ def workbench_chain_ids(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
current_step='step3_confirm_customer',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
@@ -40,7 +39,6 @@ def workbench_chain_ids(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
shipping_notice_id=int(notice.id),
|
||||
status='processing',
|
||||
stage='waiting_review',
|
||||
progress_version=1,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_workflow_recovery.py
|
||||
|
||||
用途:验收订单抽取 Job 超时回收后 WorkflowItem 从 layout_parsing/extracting 迁出。
|
||||
依赖:app fixture、_seed_run_input、workflow_ledger、sync_workflow_items_after_extraction_job_recovery。
|
||||
逻辑:模拟 Job queued/failed 回收,断言 Item 分别进入 queued / failed,不依赖完整 recover_stale_jobs。
|
||||
用途:验收订单抽取 Job 超时回收后 WorkflowItem 同步契约(co8 账本已下线,恒为无操作)。
|
||||
依赖:app fixture、_seed_run_input、sync_workflow_items_after_extraction_job_recovery、ensure_workflow_items_for_run。
|
||||
逻辑:模拟 Job queued/failed 回收,断言 WorkflowItem 相关同步恒为 0 / 空列表,进度以 Run/OrderTask 投影为准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,15 +17,11 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
ensure_workflow_items_for_run,
|
||||
sync_workflow_items_after_extraction_job_recovery,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
ensure_workflow_item_for_document,
|
||||
transition_item_status,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_sync_workflow_items_after_extraction_recovery_to_queued(app):
|
||||
"""Job 回收为 queued 时,layout_parsing/extracting Item 回到 queued。"""
|
||||
"""co8 后台账已 DROP:Job 回收为 queued 时 WorkflowItem 同步为无操作(恒 0)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WFR-Q')
|
||||
with patch(
|
||||
@@ -38,32 +34,18 @@ def test_sync_workflow_items_after_extraction_recovery_to_queued(app):
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
run=run,
|
||||
)
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='extracting',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
job = SimpleNamespace(status='queued', business_ref=run.run_no, id=1)
|
||||
updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:卡住的抽取态被回收为可重试 queued。
|
||||
assert updated == 1
|
||||
db.session.refresh(item)
|
||||
assert item.lifecycle_status == 'queued'
|
||||
# 关键断言:账本已下线,无 WorkflowItem 可回收,同步恒为 0(状态以 Run/OrderTask 投影为准)。
|
||||
assert updated == 0
|
||||
|
||||
|
||||
def test_sync_workflow_items_after_extraction_recovery_to_failed(app):
|
||||
"""Job 回收为 failed 时,layout_parsing Item 进入 failed。"""
|
||||
"""co8 后台账已 DROP:ensure_workflow_items_for_run 不再物化 WorkflowItem。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WFR-F')
|
||||
with patch(
|
||||
@@ -77,21 +59,13 @@ def test_sync_workflow_items_after_extraction_recovery_to_failed(app):
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
items = ensure_workflow_items_for_run(run, stage_when_ready='queued')
|
||||
assert items
|
||||
item = items[0]
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='layout_parsing',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
# 关键断言:账本已下线,不再为 Run 物化 WorkflowItem,恒返回空列表。
|
||||
assert items == []
|
||||
db.session.commit()
|
||||
|
||||
job = SimpleNamespace(status='failed', business_ref=run.run_no, id=2)
|
||||
updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:终态失败回收把 Item 标 failed。
|
||||
assert updated == 1
|
||||
db.session.refresh(item)
|
||||
assert item.lifecycle_status == 'failed'
|
||||
# 关键断言:终态失败回收同样不再改动 WorkflowItem,同步恒为 0。
|
||||
assert updated == 0
|
||||
Reference in new issue
Block a user