343 lines
15 KiB
Python
343 lines
15 KiB
Python
"""
|
|
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)
|