feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa

把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

@@ -1,9 +1,14 @@
"""
services/admin/shipping_inventory_service.py
services/admin/shipping_onhand_admin_service.py
用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。
依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。
用途:管理库存源、RPA Profile、在手报表配置、路由规则和外部系统映射主数据。
依赖:db、库存配置模型(含 s18 起的 FreightRpaOnhandReportConfig 配置行)、凭据加密、
Source/Profile 校验、统一 AppError。
逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。
s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 一对一配置行
(save_source 载荷内嵌 onhand_report_config 时经 _apply_onhand_report_config 写行),
站点行只保留连接、模板绑定、仓库模式与启停;启用门禁由
assert_onhand_source_can_enable 在服务层执行(PostgreSQL CHECK 不能跨表)。
"""
from __future__ import annotations
@@ -14,22 +19,22 @@ 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, ShippingNotice,
FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile, FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition,
FreightRpaOnhandRoutingRuleVersion, FreightRpaSource, FreightRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
ShippingOrderField,
ShippingInventoryParsingProfile,
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
FreightRpaParsingProfile,
ShippingNoticeLine, ShippingNoticeLineOnhandMatch,
ShippingExcelTemplate,
ShippingInventorySourceParsingBindingAudit,
ShippingReceiptReportConfig,
FreightRpaSourceParsingBindingAudit,
FreightRpaInboundReportConfig, FreightRpaOnhandReportConfig,
)
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
from app.services.shipping_notice.upload_config_validation import validate_upload_config
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.onhand_routing_engine import ALLOWED_ACTIONS
from app.services.shipping_notice import onhand_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
@@ -62,7 +67,7 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
"""
value = data.get(field, {})
if not isinstance(value, dict):
raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
return dict(value)
@@ -84,19 +89,19 @@ def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> d
"""校验 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')
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_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)},
code='SHIPPING.ONHAND_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',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
return {key: normalized[key] for key in allowed if normalized.get(key)}
@@ -105,7 +110,7 @@ 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')
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
result: list[dict[str, Any]] = []
seen_names: set[str] = set()
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
@@ -113,7 +118,7 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
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},
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
)
name = str(item.get('name') or '').strip()
mode = str(item.get('mode') or 'single').strip().lower()
@@ -121,16 +126,16 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
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')
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_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')
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_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')
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_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')
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_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')
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter: dict[str, Any] = {
'name': name, 'mode': mode, 'values': normalized_values,
'required': required, 'select_all': select_all,
@@ -138,14 +143,14 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
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')
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter['joiner'] = joiner
seen_names.add(name.lower())
result.append(parameter)
return result
def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
def _profile_payload(profile: FreightRpaProfile) -> 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,
@@ -168,15 +173,15 @@ def _iso(value: datetime | None) -> str | None:
def list_profiles() -> list[dict[str, Any]]:
"""列出 Profile 元数据,不返回可恢复的凭据。"""
return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()]
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
def delete_profile(profile_id: int) -> None:
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
profile = db.session.get(ShippingRpaProfile, profile_id)
profile = db.session.get(FreightRpaProfile, 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():
if FreightRpaSource.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()
@@ -184,10 +189,10 @@ def delete_profile(profile_id: int) -> None:
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
profile = db.session.get(FreightRpaProfile, 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 or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
prev_non_upload = (
@@ -237,26 +242,42 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
return _profile_payload(profile)
def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
"""序列化库存站点及其是否满足正式启用前置条件。"""
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
return {
'id': config.id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
}
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
"""序列化库存站点及其是否满足正式启用前置条件。
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
"""
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 [],
'onhand_report_config': (
_onhand_report_config_payload(source.onhand_report_config)
if source.onhand_report_config is not None else None
),
'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 _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
def _receipt_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'id': config.id, 'source_id': config.source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
# 入站解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
@@ -282,7 +303,7 @@ def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
raise ValidationError(
'Inbound parsing profile must be published with purpose inbound',
@@ -292,7 +313,7 @@ def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
source: FreightRpaSource, data: dict[str, Any],
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填。
@@ -328,24 +349,24 @@ def _validate_receipt_report_config(
def get_receipt_report_config(source_id: int) -> dict[str, Any] | None:
"""读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
return _receipt_report_config_payload(config) if config else None
def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
if config is None:
config = ShippingReceiptReportConfig(inventory_source_id=source.id)
config = FreightRpaInboundReportConfig(source_id=source.id)
config.created_by = actor_id
db.session.add(config)
else:
@@ -357,37 +378,173 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
append_shipping_audit_event(
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
metadata={'source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。"""
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
Args:
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
Returns:
int | None: 规整后的方案 id 或 None。
Raises:
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
"""
raw = str(profile_id).strip() if profile_id is not None else ''
if raw in {'', '0'}:
return None
if not raw.isdigit():
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
profile = db.session.get(FreightRpaParsingProfile, int(raw))
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
return profile.id
def _apply_onhand_report_config(
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
) -> FreightRpaOnhandReportConfig:
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
Args:
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
"""
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
report_path = _json_object(data, 'report_path_json')
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
if source.connector_type != 'dbs' and report_path:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
parameters = _validate_query_parameters(data)
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = report_path
config.query_parameters_json = parameters
config.parsing_profile_id = parsing_profile_id
config.updated_by = actor_id
return config
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
Args:
source_id: 库存站点主键,必须已存在。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
Raises:
NotFoundError: 站点不存在。
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
assert_onhand_source_can_enable(source)
db.session.commit()
return _onhand_report_config_payload(config)
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
Args:
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
Returns:
None: 门禁通过(站点未启用时恒通过)。
Raises:
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
"""
if not source.enabled:
return
config = source.onhand_report_config
if config is None or not config.parsing_profile_id or not source.excel_template_id:
raise ValidationError(
'Enabled inventory source requires onhand report config, parsing profile and excel template',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
"""
config = source.onhand_report_config
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,
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
'parsing_profile_checksum': (
config.parsing_profile.checksum
if config is not None and config.parsing_profile is not None else None
),
'excel_template_id': source.excel_template_id,
'config_version': source.config_version,
}
def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None:
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
if profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_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')
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
template = source.excel_template
if template is None:
return
@@ -405,7 +562,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S
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},
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
)
@@ -446,26 +603,36 @@ def bind_source_parsing_profile(
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)
profile = db.session.get(FreightRpaParsingProfile, 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]
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
sources = [db.session.get(FreightRpaSource, 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')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
config = source.onhand_report_config
previous_profile_id = config.parsing_profile_id if config is not None else None
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.parsing_profile_id = profile.id
config.updated_by = actor_id
source.updated_by = actor_id
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
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,
db.session.add(FreightRpaSourceParsingBindingAudit(
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
parsing_profile_id=config.parsing_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),
))
@@ -475,11 +642,11 @@ def bind_source_parsing_profile(
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()
if db.session.get(FreightRpaSource, source_id) is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
source_id=source_id,
).order_by(FreightRpaSourceParsingBindingAudit.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,
@@ -492,27 +659,27 @@ def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
def list_sources() -> list[dict[str, Any]]:
"""列出库存源及其稳定业务配置。"""
return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()]
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
def delete_source(source_id: int) -> None:
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
has_snapshot = FreightRpaOnhandReportFile.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 rule in FreightRpaOnhandRoutingRule.query.all()
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter(
ShippingNoticeLineInventoryMatch.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
ShippingNoticeLineOnhandMatch.source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
@@ -521,15 +688,15 @@ def delete_source(source_id: int) -> None:
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')
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
db.session.delete(source)
db.session.commit()
def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]:
def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
return {
'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no,
'id': snapshot.id, 'inventory_file_no': snapshot.onhand_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,
@@ -543,8 +710,8 @@ def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]:
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
rows = ShippingInventoryFile.query.order_by(
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
rows = FreightRpaOnhandReportFile.query.order_by(
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
return [_snapshot_payload(row) for row in rows]
@@ -563,22 +730,22 @@ def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
"""
from pathlib import Path
snapshot = db.session.get(ShippingInventoryFile, snapshot_id)
snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id)
if snapshot is None:
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND')
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_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"}')
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND')
filename = str(snapshot.source_file_name or f'{snapshot.onhand_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),
file_rows = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.rpa_run_no.is_not(None),
).order_by(
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
records = [_snapshot_payload(row) for row in file_rows]
known_identities = {
@@ -636,10 +803,12 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
return records[:max(1, min(limit, 200))]
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
template = source.excel_template
profile = source.parsing_profile
# s18 起解析方案绑定取自 onhand_report_config 配置行。
config = source.onhand_report_config
profile = config.parsing_profile if config is not None else None
if template is None or profile is None:
return []
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
@@ -669,13 +838,16 @@ def _activation_check(
}
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]:
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
测试导出不再参与启用门禁;启停由管理员显式开关完成。
"""
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'
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
config = source.onhand_report_config
parsing_profile = config.parsing_profile if config is not None else None
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
return [
@@ -685,7 +857,7 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
),
_activation_check(
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
evidence={'profile_id': source.parsing_profile_id, 'published': parsing_ready},
evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready},
),
_activation_check(
'excel_template', passed=template_ready, action='configure_excel_template',
@@ -698,7 +870,7 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
]
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
"""返回库存站点启用硬门槛的结构化结果。
Args:
@@ -719,14 +891,14 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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',
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
details=status,
)
source.enabled = True
@@ -737,9 +909,9 @@ 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)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
source.enabled = False
source.updated_by = actor_id
db.session.commit()
@@ -750,15 +922,20 @@ 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
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
"""
source = db.session.get(FreightRpaSource, 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')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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)
profile = db.session.get(FreightRpaProfile, 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)
@@ -772,32 +949,21 @@ def save_source(
'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 = source or FreightRpaSource(
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.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
source.enabled = enabled
source.updated_by = actor_id
@@ -806,16 +972,36 @@ def save_source(
if is_new:
source.created_by = actor_id
db.session.add(source)
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
if enabled and excel_template is None:
raise ValidationError(
'published excel_template_id is required',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
try:
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
db.session.flush()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
config_data = data.get('onhand_report_config')
if isinstance(config_data, dict):
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
if enabled:
assert_onhand_source_can_enable(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
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
return _source_payload(source)
def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]:
def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> 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,
@@ -832,47 +1018,47 @@ def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
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')
raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_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')
raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_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
raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc
if length < 0:
raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_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')
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_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()]
return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()]
def delete_draft_rule(rule_id: int) -> None:
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED')
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_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)
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'published':
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID')
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID')
rule.status = 'retired'
rule.updated_by = actor_id
db.session.commit()
@@ -882,12 +1068,12 @@ def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
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)
current = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if current is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_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(
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE')
rule = current if rule_id else FreightRpaOnhandRoutingRule(
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
)
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
@@ -903,37 +1089,37 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
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')
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_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')
raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED')
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
if rule_id:
db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
db.session.query(FreightRpaOnhandRoutingRuleCondition).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')
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_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
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')
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
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')
raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
else:
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
operator = str(item['operator'])
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
rule.conditions.append(FreightRpaOnhandRoutingRuleCondition(
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
order_field_id=order_field_id,
operator=operator, expected_value_json=_validate_rule_condition_expected(
@@ -946,7 +1132,7 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
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
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc
return _rule_payload(rule)
@@ -956,11 +1142,11 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
"""
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID')
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_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 = {
@@ -970,27 +1156,27 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
}
existing_codes = {
str(code).strip().upper()
for (code,) in db.session.query(ShippingInventorySource.source_code).all()
for (code,) in db.session.query(FreightRpaSource.source_code).all()
}
missing_codes = sorted(source_codes - existing_codes)
if missing_codes:
raise ValidationError(
'Routing rule references unavailable inventory sources',
code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID',
code='SHIPPING.ONHAND_RULE_SOURCE_INVALID',
details={'source_codes': missing_codes},
)
rule.status = 'published'
rule.updated_by = actor_id
db.session.add(ShippingInventoryRoutingRuleVersion(
db.session.add(FreightRpaOnhandRoutingRuleVersion(
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]:
def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]:
return {
'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id,
'id': mapping.id, 'source_id': mapping.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,
@@ -1001,31 +1187,31 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
def list_external_mappings() -> list[dict[str, Any]]:
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()]
return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()]
def delete_external_mapping(mapping_id: int) -> None:
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
record = db.session.get(ShippingInventoryExternalMapping, mapping_id)
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id)
if record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND')
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_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
record = db.session.get(FreightRpaOnhandExternalMapping, 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')
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
try:
source_id = int(data.get('inventory_source_id'))
source_id = int(data.get('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
raise ValidationError('source_id is required') from exc
if db.session.get(FreightRpaSource, source_id) is None:
raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.source_id = source_id
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
@@ -1045,5 +1231,5 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
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
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc
return _external_payload(record)
@@ -1,9 +1,14 @@
"""
services/freight_rpa/common/callback_sinks.py
用途:RPA 回调业务 sink 注册表——freight_rpa 侧的回调分发缝。
用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起
与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch.
dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact,
kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind
(inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等)
仍走本模块的 register_sink / dispatch_sink,不改 envelope)。
依赖:app.core.errors.AppError。
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,onhand 等待拆端点按 kind 分发到
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
组合根调用 register_sink 注入真实业务持久化处理器。
@@ -0,0 +1,384 @@
"""freight_rpa/common/report_audit.py
用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入
ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。
依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors.
ValidationError、SQLAlchemy 会话(app.db)。
逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa
包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/
freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与
append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent
模型,事件名(shipping_inbound_rpa_callback_received /
shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。
与 audit_service 的有意差异(均为本域受控场景):
(1)before/after 快照不做白名单投影——本域快照键均为受控诊断键
(status/error_code/sha256/file_size 等),原样入 snapshot 列;
(2)不做 XFA 加密完整快照(本域无敏感完整载荷);
(3)保留期恒为 None(货代统一审计账本永久保留);
(4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash
取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。
本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。
_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'})
_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'})
# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自
# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。
_FORBIDDEN_AUDIT_KEYS = frozenset({
'api_key',
'api_base_url',
'authorization',
'body',
'content',
'document_text',
'email_body',
'minio',
'object_key',
'object_url',
'password',
'prompt',
'provider_config',
'quote',
'raw_content',
'raw_output',
'secret',
'token',
'url',
'user_agent',
})
def _is_forbidden_audit_key(key: str) -> bool:
"""键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。"""
return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。
Returns:
命中键路径列表(调用方排序后入 ValidationError.details)。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if _is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。"""
safe = dict(metadata or {})
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'RPA report audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'RPA report audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'RPA report audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def _stable_hash(value: Any) -> str:
"""对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。"""
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None:
"""
计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。
核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。
"""
left = before if isinstance(before, dict) else {}
right = after if isinstance(after, dict) else {}
changed: dict[str, Any] = {}
added: dict[str, Any] = {}
removed: dict[str, Any] = {}
for key in sorted(set(left) | set(right)):
if key in left and key in right:
if left[key] != right[key]:
changed[key] = {'from': left[key], 'to': right[key]}
elif key in right:
added[key] = right[key]
else:
removed[key] = left[key]
if not changed and not added and not removed:
return None
return {'changed': changed, 'added': added, 'removed': removed}
def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None:
"""
读取同聚合最新一条事件的 event_hash 作为哈希链前驱。
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。
"""
previous = (
ShippingAuditEvent.query
.filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128])
.order_by(ShippingAuditEvent.id.desc())
.first()
)
if previous is None:
return None
return str(previous.event_hash) if previous.event_hash else None
def _event_hash_payload(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str | None,
result: str | None,
reason_code: str | None,
run_no: str | None,
task_no: str | None,
operation_id: str | None,
request_id: str | None,
actor_type: str,
actor_id: str | None,
before_snapshot: dict[str, Any] | None,
after_snapshot: dict[str, Any] | None,
diff_json: dict[str, Any] | None,
previous_event_hash: str | None,
sensitivity_level: str | None,
) -> dict[str, Any]:
"""组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。"""
return {
'event_type': event_type,
'aggregate_type': aggregate_type,
'aggregate_id': aggregate_id,
'action': action,
'result': result,
'reason_code': reason_code,
'workflow_id': None,
'workflow_item_id': None,
'workflow_item_version_id': None,
'version_no': None,
'run_no': run_no,
'document_id': None,
'review_case_no': None,
'task_no': task_no,
'operation_id': operation_id,
'request_id': request_id,
'actor_type': actor_type,
'actor_id': actor_id,
'before_snapshot': before_snapshot,
'after_snapshot': after_snapshot,
'diff': diff_json,
'previous_event_hash': previous_event_hash,
'sensitivity_level': sensitivity_level,
}
def append_rpa_report_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
task_no: str | None = None,
intake_no: str | None = None,
actor_type: str = 'system',
actor_id: str | int | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
owner_user_id: str | int | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
sensitivity_level: str | None = None,
) -> ShippingAuditEvent:
"""
追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。
用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的
RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名,
事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。
核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏;
[STEP 2] 计算 before/after 稳定哈希与顶层 diff;
[STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash;
[STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。
Args:
event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received);
禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。
run_no/task_no: 排程 run / task 软引用(截断 64)。
actor_type/actor_id/actor_role/actor_display: 操作主体四元组
(actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。
result: success / failure / rejected / ignored(白名单外抛 ValidationError)。
before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。
evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。
metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。
unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。
action/reason_code/reason/error_code/conversation_id/correlation_id/source/
request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。
Returns:
尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。
Raises:
ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。
"""
# [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。
if actor_type not in _ALLOWED_ACTOR_TYPES:
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
if result is not None and result not in _ALLOWED_RESULTS:
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
safe_metadata = _sanitize_metadata(metadata)
if before is not None and _collect_forbidden_keys(before):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))},
)
if after is not None and _collect_forbidden_keys(after):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))},
)
# [STEP 2] 快照哈希与顶层差异。
before_snapshot = before if isinstance(before, dict) else None
after_snapshot = after if isinstance(after, dict) else None
diff_json = _snapshot_diff(before, after)
# [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。
db.session.flush()
previous_event_hash = _resolve_previous_event_hash(
aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128],
)
resolved_run_no = str(run_no)[:64] if run_no else None
resolved_task_no = str(task_no)[:64] if task_no else None
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
resolved_operation_id = str(operation_id)[:64] if operation_id else None
resolved_request_id = str(request_id)[:64] if request_id else None
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
event_hash = _stable_hash(_event_hash_payload(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64] if action else None,
result=result,
reason_code=str(reason_code)[:128] if reason_code else None,
run_no=resolved_run_no,
task_no=resolved_task_no,
operation_id=resolved_operation_id,
request_id=resolved_request_id,
actor_type=actor_type,
actor_id=resolved_actor_id,
before_snapshot=before_snapshot,
after_snapshot=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
sensitivity_level=resolved_sensitivity,
))
# [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。
event = ShippingAuditEvent(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
run_no=resolved_run_no,
task_no=resolved_task_no,
intake_no=str(intake_no)[:64] if intake_no else None,
actor_type=actor_type,
actor_id=resolved_actor_id,
actor_role=str(actor_role)[:64] if actor_role else None,
actor_display=str(actor_display)[:128] if actor_display else None,
request_id=resolved_request_id,
operation_id=resolved_operation_id,
correlation_id=str(correlation_id)[:64] if correlation_id else None,
source=str(source)[:32] if source else None,
result=result,
error_code=str(error_code)[:64] if error_code else None,
conversation_id=str(conversation_id)[:100] if conversation_id else None,
unit_id=str(unit_id)[:64] if unit_id is not None else None,
document_id=str(document_id)[:64] if document_id is not None else None,
review_case_no=str(review_case_no)[:64] if review_case_no else None,
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
attempt_no=int(attempt_no) if attempt_no is not None else None,
action=str(action)[:64] if action else None,
reason_code=str(reason_code)[:128] if reason_code else None,
reason=str(reason)[:2000] if reason else None,
before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None,
after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None,
before_snapshot_json=before_snapshot,
after_snapshot_json=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
event_hash=event_hash,
sensitivity_level=resolved_sensitivity,
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
context_refs_json=dict(context_refs or {}) if context_refs else None,
metadata_json=safe_metadata,
retention_expires_at=None,
)
db.session.add(event)
db.session.flush()
return event
# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。
RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS
@@ -35,10 +35,10 @@ RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
# inventory_export→onhand_export、receipt_export→inbound_export(freight_upload 不变);
# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
ONHAND_EXPORT_CAPABILITY = "onhand_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
@@ -59,7 +59,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
@@ -454,7 +454,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(onhand_export / inbound_export / freight_upload)。
required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。
Returns:
(是否合格, 不合格原因列表)。
@@ -482,7 +482,7 @@ def _worker_is_eligible(
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_upload)。"""
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
@@ -610,7 +610,7 @@ def _check_rpa_worker_ready_for_capability(
message, detail_message = "ready", "ready"
else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message
@@ -731,7 +731,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
@@ -740,7 +740,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY,
required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(),
)
@@ -777,7 +777,7 @@ def assert_freight_upload_rpa_ready() -> None:
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY,
"capability": FREIGHT_RPA_UPLOAD_CAPABILITY,
},
)
@@ -906,7 +906,7 @@ def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,
"freight_upload": {
"freight_rpa_upload": {
"ready": freight_readiness.ready,
"message": freight_readiness.message,
"detail_message": freight_readiness.detail_message,
@@ -4,19 +4,24 @@ services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
schedule.freight_inbound_rpa_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingReceiptReport* 引用不变——批次 S 才改表)。
依赖:models(ShippingReceiptReportFile / ShippingReceiptRpaUnitRun / ShippingReceiptNotificationDelivery /
schedule.freight_rpa_inbound_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingInboundReport* 引用不变——批次 S 才改表)。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun / FreightRpaInboundNotificationDelivery /
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
shipping_notice.audit_service(适应度测试白名单内,本模块唯一 shipping_notice 业务依赖,
见 tests/services/freight_rpa/test_import_boundary.py)。
freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代
shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块,
边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
empty/success/failed 三个终态分支各自 commit;终态落库后的业务桥(推进在途调拨来源任务、
调拨证据同步)与排程终态归集(finalize)经 on_terminal 钩子回调 shipping_notice 侧实现,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa,
与拆分前「归档 commit 后立刻推桥」的调用顺序逐点一致。
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、
仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据
同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。
"""
from __future__ import annotations
@@ -24,26 +29,24 @@ from __future__ import annotations
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingReceiptNotificationDelivery,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
FreightRpaInboundNotificationDelivery,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
User,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
from app.services.shipping_notice.audit_service import append_shipping_audit_event
# 终态落库后的业务收尾钩子:由 shipping_notice 域注入(推进在途调拨来源任务 + 调拨证据同步
# + 排程终态归集),契约 = 原 storage.ingest_receipt_callback 中「commit 之后的桥/finalize 尾巴」。
InboundTerminalHook = Callable[..., None]
def _read_inbound_callback_file(file_path: str) -> bytes:
@@ -73,21 +76,29 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
return path.read_bytes()
def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> dict[str, Any]:
def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
on_terminal: 必填业务收尾钩子(shipping_notice 域注入,见模块 docstring);在每个终态
分支 commit 之后、以与拆分前完全一致的实参被调用——
empty/failed: on_terminal(unit, ok=False, error_code=..., error_message=...);
success: on_terminal(unit, ok=True, file_no=..., file_sha256=...)。
业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。
Returns:
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
Raises:
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造
ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调
dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2——
含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run);
处理函数异常原样外抛(不吞、不回滚已提交终态);
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
callback_id = str(payload.get('callback_id') or '').strip()
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
status = str(payload.get('status') or '').strip().lower()
@@ -98,8 +109,8 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
before=before,
@@ -111,46 +122,67 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm
},
metadata={'callback_status': status, 'skip_reason': unit.error_code},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
)
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'callback_status': status},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code, error_message=unit.error_message,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'failed'}
data = _read_inbound_callback_file(str(payload.get('file_path') or ''))
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get('sha256') or '').lower()
if claimed and claimed != sha256:
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
# unit_run_id 自单元行回填(Task 7 修复轮 2)。
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=existing.id, sha256=sha256, ok=True,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
record = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
db.session.add(record)
unit.status = 'success'; unit.finished_at = datetime.utcnow()
db.session.flush()
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
# [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=record.id, sha256=sha256, ok=True,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
Args:
@@ -161,11 +193,11 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
rows = FreightRpaInboundReportFile.query.filter(
FreightRpaInboundReportFile.archive_expires_at.is_not(None),
FreightRpaInboundReportFile.archive_expires_at <= now,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaInboundReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
@@ -173,8 +205,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
@@ -183,8 +215,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
@@ -195,7 +227,7 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
def _recipient_ids(report_file: FreightRpaInboundReportFile) -> list[int]:
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
run = report_file.unit_run.schedule_run
task = run.task if run else None
@@ -208,23 +240,23 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
Args:
file_id: 已归档收料文件主键(ShippingReceiptReportFile.id)。
file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
Returns:
dict: success_count / failed_count(file_not_found 时附 reason)。
"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None:
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
success_count = failed_count = 0
for user_id in _recipient_ids(report_file):
key = f'receipt:file:{report_file.id}:user:{user_id}'
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
delivery = FreightRpaInboundNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
if delivery and delivery.status == 'success' and not force:
success_count += 1
continue
if delivery is None:
delivery = ShippingReceiptNotificationDelivery(
delivery = FreightRpaInboundNotificationDelivery(
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
message_type='file', idempotency_key=key, status='pending',
)
@@ -234,8 +266,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
if user is None or not user.wecom_userid:
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
@@ -252,8 +284,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
success_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id),
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id),
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
@@ -262,8 +294,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
except Exception as exc:
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
@@ -5,7 +5,7 @@ services/freight_rpa/inbound/trigger_io.py
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 schedule.freight_inbound_rpa_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
逻辑:由 schedule.freight_rpa_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
@@ -3,8 +3,8 @@ services/freight_rpa/onhand/attempts.py
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值,
逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值,
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
"""
@@ -20,8 +20,8 @@ DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_ONHAND_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"onhand_rpa_drop_ingested",
"onhand_rpa_ready",
"inventory_template_mapping_used",
}
@@ -49,10 +49,10 @@ def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
since: datetime | None = last_reset.created_at if last_reset else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
ShippingTaskEvent.event_type == "onhand_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
ShippingTaskEvent.event_type == "onhand_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
@@ -2,7 +2,7 @@
services/freight_rpa/onhand/callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
(Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
(Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
scheduler/worker 启动时定期消费队列。
@@ -0,0 +1,84 @@
"""freight_rpa/onhand/report_store.py
用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域
(shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行,
插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。
依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。
逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数
(storage_path、file_sha256、onhand_lines_json、field_mapping_json、
snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后
返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不
commit】——事务提交时机归属调用方;两者都【不创建任务关联】——
shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。
【禁止】import app.services.shipping_notice / in_transit_transfer(import
方向只能反过来,边界由 tests/services/shipping_notice/
test_report_model_boundary.py 锁定)。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import NotFoundError
from app.models import FreightRpaOnhandReportFile
def insert_onhand_report(**columns: Any) -> int:
"""插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。
【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景
(RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在
shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。
核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行;
[STEP 2] db.session.add + flush(拿到自增主键且同事务内可见);
[STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。
Args:
**columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的
列名,非法列名会在构造时抛 TypeError)。无默认值语义变化——
列默认值仍由模型定义(default=)承担。
Returns:
新插入行的 file_id(int)。
Raises:
TypeError: 传入了模型不存在的列关键字。
sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引)
冲突,由调用方决定 savepoint 回滚或复用既有行。
"""
row = FreightRpaOnhandReportFile(**columns)
db.session.add(row)
db.session.flush()
return int(row.id)
def update_onhand_report(file_id: int, **columns: Any) -> None:
"""按 file_id 更新该行的给定列并 flush。不 commit。
【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写
share_mode、identity_status 回填等针对既有在手报表行的列更新场景。
核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方
持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默
吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】——
事务归属调用方;【不动任务关联】——link 表更新归发货域。
Args:
file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。
**columns: 要更新的列名与取值(禁止传入模型不存在的列名)。
Raises:
NotFoundError: file_id 对应的行不存在。
TypeError: 传入了模型不存在的列关键字。
"""
row = db.session.get(FreightRpaOnhandReportFile, file_id)
if row is None:
raise NotFoundError(
f"Onhand report file not found: {file_id}",
details={'file_id': file_id},
)
for key, value in columns.items():
setattr(row, key, value)
db.session.flush()
@@ -5,7 +5,7 @@ services/freight_rpa/onhand/trigger_io.py
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
@@ -3,11 +3,11 @@ services/freight_rpa/onhand/workflow_protocol.py
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
排程进度记账与超时窗口判定的纯协议层。
依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、
依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
AST 全包扫描锁死,含函数内延迟 import)。
逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入
逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
@@ -21,7 +21,7 @@ from pathlib import Path
from typing import Any
from app.extensions import db
from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt
from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
@@ -61,7 +61,7 @@ def is_legacy_trigger_run_no(run_no: str) -> bool:
def expected_rpa_callback_run_no(task: Any) -> str:
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
if not last_trigger:
return ""
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
@@ -101,9 +101,9 @@ def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
attempt = (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
@@ -119,7 +119,7 @@ def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
if not effective:
return
attempt = (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
@@ -199,7 +199,7 @@ def record_onhand_batch_progress(
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
# commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致:
# commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致:
# 校验通过、计数写完后立即提交,再由业务层构造响应。
db.session.commit()
return {
@@ -221,7 +221,7 @@ def compute_rpa_wait_window(
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
Args:
triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。
triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
now: 可注入当前时间(测试用);缺省 utcnow。
@@ -0,0 +1,45 @@
"""freight_rpa/reports/__init__.py
用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer
(import 边界由 tests/services/freight_rpa/test_report_queries.py 与
test_import_boundary.py 锁定)。
"""
from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind
from app.services.freight_rpa.reports.queries import (
InboundConfigView,
InboundFileView,
OnhandConfigView,
SiteView,
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_site,
latest_usable_inbound_file,
mark_inbound_parse_failure,
read_inbound_file_bytes,
usable_inbound_file_condition,
)
__all__ = [
'REPORT_KINDS',
'InboundConfigView',
'InboundFileView',
'OnhandConfigView',
'ReportFact',
'SiteView',
'clear_inbound_parse_failure',
'get_inbound_config',
'get_onhand_config',
'get_site',
'latest_usable_inbound_file',
'mark_inbound_parse_failure',
'read_inbound_file_bytes',
'require_report_kind',
'usable_inbound_file_condition',
]
@@ -0,0 +1,78 @@
"""freight_rpa/reports/dispatch.py
用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit
终态、再投递事实」的第二段分发(批次 B Task 6)。
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
require_report_kind)。
逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks /
register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码),
绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。
本模块不 commit、不 rollback。
"""
from __future__ import annotations
from typing import Callable
from app.core.errors import AppError
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
# 报表事实处理函数契约:接收单个 ReportFact,返回 None;
# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。
Handler = Callable[[ReportFact], None]
# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。
_REPORT_HANDLERS: dict[str, Handler] = {}
def register_report_handler(report_kind: str, handler: Handler) -> None:
"""
注册一个报表事实处理函数(由组合根在应用启动时调用)。
【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks /
register_onhand_sinks)时调用;测试直接调用注入临时处理函数。
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
Args:
report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
不校验其内部行为。
Raises:
ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。
"""
kind = require_report_kind(report_kind)
_REPORT_HANDLERS[kind] = handler
def dispatch_report_fact(fact: ReportFact) -> None:
"""
把已随终态 commit 的报表事实投递给对应 kind 的处理函数。
【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态
db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 /
单元不存在 / 落库失败均不得投递)。
核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数,
其异常原样向外抛(不包日志、不吞);未注册抛
AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
本函数不 commit、不 rollback。
Args:
fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/
sha256/ok/error_code/error_message)。
Raises:
ValidationError: fact.report_kind 不在白名单。
AppError: kind 未注册处理函数(404;归档终态已提交不回滚,
Worker 重试整笔回调即可补投递)。
"""
kind = require_report_kind(fact.report_kind)
handler = _REPORT_HANDLERS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No report handler registered for kind: {kind}',
http_status=404,
)
handler(fact)
@@ -0,0 +1,71 @@
"""freight_rpa/reports/facts.py
用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
report kind 只认 onhand / inbound / outbound,非法值抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
本模块不 import shipping_notice / in_transit_transfer。
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。
"""
from __future__ import annotations
from dataclasses import dataclass
from app.core.errors import ValidationError
# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用
# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。
REPORT_KINDS = ('onhand', 'inbound', 'outbound')
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
# 避免为同一类入参错误分裂出多个近义 code。
_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID'
@dataclass(frozen=True)
class ReportFact:
"""一份回报表的事实行(跨域只读传输对象)。
用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照;
ok=False 时 error_code/error_message 描述失败原因。
约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指);
unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递
必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新),
允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。
"""
report_kind: str
source_code: str
file_id: int | None
sha256: str | None
ok: bool
error_code: str | None = None
error_message: str | None = None
unit_run_id: int | None = None
def require_report_kind(value: str) -> str:
"""校验并原样返回合法的 report kind。
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。
Args:
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
Returns:
原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。
Raises:
ValidationError: value 不在白名单内(HTTP 400,不可重试)。
"""
if value not in REPORT_KINDS:
raise ValidationError(
f"Unsupported report kind: {value!r}",
code=_INVALID_KIND_ERROR_CODE,
details={'report_kind': value, 'allowed': list(REPORT_KINDS)},
)
return value
@@ -0,0 +1,599 @@
"""freight_rpa/reports/queries.py
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
app.core.errors(NotFoundError)、
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer
——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。
usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤
表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移,
两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 =
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 +
未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 =
未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window
的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer
(import 禁令)而保持口径逐位一致。
【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_
file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点
编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer
收敛为「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from sqlalchemy import ColumnElement, and_, not_, or_
from app import db
from app.core.errors import NotFoundError
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000),
# 防止上游超长错误信息把写入顶爆。
_PARSE_ERROR_CODE_MAX = 64
_PARSE_ERROR_MESSAGE_MAX = 2000
# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内
# 复制而非 import,见文件头 import 禁令)。
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
_UTC_TZ = ZoneInfo("UTC")
def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B
Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会
漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学
并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。
Args:
now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致),
缺省取当前 Asia/Shanghai 时刻。
Returns:
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
"""
if now is None:
now = datetime.now(_SHANGHAI_TZ)
if now.tzinfo is None:
now = now.replace(tzinfo=_UTC_TZ)
sh_now = now.astimezone(_SHANGHAI_TZ)
start_utc = (
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ)
.astimezone(_UTC_TZ)
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。"""
window_start, window_end = _business_date_utc_window(now)
return and_(
FreightRpaInboundReportFile.created_at >= window_start,
FreightRpaInboundReportFile.created_at < window_end,
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。
判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致):
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
(created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+
未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。
本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一
事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立
(保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid)
推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate
迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓,
不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
@dataclass(frozen=True)
class SiteView:
"""库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。
阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别
方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、
rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。
"""
source_code: str
display_name: str
connector_type: str
excel_template_id: int | None
enabled: bool
source_id: int = 0
rpa_profile_id: int = 0
warehouse_resolution_mode: str = ""
@dataclass(frozen=True)
class RpaLoginProfileView:
"""RPA 登录连接只读视图(freight_rpa_profiles 行)。
凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker
trigger,禁止出现在任何日志/接口响应中。
"""
profile_id: int
profile_code: str
login_url: str
login_config: dict
username_ciphertext: str | None
password_ciphertext: str | None
enabled: bool
@dataclass(frozen=True)
class OnhandConfigView:
"""在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
@dataclass(frozen=True)
class InboundConfigView:
"""入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。
阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行
快照需要配置行主键与版本,不再引用配置模型)。
"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
config_id: int = 0
config_version: int = 1
@dataclass(frozen=True)
class InboundProfileView:
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
定义(definition_json:field_mapping / sheet_name / header_row_index 等)
原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景
自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。
"""
profile_id: int
profile_code: str
version: int
status: str
purpose: str
definition_json: dict
@dataclass(frozen=True)
class InboundFileView:
"""入站归档文件的只读视图;source_code 取自其所属执行单元行。
parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B
Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。
"""
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
parse_failed_at: datetime | None = None
def get_site(source_code: str) -> SiteView | None:
"""按 source_code 返回库存站点只读视图。
用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用,
替代直接查询 FreightRpaSource。
核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。
Args:
source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。
Returns:
SiteView;站点不存在返回 None(调用方自行 fail-closed)。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
if site is None:
return None
return SiteView(
source_code=site.source_code,
display_name=site.display_name,
connector_type=site.connector_type,
excel_template_id=site.excel_template_id,
enabled=bool(site.enabled),
# [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。
source_id=site.id,
rpa_profile_id=site.rpa_profile_id,
warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""),
)
def get_onhand_config(source_code: str) -> OnhandConfigView | None:
"""按 source_code 返回在手报表配置只读视图。
用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在
freight_rpa_onhand_report_configs,站点行不再承载这三列)。
核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行
缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。
Args:
source_code: 站点实例编码。
Returns:
OnhandConfigView;站点无配置返回 None。
"""
config = (
FreightRpaOnhandReportConfig.query
.join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return OnhandConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
)
def get_inbound_config(source_code: str) -> InboundConfigView | None:
"""按 source_code 返回入站报表配置只读视图(与在手配置同构)。
用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点
enabled 与本配置行是否存在决定。
核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行,
命中即映射视图;缺失返回 None。
Args:
source_code: 站点实例编码。
Returns:
InboundConfigView;站点或配置不存在返回 None。
"""
config = (
FreightRpaInboundReportConfig.query
.join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return InboundConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
# [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。
config_id=config.id,
config_version=int(config.config_version or 1),
)
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码)
时调用,替代直接查询站点与其登录连接模型。
核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律
返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文
原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。
Args:
source_code: 站点实例编码(大小写敏感)。
Returns:
RpaLoginProfileView;站点或连接不存在返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
profile = site.rpa_profile if site is not None else None
if profile is None:
return None
return RpaLoginProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
login_url=profile.login_url,
login_config=dict(profile.login_config_json or {}),
username_ciphertext=profile.username_ciphertext,
password_ciphertext=profile.password_ciphertext,
enabled=bool(profile.enabled),
)
def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
"""按 source_code 返回入站配置绑定的解析方案只读视图。
用途:调拨运行期取数(movement_file_repository)、清空重建
(backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析
规则定义时调用,替代直接持有配置模型关系。
核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
不校验 status/purpose(调用方按场景自行 fail-closed,见
InboundProfileView docstring)。
Args:
source_code: 站点实例编码。
Returns:
InboundProfileView;无配置、未绑定或方案行缺失返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
config = site.inbound_report_config if site is not None else None
profile = config.parsing_profile if config is not None else None
if profile is None:
return None
return InboundProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
version=int(profile.version or 1),
status=profile.status,
purpose=profile.purpose,
definition_json=dict(profile.definition_json or {}),
)
def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView:
"""把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。"""
return InboundFileView(
file_id=report.id,
source_code=report.unit_run.source_code,
sha256=report.sha256,
storage_key=report.storage_key,
original_filename=report.original_filename,
created_at=report.created_at,
parse_failed_at=report.parse_failed_at,
)
def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool:
"""返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。
用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断
该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示
重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。
核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition,
存在任一命中即 True(纯存在性判断,不取列数据不排序)。
Args:
source_code: 来源实例编码(写在执行单元行上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
bool:存在失效但未清理的归档文件 → True;否则 False。
"""
expired = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
expired_inbound_file_condition(now=now),
)
.first()
)
return expired is not None
def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
"""维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。
用途:调拨待匹配桶「清空并重新解析」(movement_file_repository →
backlog_reparse_service,spec §6)按来源取重建清单时调用。
运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是
运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行
source_code 过滤),但【刻意无当日门禁】——重建对象正是历史
归档;保留期口径一致(archive_expires_at 为空视为长期有效)、
未删除(archive_deleted_at 为空)。按 created_at/id 升序返回
(重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询,
不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。
Args:
source_code: 来源实例编码(经执行单元行 source_code 关联)。
now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
"""
now = now or datetime.utcnow()
reports = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
.order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc())
.all()
)
return [_inbound_file_view(report) for report in reports]
def list_inbound_configured_source_codes() -> list[str]:
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
用途:在途自动调拨排程 source_codes 留空时的缺省范围
(inbound_trigger_service.list_inbound_capable_source_codes 委托本函数)
——入站文件只能来自已配置入站报表的启用站点。
核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
rows = db.session.query(FreightRpaSource.source_code).join(
FreightRpaInboundReportConfig,
FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
return [str(code) for (code,) in rows]
def latest_usable_inbound_file(
source_code: str,
*,
now: datetime | None = None,
) -> InboundFileView | None:
"""返回某来源当前「可用」的入站归档文件只读视图,最新优先。
用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有
_latest_usable_report_file 相同——经执行单元行的 source_code 过滤,
可用门禁(未删除 + 当天业务日抓取 + 未过期,见
usable_inbound_file_condition),按 created_at/id 倒序取第一条。
只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。
Returns:
InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。
"""
report = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(now=now),
)
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.first()
)
if report is None:
return None
return _inbound_file_view(report)
def read_inbound_file_bytes(file_id: int) -> bytes:
"""按 file_id 读取入站归档文件的对象字节。
用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自
持有模型 + file_asset_storage 的双跳查询。
核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError
(fail-closed);[STEP 2] 以文件的 storage_key 调
file_asset_storage.get_bytes 读取并返回字节(不含元数据)。
Args:
file_id: 归档文件主键(int;禁止传入非整数 ID)。
Returns:
文件完整字节内容。
Raises:
NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
return file_asset_storage.get_bytes(report.storage_key)
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
"""标记一份入站归档文件解析失败(写入解析失败三分层列)。
用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
使来源状态投影为 parse_failed、阻止下游当作 ready 使用。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新
parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/
parse_error_message(截断 2000)三列;[STEP 3] db.session.flush()
使同事务内投影立即可见。【不 commit】——调用方处于自己的事务,
提交/回滚归属调用方,service 层禁止越权提交。
Args:
file_id: 归档文件主键(须已入库)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
Returns:
None。失败标记随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = datetime.utcnow()
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
db.session.flush()
def clear_inbound_parse_failure(file_id: int) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被
清理/过期后调用(无业务意义)。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作
同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at /
parse_error_code / parse_error_message 置 None(三者全空即未失败的
约定态);[STEP 3] flush。【不 commit】——事务归属调用方。
Args:
file_id: 归档文件主键(须已入库)。
Returns:
None。清除随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
@@ -7,10 +7,10 @@ services/freight_rpa/upload/trigger_io.py
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相
([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换——
action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1
改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。
upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力
freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action;
schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。
"""
from __future__ import annotations
@@ -28,7 +28,7 @@ from flask import current_app
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
SCHEMA = "freight_rpa.upload.v1"
ACTION_OUTBOUND_UPLOAD = "outbound_upload"
ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload"
def _path(key: str) -> Path | None:
@@ -124,7 +124,7 @@ def write_upload_trigger(
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": ACTION_OUTBOUND_UPLOAD,
"action": ACTION_FREIGHT_RPA_UPLOAD,
"schema_version": SCHEMA,
"task_no": task_no,
"attempt_id": attempt_id,
@@ -8,7 +8,8 @@
(解析+组装单一口径)与 _detect_natural_key_collapses/_natural_key_collapse_event
(档自然键坍缩守卫与运行期同口径复用)、ledger_sync(sync_ledger_rows /
RECORD_KIND_INBOUND / FileMeta)、matching_service._effective_occupancy_filter
(占用排除口径,只读引用)、file_asset_storage、audit。
(占用排除口径,只读引用)、freight_rpa.reports.queries(站点与入站解析方案
只读入口——阶段 B Task 4 收敛)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源),
清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存,
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
@@ -42,8 +43,12 @@ from sqlalchemy import func
from app import db
from app.core.errors import AppError
from app.models import ShippingInventorySource, TransferInvoiceItem, TransferMovementLedger
from app.models import TransferInvoiceItem, TransferMovementLedger
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
get_inbound_parsing_profile,
get_site,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
_detect_natural_key_collapses,
@@ -100,24 +105,23 @@ class ReparseOutcome:
def _load_published_inbound_profile(source_code: str):
"""加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。
核心逻辑:来源(enabled)→ 收料配置 → parsing_profile,须 published 且
核心逻辑:来源(enabled)→ 入站配置 → parsing_profile,须 published 且
purpose='inbound'——与 latest_ready_file 的规则门禁一致,防止重建用了
运行期不会使用的规则口径。只读查询。
【阶段 B Task 4】读取改经 freight_rpa.reports.queries 只读入口
(get_site / get_inbound_parsing_profile),不再引用站点/报表模型;返回
InboundProfileView(code/version/definition 消费面不变)。
Args:
source_code: 来源实例编码。
Returns:
ShippingInventoryParsingProfile;无启用来源/无收料配置/规则缺失或
InboundProfileView;无启用来源/无入站配置/规则缺失或
非 published inbound 时返回 None(=无重建通道)。
"""
source = ShippingInventorySource.query.filter_by(
source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
return None
config = source.receipt_report_config
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != "published" or profile.purpose != "inbound":
return None
return profile
@@ -3,7 +3,7 @@
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
(复用 ShippingReceiptReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
(复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
@@ -18,7 +18,12 @@ from typing import Any
from flask import current_app
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
)
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
from app.services.in_transit_transfer.matching_service import (
@@ -47,6 +52,11 @@ class DefaultRouteResolver:
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经
freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型;
外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings
不改归属,见计划 Global Constraints),按站点主键直查。
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
@@ -56,14 +66,14 @@ class DefaultRouteResolver:
Raises:
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RouteNotResolvedError(source_code=source_code)
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
mappings = FreightRpaOnhandExternalMapping.query.filter_by(
source_id=site.source_id, enabled=True,
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
if site.warehouse_resolution_mode == 'inventory_match':
# [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
@@ -158,24 +168,24 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/ShippingReceiptReportConfig 缺失或 trigger
真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫: ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时
另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口
(get_site / get_inbound_config / get_inbound_parsing_profile)。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
# [守卫] ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
site = get_site(source_code)
if site is not None and site.enabled:
config = get_inbound_config(source_code)
if config is not None:
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
@@ -1,9 +1,13 @@
"""services/in_transit_transfer/evidence_sync.py
用途:入站证据同步——把来源最新可用入站文件(ShippingReceiptReport RPA 产物)解析并镜像落档(库存异动档
用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档
transfer_movement_ledger,主链路),一次解析、写档不写明细。
依赖:file_parser / ledger_sync / source_file_status / matching_service
(_latest_usable_report_file 复用)/ contracts / models / audit。
依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图
latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/
source_file_status(状态投影)/ contracts / audit。
【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file
(该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败
标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。
逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
@@ -45,6 +49,11 @@ from decimal import Decimal
from typing import Any, Mapping
from app import db
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure,
latest_usable_inbound_file,
mark_inbound_parse_failure,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.file_parser import (
@@ -57,11 +66,6 @@ from app.services.in_transit_transfer.ledger_sync import (
FileMeta,
sync_ledger_rows,
)
from app.services.in_transit_transfer.matching_service import _latest_usable_report_file
from app.services.in_transit_transfer.source_file_status import (
clear_inbound_parse_failure,
record_inbound_parse_failure,
)
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在
@@ -318,13 +322,14 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
# [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行
# commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库
# 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。
report = _latest_usable_report_file(source_code)
# 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。
file_view = latest_usable_inbound_file(source_code)
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_INBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=report.id if report is not None else None,
source_file_id=file_view.file_id if file_view is not None else None,
file_version=ready.file_version,
file_sha256=ready.checksum,
),
@@ -365,9 +370,9 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
))
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit,
# 提交归调用方。无可用 ORM 文件时为 no-op。
if report is not None and report.parse_failed_at is not None:
clear_inbound_parse_failure(report=report)
# 提交归调用方。无可用归档时为 no-op。
if file_view is not None and file_view.parse_failed_at is not None:
clear_inbound_parse_failure(file_view.file_id)
return result
@@ -375,8 +380,8 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
"""入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】:入站 RPA 回调 success 终态落文件后由
shipping_notice 域 ShippingReceiptReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingReceiptReport 归档主链路传播(B3:必须自行 commit)。
shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
@@ -407,7 +412,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
# [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃
# 绝不允许波及 ShippingReceiptReport 归档终态;丢失的落档由回调重试/人工重取兜底。
# 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
@@ -419,15 +424,15 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
# B3(任何异常不得向 ShippingReceiptReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
# B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
report = _latest_usable_report_file(source_code)
if report is not None:
record_inbound_parse_failure(
report=report,
file_view = latest_usable_inbound_file(source_code)
if file_view is not None:
mark_inbound_parse_failure(
file_view.file_id,
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
@@ -1,7 +1,7 @@
"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingReceiptReport RPA
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA
产物,shipping_notice 域术语保留);存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
@@ -1,11 +1,15 @@
"""在途调拨入站回调桥。
用途:货代入站 RPA(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留)
回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
(inbound_report_storage._advance_transfer_source_job)仍走本函数。
SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
@@ -1,70 +1,20 @@
"""在途调拨入站归档文件的可用性门禁(单一事实来源)。
"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。
用途:把「一份 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA 产物,
shipping_notice 域,术语保留)是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
入站文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
两函数同核推导,规则文本只存在一处。
用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为
freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径
(api 下载、历史消费方)透传,防止口径漂移。
依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。
逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何
freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核
推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。
"""
from __future__ import annotations
from datetime import datetime
from app.services.freight_rpa.reports.queries import (
expired_inbound_file_condition,
usable_inbound_file_condition,
)
from sqlalchemy import ColumnElement, and_, not_, or_
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.date_policy import business_date_utc_window
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
window_start, window_end = business_date_utc_window(now)
return and_(
ShippingReceiptReportFile.created_at >= window_start,
ShippingReceiptReportFile.created_at < window_end,
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"]
@@ -0,0 +1,134 @@
"""
services/in_transit_transfer/inbound_report_handler.py
用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档
终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进
调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。
依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/
配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_inbound_sinks)
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ValidationError
from app.models import FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
from app.services.in_transit_transfer.inbound_callback_bridge import (
advance_source_job_from_inbound_callback,
)
def handle_inbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
(Task 7 契约 docstring 逐字保留如上;以下为补充说明。)
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改
status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」
指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进);
[STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4]
success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖
等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档;
桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的
执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包——
freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分
前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id
——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与
failure 同一机制,绝不按来源/错误文本猜「最新单元」)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
file_id/sha256/ok/error_code/error_message)。
Returns:
None(推进/同步/收口结果全部写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。
"""
# [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由,
# 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。
kind = require_report_kind(fact.report_kind)
if kind != 'inbound':
raise ValidationError(
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定
# 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行;
# 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
if fact.ok and fact.file_id is not None:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
else:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
callback_ok=False,
error_code=fact.error_code,
error_message=fact.error_message,
)
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会
# 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。
if advanced is not None:
db.session.commit()
# [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用
# 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务
# 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。
# sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try,
# 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。
if fact.ok and fact.file_id is not None:
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
now = datetime.utcnow()
sync_and_commit_for_callback(
source_code=fact.source_code,
business_date=str(now.date()),
now=now,
)
# [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7
# 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/
# 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
# 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方——
# 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。
unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id))
if unit is None:
# 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。
from app.core.errors import NotFoundError
raise NotFoundError(
f"Inbound RPA unit not found: {fact.unit_run_id}",
details={'unit_run_id': fact.unit_run_id},
)
schedule_run_id = unit.schedule_run_id
if schedule_run_id:
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
refresh_receipt_schedule_run_progress(schedule_run_id)
finalize_receipt_schedule_run_if_complete(schedule_run_id)
@@ -1,16 +1,20 @@
"""在途调拨入站 RPA 触发服务。
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = ShippingReceiptReport RPA 产物,
复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 RPA 单元运行行(awaiting_rpa,回调按 callback_id 查库可达),
再装配入站 trigger unit 并调用 write_inbound_export_batch_trigger 原子写 trigger。
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、models、db。
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物,
复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
(awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并
调用 write_inbound_export_batch_trigger 原子写 trigger。
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、
freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile /
list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/ShippingReceiptReportConfig 缺失/rpa_profile 缺失时
一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1)
逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。
"""
from __future__ import annotations
@@ -24,6 +28,12 @@ from app.services.freight_rpa.inbound.trigger_io import (
SCHEMA,
write_inbound_export_batch_trigger,
)
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_rpa_login_profile,
get_site,
list_inbound_configured_source_codes,
)
RouteTriggerWriter = Callable[..., str | None]
@@ -34,38 +44,39 @@ def _build_trigger_unit(
"""装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None:
raise RuntimeError(f'inbound config missing: {source_code}')
profile = source.rpa_profile
profile = get_rpa_login_profile(source_code)
if profile is None or not profile.enabled:
raise RuntimeError(f'inbound source profile unavailable: {source_code}')
query_parameters = [
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
]
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'config_id': config.config_id, 'config_version': config.config_version,
'connector_type': site.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': query_parameters,
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
}
return {
'inventory_source_id': source.id,
'source_id': site.source_id,
'callback_id': f'inbound:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'source_code': site.source_code,
'connector_type': site.connector_type,
'warehouse_id': None,
'rpa_profile_id': profile.id,
'rpa_profile_id': profile.profile_id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'login_config': dict(profile.login_config or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
@@ -79,21 +90,17 @@ def _build_trigger_unit(
def list_inbound_capable_source_codes() -> list[str]:
"""列出可产出入站文件的启用来源实例(enabled 库存源 + 已配置 ShippingReceiptReport)。
"""列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件(ShippingReceiptReport
RPA 产物)只能来自已配置 ShippingReceiptReport 的站点,与货代 ShippingReceiptReport RPA 排程的站点口径一致。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件
只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。
【阶段 B Task 4】站点×入站配置 join 查询改委托
freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数
保留为调拨域语义出口(既有调用方 import 路径不变)。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource.source_code).join(
ShippingReceiptReportConfig,
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
return [str(code) for (code,) in rows]
return list_inbound_configured_source_codes()
def trigger_inbound_rpa(
@@ -122,11 +129,11 @@ def trigger_inbound_rpa(
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
unit = ShippingInboundRpaUnitRun(
unit = FreightRpaInboundUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
inventory_source_id=unit_payload['inventory_source_id'],
source_id=unit_payload['source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
@@ -192,13 +199,13 @@ def trigger_inbound_rpa_batch(
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingInboundRpaUnitRun] = []
units: list[FreightRpaInboundUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
@@ -234,8 +241,8 @@ def trigger_inbound_rpa_batch(
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingInboundRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
unit = FreightRpaInboundUnitRun(
source_id=payload['source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
@@ -45,7 +45,7 @@ assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 记录种类字面量:inbound=入站(ShippingReceiptReport RPA 产物,shipping_notice 域术语保留);
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
# outbound=出站(出货侧结构就位)。
RECORD_KIND_INBOUND = "inbound"
RECORD_KIND_OUTBOUND = "outbound"
@@ -58,7 +58,7 @@ class FileMeta:
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
Args:
source_file_id: 入站原样归档文件 id(shipping_receipt_report_files.id;
source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id;
测试/极端场景可为 None——档事实留存不依赖文件存在)。
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
@@ -158,7 +158,7 @@ def sync_ledger_rows(
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingReceiptReport
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport
RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。
parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code
(movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与
@@ -6,7 +6,9 @@
依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/
scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/
source_file_status / capability_client / date_policy / quantity / contracts /
audit / models。
audit / models。【阶段 B Task 4】取可用入站归档文件的查询已删除并收口到
freight_rpa.reports.queries.latest_usable_inbound_file(匹配不再引用
freight_rpa 报表模型;证据链消费方见 evidence_sync)。
逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind=
'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false +
@@ -40,7 +42,6 @@ from sqlalchemy import and_, or_
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import (
ShippingReceiptReportFile,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
@@ -70,7 +71,6 @@ from app.services.in_transit_transfer.file_preparation import (
)
from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
from app.services.in_transit_transfer.scope_rules import (
ScopeRule,
apply_scope_filters,
@@ -201,37 +201,6 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun
return "success"
def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None:
"""返回某来源当前「可用」(当天抓取且未清理未过期)的入站归档文件,最新优先。
【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用
文件上(parse_failed 三列)、或落档成功后清除其标记、或档落地回填
source_file_id 时调用——查询口径与
source_file_status.resolve_source_file_status 的可用文件判定一致
(inbound_file_gate.usable_inbound_file_condition),防止两处口径漂移。
核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run
关联单元运行行的 source_code)+ 可用门禁过滤;[STEP 2] 按
created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(入站执行单元行上的 source_code)。
Returns:
最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/
已清理)返回 None。
"""
return (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
def _validate_movement_date_range(
business_date: str, movement_date_from: str | None, movement_date_to: str | None,
) -> tuple[date | None, date | None]:
@@ -41,7 +41,7 @@ class MovementField:
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingReceiptReport External ASN #);
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #);
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
@@ -1,18 +1,23 @@
"""在途调拨真实异动(入站/出站)文件仓库。
用途:读取货代入站链路已落库的 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA
产物,shipping_notice 域术语保留;对象存储原始 xlsx),
用该来源 ShippingReceiptReportConfig 绑定的 inbound 解析规则(purpose='inbound',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖: ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、inbound_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站
RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound
解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的
field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
file_preparation(ReadyInboundFile 契约)、openpyxl。
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):同一 join
路径但显式去掉当日门禁,仅供 backlog_reparse_service 使用,运行期禁用。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):
委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供
backlog_reparse_service 使用,运行期禁用。
"""
from __future__ import annotations
@@ -23,11 +28,15 @@ from datetime import datetime
from io import BytesIO
from typing import Any, Mapping
from sqlalchemy import or_
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
latest_usable_inbound_file,
list_reparseable_inbound_files,
read_inbound_file_bytes,
)
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
@@ -38,7 +47,7 @@ class ReparseableArchiveFile:
"""一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。
Args:
file_id: 归档文件 id(shipping_receipt_report_files.id,档行溯源列同源)。
file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。
storage_key: 对象存储键(重建时按此取归档字节)。
sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。
file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。
@@ -66,14 +75,24 @@ def _normalize_header_label(value: Any) -> str:
class ShippingInboundFileRepository:
"""真实入站/异动 ready 文件仓库(复用 ShippingReceiptReport 归档 + inbound 解析规则)。"""
"""真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。
def __init__(self) -> None:
self._storage = file_asset_storage
【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读
入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方
(file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。
核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在
(get_inbound_config)+ 绑定解析方案须 published inbound
(get_inbound_parsing_profile,与运行期规则门禁同一口径);
[STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天
fail-closed 门禁见 queries.usable_inbound_file_condition)并按
file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案
field_mapping 提取领域行。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示,不强制匹配文件日期)。
@@ -81,45 +100,34 @@ class ShippingInboundFileRepository:
ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 inbound_file_gate。
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
view = latest_usable_inbound_file(source_code)
if view is None:
return None
data = self._storage.get_bytes(report.storage_key)
definition = profile.definition_json or {}
data = read_inbound_file_bytes(view.file_id)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
field_mapping=dict(definition.get('field_mapping') or {}),
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
header_row_index=definition.get('header_row_index'),
)
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
file_no=view.original_filename or str(view.file_id),
file_version=f"sha256:{view.sha256}"[:64],
checksum=view.sha256,
rows=tuple(rows),
)
@@ -130,13 +138,11 @@ class ShippingInboundFileRepository:
(evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义,
本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_ready_file 的归档文件查询同款
(ShippingReceiptReportFile → unit_run.has(source_code=...)),但显式去掉
「当天业务日抓取」新鲜度门禁——重建对象正是历史归档;保留期口径与
inbound_file_gate 一致(archive_expires_at 为空视为长期有效),未清理
(archive_deleted_at 空)且未过保留期(expires > now)才可重建。按归档
时间升序返回(重建必须按归档时间序重落,保证幂等重放顺序确定)。
只读查询,不触碰对象存储字节(字节由调用方按需经 file_asset_storage 取)。
核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files
维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁——
重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的
维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节
由调用方按需经 file_asset_storage 取)。
Args:
source_code: 来源实例编码(经收料执行单元行 source_code 关联)。
@@ -144,34 +150,16 @@ class ShippingInboundFileRepository:
Returns:
ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。
"""
from app.models import ShippingReceiptReportFile
reports = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 维护通道可用性 = 未清理 + 未过保留期(NULL=长期有效,与
# inbound_file_gate 保留期口径一致);【刻意无当日门禁】。
ShippingReceiptReportFile.archive_deleted_at.is_(None),
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
.order_by(ShippingReceiptReportFile.created_at.asc(), ShippingReceiptReportFile.id.asc())
.all()
)
return [
ReparseableArchiveFile(
file_id=report.id,
storage_key=report.storage_key,
sha256=report.sha256,
file_version=f"sha256:{report.sha256}"[:64],
archived_at=report.created_at,
original_filename=report.original_filename,
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=f"sha256:{view.sha256}"[:64],
archived_at=view.created_at,
original_filename=view.original_filename,
)
for report in reports
for view in list_reparseable_inbound_files(source_code, now=now)
]
@@ -196,7 +184,7 @@ def _extract_movement_rows(
header_row_index: 1-based 表头行;空则自动探测。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
@@ -251,4 +239,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
return output
@@ -1,30 +1,31 @@
"""在途调拨来源入站文件状态投影服务。
用途:只读货代入站链路(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留)
已有事实(ShippingInboundRpaUnitRun 别名 + ShippingReceiptReportFile),
用途:只读货代入站链路已有事实(入站执行单元行 + freight_rpa 入站归档文件),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile ,前者经域内别名引用)、
inbound_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新入站执行单元;命中可用门禁(当天业务日抓取且未过期,
见 inbound_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
有进行中单元 → fetching;最新单元为失败终态 → failed;
文件仍在但已失效 → expired;否则 → none。
record_inbound_parse_failure / clear_inbound_parse_failure 维护解析失败三列
(写入与清除均只 flush 不 commit,事务归属调用方)。
依赖:freight_rpa.reports.queries(最新可用入站归档 / 失效文件存在性 / 解析失败
标记的只读写入口——口径唯一权威);入站执行单元行模型(经域内别名引用)。
逻辑:【阶段 B Task 4】模型查询全部改走 freight_rpa.reports.queries 只读入口——
可用文件命中(当天业务日抓取且未过期未清理,口径见
queries.usable_inbound_file_condition)→ ready,但文件已标记解析失败
(parse_failed_at 非空)→ parse_failed(不可当 ready,仍带 file_no/
file_sha256 便于诊断);有进行中单元 → fetching;最新单元为失败终态 →
failed;空数据单元 → no_data;文件仍在但已失效 → expired;否则 → none。
record/clear_inbound_parse_failure 保留为兼容薄壳(既有调用方按 ORM 文件
对象传参),内部按主键委托 queries.mark/clear 同一实现(写入与清除均只
flush 不 commit,事务归属调用方)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingReceiptReportFile
from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun
from app.services.in_transit_transfer.inbound_file_gate import (
expired_inbound_file_condition,
usable_inbound_file_condition,
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
has_expired_inbound_file,
latest_usable_inbound_file,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
@@ -38,7 +39,8 @@ def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的入站文件状态投影。
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
inbound_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
freight_rpa.reports.queries 的可用/失效条件):保留期已到 或 非当前业务日
(Asia/Shanghai)抓取。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
@@ -46,47 +48,41 @@ def resolve_source_file_status(*, source_code: str) -> dict:
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is not None:
# 【阶段 B Task 4】可用文件读取经 freight_rpa.reports.queries 只读视图
# (file_no/failure 事实列随视图一次取得,不再引用归档文件模型)。
file_view = latest_usable_inbound_file(source_code)
if file_view is not None:
file_no = file_view.original_filename or str(file_view.file_id)
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
if report.parse_failed_at is not None:
if file_view.parse_failed_at is not None:
return {
'file_status': 'parse_failed',
'has_ready_file': False,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
active_unit = (
ShippingInboundRpaUnitRun.query
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingInboundRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingInboundRpaUnitRun.id.desc())
.filter(FreightRpaInboundUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(FreightRpaInboundUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingInboundRpaUnitRun.query
FreightRpaInboundUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingInboundRpaUnitRun.id.desc())
.order_by(FreightRpaInboundUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
@@ -96,16 +92,8 @@ def resolve_source_file_status(*, source_code: str) -> dict:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
expired_report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
expired_inbound_file_condition(),
)
.first()
)
if expired_report is not None:
# 【阶段 B Task 4】失效存在性经 queries.has_expired_inbound_file(与可用条件同核)。
if has_expired_inbound_file(source_code):
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -113,10 +101,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
def record_inbound_parse_failure(
*,
report: ShippingReceiptReportFile,
report: Any,
error_code: str,
error_message: str,
now: datetime | None = None,
) -> None:
"""标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
@@ -124,40 +111,34 @@ def record_inbound_parse_failure(
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_inbound_parse_failure。
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/
错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已
收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现);
本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。
Args:
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
report: 入站归档文件对象(仅取主键 .id;须已入库)。
error_code: 机器可读错误码(真实现内按列宽截断)。
error_message: 人类可读错误信息(真实现内做防御性截断)。
Returns:
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
None。失败标记随调用方事务落库。
"""
report.parse_failed_at = now or datetime.utcnow()
report.parse_error_code = (error_code or '')[:64]
report.parse_error_message = (error_message or '')[:2000]
db.session.flush()
_mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message)
def clear_inbound_parse_failure(*, report: ShippingReceiptReportFile) -> None:
def clear_inbound_parse_failure(*, report: Any) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象
主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列
后 flush,不 commit,事务归属调用方)。
Args:
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
report: 入站归档文件对象(仅取主键 .id;须已入库)。
Returns:
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
None。清除随调用方事务落库。
"""
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
_clear_parse_failure_by_id(report.id)
+2 -2
View File
@@ -343,8 +343,8 @@ def _register_headers_from_config() -> None:
for name, cfg in get_all_schedule_sql_configs().items():
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.freight_onhand_rpa_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_inbound_rpa_finalize import register_receipt_rpa_excel_headers
from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_rpa_inbound_finalize import register_receipt_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/freight_inbound_rpa_archive.py
backend/app/services/schedule/freight_rpa_inbound_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
file_asset_storage、timezone_util、freight_inbound_rpa_finalize.is_freight_receipt_rpa_task。
依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、
file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
@@ -21,9 +21,9 @@ from typing import Any
from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_inbound_rpa_finalize import is_freight_receipt_rpa_task
from app.services.schedule.freight_rpa_inbound_finalize import is_freight_receipt_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
@@ -111,7 +111,7 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。"""
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。"""
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
@@ -127,20 +127,20 @@ def _iter_packable_receipt_files(run: ScheduleRun):
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
Yields:
ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。
FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_receipt_rpa_task(getattr(run, 'task', None)):
return
rows = (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun,
ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
FreightRpaInboundReportFile.query.join(
FreightRpaInboundUnitRun,
FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
FreightRpaInboundUnitRun.schedule_run_id == run.id,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id.asc())
.order_by(FreightRpaInboundReportFile.id.asc())
.all()
)
for report_file in rows:
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/freight_inbound_rpa_finalize.py
backend/app/services/schedule/freight_rpa_inbound_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:ShippingReceiptRpaUnitRun、freight_inbound_rpa_archive、scheduler_service 企微通知。
依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
@@ -18,10 +18,10 @@ from sqlalchemy import func
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.freight_inbound_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_rpa_inbound_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -57,7 +57,7 @@ def register_receipt_rpa_excel_headers() -> None:
)
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]:
def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]:
"""
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
@@ -144,7 +144,7 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
@@ -239,7 +239,7 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return {'updated': False, 'reason': 'callback_id_required'}
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
return {'updated': False, 'reason': 'unit_not_found'}
if unit.status in {'success', 'empty', 'failed', 'cancelled'}:
@@ -268,7 +268,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
return {'finalized': False, 'reason': 'units_pending'}
@@ -315,7 +315,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_inbound_rpa_archive import receipt_rpa_result_excel_name
from app.services.schedule.freight_rpa_inbound_archive import receipt_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
run.excel_file_data = excel_data
@@ -331,7 +331,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'raw_receipt_zip_size': 0,
}
try:
from app.services.schedule.freight_inbound_rpa_archive import persist_receipt_rpa_raw_zip_archive
from app.services.schedule.freight_rpa_inbound_archive import persist_receipt_rpa_raw_zip_archive
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
except Exception as archive_exc:
@@ -381,7 +381,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
)
def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime:
def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
@@ -399,7 +399,7 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR
def _fail_receipt_unit_with_timeout(
unit: ShippingReceiptRpaUnitRun, *, now: datetime, timeout_seconds: int,
unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
@@ -422,7 +422,7 @@ def _fail_receipt_unit_with_timeout(
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
@@ -442,7 +442,7 @@ def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_se
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
return False
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
@@ -516,11 +516,11 @@ def recover_all_stale_orphan_receipt_units() -> int:
timeout_seconds = _receipt_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
ShippingReceiptRpaUnitRun.query
FreightRpaInboundUnitRun.query
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id.is_(None),
ShippingReceiptRpaUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(ShippingReceiptRpaUnitRun.started_at, ShippingReceiptRpaUnitRun.created_at) < cutoff,
FreightRpaInboundUnitRun.schedule_run_id.is_(None),
FreightRpaInboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(FreightRpaInboundUnitRun.started_at, FreightRpaInboundUnitRun.created_at) < cutoff,
)
.all()
)
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/freight_inbound_rpa_job.py
backend/app/services/schedule/freight_rpa_inbound_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
@@ -16,7 +16,7 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
@@ -37,16 +37,16 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
return {str(value).strip().upper() for value in values if str(value).strip()}
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]:
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).all()
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]:
def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
@@ -55,8 +55,8 @@ def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str
def _build_unit(
source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int,
) -> ShippingReceiptRpaUnitRun:
source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int,
) -> FreightRpaInboundUnitRun:
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
@@ -64,16 +64,16 @@ def _build_unit(
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
return FreightRpaInboundUnitRun(
schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]:
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。"""
source = unit.inventory_source
source = unit.source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}')
@@ -105,7 +105,7 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_receipt_rpa。
"""
units: list[ShippingReceiptRpaUnitRun] = [
units: list[FreightRpaInboundUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
@@ -1,9 +1,9 @@
"""收料原样归档三年到期对象清理(排程壳)。
批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive
(run_freight_inbound_rpa_retention_schedule,函数名 receipt 词根→inbound);
(run_freight_rpa_inbound_retention_schedule,函数名 receipt 词根→inbound);
本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册,
Task 11 已随排程壳平移改名为 freight_inbound_rpa_retention,git mv 保留历史)。
Task 11 已随排程壳平移改名为 freight_rpa_inbound_retention,git mv 保留历史)。
"""
from __future__ import annotations
@@ -13,6 +13,6 @@ from typing import Any
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。"""
from app.services.freight_rpa.inbound.report_archive import run_freight_inbound_rpa_retention_schedule
from app.services.freight_rpa.inbound.report_archive import run_freight_rpa_inbound_retention_schedule
return run_freight_inbound_rpa_retention_schedule(task, run)
return run_freight_rpa_inbound_retention_schedule(task, run)
@@ -1,8 +1,8 @@
"""
backend/app/services/schedule/freight_onhand_rpa_archive.py
backend/app/services/schedule/freight_rpa_onhand_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、freight_onhand_rpa_finalize.is_shipping_inventory_rpa_task。
依赖:ScheduleRun、FreightRpaOnhandReportFile、freight_rpa_onhand_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
@@ -21,8 +21,8 @@ from flask import current_app
from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.freight_onhand_rpa_finalize import is_shipping_inventory_rpa_task
from app.models import ScheduleRun, FreightRpaOnhandReportFile
from app.services.schedule.freight_rpa_onhand_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -98,7 +98,7 @@ def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
return f"{onhand_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
@@ -107,7 +107,7 @@ def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
return f"{onhand_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -139,10 +139,10 @@ def _iter_packable_inventory_files(
"""
遍历可实际打包的库存快照。
核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。
核心逻辑:需存在 FreightRpaOnhandReportFile 且 storage_path 指向可读文件。
Yields:
tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。
tuple[dict, FreightRpaOnhandReportFile, Path]: created 项、快照记录、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
@@ -154,8 +154,8 @@ def _iter_packable_inventory_files(
continue
inv_file = (
db.session.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/freight_onhand_rpa_finalize.py
backend/app/services/schedule/freight_rpa_onhand_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:freight_onhand_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;onhand_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
"""
@@ -276,7 +276,7 @@ def _try_recover_stale_awaiting_run(
finished_at = datetime.utcnow()
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "failed",
"detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds},
})
@@ -495,13 +495,13 @@ def _finalize_shipping_inventory_schedule_run_impl(
status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_onhand_rpa_archive import inventory_rpa_result_excel_name
from app.services.schedule.freight_rpa_onhand_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed",
"detail": {
"created_count": success_count,
@@ -537,7 +537,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"raw_inventory_zip_size": 0,
}
try:
from app.services.schedule.freight_onhand_rpa_archive import persist_inventory_rpa_raw_zip_archive
from app.services.schedule.freight_rpa_onhand_archive import persist_inventory_rpa_raw_zip_archive
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
except Exception as archive_exc:
@@ -1,10 +1,10 @@
"""
backend/app/services/schedule/freight_onhand_rpa_job.py
backend/app/services/schedule/freight_rpa_onhand_job.py
用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。
依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
依赖:onhand_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 freight_onhand_rpa_finalize 在 RPA 回调时写入。
写 trigger 后返回 awaiting_rpa_callback;终态由 freight_rpa_onhand_finalize 在 RPA 回调时写入。
"""
from __future__ import annotations
@@ -16,8 +16,8 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.freight_onhand_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.schedule.freight_rpa_onhand_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
@@ -105,21 +105,21 @@ def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
return enabled
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
def run_freight_rpa_onhand_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。
核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。
"""
sources = _filter_sources(task)
step_logs: list[dict[str, Any]] = [{
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "started",
"detail": {"source_count": len(sources)},
}]
if not sources:
message = "no enabled inventory sources"
step_logs.append({"step": "shipping_inventory_rpa", "status": "skipped", "detail": {"message": message}})
step_logs.append({"step": "freight_rpa_onhand", "status": "skipped", "detail": {"message": message}})
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
@@ -139,7 +139,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get("detail_message") or message)
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "failed",
"detail": {
"message": message,
@@ -151,7 +151,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
return len(sources), 0, len(sources), 0, [], [detail_message], step_logs
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
step_logs.append({"step": "freight_rpa_onhand", "status": "failed", "detail": {"message": message}})
return len(sources), 0, len(sources), 0, [], [message], step_logs
run.api_request_json = {
@@ -162,7 +162,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
db.session.commit()
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": AWAITING_RPA_CALLBACK_STATUS,
"detail": {"trigger_path": trigger_path, "run_no": run_no},
})
+9 -8
View File
@@ -2,9 +2,10 @@
backend/app/services/schedule/job_options.py
用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。
依赖:models.Agent、shipping_notice.inventory_source_repository。
依赖:models.Agent、shipping_notice.onhand_source_repository。
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
货代 RPA 注册键为 freight_rpa_sources 与 freight_rpa_inbound_sources。
"""
from __future__ import annotations
@@ -35,7 +36,7 @@ def _agent_apps_options() -> list[dict[str, Any]]:
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
"""启用中的货代库存源(value=source_code,来自数据库主数据)。"""
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
return [
{
@@ -53,11 +54,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).all()
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
@@ -101,8 +102,8 @@ def _users_options() -> list[dict[str, Any]]:
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"shipping_inventory_sources": _shipping_inventory_sources_options,
"shipping_receipt_sources": _shipping_receipt_sources_options,
"freight_rpa_sources": _shipping_inventory_sources_options,
"freight_rpa_inbound_sources": _shipping_receipt_sources_options,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+15 -15
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:freight_onhand_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
依赖:freight_rpa_onhand_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -34,7 +34,7 @@ class PlatformJobDefinition:
"label_key": "...", # 前端 i18n key(可选)
"required": False,
"default": [],
"options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选)
"options_source": "freight_rpa_sources", # select/multi_select 动态选项来源(可选)
"placeholder": "...", "placeholder_key": "...",
"help": "...", "help_key": "...",
}
@@ -44,7 +44,7 @@ class PlatformJobDefinition:
label: str
handler: PlatformJobHandler
description: str = ""
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
# 前端 i18n key(如 admin.schedule.form.platformJobFreightRpaOnhand);
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
label_key: str = ""
description_key: str = ""
@@ -132,9 +132,9 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_inbound_rpa_retention import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_rpa_inbound_retention import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
@@ -373,25 +373,25 @@ def _register_builtin_platform_jobs() -> None:
register_platform_job(PlatformJobDefinition(
key="freight-rpa-onhand",
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
label_key="admin.schedule.form.platformJobFreightRpaOnhand",
handler=run_freight_rpa_onhand_schedule,
description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。",
description_key="admin.schedule.form.shippingInventoryJobHint",
description_key="admin.schedule.form.freightRpaOnhandJobHint",
category="shipping",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "库存源",
"label_key": "admin.schedule.form.shippingInventorySources",
"label_key": "admin.schedule.form.freightRpaSources",
# 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
"options_source": "freight_rpa_sources",
"placeholder": "留空则导出全部启用库存源",
"placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder",
"placeholder_key": "admin.schedule.form.freightRpaSourcesPlaceholder",
"help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
"help_key": "admin.schedule.form.shippingInventorySourcesHelp",
"help_key": "admin.schedule.form.freightRpaSourcesHelp",
},
),
defaults={"source_codes": []},
@@ -404,7 +404,7 @@ def _register_builtin_platform_jobs() -> None:
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
"default": [], "options_source": "shipping_receipt_sources",
"default": [], "options_source": "freight_rpa_inbound_sources",
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
},),
defaults={"source_codes": []},
@@ -596,7 +596,7 @@ def _register_builtin_platform_jobs() -> None:
"label_key": "admin.schedule.form.transferSourceCodes",
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
"options_source": "freight_rpa_sources",
},
{
"key": "recover_history",
@@ -9,8 +9,8 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -19,11 +19,11 @@ from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.freight_onhand_rpa_finalize import (
from app.services.schedule.freight_rpa_onhand_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_inbound_rpa_finalize import (
from app.services.schedule.freight_rpa_inbound_finalize import (
recover_all_stale_orphan_receipt_units,
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
@@ -332,7 +332,7 @@ def prepare_schedule_queue() -> int:
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.freight_onhand_rpa_finalize import is_awaiting_rpa_schedule_run
from app.services.schedule.freight_rpa_onhand_finalize import is_awaiting_rpa_schedule_run
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
@@ -379,7 +379,7 @@ def prepare_schedule_queue() -> int:
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_inbound_rpa_finalize。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
@@ -23,8 +23,9 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
# 仍在导入 JSON 里出现的历史 data_source。货代在手任务的旧键已由 s17c 整列改写,
# 运行期只认 platform job key freight-rpa-onhand。
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
"shipping_inventory_rpa": "freight-rpa-onhand",
"faq_hot_aggregate": "faq-aggregate-hot",
}
@@ -18,19 +18,19 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User
from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, User
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
from app.services.schedule.freight_inbound_rpa_job import INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_onhand_rpa_finalize import (
from app.services.schedule.freight_rpa_inbound_job import INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_rpa_onhand_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_inbound_rpa_finalize import (
from app.services.schedule.freight_rpa_inbound_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
@@ -106,8 +106,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
@@ -123,7 +123,7 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
return params
def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]:
def _receipt_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
@@ -131,7 +131,7 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
task = run.task
if (
@@ -141,14 +141,14 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
):
return []
return (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
FreightRpaInboundReportFile.query.join(
FreightRpaInboundUnitRun, FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
FreightRpaInboundUnitRun.schedule_run_id == run.id,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id)
.order_by(FreightRpaInboundReportFile.id)
.all()
)
@@ -171,8 +171,8 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
@@ -238,7 +238,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
raw_zip_media_id = None
raw_zip_file_name = None
try:
from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
@@ -251,7 +251,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
receipt_zip_media_id = None
receipt_zip_file_name = None
try:
from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download
from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(
@@ -16,7 +16,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import (
coordinate_post_ot_auto_fulfill,
enqueue_post_ot_auto_fulfill_job,
)
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
list_eligible_post_ot_snapshot_line_ids,
)
@@ -5,7 +5,7 @@ services/shipping_notice/auto_progress_controller.py
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 onhand_preparation 时
覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。
库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
@@ -22,7 +22,7 @@ from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice.tool_common import log_task_event
@@ -149,8 +149,8 @@ def determine_formal_start_gate(
return 'field_conflict_resolution'
candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task)
if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen':
return 'inventory_source_routing'
return 'inventory_preparation'
return 'onhand_source_routing'
return 'onhand_preparation'
def _create_formal_execution_for_task(
@@ -418,7 +418,7 @@ def submit_auto_progress(
# (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照),
# 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。
explicit_inventory_retry = (
str(resume_gate_code or '').strip() == 'inventory_preparation'
str(resume_gate_code or '').strip() == 'onhand_preparation'
and (
str(inventory_mode or '').strip() == 'retry_rpa'
or str(trigger or '').strip() == 'manual_override_source'
@@ -433,7 +433,7 @@ def submit_auto_progress(
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = (
'inventory_preparation'
'onhand_preparation'
if explicit_inventory_retry
else str(execution.current_gate_code or '').strip() or None
)
@@ -479,16 +479,16 @@ def submit_auto_progress(
stale_job.message = '显式库存重抓:取消残留活动 Job'
gate.status = 'blocked_retryable'
gate.passed_at = None
gate.blocking_reason_code = 'inventory_rpa_retry_requested'
gate.next_action_code = 'retry_inventory_preparation'
gate.blocking_reason_code = 'onhand_rpa_retry_requested'
gate.next_action_code = 'retry_onhand_preparation'
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.lock_version = int(gate.lock_version) + 1
gate.updated_at = _utc_now()
execution.current_gate_code = 'inventory_preparation'
execution.current_gate_code = 'onhand_preparation'
# 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate
# 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。
execution.responsible_party = 'worker'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.primary_next_action_code = 'retry_onhand_preparation'
execution.updated_at = _utc_now()
db.session.flush()
active_attempt = (
@@ -532,7 +532,7 @@ def submit_auto_progress(
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
# upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步
# upload_onhand_file 等导航动作必须保留给用户;否则成功回调已同步
# 的库存事实会被旧人工阻断动作再次覆盖。
if (
gate is not None
@@ -57,7 +57,7 @@ def _unmark_running(bucket: set[str], key: str) -> None:
def _should_orchestrate_task(task: Any) -> bool:
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
if not task_is_active(task):
return False
@@ -100,7 +100,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {"status": "skipped", "message": "task already running"}
try:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
task = get_task_by_ref(normalized_task_no)
if not task:
@@ -130,7 +130,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
):
# [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
# rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
from app.services.shipping_notice.onhand_rpa_workflow import maybe_recheck_inventory_rpa_wait
recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator')
if recheck is not None:
@@ -65,7 +65,7 @@ _PROCESSING_ITEM_LIFECYCLES = frozenset({
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'onhand_matching',
'generating_excel',
})
@@ -13,7 +13,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingOrderTask, ShippingTemporaryInventorySession
from app.models import ShippingOrderTask, ShippingTemporaryOnhandSession
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
@@ -40,18 +40,18 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
normalized = str(conversation_id or '').strip()
if not normalized:
return None
item = ShippingTemporaryInventorySession.query.filter(
ShippingTemporaryInventorySession.conversation_id == normalized,
ShippingTemporaryInventorySession.status.in_([
item = ShippingTemporaryOnhandSession.query.filter(
ShippingTemporaryOnhandSession.conversation_id == normalized,
ShippingTemporaryOnhandSession.status.in_([
'created',
'awaiting_profile_confirmation',
'awaiting_mapping_suggestion',
'awaiting_mapping_confirmation',
]),
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(),
).order_by(
ShippingTemporaryInventorySession.updated_at.desc(),
ShippingTemporaryInventorySession.id.desc(),
ShippingTemporaryOnhandSession.updated_at.desc(),
ShippingTemporaryOnhandSession.id.desc(),
).first()
return str(item.session_no or '').strip().upper() or None if item else None
@@ -145,7 +145,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES: Final[frozenset[str]] = frozenset({
'manual_inventory_source_invalid',
'inventory_source_conflicted',
'inventory_source_changed',
'inventory_source_identity_mismatch',
'onhand_source_identity_mismatch',
})
# 库存源路由 — 单源不可用明细(写入 unavailable_reasons[source_code])
@@ -162,11 +162,11 @@ INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES: Final[frozenset[str]] = frozenset({
INVENTORY_PREP_REASON_CODES: Final[frozenset[str]] = frozenset({
'inventory_preparation_waiting',
'inventory_preparation_failed',
'inventory_rpa_queued',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_rpa_exhausted',
'onhand_rpa_queued',
'onhand_rpa_timeout',
'onhand_rpa_login_failed',
'onhand_rpa_export_failed',
'onhand_rpa_exhausted',
'inventory_file_missing',
'inventory_file_identity_mismatch',
'inventory_file_empty',
@@ -292,7 +292,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED: Final[frozenset[str]] = frozen
'manual_inventory_source_invalid',
'inventory_source_conflicted',
'inventory_source_changed',
'inventory_source_identity_mismatch',
'onhand_source_identity_mismatch',
})
# 附件告警已映射并可出现在审计 / Intake 投影中的子集
@@ -310,11 +310,11 @@ ATTACHMENT_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
INVENTORY_PREP_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'inventory_preparation_waiting',
'inventory_preparation_failed',
'inventory_rpa_queued',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_rpa_exhausted',
'onhand_rpa_queued',
'onhand_rpa_timeout',
'onhand_rpa_login_failed',
'onhand_rpa_export_failed',
'onhand_rpa_exhausted',
'inventory_file_missing',
'inventory_file_empty',
'inventory_file_identity_mismatch',
@@ -560,25 +560,25 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'source_excel_template_unavailable': _meta('admin', 'retry_with_latest_rules', '库存 Excel 模板未发布'),
'inventory_source_conflicted': _meta('system', 'retry_with_latest_rules', '多条规则产生冲突,需修复规则后自动重新裁决'),
'inventory_source_changed': _meta('system', 'retry_with_latest_rules', '库存源配置已变化,系统将重新裁决'),
'inventory_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'),
'onhand_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'),
'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'),
# 库存准备 / RPA / 匹配 / Excel / 上传
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'),
'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'),
'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'),
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'),
'inventory_preparation_waiting': _meta('worker', 'poll_onhand_preparation', '库存文件准备中,请稍后刷新'),
'inventory_preparation_failed': _meta('owner', 'retry_onhand_preparation', '库存准备失败,请重试或上传库存文件'),
'onhand_rpa_queued': _meta('worker', 'poll_onhand_preparation', 'RPA 任务已排队等待执行'),
'onhand_rpa_timeout': _meta('worker', 'reload_onhand_result', 'RPA 执行超时'),
'onhand_rpa_login_failed': _meta('admin', 'retry_onhand_preparation', '库存平台登录失败'),
'onhand_rpa_export_failed': _meta('worker', 'retry_onhand_preparation', '库存报表导出失败'),
'onhand_rpa_exhausted': _meta('owner', 'reload_onhand_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'retry_onhand_preparation', '未生成库存文件'),
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
'inventory_match_out_of_candidate_scope': _meta('system', 'retry_with_latest_rules', '库存命中超出当前候选范围'),
'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'),
'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'),
'inventory_mapping_required': _meta('system', 'retry_inventory_field_mapping', '库存字段映射待自动校验'),
'inventory_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'),
'inventory_file_identity_mismatch': _meta('owner', 'retry_onhand_preparation', '返回文件与所选库存源不一致'),
'inventory_file_empty': _meta('owner', 'retry_onhand_preparation', '库存文件为空或没有有效库存记录'),
'inventory_mapping_required': _meta('system', 'retry_onhand_field_mapping', '库存字段映射待自动校验'),
'inventory_match_failed': _meta('owner', 'open_onhand_match_review', '库存匹配失败'),
'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'),
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
@@ -607,13 +607,13 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'),
'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'),
'inventory_required_column_missing': _meta('system', 'retry_inventory_field_mapping', '库存文件缺少必填列'),
'inventory_column_ambiguous': _meta('system', 'retry_inventory_field_mapping', '库存列映射存在歧义'),
'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'),
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'),
'inventory_required_column_missing': _meta('system', 'retry_onhand_field_mapping', '库存文件缺少必填列'),
'inventory_column_ambiguous': _meta('system', 'retry_onhand_field_mapping', '库存列映射存在歧义'),
'inventory_sku_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 SKU'),
'inventory_reservation_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 Reservation'),
'inventory_warehouse_mismatch': _meta('owner', 'open_onhand_match_review', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_onhand_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'override_line_onhand_source', '多库存文件结果冲突'),
}
@@ -970,7 +970,7 @@ AUDIT_COVERAGE_MATRIX: Final[tuple[dict[str, Any], ...]] = (
'node': 'late_rpa_callback_ignored',
'event_type': 'rpa_callback_rejected',
'reason_code': 'late_callback_ignored',
'source_module': 'inventory_rpa_workflow.py',
'source_module': 'onhand_rpa_workflow.py',
'wire_marker': '"reason_code": "late_callback_ignored"',
'allow_empty': False,
},
@@ -1035,8 +1035,8 @@ def assert_error_explainability_contract_integrity() -> None:
'inventory_source_unavailable',
'require_manual_review',
):
assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'inventory_source_routing', (
f'{code} must own inventory_source_routing'
assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'onhand_source_routing', (
f'{code} must own onhand_source_routing'
)
# [STEP 4] meta 责任方与动作合法性
@@ -26,8 +26,8 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
FreightRpaOnhandField,
FreightRpaSource,
ShippingOrderField,
)
from app.services.file_assets.storage import file_asset_storage
@@ -327,7 +327,7 @@ def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]:
inventory_field_id = int(source_key)
except (TypeError, ValueError) as exc:
raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc
inventory_field = db.session.get(ShippingInventoryField, inventory_field_id)
inventory_field = db.session.get(FreightRpaOnhandField, inventory_field_id)
if inventory_field is None or inventory_field.status != 'active':
raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
source_key = str(inventory_field.id)
@@ -371,7 +371,7 @@ def retire(template_id: int) -> dict[str, Any]:
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
if item.status != 'published':
raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID')
if ShippingInventorySource.query.filter_by(excel_template_id=item.id).count():
if FreightRpaSource.query.filter_by(excel_template_id=item.id).count():
raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED')
item.status = 'retired'
db.session.commit()
+40 -31
View File
@@ -33,9 +33,9 @@ from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryField,
ShippingInventorySource,
ShippingNoticeLineOnhandMatch,
FreightRpaOnhandField,
FreightRpaSource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
@@ -58,11 +58,11 @@ def _notice_source_code(task: ShippingNotice) -> str | None:
task_id = int(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
).distinct().all()
if row[0]
]
@@ -76,10 +76,10 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
return None
values = [
str(row[0]).strip()
for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter(
ShippingNoticeLineInventoryMatch.task_id == int(task_id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None),
for row in db.session.query(ShippingNoticeLineOnhandMatch.chosen_odm_id).filter(
ShippingNoticeLineOnhandMatch.task_id == int(task_id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.chosen_odm_id.isnot(None),
).distinct().all()
if row[0]
]
@@ -93,11 +93,11 @@ def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
return None
task_id = int(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
).distinct().all()
]
return ids[0] if len(ids) == 1 else None
@@ -395,8 +395,8 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) ->
ids = {int(item) for item in raw_ids if item.isdigit()}
if len(ids) != len(raw_ids):
raise ValueError('发货模板引用的库存字段无效')
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
rows = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active',
).all() if ids else []
if len(rows) != len(ids):
raise ValueError('发货模板引用的库存字段已不存在')
@@ -407,7 +407,7 @@ def _inventory_field_user_label(field_id: str) -> str:
"""把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。"""
normalized = str(field_id or '').strip()
if normalized.isdigit():
row = ShippingInventoryField.query.filter_by(id=int(normalized)).first()
row = FreightRpaOnhandField.query.filter_by(id=int(normalized)).first()
display_name = str(getattr(row, 'display_name', '') or '').strip() if row else ''
if display_name:
return display_name
@@ -572,17 +572,20 @@ def _filename(
def _input_checksum(
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
task: ShippingNotice, source: FreightRpaSource, template: ShippingExcelTemplate,
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
notice_id: int | None = None,
) -> str:
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该外键。
report_config = source.onhand_report_config
payload = {
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task),
'parsing_profile_id': report_config.parsing_profile_id if report_config is not None else None,
'inventory_snapshot_id': _notice_inventory_file_id(task),
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id,
}
@@ -592,7 +595,7 @@ def _input_checksum(
def _resolve_odm_inventory_field_id() -> int | None:
"""返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。"""
field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first()
field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first()
return int(field.id) if field is not None else None
@@ -610,7 +613,7 @@ def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, st
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
@@ -762,7 +765,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
source = FreightRpaSource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
source = None
if source is None:
@@ -770,7 +773,10 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
template = source.excel_template
if template is None or template.status != 'published':
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
# s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。
report_config = source.onhand_report_config
profile = report_config.parsing_profile if report_config is not None else None
if profile is None or profile.status != 'published':
raise ValueError('库存源未绑定已发布的库存解析模板')
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
@@ -784,7 +790,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
raise ValueError('任务没有可用于导出的冻结订单快照')
from app.services.shipping_notice.effective_order_view import effective_order_field_values
header_values, all_line_values = effective_order_field_values(task)
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
@@ -801,7 +807,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
.all()
)
@@ -861,7 +867,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
row['__order_line_index'] = source_index
row['__snapshot_line_id'] = int(line.id)
line_values.append(row)
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
from app.services.shipping_notice.onhand_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part)
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
@@ -874,7 +880,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all()
for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(match_field_ids)).all()
} if match_field_ids else {}
order_field_ids: list[str] = []
inventory_field_keys: list[str] = []
@@ -958,6 +964,8 @@ def generate_shipment_excel(
assert_notice_has_no_export_artifact(task)
inputs = prepare_export_match_inputs(task)
source = inputs['source']
# s18 起解析方案绑定归 onhand_report_config 配置行;Artifact 审计外键同样取自配置行。
report_config = source.onhand_report_config
template = inputs['template']
snapshot = inputs['snapshot']
mappings = inputs['mappings']
@@ -1090,7 +1098,8 @@ def generate_shipment_excel(
artifact_no=artifact_no, task_id=task.id,
template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task),
inventory_parsing_profile_id=report_config.parsing_profile_id if report_config is not None else None,
inventory_snapshot_id=_notice_inventory_file_id(task),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id),
@@ -3,7 +3,7 @@ services/shipping_notice/field_alignment_summary.py
用途:把库存字段对齐结果格式化成适合聊天区和人工确认的摘要文本。
依赖:shipping_notice.i18n、多语言文案与字段对齐 payload。
逻辑:由 inventory_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。
逻辑:由 onhand_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。
"""
from __future__ import annotations
@@ -15,9 +15,9 @@ from typing import Any
from app.extensions import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
FreightRpaParsingProfile,
FreightRpaOnhandRoutingRule,
FreightRpaOnhandRoutingRuleCondition,
ShippingOrderDocumentProfile,
ShippingOrderField,
ShippingOrderFieldDecision,
@@ -93,11 +93,11 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
# [STEP 1] 库存路由条件
routing_rows = (
db.session.query(ShippingInventoryRoutingRuleCondition, ShippingInventoryRoutingRule)
.join(ShippingInventoryRoutingRule)
db.session.query(FreightRpaOnhandRoutingRuleCondition, FreightRpaOnhandRoutingRule)
.join(FreightRpaOnhandRoutingRule)
.filter(
ShippingInventoryRoutingRuleCondition.order_field_id == field_id,
ShippingInventoryRoutingRule.status.in_(['draft', 'published']),
FreightRpaOnhandRoutingRuleCondition.order_field_id == field_id,
FreightRpaOnhandRoutingRule.status.in_(['draft', 'published']),
)
.all()
)
@@ -114,8 +114,8 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
))
# [STEP 2] 库存解析档案 match_keys
for profile in ShippingInventoryParsingProfile.query.filter(
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
for profile in FreightRpaParsingProfile.query.filter(
FreightRpaParsingProfile.status.in_(['draft', 'published']),
).all():
for index, item in enumerate((profile.definition_json or {}).get('match_keys', []) or []):
if not isinstance(item, dict):
@@ -123,7 +123,7 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]:
if str(item.get('order_field_id') or '') != field_id:
continue
references.append(_ref(
kind='inventory_parsing_profile',
kind='onhand_parsing_profile',
object_id=profile.id,
display_name=profile.display_name or profile.profile_code,
status=profile.status,
@@ -2,8 +2,8 @@
services/shipping_notice/fulfillment_workflow.py
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、freight_rpa.upload.trigger_io、
依赖:customer_identity_gate、reservation_gate、match、export、query_service、onhand_workflow、
onhand_mapping_workflow、stp_line_onhand_match、upload_attempt_service、freight_rpa.upload.trigger_io、
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
order_task_stage_machine。
逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload,
@@ -29,14 +29,14 @@ from flask import current_app
from app import db
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask
from app.models import ShippingNotice, ShippingNoticeLineOnhandMatch, ShippingOrderTask
from app.services.shipping_notice.constants import POSITION_UPLOADED
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import (
from app.services.shipping_notice.onhand_file_store import (
active_inventory_file_for_task,
resolve_inventory_lines_for_execution,
)
from app.services.shipping_notice.inventory_workflow import (
from app.services.shipping_notice.onhand_workflow import (
ensure_inventory,
parse_inventory_lines,
)
@@ -70,10 +70,10 @@ from app.services.freight_rpa.onhand.attempts import (
upload_rpa_attempts,
)
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event, prepend_tool_message, set_task_step_progress
@@ -83,9 +83,9 @@ from app.services.shipping_notice.task_disposition_service import task_execution
def _single_candidate_source_code(task: ShippingNotice) -> str | None:
"""返回当前 CandidateSet 的唯一源;多源由行级匹配事实决定,不能伪造任务级源。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_codes = task_frozen_inventory_source_codes(task)
source_codes = task_frozen_onhand_source_codes(task)
return source_codes[0] if len(source_codes) == 1 else None
@@ -687,7 +687,7 @@ def _sync_workflow_stage(
def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
"""读取当前任务已审计的短缺放行冻结行 ID,供满足性与聚合重算共用。
核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集,
核心逻辑:只认活动 ``release_onhand_shortage`` 决定;无放行事实时返回空集,
保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
@@ -702,7 +702,7 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
.all()
)
@@ -760,11 +760,11 @@ def match_completed(task: ShippingNotice) -> bool:
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
"""
from app.models import ShippingNoticeLineInventoryMatch
from app.models import ShippingNoticeLineOnhandMatch
if task.id is None:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
return False
from app.models import ShippingOrderSnapshot
@@ -802,14 +802,14 @@ def match_completed(task: ShippingNotice) -> bool:
def inventory_match_facts_complete(task: ShippingNotice) -> bool:
"""判断当前行级匹配是否覆盖冻结订单全部项次且不再处于准备中。"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderSnapshot
from app.models import ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot
if task.id is None or not getattr(task, 'order_snapshot_id', None):
return False
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None or not snapshot.lines:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
by_line_id = {
int(row.snapshot_line_id): row
for row in rows
@@ -839,7 +839,7 @@ def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]:
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
.all()
)
@@ -916,12 +916,12 @@ def excel_gate_error(task: ShippingNotice) -> str | None:
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
# 库存准备失败是硬门禁:即使任务上残留旧的 match/export 投影,也不得继续生成
# 发货 Excel。恢复只能由显式库存准备重试或人工上传重新建立成功事实。
from app.models import ShippingInventoryPreparationAttempt
from app.models import ShippingOnhandPreparationAttempt
latest_preparation = (
ShippingInventoryPreparationAttempt.query
ShippingOnhandPreparationAttempt.query
.filter_by(task_id=int(task.id))
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc())
.first()
)
if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed':
@@ -1060,7 +1060,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_matching',
resume_gate_code='onhand_matching',
operator_id=operator_id,
line_scope_key=str(line_no) if line_no is not None else None,
)
@@ -1076,7 +1076,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
# 正式候选冻结任务必须绑定当前 frozen CandidateSet;缺失时禁止回退旧单源/JSON 路径。
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
build_inventory_candidate_blocking_reason,
build_inventory_candidate_primary_action,
get_active_candidate_set,
@@ -1150,7 +1150,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
if str(code).strip()
]
if not scoped_codes:
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines
candidate_line = next(
(
line for line in get_active_candidate_lines(task)
@@ -1181,11 +1181,11 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
position="inventory_source_review",
stop_agent_turn=True,
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import (
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
from app.services.shipping_notice.stp_line_onhand_match import (
attach_candidate_scope_to_order_lines,
apply_forced_match_source_filter,
apply_line_inventory_resolutions,
apply_line_onhand_resolutions,
match_order_lines_across_candidates,
snapshot_header_reservation_id,
)
@@ -1229,7 +1229,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
_sync_workflow_stage(
task,
lifecycle_status='inventory_matching',
lifecycle_status='onhand_matching',
event_code='inventory_match_line_started',
actor_id=actor_id,
payload={'task_no': task.task_no, 'line_no': target_line_no, 'line_index': orig_idx},
@@ -1266,7 +1266,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
if isinstance(res, dict):
res['line_no'] = target_line_no
# [STEP 4] 持久化仅本行(其他行 is_current 保持不变)
from app.services.shipping_notice.line_inventory_match_persistence import (
from app.services.shipping_notice.line_onhand_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
@@ -1299,7 +1299,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1391,14 +1391,14 @@ def _merge_line_inventory_resolutions(
def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]:
"""根据当前 LineMatch 重新计算门禁结果(fulfillable/partial/unfulfillable)与缺口。
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_onhand_shortage)
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), is_current=True)
.all()
)
@@ -1423,7 +1423,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'unit': getattr(row, 'unit', None),
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'resolved_inventory_source_code': getattr(row, 'source_code', None),
'required_qty': float(required_qty) if required_qty is not None else 0.0,
'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
@@ -1474,9 +1474,9 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
"""返回当前行级 Match 聚合结果;OT 不回读 step_payload_json 缓存。"""
if task.__class__.__name__ == 'ShippingOrderTask':
rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), is_current=True)
.order_by(ShippingNoticeLineInventoryMatch.line_no.asc())
.order_by(ShippingNoticeLineOnhandMatch.line_no.asc())
.all()
)
return [
@@ -1486,21 +1486,21 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
'snapshot_line_id': getattr(row, 'snapshot_line_id', None),
'disposition': getattr(row, 'match_result', None),
'match_result': getattr(row, 'match_result', None),
'inventory_status': getattr(row, 'inventory_status', None),
'inventory_status': getattr(row, 'onhand_status', None),
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'required_qty': getattr(row, 'required_qty', None),
'available_qty': getattr(row, 'available_qty', None),
'shortage_qty': getattr(row, 'shortage_qty', None),
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'resolved_inventory_source_code': getattr(row, 'source_code', None),
'candidate_source_codes': list(getattr(row, 'allowed_source_codes_snapshot', None) or []),
}
for row in rows
]
rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), is_current=True)
.order_by(ShippingNoticeLineInventoryMatch.line_no.asc())
.order_by(ShippingNoticeLineOnhandMatch.line_no.asc())
.all()
)
return [
@@ -1510,13 +1510,13 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
'snapshot_line_id': getattr(row, 'snapshot_line_id', None),
'disposition': getattr(row, 'match_result', None),
'match_result': getattr(row, 'match_result', None),
'inventory_status': getattr(row, 'inventory_status', None),
'inventory_status': getattr(row, 'onhand_status', None),
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'required_qty': getattr(row, 'required_qty', None),
'available_qty': getattr(row, 'available_qty', None),
'shortage_qty': getattr(row, 'shortage_qty', None),
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'resolved_inventory_source_code': getattr(row, 'source_code', None),
}
for row in rows
]
@@ -1618,7 +1618,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_matching',
resume_gate_code='onhand_matching',
operator_id=operator_id,
)
lang = resolve_lang(payload)
@@ -1698,14 +1698,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
total_notice_lines = len(order_field_lines)
_sync_workflow_stage(
task,
lifecycle_status='inventory_matching',
lifecycle_status='onhand_matching',
event_code='inventory_match_started',
actor_id=actor_id,
payload={'task_no': task.task_no},
)
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1726,11 +1726,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import (
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
from app.services.shipping_notice.stp_line_onhand_match import (
attach_candidate_scope_to_order_lines,
apply_forced_match_source_filter,
apply_line_inventory_resolutions,
apply_line_onhand_resolutions,
match_order_lines_across_candidates,
snapshot_header_reservation_id,
)
@@ -1739,7 +1739,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 人工指定源后仅保留 forced_match_source_code 对应库存行,消解多源/多文件冲突。
inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task)
use_stp_cross_match = (
len(task_frozen_inventory_source_codes(task)) >= 1
len(task_frozen_onhand_source_codes(task)) >= 1
or any(isinstance(row, dict) and row.get('__source_code') for row in (inventory_lines or []))
)
if use_stp_cross_match:
@@ -1775,9 +1775,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
inventory_lines=inventory_lines or [],
header_reservation_id=header_reservation,
)
apply_line_inventory_resolutions(task, match_payload)
apply_line_onhand_resolutions(task, match_payload)
# [STEP] Slice 1:持久化 OT 行匹配事实(ready+not_found=0;缺键→invalid_key)
from app.services.shipping_notice.line_inventory_match_persistence import (
from app.services.shipping_notice.line_onhand_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
@@ -1808,7 +1808,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
@@ -1887,7 +1887,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1899,20 +1899,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if processed == total or processed % 50 == 0:
db.session.flush()
from app.models import ShippingInventoryField, ShippingInventorySource
from app.models import FreightRpaOnhandField, FreightRpaSource
source_code = _single_candidate_source_code(task)
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = source.onhand_report_config if source is not None else None
profile = config.parsing_profile if config is not None else None
definition = profile.definition_json if profile is not None else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
mapped_field_ids = [
int(field_id) for field_id in (definition.get('field_mapping') or {})
if str(field_id).isdigit()
] if isinstance(definition, dict) else []
quantity_fields = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(mapped_field_ids),
ShippingInventoryField.status == 'active',
ShippingInventoryField.usage_type == 'inventory_quantity',
quantity_fields = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.id.in_(mapped_field_ids),
FreightRpaOnhandField.status == 'active',
FreightRpaOnhandField.usage_type == 'inventory_quantity',
).all() if mapped_field_ids else []
if len(quantity_fields) != 1:
raise ValueError('库存解析方案必须且只能配置一个库存数量字段')
@@ -1925,7 +1928,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
# 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。
# 仅更新 line_results_json 会导致订单明细继续显示“待确认”。
from app.services.shipping_notice.line_inventory_match_persistence import (
from app.services.shipping_notice.line_onhand_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
@@ -1944,7 +1947,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
+3 -3
View File
@@ -82,7 +82,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
"workflow.decision.parse_confirmed_next": "发货通知已确认。请继续在当前任务中补充库存或等待后端继续处理,并稍后刷新任务状态。",
"workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory",
"workflow.decision.parse_confirmed_manual_next": "ensure_onhand 或 parse_inventory",
"workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。",
"workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。",
"workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。",
@@ -208,7 +208,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.",
"workflow.decision.parse_confirmed_next": "The shipping notice is confirmed. Please continue with inventory for the current task or wait for the backend to continue, then refresh the task status later.",
"workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory",
"workflow.decision.parse_confirmed_manual_next": "ensure_onhand or parse_inventory",
"workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.",
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Complete inventory matching first, or reparse the order.",
"workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.",
@@ -334,7 +334,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject",
"workflow.decision.parse_confirmed_next": "ยืนยันใบแจ้งส่งสินค้าแล้ว โปรดดำเนินการเรื่องสต็อกในงานปัจจุบันต่อ หรือรอให้ระบบหลังบ้านทำต่อ แล้วค่อยรีเฟรชสถานะงาน",
"workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง",
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory",
"workflow.decision.parse_confirmed_manual_next": "ensure_onhand หรือ parse_inventory",
"workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้",
"workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่",
"workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
@@ -1,4 +1,13 @@
"""收料归档文件的授权下载服务。"""
"""
services/shipping_notice/inbound_report_access.py
用途:收料归档文件的授权列表与受控下载。
依赖:FreightRpaInboundReportFile(仅查询/取回行,供授权与审计)、当前用户、
freight_rpa/reports.read_inbound_file_bytes(归档字节唯一读取入口)。
逻辑:工作台 /api/workspace/inbound-report-files 调用本模块;下载地址只返回受控 API 路径。
阶段 B Task 5 起下载字节改经 freight_rpa/reports 只读函数取得,禁止本模块
自持模型 + 对象存储双跳读字节。
"""
from __future__ import annotations
@@ -7,8 +16,8 @@ from typing import Any
from app import db
from app.core.errors import ForbiddenError, NotFoundError
from app.models import ShippingReceiptReportFile, User
from app.services.file_assets.storage import file_asset_storage
from app.models import FreightRpaInboundReportFile, User
from app.services.freight_rpa.reports import read_inbound_file_bytes
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -17,7 +26,7 @@ def _is_admin(user: User) -> bool:
return bool(user.is_platform_admin())
def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, user: User) -> bool:
def can_download_receipt_report_file(report_file: FreightRpaInboundReportFile, user: User) -> bool:
"""仅允许管理员或所属排程通知接收人读取收料归档。"""
if _is_admin(user):
return True
@@ -28,7 +37,7 @@ def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, use
}
def _serialize_receipt_report_file(report_file: ShippingReceiptReportFile) -> dict[str, Any]:
def _serialize_receipt_report_file(report_file: FreightRpaInboundReportFile) -> dict[str, Any]:
"""输出可下载收料文件的脱敏列表投影,永不暴露对象存储 bucket 或 key。"""
unit = report_file.unit_run
run = unit.schedule_run if unit is not None else None
@@ -43,20 +52,20 @@ def _serialize_receipt_report_file(report_file: ShippingReceiptReportFile) -> di
'schedule_run_no': run.run_no if run is not None else None,
'archive_expires_at': report_file.archive_expires_at.isoformat() if report_file.archive_expires_at else None,
'created_at': report_file.created_at.isoformat() if report_file.created_at else None,
'download_url': f'/api/workspace/receipt-report-files/{report_file.id}/download',
'download_url': f'/api/workspace/inbound-report-files/{report_file.id}/download',
}
def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, Any]]:
"""列出管理员或当前排程接收人可见的未清理收料归档,并留存读取审计。"""
bounded_limit = max(1, min(int(limit), 200))
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()).all()
rows = FreightRpaInboundReportFile.query.filter(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()).all()
# 先按授权过滤再截断:不能因为前 100 条属于其他排程而遗漏当前接收人的历史文件。
visible = [item for item in rows if can_download_receipt_report_file(item, user)][:bounded_limit]
append_shipping_audit_event(
event_type='shipping_receipt_report_files_listed', aggregate_type='shipping_receipt_file_collection',
event_type='shipping_inbound_report_files_listed', aggregate_type='shipping_inbound_file_collection',
aggregate_id=str(user.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
result='success', after={'visible_count': len(visible), 'limit': bounded_limit},
metadata={'surface': 'workspace_receipt_report_files'},
@@ -67,21 +76,22 @@ def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str,
def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]:
"""授权读取私有对象并记录允许或拒绝的下载审计。"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None or report_file.archive_deleted_at is not None:
raise NotFoundError('Receipt report file not found', code='SHIPPING.RECEIPT_REPORT_FILE_NOT_FOUND')
if not can_download_receipt_report_file(report_file, user):
append_shipping_audit_event(
event_type='shipping_receipt_report_download_rejected', aggregate_type='shipping_receipt_file',
event_type='shipping_inbound_report_download_rejected', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
unit_id=report_file.unit_run_id, result='rejected', reason_code='recipient_not_authorized',
after={'status': 'rejected', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
db.session.commit()
raise ForbiddenError('You are not authorized to download this receipt report')
data = file_asset_storage.get_bytes(report_file.storage_key)
# [STEP] 阶段 B Task 5:归档字节统一经 freight_rpa/reports 只读函数读取(对象存储 key 不外泄、不双跳)。
data = read_inbound_file_bytes(file_id)
append_shipping_audit_event(
event_type='shipping_receipt_report_downloaded', aggregate_type='shipping_receipt_file',
event_type='shipping_inbound_report_downloaded', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
unit_id=report_file.unit_run_id, result='success',
after={'status': 'downloaded', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
@@ -1,4 +1,7 @@
"""收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
"""
services/shipping_notice/inbound_report_storage.py
收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的
waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程
@@ -6,12 +9,17 @@
已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。
依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、
in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥),
schedule.freight_inbound_rpa_finalize(惰性导入,仅 finalize)。
schedule.freight_rpa_inbound_finalize(惰性导入,仅 finalize)。
逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...}
envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback
归档(各终态分支各自 commit),并以 _finish_inbound_callback_terminal 作为
on_terminal 钩子——commit 之后按拆分前同一顺序执行「推桥 →(success)证据同步 →
finalize」;两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
归档(各终态分支各自 commit 后投递 ReportFact——批次 B Task 6 起归档入口不再收
on_terminal 钩子)。生产链路的终态收尾自 Task 7 起由调拨侧处理函数
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担(rpa_sinks 经
register_report_handler 注册);本模块的 _finish_inbound_callback_terminal +
_advance_transfer_source_job 留守为回归测试桥(tests/test_freight_receipt_rpa_callback.
py 经 register_report_handler 注入复刻拆分前终态收尾),其中桥推进失败
【不再吞异常】(Task 7 移除 except Exception: logger.warning——失败必须外抛,
避免把调拨推进失败再次吞掉;吞异常仅保留在证据同步双保险分支)。
"""
from __future__ import annotations
@@ -20,44 +28,50 @@ from typing import Any
from flask import current_app
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
def _advance_transfer_source_job(
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
file_no: str | None = None, file_sha256: str | None = None,
error_code: str | None = None, error_message: str | None = None,
) -> None:
"""收料回调终态推进调拨来源任务;失败只记日志,绝不回滚收料归档终态。
"""收料回调终态推进调拨来源任务并提交;失败外抛(Task 7 起不再吞异常)。
Args:
unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。
ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。
file_no / file_sha256: success 时绑定的归档文件号与指纹。
error_code / error_message: 失败时的错误码与描述。
Raises:
Exception: 桥推进/提交失败原样外抛(Task 7 移除 except 吞异常——
生产链路的推进失败改由调拨侧处理函数承担并外抛供 Worker 重试;
本函数留守为回归测试桥,同样不再吞失败)。
"""
try:
from app import db
from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback
advanced = advance_source_job_from_inbound_callback(
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
callback_ok=ok, error_code=error_code, error_message=error_message,
)
if advanced is not None:
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
db.session.commit()
except Exception as exc: # noqa: BLE001 —— 桥是记账,不是收料链路的正确性依赖
from flask import current_app
current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc)
from app import db
from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback
advanced = advance_source_job_from_inbound_callback(
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
callback_ok=ok, error_code=error_code, error_message=error_message,
)
if advanced is not None:
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
db.session.commit()
def _finish_inbound_callback_terminal(
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
file_no: str | None = None, file_sha256: str | None = None,
error_code: str | None = None, error_message: str | None = None,
) -> None:
"""终态归档 commit 之后的业务收尾(on_terminal 钩子实现),顺序与拆分前逐点一致。
"""终态归档 commit 之后的业务收尾(留守测试桥),顺序与拆分前逐点一致。
定位(Task 7 起):生产链路的终态收尾已由调拨侧处理函数
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担
(rpa_sinks 经 register_report_handler 注册);本函数留守为回归测试桥
(tests/test_freight_receipt_rpa_callback.py 经 register_report_handler 注入),
复刻拆分前的桥推进(不再吞异常)+ 证据同步 + 排程收口三段语义。
核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线);
[STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路,
@@ -82,7 +96,7 @@ def _finish_inbound_callback_terminal(
)
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
from app.services.schedule.freight_inbound_rpa_finalize import (
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
@@ -92,13 +106,17 @@ def _finish_inbound_callback_terminal(
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个收料单元回调:委托 report_archive 原样归档,终态后执行业务桥收尾。
"""幂等接收单个收料单元回调:委托 report_archive 原样归档(终态后投递事实)。
Args:
payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。
Returns:
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
业务顺序(Task 6 起):归档各终态 commit 后由 report_archive 直接投递
ReportFact(dispatch_report_fact);本域桥/finalize 收尾改经
register_report_handler 注册的处理函数承担(Task 7 接线),不再走
on_terminal 钩子。
"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
return ingest_inbound_callback(payload, on_terminal=_finish_inbound_callback_terminal)
return ingest_inbound_callback(payload)
@@ -42,11 +42,11 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
# 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。
'order_review_build': 'order_review',
'task_creation': 'order_review',
'inventory_source_routing': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep',
'inventory_field_mapping': 'fulfillment_prep',
'inventory_matching': 'fulfillment_prep',
'inventory_sufficiency': 'fulfillment_prep',
'onhand_source_routing': 'fulfillment_prep',
'onhand_preparation': 'fulfillment_prep',
'onhand_field_mapping': 'fulfillment_prep',
'onhand_matching': 'fulfillment_prep',
'onhand_sufficiency': 'fulfillment_prep',
'excel_readiness': 'fulfillment_prep',
'artifact_generation': 'fulfillment_prep',
'freight_upload_rpa': 'freight_upload',
@@ -65,12 +65,12 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'waiting_review': 'order_review',
'customer_resolving': 'order_review',
'duplicate_checking': 'order_review',
'inventory_source_resolving': 'fulfillment_prep',
'onhand_source_resolving': 'fulfillment_prep',
'order_creating': 'fulfillment_prep',
'inventory_fetching': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep',
'inventory_matching': 'fulfillment_prep',
'inventory_sufficiency': 'fulfillment_prep',
'onhand_fetching': 'fulfillment_prep',
'onhand_preparation': 'fulfillment_prep',
'onhand_matching': 'fulfillment_prep',
'onhand_sufficiency': 'fulfillment_prep',
'excel_generating': 'fulfillment_prep',
'freight_uploading': 'freight_upload',
'manual_upload_handoff': 'freight_upload',
@@ -3,9 +3,9 @@ services/shipping_notice/line_auto_fulfill_coordinator.py
用途:OT 后行级自动履约幂等协调器——统一 matching ready / OT 回调 / 补偿入口。
依赖:line_auto_fulfill_enabled、post_ot_fulfillment_wave_service、post_ot_wave_progress_service、
ShippingNoticeLineInventoryMatch / LineDecision snapshot。
ShippingNoticeLineOnhandMatch / LineDecision snapshot。
逻辑:flag 关闭时 skipped;开启时整波创建+专用推进;失败整波回滚后独立写 auto_fulfill_failed 列;
不创建 wait_inventory 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。
不创建 wait_onhand 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。
"""
from __future__ import annotations
@@ -16,12 +16,12 @@ from typing import Any
from app import db
from app.models import (
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingNoticeLineOnhandMatch,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
)
from app.services.shipping_notice.line_inventory_match_persistence import resolve_review_case_for_task
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.line_onhand_match_persistence import resolve_review_case_for_task
from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
list_eligible_post_ot_snapshot_line_ids,
@@ -40,9 +40,9 @@ def _mark_auto_fulfill_failed(
message: str,
) -> None:
"""
独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_inventory。
独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_onhand。
核心逻辑:写 ShippingNoticeLineInventoryMatch.auto_fulfill_failed* 列;可选同步 snapshot。
核心逻辑:写 ShippingNoticeLineOnhandMatch.auto_fulfill_failed* 列;可选同步 snapshot。
"""
now = datetime.utcnow()
formal_task_id = getattr(case, 'confirmed_task_id', None)
@@ -56,7 +56,7 @@ def _mark_auto_fulfill_failed(
key_s = str(key)
if formal_task_id is not None:
fact = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True)
.first()
)
@@ -1,11 +1,11 @@
"""
services/shipping_notice/line_inventory_match_persistence.py
services/shipping_notice/line_onhand_match_persistence.py
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
用途:onhand_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
依赖:ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
行级 onhand_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件
≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
@@ -20,12 +20,12 @@ from typing import Any
from app import db
from app.models import (
ShippingInventoryFile,
FreightRpaOnhandReportFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingNoticeLineOnhandMatch,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
)
@@ -87,9 +87,9 @@ def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) ->
src = str(result.get('resolved_inventory_source_code') or '')[:64] or None
if src:
return src
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_codes = task_frozen_inventory_source_codes(task)
source_codes = task_frozen_onhand_source_codes(task)
if len(source_codes) == 1:
return source_codes[0][:64]
return None
@@ -101,7 +101,7 @@ def persist_line_inventory_match_facts(
match_payload: dict[str, Any],
inventory_snapshot_id: int | None = None,
matching_rule_version: str | None = 'stp_line_v2',
) -> list[ShippingNoticeLineInventoryMatch]:
) -> list[ShippingNoticeLineOnhandMatch]:
"""
将 match_order_lines_across_candidates 结果持久化为当前事实。
@@ -111,14 +111,14 @@ def persist_line_inventory_match_facts(
case = resolve_review_case_for_task(task)
snap_id = inventory_snapshot_id
if snap_id is None:
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。
snapshot_file_no = None
if snap_id is not None:
snapshot = ShippingInventoryFile.query.get(int(snap_id))
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
snapshot = FreightRpaOnhandReportFile.query.get(int(snap_id))
snapshot_file_no = str(getattr(snapshot, 'onhand_file_no', '') or '').strip() or None
# 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照
# (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。
file_id_by_no: dict[str, int | None] = {}
@@ -135,7 +135,7 @@ def persist_line_inventory_match_facts(
if item.get('line_index') is not None
}
written: list[ShippingNoticeLineInventoryMatch] = []
written: list[ShippingNoticeLineOnhandMatch] = []
now = datetime.utcnow()
current_candidate_set = get_active_candidate_set(task)
candidate_lines_by_no = {
@@ -169,8 +169,8 @@ def persist_line_inventory_match_facts(
if line_file_no is not None:
if line_file_no not in file_id_by_no:
hit_file = (
ShippingInventoryFile.query
.filter_by(inventory_file_no=line_file_no)
FreightRpaOnhandReportFile.query
.filter_by(onhand_file_no=line_file_no)
.first()
)
file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None
@@ -221,32 +221,32 @@ def persist_line_inventory_match_facts(
existing = None
if line_snap_id is not None:
existing = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(
task_id=int(task.id),
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(line_snap_id),
onhand_snapshot_id=int(line_snap_id),
)
.first()
)
if existing is None and line_snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
.filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id.is_(None))
.first()
)
if existing is None:
(
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。
(
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), line_index=index, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
@@ -278,7 +278,7 @@ def persist_line_inventory_match_facts(
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
row = ShippingNoticeLineInventoryMatch(
row = ShippingNoticeLineOnhandMatch(
task_id=int(task.id),
review_case_id=int(case.id) if case is not None else None,
snapshot_line_id=snapshot_line_id,
@@ -295,9 +295,9 @@ def persist_line_inventory_match_facts(
else None
),
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
onhand_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
onhand_status=inventory_status,
required_qty=str(required) if required is not None else None,
available_qty=str(available) if available is not None else None,
shortage_qty=str(shortage) if shortage is not None else None,
@@ -311,7 +311,7 @@ def persist_line_inventory_match_facts(
part_number=pn,
unit=unit_value,
matching_rule_version=str(matching_rule_version or '')[:64] or None,
inventory_source_code=src_code,
source_code=src_code,
is_current=True,
matched_at=now,
# T6 行级证据
@@ -368,7 +368,7 @@ def persist_line_inventory_match_facts(
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
existing.match_result = match_result
existing.inventory_status = inventory_status
existing.onhand_status = inventory_status
existing.required_qty = str(required) if required is not None else None
existing.available_qty = str(available) if available is not None else None
existing.shortage_qty = str(shortage) if shortage is not None else None
@@ -381,7 +381,7 @@ def persist_line_inventory_match_facts(
existing.part_number = pn
existing.unit = unit_value
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
existing.inventory_source_code = src_code
existing.source_code = src_code
existing.is_current = True
existing.invalidated_at = None
existing.invalidated_by_attempt_id = None
@@ -415,23 +415,23 @@ def persist_line_inventory_match_facts(
existing.detail_json = detail_json
# 确保同 task+line 仅本条 current
(
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineOnhandMatch.snapshot_line_id == snapshot_line_id,
ShippingNoticeLineOnhandMatch.id != int(existing.id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# 同一订单行更新时关闭旧事实,保证 current 投影唯一。
(
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.line_index == index,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineOnhandMatch.line_index == index,
ShippingNoticeLineOnhandMatch.id != int(existing.id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
@@ -1,15 +1,15 @@
"""
services/shipping_notice/line_inventory_match_projection.py
services/shipping_notice/line_onhand_match_projection.py
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
依赖:ShippingNoticeLineOnhandMatch、FreightRpaOnhandTaskAttempt、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
ready+not_found→available=0;result_missing 不得转 0;
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
load_current_match_facts_by_task / onhand_rpa_is_running 在同一 HTTP 请求内 memo,
禁止按行重复查库。
"""
@@ -19,9 +19,9 @@ from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import (
ShippingInventoryFile,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
FreightRpaOnhandReportFile,
ShippingNoticeLineOnhandMatch,
FreightRpaOnhandTaskAttempt,
)
@@ -41,10 +41,10 @@ STATUS_SOURCE_CONFLICT = 'source_conflict'
STATUS_UNAVAILABLE = 'unavailable'
STATUS_INVALID_KEY = 'invalid_key'
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
ACTION_RETRY_PREPARATION = 'retry_onhand_preparation'
ACTION_RETRY_MATCHING = 'retry_onhand_matching'
ACTION_CLOSE = 'close_unfulfillable'
ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage'
ACTION_RELEASE_SHORTAGE = 'release_onhand_shortage'
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
@@ -455,10 +455,10 @@ def inventory_rpa_is_running(task: Any) -> bool:
try:
running = (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
FreightRpaOnhandTaskAttempt.task_no == task_no,
FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')),
)
.first()
is not None
@@ -496,7 +496,7 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
cache = None
rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=key, is_current=True)
.all()
)
@@ -519,7 +519,7 @@ def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dic
if task_id is None:
return {}
rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
@@ -543,11 +543,11 @@ def aggregate_match_status_for_task(task_id: int | None) -> str | None:
return 'unfulfillable' if blocked else 'fulfillable'
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
def serialize_match_fact(row: ShippingNoticeLineOnhandMatch) -> dict[str, Any]:
"""将 ORM 行序列化为投影输入。"""
snapshot = (
ShippingInventoryFile.query.get(int(row.inventory_snapshot_id))
if row.inventory_snapshot_id is not None else None
FreightRpaOnhandReportFile.query.get(int(row.onhand_snapshot_id))
if row.onhand_snapshot_id is not None else None
)
return {
'id': int(row.id),
@@ -557,10 +557,10 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'line_no': int(row.line_no),
'line_index': row.line_index,
'inventory_snapshot_id': (
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
int(row.onhand_snapshot_id) if row.onhand_snapshot_id is not None else None
),
'match_result': str(row.match_result or ''),
'inventory_status': str(row.inventory_status or ''),
'inventory_status': str(row.onhand_status or ''),
'required_qty': row.required_qty,
'available_qty': row.available_qty,
'shortage_qty': row.shortage_qty,
@@ -569,7 +569,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'part_number': row.part_number,
'unit': row.unit,
'matching_rule_version': row.matching_rule_version,
'inventory_source_code': row.inventory_source_code,
'inventory_source_code': row.source_code,
'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_file_sha256': (
@@ -3,7 +3,7 @@ services/shipping_notice/match_rule_desc.py
用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。
依赖:标准类型能力。
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
逻辑:由 onhand_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
"""
from __future__ import annotations
@@ -2,7 +2,7 @@
services/shipping_notice/notice_line_table.py
用途:从发货通知表格文本或二维行数据中解析订单行。
依赖:notice_line_values、动态 Schema 表头契约、reservation_id、inventory_snapshot(懒加载表格拆行)。
依赖:notice_line_values、动态 Schema 表头契约、reservation_id、onhand_snapshot(懒加载表格拆行)。
逻辑:调用方显式传入冻结契约;歧义表头不静默选列,输出诊断供 Run 进入复核。
"""
@@ -229,7 +229,7 @@ def inspect_notice_table_text(
Returns:
`lines`、`header_found`、`ambiguous_fields` 和表头索引。
"""
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text
text = str(raw_text or '').strip()
if not text or contract is None:
@@ -257,6 +257,6 @@ def parse_notice_table_text(
"""
从发货通知原始文本中的表格片段解析订单行。
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
核心逻辑:先借助 onhand_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
"""
return list(inspect_notice_table_text(raw_text, contract=contract)['lines'])
@@ -2,10 +2,10 @@
services/shipping_notice/notice_odm_choice_service.py
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineOnhandMatch、AppError。
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
(shipping_notice_line_onhand_matches.chosen_odm_id)上,按「同一库存快照文件」
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
"""
@@ -16,7 +16,7 @@ from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
from app.models import ShippingCustomer, ShippingNoticeLineOnhandMatch
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
@@ -127,7 +127,7 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s
http_status=409,
)
target_row = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(
task_id=int(task_id),
snapshot_line_id=int(snapshot_line_id or 0),
@@ -144,11 +144,11 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s
)
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
scope_rows = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
.filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id == target_row.onhand_snapshot_id)
.all()
) if target_row.inventory_snapshot_id is not None else [target_row]
) if target_row.onhand_snapshot_id is not None else [target_row]
lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
}
@@ -1,13 +1,13 @@
"""
services/shipping_notice/inventory_candidate_freeze_service.py
services/shipping_notice/onhand_candidate_freeze_service.py
用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表
(T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json
作为不可变审计副本。
依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、
inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。
依赖:app.models.shipping_onhand_candidates(Set/Source/Line)、onhand_source_rules、
onhand_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。
逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen)
与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用;
与 STP 建单 freeze_stp_onhand_candidates_on_task 两条路径调用;
input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。
"""
@@ -26,17 +26,17 @@ from sqlalchemy.orm import Session
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingOnhandCandidateLine,
ShippingOnhandCandidateSet,
ShippingOnhandCandidateSource,
ShippingNotice,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
from app.services.shipping_notice.onhand_source_rules import (
InventorySourceAdjudication,
_task_routing_lines,
compute_routing_fingerprint,
@@ -90,9 +90,9 @@ def _build_input_fingerprint(
def _build_manifest_snapshot(
*,
task: ShippingNotice,
set_db: ShippingInventoryCandidateSet,
sources_db: list[ShippingInventoryCandidateSource],
lines_db: list[ShippingInventoryCandidateLine],
set_db: ShippingOnhandCandidateSet,
sources_db: list[ShippingOnhandCandidateSource],
lines_db: list[ShippingOnhandCandidateLine],
routing_rule_version_json: dict[str, Any] | None,
) -> dict[str, Any]:
"""
@@ -215,35 +215,35 @@ def _find_existing_frozen_set(
review_case_id: int | None,
input_fingerprint: str,
session: Session,
) -> ShippingInventoryCandidateSet | None:
) -> ShippingOnhandCandidateSet | None:
"""
根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。
PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。
"""
if task_id is not None:
return (
session.query(ShippingInventoryCandidateSet)
session.query(ShippingOnhandCandidateSet)
.filter(
and_(
ShippingInventoryCandidateSet.task_id == task_id,
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
ShippingOnhandCandidateSet.task_id == task_id,
ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint,
ShippingOnhandCandidateSet.lifecycle_status == 'frozen',
)
)
.order_by(ShippingInventoryCandidateSet.id.desc())
.order_by(ShippingOnhandCandidateSet.id.desc())
.first()
)
if review_case_id is not None:
return (
session.query(ShippingInventoryCandidateSet)
session.query(ShippingOnhandCandidateSet)
.filter(
and_(
ShippingInventoryCandidateSet.review_case_id == review_case_id,
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
ShippingOnhandCandidateSet.review_case_id == review_case_id,
ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint,
ShippingOnhandCandidateSet.lifecycle_status == 'frozen',
)
)
.order_by(ShippingInventoryCandidateSet.id.desc())
.order_by(ShippingOnhandCandidateSet.id.desc())
.first()
)
return None
@@ -252,8 +252,8 @@ def _find_existing_frozen_set(
def _next_task_set_version(*, task_id: int, session: Session) -> int:
"""计算 Task 维度下一个 CandidateSet.version。"""
current_max = (
session.query(func.max(ShippingInventoryCandidateSet.set_version))
.filter(ShippingInventoryCandidateSet.task_id == int(task_id))
session.query(func.max(ShippingOnhandCandidateSet.set_version))
.filter(ShippingOnhandCandidateSet.task_id == int(task_id))
.scalar()
)
return int(current_max or 0) + 1
@@ -269,10 +269,10 @@ def _invalidate_task_candidate_outputs(
"""
from app.models import (
ShippingExportArtifact,
ShippingInventoryPreparationAttempt,
ShippingNoticeLineInventoryMatch,
ShippingOnhandPreparationAttempt,
ShippingNoticeLineOnhandMatch,
ShippingProcessRecoveryPlan,
ShippingTaskInventoryRpaAttempt,
FreightRpaOnhandTaskAttempt,
ShippingUploadAttempt,
)
@@ -285,18 +285,18 @@ def _invalidate_task_candidate_outputs(
task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}}
(
session.query(ShippingNoticeLineInventoryMatch)
session.query(ShippingNoticeLineOnhandMatch)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
(
session.query(ShippingTaskInventoryRpaAttempt)
session.query(FreightRpaOnhandTaskAttempt)
.filter(
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''),
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or ''),
FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')),
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
@@ -326,19 +326,19 @@ def _invalidate_task_candidate_outputs(
'finished_at': datetime.utcnow(),
'error_code': 'candidate_set_refrozen',
}, synchronize_session=False)
prep_query = session.query(ShippingInventoryPreparationAttempt).filter(
ShippingInventoryPreparationAttempt.task_id == int(task.id),
ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
prep_query = session.query(ShippingOnhandPreparationAttempt).filter(
ShippingOnhandPreparationAttempt.task_id == int(task.id),
ShippingOnhandPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
)
if old_candidate_set_id is not None:
prep_query = prep_query.filter(
ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
ShippingOnhandPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
)
prep_query.update({'status': 'superseded'}, synchronize_session=False)
active_execution_ids = [
row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter(
ShippingInventoryPreparationAttempt.task_id == int(task.id),
ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id,
row[0] for row in session.query(ShippingOnhandPreparationAttempt.execution_id).filter(
ShippingOnhandPreparationAttempt.task_id == int(task.id),
ShippingOnhandPreparationAttempt.candidate_set_id == old_candidate_set_id,
).all() if row[0]
]
if active_execution_ids:
@@ -395,7 +395,7 @@ def freeze_candidates_for_task(
session = session or db.session
if adjudication is None:
from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source
from app.services.shipping_notice.onhand_source_rules import adjudicate_inventory_source
adjudication = adjudicate_inventory_source(task)
@@ -478,7 +478,7 @@ def freeze_candidates_for_task(
'adjudication_reason': adjudication.reason,
}
existing_active = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None
else None
)
@@ -487,7 +487,7 @@ def freeze_candidates_for_task(
if getattr(task, 'id', None) is not None
else 1
)
new_set = ShippingInventoryCandidateSet(
new_set = ShippingOnhandCandidateSet(
task_id=task.id,
review_case_id=review_case_id,
execution_id=execution_id,
@@ -503,7 +503,7 @@ def freeze_candidates_for_task(
session.add(new_set)
session.flush()
created_sources: list[ShippingInventoryCandidateSource] = []
created_sources: list[ShippingOnhandCandidateSource] = []
for idx, code in enumerate(task_source_codes_ordered):
src_cfg = get_database_inventory_source(code)
rule_id: int | None = None
@@ -514,13 +514,13 @@ def freeze_candidates_for_task(
if isinstance(matched_rule_ids, list) and matched_rule_ids:
try:
_rule_ids_int = int(matched_rule_ids[0])
from app.models.shipping_inventory_config import ShippingInventoryRoutingRule
from app.models.freight_rpa_config import FreightRpaOnhandRoutingRule
rule_row = (
session.query(
ShippingInventoryRoutingRule.id,
ShippingInventoryRoutingRule.version,
FreightRpaOnhandRoutingRule.id,
FreightRpaOnhandRoutingRule.version,
)
.filter(ShippingInventoryRoutingRule.id == _rule_ids_int)
.filter(FreightRpaOnhandRoutingRule.id == _rule_ids_int)
.one_or_none()
)
if rule_row is not None:
@@ -529,7 +529,7 @@ def freeze_candidates_for_task(
except (TypeError, ValueError):
rule_id = None
rule_version = None
source = ShippingInventoryCandidateSource(
source = ShippingOnhandCandidateSource(
candidate_set_id=new_set.id,
source_code=code,
candidate_order=idx + 1,
@@ -550,7 +550,7 @@ def freeze_candidates_for_task(
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'inventory_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'onhand_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
@@ -558,10 +558,10 @@ def freeze_candidates_for_task(
created_sources.append(source)
session.flush(created_sources)
created_lines: list[ShippingInventoryCandidateLine] = []
created_lines: list[ShippingOnhandCandidateLine] = []
for sig in signatures:
line_no, source_line_no, pn, resv, codes_ordered = sig
line_entity = ShippingInventoryCandidateLine(
line_entity = ShippingOnhandCandidateLine(
candidate_set_id=new_set.id,
line_no=line_no,
source_line_no=source_line_no,
@@ -671,7 +671,7 @@ def freeze_manual_line_source_selection(
raise ValueError('未找到该订单项次')
active_set = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
if task.active_inventory_candidate_set_id is not None else None
)
existing_codes = {
@@ -733,7 +733,7 @@ def active_candidate_set_is_manually_pinned(
"""
sess = session or db.session
active_set = (
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
sess.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
else None
)
@@ -759,8 +759,8 @@ def refresh_candidates_from_current_routing(
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
核心逻辑:
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
不得自动改源,换源走 override_line_inventory_source 行级覆写。
[守卫 1] 仅多候选未定源可刷新(task_frozen_onhand_source_codes > 1);源已定单
不得自动改源,换源走 override_line_onhand_source 行级覆写。
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
[STEP 1] 记录当前活动 set_id。
@@ -778,12 +778,12 @@ def refresh_candidates_from_current_routing(
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
sess = session or db.session
if len(task_frozen_inventory_source_codes(task)) <= 1:
if len(task_frozen_onhand_source_codes(task)) <= 1:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
@@ -804,7 +804,7 @@ def refresh_candidates_from_current_routing(
'scope': 'task',
'previous_set_id': before_set_id,
'new_set_id': after_set_id,
'source_codes': task_frozen_inventory_source_codes(task),
'source_codes': task_frozen_onhand_source_codes(task),
},
source='system',
)
@@ -820,7 +820,7 @@ def refresh_line_candidates_from_current_routing(
) -> bool:
"""
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_onhand_preparation 携带
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
核心逻辑:
@@ -844,12 +844,12 @@ def refresh_line_candidates_from_current_routing(
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
from app.services.shipping_notice.onhand_source_rules import (
_task_routing_lines,
compute_routing_fingerprint,
evaluate_inventory_source_rules,
@@ -990,7 +990,7 @@ def freeze_wave_notice_routing(
"""
from app.models.shipping_notice_line import ShippingNoticeLine
from app.services.shipping_notice.export import order_field_id_values
from app.services.shipping_notice.inventory_routing_engine import (
from app.services.shipping_notice.onhand_routing_engine import (
evaluate_inventory_source_rules_for_field_values,
)
@@ -1048,7 +1048,7 @@ def freeze_wave_notice_routing(
if not task_codes:
return None
from app.services.shipping_notice.inventory_source_rules import (
from app.services.shipping_notice.onhand_source_rules import (
InventorySourceAdjudication,
_candidate,
compute_routing_fingerprint,
@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_candidate_projection.py
services/shipping_notice/onhand_candidate_projection.py
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
ShippingTaskInventoryRpaAttempt。
依赖:ShippingOrderTask、ShippingOnhandCandidateSet/Source/Line、ShippingNoticeLineOnhandMatch、
FreightRpaOnhandTaskAttempt。
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
"""
@@ -17,14 +17,14 @@ from sqlalchemy.orm import Session
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingOnhandCandidateLine,
ShippingOnhandCandidateSet,
ShippingOnhandCandidateSource,
FreightRpaOnhandReportFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
ShippingNoticeLineOnhandMatch,
FreightRpaOnhandTaskAttempt,
)
@@ -60,23 +60,23 @@ def _candidate_set_filter(
*,
include_drafts: bool = False,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSet]:
) -> list[ShippingOnhandCandidateSet]:
"""按 Task 读取候选版本列表;默认隐藏 draft。"""
if getattr(task, 'id', None) is None:
return []
query = (
_session(session)
.query(ShippingInventoryCandidateSet)
.filter(ShippingInventoryCandidateSet.task_id == int(task.id))
.query(ShippingOnhandCandidateSet)
.filter(ShippingOnhandCandidateSet.task_id == int(task.id))
)
if not include_drafts:
query = query.filter(
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
)
rows = (
query.order_by(
ShippingInventoryCandidateSet.set_version.desc(),
ShippingInventoryCandidateSet.id.desc(),
ShippingOnhandCandidateSet.set_version.desc(),
ShippingOnhandCandidateSet.id.desc(),
)
.all()
)
@@ -114,7 +114,7 @@ def get_active_candidate_set(
task: ShippingOrderTask | ShippingNotice,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
) -> ShippingOnhandCandidateSet | None:
"""
读取正式 Task 当前 frozen CandidateSet。
@@ -126,7 +126,7 @@ def get_active_candidate_set(
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
if candidate_set_id is None:
return None
row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id))
row = _session(session).get(ShippingOnhandCandidateSet, int(candidate_set_id))
if row is None:
return None
if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0):
@@ -140,18 +140,18 @@ def get_active_candidate_sources(
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
) -> list[ShippingOnhandCandidateSource]:
"""读取当前 frozen Set 的任务级候选源。"""
current = get_active_candidate_set(task, session=session)
if current is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateSource)
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id))
.query(ShippingOnhandCandidateSource)
.filter(ShippingOnhandCandidateSource.candidate_set_id == int(current.id))
.order_by(
ShippingInventoryCandidateSource.candidate_order.asc(),
ShippingInventoryCandidateSource.id.asc(),
ShippingOnhandCandidateSource.candidate_order.asc(),
ShippingOnhandCandidateSource.id.asc(),
)
.all()
)
@@ -162,18 +162,18 @@ def get_active_candidate_lines(
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
) -> list[ShippingOnhandCandidateLine]:
"""读取当前 frozen Set 的行级候选。"""
current = get_active_candidate_set(task, session=session)
if current is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateLine)
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id))
.query(ShippingOnhandCandidateLine)
.filter(ShippingOnhandCandidateLine.candidate_set_id == int(current.id))
.order_by(
ShippingInventoryCandidateLine.line_no.asc(),
ShippingInventoryCandidateLine.id.asc(),
ShippingOnhandCandidateLine.line_no.asc(),
ShippingOnhandCandidateLine.id.asc(),
)
.all()
)
@@ -198,7 +198,7 @@ def active_inventory_runtime_facts(
Returns:
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
"""
from app.models import ShippingTaskInventoryLink
from app.models import ShippingTaskOnhandLink
sess = _session(session)
candidate_set = get_active_candidate_set(task, session=sess)
@@ -206,9 +206,9 @@ def active_inventory_runtime_facts(
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()]
link = (
sess.query(ShippingTaskInventoryLink)
.filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True))
.order_by(ShippingTaskInventoryLink.id.desc())
sess.query(ShippingTaskOnhandLink)
.filter(ShippingTaskOnhandLink.task_id == int(task.id), ShippingTaskOnhandLink.is_active.is_(True))
.order_by(ShippingTaskOnhandLink.id.desc())
.first()
if getattr(task, 'id', None) is not None else None
)
@@ -218,7 +218,7 @@ def active_inventory_runtime_facts(
'source_codes': source_codes,
'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None,
'active_link': link,
'inventory_file_id': getattr(link, 'inventory_file_id', None),
'inventory_file_id': getattr(link, 'onhand_file_id', None),
'inventory_file': getattr(link, 'inventory_file', None),
}
@@ -229,26 +229,26 @@ def get_candidate_set_by_version(
*,
include_drafts: bool = False,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
) -> ShippingOnhandCandidateSet | None:
"""按 Task + set_version 读取指定候选版本。"""
if getattr(task, 'id', None) is None:
return None
query = (
_session(session)
.query(ShippingInventoryCandidateSet)
.query(ShippingOnhandCandidateSet)
.filter(
ShippingInventoryCandidateSet.task_id == int(task.id),
ShippingInventoryCandidateSet.set_version == int(version),
ShippingOnhandCandidateSet.task_id == int(task.id),
ShippingOnhandCandidateSet.set_version == int(version),
)
)
if not include_drafts:
query = query.filter(
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
)
return query.order_by(ShippingInventoryCandidateSet.id.desc()).first()
return query.order_by(ShippingOnhandCandidateSet.id.desc()).first()
def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None:
def serialize_candidate_set_summary(row: ShippingOnhandCandidateSet | None) -> dict[str, Any] | None:
"""序列化 CandidateSet 摘要供 API / Projection 复用。"""
if row is None:
return None
@@ -268,7 +268,7 @@ def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -
}
def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]:
def serialize_candidate_source(row: ShippingOnhandCandidateSource) -> dict[str, Any]:
"""序列化任务级候选源。"""
return {
'id': int(row.id),
@@ -284,7 +284,7 @@ def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[st
}
def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]:
def serialize_candidate_line(row: ShippingOnhandCandidateLine) -> dict[str, Any]:
"""序列化行级候选源与稳定行标识。"""
return {
'candidate_line_id': int(row.id),
@@ -300,20 +300,20 @@ def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, A
def _candidate_sources_for_set(
candidate_set: ShippingInventoryCandidateSet | None,
candidate_set: ShippingOnhandCandidateSet | None,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
) -> list[ShippingOnhandCandidateSource]:
"""读取指定 CandidateSet 的任务级候选源。"""
if candidate_set is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateSource)
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id))
.query(ShippingOnhandCandidateSource)
.filter(ShippingOnhandCandidateSource.candidate_set_id == int(candidate_set.id))
.order_by(
ShippingInventoryCandidateSource.candidate_order.asc(),
ShippingInventoryCandidateSource.id.asc(),
ShippingOnhandCandidateSource.candidate_order.asc(),
ShippingOnhandCandidateSource.id.asc(),
)
.all()
)
@@ -321,20 +321,20 @@ def _candidate_sources_for_set(
def _candidate_lines_for_set(
candidate_set: ShippingInventoryCandidateSet | None,
candidate_set: ShippingOnhandCandidateSet | None,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
) -> list[ShippingOnhandCandidateLine]:
"""读取指定 CandidateSet 的行级候选。"""
if candidate_set is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateLine)
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id))
.query(ShippingOnhandCandidateLine)
.filter(ShippingOnhandCandidateLine.candidate_set_id == int(candidate_set.id))
.order_by(
ShippingInventoryCandidateLine.line_no.asc(),
ShippingInventoryCandidateLine.id.asc(),
ShippingOnhandCandidateLine.line_no.asc(),
ShippingOnhandCandidateLine.id.asc(),
)
.all()
)
@@ -373,15 +373,15 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str],
return {}
rows = (
_session(session)
.query(ShippingTaskInventoryRpaAttempt)
.query(FreightRpaOnhandTaskAttempt)
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes),
FreightRpaOnhandTaskAttempt.task_no == task_no,
FreightRpaOnhandTaskAttempt.source_code.in_(source_codes),
)
.order_by(
ShippingTaskInventoryRpaAttempt.source_code.asc(),
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
FreightRpaOnhandTaskAttempt.source_code.asc(),
FreightRpaOnhandTaskAttempt.attempt_no.desc(),
FreightRpaOnhandTaskAttempt.id.desc(),
)
.all()
)
@@ -397,7 +397,7 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str],
'run_no': str(row.run_no or ''),
'error_code': getattr(row, 'error_code', None),
'error_message': getattr(row, 'error_message', None),
'inventory_file_no': getattr(row, 'inventory_file_no', None),
'inventory_file_no': getattr(row, 'onhand_file_no', None),
'updated_at': _iso(getattr(row, 'updated_at', None)),
}
return out
@@ -419,20 +419,20 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
return prepared, pending, failed
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineOnhandMatch]:
"""读取任务当前生效的行级匹配事实。"""
if getattr(task, 'id', None) is None:
return []
rows = (
_session(session)
.query(ShippingNoticeLineInventoryMatch)
.query(ShippingNoticeLineOnhandMatch)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
)
.order_by(
ShippingNoticeLineInventoryMatch.line_index.asc(),
ShippingNoticeLineInventoryMatch.id.asc(),
ShippingNoticeLineOnhandMatch.line_index.asc(),
ShippingNoticeLineOnhandMatch.id.asc(),
)
.all()
)
@@ -548,20 +548,20 @@ def project_inventory_candidate_facts(
current_match_rows = _current_match_rows(task, session=sess)
# [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。
snapshot_ids = {
int(row.inventory_snapshot_id)
int(row.onhand_snapshot_id)
for row in current_match_rows
if getattr(row, 'inventory_snapshot_id', None) is not None
if getattr(row, 'onhand_snapshot_id', None) is not None
}
snapshot_by_id: dict[int, Any] = {}
if snapshot_ids:
snapshot_by_id = {
int(item.id): item
for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all()
for item in sess.query(FreightRpaOnhandReportFile).filter(FreightRpaOnhandReportFile.id.in_(snapshot_ids)).all()
}
for row in current_match_rows:
snapshot = (
snapshot_by_id.get(int(row.inventory_snapshot_id))
if getattr(row, 'inventory_snapshot_id', None) is not None else None
snapshot_by_id.get(int(row.onhand_snapshot_id))
if getattr(row, 'onhand_snapshot_id', None) is not None else None
)
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
@@ -577,11 +577,11 @@ def project_inventory_candidate_facts(
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
'resolved_inventory_source_code': (
getattr(row, 'inventory_source_code', None)
getattr(row, 'source_code', None)
or (allowed_codes[0] if len(allowed_codes) == 1 else None)
),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
'inventory_snapshot_id': getattr(row, 'onhand_snapshot_id', None),
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
'inventory_file_sha256': (
dict(getattr(row, 'detail_json', None) or {}).get('file_sha256')
@@ -619,9 +619,9 @@ def project_inventory_candidate_facts(
'operation_id': f'match-line:{int(row.id)}',
}
elif (
str(getattr(row, 'inventory_source_code', '') or '').strip().upper()
str(getattr(row, 'source_code', '') or '').strip().upper()
and allowed_codes
and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes
and str(getattr(row, 'source_code', '') or '').strip().upper() not in allowed_codes
):
out_of_scope_details = {
'candidate_line_id': int(candidate_line_id),
@@ -631,7 +631,7 @@ def project_inventory_candidate_facts(
'actual_candidate_set_version': getattr(row, 'candidate_set_version', None),
'detected_at': datetime.utcnow().isoformat(),
'operation_id': f'match-line:{int(row.id)}',
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'resolved_inventory_source_code': getattr(row, 'source_code', None),
'allowed_source_codes_snapshot': allowed_codes,
}
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_combination_fingerprint.py
services/shipping_notice/onhand_combination_fingerprint.py
用途:为多源库存准备轮次生成稳定组合输入指纹。
依赖:标准库 hashlib/json。
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_configuration_test.py
services/shipping_notice/onhand_configuration_test.py
用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
@@ -16,17 +16,18 @@ from flask import current_app
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingInventoryConfigurationTestRun,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingInventoryValidationBatch,
FreightRpaOnhandConfigurationTestRun,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaOnhandValidationBatch,
)
def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
def _payload(run: FreightRpaOnhandConfigurationTestRun) -> dict[str, Any]:
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
return {
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
'id': run.id, 'run_no': run.run_no, 'source_id': run.source_id,
'validation_batch_id': run.validation_batch_id, 'rpa_batch_run_no': run.rpa_batch_run_no,
'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version,
'status': run.status, 'stage': run.stage,
@@ -36,10 +37,10 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
}
def _batch_payload(batch: ShippingInventoryValidationBatch) -> dict[str, Any]:
def _batch_payload(batch: FreightRpaOnhandValidationBatch) -> dict[str, Any]:
"""投影批量验证进度及其逐站点运行,供管理端按批次轮询。"""
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by(
ShippingInventoryConfigurationTestRun.id.asc(),
runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by(
FreightRpaOnhandConfigurationTestRun.id.asc(),
).all()
return {
'id': batch.id, 'batch_no': batch.batch_no, 'status': batch.status,
@@ -57,10 +58,10 @@ def _refresh_batch(batch_id: int | None) -> None:
"""按逐站点终态重算批次汇总;一个站点失败绝不覆盖其他站点结果。"""
if not batch_id:
return
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
if batch is None:
return
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all()
runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all()
terminal = {'completed', 'completed_empty', 'failed'}
batch.total_count = len(runs)
batch.success_count = sum(run.status == 'completed' for run in runs)
@@ -84,58 +85,61 @@ def _refresh_batch(batch_id: int | None) -> None:
batch.completed_at = datetime.utcnow()
def _validate_batch_sources(source_ids: list[int]) -> list[ShippingInventorySource]:
def _validate_batch_sources(source_ids: list[int]) -> list[FreightRpaSource]:
"""预检批量验证站点,强制使用已发布解析定义以明确空库存的业务语义。"""
ids: list[int] = []
for source_id in source_ids:
try:
value = int(source_id)
except (TypeError, ValueError):
raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED')
if value > 0 and value not in ids:
ids.append(value)
if not ids:
raise ValidationError('At least one inventory source is required', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
sources = ShippingInventorySource.query.filter(ShippingInventorySource.id.in_(ids)).all()
raise ValidationError('At least one inventory source is required', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED')
sources = FreightRpaSource.query.filter(FreightRpaSource.id.in_(ids)).all()
by_id = {source.id: source for source in sources}
if len(by_id) != len(ids):
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
ordered = [by_id[source_id] for source_id in ids]
for source in ordered:
if source.enabled:
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID')
if source.rpa_profile is None or not source.rpa_profile.enabled:
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
# s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。
config = source.onhand_report_config
profile = config.parsing_profile if config is not None else None
if profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
_expire_timed_out_runs(source)
active = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
active = FreightRpaOnhandConfigurationTestRun.query.filter(
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).first()
if active:
raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_ACTIVE')
raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_ACTIVE')
return ordered
def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retry_of_batch_id: int | None = None) -> dict[str, Any]:
"""创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。"""
sources = _validate_batch_sources(source_ids)
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
batch = ShippingInventoryValidationBatch(
batch = FreightRpaOnhandValidationBatch(
batch_no=f'CONFIG-BATCH-{stamp}', status='queued', total_count=len(sources), created_by=actor_id,
retry_of_batch_id=retry_of_batch_id,
)
db.session.add(batch)
db.session.flush()
grouped: dict[tuple[int, str], list[tuple[ShippingInventoryConfigurationTestRun, dict[str, Any]]]] = {}
grouped: dict[tuple[int, str], list[tuple[FreightRpaOnhandConfigurationTestRun, dict[str, Any]]]] = {}
for source in sources:
run = ShippingInventoryConfigurationTestRun(
run = FreightRpaOnhandConfigurationTestRun(
run_no=f'CONFIG-{source.source_code}-{stamp}-{source.id}', validation_batch_id=batch.id,
inventory_source_id=source.id,
source_id=source.id,
source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version,
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
)
@@ -143,7 +147,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
db.session.flush()
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
if source_payload is None:
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
source_payload = {**source_payload, 'validation_run_no': run.run_no}
grouped.setdefault((source.rpa_profile_id, source.connector_type), []).append((run, source_payload))
db.session.commit()
@@ -171,11 +175,11 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
def get_validation_batch(batch_id: int) -> dict[str, Any]:
"""返回批量验证当前汇总与逐站点结果,读取时同时收口超时任务。"""
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
if batch is None:
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
for run in ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all():
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all():
source = db.session.get(FreightRpaSource, run.source_id)
if source is not None:
_expire_timed_out_runs(source)
_refresh_batch(batch.id)
@@ -185,26 +189,26 @@ def get_validation_batch(batch_id: int) -> dict[str, Any]:
def get_latest_active_validation_batch() -> dict[str, Any] | None:
"""恢复最近仍在执行的批量验证,供管理端刷新后继续查看真实进度。"""
batch = ShippingInventoryValidationBatch.query.filter(
ShippingInventoryValidationBatch.status.in_(['queued', 'running']),
).order_by(ShippingInventoryValidationBatch.id.desc()).first()
batch = FreightRpaOnhandValidationBatch.query.filter(
FreightRpaOnhandValidationBatch.status.in_(['queued', 'running']),
).order_by(FreightRpaOnhandValidationBatch.id.desc()).first()
return get_validation_batch(batch.id) if batch is not None else None
def retry_failed_validation_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""仅重新投递失败或配置已变更的站点,已成功及空库存站点不重复执行。"""
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
if batch is None:
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
failed_ids = [run.inventory_source_id for run in ShippingInventoryConfigurationTestRun.query.filter_by(
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
failed_ids = [run.source_id for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(
validation_batch_id=batch.id, status='failed',
).all()]
if not failed_ids:
raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NO_FAILURE')
raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.ONHAND_VALIDATION_BATCH_NO_FAILURE')
return start_batch_test_export(failed_ids, actor_id=actor_id, retry_of_batch_id=batch.id)
def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool:
def _matches_current_configuration(run: FreightRpaOnhandConfigurationTestRun, source: FreightRpaSource) -> bool:
"""判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。"""
return bool(
source.rpa_profile
@@ -213,23 +217,23 @@ def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, s
)
def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
def _expire_timed_out_runs(source: FreightRpaSource) -> None:
"""按批量队列长度延长等待窗口,避免串行站点被单站超时误判。
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
"""
timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS']))
runs = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
runs = FreightRpaOnhandConfigurationTestRun.query.filter(
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).all()
for run in runs:
multiplier = 1
if run.validation_batch_id:
same_worker_queue = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.validation_batch_id == run.validation_batch_id,
ShippingInventoryConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no,
same_worker_queue = FreightRpaOnhandConfigurationTestRun.query.filter(
FreightRpaOnhandConfigurationTestRun.validation_batch_id == run.validation_batch_id,
FreightRpaOnhandConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no,
).count()
multiplier = max(1, same_worker_queue)
deadline = datetime.utcnow() - timedelta(seconds=timeout * multiplier)
@@ -243,43 +247,43 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
def get_latest_test_run(source_id: int) -> dict[str, Any] | None:
"""返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
_expire_timed_out_runs(source)
db.session.commit()
run = ShippingInventoryConfigurationTestRun.query.filter_by(
inventory_source_id=source.id,
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
source_id=source.id,
source_config_version=source.config_version,
rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1,
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first()
return _payload(run) if run else None
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。"""
source = db.session.get(ShippingInventorySource, source_id)
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
if source.enabled:
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID')
if source.rpa_profile is None or not source.rpa_profile.enabled:
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
_expire_timed_out_runs(source)
active = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
active = FreightRpaOnhandConfigurationTestRun.query.filter(
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
FreightRpaOnhandConfigurationTestRun.source_config_version == source.config_version,
FreightRpaOnhandConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first()
if active:
return _payload(active)
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
run = ShippingInventoryConfigurationTestRun(
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
run = FreightRpaOnhandConfigurationTestRun(
run_no=run_no, source_id=source.id, source_config_version=source.config_version,
rpa_profile_config_version=source.rpa_profile.config_version,
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
)
@@ -287,7 +291,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
db.session.flush()
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
if source_payload is None:
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
try:
trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={
'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id,
@@ -297,7 +301,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
raise
if not trigger:
db.session.rollback()
raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE')
raise ConflictError('RPA Worker is not ready', code='SHIPPING.ONHAND_CONFIGURATION_TEST_UNAVAILABLE')
run.result_json = {'trigger_written': True}
db.session.commit()
return _payload(run)
@@ -305,12 +309,12 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
"""读取指定库存站点的测试运行,防止跨站点查看结果。"""
run = ShippingInventoryConfigurationTestRun.query.filter_by(
inventory_source_id=source_id, run_no=str(run_no or '').strip(),
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
source_id=source_id, run_no=str(run_no or '').strip(),
).first()
if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
source = db.session.get(ShippingInventorySource, source_id)
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
source = db.session.get(FreightRpaSource, source_id)
if source is not None:
_expire_timed_out_runs(source)
db.session.commit()
@@ -320,12 +324,12 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
"""处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。"""
run_no = str(payload.get('run_no') or '').strip()
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(run_no=run_no).first()
if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
if run.status in {'completed', 'completed_empty', 'failed'}:
return _payload(run)
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
source = db.session.get(FreightRpaSource, run.source_id)
if source is None or not _matches_current_configuration(run, source):
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
run.result_json = {**(run.result_json or {}), 'stale_configuration': True}
@@ -335,7 +339,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
status = str(payload.get('status') or 'success').lower()
if status == 'empty':
# 空库存是查询业务结果,不代表登录、报表路径或 RPA 执行失败。
if source.parsing_profile is None or source.parsing_profile.status != 'published':
# s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。
config = source.onhand_report_config
profile = config.parsing_profile if config is not None else None
if profile is None or profile.status != 'published':
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出无库存数据,且尚未绑定已发布库存解析方案'; run.completed_at = datetime.utcnow()
else:
run.status = 'completed_empty'; run.stage = 'empty_data_pending_validation'
@@ -343,8 +350,8 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
'export_result': 'empty', 'structure_validation': 'not_observed',
'data_validation': 'pending_first_non_empty_export',
'message': str(payload.get('message') or '库存查询成功但当前无库存数据')[:500],
'confirmed_profile_id': source.parsing_profile_id,
'confirmed_profile_checksum': source.parsing_profile.checksum,
'confirmed_profile_id': profile.id,
'confirmed_profile_checksum': profile.checksum,
}
run.completed_at = datetime.utcnow()
db.session.commit()
@@ -370,12 +377,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, serialize_analysis
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.models import ShippingInventoryStructureAnalysis
from app.services.shipping_notice.onhand_structure_analysis import _analyse_path, serialize_analysis
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
from app.models import FreightRpaOnhandStructureAnalysis
import hashlib
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
from app.services.shipping_notice.onhand_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
suffix = resolve_inventory_upload_suffix(path.name)
@@ -384,7 +391,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
# The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy.
structure, suggested, summary, warnings = _analyse_path(path, suffix)
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
analysis = ShippingInventoryStructureAnalysis(
analysis = FreightRpaOnhandStructureAnalysis(
source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(),
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by,
@@ -392,18 +399,22 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
)
db.session.add(analysis); db.session.flush()
analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint})
# s18 起当前绑定取自 onhand_report_config 配置行;配置行缺失即无当前方案可比。
config = source.onhand_report_config
current_profile_id = config.parsing_profile_id if config is not None else None
current_profile_candidate = next((
candidate for candidate in (analysis.match_result_json.get('candidates') or [])
if int(candidate.get('profile_id') or 0) == int(source.parsing_profile_id or 0)
if int(candidate.get('profile_id') or 0) == int(current_profile_id or 0)
), None)
run.analysis_id = analysis.id; run.status = 'completed'
if current_profile_candidate is not None:
# 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。
current_profile = config.parsing_profile if config is not None else None
run.stage = 'current_profile_verified'
run.result_json = {
'analysis': serialize_analysis(analysis),
'confirmed_profile_id': source.parsing_profile_id,
'confirmed_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None,
'confirmed_profile_id': current_profile_id,
'confirmed_profile_checksum': current_profile.checksum if current_profile is not None else None,
'current_profile_verified': True,
'profile_match_level': current_profile_candidate.get('level'),
}
@@ -421,12 +432,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]:
"""接收批量 Worker 回调并逐项回写;未知运行标识只忽略,不影响同批其他站点。"""
batch_id = int(payload.get('validation_batch_id') or 0)
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
if batch is None:
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
results = payload.get('results') or []
if not isinstance(results, list):
raise ValidationError('Batch results must be a list', code='SHIPPING.INVENTORY_VALIDATION_BATCH_INVALID')
raise ValidationError('Batch results must be a list', code='SHIPPING.ONHAND_VALIDATION_BATCH_INVALID')
updated: list[dict[str, Any]] = []
ignored = 0
for item in results:
@@ -434,7 +445,7 @@ def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]:
ignored += 1
continue
run_no = str(item.get('validation_run_no') or '').strip()
run = ShippingInventoryConfigurationTestRun.query.filter_by(
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
run_no=run_no, validation_batch_id=batch.id,
).first()
if run is None:
@@ -459,22 +470,22 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]:
batch_id = int(payload.get('validation_batch_id') or 0)
run_no = str(payload.get('validation_run_no') or '').strip()
if not batch_id or not run_no:
raise ValidationError('Batch id and validation run number are required', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
raise ValidationError('Batch id and validation run number are required', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID')
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
if batch is None:
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
run = ShippingInventoryConfigurationTestRun.query.filter_by(
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
run_no=run_no, validation_batch_id=batch.id,
).first()
if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
if run.status in {'completed', 'completed_empty', 'failed'}:
return _payload(run)
# 仅接受 Worker 领取后的执行阶段,防止外部回调任意覆盖运行状态。
stage = str(payload.get('stage') or 'rpa_exporting').strip().lower()
if stage not in {'rpa_exporting'}:
raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID')
run.status = 'processing'
run.stage = stage
run.result_json = {**(run.result_json or {}), 'worker_claimed_at': datetime.utcnow().isoformat()}
@@ -485,28 +496,38 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]:
def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。"""
run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first()
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=source_id, run_no=run_no).first()
if run is None or run.status != 'completed' or run.analysis_id is None:
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY')
source = db.session.get(ShippingInventorySource, source_id)
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_READY')
source = db.session.get(FreightRpaSource, source_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if source is None or profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
if (
source.enabled
or source.config_version != run.source_config_version
or source.rpa_profile is None
or source.rpa_profile.config_version != run.rpa_profile_config_version
):
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.ONHAND_CONFIGURATION_TEST_STALE')
from app.services.shipping_notice.onhand_structure_analysis import adopt_published_profile
adopt_published_profile(run.analysis_id, profile_id)
source.parsing_profile_id = profile.id
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键;
# 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.parsing_profile_id = profile.id
config.updated_by = actor_id
source.updated_by = actor_id
source.config_version += 1
run.source_config_version = source.config_version
run.rpa_profile_config_version = source.rpa_profile.config_version
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
db.session.commit()
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
return {'test_run': _payload(run), 'parsing_profile_id': config.parsing_profile_id}
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_external_mapping.py
services/shipping_notice/onhand_external_mapping.py
用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。
依赖:ShippingInventoryExternalMapping、ShippingInventorySource。
依赖:FreightRpaOnhandExternalMapping、FreightRpaSource。
逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。
"""
@@ -10,7 +10,7 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None:
@@ -19,12 +19,12 @@ def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id:
warehouse = str(freight_warehouse_id or '').strip().upper()
if not code:
return None
source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first()
source = FreightRpaSource.query.filter_by(source_code=code, enabled=True).first()
if source is None:
return None
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
query = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id, enabled=True)
mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None
mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first()
mapping = mapping or query.filter(FreightRpaOnhandExternalMapping.freight_warehouse_id.is_(None)).first()
if mapping is None:
return None
return {
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_field_catalog.py
services/shipping_notice/onhand_field_catalog.py
用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。
依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。
依赖:FreightRpaOnhandField、统一业务异常和 SQLAlchemy 事务。
逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。
"""
@@ -14,14 +14,14 @@ from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile
from app.models import ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaParsingProfile
ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'}
ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'}
def _payload(item: ShippingInventoryField) -> dict[str, Any]:
def _payload(item: FreightRpaOnhandField) -> dict[str, Any]:
"""输出业务字段目录记录,不向管理端暴露内部字段编码。"""
return {
'id': item.id,
@@ -38,15 +38,15 @@ def _payload(item: ShippingInventoryField) -> dict[str, Any]:
def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]:
"""按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。"""
query = ShippingInventoryField.query
query = FreightRpaOnhandField.query
if not include_retired:
query = query.filter_by(status='active')
return [_payload(item) for item in query.order_by(
ShippingInventoryField.sort_order, ShippingInventoryField.id,
FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id,
).all()]
def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]:
def _normalized_payload(data: dict[str, Any], *, existing: FreightRpaOnhandField | None = None) -> dict[str, Any]:
"""校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。"""
display_name = str(data.get('display_name') or '').strip()
description = str(data.get('description') or '').strip() or None
@@ -55,11 +55,11 @@ def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryFiel
try:
sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') from exc
if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES:
raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
raise ValidationError('Inventory field data is invalid', code='SHIPPING.ONHAND_FIELD_INVALID')
if sort_order < 0 or sort_order > 9999:
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID')
return {
'display_name': display_name,
'description': description,
@@ -78,7 +78,7 @@ def _field_code(display_name: str) -> str:
stem = stem[:52]
code = stem
sequence = 2
while ShippingInventoryField.query.filter_by(field_code=code).first() is not None:
while FreightRpaOnhandField.query.filter_by(field_code=code).first() is not None:
suffix = f'_{sequence}'
code = f'{stem[:64 - len(suffix)]}{suffix}'
sequence += 1
@@ -88,9 +88,9 @@ def _field_code(display_name: str) -> str:
def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。"""
values = _normalized_payload(data)
if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None:
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
item = ShippingInventoryField(
if FreightRpaOnhandField.query.filter_by(display_name=values['display_name']).first() is not None:
raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT')
item = FreightRpaOnhandField(
field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id,
**values,
)
@@ -101,24 +101,24 @@ def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any
def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。"""
item = db.session.get(ShippingInventoryField, field_id)
item = db.session.get(FreightRpaOnhandField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
if item.status != 'active':
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE')
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.ONHAND_FIELD_IMMUTABLE')
values = _normalized_payload(data, existing=item)
references = _runtime_references(item.id)
if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type):
raise ConflictError(
'Referenced inventory field type or usage cannot be changed',
code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references},
code='SHIPPING.ONHAND_FIELD_IMMUTABLE', details={'references': references},
)
duplicate = ShippingInventoryField.query.filter(
ShippingInventoryField.display_name == values['display_name'],
ShippingInventoryField.id != item.id,
duplicate = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.display_name == values['display_name'],
FreightRpaOnhandField.id != item.id,
).first()
if duplicate is not None:
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT')
for key, value in values.items():
setattr(item, key, value)
item.updated_by = actor_id
@@ -128,14 +128,14 @@ def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -
def delete_field(field_id: int) -> dict[str, Any]:
"""物理删除从未被配置引用的用户字段。"""
item = db.session.get(ShippingInventoryField, field_id)
item = db.session.get(FreightRpaOnhandField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
references = _runtime_references(item.id)
if references:
raise ConflictError(
'Inventory field is referenced by runtime configuration',
code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references},
code='SHIPPING.ONHAND_FIELD_DELETE_BLOCKED', details={'references': references},
)
db.session.delete(item)
db.session.commit()
@@ -144,14 +144,14 @@ def delete_field(field_id: int) -> dict[str, Any]:
def retire_field(field_id: int) -> dict[str, Any]:
"""退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。"""
item = db.session.get(ShippingInventoryField, field_id)
item = db.session.get(FreightRpaOnhandField, field_id)
if item is None:
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
references = _runtime_references(item.id)
if references:
raise ConflictError(
'Inventory field is referenced by runtime configuration',
code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references},
code='SHIPPING.ONHAND_FIELD_RETIRE_BLOCKED', details={'references': references},
)
item.status = 'retired'
db.session.commit()
@@ -163,8 +163,8 @@ def _runtime_references(field_id: int) -> list[str]:
reference = str(field_id)
parsing_profiles = [
f'parsing_profile:{item.profile_code}:v{item.version}'
for item in ShippingInventoryParsingProfile.query.filter(
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
for item in FreightRpaParsingProfile.query.filter(
FreightRpaParsingProfile.status.in_(['draft', 'published']),
).all()
if reference in {
str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys()
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_file_identity.py
services/shipping_notice/onhand_file_identity.py
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
依赖:openpyxl、xlrd、csv、app.core.errors.AppError。
@@ -301,7 +301,7 @@ def assert_inventory_excel_warehouse_identity(
expected = str(expected_warehouse_id or "").strip().upper()
if not expected:
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
message="预期库位为空,无法校验库存文件内容",
http_status=409,
details={"operation": operation},
@@ -310,7 +310,7 @@ def assert_inventory_excel_warehouse_identity(
suffix = path.suffix.lower()
if suffix not in {".xls", ".xlsx", ".csv"}:
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
message="库存源身份校验仅支持 .xls / .xlsx / .csv",
http_status=409,
details={"operation": operation, "file_suffix": suffix},
@@ -319,14 +319,14 @@ def assert_inventory_excel_warehouse_identity(
found = extract_warehouse_ids_from_inventory_excel(path)
if not found:
raise AppError(
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING",
code="SHIPPING.ONHAND_FILE_WAREHOUSE_MISSING",
message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库",
http_status=409,
details={"operation": operation, "expected_warehouse_id": expected},
)
if len(found) > 1:
raise AppError(
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED",
code="SHIPPING.ONHAND_FILE_WAREHOUSE_MIXED",
message="库存文件包含多个 Warehouse ID,已拒绝入库",
http_status=409,
details={
@@ -338,7 +338,7 @@ def assert_inventory_excel_warehouse_identity(
actual = next(iter(found))
if actual != expected:
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库",
http_status=409,
details={
@@ -1,10 +1,11 @@
"""
services/shipping_notice/inventory_file_store.py
services/shipping_notice/onhand_file_store.py
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影;构造下载展示名
(build_inventory_download_name:企微压缩包短名规则 + exported_at 数据截止时间点)。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读/查询取回,禁止构造)、
freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_snapshot、export._storage_root。
逻辑:onhand_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
冻结候选读所属 OT 的 prepare 合并行(传入 Notice 时回源 order_task_id),单源读 active Link 文件;
禁止用 Notice.id 漏读 OT Link,导出数据源不得偏离行级匹配门禁命中的候选事实。
@@ -25,24 +26,25 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import (
ShippingInventoryFile,
FreightRpaOnhandReportFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingNoticeLineOnhandMatch,
ShippingOrderSnapshot,
ShippingTaskEvent,
ShippingTaskInventoryLink,
ShippingTaskOnhandLink,
)
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.freight_rpa.onhand.report_store import insert_onhand_report, update_onhand_report
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
from app.services.shipping_notice.onhand_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
from app.services.shipping_notice.inventory_source_gate import (
from app.services.shipping_notice.onhand_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
@@ -79,7 +81,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
name = str(filename or "").strip().lower()
if not name or "." not in name:
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
message="库存上传缺少可识别的文件后缀",
http_status=409,
)
@@ -90,7 +92,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
if name.endswith(".xls"):
return ".xls"
raise AppError(
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
message="库存上传仅支持 .xls / .xlsx / .csv",
http_status=409,
)
@@ -145,11 +147,11 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
pass
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
def active_inventory_file_for_task(task: ShippingNotice) -> FreightRpaOnhandReportFile | None:
"""
读取任务当前 active link 指向的库存快照。
核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入
核心逻辑:``ShippingTaskOnhandLink.task_id`` 挂在正式 OT 上;传入
``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。
Args:
@@ -163,12 +165,12 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
if task_id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(
ShippingTaskOnhandLink.query.filter_by(
task_id=int(task_id),
is_active=True,
invalidated_at=None,
)
.order_by(ShippingTaskInventoryLink.id.desc())
.order_by(ShippingTaskOnhandLink.id.desc())
.first()
)
return link.inventory_file if link else None
@@ -208,7 +210,7 @@ _DOWNLOAD_NAME_SANITIZE_RE = re.compile(r'[^\w.\-]+')
def build_inventory_download_name(
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
*,
source_file_name: str | None,
path: Path | None = None,
@@ -235,7 +237,7 @@ def build_inventory_download_name(
base = str(source_file_name or '').strip()
if not base:
suffix = Path(path or base).suffix or '.xlsx'
return f'{inv_file.inventory_file_no}{suffix.lower()}'
return f'{inv_file.onhand_file_no}{suffix.lower()}'
if _DOWNLOAD_CANONICAL_RE.match(base):
return base
seq_match = _DOWNLOAD_SEQ_PREFIX_RE.match(base)
@@ -274,10 +276,10 @@ def build_inventory_download_name(
return "_".join(tokens) + suffix.lower()
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
def read_inventory_file_lines(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
cached_rows = [
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
row for row in (inv_file.onhand_lines_json or []) if isinstance(row, dict)
]
if cached_rows:
return cached_rows, {'source': 'inventory_file_cache'}
@@ -285,7 +287,7 @@ def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dic
rows, column_meta = parse_inventory_snapshot_file(inv_file)
rows = [row for row in rows if isinstance(row, dict)]
if rows:
inv_file.inventory_lines_json = rows
inv_file.onhand_lines_json = rows
inv_file.line_count = len(rows)
db.session.flush()
return rows, column_meta
@@ -311,7 +313,7 @@ def resolve_inventory_lines_for_execution(
"""
解析库存匹配与导出的统一运行输入。
核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源
核心逻辑:已冻结候选源时优先 ``prepare_candidate_onhand_lines`` 合并各源
ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File;
否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。
@@ -326,19 +328,19 @@ def resolve_inventory_lines_for_execution(
# Notice 主键 ≠ OT 且不带候选集指针;冻结候选事实统一回源所属 OT 读取,
# 防止导出路径把多源任务退化成单源 Link,出现「行匹配过门禁但生成 Excel 失败」。
from app.models import ShippingOrderTask
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
from app.services.shipping_notice.stp_onhand_freeze import (
task_frozen_onhand_source_codes,
)
from app.services.shipping_notice.stp_line_inventory_match import (
prepare_candidate_inventory_lines,
from app.services.shipping_notice.stp_line_onhand_match import (
prepare_candidate_onhand_lines,
)
owner_task = task
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
owner_task = db.session.get(ShippingOrderTask, int(order_task_id)) or task
if len(task_frozen_inventory_source_codes(owner_task)) >= 1:
prep = prepare_candidate_inventory_lines(owner_task)
if len(task_frozen_onhand_source_codes(owner_task)) >= 1:
prep = prepare_candidate_onhand_lines(owner_task)
if prep.get('status') == 'ready':
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
if rows:
@@ -373,12 +375,12 @@ def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
)
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineOnhandMatch]:
"""读取 OT 当前有效的行级库存匹配事实。"""
task_id = getattr(task, 'id', None)
if task_id is None:
return []
return ShippingNoticeLineInventoryMatch.query.filter_by(
return ShippingNoticeLineOnhandMatch.query.filter_by(
task_id=int(task_id), is_current=True,
).all()
@@ -428,7 +430,7 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) ->
)
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> FreightRpaOnhandReportFile:
"""
保存库存 Excel 并创建任务级库存快照。
@@ -438,7 +440,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
"""
if not is_inventory_source_stable(task):
raise AppError(
code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
code="SHIPPING.ONHAND_SOURCE_GATE_BLOCKED",
message="库存源尚未稳定,拒绝保存库存上传文件",
http_status=409,
)
@@ -454,7 +456,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
path.parent.mkdir(parents=True, exist_ok=True)
try:
upload.save(str(path))
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
structure_check = validate_production_inventory_structure(source_code=source_code, path=path)
inventory_lines, column_meta = parse_inventory_excel_with_meta(
@@ -475,7 +477,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
})
if not inventory_lines:
raise AppError(
code='SHIPPING.INVENTORY_FILE_EMPTY',
code='SHIPPING.ONHAND_FILE_EMPTY',
message='库存文件没有可用于匹配的有效库存数据',
http_status=409,
)
@@ -502,8 +504,10 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
pass
raise
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
# [STEP] 阶段 B Task 5:快照行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
# 本模块拿回 file_id 后按主键取回 ORM 对象,身份校验失败回滚删除仍按 ORM 行操作。
saved_file_id = insert_onhand_report(
onhand_file_no=inventory_file_no,
user_id=task.user_id,
source_file_name=str(upload.filename or "").strip() or path.name,
storage_path=str(path),
@@ -511,7 +515,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
schema_preview_json=preview,
share_mode="task_only",
line_count=len(inventory_lines),
inventory_lines_json=inventory_lines,
onhand_lines_json=inventory_lines,
field_mapping_json=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
mapping_confirmed=True,
@@ -526,8 +530,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
snapshot_status="ready",
exported_at=datetime.utcnow(),
)
db.session.add(inv_file)
db.session.flush()
inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id)
candidates = [task]
linked_tasks = [
@@ -535,9 +538,9 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
for item in candidates
if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item)
]
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
from app.services.shipping_notice.onhand_snapshot_store import link_snapshot_to_task
created_links: list[ShippingTaskInventoryLink] = []
created_links: list[ShippingTaskOnhandLink] = []
for item in linked_tasks:
link = link_snapshot_to_task(
item,
@@ -561,13 +564,14 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
"failed to delete inventory upload after link failure %s", path
)
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定",
http_status=409,
)
created_links.append(link)
if len(linked_tasks) > 1:
inv_file.share_mode = "batch_same_identity"
# [STEP] 阶段 B Task 5:多票同身份共用时改写 share_mode 也经 report_store 更新(同一 ORM 对象,行为不变)。
update_onhand_report(inv_file.id, share_mode="batch_same_identity")
return inv_file
@@ -576,13 +580,13 @@ def save_task_inventory_file_from_local_path(
source_path: str | Path,
*,
source_file_name: str | None = None,
) -> ShippingInventoryFile:
) -> FreightRpaOnhandReportFile:
"""
将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 FreightRpaOnhandReportFile 记录时调用。
核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview,
再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。
再创建 task_only 的 FreightRpaOnhandReportFile 与 active ShippingTaskOnhandLink。
Args:
task: 当前发货任务,用于绑定 user/batch 与 active link。
@@ -590,7 +594,7 @@ def save_task_inventory_file_from_local_path(
source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。
Returns:
ShippingInventoryFile: 已持久化的库存快照对象。
FreightRpaOnhandReportFile: 已持久化的库存快照对象。
Raises:
FileNotFoundError: 源文件不存在时抛出。
@@ -607,8 +611,10 @@ def save_task_inventory_file_from_local_path(
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
# [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
# 拿回 file_id 后取回 ORM 对象并交由 replace_task_inventory_link 建立 active link(link 表留在发货域)。
saved_file_id = insert_onhand_report(
onhand_file_no=inventory_file_no,
user_id=task.user_id,
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
storage_path=str(path),
@@ -618,27 +624,26 @@ def save_task_inventory_file_from_local_path(
line_count=0,
source_query_json={'trigger_type': 'manual_upload'},
)
db.session.add(inv_file)
db.session.flush()
inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id)
replace_task_inventory_link(task, inv_file, role="owner")
return inv_file
def replace_task_inventory_link(
task: ShippingNotice,
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
*,
role: str = "member",
) -> ShippingTaskInventoryLink:
) -> ShippingTaskOnhandLink:
"""替换任务 active 库存 link,保留历史 link 审计。"""
if task.id is None:
db.session.flush()
existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all()
existing = ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True).all()
for link in existing:
link.is_active = False
new_link = ShippingTaskInventoryLink(
new_link = ShippingTaskOnhandLink(
task_id=task.id,
inventory_file_id=inv_file.id,
onhand_file_id=inv_file.id,
link_role=role,
access_mode="readonly",
linked_by_user_id=inv_file.user_id,
@@ -649,7 +654,7 @@ def replace_task_inventory_link(
task_id=task_event_task_id(task),
event_type="inventory_file_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"role": role,
"share_mode": inv_file.share_mode,
},
@@ -667,14 +672,14 @@ def read_linked_inventory_schema_preview(task: ShippingNotice) -> dict[str, Any]
return dict(inv_file.schema_preview_json)
path = Path(inv_file.storage_path)
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = inv_file.source_file_name or path.name
inv_file.schema_preview_json = preview
return preview
def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。
仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败,
@@ -682,18 +687,18 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list
"""
path = Path(inv_file.storage_path)
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
from app.models import ShippingInventorySource
from app.services.shipping_notice.inventory_parsing_profile import require_source_profile
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
from app.models import FreightRpaSource
from app.services.shipping_notice.onhand_parsing_profile import require_source_profile
from app.core.errors import ValidationError
source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first()
source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first()
profile = require_source_profile(source)
actual_format = path.suffix.lower().lstrip('.')
if actual_format != profile.file_format:
raise ValidationError(
f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
definition = dict(profile.definition_json or {})
return parse_inventory_excel_with_meta(
@@ -706,7 +711,7 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list
def apply_inventory_parse_result_to_linked_tasks(
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
inventory_lines: list[dict[str, Any]],
*,
field_mapping: dict[str, str] | None = None,
@@ -714,7 +719,7 @@ def apply_inventory_parse_result_to_linked_tasks(
mapping_confirmed: bool = False,
) -> list[ShippingNotice]:
"""把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。"""
inv_file.inventory_lines_json = inventory_lines
inv_file.onhand_lines_json = inventory_lines
inv_file.line_count = len(inventory_lines)
if field_mapping:
inv_file.field_mapping_json = field_mapping
@@ -732,7 +737,7 @@ def apply_inventory_parse_result_to_linked_tasks(
return linked_tasks
def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]:
def linked_task_nos_for_inventory_file(inv_file: FreightRpaOnhandReportFile | None) -> list[str]:
"""返回库存快照当前 active link 关联的任务编号列表。"""
if not inv_file:
return []
@@ -743,7 +748,7 @@ def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -
return sorted(set(task_nos))
def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool:
def start_inventory_file_linked_tasks(inv_file: FreightRpaOnhandReportFile | None) -> bool:
"""
按库存快照关联任务批量入队续跑。
@@ -775,7 +780,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
stage="inventory_matching",
stage="onhand_matching",
step_title="匹配库存",
status="running",
message="本批库存快照已确认,等待匹配库存",
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_mapping.py
services/shipping_notice/onhand_mapping.py
用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。
依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。
依赖:FreightRpaOnhandField、match_rule_desc、标准 `json`/`typing` 能力。
逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。
"""
@@ -11,7 +11,7 @@ from __future__ import annotations
import re
from typing import Any
from app.models import ShippingInventoryField
from app.models import FreightRpaOnhandField
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
@@ -19,7 +19,7 @@ LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "ava
LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty")
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
"""读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。"""
try:
ids = {int(key) for key in field_mapping}
@@ -27,8 +27,8 @@ def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventory
return {}
if not ids or any(item <= 0 for item in ids):
return {}
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
rows = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active',
).all()
return {str(row.id): row for row in rows}
@@ -43,7 +43,7 @@ def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool:
return False
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]:
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, FreightRpaOnhandField]]:
"""验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。"""
catalog = _catalog_by_id(field_mapping)
if _uses_catalog_ids(field_mapping):
@@ -56,8 +56,8 @@ def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str]
def usage_field_ids() -> dict[str, set[str]]:
"""按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。"""
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.status == 'active',
rows = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.status == 'active',
).all()
result: dict[str, set[str]] = {}
for row in rows:
@@ -99,7 +99,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]:
"""基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。"""
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
from app.services.shipping_notice.onhand_snapshot import _column_map, _map_header
col_map = _column_map()
norm_headers = [str(h or "").strip() for h in headers]
@@ -165,9 +165,9 @@ def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> di
"""按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。"""
if not as_catalog:
return _suggest_runtime_field_mapping(headers)
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header
rows = ShippingInventoryField.query.filter_by(status='active').all()
rows = FreightRpaOnhandField.query.filter_by(status='active').all()
header_by_name: dict[str, list[str]] = {}
for header in headers:
normalized = normalise_header(header)
@@ -1,10 +1,10 @@
"""
services/shipping_notice/inventory_mapping_workflow.py
services/shipping_notice/onhand_mapping_workflow.py
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
依赖:onhand_file_store、onhand_snapshot、query_service、state_machine、tool_common。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析;
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 onhand_lines_json。
"""
from __future__ import annotations
@@ -13,13 +13,13 @@ from typing import Any
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import (
from app.services.shipping_notice.onhand_file_store import (
_can_relink_inventory,
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
)
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
from app.services.shipping_notice.onhand_snapshot import build_field_alignment_preview
from app.services.shipping_notice.query_service import serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
@@ -44,7 +44,7 @@ def inventory_loaded_response(
将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。
核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库)
写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
写回 ``onhand_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
禁止覆盖共享 File 上已有行缓存。
Args:
@@ -57,7 +57,7 @@ def inventory_loaded_response(
field_mapping: published Profile 的字段映射快照。
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
commit: False 时仅 flush,供批量回调维持外层事务边界。
persist_lines: False 时不写 File.inventory_lines_json(复用路径)。
persist_lines: False 时不写 File.onhand_lines_json(复用路径)。
Returns:
Tool 标准响应;成功后任务可直接进入库存匹配。
@@ -101,7 +101,7 @@ def inventory_loaded_response(
)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="completed",
message=f"已载入库存 {len(inventory_lines)} 行",
@@ -138,7 +138,7 @@ def inventory_loaded_response(
"warnings": warnings or [],
"source": source,
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"inventory_file_no": inv_file.onhand_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
"persist_lines": bool(persist_lines),
},
@@ -1,8 +1,8 @@
"""
backend/app/services/shipping_notice/inventory_parsing_profile.py
backend/app/services/shipping_notice/onhand_parsing_profile.py
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
"""
@@ -18,41 +18,41 @@ from sqlalchemy import func
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingInventoryField,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
FreightRpaOnhandField,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaOnhandStructureAnalysis,
ShippingOrderField,
ShippingReceiptReportConfig,
FreightRpaInboundReportConfig,
)
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
field_ids: list[int] = []
for raw_id in field_mapping:
try:
field_id = int(raw_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
if field_id <= 0:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_ids.append(field_id)
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
fields = {str(row.id): row for row in rows if row.status == 'active'}
if len(fields) != len(set(str(item) for item in field_ids)):
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
return fields
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
if not match_ids or len(quantity_ids) != 1:
raise ValidationError(
'Parsing profile requires at least one match field and exactly one inventory quantity field',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return match_ids | quantity_ids
@@ -69,13 +69,13 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
if unknown:
raise ValidationError(
f'Movement parsing profile references unknown field: {sorted(unknown)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
if missing:
raise ValidationError(
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return mapped_codes
@@ -89,15 +89,15 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
if not isinstance(field_mapping, dict) or not field_mapping:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if purpose == 'inbound':
_required_movement_field_ids(raw)
@@ -112,7 +112,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
if not isinstance(match_keys, list) or not match_keys:
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
normalized_keys: list[dict[str, str]] = []
seen_order_fields: set[str] = set()
seen_inventory_fields: set[str] = set()
@@ -124,9 +124,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
field is None or field.status != 'active' or field.scope != 'line'
or inventory is None or inventory.usage_type != 'match_identity'
):
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
@@ -143,20 +143,20 @@ def _require_sample_evidence(
definition: dict[str, Any],
*,
file_format: str,
) -> ShippingInventoryStructureAnalysis:
) -> FreightRpaOnhandStructureAnalysis:
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
try:
analysis_id = int(sample_analysis_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'Parsing profile requires sample analysis evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
) from exc
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
raise ValidationError(
'Parsing profile sample analysis evidence is unavailable',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
@@ -166,13 +166,13 @@ def _require_sample_evidence(
if not isinstance(selected, dict):
raise ValidationError(
'Parsing profile worksheet or header row is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
duplicates = {
str(column.get('header') or '').strip()
@@ -181,12 +181,12 @@ def _require_sample_evidence(
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping uses duplicate sample headers',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
return analysis
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
"""序列化解析 Profile 管理 DTO。"""
sample_analysis = profile.sample_analysis
return {
@@ -212,49 +212,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
def list_profiles() -> list[dict[str, Any]]:
"""列出全部解析 Profile 版本。"""
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
).all()]
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile is not None and profile.status != 'draft':
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
code = str(data.get('profile_code') or '').strip().upper()
if not code:
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile is not None and code != profile.profile_code:
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
if profile is None:
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
if purpose not in {'onhand', 'inbound', 'outbound'}:
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
'Draft parsing profile purpose is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.purpose = purpose
profile.display_name = str(data.get('display_name') or code).strip()
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and requested_file_format != profile.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition'), purpose=purpose)
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
)
@@ -262,7 +262,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
if not bool(data.get('confirm_sample_replacement')):
raise ValidationError(
'Replacing inventory sample evidence requires confirmation',
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
)
history = list(profile.sample_evidence_history_json or [])
history.append({
@@ -280,11 +280,11 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
_require_sample_evidence(
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
)
@@ -304,7 +304,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
raise ValidationError(
'Parsing profile match keys must reference the current published order schema',
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
)
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
profile.checksum = hashlib.sha256(encoded).hexdigest()
@@ -317,17 +317,18 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'published':
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
bound_sources = ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count()
# 收料报表配置(ShippingReceiptReportConfig)同样绑定解析 Profile:退役前必须一并核查,
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
# 收料报表配置(FreightRpaInboundReportConfig)同样绑定解析 Profile:退役前必须一并核查,
# 否则入站文件解析链(inbound purpose)会静默失去规则。
bound_receipt_configs = ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
bound_receipt_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_receipt_configs:
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
return payload(profile)
@@ -335,18 +336,20 @@ def retire(profile_id: int) -> dict[str, Any]:
def delete_draft(profile_id: int) -> None:
"""删除从未发布的解析 Profile 草稿。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
profile = getattr(source, 'parsing_profile', None)
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = getattr(source, 'onhand_report_config', None)
profile = config.parsing_profile if config is not None else None
if profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
return profile
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_profile_matching.py
services/shipping_notice/onhand_profile_matching.py
用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。
依赖:ShippingInventoryParsingProfile、库存结构指纹服务。
依赖:FreightRpaParsingProfile、库存结构指纹服务。
逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。
"""
@@ -10,17 +10,17 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingInventoryParsingProfile
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
from app.models import FreightRpaParsingProfile
from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header
def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]:
def _profile_headers(profile: FreightRpaParsingProfile) -> list[str]:
"""读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。"""
structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {}
return [str(header) for header in structure.get('headers', [])]
def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]:
def _difference(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> dict[str, list[str]]:
"""以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。"""
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
observed = [normalise_header(header) for header in structure.get('selected_headers', [])]
@@ -32,9 +32,9 @@ def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfi
}
def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool:
def _core_mapping_matches(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> bool:
"""确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。"""
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])}
@@ -53,7 +53,7 @@ def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]:
"""查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。"""
exact = str(analysis.get('exact_structure_fingerprint') or '')
compatible = str(analysis.get('compatibility_fingerprint') or '')
profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all()
profiles = FreightRpaParsingProfile.query.filter_by(status='published').all()
candidates: list[dict[str, Any]] = []
for profile in profiles:
level = None
@@ -1,9 +1,14 @@
"""
services/shipping_notice/inventory_recovery_service.py
services/shipping_notice/onhand_recovery_service.py
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉;阶段 B Task 7
修复轮新增 onhand 报表事实落地后的候选 settle(settle_preparation_source_
from_onhand_report)与等待任务反查(waiting_preparation_source_task_ids)。
依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。SourceAttempt
被 settle 后的 PreparationAttempt 聚合(含 RecoveryPlan 收口)收敛到
_aggregate_preparation_after_source_settle——per-source RPA 回调与 onhand
事实处理函数(handle_onhand_report)共用同一聚合出口,防两路语义漂移。
"""
from __future__ import annotations
@@ -13,30 +18,30 @@ from typing import Any
from app import db
from app.models import (
ShippingInventoryFile,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
FreightRpaOnhandReportFile,
ShippingOnhandPreparationAttempt,
ShippingOnhandPreparationSourceAttempt,
ShippingOrderTask,
ShippingOrderCandidate,
ShippingTaskInventoryLink,
ShippingTaskOnhandLink,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
from app.services.shipping_notice.onhand_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts
def create_inventory_preparation_round(
*, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None,
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
gate_attempt_id: int | None = None,
) -> ShippingInventoryPreparationAttempt:
) -> ShippingOnhandPreparationAttempt:
"""创建一次任务级准备轮次;同一任务按 attempt_no 递增。"""
last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
ShippingInventoryPreparationAttempt.attempt_no.desc(),
last = ShippingOnhandPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
ShippingOnhandPreparationAttempt.attempt_no.desc(),
).first()
round_row = ShippingInventoryPreparationAttempt(
round_row = ShippingOnhandPreparationAttempt(
task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id,
recovery_plan_id=recovery_plan_id,
attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued',
@@ -53,7 +58,7 @@ def create_inventory_preparation_round(
db.session.flush()
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
if not codes:
codes = task_frozen_inventory_source_codes(task)
codes = task_frozen_onhand_source_codes(task)
active_file = active_inventory_file_for_task(task)
for source_code in codes:
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
@@ -65,15 +70,15 @@ def create_inventory_preparation_round(
parser_version=getattr(active_file, 'parser_version', None) if active_file else None,
mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None,
)
reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable)
link = ShippingTaskInventoryLink.query.filter_by(
reusable = bool(action_code == 'retry_onhand_from_field_mapping' and reusable)
link = ShippingTaskOnhandLink.query.filter_by(
task_id=int(task.id), matched_source_code=source_code, is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
source = ShippingInventoryPreparationSourceAttempt(
).order_by(ShippingTaskOnhandLink.id.desc()).first()
source = ShippingOnhandPreparationSourceAttempt(
preparation_attempt_id=int(round_row.id), source_code=source_code,
status='reusable' if reusable else 'queued',
inventory_file_id=int(active_file.id) if reusable and active_file else None,
task_inventory_link_id=int(link.id) if reusable and link else None,
onhand_file_id=int(active_file.id) if reusable and active_file else None,
task_onhand_link_id=int(link.id) if reusable and link else None,
operation_id=operation_id,
)
db.session.add(source)
@@ -90,18 +95,18 @@ def create_inventory_preparation_round(
sources=[
{
'source_code': str(item.source_code),
'snapshot_id': item.inventory_file_id,
'snapshot_id': item.onhand_file_id,
'snapshot_hash': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None)
if item.inventory_file_id else None
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'file_sha256', None)
if item.onhand_file_id else None
),
'parser_version': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None)
if item.inventory_file_id else None
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'parser_version', None)
if item.onhand_file_id else None
),
'mapping_version': (
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None)
if item.inventory_file_id else None
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'mapping_version', None)
if item.onhand_file_id else None
),
}
for item in round_row.source_attempts
@@ -114,8 +119,8 @@ def create_inventory_preparation_round(
def sync_inventory_preparation_round(
*, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any,
) -> ShippingInventoryPreparationAttempt:
*, preparation_attempt: ShippingOnhandPreparationAttempt, result: Any,
) -> ShippingOnhandPreparationAttempt:
"""将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。"""
def _read(name: str, default: Any) -> Any:
return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default)
@@ -151,29 +156,24 @@ def sync_inventory_preparation_round(
return preparation_attempt
def sync_preparation_source_from_rpa_attempt(
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
) -> None:
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
def _aggregate_preparation_after_source_settle(preparation: ShippingOnhandPreparationAttempt) -> None:
"""按 SourceAttempt 状态聚合 PreparationAttempt 终态并收口绑定的 RecoveryPlan(只 flush 不 commit)。
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。
用途:SourceAttempt 被 settle(ready/failed/waiting)后的统一聚合出口——
per-source RPA 回调(sync_preparation_source_from_rpa_attempt)与
onhand 报表事实处理函数(settle_preparation_source_from_onhand_report,
阶段 B Task 7 修复轮)共用同一聚合语义,防止两条路径漂移。
核心逻辑:任一 failed → failed;仍有 queued/running/waiting → waiting_external;
全部 ready/reusable/skipped → succeeded(记 completed_at);聚合到终态后
同步收口绑定的 RecoveryPlan(succeeded/failed + 时间戳 + 失败码),
避免已完成的计划继续占用 active-plan 互斥位。
Args:
preparation: SourceAttempt 已更新的准备轮次行。
Returns:
None。只 flush——事务提交时机归属调用方。
"""
source = ShippingInventoryPreparationSourceAttempt.query.filter_by(
rpa_attempt_id=int(rpa_attempt_id),
).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first()
if source is None:
if preparation is None:
return
status = str(rpa_status or '').strip().lower()
if status in {'succeeded', 'consumed'}:
source.status = 'ready'
if inventory_file_id:
source.inventory_file_id = int(inventory_file_id)
elif status in {'failed', 'exhausted'}:
source.status = 'failed'
elif status in {'queued', 'running'}:
source.status = 'waiting'
preparation = source.preparation_attempt
rows = list(getattr(preparation, 'source_attempts', []) or [])
if any(row.status == 'failed' for row in rows):
preparation.status = 'failed'
@@ -201,4 +201,105 @@ def sync_preparation_source_from_rpa_attempt(
if preparation.status == 'failed':
plan.failure_code = 'inventory_preparation_failed'
plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'}
def settle_preparation_source_from_onhand_report(
*, source_code: str, onhand_file_id: int,
) -> list[ShippingOnhandPreparationAttempt]:
"""onhand 报表事实落地后:把该来源等待中的 SourceAttempt settle 为 ready 并绑定文件。
【AI 触发时机】:onhand 事实处理函数(shipping_notice.onhand_report_handler.
handle_onhand_report)在文件行 commit 后投递 ok=True 事实时调用——共享快照
模型下「该来源已有可用快照」对所有等待该来源的候选准备成立。
核心逻辑:[STEP 1] 取该来源 status ∈ queued/running/waiting 且未绑定文件的
SourceAttempt(幂等集:已 ready/已绑定的行不在集合内,重复投递零副作用、
绝不重复候选行);[STEP 2] 逐行 ready + 绑定 onhand_file_id;
[STEP 3] 对受影响的 PreparationAttempt 逐一聚合终态
(_aggregate_preparation_after_source_settle,含 RecoveryPlan 收口)。
只 flush 不 commit——事务提交时机归属调用方(处理函数)。
Args:
source_code: 库存来源编码(与 SourceAttempt.source_code 精确匹配)。
onhand_file_id: 已提交的 freight_rpa_onhand_report_files 主键。
Returns:
受影响(发生了 settle)的 PreparationAttempt 列表;无等待行时为空表。
"""
waiting = (
ShippingOnhandPreparationSourceAttempt.query
.filter(
ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(),
ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')),
ShippingOnhandPreparationSourceAttempt.onhand_file_id.is_(None),
)
.all()
)
affected: dict[int, ShippingOnhandPreparationAttempt] = {}
for row in waiting:
row.status = 'ready'
row.onhand_file_id = int(onhand_file_id)
preparation = row.preparation_attempt
if preparation is not None:
affected[int(preparation.id)] = preparation
for preparation in affected.values():
_aggregate_preparation_after_source_settle(preparation)
if waiting:
db.session.flush()
return list(affected.values())
def waiting_preparation_source_task_ids(*, source_code: str) -> list[int]:
"""列出「仍在等待该来源库存」的准备轮次任务 ID(onhand 事实处理函数门禁重投影用)。
用途:onhand 失败/空事实(无文件身份)时,处理函数只对等待该来源的任务重投影
履约门禁(回调失败路径的门禁更新归处理函数),不发明/改写任何候选行。
核心逻辑:按 source_code 取 status ∈ queued/running/waiting 的 SourceAttempt,
经其准备轮次收集去重 task_id;只读查询。
Args:
source_code: 库存来源编码。
Returns:
去重后的 ShippingOrderTask.id 列表(无等待行时为空表)。
"""
rows = (
ShippingOnhandPreparationSourceAttempt.query
.filter(
ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(),
ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')),
)
.all()
)
task_ids: list[int] = []
for row in rows:
preparation = row.preparation_attempt
if preparation is not None and preparation.task_id and int(preparation.task_id) not in task_ids:
task_ids.append(int(preparation.task_id))
return task_ids
def sync_preparation_source_from_rpa_attempt(
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
) -> None:
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。聚合语义自阶段 B
Task 7 修复轮起收敛到 _aggregate_preparation_after_source_settle(与
settle_preparation_source_from_onhand_report 共用同一出口)。
"""
source = ShippingOnhandPreparationSourceAttempt.query.filter_by(
rpa_attempt_id=int(rpa_attempt_id),
).order_by(ShippingOnhandPreparationSourceAttempt.id.desc()).first()
if source is None:
return
status = str(rpa_status or '').strip().lower()
if status in {'succeeded', 'consumed'}:
source.status = 'ready'
if inventory_file_id:
source.onhand_file_id = int(inventory_file_id)
elif status in {'failed', 'exhausted'}:
source.status = 'failed'
elif status in {'queued', 'running'}:
source.status = 'waiting'
preparation = source.preparation_attempt
_aggregate_preparation_after_source_settle(preparation)
db.session.flush()
@@ -0,0 +1,156 @@
"""
services/shipping_notice/onhand_report_handler.py
用途:onhand(在手库存)报表事实的发货侧业务处理函数(阶段 B Task 7)——
在手文件归档终态 commit 后由 dispatch_report_fact 投递的 ReportFact
只在此更新发货自己的门禁与候选相关状态,绝不写调拨或 RPA 侧事实。
依赖:app.db、app.models(FreightRpaOnhandReportFile 只读行获取 / ShippingTaskOnhandLink /
ShippingOrderTask / ShippingProcessExecution)、app.core.errors
(ValidationError / NotFoundError)、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、
process_gate_bridge(门禁同步)。
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks)
注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调
(rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch)
在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮
接线;HTTP 收件入口 rpa_report_inventory_batch 只入队 Job、不 commit 文件,
故不投递)。处理函数只改发货自己的行:[候选] settle 等待该来源的
SourceAttempt 并绑定该文件(共享快照模型);[门禁] 对受影响的准备轮次任务与
挂接该文件的任务重投影履约门禁;[提交] 处理函数自行 commit(文件行已由归档方
提交,绝不回滚)。行插入唯一入口在 freight_rpa/onhand/report_store(本模块
【禁止】构造 FreightRpaOnhandReportFile 行,边界由 test_report_model_boundary 锁定);
TransferSourceJob 归调拨域(本模块不写)。
"""
from __future__ import annotations
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
def _sync_gates_for_task_ids(task_ids: list[int]) -> None:
"""对给定任务逐一重投影履约门禁(活动、非 superseded 执行链;幂等可重放)。
核心逻辑:按主键取任务与活动执行链——执行链缺失/已 superseded 时跳过
(重冻结/复活链路上 Task 指针可能短暂指向旧执行链:迟到事实只保留原始
审计,不得回写已废弃执行的 Gate);命中即 sync_fulfillment_gates_from_task
(域事实投影为 Gate 结果,重复投递重投影同值,不产生重复行)。
只写不 commit——事务提交时机归属调用方(handle_onhand_report)。
"""
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
seen: set[int] = set()
for task_id in task_ids:
if task_id in seen:
continue
seen.add(task_id)
task = db.session.get(ShippingOrderTask, int(task_id))
if task is None or not getattr(task, 'active_process_execution_id', None):
continue
execution = db.session.get(
ShippingProcessExecution, int(task.active_process_execution_id),
)
if execution is not None and str(execution.status or '').strip().lower() != 'superseded':
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
def handle_onhand_report(fact: ReportFact) -> None:
"""report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。
不插入 freight_rpa_onhand_report_files。
(Task 7 契约 docstring 逐字保留如上;修复轮补充说明见下。)
核心逻辑:
[STEP 1] kind 门禁(fail-closed,防误注册/误分发);
[STEP 2] success 事实(ok 且 file_id 有值):按主键取回已提交的 onhand 报表行
(只读——行由 freight_rpa/onhand/report_store 收敛写入,本模块只消费;缺失即
fail-closed 抛 NotFoundError);
[STEP 3 候选] settle 等待该来源的候选准备行并绑定该文件
(onhand_recovery_service.settle_preparation_source_from_onhand_report——共享
快照模型:该来源已有可用快照即对所有等待该来源的候选准备成立;幂等——
已 ready/已绑定的行不在等待集,重复投递零副作用、不重复候选行);
[STEP 4 门禁] 对受影响的准备轮次任务 + 挂接该文件(active link)的任务重投影
履约门禁(sync_fulfillment_gates_from_task,幂等可重放);
[STEP 5] db.session.commit()——处理函数提交自己的候选/门禁写(文件行已由
归档方提交,绝不回滚)。
失败/空事实(ok=False 或 file_id=None):无文件身份——不发明候选行、不 settle
任何 SourceAttempt;仅对仍在等待该来源库存的任务重投影门禁(回调失败路径的
门禁更新归本处理函数),随后同样 commit。
【不写 TransferSourceJob】(归 in_transit_transfer 域);【不构造
freight_rpa_onhand_report_files 行】(归 freight_rpa 域唯一写入口)。
异常原样外抛(不捕获):文件行已提交不回滚,Worker 重试整笔回调补齐。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind='onhand'/
source_code/file_id/sha256/ok/error_code/error_message)。
Returns:
None(候选/门禁写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 onhand(误注册/误分发,fail-closed)。
NotFoundError: fact.file_id 对应的在手报表行不存在(事实先于文件提交
属硬性不一致,fail-closed 而非静默跳过)。
"""
# [STEP 1] kind 门禁:本函数只消费 onhand 事实(dispatch 已按 kind 路由,
# 防御性复核,防止误注册成其他 kind 的处理函数后静默错写发货行)。
kind = require_report_kind(fact.report_kind)
if kind != 'onhand':
raise ValidationError(
f"handle_onhand_report only accepts onhand facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
from app.services.shipping_notice.onhand_recovery_service import (
settle_preparation_source_from_onhand_report,
waiting_preparation_source_task_ids,
)
source_code = str(fact.source_code or '').strip()
affected_task_ids: list[int] = []
if not fact.ok or fact.file_id is None:
# [STEP 2·失败/空分支] 无文件身份:不发明候选行、不 settle 任何 SourceAttempt;
# 仅对仍在等待该来源库存的任务重投影门禁(失败路径门禁更新归本处理函数)。
affected_task_ids.extend(waiting_preparation_source_task_ids(source_code=source_code))
else:
# [STEP 2·success 分支] 只读取回已提交的在手报表行(构造禁走 report_store;
# 读取按主键)。
inv_file = db.session.get(FreightRpaOnhandReportFile, int(fact.file_id))
if inv_file is None:
raise NotFoundError(
f"Onhand report file not found: {fact.file_id}",
details={'file_id': fact.file_id},
)
file_source = str(inv_file.source_code or source_code).strip()
# [STEP 3·候选] settle 等待该来源的候选准备行并绑定该文件(幂等)。
settled = (
settle_preparation_source_from_onhand_report(
source_code=file_source, onhand_file_id=int(inv_file.id),
)
if file_source
else []
)
for preparation in settled:
if preparation.task_id:
affected_task_ids.append(int(preparation.task_id))
# [STEP 4·门禁] 挂接该文件(active link)的任务一并重投影门禁。
links = (
ShippingTaskOnhandLink.query
.filter_by(onhand_file_id=inv_file.id, is_active=True)
.all()
)
for link in links:
if link.task_id:
affected_task_ids.append(int(link.task_id))
_sync_gates_for_task_ids(affected_task_ids)
# [STEP 5] 处理函数提交自己的候选/门禁写(sync_fulfillment_gates_from_task
# 不 commit——不提交则请求结束回滚会丢掉这些写;文件行已提交,不受影响)。
db.session.commit()
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_routing_engine.py
services/shipping_notice/onhand_routing_engine.py
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、onhand_source_repository。
逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源,
命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层);
随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
@@ -16,8 +16,8 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Any
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.models import FreightRpaOnhandRoutingRule, ShippingOrderSnapshot
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
from app.services.shipping_notice.routing_operators import matches_operator
@@ -76,7 +76,7 @@ class InventoryRoutingResult:
)
def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]:
def _matched_rule_summaries(rules: list[FreightRpaOnhandRoutingRule]) -> tuple[dict[str, Any], ...]:
"""将命中规则折叠为可审计、可序列化的摘要元组。"""
return tuple(
{
@@ -177,7 +177,7 @@ def _condition_value_from_maps(
def _rule_matches(
rule: ShippingInventoryRoutingRule,
rule: FreightRpaOnhandRoutingRule,
*,
value_reader,
) -> bool:
@@ -191,7 +191,7 @@ def _rule_matches(
return all(results) if rule.match_mode == 'all' else any(results)
def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, priority: int) -> InventoryRoutingResult:
def _evaluate_matched_rules(top_rules: list[FreightRpaOnhandRoutingRule], *, priority: int) -> InventoryRoutingResult:
"""
将同优先级命中规则折叠为候选集合与建单资格。
@@ -250,13 +250,13 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr
)
def _published_rules(*, scope: str, now: datetime) -> list[ShippingInventoryRoutingRule]:
def _published_rules(*, scope: str, now: datetime) -> list[FreightRpaOnhandRoutingRule]:
"""加载当前时刻有效的已发布规则,按优先级降序。"""
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
query = FreightRpaOnhandRoutingRule.query.filter_by(status='published', scope=scope)
return [
rule for rule in query.order_by(
ShippingInventoryRoutingRule.priority.desc(),
ShippingInventoryRoutingRule.id.asc(),
FreightRpaOnhandRoutingRule.priority.desc(),
FreightRpaOnhandRoutingRule.id.asc(),
).all()
if (rule.effective_from is None or rule.effective_from <= now)
and (rule.effective_to is None or rule.effective_to >= now)
@@ -1,18 +1,29 @@
"""
services/shipping_notice/inventory_rpa_workflow.py
services/shipping_notice/onhand_rpa_workflow.py
用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。
依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/
workflow_protocol 协议记账)、inventory_snapshot、inventory_mapping_workflow、query_service、
workflow_protocol 协议记账)、onhand_snapshot、onhand_mapping_workflow、query_service、
动态订单字段、tool_common、state_machine、tool_response。
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
逻辑:onhand_workflow.ensure_onhand 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/
回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice
import);快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
import); 快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export,
既有同包调用与测试 import(含 monkeypatch 接缝)不换名。
【阶段 B Task 7 修复】单回调(rpa_report_inventory)与批量 worker
(process_rpa_report_inventory_batch)在文件行 commit 后逐文件投递 onhand 报表事实
(dispatch_report_fact(ReportFact(report_kind='onhand', ...))——先 commit 再投递;
处理函数异常原样外抛、不折进 warnings;HTTP 收件入口 rpa_report_inventory_batch 只入队
Job、不 commit 文件故不投递;空结果审计快照不投递——不作可用库存复用)。候选 settle
与门禁同步由 handle_onhand_report 承担(见 onhand_report_handler.py)。修复轮 2/3:批量内
单文件处理函数失败先回滚未提交会话(半途写不得被后续 commit 持久化)并继续投递其余
已提交文件,排程 finalize 与 drop 文件清理入队照常执行,之后以
OnhandReportDispatchAfterCommitError 携带未成功文件清单原样重抛;Job 处理器把清单写回
payload(retry_dispatch_files)并 requeue,重试经「只重投失败文件」通道
(_dispatch_retry_onhand_report_files)补齐,全部成功前绝不返回 ok。
"""
from __future__ import annotations
@@ -26,16 +37,16 @@ from typing import Any
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_snapshot_store import (
from app.services.shipping_notice.onhand_snapshot import ingest_inventory_file
from app.services.shipping_notice.onhand_snapshot_store import (
find_latest_ready_snapshot,
get_or_create_rpa_inventory_snapshot,
link_snapshot_to_task,
link_snapshot_to_task_for_preparation,
)
from app.services.shipping_notice.inventory_upload import (
from app.services.shipping_notice.onhand_upload import (
delete_staged_task_inventory_file,
promote_staged_task_inventory_file,
rebuild_task_inventory_attachment_from_snapshot,
@@ -49,12 +60,12 @@ from app.services.freight_rpa.onhand.callback_cleanup import (
quarantine_callback_drop_file,
recover_pending_rpa_callback_cleanup_jobs,
)
from app.services.shipping_notice.inventory_source_gate import (
from app.services.shipping_notice.onhand_source_gate import (
assert_inventory_source_gate,
inventory_identities_match,
is_inventory_source_stable,
)
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.customer_identity_gate import (
assert_customer_identity_gate,
customer_gate_tool_response,
@@ -186,7 +197,7 @@ def _try_reuse_inventory_snapshot(
if mode == "retry_rpa":
return None
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
snapshot = find_latest_ready_snapshot(
str(rpa_source.get("source_code") or ""),
@@ -208,7 +219,7 @@ def _try_reuse_inventory_snapshot(
task,
"inventory_snapshot_reused",
{
"inventory_file_no": snapshot.inventory_file_no,
"inventory_file_no": snapshot.onhand_file_no,
"source_code": snapshot.source_code,
"warehouse_id": snapshot.warehouse_id,
"snapshot_age_seconds": link.snapshot_age_seconds,
@@ -216,7 +227,7 @@ def _try_reuse_inventory_snapshot(
)
db.session.flush()
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
try:
lines, column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError):
@@ -298,12 +309,12 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
Returns:
tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。
"""
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task):
return None, None, None
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
return None, None, None
# 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window);
@@ -344,14 +355,14 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
return None
log_task_event(
task,
"inventory_rpa_wait_rechecked",
"onhand_rpa_wait_rechecked",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
# [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落
# rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。
log_task_event(
task,
"inventory_rpa_failed",
"onhand_rpa_failed",
{
"error": "timeout",
"elapsed_seconds": elapsed,
@@ -360,7 +371,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
)
log_task_event(
task,
"inventory_rpa_exhausted",
"onhand_rpa_exhausted",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
db.session.flush()
@@ -378,7 +389,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
"""从任务正式库存身份推导快照预期二元组。"""
from app.services.shipping_notice.inventory_source_gate import task_inventory_identity
from app.services.shipping_notice.onhand_source_gate import task_inventory_identity
identity = task_inventory_identity(task)
return (
@@ -409,7 +420,7 @@ def _rollback_orphan_inventory_snapshot(
return
from sqlalchemy import inspect as sa_inspect
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
for raw in paths:
delete_inventory_storage_path(raw)
@@ -446,12 +457,12 @@ def _inventory_file_sha256(path: Path) -> str:
def _validate_reused_snapshot_callback_file(
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
callback_path: Path,
) -> str | None:
"""
校验复用快照时回调落盘文件与托管 storage_path 内容一致。
核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。
核心逻辑:不一致时拒绝复用,避免 onhand_lines_json 与 storage_path 文件分叉。
"""
storage_path = Path(str(inv_file.storage_path or ""))
if not storage_path.is_file():
@@ -463,11 +474,11 @@ def _validate_reused_snapshot_callback_file(
return None
def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path:
def _snapshot_ingest_path(inv_file: FreightRpaOnhandReportFile) -> Path:
"""返回应解析的库存快照托管路径(复用与新建均读 storage_path)。"""
path = Path(str(inv_file.storage_path or ""))
if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}")
raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.onhand_file_no}")
return path
@@ -575,7 +586,7 @@ def _flush_pending_callback_moves(
def _try_rebuild_task_inventory_attachment(
task: ShippingNotice,
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
post_commit_warnings: list[str],
) -> bool:
"""
@@ -655,12 +666,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
# per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。
source_run_no = str(payload.get('source_run_no') or '').strip()
if source_run_no:
from app.models import ShippingTaskInventoryRpaAttempt
from app.models import FreightRpaOnhandTaskAttempt
current_attempt = (
db.session.query(ShippingTaskInventoryRpaAttempt)
db.session.query(FreightRpaOnhandTaskAttempt)
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
.order_by(FreightRpaOnhandTaskAttempt.id.desc())
.first()
)
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running', 'succeeded'}:
@@ -672,12 +683,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
if source_run_no:
from app.models import ShippingTaskInventoryRpaAttempt
from app.models import FreightRpaOnhandTaskAttempt
current_attempt = (
db.session.query(ShippingTaskInventoryRpaAttempt)
db.session.query(FreightRpaOnhandTaskAttempt)
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
.order_by(FreightRpaOnhandTaskAttempt.id.desc())
.first()
)
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}:
@@ -811,9 +822,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
"""
callback_source = str(payload.get("source_code") or "").strip().upper()
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
task_sources = set(task_frozen_inventory_source_codes(task))
task_sources = set(task_frozen_onhand_source_codes(task))
if not callback_source:
return tool_response(
status="failed",
@@ -829,12 +840,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
data=serialize_task_for_tool(task),
)
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
source = get_database_inventory_source(callback_source)
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id
task_wh = resolve_inventory_source_warehouse_id(task, source=source) or ''
if is_fixed and (not callback_wh or callback_wh != task_wh):
@@ -962,7 +973,7 @@ def _resolve_batch_callback_source(
source_code = str(item.get("source_code") or "").strip().upper()
if not source_code:
return None
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
return get_database_inventory_source(source_code)
@@ -976,7 +987,7 @@ def _batch_snapshot_verify_warehouse_id(
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
return None
if task:
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id
warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or ''
return warehouse_id or None
@@ -1021,14 +1032,14 @@ def ensure_inventory_via_rpa(
allow_auto_retry: bool = True,
source_codes: list[str] | None = None,
) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。
"""触发或轮询 RPA 库存导出;成功落盘时委托 onhand_workflow.inventory_loaded_response。
Args:
allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。
poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
poll_onhand_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
manual_retry_round = mode == "retry_rpa"
disposition_reason = task_execution_block_reason(task)
@@ -1075,7 +1086,7 @@ def ensure_inventory_via_rpa(
except AppError:
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
# OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。
task.stage = "inventory_source_resolving"
task.stage = "onhand_source_resolving"
_set_workflow_error(task, "库存源尚未确定,无法启动 RPA")
db.session.commit()
return tool_response(
@@ -1108,7 +1119,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, None)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title='获取库存',
status='running',
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
@@ -1136,7 +1147,7 @@ def ensure_inventory_via_rpa(
poll_read_only = not allow_auto_retry
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title='获取库存',
status='needs_human',
message='库存 RPA 未能为全部库存源生成结果。',
@@ -1165,11 +1176,11 @@ def ensure_inventory_via_rpa(
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
timeout_seconds = rpa_inventory_timeout_seconds()
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task):
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
if last_trigger and isinstance(last_trigger.created_at, datetime):
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
if elapsed < timeout_seconds:
@@ -1190,12 +1201,12 @@ def ensure_inventory_via_rpa(
},
},
)
last_failed = latest_task_event(task, "inventory_rpa_failed")
last_failed = latest_task_event(task, "onhand_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
_set_workflow_error(task, "RPA 库存导出等待超时")
log_task_event(
task,
"inventory_rpa_failed",
"onhand_rpa_failed",
{
"error": "timeout",
"elapsed_seconds": elapsed,
@@ -1249,7 +1260,7 @@ def ensure_inventory_via_rpa(
)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="running",
message=progress_message,
@@ -1261,7 +1272,7 @@ def ensure_inventory_via_rpa(
)
log_task_event(
task,
"inventory_rpa_triggered",
"onhand_rpa_triggered",
{
"trigger": trigger,
"run_no": _extract_run_no_from_trigger(trigger),
@@ -1299,7 +1310,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, human_message[:500])
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message=human_message,
@@ -1308,7 +1319,7 @@ def ensure_inventory_via_rpa(
total=max_attempts,
detail=detail,
)
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
log_task_event(task, "onhand_rpa_retry_requested", {"reason": "trigger_failed"})
db.session.commit()
return tool_response(
status="needs_human",
@@ -1409,7 +1420,7 @@ def _handle_rpa_inventory_skipped(
_set_workflow_error(task, None)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message="货代系统当前无可用库存",
@@ -1418,7 +1429,7 @@ def _handle_rpa_inventory_skipped(
)
log_task_event(
task,
"inventory_rpa_skipped",
"onhand_rpa_skipped",
{
"skip_reason": skip_reason,
"message": detail or message,
@@ -1449,14 +1460,14 @@ def _handle_rpa_inventory_failed(
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
_set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500])
log_task_event(task, "inventory_rpa_failed", {
log_task_event(task, "onhand_rpa_failed", {
"error": _workflow_error(task),
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
"rpa_runtime": runtime,
})
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title='获取库存',
status='needs_human',
message=_workflow_error(task),
@@ -1520,7 +1531,7 @@ def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) ->
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
cleanup_retry_warnings = flush_callback_cleanup_queue()
@@ -1574,7 +1585,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。
log_task_event(
task,
'shipping_inventory_callback_ignored',
'freight_rpa_onhand_callback_ignored',
{
'run_no': run_no_raw,
'source_code': source_code_from_run,
@@ -1714,7 +1725,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
staging_path: Path | None = None
inv_file: ShippingInventoryFile | None = None
inv_file: FreightRpaOnhandReportFile | None = None
created_new = False
orphan_paths: list[str | Path] = []
try:
@@ -1780,7 +1791,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if link is None:
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
structure_check = validate_production_inventory_structure(
source_code=str(rpa_source['source_code']), path=ingest_path,
@@ -1808,7 +1819,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
}
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
@@ -1824,7 +1835,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"upload_filename": ingest_path.name,
"upload_path": str(ingest_path),
"origin_file_path": str(path),
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"reused_existing_snapshot": not created_new,
"structure_validation": column_meta.get('structure_validation'),
},
@@ -1835,7 +1846,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
lines,
column_meta=column_meta,
source="rpa_callback",
event_type="inventory_rpa_ready",
event_type="onhand_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False,
@@ -1885,7 +1896,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
path,
run_no=run_no,
task_no=task.task_no,
inventory_file_no=inv_file.inventory_file_no,
inventory_file_no=inv_file.onhand_file_no,
)
promote_ok = False
try:
@@ -1906,13 +1917,13 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
processed,
run_no=run_no,
task_no=task.task_no,
inventory_file_no=inv_file.inventory_file_no,
inventory_file_no=inv_file.onhand_file_no,
)
if move_warning:
post_commit_warnings.append(f"move_callback_file_failed:{move_warning}")
try:
from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks
from app.services.shipping_notice.onhand_file_store import start_inventory_file_linked_tasks
start_inventory_file_linked_tasks(inv_file)
except Exception as exc:
@@ -1926,10 +1937,25 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if post_commit_warnings:
_persist_post_commit_task_event(
task,
"inventory_rpa_post_commit_warning",
{"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no},
"onhand_rpa_post_commit_warning",
{"warnings": post_commit_warnings, "inventory_file_no": inv_file.onhand_file_no},
)
# [STEP 阶段 B Task 7 修复] 文件行已随上方 db.session.commit() 提交——同请求投递
# onhand 报表事实(先 commit 再投递)。处理函数异常必须原样外抛:绝不折进
# post_commit_warnings、不吞——已提交文件行保留,Worker 重试整笔回调即可补齐
# 候选 settle 与门禁收口(处理函数幂等:重复投递不重复候选行)。
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
dispatch_report_fact(ReportFact(
report_kind='onhand',
source_code=str(inv_file.source_code or ''),
file_id=int(inv_file.id),
sha256=str(inv_file.file_sha256 or '') or None,
ok=True,
))
if response is None:
return tool_response(status="failed", task=task, message="RPA 回调处理未完成")
if post_commit_warnings:
@@ -1963,7 +1989,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
existing_job = (
Job.query.filter(
Job.domain == 'shipping_notice',
Job.job_type == 'shipping_inventory_callback_process',
Job.job_type == 'freight_rpa_onhand_callback_process',
Job.business_ref == f'inventory-callback:{callback_id}',
Job.status.in_(('queued', 'running')),
)
@@ -1996,7 +2022,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
from app.jobs.types import JobType
job_id = enqueue(
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS,
receipt_payload,
domain='shipping_notice',
business_ref=f'inventory-callback:{callback_id}',
@@ -2119,6 +2145,89 @@ def _received_batch_callback_file_path(
return None
class OnhandReportDispatchAfterCommitError(RuntimeError):
"""批量 commit 后 onhand 事实投递失败(Task 7 修复轮 3)。
用途:process_rpa_report_inventory_batch 在排程收口与 drop 文件清理入队完成后,
把首轮投递的首个异常连同「未成功文件清单」一并外抛——Job 处器捕获后把清单写回
payload(retry_dispatch_files)并 fail_job(retryable=True),重试经「只重投失败
文件」通道(_dispatch_retry_onhand_report_files)补齐,不再整批重放(整批重放
会被 callback_id 已消费的 replay 检查跳过、且已收口的排程 run 校验会拦下)。
继承 RuntimeError:与既有 RuntimeError 契约(测试 match / 调用方捕获)兼容。
"""
def __init__(self, message: str, *, failed_files: list[dict[str, Any]]) -> None:
super().__init__(message)
self.failed_files = list(failed_files)
def _dispatch_retry_onhand_report_files(retry_files: list[Any]) -> dict[str, Any]:
"""Job 重试通道:只对首轮投递失败的已提交文件重投 onhand 事实(不重放整批)。
【AI 触发时机】:仅由 process_rpa_report_inventory_batch 在 payload 携带
retry_dispatch_files(Job 处理器自 OnhandReportDispatchAfterCommitError 清单写回)
时调用;普通 Worker 回调载荷不含该键,永不进入本通道。
核心逻辑:逐文件 dispatch_report_fact;单文件处理函数失败先回滚未提交会话
(半途写不得被后续 commit 持久化、PendingRollback 不得拖垮后续投递)并收集
首个异常与未成功清单;任一失败即携带清单重抛(重试绝不在处理函数未完成时
返回 ok);全部成功才返回 ok(result_status='retried'——Job 处理器据此
finish_job,且仅在此即全部处理函数已完成的情形下才标记成功)。
Args:
retry_files: 首轮未成功文件清单({source_code, file_id, sha256} 字典列表)。
Returns:
tool_response:status='ok'、data.result_status='retried'(非 failed/
partial_failed,Job 处理器走 finish_job 成功收口)。
Raises:
OnhandReportDispatchAfterCommitError: 仍有文件投递失败(携带未成功清单,
供 Job 处理器更新 payload 继续重试,直至 attempts 耗尽落终态 failed)。
"""
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
dispatch_error: Exception | None = None
remaining: list[dict[str, Any]] = []
for item in retry_files:
if not isinstance(item, dict):
continue
try:
file_id = int(item.get('file_id'))
except (TypeError, ValueError):
continue
marker = {
'source_code': str(item.get('source_code') or ''),
'file_id': file_id,
'sha256': item.get('sha256'),
}
try:
dispatch_report_fact(ReportFact(
report_kind='onhand',
source_code=marker['source_code'],
file_id=marker['file_id'],
sha256=marker['sha256'] if isinstance(marker['sha256'], str) else None,
ok=True,
))
except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余文件必须继续投递,未成功清单随专用异常重抛
db.session.rollback()
if dispatch_error is None:
dispatch_error = exc
remaining.append(marker)
logging.getLogger(__name__).warning(
'RPA onhand report fact retry dispatch failed: file_id=%s error=%s',
marker['file_id'], exc, exc_info=exc,
)
if dispatch_error is not None:
raise OnhandReportDispatchAfterCommitError(
f'RPA onhand report fact retry dispatch failed: {dispatch_error}',
failed_files=remaining,
)
return tool_response(
status='ok',
message=f'库存 RPA 回调重试完成:已补齐投递 {len(retry_files)} 个失败文件。',
data={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)},
extra={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)},
)
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"""
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
@@ -2128,10 +2237,19 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
含 schedule_run_id 时委托 finalize 终态化排程 run。
响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
cleanup_retry_warnings = flush_callback_cleanup_queue()
# [STEP 阶段 B Task 7 修复轮 3] Job 重试「只重投失败文件」通道:首轮投递失败后,
# Job 处理器把未成功文件清单写回 payload(retry_dispatch_files);重试不再整批
# 重放(task-linked 项的 Attempt 已消费 callback_id 会被 replay 检查跳过、已收口
# 的排程 run 校验也会拦下整批),只对清单内已提交文件重投事实(处理函数幂等)。
# 普通回调载荷不含该键,永不进入本通道。
retry_files = payload.get('retry_dispatch_files') if isinstance(payload, dict) else None
if retry_files:
return _dispatch_retry_onhand_report_files(retry_files)
if payload.get('schema_version') != SCHEMA:
return tool_response(status='failed', message='callback_schema_invalid', data={
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
@@ -2166,6 +2284,9 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
skipped: list[dict[str, Any]] = []
batch_new_storage_paths: list[str] = []
pending_callback_moves: list[dict[str, Any]] = []
# [STEP 阶段 B Task 7 修复] 整批事务内落地的 onhand 报表文件清单——随 created
# 同步追加/回退(单项保存点回滚时该文件行一并消失),整批 commit 后逐文件投递事实。
landed_onhand_files: list[dict[str, Any]] = []
try:
for item in results:
@@ -2187,8 +2308,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
if not item_callback_id and source_run_no_item:
item_callback_id = f"{callback_id}:{source_run_no_item}:C1"
if item_callback_id:
from app.models import ShippingTaskInventoryRpaAttempt
replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none()
from app.models import FreightRpaOnhandTaskAttempt
replay_attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(callback_id=item_callback_id).one_or_none()
if replay_attempt is not None:
skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True})
continue
@@ -2382,7 +2503,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
# 调度空结果保留为审计快照,但绝不链接给任务或作为 ready 库存复用。
source = _resolve_batch_callback_source(None, merged_item)
if source and not task_no:
from app.services.shipping_notice.inventory_snapshot_store import create_empty_rpa_inventory_snapshot
from app.services.shipping_notice.onhand_snapshot_store import create_empty_rpa_inventory_snapshot
snapshot = create_empty_rpa_inventory_snapshot(
source=source, rpa_run_no=run_no or None, schedule_run_id=schedule_run_id,
@@ -2391,7 +2512,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
)
skipped.append({
'source_code': source_code, 'warehouse_id': warehouse_id,
'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.inventory_file_no,
'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.onhand_file_no,
})
continue
@@ -2427,8 +2548,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
"error": "file_missing",
})
if task_no and source_run_no_item:
from app.models import ShippingTaskInventoryRpaAttempt
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
from app.models import FreightRpaOnhandTaskAttempt
_att = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
if _att:
_att.callback_id = item_callback_id or callback_id
_att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False
@@ -2476,7 +2597,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
item_savepoint = db.session.begin_nested()
item_orphan_path: str | None = None
created_new = False
inv_file: ShippingInventoryFile | None = None
inv_file: FreightRpaOnhandReportFile | None = None
created_entry: dict[str, Any] | None = None
try:
try:
@@ -2505,7 +2626,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
):
item_orphan_path = str(inv_file.storage_path)
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
ingest_path = _snapshot_ingest_path(inv_file)
structure_check = validate_production_inventory_structure(
@@ -2516,7 +2637,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
inv_file.mapping_source = 'parsing_profile'
inv_file.mapping_confirmed = True
created_entry = {
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"source_code": inv_file.source_code or source_code,
"warehouse_id": inv_file.warehouse_id or warehouse_id,
"reused_existing_snapshot": not created_new,
@@ -2529,6 +2650,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
},
}
created.append(created_entry)
# [STEP 阶段 B Task 7 修复] 记录落地文件(含复用行——同样随整批事务提交),
# 供整批 commit 后投递 onhand 报表事实;except 分支随 created 一并回退。
landed_onhand_files.append({
'source_code': str(inv_file.source_code or source_code or ''),
'file_id': int(inv_file.id),
'sha256': str(inv_file.file_sha256 or '') or None,
})
if item_orphan_path:
batch_new_storage_paths.append(item_orphan_path)
@@ -2562,7 +2690,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
lines,
column_meta=column_meta,
source="rpa_batch_callback",
event_type="inventory_rpa_ready",
event_type="onhand_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False,
@@ -2583,7 +2711,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
run_no=source_run_no_item,
callback_payload={
**dict(merged_item),
'inventory_file_no': inv_file.inventory_file_no,
'inventory_file_no': inv_file.onhand_file_no,
},
)
if final_code != 'succeeded':
@@ -2605,20 +2733,24 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
"run_no": run_no or None,
"task_no": task_no or None,
"schedule_run_id": schedule_run_id,
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
})
item_savepoint.commit()
except _RpaCallbackItemAbort as abort:
item_savepoint.rollback()
if item_orphan_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
delete_inventory_storage_path(item_orphan_path)
if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
batch_new_storage_paths.pop()
if created_entry and created and created[-1] is created_entry:
created.pop()
# [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录
# (保存点回滚后该文件行已消失,不得再投递其事实)。
if landed_onhand_files:
landed_onhand_files.pop()
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
@@ -2629,13 +2761,17 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
except Exception as exc:
item_savepoint.rollback()
if item_orphan_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
delete_inventory_storage_path(item_orphan_path)
if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
batch_new_storage_paths.pop()
if created_entry and created and created[-1] is created_entry:
created.pop()
# [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录
# (保存点回滚后该文件行已消失,不得再投递其事实)。
if landed_onhand_files:
landed_onhand_files.pop()
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
@@ -2661,7 +2797,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
db.session.commit()
except Exception as exc:
db.session.rollback()
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
for storage_path in batch_new_storage_paths:
delete_inventory_storage_path(storage_path)
@@ -2674,9 +2810,47 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
},
)
# [STEP 阶段 B Task 7 修复轮 2/3] 整批文件行已随上方 db.session.commit() 提交——同一
# worker 调用内逐文件投递 onhand 报表事实(先 commit 再投递)。必须放在外层
# except 之后:处理函数异常若落入该 except 会误删已提交文件的存储对象。
# 单文件处理函数失败只收集首个异常并继续投递其余已提交文件(不得因一文件失败
# 跳过其余文件的候选/门禁收口);【修复轮 3】失败点先回滚未提交会话——丢弃该次
# 处理函数半途 flush 的候选/门禁写(否则会被下一个处理函数的 commit / finalize
# 的 commit 误持久化,且数据库错误后的 PendingRollback 会拖垮后续投递与收口),
# 已 commit 的文件行不受影响(rollback 只丢弃未提交变更)。首个异常与未成功
# 文件清单在排程收口、drop 文件清理入队之后携带在专用异常上原样重抛(见下)——
# 调用方见到失败、文件行保留,Job 按 retryable=True 契约经「只重投失败文件」
# 通道补齐(处理函数幂等:重复投递不重复候选行)。空结果审计快照
# (create_empty_rpa_inventory_snapshot,no_inventory_data 分支)不投递——其明令
# 不作为可用库存复用,投递 ok=True 事实会错误 settle 等待中的候选准备。
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
dispatch_error: Exception | None = None
failed_dispatch_files: list[dict[str, Any]] = []
for landed in landed_onhand_files:
try:
dispatch_report_fact(ReportFact(
report_kind='onhand',
source_code=str(landed['source_code'] or ''),
file_id=int(landed['file_id']),
sha256=landed['sha256'],
ok=True,
))
except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余已提交文件必须继续投递,首个异常携带未成功清单在收口/清理之后重抛
# [修复轮 3] 回滚未提交会话:半途写不得被后续 commit 持久化;PendingRollback 解除。
db.session.rollback()
if dispatch_error is None:
dispatch_error = exc
failed_dispatch_files.append(dict(landed))
logging.getLogger(__name__).warning(
'RPA onhand report fact dispatch failed after batch commit: file_id=%s error=%s',
landed['file_id'], exc, exc_info=exc,
)
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
if schedule_run_id is not None:
from app.services.schedule.freight_onhand_rpa_finalize import finalize_shipping_inventory_schedule_run
from app.services.schedule.freight_rpa_onhand_finalize import finalize_shipping_inventory_schedule_run
finalize_result = finalize_shipping_inventory_schedule_run(
schedule_run_id,
@@ -2695,6 +2869,18 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
),
)
# [STEP 阶段 B Task 7 修复轮 3] drop 文件清理已先行入队/移动(不得因重抛被跳过
# ——清理只在 _flush_pending_callback_moves 内写消费标记/入队,先于此处执行):
# 首个投递异常携带未成功文件清单在专用异常上原样重抛——调用方(Job/Worker)
# 见到失败、已提交文件行保留;Job 处理器把清单写回 payload(retry_dispatch_files)
# 后 fail_job(retryable=True),重试经「只重投失败文件」通道补齐(见函数头部),
# 全部投递成功前绝不返回 ok(重试不得在处理函数未完成时被记成功)。
if dispatch_error is not None:
raise OnhandReportDispatchAfterCommitError(
f'RPA onhand report fact dispatch failed after batch commit: {dispatch_error}',
failed_files=failed_dispatch_files,
)
response_data = {
"run_no": run_no,
"created": created,
@@ -2743,7 +2929,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
def _validate_repair_inventory_snapshot(
task: ShippingNotice,
inv_file: ShippingInventoryFile | None,
inv_file: FreightRpaOnhandReportFile | None,
*,
requested_file_no: str | None = None,
) -> str | None:
@@ -2751,10 +2937,10 @@ def _validate_repair_inventory_snapshot(
校验修复接口允许使用的库存快照。
核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。
"""
from app.models import ShippingTaskInventoryLink
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh
from app.services.shipping_notice.inventory_source_gate import (
from app.models import ShippingTaskOnhandLink
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
from app.services.shipping_notice.onhand_snapshot_store import is_snapshot_fresh
from app.services.shipping_notice.onhand_source_gate import (
inventory_identities_match,
is_inventory_source_stable,
)
@@ -2766,12 +2952,12 @@ def _validate_repair_inventory_snapshot(
return "no_active_snapshot"
if inv_file.id != active.id:
return "snapshot_not_active_for_task"
if requested_file_no and active.inventory_file_no != requested_file_no:
if requested_file_no and active.onhand_file_no != requested_file_no:
return "snapshot_not_active_for_task"
if task.id is not None:
link = ShippingTaskInventoryLink.query.filter_by(
link = ShippingTaskOnhandLink.query.filter_by(
task_id=task.id,
inventory_file_id=inv_file.id,
onhand_file_id=inv_file.id,
is_active=True,
).first()
if link is None:
@@ -2782,7 +2968,7 @@ def _validate_repair_inventory_snapshot(
return "snapshot_expired"
if not is_inventory_source_stable(task):
return "inventory_source_unstable"
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
source = get_database_inventory_source(inv_file.source_code)
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
@@ -2806,7 +2992,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
tool_response:含 attachment_path 与 inventory_file_no。
"""
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
task = resolve_task_from_payload(payload)
if not task:
@@ -2821,7 +3007,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
message="任务无可用库存快照,无法重建附件",
data=serialize_task_for_tool(task),
)
if inv_file_no and inv_file.inventory_file_no != inv_file_no:
if inv_file_no and inv_file.onhand_file_no != inv_file_no:
return tool_response(
status="failed",
task=task,
@@ -2856,7 +3042,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
task,
"inventory_attachment_repaired",
{
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"attachment_path": str(attachment_path),
"source": str(payload.get("source") or "manual_repair"),
},
@@ -2878,7 +3064,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
message="任务库存附件已从快照重建",
data={
**serialize_task_for_tool(task),
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"attachment_path": str(attachment_path),
},
)
@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_snapshot.py
services/shipping_notice/onhand_snapshot.py
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
逻辑:由 onhand_workflow、onhand_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
"""
from __future__ import annotations
@@ -187,12 +187,12 @@ def _normalize_inventory_row(
# Published profiles use inventory field IDs as row keys. Field purpose and
# value type come from the user-maintained catalog, never from a fixed code.
if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns):
from app.models import ShippingInventoryField
from app.models import FreightRpaOnhandField
field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()}
catalog = {
str(item.id): item
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()
}
parsed = {
field_id: _cell(row, index)
@@ -334,7 +334,7 @@ def _load_excel_rows(
"""Load configured worksheet or CSV rows; returns rows and total row count hint."""
suffix = path.suffix.lower()
if suffix == ".csv":
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
from app.services.shipping_notice.onhand_file_identity import load_inventory_csv_rows
rows = load_inventory_csv_rows(path, max_rows=max_rows)
try:
@@ -422,7 +422,7 @@ def describe_inventory_columns(
) -> dict[str, Any]:
"""根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。"""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
from app.services.shipping_notice.onhand_mapping import build_column_meta_from_mapping
return build_column_meta_from_mapping(
headers,
@@ -587,7 +587,7 @@ def parse_inventory_rows(
) -> list[dict[str, Any]]:
"""按表头与数据行解析库存表格(Excel 或文档提取文本共用)。"""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
columns = resolve_columns_from_field_mapping(headers, field_mapping)
else:
@@ -627,7 +627,7 @@ def parse_inventory_text(
header = rows[0]
if field_mapping:
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
has_header = True
column_meta = describe_inventory_columns(
@@ -659,7 +659,7 @@ def read_inventory_schema_preview(
max_sample_rows: int = 5,
) -> dict[str, Any]:
"""仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。"""
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
scan_rows, total_rows = _load_excel_rows(path, max_rows=40)
if not scan_rows:
@@ -724,7 +724,7 @@ def parse_inventory_excel_with_meta(
headers = [str(c or "").strip() for c in rows[header_idx]]
data_rows = [list(r) for r in rows[header_idx + 1 :] if r]
if not field_mapping:
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
suggested = suggest_field_mapping(headers)
if suggested.get("part_number") and suggested.get("available_qty"):
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_snapshot_reuse_policy.py
services/shipping_notice/onhand_snapshot_reuse_policy.py
用途:统一判断库存快照是否可被当前任务复用。
依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。
依赖:FreightRpaOnhandReportFile、ShippingNotice、候选冻结事实。
逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。
"""
@@ -1,9 +1,12 @@
"""
services/shipping_notice/inventory_snapshot_store.py
services/shipping_notice/onhand_snapshot_store.py
用途:库存快照查询、TTL 复用、RPA 入库与任务关联审计。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_file_store、Flask config。
逻辑:ensure_inventory 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录。
依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读取回行,禁止构造)、
freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_file_store、Flask config。
逻辑:ensure_onhand 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录;
阶段 B Task 5 起新建/空快照行一律经 report_store.insert_onhand_report 插入,
本模块只在拿回 file_id 后按主键取回 ORM 对象并维护任务 link(关联表留在发货域)。
"""
from __future__ import annotations
@@ -19,36 +22,37 @@ from sqlalchemy.orm import Session
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingTaskEvent, ShippingTaskOnhandLink
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.inventory_file_store import (
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
from app.services.shipping_notice.onhand_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
inventory_file_upload_path,
inventory_storage_suffix_for_path,
replace_task_inventory_link,
)
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
from app.services.shipping_notice.onhand_snapshot import read_inventory_schema_preview
_SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_EMPTY = "empty"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。
# 请求内只读缓存(key: (source_code, warehouse_id) → FreightRpaOnhandReportFile | None)。
# 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一
# (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。
# 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。
_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache"
_READ_CACHE_KEY = "shipping_onhand_snapshot_read_cache"
@_sa_event.listens_for(Session, "after_flush")
def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001
"""快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。"""
touched = (
any(isinstance(obj, ShippingInventoryFile) for obj in session.new)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted)
any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.new)
or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.dirty)
or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.deleted)
)
if touched:
session.info.pop(_READ_CACHE_KEY, None)
@@ -80,10 +84,10 @@ def snapshot_expires_at(exported_at: datetime | None = None) -> datetime:
return base + timedelta(hours=inventory_snapshot_ttl_hours())
def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = None) -> bool:
def is_snapshot_fresh(inv_file: FreightRpaOnhandReportFile, *, now: datetime | None = None) -> bool:
"""
判断库存快照是否仍处于 ready 且未过期。
【AI 触发时机】:ensure_inventory 决定是否复用已有快照前调用。
【AI 触发时机】:ensure_onhand 决定是否复用已有快照前调用。
"""
if not inv_file or str(inv_file.snapshot_status or "").strip().lower() != _SNAPSHOT_STATUS_READY:
return False
@@ -99,7 +103,7 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
def find_latest_ready_snapshot(
source_code: str | None,
warehouse_id: str | None = None,
) -> ShippingInventoryFile | None:
) -> FreightRpaOnhandReportFile | None:
"""
查找指定 Source 的最新 ready 且未过期库存快照。
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
@@ -119,14 +123,14 @@ def find_latest_ready_snapshot(
if cache_key in read_cache:
return read_cache[cache_key]
query = ShippingInventoryFile.query.filter_by(
query = FreightRpaOnhandReportFile.query.filter_by(
source_code=code,
snapshot_status=_SNAPSHOT_STATUS_READY,
)
if warehouse:
query = query.filter_by(warehouse_id=warehouse)
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc()).limit(5).all()
result = None
for row in rows:
if is_snapshot_fresh(row):
@@ -141,7 +145,7 @@ def find_ready_rpa_inventory_snapshot(
rpa_run_no: str,
source_code: str,
warehouse_id: str,
) -> ShippingInventoryFile | None:
) -> FreightRpaOnhandReportFile | None:
"""
按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。
核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
@@ -152,13 +156,13 @@ def find_ready_rpa_inventory_snapshot(
if not run_no or not code or not warehouse:
return None
return (
ShippingInventoryFile.query.filter_by(
FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no=run_no,
source_code=code,
warehouse_id=warehouse,
snapshot_status=_SNAPSHOT_STATUS_READY,
)
.order_by(ShippingInventoryFile.id.desc())
.order_by(FreightRpaOnhandReportFile.id.desc())
.first()
)
@@ -177,13 +181,13 @@ def get_or_create_rpa_inventory_snapshot(
batch_id: int | None = None,
share_mode: str | None = None,
verify_warehouse_id: str | None = None,
) -> tuple[ShippingInventoryFile, bool]:
) -> tuple[FreightRpaOnhandReportFile, bool]:
"""
幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。
核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。
Returns:
tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。
tuple[FreightRpaOnhandReportFile, bool]: (快照, 是否新建)。
"""
from sqlalchemy.exc import IntegrityError
@@ -224,7 +228,7 @@ def get_or_create_rpa_inventory_snapshot(
except IntegrityError:
savepoint.rollback()
if orphan_storage_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
delete_inventory_storage_path(orphan_storage_path)
if run_no and code and warehouse:
@@ -239,7 +243,7 @@ def get_or_create_rpa_inventory_snapshot(
except Exception:
savepoint.rollback()
if orphan_storage_path:
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
delete_inventory_storage_path(orphan_storage_path)
raise
@@ -250,18 +254,18 @@ def list_available_snapshots(
source_code: str | None = None,
warehouse_id: str | None = None,
limit: int = 20,
) -> list[ShippingInventoryFile]:
) -> list[FreightRpaOnhandReportFile]:
"""列出未过期 ready 快照,供工作台查询。"""
query = ShippingInventoryFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY)
query = FreightRpaOnhandReportFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY)
if source_code:
query = query.filter_by(source_code=str(source_code).strip().upper())
if warehouse_id:
query = query.filter_by(warehouse_id=str(warehouse_id).strip().upper())
rows = query.order_by(ShippingInventoryFile.exported_at.desc()).limit(max(limit, 1)).all()
rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc()).limit(max(limit, 1)).all()
return [row for row in rows if is_snapshot_fresh(row)]
def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None:
def expire_snapshot(inv_file: FreightRpaOnhandReportFile, reason: str) -> None:
"""将快照标记为 expired。"""
inv_file.snapshot_status = _SNAPSHOT_STATUS_EXPIRED
inv_file.updated_at = datetime.utcnow()
@@ -274,7 +278,7 @@ def _normalize_header_key(value: Any) -> str:
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
"""从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。"""
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel
values = extract_warehouse_ids_from_inventory_excel(path)
if not values:
@@ -298,7 +302,7 @@ def create_inventory_snapshot_from_rpa(
batch_id: int | None = None,
share_mode: str | None = None,
verify_warehouse_id: str | None = None,
) -> ShippingInventoryFile:
) -> FreightRpaOnhandReportFile:
"""
从 RPA 导出文件创建库存快照记录。
【AI 触发时机】:RPA 单条或 batch 回调成功/失败时调用;定时任务只入库不绑定发货任务。
@@ -310,7 +314,7 @@ def create_inventory_snapshot_from_rpa(
success: False 时写入 failed 快照,不复制文件到标准目录。
Returns:
ShippingInventoryFile: 已持久化的快照对象。
FreightRpaOnhandReportFile: 已持久化的快照对象。
"""
exported_at = datetime.utcnow()
inventory_file_no = generate_inventory_file_no()
@@ -328,7 +332,7 @@ def create_inventory_snapshot_from_rpa(
local = Path(local_path)
# 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。
try:
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel
excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local)
if len(excel_warehouse_ids) == 1:
@@ -354,10 +358,13 @@ def create_inventory_snapshot_from_rpa(
snapshot_status = _SNAPSHOT_STATUS_FAILED
storage_path = str(path) if path and path.is_file() else ""
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
# [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
# 本模块只在拿到 file_id 后取回 ORM 对象;先 flush 再落盘的语义由 report_store 保持,
# 唯一约束冲突时同样不会留下已复制的孤儿文件。
file_id = insert_onhand_report(
onhand_file_no=inventory_file_no,
user_id=user_id,
source_file_name=str(source_file_name or (path.name if path else "")).strip() or None,
storage_path=storage_path or f"failed://{inventory_file_no}",
@@ -399,9 +406,8 @@ def create_inventory_snapshot_from_rpa(
"trigger_type": trigger_type,
},
)
db.session.add(inv_file)
db.session.flush()
# [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。
inv_file = db.session.get(FreightRpaOnhandReportFile, file_id)
# [STEP] flush 已在 report_store 内完成,此处先落盘再返回:唯一约束冲突(上面 insert 抛出)时不会留下已复制的孤儿文件。
if success and storage_path and not str(storage_path).startswith("failed://"):
path = Path(storage_path)
path.parent.mkdir(parents=True, exist_ok=True)
@@ -420,25 +426,26 @@ def create_inventory_snapshot_from_rpa(
def create_empty_rpa_inventory_snapshot(
*, source: dict[str, Any], rpa_run_no: str | None, schedule_run_id: int | None,
trigger_type: str, message: str | None = None,
) -> ShippingInventoryFile:
) -> FreightRpaOnhandReportFile:
"""记录 RPA 已成功执行但没有库存行的空快照;空快照永不参与库存匹配。"""
exported_at = datetime.utcnow()
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version
source_code = str(source.get('source_code') or '').strip().upper()
warehouse_id = str(source.get('warehouse_id') or '').strip().upper() or None
run_no = str(rpa_run_no or '').strip() or None
if run_no and source_code:
existing = ShippingInventoryFile.query.filter_by(
existing = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no=run_no, source_code=source_code, warehouse_id=warehouse_id,
snapshot_status=_SNAPSHOT_STATUS_EMPTY,
).order_by(ShippingInventoryFile.id.desc()).first()
).order_by(FreightRpaOnhandReportFile.id.desc()).first()
if existing is not None:
return existing
inv_file = ShippingInventoryFile(
inventory_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}',
# [STEP] 阶段 B Task 5:空快照行同样经 report_store 插入(列集与原构造逐项一致;只 flush 不 commit)。
file_id = insert_onhand_report(
onhand_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}',
schema_preview_json={'export_result': 'empty', 'message': str(message or '库存查询成功但当前无库存数据')[:500]},
share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id,
share_mode='warehouse_pool', line_count=0, onhand_lines_json=[], warehouse_id=warehouse_id,
warehouse_code=warehouse_id, source_code=source_code or None,
source_type=str(source.get('connector_type') or '').strip() or None,
# 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。
@@ -447,41 +454,39 @@ def create_empty_rpa_inventory_snapshot(
rpa_run_no=run_no, schedule_run_id=schedule_run_id,
source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'},
)
db.session.add(inv_file)
db.session.flush()
return inv_file
return db.session.get(FreightRpaOnhandReportFile, file_id)
def link_snapshot_to_task(
task: ShippingNotice,
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
*,
reason: str,
role: str = "member",
audit_payload: dict[str, Any] | None = None,
) -> ShippingTaskInventoryLink | None:
) -> ShippingTaskOnhandLink | None:
"""
将 ready 库存快照关联到发货任务并写入审计字段。
【AI 触发时机】:ensure_inventory 复用快照或 RPA 回调带 task_no 时调用。
【AI 触发时机】:ensure_onhand 复用快照或 RPA 回调带 task_no 时调用。
Returns:
ShippingTaskInventoryLink | None: 终态任务不允许 relink 时返回 None。
ShippingTaskOnhandLink | None: 终态任务不允许 relink 时返回 None。
"""
if not _can_relink_inventory(task):
return None
if not is_snapshot_fresh(inv_file):
return None
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
source = get_database_inventory_source(inv_file.source_code)
if source is None:
return None
resolved_warehouse_id = inv_file.warehouse_id
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
from app.services.shipping_notice.onhand_warehouse_resolution import resolve_dynamic_warehouse
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
try:
lines, _column_meta = read_inventory_file_lines(inv_file)
@@ -508,7 +513,7 @@ def link_snapshot_to_task(
if inv_file.exported_at:
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
from app.services.shipping_notice.inventory_source_gate import inventory_identities_match
from app.services.shipping_notice.onhand_source_gate import inventory_identities_match
identity_ok = inventory_identities_match(
task,
@@ -532,7 +537,7 @@ def link_snapshot_to_task(
"warehouse_id": resolved_warehouse_id,
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
}
db.session.add(
@@ -540,7 +545,7 @@ def link_snapshot_to_task(
task_id=task_event_task_id(task),
event_type="inventory_snapshot_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"link_reason": reason,
"snapshot_age_seconds": age_seconds,
"warehouse_id": resolved_warehouse_id,
@@ -553,11 +558,11 @@ def link_snapshot_to_task(
def link_snapshot_to_task_for_preparation(
task: ShippingNotice,
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
*,
reason: str,
audit_payload: dict[str, Any] | None = None,
) -> ShippingTaskInventoryLink | None:
) -> ShippingTaskOnhandLink | None:
"""将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。
动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论,
@@ -573,7 +578,7 @@ def link_snapshot_to_task_for_preparation(
if link is not None:
return link
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
source = get_database_inventory_source(inv_file.source_code)
if (
@@ -584,7 +589,7 @@ def link_snapshot_to_task_for_preparation(
):
return None
from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link
from app.services.shipping_notice.onhand_file_store import replace_task_inventory_link
link = replace_task_inventory_link(task, inv_file)
link.link_reason = f'{reason}_pending_matching'
@@ -593,7 +598,7 @@ def link_snapshot_to_task_for_preparation(
link.audit_payload_json = {
**(audit_payload or {}),
'source_code': inv_file.source_code,
'inventory_file_no': inv_file.inventory_file_no,
'inventory_file_no': inv_file.onhand_file_no,
'identity_status': inv_file.identity_status,
}
return link
@@ -604,8 +609,8 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] |
if task.id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
.order_by(ShippingTaskInventoryLink.id.desc())
ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True)
.order_by(ShippingTaskOnhandLink.id.desc())
.first()
)
if not link or not link.inventory_file:
@@ -613,7 +618,7 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] |
inv_file = link.inventory_file
trigger_type = (inv_file.source_query_json or {}).get("trigger_type") if isinstance(inv_file.source_query_json, dict) else None
return {
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"source_code": inv_file.source_code,
"warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id,
"warehouse_code": inv_file.warehouse_code,
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_source_gate.py
services/shipping_notice/onhand_source_gate.py
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
依赖:onhand_source_rules、onhand_source_repository、models.ShippingOrderTask、core.errors。
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet;
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
@@ -14,30 +14,31 @@ from typing import Any
from app.core.errors import AppError
from app.models import ShippingOrderTask
from app.services.shipping_notice.inventory_source_rules import (
from app.services.shipping_notice.onhand_source_rules import (
InventorySourceAdjudication,
adjudicate_inventory_source,
compute_routing_fingerprint,
extract_routing_context,
resolve_ambiguous_source_from_ready_snapshots,
)
from app.services.shipping_notice.inventory_candidate_freeze_service import (
from app.services.shipping_notice.onhand_candidate_freeze_service import (
freeze_candidates_for_task,
)
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
# 发货通知业务错误码,族名为 SHIPPING.ONHAND_*。货代 RPA 模块错误使用 FREIGHT_RPA_*。
INVENTORY_SOURCE_ERROR_CODES = {
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
"unresolved": "SHIPPING.ONHAND_SOURCE_UNRESOLVED",
"ambiguous": "SHIPPING.ONHAND_SOURCE_AMBIGUOUS",
"invalid": "SHIPPING.ONHAND_SOURCE_INVALID",
"conflicted": "SHIPPING.ONHAND_SOURCE_CONFLICTED",
"changed": "SHIPPING.ONHAND_SOURCE_CHANGED",
"identity_mismatch": "SHIPPING.ONHAND_IDENTITY_MISMATCH",
"gate_blocked": "SHIPPING.ONHAND_SOURCE_GATE_BLOCKED",
}
@@ -49,10 +50,10 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
codes = task_frozen_inventory_source_codes(task)
codes = task_frozen_onhand_source_codes(task)
lines = get_active_candidate_lines(task)
if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines):
return False
@@ -67,7 +68,7 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool:
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
current = get_active_candidate_set(task)
previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip()
@@ -206,7 +207,7 @@ def transition_task_to_inventory_source_review(
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
# OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流,
# 不能在通知准备前写入 OT。
task.stage = "inventory_source_resolving"
task.stage = "onhand_source_resolving"
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
payload = dict(getattr(task, 'step_payload_json', None) or {})
payload["inventory_source_resolution"] = {
@@ -227,7 +228,7 @@ def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySo
"""
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
【AI 触发时机】:confirm_parse / auto_progress / ensure_onhand 等入口发现门禁未通过时调用。
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。
"""
adjudication = adjudicate_and_apply_inventory_source(task)
@@ -281,11 +282,11 @@ def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
task = resolve_inventory_fact_task(task)
source_codes = task_frozen_inventory_source_codes(task)
source_codes = task_frozen_onhand_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
return {
@@ -309,20 +310,20 @@ def resolve_inventory_source_warehouse_id(
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task
task = resolve_inventory_fact_task(task)
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
return None
from app.models import ShippingTaskInventoryLink
from app.models import ShippingTaskOnhandLink
link = ShippingTaskInventoryLink.query.filter_by(
link = ShippingTaskOnhandLink.query.filter_by(
task_id=int(task_id),
matched_source_code=source_code,
is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
).order_by(ShippingTaskOnhandLink.id.desc()).first()
if link is None:
return None
return (
@@ -354,9 +355,9 @@ def inventory_identities_match(
if expected_code != task_code:
return False
else:
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
frozen = set(task_frozen_inventory_source_codes(task))
frozen = set(task_frozen_onhand_source_codes(task))
if expected_code not in frozen:
return False
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_source_identity.py
services/shipping_notice/onhand_source_identity.py
用途:校验库存源与 Warehouse 的两段式身份。
依赖:无业务模块反向依赖。
@@ -1,18 +1,21 @@
"""
services/shipping_notice/inventory_source_repository.py
services/shipping_notice/onhand_source_repository.py
用途:提供库存源主数据的最小一致性校验和受控读取入口。
依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。
依赖:models.FreightRpaSource/FreightRpaProfile/FreightRpaOnhandReportConfig、core.errors.ValidationError。
逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。
s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 配置行,
本模块非敏感快照与运行时版本指纹均改读配置行;配置行缺失即「站点未就绪」,
沿用返回 None 的既有跳过/失败语义,不新造错误码。
"""
from __future__ import annotations
from app.core.errors import ValidationError
from app.models import ShippingInventorySource, ShippingRpaProfile
from app.models import FreightRpaSource, FreightRpaProfile
def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None:
def validate_source_profile(source: FreightRpaSource, profile: FreightRpaProfile) -> None:
"""
校验库存源引用的 RPA Profile 与其 Driver 类型一致。
@@ -26,11 +29,11 @@ def validate_source_profile(source: ShippingInventorySource, profile: ShippingRp
source_type = str(source.connector_type or '').strip().lower()
profile_type = str(profile.connector_type or '').strip().lower()
if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}:
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID')
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.ONHAND_CONNECTOR_INVALID')
if source_type != profile_type:
raise ValidationError(
'Inventory Source connector_type must match its RPA Profile',
code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH',
code='SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH',
)
@@ -48,7 +51,7 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
code = str(source_code or '').strip().upper()
if not code:
return None
source = ShippingInventorySource.query.filter_by(source_code=code).first()
source = FreightRpaSource.query.filter_by(source_code=code).first()
if source is None or (enabled_only and not source.enabled):
return None
profile = source.rpa_profile
@@ -57,9 +60,14 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
login_config = dict(profile.login_config_json or {'auth_mode': 'password'})
if login_config.get('auth_mode') != 'password':
return None
# s18 起报表路径/查询条件/解析方案绑定归 onhand_report_config 配置行;
# 配置行缺失即「站点未就绪」,沿用返回 None 的既有跳过/失败语义,不新造错误码。
config = source.onhand_report_config
if config is None:
return None
# Source owns report navigation and business query values. Driver behavior is
# code/template-owned and never travels through a login connection profile.
source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {}
source_navigation = dict(config.report_path_json or {}) if source.connector_type == 'dbs' else {}
return {
'source_code': source.source_code,
'display_name': source.display_name,
@@ -70,17 +78,17 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
'warehouse_id': source.fixed_warehouse_id,
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
'config_version': source.config_version,
'parsing_profile_id': source.parsing_profile_id,
'parsing_profile_id': config.parsing_profile_id,
'excel_template_id': source.excel_template_id,
'report_path_json': dict(source.report_path_json or {}),
'query_parameters_json': list(source.query_parameters_json or []),
'report_path_json': dict(config.report_path_json or {}),
'query_parameters_json': list(config.query_parameters_json or []),
'rpa_profile_code': profile.profile_code,
# 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页,
# 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。
'upload_config_json': profile.upload_config_json,
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
'navigation': source_navigation,
'parameters': list(source.query_parameters_json or []),
'parameters': list(config.query_parameters_json or []),
'query': {},
'login_url': profile.login_url,
'login_config': login_config,
@@ -92,7 +100,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T
source_config = get_database_inventory_source(source_code, enabled_only=enabled_only)
if source_config is None:
return None
source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first()
source = FreightRpaSource.query.filter_by(source_code=source_config['source_code']).first()
profile = source.rpa_profile if source else None
if profile is None or (enabled_only and not profile.enabled):
return None
@@ -106,7 +114,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T
def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]:
"""列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。"""
query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code)
query = FreightRpaSource.query.order_by(FreightRpaSource.source_code)
if enabled_only:
query = query.filter_by(enabled=True)
result = []
@@ -123,8 +131,10 @@ def inventory_sources_runtime_version() -> str:
import json
rows = []
for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all():
for source in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all():
profile = source.rpa_profile
# s18 起报表路径/查询条件归 onhand_report_config 配置行;配置行缺失按空配置参与指纹。
config = source.onhand_report_config
rows.append({
'source_code': source.source_code,
'source_version': source.config_version,
@@ -136,8 +146,8 @@ def inventory_sources_runtime_version() -> str:
'connector_type': source.connector_type,
'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 [],
'report_path_json': (config.report_path_json or {}) if config is not None else {},
'query_parameters_json': (config.query_parameters_json or []) if config is not None else [],
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
},
'profile_config': {
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_source_rules.py
services/shipping_notice/onhand_source_rules.py
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
依赖:onhand_routing_engine、onhand_source_repository、order_field_purposes。
逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行;
行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源;
Warehouse 由 Source/匹配决定。
@@ -18,9 +18,9 @@ from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.onhand_source_identity import resolve_inventory_source_identity
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
list_database_inventory_sources,
@@ -181,8 +181,8 @@ def resolve_ambiguous_source_from_ready_snapshots(
if len(order_keys) != len(order_lines):
return adjudication
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot
matched: list[tuple[dict[str, Any], Any]] = []
checked: list[dict[str, Any]] = []
@@ -206,7 +206,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
is_match = order_keys.issubset(inventory_keys)
checked.append({
'source_code': source_code,
'inventory_file_no': snapshot.inventory_file_no,
'inventory_file_no': snapshot.onhand_file_no,
'matched': is_match,
})
if is_match:
@@ -236,7 +236,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
candidates=adjudication.candidates,
destination_candidates=adjudication.destination_candidates,
evidence=evidence,
reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}',
reason=f'unique_ready_snapshot:{snapshot.onhand_file_no}',
)
@@ -288,9 +288,9 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
"""按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
for code in task_frozen_inventory_source_codes(task):
for code in task_frozen_onhand_source_codes(task):
item = get_database_inventory_source(code)
if item is not None:
return item
@@ -299,7 +299,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
"""持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication
del source
selected = resolution or adjudicate_inventory_source(task)
@@ -308,6 +308,6 @@ def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any],
def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None:
"""兼容旧入口,写入规则裁决候选;不触发人工库存源确认。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication
apply_inventory_source_adjudication(task, resolution)
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_structure_analysis.py
services/shipping_notice/onhand_structure_analysis.py
用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。
依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
依赖:openpyxl、onhand_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。
"""
@@ -24,11 +24,11 @@ from werkzeug.datastructures import FileStorage
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.inventory_structure_fingerprint import (
from app.models import FreightRpaOnhandField, FreightRpaParsingProfile, FreightRpaOnhandStructureAnalysis
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.onhand_structure_fingerprint import (
compatibility_fingerprint,
exact_fingerprint,
normalise_header,
@@ -44,8 +44,8 @@ _SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', '
def _has_required_suggestions(mapping: dict[str, str]) -> bool:
"""确认自动建议至少覆盖一个匹配字段和一个库存数量字段。"""
rows = ShippingInventoryField.query.filter(
ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([
rows = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.status == 'active', FreightRpaOnhandField.id.in_([
int(field_id) for field_id in mapping if str(field_id).isdigit()
]),
).all() if mapping else []
@@ -118,7 +118,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
suggestions = suggest_field_mapping(headers, as_catalog=True)
catalog = {
str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all()
str(item.id): item for item in FreightRpaOnhandField.query.filter_by(status='active').all()
}
reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog}
duplicates = Counter(header for header in headers if header)
@@ -206,7 +206,7 @@ def _build_workbook_structure(
if headers:
candidates.append(candidate)
if not candidates:
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
# Prefer a populated detail sheet over a same-score cover/summary sheet.
selected = max(candidates, key=lambda item: (
item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header),
@@ -259,9 +259,9 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str
with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle:
rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))]
except OSError as exc:
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc
if not rows:
raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
raise ValidationError('Inventory file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
header_index = find_inventory_header_row_index(rows)
headers = [_normalise_header(value) for value in rows[header_index]]
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS]
@@ -294,10 +294,10 @@ def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, st
return _xls_structure(path)
if suffix == '.csv':
return _csv_structure(path)
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
def serialize_analysis(item: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]:
"""输出管理端需要的分析结果,不暴露服务器存储路径。"""
return {
'id': item.id,
@@ -319,13 +319,13 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
"""上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。"""
if upload is None or not str(upload.filename or '').strip():
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
raise ValidationError('Inventory sample file is required', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_REQUIRED')
suffix = resolve_inventory_upload_suffix(str(upload.filename))
raw = upload.stream.read(MAX_UPLOAD_BYTES + 1)
if len(raw) > MAX_UPLOAD_BYTES:
raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
raise ValidationError('Inventory sample file is too large', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
if not raw:
raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
raise ValidationError('Inventory sample file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
analysis_dir = _analysis_root() / uuid.uuid4().hex
analysis_dir.mkdir(parents=True, exist_ok=False)
path = analysis_dir / f'sample{suffix}'
@@ -337,13 +337,13 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
raise
except Exception as exc:
shutil.rmtree(analysis_dir, ignore_errors=True)
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc
selected_headers = structure.get('selected_headers', [])
selected_definition = structure_definition(
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
)
item = ShippingInventoryStructureAnalysis(
item = FreightRpaOnhandStructureAnalysis(
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None,
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
@@ -355,7 +355,7 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
)
db.session.add(item)
db.session.flush()
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
item.match_result_json = recommend_profiles({
'structure': structure,
@@ -373,22 +373,22 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
def get_analysis(analysis_id: int) -> dict[str, Any]:
"""读取既有结构分析,供管理员选择工作表、表头和来源栏位。"""
item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
item = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if item is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
return serialize_analysis(item)
def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]:
"""比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
if analysis is None or analysis.analysis_status != 'ready':
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED')
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED')
previous = profile.sample_analysis
old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else []
new_headers = list((analysis.structure_json or {}).get('selected_headers') or [])
@@ -419,14 +419,14 @@ def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data:
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if analysis is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
existing_profile = db.session.get(FreightRpaParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
if existing_profile is not None and existing_profile.file_format != analysis.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
@@ -436,21 +436,21 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
if candidate is None and sheet_name is None:
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None)
if not isinstance(candidate, dict):
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()}
mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {}
if any(str(value or '').strip() not in headers for value in mapping.values()):
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
duplicates = {
str(column.get('header') or '').strip()
for column in candidate.get('columns', [])
if isinstance(column, dict) and column.get('duplicate')
}
if any(str(value or '').strip() in duplicates for value in mapping.values()):
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
from app.services.shipping_notice import inventory_parsing_profile
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
from app.services.shipping_notice import onhand_parsing_profile
saved = inventory_parsing_profile.save_draft({
saved = onhand_parsing_profile.save_draft({
'profile_code': data.get('profile_code'),
'display_name': data.get('display_name'),
# 用途随请求透传(缺省沿用既有草稿/默认 onhand):inbound 草稿端点为定死领域字段。
@@ -465,7 +465,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
'match_keys': data.get('match_keys'),
},
}, actor_id=actor_id, profile_id=data.get('profile_id'))
profile = db.session.get(ShippingInventoryParsingProfile, saved['id'])
profile = db.session.get(FreightRpaParsingProfile, saved['id'])
selected_definition = structure_definition(
file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index,
headers=[str(value) for value in candidate.get('headers', [])],
@@ -478,17 +478,17 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
)
profile.fingerprint_version = selected_definition['fingerprint_version']
db.session.commit()
return inventory_parsing_profile.payload(profile)
return onhand_parsing_profile.payload(profile)
def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]:
"""确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if analysis is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')}
same_test_structure = bool(
@@ -496,7 +496,7 @@ def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]
and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint
)
if profile_id not in candidate_ids and not same_test_structure:
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
analysis.match_result_json = {
**match,
'adopted_profile_id': profile.id,
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_structure_drift.py
services/shipping_notice/onhand_structure_drift.py
用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。
依赖:库存源/解析方案模型、库存结构分析和方案复用服务。
@@ -12,7 +12,7 @@ from pathlib import Path
from typing import Any
from app.core.errors import ConflictError
from app.models import ShippingInventorySource
from app.models import FreightRpaSource
def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]:
@@ -28,20 +28,22 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
Raises:
ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。
"""
source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
profile = source.parsing_profile if source is not None else None
source = FreightRpaSource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = source.onhand_report_config if source is not None else None
profile = config.parsing_profile if config is not None else None
if source is None or not source.enabled or profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED')
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.onhand_structure_analysis import _analyse_path
from app.services.shipping_notice.onhand_structure_fingerprint import exact_fingerprint, structure_definition
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
suffix = resolve_inventory_upload_suffix(path.name)
actual_format = suffix.lstrip('.')
if actual_format != profile.file_format:
raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
raise ConflictError('Inventory file format changed', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED')
structure, suggested, _summary, warnings = _analyse_path(path, suffix)
configured = profile.definition_json if isinstance(profile.definition_json, dict) else {}
expected_sheet = configured.get('sheet_name')
@@ -53,14 +55,14 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
if selected is None:
raise ConflictError(
'Configured inventory worksheet or header row is unavailable',
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED',
details={'source_code': source.source_code, 'profile_id': profile.id},
)
# Compare the configured worksheet rather than the analyser's best guess.
structure = {**structure, 'selected_sheet_name': selected['sheet_name'],
'selected_header_row_index': selected['header_row_index'],
'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])}
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True)
definition = structure_definition(
@@ -79,7 +81,7 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
if candidate is None:
raise ConflictError(
'Inventory file structure is incompatible with the bound parsing profile',
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED',
details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings},
)
return {
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_structure_fingerprint.py
services/shipping_notice/onhand_structure_fingerprint.py
用途:为库存文件结构和解析定义生成稳定、可审计的指纹。
依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。
依赖:标准 hashlib/json/unicodedata;输入来自 onhand_structure_analysis 与 onhand_parsing_profile。
逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。
"""
@@ -47,7 +47,7 @@ def exact_fingerprint(definition: dict[str, Any]) -> str:
def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str:
"""按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。"""
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
usages = usage_field_ids()
@@ -1,5 +1,5 @@
"""
services/shipping_notice/inventory_temporary_session.py
services/shipping_notice/onhand_temporary_session.py
用途:处理对话上传库存候选文件的身份初检与临时会话状态。
依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。
@@ -24,33 +24,33 @@ from app.models import (
Agent,
ChatSession,
FileAsset,
ShippingInventoryStructureAnalysis,
ShippingTemporaryInventorySession,
ShippingInventoryField,
ShippingInventoryParsingProfile,
FreightRpaOnhandStructureAnalysis,
ShippingTemporaryOnhandSession,
FreightRpaOnhandField,
FreightRpaParsingProfile,
)
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.inventory_structure_analysis import (
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
from app.services.shipping_notice.onhand_structure_analysis import (
MAX_UPLOAD_BYTES,
_analyse_path,
_analysis_root,
_safe_filename,
serialize_analysis,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
from app.services.shipping_notice.onhand_structure_fingerprint import (
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
from app.services.shipping_notice.inventory_mapping import (
from app.services.shipping_notice.onhand_mapping import (
mapping_is_complete,
runtime_field_mapping,
suggest_field_mapping,
validate_field_mapping_against_headers,
)
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
from app.services.shipping_notice.onhand_snapshot import parse_inventory_excel_with_meta
_CONTEXT_PATHS = ['agent_code', 'platform.session_id']
_TTL_HOURS = 24
@@ -59,7 +59,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
if str(values.get('agent_code') or '') != 'shipping_notice':
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID')
session_id = str(values.get('platform.session_id') or '').strip()
session = (
db.session.query(ChatSession)
@@ -68,7 +68,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
.one_or_none()
)
if session is None:
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID')
return session
@@ -77,9 +77,9 @@ def _session_no() -> str:
return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]:
def _serialize(item: ShippingTemporaryOnhandSession) -> dict[str, Any]:
"""输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
return {
'session_no': item.session_no,
'status': item.status,
@@ -101,19 +101,19 @@ def _available_inventory_fields() -> list[dict[str, Any]]:
'description': item.description or '',
'value_type': item.value_type,
'usage_type': item.usage_type,
} for item in ShippingInventoryField.query.filter_by(status='active').order_by(
ShippingInventoryField.sort_order, ShippingInventoryField.id,
} for item in FreightRpaOnhandField.query.filter_by(status='active').order_by(
FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id,
).all()]
def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
def _mapping_suggestion(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None:
"""提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。"""
result = item.result_json if isinstance(item.result_json, dict) else {}
value = result.get('mapping_suggestion')
return value if isinstance(value, dict) else None
def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
def _confirmed_usage(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None:
"""输出已确认的临时使用摘要,不返回库存行或文件内部路径。"""
result = item.result_json if isinstance(item.result_json, dict) else {}
value = result.get('confirmed_usage')
@@ -128,7 +128,7 @@ def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any]
}
def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
def _serialize_dify_analysis_preview(analysis: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]:
"""返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。"""
preview = copy.deepcopy(serialize_analysis(analysis))
structure = preview.get('structure')
@@ -146,12 +146,12 @@ def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysi
return preview
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis:
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> FreightRpaOnhandStructureAnalysis:
"""对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。"""
if int(asset.file_size or 0) > MAX_UPLOAD_BYTES:
raise ValidationError(
'Temporary inventory file is too large',
code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE',
code='SHIPPING.TEMP_ONHAND_FILE_TOO_LARGE',
)
suffix = resolve_inventory_upload_suffix(asset.original_filename)
raw = read_asset_bytes(asset)
@@ -168,7 +168,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
shutil.rmtree(analysis_dir, ignore_errors=True)
raise ValidationError(
'Temporary inventory file cannot be analysed',
code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID',
code='SHIPPING.TEMP_ONHAND_ANALYSIS_INVALID',
) from exc
# 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。
suggested, _catalog = runtime_field_mapping(suggested_catalog)
@@ -177,7 +177,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
header_row_index=structure.get('selected_header_row_index') or 1,
headers=structure.get('selected_headers', []),
)
analysis = ShippingInventoryStructureAnalysis(
analysis = FreightRpaOnhandStructureAnalysis(
source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename),
storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'),
analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
@@ -189,7 +189,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
)
db.session.add(analysis)
db.session.flush()
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
analysis.match_result_json = recommend_profiles({
'structure': structure,
@@ -200,7 +200,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
return analysis
def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]:
def _classify(analysis: FreightRpaOnhandStructureAnalysis) -> tuple[str, str]:
"""在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。"""
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else []
@@ -230,27 +230,27 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any
session = _runtime_session(payload.get('agent_runtime_context'))
asset_no = str(payload.get('asset_no') or '').strip().upper()
if not asset_no:
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED')
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_ONHAND_ASSET_REQUIRED')
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none()
if asset is None or int(asset.owner_user_id) != int(session.user_id):
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND')
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_FOUND')
if str(asset.upload_status or '') != 'ready':
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY')
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_READY')
try:
resolve_inventory_upload_suffix(asset.original_filename)
except Exception as exc:
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_ONHAND_FILE_TYPE_INVALID') from exc
active = ShippingTemporaryInventorySession.query.filter(
ShippingTemporaryInventorySession.user_id == session.user_id,
ShippingTemporaryInventorySession.conversation_id == session.session_id,
ShippingTemporaryInventorySession.asset_id == asset.id,
ShippingTemporaryInventorySession.status.in_([
active = ShippingTemporaryOnhandSession.query.filter(
ShippingTemporaryOnhandSession.user_id == session.user_id,
ShippingTemporaryOnhandSession.conversation_id == session.session_id,
ShippingTemporaryOnhandSession.asset_id == asset.id,
ShippingTemporaryOnhandSession.status.in_([
'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion',
'awaiting_mapping_confirmation',
]),
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
).order_by(ShippingTemporaryInventorySession.id.desc()).first()
ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(),
).order_by(ShippingTemporaryOnhandSession.id.desc()).first()
if active:
return _serialize(active)
@@ -262,7 +262,7 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any
asset.expires_at = expires_at
match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact'
item = ShippingTemporaryInventorySession(
item = ShippingTemporaryOnhandSession(
session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id,
asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate',
file_classification_status=classification,
@@ -291,11 +291,11 @@ def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
item = ShippingTemporaryOnhandSession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}:
item.status = 'expired'
db.session.commit()
@@ -317,31 +317,31 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
item = ShippingTemporaryOnhandSession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
if item.status != 'awaiting_mapping_suggestion':
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID')
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_ONHAND_MAPPING_STATE_INVALID')
raw_mapping = payload.get('field_mapping')
if not isinstance(raw_mapping, dict) or not raw_mapping:
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID')
mapping = {
str(field_id).strip(): str(header).strip()
for field_id, header in raw_mapping.items()
if str(field_id).strip() and str(header).strip()
}
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {}
headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()]
if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping):
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID')
errors = validate_field_mapping_against_headers(headers, mapping)
if errors or not mapping_is_complete(mapping):
raise ValidationError(
'Temporary inventory mapping suggestion is incomplete or invalid',
code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors},
code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID', details={'errors': errors},
)
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
@@ -353,19 +353,19 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di
def _select_confirmed_mapping(
item: ShippingTemporaryInventorySession,
item: ShippingTemporaryOnhandSession,
*,
selected_profile_id: Any,
) -> tuple[dict[str, str], str, int | None]:
"""按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
if item.status == 'awaiting_profile_confirmation':
try:
profile_id = int(selected_profile_id)
except (TypeError, ValueError) as exc:
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') from exc
candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else []
exact_ids = {
int(candidate.get('profile_id'))
@@ -373,17 +373,17 @@ def _select_confirmed_mapping(
and str(candidate.get('level') or '') == 'exact'
and str(candidate.get('profile_id') or '').isdigit()
}
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None or profile.status != 'published' or profile_id not in exact_ids:
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id
if item.status == 'awaiting_mapping_confirmation':
suggestion = _mapping_suggestion(item) or {}
mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {}
if not mapping:
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
return dict(mapping), 'dify_candidate', None
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]:
@@ -419,7 +419,7 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。
核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁;
只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。
只写临时会话审计,不创建 FreightRpaOnhandReportFile、不修改库存站点、不回填任务库存行、不执行匹配。
Args:
payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。
@@ -429,19 +429,19 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
"""
session = _runtime_session(payload.get('agent_runtime_context'))
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(
item = ShippingTemporaryOnhandSession.query.filter_by(
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
if item.expires_at <= datetime.utcnow():
item.status = 'expired'
db.session.commit()
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED')
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_ONHAND_SESSION_EXPIRED')
mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id'))
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
try:
lines, column_meta = parse_inventory_excel_with_meta(
@@ -449,10 +449,10 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'),
)
except Exception as exc:
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID') from exc
quality = _quality_report(lines, mapping)
if not quality['passed']:
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality})
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID', details={'quality': quality})
item.task_id = None
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
@@ -470,12 +470,12 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]:
"""返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。"""
rows = ShippingTemporaryInventorySession.query.filter_by(
rows = ShippingTemporaryOnhandSession.query.filter_by(
status='confirmed_for_temporary_use',
).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
).order_by(ShippingTemporaryOnhandSession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
result: list[dict[str, Any]] = []
for item in rows:
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
confirmed = _confirmed_usage(item)
result.append({
'session_no': item.session_no,
@@ -513,24 +513,24 @@ def create_parsing_profile_draft_from_temporary_session(
新建的库存文件解析方案草稿。
"""
normalized_no = str(session_no or '').strip().upper()
item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none()
item = ShippingTemporaryOnhandSession.query.filter_by(session_no=normalized_no).one_or_none()
if item is None:
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
if item.status != 'confirmed_for_temporary_use':
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None
if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict):
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None
if existing_draft_id:
existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id)
existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id)
if existing_draft is not None:
from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload
from app.services.shipping_notice.onhand_parsing_profile import payload as profile_payload
return profile_payload(existing_draft)
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
if analysis is None:
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
payload = {
'profile_code': data.get('profile_code'),
@@ -540,9 +540,9 @@ def create_parsing_profile_draft_from_temporary_session(
'field_mapping': confirmed['field_mapping'],
'match_keys': data.get('match_keys'),
}
from app.services.shipping_notice import inventory_structure_analysis
from app.services.shipping_notice import onhand_structure_analysis
draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
draft = onhand_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
item.result_json = {
**(item.result_json if isinstance(item.result_json, dict) else {}),
'promoted_profile_draft_id': draft['id'],
@@ -4,10 +4,13 @@ services/shipping_notice/onhand_trigger_batch.py
用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、
单票按需触发的 fail-closed 入口。
依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、
shipping_notice.inventory_source_repository(按源补 Profile 密文,函数内延迟 import)。
逻辑:由 schedule.freight_onhand_rpa_job(定时批量)、inventory_configuration_test(配置测试)、
inventory_rpa_workflow / per_source_rpa_service(按需触发)调用,
shipping_notice.onhand_source_repository(按源补 Profile 密文,函数内延迟 import)。
逻辑:由 schedule.freight_rpa_onhand_job(定时批量)、onhand_configuration_test(配置测试)、
onhand_rpa_workflow / per_source_rpa_service(按需触发)调用,
与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。
s18 起 report_path_json / query_parameters_json / parsing_profile_id 改由仓库快照取自
source.onhand_report_config 配置行(navigation/parameters 由此派生);配置行缺失时
仓库返回 None,沿用「站点未就绪」的跳过/回退语义,不新造错误码。
"""
from __future__ import annotations
@@ -53,11 +56,14 @@ def write_inventory_export_batch_trigger(
if not isinstance(source, dict) or not source.get("source_code"):
continue
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
trigger_source = get_rpa_trigger_inventory_source(
str(source["source_code"]), enabled_only=not configuration_test,
) or source
# s18 起合并进来的 report_path_json / query_parameters_json / parsing_profile_id
# 均取自 source.onhand_report_config 配置行(仓库快照),配置缺失时上面已回退到
# 调用方传入的非敏感快照,沿用「站点未就绪」既有语义。
source = {**source, **trigger_source}
business_connector = str(source.get("connector_type") or "").strip().lower()
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
@@ -106,11 +112,11 @@ def write_inventory_export_batch_trigger(
return str(path)
def inventory_rpa_batch_enabled() -> bool:
def onhand_rpa_batch_enabled() -> bool:
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
raw = current_app.config.get("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED")
if raw is None:
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
raw = os.getenv("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", "true")
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
@@ -133,7 +139,7 @@ def build_on_demand_inventory_trigger_source(
Returns:
可直接传入 write_inventory_export_batch_trigger 的单源条目。
"""
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
source_code = str(rpa_source.get('source_code') or '').strip()
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
@@ -178,7 +184,7 @@ def write_inventory_export_trigger_for_task(
不再生成 legacy inventory_export trigger。
"""
body = dict(payload or {})
if inventory_rpa_batch_enabled():
if onhand_rpa_batch_enabled():
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
return write_inventory_export_batch_trigger(
@@ -193,5 +199,5 @@ def write_inventory_export_trigger_for_task(
)
raise ValidationError(
'shipping inventory RPA v2 batch trigger is required',
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
code='SHIPPING.ONHAND_RPA_V2_REQUIRED',
)
@@ -1,9 +1,9 @@
"""
services/shipping_notice/inventory_upload.py
services/shipping_notice/onhand_upload.py
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
依赖:onhand_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
逻辑:由 onhand_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
"""
@@ -19,9 +19,9 @@ from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
from app.services.shipping_notice.onhand_file_store import inventory_storage_suffix_for_path
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
_TASK_INVENTORY_MARKER = ".current_inventory"
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
@@ -164,7 +164,7 @@ def install_task_inventory_attachment_from_file(
def rebuild_task_inventory_attachment_from_snapshot(
task: ShippingOrderTask | ShippingNotice | str,
inv_file: ShippingInventoryFile,
inv_file: FreightRpaOnhandReportFile,
) -> Path:
"""
从已提交库存快照 storage_path 幂等重建任务正式附件。
@@ -183,7 +183,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
storage_path = Path(str(inv_file.storage_path or ""))
if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
raise FileNotFoundError(
f"库存快照托管文件不存在: {inv_file.inventory_file_no}",
f"库存快照托管文件不存在: {inv_file.onhand_file_no}",
)
return install_task_inventory_attachment_from_file(
task_no,
@@ -1,8 +1,8 @@
"""
services/shipping_notice/inventory_warehouse_resolution.py
services/shipping_notice/onhand_warehouse_resolution.py
用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。
依赖:ShippingInventoryField/Source、动态订单字段投影。
依赖:FreightRpaOnhandField/Source、动态订单字段投影。
逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。
"""
@@ -11,7 +11,7 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from app.models import ShippingInventoryField, ShippingInventorySource
from app.models import FreightRpaOnhandField, FreightRpaSource
from app.services.shipping_notice.export import order_field_id_values
@@ -31,8 +31,11 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution:
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = source.onhand_report_config if source is not None else None
profile = config.parsing_profile if config is not None else None
definition = profile.definition_json if profile is not None else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)]
@@ -40,9 +43,9 @@ def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]
int(field_id) for field_id in (definition.get('field_mapping') or {})
if str(field_id).isdigit()
} if isinstance(definition, dict) else set()
warehouse_fields = ShippingInventoryField.query.filter(
ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active',
ShippingInventoryField.usage_type == 'warehouse_identity',
warehouse_fields = FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.id.in_(mapped_ids), FreightRpaOnhandField.status == 'active',
FreightRpaOnhandField.usage_type == 'warehouse_identity',
).all() if mapped_ids else []
if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1:
return WarehouseResolution(None, 'warehouse_configuration_invalid')
@@ -1,11 +1,11 @@
"""
services/shipping_notice/inventory_workflow.py
services/shipping_notice/onhand_workflow.py
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 onhand_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、onhand_file_store、onhand_mapping_workflow、
onhand_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
payload.source_codes 可收窄 ensure_inventory(持久化阶段码 ensure_onhand)/ RPA 作用源(行级重抓);
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File;
动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。
"""
@@ -21,8 +21,8 @@ from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import (
POSITION_INVENTORY_SOURCE_REVIEW,
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.onhand_file_store import save_task_inventory_upload
from app.services.shipping_notice.query_service import (
get_task_by_ref,
resolve_task_from_payload,
@@ -31,7 +31,7 @@ from app.services.shipping_notice.query_service import (
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -67,20 +67,20 @@ def _link_ready_candidate_prep_or_block(
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定
(pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成
(pending_matching),仓/匹配问题留给 onhand_matching,禁止把「有文件」投影成
inventory_file_missing。仅当真的无法绑定文件时才 needs_human。
Args:
task: 已冻结候选源的订单任务。
prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。
prep: ``prepare_candidate_onhand_lines`` 的 ready 结果。
lang: 文案语言。
Returns:
None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。
"""
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_snapshot_store import (
from app.models import FreightRpaOnhandReportFile
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
from app.services.shipping_notice.onhand_snapshot_store import (
link_snapshot_to_task_for_preparation,
)
@@ -107,7 +107,7 @@ def _link_ready_candidate_prep_or_block(
break
inv_file = (
ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first()
FreightRpaOnhandReportFile.query.filter_by(onhand_file_no=file_no).first()
if file_no
else None
)
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title='获取库存',
status='needs_human',
message=t('workflow.inventory.unavailable', lang=lang),
@@ -221,10 +221,10 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
reservation_gate = _reservation_gate_response(task, lang=lang)
if reservation_gate is not None:
return reservation_gate
if operation == "ensure_inventory":
if operation == "ensure_onhand":
# [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或
# 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
get_active_candidate_sources,
@@ -251,7 +251,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
message="库存源候选集尚未冻结完成,暂不能准备库存。",
data={
**serialize_task_for_tool(task),
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
"error_code": "SHIPPING.ONHAND_SOURCE_ROUTING_REQUIRED",
"position": POSITION_INVENTORY_SOURCE_REVIEW,
},
position=POSITION_INVENTORY_SOURCE_REVIEW,
@@ -281,7 +281,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
lang = resolve_lang({"lang": None})
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
gate_resp = _inventory_source_gate_response(task, operation="upload_onhand_file", lang=lang)
if gate_resp is not None:
return gate_resp
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
try:
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="running",
message=t("workflow.inventory.uploading", lang=lang),
@@ -322,13 +322,13 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
db.session.flush()
inv_file = save_task_inventory_upload(task, upload)
inventory_lines = [
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
item for item in (inv_file.onhand_lines_json or []) if isinstance(item, dict)
]
preview = dict(inv_file.schema_preview_json or {})
except AppError as exc:
db.session.rollback()
message = str(exc.message or "库存上传被拒绝")
if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED':
if exc.code == 'SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED':
message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。'
return tool_response(
status="failed",
@@ -362,7 +362,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
task,
"inventory_snapshot_created",
{
"inventory_file_no": inv_file.inventory_file_no,
"inventory_file_no": inv_file.onhand_file_no,
"share_mode": inv_file.share_mode,
},
)
@@ -397,7 +397,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_preparation',
resume_gate_code='onhand_preparation',
operator_id=operator_id,
inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto',
line_scope_key=(
@@ -415,7 +415,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
# [STEP 0] 与 parse/upload 共用客户、Reservation、库存源门禁,避免旁路入口绕过订单侧闸门。
gate_resp = _inventory_source_gate_response(task, operation="ensure_inventory", lang=lang)
gate_resp = _inventory_source_gate_response(task, operation="ensure_onhand", lang=lang)
if gate_resp is not None:
return gate_resp
@@ -441,27 +441,27 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 2] 正常流程优先复用已完成的库存快照;缺少快照时自动进入库存 RPA。
if mode == "retry_rpa":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(
task, mode=mode, source_codes=scoped_source_codes,
)
if mode == "auto":
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
frozen_codes = task_frozen_inventory_source_codes(task)
frozen_codes = task_frozen_onhand_source_codes(task)
if len(frozen_codes) >= 1:
prep = prepare_candidate_inventory_lines(task)
prep = prepare_candidate_onhand_lines(task)
if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing':
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task.error_message = None
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="running",
message="已触发库存获取,等待各库存源回调。",
@@ -521,7 +521,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
if probe.all_prepared:
# 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。
prep = prepare_candidate_inventory_lines(task)
prep = prepare_candidate_onhand_lines(task)
else:
# 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。
log_task_event(task, "inventory_probe_failed", {
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message="库存 RPA 未能为全部库存源生成结果。",
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -599,7 +599,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 库存源已确定但没有可复用快照时,自动推进必须启动一次 RPA,
# 否则任务会错误停在人审且没有可执行的恢复动作。
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(
task,
@@ -610,7 +610,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
if has_ready_inventory_file_for_task(task):
apply_task_transition(task, TaskTransition.INVENTORY_READY)
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
stage="inventory_fetching",
stage="onhand_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -4,9 +4,9 @@ services/shipping_notice/order_build_eligibility_service.py
用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及
Candidate Qualification 统一自动建单检查。
依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、
inventory_routing_engine、inventory_source_repository、
onhand_routing_engine、onhand_source_repository、
ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、
ShippingInventorySource、process_gate_contract(原因唯一归属)。
FreightRpaSource、process_gate_contract(原因唯一归属)。
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费);
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选,
@@ -20,7 +20,7 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingInventorySource
from app.models import FreightRpaSource
from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_GATE_KEYS,
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
@@ -30,11 +30,11 @@ from app.services.shipping_notice.candidate_qualification_service import (
)
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
from app.services.shipping_notice.inventory_routing_engine import (
from app.services.shipping_notice.onhand_routing_engine import (
InventoryRoutingResult,
evaluate_inventory_source_rules_for_field_values,
)
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
list_database_inventory_sources,
)
@@ -175,7 +175,7 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
reasons: dict[str, str] = {}
for code in _normalize_manual_codes(codes):
# [STEP 1] 源不存在
source = ShippingInventorySource.query.filter_by(source_code=code).first()
source = FreightRpaSource.query.filter_by(source_code=code).first()
if source is None:
unavailable.append(code)
reasons[code] = 'source_not_found'
@@ -197,8 +197,9 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
unavailable.append(code)
reasons[code] = 'source_runtime_unavailable'
continue
# [STEP 5] 解析 Profile 未发布
parsing = source.parsing_profile
# [STEP 5] 解析 Profile 未发布(s18 起绑定归 onhand_report_config 配置行;配置行缺失即未绑定)
config = source.onhand_report_config
parsing = config.parsing_profile if config is not None else None
if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published':
unavailable.append(code)
reasons[code] = 'parsing_profile_unavailable'
@@ -539,7 +540,7 @@ def assess_order_build_eligibility(
'draft_line_id': meta.get('draft_line_id'),
'line_index': index,
'severity': 'blocking',
'owning_gate_code': 'inventory_source_routing',
'owning_gate_code': 'onhand_source_routing',
'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [],
'unavailable_source_codes': routing.get('unavailable_source_codes') or [],
'unavailable_reasons': routing.get('unavailable_reasons') or {},
@@ -578,7 +579,7 @@ def assess_order_build_eligibility(
# 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。
build_blocking_issues = [
item for item in issues
if str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
if str(item.get('owning_gate_code') or '') != 'onhand_source_routing'
]
can_build = (
bool(customer_resolved)
@@ -12,7 +12,7 @@ import re
from decimal import Decimal, InvalidOperation
from typing import Any
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text
from app.services.shipping_notice.notice_line_table import (
find_notice_header_row_index,
parse_notice_row,
@@ -16,7 +16,7 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的
正式 inventory_source_routing Gate 负责;
正式 onhand_source_routing Gate 负责;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
@@ -1440,7 +1440,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bo
upload_status = getattr(latest_upload_attempt(task), 'status', None)
# 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等
# 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。
from app.services.shipping_notice.inventory_file_store import (
from app.services.shipping_notice.onhand_file_store import (
current_inventory_matches_for_task,
has_ready_inventory_file_for_task,
)
@@ -656,7 +656,7 @@ def _validation(
# 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。
can_build = bool(eligibility.get('can_build')) and not any(
str(item.get('severity') or '') == 'blocking'
and str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
and str(item.get('owning_gate_code') or '') != 'onhand_source_routing'
for item in issues
)
# [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。
@@ -1574,7 +1574,7 @@ def _sync_review_gates_safe(
details=sync_details,
)
inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing')
inventory_issues = _blocking_issues_for_gate(result, 'onhand_source_routing')
if not inventory_issues:
# 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task;
# 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。
@@ -4,7 +4,7 @@ services/shipping_notice/order_review_fulfillment_decision_service.py
用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。
依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、
order_review_draft_service、order_review_workbench_projection、
line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、
line_onhand_match_projection(OT 行匹配事实)、fulfillment_audit、
order_review_resume_service。
逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions;
订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」=
@@ -20,17 +20,17 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingInventoryField,
ShippingInventoryFile,
ShippingInventorySource,
FreightRpaOnhandField,
FreightRpaOnhandReportFile,
FreightRpaSource,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
ShippingOrderReviewWaveLine,
ShippingNotice,
ShippingOrderTask,
ShippingTaskInventoryRpaAttempt,
FreightRpaOnhandTaskAttempt,
)
from app.services.shipping_notice.line_inventory_match_persistence import (
from app.services.shipping_notice.line_onhand_match_persistence import (
resolve_review_case_for_task,
)
from app.services.shipping_notice.workflow_ledger_service import (
@@ -44,13 +44,13 @@ def _get_soft_loader():
return soft_load_review_case_for_audit
DECISION_WAIT = 'wait_inventory'
DECISION_WAIT = 'wait_onhand'
DECISION_FULFILL = 'fulfill_complete_line_now'
DECISION_CLOSE = 'close_unfulfillable'
DECISION_REOPEN = 'reopen'
DECISION_USE_NEW_FILE = 'use_new_inventory_file'
DECISION_CHANGE_SOURCE = 'change_inventory_source'
DECISION_RELEASE_SHORTAGE = 'release_inventory_shortage'
DECISION_RELEASE_SHORTAGE = 'release_onhand_shortage'
ALLOWED_DECISIONS = frozenset({
DECISION_WAIT,
@@ -171,7 +171,7 @@ def _release_template_inventory_fields(
'field_id': field_id,
'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})',
'value': value,
'value_source': 'inventory_snapshot' if value is not None else 'manual_required',
'value_source': 'onhand_snapshot' if value is not None else 'manual_required',
'requires_manual': value is None,
})
return fields
@@ -278,7 +278,7 @@ def _is_shortage_match_fact(fact: Any) -> bool:
def _has_terminal_inventory_rpa_failure(
task: ShippingNotice,
*,
attempts: list[ShippingTaskInventoryRpaAttempt] | None = None,
attempts: list[FreightRpaOnhandTaskAttempt] | None = None,
) -> bool:
"""仅在已投递的库存 RPA 全部终态失败且无活动 Attempt 时允许无快照人工放行。"""
task_no = str(getattr(task, 'task_no', '') or '').strip()
@@ -286,20 +286,20 @@ def _has_terminal_inventory_rpa_failure(
return False
source_codes: set[str] = set()
try:
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_codes = {str(item or '').strip().upper() for item in task_frozen_onhand_source_codes(task)}
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
source_codes = set()
rows = attempts if attempts is not None else (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=task_no)
.order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc(), FreightRpaOnhandTaskAttempt.id.desc())
.all()
)
relevant = [row for row in rows if not source_codes or str(getattr(row, 'source_code', '') or '').strip().upper() in source_codes]
if not relevant or any(str(getattr(row, 'status', '') or '').lower() in {'queued', 'running'} for row in relevant):
return False
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
latest_by_source: dict[str, FreightRpaOnhandTaskAttempt] = {}
for row in relevant:
code = str(getattr(row, 'source_code', '') or '').strip().upper()
if code and code not in latest_by_source:
@@ -325,7 +325,7 @@ def _shortage_release_required_fields(
Returns:
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
其余 requires_manual);evidence_scope ∈ {'onhand_snapshot', 'part_fallback'},
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
"""
if line_index is None:
@@ -333,20 +333,20 @@ def _shortage_release_required_fields(
'Current line inventory evidence is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
snapshot = db.session.get(FreightRpaOnhandReportFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
if inventory_snapshot_id is not None and snapshot is None:
raise ConflictError(
'Current inventory snapshot is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
resolved_source_code = _resolve_shortage_release_inventory_source(
fact_source_code=inventory_source_code,
snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None,
candidate_source_codes={
str(code or '').strip().upper()
for code in task_frozen_inventory_source_codes(task)
for code in task_frozen_onhand_source_codes(task)
if str(code or '').strip()
},
)
@@ -355,7 +355,7 @@ def _shortage_release_required_fields(
'Current line inventory evidence is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
source = ShippingInventorySource.query.filter_by(
source = FreightRpaSource.query.filter_by(
source_code=resolved_source_code, enabled=True,
).first()
template = getattr(source, 'excel_template', None) if source is not None else None
@@ -379,9 +379,9 @@ def _shortage_release_required_fields(
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '').strip().isdigit()
}
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
labels = {str(row.id): str(row.display_name or '').strip() for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()} if field_ids else {}
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'onhand_snapshot'
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
expected = [
@@ -393,7 +393,7 @@ def _shortage_release_required_fields(
'Inventory matching keys are unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
try:
inventory_lines, _column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError) as exc:
@@ -405,7 +405,7 @@ def _shortage_release_required_fields(
dict(row) for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
]
evidence_scope = 'inventory_snapshot'
evidence_scope = 'onhand_snapshot'
if not candidates:
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
@@ -413,7 +413,7 @@ def _shortage_release_required_fields(
part_field_ids = {
int(field_id) for field_id, _value in expected
if str(field_id).strip().isdigit()
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
and str(getattr(db.session.get(FreightRpaOnhandField, int(field_id)), 'field_code', '') or '') == 'part_number'
}
if part_field_ids:
candidates = [
@@ -433,7 +433,7 @@ def _shortage_release_required_fields(
}
labels = {
str(row.id): str(row.display_name or '').strip()
for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()
} if field_ids else {}
return _release_template_inventory_fields(
mappings=mappings,
@@ -481,7 +481,7 @@ def _sync_confirmed_task_fulfillment_gates(
# 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算,
# 空事实任务不得被误标为缺货。
if getattr(task, 'id', None) is not None:
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
from app.models import ShippingNoticeLineOnhandMatch as _MatchRow
has_match_rows = (
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first()
is not None
@@ -592,11 +592,11 @@ def _assess_line_fulfill_complete(
return False, 'SHIPPING.REVIEW_LINE_RESERVATION_REQUIRED', req, avail
block_reason = str(proj.get('block_reason') or '').lower()
if 'shortage' in block_reason or 'insufficient' in block_reason:
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail
if avail is None:
return False, 'SHIPPING.REVIEW_LINE_INVENTORY_UNKNOWN', req, None
return False, 'SHIPPING.REVIEW_LINE_ONHAND_UNKNOWN', req, None
if avail < req:
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail
return True, None, req, avail
@@ -621,7 +621,7 @@ def _assert_line_can_fulfill_complete(
if not ok or req is None or avail is None:
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory',
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'),
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND'),
details={'draft_line_id': draft_line_id},
)
return req, avail
@@ -791,13 +791,13 @@ def project_review_case_line_decisions(
Args:
case: 复核 Case。
schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。
inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
onhand_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
source_labels: code→显示名映射。
Returns:
lines(含 inventory_source / 分域 actions)与聚合计数。
"""
from app.services.shipping_notice.line_inventory_match_projection import (
from app.services.shipping_notice.line_onhand_match_projection import (
line_auto_fulfill_enabled,
project_line_inventory_view,
)
@@ -816,13 +816,13 @@ def project_review_case_line_decisions(
task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
# [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
from app.services.shipping_notice.stp_onhand_freeze import (
task_frozen_onhand_source_codes,
)
fallback_inventory_source: dict[str, Any] | None = None
if task is not None:
frozen_codes = task_frozen_inventory_source_codes(task)
frozen_codes = task_frozen_onhand_source_codes(task)
if len(frozen_codes) == 1:
fallback_inventory_source = {
'code': frozen_codes[0],
@@ -846,7 +846,7 @@ def project_review_case_line_decisions(
'source': 'inventory_source_clue',
}
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
from app.services.shipping_notice.line_inventory_match_projection import (
from app.services.shipping_notice.line_onhand_match_projection import (
load_current_match_facts_by_line_index,
)
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
@@ -1058,7 +1058,7 @@ def build_inventory_issue_fallback(
Case 级库存兜底:仅无有效行投影且库存系统失败时返回。
核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发
retry_inventory_preparation。
retry_onhand_preparation。
Returns:
fallback 字典或 None。
@@ -1088,8 +1088,8 @@ def build_inventory_issue_fallback(
'inventory_file_missing',
'inventory_source_unavailable',
'inventory_preparation_failed',
'inventory_rpa_timeout',
'inventory_rpa_export_failed',
'onhand_rpa_timeout',
'onhand_rpa_export_failed',
'inventory_file_empty',
}
if auto_status not in {'failed', 'error'} and reason not in failed_reasons:
@@ -1101,7 +1101,7 @@ def build_inventory_issue_fallback(
'reason_label_key': kind,
'affected_line_count': 0,
'file_count': 0,
'allowed_actions': ['retry_inventory_preparation'],
'allowed_actions': ['retry_onhand_preparation'],
}
@@ -1122,7 +1122,7 @@ def _apply_shortage_line_release(
版本化落库、同步正式 OT 门禁并写审计。
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
证据字段按行事实快照解析(预约键命中 → onhand_snapshot;预约键 0 行命中
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
@@ -1161,10 +1161,10 @@ def _apply_shortage_line_release(
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
key, draft_line = pair
from app.models import ShippingNoticeLineInventoryMatch
from app.models import ShippingNoticeLineOnhandMatch
fact = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
.first()
if getattr(task, 'id', None) is not None else None
@@ -1173,10 +1173,10 @@ def _apply_shortage_line_release(
release_template_fields, resolved_scope = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
inventory_snapshot_id=getattr(fact, 'onhand_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'source_code', None) if fact is not None else None,
)
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
release_evidence_scope = str(evidence_scope or resolved_scope or 'onhand_snapshot')
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
@@ -1241,7 +1241,7 @@ def _apply_shortage_line_release(
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
# 审计口径:放行证据来自预约匹配快照(onhand_snapshot)还是料号兜底重筛(part_fallback)。
'release_evidence_scope': release_evidence_scope,
**({'auto_release': True} if auto_release else {}),
},
@@ -1300,7 +1300,7 @@ def decide_review_line_fulfillment(
核心逻辑:停用旧活动决定;task_created/fulfilled 不可逆;
reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足;
release_inventory_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。
release_onhand_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。
Args:
user_id: 操作人。
@@ -1310,7 +1310,7 @@ def decide_review_line_fulfillment(
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
release_evidence_scope 记录证据范围(onhand_snapshot / part_fallback)。
expected_draft_version: 可选草稿乐观锁。
actor_is_admin: 是否管理员(重开授权)。
@@ -1392,12 +1392,12 @@ def decide_review_line_fulfillment(
schema_fields=schema_fields,
)
if code == DECISION_RELEASE_SHORTAGE:
from app.models import ShippingNoticeLineInventoryMatch
from app.models import ShippingNoticeLineOnhandMatch
task_id = getattr(case, 'confirmed_task_id', None)
task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None
fact = (
ShippingNoticeLineInventoryMatch.query
ShippingNoticeLineOnhandMatch.query
.filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True)
.first()
if task is not None else None
@@ -1570,7 +1570,7 @@ def auto_release_part_fallback_shortages(
Returns:
自动放行的 line_index 列表(按行号升序)。
"""
from app.services.shipping_notice.line_inventory_match_projection import (
from app.services.shipping_notice.line_onhand_match_projection import (
load_current_match_facts_by_task,
)
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff. Show more