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

+3 -3
View File
@@ -1,4 +1,4 @@
# =============================================================================
# =============================================================================
# Development — docker compose / deploy_compose.sh dev
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
@@ -104,8 +104,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
+3 -3
View File
@@ -1,4 +1,4 @@
# =============================================================================
# =============================================================================
# Production — docker compose env_file + deploy_compose.sh prod
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
@@ -118,8 +118,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
+3 -3
View File
@@ -1,4 +1,4 @@
# =============================================================================
# =============================================================================
# Test — docker compose / deploy_compose.sh test
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
# - .env.dev / .env.test / .env.prod for deployment environments
@@ -117,8 +117,8 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
+6 -2
View File
@@ -80,8 +80,12 @@ def create_app(config_name='default'):
_transfer_capabilities.register_transfer_capabilities()
# onhand/inbound RPA 回调 sink 注册(幂等):/api/freight-rpa/onhand-*、/api/freight-rpa/
# inbound-* 端点经 callback_sinks.dispatch_sink 分发到业务处理器;未注册的 kind 仍显式
# 404(FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。
# inbound-* 端点经 callback_sinks.dispatch_sink 分发到业务处理器;文件/报表事实类
# 回调(inbound-batch-ready / onhand 归档终态 commit 后)经 reports.dispatch.
# dispatch_report_fact 分发到 register_report_handler 注册的处理函数
# (Task 7:inbound→in_transit_transfer.handle_inbound_report、
# onhand→shipping_notice.handle_onhand_report,均由 rpa_sinks 两个注册函数内注册);
# 未注册的 kind 仍显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。
from app.services.shipping_notice.rpa_sinks import register_inbound_sinks, register_onhand_sinks
register_onhand_sinks()
+1 -1
View File
@@ -23,7 +23,7 @@ import app.api.admin.shipping_order_extraction # noqa: F401
import app.api.admin.announcements # noqa: F401
import app.api.admin.shipping_customers # noqa: F401
import app.api.admin.shipping_identity_rules # noqa: F401
import app.api.admin.shipping_inventory # noqa: F401
import app.api.admin.shipping_notice_admin # noqa: F401
import app.api.admin_freight_rpa # noqa: F401
import app.api.admin.shipping_order_schema # noqa: F401
import app.api.admin.shipping_field_assets # noqa: F401
-589
View File
@@ -1,589 +0,0 @@
"""
api/admin/shipping_inventory.py
用途:提供库存源、路由规则及外部系统映射的管理 API。
依赖:admin blueprint、require_admin、shipping_inventory_service。
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成;
RPA Profile CRUD 已迁至 api/admin_freight_rpa.py(/api/admin/freight-rpa/rpa-profiles)。
"""
from __future__ import annotations
import json
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ConflictError
from app.core.response import ok
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice import excel_template
from app.services.shipping_notice import inventory_field_catalog
from app.services.shipping_notice import inventory_structure_analysis
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
@require_admin
def list_shipping_excel_templates():
"""列出版本化发货 Excel 模板。"""
return _ok(excel_template.list_templates())
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
@require_admin
def create_shipping_excel_template():
"""上传 xlsx 并创建模板草稿版本。"""
try:
definition = json.loads(request.form.get('definition') or '{}')
except json.JSONDecodeError as exc:
from app.core.errors import ValidationError
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
data = {
'template_code': request.form.get('template_code'),
'display_name': request.form.get('display_name'),
'definition': definition,
}
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
@require_admin
def update_shipping_excel_template(template_id: int):
"""更新 Excel 模板草稿定义。"""
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
@require_admin
def get_shipping_excel_template_layout(template_id: int):
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
return _ok(excel_template.get_layout(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
@require_admin
def create_shipping_excel_template_version(template_id: int):
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
@require_admin
def clone_shipping_excel_template(template_id: int):
"""复制已有模板为使用新编码的独立 v1 草稿。"""
return _ok(excel_template.clone_as_new_template(
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_excel_template(template_id: int):
"""校验工作簿和字段映射后发布模板。"""
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_excel_template(template_id: int):
"""退役没有启用库存源引用的模板。"""
return _ok(excel_template.retire(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
@require_admin
def delete_shipping_excel_template(template_id: int):
"""删除从未发布且未使用的模板草稿。"""
excel_template.delete_draft(template_id)
return '', 204
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
@require_admin
def list_shipping_inventory_sources():
"""列出库存业务来源。"""
return _ok(shipping_inventory_service.list_sources())
@admin_bp.route('/shipping-notice/sources', methods=['POST'])
@require_admin
def create_shipping_inventory_source():
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
), status=201)
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_source(source_id: int):
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
return _ok(shipping_inventory_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
allow_enable_transition=False,
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['GET'])
@require_admin
def get_shipping_receipt_report_config(source_id: int):
"""读取站点独立收料报表配置;库存配置和收料配置永不混写。"""
return _ok(shipping_inventory_service.get_receipt_report_config(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['PUT'])
@require_admin
def save_shipping_receipt_report_config(source_id: int):
"""保存独立收料报表配置,并由服务记录可追溯的前后快照审计。"""
return _ok(shipping_inventory_service.save_receipt_report_config(
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
@require_admin
def bind_shipping_inventory_source_parsing_profile(source_id: int):
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
payload = request.get_json(silent=True) or {}
rows = shipping_inventory_service.bind_source_parsing_profile(
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='direct',
)
return _ok(rows[0])
@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST'])
@require_admin
def bulk_bind_shipping_inventory_source_parsing_profile():
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
payload = request.get_json(silent=True) or {}
source_ids = payload.get('source_ids')
if not isinstance(source_ids, list):
source_ids = []
return _ok(shipping_inventory_service.bind_source_parsing_profile(
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='bulk',
))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
@require_admin
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
@require_admin
def activate_shipping_inventory_source(source_id: int):
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_inventory_source(source_id: int):
"""停用库存站点而不删除已有配置和运行审计。"""
return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_source(source_id: int):
"""删除无运行/路由引用的错误库存源。"""
shipping_inventory_service.delete_source(source_id)
return '', 204
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export', methods=['POST'])
@require_admin
def start_shipping_inventory_configuration_test(source_id: int):
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST'])
@require_admin
def start_shipping_inventory_validation_batch():
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.start_batch_test_export(
payload.get('source_ids') or [], actor_id=_actor_id(),
), status=202)
@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET'])
@require_admin
def get_latest_active_shipping_inventory_validation_batch():
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_active_validation_batch())
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_validation_batch(batch_id: int):
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_validation_batch(batch_id))
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
@require_admin
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_test_run(source_id, run_no))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
@require_admin
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
from app.services.shipping_notice import inventory_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(inventory_configuration_test.confirm_test_profile(
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
))
@admin_bp.route('/shipping-notice/snapshots', methods=['GET'])
@require_admin
def list_shipping_inventory_snapshots():
"""列出库存快照的管理端只读记录。"""
return _ok(shipping_inventory_service.list_snapshots())
@admin_bp.route('/shipping-notice/snapshots/<int:snapshot_id>/download', methods=['GET'])
@require_admin
def download_shipping_inventory_snapshot(snapshot_id: int):
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id)
return send_file(path, as_attachment=True, download_name=filename)
@admin_bp.route('/shipping-notice/export-records', methods=['GET'])
@require_admin
def list_shipping_inventory_export_records():
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
return _ok(shipping_inventory_service.list_export_records())
@admin_bp.route('/shipping-notice/routing-rules', methods=['GET'])
@require_admin
def list_shipping_inventory_rules():
"""列出库存源路由规则及条件。"""
return _ok(shipping_inventory_service.list_rules())
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_routing_fields():
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
})
@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_fields():
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST'])
@require_admin
def create_shipping_inventory_field():
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_field(field_id: int):
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_field(field_id: int):
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
return _ok(inventory_field_catalog.retire_field(field_id))
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_field(field_id: int):
"""删除未被配置引用的扩展库存字段。"""
inventory_field_catalog.delete_field(field_id)
return '', 204
@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_catalog():
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
from app.services.shipping_notice.excel_template import (
ALLOWED_FORMATTERS,
ALLOWED_ROW_MODES,
ALLOWED_SOURCE_KINDS,
ALLOWED_SYSTEM_FACTS,
)
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
'inventory_fields': inventory_field_catalog.list_fields(),
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
'template_row_modes': sorted(ALLOWED_ROW_MODES),
'template_formatters': sorted(ALLOWED_FORMATTERS),
})
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
@require_admin
def list_movement_fields():
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
return _ok([
{
'code': field.code, 'value_type': str(field.value_type),
'required': bool(field.required), 'is_identity': bool(field.is_identity),
}
for field in MOVEMENT_FIELDS
])
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
"""列出可复用库存解析 Profile 版本。"""
return _ok(inventory_parsing_profile.list_profiles())
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_profile():
"""创建库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_parsing_profile(profile_id: int):
"""更新库存解析 Profile 草稿。"""
return _ok(inventory_parsing_profile.save_draft(
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int):
"""发布库存解析 Profile。"""
return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_parsing_profile(profile_id: int):
"""退役无库存源引用的已发布解析 Profile。"""
return _ok(inventory_parsing_profile.retire(profile_id))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_parsing_profile(profile_id: int):
"""删除从未发布的解析 Profile 草稿。"""
inventory_parsing_profile.delete_draft(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST'])
@require_admin
def create_shipping_inventory_structure_analysis():
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
return _ok(inventory_structure_analysis.create_sample_upload(
request.files.get('file'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_structure_analysis(analysis_id: int):
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
return _ok(inventory_structure_analysis.get_analysis(analysis_id))
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
return _ok(inventory_structure_analysis.create_profile_draft(
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
@require_admin
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
payload = request.get_json(silent=True) or {}
return _ok(inventory_structure_analysis.adopt_published_profile(
analysis_id, int(payload.get('profile_id') or 0),
))
@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET'])
@require_admin
def list_confirmed_shipping_temporary_inventory_sessions():
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions())
@admin_bp.route('/shipping-notice/temporary-inventory-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
from app.services.shipping_notice import inventory_temporary_session
return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session(
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/routing-rules', methods=['POST'])
@require_admin
def create_shipping_inventory_rule():
"""创建草稿路由规则。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_rule(rule_id: int):
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_rule(rule_id: int):
"""发布草稿规则并写入不可变定义快照。"""
return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_rule(rule_id: int):
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_rule(rule_id: int):
"""删除从未发布的草稿规则。"""
shipping_inventory_service.delete_draft_rule(rule_id)
return '', 204
@admin_bp.route('/shipping-notice/external-mappings', methods=['GET'])
@require_admin
def list_shipping_inventory_external_mappings():
"""列出库存源到外部系统仓库映射。"""
return _ok(shipping_inventory_service.list_external_mappings())
@admin_bp.route('/shipping-notice/external-mappings', methods=['POST'])
@require_admin
def create_shipping_inventory_external_mapping():
"""创建精确或 Source 默认外部系统映射。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_external_mapping(mapping_id: int):
"""更新外部系统映射,不参与任何调拨动作。"""
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_external_mapping(mapping_id: int):
"""删除错误的外部系统仓库映射。"""
shipping_inventory_service.delete_external_mapping(mapping_id)
return '', 204
@@ -0,0 +1,141 @@
"""
api/admin/shipping_notice_admin.py
用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话、异动字段目录。
依赖:admin blueprint、require_admin、excel_template、异动字段契约、临时会话服务。
逻辑:货代 RPA 管理路由(sources / onhand / inbound-report-config / rpa-profiles)已迁至
api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。
临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。
"""
from __future__ import annotations
import json
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.shipping_notice import excel_template
def _actor_id() -> int | None:
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
return getattr(getattr(g, 'current_user', None), 'id', None)
def _ok(data, *, status: int = 200):
"""按平台统一 envelope 返回管理 API 成功结果。"""
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
@require_admin
def list_shipping_excel_templates():
"""列出版本化发货 Excel 模板。"""
return _ok(excel_template.list_templates())
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
@require_admin
def create_shipping_excel_template():
"""上传 xlsx 并创建模板草稿版本。"""
try:
definition = json.loads(request.form.get('definition') or '{}')
except json.JSONDecodeError as exc:
from app.core.errors import ValidationError
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
data = {
'template_code': request.form.get('template_code'),
'display_name': request.form.get('display_name'),
'definition': definition,
}
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
@require_admin
def update_shipping_excel_template(template_id: int):
"""更新 Excel 模板草稿定义。"""
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
@require_admin
def get_shipping_excel_template_layout(template_id: int):
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
return _ok(excel_template.get_layout(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
@require_admin
def create_shipping_excel_template_version(template_id: int):
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
@require_admin
def clone_shipping_excel_template(template_id: int):
"""复制已有模板为使用新编码的独立 v1 草稿。"""
return _ok(excel_template.clone_as_new_template(
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_excel_template(template_id: int):
"""校验工作簿和字段映射后发布模板。"""
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_excel_template(template_id: int):
"""退役没有启用库存源引用的模板。"""
return _ok(excel_template.retire(template_id))
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
@require_admin
def delete_shipping_excel_template(template_id: int):
"""删除从未发布且未使用的模板草稿。"""
excel_template.delete_draft(template_id)
return '', 204
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
@require_admin
def list_movement_fields():
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
return _ok([
{
'code': field.code, 'value_type': str(field.value_type),
'required': bool(field.required), 'is_identity': bool(field.is_identity),
}
for field in MOVEMENT_FIELDS
])
@admin_bp.route('/shipping-notice/temporary-onhand-sessions', methods=['GET'])
@require_admin
def list_confirmed_shipping_temporary_inventory_sessions():
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
from app.services.shipping_notice import onhand_temporary_session
return _ok(onhand_temporary_session.list_confirmed_temporary_inventory_sessions())
@admin_bp.route('/shipping-notice/temporary-onhand-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
from app.services.shipping_notice import onhand_temporary_session
return _ok(onhand_temporary_session.create_parsing_profile_draft_from_temporary_session(
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
+459 -11
View File
@@ -1,21 +1,26 @@
"""
api/admin_freight_rpa.py
用途:货代 RPA 凭据(RPA Profile)管理 API——批次 R 自 /api/admin/shipping-notice/rpa-profiles
迁移至 /api/admin/freight-rpa/rpa-profiles(批次 S 再统一 onhand/inbound 子域命名空间)。
依赖:admin blueprint、require_admin、shipping_inventory_service(服务层留原地,仅路由搬家)。
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成;
与 admin/shipping_inventory.py 的 sources/receipt-report-config 路由解耦(批次 S 再迁)。
用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、入站报表配置、RPA Profile)。
依赖:admin blueprint、require_admin、shipping_onhand_admin_service、onhand 解析/字段/结构分析服务、订单 Schema。
逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。
rpa-profiles 与本批迁入的 sources/onhand 路由同文件注册,不保留 /shipping-notice/ 双路由。
Excel 模板、temporary-onhand-sessions、movement-fields 仍在 admin/shipping_notice_admin.py。
"""
from __future__ import annotations
from flask import g, request
from flask import g, request, send_file
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ConflictError
from app.core.response import ok
from app.services.admin import shipping_inventory_service
from app.services.admin import shipping_onhand_admin_service
from app.services.shipping_notice import onhand_field_catalog
from app.services.shipping_notice import onhand_parsing_profile
from app.services.shipping_notice import onhand_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
def _actor_id() -> int | None:
@@ -32,26 +37,469 @@ def _ok(data, *, status: int = 200):
@require_admin
def list_shipping_rpa_profiles():
"""列出脱敏后的 RPA Profile 配置。"""
return _ok(shipping_inventory_service.list_profiles())
return _ok(shipping_onhand_admin_service.list_profiles())
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['POST'])
@require_admin
def create_shipping_rpa_profile():
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
return _ok(shipping_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_rpa_profile(profile_id: int):
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
return _ok(shipping_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_rpa_profile(profile_id: int):
"""删除没有库存源引用的错误连接配置。"""
shipping_inventory_service.delete_profile(profile_id)
shipping_onhand_admin_service.delete_profile(profile_id)
return '', 204
@admin_bp.route('/freight-rpa/sources', methods=['GET'])
@require_admin
def list_shipping_inventory_sources():
"""列出库存业务来源。"""
return _ok(shipping_onhand_admin_service.list_sources())
@admin_bp.route('/freight-rpa/sources', methods=['POST'])
@require_admin
def create_shipping_inventory_source():
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
return _ok(shipping_onhand_admin_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
), status=201)
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_source(source_id: int):
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
return _ok(shipping_onhand_admin_service.save_source(
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
allow_enable_transition=False,
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['GET'])
@require_admin
def get_shipping_inbound_report_config(source_id: int):
"""读取站点独立收料报表配置;库存配置和收料配置永不混写。"""
return _ok(shipping_onhand_admin_service.get_receipt_report_config(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['PUT'])
@require_admin
def save_shipping_inbound_report_config(source_id: int):
"""保存独立收料报表配置,并由服务记录可追溯的前后快照审计。"""
return _ok(shipping_onhand_admin_service.save_receipt_report_config(
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
@require_admin
def bind_shipping_inventory_source_parsing_profile(source_id: int):
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
payload = request.get_json(silent=True) or {}
rows = shipping_onhand_admin_service.bind_source_parsing_profile(
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='direct',
)
return _ok(rows[0])
@admin_bp.route('/freight-rpa/sources/bulk-bind-parsing-profile', methods=['POST'])
@require_admin
def bulk_bind_shipping_inventory_source_parsing_profile():
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
payload = request.get_json(silent=True) or {}
source_ids = payload.get('source_ids')
if not isinstance(source_ids, list):
source_ids = []
return _ok(shipping_onhand_admin_service.bind_source_parsing_profile(
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
reason=str(payload.get('reason') or ''), operation='bulk',
))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
@require_admin
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
return _ok(shipping_onhand_admin_service.get_source_parsing_binding_audits(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/activate', methods=['POST'])
@require_admin
def activate_shipping_inventory_source(source_id: int):
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
return _ok(shipping_onhand_admin_service.activate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/deactivate', methods=['POST'])
@require_admin
def deactivate_shipping_inventory_source(source_id: int):
"""停用库存站点而不删除已有配置和运行审计。"""
return _ok(shipping_onhand_admin_service.deactivate_source(source_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_source(source_id: int):
"""删除无运行/路由引用的错误库存源。"""
shipping_onhand_admin_service.delete_source(source_id)
return '', 204
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export', methods=['POST'])
@require_admin
def start_shipping_inventory_configuration_test(source_id: int):
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/freight-rpa/onhand/validation-batches', methods=['POST'])
@require_admin
def start_shipping_inventory_validation_batch():
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
from app.services.shipping_notice import onhand_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(onhand_configuration_test.start_batch_test_export(
payload.get('source_ids') or [], actor_id=_actor_id(),
), status=202)
@admin_bp.route('/freight-rpa/onhand/validation-batches/latest-active', methods=['GET'])
@require_admin
def get_latest_active_shipping_inventory_validation_batch():
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_latest_active_validation_batch())
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_validation_batch(batch_id: int):
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_validation_batch(batch_id))
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
@require_admin
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
from app.services.shipping_notice import onhand_configuration_test
return _ok(onhand_configuration_test.get_test_run(source_id, run_no))
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
@require_admin
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
from app.services.shipping_notice import onhand_configuration_test
payload = request.get_json(silent=True) or {}
return _ok(onhand_configuration_test.confirm_test_profile(
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
))
@admin_bp.route('/freight-rpa/onhand/snapshots', methods=['GET'])
@require_admin
def list_shipping_inventory_snapshots():
"""列出库存快照的管理端只读记录。"""
return _ok(shipping_onhand_admin_service.list_snapshots())
@admin_bp.route('/freight-rpa/onhand/snapshots/<int:snapshot_id>/download', methods=['GET'])
@require_admin
def download_shipping_inventory_snapshot(snapshot_id: int):
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
path, filename = shipping_onhand_admin_service.get_snapshot_download(snapshot_id)
return send_file(path, as_attachment=True, download_name=filename)
@admin_bp.route('/freight-rpa/onhand/export-records', methods=['GET'])
@require_admin
def list_shipping_inventory_export_records():
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
return _ok(shipping_onhand_admin_service.list_export_records())
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['GET'])
@require_admin
def list_shipping_inventory_rules():
"""列出库存源路由规则及条件。"""
return _ok(shipping_onhand_admin_service.list_rules())
@admin_bp.route('/freight-rpa/onhand/routing-fields', methods=['GET'])
@require_admin
def list_shipping_inventory_routing_fields():
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
})
@admin_bp.route('/freight-rpa/onhand/fields', methods=['GET'])
@require_admin
def list_shipping_inventory_fields():
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
return _ok(onhand_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
@admin_bp.route('/freight-rpa/onhand/fields', methods=['POST'])
@require_admin
def create_shipping_inventory_field():
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
return _ok(onhand_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_field(field_id: int):
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
return _ok(onhand_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_field(field_id: int):
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
return _ok(onhand_field_catalog.retire_field(field_id))
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_field(field_id: int):
"""删除未被配置引用的扩展库存字段。"""
onhand_field_catalog.delete_field(field_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/configuration-catalog', methods=['GET'])
@require_admin
def get_shipping_inventory_configuration_catalog():
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
from app.services.shipping_notice.excel_template import (
ALLOWED_FORMATTERS,
ALLOWED_ROW_MODES,
ALLOWED_SOURCE_KINDS,
ALLOWED_SYSTEM_FACTS,
)
try:
contract = order_schema_service.get_published_contract()
order_fields = contract['fields']
published = True
except ConflictError as exc:
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
raise
order_fields = []
published = False
return _ok({
'order_fields': order_fields,
'order_schema_published': published,
'inventory_fields': onhand_field_catalog.list_fields(),
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
'template_row_modes': sorted(ALLOWED_ROW_MODES),
'template_formatters': sorted(ALLOWED_FORMATTERS),
})
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
"""列出可复用库存解析 Profile 版本。"""
return _ok(onhand_parsing_profile.list_profiles())
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_profile():
"""创建库存解析 Profile 草稿。"""
return _ok(onhand_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_parsing_profile(profile_id: int):
"""更新库存解析 Profile 草稿。"""
return _ok(onhand_parsing_profile.save_draft(
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(onhand_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int):
"""发布库存解析 Profile。"""
return _ok(onhand_parsing_profile.publish(profile_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_parsing_profile(profile_id: int):
"""退役无库存源引用的已发布解析 Profile。"""
return _ok(onhand_parsing_profile.retire(profile_id))
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_parsing_profile(profile_id: int):
"""删除从未发布的解析 Profile 草稿。"""
onhand_parsing_profile.delete_draft(profile_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/structure-analyses', methods=['POST'])
@require_admin
def create_shipping_inventory_structure_analysis():
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
return _ok(onhand_structure_analysis.create_sample_upload(
request.files.get('file'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>', methods=['GET'])
@require_admin
def get_shipping_inventory_structure_analysis(analysis_id: int):
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
return _ok(onhand_structure_analysis.get_analysis(analysis_id))
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
@require_admin
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
return _ok(onhand_structure_analysis.create_profile_draft(
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
), status=201)
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
@require_admin
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
payload = request.get_json(silent=True) or {}
return _ok(onhand_structure_analysis.adopt_published_profile(
analysis_id, int(payload.get('profile_id') or 0),
))
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['POST'])
@require_admin
def create_shipping_inventory_rule():
"""创建草稿路由规则。"""
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_rule(rule_id: int):
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/publish', methods=['POST'])
@require_admin
def publish_shipping_inventory_rule(rule_id: int):
"""发布草稿规则并写入不可变定义快照。"""
return _ok(shipping_onhand_admin_service.publish_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/retire', methods=['POST'])
@require_admin
def retire_shipping_inventory_rule(rule_id: int):
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
return _ok(shipping_onhand_admin_service.retire_rule(rule_id, actor_id=_actor_id()))
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_rule(rule_id: int):
"""删除从未发布的草稿规则。"""
shipping_onhand_admin_service.delete_draft_rule(rule_id)
return '', 204
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['GET'])
@require_admin
def list_shipping_inventory_external_mappings():
"""列出库存源到外部系统仓库映射。"""
return _ok(shipping_onhand_admin_service.list_external_mappings())
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['POST'])
@require_admin
def create_shipping_inventory_external_mapping():
"""创建精确或 Source 默认外部系统映射。"""
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['PUT'])
@require_admin
def update_shipping_inventory_external_mapping(mapping_id: int):
"""更新外部系统映射,不参与任何调拨动作。"""
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['DELETE'])
@require_admin
def delete_shipping_inventory_external_mapping(mapping_id: int):
"""删除错误的外部系统仓库映射。"""
shipping_onhand_admin_service.delete_external_mapping(mapping_id)
return '', 204
+5 -5
View File
@@ -75,7 +75,7 @@ def onhand_ready():
【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。
核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink
(inventory_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写),
(onhand_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写),
envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。
"""
return jsonify(dispatch_sink('onhand-ready', **_payload()))
@@ -112,7 +112,7 @@ def onhand_batch_progress():
【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。
核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数
(inventory_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。
(onhand_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。
"""
return jsonify(dispatch_sink('onhand-batch-progress', **_payload()))
@@ -172,7 +172,7 @@ def inbound_batch_ready():
【AI 触发时机】:非 Agent 入口;收料 Worker 完成报表导出并落 drop 目录后调用。
核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根注册的业务 sink
(receipt_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive
(inbound_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive
原样归档,终态 commit 后由域内业务桥推进在途调拨并归集排程终态)——独立归档文件,
绝不进入库存回调或库存匹配链路;envelope = {'success': True, 'data': ...}(旧端点逐字一致)。
"""
@@ -186,7 +186,7 @@ def inbound_unit_progress():
【AI 触发时机】:非 Agent 入口;收料 Worker 领取单元后调用(awaiting_rpa → processing)。
核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_receipt_unit_processing
(Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize);本路由同时是收料
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料
超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08),
Worker 上报全程 404,勿再从任何路由文件删除。
"""
@@ -200,7 +200,7 @@ def inbound_batch_progress():
【AI 触发时机】:非 Agent 入口;收料 Worker 每完成一笔导出后调用(非终态)。
核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_receipt_batch_progress
(Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize),回写排程 run 计数
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数
(对齐 onhand-batch-progress 语义)。
"""
return jsonify(dispatch_sink('inbound-batch-progress', **_payload()))
+11 -11
View File
@@ -186,13 +186,13 @@ def requery_items_api(matching_no: str):
@in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"])
@require_transfer_permission
def download_source_inbound_files_api():
"""按选中来源打包下载各自最新归档入站文件(ShippingReceiptReport RPA 产物,zip);记录访问审计。"""
"""按选中来源打包下载各自最新归档入站文件(ShippingInboundReport RPA 产物,zip);记录访问审计。"""
import io
import zipfile
from pathlib import Path as _Path
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition
@@ -210,15 +210,15 @@ def download_source_inbound_files_api():
if not code:
continue
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
FreightRpaInboundReportFile.unit_run.has(source_code=code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
# 单一事实来源见 inbound_file_gate。
usable_inbound_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.first()
)
if report is None:
@@ -761,11 +761,11 @@ def transfer_sources_api():
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
"""
from app.models import ShippingInventorySource
from app.models import FreightRpaSource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
rows = ShippingInventorySource.query.filter_by(enabled=True).order_by(
ShippingInventorySource.connector_type, ShippingInventorySource.source_code,
rows = FreightRpaSource.query.filter_by(enabled=True).order_by(
FreightRpaSource.connector_type, FreightRpaSource.source_code,
).all()
return _ok([
{
@@ -782,7 +782,7 @@ def transfer_sources_api():
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
@require_transfer_permission
def retry_source_rpa_api(source_code: str):
"""对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留)。
"""对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingInboundReport trigger 链路,shipping_notice 域术语保留)。
【AI 触发时机】来源入站文件不可用需要恢复时调用:解析失败(parse_failed)先
本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。
@@ -847,7 +847,7 @@ def retry_sources_rpa_batch_api():
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingReceiptReport RPA 排程路径同效率)。
合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingInboundReport RPA 排程路径同效率)。
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
+2 -2
View File
@@ -19,12 +19,12 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.freight_onhand_rpa_finalize import (
from app.services.schedule.freight_rpa_onhand_finalize import (
apply_deferred_schedule_run_state,
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,
+17 -17
View File
@@ -18,11 +18,11 @@ from app.api.schedule.blueprint import schedule_admin_bp
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, FreightRpaInboundUnitRun
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download
from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
@@ -144,17 +144,17 @@ def get_schedule_run_receipt_raw_zip(run_id: int):
)
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
@schedule_admin_bp.route('/inbound-report-files/<int:file_id>/resend', methods=['POST'])
@require_admin
def resend_receipt_report_file(file_id: int):
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。"""
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')
user = get_current_user()
outcome = deliver_inbound_file(report_file.id, force=True)
append_shipping_audit_event(
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
event_type='shipping_inbound_report_notification_resent', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
@@ -165,7 +165,7 @@ def resend_receipt_report_file(file_id: int):
return jsonify({'success': True, 'data': outcome})
@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET'])
@schedule_admin_bp.route('/inbound-rpa-units', methods=['GET'])
@require_admin
def list_receipt_rpa_units():
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
@@ -178,15 +178,15 @@ def list_receipt_rpa_units():
except (TypeError, ValueError):
from app.core.errors import ValidationError
raise ValidationError('limit is invalid')
query = ShippingReceiptRpaUnitRun.query.order_by(
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
query = FreightRpaInboundUnitRun.query.order_by(
FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(),
)
if status:
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
query = query.filter(FreightRpaInboundUnitRun.status == status)
units = query.limit(limit).all()
user = get_current_user()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection',
event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection',
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), result='success',
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
@@ -207,11 +207,11 @@ def list_receipt_rpa_units():
} for unit in units]}})
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
@schedule_admin_bp.route('/inbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
@require_admin
def retry_receipt_rpa_unit(unit_id: int):
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
failed = db.session.get(FreightRpaInboundUnitRun, unit_id)
if failed is None:
raise NotFoundError('Receipt RPA unit not found')
if failed.status not in {'failed', 'cancelled'}:
@@ -222,15 +222,15 @@ def retry_receipt_rpa_unit(unit_id: int):
from app.core.errors import ValidationError
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED')
user = get_current_user()
retry = ShippingReceiptRpaUnitRun(
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
retry = FreightRpaInboundUnitRun(
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa',
config_snapshot_json=dict(failed.config_snapshot_json or {}),
)
db.session.add(retry)
db.session.flush()
source = retry.inventory_source
source = retry.source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
db.session.rollback()
@@ -260,7 +260,7 @@ def retry_receipt_rpa_unit(unit_id: int):
summary['awaiting_receipt_rpa'] = True
run.response_summary_json = summary
append_shipping_audit_event(
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit',
event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit',
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
before={'status': failed.status, 'error_code': failed.error_code},
+2 -2
View File
@@ -199,7 +199,7 @@ def tool_ensure_inventory():
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_ensure_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_preparation',
resume_gate_code='onhand_preparation',
))
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
@@ -222,7 +222,7 @@ def tool_match_inventory():
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
trigger='legacy_tool_match_inventory',
operator_id=payload.get('operator_id'),
resume_gate_code='inventory_matching',
resume_gate_code='onhand_matching',
))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
+1 -1
View File
@@ -12,7 +12,7 @@ from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
from app.api.workspace.voucher_check import workspace_voucher_check_bp
import app.api.workspace.shipping_process_gate # noqa: F401
import app.api.workspace.shipping_inventory_candidates # noqa: F401
import app.api.workspace.shipping_onhand_candidates # noqa: F401
__all__ = [
'workspace_announcements_bp',
+16 -16
View File
@@ -87,11 +87,11 @@ def _ok(payload: Any, *, status: int = 200):
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
@workspace_shipping_notice_bp.route('/inbound-report-files/<int:file_id>/download', methods=['GET'])
def workspace_download_receipt_report_file(file_id: int):
"""下载当前接收人或管理员有权读取的原样收料报表。"""
user = _require_user()
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
from app.services.shipping_notice.inbound_report_access import resolve_receipt_report_download
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
response = send_file(
@@ -102,7 +102,7 @@ def workspace_download_receipt_report_file(file_id: int):
return response
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
@workspace_shipping_notice_bp.route('/inbound-report-files', methods=['GET'])
def workspace_list_receipt_report_files():
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
user = _require_user()
@@ -110,7 +110,7 @@ def workspace_list_receipt_report_files():
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('limit must be an integer') from exc
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
from app.services.shipping_notice.inbound_report_access import list_receipt_report_files
return _ok({'items': list_receipt_report_files(user, limit=limit)})
@@ -1308,11 +1308,11 @@ def workspace_shipping_task_inventory_file(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
resolved = resolve_task_inventory_download(task)
if resolved is None:
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
path, download_name = resolved
from app.services.shipping_notice.fulfillment_audit import record_access_audit
record_access_audit(
@@ -1338,28 +1338,28 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no:
raise NotFoundError('Not found')
from pathlib import Path
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch
requested_file_no = str(inventory_file_no or '').strip()
inventory_file = (
ShippingInventoryFile.query
FreightRpaOnhandReportFile.query
.join(
ShippingNoticeLineInventoryMatch,
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
ShippingNoticeLineOnhandMatch,
ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id,
)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
ShippingInventoryFile.inventory_file_no == requested_file_no,
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no,
FreightRpaOnhandReportFile.onhand_file_no == requested_file_no,
)
.first()
)
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
path = Path(storage_path).resolve() if storage_path else None
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
from app.services.shipping_notice.inventory_file_store import build_inventory_download_name
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
from app.services.shipping_notice.onhand_file_store import build_inventory_download_name
download_name = build_inventory_download_name(
inventory_file, source_file_name=inventory_file.source_file_name, path=path,
)
@@ -1,8 +1,8 @@
"""
backend/app/api/workspace/shipping_inventory_candidates.py
backend/app/api/workspace/shipping_onhand_candidates.py
用途:正式 Task 库存候选只读详情 API。
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
不把可恢复业务阻断误报成 404。
"""
@@ -13,7 +13,7 @@ from flask import request
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
project_inventory_candidate_detail,
)
from app.services.shipping_notice.query_service import get_task_for_user
+4 -4
View File
@@ -370,8 +370,8 @@ class Config:
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
)
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true'
)
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
@@ -443,8 +443,8 @@ class Config:
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
)
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
+1 -1
View File
@@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401
procurement_contract_review,
schedule_run,
shipping_document_layout,
shipping_inventory_callback_process,
freight_rpa_onhand_callback_process,
shipping_notice_parse,
shipping_notice_run,
shipping_order_extraction,
@@ -1,9 +1,13 @@
"""
backend/app/jobs/handlers/shipping_inventory_callback_process.py
backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后
onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚,
重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回
payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。
"""
from __future__ import annotations
@@ -16,7 +20,7 @@ from app.jobs.types import JobType
from app.models import Job
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS)
@register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS)
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
"""处理一个已收件的库存 RPA 回调。
@@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
owned_attempt = int(job.attempts or 0)
try:
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
result_data = result.get('data') if isinstance(result, dict) else None
@@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback
settle_failed_inventory_callback(
dict(job.payload_json or {}),
@@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
message='库存 RPA 回调已异步处理',
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence
except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据
db.session.rollback()
# 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」——
# 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败
# 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、
# 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或
# attempts 耗尽。普通意外异常(无清单)仍整批自然重放。
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
)
if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files:
job.payload_json = {
**(dict(job.payload_json or {})),
'retry_dispatch_files': list(exc.failed_files),
}
db.session.commit()
fail_job(
job.id,
error=str(exc),
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
retryable=False,
# 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败
# ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与
# drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按
# 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方
# retryable=False 分支。
retryable=True,
owned_attempt=owned_attempt,
)
+7 -4
View File
@@ -3,7 +3,9 @@ backend/app/jobs/types.py
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取;
在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为
freight_rpa_onhand_callback_process。
"""
from __future__ import annotations
@@ -20,8 +22,9 @@ class JobType(StrEnum):
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
# 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
# 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。
FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process'
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
@@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping': frozenset({
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
'shipping_inventory_callback_process',
'freight_rpa_onhand_callback_process',
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
+63 -60
View File
@@ -2,8 +2,9 @@
backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。
依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
在手/入站模型导出 FreightRpa*。
"""
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
@@ -31,15 +32,15 @@ from app.models.contract_payment import (
ContractPaymentVendorRequest,
)
from app.models.shipping import (
ShippingInventoryFile,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingTaskEvent,
ShippingTaskPurgeAudit,
ShippingTaskInventoryLink,
ShippingTaskOnhandLink,
)
from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile
from app.models.shipping_order_submission import ShippingOrderSubmission
from app.models.shipping_order_task import ShippingOrderTask
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
@@ -52,8 +53,8 @@ from app.models.shipping_context_provider import ShippingContextProvider, Shippi
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_fulfillment import (
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingOnhandVerification,
ShippingOnhandVerificationLine,
ShippingReservation,
ShippingUploadAttempt,
)
@@ -95,7 +96,7 @@ from app.models.shipping_order_review import (
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit,
@@ -137,27 +138,28 @@ from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
from app.models.shipping_inventory_config import (
ShippingInventoryField,
ShippingInventoryExternalMapping,
ShippingInventoryConfigurationTestRun,
ShippingInventoryValidationBatch,
ShippingInventorySourceParsingBindingAudit,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingInventoryRoutingRuleVersion,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingRpaProfile,
from app.models.freight_rpa_config import (
FreightRpaOnhandField,
FreightRpaOnhandExternalMapping,
FreightRpaOnhandConfigurationTestRun,
FreightRpaOnhandValidationBatch,
FreightRpaSourceParsingBindingAudit,
FreightRpaParsingProfile,
FreightRpaOnhandRoutingRule,
FreightRpaOnhandRoutingRuleCondition,
FreightRpaOnhandRoutingRuleVersion,
FreightRpaSource,
FreightRpaOnhandReportConfig,
FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
)
from app.models.shipping_receipt_report import (
ShippingReceiptNotificationDelivery,
ShippingReceiptReportConfig,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
from app.models.freight_rpa_inbound_report import (
FreightRpaInboundNotificationDelivery,
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCustomer,
@@ -180,18 +182,18 @@ from app.models.shipping_identity_rule import (
ShippingIdentityRuleAuditEvent,
ShippingIdentityRuleSet,
)
from app.models.shipping_inventory_candidates import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
from app.models.shipping_onhand_candidates import (
ShippingOnhandCandidateLine,
ShippingOnhandCandidateSet,
ShippingOnhandCandidateSource,
)
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
from app.models.shipping_inventory_preparation import (
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
from app.models.shipping_onhand_preparation import (
ShippingOnhandPreparationAttempt,
ShippingOnhandPreparationSourceAttempt,
)
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping
from app.models.training import (
LeanTrainingCompletion,
LeanTrainingReminder,
@@ -319,7 +321,7 @@ __all__ = [
'ShippingOrderReviewLineDecision',
'ShippingOrderReviewWaveLine',
'ShippingOrderReviewWaveIdempotency',
'ShippingNoticeLineInventoryMatch',
'ShippingNoticeLineOnhandMatch',
'ShippingOrderReviewSuggestion',
'ShippingOrderProcessingRun',
'ShippingOrderProcessingRunIntake',
@@ -368,30 +370,31 @@ __all__ = [
'ShippingIdentityRuleAuditEvent',
'ShippingTaskEvent',
'ShippingTaskPurgeAudit',
'ShippingInventoryFile',
'ShippingTaskInventoryLink',
'ShippingRpaProfile',
'ShippingInventorySource',
'ShippingReceiptReportConfig',
'ShippingReceiptRpaUnitRun',
'ShippingReceiptReportFile',
'ShippingReceiptNotificationDelivery',
'ShippingInventoryField',
'ShippingInventoryStructureAnalysis',
'ShippingInventoryRoutingRule',
'ShippingInventoryRoutingRuleCondition',
'ShippingInventoryRoutingRuleVersion',
'ShippingInventoryExternalMapping',
'ShippingInventoryConfigurationTestRun',
'ShippingInventoryValidationBatch',
'ShippingInventorySourceParsingBindingAudit',
'ShippingInventoryParsingProfile',
'ShippingTemporaryInventorySession',
'FreightRpaOnhandReportFile',
'ShippingTaskOnhandLink',
'FreightRpaProfile',
'FreightRpaSource',
'FreightRpaOnhandReportConfig',
'FreightRpaInboundReportConfig',
'FreightRpaInboundUnitRun',
'FreightRpaInboundReportFile',
'FreightRpaInboundNotificationDelivery',
'FreightRpaOnhandField',
'FreightRpaOnhandStructureAnalysis',
'FreightRpaOnhandRoutingRule',
'FreightRpaOnhandRoutingRuleCondition',
'FreightRpaOnhandRoutingRuleVersion',
'FreightRpaOnhandExternalMapping',
'FreightRpaOnhandConfigurationTestRun',
'FreightRpaOnhandValidationBatch',
'FreightRpaSourceParsingBindingAudit',
'FreightRpaParsingProfile',
'ShippingTemporaryOnhandSession',
'ShippingExcelTemplate',
'ShippingExportArtifact',
'ShippingReservation',
'ShippingInventoryVerification',
'ShippingInventoryVerificationLine',
'ShippingOnhandVerification',
'ShippingOnhandVerificationLine',
'ShippingExportArtifactLine',
'ShippingUploadAttempt',
'ShippingProcessExecution',
@@ -426,10 +429,10 @@ __all__ = [
'MaintenanceDevice',
'MaintenanceRecord',
'MaintenanceAuditLog',
'ShippingInventoryCandidateSet',
'ShippingInventoryCandidateSource',
'ShippingInventoryCandidateLine',
'ShippingTaskInventoryRpaAttempt',
'ShippingOnhandCandidateSet',
'ShippingOnhandCandidateSource',
'ShippingOnhandCandidateLine',
'FreightRpaOnhandTaskAttempt',
'VoucherCheckProfile',
'VoucherCheckRun',
'VoucherCheckSubject',
@@ -1,9 +1,10 @@
"""
models/shipping_inventory_config.py
backend/app/models/freight_rpa_config.py
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
用途:定义货代库存源、RPA Profile、在手报表配置、通用路由规则及外部系统仓库映射主数据。
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置;
在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列),
外部系统映射仅供后端内部复用,不承载调拨决策。
"""
@@ -18,18 +19,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingInventoryField(Base):
class FreightRpaOnhandField(Base):
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
__tablename__ = 'shipping_inventory_fields'
__tablename__ = 'freight_rpa_onhand_fields'
__table_args__ = (
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'),
UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'),
CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'),
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'),
CheckConstraint(
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
name='ck_shipping_inventory_fields_usage_type',
name='ck_freight_rpa_onhand_fields_usage_type',
),
)
@@ -48,13 +49,13 @@ class ShippingInventoryField(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingRpaProfile(Base):
class FreightRpaProfile(Base):
"""货代库存登录连接配置;凭据字段始终保存密文。"""
__tablename__ = 'shipping_rpa_profiles'
__tablename__ = 'freight_rpa_profiles'
__table_args__ = (
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -81,24 +82,24 @@ class ShippingRpaProfile(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile')
class ShippingInventorySource(Base):
class FreightRpaSource(Base):
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
__tablename__ = 'shipping_inventory_sources'
__tablename__ = 'freight_rpa_sources'
__table_args__ = (
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'),
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'),
CheckConstraint(
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
name='ck_shipping_inventory_sources_warehouse_mode',
name='ck_freight_rpa_sources_warehouse_mode',
),
CheckConstraint(
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
name='ck_shipping_inventory_sources_enabled_bindings',
"enabled = false OR excel_template_id IS NOT NULL",
name='ck_freight_rpa_sources_enabled_template',
),
)
@@ -106,14 +107,12 @@ class ShippingInventorySource(Base):
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True)
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
# 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定);
# CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
@@ -122,31 +121,72 @@ class ShippingInventorySource(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources')
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
back_populates='inventory_source', cascade='all, delete-orphan'
onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship(
back_populates='source', uselist=False, cascade='all, delete-orphan',
)
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship(
back_populates='source', cascade='all, delete-orphan'
)
inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship(
back_populates='source', uselist=False, cascade='all, delete-orphan',
)
class ShippingInventorySourceParsingBindingAudit(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
class FreightRpaOnhandReportConfig(Base):
"""库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。
__tablename__ = 'shipping_inventory_source_parsing_binding_audits'
解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且
parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。
"""
__tablename__ = 'freight_rpa_onhand_report_configs'
__table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'),
UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
# 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。
source_id: Mapped[int] = mapped_column(
ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True,
)
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
# 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
)
# 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
)
# 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config')
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources')
class FreightRpaSourceParsingBindingAudit(Base):
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
__tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits'
__table_args__ = (
Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False)
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True,
)
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
operation: Mapped[str] = mapped_column(String(32), nullable=False)
reason: Mapped[str] = mapped_column(String(500), nullable=False)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -157,29 +197,27 @@ class ShippingInventorySourceParsingBindingAudit(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryParsingProfile(Base):
class FreightRpaParsingProfile(Base):
"""可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
用途以 purpose 字段为准,勿按表名推断只服务库存。
purpose='onhand':在手库存文件(原 inventory),端点用 ShippingInventoryField
库存字段目录(既有语义);
purpose='inbound':入站收料文件(原 movement),端点用定死领域字段
表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。
purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录;
purpose='inbound':入站文件,端点用定死领域字段
(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='inbound');
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
不依赖库存字段目录。校验逻辑按 purpose 分支。
绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id /
入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound');
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
"""
__tablename__ = 'shipping_inventory_parsing_profiles'
__tablename__ = 'freight_rpa_parsing_profiles'
__table_args__ = (
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
CheckConstraint(
"purpose IN ('onhand', 'inbound', 'outbound')",
name='ck_shipping_inventory_parsing_profiles_purpose',
name='ck_freight_rpa_parsing_profiles_purpose',
),
)
@@ -198,7 +236,7 @@ class ShippingInventoryParsingProfile(Base):
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
)
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
@@ -209,16 +247,17 @@ class ShippingInventoryParsingProfile(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
# s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。
sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile')
sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship(
foreign_keys=[sample_analysis_id],
)
class ShippingInventoryStructureAnalysis(Base):
class FreightRpaOnhandStructureAnalysis(Base):
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
__tablename__ = 'shipping_inventory_structure_analyses'
__tablename__ = 'freight_rpa_onhand_structure_analyses'
__table_args__ = (
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
Index('ix_inv_structure_analysis_created', 'created_at'),
@@ -246,24 +285,28 @@ class ShippingInventoryStructureAnalysis(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryConfigurationTestRun(Base):
class FreightRpaOnhandConfigurationTestRun(Base):
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
__tablename__ = 'shipping_inventory_configuration_test_runs'
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
__tablename__ = 'freight_rpa_onhand_configuration_test_runs'
__table_args__ = (
UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),
# PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。
Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
validation_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True,
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
)
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True)
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -271,10 +314,10 @@ class ShippingInventoryConfigurationTestRun(Base):
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryValidationBatch(Base):
class FreightRpaOnhandValidationBatch(Base):
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
__tablename__ = 'shipping_inventory_validation_batches'
__tablename__ = 'freight_rpa_onhand_validation_batches'
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -287,21 +330,21 @@ class ShippingInventoryValidationBatch(Base):
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True,
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
class ShippingInventoryRoutingRule(Base):
class FreightRpaOnhandRoutingRule(Base):
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
__tablename__ = 'shipping_inventory_routing_rules'
__tablename__ = 'freight_rpa_onhand_routing_rules'
__table_args__ = (
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'),
CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'),
CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'),
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -321,17 +364,17 @@ class ShippingInventoryRoutingRule(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship(
back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence'
)
class ShippingInventoryRoutingRuleCondition(Base):
class FreightRpaOnhandRoutingRuleCondition(Base):
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
__tablename__ = 'shipping_inventory_routing_rule_conditions'
__tablename__ = 'freight_rpa_onhand_routing_rule_conditions'
__table_args__ = (
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'),
CheckConstraint(
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
name='ck_inventory_routing_condition_source',
@@ -339,7 +382,7 @@ class ShippingInventoryRoutingRuleCondition(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
@@ -347,24 +390,24 @@ class ShippingInventoryRoutingRuleCondition(Base):
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions')
class ShippingInventoryRoutingRuleVersion(Base):
class FreightRpaOnhandRoutingRuleVersion(Base):
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
__tablename__ = 'shipping_inventory_routing_rule_versions'
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
__tablename__ = 'freight_rpa_onhand_routing_rule_versions'
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),)
id: Mapped[int] = mapped_column(primary_key=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
version: Mapped[int] = mapped_column(Integer, nullable=False)
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingInventoryExternalMapping(Base):
class FreightRpaOnhandExternalMapping(Base):
"""库存源到外部系统仓库的映射。
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
@@ -374,18 +417,18 @@ class ShippingInventoryExternalMapping(Base):
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
"""
__tablename__ = 'shipping_inventory_external_mappings'
__tablename__ = 'freight_rpa_onhand_external_mappings'
__table_args__ = (
Index(
'uq_shipping_inv_ext_map_src_default_enabled',
'inventory_source_id',
'source_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
),
Index(
'uq_shipping_inv_ext_map_src_wh_enabled',
'inventory_source_id',
'source_id',
'freight_warehouse_id',
unique=True,
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
@@ -394,7 +437,7 @@ class ShippingInventoryExternalMapping(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -410,4 +453,4 @@ class ShippingInventoryExternalMapping(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings')
@@ -1,9 +1,9 @@
"""
收料报表 RPA 的配置、运行、归档与通知投递持久化模型。
backend/app/models/freight_rpa_inbound_report.py
用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。
依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。
用途:入站报表 RPA 的配置、运行、归档与通知投递持久化模型。
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
"""
from __future__ import annotations
@@ -17,22 +17,22 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReceiptReportConfig(Base):
class FreightRpaInboundReportConfig(Base):
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
__tablename__ = 'shipping_receipt_report_configs'
__tablename__ = 'freight_rpa_inbound_report_configs'
__table_args__ = (
UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'),
UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
source_id: Mapped[int] = mapped_column(
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
)
report_path_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=dict, server_default=text("'{}'"), nullable=False,
@@ -47,32 +47,32 @@ class ShippingReceiptReportConfig(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config')
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship()
source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config')
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
class ShippingReceiptRpaUnitRun(Base):
class FreightRpaInboundUnitRun(Base):
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
"""
__tablename__ = 'shipping_receipt_rpa_unit_runs'
__tablename__ = 'freight_rpa_inbound_rpa_unit_runs'
__table_args__ = (
UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'),
UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'),
CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name='ck_shipping_receipt_rpa_unit_runs_status',
name='ck_freight_rpa_inbound_rpa_unit_runs_status',
),
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'),
Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
@@ -89,26 +89,26 @@ class ShippingReceiptRpaUnitRun(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
inventory_source: Mapped['ShippingInventorySource'] = relationship()
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
source: Mapped['FreightRpaSource'] = relationship()
retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['FreightRpaInboundReportFile']] = relationship(
back_populates='unit_run', cascade='all, delete-orphan',
)
class ShippingReceiptReportFile(Base):
class FreightRpaInboundReportFile(Base):
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
__tablename__ = 'shipping_receipt_report_files'
__tablename__ = 'freight_rpa_inbound_report_files'
__table_args__ = (
UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'),
Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'),
Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'),
CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'),
Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'),
Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True)
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True)
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
@@ -125,35 +125,37 @@ class ShippingReceiptReportFile(Base):
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files')
deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship(
unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files')
deliveries: Mapped[list['FreightRpaInboundNotificationDelivery']] = relationship(
back_populates='report_file', cascade='all, delete-orphan',
)
class ShippingReceiptNotificationDelivery(Base):
class FreightRpaInboundNotificationDelivery(Base):
"""收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。"""
__tablename__ = 'shipping_receipt_notification_deliveries'
__tablename__ = 'freight_rpa_inbound_notification_deliveries'
__table_args__ = (
UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'),
CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'),
UniqueConstraint('idempotency_key', name='uq_freight_rpa_inbound_notification_deliveries_idempotency'),
CheckConstraint("message_type IN ('file', 'summary')", name='ck_freight_rpa_inbound_notification_deliveries_type'),
CheckConstraint(
"status IN ('pending', 'sending', 'success', 'failed')",
name='ck_shipping_receipt_notification_deliveries_status',
name='ck_freight_rpa_inbound_notification_deliveries_status',
),
Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'),
Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'),
# PostgreSQL 标识符上限 63。表名替换后的自动名是 64 字节,故用显式短名。
Index('ix_fr_inbound_notif_deliveries_recipient_user_id', 'recipient_user_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
unit_run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True,
)
report_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True,
ForeignKey('freight_rpa_inbound_report_files.id'), nullable=True, index=True,
)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
message_type: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
@@ -164,5 +166,5 @@ class ShippingReceiptNotificationDelivery(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id])
report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries')
unit_run: Mapped[Optional[FreightRpaInboundUnitRun]] = relationship(foreign_keys=[unit_run_id])
report_file: Mapped[Optional[FreightRpaInboundReportFile]] = relationship(back_populates='deliveries')
@@ -1,8 +1,8 @@
"""
models/shipping_inventory_mapping.py
backend/app/models/freight_rpa_onhand_mapping.py
用途:保存不可变库存字段映射版本。
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
"""
@@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingInventoryMapping(Base):
class FreightRpaOnhandMapping(Base):
"""库存文件的不可变字段映射版本。"""
__tablename__ = 'shipping_inventory_mappings'
__tablename__ = 'freight_rpa_onhand_mappings'
__table_args__ = (
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,123 @@
"""
backend/app/models/freight_rpa_onhand_report_file.py
用途:货代 RPA 抓回的在手报表文件。
依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。
逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import (
Boolean,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class FreightRpaOnhandReportFile(Base):
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。
在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改,
仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。
"""
__tablename__ = 'freight_rpa_onhand_report_files'
__table_args__ = (
Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'),
Index(
'ix_freight_rpa_onhand_report_files_source_snapshot',
'source_code',
'warehouse_id',
'snapshot_status',
'exported_at',
),
Index(
'ix_freight_rpa_onhand_report_files_source_warehouse',
'source_code',
'warehouse_id',
),
Index(
'uq_freight_rpa_onhand_report_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
Index(
'uq_freight_rpa_onhand_report_files_rpa_dynamic_source_ready',
'rpa_run_no',
'source_code',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
links: Mapped[List['ShippingTaskOnhandLink']] = relationship(
'ShippingTaskOnhandLink',
back_populates='inventory_file',
cascade='all, delete-orphan',
)
@@ -1,5 +1,5 @@
"""
models/shipping_task_inventory_rpa_attempts.py
backend/app/models/freight_rpa_onhand_task_attempts.py
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
@@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = (
)
class ShippingTaskInventoryRpaAttempt(Base):
class FreightRpaOnhandTaskAttempt(Base):
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
__tablename__ = 'shipping_task_inventory_rpa_attempts'
__tablename__ = 'freight_rpa_onhand_task_rpa_attempts'
__table_args__ = (
# 三元组唯一:同一运行号同一源只允许一条记录
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
@@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base):
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+4 -4
View File
@@ -5,7 +5,7 @@
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
source_file_id 外键指向 shipping_receipt_report_files(ShippingReceiptReport 原样归档,入站证据)。
source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
@@ -606,7 +606,7 @@ class TransferMovementLedger(Base):
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
source_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_report_files.id', ondelete='SET NULL'), nullable=True,
ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True,
)
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -622,9 +622,9 @@ class TransferMovementLedger(Base):
)
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 溯源关系:档案行 → ShippingReceiptReport 原样归档文件(单向,不回挂; ShippingReceiptReportFile
# 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile
# 不感知调拨域,避免跨域 back_populates 环)。
source_file: Mapped[Optional['ShippingReceiptReportFile']] = relationship()
source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship()
@event.listens_for(TransferAuditEvent, 'before_update')
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/job.py
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
依赖:models.base.Base。
依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
"""
@@ -149,7 +149,7 @@ class Job(Base):
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True,
ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True,
)
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
+12 -105
View File
@@ -1,7 +1,7 @@
"""
backend/app/models/shipping.py
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
@@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
class ShippingInventoryFile(Base):
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
__tablename__ = 'shipping_inventory_files'
__table_args__ = (
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
Index(
'ix_shipping_inventory_files_source_snapshot',
'source_code',
'warehouse_id',
'snapshot_status',
'exported_at',
),
Index(
'ix_shipping_inventory_files_source_warehouse',
'source_code',
'warehouse_id',
),
Index(
'uq_shipping_inventory_files_rpa_identity_ready',
'rpa_run_no',
'source_code',
'warehouse_id',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
),
),
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
Index(
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
'rpa_run_no',
'source_code',
unique=True,
postgresql_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
sqlite_where=text(
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
),
),
)
id: Mapped[int] = mapped_column(primary_key=True)
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
line_count: Mapped[int] = mapped_column(Integer, default=0)
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
'ShippingTaskInventoryLink',
back_populates='inventory_file',
cascade='all, delete-orphan',
)
class ShippingTaskInventoryLink(Base):
class ShippingTaskOnhandLink(Base):
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
__tablename__ = 'shipping_task_inventory_links'
__tablename__ = 'shipping_task_onhand_links'
__table_args__ = (
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'),
Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'),
Index(
'ix_shipping_task_inventory_links_task_source',
'ix_shipping_task_onhand_links_task_source',
'task_id',
'matched_source_code',
),
@@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
@@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base):
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True)
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
@@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base):
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship(
'FreightRpaOnhandReportFile',
back_populates='links',
foreign_keys=[inventory_file_id],
foreign_keys=[onhand_file_id],
)
@@ -2,7 +2,7 @@
models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
"""
@@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template')
class ShippingExportArtifact(Base):
@@ -62,8 +62,8 @@ class ShippingExportArtifact(Base):
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
+17 -17
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_fulfillment.py
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
"""
@@ -46,53 +46,53 @@ class ShippingReservation(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingInventoryVerification(Base):
class ShippingOnhandVerification(Base):
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
__tablename__ = 'shipping_notice_inventory_verifications'
__tablename__ = 'shipping_notice_onhand_verifications'
__table_args__ = (
CheckConstraint(
"status IN ('completed', 'expired', 'superseded')",
name='ck_shipping_notice_inventory_verifications_status',
name='ck_shipping_notice_onhand_verifications_status',
),
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id',
)
class ShippingInventoryVerificationLine(Base):
class ShippingOnhandVerificationLine(Base):
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
__tablename__ = 'shipping_notice_inventory_verification_lines'
__tablename__ = 'shipping_notice_onhand_verification_lines'
__table_args__ = (
UniqueConstraint(
'verification_id', 'reservation_id',
name='uq_shipping_notice_inventory_verification_lines_reservation',
name='uq_shipping_notice_onhand_verification_lines_reservation',
),
CheckConstraint(
"status IN ('available', 'shortage', 'invalid')",
name='ck_shipping_notice_inventory_verification_lines_status',
name='ck_shipping_notice_onhand_verification_lines_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
verification_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False,
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
@@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base):
status: Mapped[str] = mapped_column(String(16), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines')
class ShippingExportArtifactLine(Base):
@@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base):
)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
verification_line_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_notice_line.py
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。
依赖:shipping_notices、shipping_order_snapshot_lines、freight_rpa_onhand_report_files、SQLAlchemy Base。
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
"""
@@ -47,7 +47,7 @@ class ShippingNoticeLine(Base):
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True,
ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, index=True,
)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -1,9 +1,9 @@
"""
models/shipping_notice_line_inventory_match.py
models/shipping_notice_line_onhand_match.py
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。
逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
"""
@@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLineInventoryMatch(Base):
class ShippingNoticeLineOnhandMatch(Base):
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
__tablename__ = 'shipping_notice_line_inventory_matches'
__tablename__ = 'shipping_notice_line_onhand_matches'
__table_args__ = (
UniqueConstraint(
'task_id',
'snapshot_line_id',
'inventory_snapshot_id',
'onhand_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
@@ -51,7 +51,7 @@ class ShippingNoticeLineInventoryMatch(Base):
),
Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'onhand_snapshot_id'),
CheckConstraint(
"match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', "
@@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base):
name='ck_shipping_notice_line_inv_match_result',
),
CheckConstraint(
"inventory_status IN ("
"onhand_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key', 'invalid'"
")",
@@ -85,22 +85,22 @@ class ShippingNoticeLineInventoryMatch(Base):
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
candidate_line_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'),
ForeignKey('shipping_onhand_candidate_lines.id', ondelete='SET NULL'),
nullable=True,
index=True,
)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'),
nullable=True,
)
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False)
onhand_status: Mapped[str] = mapped_column(String(32), nullable=False)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
@@ -111,7 +111,7 @@ class ShippingNoticeLineInventoryMatch(Base):
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -146,7 +146,7 @@ class ShippingNoticeLineInventoryMatch(Base):
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True)
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_onhand_matches.id'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
@@ -1,12 +1,12 @@
"""
models/shipping_inventory_candidates.py
models/shipping_onhand_candidates.py
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
同一时刻的完整不可变副本,用于审计与回滚。
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
@@ -39,7 +39,7 @@ def _utc_now() -> datetime:
return datetime.utcnow()
class ShippingInventoryCandidateSet(Base):
class ShippingOnhandCandidateSet(Base):
"""
库存候选集合(冻结真相根)。
@@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base):
二者至少一个非空(CheckConstraint 强制)。
"""
__tablename__ = 'shipping_inventory_candidate_sets'
__tablename__ = 'shipping_onhand_candidate_sets'
__table_args__ = (
CheckConstraint(
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
@@ -98,7 +98,7 @@ class ShippingInventoryCandidateSet(Base):
)
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True,
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True,
)
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -111,19 +111,19 @@ class ShippingInventoryCandidateSet(Base):
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship(
sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateSource.candidate_order',
order_by='ShippingOnhandCandidateSource.candidate_order',
)
lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship(
lines: Mapped[list['ShippingOnhandCandidateLine']] = relationship(
back_populates='candidate_set',
cascade='all, delete-orphan',
order_by='ShippingInventoryCandidateLine.line_no',
order_by='ShippingOnhandCandidateLine.line_no',
)
class ShippingInventoryCandidateSource(Base):
class ShippingOnhandCandidateSource(Base):
"""
任务级候选库存源(Set 的子级)。
@@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base):
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
"""
__tablename__ = 'shipping_inventory_candidate_sources'
__tablename__ = 'shipping_onhand_candidate_sources'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'source_code',
@@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base):
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
routing_rule_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True,
ForeignKey('freight_rpa_onhand_routing_rules.id', ondelete='SET NULL'), nullable=True,
)
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -170,12 +170,12 @@ class ShippingInventoryCandidateSource(Base):
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
back_populates='sources',
)
class ShippingInventoryCandidateLine(Base):
class ShippingOnhandCandidateLine(Base):
"""
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
@@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base):
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
"""
__tablename__ = 'shipping_inventory_candidate_lines'
__tablename__ = 'shipping_onhand_candidate_lines'
__table_args__ = (
UniqueConstraint(
'candidate_set_id', 'line_no',
@@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base):
id: Mapped[int] = mapped_column(primary_key=True)
candidate_set_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
)
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -215,6 +215,6 @@ class ShippingInventoryCandidateLine(Base):
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
)
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
back_populates='lines',
)
@@ -1,8 +1,8 @@
"""
models/shipping_inventory_preparation.py
models/shipping_onhand_preparation.py
用途:表达一次任务级库存准备轮次及逐库存源状态。
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
依赖:ShippingOrderTask、RecoveryPlan、FreightRpaOnhandTaskAttempt、FreightRpaOnhandReportFile、ShippingTaskOnhandLink、Base。
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
"""
@@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingInventoryPreparationAttempt(Base):
class ShippingOnhandPreparationAttempt(Base):
"""一次任务级库存准备恢复轮次。"""
__tablename__ = 'shipping_inventory_preparation_attempts'
__tablename__ = 'shipping_onhand_preparation_attempts'
__table_args__ = (
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
CheckConstraint(
@@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base):
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True)
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True)
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
@@ -46,13 +46,13 @@ class ShippingInventoryPreparationAttempt(Base):
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
source_attempts = relationship('ShippingOnhandPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
class ShippingInventoryPreparationSourceAttempt(Base):
class ShippingOnhandPreparationSourceAttempt(Base):
"""准备轮次中某个库存源的业务状态。"""
__tablename__ = 'shipping_inventory_preparation_source_attempts'
__tablename__ = 'shipping_onhand_preparation_source_attempts'
__table_args__ = (
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
CheckConstraint(
@@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base):
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True)
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True)
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True)
task_onhand_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_onhand_links.id', ondelete='SET NULL'), nullable=True)
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts')
preparation_attempt = relationship('ShippingOnhandPreparationAttempt', back_populates='source_attempts')
@@ -32,8 +32,8 @@ class ShippingOrderReviewLineDecision(Base):
),
CheckConstraint(
"decision_code IN ("
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
")",
name='ck_shipping_review_line_decisions_code',
),
+2 -2
View File
@@ -2,7 +2,7 @@
backend/app/models/shipping_order_task.py
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。
依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_onhand_candidate_sets。
逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
"""
@@ -104,7 +104,7 @@ class ShippingOrderTask(Base):
ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True,
)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True,
ForeignKey('shipping_onhand_candidate_sets.id', use_alter=True), nullable=True, index=True,
)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
+2 -2
View File
@@ -2,7 +2,7 @@
models/shipping_process_gate.py
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。
依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job、shipping_onhand_candidate_sets;状态枚举与 process_gate_contract 对齐。
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
由领域服务独占写入;Job 仅调度。
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
@@ -78,7 +78,7 @@ class ShippingProcessExecution(Base):
)
# 绑定候选版本,防止旧 callback/job 写入新候选链。
candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True,
ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True,
)
execution_revision: Mapped[int] = mapped_column(
Integer, nullable=False, default=1, server_default='1',
@@ -1,8 +1,8 @@
"""
models/shipping_temporary_inventory.py
models/shipping_temporary_onhand.py
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。
依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、freight_rpa_onhand_structure_analyses。
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
本表不代表库存站点配置,也不代表生产库存快照。
@@ -19,12 +19,12 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingTemporaryInventorySession(Base):
class ShippingTemporaryOnhandSession(Base):
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
__tablename__ = 'shipping_temporary_inventory_sessions'
__tablename__ = 'shipping_temporary_onhand_sessions'
__table_args__ = (
UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'),
UniqueConstraint('session_no', name='uq_shipping_temporary_onhand_sessions_no'),
Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'),
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
@@ -37,7 +37,7 @@ class ShippingTemporaryInventorySession(Base):
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True)
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
@@ -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': (
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff. Show more