feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则

This commit is contained in:
hugo committed 2026-07-20 19:28:17 +08:00
1 parent 88408490d7
commit 34d489a2d1
167 files changed
+10365 -7978

No files matched your search

@@ -20,6 +20,7 @@ from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
@@ -89,6 +90,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
'blockers': blockers,
'cascade': {
'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(),
'identity_evidences': db.session.query(ShippingIdentityEvidence.id).filter_by(customer_id=customer.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(),
},
}
@@ -229,6 +231,13 @@ def delete_customer(
customer_snapshot = impact['customer']
db.session.add(event)
db.session.flush()
# 新模型未在 Customer ORM 上定义 relationship;显式清理可级联配置,避免删除误建客户时外键阻断。
db.session.query(ShippingIdentityEvidence).filter_by(customer_id=customer.id).delete(synchronize_session=False)
site_ids = [item.id for item in db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).all()]
if site_ids:
db.session.query(ShippingIdentityEvidence).filter(ShippingIdentityEvidence.site_id.in_(site_ids)).delete(
synchronize_session=False,
)
db.session.delete(customer)
db.session.commit()
return {
@@ -18,6 +18,7 @@ from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
@@ -72,6 +73,12 @@ def get_customer_merge_impact(source_customer_id: int, target_customer_id: int)
(item.identifier_type, item.normalized_value) in target_identifiers
for item in source_identifiers
)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
source_evidence = db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all()
duplicate_evidence = sum((item.definition_id, item.normalized_value) in target_evidence_keys for item in source_evidence)
return {
'source': {
'id': source.id,
@@ -91,6 +98,8 @@ def get_customer_merge_impact(source_customer_id: int, target_customer_id: int)
'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(),
'identity_evidences': len(source_evidence) - duplicate_evidence,
'duplicate_identity_evidences': duplicate_evidence,
},
}
@@ -155,6 +164,25 @@ def merge_customer(
moved_identifiers += 1
removed_duplicate_identifiers = len(duplicates)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
duplicate_evidences = []
evidences_to_move = []
for evidence in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all():
key = (evidence.definition_id, evidence.normalized_value)
if key in target_evidence_keys:
duplicate_evidences.append(evidence)
else:
evidences_to_move.append(evidence)
target_evidence_keys.add(key)
for evidence in duplicate_evidences:
db.session.delete(evidence)
db.session.flush()
for evidence in evidences_to_move:
evidence.customer_id = target.id
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
@@ -191,6 +219,8 @@ def merge_customer(
'duplicate_identifiers': removed_duplicate_identifiers,
'external_references': len(external_refs),
'sites': len(source_sites),
'identity_evidences': len(evidences_to_move),
'duplicate_identity_evidences': len(duplicate_evidences),
},
},
)
@@ -24,6 +24,7 @@ from app.models import (
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -118,6 +119,7 @@ def serialize_customer(
include_identifiers: bool = False,
case_count: int | None = None,
identifier_count: int | None = None,
identity_evidence_count: int | None = None,
) -> dict[str, Any]:
"""
序列化标准客户,并可选附带识别证据和业务引用数量。
@@ -126,7 +128,8 @@ def serialize_customer(
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
identifier_count: 列表查询预聚合的识别证据数量;为空时现场查询。
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
Returns:
管理端客户 JSON 字典。
"""
@@ -143,9 +146,19 @@ def serialize_customer(
'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
@@ -173,14 +186,36 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
.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()
@@ -208,8 +243,11 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
items = query.order_by(order(sort_col), ShippingCustomer.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
return {
'items': [
serialize_customer(customer, case_count=int(case_count), identifier_count=int(identifier_count))
for customer, case_count, identifier_count in items
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,
@@ -293,6 +331,13 @@ def serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any
}
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 {
@@ -304,6 +349,13 @@ def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
'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()
],
}
@@ -20,13 +20,14 @@ from app.models import (
ShippingInventoryParsingProfile,
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
ShippingExcelTemplate,
ShippingInventorySourceParsingBindingAudit,
)
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
from app.services.shipping_notice.order_schema import service as order_schema_service
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
@@ -238,13 +239,137 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
'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 _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。"""
return {
'source_id': source.id,
'source_code': source.source_code,
'enabled': bool(source.enabled),
'parsing_profile_id': source.parsing_profile_id,
'parsing_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None,
'excel_template_id': source.excel_template_id,
'config_version': source.config_version,
}
def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None:
"""校验停用站点可直接采用的已发布方案与当前发货模板字段契约。"""
if source.enabled:
raise ConflictError('Disable inventory source before changing parsing profile', code='SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED')
if profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
if not mapping:
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
template = source.excel_template
if template is None:
return
if template.status != 'published':
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
missing_fields = sorted({
str(item.get('source_key') or '')
for item in template_mappings
if isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in mapping
})
if missing_fields:
raise ValidationError(
'Parsing profile does not provide all inventory fields required by the excel template',
code='SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
)
def bind_source_parsing_profile(
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
) -> list[dict[str, Any]]:
"""为一个或多个停用库存站点原子绑定已发布解析方案并写入追加式审计。
Args:
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
profile_id: 必须为已发布解析方案主键。
actor_id: 当前管理员主键,仅写入审计。
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
Returns:
list[dict[str, Any]]: 已更新站点的管理端 DTO。
Raises:
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
ConflictError: 试图变更已启用站点的正式解析方案。
"""
try:
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
except (TypeError, ValueError) as exc:
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
if not normalized_ids or len(normalized_ids) != len(source_ids):
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
if operation not in {'direct', 'bulk'}:
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
normalized_reason = str(reason or '').strip()
if len(normalized_reason) > 500:
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
if not normalized_reason:
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
try:
normalized_profile_id = int(profile_id)
except (TypeError, ValueError) as exc:
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
profile = db.session.get(ShippingInventoryParsingProfile, normalized_profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
sources = [db.session.get(ShippingInventorySource, source_id) for source_id in normalized_ids]
if any(source is None for source in sources):
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
typed_sources = [source for source in sources if source is not None]
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
for source in typed_sources:
_validate_source_parsing_binding(source, profile)
for source in typed_sources:
before = _binding_snapshot(source)
previous_profile_id = source.parsing_profile_id
source.parsing_profile = profile
source.updated_by = actor_id
source.config_version += 1
db.session.flush()
db.session.add(ShippingInventorySourceParsingBindingAudit(
inventory_source_id=source.id, previous_parsing_profile_id=previous_profile_id,
parsing_profile_id=profile.id, operation=operation, reason=normalized_reason, actor_id=actor_id,
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
))
db.session.commit()
return [_source_payload(source) for source in typed_sources]
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
if db.session.get(ShippingInventorySource, source_id) is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
rows = ShippingInventorySourceParsingBindingAudit.query.filter_by(
inventory_source_id=source_id,
).order_by(ShippingInventorySourceParsingBindingAudit.id.desc()).all()
return [{
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
'source_config_version_before': row.source_config_version_before,
'source_config_version_after': row.source_config_version_after,
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows]
def list_sources() -> list[dict[str, Any]]:
"""列出库存源及其稳定业务配置。"""
return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()]
@@ -397,13 +522,13 @@ def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_
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,
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['completed', 'completed_empty']),
ShippingInventoryConfigurationTestRun.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 (
@@ -413,6 +538,12 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
):
return ['configuration_test'], details
if confirmed_test.status == 'completed_empty':
# 无库存时只能确认连接与查询成功;行级解析和调拨映射留待首个非空文件或实际调拨前验证。
details['data_validation'] = 'pending_first_non_empty_export'
details['parsing_validation'] = 'pending_first_non_empty_export'
details['warehouse_mapping'] = 'deferred_until_transfer'
return missing, details
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
profile = source.parsing_profile
if analysis is None or profile is None:
@@ -447,7 +578,7 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
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')
details['parsing_validation'] = 'pending_first_non_empty_export'
return missing, details
column_by_header = {
str(item.get('header') or '').strip(): item
@@ -466,26 +597,27 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
quantity_column.get('inferred_type') != 'number'
or any(not item.get('sample_values') for item in identifier_columns)
):
missing.append('parsing_validation')
details['parsing_validation'] = 'pending_first_non_empty_export'
return missing, details
if source.warehouse_resolution_mode == 'fixed':
if not _enabled_external_mapping_exists(source, source.fixed_warehouse_id):
missing.append('warehouse_mapping')
details['warehouse_mapping'] = 'ready_for_transfer' if _enabled_external_mapping_exists(source, source.fixed_warehouse_id) else 'deferred_until_transfer'
return missing, details
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
if len(warehouse_codes) != 1:
missing.append('warehouse_identification')
details['warehouse_identification'] = 'pending_first_non_empty_export'
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')
details['warehouse_identification'] = 'pending_first_non_empty_export'
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')
details['warehouse_identification'] = 'ready_for_transfer' if sample_warehouses else 'pending_first_non_empty_export'
details['warehouse_mapping'] = 'ready_for_transfer' if sample_warehouses and all(
_enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses
) else 'deferred_until_transfer'
return missing, details
@@ -527,6 +659,8 @@ def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]
}
if run.status == 'failed':
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
if run.status == 'completed_empty':
return {'state': 'empty', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
@@ -545,11 +679,7 @@ def _activation_check(
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
"""构建库存站点正式运行的权威检查清单。
检查项按管理员完成配置的业务顺序返回。测试、解析、模板和仓库映射均以当前
``config_version`` 的持久化事实为准,避免管理端依据本地表单状态猜测启用资格。
"""
"""构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。"""
validation_missing, validation_details = _test_analysis_validation(source)
missing = set(validation_missing)
test_evidence = _latest_test_run_evidence(source)
@@ -578,28 +708,28 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
_activation_check(
'configuration_test', passed=test_complete,
action='run_configuration_test', evidence=test_evidence,
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed'} else None,
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed', 'empty'} else None,
),
_activation_check(
'parsing_validation', passed=test_complete and 'parsing_validation' not in missing,
'parsing_validation', passed=test_complete and not validation_details.get('parsing_validation'),
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
status='pending' if not test_complete else None, blocking='parsing_validation' in missing,
status='pending' if validation_details.get('parsing_validation') else None, blocking=False,
),
]
if source.warehouse_resolution_mode == 'inventory_match':
checks.append(_activation_check(
'warehouse_identification', passed=test_complete and 'warehouse_identification' not in missing,
'warehouse_identification', passed=validation_details.get('warehouse_identification') == 'ready_for_transfer',
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
status='pending' if not test_complete else None, blocking='warehouse_identification' in missing,
status='pending' if validation_details.get('warehouse_identification') else None, blocking=False,
))
checks.append(_activation_check(
'warehouse_mapping', passed=test_complete and 'warehouse_mapping' not in missing, action='configure_warehouse_mapping',
'warehouse_mapping', passed=validation_details.get('warehouse_mapping') == 'ready_for_transfer', action='configure_warehouse_mapping',
evidence={
'mode': source.warehouse_resolution_mode,
'fixed_warehouse_id': source.fixed_warehouse_id,
'sample_warehouses': validation_details['sample_warehouses'],
},
status='pending' if not test_complete else None, blocking='warehouse_mapping' in missing,
status='pending' if validation_details.get('warehouse_mapping') else None, blocking=False,
))
return checks
@@ -623,6 +753,23 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A
}
def activate_source_if_ready(source: ShippingInventorySource, *, actor_id: int | None) -> bool:
"""在测试回调后自动启用已满足全部正式运行条件的停用站点。
Args:
source: 已完成当前版本测试的库存站点;调用方负责统一提交事务。
actor_id: 发起测试的管理员标识,仅用于更新审计字段。
Returns:
当本次将站点改为启用时返回 ``True``;条件未齐或已启用时返回 ``False``。
"""
if source.enabled or not get_source_activation_status(source)['ready']:
return False
source.enabled = True
source.updated_by = actor_id
return True
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
source = db.session.get(ShippingInventorySource, source_id)
@@ -704,7 +851,6 @@ def save_source(
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
@@ -728,7 +874,7 @@ def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]:
'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,
'operator': c.operator, 'expected_value_json': c.expected_value_json,
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
}
@@ -826,22 +972,23 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
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
published_fields = {
str(config.get('field_id'))
for config in order_schema_service.get_published_contract()['fields']
if config.get('scope') == field.scope
}
if field.id not in published_fields:
raise ValidationError('Routing order field is not published', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
else:
raise ValidationError('Routing condition source is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
raise ValidationError('Routing conditions must use a published order field', 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,
order_field_id=order_field_id,
operator=operator, expected_value_json=_validate_rule_condition_expected(
operator, item.get('expected_value_json'),
), sequence=index,