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

+4
View File
@@ -14,6 +14,8 @@ from . import (
guide_service,
permission_service,
report_service,
shipping_customer_import_service,
shipping_customer_service,
user_service,
wecom_admin_service,
)
@@ -28,6 +30,8 @@ __all__ = [
'guide_service',
'permission_service',
'report_service',
'shipping_customer_import_service',
'shipping_customer_service',
'user_service',
'wecom_admin_service',
]
@@ -0,0 +1,706 @@
"""
services/admin/shipping_customer_import_service.py
用途:货代期初客户 Excel 模板、上传预检、行级决策、单事务发布与对账。
依赖:openpyxl、客户/导入模型、shipping_customer_service、customer_normalization。
逻辑:上传仅落暂存;发布前阻断错误与未决警告,正式客户及识别证据在一个事务内写入。
"""
from __future__ import annotations
import csv
import hashlib
import io
import uuid
from datetime import date, datetime, time
from typing import Any
from openpyxl import Workbook, load_workbook
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerImportBatch,
ShippingCustomerImportRow,
)
from app.services.admin.shipping_customer_service import serialize_customer
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_customer_name,
normalize_identifier,
normalize_short_code,
)
MAX_IMPORT_BYTES = 5 * 1024 * 1024
MAX_IMPORT_ROWS = 10_000
CUSTOMER_HEADERS = ('legacy_customer_key', 'standard_name', 'short_code', 'status', 'source_system', 'remark')
IDENTIFIER_HEADERS = (
'legacy_customer_key',
'source_system',
'identifier_type',
'identifier_value',
'auto_match_allowed',
'remark',
)
ROW_DECISIONS = frozenset({'create', 'update', 'merge', 'skip'})
def generate_import_batch_no() -> str:
"""生成客户导入批次号。"""
return f"SCI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def build_import_template() -> bytes:
"""生成包含 customers/identifiers 两个 Sheet 的标准期初导入模板。"""
wb = Workbook()
customers = wb.active
customers.title = 'customers'
customers.append(CUSTOMER_HEADERS)
customers.append(('INIT-000001', '无锡宇辰有限公司', 'WYC', 'active', 'INITIAL_EXCEL', '示例行,可删除'))
identifiers = wb.create_sheet('identifiers')
identifiers.append(IDENTIFIER_HEADERS)
identifiers.append(('INIT-000001', 'INITIAL_EXCEL', 'name_alias', 'WUXI YUCHEN', False, '历史英文名称'))
output = io.BytesIO()
wb.save(output)
return output.getvalue()
def _cell_bool(value: Any) -> bool:
"""将 Excel 常见真假写法转换为 bool。"""
if isinstance(value, bool):
return value
return clean_text(value).lower() in {'1', 'true', 'yes', 'y', '是'}
def _json_safe_cell(value: Any) -> Any:
"""将 Excel 单元格转换为 JSON 可持久化值,日期时间使用 ISO 8601。"""
if value is None or isinstance(value, (str, int, float, bool)):
return value
if isinstance(value, (datetime, date, time)):
return value.isoformat()
return str(value)
def _sheet_rows(workbook, sheet_name: str, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
"""校验 Sheet 表头并返回非空数据行。"""
if sheet_name not in workbook.sheetnames:
raise ValidationError(
f'Missing sheet: {sheet_name}',
code='SHIPPING.CUSTOMER_IMPORT_SHEET_MISSING',
details={'sheet': sheet_name},
)
sheet = workbook[sheet_name]
actual = tuple(clean_text(cell.value) for cell in sheet[1])
missing = [header for header in headers if header not in actual]
if missing:
raise ValidationError(
'Customer import columns missing',
code='SHIPPING.CUSTOMER_IMPORT_COLUMNS_MISSING',
details={'sheet': sheet_name, 'missing': missing},
)
positions = {header: actual.index(header) for header in headers}
result: list[tuple[int, dict[str, Any]]] = []
for row_no, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
if not any(value not in (None, '') for value in values):
continue
result.append((row_no, {header: values[index] if index < len(values) else None for header, index in positions.items()}))
if len(result) > MAX_IMPORT_ROWS:
raise ValidationError(
'Customer import contains too many rows',
code='SHIPPING.CUSTOMER_IMPORT_TOO_MANY_ROWS',
details={'sheet': sheet_name, 'max_rows': MAX_IMPORT_ROWS},
)
return result
def _existing_customer_by_ref(source_system: str, legacy_key: str) -> ShippingCustomer | None:
"""按外部来源稳定键查找已导入客户。"""
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=legacy_key,
).first()
return db.session.get(ShippingCustomer, ref.customer_id) if ref else None
def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
"""预检单条 customers 行,返回标准化字段、错误、警告和建议动作。"""
errors: list[dict[str, Any]] = []
warnings: list[dict[str, Any]] = []
legacy_key = clean_text(raw.get('legacy_customer_key'))
name = clean_text(raw.get('standard_name'))
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
status = clean_text(raw.get('status') or 'active').lower()
short_code = ''
if not legacy_key:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
elif len(legacy_key) > 128:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
if not name:
errors.append({'code': 'SHIPPING.CUSTOMER_NAME_REQUIRED', 'field': 'standard_name'})
elif len(name) > 200:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG', 'field': 'standard_name'})
if not source_system or len(source_system) > 64:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
try:
short_code = normalize_short_code(raw.get('short_code'))
except ValidationError as exc:
errors.append({'code': exc.code, 'field': 'short_code'})
if status not in {'active', 'inactive'}:
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
'customer_id': code_owner.id,
'short_code': short_code,
})
normalized_name = normalize_customer_name(name)
similar = [
item for item in db.session.query(ShippingCustomer).all()
if normalize_customer_name(item.standard_name) == normalized_name and (not existing_ref or item.id != existing_ref.id)
] if normalized_name else []
if similar:
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_MATCH',
'candidate_customer_ids': [item.id for item in similar],
})
suggested_action = 'update' if existing_ref else 'create'
target_customer_id = existing_ref.id if existing_ref else None
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
return {
'legacy_customer_key': legacy_key or None,
'normalized': {
'legacy_customer_key': legacy_key,
'standard_name': name,
'short_code': short_code,
'status': status,
'source_system': source_system,
'remark': clean_text(raw.get('remark')),
},
'errors': errors,
'warnings': warnings,
'validation_status': validation_status,
'suggested_action': suggested_action,
'target_customer_id': target_customer_id,
}
def _identifier_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
"""预检单条 identifiers 行,补齐来源系统并将公共邮箱证据降级为人工匹配。"""
errors: list[dict[str, Any]] = []
warnings: list[dict[str, Any]] = []
legacy_key = clean_text(raw.get('legacy_customer_key'))
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
kind = clean_text(raw.get('identifier_type')).lower()
value = clean_text(raw.get('identifier_value'))
auto_allowed = _cell_bool(raw.get('auto_match_allowed'))
normalized = ''
if not legacy_key:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
elif len(legacy_key) > 128:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
if not source_system or len(source_system) > 64:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
try:
normalized = normalize_identifier(kind, value)
except ValidationError as exc:
errors.append({'code': exc.code, 'field': 'identifier_value'})
if kind in {'domain', 'email'} and normalized and is_public_email_domain(normalized):
if auto_allowed:
warnings.append({'code': 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN'})
auto_allowed = False
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
return {
'legacy_customer_key': legacy_key or None,
'normalized': {
'legacy_customer_key': legacy_key,
'source_system': source_system,
'identifier_type': kind,
'identifier_value': value,
'normalized_value': normalized,
'auto_match_allowed': auto_allowed,
'remark': clean_text(raw.get('remark')),
},
'errors': errors,
'warnings': warnings,
'validation_status': validation_status,
'suggested_action': 'create',
'target_customer_id': None,
}
def serialize_import_row(row: ShippingCustomerImportRow) -> dict[str, Any]:
"""序列化导入暂存行。"""
return {
'id': row.id,
'sheet_name': row.sheet_name,
'row_no': row.row_no,
'row_type': row.row_type,
'legacy_customer_key': row.legacy_customer_key,
'raw': row.raw_json or {},
'normalized': row.normalized_json or {},
'validation_status': row.validation_status,
'errors': row.errors_json or [],
'warnings': row.warnings_json or [],
'suggested_action': row.suggested_action,
'decision_action': row.decision_action,
'target_customer_id': row.target_customer_id,
'decision_note': row.decision_note,
'result_customer_id': row.result_customer_id,
'result_status': row.result_status,
'result_message': row.result_message,
}
def serialize_import_batch(batch: ShippingCustomerImportBatch, *, include_rows: bool = True) -> dict[str, Any]:
"""序列化导入批次及统计。"""
payload: dict[str, Any] = {
'id': batch.id,
'batch_no': batch.batch_no,
'file_name': batch.file_name,
'file_hash': batch.file_hash,
'file_size': batch.file_size,
'source_system': batch.source_system,
'status': batch.status,
'total_rows': batch.total_rows,
'valid_rows': batch.valid_rows,
'warning_rows': batch.warning_rows,
'error_rows': batch.error_rows,
'published_rows': batch.published_rows,
'uploaded_by_id': batch.uploaded_by_id,
'published_by_id': batch.published_by_id,
'published_at': batch.published_at.isoformat() if batch.published_at else None,
'created_at': batch.created_at.isoformat() if batch.created_at else None,
}
if include_rows:
payload['rows'] = [serialize_import_row(row) for row in batch.rows]
return payload
def create_import_batch(upload: Any, *, source_system: str, actor_id: int | None) -> dict[str, Any]:
"""
上传并预检客户期初 Excel。
Args:
upload: Flask FileStorage,仅支持 .xlsx,最大 5 MB。
source_system: 默认来源系统;行内可覆盖。
actor_id: 上传管理员 ID。
Returns:
导入批次详情;同文件哈希重复上传返回原批次并标记 idempotent_replay。
"""
filename = clean_text(getattr(upload, 'filename', ''))
if not filename.lower().endswith('.xlsx'):
raise ValidationError('Only .xlsx customer import files are supported', code='SHIPPING.CUSTOMER_IMPORT_FILE_TYPE_INVALID')
content = upload.read() if hasattr(upload, 'read') else b''
if not content:
raise ValidationError('Customer import file is empty', code='SHIPPING.CUSTOMER_IMPORT_FILE_EMPTY')
if len(content) > MAX_IMPORT_BYTES:
raise ValidationError(
'Customer import file is too large',
code='SHIPPING.CUSTOMER_IMPORT_FILE_TOO_LARGE',
details={'max_bytes': MAX_IMPORT_BYTES},
)
normalized_source = clean_text(source_system).upper() or 'INITIAL_EXCEL'
if len(normalized_source) > 64:
raise ValidationError(
'Customer import source system is too long',
code='SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID',
details={'field': 'source_system', 'max_length': 64},
)
file_hash = hashlib.sha256(content).hexdigest()
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
file_hash=file_hash,
source_system=normalized_source,
).first()
if existing:
result = serialize_import_batch(existing)
result['idempotent_replay'] = True
return result
try:
workbook = load_workbook(io.BytesIO(content), data_only=True, read_only=True)
except Exception as exc:
raise ValidationError(
'Invalid customer import Excel file',
code='SHIPPING.CUSTOMER_IMPORT_FILE_INVALID',
details={'error_type': type(exc).__name__},
) from exc
try:
customer_rows = _sheet_rows(workbook, 'customers', CUSTOMER_HEADERS)
identifier_rows = _sheet_rows(workbook, 'identifiers', IDENTIFIER_HEADERS)
finally:
workbook.close()
batch = ShippingCustomerImportBatch(
batch_no=generate_import_batch_no(),
file_name=filename,
file_hash=file_hash,
file_size=len(content),
source_system=normalized_source,
uploaded_by_id=actor_id,
status='validated',
)
db.session.add(batch)
staged: list[ShippingCustomerImportRow] = []
try:
db.session.flush()
seen_keys: set[tuple[str, str]] = set()
order = 0
for sheet_name, row_type, rows, validator in (
(
'customers',
'customer',
customer_rows,
lambda raw: _customer_row_validation(raw, default_source_system=normalized_source),
),
(
'identifiers',
'identifier',
identifier_rows,
lambda raw: _identifier_row_validation(raw, default_source_system=normalized_source),
),
):
for row_no, raw in rows:
order += 1
result = validator(raw)
errors = list(result['errors'])
normalized = result['normalized']
if row_type == 'customer':
key = (normalized.get('source_system') or '', normalized.get('legacy_customer_key') or '')
if key in seen_keys:
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_DUPLICATE_KEY'})
result['validation_status'] = 'error'
seen_keys.add(key)
staged.append(ShippingCustomerImportRow(
batch_id=batch.id,
sheet_name=sheet_name,
row_no=row_no,
row_order=order,
row_type=row_type,
legacy_customer_key=result['legacy_customer_key'],
raw_json={key: _json_safe_cell(value) for key, value in raw.items()},
normalized_json=normalized,
validation_status=result['validation_status'],
errors_json=errors,
warnings_json=result['warnings'],
suggested_action=result['suggested_action'],
target_customer_id=result['target_customer_id'],
))
customer_sources_by_key: dict[str, set[str]] = {}
for row in staged:
if row.row_type != 'customer' or not row.legacy_customer_key or row.validation_status == 'error':
continue
customer_sources_by_key.setdefault(row.legacy_customer_key, set()).add(
clean_text((row.normalized_json or {}).get('source_system')).upper()
)
for row in staged:
if row.row_type != 'identifier' or not row.legacy_customer_key:
continue
raw_source = clean_text((row.raw_json or {}).get('source_system')).upper()
candidate_sources = customer_sources_by_key.get(row.legacy_customer_key) or set()
if not raw_source and len(candidate_sources) == 1:
row.normalized_json = {
**(row.normalized_json or {}),
'source_system': next(iter(candidate_sources)),
}
customer_keys = {
(
clean_text((row.normalized_json or {}).get('source_system')).upper(),
row.legacy_customer_key,
)
for row in staged
if row.row_type == 'customer' and row.legacy_customer_key and row.validation_status != 'error'
}
for row in staged:
if row.row_type != 'identifier' or not row.legacy_customer_key:
continue
source_system = clean_text((row.normalized_json or {}).get('source_system')).upper()
if (source_system, row.legacy_customer_key) not in customer_keys:
existing_ref = db.session.query(ShippingCustomerExternalRef.id).filter_by(
source_system=source_system,
legacy_customer_key=row.legacy_customer_key,
).first()
if not existing_ref:
row.errors_json = [
*(row.errors_json or []),
{'code': 'SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING'},
]
row.validation_status = 'error'
db.session.add_all(staged)
batch.total_rows = len(staged)
batch.valid_rows = sum(row.validation_status == 'valid' for row in staged)
batch.warning_rows = sum(row.validation_status == 'warning' for row in staged)
batch.error_rows = sum(row.validation_status == 'error' for row in staged)
db.session.commit()
except ValidationError:
db.session.rollback()
raise
except IntegrityError as exc:
db.session.rollback()
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
file_hash=file_hash,
source_system=normalized_source,
).first()
if existing is not None:
result = serialize_import_batch(existing)
result['idempotent_replay'] = True
return result
raise ConflictError(
'Customer import upload conflict',
code='SHIPPING.CUSTOMER_IMPORT_UPLOAD_CONFLICT',
) from exc
except Exception:
db.session.rollback()
raise
return serialize_import_batch(batch)
def get_import_batch(batch_id: int) -> dict[str, Any]:
"""读取导入批次详情。"""
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
return serialize_import_batch(batch)
def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""保存警告行的新增、更新/合并或跳过决定。"""
row = db.session.get(ShippingCustomerImportRow, row_id)
if row is None:
raise NotFoundError('Customer import row not found', code='SHIPPING.CUSTOMER_IMPORT_ROW_NOT_FOUND')
if row.batch.status == 'published':
raise ConflictError('Published import rows cannot be changed', code='SHIPPING.CUSTOMER_IMPORT_ALREADY_PUBLISHED')
if row.validation_status == 'error':
raise ValidationError(
'Rows with validation errors cannot be decided',
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
details={'row_id': row.id},
)
action = clean_text(data.get('action')).lower()
if action not in ROW_DECISIONS:
raise ValidationError('Invalid import row decision', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
target_id = data.get('target_customer_id')
if row.row_type == 'identifier' and action not in {'create', 'skip'}:
raise ValidationError(
'Identifier warning rows only support create or skip',
code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID',
)
if row.row_type == 'customer' and action in {'update', 'merge'}:
try:
target_id = int(target_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Target customer is required', code='SHIPPING.CUSTOMER_IMPORT_TARGET_REQUIRED') from exc
if db.session.get(ShippingCustomer, target_id) is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
else:
target_id = None
row.decision_action = action
row.target_customer_id = target_id
row.decision_note = clean_text(data.get('note')) or None
db.session.commit()
return serialize_import_row(row)
def _effective_action(row: ShippingCustomerImportRow) -> str:
"""返回发布时实际动作;警告行必须显式决策。"""
if row.validation_status == 'error':
return ''
if row.validation_status == 'warning':
return clean_text(row.decision_action).lower()
return clean_text(row.decision_action or row.suggested_action).lower()
def _upsert_external_ref(customer_id: int, *, source_system: str, legacy_key: str) -> None:
"""创建或校验客户外部来源键;禁止同一来源键静默改绑。"""
existing = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=legacy_key,
).first()
if existing:
if existing.customer_id != customer_id:
raise ConflictError(
'Customer external reference is already bound',
code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT',
)
return
db.session.add(ShippingCustomerExternalRef(
customer_id=customer_id,
source_system=source_system,
legacy_customer_key=legacy_key,
))
def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""
单事务发布已预检的客户导入批次。
Raises:
ValidationError: 存在错误行或未决警告。
ConflictError: 批次已发布或发布时唯一约束冲突。
"""
batch = (
db.session.query(ShippingCustomerImportBatch)
.filter(ShippingCustomerImportBatch.id == batch_id)
.with_for_update()
.one_or_none()
)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
if batch.status == 'published':
result = serialize_import_batch(batch)
result['idempotent_replay'] = True
return result
if any(row.validation_status == 'error' for row in batch.rows):
raise ValidationError(
'Customer import contains blocking errors',
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
details={'error_rows': batch.error_rows},
)
unresolved = [row.id for row in batch.rows if row.validation_status == 'warning' and not row.decision_action]
if unresolved:
raise ValidationError(
'Customer import warnings require decisions',
code='SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED',
details={'row_ids': unresolved},
)
customer_by_key: dict[tuple[str, str], ShippingCustomer] = {}
published = 0
try:
# [STEP 1] 先发布客户行并建立外部来源键,供 identifiers Sheet 稳定关联。
for row in [item for item in batch.rows if item.row_type == 'customer']:
action = _effective_action(row)
if action == 'skip':
row.result_status = 'skipped'
row.result_message = 'Skipped by administrator'
continue
data = row.normalized_json or {}
target: ShippingCustomer | None = None
if action in {'update', 'merge'}:
target = db.session.get(ShippingCustomer, row.target_customer_id)
if target is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if action == 'update':
target.standard_name = data['standard_name']
target.short_code = data['short_code']
target.status = data['status']
target.remark = data.get('remark') or None
target.updated_by_id = actor_id
elif action == 'create':
target = ShippingCustomer(
standard_name=data['standard_name'],
short_code=data['short_code'],
status=data['status'],
remark=data.get('remark') or None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
db.session.add(target)
db.session.flush()
else:
raise ValidationError('Invalid import action', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
_upsert_external_ref(
target.id,
source_system=data['source_system'],
legacy_key=data['legacy_customer_key'],
)
customer_by_key[(data['source_system'], data['legacy_customer_key'])] = target
row.result_customer_id = target.id
row.result_status = 'published'
row.result_message = action
published += 1
# [STEP 2] 标识行只绑定已发布/既有客户;导入标识默认 approved,保留 source=imported。
for row in [item for item in batch.rows if item.row_type == 'identifier']:
action = _effective_action(row)
if action == 'skip':
row.result_status = 'skipped'
row.result_message = 'Skipped by administrator'
continue
data = row.normalized_json or {}
source_system = data.get('source_system') or batch.source_system
customer = customer_by_key.get((source_system, data.get('legacy_customer_key')))
if customer is None:
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source_system,
legacy_customer_key=data.get('legacy_customer_key'),
).first()
customer = db.session.get(ShippingCustomer, ref.customer_id) if ref else None
if customer is None:
raise ConflictError(
'Identifier customer mapping is missing',
code='SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING',
)
existing_identifier = db.session.query(ShippingCustomerIdentifier).filter_by(
customer_id=customer.id,
identifier_type=data['identifier_type'],
normalized_value=data['normalized_value'],
).first()
if existing_identifier is None:
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type=data['identifier_type'],
raw_value=data['identifier_value'],
normalized_value=data['normalized_value'],
auto_match_allowed=bool(data.get('auto_match_allowed')),
status='approved',
source='imported',
remark=data.get('remark') or None,
confirmed_by_id=actor_id,
confirmed_at=datetime.utcnow(),
))
row.result_customer_id = customer.id
row.result_status = 'published'
row.result_message = 'identifier_created' if existing_identifier is None else 'identifier_exists'
published += 1
batch.status = 'published'
batch.published_rows = published
batch.published_by_id = actor_id
batch.published_at = datetime.utcnow()
db.session.commit()
except AppError:
db.session.rollback()
raise
except (IntegrityError, ValueError) as exc:
db.session.rollback()
raise ConflictError(
'Customer import publish conflict',
code='SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT',
) from exc
except Exception:
db.session.rollback()
raise
return serialize_import_batch(batch)
def build_reconciliation_csv(batch_id: int) -> tuple[bytes, str]:
"""从持久化导入行生成可重复下载的 UTF-8 BOM 对账 CSV。"""
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
if batch is None:
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
output = io.StringIO(newline='')
writer = csv.writer(output)
writer.writerow([
'sheet_name', 'row_no', 'legacy_customer_key', 'validation_status', 'decision_action',
'result_status', 'result_customer_id', 'result_message', 'errors', 'warnings',
])
for row in batch.rows:
writer.writerow([
row.sheet_name,
row.row_no,
row.legacy_customer_key or '',
row.validation_status,
row.decision_action or row.suggested_action or '',
row.result_status or '',
row.result_customer_id or '',
row.result_message or '',
';'.join(str(item.get('code') or item) for item in (row.errors_json or [])),
';'.join(str(item.get('code') or item) for item in (row.warnings_json or [])),
])
return ('\ufeff' + output.getvalue()).encode('utf-8'), f'{batch.batch_no}_reconciliation.csv'
@@ -0,0 +1,342 @@
"""
services/admin/shipping_customer_service.py
用途:管理货代标准客户与已审核识别证据。
依赖:db、ShippingCustomer* 模型、customer_normalization、统一 AppError。
逻辑:管理 API 委托本服务完成校验、唯一性检查、停用与序列化;不承载运行期客户裁决。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import asc, desc, func, or_
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_identifier,
normalize_short_code,
)
CUSTOMER_STATUSES = frozenset({'active', 'inactive'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
def _strict_bool(value: Any, *, field: str) -> bool:
"""只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。"""
if isinstance(value, bool):
return value
if value is None:
return False
raise ValidationError(
f'{field} must be a boolean',
code='VALIDATION.INVALID_PARAM',
details={'field': field},
)
def serialize_identifier(record: ShippingCustomerIdentifier) -> dict[str, Any]:
"""序列化客户识别证据,供管理后台列表与详情共用。"""
return {
'id': record.id,
'customer_id': record.customer_id,
'identifier_type': record.identifier_type,
'raw_value': record.raw_value,
'normalized_value': record.normalized_value,
'auto_match_allowed': bool(record.auto_match_allowed),
'status': record.status,
'source': record.source,
'remark': record.remark,
'confirmed_by_id': record.confirmed_by_id,
'confirmed_at': record.confirmed_at.isoformat() if record.confirmed_at else None,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
}
def serialize_customer(
record: ShippingCustomer,
*,
include_identifiers: bool = False,
case_count: int | None = None,
identifier_count: int | None = None,
) -> dict[str, Any]:
"""
序列化标准客户,并可选附带识别证据和业务引用数量。
Args:
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
identifier_count: 列表查询预聚合的识别证据数量;为空时现场查询。
Returns:
管理端客户 JSON 字典。
"""
payload: dict[str, Any] = {
'id': record.id,
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
}
if include_identifiers:
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
return payload
def list_customers(params: dict[str, Any]) -> dict[str, Any]:
"""
分页列出标准客户。
Args:
params: 支持 q/status/page/page_size/sort/order。
Returns:
items、total、page、page_size、pages。
"""
case_counts = (
db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count'))
.group_by(ShippingCase.customer_id)
.subquery()
)
identifier_counts = (
db.session.query(
ShippingCustomerIdentifier.customer_id.label('customer_id'),
func.count(ShippingCustomerIdentifier.id).label('identifier_count'),
)
.group_by(ShippingCustomerIdentifier.customer_id)
.subquery()
)
query = (
db.session.query(
ShippingCustomer,
func.coalesce(case_counts.c.case_count, 0),
func.coalesce(identifier_counts.c.identifier_count, 0),
)
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
)
keyword = clean_text(params.get('q'))
status = clean_text(params.get('status')).lower()
if keyword:
like = f'%{keyword}%'
query = query.filter(or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like)))
if status:
if status not in CUSTOMER_STATUSES:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
query = query.filter(ShippingCustomer.status == status)
try:
page = max(1, int(params.get('page') or 1))
page_size = min(100, max(1, int(params.get('page_size') or 20)))
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid pagination') from exc
sort_map = {
'standard_name': ShippingCustomer.standard_name,
'short_code': ShippingCustomer.short_code,
'created_at': ShippingCustomer.created_at,
'updated_at': ShippingCustomer.updated_at,
}
sort_col = sort_map.get(clean_text(params.get('sort')).lower(), ShippingCustomer.updated_at)
order = asc if clean_text(params.get('order')).lower() == 'asc' else desc
total = query.count()
items = query.order_by(order(sort_col), ShippingCustomer.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
return {
'items': [
serialize_customer(customer, case_count=int(case_count), identifier_count=int(identifier_count))
for customer, case_count, identifier_count in items
],
'total': total,
'page': page,
'page_size': page_size,
'pages': max(1, (total + page_size - 1) // page_size),
}
def get_customer(customer_id: int) -> dict[str, Any]:
"""读取客户详情;不存在时抛出统一 NotFoundError。"""
record = db.session.get(ShippingCustomer, customer_id)
if record is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return serialize_customer(record, include_identifiers=True)
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
"""校验客户简码全局唯一。"""
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
if exclude_customer_id is not None:
query = query.filter(ShippingCustomer.id != exclude_customer_id)
if query.first():
raise ConflictError(
'Customer short code already exists',
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
details={'short_code': short_code},
)
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
创建标准客户。
Args:
data: standard_name、short_code、status、remark。
actor_id: 当前管理员 ID。
Returns:
新客户详情。
"""
standard_name = clean_text(data.get('standard_name'))
if not standard_name:
raise ValidationError(
'Customer standard name is required',
code='SHIPPING.CUSTOMER_NAME_REQUIRED',
details={'field': 'standard_name'},
)
short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(short_code)
status = clean_text(data.get('status') or 'active').lower()
if status not in CUSTOMER_STATUSES:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
record = ShippingCustomer(
standard_name=standard_name,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer already exists', code='SHIPPING.CUSTOMER_CONFLICT') from exc
return serialize_customer(record, include_identifiers=True)
def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新标准客户;历史业务号使用快照,不受简码修改影响。"""
record = db.session.get(ShippingCustomer, customer_id)
if record is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
raise ValidationError('Customer standard name is required', code='SHIPPING.CUSTOMER_NAME_REQUIRED')
record.standard_name = name
if 'short_code' in data:
short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(short_code, exclude_customer_id=customer_id)
record.short_code = short_code
if 'status' in data:
status = clean_text(data.get('status')).lower()
if status not in CUSTOMER_STATUSES:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
record.status = status
if 'remark' in data:
record.remark = clean_text(data.get('remark')) or None
record.updated_by_id = actor_id
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer update conflict', code='SHIPPING.CUSTOMER_CONFLICT') from exc
return serialize_customer(record, include_identifiers=True)
def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""停用客户;不物理删除,以保留业务单和识别审计。"""
return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id)
def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
新增客户识别证据。
核心逻辑:公共邮箱域名不得开启自动匹配;approved 状态写入审核人和时间。
"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
identifier_type = clean_text(data.get('identifier_type')).lower()
raw_value = clean_text(data.get('raw_value') or data.get('identifier_value'))
normalized_value = normalize_identifier(identifier_type, raw_value)
status = clean_text(data.get('status') or 'pending').lower()
if status not in IDENTIFIER_STATUSES:
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
auto_match_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
if identifier_type in {'domain', 'email'} and is_public_email_domain(normalized_value) and auto_match_allowed:
raise ValidationError(
'Public email domains cannot be used for automatic matching',
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
)
if status != 'approved' and auto_match_allowed:
raise ValidationError(
'Only approved identifiers can enable automatic matching',
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
)
record = ShippingCustomerIdentifier(
customer_id=customer.id,
identifier_type=identifier_type,
raw_value=raw_value,
normalized_value=normalized_value,
auto_match_allowed=auto_match_allowed,
status=status,
source=clean_text(data.get('source') or 'manual').lower(),
remark=clean_text(data.get('remark')) or None,
confirmed_by_id=actor_id if status == 'approved' else None,
confirmed_at=datetime.utcnow() if status == 'approved' else None,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError(
'Customer identifier already exists',
code='SHIPPING.CUSTOMER_IDENTIFIER_EXISTS',
) from exc
return serialize_identifier(record)
def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新识别证据;先校验最终状态,再一次性修改 ORM,避免失败后残留脏状态。"""
record = db.session.get(ShippingCustomerIdentifier, identifier_id)
if record is None:
raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND')
next_status = record.status
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in IDENTIFIER_STATUSES:
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
next_allowed = record.auto_match_allowed if next_status == 'approved' else False
if 'auto_match_allowed' in data:
next_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
if record.identifier_type in {'domain', 'email'} and is_public_email_domain(record.normalized_value) and next_allowed:
raise ValidationError(
'Public email domains cannot be used for automatic matching',
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
)
if next_status != 'approved' and next_allowed:
raise ValidationError(
'Only approved identifiers can enable automatic matching',
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
)
record.status = next_status
record.auto_match_allowed = next_allowed
if next_status == 'approved' and record.confirmed_at is None:
record.confirmed_by_id = actor_id
record.confirmed_at = datetime.utcnow()
if 'remark' in data:
record.remark = clean_text(data.get('remark')) or None
db.session.commit()
return serialize_identifier(record)