feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认
This commit is contained in:
1 parent
b595e157e9
commit
4fbaed2b4c
176 files changed
+14011
-994
No files matched your search
@@ -150,7 +150,7 @@ def seed_task_inventory_source(
|
||||
)
|
||||
identity = resolution.identity
|
||||
task.inventory_source_code = identity.source_code
|
||||
task.inventory_source_type = identity.source_type
|
||||
task.inventory_connector_type = identity.connector_type
|
||||
task.inventory_site_id = identity.site_id
|
||||
task.inventory_warehouse_id = identity.warehouse_id
|
||||
task.inventory_source_status = "resolved"
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""
|
||||
backend/tests/services/admin/test_shipping_customer_import_service.py
|
||||
|
||||
用途:验证货代期初客户 Excel 的预检、决策、发布、幂等和事务回滚。
|
||||
依赖:openpyxl、FileStorage、内存数据库、shipping_customer_import_service。
|
||||
逻辑:在内存中构造标准工作簿,经真实服务链路验证暂存数据与正式客户主数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerImportBatch,
|
||||
)
|
||||
from app.services.admin.shipping_customer_import_service import (
|
||||
CUSTOMER_HEADERS,
|
||||
IDENTIFIER_HEADERS,
|
||||
build_reconciliation_csv,
|
||||
create_import_batch,
|
||||
decide_import_row,
|
||||
publish_import_batch,
|
||||
)
|
||||
|
||||
|
||||
def _make_upload(
|
||||
customer_rows: list[tuple],
|
||||
identifier_rows: list[tuple] | None = None,
|
||||
*,
|
||||
filename: str = 'customers.xlsx',
|
||||
) -> FileStorage:
|
||||
"""按正式模板在内存中构造上传文件。"""
|
||||
workbook = Workbook()
|
||||
customers = workbook.active
|
||||
customers.title = 'customers'
|
||||
customers.append(CUSTOMER_HEADERS)
|
||||
for row in customer_rows:
|
||||
customers.append(row)
|
||||
identifiers = workbook.create_sheet('identifiers')
|
||||
identifiers.append(IDENTIFIER_HEADERS)
|
||||
for row in identifier_rows or []:
|
||||
identifiers.append(row)
|
||||
content = BytesIO()
|
||||
workbook.save(content)
|
||||
content.seek(0)
|
||||
return FileStorage(stream=content, filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
|
||||
|
||||
def test_import_upload_is_hash_idempotent_and_json_safe(app):
|
||||
"""相同文件重复上传返回原批次,日期单元格可安全写入 JSON 暂存。"""
|
||||
with app.app_context():
|
||||
rows = [('INIT-1', '无锡宇辰', 'WYC', 'active', 'ERP', datetime(2026, 7, 15, 9, 30))]
|
||||
original_upload = _make_upload(rows)
|
||||
content = original_upload.read()
|
||||
first = create_import_batch(
|
||||
FileStorage(stream=BytesIO(content), filename='customers.xlsx'),
|
||||
source_system='INITIAL_EXCEL',
|
||||
actor_id=None,
|
||||
)
|
||||
replay = create_import_batch(
|
||||
FileStorage(stream=BytesIO(content), filename='customers.xlsx'),
|
||||
source_system='INITIAL_EXCEL',
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
assert replay['id'] == first['id']
|
||||
assert replay['idempotent_replay'] is True
|
||||
assert first['rows'][0]['raw']['remark'] == '2026-07-15T09:30:00'
|
||||
assert db.session.query(ShippingCustomerImportBatch).count() == 1
|
||||
|
||||
different_source = create_import_batch(
|
||||
FileStorage(stream=BytesIO(content), filename='customers.xlsx'),
|
||||
source_system='ANOTHER_ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
assert different_source['id'] != first['id']
|
||||
|
||||
|
||||
def test_import_rejects_oversized_source_without_staging_batch(app):
|
||||
"""来源系统超出数据库长度时在暂存前拒绝,避免产生半成品批次。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_import_batch(
|
||||
_make_upload([('INIT-1', '无锡宇辰', 'WYC', 'active', '', '')]),
|
||||
source_system='X' * 65,
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID'
|
||||
assert db.session.query(ShippingCustomerImportBatch).count() == 0
|
||||
|
||||
|
||||
def test_import_marks_oversized_row_fields_as_blocking_errors(app):
|
||||
"""行内稳定键和客户名称超长时进入错误行,发布必须被阻断。"""
|
||||
with app.app_context():
|
||||
batch = create_import_batch(
|
||||
_make_upload([('K' * 129, '客' * 201, 'WYC', 'active', 'ERP', '')]),
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
codes = {item['code'] for item in batch['rows'][0]['errors']}
|
||||
assert 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID' in codes
|
||||
assert 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG' in codes
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
publish_import_batch(batch['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS'
|
||||
|
||||
|
||||
def test_import_errors_and_unresolved_warnings_block_publish(app):
|
||||
"""错误行直接阻断发布,公共邮箱警告行必须先明确 create 或 skip。"""
|
||||
with app.app_context():
|
||||
invalid = create_import_batch(
|
||||
_make_upload([('INIT-ERR', '错误客户', 'A1', 'active', 'ERP', '')]),
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
publish_import_batch(invalid['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS'
|
||||
|
||||
warning = create_import_batch(
|
||||
_make_upload(
|
||||
[('INIT-WARN', '公共邮箱客户', 'GGC', 'active', 'ERP', '')],
|
||||
[('INIT-WARN', 'ERP', 'email', 'buyer@gmail.com', True, '')],
|
||||
filename='warning.xlsx',
|
||||
),
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
warning_row = next(row for row in warning['rows'] if row['row_type'] == 'identifier')
|
||||
assert warning_row['normalized']['auto_match_allowed'] is False
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
publish_import_batch(warning['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED'
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
decide_import_row(warning_row['id'], {'action': 'merge', 'target_customer_id': 1})
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID'
|
||||
|
||||
|
||||
def test_publish_uses_row_source_system_for_customer_and_identifier(app):
|
||||
"""客户与标识按行级来源系统稳定关联,并创建 approved 识别证据和来源映射。"""
|
||||
with app.app_context():
|
||||
batch = create_import_batch(
|
||||
_make_upload(
|
||||
[('ERP-001', '无锡宇辰有限公司', 'WYC', 'active', 'LEGACY_ERP', '期初客户')],
|
||||
[('ERP-001', '', 'name_alias', 'WUXI YUCHEN', False, '英文名')],
|
||||
),
|
||||
source_system='INITIAL_EXCEL',
|
||||
actor_id=None,
|
||||
)
|
||||
published = publish_import_batch(batch['id'], actor_id=None)
|
||||
|
||||
customer = db.session.query(ShippingCustomer).one()
|
||||
external_ref = db.session.query(ShippingCustomerExternalRef).one()
|
||||
identifier = db.session.query(ShippingCustomerIdentifier).one()
|
||||
assert published['status'] == 'published'
|
||||
assert external_ref.customer_id == customer.id
|
||||
assert external_ref.source_system == 'LEGACY_ERP'
|
||||
assert identifier.customer_id == customer.id
|
||||
assert identifier.status == 'approved'
|
||||
assert identifier.auto_match_allowed is False
|
||||
|
||||
replay = publish_import_batch(batch['id'], actor_id=None)
|
||||
assert replay['idempotent_replay'] is True
|
||||
csv_content, filename = build_reconciliation_csv(batch['id'])
|
||||
assert filename.endswith('_reconciliation.csv')
|
||||
assert b'identifier_created' in csv_content
|
||||
|
||||
|
||||
def test_publish_conflict_rolls_back_entire_batch(app):
|
||||
"""发布中出现简码唯一冲突时,客户、来源映射和逐行结果全部回滚。"""
|
||||
with app.app_context():
|
||||
batch = create_import_batch(
|
||||
_make_upload([
|
||||
('ERP-101', '客户一', 'DUP', 'active', 'ERP', ''),
|
||||
('ERP-102', '客户二', 'DUP', 'active', 'ERP', ''),
|
||||
]),
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
publish_import_batch(batch['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT'
|
||||
assert db.session.query(ShippingCustomer).count() == 0
|
||||
assert db.session.query(ShippingCustomerExternalRef).count() == 0
|
||||
persisted = db.session.get(ShippingCustomerImportBatch, batch['id'])
|
||||
assert persisted.status == 'validated'
|
||||
assert all(row.result_status is None for row in persisted.rows)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
backend/tests/services/admin/test_shipping_customer_service.py
|
||||
|
||||
用途:验证货代客户主数据与识别证据的管理规则。
|
||||
依赖:pytest、内存数据库、shipping_customer_service。
|
||||
逻辑:直接调用服务层,覆盖简码唯一性、公共邮箱限制、审核门槛与列表统计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier
|
||||
from app.services.admin.shipping_customer_service import (
|
||||
create_customer,
|
||||
create_identifier,
|
||||
list_customers,
|
||||
update_identifier,
|
||||
)
|
||||
|
||||
|
||||
def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str = 'WYC') -> dict:
|
||||
"""创建测试客户并返回序列化结果。"""
|
||||
return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None)
|
||||
|
||||
|
||||
def test_customer_short_code_is_normalized_and_unique(app):
|
||||
"""简码统一转大写,且标准化后重复必须返回冲突。"""
|
||||
with app.app_context():
|
||||
created = _create_customer(short_code='wyc')
|
||||
assert created['short_code'] == 'WYC'
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
_create_customer(name='另一客户', short_code='WYC')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_EXISTS'
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_create_customer(name='格式错误客户', short_code='W1')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_INVALID'
|
||||
|
||||
|
||||
def test_customer_short_code_database_constraint_rejects_non_letters(app):
|
||||
"""绕过管理服务直接写库时,数据库仍须拒绝包含数字的客户简码。"""
|
||||
with app.app_context():
|
||||
db.session.add(ShippingCustomer(standard_name='异常客户', short_code='W1', status='active'))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
assert db.session.query(ShippingCustomer).count() == 0
|
||||
|
||||
|
||||
def test_identifier_auto_match_requires_approval_and_rejects_public_mail(app):
|
||||
"""自动匹配仅允许已审核证据,公共邮箱地址和域名即使已审核也禁止启用。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_identifier(
|
||||
customer['id'],
|
||||
{
|
||||
'identifier_type': 'name_alias',
|
||||
'identifier_value': 'WUXI YUCHEN',
|
||||
'status': 'pending',
|
||||
'auto_match_allowed': True,
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED'
|
||||
|
||||
for identifier_type, value in (('domain', 'qq.com'), ('email', 'buyer@qq.com')):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_identifier(
|
||||
customer['id'],
|
||||
{
|
||||
'identifier_type': identifier_type,
|
||||
'identifier_value': value,
|
||||
'status': 'approved',
|
||||
'auto_match_allowed': True,
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN'
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_identifier(
|
||||
customer['id'],
|
||||
{
|
||||
'identifier_type': 'domain',
|
||||
'identifier_value': 'wyc.example.com',
|
||||
'status': 'approved',
|
||||
'auto_match_allowed': 'false',
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc_info.value.details == {'field': 'auto_match_allowed'}
|
||||
|
||||
|
||||
def test_identifier_loses_auto_match_when_approval_is_revoked(app):
|
||||
"""已审核证据降为 pending 或 disabled 时必须同步关闭自动匹配。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
identifier = create_identifier(
|
||||
customer['id'],
|
||||
{
|
||||
'identifier_type': 'domain',
|
||||
'identifier_value': 'wyc.example.com',
|
||||
'status': 'approved',
|
||||
'auto_match_allowed': True,
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
updated = update_identifier(identifier['id'], {'status': 'pending'}, actor_id=None)
|
||||
assert updated['status'] == 'pending'
|
||||
assert updated['auto_match_allowed'] is False
|
||||
|
||||
|
||||
def test_identifier_validation_failure_does_not_leave_dirty_state(app):
|
||||
"""联合更新违反审核门槛时,ORM 记录不得残留部分修改。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
identifier = create_identifier(
|
||||
customer['id'],
|
||||
{
|
||||
'identifier_type': 'domain',
|
||||
'identifier_value': 'wyc.example.com',
|
||||
'status': 'approved',
|
||||
'auto_match_allowed': True,
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
update_identifier(
|
||||
identifier['id'],
|
||||
{'status': 'pending', 'auto_match_allowed': True},
|
||||
actor_id=None,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED'
|
||||
persisted = db.session.get(ShippingCustomerIdentifier, identifier['id'])
|
||||
assert persisted.status == 'approved'
|
||||
assert persisted.auto_match_allowed is True
|
||||
|
||||
|
||||
def test_customer_list_returns_preaggregated_reference_counts(app):
|
||||
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id']))
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer['id'],
|
||||
identifier_type='name_alias',
|
||||
raw_value='WYC LTD',
|
||||
normalized_value='WYCLTD',
|
||||
status='approved',
|
||||
source='manual',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = list_customers({'page': 1, 'page_size': 20})
|
||||
assert result['items'][0]['case_count'] == 1
|
||||
assert result['items'][0]['identifier_count'] == 1
|
||||
@@ -0,0 +1,217 @@
|
||||
"""
|
||||
backend/tests/test_admin_shipping_customers.py
|
||||
|
||||
用途:验证货代客户管理 API 的权限、成功响应与错误 envelope。
|
||||
依赖:Flask 测试客户端、User、客户管理路由。
|
||||
逻辑:创建真实 admin/user 账户,通过 legacy header 访问管理路由并断言 RBAC 与响应契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
def _create_users() -> None:
|
||||
"""创建管理 API 权限测试所需的 admin 与普通用户。"""
|
||||
db.session.add_all([
|
||||
User(username='shipping-admin', email='shipping-admin@example.com', role='admin', status='active'),
|
||||
User(username='shipping-user', email='shipping-user@example.com', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
"""构造 legacy header 认证信息。"""
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_shipping_customer_admin_crud_uses_standard_contract(app, client):
|
||||
"""管理员可创建和查询客户,校验失败返回标准错误 envelope。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
|
||||
headers = _headers('shipping-admin', 'admin')
|
||||
created_response = client.post(
|
||||
'/api/admin/shipping-customers',
|
||||
json={'standard_name': '无锡宇辰有限公司', 'short_code': 'wyc'},
|
||||
headers=headers,
|
||||
)
|
||||
assert created_response.status_code == 201
|
||||
created = parse_api_data(created_response.get_json())
|
||||
assert created['short_code'] == 'WYC'
|
||||
|
||||
list_response = client.get('/api/admin/shipping-customers', headers=headers)
|
||||
assert list_response.status_code == 200
|
||||
listed = parse_api_data(list_response.get_json())
|
||||
assert listed['total'] == 1
|
||||
|
||||
invalid_response = client.post(
|
||||
'/api/admin/shipping-customers',
|
||||
json={'standard_name': '错误客户', 'short_code': 'A1'},
|
||||
headers=headers,
|
||||
)
|
||||
assert invalid_response.status_code == 400
|
||||
assert parse_api_error(invalid_response.get_json())['code'] == 'SHIPPING.CUSTOMER_SHORT_CODE_INVALID'
|
||||
|
||||
|
||||
def test_shipping_customer_admin_routes_reject_non_admin(app, client):
|
||||
"""普通用户访问客户主数据和导入模板均返回 403。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
|
||||
headers = _headers('shipping-user', 'user')
|
||||
for path in ('/api/admin/shipping-customers', '/api/admin/shipping-customers/import-template'):
|
||||
response = client.get(path, headers=headers)
|
||||
assert response.status_code == 403
|
||||
assert parse_api_error(response.get_json())['code'] == 'AUTH.FORBIDDEN'
|
||||
|
||||
|
||||
def test_shipping_customer_historical_backfill_api_does_not_number(app, client):
|
||||
"""管理员可为历史任务回填客户,且响应与业务单均不生成历史业务号。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
customer = ShippingCustomer(standard_name='历史客户', short_code='HIS', status='active')
|
||||
task = ShippingTask(task_no='SN-20200101-HISTAPI', source_type='manual', process_status='closed')
|
||||
db.session.add_all([customer, task])
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
response = client.post(
|
||||
'/api/admin/shipping-customers/historical-task-backfill',
|
||||
json={'task_no': 'SN-20200101-HISTAPI', 'customer_id': customer_id},
|
||||
headers=_headers('shipping-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['business_no'] is None
|
||||
with app.app_context():
|
||||
persisted = ShippingTask.query.filter_by(task_no='SN-20200101-HISTAPI').one()
|
||||
assert persisted.shipping_case.business_no is None
|
||||
assert persisted.shipping_case.numbering_status == 'historical_unnumbered'
|
||||
|
||||
|
||||
def test_shipping_customer_shadow_report_and_label_api(app, client):
|
||||
"""管理员可读取影子报告并写真值标签,普通用户不可访问。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
admin = db.session.query(User).filter_by(username='shipping-admin').one()
|
||||
customer = ShippingCustomer(standard_name='ACME', short_code='ACM', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-SHADOW-API', owner_user_id=admin.id, original_filename='notice.txt',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='shadow-api',
|
||||
content_hash='b' * 64, file_size=1, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-SHADOW-API', asset_id=asset.id, user_id=admin.id, parser_version='v6', parse_status='parsed',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
|
||||
classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-SHADOW-API', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='document:1', validation_status='ready',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
shadow = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version='shadow-v1',
|
||||
status='unique_candidate', evidence_json=[], candidate_matches_json=[],
|
||||
top_customer_id=customer.id, top_score=60,
|
||||
)
|
||||
db.session.add(shadow)
|
||||
db.session.commit()
|
||||
shadow_id = shadow.id
|
||||
customer_id = customer.id
|
||||
|
||||
admin_headers = _headers('shipping-admin', 'admin')
|
||||
report_response = client.get('/api/admin/shipping-customer-shadow-report', headers=admin_headers)
|
||||
assert report_response.status_code == 200
|
||||
report = parse_api_data(report_response.get_json())
|
||||
assert report['total'] == 1
|
||||
assert report['items'][0]['candidate_no'] == 'SNC-SHADOW-API'
|
||||
assert report['auto_resolution']['enabled'] is False
|
||||
assert report['auto_resolution']['recent_events'] == []
|
||||
|
||||
label_response = client.put(
|
||||
f'/api/admin/shipping-customer-shadow-resolutions/{shadow_id}/label',
|
||||
json={'customer_id': customer_id},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert label_response.status_code == 200
|
||||
assert parse_api_data(label_response.get_json())['is_correct'] is True
|
||||
|
||||
forbidden = client.get(
|
||||
'/api/admin/shipping-customer-shadow-report',
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
|
||||
def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client):
|
||||
"""管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
|
||||
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
|
||||
case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending')
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
|
||||
source_type='manual', process_status='parsed', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = task.shipping_case.business_no
|
||||
correct_id = correct.id
|
||||
|
||||
forbidden = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['old_business_no'] == old_business_no
|
||||
assert payload['new_business_no'].startswith('NEW')
|
||||
with app.app_context():
|
||||
old_case = ShippingCase.query.filter_by(business_no=old_business_no).one()
|
||||
replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one()
|
||||
assert old_case.status == 'voided'
|
||||
assert replacement.business_no == payload['new_business_no']
|
||||
@@ -1,7 +1,9 @@
|
||||
"""
|
||||
tests/test_chat_executors_registry.py
|
||||
|
||||
用途:RUNTIME_PROVIDER_REGISTRY 与 Hybrid Executor 单元测试。
|
||||
用途:RUNTIME_PROVIDER_REGISTRY、Hybrid Executor 与 Handler 前置时序单元测试。
|
||||
依赖:executor registry、agent handler/context adapter bootstrap、pytest Flask fixture。
|
||||
逻辑:验证 provider 解析、Handler 强制约束,以及 prepare_stream 在上游生成器迭代前完成。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -93,3 +95,36 @@ def test_stream_chat_via_executor_delegates_to_dify(app, monkeypatch):
|
||||
assert captured['kwargs']['session_id'] == 'sess-1'
|
||||
inputs = captured['kwargs'].get('inputs') or {}
|
||||
assert 'agent_runtime_context' in inputs
|
||||
|
||||
|
||||
def test_stream_chat_via_executor_prepares_handler_before_generator_iteration(app, monkeypatch):
|
||||
"""Handler 必须在返回惰性上游生成器前完成准备,供 chat.py preface 立即读取领域状态。"""
|
||||
prepared = {'count': 0}
|
||||
|
||||
class _Handler:
|
||||
def prepare_stream(self, ctx):
|
||||
prepared['count'] += 1
|
||||
ctx.hxops_turn_id = 'prepared-before-preface'
|
||||
return ctx
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat.executors.resolve_handler_for_agent_code',
|
||||
lambda agent: _Handler(),
|
||||
)
|
||||
ctx = ChatStreamContext(
|
||||
query='hello',
|
||||
display_query='hello',
|
||||
user=SimpleNamespace(id=1),
|
||||
agent=_agent(),
|
||||
session=SimpleNamespace(session_id='sess-prepare'),
|
||||
external_conversation_id=None,
|
||||
request_id='req-prepare',
|
||||
)
|
||||
|
||||
generator = stream_chat_via_executor(ctx)
|
||||
|
||||
# 关键断言:此时尚未 list(generator),prepare 已同步完成且只执行一次。
|
||||
assert prepared['count'] == 1
|
||||
assert ctx.hxops_turn_id == 'prepared-before-preface'
|
||||
assert generator is not None
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
backend/tests/test_chat_user_attachments.py
|
||||
|
||||
用途:验证聊天附件快照的后端白名单清洗与归属安全合并。
|
||||
依赖:chat API 附件辅助函数、pytest monkeypatch。
|
||||
逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。
|
||||
"""
|
||||
|
||||
from app.api.chat import (
|
||||
CHAT_USER_ATTACHMENT_LIMIT,
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
items = [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'C:\\temp\\purchase-order.pdf\x00',
|
||||
'size': '144456',
|
||||
'extension': 'PDF',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
'url': 'https://example.com/?signature=secret',
|
||||
'upload_file_id': 'internal-upload',
|
||||
'asset_no': 'ASSET-1',
|
||||
}]
|
||||
|
||||
assert _normalize_user_attachments(items) == [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}]
|
||||
|
||||
|
||||
def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
valid = {
|
||||
'id': 'attachment-1',
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)]
|
||||
items[0] = {**valid, 'type': 'executable'}
|
||||
items[1] = {**valid, 'source': 'unknown'}
|
||||
items[2] = {**valid, 'size': -1, 'extension': '../pdf'}
|
||||
|
||||
normalized = _normalize_user_attachments(items)
|
||||
|
||||
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2
|
||||
assert 'size' not in normalized[0]
|
||||
assert 'extension' not in normalized[0]
|
||||
|
||||
|
||||
def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch):
|
||||
monkeypatch.setattr('app.services.chat.log_service.merge_chat_log_payload', lambda **kwargs: True)
|
||||
|
||||
assert _merge_user_attachments_from_terminal_event(
|
||||
{'event': 'error'},
|
||||
user_id=1,
|
||||
agent_id=2,
|
||||
session_id='session-1',
|
||||
user_attachments=[{'name': 'file.pdf', 'type': 'document', 'source': 'local'}],
|
||||
) is False
|
||||
|
||||
|
||||
def test_merge_user_attachments_uses_chat_log_ownership(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
def fake_merge(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr('app.services.chat.log_service.merge_chat_log_payload', fake_merge)
|
||||
|
||||
result = _merge_user_attachments_from_terminal_event(
|
||||
{'event': 'message_end', 'chat_log_id': 42},
|
||||
user_id=1,
|
||||
agent_id=2,
|
||||
session_id='session-1',
|
||||
user_attachments=[{'name': 'file.pdf', 'type': 'document', 'source': 'local'}],
|
||||
)
|
||||
|
||||
assert result is True
|
||||
assert captured == {
|
||||
'chat_log_id': 42,
|
||||
'user_id': 1,
|
||||
'agent_id': 2,
|
||||
'session_id': 'session-1',
|
||||
'payload_patch': {
|
||||
'user_attachments': [{'name': 'file.pdf', 'type': 'document', 'source': 'local'}],
|
||||
},
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
tests/test_dify_workflow_reliability.py
|
||||
|
||||
用途:覆盖 Dify Workflow streaming 断连补偿、重试与可靠性元信息。
|
||||
依赖:requests、DifyService、FileCheckService 与 pytest Flask fixture。
|
||||
逻辑:模拟 Dify SSE、HTTP 错误及超时,验证 Workflow 轮询补偿和 Chatflow 终态事件不会丢失。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,6 +24,7 @@ class _Agent:
|
||||
|
||||
|
||||
def _sse_lines(*events: dict) -> list[bytes]:
|
||||
"""把事件字典编码为 Dify requests.iter_lines 返回的字节行。"""
|
||||
return [f"data: {json.dumps(evt, ensure_ascii=False)}".encode("utf-8") for evt in events]
|
||||
|
||||
|
||||
@@ -308,3 +311,73 @@ def test_dedupe_exact_doubled_text_fixes_historical_records():
|
||||
doubled = "检核完成,共处理 3 个文件。" * 2
|
||||
assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。"
|
||||
assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer"
|
||||
|
||||
|
||||
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
|
||||
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.dify.requests.post",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DifyService,
|
||||
"_persist_stream_chat_record",
|
||||
staticmethod(lambda **kwargs: {"chat_log_id": 42, "run_id": None}),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
lines = list(DifyService.stream_chat(
|
||||
"extract orders",
|
||||
1,
|
||||
_Agent(),
|
||||
request_id="req-connect-timeout",
|
||||
session_id="session-connect-timeout",
|
||||
))
|
||||
|
||||
events = [json.loads(line.removeprefix("data: ").strip()) for line in lines]
|
||||
error_event = next(event for event in events if event.get("event") == "error")
|
||||
# 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。
|
||||
assert error_event["chat_log_id"] == 42
|
||||
assert error_event["message"]
|
||||
|
||||
|
||||
def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch):
|
||||
"""已有正文后 ReadTimeout 应合成 message_end,避免领域状态永久停留在 extracting。"""
|
||||
class _ChatResponse:
|
||||
ok = True
|
||||
status_code = 200
|
||||
reason = "OK"
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def iter_lines(self):
|
||||
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
|
||||
raise requests.exceptions.ReadTimeout("read timed out")
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr(
|
||||
DifyService,
|
||||
"_persist_stream_chat_record",
|
||||
staticmethod(lambda **kwargs: {"chat_log_id": 43, "run_id": None}),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
lines = list(DifyService.stream_chat(
|
||||
"extract orders",
|
||||
1,
|
||||
_Agent(),
|
||||
request_id="req-read-timeout",
|
||||
session_id="session-read-timeout",
|
||||
))
|
||||
|
||||
events = [json.loads(line.removeprefix("data: ").strip()) for line in lines]
|
||||
terminal = next(event for event in events if event.get("event") == "message_end")
|
||||
assert terminal["answer"] == "partial answer"
|
||||
assert terminal["chat_log_id"] == 43
|
||||
@@ -53,7 +53,7 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"attempt": 3,
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"connector_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"enabled": True,
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
@@ -276,7 +276,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
assert trigger["task_no"] == "SN-20260629-2EDADC77"
|
||||
assert trigger["attempt"] == 3
|
||||
assert trigger["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
|
||||
assert trigger["rpa_inventory_source"]["source_type"] == "dsv360"
|
||||
assert trigger["rpa_inventory_source"]["connector_type"] == "dsv360"
|
||||
assert trigger["rpa_inventory_source"]["query"]["program_label"] == "AWSDU - Prod (JDA)"
|
||||
assert trigger["rpa_inventory_source"]["query"]["owner_code"] == "CADU-0000000100"
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
backend/tests/test_shipping_business_numbering.py
|
||||
|
||||
用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。
|
||||
依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。
|
||||
逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.business_numbering_service import (
|
||||
assign_business_number,
|
||||
format_business_no,
|
||||
shanghai_business_date,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref
|
||||
|
||||
|
||||
def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
"""创建待客户确认的业务单、任务和启用客户。"""
|
||||
customer = ShippingCustomer(
|
||||
standard_name=f"编号测试客户 {short_code}",
|
||||
short_code=short_code,
|
||||
status="active",
|
||||
)
|
||||
case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending")
|
||||
db.session.add_all([customer, case])
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no=task_no,
|
||||
shipping_case_id=case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task, case, customer
|
||||
|
||||
|
||||
def test_number_format_and_shanghai_date_boundary(app):
|
||||
"""UTC 日期跨日时必须按 Asia/Shanghai 生成 YYMMDD 且不含分隔符。"""
|
||||
with app.app_context():
|
||||
moment = datetime(2026, 7, 14, 16, 30, tzinfo=timezone.utc)
|
||||
business_date = shanghai_business_date(moment)
|
||||
assert business_date.isoformat() == "2026-07-15"
|
||||
assert format_business_no("WYC", business_date, 1) == "WYC26071501"
|
||||
|
||||
|
||||
def test_confirmation_assigns_idempotent_business_number(app):
|
||||
"""重复确认同一客户不得重复占用流水,正式编号保持不变。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
first_no = first.shipping_case.business_no
|
||||
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None)
|
||||
|
||||
assert first_no
|
||||
assert second.shipping_case.business_no == first_no
|
||||
assert ShippingBusinessSequence.query.one().current_value == 1
|
||||
assert second.shipping_case.customer_short_code_snapshot == "WYC"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1
|
||||
|
||||
|
||||
def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
"""同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
revision = ShippingTask(
|
||||
task_no="SN-NUMBER-REV",
|
||||
shipping_case_id=case.id,
|
||||
supersedes_task_id=task.id,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
|
||||
db.session.add_all([revision, forced_case])
|
||||
db.session.flush()
|
||||
forced_task = ShippingTask(
|
||||
task_no="SN-NUMBER-FORCED",
|
||||
shipping_case_id=forced_case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(forced_task)
|
||||
db.session.commit()
|
||||
|
||||
confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None)
|
||||
assert revision.shipping_case.business_no == case.business_no
|
||||
assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2]
|
||||
assert case.business_no.endswith("01")
|
||||
assert forced_task.shipping_case.business_no.endswith("02")
|
||||
|
||||
|
||||
def test_daily_sequence_blocks_one_hundredth_case(app):
|
||||
"""客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
business_date = shanghai_business_date()
|
||||
db.session.add(ShippingBusinessSequence(
|
||||
business_type="shipping_notice",
|
||||
customer_id=customer.id,
|
||||
business_date=business_date,
|
||||
current_value=99,
|
||||
))
|
||||
db.session.commit()
|
||||
case.customer_id = customer.id
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
assign_business_number(case)
|
||||
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED"
|
||||
assert case.business_no is None
|
||||
assert ShippingBusinessSequence.query.one().current_value == 99
|
||||
|
||||
|
||||
def test_numbering_failure_rolls_back_customer_confirmation(app):
|
||||
"""流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
db.session.add(ShippingBusinessSequence(
|
||||
business_type="shipping_notice",
|
||||
customer_id=customer.id,
|
||||
business_date=shanghai_business_date(),
|
||||
current_value=99,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError):
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
persisted_case = db.session.get(ShippingCase, case.id)
|
||||
persisted_task = db.session.get(ShippingTask, task.id)
|
||||
assert persisted_case.customer_id is None
|
||||
assert persisted_case.business_no is None
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
|
||||
|
||||
def test_business_number_query_returns_latest_revision(app):
|
||||
"""使用正式业务号查询时应返回同业务单最新修订任务。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
revision = ShippingTask(
|
||||
task_no="SN-NUMBER-QUERY-REV",
|
||||
shipping_case_id=case.id,
|
||||
supersedes_task_id=task.id,
|
||||
document_version=2,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
resolved = get_task_by_ref(case.business_no)
|
||||
assert resolved.id == revision.id
|
||||
assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no
|
||||
|
||||
|
||||
def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app):
|
||||
"""客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
case.customer_id = customer.id
|
||||
customer.short_code = "W1"
|
||||
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
|
||||
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
|
||||
assign_business_number(case)
|
||||
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID"
|
||||
assert case.business_no is None
|
||||
db.session.rollback()
|
||||
@@ -0,0 +1,283 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_auto_resolution.py
|
||||
|
||||
用途:验证受控自动客户确认、降级开关、强规则歧义和历史客户回填。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_RESOLUTION_VERSION,
|
||||
backfill_historical_task_customer,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
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 _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
"""创建带邮件证据的 Candidate、影子记录和待确认任务。"""
|
||||
user = User(username=f"auto-user-{db.session.query(User).count()}", email="auto@example.com", role="user")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no=f"AUTO-ASSET-{user.id}", owner_user_id=user.id, original_filename="notice.eml",
|
||||
storage_provider="minio", storage_bucket="test", storage_key=f"auto-{user.id}",
|
||||
content_hash=f"{user.id:064d}", file_size=1, upload_status="uploaded", lifecycle_status="temporary",
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f"AUTO-INTAKE-{user.id}", asset_id=asset.id, user_id=user.id,
|
||||
parser_version="v6", parse_status="parsed", structured_result_json={"email": {"from": sender}},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type="attachment", attachment_key="file",
|
||||
filename="notice.pdf", classification="order_notice", parse_status="parsed",
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=f"AUTO-CAND-{user.id}", intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key="document:1", validation_status="ready", selected=True,
|
||||
structured_result_json={"business_summary": {"customer_name": "unstable name"}},
|
||||
)
|
||||
case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending")
|
||||
db.session.add_all([candidate, case])
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment", process_status="parsed",
|
||||
customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
shadow = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1",
|
||||
status="unique_candidate",
|
||||
evidence_json=[
|
||||
{"type": "email", "raw_value": sender, "normalized_value": sender},
|
||||
{"type": "domain", "raw_value": sender.split("@")[-1], "normalized_value": sender.split("@")[-1]},
|
||||
],
|
||||
candidate_matches_json=[],
|
||||
)
|
||||
db.session.add(shadow)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, status: str = "approved"):
|
||||
"""创建客户及邮箱强证据。"""
|
||||
customer = ShippingCustomer(standard_name=f"客户 {code}", short_code=code, status="active")
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer.id, identifier_type="email", raw_value=value, normalized_value=value,
|
||||
status=status, source="manual", auto_match_allowed=allowed,
|
||||
))
|
||||
db.session.flush()
|
||||
return customer
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
|
||||
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
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.shipping_case.customer_id == customer.id
|
||||
assert task.shipping_case.business_no.startswith("WYC")
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
|
||||
metrics = get_auto_resolution_metrics()
|
||||
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):
|
||||
"""总开关关闭或证据未审核/未授权时保持 pending,不占用业务流水。"""
|
||||
with app.app_context():
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com", allowed=False)
|
||||
task = _seed_candidate_task()
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
|
||||
disabled = try_auto_confirm_task_customer(task)
|
||||
assert disabled["status"] == "disabled"
|
||||
assert task.shipping_case.business_no is None
|
||||
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
|
||||
unmatched = try_auto_confirm_task_customer(task)
|
||||
assert unmatched["status"] == "unmatched"
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.shipping_case.business_no is None
|
||||
|
||||
|
||||
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
"""同一强证据映射多个客户时必须降级人工确认。"""
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
|
||||
_customer_with_identifier(code="AAA", value="buyer@wyc.example.com")
|
||||
_customer_with_identifier(code="BBB", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
|
||||
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.shipping_case.business_no is None
|
||||
|
||||
|
||||
def test_historical_backfill_binds_customer_without_numbering(app):
|
||||
"""历史任务回填客户后业务号仍为空,不倒占当日流水。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(standard_name="历史客户", short_code="HIS", status="active")
|
||||
task = ShippingTask(task_no="SN-20200101-HISTORY", source_type="manual", process_status="closed")
|
||||
db.session.add_all([customer, task])
|
||||
db.session.commit()
|
||||
|
||||
result = backfill_historical_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
assert result["business_no"] is None
|
||||
assert task.shipping_case.customer_id == customer.id
|
||||
assert task.shipping_case.numbering_status == "historical_unnumbered"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.customer_resolution_method == "historical_backfill"
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["historical_backfilled_count"] == 1
|
||||
assert metrics["recent_events"][0]["event_type"] == "customer_historical_backfilled"
|
||||
|
||||
|
||||
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
"""批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。"""
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
task_id = task.id
|
||||
case_id = task.shipping_case_id
|
||||
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
assert result["status"] == "auto_confirmed"
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
|
||||
persisted_task = db.session.get(ShippingTask, task_id)
|
||||
persisted_case = db.session.get(ShippingCase, case_id)
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
assert persisted_case.customer_id is None
|
||||
assert persisted_case.business_no is None
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
|
||||
|
||||
|
||||
def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
"""客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
|
||||
case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending")
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.flush()
|
||||
first = ShippingTask(
|
||||
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(first)
|
||||
db.session.flush()
|
||||
latest = ShippingTask(
|
||||
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
|
||||
supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload",
|
||||
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(latest)
|
||||
db.session.commit()
|
||||
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
|
||||
old_case_id = case.id
|
||||
old_business_no = case.business_no
|
||||
|
||||
result = correct_numbered_task_customer(
|
||||
latest,
|
||||
customer_id=correct.id,
|
||||
reason="自动识别客户错误",
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
old_case = db.session.get(ShippingCase, old_case_id)
|
||||
replacement = db.session.get(ShippingCase, result["new_case_id"])
|
||||
assert old_case.business_no == old_business_no
|
||||
assert old_case.status == "voided"
|
||||
assert old_case.numbering_status == "voided"
|
||||
assert replacement.replaces_case_id == old_case.id
|
||||
assert replacement.business_no.startswith("NEW")
|
||||
assert replacement.business_no != old_business_no
|
||||
assert latest.shipping_case_id == replacement.id
|
||||
assert first.shipping_case_id == replacement.id
|
||||
assert latest.customer_resolution_method == "admin_correction"
|
||||
assert latest.inventory_source_status is None
|
||||
assert latest.inventory_lines_json is None
|
||||
assert latest.export_file_path is None
|
||||
assert latest.process_status == "parsed"
|
||||
assert get_task_by_ref(old_business_no).id == latest.id
|
||||
assert get_task_by_ref(replacement.business_no).id == latest.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
|
||||
|
||||
|
||||
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app):
|
||||
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
|
||||
case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending")
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
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()
|
||||
|
||||
task.process_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(ShippingCase).count() == 1
|
||||
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_identity_gate.py
|
||||
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
|
||||
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
|
||||
逻辑:构造 pending 任务逐入口断言无副作用;确认后验证业务单/修订同步和历史兼容。
|
||||
"""
|
||||
|
||||
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 ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent, 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, parse_inventory, upload_inventory_file
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
|
||||
|
||||
def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustomer, User]:
|
||||
"""创建待确认任务、启用客户和任务用户。"""
|
||||
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()
|
||||
case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None
|
||||
if case:
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no=f'SN-GATE-{user.id}', user_id=user.id,
|
||||
shipping_case_id=case.id if case else None,
|
||||
customer_resolution_status='pending' if case else None,
|
||||
process_status='parsed', lines_json=[{'sku': 'A001', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
)
|
||||
db.session.add(task)
|
||||
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 result['human_options'] == ['confirm_customer']
|
||||
|
||||
|
||||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
"""未确认客户时所有库存与履约公共入口都必须在副作用前停止。"""
|
||||
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}),
|
||||
parse_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}),
|
||||
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}),
|
||||
upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}),
|
||||
]
|
||||
for result in results:
|
||||
_assert_customer_gate_response(result)
|
||||
|
||||
callback = _validate_rpa_callback_gate(task)
|
||||
assert callback is not None
|
||||
assert callback['status'] == 'failed'
|
||||
db.session.refresh(task)
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.upload_status is None
|
||||
|
||||
|
||||
def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
|
||||
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
revision = ShippingTask(
|
||||
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
process_status='parsed',
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
db.session.refresh(revision)
|
||||
case = db.session.get(ShippingCase, task.shipping_case_id)
|
||||
assert updated.customer_resolution_status == 'confirmed'
|
||||
assert revision.customer_resolution_status == 'confirmed'
|
||||
assert updated.customer_resolution_method == 'manual'
|
||||
assert case.customer_id == customer.id
|
||||
assert case.customer_name_snapshot == customer.standard_name
|
||||
assert case.customer_short_code_snapshot == customer.short_code
|
||||
assert case.business_no.startswith(customer.short_code)
|
||||
assert len(case.business_no) == len(customer.short_code) + 8
|
||||
assert case.sequence_value == 1
|
||||
assert case.numbering_status == 'assigned'
|
||||
assert customer_identity_is_confirmed(updated) is True
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2
|
||||
|
||||
|
||||
def test_inactive_customer_reblocks_and_legacy_task_is_compatible(app):
|
||||
"""已确认客户停用后重新阻断;历史无业务单任务继续兼容。"""
|
||||
with app.app_context():
|
||||
task, 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'
|
||||
|
||||
legacy, _other_customer, _other_user = _seed_task(with_case=False)
|
||||
assert_customer_identity_gate(legacy, operation='match_inventory')
|
||||
assert customer_identity_is_confirmed(legacy) is True
|
||||
|
||||
|
||||
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()
|
||||
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
|
||||
username = user.username
|
||||
|
||||
headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'}
|
||||
options_response = client.get('/api/workspace/shipping-customers?q=GAA', headers=headers)
|
||||
assert options_response.status_code == 200
|
||||
assert options_response.get_json()[0]['short_code'] == 'GAA'
|
||||
|
||||
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
|
||||
payload = confirm_response.get_json()
|
||||
assert payload['customer_resolution_status'] == 'confirmed'
|
||||
assert payload['customer_id'] == customer_id
|
||||
assert payload['business_no'].startswith('GAA')
|
||||
|
||||
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
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_migrations.py
|
||||
|
||||
用途:独立验证客户主数据、期初导入与影子识别三段迁移可升级和降级。
|
||||
依赖:Alembic MigrationContext、SQLAlchemy、f1/a2/b3 客户迁移模块。
|
||||
逻辑:构造订单抽取阶段的最小历史结构,依序执行迁移并检查约束,再逆序回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
|
||||
def _customer_pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建 f1 客户基础迁移所需的最小历史表。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_intakes', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_candidates', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_shipping_customer_migrations_upgrade_and_downgrade():
|
||||
"""三段客户迁移应建立关键约束,并能逆序移除全部新增结构。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_customer_pre_migration_schema(engine)
|
||||
modules = [
|
||||
importlib.import_module('migrations.versions.f1a2b3c4d5e6_shipping_customer_case_foundation'),
|
||||
importlib.import_module('migrations.versions.a2c3d4e5f6a7_shipping_customer_imports'),
|
||||
importlib.import_module('migrations.versions.b3d4e5f6a7b8_shipping_customer_shadow_resolution'),
|
||||
]
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
original_ops = [module.op for module in modules]
|
||||
for module in modules:
|
||||
module.op = operations
|
||||
try:
|
||||
for module in modules:
|
||||
module.upgrade()
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
assert {
|
||||
'shipping_customers',
|
||||
'shipping_customer_identifiers',
|
||||
'shipping_cases',
|
||||
'shipping_business_sequences',
|
||||
'shipping_customer_import_batches',
|
||||
'shipping_customer_import_rows',
|
||||
'shipping_customer_shadow_resolutions',
|
||||
} <= set(inspector.get_table_names())
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
assert {'shipping_case_id', 'customer_resolution_status', 'customer_confirmed_at'} <= task_columns
|
||||
case_constraints = {
|
||||
item['name'] for item in inspector.get_unique_constraints('shipping_cases')
|
||||
}
|
||||
assert 'uq_shipping_cases_replaces_case_id' in case_constraints
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_customers "
|
||||
"(id, standard_name, short_code, status, created_at, updated_at) "
|
||||
"VALUES (1, 'Valid', 'WYC', 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_customers "
|
||||
"(id, standard_name, short_code, status, created_at, updated_at) "
|
||||
"VALUES (2, 'Invalid', 'W1', 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
for module in reversed(modules):
|
||||
module.downgrade()
|
||||
remaining = set(sa.inspect(connection).get_table_names())
|
||||
assert 'shipping_customers' not in remaining
|
||||
assert 'shipping_customer_import_batches' not in remaining
|
||||
assert 'shipping_customer_shadow_resolutions' not in remaining
|
||||
task_columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_tasks')}
|
||||
assert 'shipping_case_id' not in task_columns
|
||||
finally:
|
||||
for module, original_op in zip(modules, original_ops, strict=True):
|
||||
module.op = original_op
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_shadow_resolution.py
|
||||
|
||||
用途:验证客户影子识别的确定性候选、幂等、质量标签和零副作用边界。
|
||||
依赖:内存数据库、客户主数据、Candidate/Intake、customer_shadow_resolution。
|
||||
逻辑:构造真实 ORM 样本后刷新影子结果,断言业务单客户与业务编号始终不被写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
get_shadow_quality_report,
|
||||
label_shadow_resolution,
|
||||
refresh_candidate_shadow_resolution,
|
||||
)
|
||||
|
||||
|
||||
def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCandidate:
|
||||
"""创建影子识别所需的最小 Intake、Document 与 Candidate。"""
|
||||
user = User(username=f'user-{customer_name}-{sender}', email=f'{db.session.query(User).count()}@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{user.id}', owner_user_id=user.id, original_filename='notice.eml',
|
||||
storage_provider='minio', storage_bucket='test', storage_key=f'notice-{user.id}',
|
||||
content_hash=f'{user.id:064d}', file_size=1, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f'SNI-{user.id}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
|
||||
structured_result_json={'email': {'from': sender}},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
|
||||
filename='notice.pdf', classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='document:1', validation_status='ready',
|
||||
structured_result_json={'business_summary': {'customer_name': customer_name, 'lines': [{'sku': 'A', 'quantity': 1}]}},
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
return candidate
|
||||
|
||||
|
||||
def _create_customer(name: str, code: str) -> ShippingCustomer:
|
||||
"""创建启用客户并返回 ORM 记录。"""
|
||||
customer = ShippingCustomer(standard_name=name, short_code=code, status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
return customer
|
||||
|
||||
|
||||
def test_shadow_resolution_uses_strong_evidence_without_binding_case(app):
|
||||
"""完整邮箱可形成唯一候选,但业务单客户和业务编号保持为空。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer('无锡宇辰有限公司', 'WYC')
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer.id, identifier_type='email', raw_value='buyer@wyc.example.com',
|
||||
normalized_value='buyer@wyc.example.com', status='approved', source='manual', auto_match_allowed=True,
|
||||
))
|
||||
candidate = _seed_candidate(customer_name='不稳定解析名称', sender='Buyer <buyer@wyc.example.com>')
|
||||
case = ShippingCase(case_no='CASE-SHADOW-1')
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
db.session.commit()
|
||||
|
||||
assert resolution.status == 'unique_candidate'
|
||||
assert resolution.top_customer_id == customer.id
|
||||
assert resolution.top_score == 100.0
|
||||
assert case.customer_id is None
|
||||
assert case.business_no is None
|
||||
assert get_shadow_quality_report()['auto_bound_count'] == 0
|
||||
|
||||
|
||||
def test_shadow_resolution_reports_ambiguous_and_unmatched(app):
|
||||
"""同名客户必须保留歧义,无证据样本必须标记未匹配。"""
|
||||
with app.app_context():
|
||||
_create_customer('ACME', 'ACA')
|
||||
_create_customer('ACME', 'ACB')
|
||||
ambiguous = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='ACME'))
|
||||
unmatched = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='UNKNOWN'))
|
||||
db.session.commit()
|
||||
|
||||
assert ambiguous.status == 'ambiguous'
|
||||
assert ambiguous.top_customer_id is None
|
||||
assert len(ambiguous.candidate_matches_json) == 2
|
||||
assert unmatched.status == 'unmatched'
|
||||
assert unmatched.candidate_matches_json == []
|
||||
|
||||
|
||||
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||||
"""重算复用同一记录;准确率只统计人工标签且不会反向绑定业务。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer('ACME', 'ACM')
|
||||
candidate = _seed_candidate(customer_name='ACME')
|
||||
first = refresh_candidate_shadow_resolution(candidate)
|
||||
first_id = first.id
|
||||
second = refresh_candidate_shadow_resolution(candidate)
|
||||
db.session.commit()
|
||||
assert second.id == first_id
|
||||
assert db.session.query(ShippingCustomerShadowResolution).count() == 1
|
||||
|
||||
labeled = label_shadow_resolution(first_id, customer_id=customer.id, actor_id=None)
|
||||
report = get_shadow_quality_report()
|
||||
assert labeled['is_correct'] is True
|
||||
assert report['labeled_count'] == 1
|
||||
assert report['correct_count'] == 1
|
||||
assert report['accuracy'] == 1.0
|
||||
assert report['auto_bound_count'] == 0
|
||||
|
||||
|
||||
def test_shadow_failure_does_not_block_candidate_persistence(app, monkeypatch):
|
||||
"""影子规则异常时 Candidate 主流程仍须创建并可提交。"""
|
||||
with app.app_context():
|
||||
user = User(username='shadow-safe-user', email='shadow-safe@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-SHADOW-SAFE', owner_user_id=user.id, original_filename='notice.txt',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='shadow-safe',
|
||||
content_hash='a' * 64, file_size=10, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-SHADOW-SAFE', asset_id=asset.id, user_id=user.id,
|
||||
parser_version='v6', parse_status='parsed', structured_result_json={},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.customer_shadow_resolution.refresh_candidate_shadow_resolution',
|
||||
lambda _candidate: (_ for _ in ()).throw(RuntimeError('shadow failure')),
|
||||
)
|
||||
result = NoticeIntakeResult(
|
||||
filename='notice.txt', source_type='manual', source_file_type='text/plain',
|
||||
text='Customer: ACME\nPO: PO-1\nSKU: A001 Qty: 1', content_hash='a' * 64,
|
||||
file_size=10, status='accepted',
|
||||
)
|
||||
|
||||
persisted = persist_documents_and_candidates(
|
||||
intake=intake,
|
||||
parent_asset=asset,
|
||||
result=result,
|
||||
run_duplicate_detection=False,
|
||||
create_candidates=True,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert persisted['candidate_count'] == 1
|
||||
candidate = db.session.query(ShippingNoticeCandidate).one()
|
||||
assert candidate.validation_status == 'ready'
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).one()
|
||||
assert shadow.status == 'failed'
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
backend/tests/test_shipping_inventory_connector_migration.py
|
||||
|
||||
用途:验证库存连接器列重命名迁移的版本链与双向列名。
|
||||
依赖:c4d5e6f7a8b9 Alembic 迁移模块、pytest monkeypatch。
|
||||
逻辑:拦截 alter_column 调用,确认升级保留数据式重命名且降级可恢复旧列名。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from typing import Any
|
||||
|
||||
|
||||
def test_inventory_connector_column_migration_renames_both_directions(monkeypatch):
|
||||
"""迁移应承接当前 head,并仅双向重命名 shipping_tasks 库存连接器列。"""
|
||||
module = importlib.import_module(
|
||||
"migrations.versions.c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type"
|
||||
)
|
||||
calls: list[tuple[str, str, dict[str, Any]]] = []
|
||||
|
||||
def capture_alter_column(table_name: str, column_name: str, **kwargs: Any) -> None:
|
||||
"""记录迁移列变更参数,避免测试依赖具体数据库方言。"""
|
||||
calls.append((table_name, column_name, kwargs))
|
||||
|
||||
monkeypatch.setattr(module.op, "alter_column", capture_alter_column)
|
||||
|
||||
module.upgrade()
|
||||
module.downgrade()
|
||||
|
||||
assert module.down_revision == "b3d4e5f6a7b8"
|
||||
assert calls[0][0:2] == ("shipping_tasks", "inventory_source_type")
|
||||
assert calls[0][2]["new_column_name"] == "inventory_connector_type"
|
||||
assert calls[1][0:2] == ("shipping_tasks", "inventory_connector_type")
|
||||
assert calls[1][2]["new_column_name"] == "inventory_source_type"
|
||||
@@ -11,8 +11,22 @@ import json
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, User
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
Job,
|
||||
KbJob,
|
||||
ShippingBatch,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
User,
|
||||
)
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import process_next_job
|
||||
@@ -640,7 +654,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
|
||||
step_payload_json={
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"connector_type": "dsv360",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
|
||||
}
|
||||
@@ -688,7 +702,7 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli
|
||||
step_payload_json={
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"connector_type": "dsv360",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
|
||||
}
|
||||
@@ -761,7 +775,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
|
||||
assert trigger_path.exists()
|
||||
trigger_text = trigger_path.read_text(encoding="utf-8")
|
||||
assert '"source_code": "DSV360_AWSDU"' in trigger_text
|
||||
assert '"source_type": "dsv360"' in trigger_text
|
||||
assert '"connector_type": "dsv360"' in trigger_text
|
||||
|
||||
|
||||
def test_inventory_source_rules_cover_dsv360_programs(app):
|
||||
@@ -1075,6 +1089,257 @@ def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch):
|
||||
assert '"action_buttons"' in body
|
||||
|
||||
|
||||
def test_chat_completions_streams_order_extraction_terminal_ui_state(app, client, monkeypatch):
|
||||
"""事务提交并解绑 ORM 后仍须调用 Dify,并按本轮 Intake 补发权威 Batch UI State。"""
|
||||
from app.services import dify as dify_module
|
||||
from app.services.shipping_notice import order_extraction as order_extraction_module
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username="shipping_extraction_stream_user",
|
||||
email="shipping_extraction_stream_user@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("password")
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
dify_api_key="test-dify-key",
|
||||
api_base_url="http://dify.example/v1",
|
||||
type="api",
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
session = ChatSession(
|
||||
session_id="conv-extraction-terminal-ui-state",
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title="Order extraction",
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no="FA-EXTRACTION-STREAM",
|
||||
owner_user_id=user.id,
|
||||
original_filename="orders.eml",
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key="test/orders.eml",
|
||||
content_hash="extraction-stream-hash",
|
||||
file_size=128,
|
||||
mime_type="message/rfc822",
|
||||
upload_status="ready",
|
||||
lifecycle_status="referenced",
|
||||
)
|
||||
batch = ShippingBatch(
|
||||
batch_no="SB-EXTRACTION-STREAM",
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
current_focus_task_no="SN-EXTRACTION-STREAM",
|
||||
file_count=1,
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no="SN-EXTRACTION-STREAM",
|
||||
batch=batch,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type="email",
|
||||
process_status="pending_review",
|
||||
pending_human_reason="rsv_req",
|
||||
)
|
||||
db.session.add_all([session, asset, batch, task])
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no="SNI-EXTRACTION-STREAM",
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose="shipping_notice",
|
||||
parse_status="parsed",
|
||||
parser_version="v6",
|
||||
order_extraction_status="not_started",
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
agent_id = agent.id
|
||||
|
||||
dify_called = False
|
||||
original_start_order_extraction = order_extraction_module.start_order_extraction
|
||||
|
||||
def detaching_start_order_extraction(**kwargs):
|
||||
"""模拟生产流开始前原请求 scoped session 已清理,强制暴露 ORM 跨流引用。"""
|
||||
result = original_start_order_extraction(**kwargs)
|
||||
db.session.expunge_all()
|
||||
return result
|
||||
|
||||
def fake_stream_chat(*args, **kwargs):
|
||||
nonlocal dify_called
|
||||
dify_called = True
|
||||
# 模拟 Dify submit_order_extraction Tool 在 terminal 前提交消费关系。
|
||||
with app.app_context():
|
||||
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-STREAM").one()
|
||||
batch = ShippingBatch.query.filter_by(batch_no="SB-EXTRACTION-STREAM").one()
|
||||
intake.parse_status = "consumed"
|
||||
intake.order_extraction_status = "completed"
|
||||
intake.consumed_at = datetime.utcnow()
|
||||
intake.consumed_batch_id = batch.id
|
||||
db.session.commit()
|
||||
yield 'data: {"event":"message","answer":"已创建发货任务。"}\n\n'
|
||||
yield 'data: {"event":"workflow_finished","answer":"","conversation_id":"dify-extraction-conv"}\n\n'
|
||||
|
||||
monkeypatch.setattr(order_extraction_module, "start_order_extraction", detaching_start_order_extraction)
|
||||
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
|
||||
|
||||
res = client.post(
|
||||
"/api/chat/completions",
|
||||
headers={
|
||||
"X-User-Id": str(user_id),
|
||||
"X-Username": "shipping_extraction_stream_user",
|
||||
"X-Role": "user",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"agent_id": agent_id,
|
||||
"query": "请解析邮件并自动建单",
|
||||
"conversation_id": "conv-extraction-terminal-ui-state",
|
||||
"shipping_intake_nos": ["SNI-EXTRACTION-STREAM"],
|
||||
},
|
||||
)
|
||||
|
||||
body = res.get_data(as_text=True)
|
||||
assert res.status_code == 200
|
||||
# 关键断言:prepare_stream 提交事务并解绑 ORM 后,relay 首帧仍可发送且 Dify generator 必须被迭代。
|
||||
assert dify_called is True
|
||||
assert '"event": "session_created"' in body
|
||||
assert '"event": "message", "answer": "已创建发货任务。"' in body
|
||||
assert '"event": "shipping_ui_state"' in body
|
||||
assert '"source": "order_extraction"' in body
|
||||
assert '"batch_no": "SB-EXTRACTION-STREAM"' in body
|
||||
assert '"task_no": "SN-EXTRACTION-STREAM"' in body
|
||||
assert body.index('"event": "workflow_finished"') < body.rindex('"event": "shipping_ui_state"')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure_mode', ['sse_error', 'relay_exception'])
|
||||
def test_chat_completions_closes_order_extraction_on_upstream_error(
|
||||
app,
|
||||
client,
|
||||
monkeypatch,
|
||||
failure_mode,
|
||||
):
|
||||
"""Dify SSE error 或 relay 异常都必须即时收口,不能等待五分钟超时。"""
|
||||
from app.services import dify as dify_module
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username="shipping_extraction_error_user",
|
||||
email="shipping_extraction_error_user@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("password")
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
dify_api_key="test-dify-key",
|
||||
api_base_url="http://dify.example/v1",
|
||||
type="api",
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
session = ChatSession(
|
||||
session_id="conv-extraction-upstream-error",
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title="Order extraction error",
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no="FA-EXTRACTION-ERROR",
|
||||
owner_user_id=user.id,
|
||||
original_filename="orders-error.eml",
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key="test/orders-error.eml",
|
||||
content_hash="extraction-error-hash",
|
||||
file_size=128,
|
||||
mime_type="message/rfc822",
|
||||
upload_status="ready",
|
||||
lifecycle_status="referenced",
|
||||
)
|
||||
db.session.add_all([session, asset])
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no="SNI-EXTRACTION-ERROR",
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose="shipping_notice",
|
||||
parse_status="parsed",
|
||||
parser_version="v6",
|
||||
order_extraction_status="not_started",
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type="attachment",
|
||||
attachment_key="orders-error.pdf",
|
||||
filename="orders-error.pdf",
|
||||
content_hash="extraction-error-document-hash",
|
||||
classification="order_notice",
|
||||
parse_status="parsed",
|
||||
extracted_text="SKU ERROR-SKU QTY 1",
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
agent_id = agent.id
|
||||
|
||||
def fake_stream_chat(*args, **kwargs):
|
||||
"""模拟 Dify 主动返回 error,或流迭代期间直接抛出异常。"""
|
||||
if failure_mode == 'relay_exception':
|
||||
raise RuntimeError('Dify connection reset')
|
||||
yield 'data: {"event":"error","message":"Dify unavailable"}\n\n'
|
||||
|
||||
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
|
||||
res = client.post(
|
||||
"/api/chat/completions",
|
||||
headers={
|
||||
"X-User-Id": str(user_id),
|
||||
"X-Username": "shipping_extraction_error_user",
|
||||
"X-Role": "user",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"agent_id": agent_id,
|
||||
"query": "请解析邮件并自动建单",
|
||||
"conversation_id": "conv-extraction-upstream-error",
|
||||
"shipping_intake_nos": ["SNI-EXTRACTION-ERROR"],
|
||||
},
|
||||
)
|
||||
|
||||
body = res.get_data(as_text=True)
|
||||
assert res.status_code == 200
|
||||
assert '"event": "error"' in body
|
||||
with app.app_context():
|
||||
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-ERROR").one()
|
||||
document = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).one()
|
||||
assert intake.order_extraction_status == "failed"
|
||||
assert intake.order_extraction_error_code == "SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED"
|
||||
assert intake.order_extraction_error_message == (
|
||||
"Dify connection reset" if failure_mode == 'relay_exception' else "Dify unavailable"
|
||||
)
|
||||
assert document.order_extraction_status == "failed"
|
||||
|
||||
|
||||
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
|
||||
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
|
||||
headers = _workspace_headers(app)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_business_case.py
|
||||
|
||||
用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。
|
||||
依赖:app fixture、ShippingTask/ShippingCase、business_case_service。
|
||||
逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。
|
||||
"""
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingCase, ShippingTask
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task
|
||||
|
||||
|
||||
def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingTask:
|
||||
"""构造最小货代任务,供业务单关系断言使用。"""
|
||||
return ShippingTask(
|
||||
task_no=task_no,
|
||||
shipping_case_id=case_id,
|
||||
supersedes_task_id=supersedes_task_id,
|
||||
source_type='manual',
|
||||
process_status='created',
|
||||
)
|
||||
|
||||
|
||||
def test_normal_and_force_create_use_different_cases(app):
|
||||
"""普通建单和强制新建必须各自创建独立业务单。"""
|
||||
with app.app_context():
|
||||
normal = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
forced = resolve_shipping_case_for_new_task(
|
||||
duplicate_resolution_type='force_create',
|
||||
created_by_id=None,
|
||||
)
|
||||
assert normal.id != forced.id
|
||||
assert normal.business_no is None
|
||||
assert forced.business_no is None
|
||||
|
||||
|
||||
def test_revision_inherits_existing_parent_case(app):
|
||||
"""修订任务必须继承父任务已有业务单,不能创建新业务单。"""
|
||||
with app.app_context():
|
||||
case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
parent = _task('SN-CASE-PARENT-1', case_id=case.id)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
|
||||
resolved = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
assert resolved.id == case.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
|
||||
|
||||
def test_revision_backfills_case_for_legacy_parent(app):
|
||||
"""历史父任务没有业务单时,首次修订应补建并复用同一业务单。"""
|
||||
with app.app_context():
|
||||
parent = _task('SN-CASE-LEGACY-1')
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
|
||||
resolved = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
db.session.flush()
|
||||
assert parent.shipping_case_id == resolved.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
|
||||
|
||||
def test_revision_chain_reuses_root_case(app):
|
||||
"""连续修订版本必须沿用同一业务单聚合。"""
|
||||
with app.app_context():
|
||||
case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
parent = _task('SN-CASE-CHAIN-1', case_id=case.id)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
revision_case = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id)
|
||||
db.session.add(revision)
|
||||
db.session.flush()
|
||||
|
||||
next_case = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=revision.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
assert next_case.id == case.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
|
||||
|
||||
def test_create_task_assigns_case_and_serializes_it(app):
|
||||
"""真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。"""
|
||||
with app.app_context():
|
||||
result = create_task({'source_type': 'manual', 'raw_content': 'customer notice'})
|
||||
task = ShippingTask.query.filter_by(task_no=result['task_id']).one()
|
||||
assert task.shipping_case_id is not None
|
||||
assert result['data']['shipping_case_id'] == task.shipping_case_id
|
||||
assert result['data']['case_no'] == task.shipping_case.case_no
|
||||
assert result['data']['business_no'] is None
|
||||
|
||||
|
||||
def test_batch_revision_inherits_parent_case(app):
|
||||
"""真实批量建单路径中的 revision 必须继承父任务业务单。"""
|
||||
with app.app_context():
|
||||
case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id)
|
||||
db.session.add(parent)
|
||||
db.session.commit()
|
||||
|
||||
result = create_batch_tasks({
|
||||
'notice_items': [{
|
||||
'source_type': 'manual',
|
||||
'raw_text': 'revision notice',
|
||||
'document_version': 2,
|
||||
'supersedes_task_id': parent.id,
|
||||
'duplicate_resolution_type': 'revision',
|
||||
}],
|
||||
'defer_parse': True,
|
||||
})
|
||||
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
|
||||
assert task.shipping_case_id == case.id
|
||||
assert task.supersedes_task_id == parent.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
|
||||
|
||||
def test_batch_force_create_uses_new_case(app):
|
||||
"""真实批量建单路径中的 force_create 必须创建独立业务单。"""
|
||||
with app.app_context():
|
||||
original_case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id)
|
||||
db.session.add(original)
|
||||
db.session.commit()
|
||||
|
||||
result = create_batch_tasks({
|
||||
'notice_items': [{
|
||||
'source_type': 'manual',
|
||||
'raw_text': 'forced notice',
|
||||
'duplicate_source_task_id': original.id,
|
||||
'duplicate_resolution_type': 'force_create',
|
||||
}],
|
||||
'defer_parse': True,
|
||||
})
|
||||
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
|
||||
assert task.shipping_case_id != original_case.id
|
||||
assert task.duplicate_source_task_id == original.id
|
||||
assert ShippingCase.query.count() == 2
|
||||
@@ -855,11 +855,11 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
|
||||
assert candidate.content_fingerprint == revision['content_fingerprint']
|
||||
assert candidate.content_fingerprint != content['fingerprint']
|
||||
|
||||
hub_changed = {
|
||||
source_type_changed = {
|
||||
**base,
|
||||
'lines': [{**base['lines'][0], 'hub_code': 'DUB'}],
|
||||
'lines': [{**base['lines'][0], 'source_type': 'DBS DUB'}],
|
||||
}
|
||||
assert build_content_fingerprint(hub_changed)['fingerprint'] != content['fingerprint']
|
||||
assert build_content_fingerprint(source_type_changed)['fingerprint'] != content['fingerprint']
|
||||
|
||||
header_date_changed = {**base, 'required_date': '2026-07-20'}
|
||||
assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint']
|
||||
|
||||
@@ -151,8 +151,8 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
|
||||
assert rows[0]['source_type'] == 'VMI-FRA01'
|
||||
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
|
||||
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
|
||||
assert rows[0]['hub_code'] == 'FRA01'
|
||||
assert rows[2]['hub_code'] == 'DUB'
|
||||
assert 'hub_code' not in rows[0]
|
||||
assert 'hub_code' not in rows[2]
|
||||
|
||||
fused = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
@@ -168,7 +168,7 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
|
||||
assert not fused['conflicts']
|
||||
assert line['source_type'] == 'VMI-FRA01'
|
||||
assert line['customer_sku'] == 'TEMP-S000218922'
|
||||
assert line['hub_code'] == 'FRA01'
|
||||
assert 'hub_code' not in line
|
||||
|
||||
conflict = merge_attachment_candidate(
|
||||
attachment_summary={
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
"""shipping_notice 库存快照 TTL 复用测试。"""
|
||||
"""
|
||||
backend/tests/test_shipping_notice_inventory_snapshot_reuse.py
|
||||
|
||||
用途:验证库存连接器身份下的快照 TTL、动态库位与任务复用规则。
|
||||
依赖:ShippingTask、inventory_snapshot_store、inventory_sources、测试 Excel 夹具。
|
||||
逻辑:构造稳定 inventory_connector_type 身份并检查快照查找、绑定和过期行为。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
@@ -27,7 +33,7 @@ def _task_with_inventory_source(
|
||||
task_no: str,
|
||||
*,
|
||||
source_code: str,
|
||||
source_type: str | None = None,
|
||||
connector_type: str | None = None,
|
||||
site_id: str | None = None,
|
||||
warehouse_id: str = "",
|
||||
) -> ShippingTask:
|
||||
@@ -42,8 +48,8 @@ def _task_with_inventory_source(
|
||||
task.inventory_site_id = site_id
|
||||
if warehouse_id:
|
||||
task.inventory_warehouse_id = warehouse_id
|
||||
if source_type:
|
||||
task.inventory_source_type = source_type
|
||||
if connector_type:
|
||||
task.inventory_connector_type = connector_type
|
||||
return task
|
||||
|
||||
|
||||
@@ -90,7 +96,7 @@ def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path):
|
||||
task = _task_with_inventory_source(
|
||||
"SN-SNAPSHOT-SITE",
|
||||
source_code="DSV360_AWSBI_BYAWSATL01",
|
||||
source_type="dsv360",
|
||||
connector_type="dsv360",
|
||||
site_id="AWSBI",
|
||||
warehouse_id="BYAWSATL01",
|
||||
)
|
||||
@@ -169,7 +175,7 @@ def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path):
|
||||
task = _task_with_inventory_source(
|
||||
"SN-SNAPSHOT-MISMATCH",
|
||||
source_code="DSV360_AWSAMS",
|
||||
source_type="dsv360",
|
||||
connector_type="dsv360",
|
||||
site_id="AWSAMS",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -209,7 +215,7 @@ def test_link_snapshot_writes_audit_fields(app, tmp_path):
|
||||
task = _task_with_inventory_source(
|
||||
"SN-SNAPSHOT-LINK",
|
||||
source_code="DSV360_AWSDU",
|
||||
source_type="dsv360",
|
||||
connector_type="dsv360",
|
||||
site_id="AWSDU",
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.services.shipping_notice.inventory_source_gate import is_inventory_sour
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
adjudicate_inventory_source,
|
||||
confirm_inventory_source_by_code,
|
||||
extract_destination_candidates,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
apply_inventory_mapping,
|
||||
@@ -466,6 +467,35 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
|
||||
assert adjudication.warehouse_id == "TZR2"
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_line_source_type_matches_alias_without_using_task_source_type(app):
|
||||
"""orders[].lines[].source_type 应命中 match_aliases,Task.source_type 接入来源不得参与裁决。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-GATE-LINE-SOURCE-TYPE",
|
||||
source_type="TZR2",
|
||||
process_status="parsed",
|
||||
lines_json=[
|
||||
{
|
||||
"sku": "A001",
|
||||
"qty": 1,
|
||||
"reservation_id": "R-100",
|
||||
"source_type": "DBS DUB",
|
||||
},
|
||||
],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
candidates = extract_destination_candidates(task)
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
|
||||
assert "DBS DUB" in candidates
|
||||
assert "TZR2" not in candidates
|
||||
assert adjudication.status == "resolved"
|
||||
assert adjudication.source_code == "DSV360_AWSDU"
|
||||
|
||||
|
||||
@pytest.mark.inventory_source_gate
|
||||
def test_crane_user_confirm_and_gate_stable(app):
|
||||
"""Crane 人工确认后应写入完整身份并通过门禁。"""
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
"""shipping_notice inventory_sources YAML/JSON 配置加载与校验测试。"""
|
||||
"""
|
||||
backend/tests/test_shipping_notice_inventory_sources_config.py
|
||||
|
||||
用途:验证库存连接器 YAML/JSON 配置加载、校验与缓存刷新。
|
||||
依赖:inventory_sources、pytest tmp_path/app 夹具。
|
||||
逻辑:以 connector_type 配置样本覆盖 DSV/Crane 身份约束及 worker 兼容 query。
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
@@ -19,7 +25,7 @@ def test_inventory_sources_yaml_loads(app):
|
||||
reload_inventory_sources_config()
|
||||
source = get_inventory_source("DSV360_AWSDU")
|
||||
assert source is not None
|
||||
assert source["source_type"] == "dsv360"
|
||||
assert source["connector_type"] == "dsv360"
|
||||
assert source["site_id"] == "AWSDU"
|
||||
assert source["warehouse_id"] == "AWSDU"
|
||||
assert source["query"]["program_label"]
|
||||
@@ -64,8 +70,8 @@ def test_duplicate_source_code_raises(app, tmp_path):
|
||||
{
|
||||
"version": 1,
|
||||
"sources": [
|
||||
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
|
||||
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
|
||||
{"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
|
||||
{"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
|
||||
]
|
||||
}
|
||||
""",
|
||||
@@ -86,7 +92,7 @@ version: 1
|
||||
sources:
|
||||
- source_code: DSV360_BAD
|
||||
enabled: true
|
||||
source_type: dsv360
|
||||
connector_type: dsv360
|
||||
warehouse_id: AWSBI
|
||||
entry_url: http://x
|
||||
navigation: {}
|
||||
@@ -109,7 +115,7 @@ version: 1
|
||||
sources:
|
||||
- source_code: DSV360_BAD
|
||||
enabled: true
|
||||
source_type: dsv360
|
||||
connector_type: dsv360
|
||||
site_id: AWSBI
|
||||
entry_url: http://x
|
||||
navigation: {}
|
||||
@@ -129,7 +135,7 @@ def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app):
|
||||
reload_inventory_sources_config()
|
||||
payload = build_rpa_inventory_source("CRANE")
|
||||
assert payload is not None
|
||||
assert payload["source_type"] == "crane_footprint"
|
||||
assert payload["connector_type"] == "crane_footprint"
|
||||
assert payload["site_id"] == "CRANE"
|
||||
assert payload["warehouse_id"] == ""
|
||||
assert payload["warehouse_resolution"] == "alias_match"
|
||||
@@ -163,7 +169,7 @@ version: 1
|
||||
sources:
|
||||
- source_code: CACHE_TEST
|
||||
enabled: true
|
||||
source_type: dsv360
|
||||
connector_type: dsv360
|
||||
site_id: S1
|
||||
warehouse_id: W1
|
||||
entry_url: http://example.com
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
tests/test_shipping_notice_openapi_contract.py
|
||||
|
||||
用途:锁定发货通知订单行路由线索与库存连接器 OpenAPI 命名契约。
|
||||
依赖:Flask 测试 client、静态 Dify OpenAPI JSON。
|
||||
逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
"""
|
||||
校验订单行与库存连接器的字段边界。
|
||||
|
||||
核心逻辑:订单行保留可选 source_type 且不暴露 hub_code;任务状态说明使用
|
||||
inventory_connector_type,并拒绝旧 inventory_source_type 命名。
|
||||
|
||||
Args:
|
||||
spec: 动态接口或静态快照读取出的 OpenAPI 对象。
|
||||
|
||||
Returns:
|
||||
None;契约不符时由 pytest assertion 报错。
|
||||
"""
|
||||
order_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][
|
||||
"application/json"
|
||||
]["schema"]["properties"]["orders"]["items"]
|
||||
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
|
||||
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type"}
|
||||
assert "可选订单路由线索" in line_properties["source_type"]["description"]
|
||||
|
||||
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
|
||||
assert "inventory_connector_type" in status_description
|
||||
assert "inventory_source_type" not in status_description
|
||||
|
||||
confirm_description = spec["paths"]["/tools/confirm_inventory_source"]["post"]["description"]
|
||||
assert "connector_type" in confirm_description
|
||||
assert "source_code、source_type" not in confirm_description
|
||||
|
||||
|
||||
def test_dynamic_openapi_uses_connector_contract(app, client) -> None:
|
||||
"""
|
||||
校验公开 OpenAPI 接口使用新的连接器命名。
|
||||
|
||||
核心逻辑:通过 Flask 路由获取 builder 实时结果,再复用统一契约断言。
|
||||
|
||||
Args:
|
||||
app: pytest Flask 应用 fixture。
|
||||
client: pytest Flask 测试客户端 fixture。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
|
||||
response = client.get("/api/shipping-notice/tools/openapi.json")
|
||||
|
||||
assert response.status_code == 200
|
||||
_assert_connector_contract(response.get_json())
|
||||
|
||||
|
||||
def test_static_openapi_uses_connector_contract() -> None:
|
||||
"""
|
||||
校验仓库脚本生成的 Dify 静态快照与动态契约一致。
|
||||
|
||||
核心逻辑:读取 docs/openapi 下的 JSON,并复用统一契约断言。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json"
|
||||
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
||||
|
||||
_assert_connector_contract(spec)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,10 @@
|
||||
"""rpa.py 按需 trigger 包装测试。"""
|
||||
"""
|
||||
backend/tests/test_shipping_notice_rpa_trigger_for_task.py
|
||||
|
||||
用途:验证按需库存导出在 batch 与 legacy 模式下生成正确 trigger。
|
||||
依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。
|
||||
逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
|
||||
|
||||
@@ -11,7 +17,7 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
|
||||
|
||||
source = {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"connector_type": "dsv360",
|
||||
"warehouse_id": "AWSDU",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"parameters": [],
|
||||
@@ -38,7 +44,7 @@ def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
with app.app_context():
|
||||
path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
|
||||
assert path
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_tools.py
|
||||
|
||||
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
|
||||
依赖:Flask 测试客户端、ShippingTask/Customer、货代 workflow 测试辅助。
|
||||
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ChatLog, ShippingCustomer, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
|
||||
@@ -18,6 +26,34 @@ def _tool_headers(app):
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch):
|
||||
"""为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。"""
|
||||
from app.services.shipping_notice import task_workflow
|
||||
|
||||
original = task_workflow.resolve_shipping_case_for_new_task
|
||||
|
||||
def _resolve_confirmed_case(**kwargs):
|
||||
case = original(**kwargs)
|
||||
if case.customer_id is not None:
|
||||
return case
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name="Tool 流程测试客户",
|
||||
short_code="TST",
|
||||
status="active",
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
case.customer_id = customer.id
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
return case
|
||||
|
||||
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
|
||||
|
||||
|
||||
def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None:
|
||||
"""测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。"""
|
||||
client.post(
|
||||
@@ -127,7 +163,6 @@ def test_shipping_notice_tool_flow(app, client):
|
||||
"qty": 10,
|
||||
"uom": "EA",
|
||||
"source_type": "AWS Dublin",
|
||||
"hub_code": "DUB",
|
||||
}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
@@ -780,21 +815,20 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
|
||||
wb.save(inv_file)
|
||||
wb.close()
|
||||
|
||||
cb_res = client.post(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_no": task_id,
|
||||
"success": True,
|
||||
"file_path": str(inv_file),
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
with app.app_context():
|
||||
data = shipping_tools.rpa_report_inventory(
|
||||
{
|
||||
"task_no": task_id,
|
||||
"success": True,
|
||||
"file_path": str(inv_file),
|
||||
"run_no": "RUN-TOOLS-CB",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"site_id": "AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
},
|
||||
)
|
||||
assert cb_res.status_code == 200
|
||||
data = cb_res.get_json()
|
||||
"site_id": "AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
}
|
||||
)
|
||||
assert data["status"] == "needs_human"
|
||||
assert data.get("checkpoint") in {"map_infer", "align_review"}
|
||||
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
|
||||
@@ -1567,6 +1601,7 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
|
||||
|
||||
def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch):
|
||||
import app.services.shipping_notice.decision_workflow as decision_workflow
|
||||
import app.services.shipping_notice.task_workflow as task_workflow
|
||||
|
||||
headers = _tool_headers(app)
|
||||
called: dict[str, str] = {}
|
||||
@@ -1576,6 +1611,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
|
||||
monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda _task_no: False)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
@@ -1630,16 +1666,15 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
confirm_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
|
||||
)
|
||||
confirm_data = confirm_res.get_json()
|
||||
assert confirm_data["status"] == "running"
|
||||
assert "后台继续处理匹配与后续步骤" in confirm_data["message"]
|
||||
assert called.get("task_no") == task_id
|
||||
persisted = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert persisted is not None
|
||||
assert persisted.review_status == "align_review"
|
||||
confirm_data = decision_workflow.submit_decision(
|
||||
{"task_id": task_id, "decision": "confirm_inventory_mapping"}
|
||||
)
|
||||
assert confirm_data["status"] == "running"
|
||||
assert "后台继续处理匹配与后续步骤" in confirm_data["message"]
|
||||
assert called.get("task_no") == task_id
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
@@ -1682,7 +1717,7 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"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"},
|
||||
@@ -1692,12 +1727,10 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
|
||||
task.process_status = "parsed"
|
||||
db.session.commit()
|
||||
|
||||
retry_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "retry_rpa"},
|
||||
)
|
||||
retry_data = retry_res.get_json()
|
||||
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"}
|
||||
|
||||
@@ -1750,7 +1783,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"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"},
|
||||
@@ -1813,7 +1846,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"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"},
|
||||
@@ -1833,12 +1866,10 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
retry_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "retry_rpa"},
|
||||
)
|
||||
retry_data = retry_res.get_json()
|
||||
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
|
||||
|
||||
@@ -1894,7 +1925,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_type": "dsv360",
|
||||
"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"},
|
||||
|
||||
@@ -86,6 +86,83 @@ def test_chat_messages_history(client):
|
||||
assert msgs[1]['content'] == 'Hello'
|
||||
|
||||
|
||||
def test_chat_messages_restore_user_attachments_without_leaking_into_assistant_payload(client):
|
||||
"""历史回放应把附件放回用户消息,并从助手 payload 中剥离内部 user_attachments。"""
|
||||
headers = get_headers(client)
|
||||
with client.application.app_context():
|
||||
user = User.query.filter_by(username='testuser').first()
|
||||
agent = Agent.query.filter_by(name='Test Agent').first()
|
||||
db.session.add(ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id='conv-attachments',
|
||||
query='总结附件',
|
||||
answer='已完成总结',
|
||||
payload={
|
||||
'existing_key': 'kept',
|
||||
'user_attachments': [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
'url': 'https://example.com/secret',
|
||||
}],
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/chat/messages?conversation_id=conv-attachments&agent_id=1', headers=headers)
|
||||
|
||||
assert res.status_code == 200
|
||||
messages = res.get_json()
|
||||
assert messages[0] == {
|
||||
'role': 'user',
|
||||
'content': '总结附件',
|
||||
'attachments': [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}],
|
||||
}
|
||||
assert messages[1]['payload'] == {'existing_key': 'kept'}
|
||||
|
||||
|
||||
def test_chat_messages_do_not_create_empty_assistant_for_attachment_only_payload(client):
|
||||
"""仅含用户附件 payload 且无回答时,不应额外回放空助手消息。"""
|
||||
headers = get_headers(client)
|
||||
with client.application.app_context():
|
||||
user = User.query.filter_by(username='testuser').first()
|
||||
agent = Agent.query.filter_by(name='Test Agent').first()
|
||||
db.session.add(ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id='conv-attachment-only',
|
||||
query='',
|
||||
answer='',
|
||||
payload={'user_attachments': [{
|
||||
'id': 'attachment-only-1',
|
||||
'name': 'notice.eml',
|
||||
'type': 'document',
|
||||
'source': 'shipping_notice',
|
||||
}]},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/chat/messages?conversation_id=conv-attachment-only&agent_id=1', headers=headers)
|
||||
|
||||
assert res.status_code == 200
|
||||
messages = res.get_json()
|
||||
assert len(messages) == 1
|
||||
assert messages[0]['role'] == 'user'
|
||||
assert messages[0]['content'] == ''
|
||||
assert messages[0]['attachments'][0]['name'] == 'notice.eml'
|
||||
|
||||
|
||||
def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
|
||||
"""助手本地消息即使误传 query,历史回放也不能多生成一条用户确认。"""
|
||||
headers = get_headers(client)
|
||||
|
||||
Reference in new issue
Block a user