feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

@@ -16,7 +16,15 @@ 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.models import (
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
@@ -24,10 +32,54 @@ from app.services.shipping_notice.customer_normalization import (
normalize_short_code,
)
CUSTOMER_STATUSES = frozenset({'active', 'inactive'})
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):
@@ -83,6 +135,7 @@ def serialize_customer(
'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,
@@ -93,6 +146,8 @@ def serialize_customer(
}
if include_identifiers:
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
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
@@ -204,7 +259,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
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:
if status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
record = ShippingCustomer(
standard_name=standard_name,
@@ -215,6 +270,13 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
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:
@@ -223,28 +285,81 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
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_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],
}
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')
record.standard_name = name
next_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
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:
status = clean_text(data.get('status')).lower()
if status not in CUSTOMER_STATUSES:
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')
record.status = status
if 'remark' in data:
record.remark = clean_text(data.get('remark')) or None
record.updated_by_id = actor_id
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:
@@ -253,9 +368,9 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
return serialize_customer(record, include_identifiers=True)
def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]:
def deactivate_customer(customer_id: int, *, reason: object = None, actor_id: int | None) -> dict[str, Any]:
"""停用客户;不物理删除,以保留业务单和识别审计。"""
return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id)
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]:
@@ -267,6 +382,8 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int |
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)
@@ -297,6 +414,13 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int |
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:
@@ -313,6 +437,10 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int
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()
@@ -331,12 +459,101 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int
'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
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)