把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
238 lines
10 KiB
Python
238 lines
10 KiB
Python
"""
|
||
backend/tests/test_shipping_customer_identity_gate.py
|
||
|
||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。
|
||
依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。
|
||
逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断;
|
||
确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
|
||
from app import db
|
||
from app.core.errors import AppError
|
||
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,
|
||
)
|
||
|
||
|
||
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()
|
||
|
||
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, notice, customer, user
|
||
|
||
|
||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||
"""未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。"""
|
||
with app.app_context():
|
||
task, _notice, _customer, _user = _seed_task()
|
||
operations = [
|
||
'auto_progress',
|
||
'ensure_onhand',
|
||
'upload_onhand_file',
|
||
'ensure_inventory_via_rpa',
|
||
'match_inventory',
|
||
'generate_excel',
|
||
'upload_to_freight',
|
||
]
|
||
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 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, _notice, _customer, _user = _seed_task()
|
||
task.pending_human_reason = 'customer_unconfirmed'
|
||
task.error_message = '标准客户尚未确认'
|
||
db.session.commit()
|
||
|
||
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 生成时分配。"""
|
||
with app.app_context():
|
||
task, _notice, customer, user = _seed_task()
|
||
|
||
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||
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
|
||
# OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。
|
||
assert getattr(updated, 'business_no', None) is None
|
||
|
||
|
||
def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch):
|
||
"""PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。"""
|
||
with app.app_context():
|
||
task, _notice, customer, user = _seed_task()
|
||
original_query = db.session.query
|
||
lock_arguments: list[dict] = []
|
||
|
||
class OrderTaskQuerySpy:
|
||
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
|
||
|
||
def __init__(self, query):
|
||
self._query = query
|
||
|
||
def filter(self, *criteria):
|
||
self._query = self._query.filter(*criteria)
|
||
return self
|
||
|
||
def with_for_update(self, **kwargs):
|
||
lock_arguments.append(kwargs)
|
||
self._query = self._query.with_for_update(**kwargs)
|
||
return self
|
||
|
||
def one(self):
|
||
return self._query.one()
|
||
|
||
def traced_query(*entities, **kwargs):
|
||
query = original_query(*entities, **kwargs)
|
||
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': ShippingOrderTask}]
|
||
|
||
|
||
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
|
||
with app.app_context():
|
||
task, _notice, customer, user = _seed_task()
|
||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||
customer.status = 'inactive'
|
||
db.session.commit()
|
||
with pytest.raises(AppError) as exc_info:
|
||
assert_customer_identity_gate(task, operation='match_inventory')
|
||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||
|
||
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'
|
||
assert customer_identity_is_confirmed(unconfirmed) is False
|
||
|
||
|
||
def test_workspace_customer_search_and_confirmation_api(app, client):
|
||
"""业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。"""
|
||
app.config['AUTH_JWT_REQUIRED'] = False
|
||
with app.app_context():
|
||
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()
|
||
task_no = task.task_no
|
||
customer_id = customer.id
|
||
short_code = customer.short_code
|
||
username = user.username
|
||
|
||
headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'}
|
||
options_response = client.get(f'/api/workspace/shipping-customers?q={short_code}', headers=headers)
|
||
assert options_response.status_code == 200
|
||
options_payload = options_response.get_json()
|
||
assert options_payload['success'] is True
|
||
assert options_payload['data'][0]['short_code'] == short_code
|
||
|
||
confirm_response = client.post(
|
||
f'/api/workspace/shipping-tasks/{task_no}/confirm-customer',
|
||
json={'customer_id': customer_id},
|
||
headers=headers,
|
||
)
|
||
assert confirm_response.status_code == 200
|
||
envelope = confirm_response.get_json()
|
||
assert envelope['success'] is True
|
||
payload = envelope['data']
|
||
assert payload['customer_id'] == customer_id
|
||
# 新契约:确认只固化客户事实,业务编号仍由 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(
|
||
f'/api/workspace/shipping-tasks/{task_no}/confirm-customer',
|
||
json={'customer_id': customer_id},
|
||
headers=other_headers,
|
||
)
|
||
assert forbidden_response.status_code == 404
|