Files
syops/backend/app/services/admin/shipping_customer_service.py
T

612 lines
27 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,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_identifier,
normalize_short_code,
)
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
def _record_lifecycle_event(
customer: ShippingCustomer,
*,
event_type: str,
actor_id: int | None,
reason: str | None = None,
detail: dict[str, Any] | None = None,
) -> None:
"""写入仅含客户快照的治理审计,避免生命周期日志反向阻断受控删除。"""
db.session.add(ShippingCustomerLifecycleEvent(
event_type=event_type,
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=reason,
detail_json=detail or {},
))
def _required_change_reason(data: dict[str, Any]) -> str:
"""返回高风险客户变更的必填审计原因,缺失时拒绝提交。"""
reason = clean_text(data.get('reason'))
if not reason:
raise ValidationError(
'Customer change reason is required',
code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED',
details={'field': 'reason'},
)
return reason
def _identifier_snapshot(record: ShippingCustomerIdentifier) -> dict[str, Any]:
"""生成识别证据变更前后对比所需的最小审计快照。"""
return {
'identifier_id': record.id,
'identifier_type': record.identifier_type,
'normalized_value': record.normalized_value,
'status': record.status,
'auto_match_allowed': bool(record.auto_match_allowed),
'remark': record.remark,
}
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,
identity_evidence_count: int | None = None,
) -> dict[str, Any]:
"""
序列化标准客户,并可选附带识别证据和业务引用数量。
Args:
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
Returns:
管理端客户 JSON 字典。
"""
payload: dict[str, Any] = {
'id': record.id,
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'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(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
).filter_by(customer_id=record.id).count(),
}
if include_identifiers:
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
payload['identity_evidences'] = [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(customer_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
]
payload['external_refs'] = [serialize_external_ref(item) for item in record.external_refs]
payload['sites'] = [serialize_site(item) for item in record.sites]
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()
)
identity_evidence_counts = (
db.session.query(
ShippingIdentityEvidence.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.filter(ShippingIdentityEvidence.customer_id.isnot(None))
.group_by(ShippingIdentityEvidence.customer_id)
.subquery()
)
site_identity_evidence_counts = (
db.session.query(
ShippingCustomerSite.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.join(ShippingIdentityEvidence, ShippingIdentityEvidence.site_id == ShippingCustomerSite.id)
.group_by(ShippingCustomerSite.customer_id)
.subquery()
)
query = (
db.session.query(
ShippingCustomer,
func.coalesce(case_counts.c.case_count, 0),
func.coalesce(identifier_counts.c.identifier_count, 0),
func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0)
+ func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0),
)
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(site_identity_evidence_counts, site_identity_evidence_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),
identity_evidence_count=int(identity_evidence_count),
)
for customer, case_count, identifier_count, identity_evidence_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 - {'merged'}:
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)
db.session.flush()
_record_lifecycle_event(
record,
event_type='created',
actor_id=actor_id,
detail={'after': {'standard_name': standard_name, 'short_code': short_code, 'status': status}},
)
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 serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any]:
"""序列化客户在外部系统中的稳定客户编码。"""
return {
'id': record.id, 'customer_id': record.customer_id,
'source_system': record.source_system, 'customer_code': record.legacy_customer_key,
}
def _serialize_identity_evidence(record: ShippingIdentityEvidence) -> dict[str, Any]:
"""序列化配置化身份识别证据及定义快照,供客户主数据页直接渲染。"""
from app.services.shipping_notice.identity_rules.service import serialize_evidence
return serialize_evidence(record)
def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
"""序列化送货站点及其名称/外部编码标识。"""
return {
'id': record.id, 'customer_id': record.customer_id, 'site_name': record.site_name,
'site_code': record.site_code, 'address': record.address, 'city': record.city,
'country': record.country, 'status': record.status, 'remark': record.remark,
'identifiers': [{
'id': item.id, 'identifier_type': item.identifier_type,
'source_system': item.source_system, 'raw_value': item.raw_value,
'normalized_value': item.normalized_value, 'status': item.status,
} for item in record.identifiers],
'identity_evidences': [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(site_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
],
}
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 record.status == 'merged':
raise ConflictError('Merged customer cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = {
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
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')
next_name = name
if 'short_code' in data:
next_short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
high_risk_change = 'short_code' in changes or 'status' in changes
change_reason = _required_change_reason(data) if high_risk_change else clean_text(data.get('reason')) or None
record.standard_name = next_name
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
event_type='updated',
actor_id=actor_id,
reason=change_reason,
detail={'changes': changes},
)
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, *, reason: object = None, actor_id: int | None) -> dict[str, Any]:
"""停用客户;不物理删除,以保留业务单和识别审计。"""
return update_customer(customer_id, {'status': 'inactive', 'reason': reason}, 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')
if customer.status == 'merged':
raise ConflictError('Merged customer cannot receive identifiers', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
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)
db.session.flush()
_record_lifecycle_event(
customer,
event_type='identifier_created',
actor_id=actor_id,
detail={'identifier': _identifier_snapshot(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')
customer = db.session.get(ShippingCustomer, record.customer_id)
if customer is None or customer.status == 'merged':
raise ConflictError('Merged customer identifier cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = _identifier_snapshot(record)
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',
)
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else record.remark
after = {
**before,
'status': next_status,
'auto_match_allowed': bool(next_allowed),
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
requires_reason = 'status' in changes or 'auto_match_allowed' in changes
change_reason = _required_change_reason(data) if requires_reason else clean_text(data.get('reason')) or None
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()
record.remark = next_remark
_record_lifecycle_event(
customer,
event_type='identifier_updated',
actor_id=actor_id,
reason=change_reason,
detail={'identifier_id': record.id, 'changes': changes},
)
db.session.commit()
return serialize_identifier(record)
def create_external_ref(customer_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""新增来源系统客户编码;同一来源和编码只能绑定一个标准客户。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
source_system = clean_text(data.get('source_system')).upper()
customer_code = clean_text(data.get('customer_code')).upper()
if not source_system or not customer_code:
raise ValidationError('Source system and customer code are required', code='SHIPPING.CUSTOMER_EXTERNAL_REF_INVALID')
record = ShippingCustomerExternalRef(
customer_id=customer.id, source_system=source_system, legacy_customer_key=customer_code,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer external reference already exists', code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT') from exc
return serialize_external_ref(record)
def create_site(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""新增客户送货站点,站点编码在同一标准客户内唯一。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
site_name = clean_text(data.get('site_name'))
site_code = clean_text(data.get('site_code')).upper()
if not site_name or not site_code:
raise ValidationError('Site name and code are required', code='SHIPPING.CUSTOMER_SITE_INVALID')
record = ShippingCustomerSite(
customer_id=customer.id, site_name=site_name, site_code=site_code,
address=clean_text(data.get('address')) or None, city=clean_text(data.get('city')) or None,
country=clean_text(data.get('country')) or None, status='active',
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 site already exists', code='SHIPPING.CUSTOMER_SITE_CONFLICT') from exc
return serialize_site(record)
def create_site_identifier(site_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""为送货站点新增名称别名、地址或带来源系统的外部站点编码。"""
site = db.session.get(ShippingCustomerSite, site_id)
if site is None:
raise NotFoundError('Customer site not found', code='SHIPPING.CUSTOMER_SITE_NOT_FOUND')
identifier_type = clean_text(data.get('identifier_type')).lower()
if identifier_type not in {'name_alias', 'external_code', 'address'}:
raise ValidationError('Site identifier type is invalid', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
raw_value = clean_text(data.get('identifier_value'))
source_system = clean_text(data.get('source_system')).upper() if identifier_type == 'external_code' else ''
if not raw_value or (identifier_type == 'external_code' and not source_system):
raise ValidationError('Site identifier is incomplete', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
normalized = normalize_identifier('name_alias', raw_value) if identifier_type == 'name_alias' else raw_value.upper()
record = ShippingCustomerSiteIdentifier(
site_id=site.id, identifier_type=identifier_type, source_system=source_system,
raw_value=raw_value, normalized_value=normalized, status='approved',
remark=clean_text(data.get('remark')) or None,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Site identifier already exists', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_CONFLICT') from exc
return serialize_site(site)