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:
1 parent
ffc0d4a430
commit
39fe3c05f2
453 files changed
+17945
-8646
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
|
||||
|
||||
+24
-14
@@ -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}],
|
||||
+45
-27
@@ -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()
|
||||
)
|
||||
|
||||
+38
-38
@@ -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)
|
||||
)
|
||||
+20
-20
@@ -1,15 +1,15 @@
|
||||
"""
|
||||
services/shipping_notice/line_inventory_match_projection.py
|
||||
services/shipping_notice/line_onhand_match_projection.py
|
||||
|
||||
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
|
||||
依赖:ShippingNoticeLineOnhandMatch、FreightRpaOnhandTaskAttempt、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
|
||||
ready+not_found→available=0;result_missing 不得转 0;
|
||||
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
|
||||
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
||||
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
|
||||
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
|
||||
load_current_match_facts_by_task / onhand_rpa_is_running 在同一 HTTP 请求内 memo,
|
||||
禁止按行重复查库。
|
||||
"""
|
||||
|
||||
@@ -19,9 +19,9 @@ from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
)
|
||||
|
||||
|
||||
@@ -41,10 +41,10 @@ STATUS_SOURCE_CONFLICT = 'source_conflict'
|
||||
STATUS_UNAVAILABLE = 'unavailable'
|
||||
STATUS_INVALID_KEY = 'invalid_key'
|
||||
|
||||
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
|
||||
ACTION_RETRY_PREPARATION = 'retry_onhand_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_onhand_matching'
|
||||
ACTION_CLOSE = 'close_unfulfillable'
|
||||
ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage'
|
||||
ACTION_RELEASE_SHORTAGE = 'release_onhand_shortage'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
|
||||
|
||||
|
||||
@@ -455,10 +455,10 @@ def inventory_rpa_is_running(task: Any) -> bool:
|
||||
|
||||
try:
|
||||
running = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.first()
|
||||
is not None
|
||||
@@ -496,7 +496,7 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
|
||||
cache = None
|
||||
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(task_id=key, is_current=True)
|
||||
.all()
|
||||
)
|
||||
@@ -519,7 +519,7 @@ def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dic
|
||||
if task_id is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.all()
|
||||
)
|
||||
@@ -543,11 +543,11 @@ def aggregate_match_status_for_task(task_id: int | None) -> str | None:
|
||||
return 'unfulfillable' if blocked else 'fulfillable'
|
||||
|
||||
|
||||
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
|
||||
def serialize_match_fact(row: ShippingNoticeLineOnhandMatch) -> dict[str, Any]:
|
||||
"""将 ORM 行序列化为投影输入。"""
|
||||
snapshot = (
|
||||
ShippingInventoryFile.query.get(int(row.inventory_snapshot_id))
|
||||
if row.inventory_snapshot_id is not None else None
|
||||
FreightRpaOnhandReportFile.query.get(int(row.onhand_snapshot_id))
|
||||
if row.onhand_snapshot_id is not None else None
|
||||
)
|
||||
return {
|
||||
'id': int(row.id),
|
||||
@@ -557,10 +557,10 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
||||
'line_no': int(row.line_no),
|
||||
'line_index': row.line_index,
|
||||
'inventory_snapshot_id': (
|
||||
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
|
||||
int(row.onhand_snapshot_id) if row.onhand_snapshot_id is not None else None
|
||||
),
|
||||
'match_result': str(row.match_result or ''),
|
||||
'inventory_status': str(row.inventory_status or ''),
|
||||
'inventory_status': str(row.onhand_status or ''),
|
||||
'required_qty': row.required_qty,
|
||||
'available_qty': row.available_qty,
|
||||
'shortage_qty': row.shortage_qty,
|
||||
@@ -569,7 +569,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
||||
'part_number': row.part_number,
|
||||
'unit': row.unit,
|
||||
'matching_rule_version': row.matching_rule_version,
|
||||
'inventory_source_code': row.inventory_source_code,
|
||||
'inventory_source_code': row.source_code,
|
||||
'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []),
|
||||
'inventory_file_no': getattr(row, 'matched_file_no', None),
|
||||
'inventory_file_sha256': (
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/match_rule_desc.py
|
||||
|
||||
用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。
|
||||
依赖:标准类型能力。
|
||||
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
|
||||
逻辑:由 onhand_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/notice_line_table.py
|
||||
|
||||
用途:从发货通知表格文本或二维行数据中解析订单行。
|
||||
依赖:notice_line_values、动态 Schema 表头契约、reservation_id、inventory_snapshot(懒加载表格拆行)。
|
||||
依赖:notice_line_values、动态 Schema 表头契约、reservation_id、onhand_snapshot(懒加载表格拆行)。
|
||||
逻辑:调用方显式传入冻结契约;歧义表头不静默选列,输出诊断供 Run 进入复核。
|
||||
"""
|
||||
|
||||
@@ -229,7 +229,7 @@ def inspect_notice_table_text(
|
||||
Returns:
|
||||
`lines`、`header_found`、`ambiguous_fields` 和表头索引。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
|
||||
from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text
|
||||
|
||||
text = str(raw_text or '').strip()
|
||||
if not text or contract is None:
|
||||
@@ -257,6 +257,6 @@ def parse_notice_table_text(
|
||||
"""
|
||||
从发货通知原始文本中的表格片段解析订单行。
|
||||
|
||||
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
|
||||
核心逻辑:先借助 onhand_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
|
||||
"""
|
||||
return list(inspect_notice_table_text(raw_text, contract=contract)['lines'])
|
||||
@@ -2,10 +2,10 @@
|
||||
services/shipping_notice/notice_odm_choice_service.py
|
||||
|
||||
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
|
||||
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
|
||||
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineOnhandMatch、AppError。
|
||||
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
|
||||
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
|
||||
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
|
||||
(shipping_notice_line_onhand_matches.chosen_odm_id)上,按「同一库存快照文件」
|
||||
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
|
||||
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
|
||||
"""
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingCustomer, ShippingNoticeLineOnhandMatch
|
||||
|
||||
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
|
||||
|
||||
@@ -127,7 +127,7 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s
|
||||
http_status=409,
|
||||
)
|
||||
target_row = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(
|
||||
task_id=int(task_id),
|
||||
snapshot_line_id=int(snapshot_line_id or 0),
|
||||
@@ -144,11 +144,11 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s
|
||||
)
|
||||
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
|
||||
scope_rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
|
||||
.filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id == target_row.onhand_snapshot_id)
|
||||
.all()
|
||||
) if target_row.inventory_snapshot_id is not None else [target_row]
|
||||
) if target_row.onhand_snapshot_id is not None else [target_row]
|
||||
lines_by_sid = {
|
||||
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
|
||||
}
|
||||
|
||||
+68
-68
@@ -1,13 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_candidate_freeze_service.py
|
||||
services/shipping_notice/onhand_candidate_freeze_service.py
|
||||
|
||||
用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表
|
||||
(T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json
|
||||
作为不可变审计副本。
|
||||
依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、
|
||||
inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。
|
||||
依赖:app.models.shipping_onhand_candidates(Set/Source/Line)、onhand_source_rules、
|
||||
onhand_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。
|
||||
逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen)
|
||||
与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用;
|
||||
与 STP 建单 freeze_stp_onhand_candidates_on_task 两条路径调用;
|
||||
input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。
|
||||
"""
|
||||
|
||||
@@ -26,17 +26,17 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderSnapshot,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
_task_routing_lines,
|
||||
compute_routing_fingerprint,
|
||||
@@ -90,9 +90,9 @@ def _build_input_fingerprint(
|
||||
def _build_manifest_snapshot(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
set_db: ShippingInventoryCandidateSet,
|
||||
sources_db: list[ShippingInventoryCandidateSource],
|
||||
lines_db: list[ShippingInventoryCandidateLine],
|
||||
set_db: ShippingOnhandCandidateSet,
|
||||
sources_db: list[ShippingOnhandCandidateSource],
|
||||
lines_db: list[ShippingOnhandCandidateLine],
|
||||
routing_rule_version_json: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -215,35 +215,35 @@ def _find_existing_frozen_set(
|
||||
review_case_id: int | None,
|
||||
input_fingerprint: str,
|
||||
session: Session,
|
||||
) -> ShippingInventoryCandidateSet | None:
|
||||
) -> ShippingOnhandCandidateSet | None:
|
||||
"""
|
||||
根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。
|
||||
PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。
|
||||
"""
|
||||
if task_id is not None:
|
||||
return (
|
||||
session.query(ShippingInventoryCandidateSet)
|
||||
session.query(ShippingOnhandCandidateSet)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingInventoryCandidateSet.task_id == task_id,
|
||||
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
|
||||
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
|
||||
ShippingOnhandCandidateSet.task_id == task_id,
|
||||
ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint,
|
||||
ShippingOnhandCandidateSet.lifecycle_status == 'frozen',
|
||||
)
|
||||
)
|
||||
.order_by(ShippingInventoryCandidateSet.id.desc())
|
||||
.order_by(ShippingOnhandCandidateSet.id.desc())
|
||||
.first()
|
||||
)
|
||||
if review_case_id is not None:
|
||||
return (
|
||||
session.query(ShippingInventoryCandidateSet)
|
||||
session.query(ShippingOnhandCandidateSet)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingInventoryCandidateSet.review_case_id == review_case_id,
|
||||
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
|
||||
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
|
||||
ShippingOnhandCandidateSet.review_case_id == review_case_id,
|
||||
ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint,
|
||||
ShippingOnhandCandidateSet.lifecycle_status == 'frozen',
|
||||
)
|
||||
)
|
||||
.order_by(ShippingInventoryCandidateSet.id.desc())
|
||||
.order_by(ShippingOnhandCandidateSet.id.desc())
|
||||
.first()
|
||||
)
|
||||
return None
|
||||
@@ -252,8 +252,8 @@ def _find_existing_frozen_set(
|
||||
def _next_task_set_version(*, task_id: int, session: Session) -> int:
|
||||
"""计算 Task 维度下一个 CandidateSet.version。"""
|
||||
current_max = (
|
||||
session.query(func.max(ShippingInventoryCandidateSet.set_version))
|
||||
.filter(ShippingInventoryCandidateSet.task_id == int(task_id))
|
||||
session.query(func.max(ShippingOnhandCandidateSet.set_version))
|
||||
.filter(ShippingOnhandCandidateSet.task_id == int(task_id))
|
||||
.scalar()
|
||||
)
|
||||
return int(current_max or 0) + 1
|
||||
@@ -269,10 +269,10 @@ def _invalidate_task_candidate_outputs(
|
||||
"""
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOnhandPreparationAttempt,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingProcessRecoveryPlan,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
|
||||
@@ -285,18 +285,18 @@ def _invalidate_task_candidate_outputs(
|
||||
task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}}
|
||||
|
||||
(
|
||||
session.query(ShippingNoticeLineInventoryMatch)
|
||||
session.query(ShippingNoticeLineOnhandMatch)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
)
|
||||
.update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False)
|
||||
)
|
||||
(
|
||||
session.query(ShippingTaskInventoryRpaAttempt)
|
||||
session.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''),
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or ''),
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
|
||||
)
|
||||
@@ -326,19 +326,19 @@ def _invalidate_task_candidate_outputs(
|
||||
'finished_at': datetime.utcnow(),
|
||||
'error_code': 'candidate_set_refrozen',
|
||||
}, synchronize_session=False)
|
||||
prep_query = session.query(ShippingInventoryPreparationAttempt).filter(
|
||||
ShippingInventoryPreparationAttempt.task_id == int(task.id),
|
||||
ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
|
||||
prep_query = session.query(ShippingOnhandPreparationAttempt).filter(
|
||||
ShippingOnhandPreparationAttempt.task_id == int(task.id),
|
||||
ShippingOnhandPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')),
|
||||
)
|
||||
if old_candidate_set_id is not None:
|
||||
prep_query = prep_query.filter(
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
|
||||
ShippingOnhandPreparationAttempt.candidate_set_id == int(old_candidate_set_id)
|
||||
)
|
||||
prep_query.update({'status': 'superseded'}, synchronize_session=False)
|
||||
active_execution_ids = [
|
||||
row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter(
|
||||
ShippingInventoryPreparationAttempt.task_id == int(task.id),
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id,
|
||||
row[0] for row in session.query(ShippingOnhandPreparationAttempt.execution_id).filter(
|
||||
ShippingOnhandPreparationAttempt.task_id == int(task.id),
|
||||
ShippingOnhandPreparationAttempt.candidate_set_id == old_candidate_set_id,
|
||||
).all() if row[0]
|
||||
]
|
||||
if active_execution_ids:
|
||||
@@ -395,7 +395,7 @@ def freeze_candidates_for_task(
|
||||
|
||||
session = session or db.session
|
||||
if adjudication is None:
|
||||
from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_rules import adjudicate_inventory_source
|
||||
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
|
||||
@@ -478,7 +478,7 @@ def freeze_candidates_for_task(
|
||||
'adjudication_reason': adjudication.reason,
|
||||
}
|
||||
existing_active = (
|
||||
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None
|
||||
else None
|
||||
)
|
||||
@@ -487,7 +487,7 @@ def freeze_candidates_for_task(
|
||||
if getattr(task, 'id', None) is not None
|
||||
else 1
|
||||
)
|
||||
new_set = ShippingInventoryCandidateSet(
|
||||
new_set = ShippingOnhandCandidateSet(
|
||||
task_id=task.id,
|
||||
review_case_id=review_case_id,
|
||||
execution_id=execution_id,
|
||||
@@ -503,7 +503,7 @@ def freeze_candidates_for_task(
|
||||
session.add(new_set)
|
||||
session.flush()
|
||||
|
||||
created_sources: list[ShippingInventoryCandidateSource] = []
|
||||
created_sources: list[ShippingOnhandCandidateSource] = []
|
||||
for idx, code in enumerate(task_source_codes_ordered):
|
||||
src_cfg = get_database_inventory_source(code)
|
||||
rule_id: int | None = None
|
||||
@@ -514,13 +514,13 @@ def freeze_candidates_for_task(
|
||||
if isinstance(matched_rule_ids, list) and matched_rule_ids:
|
||||
try:
|
||||
_rule_ids_int = int(matched_rule_ids[0])
|
||||
from app.models.shipping_inventory_config import ShippingInventoryRoutingRule
|
||||
from app.models.freight_rpa_config import FreightRpaOnhandRoutingRule
|
||||
rule_row = (
|
||||
session.query(
|
||||
ShippingInventoryRoutingRule.id,
|
||||
ShippingInventoryRoutingRule.version,
|
||||
FreightRpaOnhandRoutingRule.id,
|
||||
FreightRpaOnhandRoutingRule.version,
|
||||
)
|
||||
.filter(ShippingInventoryRoutingRule.id == _rule_ids_int)
|
||||
.filter(FreightRpaOnhandRoutingRule.id == _rule_ids_int)
|
||||
.one_or_none()
|
||||
)
|
||||
if rule_row is not None:
|
||||
@@ -529,7 +529,7 @@ def freeze_candidates_for_task(
|
||||
except (TypeError, ValueError):
|
||||
rule_id = None
|
||||
rule_version = None
|
||||
source = ShippingInventoryCandidateSource(
|
||||
source = ShippingOnhandCandidateSource(
|
||||
candidate_set_id=new_set.id,
|
||||
source_code=code,
|
||||
candidate_order=idx + 1,
|
||||
@@ -550,7 +550,7 @@ def freeze_candidates_for_task(
|
||||
for line in debug_env.read_text(encoding='utf-8').splitlines()
|
||||
if '=' in line
|
||||
}
|
||||
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'inventory_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
|
||||
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'onhand_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
|
||||
except Exception:
|
||||
pass
|
||||
# #endregion
|
||||
@@ -558,10 +558,10 @@ def freeze_candidates_for_task(
|
||||
created_sources.append(source)
|
||||
session.flush(created_sources)
|
||||
|
||||
created_lines: list[ShippingInventoryCandidateLine] = []
|
||||
created_lines: list[ShippingOnhandCandidateLine] = []
|
||||
for sig in signatures:
|
||||
line_no, source_line_no, pn, resv, codes_ordered = sig
|
||||
line_entity = ShippingInventoryCandidateLine(
|
||||
line_entity = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=new_set.id,
|
||||
line_no=line_no,
|
||||
source_line_no=source_line_no,
|
||||
@@ -671,7 +671,7 @@ def freeze_manual_line_source_selection(
|
||||
raise ValueError('未找到该订单项次')
|
||||
|
||||
active_set = (
|
||||
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
if task.active_inventory_candidate_set_id is not None else None
|
||||
)
|
||||
existing_codes = {
|
||||
@@ -733,7 +733,7 @@ def active_candidate_set_is_manually_pinned(
|
||||
"""
|
||||
sess = session or db.session
|
||||
active_set = (
|
||||
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
sess.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
|
||||
else None
|
||||
)
|
||||
@@ -759,8 +759,8 @@ def refresh_candidates_from_current_routing(
|
||||
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
|
||||
|
||||
核心逻辑:
|
||||
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
|
||||
不得自动改源,换源走 override_line_inventory_source 行级覆写。
|
||||
[守卫 1] 仅多候选未定源可刷新(task_frozen_onhand_source_codes > 1);源已定单
|
||||
不得自动改源,换源走 override_line_onhand_source 行级覆写。
|
||||
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
|
||||
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
|
||||
[STEP 1] 记录当前活动 set_id。
|
||||
@@ -778,12 +778,12 @@ def refresh_candidates_from_current_routing(
|
||||
Returns:
|
||||
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
sess = session or db.session
|
||||
if len(task_frozen_inventory_source_codes(task)) <= 1:
|
||||
if len(task_frozen_onhand_source_codes(task)) <= 1:
|
||||
return False
|
||||
if active_candidate_set_is_manually_pinned(task, session=sess):
|
||||
return False
|
||||
@@ -804,7 +804,7 @@ def refresh_candidates_from_current_routing(
|
||||
'scope': 'task',
|
||||
'previous_set_id': before_set_id,
|
||||
'new_set_id': after_set_id,
|
||||
'source_codes': task_frozen_inventory_source_codes(task),
|
||||
'source_codes': task_frozen_onhand_source_codes(task),
|
||||
},
|
||||
source='system',
|
||||
)
|
||||
@@ -820,7 +820,7 @@ def refresh_line_candidates_from_current_routing(
|
||||
) -> bool:
|
||||
"""
|
||||
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
|
||||
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
|
||||
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_onhand_preparation 携带
|
||||
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
|
||||
|
||||
核心逻辑:
|
||||
@@ -844,12 +844,12 @@ def refresh_line_candidates_from_current_routing(
|
||||
Returns:
|
||||
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
_task_routing_lines,
|
||||
compute_routing_fingerprint,
|
||||
evaluate_inventory_source_rules,
|
||||
@@ -990,7 +990,7 @@ def freeze_wave_notice_routing(
|
||||
"""
|
||||
from app.models.shipping_notice_line import ShippingNoticeLine
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
from app.services.shipping_notice.onhand_routing_engine import (
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
|
||||
@@ -1048,7 +1048,7 @@ def freeze_wave_notice_routing(
|
||||
if not task_codes:
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
_candidate,
|
||||
compute_routing_fingerprint,
|
||||
+76
-76
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_candidate_projection.py
|
||||
services/shipping_notice/onhand_candidate_projection.py
|
||||
|
||||
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
|
||||
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
|
||||
ShippingTaskInventoryRpaAttempt。
|
||||
依赖:ShippingOrderTask、ShippingOnhandCandidateSet/Source/Line、ShippingNoticeLineOnhandMatch、
|
||||
FreightRpaOnhandTaskAttempt。
|
||||
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
|
||||
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
|
||||
"""
|
||||
@@ -17,14 +17,14 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryFile,
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
)
|
||||
|
||||
|
||||
@@ -60,23 +60,23 @@ def _candidate_set_filter(
|
||||
*,
|
||||
include_drafts: bool = False,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateSet]:
|
||||
) -> list[ShippingOnhandCandidateSet]:
|
||||
"""按 Task 读取候选版本列表;默认隐藏 draft。"""
|
||||
if getattr(task, 'id', None) is None:
|
||||
return []
|
||||
query = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateSet)
|
||||
.filter(ShippingInventoryCandidateSet.task_id == int(task.id))
|
||||
.query(ShippingOnhandCandidateSet)
|
||||
.filter(ShippingOnhandCandidateSet.task_id == int(task.id))
|
||||
)
|
||||
if not include_drafts:
|
||||
query = query.filter(
|
||||
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
|
||||
ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
|
||||
)
|
||||
rows = (
|
||||
query.order_by(
|
||||
ShippingInventoryCandidateSet.set_version.desc(),
|
||||
ShippingInventoryCandidateSet.id.desc(),
|
||||
ShippingOnhandCandidateSet.set_version.desc(),
|
||||
ShippingOnhandCandidateSet.id.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -114,7 +114,7 @@ def get_active_candidate_set(
|
||||
task: ShippingOrderTask | ShippingNotice,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> ShippingInventoryCandidateSet | None:
|
||||
) -> ShippingOnhandCandidateSet | None:
|
||||
"""
|
||||
读取正式 Task 当前 frozen CandidateSet。
|
||||
|
||||
@@ -126,7 +126,7 @@ def get_active_candidate_set(
|
||||
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
|
||||
if candidate_set_id is None:
|
||||
return None
|
||||
row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id))
|
||||
row = _session(session).get(ShippingOnhandCandidateSet, int(candidate_set_id))
|
||||
if row is None:
|
||||
return None
|
||||
if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0):
|
||||
@@ -140,18 +140,18 @@ def get_active_candidate_sources(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateSource]:
|
||||
) -> list[ShippingOnhandCandidateSource]:
|
||||
"""读取当前 frozen Set 的任务级候选源。"""
|
||||
current = get_active_candidate_set(task, session=session)
|
||||
if current is None:
|
||||
return []
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateSource)
|
||||
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id))
|
||||
.query(ShippingOnhandCandidateSource)
|
||||
.filter(ShippingOnhandCandidateSource.candidate_set_id == int(current.id))
|
||||
.order_by(
|
||||
ShippingInventoryCandidateSource.candidate_order.asc(),
|
||||
ShippingInventoryCandidateSource.id.asc(),
|
||||
ShippingOnhandCandidateSource.candidate_order.asc(),
|
||||
ShippingOnhandCandidateSource.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -162,18 +162,18 @@ def get_active_candidate_lines(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateLine]:
|
||||
) -> list[ShippingOnhandCandidateLine]:
|
||||
"""读取当前 frozen Set 的行级候选。"""
|
||||
current = get_active_candidate_set(task, session=session)
|
||||
if current is None:
|
||||
return []
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateLine)
|
||||
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id))
|
||||
.query(ShippingOnhandCandidateLine)
|
||||
.filter(ShippingOnhandCandidateLine.candidate_set_id == int(current.id))
|
||||
.order_by(
|
||||
ShippingInventoryCandidateLine.line_no.asc(),
|
||||
ShippingInventoryCandidateLine.id.asc(),
|
||||
ShippingOnhandCandidateLine.line_no.asc(),
|
||||
ShippingOnhandCandidateLine.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -198,7 +198,7 @@ def active_inventory_runtime_facts(
|
||||
Returns:
|
||||
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
|
||||
"""
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
from app.models import ShippingTaskOnhandLink
|
||||
|
||||
sess = _session(session)
|
||||
candidate_set = get_active_candidate_set(task, session=sess)
|
||||
@@ -206,9 +206,9 @@ def active_inventory_runtime_facts(
|
||||
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
|
||||
versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()]
|
||||
link = (
|
||||
sess.query(ShippingTaskInventoryLink)
|
||||
.filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True))
|
||||
.order_by(ShippingTaskInventoryLink.id.desc())
|
||||
sess.query(ShippingTaskOnhandLink)
|
||||
.filter(ShippingTaskOnhandLink.task_id == int(task.id), ShippingTaskOnhandLink.is_active.is_(True))
|
||||
.order_by(ShippingTaskOnhandLink.id.desc())
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
)
|
||||
@@ -218,7 +218,7 @@ def active_inventory_runtime_facts(
|
||||
'source_codes': source_codes,
|
||||
'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None,
|
||||
'active_link': link,
|
||||
'inventory_file_id': getattr(link, 'inventory_file_id', None),
|
||||
'inventory_file_id': getattr(link, 'onhand_file_id', None),
|
||||
'inventory_file': getattr(link, 'inventory_file', None),
|
||||
}
|
||||
|
||||
@@ -229,26 +229,26 @@ def get_candidate_set_by_version(
|
||||
*,
|
||||
include_drafts: bool = False,
|
||||
session: Session | None = None,
|
||||
) -> ShippingInventoryCandidateSet | None:
|
||||
) -> ShippingOnhandCandidateSet | None:
|
||||
"""按 Task + set_version 读取指定候选版本。"""
|
||||
if getattr(task, 'id', None) is None:
|
||||
return None
|
||||
query = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateSet)
|
||||
.query(ShippingOnhandCandidateSet)
|
||||
.filter(
|
||||
ShippingInventoryCandidateSet.task_id == int(task.id),
|
||||
ShippingInventoryCandidateSet.set_version == int(version),
|
||||
ShippingOnhandCandidateSet.task_id == int(task.id),
|
||||
ShippingOnhandCandidateSet.set_version == int(version),
|
||||
)
|
||||
)
|
||||
if not include_drafts:
|
||||
query = query.filter(
|
||||
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
|
||||
ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
|
||||
)
|
||||
return query.order_by(ShippingInventoryCandidateSet.id.desc()).first()
|
||||
return query.order_by(ShippingOnhandCandidateSet.id.desc()).first()
|
||||
|
||||
|
||||
def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None:
|
||||
def serialize_candidate_set_summary(row: ShippingOnhandCandidateSet | None) -> dict[str, Any] | None:
|
||||
"""序列化 CandidateSet 摘要供 API / Projection 复用。"""
|
||||
if row is None:
|
||||
return None
|
||||
@@ -268,7 +268,7 @@ def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -
|
||||
}
|
||||
|
||||
|
||||
def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]:
|
||||
def serialize_candidate_source(row: ShippingOnhandCandidateSource) -> dict[str, Any]:
|
||||
"""序列化任务级候选源。"""
|
||||
return {
|
||||
'id': int(row.id),
|
||||
@@ -284,7 +284,7 @@ def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[st
|
||||
}
|
||||
|
||||
|
||||
def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]:
|
||||
def serialize_candidate_line(row: ShippingOnhandCandidateLine) -> dict[str, Any]:
|
||||
"""序列化行级候选源与稳定行标识。"""
|
||||
return {
|
||||
'candidate_line_id': int(row.id),
|
||||
@@ -300,20 +300,20 @@ def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, A
|
||||
|
||||
|
||||
def _candidate_sources_for_set(
|
||||
candidate_set: ShippingInventoryCandidateSet | None,
|
||||
candidate_set: ShippingOnhandCandidateSet | None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateSource]:
|
||||
) -> list[ShippingOnhandCandidateSource]:
|
||||
"""读取指定 CandidateSet 的任务级候选源。"""
|
||||
if candidate_set is None:
|
||||
return []
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateSource)
|
||||
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id))
|
||||
.query(ShippingOnhandCandidateSource)
|
||||
.filter(ShippingOnhandCandidateSource.candidate_set_id == int(candidate_set.id))
|
||||
.order_by(
|
||||
ShippingInventoryCandidateSource.candidate_order.asc(),
|
||||
ShippingInventoryCandidateSource.id.asc(),
|
||||
ShippingOnhandCandidateSource.candidate_order.asc(),
|
||||
ShippingOnhandCandidateSource.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -321,20 +321,20 @@ def _candidate_sources_for_set(
|
||||
|
||||
|
||||
def _candidate_lines_for_set(
|
||||
candidate_set: ShippingInventoryCandidateSet | None,
|
||||
candidate_set: ShippingOnhandCandidateSet | None,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateLine]:
|
||||
) -> list[ShippingOnhandCandidateLine]:
|
||||
"""读取指定 CandidateSet 的行级候选。"""
|
||||
if candidate_set is None:
|
||||
return []
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingInventoryCandidateLine)
|
||||
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id))
|
||||
.query(ShippingOnhandCandidateLine)
|
||||
.filter(ShippingOnhandCandidateLine.candidate_set_id == int(candidate_set.id))
|
||||
.order_by(
|
||||
ShippingInventoryCandidateLine.line_no.asc(),
|
||||
ShippingInventoryCandidateLine.id.asc(),
|
||||
ShippingOnhandCandidateLine.line_no.asc(),
|
||||
ShippingOnhandCandidateLine.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -373,15 +373,15 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str],
|
||||
return {}
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingTaskInventoryRpaAttempt)
|
||||
.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code.in_(source_codes),
|
||||
)
|
||||
.order_by(
|
||||
ShippingTaskInventoryRpaAttempt.source_code.asc(),
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
|
||||
ShippingTaskInventoryRpaAttempt.id.desc(),
|
||||
FreightRpaOnhandTaskAttempt.source_code.asc(),
|
||||
FreightRpaOnhandTaskAttempt.attempt_no.desc(),
|
||||
FreightRpaOnhandTaskAttempt.id.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -397,7 +397,7 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str],
|
||||
'run_no': str(row.run_no or ''),
|
||||
'error_code': getattr(row, 'error_code', None),
|
||||
'error_message': getattr(row, 'error_message', None),
|
||||
'inventory_file_no': getattr(row, 'inventory_file_no', None),
|
||||
'inventory_file_no': getattr(row, 'onhand_file_no', None),
|
||||
'updated_at': _iso(getattr(row, 'updated_at', None)),
|
||||
}
|
||||
return out
|
||||
@@ -419,20 +419,20 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
|
||||
return prepared, pending, failed
|
||||
|
||||
|
||||
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineOnhandMatch]:
|
||||
"""读取任务当前生效的行级匹配事实。"""
|
||||
if getattr(task, 'id', None) is None:
|
||||
return []
|
||||
rows = (
|
||||
_session(session)
|
||||
.query(ShippingNoticeLineInventoryMatch)
|
||||
.query(ShippingNoticeLineOnhandMatch)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
)
|
||||
.order_by(
|
||||
ShippingNoticeLineInventoryMatch.line_index.asc(),
|
||||
ShippingNoticeLineInventoryMatch.id.asc(),
|
||||
ShippingNoticeLineOnhandMatch.line_index.asc(),
|
||||
ShippingNoticeLineOnhandMatch.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -548,20 +548,20 @@ def project_inventory_candidate_facts(
|
||||
current_match_rows = _current_match_rows(task, session=sess)
|
||||
# [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。
|
||||
snapshot_ids = {
|
||||
int(row.inventory_snapshot_id)
|
||||
int(row.onhand_snapshot_id)
|
||||
for row in current_match_rows
|
||||
if getattr(row, 'inventory_snapshot_id', None) is not None
|
||||
if getattr(row, 'onhand_snapshot_id', None) is not None
|
||||
}
|
||||
snapshot_by_id: dict[int, Any] = {}
|
||||
if snapshot_ids:
|
||||
snapshot_by_id = {
|
||||
int(item.id): item
|
||||
for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all()
|
||||
for item in sess.query(FreightRpaOnhandReportFile).filter(FreightRpaOnhandReportFile.id.in_(snapshot_ids)).all()
|
||||
}
|
||||
for row in current_match_rows:
|
||||
snapshot = (
|
||||
snapshot_by_id.get(int(row.inventory_snapshot_id))
|
||||
if getattr(row, 'inventory_snapshot_id', None) is not None else None
|
||||
snapshot_by_id.get(int(row.onhand_snapshot_id))
|
||||
if getattr(row, 'onhand_snapshot_id', None) is not None else None
|
||||
)
|
||||
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
|
||||
serialized = {
|
||||
@@ -577,11 +577,11 @@ def project_inventory_candidate_facts(
|
||||
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
|
||||
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
|
||||
'resolved_inventory_source_code': (
|
||||
getattr(row, 'inventory_source_code', None)
|
||||
getattr(row, 'source_code', None)
|
||||
or (allowed_codes[0] if len(allowed_codes) == 1 else None)
|
||||
),
|
||||
'inventory_file_no': getattr(row, 'matched_file_no', None),
|
||||
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
|
||||
'inventory_snapshot_id': getattr(row, 'onhand_snapshot_id', None),
|
||||
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
|
||||
'inventory_file_sha256': (
|
||||
dict(getattr(row, 'detail_json', None) or {}).get('file_sha256')
|
||||
@@ -619,9 +619,9 @@ def project_inventory_candidate_facts(
|
||||
'operation_id': f'match-line:{int(row.id)}',
|
||||
}
|
||||
elif (
|
||||
str(getattr(row, 'inventory_source_code', '') or '').strip().upper()
|
||||
str(getattr(row, 'source_code', '') or '').strip().upper()
|
||||
and allowed_codes
|
||||
and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes
|
||||
and str(getattr(row, 'source_code', '') or '').strip().upper() not in allowed_codes
|
||||
):
|
||||
out_of_scope_details = {
|
||||
'candidate_line_id': int(candidate_line_id),
|
||||
@@ -631,7 +631,7 @@ def project_inventory_candidate_facts(
|
||||
'actual_candidate_set_version': getattr(row, 'candidate_set_version', None),
|
||||
'detected_at': datetime.utcnow().isoformat(),
|
||||
'operation_id': f'match-line:{int(row.id)}',
|
||||
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
|
||||
'resolved_inventory_source_code': getattr(row, 'source_code', None),
|
||||
'allowed_source_codes_snapshot': allowed_codes,
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_combination_fingerprint.py
|
||||
services/shipping_notice/onhand_combination_fingerprint.py
|
||||
|
||||
用途:为多源库存准备轮次生成稳定组合输入指纹。
|
||||
依赖:标准库 hashlib/json。
|
||||
+127
-106
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_configuration_test.py
|
||||
services/shipping_notice/onhand_configuration_test.py
|
||||
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。
|
||||
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
|
||||
@@ -16,17 +16,18 @@ from flask import current_app
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryValidationBatch,
|
||||
FreightRpaOnhandConfigurationTestRun,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
FreightRpaOnhandValidationBatch,
|
||||
)
|
||||
|
||||
|
||||
def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
def _payload(run: FreightRpaOnhandConfigurationTestRun) -> dict[str, Any]:
|
||||
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
|
||||
return {
|
||||
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
|
||||
'id': run.id, 'run_no': run.run_no, 'source_id': run.source_id,
|
||||
'validation_batch_id': run.validation_batch_id, 'rpa_batch_run_no': run.rpa_batch_run_no,
|
||||
'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
'status': run.status, 'stage': run.stage,
|
||||
@@ -36,10 +37,10 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _batch_payload(batch: ShippingInventoryValidationBatch) -> dict[str, Any]:
|
||||
def _batch_payload(batch: FreightRpaOnhandValidationBatch) -> dict[str, Any]:
|
||||
"""投影批量验证进度及其逐站点运行,供管理端按批次轮询。"""
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by(
|
||||
ShippingInventoryConfigurationTestRun.id.asc(),
|
||||
runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by(
|
||||
FreightRpaOnhandConfigurationTestRun.id.asc(),
|
||||
).all()
|
||||
return {
|
||||
'id': batch.id, 'batch_no': batch.batch_no, 'status': batch.status,
|
||||
@@ -57,10 +58,10 @@ def _refresh_batch(batch_id: int | None) -> None:
|
||||
"""按逐站点终态重算批次汇总;一个站点失败绝不覆盖其他站点结果。"""
|
||||
if not batch_id:
|
||||
return
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
return
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all()
|
||||
runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all()
|
||||
terminal = {'completed', 'completed_empty', 'failed'}
|
||||
batch.total_count = len(runs)
|
||||
batch.success_count = sum(run.status == 'completed' for run in runs)
|
||||
@@ -84,58 +85,61 @@ def _refresh_batch(batch_id: int | None) -> None:
|
||||
batch.completed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _validate_batch_sources(source_ids: list[int]) -> list[ShippingInventorySource]:
|
||||
def _validate_batch_sources(source_ids: list[int]) -> list[FreightRpaSource]:
|
||||
"""预检批量验证站点,强制使用已发布解析定义以明确空库存的业务语义。"""
|
||||
ids: list[int] = []
|
||||
for source_id in source_ids:
|
||||
try:
|
||||
value = int(source_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
|
||||
raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED')
|
||||
if value > 0 and value not in ids:
|
||||
ids.append(value)
|
||||
if not ids:
|
||||
raise ValidationError('At least one inventory source is required', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED')
|
||||
sources = ShippingInventorySource.query.filter(ShippingInventorySource.id.in_(ids)).all()
|
||||
raise ValidationError('At least one inventory source is required', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED')
|
||||
sources = FreightRpaSource.query.filter(FreightRpaSource.id.in_(ids)).all()
|
||||
by_id = {source.id: source for source in sources}
|
||||
if len(by_id) != len(ids):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
ordered = [by_id[source_id] for source_id in ids]
|
||||
for source in ordered:
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID')
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。
|
||||
config = source.onhand_report_config
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
_expire_timed_out_runs(source)
|
||||
active = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
active = FreightRpaOnhandConfigurationTestRun.query.filter(
|
||||
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
|
||||
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).first()
|
||||
if active:
|
||||
raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_ACTIVE')
|
||||
raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_ACTIVE')
|
||||
return ordered
|
||||
|
||||
|
||||
def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retry_of_batch_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。"""
|
||||
sources = _validate_batch_sources(source_ids)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
||||
batch = ShippingInventoryValidationBatch(
|
||||
batch = FreightRpaOnhandValidationBatch(
|
||||
batch_no=f'CONFIG-BATCH-{stamp}', status='queued', total_count=len(sources), created_by=actor_id,
|
||||
retry_of_batch_id=retry_of_batch_id,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
grouped: dict[tuple[int, str], list[tuple[ShippingInventoryConfigurationTestRun, dict[str, Any]]]] = {}
|
||||
grouped: dict[tuple[int, str], list[tuple[FreightRpaOnhandConfigurationTestRun, dict[str, Any]]]] = {}
|
||||
for source in sources:
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run = FreightRpaOnhandConfigurationTestRun(
|
||||
run_no=f'CONFIG-{source.source_code}-{stamp}-{source.id}', validation_batch_id=batch.id,
|
||||
inventory_source_id=source.id,
|
||||
source_id=source.id,
|
||||
source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
|
||||
)
|
||||
@@ -143,7 +147,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
|
||||
db.session.flush()
|
||||
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
|
||||
if source_payload is None:
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
source_payload = {**source_payload, 'validation_run_no': run.run_no}
|
||||
grouped.setdefault((source.rpa_profile_id, source.connector_type), []).append((run, source_payload))
|
||||
db.session.commit()
|
||||
@@ -171,11 +175,11 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
|
||||
|
||||
def get_validation_batch(batch_id: int) -> dict[str, Any]:
|
||||
"""返回批量验证当前汇总与逐站点结果,读取时同时收口超时任务。"""
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
for run in ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all():
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
|
||||
for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all():
|
||||
source = db.session.get(FreightRpaSource, run.source_id)
|
||||
if source is not None:
|
||||
_expire_timed_out_runs(source)
|
||||
_refresh_batch(batch.id)
|
||||
@@ -185,26 +189,26 @@ def get_validation_batch(batch_id: int) -> dict[str, Any]:
|
||||
|
||||
def get_latest_active_validation_batch() -> dict[str, Any] | None:
|
||||
"""恢复最近仍在执行的批量验证,供管理端刷新后继续查看真实进度。"""
|
||||
batch = ShippingInventoryValidationBatch.query.filter(
|
||||
ShippingInventoryValidationBatch.status.in_(['queued', 'running']),
|
||||
).order_by(ShippingInventoryValidationBatch.id.desc()).first()
|
||||
batch = FreightRpaOnhandValidationBatch.query.filter(
|
||||
FreightRpaOnhandValidationBatch.status.in_(['queued', 'running']),
|
||||
).order_by(FreightRpaOnhandValidationBatch.id.desc()).first()
|
||||
return get_validation_batch(batch.id) if batch is not None else None
|
||||
|
||||
|
||||
def retry_failed_validation_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""仅重新投递失败或配置已变更的站点,已成功及空库存站点不重复执行。"""
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
failed_ids = [run.inventory_source_id for run in ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
|
||||
failed_ids = [run.source_id for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(
|
||||
validation_batch_id=batch.id, status='failed',
|
||||
).all()]
|
||||
if not failed_ids:
|
||||
raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NO_FAILURE')
|
||||
raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.ONHAND_VALIDATION_BATCH_NO_FAILURE')
|
||||
return start_batch_test_export(failed_ids, actor_id=actor_id, retry_of_batch_id=batch.id)
|
||||
|
||||
|
||||
def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool:
|
||||
def _matches_current_configuration(run: FreightRpaOnhandConfigurationTestRun, source: FreightRpaSource) -> bool:
|
||||
"""判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。"""
|
||||
return bool(
|
||||
source.rpa_profile
|
||||
@@ -213,23 +217,23 @@ def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, s
|
||||
)
|
||||
|
||||
|
||||
def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
def _expire_timed_out_runs(source: FreightRpaSource) -> None:
|
||||
"""按批量队列长度延长等待窗口,避免串行站点被单站超时误判。
|
||||
|
||||
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
|
||||
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
|
||||
"""
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS']))
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
runs = FreightRpaOnhandConfigurationTestRun.query.filter(
|
||||
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
|
||||
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).all()
|
||||
for run in runs:
|
||||
multiplier = 1
|
||||
if run.validation_batch_id:
|
||||
same_worker_queue = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.validation_batch_id == run.validation_batch_id,
|
||||
ShippingInventoryConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no,
|
||||
same_worker_queue = FreightRpaOnhandConfigurationTestRun.query.filter(
|
||||
FreightRpaOnhandConfigurationTestRun.validation_batch_id == run.validation_batch_id,
|
||||
FreightRpaOnhandConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no,
|
||||
).count()
|
||||
multiplier = max(1, same_worker_queue)
|
||||
deadline = datetime.utcnow() - timedelta(seconds=timeout * multiplier)
|
||||
@@ -243,43 +247,43 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
|
||||
def get_latest_test_run(source_id: int) -> dict[str, Any] | None:
|
||||
"""返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
_expire_timed_out_runs(source)
|
||||
db.session.commit()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
|
||||
source_id=source.id,
|
||||
source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first()
|
||||
return _payload(run) if run else None
|
||||
|
||||
|
||||
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID')
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
|
||||
_expire_timed_out_runs(source)
|
||||
active = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
|
||||
ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
active = FreightRpaOnhandConfigurationTestRun.query.filter(
|
||||
FreightRpaOnhandConfigurationTestRun.source_id == source.id,
|
||||
FreightRpaOnhandConfigurationTestRun.source_config_version == source.config_version,
|
||||
FreightRpaOnhandConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
|
||||
FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first()
|
||||
if active:
|
||||
return _payload(active)
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
|
||||
run = FreightRpaOnhandConfigurationTestRun(
|
||||
run_no=run_no, source_id=source.id, source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
|
||||
)
|
||||
@@ -287,7 +291,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
db.session.flush()
|
||||
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
|
||||
if source_payload is None:
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
try:
|
||||
trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={
|
||||
'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id,
|
||||
@@ -297,7 +301,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
raise
|
||||
if not trigger:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE')
|
||||
raise ConflictError('RPA Worker is not ready', code='SHIPPING.ONHAND_CONFIGURATION_TEST_UNAVAILABLE')
|
||||
run.result_json = {'trigger_written': True}
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
@@ -305,12 +309,12 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
|
||||
def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
|
||||
"""读取指定库存站点的测试运行,防止跨站点查看结果。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source_id, run_no=str(run_no or '').strip(),
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
|
||||
source_id=source_id, run_no=str(run_no or '').strip(),
|
||||
).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is not None:
|
||||
_expire_timed_out_runs(source)
|
||||
db.session.commit()
|
||||
@@ -320,12 +324,12 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
|
||||
def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。"""
|
||||
run_no = str(payload.get('run_no') or '').strip()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status in {'completed', 'completed_empty', 'failed'}:
|
||||
return _payload(run)
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
source = db.session.get(FreightRpaSource, run.source_id)
|
||||
if source is None or not _matches_current_configuration(run, source):
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
|
||||
run.result_json = {**(run.result_json or {}), 'stale_configuration': True}
|
||||
@@ -335,7 +339,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status = str(payload.get('status') or 'success').lower()
|
||||
if status == 'empty':
|
||||
# 空库存是查询业务结果,不代表登录、报表路径或 RPA 执行失败。
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。
|
||||
config = source.onhand_report_config
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None or profile.status != 'published':
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出无库存数据,且尚未绑定已发布库存解析方案'; run.completed_at = datetime.utcnow()
|
||||
else:
|
||||
run.status = 'completed_empty'; run.stage = 'empty_data_pending_validation'
|
||||
@@ -343,8 +350,8 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'export_result': 'empty', 'structure_validation': 'not_observed',
|
||||
'data_validation': 'pending_first_non_empty_export',
|
||||
'message': str(payload.get('message') or '库存查询成功但当前无库存数据')[:500],
|
||||
'confirmed_profile_id': source.parsing_profile_id,
|
||||
'confirmed_profile_checksum': source.parsing_profile.checksum,
|
||||
'confirmed_profile_id': profile.id,
|
||||
'confirmed_profile_checksum': profile.checksum,
|
||||
}
|
||||
run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
@@ -370,12 +377,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, serialize_analysis
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.models import ShippingInventoryStructureAnalysis
|
||||
from app.services.shipping_notice.onhand_structure_analysis import _analyse_path, serialize_analysis
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
|
||||
from app.models import FreightRpaOnhandStructureAnalysis
|
||||
import hashlib
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
|
||||
|
||||
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
|
||||
suffix = resolve_inventory_upload_suffix(path.name)
|
||||
@@ -384,7 +391,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy.
|
||||
structure, suggested, summary, warnings = _analyse_path(path, suffix)
|
||||
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
|
||||
analysis = ShippingInventoryStructureAnalysis(
|
||||
analysis = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
|
||||
validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by,
|
||||
@@ -392,18 +399,22 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
db.session.add(analysis); db.session.flush()
|
||||
analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint})
|
||||
# s18 起当前绑定取自 onhand_report_config 配置行;配置行缺失即无当前方案可比。
|
||||
config = source.onhand_report_config
|
||||
current_profile_id = config.parsing_profile_id if config is not None else None
|
||||
current_profile_candidate = next((
|
||||
candidate for candidate in (analysis.match_result_json.get('candidates') or [])
|
||||
if int(candidate.get('profile_id') or 0) == int(source.parsing_profile_id or 0)
|
||||
if int(candidate.get('profile_id') or 0) == int(current_profile_id or 0)
|
||||
), None)
|
||||
run.analysis_id = analysis.id; run.status = 'completed'
|
||||
if current_profile_candidate is not None:
|
||||
# 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。
|
||||
current_profile = config.parsing_profile if config is not None else None
|
||||
run.stage = 'current_profile_verified'
|
||||
run.result_json = {
|
||||
'analysis': serialize_analysis(analysis),
|
||||
'confirmed_profile_id': source.parsing_profile_id,
|
||||
'confirmed_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None,
|
||||
'confirmed_profile_id': current_profile_id,
|
||||
'confirmed_profile_checksum': current_profile.checksum if current_profile is not None else None,
|
||||
'current_profile_verified': True,
|
||||
'profile_match_level': current_profile_candidate.get('level'),
|
||||
}
|
||||
@@ -421,12 +432,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""接收批量 Worker 回调并逐项回写;未知运行标识只忽略,不影响同批其他站点。"""
|
||||
batch_id = int(payload.get('validation_batch_id') or 0)
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
|
||||
results = payload.get('results') or []
|
||||
if not isinstance(results, list):
|
||||
raise ValidationError('Batch results must be a list', code='SHIPPING.INVENTORY_VALIDATION_BATCH_INVALID')
|
||||
raise ValidationError('Batch results must be a list', code='SHIPPING.ONHAND_VALIDATION_BATCH_INVALID')
|
||||
updated: list[dict[str, Any]] = []
|
||||
ignored = 0
|
||||
for item in results:
|
||||
@@ -434,7 +445,7 @@ def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
ignored += 1
|
||||
continue
|
||||
run_no = str(item.get('validation_run_no') or '').strip()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
|
||||
run_no=run_no, validation_batch_id=batch.id,
|
||||
).first()
|
||||
if run is None:
|
||||
@@ -459,22 +470,22 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
batch_id = int(payload.get('validation_batch_id') or 0)
|
||||
run_no = str(payload.get('validation_run_no') or '').strip()
|
||||
if not batch_id or not run_no:
|
||||
raise ValidationError('Batch id and validation run number are required', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
|
||||
batch = db.session.get(ShippingInventoryValidationBatch, batch_id)
|
||||
raise ValidationError('Batch id and validation run number are required', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID')
|
||||
batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND')
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND')
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(
|
||||
run_no=run_no, validation_batch_id=batch.id,
|
||||
).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status in {'completed', 'completed_empty', 'failed'}:
|
||||
return _payload(run)
|
||||
|
||||
# 仅接受 Worker 领取后的执行阶段,防止外部回调任意覆盖运行状态。
|
||||
stage = str(payload.get('stage') or 'rpa_exporting').strip().lower()
|
||||
if stage not in {'rpa_exporting'}:
|
||||
raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID')
|
||||
raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID')
|
||||
run.status = 'processing'
|
||||
run.stage = stage
|
||||
run.result_json = {**(run.result_json or {}), 'worker_claimed_at': datetime.utcnow().isoformat()}
|
||||
@@ -485,28 +496,38 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first()
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=source_id, run_no=run_no).first()
|
||||
if run is None or run.status != 'completed' or run.analysis_id is None:
|
||||
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY')
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_READY')
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if source is None or profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
if (
|
||||
source.enabled
|
||||
or source.config_version != run.source_config_version
|
||||
or source.rpa_profile is None
|
||||
or source.rpa_profile.config_version != run.rpa_profile_config_version
|
||||
):
|
||||
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
|
||||
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
|
||||
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.ONHAND_CONFIGURATION_TEST_STALE')
|
||||
from app.services.shipping_notice.onhand_structure_analysis import adopt_published_profile
|
||||
|
||||
adopt_published_profile(run.analysis_id, profile_id)
|
||||
source.parsing_profile_id = profile.id
|
||||
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键;
|
||||
# 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.parsing_profile_id = profile.id
|
||||
config.updated_by = actor_id
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
run.source_config_version = source.config_version
|
||||
run.rpa_profile_config_version = source.rpa_profile.config_version
|
||||
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
|
||||
db.session.commit()
|
||||
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
|
||||
return {'test_run': _payload(run), 'parsing_profile_id': config.parsing_profile_id}
|
||||
+6
-6
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_external_mapping.py
|
||||
services/shipping_notice/onhand_external_mapping.py
|
||||
|
||||
用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。
|
||||
依赖:ShippingInventoryExternalMapping、ShippingInventorySource。
|
||||
依赖:FreightRpaOnhandExternalMapping、FreightRpaSource。
|
||||
逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
|
||||
|
||||
|
||||
def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None:
|
||||
@@ -19,12 +19,12 @@ def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id:
|
||||
warehouse = str(freight_warehouse_id or '').strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=code, enabled=True).first()
|
||||
if source is None:
|
||||
return None
|
||||
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
|
||||
query = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id, enabled=True)
|
||||
mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None
|
||||
mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first()
|
||||
mapping = mapping or query.filter(FreightRpaOnhandExternalMapping.freight_warehouse_id.is_(None)).first()
|
||||
if mapping is None:
|
||||
return None
|
||||
return {
|
||||
+30
-30
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_field_catalog.py
|
||||
services/shipping_notice/onhand_field_catalog.py
|
||||
|
||||
用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。
|
||||
依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。
|
||||
依赖:FreightRpaOnhandField、统一业务异常和 SQLAlchemy 事务。
|
||||
逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。
|
||||
"""
|
||||
|
||||
@@ -14,14 +14,14 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile
|
||||
from app.models import ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaParsingProfile
|
||||
|
||||
|
||||
ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'}
|
||||
ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'}
|
||||
|
||||
|
||||
def _payload(item: ShippingInventoryField) -> dict[str, Any]:
|
||||
def _payload(item: FreightRpaOnhandField) -> dict[str, Any]:
|
||||
"""输出业务字段目录记录,不向管理端暴露内部字段编码。"""
|
||||
return {
|
||||
'id': item.id,
|
||||
@@ -38,15 +38,15 @@ def _payload(item: ShippingInventoryField) -> dict[str, Any]:
|
||||
|
||||
def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]:
|
||||
"""按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。"""
|
||||
query = ShippingInventoryField.query
|
||||
query = FreightRpaOnhandField.query
|
||||
if not include_retired:
|
||||
query = query.filter_by(status='active')
|
||||
return [_payload(item) for item in query.order_by(
|
||||
ShippingInventoryField.sort_order, ShippingInventoryField.id,
|
||||
FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id,
|
||||
).all()]
|
||||
|
||||
|
||||
def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]:
|
||||
def _normalized_payload(data: dict[str, Any], *, existing: FreightRpaOnhandField | None = None) -> dict[str, Any]:
|
||||
"""校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。"""
|
||||
display_name = str(data.get('display_name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
@@ -55,11 +55,11 @@ def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryFiel
|
||||
try:
|
||||
sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') from exc
|
||||
if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES:
|
||||
raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
|
||||
raise ValidationError('Inventory field data is invalid', code='SHIPPING.ONHAND_FIELD_INVALID')
|
||||
if sort_order < 0 or sort_order > 9999:
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID')
|
||||
return {
|
||||
'display_name': display_name,
|
||||
'description': description,
|
||||
@@ -78,7 +78,7 @@ def _field_code(display_name: str) -> str:
|
||||
stem = stem[:52]
|
||||
code = stem
|
||||
sequence = 2
|
||||
while ShippingInventoryField.query.filter_by(field_code=code).first() is not None:
|
||||
while FreightRpaOnhandField.query.filter_by(field_code=code).first() is not None:
|
||||
suffix = f'_{sequence}'
|
||||
code = f'{stem[:64 - len(suffix)]}{suffix}'
|
||||
sequence += 1
|
||||
@@ -88,9 +88,9 @@ def _field_code(display_name: str) -> str:
|
||||
def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。"""
|
||||
values = _normalized_payload(data)
|
||||
if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None:
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
|
||||
item = ShippingInventoryField(
|
||||
if FreightRpaOnhandField.query.filter_by(display_name=values['display_name']).first() is not None:
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT')
|
||||
item = FreightRpaOnhandField(
|
||||
field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id,
|
||||
**values,
|
||||
)
|
||||
@@ -101,24 +101,24 @@ def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any
|
||||
|
||||
def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
item = db.session.get(FreightRpaOnhandField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
|
||||
if item.status != 'active':
|
||||
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE')
|
||||
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.ONHAND_FIELD_IMMUTABLE')
|
||||
values = _normalized_payload(data, existing=item)
|
||||
references = _runtime_references(item.id)
|
||||
if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type):
|
||||
raise ConflictError(
|
||||
'Referenced inventory field type or usage cannot be changed',
|
||||
code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references},
|
||||
code='SHIPPING.ONHAND_FIELD_IMMUTABLE', details={'references': references},
|
||||
)
|
||||
duplicate = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.display_name == values['display_name'],
|
||||
ShippingInventoryField.id != item.id,
|
||||
duplicate = FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.display_name == values['display_name'],
|
||||
FreightRpaOnhandField.id != item.id,
|
||||
).first()
|
||||
if duplicate is not None:
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT')
|
||||
for key, value in values.items():
|
||||
setattr(item, key, value)
|
||||
item.updated_by = actor_id
|
||||
@@ -128,14 +128,14 @@ def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -
|
||||
|
||||
def delete_field(field_id: int) -> dict[str, Any]:
|
||||
"""物理删除从未被配置引用的用户字段。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
item = db.session.get(FreightRpaOnhandField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
|
||||
references = _runtime_references(item.id)
|
||||
if references:
|
||||
raise ConflictError(
|
||||
'Inventory field is referenced by runtime configuration',
|
||||
code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references},
|
||||
code='SHIPPING.ONHAND_FIELD_DELETE_BLOCKED', details={'references': references},
|
||||
)
|
||||
db.session.delete(item)
|
||||
db.session.commit()
|
||||
@@ -144,14 +144,14 @@ def delete_field(field_id: int) -> dict[str, Any]:
|
||||
|
||||
def retire_field(field_id: int) -> dict[str, Any]:
|
||||
"""退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
item = db.session.get(FreightRpaOnhandField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND')
|
||||
references = _runtime_references(item.id)
|
||||
if references:
|
||||
raise ConflictError(
|
||||
'Inventory field is referenced by runtime configuration',
|
||||
code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references},
|
||||
code='SHIPPING.ONHAND_FIELD_RETIRE_BLOCKED', details={'references': references},
|
||||
)
|
||||
item.status = 'retired'
|
||||
db.session.commit()
|
||||
@@ -163,8 +163,8 @@ def _runtime_references(field_id: int) -> list[str]:
|
||||
reference = str(field_id)
|
||||
parsing_profiles = [
|
||||
f'parsing_profile:{item.profile_code}:v{item.version}'
|
||||
for item in ShippingInventoryParsingProfile.query.filter(
|
||||
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
|
||||
for item in FreightRpaParsingProfile.query.filter(
|
||||
FreightRpaParsingProfile.status.in_(['draft', 'published']),
|
||||
).all()
|
||||
if reference in {
|
||||
str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys()
|
||||
+6
-6
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_file_identity.py
|
||||
services/shipping_notice/onhand_file_identity.py
|
||||
|
||||
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
|
||||
依赖:openpyxl、xlrd、csv、app.core.errors.AppError。
|
||||
@@ -301,7 +301,7 @@ def assert_inventory_excel_warehouse_identity(
|
||||
expected = str(expected_warehouse_id or "").strip().upper()
|
||||
if not expected:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
|
||||
message="预期库位为空,无法校验库存文件内容",
|
||||
http_status=409,
|
||||
details={"operation": operation},
|
||||
@@ -310,7 +310,7 @@ def assert_inventory_excel_warehouse_identity(
|
||||
suffix = path.suffix.lower()
|
||||
if suffix not in {".xls", ".xlsx", ".csv"}:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存源身份校验仅支持 .xls / .xlsx / .csv",
|
||||
http_status=409,
|
||||
details={"operation": operation, "file_suffix": suffix},
|
||||
@@ -319,14 +319,14 @@ def assert_inventory_excel_warehouse_identity(
|
||||
found = extract_warehouse_ids_from_inventory_excel(path)
|
||||
if not found:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING",
|
||||
code="SHIPPING.ONHAND_FILE_WAREHOUSE_MISSING",
|
||||
message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库",
|
||||
http_status=409,
|
||||
details={"operation": operation, "expected_warehouse_id": expected},
|
||||
)
|
||||
if len(found) > 1:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED",
|
||||
code="SHIPPING.ONHAND_FILE_WAREHOUSE_MIXED",
|
||||
message="库存文件包含多个 Warehouse ID,已拒绝入库",
|
||||
http_status=409,
|
||||
details={
|
||||
@@ -338,7 +338,7 @@ def assert_inventory_excel_warehouse_identity(
|
||||
actual = next(iter(found))
|
||||
if actual != expected:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
|
||||
message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库",
|
||||
http_status=409,
|
||||
details={
|
||||
+73
-68
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_file_store.py
|
||||
services/shipping_notice/onhand_file_store.py
|
||||
|
||||
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影;构造下载展示名
|
||||
(build_inventory_download_name:企微压缩包短名规则 + exported_at 数据截止时间点)。
|
||||
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
|
||||
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
|
||||
依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读/查询取回,禁止构造)、
|
||||
freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_snapshot、export._storage_root。
|
||||
逻辑:onhand_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
|
||||
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
|
||||
冻结候选读所属 OT 的 prepare 合并行(传入 Notice 时回源 order_task_id),单源读 active Link 文件;
|
||||
禁止用 Notice.id 漏读 OT Link,导出数据源不得偏离行级匹配门禁命中的候选事实。
|
||||
@@ -25,24 +26,25 @@ from werkzeug.datastructures import FileStorage
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
from app.services.freight_rpa.onhand.report_store import insert_onhand_report, update_onhand_report
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
from app.services.shipping_notice.onhand_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
@@ -79,7 +81,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
|
||||
name = str(filename or "").strip().lower()
|
||||
if not name or "." not in name:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传缺少可识别的文件后缀",
|
||||
http_status=409,
|
||||
)
|
||||
@@ -90,7 +92,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
|
||||
if name.endswith(".xls"):
|
||||
return ".xls"
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传仅支持 .xls / .xlsx / .csv",
|
||||
http_status=409,
|
||||
)
|
||||
@@ -145,11 +147,11 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
|
||||
def active_inventory_file_for_task(task: ShippingNotice) -> FreightRpaOnhandReportFile | None:
|
||||
"""
|
||||
读取任务当前 active link 指向的库存快照。
|
||||
|
||||
核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入
|
||||
核心逻辑:``ShippingTaskOnhandLink.task_id`` 挂在正式 OT 上;传入
|
||||
``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。
|
||||
|
||||
Args:
|
||||
@@ -163,12 +165,12 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
|
||||
if task_id is None:
|
||||
return None
|
||||
link = (
|
||||
ShippingTaskInventoryLink.query.filter_by(
|
||||
ShippingTaskOnhandLink.query.filter_by(
|
||||
task_id=int(task_id),
|
||||
is_active=True,
|
||||
invalidated_at=None,
|
||||
)
|
||||
.order_by(ShippingTaskInventoryLink.id.desc())
|
||||
.order_by(ShippingTaskOnhandLink.id.desc())
|
||||
.first()
|
||||
)
|
||||
return link.inventory_file if link else None
|
||||
@@ -208,7 +210,7 @@ _DOWNLOAD_NAME_SANITIZE_RE = re.compile(r'[^\w.\-]+')
|
||||
|
||||
|
||||
def build_inventory_download_name(
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
*,
|
||||
source_file_name: str | None,
|
||||
path: Path | None = None,
|
||||
@@ -235,7 +237,7 @@ def build_inventory_download_name(
|
||||
base = str(source_file_name or '').strip()
|
||||
if not base:
|
||||
suffix = Path(path or base).suffix or '.xlsx'
|
||||
return f'{inv_file.inventory_file_no}{suffix.lower()}'
|
||||
return f'{inv_file.onhand_file_no}{suffix.lower()}'
|
||||
if _DOWNLOAD_CANONICAL_RE.match(base):
|
||||
return base
|
||||
seq_match = _DOWNLOAD_SEQ_PREFIX_RE.match(base)
|
||||
@@ -274,10 +276,10 @@ def build_inventory_download_name(
|
||||
return "_".join(tokens) + suffix.lower()
|
||||
|
||||
|
||||
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
def read_inventory_file_lines(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
|
||||
cached_rows = [
|
||||
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
|
||||
row for row in (inv_file.onhand_lines_json or []) if isinstance(row, dict)
|
||||
]
|
||||
if cached_rows:
|
||||
return cached_rows, {'source': 'inventory_file_cache'}
|
||||
@@ -285,7 +287,7 @@ def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dic
|
||||
rows, column_meta = parse_inventory_snapshot_file(inv_file)
|
||||
rows = [row for row in rows if isinstance(row, dict)]
|
||||
if rows:
|
||||
inv_file.inventory_lines_json = rows
|
||||
inv_file.onhand_lines_json = rows
|
||||
inv_file.line_count = len(rows)
|
||||
db.session.flush()
|
||||
return rows, column_meta
|
||||
@@ -311,7 +313,7 @@ def resolve_inventory_lines_for_execution(
|
||||
"""
|
||||
解析库存匹配与导出的统一运行输入。
|
||||
|
||||
核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源
|
||||
核心逻辑:已冻结候选源时优先 ``prepare_candidate_onhand_lines`` 合并各源
|
||||
ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File;
|
||||
否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。
|
||||
|
||||
@@ -326,19 +328,19 @@ def resolve_inventory_lines_for_execution(
|
||||
# Notice 主键 ≠ OT 且不带候选集指针;冻结候选事实统一回源所属 OT 读取,
|
||||
# 防止导出路径把多源任务退化成单源 Link,出现「行匹配过门禁但生成 Excel 失败」。
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
from app.services.shipping_notice.stp_onhand_freeze import (
|
||||
task_frozen_onhand_source_codes,
|
||||
)
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
prepare_candidate_inventory_lines,
|
||||
from app.services.shipping_notice.stp_line_onhand_match import (
|
||||
prepare_candidate_onhand_lines,
|
||||
)
|
||||
|
||||
owner_task = task
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id:
|
||||
owner_task = db.session.get(ShippingOrderTask, int(order_task_id)) or task
|
||||
if len(task_frozen_inventory_source_codes(owner_task)) >= 1:
|
||||
prep = prepare_candidate_inventory_lines(owner_task)
|
||||
if len(task_frozen_onhand_source_codes(owner_task)) >= 1:
|
||||
prep = prepare_candidate_onhand_lines(owner_task)
|
||||
if prep.get('status') == 'ready':
|
||||
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
|
||||
if rows:
|
||||
@@ -373,12 +375,12 @@ def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineOnhandMatch]:
|
||||
"""读取 OT 当前有效的行级库存匹配事实。"""
|
||||
task_id = getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return []
|
||||
return ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
return ShippingNoticeLineOnhandMatch.query.filter_by(
|
||||
task_id=int(task_id), is_current=True,
|
||||
).all()
|
||||
|
||||
@@ -428,7 +430,7 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) ->
|
||||
)
|
||||
|
||||
|
||||
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
|
||||
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> FreightRpaOnhandReportFile:
|
||||
"""
|
||||
保存库存 Excel 并创建任务级库存快照。
|
||||
|
||||
@@ -438,7 +440,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
code="SHIPPING.ONHAND_SOURCE_GATE_BLOCKED",
|
||||
message="库存源尚未稳定,拒绝保存库存上传文件",
|
||||
http_status=409,
|
||||
)
|
||||
@@ -454,7 +456,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
upload.save(str(path))
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
|
||||
|
||||
structure_check = validate_production_inventory_structure(source_code=source_code, path=path)
|
||||
inventory_lines, column_meta = parse_inventory_excel_with_meta(
|
||||
@@ -475,7 +477,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
})
|
||||
if not inventory_lines:
|
||||
raise AppError(
|
||||
code='SHIPPING.INVENTORY_FILE_EMPTY',
|
||||
code='SHIPPING.ONHAND_FILE_EMPTY',
|
||||
message='库存文件没有可用于匹配的有效库存数据',
|
||||
http_status=409,
|
||||
)
|
||||
@@ -502,8 +504,10 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
pass
|
||||
raise
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
# [STEP] 阶段 B Task 5:快照行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
|
||||
# 本模块拿回 file_id 后按主键取回 ORM 对象,身份校验失败回滚删除仍按 ORM 行操作。
|
||||
saved_file_id = insert_onhand_report(
|
||||
onhand_file_no=inventory_file_no,
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(upload.filename or "").strip() or path.name,
|
||||
storage_path=str(path),
|
||||
@@ -511,7 +515,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
schema_preview_json=preview,
|
||||
share_mode="task_only",
|
||||
line_count=len(inventory_lines),
|
||||
inventory_lines_json=inventory_lines,
|
||||
onhand_lines_json=inventory_lines,
|
||||
field_mapping_json=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
mapping_confirmed=True,
|
||||
@@ -526,8 +530,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
snapshot_status="ready",
|
||||
exported_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id)
|
||||
|
||||
candidates = [task]
|
||||
linked_tasks = [
|
||||
@@ -535,9 +538,9 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
for item in candidates
|
||||
if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item)
|
||||
]
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
from app.services.shipping_notice.onhand_snapshot_store import link_snapshot_to_task
|
||||
|
||||
created_links: list[ShippingTaskInventoryLink] = []
|
||||
created_links: list[ShippingTaskOnhandLink] = []
|
||||
for item in linked_tasks:
|
||||
link = link_snapshot_to_task(
|
||||
item,
|
||||
@@ -561,13 +564,14 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
"failed to delete inventory upload after link failure %s", path
|
||||
)
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
code="SHIPPING.ONHAND_IDENTITY_MISMATCH",
|
||||
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定",
|
||||
http_status=409,
|
||||
)
|
||||
created_links.append(link)
|
||||
if len(linked_tasks) > 1:
|
||||
inv_file.share_mode = "batch_same_identity"
|
||||
# [STEP] 阶段 B Task 5:多票同身份共用时改写 share_mode 也经 report_store 更新(同一 ORM 对象,行为不变)。
|
||||
update_onhand_report(inv_file.id, share_mode="batch_same_identity")
|
||||
return inv_file
|
||||
|
||||
|
||||
@@ -576,13 +580,13 @@ def save_task_inventory_file_from_local_path(
|
||||
source_path: str | Path,
|
||||
*,
|
||||
source_file_name: str | None = None,
|
||||
) -> ShippingInventoryFile:
|
||||
) -> FreightRpaOnhandReportFile:
|
||||
"""
|
||||
将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。
|
||||
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。
|
||||
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 FreightRpaOnhandReportFile 记录时调用。
|
||||
|
||||
核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview,
|
||||
再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。
|
||||
再创建 task_only 的 FreightRpaOnhandReportFile 与 active ShippingTaskOnhandLink。
|
||||
|
||||
Args:
|
||||
task: 当前发货任务,用于绑定 user/batch 与 active link。
|
||||
@@ -590,7 +594,7 @@ def save_task_inventory_file_from_local_path(
|
||||
source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。
|
||||
|
||||
Returns:
|
||||
ShippingInventoryFile: 已持久化的库存快照对象。
|
||||
FreightRpaOnhandReportFile: 已持久化的库存快照对象。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源文件不存在时抛出。
|
||||
@@ -607,8 +611,10 @@ def save_task_inventory_file_from_local_path(
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
# [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
|
||||
# 拿回 file_id 后取回 ORM 对象并交由 replace_task_inventory_link 建立 active link(link 表留在发货域)。
|
||||
saved_file_id = insert_onhand_report(
|
||||
onhand_file_no=inventory_file_no,
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
|
||||
storage_path=str(path),
|
||||
@@ -618,27 +624,26 @@ def save_task_inventory_file_from_local_path(
|
||||
line_count=0,
|
||||
source_query_json={'trigger_type': 'manual_upload'},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id)
|
||||
replace_task_inventory_link(task, inv_file, role="owner")
|
||||
return inv_file
|
||||
|
||||
|
||||
def replace_task_inventory_link(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
*,
|
||||
role: str = "member",
|
||||
) -> ShippingTaskInventoryLink:
|
||||
) -> ShippingTaskOnhandLink:
|
||||
"""替换任务 active 库存 link,保留历史 link 审计。"""
|
||||
if task.id is None:
|
||||
db.session.flush()
|
||||
existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all()
|
||||
existing = ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True).all()
|
||||
for link in existing:
|
||||
link.is_active = False
|
||||
new_link = ShippingTaskInventoryLink(
|
||||
new_link = ShippingTaskOnhandLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inv_file.id,
|
||||
onhand_file_id=inv_file.id,
|
||||
link_role=role,
|
||||
access_mode="readonly",
|
||||
linked_by_user_id=inv_file.user_id,
|
||||
@@ -649,7 +654,7 @@ def replace_task_inventory_link(
|
||||
task_id=task_event_task_id(task),
|
||||
event_type="inventory_file_linked",
|
||||
detail_json={
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"role": role,
|
||||
"share_mode": inv_file.share_mode,
|
||||
},
|
||||
@@ -667,14 +672,14 @@ def read_linked_inventory_schema_preview(task: ShippingNotice) -> dict[str, Any]
|
||||
return dict(inv_file.schema_preview_json)
|
||||
path = Path(inv_file.storage_path)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = inv_file.source_file_name or path.name
|
||||
inv_file.schema_preview_json = preview
|
||||
return preview
|
||||
|
||||
|
||||
def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。
|
||||
|
||||
仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败,
|
||||
@@ -682,18 +687,18 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list
|
||||
"""
|
||||
path = Path(inv_file.storage_path)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.shipping_notice.inventory_parsing_profile import require_source_profile
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
|
||||
from app.models import FreightRpaSource
|
||||
from app.services.shipping_notice.onhand_parsing_profile import require_source_profile
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first()
|
||||
profile = require_source_profile(source)
|
||||
actual_format = path.suffix.lower().lstrip('.')
|
||||
if actual_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
definition = dict(profile.definition_json or {})
|
||||
return parse_inventory_excel_with_meta(
|
||||
@@ -706,7 +711,7 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list
|
||||
|
||||
|
||||
def apply_inventory_parse_result_to_linked_tasks(
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
@@ -714,7 +719,7 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
mapping_confirmed: bool = False,
|
||||
) -> list[ShippingNotice]:
|
||||
"""把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。"""
|
||||
inv_file.inventory_lines_json = inventory_lines
|
||||
inv_file.onhand_lines_json = inventory_lines
|
||||
inv_file.line_count = len(inventory_lines)
|
||||
if field_mapping:
|
||||
inv_file.field_mapping_json = field_mapping
|
||||
@@ -732,7 +737,7 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
return linked_tasks
|
||||
|
||||
|
||||
def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]:
|
||||
def linked_task_nos_for_inventory_file(inv_file: FreightRpaOnhandReportFile | None) -> list[str]:
|
||||
"""返回库存快照当前 active link 关联的任务编号列表。"""
|
||||
if not inv_file:
|
||||
return []
|
||||
@@ -743,7 +748,7 @@ def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -
|
||||
return sorted(set(task_nos))
|
||||
|
||||
|
||||
def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool:
|
||||
def start_inventory_file_linked_tasks(inv_file: FreightRpaOnhandReportFile | None) -> bool:
|
||||
"""
|
||||
按库存快照关联任务批量入队续跑。
|
||||
|
||||
@@ -775,7 +780,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_matching",
|
||||
stage="onhand_matching",
|
||||
step_title="匹配库存",
|
||||
status="running",
|
||||
message="本批库存快照已确认,等待匹配库存",
|
||||
+12
-12
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_mapping.py
|
||||
services/shipping_notice/onhand_mapping.py
|
||||
|
||||
用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。
|
||||
依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。
|
||||
依赖:FreightRpaOnhandField、match_rule_desc、标准 `json`/`typing` 能力。
|
||||
逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。
|
||||
"""
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryField
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||||
|
||||
@@ -19,7 +19,7 @@ LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "ava
|
||||
LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty")
|
||||
|
||||
|
||||
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
|
||||
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||||
"""读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。"""
|
||||
try:
|
||||
ids = {int(key) for key in field_mapping}
|
||||
@@ -27,8 +27,8 @@ def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventory
|
||||
return {}
|
||||
if not ids or any(item <= 0 for item in ids):
|
||||
return {}
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
|
||||
rows = FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active',
|
||||
).all()
|
||||
return {str(row.id): row for row in rows}
|
||||
|
||||
@@ -43,7 +43,7 @@ def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]:
|
||||
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, FreightRpaOnhandField]]:
|
||||
"""验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。"""
|
||||
catalog = _catalog_by_id(field_mapping)
|
||||
if _uses_catalog_ids(field_mapping):
|
||||
@@ -56,8 +56,8 @@ def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str]
|
||||
|
||||
def usage_field_ids() -> dict[str, set[str]]:
|
||||
"""按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。"""
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.status == 'active',
|
||||
rows = FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.status == 'active',
|
||||
).all()
|
||||
result: dict[str, set[str]] = {}
|
||||
for row in rows:
|
||||
@@ -99,7 +99,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
|
||||
|
||||
def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]:
|
||||
"""基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。"""
|
||||
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
|
||||
from app.services.shipping_notice.onhand_snapshot import _column_map, _map_header
|
||||
|
||||
col_map = _column_map()
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
@@ -165,9 +165,9 @@ def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> di
|
||||
"""按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。"""
|
||||
if not as_catalog:
|
||||
return _suggest_runtime_field_mapping(headers)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header
|
||||
|
||||
rows = ShippingInventoryField.query.filter_by(status='active').all()
|
||||
rows = FreightRpaOnhandField.query.filter_by(status='active').all()
|
||||
header_by_name: dict[str, list[str]] = {}
|
||||
for header in headers:
|
||||
normalized = normalise_header(header)
|
||||
+9
-9
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_mapping_workflow.py
|
||||
services/shipping_notice/onhand_mapping_workflow.py
|
||||
|
||||
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
|
||||
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
|
||||
依赖:onhand_file_store、onhand_snapshot、query_service、state_machine、tool_common。
|
||||
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析;
|
||||
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。
|
||||
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 onhand_lines_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,13 +13,13 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
_can_relink_inventory,
|
||||
active_inventory_file_for_task,
|
||||
apply_inventory_parse_result_to_linked_tasks,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
|
||||
from app.services.shipping_notice.onhand_snapshot import build_field_alignment_preview
|
||||
from app.services.shipping_notice.query_service import serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
@@ -44,7 +44,7 @@ def inventory_loaded_response(
|
||||
将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。
|
||||
|
||||
核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库)
|
||||
写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
|
||||
写回 ``onhand_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
|
||||
禁止覆盖共享 File 上已有行缓存。
|
||||
|
||||
Args:
|
||||
@@ -57,7 +57,7 @@ def inventory_loaded_response(
|
||||
field_mapping: published Profile 的字段映射快照。
|
||||
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
|
||||
commit: False 时仅 flush,供批量回调维持外层事务边界。
|
||||
persist_lines: False 时不写 File.inventory_lines_json(复用路径)。
|
||||
persist_lines: False 时不写 File.onhand_lines_json(复用路径)。
|
||||
|
||||
Returns:
|
||||
Tool 标准响应;成功后任务可直接进入库存匹配。
|
||||
@@ -101,7 +101,7 @@ def inventory_loaded_response(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="completed",
|
||||
message=f"已载入库存 {len(inventory_lines)} 行",
|
||||
@@ -138,7 +138,7 @@ def inventory_loaded_response(
|
||||
"warnings": warnings or [],
|
||||
"source": source,
|
||||
"column_meta": column_meta,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"inventory_file_no": inv_file.onhand_file_no if inv_file else None,
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
"persist_lines": bool(persist_lines),
|
||||
},
|
||||
+66
-63
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/inventory_parsing_profile.py
|
||||
backend/app/services/shipping_notice/onhand_parsing_profile.py
|
||||
|
||||
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
|
||||
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
|
||||
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。
|
||||
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
|
||||
"""
|
||||
|
||||
@@ -18,41 +18,41 @@ from sqlalchemy import func
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
ShippingOrderField,
|
||||
ShippingReceiptReportConfig,
|
||||
FreightRpaInboundReportConfig,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||||
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||||
field_ids: list[int] = []
|
||||
for raw_id in field_mapping:
|
||||
try:
|
||||
field_id = int(raw_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
|
||||
if field_id <= 0:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_ids.append(field_id)
|
||||
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
fields = {str(row.id): row for row in rows if row.status == 'active'}
|
||||
if len(fields) != len(set(str(item) for item in field_ids)):
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
return fields
|
||||
|
||||
|
||||
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
|
||||
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
|
||||
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
|
||||
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
|
||||
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
|
||||
if not match_ids or len(quantity_ids) != 1:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return match_ids | quantity_ids
|
||||
|
||||
@@ -69,13 +69,13 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile references unknown field: {sorted(unknown)}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return mapped_codes
|
||||
|
||||
@@ -89,15 +89,15 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
|
||||
'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_mapping = raw.get('field_mapping')
|
||||
if not isinstance(field_mapping, dict) or not field_mapping:
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if any(not str(value or '').strip() for value in field_mapping.values()):
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
header_row_index = raw.get('header_row_index')
|
||||
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
|
||||
if purpose == 'inbound':
|
||||
_required_movement_field_ids(raw)
|
||||
@@ -112,7 +112,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
|
||||
_required_catalog_field_ids(catalog_fields)
|
||||
match_keys = raw.get('match_keys')
|
||||
if not isinstance(match_keys, list) or not match_keys:
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
seen_order_fields: set[str] = set()
|
||||
seen_inventory_fields: set[str] = set()
|
||||
@@ -124,9 +124,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
|
||||
field is None or field.status != 'active' or field.scope != 'line'
|
||||
or inventory is None or inventory.usage_type != 'match_identity'
|
||||
):
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
seen_order_fields.add(field.id)
|
||||
seen_inventory_fields.add(inventory_field)
|
||||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
|
||||
@@ -143,20 +143,20 @@ def _require_sample_evidence(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
file_format: str,
|
||||
) -> ShippingInventoryStructureAnalysis:
|
||||
) -> FreightRpaOnhandStructureAnalysis:
|
||||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||||
try:
|
||||
analysis_id = int(sample_analysis_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires sample analysis evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
) from exc
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
|
||||
raise ValidationError(
|
||||
'Parsing profile sample analysis evidence is unavailable',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
@@ -166,13 +166,13 @@ def _require_sample_evidence(
|
||||
if not isinstance(selected, dict):
|
||||
raise ValidationError(
|
||||
'Parsing profile worksheet or header row is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
|
||||
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
@@ -181,12 +181,12 @@ def _require_sample_evidence(
|
||||
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping uses duplicate sample headers',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
return analysis
|
||||
|
||||
|
||||
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
|
||||
"""序列化解析 Profile 管理 DTO。"""
|
||||
sample_analysis = profile.sample_analysis
|
||||
return {
|
||||
@@ -212,49 +212,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出全部解析 Profile 版本。"""
|
||||
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
|
||||
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
|
||||
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
|
||||
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
|
||||
).all()]
|
||||
|
||||
|
||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
code = str(data.get('profile_code') or '').strip().upper()
|
||||
if not code:
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile is not None and code != profile.profile_code:
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
if profile is None:
|
||||
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
db.session.add(profile)
|
||||
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
|
||||
if purpose not in {'onhand', 'inbound', 'outbound'}:
|
||||
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and purpose != profile.purpose:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile purpose is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.purpose = purpose
|
||||
profile.display_name = str(data.get('display_name') or code).strip()
|
||||
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and requested_file_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.file_format = requested_file_format
|
||||
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
sample_analysis = _require_sample_evidence(
|
||||
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
|
||||
)
|
||||
@@ -262,7 +262,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
|
||||
if not bool(data.get('confirm_sample_replacement')):
|
||||
raise ValidationError(
|
||||
'Replacing inventory sample evidence requires confirmation',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
)
|
||||
history = list(profile.sample_evidence_history_json or [])
|
||||
history.append({
|
||||
@@ -280,11 +280,11 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
|
||||
|
||||
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
_require_sample_evidence(
|
||||
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
|
||||
)
|
||||
@@ -304,7 +304,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
@@ -317,17 +317,18 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
|
||||
def retire(profile_id: int) -> dict[str, Any]:
|
||||
"""退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published':
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
|
||||
bound_sources = ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
# 收料报表配置(ShippingReceiptReportConfig)同样绑定解析 Profile:退役前必须一并核查,
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
|
||||
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
|
||||
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
# 收料报表配置(FreightRpaInboundReportConfig)同样绑定解析 Profile:退役前必须一并核查,
|
||||
# 否则入站文件解析链(inbound purpose)会静默失去规则。
|
||||
bound_receipt_configs = ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
bound_receipt_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
if bound_sources or bound_receipt_configs:
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
profile.status = 'retired'
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
@@ -335,18 +336,20 @@ def retire(profile_id: int) -> dict[str, Any]:
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
|
||||
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
|
||||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
||||
profile = getattr(source, 'parsing_profile', None)
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||||
config = getattr(source, 'onhand_report_config', None)
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
return profile
|
||||
+9
-9
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_profile_matching.py
|
||||
services/shipping_notice/onhand_profile_matching.py
|
||||
|
||||
用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。
|
||||
依赖:ShippingInventoryParsingProfile、库存结构指纹服务。
|
||||
依赖:FreightRpaParsingProfile、库存结构指纹服务。
|
||||
逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。
|
||||
"""
|
||||
|
||||
@@ -10,17 +10,17 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
|
||||
from app.models import FreightRpaParsingProfile
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header
|
||||
|
||||
|
||||
def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]:
|
||||
def _profile_headers(profile: FreightRpaParsingProfile) -> list[str]:
|
||||
"""读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。"""
|
||||
structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {}
|
||||
return [str(header) for header in structure.get('headers', [])]
|
||||
|
||||
|
||||
def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]:
|
||||
def _difference(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> dict[str, list[str]]:
|
||||
"""以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。"""
|
||||
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
|
||||
observed = [normalise_header(header) for header in structure.get('selected_headers', [])]
|
||||
@@ -32,9 +32,9 @@ def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfi
|
||||
}
|
||||
|
||||
|
||||
def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool:
|
||||
def _core_mapping_matches(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> bool:
|
||||
"""确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。"""
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
|
||||
observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])}
|
||||
@@ -53,7 +53,7 @@ def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]:
|
||||
"""查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。"""
|
||||
exact = str(analysis.get('exact_structure_fingerprint') or '')
|
||||
compatible = str(analysis.get('compatibility_fingerprint') or '')
|
||||
profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all()
|
||||
profiles = FreightRpaParsingProfile.query.filter_by(status='published').all()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for profile in profiles:
|
||||
level = None
|
||||
+153
-52
@@ -1,9 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_recovery_service.py
|
||||
services/shipping_notice/onhand_recovery_service.py
|
||||
|
||||
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。
|
||||
用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉;阶段 B Task 7
|
||||
修复轮新增 onhand 报表事实落地后的候选 settle(settle_preparation_source_
|
||||
from_onhand_report)与等待任务反查(waiting_preparation_source_task_ids)。
|
||||
依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。
|
||||
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。
|
||||
逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。SourceAttempt
|
||||
被 settle 后的 PreparationAttempt 聚合(含 RecoveryPlan 收口)收敛到
|
||||
_aggregate_preparation_after_source_settle——per-source RPA 回调与 onhand
|
||||
事实处理函数(handle_onhand_report)共用同一聚合出口,防两路语义漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,30 +18,30 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingOnhandPreparationAttempt,
|
||||
ShippingOnhandPreparationSourceAttempt,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderCandidate,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
|
||||
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_combination_fingerprint import build_inventory_combination_fingerprint
|
||||
from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts
|
||||
|
||||
|
||||
def create_inventory_preparation_round(
|
||||
*, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None,
|
||||
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
|
||||
gate_attempt_id: int | None = None,
|
||||
) -> ShippingInventoryPreparationAttempt:
|
||||
) -> ShippingOnhandPreparationAttempt:
|
||||
"""创建一次任务级准备轮次;同一任务按 attempt_no 递增。"""
|
||||
last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
|
||||
ShippingInventoryPreparationAttempt.attempt_no.desc(),
|
||||
last = ShippingOnhandPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by(
|
||||
ShippingOnhandPreparationAttempt.attempt_no.desc(),
|
||||
).first()
|
||||
round_row = ShippingInventoryPreparationAttempt(
|
||||
round_row = ShippingOnhandPreparationAttempt(
|
||||
task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id,
|
||||
recovery_plan_id=recovery_plan_id,
|
||||
attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued',
|
||||
@@ -53,7 +58,7 @@ def create_inventory_preparation_round(
|
||||
db.session.flush()
|
||||
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
|
||||
if not codes:
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
codes = task_frozen_onhand_source_codes(task)
|
||||
active_file = active_inventory_file_for_task(task)
|
||||
for source_code in codes:
|
||||
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
|
||||
@@ -65,15 +70,15 @@ def create_inventory_preparation_round(
|
||||
parser_version=getattr(active_file, 'parser_version', None) if active_file else None,
|
||||
mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None,
|
||||
)
|
||||
reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable)
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
reusable = bool(action_code == 'retry_onhand_from_field_mapping' and reusable)
|
||||
link = ShippingTaskOnhandLink.query.filter_by(
|
||||
task_id=int(task.id), matched_source_code=source_code, is_active=True,
|
||||
).order_by(ShippingTaskInventoryLink.id.desc()).first()
|
||||
source = ShippingInventoryPreparationSourceAttempt(
|
||||
).order_by(ShippingTaskOnhandLink.id.desc()).first()
|
||||
source = ShippingOnhandPreparationSourceAttempt(
|
||||
preparation_attempt_id=int(round_row.id), source_code=source_code,
|
||||
status='reusable' if reusable else 'queued',
|
||||
inventory_file_id=int(active_file.id) if reusable and active_file else None,
|
||||
task_inventory_link_id=int(link.id) if reusable and link else None,
|
||||
onhand_file_id=int(active_file.id) if reusable and active_file else None,
|
||||
task_onhand_link_id=int(link.id) if reusable and link else None,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
db.session.add(source)
|
||||
@@ -90,18 +95,18 @@ def create_inventory_preparation_round(
|
||||
sources=[
|
||||
{
|
||||
'source_code': str(item.source_code),
|
||||
'snapshot_id': item.inventory_file_id,
|
||||
'snapshot_id': item.onhand_file_id,
|
||||
'snapshot_hash': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None)
|
||||
if item.inventory_file_id else None
|
||||
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'file_sha256', None)
|
||||
if item.onhand_file_id else None
|
||||
),
|
||||
'parser_version': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None)
|
||||
if item.inventory_file_id else None
|
||||
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'parser_version', None)
|
||||
if item.onhand_file_id else None
|
||||
),
|
||||
'mapping_version': (
|
||||
getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None)
|
||||
if item.inventory_file_id else None
|
||||
getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'mapping_version', None)
|
||||
if item.onhand_file_id else None
|
||||
),
|
||||
}
|
||||
for item in round_row.source_attempts
|
||||
@@ -114,8 +119,8 @@ def create_inventory_preparation_round(
|
||||
|
||||
|
||||
def sync_inventory_preparation_round(
|
||||
*, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any,
|
||||
) -> ShippingInventoryPreparationAttempt:
|
||||
*, preparation_attempt: ShippingOnhandPreparationAttempt, result: Any,
|
||||
) -> ShippingOnhandPreparationAttempt:
|
||||
"""将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。"""
|
||||
def _read(name: str, default: Any) -> Any:
|
||||
return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default)
|
||||
@@ -151,29 +156,24 @@ def sync_inventory_preparation_round(
|
||||
return preparation_attempt
|
||||
|
||||
|
||||
def sync_preparation_source_from_rpa_attempt(
|
||||
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
|
||||
) -> None:
|
||||
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
|
||||
def _aggregate_preparation_after_source_settle(preparation: ShippingOnhandPreparationAttempt) -> None:
|
||||
"""按 SourceAttempt 状态聚合 PreparationAttempt 终态并收口绑定的 RecoveryPlan(只 flush 不 commit)。
|
||||
|
||||
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
|
||||
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。
|
||||
用途:SourceAttempt 被 settle(ready/failed/waiting)后的统一聚合出口——
|
||||
per-source RPA 回调(sync_preparation_source_from_rpa_attempt)与
|
||||
onhand 报表事实处理函数(settle_preparation_source_from_onhand_report,
|
||||
阶段 B Task 7 修复轮)共用同一聚合语义,防止两条路径漂移。
|
||||
核心逻辑:任一 failed → failed;仍有 queued/running/waiting → waiting_external;
|
||||
全部 ready/reusable/skipped → succeeded(记 completed_at);聚合到终态后
|
||||
同步收口绑定的 RecoveryPlan(succeeded/failed + 时间戳 + 失败码),
|
||||
避免已完成的计划继续占用 active-plan 互斥位。
|
||||
Args:
|
||||
preparation: SourceAttempt 已更新的准备轮次行。
|
||||
Returns:
|
||||
None。只 flush——事务提交时机归属调用方。
|
||||
"""
|
||||
source = ShippingInventoryPreparationSourceAttempt.query.filter_by(
|
||||
rpa_attempt_id=int(rpa_attempt_id),
|
||||
).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first()
|
||||
if source is None:
|
||||
if preparation is None:
|
||||
return
|
||||
status = str(rpa_status or '').strip().lower()
|
||||
if status in {'succeeded', 'consumed'}:
|
||||
source.status = 'ready'
|
||||
if inventory_file_id:
|
||||
source.inventory_file_id = int(inventory_file_id)
|
||||
elif status in {'failed', 'exhausted'}:
|
||||
source.status = 'failed'
|
||||
elif status in {'queued', 'running'}:
|
||||
source.status = 'waiting'
|
||||
preparation = source.preparation_attempt
|
||||
rows = list(getattr(preparation, 'source_attempts', []) or [])
|
||||
if any(row.status == 'failed' for row in rows):
|
||||
preparation.status = 'failed'
|
||||
@@ -201,4 +201,105 @@ def sync_preparation_source_from_rpa_attempt(
|
||||
if preparation.status == 'failed':
|
||||
plan.failure_code = 'inventory_preparation_failed'
|
||||
plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'}
|
||||
|
||||
|
||||
def settle_preparation_source_from_onhand_report(
|
||||
*, source_code: str, onhand_file_id: int,
|
||||
) -> list[ShippingOnhandPreparationAttempt]:
|
||||
"""onhand 报表事实落地后:把该来源等待中的 SourceAttempt settle 为 ready 并绑定文件。
|
||||
|
||||
【AI 触发时机】:onhand 事实处理函数(shipping_notice.onhand_report_handler.
|
||||
handle_onhand_report)在文件行 commit 后投递 ok=True 事实时调用——共享快照
|
||||
模型下「该来源已有可用快照」对所有等待该来源的候选准备成立。
|
||||
|
||||
核心逻辑:[STEP 1] 取该来源 status ∈ queued/running/waiting 且未绑定文件的
|
||||
SourceAttempt(幂等集:已 ready/已绑定的行不在集合内,重复投递零副作用、
|
||||
绝不重复候选行);[STEP 2] 逐行 ready + 绑定 onhand_file_id;
|
||||
[STEP 3] 对受影响的 PreparationAttempt 逐一聚合终态
|
||||
(_aggregate_preparation_after_source_settle,含 RecoveryPlan 收口)。
|
||||
只 flush 不 commit——事务提交时机归属调用方(处理函数)。
|
||||
|
||||
Args:
|
||||
source_code: 库存来源编码(与 SourceAttempt.source_code 精确匹配)。
|
||||
onhand_file_id: 已提交的 freight_rpa_onhand_report_files 主键。
|
||||
Returns:
|
||||
受影响(发生了 settle)的 PreparationAttempt 列表;无等待行时为空表。
|
||||
"""
|
||||
waiting = (
|
||||
ShippingOnhandPreparationSourceAttempt.query
|
||||
.filter(
|
||||
ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(),
|
||||
ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')),
|
||||
ShippingOnhandPreparationSourceAttempt.onhand_file_id.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
affected: dict[int, ShippingOnhandPreparationAttempt] = {}
|
||||
for row in waiting:
|
||||
row.status = 'ready'
|
||||
row.onhand_file_id = int(onhand_file_id)
|
||||
preparation = row.preparation_attempt
|
||||
if preparation is not None:
|
||||
affected[int(preparation.id)] = preparation
|
||||
for preparation in affected.values():
|
||||
_aggregate_preparation_after_source_settle(preparation)
|
||||
if waiting:
|
||||
db.session.flush()
|
||||
return list(affected.values())
|
||||
|
||||
|
||||
def waiting_preparation_source_task_ids(*, source_code: str) -> list[int]:
|
||||
"""列出「仍在等待该来源库存」的准备轮次任务 ID(onhand 事实处理函数门禁重投影用)。
|
||||
|
||||
用途:onhand 失败/空事实(无文件身份)时,处理函数只对等待该来源的任务重投影
|
||||
履约门禁(回调失败路径的门禁更新归处理函数),不发明/改写任何候选行。
|
||||
核心逻辑:按 source_code 取 status ∈ queued/running/waiting 的 SourceAttempt,
|
||||
经其准备轮次收集去重 task_id;只读查询。
|
||||
Args:
|
||||
source_code: 库存来源编码。
|
||||
Returns:
|
||||
去重后的 ShippingOrderTask.id 列表(无等待行时为空表)。
|
||||
"""
|
||||
rows = (
|
||||
ShippingOnhandPreparationSourceAttempt.query
|
||||
.filter(
|
||||
ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(),
|
||||
ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
task_ids: list[int] = []
|
||||
for row in rows:
|
||||
preparation = row.preparation_attempt
|
||||
if preparation is not None and preparation.task_id and int(preparation.task_id) not in task_ids:
|
||||
task_ids.append(int(preparation.task_id))
|
||||
return task_ids
|
||||
|
||||
|
||||
def sync_preparation_source_from_rpa_attempt(
|
||||
*, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None,
|
||||
) -> None:
|
||||
"""由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。
|
||||
|
||||
SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次,
|
||||
因而不会污染当前 GateAttempt 对应的 PreparationAttempt。聚合语义自阶段 B
|
||||
Task 7 修复轮起收敛到 _aggregate_preparation_after_source_settle(与
|
||||
settle_preparation_source_from_onhand_report 共用同一出口)。
|
||||
"""
|
||||
source = ShippingOnhandPreparationSourceAttempt.query.filter_by(
|
||||
rpa_attempt_id=int(rpa_attempt_id),
|
||||
).order_by(ShippingOnhandPreparationSourceAttempt.id.desc()).first()
|
||||
if source is None:
|
||||
return
|
||||
status = str(rpa_status or '').strip().lower()
|
||||
if status in {'succeeded', 'consumed'}:
|
||||
source.status = 'ready'
|
||||
if inventory_file_id:
|
||||
source.onhand_file_id = int(inventory_file_id)
|
||||
elif status in {'failed', 'exhausted'}:
|
||||
source.status = 'failed'
|
||||
elif status in {'queued', 'running'}:
|
||||
source.status = 'waiting'
|
||||
preparation = source.preparation_attempt
|
||||
_aggregate_preparation_after_source_settle(preparation)
|
||||
db.session.flush()
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
services/shipping_notice/onhand_report_handler.py
|
||||
|
||||
用途:onhand(在手库存)报表事实的发货侧业务处理函数(阶段 B Task 7)——
|
||||
在手文件归档终态 commit 后由 dispatch_report_fact 投递的 ReportFact
|
||||
只在此更新发货自己的门禁与候选相关状态,绝不写调拨或 RPA 侧事实。
|
||||
依赖:app.db、app.models(FreightRpaOnhandReportFile 只读行获取 / ShippingTaskOnhandLink /
|
||||
ShippingOrderTask / ShippingProcessExecution)、app.core.errors
|
||||
(ValidationError / NotFoundError)、freight_rpa.reports.facts(ReportFact /
|
||||
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
|
||||
onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、
|
||||
process_gate_bridge(门禁同步)。
|
||||
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks)
|
||||
注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调
|
||||
(rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch)
|
||||
在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮
|
||||
接线;HTTP 收件入口 rpa_report_inventory_batch 只入队 Job、不 commit 文件,
|
||||
故不投递)。处理函数只改发货自己的行:[候选] settle 等待该来源的
|
||||
SourceAttempt 并绑定该文件(共享快照模型);[门禁] 对受影响的准备轮次任务与
|
||||
挂接该文件的任务重投影履约门禁;[提交] 处理函数自行 commit(文件行已由归档方
|
||||
提交,绝不回滚)。行插入唯一入口在 freight_rpa/onhand/report_store(本模块
|
||||
【禁止】构造 FreightRpaOnhandReportFile 行,边界由 test_report_model_boundary 锁定);
|
||||
TransferSourceJob 归调拨域(本模块不写)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink
|
||||
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
|
||||
|
||||
|
||||
def _sync_gates_for_task_ids(task_ids: list[int]) -> None:
|
||||
"""对给定任务逐一重投影履约门禁(活动、非 superseded 执行链;幂等可重放)。
|
||||
|
||||
核心逻辑:按主键取任务与活动执行链——执行链缺失/已 superseded 时跳过
|
||||
(重冻结/复活链路上 Task 指针可能短暂指向旧执行链:迟到事实只保留原始
|
||||
审计,不得回写已废弃执行的 Gate);命中即 sync_fulfillment_gates_from_task
|
||||
(域事实投影为 Gate 结果,重复投递重投影同值,不产生重复行)。
|
||||
只写不 commit——事务提交时机归属调用方(handle_onhand_report)。
|
||||
"""
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
seen: set[int] = set()
|
||||
for task_id in task_ids:
|
||||
if task_id in seen:
|
||||
continue
|
||||
seen.add(task_id)
|
||||
task = db.session.get(ShippingOrderTask, int(task_id))
|
||||
if task is None or not getattr(task, 'active_process_execution_id', None):
|
||||
continue
|
||||
execution = db.session.get(
|
||||
ShippingProcessExecution, int(task.active_process_execution_id),
|
||||
)
|
||||
if execution is not None and str(execution.status or '').strip().lower() != 'superseded':
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
|
||||
|
||||
|
||||
def handle_onhand_report(fact: ReportFact) -> None:
|
||||
"""report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。
|
||||
不插入 freight_rpa_onhand_report_files。
|
||||
|
||||
(Task 7 契约 docstring 逐字保留如上;修复轮补充说明见下。)
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] kind 门禁(fail-closed,防误注册/误分发);
|
||||
[STEP 2] success 事实(ok 且 file_id 有值):按主键取回已提交的 onhand 报表行
|
||||
(只读——行由 freight_rpa/onhand/report_store 收敛写入,本模块只消费;缺失即
|
||||
fail-closed 抛 NotFoundError);
|
||||
[STEP 3 候选] settle 等待该来源的候选准备行并绑定该文件
|
||||
(onhand_recovery_service.settle_preparation_source_from_onhand_report——共享
|
||||
快照模型:该来源已有可用快照即对所有等待该来源的候选准备成立;幂等——
|
||||
已 ready/已绑定的行不在等待集,重复投递零副作用、不重复候选行);
|
||||
[STEP 4 门禁] 对受影响的准备轮次任务 + 挂接该文件(active link)的任务重投影
|
||||
履约门禁(sync_fulfillment_gates_from_task,幂等可重放);
|
||||
[STEP 5] db.session.commit()——处理函数提交自己的候选/门禁写(文件行已由
|
||||
归档方提交,绝不回滚)。
|
||||
失败/空事实(ok=False 或 file_id=None):无文件身份——不发明候选行、不 settle
|
||||
任何 SourceAttempt;仅对仍在等待该来源库存的任务重投影门禁(回调失败路径的
|
||||
门禁更新归本处理函数),随后同样 commit。
|
||||
【不写 TransferSourceJob】(归 in_transit_transfer 域);【不构造
|
||||
freight_rpa_onhand_report_files 行】(归 freight_rpa 域唯一写入口)。
|
||||
异常原样外抛(不捕获):文件行已提交不回滚,Worker 重试整笔回调补齐。
|
||||
|
||||
Args:
|
||||
fact: 终态已提交后由归档入口构造的报表事实(report_kind='onhand'/
|
||||
source_code/file_id/sha256/ok/error_code/error_message)。
|
||||
Returns:
|
||||
None(候选/门禁写库,不返回业务值)。
|
||||
Raises:
|
||||
ValidationError: report_kind 非 onhand(误注册/误分发,fail-closed)。
|
||||
NotFoundError: fact.file_id 对应的在手报表行不存在(事实先于文件提交
|
||||
属硬性不一致,fail-closed 而非静默跳过)。
|
||||
"""
|
||||
# [STEP 1] kind 门禁:本函数只消费 onhand 事实(dispatch 已按 kind 路由,
|
||||
# 防御性复核,防止误注册成其他 kind 的处理函数后静默错写发货行)。
|
||||
kind = require_report_kind(fact.report_kind)
|
||||
if kind != 'onhand':
|
||||
raise ValidationError(
|
||||
f"handle_onhand_report only accepts onhand facts, got: {kind!r}",
|
||||
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
|
||||
details={'report_kind': fact.report_kind},
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.onhand_recovery_service import (
|
||||
settle_preparation_source_from_onhand_report,
|
||||
waiting_preparation_source_task_ids,
|
||||
)
|
||||
|
||||
source_code = str(fact.source_code or '').strip()
|
||||
affected_task_ids: list[int] = []
|
||||
|
||||
if not fact.ok or fact.file_id is None:
|
||||
# [STEP 2·失败/空分支] 无文件身份:不发明候选行、不 settle 任何 SourceAttempt;
|
||||
# 仅对仍在等待该来源库存的任务重投影门禁(失败路径门禁更新归本处理函数)。
|
||||
affected_task_ids.extend(waiting_preparation_source_task_ids(source_code=source_code))
|
||||
else:
|
||||
# [STEP 2·success 分支] 只读取回已提交的在手报表行(构造禁走 report_store;
|
||||
# 读取按主键)。
|
||||
inv_file = db.session.get(FreightRpaOnhandReportFile, int(fact.file_id))
|
||||
if inv_file is None:
|
||||
raise NotFoundError(
|
||||
f"Onhand report file not found: {fact.file_id}",
|
||||
details={'file_id': fact.file_id},
|
||||
)
|
||||
file_source = str(inv_file.source_code or source_code).strip()
|
||||
|
||||
# [STEP 3·候选] settle 等待该来源的候选准备行并绑定该文件(幂等)。
|
||||
settled = (
|
||||
settle_preparation_source_from_onhand_report(
|
||||
source_code=file_source, onhand_file_id=int(inv_file.id),
|
||||
)
|
||||
if file_source
|
||||
else []
|
||||
)
|
||||
for preparation in settled:
|
||||
if preparation.task_id:
|
||||
affected_task_ids.append(int(preparation.task_id))
|
||||
|
||||
# [STEP 4·门禁] 挂接该文件(active link)的任务一并重投影门禁。
|
||||
links = (
|
||||
ShippingTaskOnhandLink.query
|
||||
.filter_by(onhand_file_id=inv_file.id, is_active=True)
|
||||
.all()
|
||||
)
|
||||
for link in links:
|
||||
if link.task_id:
|
||||
affected_task_ids.append(int(link.task_id))
|
||||
|
||||
_sync_gates_for_task_ids(affected_task_ids)
|
||||
|
||||
# [STEP 5] 处理函数提交自己的候选/门禁写(sync_fulfillment_gates_from_task
|
||||
# 不 commit——不提交则请求结束回滚会丢掉这些写;文件行已提交,不受影响)。
|
||||
db.session.commit()
|
||||
+11
-11
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_routing_engine.py
|
||||
services/shipping_notice/onhand_routing_engine.py
|
||||
|
||||
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、onhand_source_repository。
|
||||
逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源,
|
||||
命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层);
|
||||
随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
@@ -16,8 +16,8 @@ from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
from app.models import FreightRpaOnhandRoutingRule, ShippingOrderSnapshot
|
||||
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
|
||||
from app.services.shipping_notice.routing_operators import matches_operator
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ class InventoryRoutingResult:
|
||||
)
|
||||
|
||||
|
||||
def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]:
|
||||
def _matched_rule_summaries(rules: list[FreightRpaOnhandRoutingRule]) -> tuple[dict[str, Any], ...]:
|
||||
"""将命中规则折叠为可审计、可序列化的摘要元组。"""
|
||||
return tuple(
|
||||
{
|
||||
@@ -177,7 +177,7 @@ def _condition_value_from_maps(
|
||||
|
||||
|
||||
def _rule_matches(
|
||||
rule: ShippingInventoryRoutingRule,
|
||||
rule: FreightRpaOnhandRoutingRule,
|
||||
*,
|
||||
value_reader,
|
||||
) -> bool:
|
||||
@@ -191,7 +191,7 @@ def _rule_matches(
|
||||
return all(results) if rule.match_mode == 'all' else any(results)
|
||||
|
||||
|
||||
def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, priority: int) -> InventoryRoutingResult:
|
||||
def _evaluate_matched_rules(top_rules: list[FreightRpaOnhandRoutingRule], *, priority: int) -> InventoryRoutingResult:
|
||||
"""
|
||||
将同优先级命中规则折叠为候选集合与建单资格。
|
||||
|
||||
@@ -250,13 +250,13 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr
|
||||
)
|
||||
|
||||
|
||||
def _published_rules(*, scope: str, now: datetime) -> list[ShippingInventoryRoutingRule]:
|
||||
def _published_rules(*, scope: str, now: datetime) -> list[FreightRpaOnhandRoutingRule]:
|
||||
"""加载当前时刻有效的已发布规则,按优先级降序。"""
|
||||
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
query = FreightRpaOnhandRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
return [
|
||||
rule for rule in query.order_by(
|
||||
ShippingInventoryRoutingRule.priority.desc(),
|
||||
ShippingInventoryRoutingRule.id.asc(),
|
||||
FreightRpaOnhandRoutingRule.priority.desc(),
|
||||
FreightRpaOnhandRoutingRule.id.asc(),
|
||||
).all()
|
||||
if (rule.effective_from is None or rule.effective_from <= now)
|
||||
and (rule.effective_to is None or rule.effective_to >= now)
|
||||
+285
-99
@@ -1,18 +1,29 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
services/shipping_notice/onhand_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。
|
||||
依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/
|
||||
workflow_protocol 协议记账)、inventory_snapshot、inventory_mapping_workflow、query_service、
|
||||
workflow_protocol 协议记账)、onhand_snapshot、onhand_mapping_workflow、query_service、
|
||||
动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
逻辑:onhand_workflow.ensure_onhand 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
|
||||
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
|
||||
Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/
|
||||
回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice
|
||||
import);快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
|
||||
import); 快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
|
||||
留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export,
|
||||
既有同包调用与测试 import(含 monkeypatch 接缝)不换名。
|
||||
【阶段 B Task 7 修复】单回调(rpa_report_inventory)与批量 worker
|
||||
(process_rpa_report_inventory_batch)在文件行 commit 后逐文件投递 onhand 报表事实
|
||||
(dispatch_report_fact(ReportFact(report_kind='onhand', ...))——先 commit 再投递;
|
||||
处理函数异常原样外抛、不折进 warnings;HTTP 收件入口 rpa_report_inventory_batch 只入队
|
||||
Job、不 commit 文件故不投递;空结果审计快照不投递——不作可用库存复用)。候选 settle
|
||||
与门禁同步由 handle_onhand_report 承担(见 onhand_report_handler.py)。修复轮 2/3:批量内
|
||||
单文件处理函数失败先回滚未提交会话(半途写不得被后续 commit 持久化)并继续投递其余
|
||||
已提交文件,排程 finalize 与 drop 文件清理入队照常执行,之后以
|
||||
OnhandReportDispatchAfterCommitError 携带未成功文件清单原样重抛;Job 处理器把清单写回
|
||||
payload(retry_dispatch_files)并 requeue,重试经「只重投失败文件」通道
|
||||
(_dispatch_retry_onhand_report_files)补齐,全部成功前绝不返回 ok。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,16 +37,16 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
from app.services.shipping_notice.onhand_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.onhand_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
get_or_create_rpa_inventory_snapshot,
|
||||
link_snapshot_to_task,
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
from app.services.shipping_notice.onhand_upload import (
|
||||
delete_staged_task_inventory_file,
|
||||
promote_staged_task_inventory_file,
|
||||
rebuild_task_inventory_attachment_from_snapshot,
|
||||
@@ -49,12 +60,12 @@ from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
quarantine_callback_drop_file,
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
assert_inventory_source_gate,
|
||||
inventory_identities_match,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
customer_gate_tool_response,
|
||||
@@ -186,7 +197,7 @@ def _try_reuse_inventory_snapshot(
|
||||
if mode == "retry_rpa":
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
|
||||
|
||||
snapshot = find_latest_ready_snapshot(
|
||||
str(rpa_source.get("source_code") or ""),
|
||||
@@ -208,7 +219,7 @@ def _try_reuse_inventory_snapshot(
|
||||
task,
|
||||
"inventory_snapshot_reused",
|
||||
{
|
||||
"inventory_file_no": snapshot.inventory_file_no,
|
||||
"inventory_file_no": snapshot.onhand_file_no,
|
||||
"source_code": snapshot.source_code,
|
||||
"warehouse_id": snapshot.warehouse_id,
|
||||
"snapshot_age_seconds": link.snapshot_age_seconds,
|
||||
@@ -216,7 +227,7 @@ def _try_reuse_inventory_snapshot(
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
|
||||
try:
|
||||
lines, column_meta = read_inventory_file_lines(snapshot)
|
||||
except (OSError, ValueError, AppError):
|
||||
@@ -298,12 +309,12 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
|
||||
Returns:
|
||||
tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task):
|
||||
return None, None, None
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
|
||||
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
|
||||
return None, None, None
|
||||
# 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window);
|
||||
@@ -344,14 +355,14 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
return None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_wait_rechecked",
|
||||
"onhand_rpa_wait_rechecked",
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
# [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落
|
||||
# rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_failed",
|
||||
"onhand_rpa_failed",
|
||||
{
|
||||
"error": "timeout",
|
||||
"elapsed_seconds": elapsed,
|
||||
@@ -360,7 +371,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_exhausted",
|
||||
"onhand_rpa_exhausted",
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.flush()
|
||||
@@ -378,7 +389,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
|
||||
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
|
||||
"""从任务正式库存身份推导快照预期二元组。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import task_inventory_identity
|
||||
from app.services.shipping_notice.onhand_source_gate import task_inventory_identity
|
||||
|
||||
identity = task_inventory_identity(task)
|
||||
return (
|
||||
@@ -409,7 +420,7 @@ def _rollback_orphan_inventory_snapshot(
|
||||
return
|
||||
from sqlalchemy import inspect as sa_inspect
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
for raw in paths:
|
||||
delete_inventory_storage_path(raw)
|
||||
@@ -446,12 +457,12 @@ def _inventory_file_sha256(path: Path) -> str:
|
||||
|
||||
|
||||
def _validate_reused_snapshot_callback_file(
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
callback_path: Path,
|
||||
) -> str | None:
|
||||
"""
|
||||
校验复用快照时回调落盘文件与托管 storage_path 内容一致。
|
||||
核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。
|
||||
核心逻辑:不一致时拒绝复用,避免 onhand_lines_json 与 storage_path 文件分叉。
|
||||
"""
|
||||
storage_path = Path(str(inv_file.storage_path or ""))
|
||||
if not storage_path.is_file():
|
||||
@@ -463,11 +474,11 @@ def _validate_reused_snapshot_callback_file(
|
||||
return None
|
||||
|
||||
|
||||
def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path:
|
||||
def _snapshot_ingest_path(inv_file: FreightRpaOnhandReportFile) -> Path:
|
||||
"""返回应解析的库存快照托管路径(复用与新建均读 storage_path)。"""
|
||||
path = Path(str(inv_file.storage_path or ""))
|
||||
if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
|
||||
raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}")
|
||||
raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.onhand_file_no}")
|
||||
return path
|
||||
|
||||
|
||||
@@ -575,7 +586,7 @@ def _flush_pending_callback_moves(
|
||||
|
||||
def _try_rebuild_task_inventory_attachment(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
post_commit_warnings: list[str],
|
||||
) -> bool:
|
||||
"""
|
||||
@@ -655,12 +666,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
|
||||
# per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。
|
||||
source_run_no = str(payload.get('source_run_no') or '').strip()
|
||||
if source_run_no:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
|
||||
current_attempt = (
|
||||
db.session.query(ShippingTaskInventoryRpaAttempt)
|
||||
db.session.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.order_by(FreightRpaOnhandTaskAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running', 'succeeded'}:
|
||||
@@ -672,12 +683,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
|
||||
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
|
||||
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
|
||||
if source_run_no:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
|
||||
current_attempt = (
|
||||
db.session.query(ShippingTaskInventoryRpaAttempt)
|
||||
db.session.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.order_by(FreightRpaOnhandTaskAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}:
|
||||
@@ -811,9 +822,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
|
||||
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
|
||||
"""
|
||||
callback_source = str(payload.get("source_code") or "").strip().upper()
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
task_sources = set(task_frozen_inventory_source_codes(task))
|
||||
task_sources = set(task_frozen_onhand_source_codes(task))
|
||||
if not callback_source:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
@@ -829,12 +840,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(callback_source)
|
||||
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
|
||||
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
|
||||
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
|
||||
from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id
|
||||
|
||||
task_wh = resolve_inventory_source_warehouse_id(task, source=source) or ''
|
||||
if is_fixed and (not callback_wh or callback_wh != task_wh):
|
||||
@@ -962,7 +973,7 @@ def _resolve_batch_callback_source(
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
return None
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
return get_database_inventory_source(source_code)
|
||||
|
||||
@@ -976,7 +987,7 @@ def _batch_snapshot_verify_warehouse_id(
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
|
||||
return None
|
||||
if task:
|
||||
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
|
||||
from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id
|
||||
|
||||
warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or ''
|
||||
return warehouse_id or None
|
||||
@@ -1021,14 +1032,14 @@ def ensure_inventory_via_rpa(
|
||||
allow_auto_retry: bool = True,
|
||||
source_codes: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 onhand_workflow.inventory_loaded_response。
|
||||
|
||||
Args:
|
||||
allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。
|
||||
poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
|
||||
poll_onhand_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
|
||||
source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
disposition_reason = task_execution_block_reason(task)
|
||||
@@ -1075,7 +1086,7 @@ def ensure_inventory_via_rpa(
|
||||
except AppError:
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
# OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。
|
||||
task.stage = "inventory_source_resolving"
|
||||
task.stage = "onhand_source_resolving"
|
||||
_set_workflow_error(task, "库存源尚未确定,无法启动 RPA")
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
@@ -1108,7 +1119,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title='获取库存',
|
||||
status='running',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
@@ -1136,7 +1147,7 @@ def ensure_inventory_via_rpa(
|
||||
poll_read_only = not allow_auto_retry
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
@@ -1165,11 +1176,11 @@ def ensure_inventory_via_rpa(
|
||||
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
||||
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task):
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
@@ -1190,12 +1201,12 @@ def ensure_inventory_via_rpa(
|
||||
},
|
||||
},
|
||||
)
|
||||
last_failed = latest_task_event(task, "inventory_rpa_failed")
|
||||
last_failed = latest_task_event(task, "onhand_rpa_failed")
|
||||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||||
_set_workflow_error(task, "RPA 库存导出等待超时")
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_failed",
|
||||
"onhand_rpa_failed",
|
||||
{
|
||||
"error": "timeout",
|
||||
"elapsed_seconds": elapsed,
|
||||
@@ -1249,7 +1260,7 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=progress_message,
|
||||
@@ -1261,7 +1272,7 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_triggered",
|
||||
"onhand_rpa_triggered",
|
||||
{
|
||||
"trigger": trigger,
|
||||
"run_no": _extract_run_no_from_trigger(trigger),
|
||||
@@ -1299,7 +1310,7 @@ def ensure_inventory_via_rpa(
|
||||
_set_workflow_error(task, human_message[:500])
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=human_message,
|
||||
@@ -1308,7 +1319,7 @@ def ensure_inventory_via_rpa(
|
||||
total=max_attempts,
|
||||
detail=detail,
|
||||
)
|
||||
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
|
||||
log_task_event(task, "onhand_rpa_retry_requested", {"reason": "trigger_failed"})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -1409,7 +1420,7 @@ def _handle_rpa_inventory_skipped(
|
||||
_set_workflow_error(task, None)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="货代系统当前无可用库存",
|
||||
@@ -1418,7 +1429,7 @@ def _handle_rpa_inventory_skipped(
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_skipped",
|
||||
"onhand_rpa_skipped",
|
||||
{
|
||||
"skip_reason": skip_reason,
|
||||
"message": detail or message,
|
||||
@@ -1449,14 +1460,14 @@ def _handle_rpa_inventory_failed(
|
||||
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
_set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500])
|
||||
log_task_event(task, "inventory_rpa_failed", {
|
||||
log_task_event(task, "onhand_rpa_failed", {
|
||||
"error": _workflow_error(task),
|
||||
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
|
||||
"rpa_runtime": runtime,
|
||||
})
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=_workflow_error(task),
|
||||
@@ -1520,7 +1531,7 @@ def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) ->
|
||||
|
||||
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
cleanup_retry_warnings = flush_callback_cleanup_queue()
|
||||
@@ -1574,7 +1585,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。
|
||||
log_task_event(
|
||||
task,
|
||||
'shipping_inventory_callback_ignored',
|
||||
'freight_rpa_onhand_callback_ignored',
|
||||
{
|
||||
'run_no': run_no_raw,
|
||||
'source_code': source_code_from_run,
|
||||
@@ -1714,7 +1725,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
staging_path: Path | None = None
|
||||
inv_file: ShippingInventoryFile | None = None
|
||||
inv_file: FreightRpaOnhandReportFile | None = None
|
||||
created_new = False
|
||||
orphan_paths: list[str | Path] = []
|
||||
try:
|
||||
@@ -1780,7 +1791,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if link is None:
|
||||
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
|
||||
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
|
||||
|
||||
structure_check = validate_production_inventory_structure(
|
||||
source_code=str(rpa_source['source_code']), path=ingest_path,
|
||||
@@ -1808,7 +1819,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="RPA 库存文件已返回,正在读取库存快照",
|
||||
@@ -1824,7 +1835,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"upload_filename": ingest_path.name,
|
||||
"upload_path": str(ingest_path),
|
||||
"origin_file_path": str(path),
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"reused_existing_snapshot": not created_new,
|
||||
"structure_validation": column_meta.get('structure_validation'),
|
||||
},
|
||||
@@ -1835,7 +1846,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lines,
|
||||
column_meta=column_meta,
|
||||
source="rpa_callback",
|
||||
event_type="inventory_rpa_ready",
|
||||
event_type="onhand_rpa_ready",
|
||||
field_mapping=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
commit=False,
|
||||
@@ -1885,7 +1896,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
path,
|
||||
run_no=run_no,
|
||||
task_no=task.task_no,
|
||||
inventory_file_no=inv_file.inventory_file_no,
|
||||
inventory_file_no=inv_file.onhand_file_no,
|
||||
)
|
||||
promote_ok = False
|
||||
try:
|
||||
@@ -1906,13 +1917,13 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
processed,
|
||||
run_no=run_no,
|
||||
task_no=task.task_no,
|
||||
inventory_file_no=inv_file.inventory_file_no,
|
||||
inventory_file_no=inv_file.onhand_file_no,
|
||||
)
|
||||
if move_warning:
|
||||
post_commit_warnings.append(f"move_callback_file_failed:{move_warning}")
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks
|
||||
from app.services.shipping_notice.onhand_file_store import start_inventory_file_linked_tasks
|
||||
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
except Exception as exc:
|
||||
@@ -1926,10 +1937,25 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if post_commit_warnings:
|
||||
_persist_post_commit_task_event(
|
||||
task,
|
||||
"inventory_rpa_post_commit_warning",
|
||||
{"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no},
|
||||
"onhand_rpa_post_commit_warning",
|
||||
{"warnings": post_commit_warnings, "inventory_file_no": inv_file.onhand_file_no},
|
||||
)
|
||||
|
||||
# [STEP 阶段 B Task 7 修复] 文件行已随上方 db.session.commit() 提交——同请求投递
|
||||
# onhand 报表事实(先 commit 再投递)。处理函数异常必须原样外抛:绝不折进
|
||||
# post_commit_warnings、不吞——已提交文件行保留,Worker 重试整笔回调即可补齐
|
||||
# 候选 settle 与门禁收口(处理函数幂等:重复投递不重复候选行)。
|
||||
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='onhand',
|
||||
source_code=str(inv_file.source_code or ''),
|
||||
file_id=int(inv_file.id),
|
||||
sha256=str(inv_file.file_sha256 or '') or None,
|
||||
ok=True,
|
||||
))
|
||||
|
||||
if response is None:
|
||||
return tool_response(status="failed", task=task, message="RPA 回调处理未完成")
|
||||
if post_commit_warnings:
|
||||
@@ -1963,7 +1989,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
existing_job = (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == 'shipping_inventory_callback_process',
|
||||
Job.job_type == 'freight_rpa_onhand_callback_process',
|
||||
Job.business_ref == f'inventory-callback:{callback_id}',
|
||||
Job.status.in_(('queued', 'running')),
|
||||
)
|
||||
@@ -1996,7 +2022,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS,
|
||||
receipt_payload,
|
||||
domain='shipping_notice',
|
||||
business_ref=f'inventory-callback:{callback_id}',
|
||||
@@ -2119,6 +2145,89 @@ def _received_batch_callback_file_path(
|
||||
return None
|
||||
|
||||
|
||||
class OnhandReportDispatchAfterCommitError(RuntimeError):
|
||||
"""批量 commit 后 onhand 事实投递失败(Task 7 修复轮 3)。
|
||||
|
||||
用途:process_rpa_report_inventory_batch 在排程收口与 drop 文件清理入队完成后,
|
||||
把首轮投递的首个异常连同「未成功文件清单」一并外抛——Job 处器捕获后把清单写回
|
||||
payload(retry_dispatch_files)并 fail_job(retryable=True),重试经「只重投失败
|
||||
文件」通道(_dispatch_retry_onhand_report_files)补齐,不再整批重放(整批重放
|
||||
会被 callback_id 已消费的 replay 检查跳过、且已收口的排程 run 校验会拦下)。
|
||||
继承 RuntimeError:与既有 RuntimeError 契约(测试 match / 调用方捕获)兼容。
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, failed_files: list[dict[str, Any]]) -> None:
|
||||
super().__init__(message)
|
||||
self.failed_files = list(failed_files)
|
||||
|
||||
|
||||
def _dispatch_retry_onhand_report_files(retry_files: list[Any]) -> dict[str, Any]:
|
||||
"""Job 重试通道:只对首轮投递失败的已提交文件重投 onhand 事实(不重放整批)。
|
||||
|
||||
【AI 触发时机】:仅由 process_rpa_report_inventory_batch 在 payload 携带
|
||||
retry_dispatch_files(Job 处理器自 OnhandReportDispatchAfterCommitError 清单写回)
|
||||
时调用;普通 Worker 回调载荷不含该键,永不进入本通道。
|
||||
核心逻辑:逐文件 dispatch_report_fact;单文件处理函数失败先回滚未提交会话
|
||||
(半途写不得被后续 commit 持久化、PendingRollback 不得拖垮后续投递)并收集
|
||||
首个异常与未成功清单;任一失败即携带清单重抛(重试绝不在处理函数未完成时
|
||||
返回 ok);全部成功才返回 ok(result_status='retried'——Job 处理器据此
|
||||
finish_job,且仅在此即全部处理函数已完成的情形下才标记成功)。
|
||||
Args:
|
||||
retry_files: 首轮未成功文件清单({source_code, file_id, sha256} 字典列表)。
|
||||
Returns:
|
||||
tool_response:status='ok'、data.result_status='retried'(非 failed/
|
||||
partial_failed,Job 处理器走 finish_job 成功收口)。
|
||||
Raises:
|
||||
OnhandReportDispatchAfterCommitError: 仍有文件投递失败(携带未成功清单,
|
||||
供 Job 处理器更新 payload 继续重试,直至 attempts 耗尽落终态 failed)。
|
||||
"""
|
||||
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
|
||||
dispatch_error: Exception | None = None
|
||||
remaining: list[dict[str, Any]] = []
|
||||
for item in retry_files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
file_id = int(item.get('file_id'))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
marker = {
|
||||
'source_code': str(item.get('source_code') or ''),
|
||||
'file_id': file_id,
|
||||
'sha256': item.get('sha256'),
|
||||
}
|
||||
try:
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='onhand',
|
||||
source_code=marker['source_code'],
|
||||
file_id=marker['file_id'],
|
||||
sha256=marker['sha256'] if isinstance(marker['sha256'], str) else None,
|
||||
ok=True,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余文件必须继续投递,未成功清单随专用异常重抛
|
||||
db.session.rollback()
|
||||
if dispatch_error is None:
|
||||
dispatch_error = exc
|
||||
remaining.append(marker)
|
||||
logging.getLogger(__name__).warning(
|
||||
'RPA onhand report fact retry dispatch failed: file_id=%s error=%s',
|
||||
marker['file_id'], exc, exc_info=exc,
|
||||
)
|
||||
if dispatch_error is not None:
|
||||
raise OnhandReportDispatchAfterCommitError(
|
||||
f'RPA onhand report fact retry dispatch failed: {dispatch_error}',
|
||||
failed_files=remaining,
|
||||
)
|
||||
return tool_response(
|
||||
status='ok',
|
||||
message=f'库存 RPA 回调重试完成:已补齐投递 {len(retry_files)} 个失败文件。',
|
||||
data={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)},
|
||||
extra={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)},
|
||||
)
|
||||
|
||||
|
||||
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
|
||||
@@ -2128,10 +2237,19 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
含 schedule_run_id 时委托 finalize 终态化排程 run。
|
||||
响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
|
||||
|
||||
cleanup_retry_warnings = flush_callback_cleanup_queue()
|
||||
|
||||
# [STEP 阶段 B Task 7 修复轮 3] Job 重试「只重投失败文件」通道:首轮投递失败后,
|
||||
# Job 处理器把未成功文件清单写回 payload(retry_dispatch_files);重试不再整批
|
||||
# 重放(task-linked 项的 Attempt 已消费 callback_id 会被 replay 检查跳过、已收口
|
||||
# 的排程 run 校验也会拦下整批),只对清单内已提交文件重投事实(处理函数幂等)。
|
||||
# 普通回调载荷不含该键,永不进入本通道。
|
||||
retry_files = payload.get('retry_dispatch_files') if isinstance(payload, dict) else None
|
||||
if retry_files:
|
||||
return _dispatch_retry_onhand_report_files(retry_files)
|
||||
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
@@ -2166,6 +2284,9 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
skipped: list[dict[str, Any]] = []
|
||||
batch_new_storage_paths: list[str] = []
|
||||
pending_callback_moves: list[dict[str, Any]] = []
|
||||
# [STEP 阶段 B Task 7 修复] 整批事务内落地的 onhand 报表文件清单——随 created
|
||||
# 同步追加/回退(单项保存点回滚时该文件行一并消失),整批 commit 后逐文件投递事实。
|
||||
landed_onhand_files: list[dict[str, Any]] = []
|
||||
|
||||
try:
|
||||
for item in results:
|
||||
@@ -2187,8 +2308,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
if not item_callback_id and source_run_no_item:
|
||||
item_callback_id = f"{callback_id}:{source_run_no_item}:C1"
|
||||
if item_callback_id:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none()
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
replay_attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(callback_id=item_callback_id).one_or_none()
|
||||
if replay_attempt is not None:
|
||||
skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True})
|
||||
continue
|
||||
@@ -2382,7 +2503,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
# 调度空结果保留为审计快照,但绝不链接给任务或作为 ready 库存复用。
|
||||
source = _resolve_batch_callback_source(None, merged_item)
|
||||
if source and not task_no:
|
||||
from app.services.shipping_notice.inventory_snapshot_store import create_empty_rpa_inventory_snapshot
|
||||
from app.services.shipping_notice.onhand_snapshot_store import create_empty_rpa_inventory_snapshot
|
||||
|
||||
snapshot = create_empty_rpa_inventory_snapshot(
|
||||
source=source, rpa_run_no=run_no or None, schedule_run_id=schedule_run_id,
|
||||
@@ -2391,7 +2512,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
)
|
||||
skipped.append({
|
||||
'source_code': source_code, 'warehouse_id': warehouse_id,
|
||||
'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.inventory_file_no,
|
||||
'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.onhand_file_no,
|
||||
})
|
||||
continue
|
||||
|
||||
@@ -2427,8 +2548,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
"error": "file_missing",
|
||||
})
|
||||
if task_no and source_run_no_item:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
_att = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
|
||||
if _att:
|
||||
_att.callback_id = item_callback_id or callback_id
|
||||
_att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False
|
||||
@@ -2476,7 +2597,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
item_savepoint = db.session.begin_nested()
|
||||
item_orphan_path: str | None = None
|
||||
created_new = False
|
||||
inv_file: ShippingInventoryFile | None = None
|
||||
inv_file: FreightRpaOnhandReportFile | None = None
|
||||
created_entry: dict[str, Any] | None = None
|
||||
try:
|
||||
try:
|
||||
@@ -2505,7 +2626,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
):
|
||||
item_orphan_path = str(inv_file.storage_path)
|
||||
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
|
||||
|
||||
ingest_path = _snapshot_ingest_path(inv_file)
|
||||
structure_check = validate_production_inventory_structure(
|
||||
@@ -2516,7 +2637,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
inv_file.mapping_source = 'parsing_profile'
|
||||
inv_file.mapping_confirmed = True
|
||||
created_entry = {
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"source_code": inv_file.source_code or source_code,
|
||||
"warehouse_id": inv_file.warehouse_id or warehouse_id,
|
||||
"reused_existing_snapshot": not created_new,
|
||||
@@ -2529,6 +2650,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
},
|
||||
}
|
||||
created.append(created_entry)
|
||||
# [STEP 阶段 B Task 7 修复] 记录落地文件(含复用行——同样随整批事务提交),
|
||||
# 供整批 commit 后投递 onhand 报表事实;except 分支随 created 一并回退。
|
||||
landed_onhand_files.append({
|
||||
'source_code': str(inv_file.source_code or source_code or ''),
|
||||
'file_id': int(inv_file.id),
|
||||
'sha256': str(inv_file.file_sha256 or '') or None,
|
||||
})
|
||||
if item_orphan_path:
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
|
||||
@@ -2562,7 +2690,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
lines,
|
||||
column_meta=column_meta,
|
||||
source="rpa_batch_callback",
|
||||
event_type="inventory_rpa_ready",
|
||||
event_type="onhand_rpa_ready",
|
||||
field_mapping=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
commit=False,
|
||||
@@ -2583,7 +2711,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
'inventory_file_no': inv_file.onhand_file_no,
|
||||
},
|
||||
)
|
||||
if final_code != 'succeeded':
|
||||
@@ -2605,20 +2733,24 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
"run_no": run_no or None,
|
||||
"task_no": task_no or None,
|
||||
"schedule_run_id": schedule_run_id,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
})
|
||||
|
||||
item_savepoint.commit()
|
||||
except _RpaCallbackItemAbort as abort:
|
||||
item_savepoint.rollback()
|
||||
if item_orphan_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(item_orphan_path)
|
||||
if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
|
||||
batch_new_storage_paths.pop()
|
||||
if created_entry and created and created[-1] is created_entry:
|
||||
created.pop()
|
||||
# [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录
|
||||
# (保存点回滚后该文件行已消失,不得再投递其事实)。
|
||||
if landed_onhand_files:
|
||||
landed_onhand_files.pop()
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
@@ -2629,13 +2761,17 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
except Exception as exc:
|
||||
item_savepoint.rollback()
|
||||
if item_orphan_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(item_orphan_path)
|
||||
if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path:
|
||||
batch_new_storage_paths.pop()
|
||||
if created_entry and created and created[-1] is created_entry:
|
||||
created.pop()
|
||||
# [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录
|
||||
# (保存点回滚后该文件行已消失,不得再投递其事实)。
|
||||
if landed_onhand_files:
|
||||
landed_onhand_files.pop()
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
@@ -2661,7 +2797,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
for storage_path in batch_new_storage_paths:
|
||||
delete_inventory_storage_path(storage_path)
|
||||
@@ -2674,9 +2810,47 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 阶段 B Task 7 修复轮 2/3] 整批文件行已随上方 db.session.commit() 提交——同一
|
||||
# worker 调用内逐文件投递 onhand 报表事实(先 commit 再投递)。必须放在外层
|
||||
# except 之后:处理函数异常若落入该 except 会误删已提交文件的存储对象。
|
||||
# 单文件处理函数失败只收集首个异常并继续投递其余已提交文件(不得因一文件失败
|
||||
# 跳过其余文件的候选/门禁收口);【修复轮 3】失败点先回滚未提交会话——丢弃该次
|
||||
# 处理函数半途 flush 的候选/门禁写(否则会被下一个处理函数的 commit / finalize
|
||||
# 的 commit 误持久化,且数据库错误后的 PendingRollback 会拖垮后续投递与收口),
|
||||
# 已 commit 的文件行不受影响(rollback 只丢弃未提交变更)。首个异常与未成功
|
||||
# 文件清单在排程收口、drop 文件清理入队之后携带在专用异常上原样重抛(见下)——
|
||||
# 调用方见到失败、文件行保留,Job 按 retryable=True 契约经「只重投失败文件」
|
||||
# 通道补齐(处理函数幂等:重复投递不重复候选行)。空结果审计快照
|
||||
# (create_empty_rpa_inventory_snapshot,no_inventory_data 分支)不投递——其明令
|
||||
# 不作为可用库存复用,投递 ok=True 事实会错误 settle 等待中的候选准备。
|
||||
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
|
||||
dispatch_error: Exception | None = None
|
||||
failed_dispatch_files: list[dict[str, Any]] = []
|
||||
for landed in landed_onhand_files:
|
||||
try:
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='onhand',
|
||||
source_code=str(landed['source_code'] or ''),
|
||||
file_id=int(landed['file_id']),
|
||||
sha256=landed['sha256'],
|
||||
ok=True,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余已提交文件必须继续投递,首个异常携带未成功清单在收口/清理之后重抛
|
||||
# [修复轮 3] 回滚未提交会话:半途写不得被后续 commit 持久化;PendingRollback 解除。
|
||||
db.session.rollback()
|
||||
if dispatch_error is None:
|
||||
dispatch_error = exc
|
||||
failed_dispatch_files.append(dict(landed))
|
||||
logging.getLogger(__name__).warning(
|
||||
'RPA onhand report fact dispatch failed after batch commit: file_id=%s error=%s',
|
||||
landed['file_id'], exc, exc_info=exc,
|
||||
)
|
||||
|
||||
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
|
||||
if schedule_run_id is not None:
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
from app.services.schedule.freight_rpa_onhand_finalize import finalize_shipping_inventory_schedule_run
|
||||
|
||||
finalize_result = finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id,
|
||||
@@ -2695,6 +2869,18 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
),
|
||||
)
|
||||
|
||||
# [STEP 阶段 B Task 7 修复轮 3] drop 文件清理已先行入队/移动(不得因重抛被跳过
|
||||
# ——清理只在 _flush_pending_callback_moves 内写消费标记/入队,先于此处执行):
|
||||
# 首个投递异常携带未成功文件清单在专用异常上原样重抛——调用方(Job/Worker)
|
||||
# 见到失败、已提交文件行保留;Job 处理器把清单写回 payload(retry_dispatch_files)
|
||||
# 后 fail_job(retryable=True),重试经「只重投失败文件」通道补齐(见函数头部),
|
||||
# 全部投递成功前绝不返回 ok(重试不得在处理函数未完成时被记成功)。
|
||||
if dispatch_error is not None:
|
||||
raise OnhandReportDispatchAfterCommitError(
|
||||
f'RPA onhand report fact dispatch failed after batch commit: {dispatch_error}',
|
||||
failed_files=failed_dispatch_files,
|
||||
)
|
||||
|
||||
response_data = {
|
||||
"run_no": run_no,
|
||||
"created": created,
|
||||
@@ -2743,7 +2929,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
def _validate_repair_inventory_snapshot(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile | None,
|
||||
inv_file: FreightRpaOnhandReportFile | None,
|
||||
*,
|
||||
requested_file_no: str | None = None,
|
||||
) -> str | None:
|
||||
@@ -2751,10 +2937,10 @@ def _validate_repair_inventory_snapshot(
|
||||
校验修复接口允许使用的库存快照。
|
||||
核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。
|
||||
"""
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.models import ShippingTaskOnhandLink
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_snapshot_store import is_snapshot_fresh
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
inventory_identities_match,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
@@ -2766,12 +2952,12 @@ def _validate_repair_inventory_snapshot(
|
||||
return "no_active_snapshot"
|
||||
if inv_file.id != active.id:
|
||||
return "snapshot_not_active_for_task"
|
||||
if requested_file_no and active.inventory_file_no != requested_file_no:
|
||||
if requested_file_no and active.onhand_file_no != requested_file_no:
|
||||
return "snapshot_not_active_for_task"
|
||||
if task.id is not None:
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
link = ShippingTaskOnhandLink.query.filter_by(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inv_file.id,
|
||||
onhand_file_id=inv_file.id,
|
||||
is_active=True,
|
||||
).first()
|
||||
if link is None:
|
||||
@@ -2782,7 +2968,7 @@ def _validate_repair_inventory_snapshot(
|
||||
return "snapshot_expired"
|
||||
if not is_inventory_source_stable(task):
|
||||
return "inventory_source_unstable"
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(inv_file.source_code)
|
||||
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
@@ -2806,7 +2992,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
tool_response:含 attachment_path 与 inventory_file_no。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
|
||||
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
@@ -2821,7 +3007,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message="任务无可用库存快照,无法重建附件",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
if inv_file_no and inv_file.inventory_file_no != inv_file_no:
|
||||
if inv_file_no and inv_file.onhand_file_no != inv_file_no:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
@@ -2856,7 +3042,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
"inventory_attachment_repaired",
|
||||
{
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"attachment_path": str(attachment_path),
|
||||
"source": str(payload.get("source") or "manual_repair"),
|
||||
},
|
||||
@@ -2878,7 +3064,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message="任务库存附件已从快照重建",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"attachment_path": str(attachment_path),
|
||||
},
|
||||
)
|
||||
+10
-10
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_snapshot.py
|
||||
services/shipping_notice/onhand_snapshot.py
|
||||
|
||||
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
|
||||
依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。
|
||||
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
|
||||
逻辑:由 onhand_workflow、onhand_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -187,12 +187,12 @@ def _normalize_inventory_row(
|
||||
# Published profiles use inventory field IDs as row keys. Field purpose and
|
||||
# value type come from the user-maintained catalog, never from a fixed code.
|
||||
if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns):
|
||||
from app.models import ShippingInventoryField
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()}
|
||||
catalog = {
|
||||
str(item.id): item
|
||||
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
|
||||
for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()
|
||||
}
|
||||
parsed = {
|
||||
field_id: _cell(row, index)
|
||||
@@ -334,7 +334,7 @@ def _load_excel_rows(
|
||||
"""Load configured worksheet or CSV rows; returns rows and total row count hint."""
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".csv":
|
||||
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
|
||||
from app.services.shipping_notice.onhand_file_identity import load_inventory_csv_rows
|
||||
|
||||
rows = load_inventory_csv_rows(path, max_rows=max_rows)
|
||||
try:
|
||||
@@ -422,7 +422,7 @@ def describe_inventory_columns(
|
||||
) -> dict[str, Any]:
|
||||
"""根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。"""
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import build_column_meta_from_mapping
|
||||
|
||||
return build_column_meta_from_mapping(
|
||||
headers,
|
||||
@@ -587,7 +587,7 @@ def parse_inventory_rows(
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按表头与数据行解析库存表格(Excel 或文档提取文本共用)。"""
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
|
||||
|
||||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||||
else:
|
||||
@@ -627,7 +627,7 @@ def parse_inventory_text(
|
||||
|
||||
header = rows[0]
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
|
||||
|
||||
has_header = True
|
||||
column_meta = describe_inventory_columns(
|
||||
@@ -659,7 +659,7 @@ def read_inventory_schema_preview(
|
||||
max_sample_rows: int = 5,
|
||||
) -> dict[str, Any]:
|
||||
"""仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。"""
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||||
|
||||
scan_rows, total_rows = _load_excel_rows(path, max_rows=40)
|
||||
if not scan_rows:
|
||||
@@ -724,7 +724,7 @@ def parse_inventory_excel_with_meta(
|
||||
headers = [str(c or "").strip() for c in rows[header_idx]]
|
||||
data_rows = [list(r) for r in rows[header_idx + 1 :] if r]
|
||||
if not field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||||
|
||||
suggested = suggest_field_mapping(headers)
|
||||
if suggested.get("part_number") and suggested.get("available_qty"):
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_snapshot_reuse_policy.py
|
||||
services/shipping_notice/onhand_snapshot_reuse_policy.py
|
||||
|
||||
用途:统一判断库存快照是否可被当前任务复用。
|
||||
依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。
|
||||
依赖:FreightRpaOnhandReportFile、ShippingNotice、候选冻结事实。
|
||||
逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。
|
||||
"""
|
||||
|
||||
+70
-65
@@ -1,9 +1,12 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_snapshot_store.py
|
||||
services/shipping_notice/onhand_snapshot_store.py
|
||||
|
||||
用途:库存快照查询、TTL 复用、RPA 入库与任务关联审计。
|
||||
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_file_store、Flask config。
|
||||
逻辑:ensure_inventory 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录。
|
||||
依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读取回行,禁止构造)、
|
||||
freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_file_store、Flask config。
|
||||
逻辑:ensure_onhand 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录;
|
||||
阶段 B Task 5 起新建/空快照行一律经 report_store.insert_onhand_report 插入,
|
||||
本模块只在拿回 file_id 后按主键取回 ORM 对象并维护任务 link(关联表留在发货域)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,36 +22,37 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingTaskEvent, ShippingTaskOnhandLink
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
_can_relink_inventory,
|
||||
generate_inventory_file_no,
|
||||
inventory_file_upload_path,
|
||||
inventory_storage_suffix_for_path,
|
||||
replace_task_inventory_link,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview
|
||||
from app.services.shipping_notice.onhand_snapshot import read_inventory_schema_preview
|
||||
|
||||
_SNAPSHOT_STATUS_READY = "ready"
|
||||
_SNAPSHOT_STATUS_EMPTY = "empty"
|
||||
_SNAPSHOT_STATUS_FAILED = "failed"
|
||||
_SNAPSHOT_STATUS_EXPIRED = "expired"
|
||||
|
||||
# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。
|
||||
# 请求内只读缓存(key: (source_code, warehouse_id) → FreightRpaOnhandReportFile | None)。
|
||||
# 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一
|
||||
# (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。
|
||||
# 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。
|
||||
_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache"
|
||||
_READ_CACHE_KEY = "shipping_onhand_snapshot_read_cache"
|
||||
|
||||
|
||||
@_sa_event.listens_for(Session, "after_flush")
|
||||
def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001
|
||||
"""快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。"""
|
||||
touched = (
|
||||
any(isinstance(obj, ShippingInventoryFile) for obj in session.new)
|
||||
or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty)
|
||||
or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted)
|
||||
any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.new)
|
||||
or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.dirty)
|
||||
or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.deleted)
|
||||
)
|
||||
if touched:
|
||||
session.info.pop(_READ_CACHE_KEY, None)
|
||||
@@ -80,10 +84,10 @@ def snapshot_expires_at(exported_at: datetime | None = None) -> datetime:
|
||||
return base + timedelta(hours=inventory_snapshot_ttl_hours())
|
||||
|
||||
|
||||
def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = None) -> bool:
|
||||
def is_snapshot_fresh(inv_file: FreightRpaOnhandReportFile, *, now: datetime | None = None) -> bool:
|
||||
"""
|
||||
判断库存快照是否仍处于 ready 且未过期。
|
||||
【AI 触发时机】:ensure_inventory 决定是否复用已有快照前调用。
|
||||
【AI 触发时机】:ensure_onhand 决定是否复用已有快照前调用。
|
||||
"""
|
||||
if not inv_file or str(inv_file.snapshot_status or "").strip().lower() != _SNAPSHOT_STATUS_READY:
|
||||
return False
|
||||
@@ -99,7 +103,7 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
|
||||
def find_latest_ready_snapshot(
|
||||
source_code: str | None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> ShippingInventoryFile | None:
|
||||
) -> FreightRpaOnhandReportFile | None:
|
||||
"""
|
||||
查找指定 Source 的最新 ready 且未过期库存快照。
|
||||
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
|
||||
@@ -119,14 +123,14 @@ def find_latest_ready_snapshot(
|
||||
if cache_key in read_cache:
|
||||
return read_cache[cache_key]
|
||||
|
||||
query = ShippingInventoryFile.query.filter_by(
|
||||
query = FreightRpaOnhandReportFile.query.filter_by(
|
||||
source_code=code,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
if warehouse:
|
||||
query = query.filter_by(warehouse_id=warehouse)
|
||||
|
||||
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
|
||||
rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc()).limit(5).all()
|
||||
result = None
|
||||
for row in rows:
|
||||
if is_snapshot_fresh(row):
|
||||
@@ -141,7 +145,7 @@ def find_ready_rpa_inventory_snapshot(
|
||||
rpa_run_no: str,
|
||||
source_code: str,
|
||||
warehouse_id: str,
|
||||
) -> ShippingInventoryFile | None:
|
||||
) -> FreightRpaOnhandReportFile | None:
|
||||
"""
|
||||
按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。
|
||||
核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
|
||||
@@ -152,13 +156,13 @@ def find_ready_rpa_inventory_snapshot(
|
||||
if not run_no or not code or not warehouse:
|
||||
return None
|
||||
return (
|
||||
ShippingInventoryFile.query.filter_by(
|
||||
FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
warehouse_id=warehouse,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
.order_by(ShippingInventoryFile.id.desc())
|
||||
.order_by(FreightRpaOnhandReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -177,13 +181,13 @@ def get_or_create_rpa_inventory_snapshot(
|
||||
batch_id: int | None = None,
|
||||
share_mode: str | None = None,
|
||||
verify_warehouse_id: str | None = None,
|
||||
) -> tuple[ShippingInventoryFile, bool]:
|
||||
) -> tuple[FreightRpaOnhandReportFile, bool]:
|
||||
"""
|
||||
幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。
|
||||
核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。
|
||||
|
||||
Returns:
|
||||
tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。
|
||||
tuple[FreightRpaOnhandReportFile, bool]: (快照, 是否新建)。
|
||||
"""
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
@@ -224,7 +228,7 @@ def get_or_create_rpa_inventory_snapshot(
|
||||
except IntegrityError:
|
||||
savepoint.rollback()
|
||||
if orphan_storage_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(orphan_storage_path)
|
||||
if run_no and code and warehouse:
|
||||
@@ -239,7 +243,7 @@ def get_or_create_rpa_inventory_snapshot(
|
||||
except Exception:
|
||||
savepoint.rollback()
|
||||
if orphan_storage_path:
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(orphan_storage_path)
|
||||
raise
|
||||
@@ -250,18 +254,18 @@ def list_available_snapshots(
|
||||
source_code: str | None = None,
|
||||
warehouse_id: str | None = None,
|
||||
limit: int = 20,
|
||||
) -> list[ShippingInventoryFile]:
|
||||
) -> list[FreightRpaOnhandReportFile]:
|
||||
"""列出未过期 ready 快照,供工作台查询。"""
|
||||
query = ShippingInventoryFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY)
|
||||
query = FreightRpaOnhandReportFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY)
|
||||
if source_code:
|
||||
query = query.filter_by(source_code=str(source_code).strip().upper())
|
||||
if warehouse_id:
|
||||
query = query.filter_by(warehouse_id=str(warehouse_id).strip().upper())
|
||||
rows = query.order_by(ShippingInventoryFile.exported_at.desc()).limit(max(limit, 1)).all()
|
||||
rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc()).limit(max(limit, 1)).all()
|
||||
return [row for row in rows if is_snapshot_fresh(row)]
|
||||
|
||||
|
||||
def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None:
|
||||
def expire_snapshot(inv_file: FreightRpaOnhandReportFile, reason: str) -> None:
|
||||
"""将快照标记为 expired。"""
|
||||
inv_file.snapshot_status = _SNAPSHOT_STATUS_EXPIRED
|
||||
inv_file.updated_at = datetime.utcnow()
|
||||
@@ -274,7 +278,7 @@ def _normalize_header_key(value: Any) -> str:
|
||||
|
||||
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
|
||||
"""从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。"""
|
||||
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
|
||||
values = extract_warehouse_ids_from_inventory_excel(path)
|
||||
if not values:
|
||||
@@ -298,7 +302,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
batch_id: int | None = None,
|
||||
share_mode: str | None = None,
|
||||
verify_warehouse_id: str | None = None,
|
||||
) -> ShippingInventoryFile:
|
||||
) -> FreightRpaOnhandReportFile:
|
||||
"""
|
||||
从 RPA 导出文件创建库存快照记录。
|
||||
【AI 触发时机】:RPA 单条或 batch 回调成功/失败时调用;定时任务只入库不绑定发货任务。
|
||||
@@ -310,7 +314,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
success: False 时写入 failed 快照,不复制文件到标准目录。
|
||||
|
||||
Returns:
|
||||
ShippingInventoryFile: 已持久化的快照对象。
|
||||
FreightRpaOnhandReportFile: 已持久化的快照对象。
|
||||
"""
|
||||
exported_at = datetime.utcnow()
|
||||
inventory_file_no = generate_inventory_file_no()
|
||||
@@ -328,7 +332,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
local = Path(local_path)
|
||||
# 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel
|
||||
|
||||
excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local)
|
||||
if len(excel_warehouse_ids) == 1:
|
||||
@@ -354,10 +358,13 @@ def create_inventory_snapshot_from_rpa(
|
||||
snapshot_status = _SNAPSHOT_STATUS_FAILED
|
||||
storage_path = str(path) if path and path.is_file() else ""
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
# [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit),
|
||||
# 本模块只在拿到 file_id 后取回 ORM 对象;先 flush 再落盘的语义由 report_store 保持,
|
||||
# 唯一约束冲突时同样不会留下已复制的孤儿文件。
|
||||
file_id = insert_onhand_report(
|
||||
onhand_file_no=inventory_file_no,
|
||||
user_id=user_id,
|
||||
source_file_name=str(source_file_name or (path.name if path else "")).strip() or None,
|
||||
storage_path=storage_path or f"failed://{inventory_file_no}",
|
||||
@@ -399,9 +406,8 @@ def create_inventory_snapshot_from_rpa(
|
||||
"trigger_type": trigger_type,
|
||||
},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
# [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。
|
||||
inv_file = db.session.get(FreightRpaOnhandReportFile, file_id)
|
||||
# [STEP] flush 已在 report_store 内完成,此处先落盘再返回:唯一约束冲突(上面 insert 抛出)时不会留下已复制的孤儿文件。
|
||||
if success and storage_path and not str(storage_path).startswith("failed://"):
|
||||
path = Path(storage_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -420,25 +426,26 @@ def create_inventory_snapshot_from_rpa(
|
||||
def create_empty_rpa_inventory_snapshot(
|
||||
*, source: dict[str, Any], rpa_run_no: str | None, schedule_run_id: int | None,
|
||||
trigger_type: str, message: str | None = None,
|
||||
) -> ShippingInventoryFile:
|
||||
) -> FreightRpaOnhandReportFile:
|
||||
"""记录 RPA 已成功执行但没有库存行的空快照;空快照永不参与库存匹配。"""
|
||||
exported_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version
|
||||
|
||||
source_code = str(source.get('source_code') or '').strip().upper()
|
||||
warehouse_id = str(source.get('warehouse_id') or '').strip().upper() or None
|
||||
run_no = str(rpa_run_no or '').strip() or None
|
||||
if run_no and source_code:
|
||||
existing = ShippingInventoryFile.query.filter_by(
|
||||
existing = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no=run_no, source_code=source_code, warehouse_id=warehouse_id,
|
||||
snapshot_status=_SNAPSHOT_STATUS_EMPTY,
|
||||
).order_by(ShippingInventoryFile.id.desc()).first()
|
||||
).order_by(FreightRpaOnhandReportFile.id.desc()).first()
|
||||
if existing is not None:
|
||||
return existing
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}',
|
||||
# [STEP] 阶段 B Task 5:空快照行同样经 report_store 插入(列集与原构造逐项一致;只 flush 不 commit)。
|
||||
file_id = insert_onhand_report(
|
||||
onhand_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}',
|
||||
schema_preview_json={'export_result': 'empty', 'message': str(message or '库存查询成功但当前无库存数据')[:500]},
|
||||
share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id,
|
||||
share_mode='warehouse_pool', line_count=0, onhand_lines_json=[], warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id, source_code=source_code or None,
|
||||
source_type=str(source.get('connector_type') or '').strip() or None,
|
||||
# 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。
|
||||
@@ -447,41 +454,39 @@ def create_empty_rpa_inventory_snapshot(
|
||||
rpa_run_no=run_no, schedule_run_id=schedule_run_id,
|
||||
source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
return inv_file
|
||||
return db.session.get(FreightRpaOnhandReportFile, file_id)
|
||||
|
||||
|
||||
def link_snapshot_to_task(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
*,
|
||||
reason: str,
|
||||
role: str = "member",
|
||||
audit_payload: dict[str, Any] | None = None,
|
||||
) -> ShippingTaskInventoryLink | None:
|
||||
) -> ShippingTaskOnhandLink | None:
|
||||
"""
|
||||
将 ready 库存快照关联到发货任务并写入审计字段。
|
||||
【AI 触发时机】:ensure_inventory 复用快照或 RPA 回调带 task_no 时调用。
|
||||
【AI 触发时机】:ensure_onhand 复用快照或 RPA 回调带 task_no 时调用。
|
||||
|
||||
Returns:
|
||||
ShippingTaskInventoryLink | None: 终态任务不允许 relink 时返回 None。
|
||||
ShippingTaskOnhandLink | None: 终态任务不允许 relink 时返回 None。
|
||||
"""
|
||||
if not _can_relink_inventory(task):
|
||||
return None
|
||||
if not is_snapshot_fresh(inv_file):
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(inv_file.source_code)
|
||||
if source is None:
|
||||
return None
|
||||
resolved_warehouse_id = inv_file.warehouse_id
|
||||
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
|
||||
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
|
||||
from app.services.shipping_notice.onhand_warehouse_resolution import resolve_dynamic_warehouse
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
|
||||
|
||||
try:
|
||||
lines, _column_meta = read_inventory_file_lines(inv_file)
|
||||
@@ -508,7 +513,7 @@ def link_snapshot_to_task(
|
||||
if inv_file.exported_at:
|
||||
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
|
||||
|
||||
from app.services.shipping_notice.inventory_source_gate import inventory_identities_match
|
||||
from app.services.shipping_notice.onhand_source_gate import inventory_identities_match
|
||||
|
||||
identity_ok = inventory_identities_match(
|
||||
task,
|
||||
@@ -532,7 +537,7 @@ def link_snapshot_to_task(
|
||||
"warehouse_id": resolved_warehouse_id,
|
||||
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
|
||||
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
|
||||
}
|
||||
db.session.add(
|
||||
@@ -540,7 +545,7 @@ def link_snapshot_to_task(
|
||||
task_id=task_event_task_id(task),
|
||||
event_type="inventory_snapshot_linked",
|
||||
detail_json={
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"link_reason": reason,
|
||||
"snapshot_age_seconds": age_seconds,
|
||||
"warehouse_id": resolved_warehouse_id,
|
||||
@@ -553,11 +558,11 @@ def link_snapshot_to_task(
|
||||
|
||||
def link_snapshot_to_task_for_preparation(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
*,
|
||||
reason: str,
|
||||
audit_payload: dict[str, Any] | None = None,
|
||||
) -> ShippingTaskInventoryLink | None:
|
||||
) -> ShippingTaskOnhandLink | None:
|
||||
"""将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。
|
||||
|
||||
动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论,
|
||||
@@ -573,7 +578,7 @@ def link_snapshot_to_task_for_preparation(
|
||||
if link is not None:
|
||||
return link
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(inv_file.source_code)
|
||||
if (
|
||||
@@ -584,7 +589,7 @@ def link_snapshot_to_task_for_preparation(
|
||||
):
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link
|
||||
from app.services.shipping_notice.onhand_file_store import replace_task_inventory_link
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file)
|
||||
link.link_reason = f'{reason}_pending_matching'
|
||||
@@ -593,7 +598,7 @@ def link_snapshot_to_task_for_preparation(
|
||||
link.audit_payload_json = {
|
||||
**(audit_payload or {}),
|
||||
'source_code': inv_file.source_code,
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
'inventory_file_no': inv_file.onhand_file_no,
|
||||
'identity_status': inv_file.identity_status,
|
||||
}
|
||||
return link
|
||||
@@ -604,8 +609,8 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] |
|
||||
if task.id is None:
|
||||
return None
|
||||
link = (
|
||||
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
|
||||
.order_by(ShippingTaskInventoryLink.id.desc())
|
||||
ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True)
|
||||
.order_by(ShippingTaskOnhandLink.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not link or not link.inventory_file:
|
||||
@@ -613,7 +618,7 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] |
|
||||
inv_file = link.inventory_file
|
||||
trigger_type = (inv_file.source_query_json or {}).get("trigger_type") if isinstance(inv_file.source_query_json, dict) else None
|
||||
return {
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"source_code": inv_file.source_code,
|
||||
"warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id,
|
||||
"warehouse_code": inv_file.warehouse_code,
|
||||
+28
-27
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_gate.py
|
||||
services/shipping_notice/onhand_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
|
||||
依赖:onhand_source_rules、onhand_source_repository、models.ShippingOrderTask、core.errors。
|
||||
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
|
||||
apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet;
|
||||
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
|
||||
@@ -14,30 +14,31 @@ from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
resolve_ambiguous_source_from_ready_snapshots,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import (
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import (
|
||||
freeze_candidates_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
|
||||
|
||||
# 发货通知业务错误码,族名为 SHIPPING.ONHAND_*。货代 RPA 模块错误使用 FREIGHT_RPA_*。
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
|
||||
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
|
||||
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
|
||||
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
|
||||
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
"unresolved": "SHIPPING.ONHAND_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.ONHAND_SOURCE_AMBIGUOUS",
|
||||
"invalid": "SHIPPING.ONHAND_SOURCE_INVALID",
|
||||
"conflicted": "SHIPPING.ONHAND_SOURCE_CONFLICTED",
|
||||
"changed": "SHIPPING.ONHAND_SOURCE_CHANGED",
|
||||
"identity_mismatch": "SHIPPING.ONHAND_IDENTITY_MISMATCH",
|
||||
"gate_blocked": "SHIPPING.ONHAND_SOURCE_GATE_BLOCKED",
|
||||
}
|
||||
|
||||
|
||||
@@ -49,10 +50,10 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
|
||||
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
|
||||
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
codes = task_frozen_onhand_source_codes(task)
|
||||
lines = get_active_candidate_lines(task)
|
||||
if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines):
|
||||
return False
|
||||
@@ -67,7 +68,7 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
|
||||
|
||||
current = get_active_candidate_set(task)
|
||||
previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip()
|
||||
@@ -206,7 +207,7 @@ def transition_task_to_inventory_source_review(
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
# OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流,
|
||||
# 不能在通知准备前写入 OT。
|
||||
task.stage = "inventory_source_resolving"
|
||||
task.stage = "onhand_source_resolving"
|
||||
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
|
||||
payload = dict(getattr(task, 'step_payload_json', None) or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
@@ -227,7 +228,7 @@ def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySo
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
|
||||
|
||||
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
|
||||
【AI 触发时机】:confirm_parse / auto_progress / ensure_onhand 等入口发现门禁未通过时调用。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。
|
||||
"""
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
@@ -281,11 +282,11 @@ def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
|
||||
|
||||
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
task = resolve_inventory_fact_task(task)
|
||||
source_codes = task_frozen_inventory_source_codes(task)
|
||||
source_codes = task_frozen_onhand_source_codes(task)
|
||||
source_code = source_codes[0] if len(source_codes) == 1 else None
|
||||
source = get_database_inventory_source(source_code) if source_code else None
|
||||
return {
|
||||
@@ -309,20 +310,20 @@ def resolve_inventory_source_warehouse_id(
|
||||
if mode == 'fixed':
|
||||
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
|
||||
|
||||
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
|
||||
from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task
|
||||
|
||||
task = resolve_inventory_fact_task(task)
|
||||
task_id = getattr(task, 'id', None)
|
||||
source_code = str(source.get('source_code') or '').strip().upper()
|
||||
if not task_id or not source_code:
|
||||
return None
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
from app.models import ShippingTaskOnhandLink
|
||||
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
link = ShippingTaskOnhandLink.query.filter_by(
|
||||
task_id=int(task_id),
|
||||
matched_source_code=source_code,
|
||||
is_active=True,
|
||||
).order_by(ShippingTaskInventoryLink.id.desc()).first()
|
||||
).order_by(ShippingTaskOnhandLink.id.desc()).first()
|
||||
if link is None:
|
||||
return None
|
||||
return (
|
||||
@@ -354,9 +355,9 @@ def inventory_identities_match(
|
||||
if expected_code != task_code:
|
||||
return False
|
||||
else:
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
frozen = set(task_frozen_inventory_source_codes(task))
|
||||
frozen = set(task_frozen_onhand_source_codes(task))
|
||||
if expected_code not in frozen:
|
||||
return False
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_identity.py
|
||||
services/shipping_notice/onhand_source_identity.py
|
||||
|
||||
用途:校验库存源与 Warehouse 的两段式身份。
|
||||
依赖:无业务模块反向依赖。
|
||||
+27
-17
@@ -1,18 +1,21 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_repository.py
|
||||
services/shipping_notice/onhand_source_repository.py
|
||||
|
||||
用途:提供库存源主数据的最小一致性校验和受控读取入口。
|
||||
依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。
|
||||
依赖:models.FreightRpaSource/FreightRpaProfile/FreightRpaOnhandReportConfig、core.errors.ValidationError。
|
||||
逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。
|
||||
s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 配置行,
|
||||
本模块非敏感快照与运行时版本指纹均改读配置行;配置行缺失即「站点未就绪」,
|
||||
沿用返回 None 的既有跳过/失败语义,不新造错误码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile
|
||||
from app.models import FreightRpaSource, FreightRpaProfile
|
||||
|
||||
|
||||
def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None:
|
||||
def validate_source_profile(source: FreightRpaSource, profile: FreightRpaProfile) -> None:
|
||||
"""
|
||||
校验库存源引用的 RPA Profile 与其 Driver 类型一致。
|
||||
|
||||
@@ -26,11 +29,11 @@ def validate_source_profile(source: ShippingInventorySource, profile: ShippingRp
|
||||
source_type = str(source.connector_type or '').strip().lower()
|
||||
profile_type = str(profile.connector_type or '').strip().lower()
|
||||
if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}:
|
||||
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID')
|
||||
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.ONHAND_CONNECTOR_INVALID')
|
||||
if source_type != profile_type:
|
||||
raise ValidationError(
|
||||
'Inventory Source connector_type must match its RPA Profile',
|
||||
code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH',
|
||||
code='SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH',
|
||||
)
|
||||
|
||||
|
||||
@@ -48,7 +51,7 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
|
||||
code = str(source_code or '').strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=code).first()
|
||||
if source is None or (enabled_only and not source.enabled):
|
||||
return None
|
||||
profile = source.rpa_profile
|
||||
@@ -57,9 +60,14 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
|
||||
login_config = dict(profile.login_config_json or {'auth_mode': 'password'})
|
||||
if login_config.get('auth_mode') != 'password':
|
||||
return None
|
||||
# s18 起报表路径/查询条件/解析方案绑定归 onhand_report_config 配置行;
|
||||
# 配置行缺失即「站点未就绪」,沿用返回 None 的既有跳过/失败语义,不新造错误码。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
return None
|
||||
# Source owns report navigation and business query values. Driver behavior is
|
||||
# code/template-owned and never travels through a login connection profile.
|
||||
source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {}
|
||||
source_navigation = dict(config.report_path_json or {}) if source.connector_type == 'dbs' else {}
|
||||
return {
|
||||
'source_code': source.source_code,
|
||||
'display_name': source.display_name,
|
||||
@@ -70,17 +78,17 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
|
||||
'warehouse_id': source.fixed_warehouse_id,
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
|
||||
'config_version': source.config_version,
|
||||
'parsing_profile_id': source.parsing_profile_id,
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'report_path_json': dict(source.report_path_json or {}),
|
||||
'query_parameters_json': list(source.query_parameters_json or []),
|
||||
'report_path_json': dict(config.report_path_json or {}),
|
||||
'query_parameters_json': list(config.query_parameters_json or []),
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
# 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页,
|
||||
# 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
|
||||
'navigation': source_navigation,
|
||||
'parameters': list(source.query_parameters_json or []),
|
||||
'parameters': list(config.query_parameters_json or []),
|
||||
'query': {},
|
||||
'login_url': profile.login_url,
|
||||
'login_config': login_config,
|
||||
@@ -92,7 +100,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T
|
||||
source_config = get_database_inventory_source(source_code, enabled_only=enabled_only)
|
||||
if source_config is None:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=source_config['source_code']).first()
|
||||
profile = source.rpa_profile if source else None
|
||||
if profile is None or (enabled_only and not profile.enabled):
|
||||
return None
|
||||
@@ -106,7 +114,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T
|
||||
|
||||
def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]:
|
||||
"""列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。"""
|
||||
query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code)
|
||||
query = FreightRpaSource.query.order_by(FreightRpaSource.source_code)
|
||||
if enabled_only:
|
||||
query = query.filter_by(enabled=True)
|
||||
result = []
|
||||
@@ -123,8 +131,10 @@ def inventory_sources_runtime_version() -> str:
|
||||
import json
|
||||
|
||||
rows = []
|
||||
for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all():
|
||||
for source in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all():
|
||||
profile = source.rpa_profile
|
||||
# s18 起报表路径/查询条件归 onhand_report_config 配置行;配置行缺失按空配置参与指纹。
|
||||
config = source.onhand_report_config
|
||||
rows.append({
|
||||
'source_code': source.source_code,
|
||||
'source_version': source.config_version,
|
||||
@@ -136,8 +146,8 @@ def inventory_sources_runtime_version() -> str:
|
||||
'connector_type': source.connector_type,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'report_path_json': source.report_path_json or {},
|
||||
'query_parameters_json': source.query_parameters_json or [],
|
||||
'report_path_json': (config.report_path_json or {}) if config is not None else {},
|
||||
'query_parameters_json': (config.query_parameters_json or []) if config is not None else [],
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
|
||||
},
|
||||
'profile_config': {
|
||||
+13
-13
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
services/shipping_notice/onhand_source_rules.py
|
||||
|
||||
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
|
||||
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
|
||||
依赖:onhand_routing_engine、onhand_source_repository、order_field_purposes。
|
||||
逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行;
|
||||
行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源;
|
||||
Warehouse 由 Source/匹配决定。
|
||||
@@ -18,9 +18,9 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderSnapshot
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.onhand_source_identity import resolve_inventory_source_identity
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
list_database_inventory_sources,
|
||||
@@ -181,8 +181,8 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
if len(order_keys) != len(order_lines):
|
||||
return adjudication
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
|
||||
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot
|
||||
|
||||
matched: list[tuple[dict[str, Any], Any]] = []
|
||||
checked: list[dict[str, Any]] = []
|
||||
@@ -206,7 +206,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
is_match = order_keys.issubset(inventory_keys)
|
||||
checked.append({
|
||||
'source_code': source_code,
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
'inventory_file_no': snapshot.onhand_file_no,
|
||||
'matched': is_match,
|
||||
})
|
||||
if is_match:
|
||||
@@ -236,7 +236,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
candidates=adjudication.candidates,
|
||||
destination_candidates=adjudication.destination_candidates,
|
||||
evidence=evidence,
|
||||
reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}',
|
||||
reason=f'unique_ready_snapshot:{snapshot.onhand_file_no}',
|
||||
)
|
||||
|
||||
|
||||
@@ -288,9 +288,9 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。"""
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
for code in task_frozen_inventory_source_codes(task):
|
||||
for code in task_frozen_onhand_source_codes(task):
|
||||
item = get_database_inventory_source(code)
|
||||
if item is not None:
|
||||
return item
|
||||
@@ -299,7 +299,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
|
||||
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
"""持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
del source
|
||||
selected = resolution or adjudicate_inventory_source(task)
|
||||
@@ -308,6 +308,6 @@ def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any],
|
||||
|
||||
def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None:
|
||||
"""兼容旧入口,写入规则裁决候选;不触发人工库存源确认。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
+44
-44
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_analysis.py
|
||||
services/shipping_notice/onhand_structure_analysis.py
|
||||
|
||||
用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。
|
||||
依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
|
||||
依赖:openpyxl、onhand_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
|
||||
逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。
|
||||
"""
|
||||
|
||||
@@ -24,11 +24,11 @@ from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
from app.models import FreightRpaOnhandField, FreightRpaParsingProfile, FreightRpaOnhandStructureAnalysis
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import (
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
normalise_header,
|
||||
@@ -44,8 +44,8 @@ _SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', '
|
||||
|
||||
def _has_required_suggestions(mapping: dict[str, str]) -> bool:
|
||||
"""确认自动建议至少覆盖一个匹配字段和一个库存数量字段。"""
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([
|
||||
rows = FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.status == 'active', FreightRpaOnhandField.id.in_([
|
||||
int(field_id) for field_id in mapping if str(field_id).isdigit()
|
||||
]),
|
||||
).all() if mapping else []
|
||||
@@ -118,7 +118,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di
|
||||
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
|
||||
suggestions = suggest_field_mapping(headers, as_catalog=True)
|
||||
catalog = {
|
||||
str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all()
|
||||
str(item.id): item for item in FreightRpaOnhandField.query.filter_by(status='active').all()
|
||||
}
|
||||
reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog}
|
||||
duplicates = Counter(header for header in headers if header)
|
||||
@@ -206,7 +206,7 @@ def _build_workbook_structure(
|
||||
if headers:
|
||||
candidates.append(candidate)
|
||||
if not candidates:
|
||||
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
|
||||
# Prefer a populated detail sheet over a same-score cover/summary sheet.
|
||||
selected = max(candidates, key=lambda item: (
|
||||
item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header),
|
||||
@@ -259,9 +259,9 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str
|
||||
with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle:
|
||||
rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))]
|
||||
except OSError as exc:
|
||||
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
if not rows:
|
||||
raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
raise ValidationError('Inventory file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
|
||||
header_index = find_inventory_header_row_index(rows)
|
||||
headers = [_normalise_header(value) for value in rows[header_index]]
|
||||
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS]
|
||||
@@ -294,10 +294,10 @@ def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, st
|
||||
return _xls_structure(path)
|
||||
if suffix == '.csv':
|
||||
return _csv_structure(path)
|
||||
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
|
||||
|
||||
|
||||
def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
|
||||
def serialize_analysis(item: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]:
|
||||
"""输出管理端需要的分析结果,不暴露服务器存储路径。"""
|
||||
return {
|
||||
'id': item.id,
|
||||
@@ -319,13 +319,13 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
|
||||
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。"""
|
||||
if upload is None or not str(upload.filename or '').strip():
|
||||
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
|
||||
raise ValidationError('Inventory sample file is required', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_REQUIRED')
|
||||
suffix = resolve_inventory_upload_suffix(str(upload.filename))
|
||||
raw = upload.stream.read(MAX_UPLOAD_BYTES + 1)
|
||||
if len(raw) > MAX_UPLOAD_BYTES:
|
||||
raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
|
||||
raise ValidationError('Inventory sample file is too large', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
|
||||
if not raw:
|
||||
raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
raise ValidationError('Inventory sample file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID')
|
||||
analysis_dir = _analysis_root() / uuid.uuid4().hex
|
||||
analysis_dir.mkdir(parents=True, exist_ok=False)
|
||||
path = analysis_dir / f'sample{suffix}'
|
||||
@@ -337,13 +337,13 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
|
||||
raise
|
||||
except Exception as exc:
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
selected_headers = structure.get('selected_headers', [])
|
||||
selected_definition = structure_definition(
|
||||
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
|
||||
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
|
||||
)
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
item = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None,
|
||||
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
|
||||
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
|
||||
@@ -355,7 +355,7 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
|
||||
|
||||
item.match_result_json = recommend_profiles({
|
||||
'structure': structure,
|
||||
@@ -373,22 +373,22 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
|
||||
|
||||
def get_analysis(analysis_id: int) -> dict[str, Any]:
|
||||
"""读取既有结构分析,供管理员选择工作表、表头和来源栏位。"""
|
||||
item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
item = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
return serialize_analysis(item)
|
||||
|
||||
|
||||
def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
if analysis is None or analysis.analysis_status != 'ready':
|
||||
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED')
|
||||
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED')
|
||||
previous = profile.sample_analysis
|
||||
old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else []
|
||||
new_headers = list((analysis.structure_json or {}).get('selected_headers') or [])
|
||||
@@ -419,14 +419,14 @@ def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data:
|
||||
|
||||
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if analysis is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
existing_profile = db.session.get(FreightRpaParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
|
||||
if existing_profile is not None and existing_profile.file_format != analysis.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
|
||||
@@ -436,21 +436,21 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
if candidate is None and sheet_name is None:
|
||||
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None)
|
||||
if not isinstance(candidate, dict):
|
||||
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()}
|
||||
mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {}
|
||||
if any(str(value or '').strip() not in headers for value in mapping.values()):
|
||||
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
for column in candidate.get('columns', [])
|
||||
if isinstance(column, dict) and column.get('duplicate')
|
||||
}
|
||||
if any(str(value or '').strip() in duplicates for value in mapping.values()):
|
||||
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
|
||||
saved = inventory_parsing_profile.save_draft({
|
||||
saved = onhand_parsing_profile.save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
# 用途随请求透传(缺省沿用既有草稿/默认 onhand):inbound 草稿端点为定死领域字段。
|
||||
@@ -465,7 +465,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
'match_keys': data.get('match_keys'),
|
||||
},
|
||||
}, actor_id=actor_id, profile_id=data.get('profile_id'))
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, saved['id'])
|
||||
profile = db.session.get(FreightRpaParsingProfile, saved['id'])
|
||||
selected_definition = structure_definition(
|
||||
file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index,
|
||||
headers=[str(value) for value in candidate.get('headers', [])],
|
||||
@@ -478,17 +478,17 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
)
|
||||
profile.fingerprint_version = selected_definition['fingerprint_version']
|
||||
db.session.commit()
|
||||
return inventory_parsing_profile.payload(profile)
|
||||
return onhand_parsing_profile.payload(profile)
|
||||
|
||||
|
||||
def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]:
|
||||
"""确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if analysis is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
|
||||
candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')}
|
||||
same_test_structure = bool(
|
||||
@@ -496,7 +496,7 @@ def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]
|
||||
and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint
|
||||
)
|
||||
if profile_id not in candidate_ids and not same_test_structure:
|
||||
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
analysis.match_result_json = {
|
||||
**match,
|
||||
'adopted_profile_id': profile.id,
|
||||
+15
-13
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_drift.py
|
||||
services/shipping_notice/onhand_structure_drift.py
|
||||
|
||||
用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。
|
||||
依赖:库存源/解析方案模型、库存结构分析和方案复用服务。
|
||||
@@ -12,7 +12,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingInventorySource
|
||||
from app.models import FreightRpaSource
|
||||
|
||||
|
||||
def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]:
|
||||
@@ -28,20 +28,22 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
|
||||
Raises:
|
||||
ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
|
||||
profile = source.parsing_profile if source is not None else None
|
||||
source = FreightRpaSource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||||
config = source.onhand_report_config if source is not None else None
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if source is None or not source.enabled or profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
|
||||
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED')
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.onhand_structure_analysis import _analyse_path
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
|
||||
|
||||
suffix = resolve_inventory_upload_suffix(path.name)
|
||||
actual_format = suffix.lstrip('.')
|
||||
if actual_format != profile.file_format:
|
||||
raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
|
||||
raise ConflictError('Inventory file format changed', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED')
|
||||
structure, suggested, _summary, warnings = _analyse_path(path, suffix)
|
||||
configured = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
expected_sheet = configured.get('sheet_name')
|
||||
@@ -53,14 +55,14 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
|
||||
if selected is None:
|
||||
raise ConflictError(
|
||||
'Configured inventory worksheet or header row is unavailable',
|
||||
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
|
||||
code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED',
|
||||
details={'source_code': source.source_code, 'profile_id': profile.id},
|
||||
)
|
||||
# Compare the configured worksheet rather than the analyser's best guess.
|
||||
structure = {**structure, 'selected_sheet_name': selected['sheet_name'],
|
||||
'selected_header_row_index': selected['header_row_index'],
|
||||
'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])}
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||||
|
||||
suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True)
|
||||
definition = structure_definition(
|
||||
@@ -79,7 +81,7 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) ->
|
||||
if candidate is None:
|
||||
raise ConflictError(
|
||||
'Inventory file structure is incompatible with the bound parsing profile',
|
||||
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
|
||||
code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED',
|
||||
details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings},
|
||||
)
|
||||
return {
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_fingerprint.py
|
||||
services/shipping_notice/onhand_structure_fingerprint.py
|
||||
|
||||
用途:为库存文件结构和解析定义生成稳定、可审计的指纹。
|
||||
依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。
|
||||
依赖:标准 hashlib/json/unicodedata;输入来自 onhand_structure_analysis 与 onhand_parsing_profile。
|
||||
逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ def exact_fingerprint(definition: dict[str, Any]) -> str:
|
||||
|
||||
def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str:
|
||||
"""按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。"""
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
usages = usage_field_ids()
|
||||
+75
-75
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_temporary_session.py
|
||||
services/shipping_notice/onhand_temporary_session.py
|
||||
|
||||
用途:处理对话上传库存候选文件的身份初检与临时会话状态。
|
||||
依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。
|
||||
@@ -24,33 +24,33 @@ from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingTemporaryInventorySession,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
ShippingTemporaryOnhandSession,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaParsingProfile,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_structure_analysis import (
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.onhand_structure_analysis import (
|
||||
MAX_UPLOAD_BYTES,
|
||||
_analyse_path,
|
||||
_analysis_root,
|
||||
_safe_filename,
|
||||
serialize_analysis,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import (
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
structure_definition,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import (
|
||||
from app.services.shipping_notice.onhand_mapping import (
|
||||
mapping_is_complete,
|
||||
runtime_field_mapping,
|
||||
suggest_field_mapping,
|
||||
validate_field_mapping_against_headers,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
|
||||
from app.services.shipping_notice.onhand_snapshot import parse_inventory_excel_with_meta
|
||||
|
||||
_CONTEXT_PATHS = ['agent_code', 'platform.session_id']
|
||||
_TTL_HOURS = 24
|
||||
@@ -59,7 +59,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
|
||||
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
|
||||
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
|
||||
if str(values.get('agent_code') or '') != 'shipping_notice':
|
||||
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
|
||||
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID')
|
||||
session_id = str(values.get('platform.session_id') or '').strip()
|
||||
session = (
|
||||
db.session.query(ChatSession)
|
||||
@@ -68,7 +68,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
|
||||
.one_or_none()
|
||||
)
|
||||
if session is None:
|
||||
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
|
||||
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID')
|
||||
return session
|
||||
|
||||
|
||||
@@ -77,9 +77,9 @@ def _session_no() -> str:
|
||||
return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
|
||||
|
||||
|
||||
def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]:
|
||||
def _serialize(item: ShippingTemporaryOnhandSession) -> dict[str, Any]:
|
||||
"""输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
return {
|
||||
'session_no': item.session_no,
|
||||
'status': item.status,
|
||||
@@ -101,19 +101,19 @@ def _available_inventory_fields() -> list[dict[str, Any]]:
|
||||
'description': item.description or '',
|
||||
'value_type': item.value_type,
|
||||
'usage_type': item.usage_type,
|
||||
} for item in ShippingInventoryField.query.filter_by(status='active').order_by(
|
||||
ShippingInventoryField.sort_order, ShippingInventoryField.id,
|
||||
} for item in FreightRpaOnhandField.query.filter_by(status='active').order_by(
|
||||
FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id,
|
||||
).all()]
|
||||
|
||||
|
||||
def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
|
||||
def _mapping_suggestion(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None:
|
||||
"""提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。"""
|
||||
result = item.result_json if isinstance(item.result_json, dict) else {}
|
||||
value = result.get('mapping_suggestion')
|
||||
return value if isinstance(value, dict) else None
|
||||
|
||||
|
||||
def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
|
||||
def _confirmed_usage(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None:
|
||||
"""输出已确认的临时使用摘要,不返回库存行或文件内部路径。"""
|
||||
result = item.result_json if isinstance(item.result_json, dict) else {}
|
||||
value = result.get('confirmed_usage')
|
||||
@@ -128,7 +128,7 @@ def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any]
|
||||
}
|
||||
|
||||
|
||||
def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
|
||||
def _serialize_dify_analysis_preview(analysis: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]:
|
||||
"""返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。"""
|
||||
preview = copy.deepcopy(serialize_analysis(analysis))
|
||||
structure = preview.get('structure')
|
||||
@@ -146,12 +146,12 @@ def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysi
|
||||
return preview
|
||||
|
||||
|
||||
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis:
|
||||
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> FreightRpaOnhandStructureAnalysis:
|
||||
"""对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。"""
|
||||
if int(asset.file_size or 0) > MAX_UPLOAD_BYTES:
|
||||
raise ValidationError(
|
||||
'Temporary inventory file is too large',
|
||||
code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE',
|
||||
code='SHIPPING.TEMP_ONHAND_FILE_TOO_LARGE',
|
||||
)
|
||||
suffix = resolve_inventory_upload_suffix(asset.original_filename)
|
||||
raw = read_asset_bytes(asset)
|
||||
@@ -168,7 +168,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise ValidationError(
|
||||
'Temporary inventory file cannot be analysed',
|
||||
code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID',
|
||||
code='SHIPPING.TEMP_ONHAND_ANALYSIS_INVALID',
|
||||
) from exc
|
||||
# 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。
|
||||
suggested, _catalog = runtime_field_mapping(suggested_catalog)
|
||||
@@ -177,7 +177,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
|
||||
header_row_index=structure.get('selected_header_row_index') or 1,
|
||||
headers=structure.get('selected_headers', []),
|
||||
)
|
||||
analysis = ShippingInventoryStructureAnalysis(
|
||||
analysis = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename),
|
||||
storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'),
|
||||
analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
|
||||
@@ -189,7 +189,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
|
||||
)
|
||||
db.session.add(analysis)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
from app.services.shipping_notice.onhand_profile_matching import recommend_profiles
|
||||
|
||||
analysis.match_result_json = recommend_profiles({
|
||||
'structure': structure,
|
||||
@@ -200,7 +200,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt
|
||||
return analysis
|
||||
|
||||
|
||||
def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]:
|
||||
def _classify(analysis: FreightRpaOnhandStructureAnalysis) -> tuple[str, str]:
|
||||
"""在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。"""
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else []
|
||||
@@ -230,27 +230,27 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
asset_no = str(payload.get('asset_no') or '').strip().upper()
|
||||
if not asset_no:
|
||||
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED')
|
||||
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_ONHAND_ASSET_REQUIRED')
|
||||
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none()
|
||||
if asset is None or int(asset.owner_user_id) != int(session.user_id):
|
||||
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND')
|
||||
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_FOUND')
|
||||
if str(asset.upload_status or '') != 'ready':
|
||||
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY')
|
||||
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_READY')
|
||||
try:
|
||||
resolve_inventory_upload_suffix(asset.original_filename)
|
||||
except Exception as exc:
|
||||
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc
|
||||
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_ONHAND_FILE_TYPE_INVALID') from exc
|
||||
|
||||
active = ShippingTemporaryInventorySession.query.filter(
|
||||
ShippingTemporaryInventorySession.user_id == session.user_id,
|
||||
ShippingTemporaryInventorySession.conversation_id == session.session_id,
|
||||
ShippingTemporaryInventorySession.asset_id == asset.id,
|
||||
ShippingTemporaryInventorySession.status.in_([
|
||||
active = ShippingTemporaryOnhandSession.query.filter(
|
||||
ShippingTemporaryOnhandSession.user_id == session.user_id,
|
||||
ShippingTemporaryOnhandSession.conversation_id == session.session_id,
|
||||
ShippingTemporaryOnhandSession.asset_id == asset.id,
|
||||
ShippingTemporaryOnhandSession.status.in_([
|
||||
'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion',
|
||||
'awaiting_mapping_confirmation',
|
||||
]),
|
||||
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
|
||||
).order_by(ShippingTemporaryInventorySession.id.desc()).first()
|
||||
ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(),
|
||||
).order_by(ShippingTemporaryOnhandSession.id.desc()).first()
|
||||
if active:
|
||||
return _serialize(active)
|
||||
|
||||
@@ -262,7 +262,7 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any
|
||||
asset.expires_at = expires_at
|
||||
match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
|
||||
has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact'
|
||||
item = ShippingTemporaryInventorySession(
|
||||
item = ShippingTemporaryOnhandSession(
|
||||
session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate',
|
||||
file_classification_status=classification,
|
||||
@@ -291,11 +291,11 @@ def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
item = ShippingTemporaryOnhandSession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
|
||||
if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}:
|
||||
item.status = 'expired'
|
||||
db.session.commit()
|
||||
@@ -317,31 +317,31 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
item = ShippingTemporaryOnhandSession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
|
||||
if item.status != 'awaiting_mapping_suggestion':
|
||||
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID')
|
||||
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_ONHAND_MAPPING_STATE_INVALID')
|
||||
raw_mapping = payload.get('field_mapping')
|
||||
if not isinstance(raw_mapping, dict) or not raw_mapping:
|
||||
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
|
||||
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID')
|
||||
mapping = {
|
||||
str(field_id).strip(): str(header).strip()
|
||||
for field_id, header in raw_mapping.items()
|
||||
if str(field_id).strip() and str(header).strip()
|
||||
}
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {}
|
||||
headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()]
|
||||
if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping):
|
||||
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
|
||||
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID')
|
||||
errors = validate_field_mapping_against_headers(headers, mapping)
|
||||
if errors or not mapping_is_complete(mapping):
|
||||
raise ValidationError(
|
||||
'Temporary inventory mapping suggestion is incomplete or invalid',
|
||||
code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors},
|
||||
code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID', details={'errors': errors},
|
||||
)
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
@@ -353,19 +353,19 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di
|
||||
|
||||
|
||||
def _select_confirmed_mapping(
|
||||
item: ShippingTemporaryInventorySession,
|
||||
item: ShippingTemporaryOnhandSession,
|
||||
*,
|
||||
selected_profile_id: Any,
|
||||
) -> tuple[dict[str, str], str, int | None]:
|
||||
"""按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
|
||||
if item.status == 'awaiting_profile_confirmation':
|
||||
try:
|
||||
profile_id = int(selected_profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc
|
||||
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') from exc
|
||||
candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else []
|
||||
exact_ids = {
|
||||
int(candidate.get('profile_id'))
|
||||
@@ -373,17 +373,17 @@ def _select_confirmed_mapping(
|
||||
and str(candidate.get('level') or '') == 'exact'
|
||||
and str(candidate.get('profile_id') or '').isdigit()
|
||||
}
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None or profile.status != 'published' or profile_id not in exact_ids:
|
||||
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
|
||||
return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id
|
||||
if item.status == 'awaiting_mapping_confirmation':
|
||||
suggestion = _mapping_suggestion(item) or {}
|
||||
mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
|
||||
return dict(mapping), 'dify_candidate', None
|
||||
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
|
||||
|
||||
|
||||
def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]:
|
||||
@@ -419,7 +419,7 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。
|
||||
核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁;
|
||||
只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。
|
||||
只写临时会话审计,不创建 FreightRpaOnhandReportFile、不修改库存站点、不回填任务库存行、不执行匹配。
|
||||
|
||||
Args:
|
||||
payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。
|
||||
@@ -429,19 +429,19 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
item = ShippingTemporaryOnhandSession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
|
||||
if item.expires_at <= datetime.utcnow():
|
||||
item.status = 'expired'
|
||||
db.session.commit()
|
||||
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED')
|
||||
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_ONHAND_SESSION_EXPIRED')
|
||||
mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id'))
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID')
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
try:
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
@@ -449,10 +449,10 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'),
|
||||
)
|
||||
except Exception as exc:
|
||||
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc
|
||||
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID') from exc
|
||||
quality = _quality_report(lines, mapping)
|
||||
if not quality['passed']:
|
||||
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality})
|
||||
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID', details={'quality': quality})
|
||||
item.task_id = None
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
@@ -470,12 +470,12 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。"""
|
||||
rows = ShippingTemporaryInventorySession.query.filter_by(
|
||||
rows = ShippingTemporaryOnhandSession.query.filter_by(
|
||||
status='confirmed_for_temporary_use',
|
||||
).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
|
||||
).order_by(ShippingTemporaryOnhandSession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
|
||||
result: list[dict[str, Any]] = []
|
||||
for item in rows:
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
confirmed = _confirmed_usage(item)
|
||||
result.append({
|
||||
'session_no': item.session_no,
|
||||
@@ -513,24 +513,24 @@ def create_parsing_profile_draft_from_temporary_session(
|
||||
新建的库存文件解析方案草稿。
|
||||
"""
|
||||
normalized_no = str(session_no or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none()
|
||||
item = ShippingTemporaryOnhandSession.query.filter_by(session_no=normalized_no).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND')
|
||||
if item.status != 'confirmed_for_temporary_use':
|
||||
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
|
||||
confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None
|
||||
if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict):
|
||||
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
|
||||
existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None
|
||||
if existing_draft_id:
|
||||
existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id)
|
||||
existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id)
|
||||
if existing_draft is not None:
|
||||
from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload
|
||||
from app.services.shipping_notice.onhand_parsing_profile import payload as profile_payload
|
||||
|
||||
return profile_payload(existing_draft)
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID')
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
payload = {
|
||||
'profile_code': data.get('profile_code'),
|
||||
@@ -540,9 +540,9 @@ def create_parsing_profile_draft_from_temporary_session(
|
||||
'field_mapping': confirmed['field_mapping'],
|
||||
'match_keys': data.get('match_keys'),
|
||||
}
|
||||
from app.services.shipping_notice import inventory_structure_analysis
|
||||
from app.services.shipping_notice import onhand_structure_analysis
|
||||
|
||||
draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
|
||||
draft = onhand_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
'promoted_profile_draft_id': draft['id'],
|
||||
@@ -4,10 +4,13 @@ services/shipping_notice/onhand_trigger_batch.py
|
||||
用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、
|
||||
单票按需触发的 fail-closed 入口。
|
||||
依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、
|
||||
shipping_notice.inventory_source_repository(按源补 Profile 密文,函数内延迟 import)。
|
||||
逻辑:由 schedule.freight_onhand_rpa_job(定时批量)、inventory_configuration_test(配置测试)、
|
||||
inventory_rpa_workflow / per_source_rpa_service(按需触发)调用,
|
||||
shipping_notice.onhand_source_repository(按源补 Profile 密文,函数内延迟 import)。
|
||||
逻辑:由 schedule.freight_rpa_onhand_job(定时批量)、onhand_configuration_test(配置测试)、
|
||||
onhand_rpa_workflow / per_source_rpa_service(按需触发)调用,
|
||||
与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。
|
||||
s18 起 report_path_json / query_parameters_json / parsing_profile_id 改由仓库快照取自
|
||||
source.onhand_report_config 配置行(navigation/parameters 由此派生);配置行缺失时
|
||||
仓库返回 None,沿用「站点未就绪」的跳过/回退语义,不新造错误码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -53,11 +56,14 @@ def write_inventory_export_batch_trigger(
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
# s18 起合并进来的 report_path_json / query_parameters_json / parsing_profile_id
|
||||
# 均取自 source.onhand_report_config 配置行(仓库快照),配置缺失时上面已回退到
|
||||
# 调用方传入的非敏感快照,沿用「站点未就绪」既有语义。
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
@@ -106,11 +112,11 @@ def write_inventory_export_batch_trigger(
|
||||
return str(path)
|
||||
|
||||
|
||||
def inventory_rpa_batch_enabled() -> bool:
|
||||
def onhand_rpa_batch_enabled() -> bool:
|
||||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED")
|
||||
if raw is None:
|
||||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
raw = os.getenv("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", "true")
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
@@ -133,7 +139,7 @@ def build_on_demand_inventory_trigger_source(
|
||||
Returns:
|
||||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
@@ -178,7 +184,7 @@ def write_inventory_export_trigger_for_task(
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
if onhand_rpa_batch_enabled():
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||||
return write_inventory_export_batch_trigger(
|
||||
@@ -193,5 +199,5 @@ def write_inventory_export_trigger_for_task(
|
||||
)
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
code='SHIPPING.ONHAND_RPA_V2_REQUIRED',
|
||||
)
|
||||
+7
-7
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_upload.py
|
||||
services/shipping_notice/onhand_upload.py
|
||||
|
||||
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
|
||||
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
|
||||
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
|
||||
依赖:onhand_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
|
||||
逻辑:由 onhand_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
|
||||
正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
|
||||
"""
|
||||
|
||||
@@ -19,9 +19,9 @@ from typing import Any
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
|
||||
from app.services.shipping_notice.onhand_file_store import inventory_storage_suffix_for_path
|
||||
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
|
||||
_TASK_INVENTORY_MARKER = ".current_inventory"
|
||||
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
|
||||
@@ -164,7 +164,7 @@ def install_task_inventory_attachment_from_file(
|
||||
|
||||
def rebuild_task_inventory_attachment_from_snapshot(
|
||||
task: ShippingOrderTask | ShippingNotice | str,
|
||||
inv_file: ShippingInventoryFile,
|
||||
inv_file: FreightRpaOnhandReportFile,
|
||||
) -> Path:
|
||||
"""
|
||||
从已提交库存快照 storage_path 幂等重建任务正式附件。
|
||||
@@ -183,7 +183,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
|
||||
storage_path = Path(str(inv_file.storage_path or ""))
|
||||
if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
|
||||
raise FileNotFoundError(
|
||||
f"库存快照托管文件不存在: {inv_file.inventory_file_no}",
|
||||
f"库存快照托管文件不存在: {inv_file.onhand_file_no}",
|
||||
)
|
||||
return install_task_inventory_attachment_from_file(
|
||||
task_no,
|
||||
+11
-8
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_warehouse_resolution.py
|
||||
services/shipping_notice/onhand_warehouse_resolution.py
|
||||
|
||||
用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。
|
||||
依赖:ShippingInventoryField/Source、动态订单字段投影。
|
||||
依赖:FreightRpaOnhandField/Source、动态订单字段投影。
|
||||
逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。
|
||||
"""
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryField, ShippingInventorySource
|
||||
from app.models import FreightRpaOnhandField, FreightRpaSource
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
@@ -31,8 +31,11 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
|
||||
|
||||
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution:
|
||||
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
|
||||
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
|
||||
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||||
config = source.onhand_report_config if source is not None else None
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
definition = profile.definition_json if profile is not None else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
|
||||
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
|
||||
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)]
|
||||
@@ -40,9 +43,9 @@ def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]
|
||||
int(field_id) for field_id in (definition.get('field_mapping') or {})
|
||||
if str(field_id).isdigit()
|
||||
} if isinstance(definition, dict) else set()
|
||||
warehouse_fields = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active',
|
||||
ShippingInventoryField.usage_type == 'warehouse_identity',
|
||||
warehouse_fields = FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.id.in_(mapped_ids), FreightRpaOnhandField.status == 'active',
|
||||
FreightRpaOnhandField.usage_type == 'warehouse_identity',
|
||||
).all() if mapped_ids else []
|
||||
if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1:
|
||||
return WarehouseResolution(None, 'warehouse_configuration_invalid')
|
||||
+40
-40
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_workflow.py
|
||||
services/shipping_notice/onhand_workflow.py
|
||||
|
||||
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
|
||||
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、
|
||||
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
|
||||
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 onhand_rpa_workflow。
|
||||
依赖:customer_identity_gate、reservation_gate、onhand_file_store、onhand_mapping_workflow、
|
||||
onhand_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
|
||||
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
|
||||
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
|
||||
payload.source_codes 可收窄 ensure_inventory(持久化阶段码 ensure_onhand)/ RPA 作用源(行级重抓);
|
||||
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File;
|
||||
动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。
|
||||
"""
|
||||
@@ -21,8 +21,8 @@ from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
POSITION_INVENTORY_SOURCE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
|
||||
from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.onhand_file_store import save_task_inventory_upload
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
resolve_task_from_payload,
|
||||
@@ -31,7 +31,7 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
@@ -67,20 +67,20 @@ def _link_ready_candidate_prep_or_block(
|
||||
|
||||
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
|
||||
快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定
|
||||
(pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成
|
||||
(pending_matching),仓/匹配问题留给 onhand_matching,禁止把「有文件」投影成
|
||||
inventory_file_missing。仅当真的无法绑定文件时才 needs_human。
|
||||
|
||||
Args:
|
||||
task: 已冻结候选源的订单任务。
|
||||
prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。
|
||||
prep: ``prepare_candidate_onhand_lines`` 的 ready 结果。
|
||||
lang: 文案语言。
|
||||
|
||||
Returns:
|
||||
None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。
|
||||
"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_snapshot_store import (
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
|
||||
@@ -107,7 +107,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
break
|
||||
|
||||
inv_file = (
|
||||
ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first()
|
||||
FreightRpaOnhandReportFile.query.filter_by(onhand_file_no=file_no).first()
|
||||
if file_no
|
||||
else None
|
||||
)
|
||||
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=t('workflow.inventory.unavailable', lang=lang),
|
||||
@@ -221,10 +221,10 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
|
||||
reservation_gate = _reservation_gate_response(task, lang=lang)
|
||||
if reservation_gate is not None:
|
||||
return reservation_gate
|
||||
if operation == "ensure_inventory":
|
||||
if operation == "ensure_onhand":
|
||||
# [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或
|
||||
# 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
get_active_candidate_lines,
|
||||
get_active_candidate_set,
|
||||
get_active_candidate_sources,
|
||||
@@ -251,7 +251,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
|
||||
message="库存源候选集尚未冻结完成,暂不能准备库存。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
|
||||
"error_code": "SHIPPING.ONHAND_SOURCE_ROUTING_REQUIRED",
|
||||
"position": POSITION_INVENTORY_SOURCE_REVIEW,
|
||||
},
|
||||
position=POSITION_INVENTORY_SOURCE_REVIEW,
|
||||
@@ -281,7 +281,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||
lang = resolve_lang({"lang": None})
|
||||
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
|
||||
gate_resp = _inventory_source_gate_response(task, operation="upload_onhand_file", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||||
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
try:
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message=t("workflow.inventory.uploading", lang=lang),
|
||||
@@ -322,13 +322,13 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
db.session.flush()
|
||||
inv_file = save_task_inventory_upload(task, upload)
|
||||
inventory_lines = [
|
||||
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
|
||||
item for item in (inv_file.onhand_lines_json or []) if isinstance(item, dict)
|
||||
]
|
||||
preview = dict(inv_file.schema_preview_json or {})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
message = str(exc.message or "库存上传被拒绝")
|
||||
if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED':
|
||||
if exc.code == 'SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED':
|
||||
message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。'
|
||||
return tool_response(
|
||||
status="failed",
|
||||
@@ -362,7 +362,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
task,
|
||||
"inventory_snapshot_created",
|
||||
{
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"inventory_file_no": inv_file.onhand_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
},
|
||||
)
|
||||
@@ -397,7 +397,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task_no, trigger=trigger,
|
||||
expected_version=None,
|
||||
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
|
||||
resume_gate_code='inventory_preparation',
|
||||
resume_gate_code='onhand_preparation',
|
||||
operator_id=operator_id,
|
||||
inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto',
|
||||
line_scope_key=(
|
||||
@@ -415,7 +415,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
# [STEP 0] 与 parse/upload 共用客户、Reservation、库存源门禁,避免旁路入口绕过订单侧闸门。
|
||||
gate_resp = _inventory_source_gate_response(task, operation="ensure_inventory", lang=lang)
|
||||
gate_resp = _inventory_source_gate_response(task, operation="ensure_onhand", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
@@ -441,27 +441,27 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP 2] 正常流程优先复用已完成的库存快照;缺少快照时自动进入库存 RPA。
|
||||
if mode == "retry_rpa":
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
return ensure_inventory_via_rpa(
|
||||
task, mode=mode, source_codes=scoped_source_codes,
|
||||
)
|
||||
|
||||
if mode == "auto":
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
|
||||
|
||||
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
frozen_codes = task_frozen_onhand_source_codes(task)
|
||||
if len(frozen_codes) >= 1:
|
||||
prep = prepare_candidate_inventory_lines(task)
|
||||
prep = prepare_candidate_onhand_lines(task)
|
||||
if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing':
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发库存获取,等待各库存源回调。",
|
||||
@@ -521,7 +521,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
if probe.all_prepared:
|
||||
# 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。
|
||||
prep = prepare_candidate_inventory_lines(task)
|
||||
prep = prepare_candidate_onhand_lines(task)
|
||||
else:
|
||||
# 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。
|
||||
log_task_event(task, "inventory_probe_failed", {
|
||||
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存 RPA 未能为全部库存源生成结果。",
|
||||
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -599,7 +599,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# 库存源已确定但没有可复用快照时,自动推进必须启动一次 RPA,
|
||||
# 否则任务会错误停在人审且没有可执行的恢复动作。
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
return ensure_inventory_via_rpa(
|
||||
task,
|
||||
@@ -610,7 +610,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
|
||||
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
if has_ready_inventory_file_for_task(task):
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||||
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="inventory_fetching",
|
||||
stage="onhand_fetching",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
@@ -4,9 +4,9 @@ services/shipping_notice/order_build_eligibility_service.py
|
||||
用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及
|
||||
Candidate Qualification 统一自动建单检查。
|
||||
依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、
|
||||
inventory_routing_engine、inventory_source_repository、
|
||||
onhand_routing_engine、onhand_source_repository、
|
||||
ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、
|
||||
ShippingInventorySource、process_gate_contract(原因唯一归属)。
|
||||
FreightRpaSource、process_gate_contract(原因唯一归属)。
|
||||
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费);
|
||||
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
|
||||
停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选,
|
||||
@@ -20,7 +20,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventorySource
|
||||
from app.models import FreightRpaSource
|
||||
from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS,
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
|
||||
@@ -30,11 +30,11 @@ from app.services.shipping_notice.candidate_qualification_service import (
|
||||
)
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
from app.services.shipping_notice.onhand_routing_engine import (
|
||||
InventoryRoutingResult,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
@@ -175,7 +175,7 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
|
||||
reasons: dict[str, str] = {}
|
||||
for code in _normalize_manual_codes(codes):
|
||||
# [STEP 1] 源不存在
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=code).first()
|
||||
if source is None:
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'source_not_found'
|
||||
@@ -197,8 +197,9 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'source_runtime_unavailable'
|
||||
continue
|
||||
# [STEP 5] 解析 Profile 未发布
|
||||
parsing = source.parsing_profile
|
||||
# [STEP 5] 解析 Profile 未发布(s18 起绑定归 onhand_report_config 配置行;配置行缺失即未绑定)
|
||||
config = source.onhand_report_config
|
||||
parsing = config.parsing_profile if config is not None else None
|
||||
if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published':
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'parsing_profile_unavailable'
|
||||
@@ -539,7 +540,7 @@ def assess_order_build_eligibility(
|
||||
'draft_line_id': meta.get('draft_line_id'),
|
||||
'line_index': index,
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'inventory_source_routing',
|
||||
'owning_gate_code': 'onhand_source_routing',
|
||||
'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [],
|
||||
'unavailable_source_codes': routing.get('unavailable_source_codes') or [],
|
||||
'unavailable_reasons': routing.get('unavailable_reasons') or {},
|
||||
@@ -578,7 +579,7 @@ def assess_order_build_eligibility(
|
||||
# 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。
|
||||
build_blocking_issues = [
|
||||
item for item in issues
|
||||
if str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
|
||||
if str(item.get('owning_gate_code') or '') != 'onhand_source_routing'
|
||||
]
|
||||
can_build = (
|
||||
bool(customer_resolved)
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
|
||||
from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text
|
||||
from app.services.shipping_notice.notice_line_table import (
|
||||
find_notice_header_row_index,
|
||||
parse_notice_row,
|
||||
|
||||
@@ -16,7 +16,7 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
|
||||
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
|
||||
Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的
|
||||
正式 inventory_source_routing Gate 负责;
|
||||
正式 onhand_source_routing Gate 负责;
|
||||
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
|
||||
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
|
||||
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
|
||||
@@ -1440,7 +1440,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bo
|
||||
upload_status = getattr(latest_upload_attempt(task), 'status', None)
|
||||
# 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等
|
||||
# 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
current_inventory_matches_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
)
|
||||
|
||||
@@ -656,7 +656,7 @@ def _validation(
|
||||
# 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。
|
||||
can_build = bool(eligibility.get('can_build')) and not any(
|
||||
str(item.get('severity') or '') == 'blocking'
|
||||
and str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
|
||||
and str(item.get('owning_gate_code') or '') != 'onhand_source_routing'
|
||||
for item in issues
|
||||
)
|
||||
# [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。
|
||||
@@ -1574,7 +1574,7 @@ def _sync_review_gates_safe(
|
||||
details=sync_details,
|
||||
)
|
||||
|
||||
inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing')
|
||||
inventory_issues = _blocking_issues_for_gate(result, 'onhand_source_routing')
|
||||
if not inventory_issues:
|
||||
# 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task;
|
||||
# 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。
|
||||
|
||||
@@ -4,7 +4,7 @@ services/shipping_notice/order_review_fulfillment_decision_service.py
|
||||
用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。
|
||||
依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、
|
||||
order_review_draft_service、order_review_workbench_projection、
|
||||
line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、
|
||||
line_onhand_match_projection(OT 行匹配事实)、fulfillment_audit、
|
||||
order_review_resume_service。
|
||||
逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions;
|
||||
订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」=
|
||||
@@ -20,17 +20,17 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventorySource,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaSource,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
ShippingOrderReviewWaveLine,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
from app.services.shipping_notice.line_onhand_match_persistence import (
|
||||
resolve_review_case_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
@@ -44,13 +44,13 @@ def _get_soft_loader():
|
||||
return soft_load_review_case_for_audit
|
||||
|
||||
|
||||
DECISION_WAIT = 'wait_inventory'
|
||||
DECISION_WAIT = 'wait_onhand'
|
||||
DECISION_FULFILL = 'fulfill_complete_line_now'
|
||||
DECISION_CLOSE = 'close_unfulfillable'
|
||||
DECISION_REOPEN = 'reopen'
|
||||
DECISION_USE_NEW_FILE = 'use_new_inventory_file'
|
||||
DECISION_CHANGE_SOURCE = 'change_inventory_source'
|
||||
DECISION_RELEASE_SHORTAGE = 'release_inventory_shortage'
|
||||
DECISION_RELEASE_SHORTAGE = 'release_onhand_shortage'
|
||||
|
||||
ALLOWED_DECISIONS = frozenset({
|
||||
DECISION_WAIT,
|
||||
@@ -171,7 +171,7 @@ def _release_template_inventory_fields(
|
||||
'field_id': field_id,
|
||||
'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})',
|
||||
'value': value,
|
||||
'value_source': 'inventory_snapshot' if value is not None else 'manual_required',
|
||||
'value_source': 'onhand_snapshot' if value is not None else 'manual_required',
|
||||
'requires_manual': value is None,
|
||||
})
|
||||
return fields
|
||||
@@ -278,7 +278,7 @@ def _is_shortage_match_fact(fact: Any) -> bool:
|
||||
def _has_terminal_inventory_rpa_failure(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
attempts: list[ShippingTaskInventoryRpaAttempt] | None = None,
|
||||
attempts: list[FreightRpaOnhandTaskAttempt] | None = None,
|
||||
) -> bool:
|
||||
"""仅在已投递的库存 RPA 全部终态失败且无活动 Attempt 时允许无快照人工放行。"""
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip()
|
||||
@@ -286,20 +286,20 @@ def _has_terminal_inventory_rpa_failure(
|
||||
return False
|
||||
source_codes: set[str] = set()
|
||||
try:
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
source_codes = {str(item or '').strip().upper() for item in task_frozen_onhand_source_codes(task)}
|
||||
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
|
||||
source_codes = set()
|
||||
rows = attempts if attempts is not None else (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter_by(task_no=task_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc(), FreightRpaOnhandTaskAttempt.id.desc())
|
||||
.all()
|
||||
)
|
||||
relevant = [row for row in rows if not source_codes or str(getattr(row, 'source_code', '') or '').strip().upper() in source_codes]
|
||||
if not relevant or any(str(getattr(row, 'status', '') or '').lower() in {'queued', 'running'} for row in relevant):
|
||||
return False
|
||||
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
|
||||
latest_by_source: dict[str, FreightRpaOnhandTaskAttempt] = {}
|
||||
for row in relevant:
|
||||
code = str(getattr(row, 'source_code', '') or '').strip().upper()
|
||||
if code and code not in latest_by_source:
|
||||
@@ -325,7 +325,7 @@ def _shortage_release_required_fields(
|
||||
|
||||
Returns:
|
||||
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
|
||||
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
|
||||
其余 requires_manual);evidence_scope ∈ {'onhand_snapshot', 'part_fallback'},
|
||||
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
|
||||
"""
|
||||
if line_index is None:
|
||||
@@ -333,20 +333,20 @@ def _shortage_release_required_fields(
|
||||
'Current line inventory evidence is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
|
||||
snapshot = db.session.get(FreightRpaOnhandReportFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
|
||||
if inventory_snapshot_id is not None and snapshot is None:
|
||||
raise ConflictError(
|
||||
'Current inventory snapshot is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
resolved_source_code = _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=inventory_source_code,
|
||||
snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None,
|
||||
candidate_source_codes={
|
||||
str(code or '').strip().upper()
|
||||
for code in task_frozen_inventory_source_codes(task)
|
||||
for code in task_frozen_onhand_source_codes(task)
|
||||
if str(code or '').strip()
|
||||
},
|
||||
)
|
||||
@@ -355,7 +355,7 @@ def _shortage_release_required_fields(
|
||||
'Current line inventory evidence is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
source = ShippingInventorySource.query.filter_by(
|
||||
source = FreightRpaSource.query.filter_by(
|
||||
source_code=resolved_source_code, enabled=True,
|
||||
).first()
|
||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||
@@ -379,9 +379,9 @@ def _shortage_release_required_fields(
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '').strip().isdigit()
|
||||
}
|
||||
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
|
||||
labels = {str(row.id): str(row.display_name or '').strip() for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()} if field_ids else {}
|
||||
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'onhand_snapshot'
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
|
||||
expected = [
|
||||
@@ -393,7 +393,7 @@ def _shortage_release_required_fields(
|
||||
'Inventory matching keys are unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
|
||||
try:
|
||||
inventory_lines, _column_meta = read_inventory_file_lines(snapshot)
|
||||
except (OSError, ValueError, AppError) as exc:
|
||||
@@ -405,7 +405,7 @@ def _shortage_release_required_fields(
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
]
|
||||
evidence_scope = 'inventory_snapshot'
|
||||
evidence_scope = 'onhand_snapshot'
|
||||
if not candidates:
|
||||
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
|
||||
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
|
||||
@@ -413,7 +413,7 @@ def _shortage_release_required_fields(
|
||||
part_field_ids = {
|
||||
int(field_id) for field_id, _value in expected
|
||||
if str(field_id).strip().isdigit()
|
||||
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
|
||||
and str(getattr(db.session.get(FreightRpaOnhandField, int(field_id)), 'field_code', '') or '') == 'part_number'
|
||||
}
|
||||
if part_field_ids:
|
||||
candidates = [
|
||||
@@ -433,7 +433,7 @@ def _shortage_release_required_fields(
|
||||
}
|
||||
labels = {
|
||||
str(row.id): str(row.display_name or '').strip()
|
||||
for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
|
||||
for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()
|
||||
} if field_ids else {}
|
||||
return _release_template_inventory_fields(
|
||||
mappings=mappings,
|
||||
@@ -481,7 +481,7 @@ def _sync_confirmed_task_fulfillment_gates(
|
||||
# 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算,
|
||||
# 空事实任务不得被误标为缺货。
|
||||
if getattr(task, 'id', None) is not None:
|
||||
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
|
||||
from app.models import ShippingNoticeLineOnhandMatch as _MatchRow
|
||||
has_match_rows = (
|
||||
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first()
|
||||
is not None
|
||||
@@ -592,11 +592,11 @@ def _assess_line_fulfill_complete(
|
||||
return False, 'SHIPPING.REVIEW_LINE_RESERVATION_REQUIRED', req, avail
|
||||
block_reason = str(proj.get('block_reason') or '').lower()
|
||||
if 'shortage' in block_reason or 'insufficient' in block_reason:
|
||||
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail
|
||||
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail
|
||||
if avail is None:
|
||||
return False, 'SHIPPING.REVIEW_LINE_INVENTORY_UNKNOWN', req, None
|
||||
return False, 'SHIPPING.REVIEW_LINE_ONHAND_UNKNOWN', req, None
|
||||
if avail < req:
|
||||
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail
|
||||
return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail
|
||||
return True, None, req, avail
|
||||
|
||||
|
||||
@@ -621,7 +621,7 @@ def _assert_line_can_fulfill_complete(
|
||||
if not ok or req is None or avail is None:
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory',
|
||||
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'),
|
||||
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND'),
|
||||
details={'draft_line_id': draft_line_id},
|
||||
)
|
||||
return req, avail
|
||||
@@ -791,13 +791,13 @@ def project_review_case_line_decisions(
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。
|
||||
inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
|
||||
onhand_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
|
||||
source_labels: code→显示名映射。
|
||||
|
||||
Returns:
|
||||
lines(含 inventory_source / 分域 actions)与聚合计数。
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
line_auto_fulfill_enabled,
|
||||
project_line_inventory_view,
|
||||
)
|
||||
@@ -816,13 +816,13 @@ def project_review_case_line_decisions(
|
||||
task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
|
||||
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
|
||||
# [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
from app.services.shipping_notice.stp_onhand_freeze import (
|
||||
task_frozen_onhand_source_codes,
|
||||
)
|
||||
|
||||
fallback_inventory_source: dict[str, Any] | None = None
|
||||
if task is not None:
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
frozen_codes = task_frozen_onhand_source_codes(task)
|
||||
if len(frozen_codes) == 1:
|
||||
fallback_inventory_source = {
|
||||
'code': frozen_codes[0],
|
||||
@@ -846,7 +846,7 @@ def project_review_case_line_decisions(
|
||||
'source': 'inventory_source_clue',
|
||||
}
|
||||
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
load_current_match_facts_by_line_index,
|
||||
)
|
||||
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
|
||||
@@ -1058,7 +1058,7 @@ def build_inventory_issue_fallback(
|
||||
Case 级库存兜底:仅无有效行投影且库存系统失败时返回。
|
||||
|
||||
核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发
|
||||
retry_inventory_preparation。
|
||||
retry_onhand_preparation。
|
||||
|
||||
Returns:
|
||||
fallback 字典或 None。
|
||||
@@ -1088,8 +1088,8 @@ def build_inventory_issue_fallback(
|
||||
'inventory_file_missing',
|
||||
'inventory_source_unavailable',
|
||||
'inventory_preparation_failed',
|
||||
'inventory_rpa_timeout',
|
||||
'inventory_rpa_export_failed',
|
||||
'onhand_rpa_timeout',
|
||||
'onhand_rpa_export_failed',
|
||||
'inventory_file_empty',
|
||||
}
|
||||
if auto_status not in {'failed', 'error'} and reason not in failed_reasons:
|
||||
@@ -1101,7 +1101,7 @@ def build_inventory_issue_fallback(
|
||||
'reason_label_key': kind,
|
||||
'affected_line_count': 0,
|
||||
'file_count': 0,
|
||||
'allowed_actions': ['retry_inventory_preparation'],
|
||||
'allowed_actions': ['retry_onhand_preparation'],
|
||||
}
|
||||
|
||||
|
||||
@@ -1122,7 +1122,7 @@ def _apply_shortage_line_release(
|
||||
版本化落库、同步正式 OT 门禁并写审计。
|
||||
|
||||
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
|
||||
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
|
||||
证据字段按行事实快照解析(预约键命中 → onhand_snapshot;预约键 0 行命中
|
||||
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
|
||||
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
|
||||
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
|
||||
@@ -1161,10 +1161,10 @@ def _apply_shortage_line_release(
|
||||
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
key, draft_line = pair
|
||||
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingNoticeLineOnhandMatch
|
||||
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
@@ -1173,10 +1173,10 @@ def _apply_shortage_line_release(
|
||||
release_template_fields, resolved_scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
||||
inventory_snapshot_id=getattr(fact, 'onhand_snapshot_id', None) if fact is not None else None,
|
||||
inventory_source_code=getattr(fact, 'source_code', None) if fact is not None else None,
|
||||
)
|
||||
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
|
||||
release_evidence_scope = str(evidence_scope or resolved_scope or 'onhand_snapshot')
|
||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||
release_values = _validate_inventory_shortage_release_fields(
|
||||
required_fields=release_required_fields,
|
||||
@@ -1241,7 +1241,7 @@ def _apply_shortage_line_release(
|
||||
'draft_line_id': key,
|
||||
'release_field_values': release_values,
|
||||
'release_required_fields': release_required_fields,
|
||||
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
|
||||
# 审计口径:放行证据来自预约匹配快照(onhand_snapshot)还是料号兜底重筛(part_fallback)。
|
||||
'release_evidence_scope': release_evidence_scope,
|
||||
**({'auto_release': True} if auto_release else {}),
|
||||
},
|
||||
@@ -1300,7 +1300,7 @@ def decide_review_line_fulfillment(
|
||||
|
||||
核心逻辑:停用旧活动决定;task_created/fulfilled 不可逆;
|
||||
reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足;
|
||||
release_inventory_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。
|
||||
release_onhand_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
@@ -1310,7 +1310,7 @@ def decide_review_line_fulfillment(
|
||||
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
|
||||
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
|
||||
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
|
||||
release_evidence_scope 记录证据范围(onhand_snapshot / part_fallback)。
|
||||
expected_draft_version: 可选草稿乐观锁。
|
||||
actor_is_admin: 是否管理员(重开授权)。
|
||||
|
||||
@@ -1392,12 +1392,12 @@ def decide_review_line_fulfillment(
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingNoticeLineOnhandMatch
|
||||
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
ShippingNoticeLineOnhandMatch.query
|
||||
.filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True)
|
||||
.first()
|
||||
if task is not None else None
|
||||
@@ -1570,7 +1570,7 @@ def auto_release_part_fallback_shortages(
|
||||
Returns:
|
||||
自动放行的 line_index 列表(按行号升序)。
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
load_current_match_facts_by_task,
|
||||
)
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ from app.models import (
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
inventory_rpa_is_running as _inventory_rpa_is_running,
|
||||
)
|
||||
|
||||
|
||||
@@ -70,16 +70,16 @@ _PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({
|
||||
|
||||
# Worker 等待类库存准备:即使存在 Gate 行,也不得投影为人工待办。
|
||||
_SYSTEM_WAIT_INVENTORY_GATES: frozenset[str] = frozenset({
|
||||
'inventory_preparation',
|
||||
'onhand_preparation',
|
||||
})
|
||||
|
||||
# 库存/履约域(正式 OT 后允许在 owner_type=human 时成为当前阻断)。
|
||||
_POST_OT_INVENTORY_FULFILLMENT_GATES: frozenset[str] = frozenset({
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'reservation_validation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_field_mapping',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'line_fulfillment',
|
||||
'shortage_review',
|
||||
'fulfillment_decision',
|
||||
@@ -486,7 +486,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
export_file_path = getattr(latest_export_artifact(task), 'file_path', None)
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
current_inventory_matches_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
)
|
||||
@@ -494,8 +494,8 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
has_match = bool(current_inventory_matches_for_task(task))
|
||||
has_inventory = has_ready_inventory_file_for_task(task)
|
||||
else:
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
match_status = aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None))
|
||||
has_match = bool(match_status)
|
||||
has_inventory = has_ready_inventory_file_for_task(task)
|
||||
@@ -690,7 +690,7 @@ def project_stage_for_task(
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
has_verified_upload_success,
|
||||
@@ -704,12 +704,12 @@ def project_stage_for_task(
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||||
verified_upload_success = has_verified_upload_success(task)
|
||||
if isinstance(owner, ShippingOrderTask):
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
match_facts = list(load_current_match_facts_by_task(getattr(owner, 'id', None)).values())
|
||||
has_task_match = bool(match_facts)
|
||||
else:
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
has_task_match = bool(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)))
|
||||
progress_state = (
|
||||
'uploaded' if verified_upload_success
|
||||
@@ -758,13 +758,13 @@ def project_stage_for_task(
|
||||
# Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。
|
||||
if ot_stage == 'order_creating':
|
||||
if progress_state in {'inventory_ready'}:
|
||||
return _with_label('inventory_fetching', source='notice_inventory')
|
||||
return _with_label('onhand_fetching', source='notice_inventory')
|
||||
if progress_state in {'matched', 'export_ready'}:
|
||||
_status, mapped = map_notice_to_processing_status_stage(task)
|
||||
code = str(mapped or 'inventory_matching').strip() or 'inventory_matching'
|
||||
code = str(mapped or 'onhand_matching').strip() or 'onhand_matching'
|
||||
return _with_label(code, source='notice_map')
|
||||
if progress_state in {None, '', 'not_started'}:
|
||||
return _with_label('inventory_fetching', source='post_ot_inventory')
|
||||
return _with_label('onhand_fetching', source='post_ot_inventory')
|
||||
return _with_label(ot_stage, source='order_task')
|
||||
|
||||
# [STEP 2] Notice 尚无履约领域事实:统一 order_creating。
|
||||
|
||||
@@ -65,11 +65,11 @@ _PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
# 正式 Process Gate 的库存履约阶段 → 统一 15 阶投影阶段。
|
||||
# Gate 码不是 15 阶成员,必须在写路径转换后再回写 OT,避免已建单任务残留建单前 stage。
|
||||
_PROCESS_GATE_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'onhand_source_routing': 'onhand_source_resolving',
|
||||
'onhand_preparation': 'onhand_fetching',
|
||||
'onhand_field_mapping': 'onhand_fetching',
|
||||
'onhand_matching': 'onhand_matching',
|
||||
'onhand_sufficiency': 'onhand_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
@@ -220,7 +220,7 @@ def resolve_pre_confirm_stage(
|
||||
根据 Candidate 资格评估结果解析确认建单前的 OT (stage, status)。
|
||||
|
||||
核心逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking;
|
||||
库存源阻断 → inventory_source_resolving;否则 waiting_review。
|
||||
库存源阻断 → onhand_source_resolving;否则 waiting_review。
|
||||
prefer_waiting_review 仅在无阻断时抬升到 waiting_review,不得覆盖前置业务阻断。
|
||||
|
||||
Args:
|
||||
@@ -258,7 +258,7 @@ def resolve_pre_confirm_stage(
|
||||
return 'duplicate_checking', 'waiting_review'
|
||||
|
||||
if any('inventory' in code for code in blocking):
|
||||
return 'inventory_source_resolving', 'waiting_review'
|
||||
return 'onhand_source_resolving', 'waiting_review'
|
||||
|
||||
# [BE-02] prefer_waiting_review 不得跳过客户/查重/库存源阻断;无阻断时才落到复核。
|
||||
return 'waiting_review', 'waiting_review'
|
||||
@@ -373,7 +373,7 @@ def sync_order_task_stage_for_notice(
|
||||
stage = gate_stage
|
||||
status = 'blocked'
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'inventory_matching'
|
||||
stage = 'onhand_matching'
|
||||
return sync_order_task_processing_state(
|
||||
ot,
|
||||
stage=stage,
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
services/shipping_notice/per_source_rpa_service.py
|
||||
|
||||
用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。
|
||||
依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、
|
||||
依赖:models.FreightRpaOnhandTaskAttempt、onhand_candidate_freeze_service(取候选源)、
|
||||
rpa.write_inventory_export_batch_trigger(批次 trigger 文件写入,单文件多源)与
|
||||
rpa.build_on_demand_inventory_trigger_source(逐源条目构造)、
|
||||
inventory_snapshot_store(快照复用判断)。
|
||||
onhand_snapshot_store(快照复用判断)。
|
||||
逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层,
|
||||
新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。
|
||||
三元组 (task_no, source_code, run_no) 幂等定位;迟到回调标记 superseded 不回写业务。
|
||||
@@ -27,14 +27,14 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingNotice,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
from app.services.shipping_notice.stp_onhand_freeze import (
|
||||
task_frozen_onhand_source_codes,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
from app.services.shipping_notice.onhand_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
is_snapshot_fresh,
|
||||
)
|
||||
@@ -45,7 +45,7 @@ from app.services.shipping_notice.onhand_trigger_batch import (
|
||||
from app.services.freight_rpa.onhand.trigger_io import SCHEMA
|
||||
|
||||
|
||||
def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None:
|
||||
def _archive_unclaimed_trigger(attempt: FreightRpaOnhandTaskAttempt) -> str | None:
|
||||
"""将仍在 trigger 根目录的未领取文件移入 failed;Worker 已领取/移走时安全忽略。"""
|
||||
if str(getattr(attempt, 'status', '') or '') != 'queued':
|
||||
return None
|
||||
@@ -70,7 +70,7 @@ def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str
|
||||
|
||||
|
||||
def _attempt_ref_has_ready_snapshot(
|
||||
attempt: ShippingTaskInventoryRpaAttempt,
|
||||
attempt: FreightRpaOnhandTaskAttempt,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> bool:
|
||||
@@ -80,12 +80,12 @@ def _attempt_ref_has_ready_snapshot(
|
||||
被误判为 prepared 而绕过有效库存门禁。
|
||||
"""
|
||||
sess = session or db.session
|
||||
file_no = str(getattr(attempt, 'inventory_file_no', '') or '').strip()
|
||||
file_no = str(getattr(attempt, 'onhand_file_no', '') or '').strip()
|
||||
if not file_no:
|
||||
return False
|
||||
inv_file = (
|
||||
sess.query(ShippingInventoryFile)
|
||||
.filter(ShippingInventoryFile.inventory_file_no == file_no)
|
||||
sess.query(FreightRpaOnhandReportFile)
|
||||
.filter(FreightRpaOnhandReportFile.onhand_file_no == file_no)
|
||||
.one_or_none()
|
||||
)
|
||||
return is_snapshot_fresh(inv_file)
|
||||
@@ -94,7 +94,7 @@ def _attempt_ref_has_ready_snapshot(
|
||||
def _validate_callback_attempt_identity(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
attempt: ShippingTaskInventoryRpaAttempt,
|
||||
attempt: FreightRpaOnhandTaskAttempt,
|
||||
callback_payload: dict[str, Any],
|
||||
) -> bool:
|
||||
"""校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。"""
|
||||
@@ -147,7 +147,7 @@ class PerSourcePrepareResult:
|
||||
source_attempts: dict[str, dict[str, Any]] # source_code → {attempt_no, status, run_no, error}
|
||||
|
||||
|
||||
def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str:
|
||||
def _per_source_run_no(attempt: FreightRpaOnhandTaskAttempt) -> str:
|
||||
"""
|
||||
构造 per-source 唯一 run_no:PSR-<attempt_id>(dumb ID)。
|
||||
|
||||
@@ -166,20 +166,20 @@ def _latest_attempt(
|
||||
source_code: str,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> ShippingTaskInventoryRpaAttempt | None:
|
||||
) -> FreightRpaOnhandTaskAttempt | None:
|
||||
"""查询 (task, source) 维度最新的 Attempt(按 attempt_no desc, id desc)。"""
|
||||
sess = session or db.session
|
||||
return (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
sess.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code,
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code,
|
||||
)
|
||||
)
|
||||
.order_by(
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
|
||||
ShippingTaskInventoryRpaAttempt.id.desc(),
|
||||
FreightRpaOnhandTaskAttempt.attempt_no.desc(),
|
||||
FreightRpaOnhandTaskAttempt.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
@@ -194,12 +194,12 @@ def _consumed_run_nos(
|
||||
"""查询 (task, source) 维度已 consumed/superseded 的 run_no 集合,用于回调幂等/迟到判断。"""
|
||||
sess = session or db.session
|
||||
rows = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt.run_no)
|
||||
sess.query(FreightRpaOnhandTaskAttempt.run_no)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code,
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded')),
|
||||
)
|
||||
)
|
||||
.all()
|
||||
@@ -219,25 +219,25 @@ def _next_attempt_no(
|
||||
"""
|
||||
sess = session or db.session
|
||||
last_success = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
sess.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('succeeded', 'consumed')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code,
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('succeeded', 'consumed')),
|
||||
)
|
||||
)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc())
|
||||
.order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
base_no = last_success.attempt_no if last_success else 0
|
||||
subsequent_count = (
|
||||
sess.query(func.count(ShippingTaskInventoryRpaAttempt.id))
|
||||
sess.query(func.count(FreightRpaOnhandTaskAttempt.id))
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code,
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no > base_no,
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code,
|
||||
FreightRpaOnhandTaskAttempt.attempt_no > base_no,
|
||||
)
|
||||
)
|
||||
.scalar()
|
||||
@@ -264,7 +264,7 @@ def _snapshot_ready_for_source(
|
||||
snap = find_latest_ready_snapshot(source_code, warehouse_id)
|
||||
except Exception:
|
||||
snap = None
|
||||
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
source_config_version = None
|
||||
if isinstance(rpa_source, dict):
|
||||
source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version')
|
||||
@@ -314,7 +314,7 @@ def ensure_all_required_sources_prepared(
|
||||
) -> PerSourcePrepareResult:
|
||||
"""
|
||||
遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。
|
||||
【AI 触发时机】:inventory_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。
|
||||
【AI 触发时机】:onhand_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] 从 T3 冻结表/兼容 step_payload 读取候选 source_codes(保序)。
|
||||
@@ -325,10 +325,10 @@ def ensure_all_required_sources_prepared(
|
||||
- succeeded/consumed → 已 prepared
|
||||
- 从未 attempt → 首次触发新 attempt(queued 新 run)
|
||||
- failed/exhausted → 仅用户显式 retry_rpa 才触发下一 Attempt
|
||||
c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件
|
||||
c. 写 FreightRpaOnhandTaskAttempt 记录 + trigger 文件
|
||||
|
||||
Args:
|
||||
allow_auto_retry: 只读轮询开关。poll_inventory_preparation 等查询路径必须传 False:
|
||||
allow_auto_retry: 只读轮询开关。poll_onhand_preparation 等查询路径必须传 False:
|
||||
轮询只消费 Attempt 事实(快照复用/pending/failed 上报),禁止自动新建 Attempt。
|
||||
无论此开关取值,失败后的重试都只能由用户显式动作(mode='retry_rpa')发起,
|
||||
避免 RPA Worker 离线时形成“失败→重试→再失败”的无人值守空转环。
|
||||
@@ -349,7 +349,7 @@ def ensure_all_required_sources_prepared(
|
||||
# SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。
|
||||
pass
|
||||
source_codes = [
|
||||
str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task))
|
||||
str(code).strip().upper() for code in (source_codes or task_frozen_onhand_source_codes(task))
|
||||
if str(code).strip()
|
||||
]
|
||||
if not source_codes:
|
||||
@@ -359,14 +359,14 @@ def ensure_all_required_sources_prepared(
|
||||
failed_source_codes=[], source_attempts={},
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
prepared: list[str] = []
|
||||
pending: list[str] = []
|
||||
failed: list[str] = []
|
||||
# 本轮待触发源的单源条目与对应 Attempt;循环后合并写入单个批次 trigger。
|
||||
pending_payloads: list[dict[str, Any]] = []
|
||||
pending_attempts: list[ShippingTaskInventoryRpaAttempt] = []
|
||||
pending_attempts: list[FreightRpaOnhandTaskAttempt] = []
|
||||
|
||||
for source_code in source_codes:
|
||||
rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code}
|
||||
@@ -386,8 +386,8 @@ def ensure_all_required_sources_prepared(
|
||||
# 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt,
|
||||
# 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。
|
||||
if mode == 'retry_rpa' or current_status in {'failed', 'exhausted'}:
|
||||
from app.models.shipping_task_inventory_rpa_attempts import (
|
||||
ShippingTaskInventoryRpaAttempt as _Attempt2,
|
||||
from app.models.freight_rpa_onhand_task_attempts import (
|
||||
FreightRpaOnhandTaskAttempt as _Attempt2,
|
||||
)
|
||||
q = (
|
||||
sess.query(_Attempt2)
|
||||
@@ -433,7 +433,7 @@ def ensure_all_required_sources_prepared(
|
||||
next_att_no = _next_attempt_no(task_no, source_code, session=sess)
|
||||
|
||||
# [STEP 2c] 新建 Attempt + 写 trigger 文件
|
||||
new_att = ShippingTaskInventoryRpaAttempt(
|
||||
new_att = FreightRpaOnhandTaskAttempt(
|
||||
task_no=task_no,
|
||||
source_code=source_code,
|
||||
attempt_no=next_att_no,
|
||||
@@ -450,7 +450,7 @@ def ensure_all_required_sources_prepared(
|
||||
sess.flush([new_att])
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source)
|
||||
@@ -565,7 +565,7 @@ def per_source_callback_handler(
|
||||
run_no: str,
|
||||
callback_payload: dict[str, Any],
|
||||
session: Session | None = None,
|
||||
) -> tuple[str, ShippingTaskInventoryRpaAttempt | None]:
|
||||
) -> tuple[str, FreightRpaOnhandTaskAttempt | None]:
|
||||
"""
|
||||
处理 per-source 库存 RPA 回调(三元组幂等 + 迟到保护 + Task 全局状态保护)。
|
||||
【AI 触发时机】:RPA Dropzone 回调入口、手动 ingest API、Worker 补录回调统一调用本函数。
|
||||
@@ -586,7 +586,7 @@ def per_source_callback_handler(
|
||||
session: 可选 Session。
|
||||
|
||||
Returns:
|
||||
(result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None)
|
||||
(result_code: str, attempt: FreightRpaOnhandTaskAttempt | None)
|
||||
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, validated, succeeded, failed}
|
||||
"""
|
||||
sess = session or db.session
|
||||
@@ -598,7 +598,7 @@ def per_source_callback_handler(
|
||||
callback_id = str((callback_payload or {}).get('callback_id') or '').strip()
|
||||
if callback_id:
|
||||
callback_attempt = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
sess.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter_by(callback_id=callback_id)
|
||||
.one_or_none()
|
||||
)
|
||||
@@ -614,12 +614,12 @@ def per_source_callback_handler(
|
||||
|
||||
# [STEP 2] 三元组定位
|
||||
attempt = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
sess.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code_up,
|
||||
ShippingTaskInventoryRpaAttempt.run_no == run_no,
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code_up,
|
||||
FreightRpaOnhandTaskAttempt.run_no == run_no,
|
||||
)
|
||||
)
|
||||
.one_or_none()
|
||||
@@ -638,7 +638,7 @@ def per_source_callback_handler(
|
||||
attempt.error_code = 'trigger_identity_invalid'
|
||||
attempt.error_message = str((callback_payload or {}).get('error_message') or 'RPA trigger identity is invalid.')[:2000]
|
||||
attempt.updated_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
|
||||
sess.flush([attempt])
|
||||
return 'failed', attempt
|
||||
@@ -664,13 +664,13 @@ def per_source_callback_handler(
|
||||
except (TypeError, ValueError):
|
||||
current_attempt_no = 0
|
||||
newer_count = (
|
||||
sess.query(func.count(ShippingTaskInventoryRpaAttempt.id))
|
||||
sess.query(func.count(FreightRpaOnhandTaskAttempt.id))
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.source_code == source_code_up,
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no > current_attempt_no,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded', 'succeeded')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.source_code == source_code_up,
|
||||
FreightRpaOnhandTaskAttempt.attempt_no > current_attempt_no,
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded', 'succeeded')),
|
||||
)
|
||||
)
|
||||
.scalar()
|
||||
@@ -714,7 +714,7 @@ def per_source_callback_handler(
|
||||
attempt.callback_file_path = str(callback_payload.get('callback_file_path') or '').strip() or None
|
||||
inventory_file_no = str(callback_payload.get('inventory_file_no') or '').strip() or None
|
||||
if inventory_file_no:
|
||||
attempt.inventory_file_no = inventory_file_no
|
||||
attempt.onhand_file_no = inventory_file_no
|
||||
|
||||
error_code = str(callback_payload.get('error_code') or '').strip() or None
|
||||
error_message = str(callback_payload.get('error_message') or '').strip() or None
|
||||
@@ -723,15 +723,15 @@ def per_source_callback_handler(
|
||||
attempt.transaction_status = 'rejected'
|
||||
attempt.error_code = error_code
|
||||
attempt.error_message = error_message[:2000] if error_message else None
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
|
||||
sess.flush([attempt])
|
||||
return 'failed', attempt
|
||||
# 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功)
|
||||
if inventory_file_no:
|
||||
_inv = (
|
||||
sess.query(ShippingInventoryFile)
|
||||
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
|
||||
sess.query(FreightRpaOnhandReportFile)
|
||||
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
|
||||
.one_or_none()
|
||||
)
|
||||
if _inv is None or not is_snapshot_fresh(_inv):
|
||||
@@ -749,13 +749,13 @@ def per_source_callback_handler(
|
||||
attempt.error_message = (
|
||||
f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000]
|
||||
)
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed')
|
||||
sess.flush([attempt])
|
||||
return 'failed', attempt
|
||||
attempt.status = 'succeeded'
|
||||
attempt.transaction_status = 'succeeded'
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
sync_preparation_source_from_rpa_attempt(
|
||||
rpa_attempt_id=int(attempt.id),
|
||||
rpa_status='succeeded',
|
||||
@@ -766,7 +766,7 @@ def per_source_callback_handler(
|
||||
# 调用方在同一事务提交后,Job 才对 Worker 可见。
|
||||
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
|
||||
|
||||
submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded', commit=False)
|
||||
submit_auto_progress(task=task, trigger='onhand_rpa_callback_succeeded', commit=False)
|
||||
return 'succeeded', attempt
|
||||
|
||||
|
||||
@@ -785,7 +785,7 @@ def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source_code = str(item.get('source_code') or '').strip().upper()
|
||||
source_run_no = str(item.get('source_run_no') or '').strip()
|
||||
lease_token = str(item.get('lease_token') or '').strip()
|
||||
attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(
|
||||
attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(
|
||||
task_no=task_no, source_code=source_code, source_run_no=source_run_no,
|
||||
).one_or_none()
|
||||
if attempt is None or str(attempt.lease_token or '') != lease_token:
|
||||
@@ -829,15 +829,15 @@ def per_source_timeout_scan(
|
||||
task_no = str(task.task_no or '').strip()
|
||||
threshold = datetime.utcnow() - timedelta(seconds=max(int(timeout_seconds), 1))
|
||||
candidates = (
|
||||
sess.query(ShippingTaskInventoryRpaAttempt)
|
||||
sess.query(FreightRpaOnhandTaskAttempt)
|
||||
.filter(
|
||||
and_(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == task_no,
|
||||
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
|
||||
FreightRpaOnhandTaskAttempt.task_no == task_no,
|
||||
FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')),
|
||||
or_(
|
||||
ShippingTaskInventoryRpaAttempt.triggered_at <= threshold,
|
||||
ShippingTaskInventoryRpaAttempt.leased_at <= threshold,
|
||||
ShippingTaskInventoryRpaAttempt.created_at <= threshold,
|
||||
FreightRpaOnhandTaskAttempt.triggered_at <= threshold,
|
||||
FreightRpaOnhandTaskAttempt.leased_at <= threshold,
|
||||
FreightRpaOnhandTaskAttempt.created_at <= threshold,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -868,7 +868,7 @@ def per_source_timeout_scan(
|
||||
att.extra_json = extra
|
||||
# 超时扫描与正式回调共享同一准备轮次事实;否则 Attempt 已失败而
|
||||
# PreparationAttempt 仍停在 waiting_external,工作台会错误禁用重试。
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt
|
||||
|
||||
sync_preparation_source_from_rpa_attempt(
|
||||
rpa_attempt_id=int(att.id),
|
||||
|
||||
@@ -66,7 +66,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
|
||||
if str(line.get('inventory_status') or '') != 'ready':
|
||||
raise ConflictError(
|
||||
'Inventory not ready for post-OT wave',
|
||||
code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY',
|
||||
code='SHIPPING.REVIEW_LINE_ONHAND_NOT_READY',
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')},
|
||||
)
|
||||
if str(line.get('match_result') or '') != 'matched':
|
||||
@@ -75,11 +75,11 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
|
||||
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id'), 'match_result': line.get('match_result')},
|
||||
)
|
||||
is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage'
|
||||
is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_onhand_shortage'
|
||||
if line.get('is_shortage') and not is_released_shortage:
|
||||
raise ConflictError(
|
||||
'Line has inventory shortage',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND',
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id')},
|
||||
)
|
||||
req = _parse_qty(line.get('required_qty'))
|
||||
@@ -87,7 +87,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
|
||||
if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage):
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory facts',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND',
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id')},
|
||||
)
|
||||
return req, avail
|
||||
@@ -311,13 +311,13 @@ def create_post_ot_fulfillment_wave(
|
||||
revision_id=None,
|
||||
)
|
||||
# [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_wave_notice_routing
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_wave_notice_routing
|
||||
|
||||
routing_result = freeze_wave_notice_routing(notice, source_notice=None)
|
||||
if routing_result is None or not routing_result.source_codes:
|
||||
raise ConflictError(
|
||||
'Inventory source routing is unresolved for selected fulfillment lines',
|
||||
code='SHIPPING.REVIEW_LINE_INVENTORY_SOURCE_UNRESOLVED',
|
||||
code='SHIPPING.REVIEW_LINE_ONHAND_SOURCE_UNRESOLVED',
|
||||
details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]},
|
||||
)
|
||||
db.session.flush()
|
||||
@@ -351,7 +351,7 @@ def create_post_ot_fulfillment_wave(
|
||||
if (
|
||||
key in accepted_snapshot_line_ids
|
||||
and current is not None
|
||||
and current.decision_code == 'release_inventory_shortage'
|
||||
and current.decision_code == 'release_onhand_shortage'
|
||||
):
|
||||
current.line_status = 'task_created'
|
||||
current.task_id = int(order_task.id)
|
||||
@@ -476,7 +476,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li
|
||||
列出可自动/人工履约的行(ready+matched+未关闭+未终态)。
|
||||
|
||||
核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下
|
||||
``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。
|
||||
``release_onhand_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
@@ -496,7 +496,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li
|
||||
if str(item.get('match_result') or '') != 'matched':
|
||||
continue
|
||||
decision_code = str((item.get('decision') or {}).get('decision_code') or '')
|
||||
if item.get('is_shortage') and decision_code != 'release_inventory_shortage':
|
||||
if item.get('is_shortage') and decision_code != 'release_onhand_shortage':
|
||||
continue
|
||||
if item.get('user_line_status') == 'auto_fulfill_failed':
|
||||
continue
|
||||
@@ -504,7 +504,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li
|
||||
continue
|
||||
req = _parse_qty(item.get('required_qty'))
|
||||
avail = _parse_qty(item.get('available_qty'))
|
||||
is_released_shortage = decision_code == 'release_inventory_shortage'
|
||||
is_released_shortage = decision_code == 'release_onhand_shortage'
|
||||
if req is None or (avail is None and not is_released_shortage) or (
|
||||
avail is not None and avail < req and not is_released_shortage
|
||||
):
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/process_gate_bridge.py
|
||||
|
||||
用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、
|
||||
将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。
|
||||
依赖:process_gate_service、process_gate_contract、constants、inventory_rpa_workflow、
|
||||
依赖:process_gate_service、process_gate_contract、constants、onhand_rpa_workflow、
|
||||
ShippingProcessExecution、ShippingOrderReviewCase、ShippingNotice。
|
||||
逻辑:由 order_extraction_run_service / order_review_confirmation_service /
|
||||
order_review_draft_service / progress_workflow / process_gate_executor 调用;
|
||||
@@ -11,9 +11,9 @@ services/shipping_notice/process_gate_bridge.py
|
||||
复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details;
|
||||
确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定;
|
||||
禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code;
|
||||
建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation
|
||||
供 ensure_inventory(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时,
|
||||
不把 inventory_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。
|
||||
建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_onhand_preparation
|
||||
供 ensure_onhand(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时,
|
||||
不把 onhand_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -60,7 +60,7 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str
|
||||
if upload_status == 'failed':
|
||||
return 'upload_failed'
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
current_inventory_matches_have_shortage,
|
||||
inventory_matches_complete_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
@@ -69,12 +69,12 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str
|
||||
if inventory_matches_complete_for_task(task):
|
||||
return 'shortage_review' if current_inventory_matches_have_shortage(task) else 'matched'
|
||||
return 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'created'
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
match_status = aggregate_match_status_for_task(match_task_id) or ''
|
||||
if match_status in {'fulfillable', 'partial', 'unfulfillable'}:
|
||||
return 'matched'
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
if has_ready_inventory_file_for_task(task):
|
||||
return 'inventory_ready'
|
||||
return 'created'
|
||||
@@ -84,32 +84,32 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice)
|
||||
"""
|
||||
由任务事实推导库存准备门禁阻断原因码。
|
||||
|
||||
核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt
|
||||
核心逻辑:pending_human_reason、最近 onhand_rpa_failed 事件与逐源 Attempt
|
||||
失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
|
||||
惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。
|
||||
惰性导入 constants / onhand_rpa_workflow,避免与桥接模块循环依赖。
|
||||
|
||||
Args:
|
||||
task: 履约任务。
|
||||
|
||||
Returns:
|
||||
稳定阻断原因码(归属 inventory_preparation)。
|
||||
稳定阻断原因码(归属 onhand_preparation)。
|
||||
"""
|
||||
from app.services.shipping_notice.constants import (
|
||||
PH_INV_UNAVAIL,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event
|
||||
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
pending = str(task_blocking_reason(task) or '').strip()
|
||||
if pending == PH_RPA_PENDING:
|
||||
return 'inventory_rpa_queued'
|
||||
return 'onhand_rpa_queued'
|
||||
if pending == PH_RPA_EXHAUSTED:
|
||||
return 'inventory_rpa_exhausted'
|
||||
return 'onhand_rpa_exhausted'
|
||||
|
||||
if getattr(task, 'id', None) is not None:
|
||||
failed = latest_task_event(task, 'inventory_rpa_failed')
|
||||
failed = latest_task_event(task, 'onhand_rpa_failed')
|
||||
if failed is not None:
|
||||
payload = getattr(failed, 'detail_json', None)
|
||||
if not isinstance(payload, dict):
|
||||
@@ -119,29 +119,29 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice)
|
||||
code = str(payload.get('error_code') or '').strip().lower()
|
||||
blob = f'{err} {code}'
|
||||
if 'timeout' in blob or ('not ready' in blob and 'within' in blob):
|
||||
return 'inventory_rpa_timeout'
|
||||
return 'onhand_rpa_timeout'
|
||||
if 'login' in blob or 'auth' in blob:
|
||||
return 'inventory_rpa_login_failed'
|
||||
return 'onhand_rpa_login_failed'
|
||||
if 'export' in blob or 'rpa_export' in blob:
|
||||
return 'inventory_rpa_export_failed'
|
||||
return 'onhand_rpa_export_failed'
|
||||
if 'empty' in blob:
|
||||
return 'inventory_file_empty'
|
||||
if 'identity' in blob or 'mismatch' in blob:
|
||||
return 'inventory_file_identity_mismatch'
|
||||
return 'inventory_rpa_export_failed'
|
||||
return 'onhand_rpa_export_failed'
|
||||
|
||||
# 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧
|
||||
# ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
|
||||
latest_attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(),
|
||||
FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or '').strip(),
|
||||
)
|
||||
.order_by(
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
|
||||
ShippingTaskInventoryRpaAttempt.id.desc(),
|
||||
FreightRpaOnhandTaskAttempt.attempt_no.desc(),
|
||||
FreightRpaOnhandTaskAttempt.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
@@ -152,16 +152,16 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice)
|
||||
str(latest_attempt.error_message or '').strip().lower(),
|
||||
])
|
||||
if 'exhausted' in blob:
|
||||
return 'inventory_rpa_exhausted'
|
||||
return 'onhand_rpa_exhausted'
|
||||
if 'timeout' in blob or ('not ready' in blob and 'within' in blob):
|
||||
return 'inventory_rpa_timeout'
|
||||
return 'onhand_rpa_timeout'
|
||||
if 'login' in blob or 'auth' in blob:
|
||||
return 'inventory_rpa_login_failed'
|
||||
return 'onhand_rpa_login_failed'
|
||||
if 'empty' in blob:
|
||||
return 'inventory_file_empty'
|
||||
if 'identity' in blob or 'mismatch' in blob:
|
||||
return 'inventory_file_identity_mismatch'
|
||||
return 'inventory_rpa_export_failed'
|
||||
return 'onhand_rpa_export_failed'
|
||||
|
||||
# inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计,
|
||||
# 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。
|
||||
@@ -174,7 +174,7 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice)
|
||||
return 'inventory_file_missing'
|
||||
|
||||
# [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task
|
||||
|
||||
active_lines = active_inventory_lines_for_task(task)
|
||||
if isinstance(active_lines, list):
|
||||
@@ -216,7 +216,7 @@ def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str:
|
||||
return 'upload_rpa_pending'
|
||||
if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed':
|
||||
# [STEP] 登录失败优先于泛化 upload_rpa_failed,便于责任方落到 admin
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event
|
||||
|
||||
if getattr(task, 'id', None) is not None:
|
||||
failed = latest_task_event(task, 'upload_rpa_failed') or latest_task_event(
|
||||
@@ -532,26 +532,26 @@ def sync_execution_after_review_confirm(
|
||||
)
|
||||
# [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。
|
||||
# CandidateSet 是 inventory_source_routing 通过的必要业务事实。
|
||||
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source
|
||||
|
||||
adjudication = adjudicate_and_apply_inventory_source(
|
||||
task,
|
||||
execution_id=int(execution.id),
|
||||
)
|
||||
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
|
||||
|
||||
if not task_frozen_inventory_source_codes(task):
|
||||
if not task_frozen_onhand_source_codes(task):
|
||||
# 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。
|
||||
return execution
|
||||
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_source_routing',
|
||||
gate_code='onhand_source_routing',
|
||||
passed=True,
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'candidate_set_id': int(task.active_inventory_candidate_set_id),
|
||||
'source_codes': task_frozen_inventory_source_codes(task),
|
||||
'source_codes': task_frozen_onhand_source_codes(task),
|
||||
'status': str(adjudication.status or 'resolved'),
|
||||
},
|
||||
actor_type='user',
|
||||
@@ -673,14 +673,14 @@ def sync_inventory_routing_gate_for_case(
|
||||
blocking_reason_code: str | None = None,
|
||||
) -> ShippingProcessGate | None:
|
||||
"""
|
||||
将库存源路由业务结果同步到 inventory_source_routing Gate。
|
||||
将库存源路由业务结果同步到 onhand_source_routing Gate。
|
||||
|
||||
Returns:
|
||||
更新后的 Gate;无 Execution 时尝试创建后同步。
|
||||
"""
|
||||
return sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='inventory_source_routing',
|
||||
gate_code='onhand_source_routing',
|
||||
passed=passed,
|
||||
actor_id=actor_id,
|
||||
details=details,
|
||||
@@ -900,8 +900,8 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
|
||||
自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running
|
||||
会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。
|
||||
仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止
|
||||
用户主动 retry_inventory_preparation。
|
||||
仅处理 trigger_type=auto 且 action_code=poll_onhand_preparation,绝不终止
|
||||
用户主动 retry_onhand_preparation。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingProcessGateAttempt
|
||||
@@ -915,7 +915,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
):
|
||||
return
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).with_for_update().first()
|
||||
if gate is None:
|
||||
return
|
||||
@@ -932,7 +932,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
now = datetime.utcnow()
|
||||
for attempt in active_attempts:
|
||||
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
|
||||
if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation':
|
||||
if str(snapshot.get('action_code') or '').strip() != 'poll_onhand_preparation':
|
||||
continue
|
||||
before = {'status': attempt.status, 'gate_code': gate.gate_code}
|
||||
attempt.status = 'superseded'
|
||||
@@ -965,10 +965,10 @@ def sync_fulfillment_gates_from_task(
|
||||
actor_id: str | int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。
|
||||
按 ShippingNotice 履约状态同步 onhand_preparation→freight_upload_rpa→manual_upload_handoff。
|
||||
|
||||
核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果;
|
||||
建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数;
|
||||
建单后尚无库存行时不投影假失败,只露出 retry_onhand_preparation 供自动取数;
|
||||
RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断
|
||||
manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。
|
||||
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
|
||||
@@ -995,7 +995,7 @@ def sync_fulfillment_gates_from_task(
|
||||
match_completed,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
active_inventory_lines_for_task,
|
||||
)
|
||||
@@ -1087,18 +1087,18 @@ def sync_fulfillment_gates_from_task(
|
||||
# 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。
|
||||
preparation = None
|
||||
try:
|
||||
from app.models import ShippingInventoryPreparationAttempt
|
||||
from app.models import ShippingOnhandPreparationAttempt
|
||||
|
||||
prep_query = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
ShippingOnhandPreparationAttempt.query
|
||||
.filter_by(task_id=int(task.id), execution_id=int(execution.id))
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.filter(ShippingOnhandPreparationAttempt.status != 'superseded')
|
||||
)
|
||||
if execution.candidate_set_id is not None:
|
||||
prep_query = prep_query.filter(
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
|
||||
ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
|
||||
)
|
||||
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
|
||||
preparation = prep_query.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()).first()
|
||||
except Exception: # noqa: BLE001
|
||||
preparation = None
|
||||
# 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为
|
||||
@@ -1122,7 +1122,7 @@ def sync_fulfillment_gates_from_task(
|
||||
task_rpa_exhausted = str(task_blocking_reason(task) or '').strip() == 'rpa_exhausted'
|
||||
if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending):
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
execution=execution, gate_code='onhand_preparation', passed=False,
|
||||
outcome='waiting_external', effective_result={'findings': [], **task_facts},
|
||||
blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
@@ -1138,7 +1138,7 @@ def sync_fulfillment_gates_from_task(
|
||||
or 'inventory_preparation_failed'
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
execution=execution, gate_code='onhand_preparation', passed=False,
|
||||
outcome='blocked_retryable', effective_result={'findings': [], **task_facts},
|
||||
blocking_reason_code=preparation_reason, actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
@@ -1147,7 +1147,7 @@ def sync_fulfillment_gates_from_task(
|
||||
return
|
||||
if preparation.status == 'succeeded' and required and len(prepared) == len(required):
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=True,
|
||||
execution=execution, gate_code='onhand_preparation', passed=True,
|
||||
effective_result=task_facts, actor_type=actor_type, actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True,
|
||||
)
|
||||
@@ -1160,22 +1160,22 @@ def sync_fulfillment_gates_from_task(
|
||||
# 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。
|
||||
if pending_reason == PH_RPA_PENDING:
|
||||
outcome = 'waiting_external'
|
||||
waiting_reason = 'inventory_rpa_queued'
|
||||
waiting_reason = 'onhand_rpa_queued'
|
||||
elif pending_reason == PH_RPA_EXHAUSTED:
|
||||
# 兼容历史 rpa_exhausted:自动次数上限不得限制用户再次发起库存准备。
|
||||
outcome = 'blocked_retryable'
|
||||
waiting_reason = 'inventory_rpa_exhausted'
|
||||
waiting_reason = 'onhand_rpa_exhausted'
|
||||
else:
|
||||
outcome = 'blocked_retryable'
|
||||
waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed'
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
passed=False,
|
||||
outcome=outcome,
|
||||
effective_result={
|
||||
'findings': _fulfillment_blocking_finding(
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
reason_code=waiting_reason,
|
||||
details=task_facts,
|
||||
),
|
||||
@@ -1194,7 +1194,7 @@ def sync_fulfillment_gates_from_task(
|
||||
if not has_inventory_lines and status == 'created':
|
||||
prep_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code='inventory_preparation')
|
||||
.filter_by(execution_id=int(execution.id), gate_code='onhand_preparation')
|
||||
.first()
|
||||
)
|
||||
if prep_gate is not None and str(prep_gate.status or '').strip().lower() in {
|
||||
@@ -1206,10 +1206,10 @@ def sync_fulfillment_gates_from_task(
|
||||
)
|
||||
prep_gate.next_action_code = (
|
||||
primary_next_action_for_gate(
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
status='blocked_retryable',
|
||||
)
|
||||
or 'retry_inventory_preparation'
|
||||
or 'retry_onhand_preparation'
|
||||
)
|
||||
prep_gate.updated_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
@@ -1223,13 +1223,13 @@ def sync_fulfillment_gates_from_task(
|
||||
inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
passed=inv_prep_passed,
|
||||
outcome=None if inv_prep_passed else 'blocked_retryable',
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if inv_prep_passed else _fulfillment_blocking_finding(
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
reason_code=str(inv_prep_reason or 'inventory_preparation_failed'),
|
||||
details=task_facts,
|
||||
)
|
||||
@@ -1250,13 +1250,13 @@ def sync_fulfillment_gates_from_task(
|
||||
mapping_reason = 'inventory_mapping_required' if mapping_needed else None
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_field_mapping',
|
||||
gate_code='onhand_field_mapping',
|
||||
passed=not mapping_needed,
|
||||
outcome='blocked_retryable' if mapping_needed else None,
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if not mapping_needed else _fulfillment_blocking_finding(
|
||||
gate_code='inventory_field_mapping',
|
||||
gate_code='onhand_field_mapping',
|
||||
reason_code=mapping_reason or 'inventory_mapping_required',
|
||||
details={
|
||||
**task_facts,
|
||||
@@ -1281,8 +1281,8 @@ def sync_fulfillment_gates_from_task(
|
||||
classify_inventory_match_reason,
|
||||
)
|
||||
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
from app.models import ShippingNoticeLineOnhandMatch
|
||||
current_match_rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
line_results = [{'disposition': row.match_result} for row in current_match_rows]
|
||||
# 库存已就绪但尚无匹配行:匹配 Gate 若仍是 pending/queued/running,说明匹配尚未执行完,
|
||||
# 不得投影成 inventory_match_failed(界面会显示 --,并与 auto-progress 并发踩踏)。
|
||||
@@ -1290,13 +1290,13 @@ def sync_fulfillment_gates_from_task(
|
||||
if not match_passed and not current_match_rows:
|
||||
match_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code='inventory_matching')
|
||||
.filter_by(execution_id=int(execution.id), gate_code='onhand_matching')
|
||||
.first()
|
||||
)
|
||||
match_gate_status = str(getattr(match_gate, 'status', '') or '').strip().lower() if match_gate else ''
|
||||
if match_gate is not None and match_gate_status in {'pending', 'queued', 'running'}:
|
||||
if not str(match_gate.next_action_code or '').strip():
|
||||
match_gate.next_action_code = 'retry_inventory_matching'
|
||||
match_gate.next_action_code = 'retry_onhand_matching'
|
||||
match_gate.updated_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
_refresh_execution_pointers,
|
||||
@@ -1309,14 +1309,14 @@ def sync_fulfillment_gates_from_task(
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
passed=match_passed,
|
||||
# 匹配已执行过但仍无终态事实时,才投影可重试失败并露出 retry_inventory_matching。
|
||||
outcome='blocked_retryable' if not match_passed else None,
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if match_passed else _fulfillment_blocking_finding(
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
reason_code=str(match_reason or 'inventory_match_failed'),
|
||||
details={
|
||||
**task_facts,
|
||||
@@ -1351,13 +1351,13 @@ def sync_fulfillment_gates_from_task(
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_sufficiency',
|
||||
gate_code='onhand_sufficiency',
|
||||
passed=sufficiency_ok,
|
||||
outcome='blocked_manual' if shortage else None,
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if sufficiency_ok else _fulfillment_blocking_finding(
|
||||
gate_code='inventory_sufficiency',
|
||||
gate_code='onhand_sufficiency',
|
||||
reason_code=str(shortage_reason or 'inventory_insufficient'),
|
||||
details={**task_facts, 'match_status': match_status or None},
|
||||
)
|
||||
|
||||
@@ -223,7 +223,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'gate_code': 'onhand_source_routing',
|
||||
'sequence_no': 12,
|
||||
'label': '库存源路由',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'},
|
||||
@@ -236,56 +236,56 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_preparation',
|
||||
'gate_code': 'onhand_preparation',
|
||||
'sequence_no': 13,
|
||||
'label': '库存文件或快照准备',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_preparation'},
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_preparation'},
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_preparation',
|
||||
'waiting_external': 'poll_inventory_preparation',
|
||||
'blocked_manual': 'retry_inventory_preparation',
|
||||
'blocked_retryable': 'retry_onhand_preparation',
|
||||
'waiting_external': 'poll_onhand_preparation',
|
||||
'blocked_manual': 'retry_onhand_preparation',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_field_mapping',
|
||||
'gate_code': 'onhand_field_mapping',
|
||||
'sequence_no': 14,
|
||||
'label': '库存字段映射',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_field_mapping'},
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_field_mapping'},
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_field_mapping',
|
||||
'blocked_retryable': 'retry_onhand_field_mapping',
|
||||
# 字段映射是库存模板治理,不允许用户确认技术映射。
|
||||
'blocked_manual': 'retry_inventory_field_mapping',
|
||||
'blocked_manual': 'retry_onhand_field_mapping',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_matching',
|
||||
'gate_code': 'onhand_matching',
|
||||
'sequence_no': 15,
|
||||
'label': 'Reservation + 料号匹配',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_matching'},
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_matching'},
|
||||
'responsible_party': 'worker',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_matching',
|
||||
'blocked_manual': 'open_inventory_match_review',
|
||||
'blocked_retryable': 'retry_onhand_matching',
|
||||
'blocked_manual': 'open_onhand_match_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'gate_code': 'onhand_sufficiency',
|
||||
'sequence_no': 16,
|
||||
'label': '库存满足性',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_sufficiency'},
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_sufficiency'},
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_inventory_sufficiency',
|
||||
'blocked_retryable': 'recheck_onhand_sufficiency',
|
||||
'blocked_manual': 'open_shortage_review',
|
||||
},
|
||||
},
|
||||
@@ -366,17 +366,17 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'retry_with_latest_rules',
|
||||
'recheck_freeze_readiness',
|
||||
'retry_task_creation',
|
||||
'retry_inventory_preparation',
|
||||
'reload_inventory_result',
|
||||
'poll_inventory_preparation',
|
||||
'retry_inventory_field_mapping',
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_inventory_from_field_mapping',
|
||||
'retry_inventory_from_matching',
|
||||
'override_line_inventory_source',
|
||||
'open_inventory_match_review',
|
||||
'recheck_inventory_sufficiency',
|
||||
'retry_onhand_preparation',
|
||||
'reload_onhand_result',
|
||||
'poll_onhand_preparation',
|
||||
'retry_onhand_field_mapping',
|
||||
'retry_onhand_matching',
|
||||
'retry_onhand_from_preparation',
|
||||
'retry_onhand_from_field_mapping',
|
||||
'retry_onhand_from_matching',
|
||||
'override_line_onhand_source',
|
||||
'open_onhand_match_review',
|
||||
'recheck_onhand_sufficiency',
|
||||
'open_shortage_review',
|
||||
'recheck_excel_readiness',
|
||||
'regenerate_excel_artifact',
|
||||
@@ -405,7 +405,7 @@ PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = {
|
||||
for _code in {
|
||||
'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation',
|
||||
'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts',
|
||||
'open_inventory_match_review', 'open_shortage_review',
|
||||
'open_onhand_match_review', 'open_shortage_review',
|
||||
}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation'
|
||||
# ``ui_handler`` 是页面宿主能力标识,不参与动作授权或业务裁决。后端在这里声明
|
||||
@@ -418,16 +418,16 @@ for _code, _ui_handler in {
|
||||
'confirm_customer': {'ui_handler': 'customer_resolution'},
|
||||
'adjudicate_duplicate': {'ui_handler': 'duplicate_review'},
|
||||
'resolve_field_conflicts': {'ui_handler': 'field_conflicts'},
|
||||
'open_inventory_match_review': {'ui_handler': 'inventory_match_review'},
|
||||
'open_onhand_match_review': {'ui_handler': 'inventory_match_review'},
|
||||
'open_shortage_review': {'ui_handler': 'shortage_review'},
|
||||
}.items():
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler)
|
||||
# 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。
|
||||
PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog'
|
||||
PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation'
|
||||
for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}:
|
||||
for _code in {'retry_onhand_from_preparation', 'retry_onhand_from_field_mapping', 'retry_onhand_from_matching'}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery'
|
||||
for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}:
|
||||
for _code in {'poll_onhand_preparation', 'poll_freight_upload_rpa'}:
|
||||
PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh'
|
||||
|
||||
def action_presentation(
|
||||
@@ -478,25 +478,25 @@ def inventory_preparation_primary_action(
|
||||
"""裁决库存准备 Gate 面向业务用户的主动作。
|
||||
|
||||
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
|
||||
``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching``
|
||||
``retry_onhand_preparation``(显式重跑 RPA)与 ``retry_onhand_matching``
|
||||
(复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。
|
||||
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
||||
``retry_inventory_matching``。
|
||||
边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。
|
||||
因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用
|
||||
已下线的 ``reload_onhand_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
||||
``retry_onhand_matching``。
|
||||
边界(STP 多候选,ensure_onhand auto 模式):缺快照停人工待处理、不隐式触发 RPA。
|
||||
因此获取库存未成功(无行级匹配结果)时,``retry_onhand_matching`` 由阶段能力禁用
|
||||
(disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task),
|
||||
重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。
|
||||
重抓必须走显式的 ``retry_onhand_preparation``;本函数只裁决按钮位次,不禁用按钮。
|
||||
"""
|
||||
normalized_status = str(status or '').strip().lower()
|
||||
normalized_reason = str(blocking_reason_code or '').strip().lower()
|
||||
if normalized_status == 'waiting_external':
|
||||
return 'poll_inventory_preparation'
|
||||
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
|
||||
return 'poll_onhand_preparation'
|
||||
if normalized_reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'}:
|
||||
# [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力
|
||||
# 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。
|
||||
return 'retry_inventory_matching'
|
||||
return 'retry_onhand_matching'
|
||||
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
|
||||
return 'retry_inventory_preparation'
|
||||
return 'retry_onhand_preparation'
|
||||
return None
|
||||
|
||||
|
||||
@@ -534,10 +534,10 @@ def gate_side_recovery_actions(
|
||||
# [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照
|
||||
# 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。
|
||||
if (
|
||||
code == 'inventory_preparation'
|
||||
and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
|
||||
code == 'onhand_preparation'
|
||||
and reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'}
|
||||
):
|
||||
sides.append('retry_inventory_preparation')
|
||||
sides.append('retry_onhand_preparation')
|
||||
# [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。
|
||||
if (
|
||||
code == 'manual_upload_handoff'
|
||||
@@ -547,8 +547,8 @@ def gate_side_recovery_actions(
|
||||
# [STEP] 行级库存源人工覆写(方案 3·放开):通知准备(Excel 生成前)与库存匹配阶段
|
||||
# 均允许用户把某行库存源覆写为任一已启用源后再重匹配;Excel 锁与源启用校验由执行器负责。
|
||||
# 已取代旧 D5 多文件冲突逐行选源(select_line_inventory_source,已下线)。
|
||||
if code in {'inventory_source_routing', 'inventory_preparation', 'inventory_matching'}:
|
||||
sides.append('override_line_inventory_source')
|
||||
if code in {'onhand_source_routing', 'onhand_preparation', 'onhand_matching'}:
|
||||
sides.append('override_line_onhand_source')
|
||||
return tuple(sides)
|
||||
|
||||
|
||||
@@ -582,7 +582,7 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'inventory_source_unavailable',
|
||||
'inventory_source_conflicted',
|
||||
'inventory_source_changed',
|
||||
'inventory_source_identity_mismatch',
|
||||
'onhand_source_identity_mismatch',
|
||||
'inventory_multi_file_conflict',
|
||||
'inventory_sku_not_found',
|
||||
'inventory_reservation_not_found',
|
||||
@@ -623,11 +623,11 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'task_creation_failed',
|
||||
'inventory_preparation_failed',
|
||||
'inventory_preparation_waiting',
|
||||
'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',
|
||||
@@ -693,18 +693,18 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'cross_source_conflict': 'field_conflict_resolution',
|
||||
'pdf_preferred_critical_conflict': 'field_conflict_resolution',
|
||||
'pdf_preferred': 'field_conflict_resolution',
|
||||
'no_inventory_source_candidates': 'inventory_source_routing',
|
||||
'require_manual_review': 'inventory_source_routing',
|
||||
'inventory_source_unavailable': 'inventory_source_routing',
|
||||
'inventory_source_conflicted': 'inventory_source_routing',
|
||||
'inventory_source_changed': 'inventory_source_routing',
|
||||
'inventory_source_identity_mismatch': 'inventory_source_routing',
|
||||
'inventory_multi_file_conflict': 'inventory_matching',
|
||||
'inventory_sku_not_found': 'inventory_matching',
|
||||
'inventory_reservation_not_found': 'inventory_matching',
|
||||
'inventory_warehouse_mismatch': 'inventory_matching',
|
||||
'inventory_required_column_missing': 'inventory_field_mapping',
|
||||
'inventory_column_ambiguous': 'inventory_field_mapping',
|
||||
'no_inventory_source_candidates': 'onhand_source_routing',
|
||||
'require_manual_review': 'onhand_source_routing',
|
||||
'inventory_source_unavailable': 'onhand_source_routing',
|
||||
'inventory_source_conflicted': 'onhand_source_routing',
|
||||
'inventory_source_changed': 'onhand_source_routing',
|
||||
'onhand_source_identity_mismatch': 'onhand_source_routing',
|
||||
'inventory_multi_file_conflict': 'onhand_matching',
|
||||
'inventory_sku_not_found': 'onhand_matching',
|
||||
'inventory_reservation_not_found': 'onhand_matching',
|
||||
'inventory_warehouse_mismatch': 'onhand_matching',
|
||||
'inventory_required_column_missing': 'onhand_field_mapping',
|
||||
'inventory_column_ambiguous': 'onhand_field_mapping',
|
||||
'excel_template_missing': 'excel_readiness',
|
||||
'excel_input_incomplete': 'excel_readiness',
|
||||
'artifact_validation_failed': 'artifact_generation',
|
||||
@@ -753,20 +753,20 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'run_cancelled': 'order_freeze_readiness',
|
||||
'pending_orders_present': 'order_freeze_readiness',
|
||||
'task_creation_failed': 'task_creation',
|
||||
'inventory_preparation_failed': 'inventory_preparation',
|
||||
'inventory_preparation_waiting': 'inventory_preparation',
|
||||
'inventory_rpa_queued': 'inventory_preparation',
|
||||
'inventory_rpa_timeout': 'inventory_preparation',
|
||||
'inventory_rpa_login_failed': 'inventory_preparation',
|
||||
'inventory_rpa_export_failed': 'inventory_preparation',
|
||||
'inventory_rpa_exhausted': 'inventory_preparation',
|
||||
'inventory_file_missing': 'inventory_preparation',
|
||||
'inventory_file_empty': 'inventory_preparation',
|
||||
'inventory_file_identity_mismatch': 'inventory_preparation',
|
||||
'inventory_mapping_required': 'inventory_field_mapping',
|
||||
'inventory_match_failed': 'inventory_matching',
|
||||
'inventory_insufficient': 'inventory_sufficiency',
|
||||
'inventory_shortage_review_required': 'inventory_sufficiency',
|
||||
'inventory_preparation_failed': 'onhand_preparation',
|
||||
'inventory_preparation_waiting': 'onhand_preparation',
|
||||
'onhand_rpa_queued': 'onhand_preparation',
|
||||
'onhand_rpa_timeout': 'onhand_preparation',
|
||||
'onhand_rpa_login_failed': 'onhand_preparation',
|
||||
'onhand_rpa_export_failed': 'onhand_preparation',
|
||||
'onhand_rpa_exhausted': 'onhand_preparation',
|
||||
'inventory_file_missing': 'onhand_preparation',
|
||||
'inventory_file_empty': 'onhand_preparation',
|
||||
'inventory_file_identity_mismatch': 'onhand_preparation',
|
||||
'inventory_mapping_required': 'onhand_field_mapping',
|
||||
'inventory_match_failed': 'onhand_matching',
|
||||
'inventory_insufficient': 'onhand_sufficiency',
|
||||
'inventory_shortage_review_required': 'onhand_sufficiency',
|
||||
'excel_not_ready': 'excel_readiness',
|
||||
'artifact_generation_failed': 'artifact_generation',
|
||||
'manual_upload_pending': 'manual_upload_handoff',
|
||||
@@ -884,16 +884,16 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool:
|
||||
|
||||
if recovery_plan_for_action(current_gate=code, action_code=action) is not None:
|
||||
return True
|
||||
if action == 'retry_inventory_matching' and code in {
|
||||
'inventory_preparation', 'inventory_matching', 'inventory_sufficiency',
|
||||
if action == 'retry_onhand_matching' and code in {
|
||||
'onhand_preparation', 'onhand_matching', 'onhand_sufficiency',
|
||||
}:
|
||||
return True
|
||||
if action == 'reload_inventory_result' and code == 'inventory_preparation':
|
||||
if action == 'reload_onhand_result' and code == 'onhand_preparation':
|
||||
return True
|
||||
# 人工覆写行级库存源(方案 3·放开):通知准备(取数失败/多候选)与匹配阶段(Excel 前)均可。
|
||||
# 已取代旧 D5 逐行选源(select_line_inventory_source,已下线)。
|
||||
if action == 'override_line_inventory_source' and code in {
|
||||
'inventory_source_routing', 'inventory_preparation', 'inventory_matching',
|
||||
if action == 'override_line_onhand_source' and code in {
|
||||
'onhand_source_routing', 'onhand_preparation', 'onhand_matching',
|
||||
}:
|
||||
return True
|
||||
navigation_owners = {
|
||||
@@ -904,8 +904,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool:
|
||||
'confirm_customer': {'customer_resolution'},
|
||||
'adjudicate_duplicate': {'duplicate_detection'},
|
||||
'resolve_field_conflicts': {'field_conflict_resolution'},
|
||||
'open_inventory_match_review': {'inventory_matching'},
|
||||
'open_shortage_review': {'inventory_sufficiency'},
|
||||
'open_onhand_match_review': {'onhand_matching'},
|
||||
'open_shortage_review': {'onhand_sufficiency'},
|
||||
'regenerate_manual_upload_todo': {'manual_upload_handoff'},
|
||||
}
|
||||
# 人工交接 Gate 可由用户显式重新发起 RPA;自动上传开关不影响该恢复入口。
|
||||
@@ -1153,17 +1153,17 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = {
|
||||
'inventory_source_unavailable': 'needs_human', # 候选源配置被禁用(需人工改路由)
|
||||
'inventory_source_conflicted': 'needs_human', # 路由规则冲突
|
||||
'inventory_source_changed': 'retryable_tech', # 配置漂移,可重跑规则
|
||||
'inventory_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认
|
||||
'onhand_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认
|
||||
'retry_with_latest_rules': 'retryable_tech',
|
||||
|
||||
# --- 库存准备 / RPA ---
|
||||
'inventory_preparation_failed': 'retryable_tech',
|
||||
'inventory_preparation_waiting': 'retryable_tech',
|
||||
'inventory_rpa_queued': 'retryable_tech',
|
||||
'inventory_rpa_timeout': 'retryable_tech',
|
||||
'inventory_rpa_login_failed': 'retryable_tech',
|
||||
'inventory_rpa_export_failed': 'retryable_tech',
|
||||
'inventory_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传
|
||||
'onhand_rpa_queued': 'retryable_tech',
|
||||
'onhand_rpa_timeout': 'retryable_tech',
|
||||
'onhand_rpa_login_failed': 'retryable_tech',
|
||||
'onhand_rpa_export_failed': 'retryable_tech',
|
||||
'onhand_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传
|
||||
'inventory_file_missing': 'retryable_tech',
|
||||
'inventory_file_empty': 'retryable_tech',
|
||||
'inventory_file_identity_mismatch': 'needs_human',
|
||||
@@ -1244,9 +1244,9 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = {
|
||||
|
||||
INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = (
|
||||
'order_freeze_readiness', # 订单 Snapshot 冻结(sub_stage=frozen)
|
||||
'inventory_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated)
|
||||
'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready)
|
||||
'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking)
|
||||
'onhand_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated)
|
||||
'onhand_preparation', # 多源快照准备(sub_stage=snapshots_ready)
|
||||
'onhand_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking)
|
||||
)
|
||||
|
||||
INVENTORY_SUB_STAGES: Final[frozenset[str]] = frozenset({
|
||||
@@ -1369,9 +1369,9 @@ def derive_position(*, gate_code: str | None, review_status: str | None) -> str
|
||||
'order_field_extraction': 'parse_review',
|
||||
'customer_resolution': 'customer_review',
|
||||
'reservation_validation': 'rsv_req',
|
||||
'inventory_preparation': 'inventory_pending',
|
||||
'inventory_matching': 'ready_to_match',
|
||||
'inventory_sufficiency': 'shortage_review',
|
||||
'onhand_preparation': 'inventory_pending',
|
||||
'onhand_matching': 'ready_to_match',
|
||||
'onhand_sufficiency': 'shortage_review',
|
||||
'order_freeze_readiness': 'order_freeze',
|
||||
'excel_readiness': 'ready_to_export',
|
||||
'artifact_generation': 'export_ready',
|
||||
@@ -1404,44 +1404,44 @@ def derive_todo_category(*, user_mode: str, position: str | None = None) -> str:
|
||||
# ============================================================
|
||||
|
||||
STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = {
|
||||
'override_line_inventory_source': {
|
||||
'override_line_onhand_source': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'line',
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'action_code': 'override_line_onhand_source',
|
||||
'invalidate': {
|
||||
'inventory_field_mapping', 'inventory_matching',
|
||||
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
'onhand_field_mapping', 'onhand_matching',
|
||||
'onhand_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reset_to': 'onhand_preparation',
|
||||
},
|
||||
'retry_inventory_preparation': {
|
||||
'retry_onhand_preparation': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'retry_inventory_preparation',
|
||||
'action_code': 'retry_onhand_preparation',
|
||||
'invalidate': {
|
||||
'inventory_field_mapping', 'inventory_matching',
|
||||
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
'onhand_field_mapping', 'onhand_matching',
|
||||
'onhand_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reset_to': 'onhand_preparation',
|
||||
},
|
||||
# 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。
|
||||
# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel,
|
||||
# 因此不重置回 inventory_preparation,也不作废上游 source/mapping。
|
||||
'retry_inventory_matching': {
|
||||
'retry_onhand_matching': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'action_code': 'retry_onhand_matching',
|
||||
'invalidate': {
|
||||
'inventory_matching', 'inventory_sufficiency',
|
||||
'onhand_matching', 'onhand_sufficiency',
|
||||
'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'invalidate_change_type': 'inventory_field_mapping_changed',
|
||||
'reset_to': 'inventory_matching',
|
||||
'reset_to': 'onhand_matching',
|
||||
},
|
||||
'reload_inventory_result': {
|
||||
'reload_onhand_result': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'reload_inventory_result',
|
||||
'action_code': 'reload_onhand_result',
|
||||
'invalidate': frozenset(),
|
||||
'reset_to': None,
|
||||
},
|
||||
|
||||
@@ -21,13 +21,13 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'customer_resolution',
|
||||
'duplicate_detection',
|
||||
'field_conflict_resolution',
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'order_freeze_readiness',
|
||||
'task_creation',
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_preparation',
|
||||
'onhand_field_mapping',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -36,8 +36,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'reservation_changed': (
|
||||
'duplicate_detection',
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -45,8 +45,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
),
|
||||
'part_number_changed': (
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -54,8 +54,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
),
|
||||
'quantity_changed': (
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -65,37 +65,37 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'duplicate_detection',
|
||||
'order_freeze_readiness',
|
||||
'task_creation',
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_preparation',
|
||||
'onhand_field_mapping',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_source_changed': (
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_preparation',
|
||||
'onhand_field_mapping',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_file_changed': (
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_field_mapping',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_field_mapping_changed': (
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -113,7 +113,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'task_creation',
|
||||
),
|
||||
'field_conflict_resolved': (
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'order_freeze_readiness',
|
||||
'task_creation',
|
||||
),
|
||||
@@ -125,15 +125,15 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'reservation_confirmed': (
|
||||
'duplicate_detection',
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'line_fulfillment_decision_changed': (
|
||||
'inventory_sufficiency',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'freight_upload_rpa',
|
||||
@@ -153,13 +153,13 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'field_conflict_resolution': ('duplicate_detection',),
|
||||
'task_creation': ('field_conflict_resolution',),
|
||||
'order_freeze_readiness': ('task_creation',),
|
||||
'inventory_source_routing': ('order_freeze_readiness',),
|
||||
'inventory_preparation': ('inventory_source_routing',),
|
||||
'inventory_field_mapping': ('inventory_preparation',),
|
||||
'inventory_matching': ('inventory_field_mapping',),
|
||||
'inventory_sufficiency': ('inventory_matching',),
|
||||
'onhand_source_routing': ('order_freeze_readiness',),
|
||||
'onhand_preparation': ('onhand_source_routing',),
|
||||
'onhand_field_mapping': ('onhand_preparation',),
|
||||
'onhand_matching': ('onhand_field_mapping',),
|
||||
'onhand_sufficiency': ('onhand_matching',),
|
||||
# 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。
|
||||
'excel_readiness': ('inventory_matching',),
|
||||
'excel_readiness': ('onhand_matching',),
|
||||
'artifact_generation': ('excel_readiness',),
|
||||
'freight_upload_rpa': ('artifact_generation',),
|
||||
'manual_upload_handoff': ('freight_upload_rpa',),
|
||||
@@ -217,5 +217,5 @@ def assert_process_gate_dependency_integrity() -> None:
|
||||
)
|
||||
# 仅重新生成 Excel 不得失效库存匹配。
|
||||
excel_only = set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only'])
|
||||
assert 'inventory_matching' not in excel_only
|
||||
assert 'onhand_matching' not in excel_only
|
||||
assert 'artifact_generation' in excel_only
|
||||
@@ -3,9 +3,9 @@ services/shipping_notice/process_gate_executor.py
|
||||
|
||||
用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。
|
||||
依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、
|
||||
inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、
|
||||
onhand_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、
|
||||
document_layout.lifecycle、process_gate_contract、process_gate_bridge、
|
||||
inventory_candidate_projection、recovery_invalidation_service。
|
||||
onhand_candidate_projection、recovery_invalidation_service。
|
||||
逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态;
|
||||
库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径;
|
||||
co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem;
|
||||
@@ -73,7 +73,7 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({
|
||||
'confirm_customer',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
'regenerate_manual_upload_todo',
|
||||
})
|
||||
@@ -81,8 +81,8 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({
|
||||
# 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。
|
||||
# poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。
|
||||
_FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_onhand_preparation',
|
||||
'retry_onhand_from_preparation',
|
||||
})
|
||||
|
||||
# 人工入口:前端应导航,不把业务状态改为 passed。
|
||||
@@ -94,7 +94,7 @@ _NAVIGATION_ACTIONS: frozenset[str] = frozenset({
|
||||
'confirm_customer',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
})
|
||||
|
||||
@@ -191,16 +191,16 @@ def _dispatch_action(
|
||||
'retry_customer_resolution': _handle_recheck_task_gates,
|
||||
'retry_duplicate_detection': _handle_recheck_task_gates,
|
||||
'retry_task_creation': _handle_retry_task_creation,
|
||||
'retry_inventory_preparation': _handle_retry_inventory_preparation,
|
||||
'reload_inventory_result': _handle_reload_inventory_result,
|
||||
'poll_inventory_preparation': _handle_retry_inventory_preparation,
|
||||
'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping,
|
||||
'retry_inventory_matching': _handle_retry_inventory_matching,
|
||||
'retry_inventory_from_preparation': _handle_retry_inventory_preparation,
|
||||
'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping,
|
||||
'retry_inventory_from_matching': _handle_retry_inventory_from_matching,
|
||||
'override_line_inventory_source': _handle_override_line_inventory_source,
|
||||
'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency,
|
||||
'retry_onhand_preparation': _handle_retry_inventory_preparation,
|
||||
'reload_onhand_result': _handle_reload_inventory_result,
|
||||
'poll_onhand_preparation': _handle_retry_inventory_preparation,
|
||||
'retry_onhand_field_mapping': _handle_retry_inventory_field_mapping,
|
||||
'retry_onhand_matching': _handle_retry_inventory_matching,
|
||||
'retry_onhand_from_preparation': _handle_retry_inventory_preparation,
|
||||
'retry_onhand_from_field_mapping': _handle_retry_inventory_from_field_mapping,
|
||||
'retry_onhand_from_matching': _handle_retry_inventory_from_matching,
|
||||
'override_line_onhand_source': _handle_override_line_inventory_source,
|
||||
'recheck_onhand_sufficiency': _handle_recheck_inventory_sufficiency,
|
||||
'recheck_excel_readiness': _handle_recheck_excel_readiness,
|
||||
'regenerate_excel_artifact': _handle_regenerate_excel,
|
||||
'poll_freight_upload_rpa': _handle_freight_upload_rpa,
|
||||
@@ -213,8 +213,8 @@ def _dispatch_action(
|
||||
'confirm_customer': _manual_open('confirm_customer', 'customer_resolution'),
|
||||
'adjudicate_duplicate': _manual_open('adjudicate_duplicate', 'duplicate_detection'),
|
||||
'resolve_field_conflicts': _manual_open('resolve_field_conflicts', 'field_conflict_resolution'),
|
||||
'open_inventory_match_review': _manual_open('open_inventory_match_review', 'inventory_matching'),
|
||||
'open_shortage_review': _manual_open('open_shortage_review', 'inventory_sufficiency'),
|
||||
'open_onhand_match_review': _manual_open('open_onhand_match_review', 'onhand_matching'),
|
||||
'open_shortage_review': _manual_open('open_shortage_review', 'onhand_sufficiency'),
|
||||
}
|
||||
handler = handlers.get(action_code)
|
||||
if handler is None:
|
||||
@@ -374,7 +374,7 @@ def _resolve_line_inventory_scope(
|
||||
由 snapshot_line_id / line_scope_key 解析行级库存作用域。
|
||||
|
||||
核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。
|
||||
Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。
|
||||
Gate 直调 ensure_onhand 时绕过 progress_workflow,必须在此收窄源范围。
|
||||
|
||||
Args:
|
||||
task: 当前 OT / 兼容 Notice owner。
|
||||
@@ -396,7 +396,7 @@ def _resolve_line_inventory_scope(
|
||||
return None
|
||||
|
||||
from app.models import ShippingOrderSnapshot
|
||||
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
|
||||
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
scoped_line = next(
|
||||
@@ -819,10 +819,10 @@ def _handle_retry_inventory_preparation(
|
||||
"""
|
||||
重试/轮询库存准备。
|
||||
|
||||
核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation →
|
||||
核心逻辑:按已有动作码映射 ensure_inventory mode(retry_onhand_preparation →
|
||||
retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto);
|
||||
若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄
|
||||
RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导
|
||||
RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory(阶段码 ensure_onhand)后按任务事实推导
|
||||
细粒度阻断码,再同步履约门禁。
|
||||
|
||||
Args:
|
||||
@@ -834,8 +834,8 @@ def _handle_retry_inventory_preparation(
|
||||
Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round
|
||||
from app.services.shipping_notice.onhand_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.onhand_recovery_service import create_inventory_preparation_round
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
inventory_preparation_reason_code,
|
||||
@@ -854,7 +854,7 @@ def _handle_retry_inventory_preparation(
|
||||
# [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。
|
||||
# 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。
|
||||
if task is not None:
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
get_active_candidate_lines,
|
||||
get_active_candidate_set,
|
||||
get_active_candidate_sources,
|
||||
@@ -874,26 +874,26 @@ def _handle_retry_inventory_preparation(
|
||||
'blocking_reason_code': 'inventory_source_routing_required',
|
||||
'effective_result_json': {'findings': [], 'routing_required': True},
|
||||
'output_snapshot': {
|
||||
'action_code': str(payload.get('action_code') or 'retry_inventory_preparation'),
|
||||
'action_code': str(payload.get('action_code') or 'retry_onhand_preparation'),
|
||||
'routing_required': True,
|
||||
},
|
||||
}
|
||||
if task is not None and payload.get('action_code') == 'poll_inventory_preparation':
|
||||
if task is not None and payload.get('action_code') == 'poll_onhand_preparation':
|
||||
# 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。
|
||||
# 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。
|
||||
from app.models import ShippingInventoryPreparationAttempt
|
||||
from app.models import ShippingOnhandPreparationAttempt
|
||||
|
||||
failed_preparation_query = ShippingInventoryPreparationAttempt.query.filter_by(
|
||||
failed_preparation_query = ShippingOnhandPreparationAttempt.query.filter_by(
|
||||
task_id=int(task.id),
|
||||
execution_id=int(execution.id),
|
||||
status='failed',
|
||||
)
|
||||
if execution.candidate_set_id is not None:
|
||||
failed_preparation_query = failed_preparation_query.filter(
|
||||
ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
|
||||
ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id)
|
||||
)
|
||||
failed_preparation = failed_preparation_query.order_by(
|
||||
ShippingInventoryPreparationAttempt.attempt_no.desc()
|
||||
ShippingOnhandPreparationAttempt.attempt_no.desc()
|
||||
).first()
|
||||
if failed_preparation is not None:
|
||||
prep_reason = inventory_preparation_reason_code(task)
|
||||
@@ -907,7 +907,7 @@ def _handle_retry_inventory_preparation(
|
||||
'poll_skipped_after_callback_failure': True,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'poll_inventory_preparation',
|
||||
'action_code': 'poll_onhand_preparation',
|
||||
'poll_skipped_after_callback_failure': True,
|
||||
},
|
||||
}
|
||||
@@ -925,7 +925,7 @@ def _handle_retry_inventory_preparation(
|
||||
else payload.get('snapshot_line_id')
|
||||
),
|
||||
)
|
||||
if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
|
||||
if task is not None and payload.get('action_code') != 'poll_onhand_preparation' and not is_initial_auto_dispatch:
|
||||
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
|
||||
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
|
||||
if not task.order_snapshot_id:
|
||||
@@ -948,11 +948,11 @@ def _handle_retry_inventory_preparation(
|
||||
# override_line_inventory_source)。
|
||||
# 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope
|
||||
# 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。
|
||||
if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
|
||||
if str(payload.get('action_code') or '').strip() == 'retry_onhand_preparation':
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
|
||||
if latest_export_artifact(task) is None:
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import (
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import (
|
||||
refresh_candidates_from_current_routing,
|
||||
refresh_line_candidates_from_current_routing,
|
||||
)
|
||||
@@ -975,9 +975,9 @@ def _handle_retry_inventory_preparation(
|
||||
if refreshed_scope is not None:
|
||||
line_scope = refreshed_scope
|
||||
if payload.get('action_code') in {
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_inventory_from_field_mapping',
|
||||
'retry_onhand_preparation',
|
||||
'retry_onhand_from_preparation',
|
||||
'retry_onhand_from_field_mapping',
|
||||
}:
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
@@ -991,7 +991,7 @@ def _handle_retry_inventory_preparation(
|
||||
task=task,
|
||||
execution_id=int(execution.id),
|
||||
recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None,
|
||||
action_code=str(payload.get('action_code') or 'retry_inventory_preparation'),
|
||||
action_code=str(payload.get('action_code') or 'retry_onhand_preparation'),
|
||||
operation_id=str(payload.get('operation_id') or '').strip() or None,
|
||||
gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None,
|
||||
)
|
||||
@@ -1016,13 +1016,13 @@ def _handle_retry_inventory_preparation(
|
||||
inventory_payload['mode'] = 'auto'
|
||||
else:
|
||||
inventory_payload['mode'] = 'retry_rpa'
|
||||
if action_code == 'poll_inventory_preparation':
|
||||
if action_code == 'poll_onhand_preparation':
|
||||
# [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试,
|
||||
# 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。
|
||||
inventory_payload['allow_auto_retry'] = False
|
||||
response = ensure_inventory(inventory_payload)
|
||||
if preparation_round is not None:
|
||||
from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round
|
||||
from app.services.shipping_notice.onhand_recovery_service import sync_inventory_preparation_round
|
||||
|
||||
rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {}
|
||||
sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result)
|
||||
@@ -1032,7 +1032,7 @@ def _handle_retry_inventory_preparation(
|
||||
else 'inventory_preparation_failed'
|
||||
)
|
||||
outcome = _tool_outcome(
|
||||
action_code='retry_inventory_preparation',
|
||||
action_code='retry_onhand_preparation',
|
||||
response=response,
|
||||
# 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成;
|
||||
# Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分
|
||||
@@ -1057,7 +1057,7 @@ def _handle_override_line_inventory_source(
|
||||
校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写;
|
||||
覆写后把该行候选钉为所选源。人工指定即定论:不再重跑路由规则。
|
||||
- 当前在 routing:passed 后由 complete → enqueue 首投库存准备(按冻结源取数)。
|
||||
- 当前在准备/匹配:定向回 inventory_preparation,mode=auto(有快照复用,无则 RPA)。
|
||||
- 当前在准备/匹配:定向回 onhand_preparation,mode=auto(有快照复用,无则 RPA)。
|
||||
|
||||
Args:
|
||||
execution: 门禁执行上下文。
|
||||
@@ -1069,12 +1069,12 @@ def _handle_override_line_inventory_source(
|
||||
"""
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import (
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import (
|
||||
freeze_manual_line_source_selection,
|
||||
)
|
||||
|
||||
@@ -1123,7 +1123,7 @@ def _handle_override_line_inventory_source(
|
||||
event_type='review_line_source_overridden',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=str(task.task_no),
|
||||
action='override_line_inventory_source',
|
||||
action='override_line_onhand_source',
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id,
|
||||
task_no=task.task_no,
|
||||
@@ -1139,7 +1139,7 @@ def _handle_override_line_inventory_source(
|
||||
'selected_line_no': line_no, 'all_lines_selected': False,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'action_code': 'override_line_onhand_source',
|
||||
'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'all_lines_selected': False,
|
||||
},
|
||||
@@ -1148,7 +1148,7 @@ def _handle_override_line_inventory_source(
|
||||
# 人工指定源即定论:冻结候选后不再重跑路由规则。routing Gate 以 passed 收口,
|
||||
# complete_gate_attempt → _enqueue_auto_progress_after_gate_pass 首投 inventory_preparation
|
||||
#(按已冻结源取数:有 ready 快照复用,否则再 RPA)。禁止在本 Attempt 内递归推进。
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
if gate.gate_code == 'onhand_source_routing':
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {
|
||||
@@ -1156,7 +1156,7 @@ def _handle_override_line_inventory_source(
|
||||
'selected_line_no': line_no, 'all_lines_selected': True,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'action_code': 'override_line_onhand_source',
|
||||
'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'all_lines_selected': True,
|
||||
},
|
||||
@@ -1172,7 +1172,7 @@ def _handle_override_line_inventory_source(
|
||||
task.task_no,
|
||||
trigger='manual_override_source',
|
||||
operator_id=actor_id,
|
||||
resume_gate_code='inventory_preparation',
|
||||
resume_gate_code='onhand_preparation',
|
||||
inventory_mode='auto',
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
@@ -1181,7 +1181,7 @@ def _handle_override_line_inventory_source(
|
||||
# RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。
|
||||
db.session.flush()
|
||||
preparation_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).first()
|
||||
gate_status = str(getattr(preparation_gate, 'status', '') or '').strip().lower()
|
||||
reason_code = str(getattr(preparation_gate, 'blocking_reason_code', '') or '').strip() or None
|
||||
@@ -1201,7 +1201,7 @@ def _handle_override_line_inventory_source(
|
||||
'inventory_preparation_status': gate_status or 'blocked_retryable',
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'action_code': 'override_line_onhand_source',
|
||||
'inventory_preparation_status': gate_status or 'blocked_retryable',
|
||||
},
|
||||
}
|
||||
@@ -1216,14 +1216,14 @@ def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool:
|
||||
"""
|
||||
任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。
|
||||
|
||||
【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。
|
||||
【AI 触发时机】:onhand_preparation Gate 执行前判断是否需要补做路由裁决。
|
||||
|
||||
核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结,
|
||||
没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。
|
||||
"""
|
||||
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
|
||||
|
||||
return bool(task_frozen_inventory_source_codes(task))
|
||||
return bool(task_frozen_onhand_source_codes(task))
|
||||
|
||||
|
||||
def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None:
|
||||
@@ -1247,8 +1247,8 @@ def _handle_reload_inventory_result(
|
||||
RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
inventory_preparation_reason_code,
|
||||
sync_fulfillment_gates_from_task,
|
||||
@@ -1260,7 +1260,7 @@ def _handle_reload_inventory_result(
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_preparation_failed',
|
||||
'effective_result_json': {'findings': []},
|
||||
'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False},
|
||||
'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False},
|
||||
}
|
||||
response = _try_reuse_inventory_snapshot(
|
||||
task,
|
||||
@@ -1280,7 +1280,7 @@ def _handle_reload_inventory_result(
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': inventory_preparation_reason_code(task),
|
||||
'effective_result_json': {'findings': [], 'snapshot_found': False},
|
||||
'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False},
|
||||
'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False},
|
||||
}
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
@@ -1288,7 +1288,7 @@ def _handle_reload_inventory_result(
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
return _tool_outcome(
|
||||
action_code='reload_inventory_result',
|
||||
action_code='reload_onhand_result',
|
||||
response=response,
|
||||
blocking_reason_code=inventory_preparation_reason_code(task),
|
||||
)
|
||||
@@ -1304,7 +1304,7 @@ def _handle_retry_inventory_field_mapping(
|
||||
重试库存字段映射:检查活跃库存文件 mapping_confirmed / 已解析行,不重跑库存准备。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
task = _resolve_order_task(execution)
|
||||
@@ -1313,10 +1313,10 @@ def _handle_retry_inventory_field_mapping(
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_mapping_required',
|
||||
'effective_result_json': {'findings': []},
|
||||
'output_snapshot': {'action_code': 'retry_inventory_field_mapping'},
|
||||
'output_snapshot': {'action_code': 'retry_onhand_field_mapping'},
|
||||
}
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task
|
||||
|
||||
mapped = bool(
|
||||
inv_file is not None
|
||||
@@ -1325,7 +1325,7 @@ def _handle_retry_inventory_field_mapping(
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_field_mapping',
|
||||
gate_code='onhand_field_mapping',
|
||||
passed=mapped,
|
||||
# 映射来自已发布库存模板,缺失或不确定只能由系统重试/配置治理解决,
|
||||
# 不能把技术映射确认伪装为人工业务操作。
|
||||
@@ -1345,13 +1345,13 @@ def _handle_retry_inventory_field_mapping(
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {'findings': [], 'mapping_confirmed': True},
|
||||
'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': True},
|
||||
'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': True},
|
||||
}
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_mapping_required',
|
||||
'effective_result_json': {'findings': []},
|
||||
'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': False},
|
||||
'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': False},
|
||||
}
|
||||
|
||||
|
||||
@@ -1364,14 +1364,14 @@ def _handle_retry_inventory_from_field_mapping(
|
||||
"""
|
||||
从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。
|
||||
|
||||
Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt,
|
||||
Follow-up P1:映射 Attempt 应收口后仅 enqueue ``onhand_matching`` Attempt,
|
||||
禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。
|
||||
"""
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
|
||||
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code='retry_inventory_from_field_mapping',
|
||||
action_code='retry_onhand_from_field_mapping',
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
@@ -1401,11 +1401,11 @@ def _handle_retry_inventory_matching(
|
||||
|
||||
核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和
|
||||
“匹配成功但库存不足”。匹配成功但库存不足时,前置的
|
||||
``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency;
|
||||
当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的
|
||||
``sync_fulfillment_gates_from_task`` 已将缺口写入 onhand_sufficiency;
|
||||
当前 onhand_matching Attempt 必须以 passed 收口,否则会覆盖正确的
|
||||
满足性 Gate 归属并再次显示“进入库存匹配处理”。
|
||||
行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退
|
||||
ensure_inventory 时携带该行 source_codes。
|
||||
ensure_onhand 时携带该行 source_codes。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
@@ -1438,7 +1438,7 @@ def _handle_retry_inventory_matching(
|
||||
sufficient = bool(task is not None and match_completed(task))
|
||||
match_status = 'fulfillable' if sufficient else ('unfulfillable' if match_complete else '')
|
||||
has_shortage = match_complete and not sufficient
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
shortage = [
|
||||
row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values()
|
||||
@@ -1455,7 +1455,7 @@ def _handle_retry_inventory_matching(
|
||||
'shortage': shortage,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'action_code': 'retry_onhand_matching',
|
||||
'tool_status': 'passed',
|
||||
'business_result': 'fulfillable',
|
||||
},
|
||||
@@ -1473,13 +1473,13 @@ def _handle_retry_inventory_matching(
|
||||
'shortage': shortage,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'action_code': 'retry_onhand_matching',
|
||||
'tool_status': 'needs_human',
|
||||
'business_result': 'inventory_shortage',
|
||||
},
|
||||
}
|
||||
outcome = _tool_outcome(
|
||||
action_code='retry_inventory_matching',
|
||||
action_code='retry_onhand_matching',
|
||||
response=response,
|
||||
blocking_reason_code='inventory_match_failed',
|
||||
invalidate_change_type=None,
|
||||
@@ -1498,7 +1498,7 @@ def _handle_retry_inventory_from_matching(
|
||||
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code='retry_inventory_from_matching',
|
||||
action_code='retry_onhand_from_matching',
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
)
|
||||
@@ -1529,11 +1529,11 @@ def _handle_recheck_inventory_sufficiency(
|
||||
'blocking_reason_code': 'inventory_insufficient',
|
||||
'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'},
|
||||
'effective_result_json': {'findings': []},
|
||||
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'},
|
||||
'output_snapshot': {'action_code': 'recheck_onhand_sufficiency'},
|
||||
}
|
||||
# [BE-满足性复盘] 复核先按当前放行/匹配事实重算任务级履约态,避免"Gate 认为满足、
|
||||
# 任务却仍标 unfulfillable/shortage"的旧状态残留。仅在确有匹配行时重算(空事实不误标缺货)。
|
||||
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
|
||||
from app.models import ShippingNoticeLineOnhandMatch as _MatchRow
|
||||
|
||||
if getattr(task, 'id', None) is not None and (
|
||||
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None
|
||||
@@ -1542,16 +1542,16 @@ def _handle_recheck_inventory_sufficiency(
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
|
||||
sufficient = match_completed(task)
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingNoticeLineOnhandMatch
|
||||
shortage = [
|
||||
{'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty}
|
||||
for row in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
for row in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'}
|
||||
]
|
||||
match_status = 'fulfillable' if sufficient else 'unfulfillable'
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_sufficiency',
|
||||
gate_code='onhand_sufficiency',
|
||||
passed=sufficient,
|
||||
outcome=None if sufficient else 'blocked_manual',
|
||||
effective_result={
|
||||
@@ -1569,14 +1569,14 @@ def _handle_recheck_inventory_sufficiency(
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {'findings': [], 'match_status': match_status},
|
||||
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True},
|
||||
'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': True},
|
||||
}
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_insufficient',
|
||||
'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'},
|
||||
'effective_result_json': {'findings': [], 'shortage': shortage},
|
||||
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': False},
|
||||
'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': False},
|
||||
}
|
||||
|
||||
|
||||
@@ -1786,7 +1786,7 @@ def _handle_inventory_reroute(
|
||||
from app.models import ShippingOrderReviewCase
|
||||
from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing
|
||||
|
||||
if gate.gate_code != 'inventory_source_routing':
|
||||
if gate.gate_code != 'onhand_source_routing':
|
||||
raise ValidationError(
|
||||
'Action does not belong to this gate',
|
||||
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
|
||||
|
||||
@@ -75,7 +75,7 @@ def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int:
|
||||
其执行入口会再次读取 Gate 并自行停止。
|
||||
|
||||
Args:
|
||||
gate_id: inventory_preparation Gate 主键。
|
||||
gate_id: onhand_preparation Gate 主键。
|
||||
reason: 取消原因,写入 Job message 供审计排查。
|
||||
|
||||
Returns:
|
||||
@@ -238,13 +238,13 @@ def schedule_waiting_external_poll(
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation' and execution.task_id:
|
||||
if str(gate.gate_code or '').strip() == 'onhand_preparation' and execution.task_id:
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
from app.models import ShippingOrderTask
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
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
|
||||
|
||||
has_inventory_lines = bool(task is not None and has_ready_inventory_file_for_task(task))
|
||||
if task is not None and has_inventory_lines:
|
||||
@@ -257,8 +257,8 @@ def schedule_waiting_external_poll(
|
||||
# 外部轮询超时是新的、可恢复的业务事实;不能保留原来的
|
||||
# inventory_rpa_queued,否则页面会同时显示“等待外部”和“人工处理”。
|
||||
timeout_reason = (
|
||||
'inventory_rpa_timeout'
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation'
|
||||
'onhand_rpa_timeout'
|
||||
if str(gate.gate_code or '').strip() == 'onhand_preparation'
|
||||
else (gate.blocking_reason_code or 'gate_invalidated')
|
||||
)
|
||||
timeout_action = primary_next_action_for_gate(
|
||||
@@ -314,11 +314,11 @@ def schedule_waiting_external_poll(
|
||||
# (例如从 inventory_matching 回到 inventory_preparation)完成后,原 Gate
|
||||
# 可能短暂保留 waiting_external,但不能把准备阶段的轮询动作投递到该原 Gate;
|
||||
# 否则 executor 的归属校验会把过期 poll 误记为技术失败。
|
||||
if not action and str(gate.gate_code or '').strip() == 'inventory_preparation':
|
||||
action = 'poll_inventory_preparation'
|
||||
if not action and str(gate.gate_code or '').strip() == 'onhand_preparation':
|
||||
action = 'poll_onhand_preparation'
|
||||
if (
|
||||
str(gate.gate_code or '').strip() != 'inventory_preparation'
|
||||
and str(action or '').strip() == 'poll_inventory_preparation'
|
||||
str(gate.gate_code or '').strip() != 'onhand_preparation'
|
||||
and str(action or '').strip() == 'poll_onhand_preparation'
|
||||
):
|
||||
_LOGGER.info(
|
||||
'skip stale inventory-preparation poll: gate_id=%s gate_code=%s',
|
||||
@@ -344,7 +344,7 @@ def schedule_waiting_external_poll(
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation':
|
||||
if str(gate.gate_code or '').strip() == 'onhand_preparation':
|
||||
poll_count = int(effective.get('poll_count') or 0) + 1
|
||||
effective['poll_count'] = poll_count
|
||||
gate.effective_result_json = effective
|
||||
@@ -391,7 +391,7 @@ def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]:
|
||||
outcome = _handle_retry_inventory_preparation(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload={'action_code': 'poll_inventory_preparation'},
|
||||
payload={'action_code': 'poll_onhand_preparation'},
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.refresh(gate)
|
||||
|
||||
@@ -49,7 +49,7 @@ _PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: frozenset[str] = frozenset({
|
||||
'confirm_customer',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
})
|
||||
|
||||
@@ -63,7 +63,7 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = {
|
||||
'confirm_customer': 'draft',
|
||||
'adjudicate_duplicate': 'draft',
|
||||
'resolve_field_conflicts': 'evidence',
|
||||
'open_inventory_match_review': 'draft',
|
||||
'open_onhand_match_review': 'draft',
|
||||
'open_shortage_review': 'draft',
|
||||
}
|
||||
|
||||
@@ -134,8 +134,8 @@ def _resolve_recovery_next_action(
|
||||
"""
|
||||
单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。
|
||||
|
||||
[STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配,
|
||||
无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
|
||||
[STEP 1] 库存 RPA 超时/耗尽下发 ``retry_onhand_matching``(优先复用已有快照重匹配,
|
||||
无快照则回退 RPA);其他库存准备失败下发 ``retry_onhand_preparation``,由用户明确重新触发 RPA。
|
||||
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
|
||||
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
|
||||
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
|
||||
@@ -148,27 +148,27 @@ def _resolve_recovery_next_action(
|
||||
has_formal_task = bool(execution and getattr(execution, 'task_id', None))
|
||||
|
||||
# [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。
|
||||
if blocking_gate_code == 'inventory_preparation':
|
||||
if blocking_gate_code == 'onhand_preparation':
|
||||
inventory_action = inventory_preparation_primary_action(status, normalized_reason)
|
||||
if inventory_action:
|
||||
return inventory_action, False
|
||||
|
||||
# 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker,
|
||||
# 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。
|
||||
if blocking_gate_code == 'inventory_matching' and (
|
||||
if blocking_gate_code == 'onhand_matching' and (
|
||||
has_formal_task or status == 'blocked_retryable'
|
||||
):
|
||||
return 'retry_inventory_matching', False
|
||||
return 'retry_onhand_matching', False
|
||||
|
||||
# 库存不足只阻断履约决策,不能把已经确认的活动 Excel 误判为库存源失效。
|
||||
# 因此默认复用该快照执行重匹配;用户若明确选择重新获取库存,再由 RecoveryPlan
|
||||
# 回到 inventory_preparation 强制触发 RPA。
|
||||
if (
|
||||
blocking_gate_code == 'inventory_sufficiency'
|
||||
blocking_gate_code == 'onhand_sufficiency'
|
||||
and has_formal_task
|
||||
and _has_confirmed_inventory_for_matching(execution)
|
||||
):
|
||||
return 'retry_inventory_matching', False
|
||||
return 'retry_onhand_matching', False
|
||||
|
||||
# [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。
|
||||
if (
|
||||
@@ -203,15 +203,15 @@ def _resolve_recovery_next_action(
|
||||
# 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。
|
||||
if not next_action:
|
||||
recovery_targets = full.get('recovery_targets') or []
|
||||
if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task:
|
||||
next_action = 'open_inventory_match_review'
|
||||
if recovery_targets and blocking_gate_code == 'onhand_matching' and not has_formal_task:
|
||||
next_action = 'open_onhand_match_review'
|
||||
technical_auto_only = False
|
||||
elif recovery_targets and blocking_gate_code == 'inventory_sufficiency':
|
||||
elif recovery_targets and blocking_gate_code == 'onhand_sufficiency':
|
||||
next_action = 'open_shortage_review'
|
||||
technical_auto_only = False
|
||||
# 库存准备/匹配/货代上传 RPA 在 blocked_retryable 时仍允许业务用户恢复。
|
||||
if not next_action and blocking_gate_code in {
|
||||
'inventory_preparation', 'inventory_matching', 'freight_upload_rpa',
|
||||
'onhand_preparation', 'onhand_matching', 'freight_upload_rpa',
|
||||
}:
|
||||
candidate = _projection_primary_next_action(
|
||||
gate_code=blocking_gate_code, status=status,
|
||||
@@ -531,7 +531,7 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -
|
||||
"""判断正式任务是否已有可复用、未失效的已确认库存快照。"""
|
||||
if not execution.task_id:
|
||||
return False
|
||||
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 = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
return bool(task is not None and has_ready_inventory_file_for_task(task))
|
||||
@@ -573,12 +573,12 @@ def _ensure_editable_row_source_actions(
|
||||
if not _row_source_editable(execution):
|
||||
return
|
||||
code = str(gate_code or '').strip().lower()
|
||||
if code not in {'inventory_preparation', 'inventory_matching'}:
|
||||
if code not in {'onhand_preparation', 'onhand_matching'}:
|
||||
return
|
||||
# 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口,
|
||||
# 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。
|
||||
# retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。
|
||||
for side in ('override_line_inventory_source',):
|
||||
for side in ('override_line_onhand_source',):
|
||||
if side not in allowed_actions and is_business_user_action(side):
|
||||
allowed_actions.append(side)
|
||||
|
||||
@@ -630,12 +630,12 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
blocking = None
|
||||
if (
|
||||
isinstance(current, dict)
|
||||
and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching'
|
||||
and str(current.get('gate_code') or '').strip().lower() == 'onhand_matching'
|
||||
and str(current.get('status') or '').strip().lower() == 'pending'
|
||||
and _has_confirmed_inventory_for_matching(execution)
|
||||
):
|
||||
# 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。
|
||||
current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'}
|
||||
current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_matching'}
|
||||
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
|
||||
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
|
||||
}:
|
||||
@@ -686,23 +686,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
action_items: list[dict[str, str]] = []
|
||||
is_formal_inventory_matching = bool(
|
||||
getattr(execution, 'task_id', None)
|
||||
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching'
|
||||
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_matching'
|
||||
)
|
||||
is_formal_inventory_sufficiency = bool(
|
||||
getattr(execution, 'task_id', None)
|
||||
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_sufficiency'
|
||||
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_sufficiency'
|
||||
)
|
||||
recovery_targets = full.get('recovery_targets') or []
|
||||
if is_formal_inventory_matching:
|
||||
recovery_targets = [
|
||||
target for target in recovery_targets
|
||||
if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation'
|
||||
if str(target.get('action_code') or '').strip() == 'retry_onhand_from_preparation'
|
||||
]
|
||||
elif is_formal_inventory_sufficiency:
|
||||
# Gate 16 对用户只公开稳定动作码:重匹配复用当前快照;重新获取库存才回到 RPA。
|
||||
recovery_targets = [
|
||||
target for target in recovery_targets
|
||||
if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation'
|
||||
if str(target.get('action_code') or '').strip() == 'retry_onhand_preparation'
|
||||
]
|
||||
# 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。
|
||||
recovery_targets = [
|
||||
|
||||
@@ -122,21 +122,21 @@ def _primary_recovery_action(
|
||||
*, execution: ShippingProcessExecution, gate: ShippingProcessGate,
|
||||
) -> str | None:
|
||||
"""按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。"""
|
||||
if gate.gate_code == 'inventory_preparation':
|
||||
if gate.gate_code == 'onhand_preparation':
|
||||
return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code)
|
||||
# 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。
|
||||
if gate.gate_code == 'inventory_matching' and execution.task_id:
|
||||
return 'retry_inventory_matching'
|
||||
if gate.gate_code == 'inventory_sufficiency' and execution.task_id:
|
||||
if gate.gate_code == 'onhand_matching' and execution.task_id:
|
||||
return 'retry_onhand_matching'
|
||||
if gate.gate_code == 'onhand_sufficiency' and execution.task_id:
|
||||
from app.models import ShippingOrderTask
|
||||
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 = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
if (
|
||||
task is not None
|
||||
and has_ready_inventory_file_for_task(task)
|
||||
):
|
||||
return 'retry_inventory_matching'
|
||||
return 'retry_onhand_matching'
|
||||
return gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status=gate.status,
|
||||
)
|
||||
@@ -196,6 +196,7 @@ def request_gate_action(
|
||||
核心逻辑:校验 action 属于契约且与当前门禁主要动作一致(或为同门禁允许的附属动作);
|
||||
创建 queued Attempt 后,同步动作立即 execute_queued_attempt,异步动作入队 Gate Job。
|
||||
客户端禁止提交起始阶段/目标状态/Worker 名。
|
||||
retry_onhand_from_* 打在错误 Gate 上时返回 SHIPPING.RECOVERY_TARGET_INVALID。
|
||||
|
||||
Args:
|
||||
execution_no / gate_code: 定位目标。
|
||||
@@ -246,7 +247,7 @@ def request_gate_action(
|
||||
# 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的
|
||||
# RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。
|
||||
recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action)
|
||||
if action.startswith('retry_inventory_from_') and recovery_definition is None:
|
||||
if action.startswith('retry_onhand_from_') and recovery_definition is None:
|
||||
raise ValidationError(
|
||||
'Recovery target is not allowed for current gate',
|
||||
code='SHIPPING.RECOVERY_TARGET_INVALID',
|
||||
@@ -310,14 +311,14 @@ def request_gate_action(
|
||||
# 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑),
|
||||
# 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。
|
||||
if stage_exempt:
|
||||
if action == 'retry_inventory_matching':
|
||||
if action == 'retry_onhand_matching':
|
||||
result = execute_stage_capability_rematch(
|
||||
execution=execution,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
elif action == 'override_line_inventory_source':
|
||||
elif action == 'override_line_onhand_source':
|
||||
# [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用
|
||||
# execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」
|
||||
# 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。
|
||||
|
||||
@@ -953,10 +953,10 @@ def _abort_active_attempt_as_superseded(
|
||||
"""把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。
|
||||
|
||||
触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、
|
||||
且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。
|
||||
且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_onhand_source)。
|
||||
仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方
|
||||
常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败
|
||||
覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。
|
||||
覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / onhand_matching 曾因此永卡失败态)。
|
||||
"""
|
||||
now = _utc_now()
|
||||
active_attempt.status = 'superseded'
|
||||
@@ -1090,8 +1090,8 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
"""门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。
|
||||
|
||||
核心逻辑:刷新指针后对「当前未通过 Gate」入队唯一 Attempt/Job。典型场景:
|
||||
人工指定库存源使 ``inventory_source_routing`` passed 后,下一道仍是
|
||||
``pending`` 且 ``next_action_code`` 为空的 ``inventory_preparation``——必须在此
|
||||
人工指定库存源使 ``onhand_source_routing`` passed 后,下一道仍是
|
||||
``pending`` 且 ``next_action_code`` 为空的 ``onhand_preparation``——必须在此
|
||||
补种首投动作并入队,按已冻结源取数,禁止静默 return 导致永久「库存文件未准备」。
|
||||
"""
|
||||
try:
|
||||
@@ -1154,8 +1154,8 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
# 初次进入库存准备也使用 retry_inventory_preparation 执行器;仅当还未创建
|
||||
# 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试,
|
||||
# 不能由 AutoProgress 无限重放。
|
||||
if next_gate.next_action_code == 'retry_inventory_preparation':
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
if next_gate.next_action_code == 'retry_onhand_preparation':
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
|
||||
from app.models import ShippingOrderTask
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
@@ -1164,7 +1164,7 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
return
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip()
|
||||
existing = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter_by(task_no=task_no)
|
||||
.first()
|
||||
if task_no else None
|
||||
@@ -1173,7 +1173,7 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
return
|
||||
if (
|
||||
(
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
next_gate.next_action_code in {'retry_onhand_matching'}
|
||||
and not _auto_match_enabled()
|
||||
)
|
||||
or (
|
||||
@@ -1312,8 +1312,8 @@ def sync_gate_from_business_result(
|
||||
|
||||
核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。
|
||||
已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。
|
||||
已有活动 Attempt 时:仅 auto poll_inventory_preparation 可提前收口;
|
||||
其余(含库存就绪的 retry_inventory_preparation)留给外层 Attempt 统一 complete。
|
||||
已有活动 Attempt 时:仅 auto poll_onhand_preparation 可提前收口;
|
||||
其余(含库存就绪的 retry_onhand_preparation)留给外层 Attempt 统一 complete。
|
||||
|
||||
Args:
|
||||
invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。
|
||||
@@ -1358,7 +1358,7 @@ def sync_gate_from_business_result(
|
||||
)
|
||||
is_auto_poll = (
|
||||
active_attempt.trigger_type == 'auto'
|
||||
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
|
||||
and str(snapshot.get('action_code') or '').strip() == 'poll_onhand_preparation'
|
||||
)
|
||||
if is_auto_poll and passed:
|
||||
return complete_gate_attempt(
|
||||
@@ -1378,7 +1378,7 @@ def sync_gate_from_business_result(
|
||||
is_conflicting_user_line_action = (
|
||||
active_attempt.trigger_type in {'user_manual', 'user_retry'}
|
||||
and str(snapshot.get('action_code') or '').strip() in {
|
||||
'override_line_inventory_source',
|
||||
'override_line_onhand_source',
|
||||
}
|
||||
)
|
||||
if is_conflicting_user_line_action and passed:
|
||||
@@ -1430,7 +1430,7 @@ def sync_gate_from_business_result(
|
||||
'blocked_manual' if blocking_reason_code else 'blocked_retryable'
|
||||
)
|
||||
resolved_invalidate = invalidate_change_type
|
||||
if resolved_invalidate is None and passed and gate_code == 'inventory_source_routing':
|
||||
if resolved_invalidate is None and passed and gate_code == 'onhand_source_routing':
|
||||
resolved_invalidate = 'inventory_source_changed'
|
||||
return complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
@@ -1475,7 +1475,7 @@ def execute_stage_capability(
|
||||
|
||||
核心步骤:
|
||||
[STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate
|
||||
时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。
|
||||
时才作废;如 reload_onhand_result 声明为空集合则跳过,直接重读)。
|
||||
[STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。
|
||||
[STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定
|
||||
以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False
|
||||
@@ -1522,7 +1522,7 @@ def execute_stage_capability(
|
||||
# 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate;
|
||||
# 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。
|
||||
resume_gate_code=str(reset_to or '').strip() or None,
|
||||
inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto',
|
||||
inventory_mode='retry_rpa' if reset_to == 'onhand_preparation' else 'auto',
|
||||
line_scope_key=str(line_scope_key).strip() or None,
|
||||
)
|
||||
# run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常;
|
||||
@@ -1561,7 +1561,7 @@ def execute_stage_capability_rematch(
|
||||
【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成)
|
||||
时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处
|
||||
保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经
|
||||
inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel),
|
||||
onhand_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel),
|
||||
避免错误重抓 RPA 或重做字段映射。
|
||||
|
||||
Args:
|
||||
@@ -1584,27 +1584,27 @@ def execute_stage_capability_rematch(
|
||||
))
|
||||
match_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code='inventory_matching')
|
||||
.filter_by(execution_id=int(execution.id), gate_code='onhand_matching')
|
||||
.first()
|
||||
)
|
||||
if match_gate is None:
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reset_to': 'onhand_matching',
|
||||
'reran': False,
|
||||
'reran_reason': 'inventory_matching_gate_missing',
|
||||
}
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
trigger_type='user_retry',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
expected_gate_version=None,
|
||||
input_snapshot={
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'action_code': 'retry_onhand_matching',
|
||||
'payload': {
|
||||
'actor_user_id': actor_id,
|
||||
'idempotency_key': str(idempotency_key or ''),
|
||||
@@ -1619,7 +1619,7 @@ def execute_stage_capability_rematch(
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reset_to': 'onhand_matching',
|
||||
'reran': False,
|
||||
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
|
||||
}
|
||||
@@ -1628,7 +1628,7 @@ def execute_stage_capability_rematch(
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reset_to': 'onhand_matching',
|
||||
'reran': reran,
|
||||
'gate_status': updated_gate.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
@@ -1647,13 +1647,13 @@ def execute_stage_capability_override_source(
|
||||
"""执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。
|
||||
|
||||
【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交
|
||||
override_line_inventory_source)时由 request_gate_action 调用。
|
||||
override_line_onhand_source)时由 request_gate_action 调用。
|
||||
|
||||
关键差异 / root cause 说明:
|
||||
- `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` /
|
||||
- `override_line_onhand_source` 是「行级」动作,必须携带用户选定的 ``line_no`` /
|
||||
``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个
|
||||
关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。
|
||||
- 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义,
|
||||
- 本函数保留通用能力「作废下游 + 重置回 onhand_preparation + 幂等重跑」的语义,
|
||||
但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到
|
||||
CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress
|
||||
按新候选重取/匹配库存,从而让 RPA 正常触发。
|
||||
@@ -1678,10 +1678,10 @@ def execute_stage_capability_override_source(
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
# 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。
|
||||
exclude_gate_codes={'inventory_preparation'} - {''},
|
||||
exclude_gate_codes={'onhand_preparation'} - {''},
|
||||
))
|
||||
# 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
# 与 STAGE_CAPABILITY_DEFINITIONS['override_line_onhand_source'] 保持一致。
|
||||
execution.current_gate_code = 'onhand_preparation'
|
||||
prepared_payload = dict(payload or {})
|
||||
prepared_payload.setdefault('idempotency_key', str(idempotency_key or ''))
|
||||
try:
|
||||
@@ -1694,7 +1694,7 @@ def execute_stage_capability_override_source(
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
expected_gate_version=None,
|
||||
input_snapshot={
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'action_code': 'override_line_onhand_source',
|
||||
'payload': prepared_payload,
|
||||
},
|
||||
)
|
||||
@@ -1704,7 +1704,7 @@ def execute_stage_capability_override_source(
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reset_to': 'onhand_preparation',
|
||||
'reran': False,
|
||||
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
|
||||
}
|
||||
@@ -1712,7 +1712,7 @@ def execute_stage_capability_override_source(
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reset_to': 'onhand_preparation',
|
||||
'reran': reran,
|
||||
'gate_status': updated_gate.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
|
||||
@@ -42,10 +42,10 @@ _WRITE_ACTION_CODES = frozenset({
|
||||
'adjudicate_duplicate',
|
||||
'reconcile_and_progress',
|
||||
'open_profile_review',
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_preparation',
|
||||
'upload_onhand_file',
|
||||
'retry_onhand_preparation',
|
||||
'retry_parse',
|
||||
'retry_failed_documents',
|
||||
'regenerate_excel',
|
||||
@@ -58,9 +58,9 @@ _WRITE_ACTION_CODES = frozenset({
|
||||
|
||||
# 建单前禁止下发的履约写动作(匹配 / Excel / 上传等)。
|
||||
_POST_CREATE_ONLY_ACTION_CODES = frozenset({
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'upload_onhand_file',
|
||||
'regenerate_excel',
|
||||
'download_excel',
|
||||
'open_manual_upload',
|
||||
@@ -68,8 +68,8 @@ _POST_CREATE_ONLY_ACTION_CODES = frozenset({
|
||||
|
||||
_POST_CREATE_STAGES = frozenset({
|
||||
'order_creating',
|
||||
'inventory_fetching',
|
||||
'inventory_matching',
|
||||
'onhand_fetching',
|
||||
'onhand_matching',
|
||||
'excel_generating',
|
||||
'freight_uploading',
|
||||
'completed',
|
||||
@@ -89,8 +89,8 @@ _ACTION_CODE_ALIASES: dict[str, str] = {
|
||||
'mark_manual_uploaded': 'open_manual_upload',
|
||||
'regenerate_manual_upload_todo': 'open_manual_upload',
|
||||
# [BE-05] Notice ui_state / Gate 业务动作收口到统一契约意图。
|
||||
'rematch': 'open_inventory_match_review',
|
||||
'match_inventory': 'open_inventory_match_review',
|
||||
'rematch': 'open_onhand_match_review',
|
||||
'match_inventory': 'open_onhand_match_review',
|
||||
'generate_excel': 'regenerate_excel',
|
||||
'confirm_inventory_source': 'open_inventory_source_review',
|
||||
# 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由
|
||||
@@ -196,8 +196,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
|
||||
核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传
|
||||
→ freight_uploading;
|
||||
导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching;
|
||||
matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。
|
||||
导出/Excel → excel_generating;waiting_inventory/parsed → onhand_fetching;
|
||||
matching/inventory_ready/matched → onhand_matching;建单中 → order_creating。
|
||||
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
|
||||
|
||||
Args:
|
||||
@@ -221,7 +221,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
export_path = ''
|
||||
projected_upload = None
|
||||
try:
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else ''
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
latest_export_artifact,
|
||||
@@ -270,20 +270,20 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
if ps == 'matched' and export_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching':
|
||||
return ('automating', 'inventory_matching')
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or step == 'onhand_matching':
|
||||
return ('automating', 'onhand_matching')
|
||||
|
||||
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
|
||||
if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching':
|
||||
return ('automating', 'inventory_fetching')
|
||||
if ps in {'waiting_inventory', 'parsed'} or step == 'onhand_fetching':
|
||||
return ('automating', 'onhand_fetching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating':
|
||||
return ('automating', 'order_creating')
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'}:
|
||||
return ('automating', 'inventory_fetching')
|
||||
if ps in {'fetching_inventory', 'onhand_fetching'}:
|
||||
return ('automating', 'onhand_fetching')
|
||||
if ps in {'parsing', 'parsed_pending'}:
|
||||
return ('automating', 'order_creating')
|
||||
# [BE-03] 未知状态 fail-closed:禁止猜测为正常「创建订单中」。
|
||||
@@ -560,11 +560,11 @@ def reconcile_processing_projection_facts(
|
||||
gate_stage = {
|
||||
# 正式 20-Gate 进入履约后,兼容 OT 字段可能尚未被旧写路径同步。
|
||||
# 读投影必须以 Gate 统一覆盖,避免历史 waiting_review 重新污染批次中心。
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'onhand_source_routing': 'onhand_source_resolving',
|
||||
'onhand_preparation': 'onhand_fetching',
|
||||
'onhand_field_mapping': 'onhand_fetching',
|
||||
'onhand_matching': 'onhand_matching',
|
||||
'onhand_sufficiency': 'onhand_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
@@ -687,8 +687,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = {
|
||||
'document_parsing': 'document_parsing',
|
||||
'order_creating': 'order_creating',
|
||||
'waiting_review': 'waiting_human_review',
|
||||
'inventory_fetching': 'inventory_fetch',
|
||||
'inventory_matching': 'inventory_match',
|
||||
'onhand_fetching': 'inventory_fetch',
|
||||
'onhand_matching': 'inventory_match',
|
||||
'excel_generating': 'excel_generate',
|
||||
'freight_uploading': 'freight_upload',
|
||||
'completed': 'completed',
|
||||
@@ -851,9 +851,9 @@ def apply_user_projection_fields(
|
||||
if user_stage is None:
|
||||
if old_stage in {'document_parsing', 'order_creating'}:
|
||||
user_stage = 'document_parsing'
|
||||
elif old_stage in {'inventory_fetching'}:
|
||||
elif old_stage in {'onhand_fetching'}:
|
||||
user_stage = 'inventory_fetch'
|
||||
elif old_stage in {'inventory_matching'}:
|
||||
elif old_stage in {'onhand_matching'}:
|
||||
user_stage = 'inventory_match'
|
||||
elif old_stage in {'excel_generating'}:
|
||||
user_stage = 'excel_generate'
|
||||
@@ -980,9 +980,9 @@ def apply_user_projection_fields(
|
||||
|
||||
# ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None =====
|
||||
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
|
||||
'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'retry_onhand_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
|
||||
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
|
||||
'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa',
|
||||
'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact',
|
||||
@@ -991,8 +991,8 @@ def apply_user_projection_fields(
|
||||
'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review',
|
||||
}
|
||||
_ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = {
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
|
||||
'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
|
||||
'open_order_review': 'chat.shippingProcessing.action.open_order_review',
|
||||
'retry_freight_upload_rpa': 'chat.shippingProcessing.action.retry_freight_upload_rpa',
|
||||
'match_inventory': 'chat.shippingProcessing.action.match_inventory',
|
||||
@@ -1031,7 +1031,7 @@ def apply_user_projection_fields(
|
||||
# waiting_human 仅按 Gate/领域阻断映射精确业务入口。
|
||||
if user_status == 'waiting_human':
|
||||
if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}:
|
||||
code = 'open_inventory_match_review'
|
||||
code = 'open_onhand_match_review'
|
||||
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
|
||||
if bcode in {'order_review_required', 'freeze_not_ready'}:
|
||||
code = 'open_order_review'
|
||||
@@ -1113,11 +1113,11 @@ def apply_user_projection_fields(
|
||||
# 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。
|
||||
gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
|
||||
gate_order = {
|
||||
'inventory_source_routing': 0,
|
||||
'inventory_preparation': 1,
|
||||
'inventory_field_mapping': 2,
|
||||
'inventory_matching': 3,
|
||||
'inventory_sufficiency': 4,
|
||||
'onhand_source_routing': 0,
|
||||
'onhand_preparation': 1,
|
||||
'onhand_field_mapping': 2,
|
||||
'onhand_matching': 3,
|
||||
'onhand_sufficiency': 4,
|
||||
'excel_readiness': 5,
|
||||
'artifact_generation': 6,
|
||||
'manual_upload_handoff': 7,
|
||||
@@ -1138,7 +1138,7 @@ def apply_user_projection_fields(
|
||||
# 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate
|
||||
# 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
)
|
||||
candidate_facts = project_inventory_candidate_facts(order_task)
|
||||
@@ -1163,8 +1163,8 @@ def apply_user_projection_fields(
|
||||
payload['projection_data_inconsistent'] = True
|
||||
# P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。
|
||||
try:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all()
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
attempts = FreightRpaOnhandTaskAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all()
|
||||
facts['rpa_attempts'] = [{
|
||||
'source_code': a.source_code, 'attempt_no': a.attempt_no,
|
||||
'source_run_no': a.source_run_no, 'status': a.status,
|
||||
|
||||
@@ -41,7 +41,7 @@ WORKFLOW_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'extracting',
|
||||
'pending_review',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'onhand_matching',
|
||||
'generating_excel',
|
||||
'manual_upload_pending',
|
||||
'reparse_failed',
|
||||
@@ -242,11 +242,11 @@ SHIPPING_PROCESSING_STAGES: Final[tuple[str, ...]] = (
|
||||
'candidate_creating',
|
||||
'customer_resolving',
|
||||
'duplicate_checking',
|
||||
'inventory_source_resolving',
|
||||
'onhand_source_resolving',
|
||||
'waiting_review',
|
||||
'order_creating',
|
||||
'inventory_fetching',
|
||||
'inventory_matching',
|
||||
'onhand_fetching',
|
||||
'onhand_matching',
|
||||
'excel_generating',
|
||||
'freight_uploading',
|
||||
'completed',
|
||||
@@ -283,11 +283,11 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
|
||||
'resolve_field_conflicts',
|
||||
'adjudicate_duplicate',
|
||||
'open_inventory_source_review',
|
||||
'open_inventory_match_review',
|
||||
'open_onhand_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_matching',
|
||||
'upload_onhand_file',
|
||||
'retry_onhand_preparation',
|
||||
'retry_onhand_matching',
|
||||
'retry_parse',
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
@@ -916,7 +916,7 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'path_id_hash',
|
||||
'revision_no',
|
||||
# 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。
|
||||
'inventory_source_id',
|
||||
'source_id',
|
||||
'connector_type',
|
||||
'config_version',
|
||||
'report_path_json',
|
||||
@@ -987,11 +987,11 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = (
|
||||
'chat.shippingProcessing.stage.candidate_creating',
|
||||
'chat.shippingProcessing.stage.customer_resolving',
|
||||
'chat.shippingProcessing.stage.duplicate_checking',
|
||||
'chat.shippingProcessing.stage.inventory_source_resolving',
|
||||
'chat.shippingProcessing.stage.onhand_source_resolving',
|
||||
'chat.shippingProcessing.stage.waiting_review',
|
||||
'chat.shippingProcessing.stage.order_creating',
|
||||
'chat.shippingProcessing.stage.inventory_fetching',
|
||||
'chat.shippingProcessing.stage.inventory_matching',
|
||||
'chat.shippingProcessing.stage.onhand_fetching',
|
||||
'chat.shippingProcessing.stage.onhand_matching',
|
||||
'chat.shippingProcessing.stage.excel_generating',
|
||||
'chat.shippingProcessing.stage.freight_uploading',
|
||||
'chat.shippingProcessing.stage.completed',
|
||||
@@ -1004,9 +1004,9 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = (
|
||||
'chat.shippingProcessing.action.none',
|
||||
'chat.shippingProcessing.action.open_order_review',
|
||||
'chat.shippingProcessing.action.edit_formal_task',
|
||||
'chat.shippingProcessing.action.open_inventory_match_review',
|
||||
'chat.shippingProcessing.action.open_onhand_match_review',
|
||||
'chat.shippingProcessing.action.open_shortage_review',
|
||||
'chat.shippingProcessing.action.upload_inventory_file',
|
||||
'chat.shippingProcessing.action.upload_onhand_file',
|
||||
'chat.shippingProcessing.action.retry',
|
||||
'chat.shippingProcessing.action.refresh',
|
||||
'chat.shippingProcessing.action.regenerate_excel',
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
|
||||
依赖:customer_identity_gate、tool_common、query_service、onhand_workflow、fulfillment_workflow、
|
||||
process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、
|
||||
state_machine(双读回退)、tool_response、process_gate_bridge。
|
||||
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交
|
||||
当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留
|
||||
供兼容调用方,但不得再由本 facade 直接跨 Gate 调度;
|
||||
早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state;
|
||||
inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。
|
||||
onhand_preparation 的 retryable_tech 阻断不早停,交给 ensure_onhand(复用快照或 RPA)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,11 +29,11 @@ from app.services.shipping_notice.constants import (
|
||||
RS_PARSE_REVIEW,
|
||||
RS_RSV_REQ,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
ensure_inventory_source_review_state,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory
|
||||
from app.services.shipping_notice.onhand_workflow import ensure_inventory as _legacy_ensure_inventory
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event
|
||||
@@ -46,8 +46,8 @@ def _entry_user_mode(task) -> str:
|
||||
自动推进入口早停:从 Gate 推导用户处置模式。
|
||||
|
||||
无活动 Execution 时回退 resolve_task_ui_state.user_mode。
|
||||
inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker
|
||||
继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。
|
||||
onhand_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker
|
||||
继续走 ensure_onhand(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
derive_user_mode,
|
||||
@@ -73,7 +73,7 @@ def _entry_user_mode(task) -> str:
|
||||
# blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由
|
||||
# submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。
|
||||
if (
|
||||
gate_code == 'inventory_preparation'
|
||||
gate_code == 'onhand_preparation'
|
||||
and status == 'blocked_retryable'
|
||||
and user_mode_for_blocking_reason(reason_code) == 'retryable_tech'
|
||||
):
|
||||
@@ -131,10 +131,10 @@ def _entry_position(task) -> str | None:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RESUME_GATE_CODE_LEGACY_ENTRY = {
|
||||
# inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现)
|
||||
'inventory_preparation': 'ensure_inventory',
|
||||
# inventory_preparation → 调 onhand_workflow.ensure_inventory 逻辑(复用旧实现)
|
||||
'onhand_preparation': 'ensure_onhand',
|
||||
# inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次)
|
||||
'inventory_matching': 'match_inventory',
|
||||
'onhand_matching': 'match_inventory',
|
||||
# None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传)
|
||||
'auto': 'auto_progress_full',
|
||||
None: 'auto_progress_full',
|
||||
@@ -223,18 +223,18 @@ def _dispatch_legacy_orchestration(
|
||||
'resume_gate_code': resume_gate_code,
|
||||
'mode': inventory_mode,
|
||||
}
|
||||
if entry == 'ensure_inventory':
|
||||
if entry == 'ensure_onhand':
|
||||
# [T4 集成] 库存准备:如果存在 per-source 候选冻结,优先走 per_source_rpa_service 逐源准备
|
||||
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
from app.services.shipping_notice.stp_onhand_freeze import (
|
||||
task_frozen_onhand_source_codes,
|
||||
)
|
||||
frozen_sources = task_frozen_inventory_source_codes(task)
|
||||
frozen_sources = task_frozen_onhand_source_codes(task)
|
||||
if frozen_sources and len(frozen_sources) >= 1:
|
||||
scoped_source_codes: list[str] | None = None
|
||||
scope_key = str(line_scope_key or '').strip()
|
||||
if scope_key:
|
||||
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
|
||||
|
||||
try:
|
||||
scoped_line_id = int(scope_key)
|
||||
@@ -342,7 +342,7 @@ def run_task_auto_progress(
|
||||
"""
|
||||
唯一 AutoProgress Orchestrator Facade。
|
||||
【AI 触发时机】:所有需要推进发货任务状态的入口(Tool API、Batch Orchestrator、Retry Decision、
|
||||
Gate Handler post-action)均应调用本函数;禁止直接调 inventory_workflow.ensure_inventory
|
||||
Gate Handler post-action)均应调用本函数;禁止直接调 onhand_workflow.ensure_onhand
|
||||
或 fulfillment_workflow.match_inventory 绕过并发锁。
|
||||
|
||||
核心步骤:
|
||||
@@ -777,7 +777,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
# [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。
|
||||
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 has_ready_inventory_file_for_task(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||||
依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
|
||||
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
|
||||
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
|
||||
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
|
||||
order_review_projection(任务中心 STP retry 动作投影)。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
@@ -43,8 +43,8 @@ from app.models import (
|
||||
FileAsset,
|
||||
ShippingExportArtifact,
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryFile,
|
||||
ShippingOnhandVerification,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
@@ -64,9 +64,9 @@ from app.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingTaskEvent,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
@@ -125,9 +125,9 @@ _REVIEW_TODO_GATE_CODES = frozenset({
|
||||
'reservation_validation',
|
||||
})
|
||||
_EXCEPTION_TODO_GATE_CODES = frozenset({
|
||||
'inventory_sufficiency',
|
||||
'onhand_sufficiency',
|
||||
'freight_upload_rpa',
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'excel_readiness',
|
||||
})
|
||||
_RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'})
|
||||
@@ -281,8 +281,8 @@ class TaskProjection(str, Enum):
|
||||
def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]:
|
||||
"""为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。"""
|
||||
inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id)
|
||||
verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by(
|
||||
ShippingInventoryVerification.created_at, ShippingInventoryVerification.id,
|
||||
verifications = ShippingOnhandVerification.query.filter_by(task_id=inventory_task_id).order_by(
|
||||
ShippingOnhandVerification.created_at, ShippingOnhandVerification.id,
|
||||
).all()
|
||||
artifacts = []
|
||||
if isinstance(task, ShippingNotice):
|
||||
@@ -307,7 +307,7 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]
|
||||
).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else []
|
||||
return {
|
||||
'inventory_verifications': [{
|
||||
'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id,
|
||||
'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.onhand_snapshot_id,
|
||||
'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'lines': [{
|
||||
'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty),
|
||||
@@ -486,7 +486,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""Tool data 基础字段(裁剪前)。"""
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
header, lines, _field_display = _order_values_for_projection(task)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
match_facts = list(load_current_match_facts_by_task(task.id).values())
|
||||
customer = _order_task_customer_projection(task)
|
||||
@@ -517,7 +517,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
'conversation_id': task.conversation_id,
|
||||
'step_payload': task.step_payload_json or {},
|
||||
**inventory,
|
||||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||||
'onhand_snapshot': _serialize_inventory_snapshot(task),
|
||||
}
|
||||
from app.services.shipping_notice.notice_upload import max_notice_chars
|
||||
from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode
|
||||
@@ -560,9 +560,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
}
|
||||
raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip()
|
||||
lines = payload["lines"]
|
||||
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
|
||||
from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link
|
||||
|
||||
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
|
||||
payload["onhand_snapshot"] = serialize_inventory_snapshot_link(task)
|
||||
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
|
||||
if raw_content and not lines:
|
||||
limit = max_notice_chars()
|
||||
@@ -574,7 +574,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
|
||||
def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
|
||||
"""从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
rows = list(load_current_match_facts_by_task(task_id).values())
|
||||
@@ -652,7 +652,7 @@ def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tu
|
||||
|
||||
def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""工作台任务摘要中的库存快照投影。"""
|
||||
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
|
||||
from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link
|
||||
|
||||
return serialize_inventory_snapshot_link(task)
|
||||
|
||||
@@ -675,7 +675,7 @@ def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]:
|
||||
|
||||
def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]:
|
||||
"""从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts
|
||||
from app.services.shipping_notice.onhand_candidate_projection import project_inventory_candidate_facts
|
||||
|
||||
facts = project_inventory_candidate_facts(task)
|
||||
sources = list(facts.get('sources') or [])
|
||||
@@ -816,7 +816,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
|
||||
for result in (task_disposition_capability(task, action),)
|
||||
}
|
||||
step_payload = task.step_payload_json or {}
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
match_facts = list(load_current_match_facts_by_task(task.id).values())
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
@@ -852,7 +852,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
|
||||
'destination_country': header.get('destination_country'),
|
||||
'warehouse_hint': header.get('warehouse_hint'),
|
||||
**inventory,
|
||||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||||
'onhand_snapshot': _serialize_inventory_snapshot(task),
|
||||
'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]},
|
||||
'line_results': match_facts,
|
||||
'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None),
|
||||
@@ -864,13 +864,13 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
|
||||
workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {}
|
||||
step_payload = workflow_payload
|
||||
header = current_header_field_values_or_empty(workflow_owner)
|
||||
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
inventory_facts = active_inventory_runtime_facts(workflow_owner)
|
||||
source_codes = task_frozen_inventory_source_codes(workflow_owner)
|
||||
source_codes = task_frozen_onhand_source_codes(workflow_owner)
|
||||
routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {})
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
match_task_id = getattr(workflow_owner, 'id', None) or task.id
|
||||
match_facts = list(load_current_match_facts_by_task(match_task_id).values())
|
||||
match_status_projection = (
|
||||
@@ -931,7 +931,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
|
||||
"inventory_source_method": routing.get('adjudication_method'),
|
||||
"inventory_source_config_version": inventory_facts.get('source_config_version'),
|
||||
"inventory_routing_fingerprint": routing.get('routing_fingerprint'),
|
||||
"inventory_snapshot": _serialize_inventory_snapshot(workflow_owner),
|
||||
"onhand_snapshot": _serialize_inventory_snapshot(workflow_owner),
|
||||
"shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]},
|
||||
"line_results": match_facts,
|
||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||
@@ -1424,9 +1424,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
if snapshot is not None:
|
||||
matches_by_snapshot_line_id = {
|
||||
int(item.snapshot_line_id): item
|
||||
for item in ShippingNoticeLineInventoryMatch.query.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(owner.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
for item in ShippingNoticeLineOnhandMatch.query.filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == int(owner.id),
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
).all()
|
||||
if item.snapshot_line_id is not None
|
||||
}
|
||||
@@ -1434,9 +1434,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
# 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。
|
||||
matches_by_snapshot_line_id = {
|
||||
int(item.snapshot_line_id): item
|
||||
for item in ShippingNoticeLineInventoryMatch.query.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
for item in ShippingNoticeLineOnhandMatch.query.filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
).all()
|
||||
if item.snapshot_line_id is not None
|
||||
}
|
||||
@@ -1453,7 +1453,7 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||||
'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty
|
||||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||||
'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status
|
||||
'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).onhand_status
|
||||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||||
} for item in rows]
|
||||
|
||||
@@ -2175,15 +2175,15 @@ def _order_task_todo_category_sql_expr():
|
||||
reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, ""))
|
||||
ready_file = exists(
|
||||
select(1)
|
||||
.select_from(ShippingTaskInventoryLink)
|
||||
.join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id)
|
||||
.select_from(ShippingTaskOnhandLink)
|
||||
.join(FreightRpaOnhandReportFile, FreightRpaOnhandReportFile.id == ShippingTaskOnhandLink.onhand_file_id)
|
||||
.where(
|
||||
ShippingTaskInventoryLink.task_id == ShippingOrderTask.id,
|
||||
ShippingTaskInventoryLink.is_active.is_(True),
|
||||
ShippingTaskInventoryLink.invalidated_at.is_(None),
|
||||
ShippingInventoryFile.snapshot_status == 'ready',
|
||||
ShippingInventoryFile.invalidated_at.is_(None),
|
||||
ShippingInventoryFile.line_count > 0,
|
||||
ShippingTaskOnhandLink.task_id == ShippingOrderTask.id,
|
||||
ShippingTaskOnhandLink.is_active.is_(True),
|
||||
ShippingTaskOnhandLink.invalidated_at.is_(None),
|
||||
FreightRpaOnhandReportFile.snapshot_status == 'ready',
|
||||
FreightRpaOnhandReportFile.invalidated_at.is_(None),
|
||||
FreightRpaOnhandReportFile.line_count > 0,
|
||||
)
|
||||
)
|
||||
incomplete_match = exists(
|
||||
@@ -2192,24 +2192,24 @@ def _order_task_todo_category_sql_expr():
|
||||
.where(
|
||||
ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id,
|
||||
~exists(
|
||||
select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||||
ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id,
|
||||
ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'preparing',
|
||||
select(1).select_from(ShippingNoticeLineOnhandMatch).where(
|
||||
ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id,
|
||||
ShippingNoticeLineOnhandMatch.snapshot_line_id == ShippingOrderSnapshotLine.id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result != 'preparing',
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
has_shortage = exists(
|
||||
select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||||
ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
select(1).select_from(ShippingNoticeLineOnhandMatch).where(
|
||||
ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
db.or_(
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
ShippingNoticeLineOnhandMatch.match_result != 'matched',
|
||||
db.and_(
|
||||
ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None),
|
||||
ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')),
|
||||
ShippingNoticeLineOnhandMatch.shortage_qty.isnot(None),
|
||||
ShippingNoticeLineOnhandMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -2242,7 +2242,7 @@ def _order_task_todo_category_sql_expr():
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")),
|
||||
(stage.in_(("onhand_source_resolving", "notification_preparation", "onhand_fetching", "onhand_matching", "order_creating")), literal("in_progress")),
|
||||
else_=literal("exception"),
|
||||
)
|
||||
|
||||
@@ -2623,10 +2623,10 @@ def _todo_category_sql_filter(allowed: frozenset[str]):
|
||||
clauses.append(
|
||||
db.or_(
|
||||
workflow_current_step.isnot(None),
|
||||
exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||||
ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
|
||||
exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(
|
||||
ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
||||
)),
|
||||
artifact_exists,
|
||||
upload_pending,
|
||||
@@ -2705,9 +2705,9 @@ def _task_todo_category_sql_expr():
|
||||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded"))))
|
||||
upload_success = _verified_upload_success_sql_expr()
|
||||
upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown"))))
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||||
ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(
|
||||
ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
))
|
||||
return case(
|
||||
(upload_success, literal("done")),
|
||||
@@ -2847,7 +2847,7 @@ def _todo_tasks_base_query(
|
||||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||||
upload_success = _verified_upload_success_sql_expr()
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True)))
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True)))
|
||||
if task_no:
|
||||
q = q.filter(ShippingNotice.task_no == str(task_no).strip())
|
||||
if customer_needle:
|
||||
@@ -3259,7 +3259,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]:
|
||||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||||
upload_success = _verified_upload_success_sql_expr()
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True)))
|
||||
match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True)))
|
||||
pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count()
|
||||
pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
|
||||
@@ -94,7 +94,7 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool:
|
||||
return False
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
pending_reason = str(task_blocking_reason(task) or '').strip()
|
||||
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
|
||||
|
||||
return (
|
||||
pending_reason == PH_RPA_PENDING
|
||||
@@ -112,7 +112,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
|
||||
task = get_task_by_ref(task_no)
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING:
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import next_inventory_rpa_recheck_at
|
||||
|
||||
scheduled_at = next_inventory_rpa_recheck_at(task)
|
||||
if scheduled_at is None:
|
||||
@@ -224,7 +224,7 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS,
|
||||
JobType.SHIPPING_PDF_AUTOMARK,
|
||||
JobType.SHIPPING_STP_AUTO_CREATE,
|
||||
JobType.SHIPPING_LINE_AUTO_FULFILL,
|
||||
|
||||
@@ -15,11 +15,11 @@ from sqlalchemy import false
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryMapping,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOnhandVerification,
|
||||
FreightRpaOnhandMapping,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingProcessExecution,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
ShippingUploadAttempt,
|
||||
ShippingNotice,
|
||||
)
|
||||
@@ -43,10 +43,10 @@ def _noticed_snapshot_line_ids(task_id: int) -> set[int]:
|
||||
return {int(row[0]) for row in rows if row[0] is not None}
|
||||
|
||||
|
||||
def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]:
|
||||
def _match_row_source_codes(row: ShippingNoticeLineOnhandMatch) -> set[str]:
|
||||
"""从匹配事实抽取规范化库存源集合,供行级失效过滤。"""
|
||||
codes: set[str] = set()
|
||||
primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper()
|
||||
primary = str(getattr(row, 'source_code', '') or '').strip().upper()
|
||||
if primary:
|
||||
codes.add(primary)
|
||||
for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []):
|
||||
@@ -89,10 +89,10 @@ def invalidate_inventory_downstream(
|
||||
task = db.session.get(ShippingOrderTask, task_id)
|
||||
result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
|
||||
change_type = {
|
||||
'retry_inventory_preparation': 'inventory_file_changed',
|
||||
'retry_inventory_from_preparation': 'inventory_file_changed',
|
||||
'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed',
|
||||
'retry_inventory_from_matching': 'inventory_matching_changed',
|
||||
'retry_onhand_preparation': 'inventory_file_changed',
|
||||
'retry_onhand_from_preparation': 'inventory_file_changed',
|
||||
'retry_onhand_from_field_mapping': 'inventory_field_mapping_changed',
|
||||
'retry_onhand_from_matching': 'inventory_matching_changed',
|
||||
}.get(action_code, 'inventory_matching_changed')
|
||||
result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id)
|
||||
scoped_codes = {
|
||||
@@ -103,8 +103,8 @@ def invalidate_inventory_downstream(
|
||||
line_scoped = bool(scoped_codes)
|
||||
protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set()
|
||||
scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None
|
||||
if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}:
|
||||
links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all()
|
||||
if action_code in {'retry_onhand_preparation', 'retry_onhand_from_preparation'}:
|
||||
links = ShippingTaskOnhandLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all()
|
||||
for link in links:
|
||||
link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper()
|
||||
if line_scoped and link_code and link_code not in scoped_codes:
|
||||
@@ -118,26 +118,26 @@ def invalidate_inventory_downstream(
|
||||
link.invalidation_reason = action_code
|
||||
result['links'].append(int(link.id))
|
||||
affected_file_ids = [
|
||||
int(link.inventory_file_id)
|
||||
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all()
|
||||
if link.inventory_file_id and (
|
||||
int(link.onhand_file_id)
|
||||
for link in ShippingTaskOnhandLink.query.filter_by(task_id=task_id).all()
|
||||
if link.onhand_file_id and (
|
||||
not line_scoped
|
||||
or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes
|
||||
)
|
||||
]
|
||||
if action_code in {
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_inventory_from_field_mapping',
|
||||
'retry_onhand_preparation',
|
||||
'retry_onhand_from_preparation',
|
||||
'retry_onhand_from_field_mapping',
|
||||
} and affected_file_ids:
|
||||
mappings = ShippingInventoryMapping.query.filter(
|
||||
ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids),
|
||||
ShippingInventoryMapping.status == 'active',
|
||||
mappings = FreightRpaOnhandMapping.query.filter(
|
||||
FreightRpaOnhandMapping.onhand_file_id.in_(affected_file_ids),
|
||||
FreightRpaOnhandMapping.status == 'active',
|
||||
).with_for_update().all()
|
||||
for mapping in mappings:
|
||||
mapping.status = 'invalidated'
|
||||
result['mappings'].append(int(mapping.id))
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all()
|
||||
matches = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all()
|
||||
for row in matches:
|
||||
row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0)
|
||||
if line_scoped and row_line_id in protected_line_ids:
|
||||
@@ -154,7 +154,7 @@ def invalidate_inventory_downstream(
|
||||
row.invalidation_reason = action_code
|
||||
result['matches'].append(int(row.id))
|
||||
if not line_scoped:
|
||||
verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
|
||||
verifications = ShippingOnhandVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
|
||||
for verification in verifications:
|
||||
verification.status = 'superseded'
|
||||
result['verifications'].append(int(verification.id))
|
||||
|
||||
@@ -12,50 +12,50 @@ from typing import Any
|
||||
|
||||
|
||||
RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = {
|
||||
'inventory_matching': {
|
||||
'retry_inventory_from_preparation': {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_matching',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping',),
|
||||
'onhand_matching': {
|
||||
'retry_onhand_from_preparation': {
|
||||
'target_gate': 'onhand_preparation',
|
||||
'resume_after_gate': 'onhand_matching',
|
||||
'allowed_intermediate_gates': ('onhand_field_mapping',),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
'retry_inventory_from_field_mapping': {
|
||||
'target_gate': 'inventory_field_mapping',
|
||||
'resume_after_gate': 'inventory_matching',
|
||||
'retry_onhand_from_field_mapping': {
|
||||
'target_gate': 'onhand_field_mapping',
|
||||
'resume_after_gate': 'onhand_matching',
|
||||
'allowed_intermediate_gates': (),
|
||||
'invalidate_change_type': 'inventory_field_mapping_changed',
|
||||
'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'invalidates': ('onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
},
|
||||
# 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。
|
||||
'inventory_sufficiency': {
|
||||
'onhand_sufficiency': {
|
||||
# 公开动作:用户明确选择“重新获取库存”时回到准备 Gate,强制创建新的 RPA
|
||||
# Attempt;不能要求客户端传递内部的 retry_inventory_from_preparation。
|
||||
'retry_inventory_preparation': {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_sufficiency',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'),
|
||||
'retry_onhand_preparation': {
|
||||
'target_gate': 'onhand_preparation',
|
||||
'resume_after_gate': 'onhand_sufficiency',
|
||||
'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
'retry_inventory_from_preparation': {
|
||||
'target_gate': 'inventory_preparation',
|
||||
'resume_after_gate': 'inventory_sufficiency',
|
||||
'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'),
|
||||
'retry_onhand_from_preparation': {
|
||||
'target_gate': 'onhand_preparation',
|
||||
'resume_after_gate': 'onhand_sufficiency',
|
||||
'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'),
|
||||
'invalidate_change_type': 'inventory_file_changed',
|
||||
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
'retry_inventory_from_matching': {
|
||||
'target_gate': 'inventory_matching',
|
||||
'resume_after_gate': 'inventory_sufficiency',
|
||||
'retry_onhand_from_matching': {
|
||||
'target_gate': 'onhand_matching',
|
||||
'resume_after_gate': 'onhand_sufficiency',
|
||||
'allowed_intermediate_gates': (),
|
||||
'invalidate_change_type': 'inventory_matching_changed',
|
||||
'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
|
||||
'invalidates': ('onhand_matching', 'onhand_sufficiency', 'excel', 'upload'),
|
||||
'permission': 'owner_or_admin',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -107,8 +107,8 @@ def complete_recovery_plan_for_attempt(
|
||||
resolved_outcome = str(outcome)
|
||||
rematch_reached_shortage_review = (
|
||||
resolved_outcome == 'blocked_manual'
|
||||
and str(plan.action_code or '') == 'retry_inventory_from_matching'
|
||||
and str(plan.resume_after_gate or '') == 'inventory_sufficiency'
|
||||
and str(plan.action_code or '') == 'retry_onhand_from_matching'
|
||||
and str(plan.resume_after_gate or '') == 'onhand_sufficiency'
|
||||
and str(business_result_code or '') == 'inventory_shortage_review_required'
|
||||
)
|
||||
excel_regeneration_reached_manual_upload = (
|
||||
|
||||
@@ -103,7 +103,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
|
||||
from app.models import ShippingOrderTask
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||||
review_status = _clean_text(getattr(owner, "review_status", None)).lower()
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower()
|
||||
pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower()
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/reservation_id.py
|
||||
|
||||
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
|
||||
依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。
|
||||
逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用;
|
||||
逻辑:由 notice_lines、onhand_snapshot、match、extract、EML 补充解析等多个模块复用;
|
||||
归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。
|
||||
另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为
|
||||
5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并
|
||||
|
||||
@@ -17,8 +17,8 @@ from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingOnhandVerification,
|
||||
ShippingOnhandVerificationLine,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderTask,
|
||||
ShippingReservation,
|
||||
@@ -190,12 +190,12 @@ def _transfer_confirmed_revision(
|
||||
def record_inventory_verification(
|
||||
task: ShippingNotice, *, inventory_snapshot_id: int | None, source_config_version: str | None,
|
||||
line_results: list[dict[str, Any]],
|
||||
) -> ShippingInventoryVerification:
|
||||
) -> ShippingOnhandVerification:
|
||||
"""把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。"""
|
||||
reservations = ensure_task_reservations(task)
|
||||
by_key = {row.reservation_id: row for row in reservations}
|
||||
verification = ShippingInventoryVerification(
|
||||
task_id=task.id, inventory_snapshot_id=inventory_snapshot_id,
|
||||
verification = ShippingOnhandVerification(
|
||||
task_id=task.id, onhand_snapshot_id=inventory_snapshot_id,
|
||||
source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)},
|
||||
)
|
||||
db.session.add(verification)
|
||||
@@ -218,7 +218,7 @@ def record_inventory_verification(
|
||||
seen_reservation_ids.add(reservation_id)
|
||||
available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0')
|
||||
status = 'available' if available >= required else 'shortage'
|
||||
db.session.add(ShippingInventoryVerificationLine(
|
||||
db.session.add(ShippingOnhandVerificationLine(
|
||||
verification_id=verification.id, reservation_id=reservation.id, required_qty=required,
|
||||
available_qty=available, status=status, detail_json={'line_status': item.get('line_status')},
|
||||
))
|
||||
@@ -236,7 +236,7 @@ def reserve_available_for_artifact(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
artifact: ShippingExportArtifact,
|
||||
verification: ShippingInventoryVerification,
|
||||
verification: ShippingOnhandVerification,
|
||||
released_snapshot_line_ids: set[int] | None = None,
|
||||
selected_snapshot_line_ids: set[int] | None = None,
|
||||
) -> list[ShippingReservation]:
|
||||
@@ -244,7 +244,7 @@ def reserve_available_for_artifact(
|
||||
锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。
|
||||
|
||||
核心逻辑:默认只消费 ``available`` Reservation;调用方仅可传入从活动
|
||||
``release_inventory_shortage`` 决定解析出的冻结行 ID,使该行的 shortage
|
||||
``release_onhand_shortage`` 决定解析出的冻结行 ID,使该行的 shortage
|
||||
Verification 作为放行审计的一部分绑定到 Artifact,其他 shortage 不得被捎带导出。
|
||||
|
||||
Args:
|
||||
@@ -311,7 +311,7 @@ def current_available_snapshot_line_ids(
|
||||
released_snapshot_line_ids: set[int] | None = None,
|
||||
selected_snapshot_line_ids: set[int] | None = None,
|
||||
closed_snapshot_line_ids: set[int] | None = None,
|
||||
) -> tuple[ShippingInventoryVerification, set[int]]:
|
||||
) -> tuple[ShippingOnhandVerification, set[int]]:
|
||||
"""
|
||||
取得最新核验中可导出的冻结订单行。
|
||||
|
||||
@@ -328,8 +328,8 @@ def current_available_snapshot_line_ids(
|
||||
(最新核验轮次, 本次可导出的冻结订单行 ID)。
|
||||
"""
|
||||
verification = (
|
||||
ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed')
|
||||
.order_by(ShippingInventoryVerification.id.desc()).first()
|
||||
ShippingOnhandVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed')
|
||||
.order_by(ShippingOnhandVerification.id.desc()).first()
|
||||
)
|
||||
if verification is None:
|
||||
raise ConflictError('No inventory verification is available', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/routing_operators.py
|
||||
|
||||
用途:执行库存源路由规则允许的比较操作。
|
||||
依赖:无业务服务依赖;由 inventory_routing_engine 调用。
|
||||
依赖:无业务服务依赖;由 onhand_routing_engine 调用。
|
||||
逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。
|
||||
"""
|
||||
|
||||
|
||||
@@ -2,15 +2,22 @@
|
||||
services/shipping_notice/rpa_sinks.py
|
||||
|
||||
用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把
|
||||
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器。
|
||||
依赖:freight_rpa.common.callback_sinks(register_sink)、inventory_rpa_workflow(快照落盘/
|
||||
批量 ingest)、per_source_rpa_service(Attempt 认领)、inventory_configuration_test(配置测试)、
|
||||
receipt_report_storage(inbound 归档入口 + 业务桥留守)、schedule.freight_inbound_rpa_finalize
|
||||
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器,并把文件/报表
|
||||
事实 kind 接到 reports.dispatch 的处理函数(阶段 B Task 7)。
|
||||
依赖:freight_rpa.common.callback_sinks(register_sink——进度类回调注册表)、
|
||||
freight_rpa.reports.dispatch(register_report_handler——文件/报表事实处理函数注册表)、
|
||||
onhand_rpa_workflow(快照落盘/批量 ingest)、per_source_rpa_service(Attempt 认领)、
|
||||
onhand_configuration_test(配置测试)、inbound_report_storage(inbound 归档入口 +
|
||||
业务桥留守)、in_transit_transfer.inbound_report_handler / onhand_report_handler
|
||||
(Task 7 的两个文件事实处理函数)、schedule.freight_rpa_inbound_finalize
|
||||
(inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。
|
||||
逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成
|
||||
注册(幂等,重复注册覆盖)。各 sink 仅做两件事:① 复刻旧 shipping-notice rpa 回调端点
|
||||
端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入旧路由
|
||||
等价的 payload['repair']=True。业务事务边界完全由被包装的域内函数保持,本层不碰 db。
|
||||
注册(幂等,重复注册覆盖)。进度类 sink 仅做两件事:① 复刻旧 shipping-notice rpa
|
||||
回调端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入
|
||||
旧路由等价的 payload['repair']=True。文件事实处理函数经 register_report_handler 注册
|
||||
(Task 7:inbound→handle_inbound_report、onhand→handle_onhand_report)——归档入口
|
||||
终态 commit 后经 dispatch_report_fact 投递 ReportFact 调入;业务事务边界完全由被
|
||||
包装的域内函数保持,本层只做接线,不碰 db。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -47,57 +54,74 @@ def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]])
|
||||
|
||||
def _onhand_repair_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""受控库存回调修复:等价旧 /rpa/inventory-repair——payload['repair']=True 后走 batch-ready ingest。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
payload['repair'] = True
|
||||
return rpa_report_inventory_batch(payload)
|
||||
|
||||
|
||||
def register_onhand_sinks() -> None:
|
||||
"""组合根入口:注册全部 onhand 回调 sink(幂等;create_app 每次启动调用)。
|
||||
"""组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀;被包装函数全部住在
|
||||
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在
|
||||
shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch)
|
||||
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线。
|
||||
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线;
|
||||
文件事实处理函数走 reports.dispatch(Task 7):'onhand' kind 经
|
||||
register_report_handler 注册 handle_onhand_report(在手文件归档终态 commit 后由
|
||||
dispatch_report_fact 调入),进度类 sink 仍走 register_sink、envelope 不变。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.shipping_notice import inventory_configuration_test, inventory_rpa_workflow
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice import onhand_configuration_test, onhand_rpa_workflow
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
|
||||
register_sink('onhand-ready', _bare(inventory_rpa_workflow.rpa_report_inventory))
|
||||
register_sink('onhand-batch-ready', _bare(inventory_rpa_workflow.rpa_report_inventory_batch))
|
||||
register_sink('onhand-ready', _bare(onhand_rpa_workflow.rpa_report_inventory))
|
||||
register_sink('onhand-batch-ready', _bare(onhand_rpa_workflow.rpa_report_inventory_batch))
|
||||
register_sink('onhand-batch-claimed', _success_data_envelope(claim_inventory_batch))
|
||||
register_sink('onhand-batch-progress', _bare(inventory_rpa_workflow.report_inventory_batch_progress))
|
||||
register_sink('onhand-batch-progress', _bare(onhand_rpa_workflow.report_inventory_batch_progress))
|
||||
register_sink(
|
||||
'onhand-configuration-test-start',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_progress),
|
||||
_ok_data_envelope(onhand_configuration_test.report_batch_test_progress),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-analyze',
|
||||
_ok_data_envelope(inventory_configuration_test.report_test_export),
|
||||
_ok_data_envelope(onhand_configuration_test.report_test_export),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-complete',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_exports),
|
||||
_ok_data_envelope(onhand_configuration_test.report_batch_test_exports),
|
||||
)
|
||||
register_sink('onhand-repair', _onhand_repair_sink)
|
||||
# [STEP Task 7] 文件事实处理函数注册:onhand 归档终态 commit 后经
|
||||
# dispatch_report_fact 投递 ReportFact(report_kind='onhand')到本处理函数。
|
||||
register_report_handler('onhand', handle_onhand_report)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""组合根入口:注册全部 inbound(收料)回调 sink(幂等;create_app 每次启动调用)。
|
||||
"""组合根入口:注册全部 inbound(收料)回调 sink 与 inbound 事实处理函数(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
|
||||
业务处理器 = receipt_report_storage.ingest_receipt_callback(归档能力下沉
|
||||
freight_rpa.inbound.report_archive 后的域内入口,内部把「终态推进在途调拨来源任务
|
||||
+ 调拨证据同步 + 排程终态归集」业务桥作为 on_terminal 钩子注入——业务桥留守
|
||||
shipping_notice,与拆分前调用方向一致);unit/batch-progress 处理器仍住排程壳
|
||||
(Task 11 已平移改名为 schedule.freight_inbound_rpa_finalize),按「处理函数住在哪个包」
|
||||
由本层接注册表。三个 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
|
||||
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
|
||||
业务处理器 = inbound_report_storage.ingest_receipt_callback(归档能力下沉
|
||||
freight_rpa.inbound.report_archive 后的域内入口;批次 B Task 6 起归档入口不再收
|
||||
on_terminal 钩子——终态 commit 后由 report_archive 直接投递 ReportFact);
|
||||
unit/batch-progress 处理器仍住排程壳
|
||||
(Task 11 已平移改名为 schedule.freight_rpa_inbound_finalize),按「处理函数住在哪个包」
|
||||
由本层接注册表。三个进度类 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
|
||||
文件事实处理函数走 reports.dispatch(Task 7):'inbound' kind 经 register_report_handler
|
||||
注册 in_transit_transfer.handle_inbound_report(调拨推进/证据同步/排程收口均由该
|
||||
处理函数承担,freight_rpa 不 import 桥与 finalize),进度类 sink 仍走 register_sink、
|
||||
envelope 不变。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.schedule import freight_inbound_rpa_finalize
|
||||
from app.services.shipping_notice import receipt_report_storage
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
from app.services.schedule import freight_rpa_inbound_finalize
|
||||
from app.services.shipping_notice import inbound_report_storage
|
||||
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(receipt_report_storage.ingest_receipt_callback))
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_inbound_rpa_finalize.mark_receipt_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_inbound_rpa_finalize.report_receipt_batch_progress))
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(inbound_report_storage.ingest_receipt_callback))
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_receipt_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_receipt_batch_progress))
|
||||
# [STEP Task 7] 文件事实处理函数注册:inbound 归档各终态 commit 后经
|
||||
# dispatch_report_fact 投递 ReportFact(report_kind='inbound')到调拨侧处理函数。
|
||||
register_report_handler('inbound', handle_inbound_report)
|
||||
@@ -120,7 +120,7 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]:
|
||||
owner = task
|
||||
if isinstance(task, ShippingNotice) and task.order_task_id:
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or ''
|
||||
upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip()
|
||||
|
||||
@@ -88,8 +88,8 @@ def create_shipping_notice_after_inventory_gate(
|
||||
|
||||
# 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时,
|
||||
# OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink
|
||||
fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch, ShippingTaskOnhandLink
|
||||
fact_rows = ShippingNoticeLineOnhandMatch.query.filter_by(
|
||||
task_id=int(order_task.id), is_current=True,
|
||||
).all()
|
||||
by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
|
||||
@@ -106,7 +106,7 @@ def create_shipping_notice_after_inventory_gate(
|
||||
or (
|
||||
not (
|
||||
str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched'
|
||||
and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready'
|
||||
and str(by_line[int(line_id)].onhand_status or '').strip().lower() == 'ready'
|
||||
)
|
||||
and int(line_id) not in released_ids
|
||||
)
|
||||
@@ -114,29 +114,29 @@ def create_shipping_notice_after_inventory_gate(
|
||||
):
|
||||
raise ConflictError(
|
||||
"Inventory matching must pass before creating a shipping notice",
|
||||
code="SHIPPING.INVENTORY_GATE_NOT_PASSED",
|
||||
code="SHIPPING.ONHAND_GATE_NOT_PASSED",
|
||||
)
|
||||
|
||||
inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {}
|
||||
for snapshot_line_id in target_ids:
|
||||
match = by_line[int(snapshot_line_id)]
|
||||
inventory_file = (
|
||||
db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id))
|
||||
if match.inventory_snapshot_id is not None
|
||||
db.session.get(FreightRpaOnhandReportFile, int(match.onhand_snapshot_id))
|
||||
if match.onhand_snapshot_id is not None
|
||||
else None
|
||||
)
|
||||
link = (
|
||||
ShippingTaskInventoryLink.query.filter_by(
|
||||
ShippingTaskOnhandLink.query.filter_by(
|
||||
task_id=int(order_task.id),
|
||||
inventory_file_id=int(inventory_file.id),
|
||||
matched_source_code=match.inventory_source_code,
|
||||
onhand_file_id=int(inventory_file.id),
|
||||
matched_source_code=match.source_code,
|
||||
is_active=True,
|
||||
).order_by(ShippingTaskInventoryLink.id.desc()).first()
|
||||
).order_by(ShippingTaskOnhandLink.id.desc()).first()
|
||||
if inventory_file is not None
|
||||
else None
|
||||
)
|
||||
inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = {
|
||||
'inventory_source_code': match.inventory_source_code,
|
||||
'inventory_source_code': match.source_code,
|
||||
'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None,
|
||||
'inventory_warehouse_id': (
|
||||
str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper()
|
||||
|
||||
@@ -489,9 +489,9 @@ _ACTIVITY_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'review_required': 'waiting_review',
|
||||
'waiting_review': 'waiting_review',
|
||||
'order_creating': 'order_creating',
|
||||
'inventory_source_resolving': 'inventory_source_resolving',
|
||||
'inventory_fetching': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'onhand_source_resolving': 'onhand_source_resolving',
|
||||
'onhand_fetching': 'onhand_fetching',
|
||||
'onhand_matching': 'onhand_matching',
|
||||
'excel_generating': 'excel_generating',
|
||||
'freight_uploading': 'freight_uploading',
|
||||
'completed': 'completed',
|
||||
@@ -2092,14 +2092,14 @@ def _project_order_task_work_item(
|
||||
inventory_preparation = None
|
||||
if notice is not None:
|
||||
try:
|
||||
from app.models import ShippingInventoryPreparationAttempt
|
||||
from app.models import ShippingOnhandPreparationAttempt
|
||||
|
||||
preparation_task_id = getattr(order_task, 'id', None) if order_task is not None else getattr(notice, 'order_task_id', None)
|
||||
preparation = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
ShippingOnhandPreparationAttempt.query
|
||||
.filter_by(task_id=int(preparation_task_id))
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||||
.filter(ShippingOnhandPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else []
|
||||
@@ -2113,7 +2113,7 @@ def _project_order_task_work_item(
|
||||
'attempt_no': int(preparation.attempt_no),
|
||||
'status': row.status,
|
||||
'rpa_attempt_id': row.rpa_attempt_id,
|
||||
'inventory_file_id': row.inventory_file_id,
|
||||
'inventory_file_id': row.onhand_file_id,
|
||||
}
|
||||
for row in source_attempts
|
||||
}
|
||||
@@ -2137,7 +2137,7 @@ def _project_order_task_work_item(
|
||||
# PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用
|
||||
# fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。
|
||||
payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task)
|
||||
payload['inventory_preparation'] = inventory_preparation
|
||||
payload['onhand_preparation'] = inventory_preparation
|
||||
|
||||
# pre_ot_stp 是内部责任阶段,不是会话时间线展示枚举;最终输出统一为正式建单节点。
|
||||
if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp':
|
||||
@@ -3330,8 +3330,8 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -
|
||||
# 空 Candidate Case 的同一入口用于解析处置;不得借动作码跳到订单复核。
|
||||
return 'order_review' if lifecycle_stage == 'order_review' else 'intake_parse'
|
||||
if code in {
|
||||
'open_inventory_match_review', 'match_inventory', 'rematch', 'open_shortage_review',
|
||||
'upload_inventory_file', 'retry_inventory_preparation', 'regenerate_excel', 'generate_excel',
|
||||
'open_onhand_match_review', 'match_inventory', 'rematch', 'open_shortage_review',
|
||||
'upload_onhand_file', 'retry_onhand_preparation', 'regenerate_excel', 'generate_excel',
|
||||
}:
|
||||
return 'fulfillment_prep'
|
||||
if code in {
|
||||
|
||||
@@ -14,7 +14,7 @@ import logging
|
||||
|
||||
from flask import current_app
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt
|
||||
from app.models import ShippingOrderTask, FreightRpaOnhandTaskAttempt
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -67,8 +67,8 @@ def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int:
|
||||
"""
|
||||
task_nos = [
|
||||
str(row[0])
|
||||
for row in db.session.query(ShippingTaskInventoryRpaAttempt.task_no)
|
||||
.filter(ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')))
|
||||
for row in db.session.query(FreightRpaOnhandTaskAttempt.task_no)
|
||||
.filter(FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')))
|
||||
.distinct()
|
||||
.all()
|
||||
]
|
||||
|
||||
@@ -364,7 +364,7 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
|
||||
将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。
|
||||
|
||||
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
|
||||
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
|
||||
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → onhand_fetching 等)。
|
||||
|
||||
Args:
|
||||
task: 待更新的 ShippingNotice 实例(尚未 commit)。
|
||||
|
||||
+19
-19
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/stp_line_inventory_match.py
|
||||
services/shipping_notice/stp_line_onhand_match.py
|
||||
|
||||
用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。
|
||||
依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、
|
||||
inventory_source_rules、ShippingOrderSnapshot。
|
||||
逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制
|
||||
依赖:stp_onhand_freeze、reservation_id、onhand_snapshot_store、onhand_source_repository、
|
||||
onhand_source_rules、ShippingOrderSnapshot。
|
||||
逻辑:ensure_onhand 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制
|
||||
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
|
||||
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
|
||||
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
|
||||
@@ -18,21 +18,21 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingNotice
|
||||
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,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
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
|
||||
|
||||
|
||||
def _norm_part(value: Any) -> str:
|
||||
@@ -142,7 +142,7 @@ def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> st
|
||||
return validated_reservation_id(header_values.get('reservation_id'))
|
||||
|
||||
|
||||
def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
def prepare_candidate_onhand_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。
|
||||
|
||||
@@ -156,8 +156,8 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
Returns:
|
||||
status / lines / missing_source_codes / loaded_source_codes / evidence。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
|
||||
from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines
|
||||
from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot
|
||||
|
||||
current_set = get_active_candidate_set(task)
|
||||
if current_set is None:
|
||||
@@ -174,7 +174,7 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
candidate_lines = get_active_candidate_lines(task)
|
||||
task_level_codes = list(task_frozen_inventory_source_codes(task))
|
||||
task_level_codes = list(task_frozen_onhand_source_codes(task))
|
||||
required_codes: list[str] = []
|
||||
for line in candidate_lines:
|
||||
for raw in list(getattr(line, 'source_codes_json', None) or []):
|
||||
@@ -225,21 +225,21 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
evidence.append({
|
||||
'source_code': code,
|
||||
'status': 'snapshot_empty',
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
'inventory_file_no': snapshot.onhand_file_no,
|
||||
'required': in_required,
|
||||
})
|
||||
continue
|
||||
for row in lines:
|
||||
tagged = dict(row)
|
||||
tagged['__source_code'] = code
|
||||
tagged['__inventory_file_no'] = snapshot.inventory_file_no
|
||||
tagged['__inventory_file_no'] = snapshot.onhand_file_no
|
||||
merged.append(tagged)
|
||||
loaded.append(code)
|
||||
evidence.append({
|
||||
'source_code': code,
|
||||
'status': 'loaded',
|
||||
'candidate_set_id': int(current_set.id),
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
'inventory_file_no': snapshot.onhand_file_no,
|
||||
'line_count': len(lines),
|
||||
'required': in_required,
|
||||
})
|
||||
@@ -540,7 +540,7 @@ def match_order_lines_across_candidates(
|
||||
}
|
||||
|
||||
|
||||
def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None:
|
||||
def apply_line_onhand_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None:
|
||||
"""
|
||||
将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。
|
||||
"""
|
||||
@@ -556,10 +556,10 @@ def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]:
|
||||
candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用
|
||||
库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
load_current_match_facts_by_task,
|
||||
)
|
||||
codes: list[str] = []
|
||||
@@ -603,7 +603,7 @@ def apply_forced_match_source_filter(
|
||||
过滤后的库存行;无强制源时原样返回。
|
||||
"""
|
||||
if task.__class__.__name__ == 'ShippingOrderTask':
|
||||
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
|
||||
selected = set()
|
||||
for row in get_active_candidate_lines(task):
|
||||
selected.update(str(code or '').strip().upper() for code in (getattr(row, 'source_codes_json', None) or []) if str(code or '').strip())
|
||||
+9
-9
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/stp_inventory_freeze.py
|
||||
services/shipping_notice/stp_onhand_freeze.py
|
||||
|
||||
用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。
|
||||
依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。
|
||||
依赖:onhand_source_gate、onhand_source_repository、onhand_source_rules、tool_common。
|
||||
逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved;
|
||||
多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review);
|
||||
冻结结果写入 ShippingTaskEvent(candidates_frozen / inventory_source_resolved_at_build)。
|
||||
@@ -13,18 +13,18 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import (
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import (
|
||||
freeze_candidates_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
get_active_candidate_sources,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
from app.services.shipping_notice.onhand_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
_candidate,
|
||||
compute_routing_fingerprint,
|
||||
@@ -56,7 +56,7 @@ def collect_frozen_candidate_codes(line_projections: list[dict[str, Any]] | None
|
||||
return codes
|
||||
|
||||
|
||||
def freeze_stp_inventory_candidates_on_task(
|
||||
def freeze_stp_onhand_candidates_on_task(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
line_projections: list[dict[str, Any]] | None,
|
||||
@@ -183,7 +183,7 @@ def freeze_stp_inventory_candidates_on_task(
|
||||
return adjudication
|
||||
|
||||
|
||||
def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]:
|
||||
def task_frozen_onhand_source_codes(task: ShippingNotice) -> list[str]:
|
||||
"""
|
||||
读取任务上冻结的候选库存源(单源任务则回退 inventory_source_code)。
|
||||
|
||||
@@ -103,7 +103,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
).strip().lower()
|
||||
direct_match_status = getattr(task, 'match_status', None)
|
||||
if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask':
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values())
|
||||
match_status = 'matched' if match_facts and all(
|
||||
@@ -112,7 +112,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
for row in match_facts
|
||||
) else ('shortage' if match_facts else '')
|
||||
elif direct_match_status is None:
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower()
|
||||
else:
|
||||
match_status = str(direct_match_status or '').strip().lower()
|
||||
@@ -128,7 +128,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
artifact = latest_export_artifact(task)
|
||||
has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip())
|
||||
projected_upload = project_notice_upload_status(task)
|
||||
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
|
||||
progress_state = (
|
||||
'uploaded' if projected_upload == 'uploaded' else
|
||||
'upload_failed' if projected_upload == 'failed' else
|
||||
|
||||
@@ -93,7 +93,7 @@ def _target_is_safe(task: ShippingNotice) -> bool:
|
||||
|
||||
if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ:
|
||||
return False
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
current_inventory_matches_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
)
|
||||
|
||||
@@ -25,9 +25,9 @@ from app.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
ShippingTaskPurgeAudit,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
)
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
|
||||
@@ -307,8 +307,8 @@ def move_task_to_recycle_bin(
|
||||
).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first()
|
||||
)
|
||||
or getattr(owner_task, 'candidate_id', None)
|
||||
or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first())
|
||||
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first()
|
||||
or bool(db.session.query(ShippingNoticeLineOnhandMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first())
|
||||
or db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(owner_task.id)).first()
|
||||
or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first()
|
||||
or (
|
||||
isinstance(task, ShippingNotice)
|
||||
@@ -442,11 +442,11 @@ def purge_task_permanently(
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
blocking_counts = {
|
||||
'current_order_extraction': int(bool(task.current_order_extraction_id)),
|
||||
'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(),
|
||||
'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(),
|
||||
}
|
||||
blocking = {key: value for key, value in blocking_counts.items() if value}
|
||||
@@ -465,7 +465,7 @@ def purge_task_permanently(
|
||||
))
|
||||
return
|
||||
|
||||
from app.models import ShippingTemporaryInventorySession
|
||||
from app.models import ShippingTemporaryOnhandSession
|
||||
|
||||
# [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。
|
||||
owner = task if hasattr(task, 'current_order_extraction_id') else None
|
||||
@@ -481,19 +481,19 @@ def purge_task_permanently(
|
||||
'source_intake': int(bool(task.source_intake_id)),
|
||||
'source_candidate': int(bool(task.source_candidate_id)),
|
||||
'current_order_extraction': int(bool(task.current_order_extraction_id)),
|
||||
'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'successor': int(_has_successor(task)),
|
||||
'duplicate_link': int(bool(task.duplicate_source_task_id)),
|
||||
'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter(
|
||||
ShippingNotice.duplicate_source_task_id == int(task.id),
|
||||
).count(),
|
||||
'external_upload_fact': int(_has_external_fulfillment(task)),
|
||||
'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'export_artifact': db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).count(),
|
||||
'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(),
|
||||
'temporary_inventory_session': db.session.query(ShippingTemporaryInventorySession.id).filter_by(task_id=int(task.id)).count(),
|
||||
'temporary_inventory_session': db.session.query(ShippingTemporaryOnhandSession.id).filter_by(task_id=int(task.id)).count(),
|
||||
'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(),
|
||||
'non_disposition_event': db.session.query(ShippingTaskEvent.id).filter(
|
||||
ShippingTaskEvent.task_id == int(task.id),
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_field_gate.py
|
||||
|
||||
用途:未解决订单字段冲突门禁,阻断库存/匹配/导出下游副作用。
|
||||
依赖:task_field_conflict_service、i18n、tool_response、query_service.serialize_task_for_tool。
|
||||
逻辑:inventory_workflow / inventory_rpa_workflow / fulfillment_workflow 在副作用前调用。
|
||||
逻辑:onhand_workflow / onhand_rpa_workflow / fulfillment_workflow 在副作用前调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,7 +45,7 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.onhand_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
acquire_notice_create_locks,
|
||||
assert_no_exact_duplicate_notices,
|
||||
@@ -65,7 +65,7 @@ from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent
|
||||
|
||||
def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool:
|
||||
"""读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。"""
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
return has_ready_inventory_file_for_task(task)
|
||||
|
||||
@@ -352,8 +352,8 @@ def _apply_notice_edit_change_effects(
|
||||
按 Schema change_effect 选择性失效下游;无 legacy 全量 reset。
|
||||
|
||||
核心逻辑:
|
||||
rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT inventory_source_resolving;
|
||||
rerun_inventory_matching → 清匹配/导出、OT inventory_matching;
|
||||
rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT onhand_source_resolving;
|
||||
rerun_inventory_matching → 清匹配/导出、OT onhand_matching;
|
||||
regenerate_excel → 仅清导出、OT excel_generating;
|
||||
require_revision → 全量下游 reset;
|
||||
none → 跳过重型 reset(Excel 冻结由 assert_formal_task_not_excel_frozen 拦截)。
|
||||
@@ -368,7 +368,7 @@ def _apply_notice_edit_change_effects(
|
||||
"""
|
||||
from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
adjudicate_and_apply_inventory_source,
|
||||
clear_inventory_source_confirmation,
|
||||
)
|
||||
@@ -394,23 +394,23 @@ def _apply_notice_edit_change_effects(
|
||||
if 'rerun_inventory_source_resolution' in effects:
|
||||
clear_inventory_source_confirmation(task)
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_source_resolving')
|
||||
_set_notice_invalidated_from_stage(task, 'onhand_source_resolving')
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable
|
||||
|
||||
stable = is_inventory_source_stable(task)
|
||||
if order_task is not None:
|
||||
if stable:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
stage='onhand_fetching',
|
||||
status='processing',
|
||||
)
|
||||
_clear_notice_invalidated_from_stage(task)
|
||||
else:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_source_resolving',
|
||||
stage='onhand_source_resolving',
|
||||
status='blocked',
|
||||
)
|
||||
applied.add('rerun_inventory_source_resolution')
|
||||
@@ -418,11 +418,11 @@ def _apply_notice_edit_change_effects(
|
||||
|
||||
if 'rerun_inventory_matching' in effects:
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_matching')
|
||||
_set_notice_invalidated_from_stage(task, 'onhand_matching')
|
||||
if order_task is not None:
|
||||
sync_order_task_processing_state(
|
||||
order_task,
|
||||
stage='inventory_matching',
|
||||
stage='onhand_matching',
|
||||
status='processing',
|
||||
)
|
||||
applied.add('rerun_inventory_matching')
|
||||
@@ -881,7 +881,7 @@ def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) ->
|
||||
"""
|
||||
if order_task is None:
|
||||
return None
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task
|
||||
|
||||
facts = list(load_current_match_facts_by_task(order_task.id).values())
|
||||
if not facts:
|
||||
|
||||
@@ -3,8 +3,8 @@ services/shipping_notice/tool_common.py
|
||||
|
||||
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
|
||||
log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
|
||||
逻辑:task_workflow / onhand_workflow / fulfillment_workflow / decision_workflow 共用;
|
||||
log_task_event 对 onhand_rpa_/inventory_source_/export_/notice_replace/
|
||||
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
|
||||
另提供 generic/XFA/LLM 等主链灰度开关读取。
|
||||
"""
|
||||
@@ -76,9 +76,9 @@ def auto_progress_enabled() -> bool:
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
|
||||
|
||||
|
||||
def auto_rpa_inventory_enabled() -> bool:
|
||||
"""是否允许自动触发 RPA 导出库存。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True)
|
||||
def auto_rpa_onhand_enabled() -> bool:
|
||||
"""是否允许自动触发 RPA 导出在手库存(SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED)。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED", True)
|
||||
|
||||
|
||||
def rpa_inventory_timeout_seconds() -> int:
|
||||
@@ -236,7 +236,7 @@ def set_task_step_progress(
|
||||
stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。
|
||||
|
||||
Args:
|
||||
stage: 15 阶契约码(如 inventory_fetching / inventory_matching /
|
||||
stage: 15 阶契约码(如 onhand_fetching / onhand_matching /
|
||||
excel_generating / freight_uploading);禁止传入 CheckPoint 时代
|
||||
stepN_* 遗留键(已全部清除)。
|
||||
step_title: 展示用步骤名。
|
||||
@@ -404,7 +404,7 @@ def log_task_event(
|
||||
|
||||
event_name = str(event_type or '')
|
||||
dual_write = event_name.startswith((
|
||||
'inventory_rpa_',
|
||||
'onhand_rpa_',
|
||||
'inventory_source_',
|
||||
'export_',
|
||||
'notice_replace',
|
||||
@@ -512,11 +512,11 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -
|
||||
name = str(event_type or '').strip()
|
||||
err_blob = f"{detail.get('error') or ''} {detail.get('error_code') or ''}".lower()
|
||||
mapping = {
|
||||
'inventory_rpa_queued': 'inventory_rpa_queued',
|
||||
'inventory_rpa_started': 'inventory_rpa_queued',
|
||||
'inventory_rpa_timeout': 'inventory_rpa_timeout',
|
||||
'inventory_rpa_exhausted': 'inventory_rpa_exhausted',
|
||||
'inventory_rpa_failed': 'inventory_rpa_export_failed',
|
||||
'onhand_rpa_queued': 'onhand_rpa_queued',
|
||||
'onhand_rpa_started': 'onhand_rpa_queued',
|
||||
'onhand_rpa_timeout': 'onhand_rpa_timeout',
|
||||
'onhand_rpa_exhausted': 'onhand_rpa_exhausted',
|
||||
'onhand_rpa_failed': 'onhand_rpa_export_failed',
|
||||
'notice_replaced': 'attachment_replaced',
|
||||
'notice_replace_extract_failed': 'document_text_unavailable',
|
||||
'freight_cancellation_completed': 'task_voided_for_correction',
|
||||
@@ -528,14 +528,14 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -
|
||||
}
|
||||
if name in mapping:
|
||||
code = mapping[name]
|
||||
if name == 'inventory_rpa_failed':
|
||||
if name == 'onhand_rpa_failed':
|
||||
if 'timeout' in err_blob or ('not ready' in err_blob and 'within' in err_blob):
|
||||
return 'inventory_rpa_timeout'
|
||||
return 'onhand_rpa_timeout'
|
||||
if 'login' in err_blob or 'auth' in err_blob:
|
||||
return 'inventory_rpa_login_failed'
|
||||
return 'onhand_rpa_login_failed'
|
||||
if 'export' in err_blob:
|
||||
return 'inventory_rpa_export_failed'
|
||||
return 'inventory_rpa_export_failed'
|
||||
return 'onhand_rpa_export_failed'
|
||||
return 'onhand_rpa_export_failed'
|
||||
if name == 'notice_replace_extract_failed':
|
||||
from app.services.shipping_notice.error_explainability_contract import (
|
||||
primary_attachment_reason_from_warnings,
|
||||
@@ -545,8 +545,8 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -
|
||||
)
|
||||
return from_warnings or code
|
||||
return code
|
||||
if name.startswith('inventory_rpa_') and name.endswith('_failed'):
|
||||
return 'inventory_rpa_export_failed'
|
||||
if name.startswith('onhand_rpa_') and name.endswith('_failed'):
|
||||
return 'onhand_rpa_export_failed'
|
||||
if name.startswith('upload_rpa') and 'fail' in name:
|
||||
return 'upload_rpa_failed'
|
||||
return None
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/tool_response.py
|
||||
|
||||
用途:统一构建发货通知 Tool 的 JSON 响应结构。
|
||||
依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。
|
||||
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
|
||||
逻辑:由 task_workflow、onhand_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
|
||||
已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。
|
||||
"""
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/tools.py
|
||||
|
||||
用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。
|
||||
依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow。
|
||||
依赖:customer_identity_gate、task_workflow、onhand_workflow、onhand_rpa_workflow、fulfillment_workflow。
|
||||
逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。
|
||||
"""
|
||||
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice import (
|
||||
fulfillment_workflow,
|
||||
inventory_rpa_workflow,
|
||||
inventory_workflow,
|
||||
onhand_rpa_workflow,
|
||||
onhand_workflow,
|
||||
task_workflow,
|
||||
)
|
||||
from app.services.shipping_notice import customer_identity_gate
|
||||
@@ -29,37 +29,37 @@ remove_notice_line = task_workflow.remove_notice_line
|
||||
confirm_customer = customer_identity_gate.confirm_customer
|
||||
|
||||
# 库存阶段
|
||||
ensure_inventory = inventory_workflow.ensure_inventory
|
||||
upload_inventory_file = inventory_workflow.upload_inventory_file
|
||||
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
|
||||
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
|
||||
repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
|
||||
ensure_inventory = onhand_workflow.ensure_inventory
|
||||
upload_inventory_file = onhand_workflow.upload_inventory_file
|
||||
rpa_report_inventory = onhand_rpa_workflow.rpa_report_inventory
|
||||
rpa_report_inventory_batch = onhand_rpa_workflow.rpa_report_inventory_batch
|
||||
repair_task_inventory_attachment = onhand_rpa_workflow.repair_task_inventory_attachment
|
||||
|
||||
|
||||
def create_temporary_inventory_session(payload: dict):
|
||||
"""创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create
|
||||
from app.services.shipping_notice.onhand_temporary_session import create_temporary_inventory_session as _create
|
||||
|
||||
return _create(payload)
|
||||
|
||||
|
||||
def get_temporary_inventory_session(payload: dict):
|
||||
"""读取临时库存候选会话的脱敏结构预览;仅供 Dify 固定分支调用。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import get_temporary_inventory_session as _get
|
||||
from app.services.shipping_notice.onhand_temporary_session import get_temporary_inventory_session as _get
|
||||
|
||||
return _get(payload)
|
||||
|
||||
|
||||
def submit_temporary_inventory_mapping_suggestion(payload: dict):
|
||||
"""保存 Dify 临时库存映射候选;后端校验后仍须由用户确认。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit
|
||||
from app.services.shipping_notice.onhand_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit
|
||||
|
||||
return _submit(payload)
|
||||
|
||||
|
||||
def confirm_temporary_inventory_use(payload: dict):
|
||||
"""确认当前会话临时库存使用并执行后端确定性质量校验。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import confirm_temporary_inventory_use as _confirm
|
||||
from app.services.shipping_notice.onhand_temporary_session import confirm_temporary_inventory_use as _confirm
|
||||
|
||||
return _confirm(payload)
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ services/shipping_notice/ui_state.py
|
||||
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、
|
||||
query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、
|
||||
process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、
|
||||
process_gate_projection、line_onhand_match_projection、onhand_candidate_projection、
|
||||
order_review_fulfillment_decision_service(短缺放行模板字段)、
|
||||
order_review_workbench_projection、inventory_source_repository(preparation.source_options)。
|
||||
order_review_workbench_projection、onhand_source_repository(preparation.source_options)。
|
||||
逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode);
|
||||
Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id);
|
||||
五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列),
|
||||
@@ -56,7 +56,7 @@ from app.services.shipping_notice.constants import (
|
||||
RS_PARSE_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGES,
|
||||
project_lifecycle,
|
||||
@@ -90,7 +90,7 @@ _REVIEW_ENTRY_POSITIONS = {
|
||||
}
|
||||
|
||||
_NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = {
|
||||
POSITION_INVENTORY_PENDING: "ensure_inventory",
|
||||
POSITION_INVENTORY_PENDING: "ensure_onhand",
|
||||
POSITION_ORDER_FREEZE: "freeze_order",
|
||||
POSITION_READY_MATCH: "match_inventory",
|
||||
POSITION_READY_EXPORT: "generate_excel",
|
||||
@@ -407,12 +407,12 @@ def _derived_entry_surface(
|
||||
if user_mode in {'must_human', 'wait_manual_upload'}:
|
||||
return 'task_workbench'
|
||||
if code in {
|
||||
'inventory_preparation',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'onhand_preparation',
|
||||
'onhand_matching',
|
||||
'onhand_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'order_freeze_readiness',
|
||||
}:
|
||||
return 'task_workbench'
|
||||
@@ -467,11 +467,11 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
)
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
from app.services.shipping_notice.stp_line_onhand_match import multi_source_recovery_source_codes
|
||||
from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS
|
||||
|
||||
owner = task
|
||||
@@ -488,7 +488,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
)
|
||||
status = 'candidates_frozen' if candidate_projection.get('current_set') else ''
|
||||
method = 'candidate_set' if candidate_projection.get('current_set') else ''
|
||||
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(owner)
|
||||
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_onhand_source_codes(owner)
|
||||
has_stp = (
|
||||
status in {'candidates_frozen', 'resolved'}
|
||||
or method.startswith('stp')
|
||||
@@ -503,7 +503,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
compact_resolutions: list[dict[str, Any]] = []
|
||||
resolution_source = list(candidate_projection.get('line_resolutions') or [])
|
||||
if not resolution_source and getattr(owner, 'id', None) is not None:
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
from app.models import ShippingNoticeLineOnhandMatch
|
||||
|
||||
resolution_source = [{
|
||||
'line_index': row.line_index,
|
||||
@@ -511,7 +511,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
'disposition': row.match_result,
|
||||
'effective_reservation_id': row.reservation_id,
|
||||
'part_number': row.part_number,
|
||||
'resolved_inventory_source_code': row.inventory_source_code,
|
||||
'resolved_inventory_source_code': row.source_code,
|
||||
'inventory_file_no': row.matched_file_no,
|
||||
'inventory_row_index': row.matched_row_index,
|
||||
'match_attempt_id': row.match_attempt_id,
|
||||
@@ -519,9 +519,9 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
'matched_qty': row.matched_qty or row.available_qty,
|
||||
'shortage_qty': row.shortage_qty,
|
||||
'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'),
|
||||
} for row in ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
} for row in ShippingNoticeLineOnhandMatch.query.filter_by(
|
||||
task_id=int(owner.id), is_current=True,
|
||||
).order_by(ShippingNoticeLineInventoryMatch.line_no, ShippingNoticeLineInventoryMatch.id).all()]
|
||||
).order_by(ShippingNoticeLineOnhandMatch.line_no, ShippingNoticeLineOnhandMatch.id).all()]
|
||||
for item in resolution_source:
|
||||
disposition = str(item.get('disposition') or 'unknown')
|
||||
counts[disposition] = counts.get(disposition, 0) + 1
|
||||
@@ -778,19 +778,19 @@ def _stage_capabilities_for_task(
|
||||
}
|
||||
if source_locked:
|
||||
cap.update(disabled('excel_locked'))
|
||||
elif code == 'retry_inventory_preparation':
|
||||
elif code == 'retry_onhand_preparation':
|
||||
# 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。
|
||||
retry_available = has_candidates or bool(failed_codes)
|
||||
cap['enabled'] = retry_available
|
||||
cap['disabled_reason'] = None if retry_available else 'no_candidates'
|
||||
elif code == 'override_line_inventory_source':
|
||||
elif code == 'override_line_onhand_source':
|
||||
cap['enabled'] = has_candidates
|
||||
cap['disabled_reason'] = None if has_candidates else 'no_candidates'
|
||||
elif code == 'reload_inventory_result':
|
||||
elif code == 'reload_onhand_result':
|
||||
has_prior = bool(resolved_codes)
|
||||
cap['enabled'] = has_prior
|
||||
cap['disabled_reason'] = None if has_prior else 'no_prior_result'
|
||||
elif code == 'retry_inventory_matching':
|
||||
elif code == 'retry_onhand_matching':
|
||||
cap['enabled'] = has_match_result
|
||||
cap['disabled_reason'] = None if has_match_result else 'no_match_result'
|
||||
result.append(cap)
|
||||
@@ -814,15 +814,15 @@ def _build_stage_context(
|
||||
preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉;
|
||||
preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染);
|
||||
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询;
|
||||
inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。
|
||||
onhand_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
|
||||
from app.models.shipping_excel_template import ShippingExportArtifact
|
||||
from app.models.shipping_fulfillment import ShippingUploadAttempt
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
inventory_rpa_is_running,
|
||||
load_current_match_facts_by_task,
|
||||
project_line_inventory_view,
|
||||
@@ -1014,27 +1014,27 @@ def _build_stage_context(
|
||||
inventory_sources: list[dict[str, Any]] = []
|
||||
latest_preparation = None
|
||||
if getattr(order_task, 'id', None):
|
||||
from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt
|
||||
from app.models.shipping_onhand_preparation import ShippingOnhandPreparationAttempt
|
||||
|
||||
latest_preparation = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
ShippingOnhandPreparationAttempt.query
|
||||
.filter_by(task_id=int(order_task.id))
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||||
.filter(ShippingOnhandPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
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
|
||||
|
||||
downloadable_inventory = resolve_task_inventory_download(order_task)
|
||||
for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []):
|
||||
inventory_sources.append({
|
||||
'source_code': source_attempt.source_code,
|
||||
'status': source_attempt.status,
|
||||
'inventory_file_id': source_attempt.inventory_file_id,
|
||||
'inventory_file_id': source_attempt.onhand_file_id,
|
||||
})
|
||||
|
||||
# [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。
|
||||
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
|
||||
|
||||
source_options = [
|
||||
{
|
||||
@@ -1352,7 +1352,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
|
||||
|
||||
核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读
|
||||
active_process_execution_id,回退按 OT.id 取最新非 superseded Execution;
|
||||
套用 apply_post_ot_gate_rules,使 inventory_preparation 等系统等待
|
||||
套用 apply_post_ot_gate_rules,使 onhand_preparation 等系统等待
|
||||
不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。
|
||||
同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。
|
||||
|
||||
|
||||
@@ -336,7 +336,7 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
|
||||
Returns:
|
||||
True 表示已进入 matched 或更后阶段。
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task
|
||||
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
match_status = aggregate_match_status_for_task(match_task_id) or ''
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
|
||||
|
||||
Reference in new issue
Block a user