feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认

This commit is contained in:
hugo committed 2026-07-16 08:16:19 +08:00
1 parent b595e157e9
commit 4fbaed2b4c
176 files changed
+14011 -994

No files matched your search

@@ -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