feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误
- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一 - 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单 - worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步 - 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5) - 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6) - 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果 - 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
This commit is contained in:
1 parent
993e581135
commit
abf3d48927
144 files changed
+10161
-2132
No files matched your search
@@ -18,7 +18,6 @@ from app.models import (
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
@@ -295,7 +294,11 @@ def _validate_movement_profile_binding(profile_id: Any) -> int | None:
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填。
|
||||
|
||||
DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认;
|
||||
不作为排程是否产出执行单元的门禁(一源一单元)。
|
||||
"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
@@ -309,14 +312,7 @@ def _validate_receipt_report_config(
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
|
||||
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
|
||||
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
|
||||
if len(warehouse_conditions) != 1 or not any(warehouse_values):
|
||||
raise ValidationError(
|
||||
'DBS receipt report requires exactly one Warehouse query condition with values',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
# Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
@@ -385,9 +381,7 @@ def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
|
||||
|
||||
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 {}
|
||||
@@ -418,7 +412,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S
|
||||
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: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
@@ -642,115 +636,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
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(
|
||||
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 (
|
||||
not confirmed_test
|
||||
or source.rpa_profile is None
|
||||
or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version
|
||||
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:
|
||||
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)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
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)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
if source.warehouse_resolution_mode == 'fixed':
|
||||
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:
|
||||
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:
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
@@ -770,35 +655,11 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if run is None:
|
||||
return {'state': 'not_started'}
|
||||
profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None
|
||||
if (
|
||||
run.source_config_version != source.config_version
|
||||
or run.rpa_profile_config_version != profile_version
|
||||
):
|
||||
return {
|
||||
'state': 'stale', 'run_no': run.run_no, 'status': run.status,
|
||||
'source_config_version': run.source_config_version,
|
||||
'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
}
|
||||
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}
|
||||
|
||||
|
||||
def _activation_check(
|
||||
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
|
||||
blocking: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造单项上线门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
return {
|
||||
'code': code,
|
||||
'status': status or ('passed' if passed else 'pending'),
|
||||
@@ -809,16 +670,15 @@ def _activation_check(
|
||||
|
||||
|
||||
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。"""
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing = set(validation_missing)
|
||||
test_evidence = _latest_test_run_evidence(source)
|
||||
test_complete = 'configuration_test' not in missing
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_valid = template_ready and 'template_validation' not in missing
|
||||
checks = [
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_activation_check(
|
||||
'rpa_profile', passed=profile_ready, action='configure_connection',
|
||||
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
|
||||
@@ -832,40 +692,14 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
|
||||
evidence={'template_id': source.excel_template_id, 'published': template_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'template_validation', passed=not template_ready or template_valid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid,
|
||||
),
|
||||
_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', 'empty'} else None,
|
||||
),
|
||||
_activation_check(
|
||||
'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 validation_details.get('parsing_validation') else None, blocking=False,
|
||||
'template_validation', passed=not template_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
if source.warehouse_resolution_mode == 'inventory_match':
|
||||
checks.append(_activation_check(
|
||||
'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 validation_details.get('warehouse_identification') else None, blocking=False,
|
||||
))
|
||||
checks.append(_activation_check(
|
||||
'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 validation_details.get('warehouse_mapping') else None, blocking=False,
|
||||
))
|
||||
return checks
|
||||
|
||||
|
||||
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""返回库存站点正式运行的结构化门禁结果。
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
Args:
|
||||
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
|
||||
@@ -883,25 +717,8 @@ 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)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
@@ -919,7 +736,7 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
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')
|
||||
|
||||
Reference in new issue
Block a user