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

+4
View File
@@ -15,6 +15,8 @@ from . import (
permission_service,
report_service,
shipping_customer_import_service,
shipping_customer_lifecycle_service,
shipping_customer_merge_service,
shipping_customer_service,
user_service,
wecom_admin_service,
@@ -31,6 +33,8 @@ __all__ = [
'permission_service',
'report_service',
'shipping_customer_import_service',
'shipping_customer_lifecycle_service',
'shipping_customer_merge_service',
'shipping_customer_service',
'user_service',
'wecom_admin_service',
@@ -497,8 +497,11 @@ def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]:
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:
target = db.session.get(ShippingCustomer, target_id)
if target is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
else:
target_id = None
row.decision_action = action
@@ -586,6 +589,8 @@ def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, An
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 target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
if action == 'update':
target.standard_name = data['standard_name']
target.short_code = data['short_code']
@@ -0,0 +1,244 @@
"""
services/admin/shipping_customer_lifecycle_service.py
用途:统一计算货代客户生命周期影响和永久删除资格。
依赖:客户、业务单、流水、导入、影子识别模型及统一 AppError。
逻辑:所有删除入口先调用本服务;业务和识别审计引用均阻断删除,识别证据仅作为可级联配置数据。
"""
from __future__ import annotations
from typing import Any
from app import db
from sqlalchemy import select
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderCustomerMatch,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
)
def _legacy_shadow_json_match_count(customer_id: int, *, matched_resolution_ids: set[int]) -> int:
"""统计规范化迁移前 JSON 中仍未映射的候选,防止现存审计记录漏算。"""
count = 0
rows = db.session.query(
ShippingCustomerShadowResolution.id,
ShippingCustomerShadowResolution.candidate_matches_json,
).all()
for resolution_id, matches in rows:
if int(resolution_id) in matched_resolution_ids:
continue
for item in matches or []:
if not isinstance(item, dict):
continue
try:
if int(item.get('customer_id')) == customer_id:
count += 1
break
except (TypeError, ValueError):
continue
return count
def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, Any]:
"""按已锁定或已读取的客户对象统计删除资格,保证各删除入口使用同一口径。"""
matched_resolution_ids = {
int(row[0])
for row in db.session.query(ShippingCustomerShadowMatch.resolution_id)
.filter_by(customer_id=customer.id)
.all()
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
'shadow_manual_labels': db.session.query(ShippingCustomerShadowResolution.id).filter_by(manual_customer_id=customer.id).count(),
'shadow_candidate_matches': shadow_normalized + _legacy_shadow_json_match_count(
customer.id,
matched_resolution_ids=matched_resolution_ids,
),
'merged_source_customers': db.session.query(ShippingCustomer.id).filter_by(
merged_into_customer_id=customer.id,
).count(),
'merged_into_customer': int(customer.merged_into_customer_id is not None),
}
return {
'customer': {
'id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'status': customer.status,
},
'can_delete': not any(blockers.values()),
'blockers': blockers,
'cascade': {
'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(),
},
}
def get_customer_lifecycle_impact(customer_id: int) -> dict[str, Any]:
"""
返回客户永久删除前必须检查的全部引用和可级联配置数据。
Args:
customer_id: 标准客户主键。
Returns:
客户快照、can_delete、阻断引用计数和可级联识别证据数。
"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return _build_customer_lifecycle_impact(customer)
def get_customer_lifecycle_timeline(customer_id: int, *, limit: int = 100) -> dict[str, Any]:
"""返回客户关键治理操作的倒序时间线,事件只含快照而不依赖客户外键。"""
customer = db.session.get(ShippingCustomer, customer_id)
rows = (
db.session.query(ShippingCustomerLifecycleEvent)
.filter_by(customer_id_snapshot=customer_id)
.order_by(ShippingCustomerLifecycleEvent.id.desc())
.limit(max(1, min(int(limit), 500)))
.all()
)
if customer is None and not rows:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
# 受控删除后主表已不存在;以最近生命周期快照继续提供审计回放。
customer_snapshot = _build_customer_lifecycle_impact(customer)['customer'] if customer is not None else {
'id': customer_id,
'standard_name': rows[0].customer_name_snapshot,
'short_code': rows[0].customer_short_code_snapshot,
'status': 'deleted',
}
return {
'customer': customer_snapshot,
'items': [{
'id': row.id,
'event_type': row.event_type,
'actor_id': row.actor_id,
'reason': row.reason,
'detail': row.detail_json or {},
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows],
}
def get_customer_governance_quality(*, limit: int = 100) -> dict[str, Any]:
"""汇总影子识别、自动确认门禁和生命周期事件,供管理端持续治理。"""
from app.services.shipping_notice.customer_shadow_resolution import get_shadow_quality_report
from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics
report = get_shadow_quality_report(limit=limit)
report['auto_resolution'] = get_auto_resolution_metrics()
event_counts = dict(
db.session.query(ShippingCustomerLifecycleEvent.event_type, db.func.count())
.group_by(ShippingCustomerLifecycleEvent.event_type)
.all()
)
return {
'shadow_quality': report,
'lifecycle_event_counts': event_counts,
}
def delete_customer(
customer_id: int,
*,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
受控永久删除未进入任何业务或审计链的误建客户。
Args:
customer_id: 待删除的标准客户主键。
confirmation_short_code: 管理员二次输入的客户简码,忽略首尾空格并按大写比对。
reason: 必填删除原因,写入不可反向引用客户的生命周期审计。
actor_id: 当前管理员主键。
Returns:
已删除客户的快照、级联删除证据数与审计事件主键。
Raises:
ValidationError: 删除原因或二次确认简码不合法。
ConflictError: 锁定后发现存在任一阻断引用。
NotFoundError: 客户不存在。
"""
confirmed_code = str(confirmation_short_code or '').strip().upper()
delete_reason = str(reason or '').strip()
if not delete_reason:
raise ValidationError(
'Customer deletion reason is required',
code='SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED',
details={'field': 'reason'},
)
try:
# 锁住客户行后再统计引用,避免预检与提交之间出现可删除的错误判断。
customer = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id == customer_id)
.with_for_update()
).scalar_one_or_none()
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if confirmed_code != customer.short_code:
raise ValidationError(
'Customer deletion confirmation short code is invalid',
code='SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = _build_customer_lifecycle_impact(customer)
if not impact['can_delete']:
raise ConflictError(
'Customer deletion is blocked by lifecycle references',
code='SHIPPING.CUSTOMER_DELETE_BLOCKED',
details={'blockers': impact['blockers']},
)
event = ShippingCustomerLifecycleEvent(
event_type='deleted',
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=delete_reason,
detail_json={
'cascade': impact['cascade'],
},
)
customer_snapshot = impact['customer']
db.session.add(event)
db.session.flush()
db.session.delete(customer)
db.session.commit()
return {
'deleted_customer': customer_snapshot,
'cascade': impact['cascade'],
'lifecycle_event_id': event.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -0,0 +1,227 @@
"""
services/admin/shipping_customer_merge_service.py
用途:执行货代标准客户的受控身份归并。
依赖:客户、识别证据、外部来源键、生命周期审计与统一业务异常。
逻辑:历史业务、编号、导入和影子审计保持指向源客户;仅将未来识别配置归并至目标客户。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy import select
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
)
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
def _load_customers_for_merge(source_customer_id: int, target_customer_id: int) -> tuple[ShippingCustomer, ShippingCustomer]:
"""按主键固定顺序锁住源和目标客户,避免两个反向合并请求产生死锁。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
ids = sorted({int(source_customer_id), int(target_customer_id)})
records = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id.in_(ids))
.order_by(ShippingCustomer.id.asc())
.with_for_update()
).scalars().all()
by_id = {int(record.id): record for record in records}
source = by_id.get(int(source_customer_id))
target = by_id.get(int(target_customer_id))
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return source, target
def _assert_merge_allowed(source: ShippingCustomer, target: ShippingCustomer) -> None:
"""校验合并两端均处于可操作状态,禁止链式或循环归并。"""
if source.status == 'merged' or source.merged_into_customer_id is not None:
raise ConflictError('Source customer has already been merged', code='SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED')
if target.status != 'active' or target.merged_into_customer_id is not None:
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
def get_customer_merge_impact(source_customer_id: int, target_customer_id: int) -> dict[str, Any]:
"""预览归并的历史保留引用与可迁移配置,不执行任何数据修改。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
source = db.session.get(ShippingCustomer, source_customer_id)
target = db.session.get(ShippingCustomer, target_customer_id)
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
_assert_merge_allowed(source, target)
target_identifiers = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
source_identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all()
duplicate_identifiers = sum(
(item.identifier_type, item.normalized_value) in target_identifiers
for item in source_identifiers
)
return {
'source': {
'id': source.id,
'standard_name': source.standard_name,
'short_code': source.short_code,
'status': source.status,
},
'target': {
'id': target.id,
'standard_name': target.standard_name,
'short_code': target.short_code,
'status': target.status,
},
'historical_references': get_customer_lifecycle_impact(source.id)['blockers'],
'migrate': {
'identifiers': len(source_identifiers) - duplicate_identifiers,
'duplicate_identifiers': duplicate_identifiers,
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=source.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=source.id).count(),
},
}
def merge_customer(
source_customer_id: int,
*,
target_customer_id: int,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
原子归并重复客户,不改写历史业务号及其引用。
Args:
source_customer_id: 待归并的源客户。
target_customer_id: 承接未来识别配置的启用目标客户。
confirmation_short_code: 必须匹配源客户当前简码。
reason: 必填合并原因。
actor_id: 当前管理员主键。
Returns:
源/目标快照、迁移统计与合并审计主键。
"""
merge_reason = str(reason or '').strip()
confirmation = str(confirmation_short_code or '').strip().upper()
if not merge_reason:
raise ValidationError('Customer merge reason is required', code='SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED')
try:
source, target = _load_customers_for_merge(source_customer_id, target_customer_id)
_assert_merge_allowed(source, target)
if confirmation != source.short_code:
raise ValidationError(
'Customer merge confirmation short code is invalid',
code='SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = get_customer_merge_impact(source.id, target.id)
target_identifier_keys = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
moved_identifiers = 0
duplicates: list[ShippingCustomerIdentifier] = []
identifiers_to_move: list[ShippingCustomerIdentifier] = []
for identifier in db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all():
key = (identifier.identifier_type, identifier.normalized_value)
if key in target_identifier_keys:
duplicates.append(identifier)
else:
identifiers_to_move.append(identifier)
target_identifier_keys.add(key)
# 先实际删除与目标重复的证据,再更新其余证据的外键,避免唯一约束瞬时冲突。
for identifier in duplicates:
db.session.delete(identifier)
db.session.flush()
for identifier in identifiers_to_move:
identifier.customer_id = target.id
moved_identifiers += 1
removed_duplicate_identifiers = len(duplicates)
external_refs = db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=source.id).all()
for external_ref in external_refs:
external_ref.customer_id = target.id
target_site_codes = {
item.site_code for item in db.session.query(ShippingCustomerSite).filter_by(customer_id=target.id).all()
}
source_sites = db.session.query(ShippingCustomerSite).filter_by(customer_id=source.id).all()
duplicate_site_codes = sorted({item.site_code for item in source_sites if item.site_code in target_site_codes})
if duplicate_site_codes:
raise ConflictError(
'Customer sites conflict during merge',
code='SHIPPING.CUSTOMER_MERGE_SITE_CONFLICT',
details={'site_codes': duplicate_site_codes},
)
for site in source_sites:
site.customer_id = target.id
source_snapshot = impact['source']
target_snapshot = impact['target']
merge = ShippingCustomerMerge(
source_customer_id_snapshot=source.id,
source_name_snapshot=source.standard_name,
source_short_code_snapshot=source.short_code,
target_customer_id_snapshot=target.id,
target_name_snapshot=target.standard_name,
target_short_code_snapshot=target.short_code,
actor_id=actor_id,
reason=merge_reason,
detail_json={
'historical_references': impact['historical_references'],
'migrate': {
'identifiers': moved_identifiers,
'duplicate_identifiers': removed_duplicate_identifiers,
'external_references': len(external_refs),
'sites': len(source_sites),
},
},
)
source.status = 'merged'
source.merged_into_customer_id = target.id
source.updated_by_id = actor_id
db.session.add_all([
merge,
ShippingCustomerLifecycleEvent(
event_type='merged_source', customer_id_snapshot=source.id,
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'target': target_snapshot},
),
ShippingCustomerLifecycleEvent(
event_type='merged_target', customer_id_snapshot=target.id,
customer_name_snapshot=target.standard_name, customer_short_code_snapshot=target.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'source': source_snapshot},
),
])
db.session.commit()
return {
'source': source_snapshot,
'target': target_snapshot,
'migrate': merge.detail_json['migrate'],
'merge_id': merge.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -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)
@@ -0,0 +1,855 @@
"""
services/admin/shipping_inventory_service.py
用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。
依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。
逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.extensions import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingTask,
ShippingOrderField,
ShippingInventoryParsingProfile,
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
ShippingExcelTemplate,
)
from app.services.shipping_notice.credential_crypto import encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS
from app.services.shipping_notice import inventory_parsing_profile
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
value = str(data.get(field) or '').strip()
if required and not value:
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
return value or None
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
value = data.get(field, default)
if not isinstance(value, bool):
raise ValidationError(f'{field} must be a boolean', details={'field': field})
return value
def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
"""读取并复制对象型 JSON 配置。
Args:
data: 管理 API 的请求载荷。
field: 只允许 JSON object 的字段名。
Returns:
dict[str, Any]: 空值规范化为空对象后的可写入配置。
Raises:
ValidationError: 字段不是 JSON object。
"""
value = data.get(field, {})
if not isinstance(value, dict):
raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
if auth_mode != 'password':
raise ValidationError(
'Only password authentication is currently supported',
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
)
return {'auth_mode': auth_mode}
def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
if set(report_path) - allowed:
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
if connector_type == 'dbs':
missing = [key for key in allowed if not normalized.get(key)]
if missing:
raise ValidationError(
'DBS inventory source requires a complete report path',
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
)
elif normalized:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID',
)
return {key: normalized[key] for key in allowed if normalized.get(key)}
def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
raw = data.get('query_parameters_json', [])
if not isinstance(raw, list):
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[dict[str, Any]] = []
seen_names: set[str] = set()
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
for index, item in enumerate(raw):
if not isinstance(item, dict) or set(item) - allowed:
raise ValidationError(
'query parameter contains unsupported fields',
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'index': index},
)
name = str(item.get('name') or '').strip()
mode = str(item.get('mode') or 'single').strip().lower()
values = item.get('values', [])
required = item.get('required', False)
select_all = item.get('select_all', False)
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
raise ValidationError('query parameter values must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
if not isinstance(required, bool) or not isinstance(select_all, bool):
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
normalized_values = [value.strip() for value in values if value.strip()]
if required and not normalized_values and not select_all:
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
if select_all and mode != 'multi_select':
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
parameter: dict[str, Any] = {
'name': name, 'mode': mode, 'values': normalized_values,
'required': required, 'select_all': select_all,
}
if mode == 'multi_text':
joiner = str(item.get('joiner') or ',').strip()
if not joiner:
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
parameter['joiner'] = joiner
seen_names.add(name.lower())
result.append(parameter)
return result
def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
}
def _mask(ciphertext: str | None) -> str | None:
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
return 'configured' if ciphertext else None
def _iso(value: datetime | None) -> str | None:
return value.isoformat() if value else None
def list_profiles() -> list[dict[str, Any]]:
"""列出 Profile 元数据,不返回可恢复的凭据。"""
return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()]
def delete_profile(profile_id: int) -> None:
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
profile = db.session.get(ShippingRpaProfile, profile_id)
if profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
if ShippingInventorySource.query.filter_by(rpa_profile_id=profile.id).count():
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
profile = db.session.get(ShippingRpaProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
profile.display_name = str(_text(data, 'display_name', required=True))
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
profile.login_url = str(_text(data, 'login_url', required=True))
profile.login_config_json = _validate_profile_login_config(data)
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
if not profile.enabled and any(source.enabled for source in profile.sources):
raise ConflictError(
'Disable inventory sources before disabling their RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
)
username = _text(data, 'username')
password = _text(data, 'password')
if username is not None:
profile.username_ciphertext = encrypt_credential(username)
if password is not None:
profile.password_ciphertext = encrypt_credential(password)
if username is not None or password is not None:
profile.credential_updated_at = datetime.utcnow()
profile.updated_by = actor_id
if profile_id:
profile.config_version += 1
if not profile_id:
profile.created_by = actor_id
db.session.add(profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
return _profile_payload(profile)
def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
"""序列化库存站点及其是否满足正式启用前置条件。"""
return {
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
'parsing_profile_id': source.parsing_profile_id,
'excel_template_id': source.excel_template_id,
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
'report_path_json': source.report_path_json or {}, 'query_parameters_json': source.query_parameters_json or [],
'match_aliases_json': source.match_aliases_json or [],
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
'activation': get_source_activation_status(source),
}
def list_sources() -> list[dict[str, Any]]:
"""列出库存源及其稳定业务配置。"""
return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()]
def delete_source(source_id: int) -> None:
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
source_code = str(source.source_code or '').strip().upper()
has_mapping = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id).count() > 0
has_snapshot = ShippingInventoryFile.query.filter_by(source_code=source_code).count() > 0
has_rule = any(
source_code in {str(code).strip().upper() for code in candidates}
for rule in ShippingInventoryRoutingRule.query.all()
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = ShippingTask.query.filter_by(inventory_source_code=source_code).count() > 0
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
if isinstance(source_codes, list)
)
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
raise ConflictError('Inventory Source has operational references', code='SHIPPING.INVENTORY_SOURCE_DELETE_BLOCKED')
db.session.delete(source)
db.session.commit()
def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]:
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
return {
'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no,
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
}
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
rows = ShippingInventoryFile.query.order_by(
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
return [_snapshot_payload(row) for row in rows]
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
"""返回管理员可下载的库存快照路径及安全文件名。
Args:
snapshot_id: 库存快照主键。
Returns:
本地托管文件绝对路径和面向下载的文件名。
Raises:
NotFoundError: 快照不存在或托管文件已不存在。
"""
from pathlib import Path
snapshot = db.session.get(ShippingInventoryFile, snapshot_id)
if snapshot is None:
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND')
path = Path(str(snapshot.storage_path or '')).resolve()
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.INVENTORY_SNAPSHOT_FILE_NOT_FOUND')
filename = str(snapshot.source_file_name or f'{snapshot.inventory_file_no}{path.suffix or ".xlsx"}')
return str(path), filename
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
file_rows = ShippingInventoryFile.query.filter(
ShippingInventoryFile.rpa_run_no.is_not(None),
).order_by(
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
records = [_snapshot_payload(row) for row in file_rows]
known_identities = {
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
for item in records
}
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
ScheduleTask.platform_api_path == 'shipping-inventory-rpa',
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
for run in schedule_runs:
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
items: list[tuple[str, dict[str, Any]]] = []
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
for item in response.get(key) if isinstance(response.get(key), list) else []:
if isinstance(item, dict):
items.append((status, item))
if not items and run.status in {'queued', 'running'}:
pending = (run.response_summary_json or {}).get('pending_details', [])
for item in pending if isinstance(pending, list) else []:
if isinstance(item, dict):
items.append(('awaiting_rpa', item))
if not items and run.status in {'failed', 'partial_failed'}:
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
for status, item in items:
source_code = str(item.get('source_code') or '').strip()
warehouse_id = str(item.get('warehouse_id') or '').strip()
identity = (run_no, source_code, warehouse_id)
if identity in known_identities:
continue
known_identities.add(identity)
records.append({
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
'inventory_file_no': None,
'source_code': source_code or None,
'warehouse_id': warehouse_id or None,
'snapshot_status': status,
'export_status': status,
'identity_status': None,
'line_count': 0,
'share_mode': None,
'exported_at': _iso(run.finished_at or run.created_at),
'expires_at': None,
'rpa_run_no': run_no or None,
'schedule_run_id': run.id,
'source_file_name': None,
'created_at': _iso(run.created_at),
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
})
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
return records[:max(1, min(limit, 200))]
def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool:
"""判断已确认的货代仓库是否已有精确映射或库存源默认映射。"""
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
warehouse = str(warehouse_id or '').strip().upper()
if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None:
return True
return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None
def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
"""复核当前测试文件与已绑定方案,返回解析和仓库映射的启用前置条件。"""
missing: list[str] = []
details: dict[str, Any] = {'sample_warehouses': []}
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter_by(
inventory_source_id=source.id,
status='completed',
source_config_version=source.config_version,
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
if not confirmed_test or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0):
return ['configuration_test'], details
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
profile = source.parsing_profile
if analysis is None or profile is None:
return ['configuration_test'], details
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
selected = next((item for item in candidates if isinstance(item, dict)
and item.get('sheet_name') == definition.get('sheet_name')
and item.get('header_row_index') == definition.get('header_row_index')), None)
headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()]
duplicate_headers = {
str(item.get('header') or '').strip()
for item in (selected or {}).get('columns', [])
if isinstance(item, dict) and item.get('duplicate')
}
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
runtime_mapping, catalog = runtime_field_mapping(mapping)
usages = usage_field_ids()
mapped_ids = set(runtime_mapping)
match_fields = mapped_ids & usages.get('match_identity', set())
quantity_fields = mapped_ids & usages.get('inventory_quantity', set())
required_fields = match_fields | quantity_fields
if (
not selected
or not match_fields
or len(quantity_fields) != 1
or not required_fields <= set(runtime_mapping)
or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields)
or any(str(value or '').strip() in duplicate_headers for value in mapping.values())
or not int((selected or {}).get('sample_row_count') or 0)
):
missing.append('parsing_validation')
return missing, details
column_by_header = {
str(item.get('header') or '').strip(): item
for item in (selected or {}).get('columns', []) if isinstance(item, dict)
}
quantity_codes = quantity_fields
quantity_column = next((
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
for field in quantity_codes
), {})
identifier_columns = [
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
for field in match_fields
]
if (
quantity_column.get('inferred_type') != 'number'
or any(not item.get('sample_values') for item in identifier_columns)
):
missing.append('parsing_validation')
return missing, details
if source.warehouse_resolution_mode == 'fixed':
if not _enabled_external_mapping_exists(source, source.fixed_warehouse_id):
missing.append('warehouse_mapping')
return missing, details
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
if len(warehouse_codes) != 1:
missing.append('warehouse_identification')
return missing, details
warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '')
if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers:
missing.append('warehouse_identification')
return missing, details
column = next((item for item in (selected or {}).get('columns', [])
if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {})
sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()})
details['sample_warehouses'] = sample_warehouses
if not sample_warehouses or any(not _enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses):
missing.append('warehouse_mapping')
return missing, details
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
template = source.excel_template
profile = source.parsing_profile
if template is None or profile is None:
return []
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
invalid = any(
isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in inventory_fields
for item in mappings
)
return ['template_validation'] if not mappings or invalid else []
def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
"""计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。"""
missing: list[str] = []
if source.rpa_profile is None or not source.rpa_profile.enabled:
missing.append('rpa_profile')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
missing.append('parsing_profile')
if source.excel_template is None or source.excel_template.status != 'published':
missing.append('excel_template')
else:
missing.extend(_template_validation_missing(source))
validation_missing, validation_details = _test_analysis_validation(source)
missing.extend(validation_missing)
return missing, validation_details
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
"""返回库存站点启用检查结果,供管理端展示下一步操作。"""
missing, validation = _activation_missing_requirements(source)
return {
'ready': not missing,
'missing_requirements': missing,
'validation': validation,
}
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
status = get_source_activation_status(source)
if not status['ready']:
raise ConflictError(
'Inventory Source is not ready for activation',
code='SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED',
details=status,
)
source.enabled = True
source.updated_by = actor_id
source.config_version += 1
db.session.commit()
return _source_payload(source)
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。"""
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
source.enabled = False
source.updated_by = actor_id
source.config_version += 1
db.session.commit()
return _source_payload(source)
def save_source(
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
allow_enable_transition: bool = True,
) -> dict[str, Any]:
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。"""
source = db.session.get(ShippingInventorySource, source_id) if source_id else None
if source_id and source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
try:
profile_id = int(data.get('rpa_profile_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('rpa_profile_id is required') from exc
profile = db.session.get(ShippingRpaProfile, profile_id)
if profile is None:
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
if not allow_enable_transition:
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
enabled = bool(source.enabled) if source is not None else False
else:
enabled = requested_enabled
if enabled and not profile.enabled:
raise ValidationError(
'Enabled Inventory Source requires an enabled RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLED',
)
parsing_profile_id = data.get('parsing_profile_id')
parsing_profile = db.session.get(ShippingInventoryParsingProfile, int(parsing_profile_id)) if str(parsing_profile_id or '').isdigit() else None
if parsing_profile_id not in (None, '', 0, '0') and (parsing_profile is None or parsing_profile.status != 'published'):
raise ValidationError('parsing_profile_id must reference a published profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
if enabled and parsing_profile is None:
raise ValidationError('published parsing_profile_id is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
excel_template_id = data.get('excel_template_id')
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
if enabled and excel_template is None:
raise ValidationError('published excel_template_id is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
is_new = source is None
source = source or ShippingInventorySource(
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
)
source.source_code = str(_text(data, 'source_code', required=True)).upper()
source.display_name = str(_text(data, 'display_name', required=True))
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
source.rpa_profile = profile
source.parsing_profile = parsing_profile
source.excel_template = excel_template
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
source.report_path_json = _validate_report_path(source.connector_type, _json_object(data, 'report_path_json'))
source.query_parameters_json = _validate_query_parameters(data)
source.match_aliases_json = _json_string_list(data, 'match_aliases_json')
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
source.enabled = enabled
source.updated_by = actor_id
if source_id:
source.config_version += 1
if is_new:
source.created_by = actor_id
db.session.add(source)
validate_source_profile(source, profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.INVENTORY_SOURCE_INVALID') from exc
return _source_payload(source)
def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]:
return {
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
'system_fact_key': c.system_fact_key, 'operator': c.operator, 'expected_value_json': c.expected_value_json,
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
}
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
if operator in {'is_empty', 'is_not_empty'}:
return None
if operator in {'in', 'not_in'}:
if not isinstance(value, list):
raise ValidationError('List operator requires a string list', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
normalized = [str(item).strip() for item in value if str(item).strip()]
if not normalized:
raise ValidationError('List operator requires at least one value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
return normalized
if operator in {'numeric_length', 'string_length'}:
try:
length = int(value)
except (TypeError, ValueError) as exc:
raise ValidationError('Length operator requires an integer', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') from exc
if length < 0:
raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
return length
if not isinstance(value, str) or not value.strip():
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
return value.strip()
def list_rules() -> list[dict[str, Any]]:
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
return [_rule_payload(item) for item in ShippingInventoryRoutingRule.query.order_by(ShippingInventoryRoutingRule.priority.desc()).all()]
def delete_draft_rule(rule_id: int) -> None:
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED')
db.session.delete(rule)
db.session.commit()
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
if rule.status != 'published':
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID')
rule.status = 'retired'
rule.updated_by = actor_id
db.session.commit()
return _rule_payload(rule)
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
if rule_id:
current = db.session.get(ShippingInventoryRoutingRule, rule_id)
if current is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
if current.status != 'draft':
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.INVENTORY_RULE_IMMUTABLE')
rule = current if rule_id else ShippingInventoryRoutingRule(
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
)
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
rule.rule_name = str(_text(data, 'rule_name', required=True))
rule.scope = str(_text(data, 'scope', required=True)).lower()
rule.priority = int(data.get('priority') or 0)
rule.match_mode = str(data.get('match_mode') or 'all').lower()
rule.status = 'draft'
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
rule.version = int(data.get('version') or 1)
if not rule_id:
rule.created_by = actor_id
rule.updated_by = actor_id
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.INVENTORY_RULE_INVALID')
conditions = data.get('conditions')
if not isinstance(conditions, list) or not conditions:
raise ValidationError('Routing rule requires conditions', code='SHIPPING.INVENTORY_RULE_CONDITIONS_REQUIRED')
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
if rule_id:
db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
synchronize_session=False
)
db.session.flush()
db.session.expire(rule, ['conditions'])
for index, item in enumerate(conditions, start=1):
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
source_kind = str(item.get('source_kind') or 'order_field')
order_field_id = str(item.get('order_field_id') or '') or None
system_fact_key = str(item.get('system_fact_key') or '') or None
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
if source_kind == 'order_field':
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
system_fact_key = None
elif source_kind == 'system_fact':
if system_fact_key not in ALLOWED_SYSTEM_FACT_KEYS:
raise ValidationError('Routing system fact is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
order_field_id = None
else:
raise ValidationError('Routing condition source is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
operator = str(item['operator'])
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
order_field_id=order_field_id, system_fact_key=system_fact_key,
operator=operator, expected_value_json=_validate_rule_condition_expected(
operator, item.get('expected_value_json'),
), sequence=index,
))
if not rule_id:
db.session.add(rule)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.INVENTORY_RULE_CONFLICT') from exc
return _rule_payload(rule)
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布草稿并写入不可变规则定义快照。"""
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID')
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
source_codes = {
str(code or '').strip().upper()
for code in payload.get('source_codes', [])
if str(code or '').strip()
}
enabled_codes = {
str(code).strip().upper()
for (code,) in db.session.query(ShippingInventorySource.source_code).filter_by(enabled=True).all()
}
missing_codes = sorted(source_codes - enabled_codes)
if missing_codes:
raise ValidationError(
'Routing rule references unavailable inventory sources',
code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID',
details={'source_codes': missing_codes},
)
rule.status = 'published'
rule.updated_by = actor_id
db.session.add(ShippingInventoryRoutingRuleVersion(
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
))
db.session.commit()
return _rule_payload(rule)
def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, Any]:
return {
'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id,
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
def list_external_mappings() -> list[dict[str, Any]]:
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()]
def delete_external_mapping(mapping_id: int) -> None:
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
record = db.session.get(ShippingInventoryExternalMapping, mapping_id)
if record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND')
db.session.delete(record)
db.session.commit()
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
"""创建或更新精确/默认外部系统映射。"""
record = db.session.get(ShippingInventoryExternalMapping, mapping_id) if mapping_id else None
if mapping_id and record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND')
try:
source_id = int(data.get('inventory_source_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('inventory_source_id is required') from exc
if db.session.get(ShippingInventorySource, source_id) is None:
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.inventory_source_id = source_id
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
record.updated_by = actor_id
if not mapping_id:
record.created_by = actor_id
db.session.add(record)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_CONFLICT') from exc
return _external_payload(record)