test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user