refactor(shipping-inventory): 统一库存准备事实来源与门禁状态
This commit is contained in:
1 parent
761a06e21a
commit
eb55f407ae
62 files changed
+4242
-1471
No files matched your search
@@ -19,6 +19,7 @@ from app.models import (
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingReceiptReportConfig,
|
||||
@@ -497,7 +498,11 @@ def delete_source(source_id: int) -> None:
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_task = db.session.query(ShippingNoticeLine.id).filter(
|
||||
ShippingNoticeLine.inventory_source_code == source_code,
|
||||
).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter(
|
||||
ShippingNoticeLineInventoryMatch.inventory_source_code == source_code,
|
||||
).first() is not None
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -193,7 +193,7 @@ def _collect_order_line_candidates(
|
||||
line_codes = list(task_level_source_codes_ordered)
|
||||
|
||||
line_projections.append({
|
||||
'line_key': f'{task.id}:{line_no}',
|
||||
# 该阶段只产生候选投影;冻结档建立后由 snapshot_line_id 作为唯一行身份。
|
||||
'line_index': idx,
|
||||
'line_no': line_no,
|
||||
'source_line_no': source_line_no,
|
||||
@@ -276,19 +276,13 @@ def _invalidate_task_candidate_outputs(
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
task.upload_status = None
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload.pop('line_inventory_resolutions', None)
|
||||
payload.pop('resolved_ok_source_codes', None)
|
||||
payload.pop('excel_binding_source_code', None)
|
||||
payload.pop('multi_source_excel_block', None)
|
||||
task.step_payload_json = payload
|
||||
if task.__class__.__name__ != 'ShippingOrderTask':
|
||||
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)
|
||||
@@ -306,12 +300,18 @@ def _invalidate_task_candidate_outputs(
|
||||
)
|
||||
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
|
||||
)
|
||||
artifact_ids = [
|
||||
row[0] for row in session.query(ShippingExportArtifact.id).filter(
|
||||
ShippingExportArtifact.task_id == int(task.id),
|
||||
ShippingExportArtifact.status.in_(('ready', 'uploading')),
|
||||
notice_ids = [
|
||||
int(row.id)
|
||||
for row in session.query(ShippingNotice.id).filter(
|
||||
ShippingNotice.order_task_id == int(task.id),
|
||||
).all()
|
||||
]
|
||||
artifact_ids = [
|
||||
row[0] for row in session.query(ShippingExportArtifact.id).filter(
|
||||
ShippingExportArtifact.task_id.in_(notice_ids),
|
||||
ShippingExportArtifact.status.in_(('ready', 'uploading')),
|
||||
).all()
|
||||
] if notice_ids else []
|
||||
if artifact_ids:
|
||||
session.query(ShippingExportArtifact).filter(
|
||||
ShippingExportArtifact.id.in_(artifact_ids),
|
||||
@@ -358,6 +358,7 @@ def freeze_candidates_for_task(
|
||||
execution_id: int | None = None,
|
||||
frozen_by_id: int | None = None,
|
||||
line_projections: list[dict[str, Any]] | None = None,
|
||||
preserve_empty_line_candidates: bool = False,
|
||||
session: Session | None = None,
|
||||
) -> CandidateFreezeResult:
|
||||
"""
|
||||
@@ -370,7 +371,6 @@ def freeze_candidates_for_task(
|
||||
[STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。
|
||||
[STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。
|
||||
[STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。
|
||||
[STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。
|
||||
|
||||
Args:
|
||||
task: 已 flush 的 ShippingNotice(有 id 字段)。
|
||||
@@ -380,6 +380,8 @@ def freeze_candidates_for_task(
|
||||
execution_id: 可选的 ProcessExecution 绑定 ID。
|
||||
frozen_by_id: 人工覆盖冻结时的操作人 ID。
|
||||
line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。
|
||||
preserve_empty_line_candidates: 仅人工逐项选源时为 True;保留尚未选择源的
|
||||
Snapshot 行为空列表,使 Gate 能继续阻断而不会误触发整单库存准备。
|
||||
session: 可选的 SQLAlchemy Session(缺省用 db.session)。
|
||||
|
||||
Returns:
|
||||
@@ -421,18 +423,14 @@ def freeze_candidates_for_task(
|
||||
continue
|
||||
codes_raw = item.get('candidate_inventory_source_codes') or []
|
||||
codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()]
|
||||
if not codes:
|
||||
if not codes and not preserve_empty_line_candidates:
|
||||
codes = list(task_source_codes_ordered)
|
||||
line_index = item.get('line_index')
|
||||
try:
|
||||
line_no = int(item.get('line_no') or 0)
|
||||
except (TypeError, ValueError):
|
||||
line_no = 0
|
||||
if line_no <= 0:
|
||||
try:
|
||||
line_no = int(line_index) + 1
|
||||
except (TypeError, ValueError):
|
||||
line_no = len(signatures) + 1
|
||||
raise ValueError('候选行缺少持久化 line_no,禁止从 line_index 派生项次')
|
||||
signatures.append((
|
||||
line_no,
|
||||
str(item.get('source_line_no') or '').strip() or None,
|
||||
@@ -599,22 +597,22 @@ def freeze_candidates_for_task(
|
||||
|
||||
if getattr(task, 'id', None) is not None:
|
||||
task.active_inventory_candidate_set_id = int(new_set.id)
|
||||
# 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
supersede_auto_progress_for_candidate_refreeze,
|
||||
)
|
||||
# 人工逐项选源正由当前 GateAttempt 执行时,不能把它自己 supersede,
|
||||
# 否则选源已落库但 Attempt 无法完成。该 Execution 只更新候选版本,仍停在
|
||||
# routing Gate;所有项次选完后才进入库存准备。其他重冻结仍取消旧链。
|
||||
current_execution_id = getattr(task, 'active_process_execution_id', None)
|
||||
if execution_id is not None and int(current_execution_id or 0) == int(execution_id):
|
||||
from app.models import ShippingProcessExecution
|
||||
|
||||
supersede_auto_progress_for_candidate_refreeze(task)
|
||||
current_execution = session.get(ShippingProcessExecution, int(execution_id))
|
||||
if current_execution is not None:
|
||||
current_execution.candidate_set_id = int(new_set.id)
|
||||
else:
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
supersede_auto_progress_for_candidate_refreeze,
|
||||
)
|
||||
|
||||
# [STEP 5] 回填 task 字段(幂等覆盖)
|
||||
task.inventory_source_status = 'candidates_frozen'
|
||||
task.inventory_source_method = (
|
||||
'manual_override_freeze' if frozen_by_id is not None
|
||||
else (adjudication.method or 'rule_evaluation_freeze')
|
||||
)
|
||||
task.inventory_source_config_version = config_version
|
||||
task.inventory_routing_fingerprint = routing_fingerprint
|
||||
# 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节
|
||||
supersede_auto_progress_for_candidate_refreeze(task)
|
||||
|
||||
return CandidateFreezeResult(
|
||||
candidate_set_id=new_set.id,
|
||||
@@ -624,3 +622,204 @@ def freeze_candidates_for_task(
|
||||
manifest_snapshot_sha256=manifest_sha256,
|
||||
set_version=set_version,
|
||||
)
|
||||
|
||||
|
||||
def freeze_manual_line_source_selection(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
line_no: int,
|
||||
source_code: str,
|
||||
actor_id: int | None,
|
||||
reason: str | None,
|
||||
execution_id: int | None,
|
||||
session: Session | None = None,
|
||||
) -> tuple[CandidateFreezeResult, bool]:
|
||||
"""
|
||||
将通知准备的人工选源冻结为新的 CandidateSet 版本。
|
||||
|
||||
核心逻辑:以冻结 Snapshot 的全量 line_no 为骨架,继承当前候选行的选择后仅替换目标项次。
|
||||
没有自动候选时也会先创建全量 CandidateLine;未选源项保持空数组,只有每一项都有源时才返回
|
||||
``all_lines_selected=True``,调用方据此允许进入库存准备/RPA。
|
||||
|
||||
Args:
|
||||
task: 已冻结订单对应的 OT。
|
||||
line_no: 用户选择库存源的 Snapshot 项次,必须存在。
|
||||
source_code: 已启用库存源编码。
|
||||
actor_id: 操作人,用于候选源与候选行审计。
|
||||
reason: 人工选择原因。
|
||||
execution_id: 当前流程 Execution,用于绑定候选版本。
|
||||
session: 可选数据库会话。
|
||||
|
||||
Returns:
|
||||
(CandidateFreezeResult, all_lines_selected)。
|
||||
|
||||
Raises:
|
||||
ValueError: OT 未冻结 Snapshot 或项次不存在。
|
||||
"""
|
||||
session = session or db.session
|
||||
snapshot = (
|
||||
session.query(ShippingOrderSnapshot)
|
||||
.filter(ShippingOrderSnapshot.task_id == int(task.id))
|
||||
.one_or_none()
|
||||
)
|
||||
if snapshot is None:
|
||||
raise ValueError('人工选源前必须先冻结订单 Snapshot')
|
||||
|
||||
snapshot_lines = sorted(list(snapshot.lines or []), key=lambda row: int(row.line_no))
|
||||
wanted_line = int(line_no)
|
||||
if not any(int(row.line_no) == wanted_line for row in snapshot_lines):
|
||||
raise ValueError('未找到该订单项次')
|
||||
|
||||
active_set = (
|
||||
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
if task.active_inventory_candidate_set_id is not None else None
|
||||
)
|
||||
existing_codes = {
|
||||
int(row.line_no): [str(code).strip().upper() for code in (row.source_codes_json or []) if str(code).strip()]
|
||||
for row in (active_set.lines if active_set is not None else [])
|
||||
}
|
||||
line_projections: list[dict[str, Any]] = []
|
||||
for row in snapshot_lines:
|
||||
current_line_no = int(row.line_no)
|
||||
codes = [source_code] if current_line_no == wanted_line else existing_codes.get(current_line_no, [])
|
||||
line_projections.append({
|
||||
'line_no': current_line_no,
|
||||
'source_line_no': str(row.line_no),
|
||||
'part_number': row.part_number,
|
||||
'reservation_id': row.reservation_id,
|
||||
'candidate_inventory_source_codes': codes,
|
||||
})
|
||||
|
||||
source_codes = []
|
||||
for projection in line_projections:
|
||||
for code in projection['candidate_inventory_source_codes']:
|
||||
if code not in source_codes:
|
||||
source_codes.append(code)
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='manual',
|
||||
method='manual_line_selection',
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
|
||||
candidates=[{'source_code': code} for code in source_codes],
|
||||
evidence=[{'line_no': wanted_line, 'source_code': source_code, 'reason': reason or '人工指定库存源'}],
|
||||
reason='manual_line_selection',
|
||||
)
|
||||
result = freeze_candidates_for_task(
|
||||
task,
|
||||
adjudication=adjudication,
|
||||
execution_id=execution_id,
|
||||
frozen_by_id=actor_id,
|
||||
line_projections=line_projections,
|
||||
preserve_empty_line_candidates=True,
|
||||
session=session,
|
||||
)
|
||||
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
|
||||
|
||||
|
||||
def freeze_wave_notice_routing(
|
||||
notice: ShippingNotice,
|
||||
*,
|
||||
source_notice: ShippingNotice | None = None,
|
||||
) -> CandidateFreezeResult | None:
|
||||
"""
|
||||
按波次自身行重跑库存源路由并冻结候选集(设计 D8:波次不再继承首通知源)。
|
||||
|
||||
【AI 触发时机】建波次通知(post_ot_fulfillment_wave)且在写入波次 ShippingNoticeLine 后调用;
|
||||
仅当波次行需要独立路由(不同行可能不同仓)时使用。
|
||||
|
||||
核心逻辑:以订单级 header(field_id 值)+ 波次行 ShippingNoticeLine.field_values_json
|
||||
逐行调用 ``evaluate_inventory_source_rules_for_field_values(scope='line')`` 得到行级候选;
|
||||
以全波次行候选并集作为任务级候选集,调用 ``freeze_candidates_for_task`` 冻结 Set/Source/Line
|
||||
(候选快照已在本地,后续匹配不重复 RPA)。
|
||||
|
||||
Args:
|
||||
notice: 已 flush 且已写入波次行的波次通知。
|
||||
source_notice: 订单首个冻结通知(提供订单级 header 事实);缺省用 notice。
|
||||
|
||||
Returns:
|
||||
CandidateFreezeResult;无任何波次行候选时返回 None(交由无候选阻断,不冻结)。
|
||||
"""
|
||||
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 (
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
|
||||
src = source_notice or notice
|
||||
try:
|
||||
header, _full_lines = order_field_id_values(src)
|
||||
except ValueError:
|
||||
header = {}
|
||||
|
||||
wave_lines = (
|
||||
ShippingNoticeLine.query.filter_by(notice_id=int(notice.id)).order_by(ShippingNoticeLine.position).all()
|
||||
if getattr(notice, 'id', None) is not None
|
||||
else []
|
||||
)
|
||||
# [回退] 与首单路径一致(_collect_order_line_candidates):行级无规则命中时回退到订单级 task 候选集,
|
||||
# 避免波次行「一条规则都不命中」时被算成无候选而卡死。
|
||||
task_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header, scope='task',
|
||||
)
|
||||
task_source_codes = [str(c or '').strip().upper() for c in (getattr(task_result, 'source_codes', None) or []) if str(c or '').strip()]
|
||||
|
||||
line_projections: list[dict[str, Any]] = []
|
||||
task_codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for idx, line in enumerate(wave_lines):
|
||||
line_values = dict(getattr(line, 'field_values_json', None) or {})
|
||||
line_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header,
|
||||
line_field_values=line_values,
|
||||
scope='line',
|
||||
)
|
||||
resolved = str(getattr(line_result, 'status', '') or '') == 'resolved' and bool(getattr(line_result, 'source_codes', None))
|
||||
if resolved:
|
||||
codes = [str(c or '').strip().upper() for c in (getattr(line_result, 'source_codes', None) or []) if str(c or '').strip()]
|
||||
else:
|
||||
codes = list(task_source_codes)
|
||||
if not codes:
|
||||
codes = list(task_source_codes)
|
||||
for code in codes:
|
||||
if code not in seen:
|
||||
seen.add(code)
|
||||
task_codes.append(code)
|
||||
line_projections.append({
|
||||
'line_index': idx,
|
||||
'line_no': idx + 1,
|
||||
'source_line_no': str(getattr(line, 'line_no', None) or '').strip() or None,
|
||||
'part_number': str(getattr(line, 'part_number', None) or '').strip() or None,
|
||||
'reservation_id': str(getattr(line, 'reservation_id', None) or '').strip() or None,
|
||||
'candidate_inventory_source_codes': codes,
|
||||
'selection_mode': 'line_rule' if resolved else 'task_fallback',
|
||||
'routing_status': str(getattr(line_result, 'status', '') or ''),
|
||||
'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()),
|
||||
})
|
||||
|
||||
if not task_codes:
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
_candidate,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
|
||||
candidates = []
|
||||
for code in task_codes:
|
||||
src_cfg = get_database_inventory_source(code)
|
||||
if src_cfg:
|
||||
candidates.append(_candidate(src_cfg))
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='candidates_frozen',
|
||||
method='wave_line_routing',
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(notice)),
|
||||
candidates=candidates,
|
||||
)
|
||||
return freeze_candidates_for_task(
|
||||
notice,
|
||||
adjudication=adjudication,
|
||||
line_projections=line_projections,
|
||||
)
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/inventory_candidate_projection.py
|
||||
|
||||
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
|
||||
依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
|
||||
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
|
||||
ShippingTaskInventoryRpaAttempt。
|
||||
逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
|
||||
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
|
||||
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.models import (
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
@@ -55,7 +55,7 @@ def _normalized_codes(codes: list[Any] | None) -> list[str]:
|
||||
|
||||
|
||||
def _candidate_set_filter(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
include_drafts: bool = False,
|
||||
session: Session | None = None,
|
||||
@@ -83,14 +83,14 @@ def _candidate_set_filter(
|
||||
|
||||
|
||||
def get_active_candidate_set(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> ShippingInventoryCandidateSet | None:
|
||||
"""
|
||||
读取正式 Task 当前 frozen CandidateSet。
|
||||
|
||||
核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id;
|
||||
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
|
||||
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
|
||||
"""
|
||||
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
|
||||
@@ -107,7 +107,7 @@ def get_active_candidate_set(
|
||||
|
||||
|
||||
def get_active_candidate_sources(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateSource]:
|
||||
@@ -129,7 +129,7 @@ def get_active_candidate_sources(
|
||||
|
||||
|
||||
def get_active_candidate_lines(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> list[ShippingInventoryCandidateLine]:
|
||||
@@ -150,8 +150,51 @@ def get_active_candidate_lines(
|
||||
return list(rows)
|
||||
|
||||
|
||||
def active_inventory_runtime_facts(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取通知准备的当前运行事实,替代 OT 上的库存路由和快照投影列。
|
||||
|
||||
核心逻辑:库存源只读当前 CandidateSet/Source;库存文件只读 active Link;配置版本
|
||||
取 CandidateSource 的冻结版本,不能回读 Task 的可变历史字段。
|
||||
|
||||
Args:
|
||||
task: 当前订单任务。
|
||||
session: 可选数据库会话。
|
||||
|
||||
Returns:
|
||||
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
|
||||
"""
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
|
||||
sess = _session(session)
|
||||
candidate_set = get_active_candidate_set(task, session=sess)
|
||||
sources = get_active_candidate_sources(task, session=sess)
|
||||
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())
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
)
|
||||
return {
|
||||
'candidate_set': candidate_set,
|
||||
'candidate_set_id': getattr(candidate_set, 'id', None),
|
||||
'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': getattr(link, 'inventory_file', None),
|
||||
}
|
||||
|
||||
|
||||
def get_candidate_set_by_version(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
version: int,
|
||||
*,
|
||||
include_drafts: bool = False,
|
||||
@@ -271,7 +314,7 @@ def _candidate_lines_for_set(
|
||||
def build_inventory_candidate_blocking_reason(
|
||||
code: str,
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造统一 blocking_reason DTO。"""
|
||||
@@ -293,7 +336,7 @@ def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rule
|
||||
}
|
||||
|
||||
|
||||
def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
|
||||
def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
|
||||
"""查询任务下每个候选源的最新 Attempt 摘要。"""
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip()
|
||||
if not task_no or not source_codes:
|
||||
@@ -346,7 +389,7 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
|
||||
return prepared, pending, failed
|
||||
|
||||
|
||||
def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
"""读取任务当前生效的行级匹配事实。"""
|
||||
if getattr(task, 'id', None) is None:
|
||||
return []
|
||||
@@ -367,7 +410,7 @@ def _current_match_rows(task: ShippingNotice, *, session: Session | None = None)
|
||||
|
||||
|
||||
def project_inventory_candidate_detail(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
version: str | int = 'current',
|
||||
session: Session | None = None,
|
||||
@@ -426,7 +469,7 @@ def project_inventory_candidate_detail(
|
||||
|
||||
|
||||
def project_inventory_candidate_facts(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
include_history: bool = False,
|
||||
@@ -493,14 +536,20 @@ def project_inventory_candidate_facts(
|
||||
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
|
||||
serialized = {
|
||||
'id': int(row.id),
|
||||
'line_key': str(row.line_key or ''),
|
||||
'snapshot_line_id': int(row.snapshot_line_id),
|
||||
'line_no': int(row.line_no),
|
||||
'line_index': getattr(row, 'line_index', None),
|
||||
'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'),
|
||||
'candidate_set_id': getattr(row, 'candidate_set_id', None),
|
||||
'candidate_set_version': getattr(row, 'candidate_set_version', None),
|
||||
'candidate_line_id': getattr(row, 'candidate_line_id', None),
|
||||
'allowed_source_codes_snapshot': allowed_codes,
|
||||
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
|
||||
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
|
||||
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
|
||||
'resolved_inventory_source_code': (
|
||||
getattr(row, 'inventory_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_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
|
||||
|
||||
@@ -19,7 +19,15 @@ from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
@@ -29,10 +37,14 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
def _can_relink_inventory(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||||
return not has_verified_upload_success(task) \
|
||||
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
|
||||
|
||||
|
||||
@@ -130,10 +142,15 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
|
||||
|
||||
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
|
||||
"""读取任务当前 active link 指向的库存快照。"""
|
||||
if task.id is None:
|
||||
task_id = getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
link = (
|
||||
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
|
||||
ShippingTaskInventoryLink.query.filter_by(
|
||||
task_id=int(task_id),
|
||||
is_active=True,
|
||||
invalidated_at=None,
|
||||
)
|
||||
.order_by(ShippingTaskInventoryLink.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -162,24 +179,33 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] |
|
||||
return path, filename
|
||||
|
||||
|
||||
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
|
||||
cached_rows = [
|
||||
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
|
||||
]
|
||||
if cached_rows:
|
||||
return cached_rows, {'source': 'inventory_file_cache'}
|
||||
|
||||
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.line_count = len(rows)
|
||||
db.session.flush()
|
||||
return rows, column_meta
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
|
||||
"""读取任务活动库存文件的行事实;解析失败由调用方 Gate 转为可解释状态。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file and isinstance(inv_file.inventory_lines_json, list):
|
||||
rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
|
||||
if not rows and Path(inv_file.storage_path).is_file():
|
||||
try:
|
||||
reparsed, _meta = parse_inventory_snapshot_file(inv_file)
|
||||
if reparsed:
|
||||
inv_file.inventory_lines_json = reparsed
|
||||
inv_file.line_count = len(reparsed)
|
||||
db.session.flush()
|
||||
rows = reparsed
|
||||
except Exception: # noqa: BLE001
|
||||
# 解析失败时保留原快照,交由上层 Gate 报告可解释错误。
|
||||
pass
|
||||
if inv_file is None:
|
||||
return []
|
||||
try:
|
||||
rows, _column_meta = read_inventory_file_lines(inv_file)
|
||||
return rows
|
||||
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
except (OSError, ValueError, AppError):
|
||||
return []
|
||||
|
||||
|
||||
def resolve_inventory_lines_for_execution(
|
||||
@@ -195,7 +221,7 @@ def resolve_inventory_lines_for_execution(
|
||||
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
|
||||
|
||||
Returns:
|
||||
本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。
|
||||
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
|
||||
"""
|
||||
if active_inventory_file_for_task(task) is not None:
|
||||
return active_inventory_lines_for_task(task)
|
||||
@@ -203,7 +229,7 @@ def resolve_inventory_lines_for_execution(
|
||||
rows = [row for row in legacy_payload_lines if isinstance(row, dict)]
|
||||
if rows:
|
||||
return rows
|
||||
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
return []
|
||||
|
||||
|
||||
def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
|
||||
@@ -214,6 +240,60 @@ def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
|
||||
"""判断 OT 是否已绑定一份有效且已解析的库存文件。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
return bool(
|
||||
inv_file is not None
|
||||
and str(inv_file.snapshot_status or '').strip().lower() == 'ready'
|
||||
and inv_file.invalidated_at is None
|
||||
and int(inv_file.line_count or 0) > 0
|
||||
)
|
||||
|
||||
|
||||
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
"""读取 OT 当前有效的行级库存匹配事实。"""
|
||||
task_id = getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return []
|
||||
return ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task_id), is_current=True,
|
||||
).all()
|
||||
|
||||
|
||||
def inventory_matches_complete_for_task(task: ShippingNotice) -> bool:
|
||||
"""判断当前 Match 是否已覆盖冻结订单全部项次且不在准备中。"""
|
||||
task_id = getattr(task, 'id', None)
|
||||
snapshot_id = getattr(task, 'order_snapshot_id', None)
|
||||
if task_id is None or not snapshot_id:
|
||||
return False
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
|
||||
if snapshot is None or not snapshot.lines:
|
||||
return False
|
||||
matches = {
|
||||
int(row.snapshot_line_id): row
|
||||
for row in current_inventory_matches_for_task(task)
|
||||
if row.snapshot_line_id is not None
|
||||
}
|
||||
expected = {int(line.id) for line in snapshot.lines}
|
||||
return set(matches) == expected and all(
|
||||
str(row.match_result or '').strip().lower() != 'preparing'
|
||||
for row in matches.values()
|
||||
)
|
||||
|
||||
|
||||
def current_inventory_matches_have_shortage(task: ShippingNotice) -> bool:
|
||||
"""判断当前行级匹配中是否存在尚未满足的缺口或匹配失败。"""
|
||||
for row in current_inventory_matches_for_task(task):
|
||||
try:
|
||||
shortage = float(row.shortage_qty or 0)
|
||||
except (TypeError, ValueError):
|
||||
shortage = 0.0
|
||||
if str(row.match_result or '').strip().lower() != 'matched' or shortage > 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool:
|
||||
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
|
||||
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
|
||||
@@ -314,9 +394,11 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
|
||||
mapping_source='parsing_profile',
|
||||
mapping_confirmed=True,
|
||||
source_code=source_code,
|
||||
source_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
source_type=str(
|
||||
(get_database_inventory_source(source_code) or {}).get('connector_type') or ''
|
||||
).strip() or None,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
|
||||
source_config_version=inventory_sources_runtime_version(),
|
||||
source_query_json={'trigger_type': 'manual_upload'},
|
||||
identity_status="pending",
|
||||
snapshot_status="ready",
|
||||
@@ -442,7 +524,7 @@ def replace_task_inventory_link(
|
||||
db.session.add(new_link)
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
task_id=task_event_task_id(task),
|
||||
event_type="inventory_file_linked",
|
||||
detail_json={
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
@@ -524,8 +606,6 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
continue
|
||||
if not _can_relink_inventory(link.task):
|
||||
continue
|
||||
link.task.inventory_snapshot_id = inv_file.id
|
||||
link.task.inventory_lines_json = inventory_lines
|
||||
linked_tasks.append(link.task)
|
||||
return linked_tasks
|
||||
|
||||
@@ -569,7 +649,8 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
task = link.task
|
||||
if not link.is_active or not task:
|
||||
continue
|
||||
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||||
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,
|
||||
step_key="step5_match_inventory",
|
||||
|
||||
@@ -65,7 +65,7 @@ def inventory_loaded_response(
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
else:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
|
||||
|
||||
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
|
||||
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
|
||||
@@ -73,9 +73,6 @@ def inventory_loaded_response(
|
||||
for affected in [task, *linked_tasks]:
|
||||
if affected is None:
|
||||
continue
|
||||
affected.match_status = None
|
||||
affected.line_results_json = None
|
||||
affected.shortage_json = None
|
||||
|
||||
try:
|
||||
order_lines = task_line_purpose_values(task)
|
||||
|
||||
@@ -16,16 +16,19 @@ from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderCandidate,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
def create_inventory_preparation_round(
|
||||
*, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None,
|
||||
*, 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:
|
||||
@@ -50,8 +53,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 = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()]
|
||||
codes = [code for code in codes if code]
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
active_file = active_inventory_file_for_task(task)
|
||||
for source_code in codes:
|
||||
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
|
||||
@@ -76,8 +78,14 @@ def create_inventory_preparation_round(
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.flush()
|
||||
source_candidate = (
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.consumed_task_id == int(task.id))
|
||||
.order_by(ShippingOrderCandidate.id.desc())
|
||||
.first()
|
||||
)
|
||||
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
|
||||
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
|
||||
task_snapshot_fingerprint=str(getattr(source_candidate, 'content_fingerprint', '') or ''),
|
||||
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
|
||||
sources=[
|
||||
{
|
||||
@@ -99,7 +107,7 @@ def create_inventory_preparation_round(
|
||||
for item in round_row.source_attempts
|
||||
],
|
||||
reservation_version=str(getattr(task, 'order_data_version', '') or ''),
|
||||
matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''),
|
||||
matching_rule_version=str(active_inventory_runtime_facts(task).get('source_config_version') or ''),
|
||||
)
|
||||
db.session.flush()
|
||||
return round_row
|
||||
|
||||
@@ -313,9 +313,25 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
"inventory_rpa_wait_rechecked",
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
# [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落
|
||||
# rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_failed",
|
||||
{
|
||||
"error": "timeout",
|
||||
"elapsed_seconds": elapsed,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
},
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_exhausted",
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.flush()
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
_set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel")
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
_set_workflow_error(task, "RPA 库存导出等待超时,已停止自动重试,请选择重新获取库存或上传库存 Excel")
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
|
||||
@@ -18,7 +18,9 @@ from sqlalchemy import event as _sa_event
|
||||
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.services.shipping_notice.tool_common import task_event_task_id
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
_can_relink_inventory,
|
||||
generate_inventory_file_no,
|
||||
@@ -468,24 +470,24 @@ def link_snapshot_to_task(
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
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
|
||||
|
||||
lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines and Path(inv_file.storage_path).is_file():
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
|
||||
|
||||
lines, _column_meta = parse_inventory_snapshot_file(inv_file)
|
||||
inv_file.inventory_lines_json = lines
|
||||
inv_file.line_count = len(lines)
|
||||
try:
|
||||
lines, _column_meta = read_inventory_file_lines(inv_file)
|
||||
except (OSError, ValueError, AppError):
|
||||
lines = []
|
||||
resolution = resolve_dynamic_warehouse(
|
||||
task=task,
|
||||
inventory_lines=lines,
|
||||
fallback_warehouse_id=inv_file.warehouse_id,
|
||||
source_code=inv_file.source_code,
|
||||
)
|
||||
if not resolution.warehouse_id:
|
||||
# identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因
|
||||
@@ -513,10 +515,6 @@ def link_snapshot_to_task(
|
||||
if not identity_ok:
|
||||
return None
|
||||
|
||||
# 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。
|
||||
if not task.inventory_warehouse_id:
|
||||
task.inventory_warehouse_id = resolved_warehouse_id
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file, role=role)
|
||||
link.link_reason = reason
|
||||
link.matched_warehouse_id = resolved_warehouse_id
|
||||
@@ -533,10 +531,9 @@ def link_snapshot_to_task(
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
|
||||
}
|
||||
task.inventory_snapshot_id = inv_file.id
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
task_id=task_event_task_id(task),
|
||||
event_type="inventory_snapshot_linked",
|
||||
detail_json={
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
@@ -574,7 +571,7 @@ def link_snapshot_to_task_for_preparation(
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
source = get_database_inventory_source(inv_file.source_code)
|
||||
if (
|
||||
source is None
|
||||
or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match'
|
||||
@@ -595,7 +592,6 @@ def link_snapshot_to_task_for_preparation(
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
'identity_status': inv_file.identity_status,
|
||||
}
|
||||
task.inventory_snapshot_id = inv_file.id
|
||||
return link
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingNotice、core.errors。
|
||||
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
|
||||
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
|
||||
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
|
||||
"""
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
@@ -29,8 +29,6 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
)
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"})
|
||||
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
|
||||
@@ -42,7 +40,7 @@ INVENTORY_SOURCE_ERROR_CODES = {
|
||||
}
|
||||
|
||||
|
||||
def is_inventory_source_stable(task: ShippingNotice) -> bool:
|
||||
def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
|
||||
"""
|
||||
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
|
||||
|
||||
@@ -50,135 +48,81 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool:
|
||||
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
|
||||
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
|
||||
"""
|
||||
status = str(task.inventory_source_status or "").strip()
|
||||
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
return False
|
||||
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
|
||||
|
||||
if status == "candidates_frozen":
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
codes = task_frozen_inventory_source_codes(task)
|
||||
return bool(codes) and all(get_database_inventory_source(code) for code in codes)
|
||||
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
if not code:
|
||||
codes = task_frozen_inventory_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
|
||||
connector_type = str(task.inventory_connector_type or "").strip()
|
||||
if not connector_type:
|
||||
return False
|
||||
source = get_database_inventory_source(code)
|
||||
if not source:
|
||||
return False
|
||||
if connector_type != str(source.get("connector_type") or "").strip():
|
||||
return False
|
||||
|
||||
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
|
||||
fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper()
|
||||
task_warehouse = str(task.inventory_warehouse_id or '').strip().upper()
|
||||
if mode == 'fixed' and task_warehouse != fixed_warehouse:
|
||||
return False
|
||||
|
||||
for code in codes:
|
||||
source = get_database_inventory_source(code)
|
||||
if not source:
|
||||
return False
|
||||
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'fixed' and not str(source.get('fixed_warehouse_id') or '').strip():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
|
||||
def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
|
||||
previous = str(task.inventory_routing_fingerprint or "").strip()
|
||||
from app.services.shipping_notice.inventory_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()
|
||||
if not previous:
|
||||
return False
|
||||
return previous != compute_routing_fingerprint(context)
|
||||
|
||||
|
||||
def inventory_source_config_changed(task: ShippingNotice) -> bool:
|
||||
def inventory_source_config_changed(task: ShippingOrderTask) -> bool:
|
||||
"""
|
||||
配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。
|
||||
|
||||
核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务;
|
||||
只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。
|
||||
"""
|
||||
status = str(task.inventory_source_status or "").strip()
|
||||
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
# 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。
|
||||
return bool(status)
|
||||
return not is_inventory_source_stable(task)
|
||||
|
||||
|
||||
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
|
||||
"""将标准化目的地线索写入任务独立字段。"""
|
||||
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
|
||||
task.destination_city = str(context.get("destination_city") or "").strip() or None
|
||||
task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
|
||||
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
|
||||
|
||||
|
||||
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
def clear_inventory_source_confirmation(task: ShippingOrderTask) -> None:
|
||||
"""路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。"""
|
||||
task.inventory_source_confirmed_by = None
|
||||
task.inventory_source_confirmed_at = None
|
||||
if str(task.inventory_source_status or "").strip() == "user_confirmed":
|
||||
task.inventory_source_status = "unresolved"
|
||||
task.inventory_source_method = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload = dict(getattr(task, 'step_payload_json', None) or {})
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def apply_inventory_source_adjudication(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
execution_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
|
||||
核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
|
||||
将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。
|
||||
|
||||
Args:
|
||||
execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前
|
||||
正在执行的门禁链(否则会误 supersede 活动 Execution)。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
|
||||
task.inventory_routing_fingerprint = fingerprint
|
||||
apply_destination_fields(task, context)
|
||||
|
||||
task.inventory_source_status = adjudication.status
|
||||
task.inventory_source_method = adjudication.method or None
|
||||
task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version()
|
||||
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_connector_type = adjudication.connector_type
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
task.inventory_warehouse_id = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": adjudication.status,
|
||||
"method": adjudication.method,
|
||||
"reason": adjudication.reason,
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
"candidates": adjudication.candidates,
|
||||
"evidence": adjudication.evidence,
|
||||
"conflicts": adjudication.conflicts,
|
||||
"config_version": adjudication.config_version,
|
||||
"routing_fingerprint": fingerprint,
|
||||
}
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if rpa_source:
|
||||
payload["rpa_inventory_source"] = rpa_source
|
||||
else:
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
task.step_payload_json = payload
|
||||
if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)):
|
||||
freeze_candidates_for_task(
|
||||
task, adjudication=adjudication, execution_id=execution_id,
|
||||
)
|
||||
|
||||
|
||||
def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
def adjudicate_and_apply_inventory_source(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
execution_id: int | None = None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对任务执行库存源裁决并写入独立字段。
|
||||
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。
|
||||
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决;
|
||||
库存准备 Gate 在任务尚无冻结候选源时补裁决(传入当前 execution_id 以避免撤销活动链)。
|
||||
|
||||
Args:
|
||||
execution_id: 可选;透传给冻结服务,使重冻结不撤销当前正在执行的门禁链。
|
||||
"""
|
||||
context = extract_routing_context(task)
|
||||
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
|
||||
@@ -201,7 +145,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
)
|
||||
):
|
||||
try:
|
||||
freeze_result = freeze_candidates_for_task(task, adjudication=adjudication)
|
||||
freeze_result = freeze_candidates_for_task(
|
||||
task, adjudication=adjudication, execution_id=execution_id,
|
||||
)
|
||||
# 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段,
|
||||
# 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。
|
||||
evidence_merged = list(adjudication.evidence or [])
|
||||
@@ -232,12 +178,12 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。
|
||||
pass
|
||||
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
apply_inventory_source_adjudication(task, adjudication, execution_id=execution_id)
|
||||
return adjudication
|
||||
|
||||
|
||||
def transition_task_to_inventory_source_review(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
error_message: str | None = None,
|
||||
@@ -251,9 +197,11 @@ def transition_task_to_inventory_source_review(
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.current_step = "step2_parse_confirm"
|
||||
# OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流,
|
||||
# 不能在通知准备前写入 OT。
|
||||
task.stage = "inventory_source_resolving"
|
||||
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload = dict(getattr(task, 'step_payload_json', None) or {})
|
||||
payload["inventory_source_resolution"] = {
|
||||
"status": adjudication.status,
|
||||
"method": adjudication.method,
|
||||
@@ -268,7 +216,7 @@ def transition_task_to_inventory_source_review(
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
|
||||
|
||||
@@ -282,7 +230,7 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc
|
||||
|
||||
|
||||
def assert_inventory_source_gate(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
operation: str = "continue",
|
||||
) -> None:
|
||||
@@ -307,36 +255,67 @@ def assert_inventory_source_gate(
|
||||
)
|
||||
if is_inventory_source_stable(task):
|
||||
return
|
||||
status = str(task.inventory_source_status or "unresolved").strip()
|
||||
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
|
||||
reason_by_status = {
|
||||
"conflicted": "inventory_source_conflicted",
|
||||
"changed": "inventory_source_changed",
|
||||
"identity_mismatch": "inventory_source_identity_mismatch",
|
||||
}
|
||||
code = INVENTORY_SOURCE_ERROR_CODES['unresolved']
|
||||
raise AppError(
|
||||
code=code,
|
||||
message="库存源尚未确定,无法继续后续流程",
|
||||
http_status=409,
|
||||
details={
|
||||
"operation": operation,
|
||||
"inventory_source_status": status,
|
||||
"inventory_source_status": 'unresolved',
|
||||
"task_no": task.task_no,
|
||||
"reason_code": reason_by_status.get(status, "require_manual_review"),
|
||||
"reason_code": "require_manual_review",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def task_inventory_identity(task: ShippingNotice) -> dict[str, str | None]:
|
||||
"""返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。"""
|
||||
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
|
||||
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
source_codes = task_frozen_inventory_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 {
|
||||
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
|
||||
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
"inventory_source_code": source_code,
|
||||
"inventory_warehouse_id": resolve_inventory_source_warehouse_id(task, source=source),
|
||||
}
|
||||
|
||||
|
||||
def resolve_inventory_source_warehouse_id(
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
source: dict[str, Any] | None,
|
||||
) -> str | None:
|
||||
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
|
||||
if not source:
|
||||
return None
|
||||
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
|
||||
if mode == 'fixed':
|
||||
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
|
||||
|
||||
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
|
||||
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
task_id=int(task_id),
|
||||
matched_source_code=source_code,
|
||||
is_active=True,
|
||||
).order_by(ShippingTaskInventoryLink.id.desc()).first()
|
||||
if link is None:
|
||||
return None
|
||||
return (
|
||||
str(link.matched_warehouse_id or '').strip().upper()
|
||||
or str(getattr(link.inventory_file, 'warehouse_id', '') or '').strip().upper()
|
||||
or None
|
||||
)
|
||||
|
||||
|
||||
def inventory_identities_match(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
source_code: str | None,
|
||||
warehouse_id: str | None,
|
||||
@@ -344,8 +323,7 @@ def inventory_identities_match(
|
||||
"""
|
||||
校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。
|
||||
|
||||
核心逻辑:单源任务要求与 task.inventory_source_code 一致;
|
||||
candidates_frozen 时允许文件源属于冻结候选集合。
|
||||
核心逻辑:单源任务要求与唯一 CandidateSource 一致;多源允许文件源属于当前 CandidateSet。
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
return False
|
||||
|
||||
@@ -15,7 +15,8 @@ from dataclasses import dataclass, field, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNotice
|
||||
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 (
|
||||
@@ -49,17 +50,26 @@ InventorySourceResolution = InventorySourceAdjudication
|
||||
|
||||
|
||||
def extract_routing_context(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
"""从冻结订单(冻结前为当前 Extraction)读取路由审计上下文。"""
|
||||
header = current_header_field_values_or_empty(task)
|
||||
snapshot_id = getattr(task, 'order_snapshot_id', None)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
|
||||
if snapshot is not None:
|
||||
fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or [])
|
||||
frozen_values = dict(snapshot.header_values_json or {})
|
||||
header = {
|
||||
str(field.get('field_code') or ''): frozen_values.get(str(field.get('field_id') or ''))
|
||||
for field in fields
|
||||
if field.get('scope') == 'header' and str(field.get('field_code') or '')
|
||||
}
|
||||
return {
|
||||
'destination_code': task.destination_code,
|
||||
'destination_city': task.destination_city,
|
||||
'destination_country': task.destination_country,
|
||||
'warehouse_hint': task.warehouse_hint,
|
||||
'destination_code': header.get('destination_code'),
|
||||
'destination_city': header.get('destination_city'),
|
||||
'destination_country': header.get('destination_country'),
|
||||
'warehouse_hint': header.get('warehouse_hint'),
|
||||
'customer_code': header.get('customer_code'),
|
||||
'customer_name': header.get('customer_name') or header.get('bill_to_customer'),
|
||||
'order_type': payload.get('order_type'),
|
||||
'customer_name': header.get('customer_name'),
|
||||
'order_type': header.get('order_type'),
|
||||
'destination_candidates': [],
|
||||
}
|
||||
|
||||
@@ -165,7 +175,7 @@ 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 parse_inventory_snapshot_file
|
||||
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
|
||||
|
||||
matched: list[tuple[dict[str, Any], Any]] = []
|
||||
@@ -179,12 +189,10 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
if snapshot is None:
|
||||
checked.append({'source_code': source_code, 'snapshot': 'missing'})
|
||||
continue
|
||||
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines:
|
||||
try:
|
||||
lines, _column_meta = parse_inventory_snapshot_file(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
try:
|
||||
lines, _column_meta = read_inventory_file_lines(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
inventory_keys = {
|
||||
key for row in lines
|
||||
if isinstance(row, dict) and (key := _snapshot_match_key(row))
|
||||
@@ -251,10 +259,7 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。"""
|
||||
primary = get_database_inventory_source(task.inventory_source_code)
|
||||
if primary is not None:
|
||||
return primary
|
||||
"""按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。"""
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
for code in task_frozen_inventory_source_codes(task):
|
||||
@@ -265,7 +270,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:
|
||||
"""持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。"""
|
||||
"""持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
del source
|
||||
|
||||
@@ -19,7 +19,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNotice
|
||||
from app.models import ShippingInventoryFile, 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
|
||||
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
|
||||
@@ -163,7 +163,7 @@ def install_task_inventory_attachment_from_file(
|
||||
|
||||
|
||||
def rebuild_task_inventory_attachment_from_snapshot(
|
||||
task: ShippingNotice | str,
|
||||
task: ShippingOrderTask | ShippingNotice | str,
|
||||
inv_file: ShippingInventoryFile,
|
||||
) -> Path:
|
||||
"""
|
||||
@@ -177,7 +177,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
|
||||
Returns:
|
||||
重建后的任务正式附件路径。
|
||||
"""
|
||||
task_no = task.task_no if isinstance(task, ShippingNotice) else str(task or "").strip()
|
||||
task_no = str(getattr(task, "task_no", task) or "").strip()
|
||||
if not task_no:
|
||||
raise ValueError("task_no is required")
|
||||
storage_path = Path(str(inv_file.storage_path or ""))
|
||||
|
||||
@@ -29,9 +29,9 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
|
||||
return values if values and all(values) else None
|
||||
|
||||
|
||||
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution:
|
||||
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=task.inventory_source_code).first()
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
|
||||
definition = source.parsing_profile.definition_json if source and source.parsing_profile 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)]
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
)
|
||||
@@ -52,7 +52,7 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
|
||||
return None
|
||||
|
||||
|
||||
def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, Any] | None:
|
||||
def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存入口统一检查订单侧 Reservation ID。
|
||||
|
||||
@@ -86,7 +86,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str,
|
||||
)
|
||||
|
||||
|
||||
def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lang: str) -> dict[str, Any] | None:
|
||||
def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
|
||||
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
|
||||
@@ -112,6 +112,43 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
|
||||
reservation_gate = _reservation_gate_response(task, lang=lang)
|
||||
if reservation_gate is not None:
|
||||
return reservation_gate
|
||||
if operation == "ensure_inventory":
|
||||
# [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或
|
||||
# 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
get_active_candidate_lines,
|
||||
get_active_candidate_set,
|
||||
get_active_candidate_sources,
|
||||
)
|
||||
|
||||
candidate_set = get_active_candidate_set(task)
|
||||
sources = get_active_candidate_sources(task)
|
||||
lines = get_active_candidate_lines(task)
|
||||
invalid_lines = [
|
||||
line for line in lines
|
||||
if not list(getattr(line, "source_codes_json", None) or [])
|
||||
]
|
||||
if (
|
||||
not task.order_snapshot_id
|
||||
or candidate_set is None
|
||||
or str(getattr(candidate_set, "lifecycle_status", "") or "").lower() != "frozen"
|
||||
or not sources
|
||||
or not lines
|
||||
or invalid_lines
|
||||
):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源候选集尚未冻结完成,暂不能准备库存。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
|
||||
"checkpoint": CP_INVENTORY_SOURCE_REVIEW,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
if is_inventory_source_stable(task):
|
||||
return None
|
||||
try:
|
||||
@@ -138,7 +175,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||||
if has_verified_upload_success(task) or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
@@ -267,6 +305,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# [STEP 1] 优先接受当前请求直接携带的库存明细。
|
||||
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
|
||||
mode = str(payload.get("mode") or "auto").strip().lower()
|
||||
# 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实,
|
||||
# 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。
|
||||
allow_auto_retry = bool(payload.get('allow_auto_retry', True))
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
if inventory_lines:
|
||||
return inventory_loaded_response(
|
||||
@@ -290,7 +331,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen':
|
||||
if len(frozen_codes) >= 1:
|
||||
prep = prepare_candidate_inventory_lines(task)
|
||||
if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing':
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
@@ -319,7 +360,70 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
},
|
||||
},
|
||||
)
|
||||
if prep.get('status') == 'missing_files':
|
||||
if prep.get('status') in {'missing_files', 'partial_missing'}:
|
||||
# [STEP] 缺失源自动批次探测(设计 D3/D4):不再停在 needs_human;
|
||||
# 已有 ready 快照的源由 ensure_all_required_sources_prepared 复用,
|
||||
# 仅缺失源进入单批次 trigger;回调后由下一轮 ensure 继续推进匹配。
|
||||
from app.services.shipping_notice.per_source_rpa_service import (
|
||||
ensure_all_required_sources_prepared,
|
||||
)
|
||||
probe = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry)
|
||||
if probe.pending_source_codes:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发库存获取,等待各库存源回调。",
|
||||
progress_percent=60,
|
||||
detail="等待库存 RPA 回调",
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="running",
|
||||
task=task,
|
||||
message="已触发库存获取,等待各库存源回调。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'rpa': {'pending_source_codes': list(probe.pending_source_codes)},
|
||||
},
|
||||
)
|
||||
if probe.all_prepared:
|
||||
# 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。
|
||||
prep = prepare_candidate_inventory_lines(task)
|
||||
else:
|
||||
# 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。
|
||||
log_task_event(task, "inventory_probe_failed", {
|
||||
'failed_source_codes': list(probe.failed_source_codes or []),
|
||||
})
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="库存 RPA 未能为全部库存源生成结果。",
|
||||
progress_percent=100,
|
||||
detail="请重新获取库存或上传库存 Excel。",
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
# [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时
|
||||
# 返回 status='failed'(executor 映射为 blocked_retryable),
|
||||
# 不伪装成人工阻断;显式路径维持 needs_human。
|
||||
status="failed" if not allow_auto_retry else "needs_human",
|
||||
task=task,
|
||||
message="库存 RPA 未能为全部库存源生成结果。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'blocking_reason': {'code': 'inventory_preparation_failed'},
|
||||
'poll_read_only': not allow_auto_retry,
|
||||
},
|
||||
)
|
||||
if prep.get('status') in {'missing_files', 'partial_missing'}:
|
||||
# 防御:探测后仍缺失(如快照在探测窗口内失效),不得带着残缺数据进入匹配。
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -343,32 +447,6 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
},
|
||||
)
|
||||
if prep.get('status') == 'partial_missing':
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
progress_percent=0,
|
||||
detail=t("workflow.inventory.unavailable", lang=lang),
|
||||
)
|
||||
log_task_event(task, "inventory_candidate_files_partial", {
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
'loaded_source_codes': prep.get('loaded_source_codes') or [],
|
||||
})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'missing_source_codes': prep.get('missing_source_codes') or [],
|
||||
'loaded_source_codes': prep.get('loaded_source_codes') or [],
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
|
||||
return inventory_loaded_response(
|
||||
@@ -391,11 +469,13 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# 否则任务会错误停在人审且没有可执行的恢复动作。
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
return ensure_inventory_via_rpa(task, mode=mode)
|
||||
return ensure_inventory_via_rpa(task, mode=mode, allow_auto_retry=allow_auto_retry)
|
||||
|
||||
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
|
||||
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
|
||||
if task.inventory_lines_json:
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
if has_ready_inventory_file_for_task(task):
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/line_inventory_match_persistence.py
|
||||
|
||||
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库;
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
|
||||
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
||||
"""
|
||||
|
||||
@@ -26,19 +26,6 @@ from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
)
|
||||
|
||||
|
||||
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
|
||||
"""Case 草稿行序 → line_key。"""
|
||||
if case is None or case.current_draft is None:
|
||||
return {}
|
||||
out: dict[int, str] = {}
|
||||
for idx, line in enumerate(list(case.current_draft.lines_json or [])):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
|
||||
out[idx] = key
|
||||
return out
|
||||
|
||||
|
||||
def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
反查确认到该 OT 的 Review Case。
|
||||
@@ -85,6 +72,24 @@ def map_disposition_to_match_codes(
|
||||
return 'result_missing', 'unavailable'
|
||||
|
||||
|
||||
def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
行级已定源:优先取匹配结果,缺失时回退到任务级已定源(Approach 1)。
|
||||
|
||||
核心逻辑:匹配未回填源时,只有当前 CandidateSet 恰有一个源才回填;
|
||||
不从 OT 读取任务级库存源投影。
|
||||
"""
|
||||
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
|
||||
|
||||
source_codes = task_frozen_inventory_source_codes(task)
|
||||
if len(source_codes) == 1:
|
||||
return source_codes[0][:64]
|
||||
return None
|
||||
|
||||
|
||||
def persist_line_inventory_match_facts(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
@@ -95,14 +100,15 @@ def persist_line_inventory_match_facts(
|
||||
"""
|
||||
将 match_order_lines_across_candidates 结果持久化为当前事实。
|
||||
|
||||
核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current;
|
||||
核心逻辑:按冻结订单行项次解析 snapshot_line_id;同快照幂等更新;否则新增并切换 is_current;
|
||||
无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。
|
||||
"""
|
||||
case = resolve_review_case_for_task(task)
|
||||
keys_by_index = _draft_line_keys_by_index(case)
|
||||
snap_id = inventory_snapshot_id
|
||||
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
|
||||
snap_id = int(task.inventory_snapshot_id)
|
||||
if snap_id is None:
|
||||
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
|
||||
|
||||
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
|
||||
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
|
||||
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
|
||||
snapshot_file_no = None
|
||||
@@ -129,6 +135,12 @@ def persist_line_inventory_match_facts(
|
||||
int(row.line_no): row
|
||||
for row in get_active_candidate_lines(task)
|
||||
}
|
||||
from app.models import ShippingOrderSnapshot
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None
|
||||
snapshot_lines_by_no = {
|
||||
int(line.line_no): line for line in (snapshot.lines if snapshot is not None else [])
|
||||
if str(getattr(line, 'line_no', '') or '').isdigit()
|
||||
}
|
||||
|
||||
for result in line_results:
|
||||
try:
|
||||
@@ -136,15 +148,11 @@ def persist_line_inventory_match_facts(
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
res = res_by_index.get(index) or {}
|
||||
# Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底,
|
||||
# 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。
|
||||
line_key = str(
|
||||
keys_by_index.get(index)
|
||||
or res.get('line_key')
|
||||
or f'line-{index + 1}'
|
||||
).strip()
|
||||
if not line_key:
|
||||
line_no = index + 1
|
||||
snapshot_line = snapshot_lines_by_no.get(line_no)
|
||||
if snapshot_line is None:
|
||||
continue
|
||||
snapshot_line_id = int(snapshot_line.id)
|
||||
|
||||
match_result, inventory_status = map_disposition_to_match_codes(
|
||||
disposition=str(result.get('disposition') or res.get('disposition') or ''),
|
||||
@@ -192,7 +200,8 @@ def persist_line_inventory_match_facts(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(
|
||||
task_id=int(task.id),
|
||||
line_key=line_key,
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
line_no=line_no,
|
||||
inventory_snapshot_id=int(snap_id),
|
||||
)
|
||||
.first()
|
||||
@@ -200,7 +209,7 @@ def persist_line_inventory_match_facts(
|
||||
if existing is None and snap_id is None:
|
||||
existing = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
|
||||
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
|
||||
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
|
||||
.first()
|
||||
)
|
||||
@@ -208,18 +217,17 @@ def persist_line_inventory_match_facts(
|
||||
if existing is None:
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
|
||||
.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)
|
||||
)
|
||||
# Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实,
|
||||
# 避免同一订单行同时存在两个 current 投影。
|
||||
# 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_index=index, is_current=True)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
src_code = _line_resolved_source_code(task, result)
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
@@ -249,7 +257,8 @@ def persist_line_inventory_match_facts(
|
||||
row = ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id),
|
||||
review_case_id=int(case.id) if case is not None else None,
|
||||
line_key=line_key,
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
line_no=line_no,
|
||||
line_index=index,
|
||||
candidate_set_id=(
|
||||
int(current_candidate_set.id)
|
||||
@@ -301,7 +310,7 @@ def persist_line_inventory_match_facts(
|
||||
written.append(row)
|
||||
else:
|
||||
# [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
src_code = _line_resolved_source_code(task, result)
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
@@ -374,14 +383,13 @@ def persist_line_inventory_match_facts(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.line_key == line_key,
|
||||
ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id,
|
||||
ShippingNoticeLineInventoryMatch.id != int(existing.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
# Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键;
|
||||
# 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。
|
||||
# 同一订单行更新时关闭旧事实,保证 current 投影唯一。
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter(
|
||||
|
||||
@@ -414,8 +414,8 @@ def resolve_allowed_actions(
|
||||
return [*inv, *line]
|
||||
|
||||
|
||||
def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]:
|
||||
"""加载 OT 当前行匹配事实,键为 line_key。"""
|
||||
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
|
||||
"""加载 OT 当前行匹配事实,键为冻结订单行 ID。"""
|
||||
if task_id is None:
|
||||
return {}
|
||||
rows = (
|
||||
@@ -423,15 +423,27 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str,
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.all()
|
||||
)
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
out: dict[int, dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
key = str(row.line_key or '').strip()
|
||||
if not key:
|
||||
if row.snapshot_line_id is None:
|
||||
continue
|
||||
out[key] = serialize_match_fact(row)
|
||||
out[int(row.snapshot_line_id)] = serialize_match_fact(row)
|
||||
return out
|
||||
|
||||
|
||||
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
|
||||
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
|
||||
facts = list(load_current_match_facts_by_task(task_id).values())
|
||||
if not facts:
|
||||
return None
|
||||
blocked = any(
|
||||
str(row.get('match_result') or '').strip().lower() != 'matched'
|
||||
or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
|
||||
for row in facts
|
||||
)
|
||||
return 'unfulfillable' if blocked else 'fulfillable'
|
||||
|
||||
|
||||
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
|
||||
"""将 ORM 行序列化为投影输入。"""
|
||||
snapshot = (
|
||||
@@ -442,7 +454,8 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
||||
'id': int(row.id),
|
||||
'task_id': int(row.task_id),
|
||||
'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None,
|
||||
'line_key': str(row.line_key),
|
||||
'snapshot_line_id': int(row.snapshot_line_id),
|
||||
'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
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.models import (
|
||||
ShippingOrderReviewLineDecision,
|
||||
ShippingOrderReviewWaveLine,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
@@ -236,15 +237,16 @@ def _release_fact_identity(fact: dict[str, Any] | None) -> tuple[int | None, int
|
||||
def _resolve_shortage_release_inventory_source(
|
||||
*,
|
||||
fact_source_code: Any,
|
||||
task_source_code: Any,
|
||||
snapshot_source_code: Any,
|
||||
candidate_source_codes: set[str] | None = None,
|
||||
) -> str | None:
|
||||
"""按行事实、OT、快照顺序恢复短缺放行所需的库存源。"""
|
||||
for value in (fact_source_code, task_source_code, snapshot_source_code):
|
||||
"""按行事实、库存文件、唯一冻结候选源顺序恢复短缺放行所需的库存源。"""
|
||||
for value in (fact_source_code, snapshot_source_code):
|
||||
normalized = str(value or '').strip().upper()
|
||||
if normalized:
|
||||
return normalized
|
||||
return None
|
||||
codes = candidate_source_codes or set()
|
||||
return next(iter(codes)) if len(codes) == 1 else None
|
||||
|
||||
|
||||
def _is_shortage_match_fact(fact: Any) -> bool:
|
||||
@@ -285,9 +287,6 @@ def _has_terminal_inventory_rpa_failure(
|
||||
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
|
||||
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
|
||||
source_codes = set()
|
||||
source_code = str(getattr(task, 'inventory_source_code', '') or '').strip().upper()
|
||||
if source_code:
|
||||
source_codes.add(source_code)
|
||||
rows = attempts if attempts is not None else (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=task_no)
|
||||
@@ -326,15 +325,21 @@ def _shortage_release_required_fields(
|
||||
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
|
||||
if inventory_snapshot_id is not None and (snapshot is None or not isinstance(snapshot.inventory_lines_json, list)):
|
||||
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
|
||||
|
||||
resolved_source_code = _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=inventory_source_code,
|
||||
task_source_code=getattr(task, 'inventory_source_code', None),
|
||||
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)
|
||||
if str(code or '').strip()
|
||||
},
|
||||
)
|
||||
if not resolved_source_code:
|
||||
raise ConflictError(
|
||||
@@ -366,7 +371,7 @@ def _shortage_release_required_fields(
|
||||
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 {}
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + _release_template_system_fields(mappings=mappings, warehouse_id=getattr(task, 'inventory_warehouse_id', None))
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
|
||||
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 = [
|
||||
@@ -378,9 +383,17 @@ 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
|
||||
try:
|
||||
inventory_lines, _column_meta = read_inventory_file_lines(snapshot)
|
||||
except (OSError, ValueError, AppError) as exc:
|
||||
raise ConflictError(
|
||||
'Current inventory snapshot is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
) from exc
|
||||
candidates = [
|
||||
dict(row) for row in snapshot.inventory_lines_json if isinstance(row, dict)
|
||||
and all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
]
|
||||
field_ids = {
|
||||
int(str(item.get('source_key') or '').strip())
|
||||
@@ -398,9 +411,6 @@ def _shortage_release_required_fields(
|
||||
mappings=mappings,
|
||||
candidates=candidates,
|
||||
field_labels=labels,
|
||||
) + _release_template_system_fields(
|
||||
mappings=mappings,
|
||||
warehouse_id=getattr(task, 'inventory_warehouse_id', None),
|
||||
)
|
||||
|
||||
|
||||
@@ -426,7 +436,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
if task_id is None:
|
||||
return
|
||||
task = db.session.get(ShippingNotice, int(task_id))
|
||||
task = db.session.get(ShippingOrderTask, int(task_id))
|
||||
if task is None:
|
||||
return
|
||||
# [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态
|
||||
@@ -556,7 +566,7 @@ def _assess_line_fulfill_complete(
|
||||
|
||||
def _assert_line_can_fulfill_complete(
|
||||
*,
|
||||
line_key: str,
|
||||
draft_line_id: str,
|
||||
draft_line: dict[str, Any],
|
||||
proj: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
@@ -576,13 +586,13 @@ def _assert_line_can_fulfill_complete(
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory',
|
||||
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'),
|
||||
details={'line_key': line_key},
|
||||
details={'draft_line_id': draft_line_id},
|
||||
)
|
||||
return req, avail
|
||||
|
||||
|
||||
def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
"""line_key → 草稿行。"""
|
||||
"""draft_line_id → 草稿行。"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return {}
|
||||
@@ -590,16 +600,16 @@ def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
for idx, line in enumerate(list(draft.lines_json or [])):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
|
||||
key = str(line.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
|
||||
row = dict(line)
|
||||
row['_line_index'] = idx
|
||||
row['_line_key'] = key
|
||||
row['_draft_line_id'] = key
|
||||
out[key] = row
|
||||
return out
|
||||
|
||||
|
||||
def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
"""line_key → eligibility line projection。"""
|
||||
"""draft_line_id → eligibility line projection。"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return {}
|
||||
@@ -608,29 +618,29 @@ def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, A
|
||||
for idx, item in enumerate(list(validation.get('line_projections') or [])):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
key = str(item.get('line_key') or '').strip() or f'line-{idx + 1}'
|
||||
key = str(item.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
|
||||
out[key] = dict(item)
|
||||
return out
|
||||
|
||||
|
||||
def _active_decision(
|
||||
case: ShippingOrderReviewCase,
|
||||
line_key: str,
|
||||
draft_line_id: str,
|
||||
) -> ShippingOrderReviewLineDecision | None:
|
||||
"""取某行当前活动决定。"""
|
||||
return (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(review_case_id=int(case.id), line_key=str(line_key), is_active=True)
|
||||
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id), is_active=True)
|
||||
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _next_version(case: ShippingOrderReviewCase, line_key: str) -> int:
|
||||
def _next_version(case: ShippingOrderReviewCase, draft_line_id: str) -> int:
|
||||
"""下一决定版本号。"""
|
||||
latest = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(review_case_id=int(case.id), line_key=str(line_key))
|
||||
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id))
|
||||
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -641,7 +651,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
|
||||
"""用户态决定投影。"""
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'line_key': row.line_key,
|
||||
'draft_line_id': row.draft_line_id,
|
||||
'line_index': row.line_index,
|
||||
'decision_version': int(row.decision_version),
|
||||
'decision_code': row.decision_code,
|
||||
@@ -766,44 +776,33 @@ def project_review_case_line_decisions(
|
||||
schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case)
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
|
||||
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None
|
||||
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingOrderTask) else None
|
||||
if task is None and getattr(case, 'confirmed_task_id', None) is not None:
|
||||
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
|
||||
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] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示)
|
||||
# 优先级:行级 inventory_source_code > Task resolved 正式源 > candidates_frozen > resolving
|
||||
# [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
)
|
||||
|
||||
fallback_inventory_source: dict[str, Any] | None = None
|
||||
if task is not None:
|
||||
task_source_code = str(task.inventory_source_code or '').strip().upper() or None
|
||||
task_source_status = str(task.inventory_source_status or '').strip()
|
||||
if task_source_code and task_source_status == 'resolved':
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
if len(frozen_codes) == 1:
|
||||
fallback_inventory_source = {
|
||||
'code': task_source_code,
|
||||
'code': frozen_codes[0],
|
||||
'label': None,
|
||||
'status': 'resolved',
|
||||
'source': 'task_inventory_source',
|
||||
'source': 'frozen_inventory_candidates',
|
||||
}
|
||||
elif frozen_codes:
|
||||
fallback_inventory_source = {
|
||||
'code': None,
|
||||
'label': None,
|
||||
'status': 'candidates_frozen',
|
||||
'candidates': list(frozen_codes),
|
||||
'source': 'frozen_inventory_candidates',
|
||||
}
|
||||
elif task_source_status == 'candidates_frozen':
|
||||
frozen_codes = task_frozen_inventory_source_codes(task)
|
||||
if frozen_codes:
|
||||
fallback_inventory_source = {
|
||||
'code': None,
|
||||
'label': None,
|
||||
'status': 'candidates_frozen',
|
||||
'candidates': list(frozen_codes),
|
||||
'source': 'frozen_inventory_candidates',
|
||||
}
|
||||
else:
|
||||
fallback_inventory_source = {
|
||||
'code': None,
|
||||
'label': None,
|
||||
'status': 'resolving',
|
||||
'source': 'inventory_source_clue',
|
||||
}
|
||||
else:
|
||||
fallback_inventory_source = {
|
||||
'code': None,
|
||||
@@ -825,10 +824,10 @@ def project_review_case_line_decisions(
|
||||
active_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(review_case_id=int(case.id), is_active=True)
|
||||
.order_by(ShippingOrderReviewLineDecision.line_key.asc())
|
||||
.order_by(ShippingOrderReviewLineDecision.draft_line_id.asc())
|
||||
.all()
|
||||
)
|
||||
by_key = {str(row.line_key): row for row in active_rows}
|
||||
by_key = {str(row.draft_line_id): row for row in active_rows}
|
||||
|
||||
lines_out: list[dict[str, Any]] = []
|
||||
for key, draft_line in draft_lines.items():
|
||||
@@ -909,8 +908,6 @@ def project_review_case_line_decisions(
|
||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||
if release_line_index is None:
|
||||
release_line_index = draft_line.get('_line_index')
|
||||
if not release_source_code:
|
||||
release_source_code = getattr(task, 'inventory_source_code', None)
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
@@ -925,7 +922,7 @@ def project_review_case_line_decisions(
|
||||
available = inv_view.get('available_qty')
|
||||
shortage = inv_view.get('shortage_qty')
|
||||
lines_out.append({
|
||||
'line_key': key,
|
||||
'draft_line_id': key,
|
||||
'line_index': draft_line.get('_line_index'),
|
||||
'reservation_id': _line_reservation_id(draft_line, proj),
|
||||
'part_number': _line_part_number(
|
||||
@@ -1067,7 +1064,7 @@ def decide_review_line_fulfillment(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
draft_line_id: str,
|
||||
decision_code: str,
|
||||
reason: str | None = None,
|
||||
release_field_values: dict[str, Any] | None = None,
|
||||
@@ -1084,7 +1081,7 @@ def decide_review_line_fulfillment(
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
case_no: Case 编号。
|
||||
line_key: 草稿行键。
|
||||
draft_line_id: 草稿行键。
|
||||
decision_code: 决定码。
|
||||
reason: 关闭/重开/短缺放行必填原因。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
||||
@@ -1118,7 +1115,7 @@ def decide_review_line_fulfillment(
|
||||
)
|
||||
|
||||
lines = _draft_line_map(case)
|
||||
key = str(line_key or '').strip()
|
||||
key = str(draft_line_id or '').strip()
|
||||
if key not in lines:
|
||||
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
|
||||
@@ -1128,20 +1125,20 @@ def decide_review_line_fulfillment(
|
||||
raise ConflictError(
|
||||
'Line already fulfilled in a task wave',
|
||||
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
|
||||
details={'line_key': key, 'line_status': current.line_status},
|
||||
details={'draft_line_id': key, 'line_status': current.line_status},
|
||||
)
|
||||
if code == DECISION_REOPEN:
|
||||
if current is None or current.line_status != 'closed_unfulfillable':
|
||||
raise ConflictError(
|
||||
'Only closed_unfulfillable lines can be reopened',
|
||||
code='SHIPPING.REVIEW_LINE_REOPEN_NOT_ALLOWED',
|
||||
details={'line_key': key},
|
||||
details={'draft_line_id': key},
|
||||
)
|
||||
if not actor_is_admin:
|
||||
raise ConflictError(
|
||||
'Reopen requires admin',
|
||||
code='SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN',
|
||||
details={'line_key': key},
|
||||
details={'draft_line_id': key},
|
||||
)
|
||||
elif current is not None and current.line_status == 'closed_unfulfillable':
|
||||
raise ConflictError(
|
||||
@@ -1161,7 +1158,7 @@ def decide_review_line_fulfillment(
|
||||
avail_qty = _parse_qty(proj.get('available_qty'))
|
||||
if code == DECISION_FULFILL:
|
||||
req_qty, avail_qty = _assert_line_can_fulfill_complete(
|
||||
line_key=key,
|
||||
draft_line_id=key,
|
||||
draft_line=draft_line,
|
||||
proj=proj,
|
||||
schema_fields=schema_fields,
|
||||
@@ -1170,10 +1167,10 @@ def decide_review_line_fulfillment(
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
task = db.session.get(ShippingNotice, int(task_id)) if task_id is not None else None
|
||||
task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=key, is_current=True)
|
||||
.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
|
||||
)
|
||||
@@ -1182,25 +1179,20 @@ def decide_review_line_fulfillment(
|
||||
raise ConflictError(
|
||||
'Only shortage lines can be released',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_NOT_ALLOWED',
|
||||
details={'line_key': key},
|
||||
details={'draft_line_id': key},
|
||||
)
|
||||
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
|
||||
release_template_fields = _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 getattr(task, 'inventory_source_code', None),
|
||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
||||
) if task is not None else []
|
||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||
release_values = _validate_inventory_shortage_release_fields(
|
||||
required_fields=release_required_fields,
|
||||
supplied_values=release_field_values or {},
|
||||
)
|
||||
supplied_warehouse_id = str(release_values.get('system_fact:warehouse_id') or '').strip().upper()
|
||||
if supplied_warehouse_id:
|
||||
# Header Warehouse ID 是动态库存源导出的任务级系统事实;人工放行时必须
|
||||
# 显式固化,供后续 Excel 生成消费,并同时保留在决定快照中审计。
|
||||
task.inventory_warehouse_id = supplied_warehouse_id
|
||||
else:
|
||||
release_required_fields = []
|
||||
release_values = {}
|
||||
@@ -1213,7 +1205,7 @@ def decide_review_line_fulfillment(
|
||||
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
line_key=key,
|
||||
draft_line_id=key,
|
||||
line_index=draft_line.get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
decision_code=code,
|
||||
@@ -1237,7 +1229,7 @@ def decide_review_line_fulfillment(
|
||||
'decision_source': 'user',
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'line_key': key,
|
||||
'draft_line_id': key,
|
||||
'release_field_values': release_values,
|
||||
'release_required_fields': release_required_fields,
|
||||
},
|
||||
@@ -1262,7 +1254,7 @@ def decide_review_line_fulfillment(
|
||||
review_case_no=str(case.case_no),
|
||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||
metadata={
|
||||
'line_key': key,
|
||||
'draft_line_id': key,
|
||||
'decision_code': code,
|
||||
'decision_version': int(row.decision_version),
|
||||
'line_status': status,
|
||||
@@ -1301,7 +1293,7 @@ def close_remaining_fulfillment(
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
reason: str,
|
||||
line_keys: list[str] | None = None,
|
||||
draft_line_ids: list[str] | None = None,
|
||||
expected_draft_version: Any = None,
|
||||
actor_is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
@@ -1312,7 +1304,7 @@ def close_remaining_fulfillment(
|
||||
user_id: 操作人。
|
||||
case_no: Case 编号。
|
||||
reason: 强制原因。
|
||||
line_keys: 指定行;为空则关闭全部开放行。
|
||||
draft_line_ids: 指定行;为空则关闭全部开放行。
|
||||
expected_draft_version: 可选草稿版本。
|
||||
actor_is_admin: 透传给 decide(关闭本身不要求管理员)。
|
||||
|
||||
@@ -1326,10 +1318,10 @@ def close_remaining_fulfillment(
|
||||
)
|
||||
case = _load_writable_case(user_id=user_id, case_no=case_no)
|
||||
projection = project_review_case_line_decisions(case)
|
||||
targets = list(line_keys or [])
|
||||
targets = list(draft_line_ids or [])
|
||||
if not targets:
|
||||
targets = [
|
||||
str(item['line_key'])
|
||||
str(item['draft_line_id'])
|
||||
for item in projection.get('lines') or []
|
||||
if item.get('line_status') not in _TERMINAL_ACTIVE
|
||||
]
|
||||
@@ -1338,7 +1330,7 @@ def close_remaining_fulfillment(
|
||||
last = decide_review_line_fulfillment(
|
||||
user_id=user_id,
|
||||
case_no=case_no,
|
||||
line_key=key,
|
||||
draft_line_id=key,
|
||||
decision_code=DECISION_CLOSE,
|
||||
reason=reason,
|
||||
expected_draft_version=expected_draft_version,
|
||||
|
||||
@@ -301,6 +301,7 @@ def ensure_all_required_sources_prepared(
|
||||
mode: str = 'auto',
|
||||
session: Session | None = None,
|
||||
allow_auto_retry: bool = True,
|
||||
source_codes: list[str] | None = None,
|
||||
) -> PerSourcePrepareResult:
|
||||
"""
|
||||
遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。
|
||||
@@ -338,7 +339,10 @@ def ensure_all_required_sources_prepared(
|
||||
except Exception:
|
||||
# SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。
|
||||
pass
|
||||
source_codes = task_frozen_inventory_source_codes(task)
|
||||
source_codes = [
|
||||
str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task))
|
||||
if str(code).strip()
|
||||
]
|
||||
if not source_codes:
|
||||
return PerSourcePrepareResult(
|
||||
task_no=task_no, all_prepared=False,
|
||||
@@ -394,7 +398,15 @@ def ensure_all_required_sources_prepared(
|
||||
current_status = double_check.status
|
||||
att = double_check
|
||||
|
||||
if current_status in ('succeeded', 'consumed') and att and _attempt_ref_has_ready_snapshot(att, session=sess):
|
||||
# 显式 retry_rpa 必须忽略历史成功 Attempt,即使其仍指向 ready 快照;
|
||||
# 否则“重新获取库存”会被误判为已准备完成,既不创建新 RPA Attempt,
|
||||
# 也不会写入新的 trigger 文件。
|
||||
if (
|
||||
mode != 'retry_rpa'
|
||||
and current_status in ('succeeded', 'consumed')
|
||||
and att
|
||||
and _attempt_ref_has_ready_snapshot(att, session=sess)
|
||||
):
|
||||
prepared.append(source_code)
|
||||
continue
|
||||
|
||||
|
||||
@@ -67,20 +67,20 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
|
||||
raise ConflictError(
|
||||
'Inventory not ready for post-OT wave',
|
||||
code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY',
|
||||
details={'line_key': line.get('line_key'), 'inventory_status': line.get('inventory_status')},
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')},
|
||||
)
|
||||
if str(line.get('match_result') or '') != 'matched':
|
||||
raise ConflictError(
|
||||
'Line match result does not allow fulfill',
|
||||
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
|
||||
details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')},
|
||||
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'
|
||||
if line.get('is_shortage') and not is_released_shortage:
|
||||
raise ConflictError(
|
||||
'Line has inventory shortage',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
details={'line_key': line.get('line_key')},
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id')},
|
||||
)
|
||||
req = _parse_qty(line.get('required_qty'))
|
||||
avail = _parse_qty(line.get('available_qty'))
|
||||
@@ -88,19 +88,19 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory facts',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
details={'line_key': line.get('line_key')},
|
||||
details={'snapshot_line_id': line.get('snapshot_line_id')},
|
||||
)
|
||||
return req, avail
|
||||
|
||||
|
||||
def _stable_line_keys(keys: list[str]) -> list[str]:
|
||||
"""稳定排序行键。"""
|
||||
return sorted({str(k).strip() for k in keys if str(k).strip()})
|
||||
def _stable_snapshot_line_ids(ids: list[int]) -> list[int]:
|
||||
"""稳定排序冻结订单行 ID。"""
|
||||
return sorted({int(item) for item in ids})
|
||||
|
||||
|
||||
def _line_keys_hash(keys: list[str]) -> str:
|
||||
"""行集合指纹。"""
|
||||
payload = json.dumps(_stable_line_keys(keys), ensure_ascii=False, separators=(',', ':'))
|
||||
def _snapshot_line_ids_hash(ids: list[int]) -> str:
|
||||
"""冻结订单行集合指纹。"""
|
||||
payload = json.dumps(_stable_snapshot_line_ids(ids), ensure_ascii=False, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple
|
||||
(单一 snapshot_id 或 None, fingerprint 字符串)。
|
||||
"""
|
||||
ids: list[int] = []
|
||||
by_key = {str(item.get('line_key') or ''): item for item in lines}
|
||||
by_key = {str(item.get('snapshot_line_id') or ''): item for item in lines}
|
||||
for key in keys:
|
||||
item = by_key.get(key) or {}
|
||||
raw = item.get('inventory_snapshot_id')
|
||||
@@ -131,14 +131,14 @@ def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple
|
||||
def _params_conflict(
|
||||
row: ShippingOrderReviewWaveIdempotency,
|
||||
*,
|
||||
line_keys: list[str],
|
||||
snapshot_line_ids: list[int],
|
||||
fingerprint: str,
|
||||
decision_source: str,
|
||||
) -> bool:
|
||||
"""同 key 参数是否与已存记录冲突。"""
|
||||
if str(row.decision_source or '') != str(decision_source):
|
||||
return True
|
||||
if str(row.line_keys_hash or '') != _line_keys_hash(line_keys):
|
||||
if str(row.snapshot_line_ids_hash or '') != _snapshot_line_ids_hash(snapshot_line_ids):
|
||||
return True
|
||||
if str(row.inventory_snapshot_fingerprint or '') != str(fingerprint):
|
||||
return True
|
||||
@@ -148,7 +148,7 @@ def _params_conflict(
|
||||
def create_post_ot_fulfillment_wave(
|
||||
*,
|
||||
case_no: str,
|
||||
line_keys: list[str],
|
||||
snapshot_line_ids: list[int],
|
||||
decision_source: str = 'system',
|
||||
actor_user_id: int | None = None,
|
||||
reason: str | None = None,
|
||||
@@ -162,21 +162,21 @@ def create_post_ot_fulfillment_wave(
|
||||
|
||||
Args:
|
||||
case_no: Case 编号。
|
||||
line_keys: 本波次行键。
|
||||
snapshot_line_ids: 本波次冻结订单行 ID。
|
||||
decision_source: system | user。
|
||||
actor_user_id: 人工操作人;系统可为 None。
|
||||
reason: 备注。
|
||||
idempotency_key: 可选幂等键(独立表强约束)。
|
||||
|
||||
Returns:
|
||||
wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
|
||||
wave_no / task_no / notice_no / accepted_snapshot_line_ids / skipped_snapshot_line_ids / line_fulfillment /
|
||||
idempotency_row_id / idempotent_replay。
|
||||
"""
|
||||
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
|
||||
keys = [str(int(k)) for k in (snapshot_line_ids or [])]
|
||||
if not keys:
|
||||
raise ValidationError('line_keys required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
|
||||
raise ValidationError('snapshot_line_ids required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
|
||||
if len(keys) != len(set(keys)):
|
||||
raise ValidationError('Duplicate line_keys', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
|
||||
raise ValidationError('Duplicate snapshot_line_ids', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
|
||||
source = str(decision_source or 'system').strip()
|
||||
if source not in {'system', 'user'}:
|
||||
raise ValidationError('Invalid decision_source', code='SHIPPING.REVIEW_DECISION_SOURCE_INVALID')
|
||||
@@ -197,12 +197,12 @@ def create_post_ot_fulfillment_wave(
|
||||
'Formal OT required for post-OT fulfillment wave',
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_REQUIRES_OT',
|
||||
)
|
||||
task: ShippingNotice = formal['task']
|
||||
task: ShippingOrderTask = formal['task']
|
||||
|
||||
projected = project_review_case_line_decisions(case)
|
||||
projected_lines = [item for item in list(projected.get('lines') or []) if isinstance(item, dict)]
|
||||
by_key = {
|
||||
str(item.get('line_key') or ''): item
|
||||
str(item.get('snapshot_line_id') or ''): item
|
||||
for item in projected_lines
|
||||
}
|
||||
snap_id, snap_fp = _snapshot_fingerprint(projected_lines, keys)
|
||||
@@ -217,7 +217,7 @@ def create_post_ot_fulfillment_wave(
|
||||
if existing is not None:
|
||||
if _params_conflict(
|
||||
existing,
|
||||
line_keys=keys,
|
||||
snapshot_line_ids=[int(k) for k in keys],
|
||||
fingerprint=snap_fp,
|
||||
decision_source=source,
|
||||
):
|
||||
@@ -226,7 +226,7 @@ def create_post_ot_fulfillment_wave(
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT',
|
||||
details={
|
||||
'idempotency_key': idem_key,
|
||||
'existing_line_keys_hash': existing.line_keys_hash,
|
||||
'existing_snapshot_line_ids_hash': existing.snapshot_line_ids_hash,
|
||||
'existing_snapshot_fingerprint': existing.inventory_snapshot_fingerprint,
|
||||
'existing_decision_source': existing.decision_source,
|
||||
},
|
||||
@@ -238,15 +238,15 @@ def create_post_ot_fulfillment_wave(
|
||||
return replay
|
||||
|
||||
assigned = {
|
||||
str(row.line_key)
|
||||
str(int(row.snapshot_line_id))
|
||||
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
|
||||
}
|
||||
|
||||
accepted: list[str] = []
|
||||
skipped: list[str] = []
|
||||
accepted_snapshot_line_ids: list[str] = []
|
||||
skipped_snapshot_line_ids: list[str] = []
|
||||
for key in keys:
|
||||
if key in assigned:
|
||||
skipped.append(key)
|
||||
skipped_snapshot_line_ids.append(key)
|
||||
continue
|
||||
line = by_key.get(key)
|
||||
if line is None:
|
||||
@@ -255,14 +255,14 @@ def create_post_ot_fulfillment_wave(
|
||||
raise ConflictError(
|
||||
'Closed line cannot enter wave',
|
||||
code='SHIPPING.REVIEW_LINE_CLOSED',
|
||||
details={'line_key': key},
|
||||
details={'snapshot_line_id': key},
|
||||
)
|
||||
_assert_fact_allows_fulfill(line)
|
||||
accepted.append(key)
|
||||
accepted_snapshot_line_ids.append(key)
|
||||
|
||||
wave_no = None
|
||||
notice = None
|
||||
if accepted:
|
||||
if accepted_snapshot_line_ids:
|
||||
max_wave = (
|
||||
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
|
||||
.filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id))
|
||||
@@ -272,89 +272,89 @@ def create_post_ot_fulfillment_wave(
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
_persist_wave_lines_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
source_notice = _source_notice_for_order_facts(task)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id)
|
||||
snapshot_line_ids = {
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
selected_snapshot_line_ids = {
|
||||
int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id)
|
||||
for key in accepted
|
||||
for key in accepted_snapshot_line_ids
|
||||
if snapshot is not None
|
||||
and (by_key[key] or {}).get('line_index') is not None
|
||||
and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines)
|
||||
}
|
||||
if len(snapshot_line_ids) != len(accepted):
|
||||
if len(selected_snapshot_line_ids) != len(accepted_snapshot_line_ids):
|
||||
raise ConflictError(
|
||||
'Selected review lines do not map to frozen order lines',
|
||||
code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING',
|
||||
)
|
||||
order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None
|
||||
if order_task is None:
|
||||
raise ConflictError(
|
||||
'Formal notice is not linked to an order task',
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED',
|
||||
)
|
||||
order_task = task
|
||||
# [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照;
|
||||
# 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。
|
||||
if task.customer_id is None:
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
|
||||
|
||||
if customer_confirmation_facts(order_task)['customer_id'] is None:
|
||||
raise ConflictError(
|
||||
'Formal notice customer is required before creating a fulfillment wave',
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED',
|
||||
)
|
||||
notice = ShippingNotice(
|
||||
task_no=generate_task_no(),
|
||||
order_task_id=int(order_task.id),
|
||||
customer_id=task.customer_id,
|
||||
customer_name_snapshot=task.customer_name_snapshot,
|
||||
customer_short_code_snapshot=task.customer_short_code_snapshot,
|
||||
user_id=task.user_id,
|
||||
conversation_id=task.conversation_id,
|
||||
source_type='post_ot_fulfillment_wave',
|
||||
inventory_source_code=task.inventory_source_code,
|
||||
inventory_connector_type=task.inventory_connector_type,
|
||||
inventory_warehouse_id=task.inventory_warehouse_id,
|
||||
inventory_source_status=task.inventory_source_status,
|
||||
inventory_source_method=task.inventory_source_method,
|
||||
inventory_source_config_version=task.inventory_source_config_version,
|
||||
inventory_routing_fingerprint=task.inventory_routing_fingerprint,
|
||||
inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
customer_resolution_method=task.customer_resolution_method,
|
||||
customer_identity_fingerprint=task.customer_identity_fingerprint,
|
||||
customer_confirmed_by=task.customer_confirmed_by,
|
||||
customer_confirmed_at=task.customer_confirmed_at,
|
||||
from app.services.shipping_notice.shipping_notice_creation_service import (
|
||||
create_shipping_notice_after_inventory_gate,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
notice.customer_resolution_status = 'confirmed'
|
||||
replace_notice_lines_from_snapshot(
|
||||
notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids,
|
||||
notice = create_shipping_notice_after_inventory_gate(
|
||||
order_task,
|
||||
snapshot_line_ids=selected_snapshot_line_ids,
|
||||
source_type='post_ot_fulfillment_wave',
|
||||
)
|
||||
_persist_wave_lines_for_task(
|
||||
case=case,
|
||||
task=notice,
|
||||
line_keys=accepted,
|
||||
snapshot_line_ids=list(selected_snapshot_line_ids),
|
||||
wave_no=wave_no,
|
||||
revision_id=None,
|
||||
)
|
||||
# [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。
|
||||
from app.services.shipping_notice.inventory_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',
|
||||
details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 写入/推进履约决定(含已在 wave 的幂等行)
|
||||
draft_lines = _draft_line_map(case)
|
||||
draft_lines_by_index = {
|
||||
int(row.get('_line_index')): row
|
||||
for row in draft_lines.values()
|
||||
if row.get('_line_index') is not None
|
||||
}
|
||||
now = datetime.utcnow()
|
||||
for key in keys:
|
||||
line = by_key.get(key) or {}
|
||||
current = _active_decision(case, key)
|
||||
line_index = line.get('line_index')
|
||||
draft_line = draft_lines_by_index.get(int(line_index)) if line_index is not None else None
|
||||
draft_line_id = str(
|
||||
(line or {}).get('draft_line_id') or (draft_line or {}).get('_draft_line_id') or ''
|
||||
).strip()
|
||||
if not draft_line_id:
|
||||
raise ConflictError(
|
||||
'Selected review line is missing draft identity',
|
||||
code='SHIPPING.REVIEW_LINE_DRAFT_MAPPING_MISSING',
|
||||
details={'snapshot_line_id': key},
|
||||
)
|
||||
current = _active_decision(case, draft_line_id)
|
||||
if current is not None and current.line_status in {'task_created', 'fulfilled'}:
|
||||
continue
|
||||
# [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中,
|
||||
# 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。
|
||||
if (
|
||||
key in accepted
|
||||
key in accepted_snapshot_line_ids
|
||||
and current is not None
|
||||
and current.decision_code == 'release_inventory_shortage'
|
||||
):
|
||||
current.line_status = 'task_created'
|
||||
current.task_id = int(notice.id)
|
||||
current.task_id = int(order_task.id)
|
||||
current.wave_no = int(wave_no) if wave_no is not None else None
|
||||
current.updated_at = now
|
||||
continue
|
||||
@@ -365,20 +365,20 @@ def create_post_ot_fulfillment_wave(
|
||||
avail = str(line.get('available_qty') or '') or None
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
line_key=key,
|
||||
line_index=(draft_lines.get(key) or {}).get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
draft_line_id=draft_line_id,
|
||||
line_index=line_index,
|
||||
decision_version=_next_version(case, draft_line_id),
|
||||
decision_code=DECISION_FULFILL,
|
||||
decision_source=source,
|
||||
line_status='task_created' if key in assigned or key in accepted else _STATUS_BY_DECISION[DECISION_FULFILL],
|
||||
line_status='task_created' if key in assigned or key in accepted_snapshot_line_ids else _STATUS_BY_DECISION[DECISION_FULFILL],
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
required_qty=req,
|
||||
available_qty=avail,
|
||||
reservation_id=line.get('reservation_id'),
|
||||
part_number=line.get('part_number'),
|
||||
task_id=int(notice.id) if key in accepted else int(task.id),
|
||||
wave_no=wave_no if key in accepted else (
|
||||
task_id=int(order_task.id),
|
||||
wave_no=wave_no if key in accepted_snapshot_line_ids else (
|
||||
int(current.wave_no) if current is not None and current.wave_no is not None else None
|
||||
),
|
||||
actor_user_id=int(actor_user_id) if actor_user_id is not None else None,
|
||||
@@ -392,14 +392,14 @@ def create_post_ot_fulfillment_wave(
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
if key in accepted:
|
||||
if key in accepted_snapshot_line_ids:
|
||||
row.line_status = 'task_created'
|
||||
row.wave_no = wave_no
|
||||
elif key in assigned:
|
||||
row.line_status = 'task_created'
|
||||
existing_wave = (
|
||||
ShippingOrderReviewWaveLine.query
|
||||
.filter_by(review_case_id=int(case.id), line_key=key)
|
||||
.filter_by(review_case_id=int(case.id), snapshot_line_id=int((line or {}).get('snapshot_line_id') or key))
|
||||
.first()
|
||||
)
|
||||
if existing_wave is not None:
|
||||
@@ -418,11 +418,11 @@ def create_post_ot_fulfillment_wave(
|
||||
review_case_no=str(case.case_no),
|
||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||
task_no=str(task.task_no),
|
||||
before={'line_keys': keys},
|
||||
before={'snapshot_line_ids': [int(item) for item in keys]},
|
||||
after={
|
||||
'wave_no': wave_no,
|
||||
'accepted_line_keys': accepted,
|
||||
'skipped_line_keys': skipped,
|
||||
'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids],
|
||||
'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids],
|
||||
'decision_source': source,
|
||||
'idempotency_key': idem_key,
|
||||
},
|
||||
@@ -430,13 +430,13 @@ def create_post_ot_fulfillment_wave(
|
||||
|
||||
result = {
|
||||
'case_no': case.case_no,
|
||||
'task_no': notice.task_no if notice is not None else task.task_no,
|
||||
'task_id': int(notice.id) if notice is not None else int(task.id),
|
||||
'task_no': task.task_no,
|
||||
'task_id': int(task.id),
|
||||
'review_case_id': int(case.id),
|
||||
'wave_no': wave_no,
|
||||
'notice_no': notice.task_no if notice is not None else None,
|
||||
'accepted_line_keys': accepted,
|
||||
'skipped_line_keys': skipped,
|
||||
'notice_no': notice.business_no if notice is not None else None,
|
||||
'accepted_snapshot_line_ids': [int(item) for item in accepted_snapshot_line_ids],
|
||||
'skipped_snapshot_line_ids': [int(item) for item in skipped_snapshot_line_ids],
|
||||
'decision_source': source,
|
||||
'idempotent_replay': False,
|
||||
'line_fulfillment': project_review_case_line_decisions(case),
|
||||
@@ -448,12 +448,12 @@ def create_post_ot_fulfillment_wave(
|
||||
idem_row = ShippingOrderReviewWaveIdempotency(
|
||||
idempotency_key=persist_key,
|
||||
review_case_id=int(case.id),
|
||||
task_id=int(notice.id) if notice is not None else int(task.id),
|
||||
task_no=str(notice.task_no if notice is not None else task.task_no),
|
||||
task_id=int(task.id),
|
||||
task_no=str(task.task_no),
|
||||
wave_no=wave_no,
|
||||
decision_source=source,
|
||||
line_keys_json=_stable_line_keys(keys),
|
||||
line_keys_hash=_line_keys_hash(keys),
|
||||
snapshot_line_ids_json=[int(item) for item in keys],
|
||||
snapshot_line_ids_hash=_snapshot_line_ids_hash([int(item) for item in keys]),
|
||||
inventory_snapshot_id=snap_id,
|
||||
inventory_snapshot_fingerprint=snap_fp,
|
||||
status='succeeded',
|
||||
@@ -471,7 +471,7 @@ def create_post_ot_fulfillment_wave(
|
||||
return result
|
||||
|
||||
|
||||
def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
|
||||
def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> list[str]:
|
||||
"""
|
||||
列出可自动/人工履约的行(ready+matched+未关闭+未终态)。
|
||||
|
||||
@@ -482,7 +482,7 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
|
||||
case: 复核 Case。
|
||||
|
||||
Returns:
|
||||
line_key 列表。
|
||||
snapshot_line_id 列表。
|
||||
"""
|
||||
projected = project_review_case_line_decisions(case)
|
||||
out: list[str] = []
|
||||
@@ -509,5 +509,5 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
|
||||
avail is not None and avail < req and not is_released_shortage
|
||||
):
|
||||
continue
|
||||
out.append(str(item.get('line_key') or ''))
|
||||
out.append(str(item.get('snapshot_line_id') or ''))
|
||||
return [k for k in out if k]
|
||||
@@ -17,7 +17,7 @@ from app.models import (
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingProcessExecution,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
@@ -52,7 +52,7 @@ def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set
|
||||
"""
|
||||
owners: set[int] = set()
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
if task is not None and task.user_id is not None:
|
||||
owners.add(int(task.user_id))
|
||||
if execution.review_case_id is not None:
|
||||
@@ -201,7 +201,8 @@ def _record_permission_denied(
|
||||
"""
|
||||
task_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
from app.models import ShippingOrderTask
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
task_no = str(task.task_no) if task is not None else None
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_permission_denied',
|
||||
@@ -241,7 +242,8 @@ def execution_audit_scope_keys(execution: ShippingProcessExecution) -> dict[str,
|
||||
task_no = None
|
||||
case_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
from app.models import ShippingOrderTask
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
task_no = str(task.task_no) if task is not None else None
|
||||
if execution.review_case_id is not None:
|
||||
case = db.session.get(ShippingOrderReviewCase, int(execution.review_case_id))
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.audit_query_service import serialize_shipping_audit_event
|
||||
from app.services.shipping_notice.process_gate_access_service import execution_audit_scope_keys
|
||||
@@ -79,7 +79,7 @@ def serialize_execution_admin_summary(execution: ShippingProcessExecution) -> di
|
||||
).first()
|
||||
task_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
task_no = str(task.task_no) if task is not None else None
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
@@ -160,7 +160,7 @@ def list_admin_process_executions(
|
||||
like = f'%{keyword}%'
|
||||
task_ids = [
|
||||
int(row.id)
|
||||
for row in ShippingNotice.query.filter(ShippingNotice.task_no.ilike(like)).limit(200).all()
|
||||
for row in ShippingOrderTask.query.filter(ShippingOrderTask.task_no.ilike(like)).limit(200).all()
|
||||
]
|
||||
filters = [ShippingProcessExecution.execution_no.ilike(like)]
|
||||
if task_ids:
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
@@ -39,36 +40,48 @@ from app.services.shipping_notice.process_gate_service import (
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _derived_fulfillment_status(task: ShippingNotice) -> str:
|
||||
def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str:
|
||||
"""从领域结果事实推导履约分支,不读取旧流程状态字段。"""
|
||||
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
|
||||
if upload_status in {'uploaded', 'succeeded', 'success'}:
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
|
||||
upload_attempt = latest_upload_attempt(task)
|
||||
upload_status = str(getattr(upload_attempt, 'status', None) or '').strip().lower()
|
||||
if has_verified_upload_success(task):
|
||||
return 'uploaded'
|
||||
pending = str(getattr(task, 'pending_human_reason', None) or '').strip()
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
pending = str(task_blocking_reason(task) or '').strip()
|
||||
if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}:
|
||||
return 'waiting_inventory'
|
||||
if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
|
||||
return 'waiting_upload'
|
||||
if upload_status == 'failed':
|
||||
return 'upload_failed'
|
||||
if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json:
|
||||
return 'shortage_review'
|
||||
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
current_inventory_matches_have_shortage,
|
||||
inventory_matches_complete_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
)
|
||||
|
||||
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
|
||||
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'
|
||||
if str(getattr(task, 'export_file_path', None) or '').strip():
|
||||
return 'inventory_ready'
|
||||
if isinstance(getattr(task, 'inventory_lines_json', None), list) and task.inventory_lines_json:
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
if has_ready_inventory_file_for_task(task):
|
||||
return 'inventory_ready'
|
||||
return 'created'
|
||||
|
||||
|
||||
def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) -> str:
|
||||
"""
|
||||
由任务事实推导库存准备门禁阻断原因码。
|
||||
|
||||
核心逻辑:pending_human_reason 与最近 inventory_rpa_failed 事件优先于泛化
|
||||
inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
|
||||
核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt
|
||||
失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。
|
||||
惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。
|
||||
|
||||
Args:
|
||||
@@ -84,7 +97,8 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event
|
||||
|
||||
pending = str(task.pending_human_reason or '').strip()
|
||||
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'
|
||||
if pending == PH_RPA_EXHAUSTED:
|
||||
@@ -112,6 +126,39 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
return 'inventory_file_identity_mismatch'
|
||||
return 'inventory_rpa_export_failed'
|
||||
|
||||
# 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧
|
||||
# ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
latest_attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter(
|
||||
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(),
|
||||
)
|
||||
.order_by(
|
||||
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
|
||||
ShippingTaskInventoryRpaAttempt.id.desc(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {'failed', 'exhausted'}:
|
||||
blob = ' '.join([
|
||||
str(latest_attempt.status or '').strip().lower(),
|
||||
str(latest_attempt.error_code or '').strip().lower(),
|
||||
str(latest_attempt.error_message or '').strip().lower(),
|
||||
])
|
||||
if 'exhausted' in blob:
|
||||
return 'inventory_rpa_exhausted'
|
||||
if 'timeout' in blob or ('not ready' in blob and 'within' in blob):
|
||||
return 'inventory_rpa_timeout'
|
||||
if 'login' in blob or 'auth' in blob:
|
||||
return 'inventory_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'
|
||||
|
||||
# inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计,
|
||||
# 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。
|
||||
if pending == PH_INV_UNAVAIL:
|
||||
@@ -120,7 +167,7 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
# 未持久化测试对象仍携带 ``[]`` 时,明确表达“文件已解析但无库存行”。
|
||||
# ``None`` 才表示未得到库存文件,避免把空文件误投影成缺文件。
|
||||
if getattr(task, 'id', None) is None:
|
||||
return 'inventory_file_empty' if getattr(task, 'inventory_lines_json', None) == [] else 'inventory_file_missing'
|
||||
return 'inventory_file_missing'
|
||||
|
||||
# [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
@@ -141,7 +188,7 @@ _FREIGHT_UPLOAD_RPA_REASON_CODES = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def manual_upload_reason_code(task: ShippingNotice) -> str:
|
||||
def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str:
|
||||
"""
|
||||
由任务事实推导货代上传相关阻断原因码。
|
||||
|
||||
@@ -158,7 +205,8 @@ def manual_upload_reason_code(task: ShippingNotice) -> str:
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
)
|
||||
|
||||
pending = str(task.pending_human_reason or '').strip()
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
pending = str(task_blocking_reason(task) or '').strip()
|
||||
status = _derived_fulfillment_status(task)
|
||||
if pending == PH_UPLOAD_RPA_PENDING:
|
||||
return 'upload_rpa_pending'
|
||||
@@ -243,11 +291,20 @@ def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExe
|
||||
)
|
||||
|
||||
|
||||
def find_execution_for_task(task: ShippingNotice) -> ShippingProcessExecution | None:
|
||||
"""按 Task 查找绑定的 Execution。"""
|
||||
def find_execution_for_task(task: ShippingOrderTask | ShippingNotice) -> ShippingProcessExecution | None:
|
||||
"""按 OT 查找绑定的 Execution;正式 Notice 入口仅沿 order_task_id 定位其 OT。"""
|
||||
task_id = (
|
||||
int(task.id)
|
||||
if isinstance(task, ShippingOrderTask) and getattr(task, 'id', None) is not None
|
||||
else int(task.order_task_id)
|
||||
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None) is not None
|
||||
else None
|
||||
)
|
||||
if task_id is None:
|
||||
return None
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter_by(task_id=task_id)
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
@@ -348,7 +405,7 @@ def mark_gates_passed_through(
|
||||
"""
|
||||
将 sequence 不大于 through_gate_code 且仍为 pending/skipped 的门禁标记为 passed。
|
||||
|
||||
核心逻辑:用于人工确认建单后一次性推进到 task_creation;已阻断门禁不静默覆盖。
|
||||
核心逻辑:用于人工确认建单后推进已满足的前置门禁;已阻断门禁不静默覆盖。
|
||||
|
||||
Returns:
|
||||
实际推进的 gate_code 列表。
|
||||
@@ -368,11 +425,9 @@ def mark_gates_passed_through(
|
||||
break
|
||||
if gate.status in {'passed', 'skipped'}:
|
||||
continue
|
||||
if gate.status not in {'pending', 'blocked_manual', 'blocked_retryable', 'invalidated', 'queued'}:
|
||||
continue
|
||||
# 仅放行人工确认可覆盖的冻结就绪与前置 pending;技术失败不覆盖。
|
||||
if gate.status == 'failed_terminal':
|
||||
if gate.status not in {'pending', 'skipped'}:
|
||||
continue
|
||||
# 人工确认只能推进仍未评估的前置门禁;任何真实阻断必须保留。
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code=gate.gate_code,
|
||||
@@ -394,7 +449,7 @@ def mark_gates_passed_through(
|
||||
def sync_execution_after_review_confirm(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
actor_id: int,
|
||||
) -> ShippingProcessExecution | None:
|
||||
"""
|
||||
@@ -407,7 +462,7 @@ def sync_execution_after_review_confirm(
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
task: 本波次新建的 ShippingNotice。
|
||||
task: 复核确认生成的 ShippingOrderTask。
|
||||
actor_id: 确认操作人。
|
||||
|
||||
Returns:
|
||||
@@ -436,13 +491,74 @@ def sync_execution_after_review_confirm(
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
)
|
||||
mark_gates_passed_through(
|
||||
# Task 已真实创建并绑定 Execution,先收口 task_creation;后续 Gate 不得越过该事实。
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
through_gate_code='task_creation',
|
||||
gate_code='task_creation',
|
||||
passed=True,
|
||||
effective_result={'findings': [], 'task_id': int(task.id), 'task_no': task.task_no},
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
reason='review_confirmed',
|
||||
idempotency_key=f'task-creation-after-confirm:{execution.execution_no}:{task.id}',
|
||||
force=True,
|
||||
)
|
||||
# Snapshot 已在确认事务中成功冻结;该事实单独收口 order_freeze_readiness。
|
||||
from app.models import ShippingOrderSnapshot
|
||||
|
||||
snapshot_id = getattr(task, 'order_snapshot_id', None)
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(snapshot_id))
|
||||
if snapshot_id is not None else None
|
||||
)
|
||||
if not (
|
||||
snapshot is not None
|
||||
and int(getattr(snapshot, 'task_id', 0) or 0) == int(task.id)
|
||||
and int(getattr(snapshot, 'extraction_id', 0) or 0) == int(task.current_order_extraction_id or 0)
|
||||
):
|
||||
return execution
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='order_freeze_readiness',
|
||||
passed=True,
|
||||
effective_result={'findings': [], 'task_id': int(task.id), 'snapshot_id': int(snapshot_id)},
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'order-freeze-after-confirm:{execution.execution_no}:{snapshot_id}',
|
||||
force=True,
|
||||
)
|
||||
# [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。
|
||||
# CandidateSet 是 inventory_source_routing 通过的必要业务事实。
|
||||
from app.services.shipping_notice.inventory_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
|
||||
|
||||
if not task_frozen_inventory_source_codes(task):
|
||||
# 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。
|
||||
return execution
|
||||
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_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),
|
||||
'status': str(adjudication.status or 'resolved'),
|
||||
},
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
idempotency_key=(
|
||||
f'inventory-routing-after-confirm:{execution.execution_no}:'
|
||||
f'{task.active_inventory_candidate_set_id}'
|
||||
),
|
||||
force=True,
|
||||
)
|
||||
|
||||
# [STEP] 建单后立即按 Task 状态投影履约门禁,避免 13–19 长期停留 pending。
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
@@ -785,12 +901,13 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
|
||||
if (
|
||||
_derived_fulfillment_status(task) != 'waiting_inventory'
|
||||
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
|
||||
or str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING
|
||||
):
|
||||
return
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
@@ -857,7 +974,7 @@ def sync_fulfillment_gates_from_task(
|
||||
"""
|
||||
if not execution.task_id:
|
||||
return
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
if task is None:
|
||||
return
|
||||
|
||||
@@ -868,19 +985,29 @@ def sync_fulfillment_gates_from_task(
|
||||
actor_id=actor_id,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
inventory_match_facts_complete,
|
||||
match_completed,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
active_inventory_lines_for_task,
|
||||
)
|
||||
|
||||
match_status = str(task.match_status or '').strip()
|
||||
has_export = bool(str(task.export_file_path or '').strip())
|
||||
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
has_inventory_lines = bool(
|
||||
inv_file is not None
|
||||
and str(getattr(inv_file, 'snapshot_status', '') or '').strip().lower() == 'ready'
|
||||
and getattr(inv_file, 'invalidated_at', None) is None
|
||||
and active_inventory_lines_for_task(task)
|
||||
)
|
||||
status = _derived_fulfillment_status(task)
|
||||
# [STEP 1A] 已验证并绑定的库存行是库存准备的正式成功事实。RPA 回调与
|
||||
# 旧失败/超时 Attempt 可以乱序到达;不能让遗留的 rpa_exhausted 把已成功
|
||||
# 入库的任务重新投影为 waiting_inventory,否则 Gate 会停在“手工上传”。
|
||||
if has_inventory_lines and status == 'waiting_inventory':
|
||||
status = 'inventory_ready'
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
|
||||
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
|
||||
done_statuses = {'uploaded', 'closed'}
|
||||
@@ -918,16 +1045,10 @@ def sync_fulfillment_gates_from_task(
|
||||
force=True,
|
||||
)
|
||||
return
|
||||
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
|
||||
sufficiency_ok = match_completed(task)
|
||||
shortage = (not sufficiency_ok) and (
|
||||
match_status in {'unfulfillable', 'partial'}
|
||||
or bool(task.shortage_json)
|
||||
or status == 'shortage_review'
|
||||
)
|
||||
match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in {
|
||||
'matched', 'waiting_upload', 'upload_failed', *done_statuses,
|
||||
}
|
||||
match_passed = inventory_match_facts_complete(task)
|
||||
shortage = match_passed and not sufficiency_ok
|
||||
match_status = 'fulfillable' if sufficiency_ok else ('unfulfillable' if match_passed else None)
|
||||
# 手动上传文件也必须由已发布库存模板自动映射;若尚未完成,只能进入系统
|
||||
# 可重试状态,不能产生“人工确认字段映射”业务节点。
|
||||
source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None
|
||||
@@ -993,7 +1114,7 @@ def sync_fulfillment_gates_from_task(
|
||||
})
|
||||
# Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能
|
||||
# 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。
|
||||
task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted'
|
||||
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,
|
||||
@@ -1029,7 +1150,7 @@ def sync_fulfillment_gates_from_task(
|
||||
if status == 'waiting_inventory':
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
pending_reason = str(task_blocking_reason(task) or '').strip()
|
||||
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或历史次数耗尽时
|
||||
# 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。
|
||||
if pending_reason == PH_RPA_PENDING:
|
||||
@@ -1062,7 +1183,9 @@ def sync_fulfillment_gates_from_task(
|
||||
force=True,
|
||||
)
|
||||
return
|
||||
inv_prep_passed = status in post_inventory or has_inventory_lines
|
||||
# 库存准备的成功事实只能是已验证并绑定的库存行。下游状态可能因历史脏数据、
|
||||
# 并发投影或错误侧路动作残留,绝不能反向证明库存文件已经准备完成。
|
||||
inv_prep_passed = has_inventory_lines
|
||||
inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -1124,11 +1247,9 @@ def sync_fulfillment_gates_from_task(
|
||||
classify_inventory_match_reason,
|
||||
)
|
||||
|
||||
line_results = (
|
||||
list(task.line_results_json)
|
||||
if isinstance(task.line_results_json, list)
|
||||
else []
|
||||
)
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
line_results = [{'disposition': row.match_result} for row in current_match_rows]
|
||||
match_reason = None if match_passed else classify_inventory_match_reason(
|
||||
line_results=line_results,
|
||||
match_status=match_status,
|
||||
@@ -1190,7 +1311,11 @@ def sync_fulfillment_gates_from_task(
|
||||
)
|
||||
),
|
||||
'match_status': match_status or None,
|
||||
'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None,
|
||||
'shortage': [
|
||||
{'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty}
|
||||
for row in current_match_rows
|
||||
if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'}
|
||||
],
|
||||
},
|
||||
blocking_reason_code=None if sufficiency_ok else str(shortage_reason or 'inventory_insufficient'),
|
||||
actor_type=actor_type,
|
||||
@@ -1198,6 +1323,7 @@ def sync_fulfillment_gates_from_task(
|
||||
idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}',
|
||||
force=True,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
|
||||
# [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。
|
||||
# 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。
|
||||
excel_error = excel_gate_error(task)
|
||||
@@ -1225,6 +1351,17 @@ def sync_fulfillment_gates_from_task(
|
||||
if not excel_ready:
|
||||
return
|
||||
|
||||
# [STEP 6A] 正式 Notice 仅在库存门禁通过后的产物生成动作中创建。通知准备
|
||||
# 及 Excel 资格检查必须只读 OT;进入产物/上传后段才允许读取 Notice 事实。
|
||||
formal_notice = (
|
||||
ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
export_artifact = latest_export_artifact(formal_notice) if formal_notice is not None else None
|
||||
has_export = export_artifact is not None
|
||||
status = None
|
||||
if formal_notice is not None:
|
||||
status = _derived_fulfillment_status(formal_notice)
|
||||
artifact_ok = has_export or status in done_statuses
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
@@ -1254,7 +1391,7 @@ def sync_fulfillment_gates_from_task(
|
||||
|
||||
# [STEP 7] freight_upload_rpa(RPA)与 manual_upload_handoff(真正人工)分离。
|
||||
uploaded = status in done_statuses
|
||||
upload_reason = None if uploaded else manual_upload_reason_code(task)
|
||||
upload_reason = None if uploaded else manual_upload_reason_code(formal_notice or task)
|
||||
task_details = {
|
||||
'derived_fulfillment_status': status or None,
|
||||
'task_no': str(task.task_no or '') or None,
|
||||
|
||||
@@ -196,23 +196,21 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'gate_code': 'task_creation',
|
||||
'sequence_no': 10,
|
||||
'label': '库存源路由',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'},
|
||||
'responsible_party': 'owner',
|
||||
'label': '订单任务创建',
|
||||
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'},
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_with_latest_rules',
|
||||
# 库存源由规则自动裁决;规则冲突属于配置/数据治理,不允许用户人工选源。
|
||||
'blocked_manual': 'retry_with_latest_rules',
|
||||
'blocked_retryable': 'retry_task_creation',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'sequence_no': 11,
|
||||
'label': '订单冻结资格',
|
||||
'label': '订单冻结完成',
|
||||
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'freeze_readiness'},
|
||||
'responsible_party': 'system',
|
||||
'implementation_status': 'implemented',
|
||||
@@ -223,15 +221,16 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'task_creation',
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'sequence_no': 12,
|
||||
'label': 'ShippingNotice 创建',
|
||||
'ui_placement': {'target_surface': 'order_review', 'target_anchor': 'task_creation'},
|
||||
'responsible_party': 'system',
|
||||
'label': '库存源路由',
|
||||
'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'},
|
||||
'responsible_party': 'owner',
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_task_creation',
|
||||
'blocked_retryable': 'retry_with_latest_rules',
|
||||
'blocked_manual': 'retry_with_latest_rules',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -373,6 +372,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'retry_inventory_from_preparation',
|
||||
'retry_inventory_from_field_mapping',
|
||||
'retry_inventory_from_matching',
|
||||
'override_line_inventory_source',
|
||||
'open_inventory_match_review',
|
||||
'recheck_inventory_sufficiency',
|
||||
'open_shortage_review',
|
||||
@@ -473,13 +473,21 @@ def inventory_preparation_primary_action(
|
||||
status: str | None,
|
||||
blocking_reason_code: str | None = None,
|
||||
) -> str | None:
|
||||
"""裁决库存准备 Gate 面向业务用户的主动作。"""
|
||||
"""裁决库存准备 Gate 面向业务用户的主动作。
|
||||
|
||||
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
|
||||
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
|
||||
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
|
||||
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
||||
``retry_inventory_matching``。
|
||||
"""
|
||||
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 'reload_inventory_result'
|
||||
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
|
||||
return 'retry_inventory_matching'
|
||||
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
|
||||
return 'retry_inventory_preparation'
|
||||
return None
|
||||
@@ -490,6 +498,53 @@ def is_technical_gate_party(responsible_party: str | None) -> bool:
|
||||
return str(responsible_party or '').strip() in PROCESS_GATE_TECHNICAL_PARTIES
|
||||
|
||||
|
||||
def gate_side_recovery_actions(
|
||||
*,
|
||||
gate_code: str,
|
||||
status: str | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
) -> tuple[str, ...]:
|
||||
"""
|
||||
返回当前阻断状态下,除主动作外业务用户仍可提交的侧路恢复动作序列。
|
||||
|
||||
核心逻辑:投影层(serialize_process_gate 的 allowed_actions 侧路)与校验层
|
||||
(request_gate_action 的 allowed_side)必须共用同一份裁决,禁止各自硬编码,
|
||||
否则会出现「投影放行按钮、校验却拒绝提交」的漂移(如 RPA 超时/耗尽时点击
|
||||
「重新获取库存 (RPA)」被报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。
|
||||
这些动作由 Gate 契约或状态显式允许;仅用于展示/提交统一入口,不改变主动作。
|
||||
|
||||
Args:
|
||||
gate_code: 当前阻断 Gate 编码。
|
||||
status: Gate 状态(如 blocked_retryable / blocked_manual / waiting_external)。
|
||||
blocking_reason_code: 阻断原因码。
|
||||
|
||||
Returns:
|
||||
允许的侧路动作码序列(有序,保证投影 allowed_actions 顺序稳定);无则空元组。
|
||||
"""
|
||||
code = str(gate_code or '').strip().lower()
|
||||
reason = str(blocking_reason_code or '').strip().lower()
|
||||
sides: list[str] = []
|
||||
# [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照
|
||||
# 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。
|
||||
if (
|
||||
code == 'inventory_preparation'
|
||||
and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
|
||||
):
|
||||
sides.append('retry_inventory_preparation')
|
||||
# [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。
|
||||
if (
|
||||
code == 'manual_upload_handoff'
|
||||
and reason in {'manual_upload_pending', 'upload_result_unknown'}
|
||||
):
|
||||
sides.append('retry_freight_upload_rpa')
|
||||
# [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')
|
||||
return tuple(sides)
|
||||
|
||||
|
||||
PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'document_unavailable',
|
||||
'layout_parse_failed',
|
||||
@@ -822,10 +877,18 @@ 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 == 'inventory_sufficiency':
|
||||
if action == 'retry_inventory_matching' and code in {
|
||||
'inventory_preparation', 'inventory_matching', 'inventory_sufficiency',
|
||||
}:
|
||||
return True
|
||||
if action == 'reload_inventory_result' and code == 'inventory_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',
|
||||
}:
|
||||
return True
|
||||
navigation_owners = {
|
||||
'open_order_review': {'order_freeze_readiness', 'order_field_extraction'},
|
||||
'open_profile_review': {'document_profile_routing'},
|
||||
@@ -1173,8 +1236,8 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = {
|
||||
# ============================================================
|
||||
|
||||
INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = (
|
||||
'inventory_source_routing', # 路由规则计算(sub_stage=calculated)
|
||||
'order_freeze_readiness', # 候选冻结(建单瞬间,sub_stage=frozen)——注意:复用现有 Gate,避免 seq 漂移
|
||||
'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)
|
||||
)
|
||||
@@ -1241,3 +1304,72 @@ def user_mode_for_blocking_reason(reason_code: str | None) -> str | None:
|
||||
if not reason_code:
|
||||
return None
|
||||
return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip())
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 阶段能力集(Stage Capabilities)——一期:通知准备阶段
|
||||
# 能力可用性 = 阶段 + Excel 未生成 + 预条件(数据在场),不由门禁通过与否决定。
|
||||
# 与 PROCESS_GATE_ACTION_CODES(门禁恢复动作)语义不同:能力动作允许请求「非当前 gate」,
|
||||
# request_gate_action 对阶段能力豁免,并走 execute_stage_capability(作废下游——重置+重跑)。
|
||||
# ============================================================
|
||||
|
||||
STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = {
|
||||
'override_line_inventory_source': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'line',
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'invalidate': {
|
||||
'inventory_field_mapping', 'inventory_matching',
|
||||
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'reset_to': 'inventory_preparation',
|
||||
},
|
||||
'retry_inventory_preparation': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'retry_inventory_preparation',
|
||||
'invalidate': {
|
||||
'inventory_field_mapping', 'inventory_matching',
|
||||
'inventory_sufficiency', 'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'reset_to': 'inventory_preparation',
|
||||
},
|
||||
# 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。
|
||||
# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel,
|
||||
# 因此不重置回 inventory_preparation,也不作废上游 source/mapping。
|
||||
'retry_inventory_matching': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'invalidate': {
|
||||
'inventory_matching', 'inventory_sufficiency',
|
||||
'excel_readiness', 'artifact_generation',
|
||||
},
|
||||
'invalidate_change_type': 'inventory_field_mapping_changed',
|
||||
'reset_to': 'inventory_matching',
|
||||
},
|
||||
'reload_inventory_result': {
|
||||
'stage': 'fulfillment_prep',
|
||||
'scope': 'task',
|
||||
'action_code': 'reload_inventory_result',
|
||||
'invalidate': frozenset(),
|
||||
'reset_to': None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def stage_capability(action_code: str | None) -> dict[str, Any] | None:
|
||||
"""按动作码返回阶段能力定义;非阶段能力返回 None。"""
|
||||
code = str(action_code or '').strip()
|
||||
return STAGE_CAPABILITY_DEFINITIONS.get(code)
|
||||
|
||||
|
||||
def is_stage_capability(action_code: str | None) -> bool:
|
||||
"""判断动作码是否为阶段能力。"""
|
||||
return stage_capability(action_code) is not None
|
||||
|
||||
|
||||
def capability_stage(action_code: str | None) -> str | None:
|
||||
"""返回能力所属阶段码;非能力返回 None。"""
|
||||
cap = stage_capability(action_code)
|
||||
return str(cap['stage']) if cap else None
|
||||
@@ -151,10 +151,10 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'customer_resolution': ('reservation_validation',),
|
||||
'duplicate_detection': ('customer_resolution',),
|
||||
'field_conflict_resolution': ('duplicate_detection',),
|
||||
'inventory_source_routing': ('field_conflict_resolution',),
|
||||
'order_freeze_readiness': ('inventory_source_routing',),
|
||||
'task_creation': ('order_freeze_readiness',),
|
||||
'inventory_preparation': ('task_creation',),
|
||||
'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',),
|
||||
|
||||
@@ -18,6 +18,8 @@ from typing import Any, Callable
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
@@ -188,6 +190,7 @@ def _dispatch_action(
|
||||
'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,
|
||||
'recheck_excel_readiness': _handle_recheck_excel_readiness,
|
||||
'regenerate_excel_artifact': _handle_regenerate_excel,
|
||||
@@ -339,9 +342,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
|
||||
``_orchestrator_internal_dispatch``,禁止库存/Excel workflow 再次绕回
|
||||
``run_task_auto_progress``,把当前活动 Attempt 误判成“无待处理 Gate”。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
if task is None:
|
||||
raise ValidationError('Execution has no bound task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND')
|
||||
return {
|
||||
@@ -706,9 +707,7 @@ def _handle_retry_task_creation(
|
||||
)
|
||||
task_no = (result or {}).get('task_no')
|
||||
if task_no:
|
||||
from app.models import ShippingNotice
|
||||
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no)).first()
|
||||
task = ShippingOrderTask.query.filter_by(task_no=str(task_no)).first()
|
||||
if task is not None:
|
||||
bind_execution_task(
|
||||
execution_no=str(execution.execution_no),
|
||||
@@ -757,7 +756,7 @@ def _handle_retry_inventory_preparation(
|
||||
sync_fulfillment_gates_from_task,
|
||||
)
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_order_task(execution)
|
||||
recovery_plan_id = payload.get('recovery_plan_id')
|
||||
# Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。
|
||||
# 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。
|
||||
@@ -766,6 +765,33 @@ def _handle_retry_inventory_preparation(
|
||||
or payload.get('user_id')
|
||||
or payload.get('operator_id')
|
||||
)
|
||||
# [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。
|
||||
# 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。
|
||||
if task is not None:
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
get_active_candidate_lines,
|
||||
get_active_candidate_set,
|
||||
get_active_candidate_sources,
|
||||
)
|
||||
candidate_set = get_active_candidate_set(task)
|
||||
lines = get_active_candidate_lines(task)
|
||||
sources = get_active_candidate_sources(task)
|
||||
if (
|
||||
not task.order_snapshot_id
|
||||
or candidate_set is None
|
||||
or not sources
|
||||
or not lines
|
||||
or any(not list(getattr(line, 'source_codes_json', None) or []) for line in lines)
|
||||
):
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
'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'),
|
||||
'routing_required': True,
|
||||
},
|
||||
}
|
||||
if task is not None and payload.get('action_code') == 'poll_inventory_preparation':
|
||||
# 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。
|
||||
# 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。
|
||||
@@ -800,7 +826,11 @@ def _handle_retry_inventory_preparation(
|
||||
},
|
||||
}
|
||||
preparation_round = None
|
||||
is_initial_auto_dispatch = str(payload.get('trigger') or '') == 'gate_attempt_passed'
|
||||
is_manual_rpa_retry = str(payload.get('inventory_mode') or '').strip() == 'retry_rpa'
|
||||
is_initial_auto_dispatch = (
|
||||
str(payload.get('trigger') or '') == 'gate_attempt_passed'
|
||||
and not is_manual_rpa_retry
|
||||
)
|
||||
if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
|
||||
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
|
||||
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
|
||||
@@ -834,9 +864,19 @@ def _handle_retry_inventory_preparation(
|
||||
gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None,
|
||||
)
|
||||
inventory_payload = _task_payload(execution, payload)
|
||||
# 阶段能力重试在入队时统一保存为 line_scope_key;兼容旧 Attempt 仍可能携带 snapshot_line_id。
|
||||
inventory_payload['line_scope_key'] = (
|
||||
payload.get('line_scope_key')
|
||||
if payload.get('line_scope_key') is not None
|
||||
else payload.get('snapshot_line_id')
|
||||
)
|
||||
# 只有用户显式重试强制生成新 Attempt;首次自动投递应先尝试复用有效快照。
|
||||
if payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
|
||||
inventory_payload['mode'] = 'retry_rpa'
|
||||
if str(payload.get('action_code') or '') == 'poll_inventory_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
|
||||
@@ -861,6 +901,197 @@ def _handle_retry_inventory_preparation(
|
||||
return outcome
|
||||
|
||||
|
||||
def _handle_override_line_inventory_source(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
gate: ShippingProcessGate,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
人工覆写行级库存源(方案 3·放开):通知准备阶段(Excel 生成前)允许用户把某行库存源
|
||||
覆写为任一**已启用**库存源,而不仅限于规则候选。先放开、后续再收紧到仅候选源。
|
||||
|
||||
校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写;
|
||||
覆写后把该行候选钉为所选源并重跑该行匹配(snapshot 复用/触发 RPA 由既有
|
||||
auto-progress / ensure_inventory 处理:有未过期快照直接匹配,否则重新 RPA)。
|
||||
|
||||
Args:
|
||||
execution: 门禁执行上下文。
|
||||
gate: 当前门禁实例。
|
||||
payload: 含 line_no / source_code / 可选 reason、actor_user_id。
|
||||
|
||||
Returns:
|
||||
符合动作契约的 tool 响应。
|
||||
"""
|
||||
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 (
|
||||
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 (
|
||||
freeze_manual_line_source_selection,
|
||||
)
|
||||
|
||||
task = _resolve_order_task(execution)
|
||||
line_no_raw = payload.get('line_no')
|
||||
source_code = str(payload.get('source_code') or '').strip().upper()
|
||||
reason = str(payload.get('reason') or '').strip()[:500] or None
|
||||
actor_raw = payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id')
|
||||
try:
|
||||
line_no = int(line_no_raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID') from exc
|
||||
if task is None or not source_code or line_no < 1:
|
||||
raise ValidationError('line_no 与 source_code 必填', code='SHIPPING.LINE_SOURCE_INVALID')
|
||||
# Excel 是不可变输出边界(D7):生成后源锁定,改源只能走撤销/人工流程。
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
if (latest_export_artifact(task) is not None):
|
||||
raise ConflictError(
|
||||
'通知 Excel 已生成,库存源已锁定,请走撤销/人工纠错流程',
|
||||
code='SHIPPING.LINE_SOURCE_LOCKED',
|
||||
)
|
||||
# 方案 3:任一已启用源都允许(不限于规则候选)。
|
||||
enabled_codes = {
|
||||
str(item.get('source_code') or '').strip().upper()
|
||||
for item in list_database_inventory_sources(enabled_only=True)
|
||||
}
|
||||
if source_code not in enabled_codes or get_database_inventory_source(source_code) is None:
|
||||
raise ConflictError('所选库存源不存在或已停用', code='SHIPPING.LINE_SOURCE_UNAVAILABLE')
|
||||
try:
|
||||
actor_id = int(actor_raw) if actor_raw not in (None, '') else None
|
||||
except (TypeError, ValueError):
|
||||
actor_id = None
|
||||
try:
|
||||
candidate_result, all_lines_selected = freeze_manual_line_source_selection(
|
||||
task,
|
||||
line_no=line_no,
|
||||
source_code=source_code,
|
||||
actor_id=actor_id,
|
||||
reason=reason,
|
||||
execution_id=int(execution.id),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ConflictError(str(exc), code='SHIPPING.REVIEW_LINE_NOT_FOUND') from exc
|
||||
db.session.flush()
|
||||
record_fulfillment_audit(
|
||||
event_type='review_line_source_overridden',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=str(task.task_no),
|
||||
action='override_line_inventory_source',
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id,
|
||||
task_no=task.task_no,
|
||||
before={'line_no': line_no, 'previous_source_code': None},
|
||||
after={'line_no': line_no, 'selected_source_code': source_code, 'reason': reason},
|
||||
)
|
||||
if not all_lines_selected:
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'no_inventory_source_candidates',
|
||||
'effective_result_json': {
|
||||
'findings': [], 'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'selected_line_no': line_no, 'all_lines_selected': False,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'all_lines_selected': False,
|
||||
},
|
||||
}
|
||||
|
||||
# 首次人工选源完成的是 routing Gate 本身;让 Attempt 以 passed 收口后,
|
||||
# process_gate_service 会统一入队下一道 inventory_preparation,避免在当前
|
||||
# routing Attempt 内递归触发 RPA 而把 Gate 状态写错。
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {
|
||||
'findings': [], 'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'selected_line_no': line_no, 'all_lines_selected': True,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'candidate_set_id': candidate_result.candidate_set_id,
|
||||
'all_lines_selected': True,
|
||||
},
|
||||
}
|
||||
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
# [ROOT CAUSE FIX · RPA 不触发] 行级库存源覆写冻结新候选后,必须把 inventory_preparation Gate
|
||||
# 作为「定向人工恢复」重新推进:显式传 resume_gate_code='inventory_preparation' 与
|
||||
# inventory_mode='retry_rpa'。否则 AutoProgress 会读取该 Gate 残留的 next_action_code
|
||||
# (waiting_external → poll_inventory_preparation),只排队一个只读 poll,既不创建
|
||||
# InventoryPreparationAttempt 也不触发 RPA,最终永远停在 inventory_file_empty。
|
||||
# 与 execute_stage_capability 的「重新获取库存」路径保持同一语义(见 process_gate_service)。
|
||||
run_task_auto_progress(
|
||||
task.task_no,
|
||||
trigger='manual_override_source',
|
||||
operator_id=actor_id,
|
||||
resume_gate_code='inventory_preparation',
|
||||
inventory_mode='retry_rpa',
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
# 覆写库存源只改变后续取数/匹配的输入,不能把“库存准备”本身伪造成成功。
|
||||
# 续跑后必须以 Gate 同步得到的库存事实收口:只有有效库存快照已落库时才通过;
|
||||
# RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。
|
||||
db.session.flush()
|
||||
preparation_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_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
|
||||
if gate_status == 'passed':
|
||||
outcome = 'passed'
|
||||
elif gate_status in {'queued', 'running', 'waiting_external'}:
|
||||
outcome = 'waiting_external'
|
||||
else:
|
||||
outcome = 'blocked_retryable'
|
||||
return {
|
||||
'outcome': outcome,
|
||||
'blocking_reason_code': None if outcome == 'passed' else (
|
||||
reason_code or 'inventory_preparation_failed'
|
||||
),
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'inventory_preparation_status': gate_status or 'blocked_retryable',
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'inventory_preparation_status': gate_status or 'blocked_retryable',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_order_task(execution: ShippingProcessExecution) -> ShippingOrderTask | None:
|
||||
"""按 Execution.task_id 解析 OT;Execution 永不直接指向正式 Notice。"""
|
||||
return ShippingOrderTask.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
|
||||
|
||||
def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool:
|
||||
"""
|
||||
任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。
|
||||
|
||||
【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。
|
||||
|
||||
核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结,
|
||||
没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。
|
||||
"""
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
return bool(task_frozen_inventory_source_codes(task))
|
||||
|
||||
|
||||
def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None:
|
||||
"""解析已由库存门禁创建的正式 Notice,仅供 Excel/上传动作使用。"""
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return None
|
||||
return ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
|
||||
|
||||
|
||||
def _handle_reload_inventory_result(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
@@ -881,7 +1112,7 @@ def _handle_reload_inventory_result(
|
||||
sync_fulfillment_gates_from_task,
|
||||
)
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
@@ -895,6 +1126,14 @@ def _handle_reload_inventory_result(
|
||||
mode='reload_result',
|
||||
)
|
||||
if response is None:
|
||||
# [STEP] 重读未命中意味着本次等待链没有可消费的回调结果。Gate 将收口为
|
||||
# blocked_retryable,必须同步取消尚未领取的延迟 poll,避免继续显示/执行轮询。
|
||||
from app.services.shipping_notice.process_gate_job_service import cancel_inventory_external_wait_polls
|
||||
|
||||
cancel_inventory_external_wait_polls(
|
||||
gate_id=int(gate.id),
|
||||
reason='库存结果重读未命中,外部等待轮询已终止',
|
||||
)
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': inventory_preparation_reason_code(task),
|
||||
@@ -926,7 +1165,7 @@ def _handle_retry_inventory_field_mapping(
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
@@ -1025,9 +1264,38 @@ def _handle_retry_inventory_matching(
|
||||
|
||||
response = match_inventory(_task_payload(execution, payload))
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
|
||||
has_shortage = bool(getattr(task, 'shortage_json', None))
|
||||
task = _resolve_order_task(execution)
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
inventory_match_facts_complete,
|
||||
match_completed,
|
||||
)
|
||||
|
||||
match_complete = bool(task is not None and inventory_match_facts_complete(task))
|
||||
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
|
||||
|
||||
shortage = [
|
||||
row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values()
|
||||
if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
|
||||
]
|
||||
# 订单已可履约:重匹配为成功,交由 suff/artifact 后续;不得把 match_inventory 内部
|
||||
# run_task_auto_progress 的"无待处理 Gate"(status='completed')误判为失败。
|
||||
if match_status == 'fulfillable':
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
'shortage': shortage,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'retry_inventory_matching',
|
||||
'tool_status': 'passed',
|
||||
'business_result': 'fulfillable',
|
||||
},
|
||||
}
|
||||
if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and (
|
||||
match_status in {'partial', 'unfulfillable'} or has_shortage
|
||||
):
|
||||
@@ -1038,7 +1306,7 @@ def _handle_retry_inventory_matching(
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
'shortage': getattr(task, 'shortage_json', None),
|
||||
'shortage': shortage,
|
||||
},
|
||||
'output_snapshot': {
|
||||
'action_code': 'retry_inventory_matching',
|
||||
@@ -1083,14 +1351,14 @@ def _handle_recheck_inventory_sufficiency(
|
||||
gate: ShippingProcessGate,
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。"""
|
||||
"""独立库存满足性复核:读取当前行级 Match,不重跑库存匹配。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
recompute_task_fulfillment_state,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
@@ -1110,7 +1378,13 @@ def _handle_recheck_inventory_sufficiency(
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
|
||||
sufficient = match_completed(task)
|
||||
shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
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()
|
||||
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',
|
||||
@@ -1118,19 +1392,19 @@ def _handle_recheck_inventory_sufficiency(
|
||||
outcome=None if sufficient else 'blocked_manual',
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'match_status': task.match_status,
|
||||
'match_status': match_status,
|
||||
'shortage': shortage,
|
||||
},
|
||||
blocking_reason_code=None if sufficient else 'inventory_insufficient',
|
||||
actor_type='system',
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
idempotency_key=f'inv-suff:{execution.execution_no}:{task.match_status}:{sufficient}',
|
||||
idempotency_key=f'inv-suff:{execution.execution_no}:{match_status}:{sufficient}',
|
||||
force=True,
|
||||
)
|
||||
if sufficient:
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {'findings': [], 'match_status': task.match_status},
|
||||
'effective_result_json': {'findings': [], 'match_status': match_status},
|
||||
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True},
|
||||
}
|
||||
return {
|
||||
@@ -1149,11 +1423,10 @@ def _handle_recheck_excel_readiness(
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Excel 生成资格检查:只跑 excel_gate_error,不生成 Artifact。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_retryable',
|
||||
@@ -1171,7 +1444,7 @@ def _handle_recheck_excel_readiness(
|
||||
blocking_reason_code=None if ready else 'excel_not_ready',
|
||||
actor_type='system',
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{task.match_status}',
|
||||
idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{getattr(task, "order_data_version", 1)}',
|
||||
force=True,
|
||||
)
|
||||
if ready:
|
||||
@@ -1196,22 +1469,16 @@ def _handle_regenerate_excel(
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。"""
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
existing = (
|
||||
ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
|
||||
if task is not None and task.id is not None else None
|
||||
)
|
||||
if existing is not None:
|
||||
task = _resolve_order_task(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'notice_excel_already_generated',
|
||||
'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'},
|
||||
'outcome': 'blocked_retryable',
|
||||
'blocking_reason_code': 'artifact_generation_failed',
|
||||
'effective_result_json': {'findings': []},
|
||||
'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True},
|
||||
'output_snapshot': {'action_code': 'regenerate_excel_artifact'},
|
||||
}
|
||||
response = generate_excel(_task_payload(execution, payload))
|
||||
outcome = _tool_outcome(
|
||||
@@ -1246,7 +1513,7 @@ def _handle_freight_upload_rpa(
|
||||
sync_fulfillment_gates_from_task,
|
||||
)
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_shipping_notice(execution)
|
||||
if task is None:
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
@@ -1287,7 +1554,7 @@ def _handle_regenerate_manual_upload_todo(
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
task = _resolve_shipping_notice(execution)
|
||||
if task is None:
|
||||
return _manual_open('regenerate_manual_upload_todo', 'manual_upload_handoff')(
|
||||
execution=execution, gate=gate, payload=payload,
|
||||
@@ -1377,7 +1644,7 @@ def _handle_inventory_reroute(
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=str(payload.get('idempotency_key') or f'gate-reroute-{gate.id}-{gate.evaluation_version}'),
|
||||
line_key=str(payload.get('line_key') or '').strip() or None,
|
||||
draft_line_id=str(payload.get('draft_line_id') or '').strip() or None,
|
||||
)
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
@@ -1416,7 +1683,7 @@ def _handle_recheck_freeze(
|
||||
},
|
||||
'output_snapshot': {'action_code': 'recheck_freeze_readiness'},
|
||||
}
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
task = _resolve_order_task(execution)
|
||||
extraction = None
|
||||
if task is not None and task.order_extraction_id:
|
||||
extraction = ShippingOrderExtraction.query.get(int(task.order_extraction_id))
|
||||
|
||||
@@ -24,7 +24,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.models import Job, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate, primary_next_action_for_gate
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
@@ -61,6 +61,40 @@ def _technical_job_max_attempts() -> int:
|
||||
return 1
|
||||
|
||||
|
||||
def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int:
|
||||
"""
|
||||
取消某库存准备 Gate 尚未领取的延迟轮询 Job。
|
||||
|
||||
核心逻辑:库存 Gate 从 waiting_external 收口为失败/人工恢复后,排队中的
|
||||
``external-wait:<gate_id>:*`` 不再有业务意义,必须立即取消,不能等到下一次
|
||||
延迟触发后才发现 Gate 已变更。仅更新 queued Job;运行中的 Job 不能强杀,
|
||||
其执行入口会再次读取 Gate 并自行停止。
|
||||
|
||||
Args:
|
||||
gate_id: inventory_preparation Gate 主键。
|
||||
reason: 取消原因,写入 Job message 供审计排查。
|
||||
|
||||
Returns:
|
||||
被取消的 Job 数量。
|
||||
"""
|
||||
now = _utc_now()
|
||||
return int(
|
||||
Job.query.filter(
|
||||
Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
|
||||
Job.status == 'queued',
|
||||
Job.business_ref.like(f'external-wait:{int(gate_id)}:%'),
|
||||
).update(
|
||||
{
|
||||
'status': 'cancelled',
|
||||
'finished_at': now,
|
||||
'message': str(reason or '库存等待已终止')[:500],
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int:
|
||||
"""
|
||||
入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。
|
||||
@@ -204,11 +238,11 @@ def schedule_waiting_external_poll(
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
has_inventory_lines = bool(
|
||||
isinstance(getattr(task, 'inventory_lines_json', None), list)
|
||||
and getattr(task, 'inventory_lines_json', None)
|
||||
)
|
||||
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
|
||||
|
||||
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:
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
|
||||
db.session.flush()
|
||||
@@ -306,6 +340,22 @@ 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':
|
||||
poll_count = int(effective.get('poll_count') or 0) + 1
|
||||
effective['poll_count'] = poll_count
|
||||
gate.effective_result_json = effective
|
||||
delay_seconds = min(poll_seconds * (2 ** min(poll_count - 1, 3)), 300)
|
||||
return int(enqueue(
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
{'external_wait_poll_gate_id': int(gate.id)},
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
business_ref=f'external-wait:{int(gate.id)}:{poll_count}',
|
||||
message='等待库存 RPA 回传,延迟复查',
|
||||
max_attempts=1,
|
||||
scheduled_at=now + timedelta(seconds=delay_seconds),
|
||||
dedupe_active=False,
|
||||
commit=False,
|
||||
))
|
||||
poll_attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=gate.gate_code,
|
||||
@@ -324,6 +374,30 @@ def schedule_waiting_external_poll(
|
||||
)
|
||||
|
||||
|
||||
def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]:
|
||||
"""执行库存 RPA 的只读等待轮询,不创建新的 Gate Attempt。"""
|
||||
gate = ShippingProcessGate.query.filter_by(id=int(gate_id)).with_for_update().first()
|
||||
if gate is None or gate.status != 'waiting_external':
|
||||
return {'gate_status': getattr(gate, 'status', 'missing'), 'stopped': True}
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return {'gate_status': 'missing_execution', 'stopped': True}
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
outcome = _handle_retry_inventory_preparation(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload={'action_code': 'poll_inventory_preparation'},
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.refresh(gate)
|
||||
return {
|
||||
'gate_id': int(gate.id),
|
||||
'gate_status': gate.status,
|
||||
'outcome': str(outcome.get('outcome') or ''),
|
||||
}
|
||||
|
||||
|
||||
def heartbeat_gate_attempt(
|
||||
*,
|
||||
attempt_id: int,
|
||||
|
||||
@@ -15,11 +15,14 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingProcessRecoveryPlan,
|
||||
ShippingOrderTask,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.error_explainability_contract import (
|
||||
build_explainability_reason,
|
||||
@@ -29,6 +32,7 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES,
|
||||
action_presentation,
|
||||
gate_side_recovery_actions,
|
||||
get_process_gate_definition,
|
||||
inventory_preparation_primary_action,
|
||||
is_business_user_action,
|
||||
@@ -62,6 +66,51 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = {
|
||||
'open_shortage_review': 'draft',
|
||||
}
|
||||
|
||||
|
||||
def task_blocking_reason(task: ShippingOrderTask | ShippingNotice | None) -> str | None:
|
||||
"""读取任务当前人工阻断原因;OT 以 Process Gate 为唯一事实源。"""
|
||||
if task is None:
|
||||
return None
|
||||
if not isinstance(task, ShippingOrderTask):
|
||||
owner = None
|
||||
if getattr(task, 'order_task_id', None):
|
||||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
if owner is not None:
|
||||
task = owner
|
||||
else:
|
||||
return None
|
||||
execution_id = getattr(task, 'active_process_execution_id', None)
|
||||
if execution_id is None:
|
||||
# OT 在 Execution 尚未绑定/旧执行已清理时,pending_human_reason 仍是
|
||||
# 当前任务的流程事实;不能只回退到技术 error_code,否则 RPA 耗尽、
|
||||
# 库存不可用等业务阻断会被误判为“无阻断”,恢复入口也不会下发。
|
||||
return (
|
||||
str(
|
||||
getattr(task, 'pending_human_reason', None)
|
||||
or getattr(task, 'error_code', None)
|
||||
or ''
|
||||
).strip()
|
||||
or None
|
||||
)
|
||||
execution = db.session.get(ShippingProcessExecution, int(execution_id))
|
||||
if execution is None or str(execution.status or '').strip().lower() == 'superseded':
|
||||
return (
|
||||
str(
|
||||
getattr(task, 'pending_human_reason', None)
|
||||
or getattr(task, 'error_code', None)
|
||||
or ''
|
||||
).strip()
|
||||
or None
|
||||
)
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id))
|
||||
.filter(ShippingProcessGate.status.in_(('blocked_manual', 'blocked_retryable', 'waiting_external')))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc())
|
||||
.first()
|
||||
)
|
||||
return str(getattr(gate, 'blocking_reason_code', None) or '').strip() or None
|
||||
|
||||
def _projection_gate_definition(gate_code: str) -> dict[str, Any]:
|
||||
"""只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。"""
|
||||
return get_process_gate_definition(gate_code)
|
||||
@@ -84,8 +133,8 @@ def _resolve_recovery_next_action(
|
||||
"""
|
||||
单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。
|
||||
|
||||
[STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果;
|
||||
其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
|
||||
[STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配,
|
||||
无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
|
||||
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
|
||||
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
|
||||
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
|
||||
@@ -438,9 +487,7 @@ def _execution_navigation_refs(execution: ShippingProcessExecution) -> dict[str,
|
||||
if run is not None and getattr(run, 'run_no', None):
|
||||
review_run_no = str(run.run_no)
|
||||
if execution.task_id:
|
||||
from app.models import ShippingNotice
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
if task is not None:
|
||||
task_no = str(task.task_no)
|
||||
return {
|
||||
@@ -483,19 +530,56 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -
|
||||
"""判断正式任务是否已有可复用、未失效的已确认库存快照。"""
|
||||
if not execution.task_id:
|
||||
return False
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json:
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
return bool(task is not None and has_ready_inventory_file_for_task(task))
|
||||
|
||||
|
||||
def _row_source_editable(execution: ShippingProcessExecution) -> bool:
|
||||
"""判断正式任务是否仍处于「行级库存源可编辑」阶段(发货 Excel 尚未生成)。
|
||||
|
||||
核心逻辑:锁定边界 = Excel 生成(D7)。只有生成发货通知/发货 Excel 之后
|
||||
(存在有效 ShippingExportArtifact)才锁定行源;此前用户应能对行反复选源/覆写,
|
||||
因此行级编辑动作的授权必须以此为准,而不能依赖门禁是否恰好处于人工阻断态。
|
||||
"""
|
||||
if not getattr(execution, 'task_id', None):
|
||||
return False
|
||||
inventory_file = active_inventory_file_for_task(task)
|
||||
return bool(
|
||||
inventory_file is not None
|
||||
and str(getattr(inventory_file, 'snapshot_status', '') or '').strip().lower() == 'ready'
|
||||
and getattr(inventory_file, 'invalidated_at', None) is None
|
||||
and bool(getattr(inventory_file, 'mapping_confirmed', False))
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
notice = (
|
||||
ShippingNotice.query.filter_by(order_task_id=int(task.id)).order_by(ShippingNotice.id.desc()).first()
|
||||
if task is not None else None
|
||||
)
|
||||
if notice is None:
|
||||
# OT 阶段尚未生成正式 Notice,库存源天然可编辑。
|
||||
return True
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
return latest_export_artifact(notice) is None
|
||||
|
||||
|
||||
def _ensure_editable_row_source_actions(
|
||||
*,
|
||||
allowed_actions: list[str],
|
||||
gate_code: str | None,
|
||||
execution: ShippingProcessExecution,
|
||||
) -> None:
|
||||
"""行级库源可编辑时,确保允许前端展示并提交行级选源/覆写动作。
|
||||
|
||||
与 project_user_gate_summary 的 `if blocking:` 侧路不同:行可编辑性由「Excel 是否
|
||||
生成」(_row_source_editable)决定,而非门禁是否处于阻断态。避免首次覆写成功后门禁
|
||||
推进、allowed_actions 清空,导致用户对同一行二次编辑在前端被 noAction 拦下。
|
||||
"""
|
||||
if not _row_source_editable(execution):
|
||||
return
|
||||
code = str(gate_code or '').strip().lower()
|
||||
if code not in {'inventory_preparation', 'inventory_matching'}:
|
||||
return
|
||||
# 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口,
|
||||
# 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。
|
||||
# retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。
|
||||
for side in ('override_line_inventory_source',):
|
||||
if side not in allowed_actions and is_business_user_action(side):
|
||||
allowed_actions.append(side)
|
||||
|
||||
|
||||
def _excel_regeneration_allowed(
|
||||
@@ -504,10 +588,18 @@ def _excel_regeneration_allowed(
|
||||
"""判断上传阶段是否仍可安全替代 Excel;已上传、未知结果和并发恢复一律拒绝。"""
|
||||
if not execution.task_id or active_recovery_plans:
|
||||
return False
|
||||
from app.models import ShippingExportArtifact, ShippingUploadAttempt
|
||||
from app.models import ShippingExportArtifact, ShippingUploadAttempt, ShippingNotice
|
||||
|
||||
# ProcessExecution.task_id 始终指向 OT;Artifact.task_id 指向正式 Notice。
|
||||
# 不能直接用 OT 主键查询 Artifact,否则会误判没有可重生的 Excel。
|
||||
notice = ShippingNotice.query.filter_by(order_task_id=int(execution.task_id)).order_by(
|
||||
ShippingNotice.id.desc(),
|
||||
).first()
|
||||
if notice is None:
|
||||
return False
|
||||
|
||||
artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == int(execution.task_id),
|
||||
ShippingExportArtifact.task_id == int(notice.id),
|
||||
ShippingExportArtifact.status == 'ready',
|
||||
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
|
||||
if artifact is None:
|
||||
@@ -615,24 +707,18 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
if blocking:
|
||||
if next_action and is_business_user_action(str(next_action)):
|
||||
allowed_actions.append(str(next_action))
|
||||
# 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作,
|
||||
# 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。
|
||||
if (
|
||||
str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation'
|
||||
and str(reason_code or '').strip().lower()
|
||||
in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
|
||||
and 'retry_inventory_preparation' not in allowed_actions
|
||||
# [STEP] 侧路动作与校验层同源:allowed_actions 的侧路必须等于
|
||||
# request_gate_action 的 allowed_side(gate_side_recovery_actions),
|
||||
# 禁止在此另行硬编码,避免「投影放行按钮、校验却拒绝提交」的漂移。
|
||||
# 覆盖:RPA 超时/耗尽的显式 RPA 重试、Gate 20 人工交接下的货代 RPA 重试、
|
||||
# 库存多文件冲突行的人工选源。
|
||||
for side_code in gate_side_recovery_actions(
|
||||
gate_code=str(blocking.get('gate_code') or ''),
|
||||
status=str(blocking.get('status') or ''),
|
||||
blocking_reason_code=reason_code,
|
||||
):
|
||||
allowed_actions.append('retry_inventory_preparation')
|
||||
# Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。
|
||||
# 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。
|
||||
if (
|
||||
str(blocking.get('gate_code') or '').strip().lower() == 'manual_upload_handoff'
|
||||
and str(reason_code or '').strip().lower() in {
|
||||
'manual_upload_pending', 'upload_result_unknown',
|
||||
}
|
||||
):
|
||||
allowed_actions.append('retry_freight_upload_rpa')
|
||||
if side_code not in allowed_actions:
|
||||
allowed_actions.append(side_code)
|
||||
for target in recovery_targets:
|
||||
code = str(target.get('action_code') or '').strip()
|
||||
if code and code not in allowed_actions and is_business_user_action(code):
|
||||
@@ -667,6 +753,38 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
if item:
|
||||
action_items.append(item)
|
||||
|
||||
# [EDITABLE] 行级库源可编辑(Excel 未生成)时,选源/覆写动作不与门禁阻断态绑定:
|
||||
# 即使门禁已推进/不再处于人工阻断态,也应继续授权,避免首提成功后再编辑被 noAction 拦下。
|
||||
_ensure_editable_row_source_actions(
|
||||
allowed_actions=allowed_actions,
|
||||
gate_code=current_gate_code or str((blocking or {}).get('gate_code') or ''),
|
||||
execution=execution,
|
||||
)
|
||||
# 上面新增了行级编辑动作(尤其当 `if blocking:` 为假时原 action_items 为空),需重建 presentation。
|
||||
# 与 `if blocking:` 内建项保持同构,避免漏掉因可编辑性补充的动作。
|
||||
existing_codes = {str(item.get('code') or '') for item in action_items}
|
||||
for code in allowed_actions:
|
||||
if code in existing_codes:
|
||||
continue
|
||||
item = action_presentation(code, gate_code=current_gate_code)
|
||||
recovery_definition = None
|
||||
try:
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
|
||||
recovery_definition = recovery_plan_for_action(
|
||||
current_gate=current_gate_code or '', action_code=code,
|
||||
)
|
||||
except Exception: # noqa: BLE001 - recoverable (unknown gate) must not break presentation
|
||||
recovery_definition = None
|
||||
placement = (recovery_definition or {}).get('ui_placement')
|
||||
if item and isinstance(placement, dict):
|
||||
item.update({
|
||||
'target_surface': placement.get('target_surface'),
|
||||
'target_anchor': placement.get('target_anchor'),
|
||||
})
|
||||
if item:
|
||||
action_items.append(item)
|
||||
|
||||
# [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源;
|
||||
# request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。
|
||||
explainability = None
|
||||
@@ -867,7 +985,8 @@ _USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({
|
||||
'matched_rule_ids',
|
||||
'raw_rule_source_codes',
|
||||
'candidate_inventory_source_codes',
|
||||
'line_key',
|
||||
'draft_line_id',
|
||||
'snapshot_line_id',
|
||||
'line_index',
|
||||
'field_code',
|
||||
'request_id',
|
||||
|
||||
@@ -19,17 +19,26 @@ from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingPr
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_ACTION_CODES,
|
||||
gate_side_recovery_actions,
|
||||
get_process_gate_definition,
|
||||
inventory_preparation_primary_action,
|
||||
is_business_user_action,
|
||||
is_stage_capability,
|
||||
is_technical_gate_party,
|
||||
primary_next_action_for_gate,
|
||||
stage_capability,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_executor import (
|
||||
action_requires_async_worker,
|
||||
execute_queued_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
from app.services.shipping_notice.process_gate_projection import serialize_process_gate
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
execute_stage_capability,
|
||||
execute_stage_capability_override_source,
|
||||
execute_stage_capability_rematch,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
from app.services.shipping_notice.recovery_plan_service import bind_recovery_attempt, create_recovery_plan
|
||||
|
||||
@@ -119,19 +128,13 @@ def _primary_recovery_action(
|
||||
if gate.gate_code == 'inventory_matching' and execution.task_id:
|
||||
return 'retry_inventory_matching'
|
||||
if gate.gate_code == 'inventory_sufficiency' and execution.task_id:
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
inventory_file = active_inventory_file_for_task(task) if task is not None else None
|
||||
task = ShippingOrderTask.query.get(int(execution.task_id))
|
||||
if (
|
||||
task is not None
|
||||
and isinstance(task.inventory_lines_json, list)
|
||||
and bool(task.inventory_lines_json)
|
||||
and inventory_file is not None
|
||||
and str(inventory_file.snapshot_status or '').strip().lower() == 'ready'
|
||||
and inventory_file.invalidated_at is None
|
||||
and bool(inventory_file.mapping_confirmed)
|
||||
and has_ready_inventory_file_for_task(task)
|
||||
):
|
||||
return 'retry_inventory_matching'
|
||||
return gate.next_action_code or primary_next_action_for_gate(
|
||||
@@ -139,6 +142,43 @@ def _primary_recovery_action(
|
||||
)
|
||||
|
||||
|
||||
def is_stage_capability_exempt(
|
||||
*,
|
||||
current_gate: str,
|
||||
requested_gate: str,
|
||||
action_code: str,
|
||||
lifecycle_stage: str,
|
||||
) -> bool:
|
||||
"""判断阶段能力动作是否豁免「必须命中当前 gate」校验。
|
||||
|
||||
【AI 触发时机】:request_gate_action 对阶段能力动作允许请求非当前 Gate 时调用;
|
||||
本函数为纯谓词、无 IO,供单测直接验证豁免边界。
|
||||
|
||||
核心逻辑(三条件同时满足才放行):
|
||||
1) 动作是阶段能力(stage_capability 非 None);
|
||||
2) 当前生命周期阶段 == 能力阶段(cap['stage']);
|
||||
3) 请求的目标 Gate 落在该能力作废或重置范围(invalidate ∪ reset_to)。
|
||||
|
||||
Args:
|
||||
current_gate: 当前 Execution 的 current_gate_code(保留用于接口对称,当前逻辑未使用)。
|
||||
requested_gate: 用户请求的 Gate 编码。
|
||||
action_code: 请求的动作码。
|
||||
lifecycle_stage: 当前生命周期阶段码(由 current_gate 的 ui_placement.target_surface 派生)。
|
||||
|
||||
Returns:
|
||||
True 表示豁免非当前 Gate 校验;否则 False 走既有校验。
|
||||
"""
|
||||
cap = stage_capability(action_code)
|
||||
if cap is None:
|
||||
return False
|
||||
if lifecycle_stage != cap.get('stage'):
|
||||
return False
|
||||
targets = set(cap.get('invalidate') or ())
|
||||
if cap.get('reset_to'):
|
||||
targets.add(cap['reset_to'])
|
||||
return requested_gate in targets
|
||||
|
||||
|
||||
def request_gate_action(
|
||||
*,
|
||||
execution_no: str,
|
||||
@@ -213,9 +253,47 @@ def request_gate_action(
|
||||
details={'current_gate': gate.gate_code, 'action_code': action},
|
||||
)
|
||||
|
||||
# [STAGE_CAPABILITY] 生命周期阶段由当前 execution 的 current_gate 映射派生:
|
||||
# 用 gate 定义的 ui_placement.target_surface 作为阶段码(库存门禁 → fulfillment_prep)。
|
||||
# 校验路径不再重算完整 ui_state,避免重活。
|
||||
lifecycle_stage = ''
|
||||
if current_gate:
|
||||
try:
|
||||
lifecycle_stage = str(
|
||||
get_process_gate_definition(current_gate).get('ui_placement', {}).get('target_surface') or ''
|
||||
)
|
||||
except KeyError:
|
||||
lifecycle_stage = ''
|
||||
|
||||
# [STAGE_CAPABILITY] 阶段能力豁免:通知准备阶段内允许回退/重抓到上游库存 gate。
|
||||
# 前道数据可变,用户可在窗口内重抓/改源;执行走 execute_stage_capability,
|
||||
# 不走普通主/侧路动作校验,也不触发 SHIPPING.PROCESS_GATE_NOT_CURRENT。
|
||||
stage_cap = stage_capability(action)
|
||||
stage_exempt = (
|
||||
is_stage_capability(action)
|
||||
and is_stage_capability_exempt(
|
||||
current_gate=current_gate,
|
||||
requested_gate=str(gate.gate_code or '').strip(),
|
||||
action_code=action,
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP] 库存阶段能力只属于正式 OT 执行链。建单前的 Review Execution 可以没有
|
||||
# task_id,但绝不能借同名 Gate 执行 reload/retry 并制造无归属 Attempt。
|
||||
if is_stage_capability(action) and not execution.task_id:
|
||||
raise ValidationError(
|
||||
'Stage capability requires a bound shipping order task',
|
||||
code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND',
|
||||
details={'execution_no': execution.execution_no, 'action_code': action},
|
||||
)
|
||||
|
||||
# [GLOBAL ACTION GUARD] 所有 20 Gate 共用同一入口:请求 Gate 必须是 Execution 当前 Gate。
|
||||
# 跨阶段动作已在前面完成目标归属判定,避免错误地把非法恢复目标报告为状态漂移。
|
||||
if replay_attempt is None and (not current_gate or current_gate != str(gate.gate_code or '').strip()):
|
||||
# 阶段能力(stage_exempt)允许访问非当前 Gate,故豁免此校验。
|
||||
if replay_attempt is None and not stage_exempt and (
|
||||
not current_gate or current_gate != str(gate.gate_code or '').strip()
|
||||
):
|
||||
raise ValidationError(
|
||||
'Action must target the current process gate',
|
||||
code='SHIPPING.PROCESS_GATE_NOT_CURRENT',
|
||||
@@ -227,6 +305,38 @@ def request_gate_action(
|
||||
},
|
||||
)
|
||||
|
||||
# [STAGE_CAPABILITY] 阶段能力直接执行:作废下游 + 重置回起始 gate + 幂等重跑;
|
||||
# 不经过下方普通主/侧路动作校验(primary/allowed_side)与技术 Gate 守卫。
|
||||
# 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑),
|
||||
# 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。
|
||||
if stage_exempt:
|
||||
if action == 'retry_inventory_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':
|
||||
# [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用
|
||||
# execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」
|
||||
# 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。
|
||||
result = execute_stage_capability_override_source(
|
||||
execution=execution, gate=gate, payload=body,
|
||||
actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key,
|
||||
)
|
||||
else:
|
||||
result = execute_stage_capability(
|
||||
execution=execution, gate=gate, capability=stage_cap,
|
||||
actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key,
|
||||
line_scope_key=body.get('snapshot_line_id'),
|
||||
)
|
||||
return {
|
||||
'outcome': 'submitted',
|
||||
'gate_summary': serialize_process_gate(gate),
|
||||
'stage_capability': result,
|
||||
}
|
||||
|
||||
# [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。
|
||||
# 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。
|
||||
if str(actor_type or '') == 'user' and not is_business_user_action(action):
|
||||
@@ -258,8 +368,15 @@ def request_gate_action(
|
||||
)
|
||||
|
||||
primary = _primary_recovery_action(execution=execution, gate=gate)
|
||||
# [STEP] 库存准备、选源与字段映射均为自动治理,不提供库存文件人工补传旁路。
|
||||
allowed_side: set[str] = set()
|
||||
# [STEP] 侧路动作与投影层同源:request_gate_action 的 allowed_side 必须等于
|
||||
# serialize_process_gate 投影暴露的侧路动作集,否则会出现「按钮可点但提交被拒」的
|
||||
# 漂移(例如 RPA 超时/耗尽时点击「重新获取库存 (RPA)」被报
|
||||
# SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED)。禁止在此另行硬编码。
|
||||
allowed_side = set(gate_side_recovery_actions(
|
||||
gate_code=gate.gate_code,
|
||||
status=gate.status,
|
||||
blocking_reason_code=gate.blocking_reason_code,
|
||||
))
|
||||
if primary and action != primary and action not in allowed_side and recovery_definition is None:
|
||||
raise ValidationError(
|
||||
'Action is not the primary recovery action for this gate',
|
||||
|
||||
@@ -76,11 +76,11 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution:
|
||||
|
||||
def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None:
|
||||
"""
|
||||
为既有 Execution 补齐契约新增的门禁行(如 freight_upload_rpa)。
|
||||
为既有 Execution 补齐并校正当前 Gate 契约。
|
||||
|
||||
核心逻辑:按 PROCESS_GATE_DEFINITIONS 插入缺失 gate_code;若旧版
|
||||
manual_upload_handoff 仍占 sequence 19,先挪到 20 再插入 freight_upload_rpa=19,
|
||||
避免 uq_shipping_process_gates_execution_sequence 冲突。不改动既有状态语义。
|
||||
核心逻辑:先将既有 Gate 临时移位,再按 PROCESS_GATE_DEFINITIONS 写回
|
||||
sequence_no 并插入缺失 Gate,避免顺序调整时触发唯一约束;只修正结构顺序,
|
||||
不改动既有状态语义。
|
||||
|
||||
Args:
|
||||
execution: 目标 Execution。
|
||||
@@ -90,32 +90,35 @@ def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> N
|
||||
now = _utc_now()
|
||||
changed = False
|
||||
|
||||
# [STEP 1] 旧 Execution:manual 占 19 时先腾出序号给 freight_upload_rpa。
|
||||
manual = by_code.get('manual_upload_handoff')
|
||||
freight_def = next(
|
||||
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'freight_upload_rpa'),
|
||||
None,
|
||||
# [STEP 1] 旧 Execution:先把既有 Gate 行移到临时序号,避免顺序交换时触发
|
||||
# uq_shipping_process_gates_execution_sequence;随后统一写入当前契约 sequence_no。
|
||||
# 这样 PROCESS_GATE_DEFINITIONS 调整后,既有 Execution 也不会继续沿用旧顺序。
|
||||
expected_by_code = {
|
||||
str(item['gate_code']): int(item['sequence_no'])
|
||||
for item in PROCESS_GATE_DEFINITIONS
|
||||
}
|
||||
needs_sequence_reconcile = any(
|
||||
code in expected_by_code and int(row.sequence_no or 0) != expected_by_code[code]
|
||||
for code, row in by_code.items()
|
||||
)
|
||||
manual_def = next(
|
||||
(item for item in PROCESS_GATE_DEFINITIONS if item['gate_code'] == 'manual_upload_handoff'),
|
||||
None,
|
||||
)
|
||||
if (
|
||||
freight_def is not None
|
||||
and manual_def is not None
|
||||
and 'freight_upload_rpa' not in by_code
|
||||
and manual is not None
|
||||
and int(manual.sequence_no) == int(freight_def['sequence_no'])
|
||||
):
|
||||
manual.sequence_no = int(manual_def['sequence_no'])
|
||||
manual.updated_at = now
|
||||
if needs_sequence_reconcile:
|
||||
sequence_offset = 1000
|
||||
for row in rows:
|
||||
row.sequence_no = sequence_offset + int(row.sequence_no or 0)
|
||||
row.updated_at = now
|
||||
changed = True
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 插入仍缺失的门禁行。
|
||||
# [STEP 2] 按当前契约修正既有 Gate 顺序,并插入仍缺失的门禁行。
|
||||
for item in PROCESS_GATE_DEFINITIONS:
|
||||
code = str(item['gate_code'])
|
||||
if code in by_code:
|
||||
row = by_code[code]
|
||||
expected_sequence = int(item['sequence_no'])
|
||||
if int(row.sequence_no or 0) != expected_sequence:
|
||||
row.sequence_no = expected_sequence
|
||||
row.updated_at = now
|
||||
changed = True
|
||||
continue
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
@@ -269,14 +272,24 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
|
||||
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
|
||||
if getattr(execution, 'task_id', None) is None:
|
||||
return
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
|
||||
notice = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
notice = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(order_task_id=int(task.id))
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.first()
|
||||
if task is not None else None
|
||||
)
|
||||
if notice is not None:
|
||||
sync_order_task_stage_for_notice(notice)
|
||||
sync_order_task_stage_for_notice(notice, order_task=task)
|
||||
elif task is not None:
|
||||
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
|
||||
task.stage = task.stage or 'notification_preparation'
|
||||
|
||||
|
||||
def ensure_execution_for_workflow_version(
|
||||
@@ -412,7 +425,7 @@ def bind_execution_task(
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessExecution:
|
||||
"""建单后绑定 ShippingNotice;幂等覆盖空 task_id。"""
|
||||
"""正式建单后将 Execution 绑定到 ShippingOrderTask;仅允许填充空 task_id。"""
|
||||
execution = _locked_execution(execution_no)
|
||||
if execution.task_id and int(execution.task_id) != int(task_id):
|
||||
raise ConflictError('Execution already bound to another task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND')
|
||||
@@ -787,6 +800,36 @@ def complete_gate_attempt(
|
||||
return gate
|
||||
|
||||
|
||||
def _abort_active_attempt_as_superseded(
|
||||
*,
|
||||
gate: ShippingProcessGate,
|
||||
active_attempt: ShippingProcessGateAttempt,
|
||||
reason: str,
|
||||
) -> None:
|
||||
"""把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。
|
||||
|
||||
触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、
|
||||
且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。
|
||||
仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方
|
||||
常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败
|
||||
覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。
|
||||
"""
|
||||
now = _utc_now()
|
||||
active_attempt.status = 'superseded'
|
||||
active_attempt.finished_at = now
|
||||
active_attempt.lease_token = None
|
||||
active_attempt.lease_expires_at = None
|
||||
active_attempt.error_code = str(reason or 'business_fact_passed')[:64]
|
||||
active_attempt.error_summary = 'Attempt superseded by a newer passed business fact.'
|
||||
gate.status = 'pending'
|
||||
gate.blocking_reason_code = None
|
||||
gate.blocking_reason_json = None
|
||||
gate.next_action_code = None
|
||||
gate.latest_attempt_id = int(active_attempt.id)
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.updated_at = now
|
||||
|
||||
|
||||
def skip_gate_as_superseded(
|
||||
*,
|
||||
execution_no: str,
|
||||
@@ -953,9 +996,13 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
# 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试,
|
||||
# 不能由 AutoProgress 无限重放。
|
||||
if next_gate.next_action_code == 'retry_inventory_preparation':
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
from app.models import ShippingOrderTask
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id))
|
||||
if task is None:
|
||||
# Execution 必须绑定 OT;缺失任务时禁止自动投递,避免错误重放。
|
||||
return
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip()
|
||||
existing = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
@@ -986,6 +1033,9 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
expected_gate_version=int(next_gate.evaluation_version),
|
||||
input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}},
|
||||
)
|
||||
# 幂等命中时队列函数可能返回 None;此时已有 Attempt,无需再次投递。
|
||||
if attempt is None:
|
||||
return
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None)
|
||||
except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖
|
||||
@@ -999,7 +1049,7 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
result='failure',
|
||||
reason_code='auto_progress_enqueue_failed',
|
||||
error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED',
|
||||
error_summary=str(exc)[:500],
|
||||
reason=str(exc)[:500],
|
||||
after={'execution_no': execution.execution_no, 'gate_code': gate.gate_code},
|
||||
source='process_gate',
|
||||
)
|
||||
@@ -1011,14 +1061,22 @@ def invalidate_downstream_gates(
|
||||
change_type: str,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
exclude_gate_codes: set[str] | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
将依赖图指定的下游已通过门禁标记为 invalidated。
|
||||
|
||||
Args:
|
||||
execution: 当前正式执行链。
|
||||
change_type: 上游输入变更类型。
|
||||
actor_type / actor_id: 触发审计主体。
|
||||
exclude_gate_codes: 本次重置的起始 Gate;即使依赖图包含它也不得作废。
|
||||
|
||||
Returns:
|
||||
实际失效的 gate_code 列表。
|
||||
"""
|
||||
targets = set(compute_invalidated_gates(change_type))
|
||||
targets.difference_update({str(code).strip() for code in (exclude_gate_codes or set())})
|
||||
if not targets:
|
||||
return []
|
||||
now = _utc_now()
|
||||
@@ -1141,15 +1199,40 @@ def sync_gate_from_business_result(
|
||||
active_attempt.trigger_type == 'auto'
|
||||
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
|
||||
)
|
||||
if not inventory_ready or not is_auto_poll:
|
||||
return gate
|
||||
return complete_gate_attempt(
|
||||
attempt_id=int(active_attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot=effective_result_json,
|
||||
recommendation_json=recommendation_json,
|
||||
effective_result_json=effective_result_json,
|
||||
if (inventory_ready or is_auto_poll) and passed:
|
||||
return complete_gate_attempt(
|
||||
attempt_id=int(active_attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot=effective_result_json,
|
||||
recommendation_json=recommendation_json,
|
||||
effective_result_json=effective_result_json,
|
||||
)
|
||||
# [STEP] 业务事实已判定通过,但占位 Attempt 是一个与本 Gate 通过评估无冲突的
|
||||
# 行级人工动作(例如并发 override_line_inventory_source)。
|
||||
# 若直接 `return gate` 静默丢弃,该并发 Attempt 随后以失败态收口会把真实成功
|
||||
# 覆盖为 blocked_retryable,前端误判「自动处理失败」(真实任务
|
||||
# SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。
|
||||
# 仅对这类行级人工动作做 superseded 收口;同 Gate 的自动准备/匹配 Attempt 属于
|
||||
# 当前执行器自身体系,必须保留让外层统一 complete,禁止在此提前收口或再入队。
|
||||
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',
|
||||
}
|
||||
)
|
||||
if is_conflicting_user_line_action and passed:
|
||||
# 收口该并发行级动作后继续走下方 queue+complete 写入 passed(Gate 已复位
|
||||
# 为 pending,且活动 Attempt 已清除,可安全再入队)。
|
||||
_abort_active_attempt_as_superseded(
|
||||
gate=gate,
|
||||
active_attempt=active_attempt,
|
||||
reason=f'business_fact_passed:{gate_code}',
|
||||
)
|
||||
db.session.flush()
|
||||
else:
|
||||
# 其余活动 Attempt(同 Gate 自动准备/匹配、轮询、或非 passed 同步)都交由
|
||||
# 外层 Attempt 统一 complete,禁止在此提前收口或再入队,避免 PROCESS_GATE_BUSY。
|
||||
return gate
|
||||
|
||||
if allow_repass and gate.status == 'passed':
|
||||
gate.status = 'invalidated'
|
||||
@@ -1198,3 +1281,278 @@ def sync_gate_from_business_result(
|
||||
effective_result_json=effective_result_json,
|
||||
invalidate_change_type=resolved_invalidate,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 阶段能力编排器 · execute_stage_capability(作废下游 + 重置 + 幂等重跑)
|
||||
#
|
||||
# 用途:阶段能力允许在窗口内回退/重抓库存源;当前道(inventory_preparation)输入一旦
|
||||
# 变化,下游 mapping/matching/sufficiency/excel/artifact 结果必须作废并重算,
|
||||
# 避免「旧匹配 + 新库存」拼出错误 Excel。
|
||||
# 依赖:run_task_auto_progress(progress_workflow,本模块模块级引用以便测试打桩)、
|
||||
# invalidate_downstream_gates(同文件)、process_gate_contract.stage_capability。
|
||||
# 逻辑:作废下游 → 重置执行指针回能力起始 gate → 解析 task_no 后幂等重跑;重跑失败
|
||||
# 不抛出,仅置 reran=False 交给调用方/前端处置。
|
||||
# ============================================================
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
|
||||
def execute_stage_capability(
|
||||
*,
|
||||
execution: Any,
|
||||
gate: Any,
|
||||
capability: dict[str, Any],
|
||||
actor_type: str,
|
||||
actor_id: int | str | None,
|
||||
idempotency_key: str,
|
||||
line_scope_key: int | str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""执行阶段能力(一期·通知准备):作废下游库存 gate → 重置回准备 → 幂等重跑。
|
||||
|
||||
【AI 触发时机】:用户在通知准备阶段点击「重抓库存 / 重读结果 / 行级改源」等能力按钮
|
||||
时由上游编排器调用;不要把作废/重算逻辑散落在各执行器里。
|
||||
|
||||
核心步骤:
|
||||
[STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate
|
||||
时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。
|
||||
[STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。
|
||||
[STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定
|
||||
以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False
|
||||
(run_task_auto_progress 对失败返回 dict 而非抛异常,不能仅凭「未抛异常」判成功)。
|
||||
|
||||
Args:
|
||||
execution: 当前 ShippingProcessExecution。
|
||||
gate: 触发能力的门禁行(为接口稳定保留;当前失效链不依赖具体 gate)。
|
||||
capability: STAGE_CAPABILITY_DEFINITIONS 的能力定义。
|
||||
actor_type: 触发方角色(user/system/admin)。
|
||||
actor_id: 触发方 ID(可空)。
|
||||
idempotency_key: 幂等键;随调用透传给 run_task_auto_progress,供其短时幂等去重,避免重放重复推进。
|
||||
|
||||
Returns:
|
||||
dict: {'invalidated_gates': list[str], 'reset_to': str|None, 'reran': bool};
|
||||
重跑未成功时附带 'reran_reason': str(失败状态或异常摘要)。
|
||||
"""
|
||||
invalidated: list[str] = []
|
||||
if capability.get('invalidate'):
|
||||
invalidated = list(invalidate_downstream_gates(
|
||||
execution=execution,
|
||||
change_type='inventory_source_changed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
# 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。
|
||||
exclude_gate_codes={str(capability.get('reset_to') or '').strip()} - {''},
|
||||
))
|
||||
reset_to = capability.get('reset_to')
|
||||
if reset_to:
|
||||
execution.current_gate_code = reset_to
|
||||
reran = False
|
||||
reran_reason: str | None = None
|
||||
try:
|
||||
# [STEP 3] execution 持有 ShippingOrderTask 主键,先解析出 task_no。
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
task = db.session.get(ShippingOrderTask, int(execution.task_id)) if getattr(execution, 'task_id', None) else None
|
||||
task_no = getattr(task, 'task_no', None)
|
||||
progress_result = run_task_auto_progress(
|
||||
task_no,
|
||||
trigger='manual_stage_capability',
|
||||
idempotency_key=idempotency_key,
|
||||
operator_id=str(actor_id) if actor_id is not None else None,
|
||||
# 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate;
|
||||
# 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。
|
||||
resume_gate_code=str(reset_to or '').strip() or None,
|
||||
inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto',
|
||||
line_scope_key=str(line_scope_key).strip() or None,
|
||||
)
|
||||
# run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常;
|
||||
# 仅凭「未抛异常」会把实际失败误判为 reran=True。按返回状态判定后写入失败原因。
|
||||
if isinstance(progress_result, dict):
|
||||
run_status = str(progress_result.get('status') or '')
|
||||
if run_status in {'failed', 'conflict'}:
|
||||
reran = False
|
||||
reran_reason = (
|
||||
str(progress_result.get('message') or '')
|
||||
or str(progress_result.get('current_progress_version') or '')
|
||||
or run_status
|
||||
)
|
||||
else:
|
||||
reran = True
|
||||
else:
|
||||
reran = True
|
||||
except Exception as exc: # noqa: BLE001 — 幂等重跑失败不抛,交由调用方/前端处置
|
||||
reran = False
|
||||
reran_reason = f'{type(exc).__name__}: {str(exc)[:200]}'
|
||||
result: dict[str, Any] = {'invalidated_gates': invalidated, 'reset_to': reset_to, 'reran': reran}
|
||||
if reran_reason is not None:
|
||||
result['reran_reason'] = reran_reason
|
||||
return result
|
||||
|
||||
|
||||
def execute_stage_capability_rematch(
|
||||
*,
|
||||
execution: Any,
|
||||
actor_type: str,
|
||||
actor_id: int | str | None,
|
||||
idempotency_key: str,
|
||||
) -> dict[str, Any]:
|
||||
"""执行「重新匹配库存」阶段能力:作废匹配及下游,重跑匹配并重新收口满足性/Excel 事实。
|
||||
|
||||
【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成)
|
||||
时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处
|
||||
保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经
|
||||
inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel),
|
||||
避免错误重抓 RPA 或重做字段映射。
|
||||
|
||||
Args:
|
||||
execution: 当前 ShippingProcessExecution。
|
||||
actor_type: 触发方角色(user/system/admin)。
|
||||
actor_id: 触发方 ID(可空)。
|
||||
idempotency_key: 幂等键;随 Attempt 透传。
|
||||
|
||||
Returns:
|
||||
dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'};
|
||||
重匹配未成功时附带 'reran_reason'(缺 matching gate 或 Attempt 执行异常摘要)。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
|
||||
invalidated = list(invalidate_downstream_gates(
|
||||
execution=execution,
|
||||
change_type='inventory_field_mapping_changed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
))
|
||||
match_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code='inventory_matching')
|
||||
.first()
|
||||
)
|
||||
if match_gate is None:
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reran': False,
|
||||
'reran_reason': 'inventory_matching_gate_missing',
|
||||
}
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_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',
|
||||
'payload': {
|
||||
'actor_user_id': actor_id,
|
||||
'idempotency_key': str(idempotency_key or ''),
|
||||
'source': 'stage_capability_rematch',
|
||||
},
|
||||
},
|
||||
)
|
||||
try:
|
||||
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
|
||||
reran = True
|
||||
except Exception as exc: # noqa: BLE001 — 重匹配失败不抛,交由调用方/前端处置
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reran': False,
|
||||
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
|
||||
}
|
||||
# 收口执行指针到最早未通过 gate(complete_gate_attempt 已刷新,此处兜底幂等)。
|
||||
_refresh_execution_pointers(execution)
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_matching',
|
||||
'reran': reran,
|
||||
'gate_status': updated_gate.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
}
|
||||
|
||||
|
||||
def execute_stage_capability_override_source(
|
||||
*,
|
||||
execution: Any,
|
||||
gate: Any,
|
||||
payload: dict[str, Any],
|
||||
actor_type: str,
|
||||
actor_id: int | str | None,
|
||||
idempotency_key: str,
|
||||
) -> dict[str, Any]:
|
||||
"""执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。
|
||||
|
||||
【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交
|
||||
override_line_inventory_source)时由 request_gate_action 调用。
|
||||
|
||||
关键差异 / root cause 说明:
|
||||
- `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` /
|
||||
``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个
|
||||
关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。
|
||||
- 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义,
|
||||
但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到
|
||||
CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress
|
||||
按新候选重取/匹配库存,从而让 RPA 正常触发。
|
||||
|
||||
Args:
|
||||
execution: 当前 ShippingProcessExecution。
|
||||
gate: 触发能力的门禁行。
|
||||
payload: 用户提交的原始动作载荷(含 line_no / source_code / reason / actor_user_id)。
|
||||
actor_type: 触发方角色(user/system/admin)。
|
||||
actor_id: 触发方 ID(可空)。
|
||||
idempotency_key: 幂等键;随 Attempt 透传。
|
||||
|
||||
Returns:
|
||||
dict: {'invalidated_gates', 'reset_to', 'reran', 'gate_status', 'current_gate_code'};
|
||||
失败时附带 'reran_reason'。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
|
||||
invalidated = list(invalidate_downstream_gates(
|
||||
execution=execution,
|
||||
change_type='inventory_source_changed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
# 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。
|
||||
exclude_gate_codes={'inventory_preparation'} - {''},
|
||||
))
|
||||
# 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
prepared_payload = dict(payload or {})
|
||||
prepared_payload.setdefault('idempotency_key', str(idempotency_key or ''))
|
||||
try:
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=str(gate.gate_code),
|
||||
trigger_type='user_manual',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
expected_gate_version=None,
|
||||
input_snapshot={
|
||||
'action_code': 'override_line_inventory_source',
|
||||
'payload': prepared_payload,
|
||||
},
|
||||
)
|
||||
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
|
||||
reran = True
|
||||
except Exception as exc: # noqa: BLE001 — 覆写失败不抛,交由调用方/前端处置
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reran': False,
|
||||
'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}',
|
||||
}
|
||||
_refresh_execution_pointers(execution)
|
||||
db.session.flush()
|
||||
return {
|
||||
'invalidated_gates': invalidated,
|
||||
'reset_to': 'inventory_preparation',
|
||||
'reran': reran,
|
||||
'gate_status': updated_gate.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/stp_inventory_freeze.py
|
||||
|
||||
用途:建单时将资格服务的行级库存源候选冻结到 Task,供后续库存准备消费。
|
||||
用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。
|
||||
依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。
|
||||
逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved;
|
||||
多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review);
|
||||
@@ -62,7 +62,7 @@ def freeze_stp_inventory_candidates_on_task(
|
||||
line_projections: list[dict[str, Any]] | None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
将建单前候选冻结到任务字段与 step_payload。
|
||||
将建单前候选冻结到 CandidateSet;任务仅保留 CandidateSet 指针。
|
||||
|
||||
核心逻辑:
|
||||
- 恰好 1 个有效启用候选 → status=resolved(任务级摘要);
|
||||
@@ -87,7 +87,7 @@ def freeze_stp_inventory_candidates_on_task(
|
||||
'freeze': 'stp_build',
|
||||
'line_projections': [
|
||||
{
|
||||
'line_key': item.get('line_key'),
|
||||
'draft_line_id': item.get('draft_line_id'),
|
||||
'line_index': item.get('line_index'),
|
||||
'candidate_inventory_source_codes': list(item.get('candidate_inventory_source_codes') or []),
|
||||
'selection_mode': item.get('selection_mode'),
|
||||
@@ -148,36 +148,7 @@ def freeze_stp_inventory_candidates_on_task(
|
||||
line_projections=line_projections,
|
||||
)
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_candidates'] = {
|
||||
'source_codes': valid_codes,
|
||||
'lines': evidence[0]['line_projections'],
|
||||
'frozen_at': 'build',
|
||||
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
# 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。
|
||||
if adjudication.status == 'candidates_frozen':
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_candidates'] = {
|
||||
'source_codes': valid_codes,
|
||||
'lines': evidence[0]['line_projections'],
|
||||
'frozen_at': 'build',
|
||||
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
|
||||
}
|
||||
resolution = dict(payload.get('inventory_source_resolution') or {})
|
||||
resolution['status'] = 'candidates_frozen'
|
||||
resolution['candidates'] = candidates
|
||||
resolution['reason'] = adjudication.reason
|
||||
payload['inventory_source_resolution'] = resolution
|
||||
task.step_payload_json = payload
|
||||
task.inventory_source_status = 'candidates_frozen'
|
||||
task.inventory_source_method = 'stp_build_freeze'
|
||||
task.inventory_source_config_version = config_version
|
||||
task.inventory_routing_fingerprint = fingerprint
|
||||
|
||||
# [STEP] 仅对真实 ORM 任务写审计事件(单测 SimpleNamespace 跳过)。
|
||||
if isinstance(task, ShippingNotice):
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
@@ -227,7 +198,4 @@ def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]:
|
||||
for source in get_active_candidate_sources(task)
|
||||
if str(source.source_code or '').strip()
|
||||
]
|
||||
if codes:
|
||||
return list(dict.fromkeys(codes))
|
||||
single = str(task.inventory_source_code or '').strip().upper()
|
||||
return [single] if single else []
|
||||
return list(dict.fromkeys(codes))
|
||||
@@ -123,7 +123,7 @@ 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 parse_inventory_snapshot_file
|
||||
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
|
||||
|
||||
current_set = get_active_candidate_set(task)
|
||||
@@ -182,12 +182,10 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
'required': in_required,
|
||||
})
|
||||
continue
|
||||
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines:
|
||||
try:
|
||||
lines, _meta = parse_inventory_snapshot_file(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
try:
|
||||
lines, _meta = read_inventory_file_lines(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
if not lines:
|
||||
if in_required:
|
||||
missing.append(code)
|
||||
@@ -213,18 +211,6 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
|
||||
'required': in_required,
|
||||
})
|
||||
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['candidate_inventory_prep'] = {
|
||||
'candidate_set_id': int(current_set.id),
|
||||
'candidate_set_version': int(current_set.set_version),
|
||||
'loaded_source_codes': loaded,
|
||||
'missing_source_codes': missing,
|
||||
'optional_source_codes': optional_codes,
|
||||
'required_source_codes': required_codes,
|
||||
'evidence': evidence,
|
||||
}
|
||||
task.step_payload_json = payload
|
||||
|
||||
if not merged and required_codes:
|
||||
return {
|
||||
'status': 'missing_files',
|
||||
@@ -469,7 +455,7 @@ def match_order_lines_across_candidates(
|
||||
line_results.append(result)
|
||||
resolutions.append({
|
||||
'line_index': index,
|
||||
'line_key': line.get('line_key'),
|
||||
'line_no': int(line.get('line_no') or index + 1),
|
||||
'disposition': result['disposition'],
|
||||
'effective_reservation_id': effective,
|
||||
'part_number': part or None,
|
||||
@@ -503,80 +489,43 @@ def match_order_lines_across_candidates(
|
||||
|
||||
def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None:
|
||||
"""
|
||||
将跨候选匹配结果写入任务并投影汇总库存源。
|
||||
|
||||
核心逻辑:全部 ok 时投影 inventory_source_code(多源取首个作 Excel 模板绑定,
|
||||
行级 resolved 仍保留在 line_inventory_resolutions);不再因多源成功命中阻断制单。
|
||||
将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。
|
||||
"""
|
||||
resolutions = list(match_payload.get('resolutions') or [])
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload['line_inventory_resolutions'] = resolutions
|
||||
# 历史阻断标记:全成功多源场景不再阻断,清理以免误伤自动链。
|
||||
payload.pop('multi_source_excel_block', None)
|
||||
task.step_payload_json = payload
|
||||
task.match_status = str(match_payload.get('match_status') or '')
|
||||
task.line_results_json = list(match_payload.get('line_results') or [])
|
||||
task.shortage_json = dict(match_payload.get('shortage_json') or {})
|
||||
del task, match_payload
|
||||
|
||||
ok_sources = sorted({
|
||||
str(item.get('resolved_inventory_source_code') or '').strip().upper()
|
||||
for item in resolutions
|
||||
if item.get('disposition') == 'ok' and item.get('resolved_inventory_source_code')
|
||||
})
|
||||
if match_payload.get('match_status') == 'fulfillable' and ok_sources:
|
||||
primary = ok_sources[0]
|
||||
source = get_database_inventory_source(primary)
|
||||
if source is not None:
|
||||
task.inventory_source_code = primary
|
||||
task.inventory_connector_type = str(source.get('connector_type') or '') or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
|
||||
task.inventory_source_status = 'resolved'
|
||||
task.inventory_source_method = (
|
||||
'stp_line_match' if len(ok_sources) == 1 else 'stp_line_match_multi'
|
||||
)
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
if len(ok_sources) > 1:
|
||||
payload['resolved_ok_source_codes'] = ok_sources
|
||||
payload['excel_binding_source_code'] = primary
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]:
|
||||
"""
|
||||
多文件冲突时可人工指定的库存源编码列表。
|
||||
|
||||
核心逻辑:仅汇总 multi_file_conflict 行的 candidate_hit_source_codes;
|
||||
全成功多源制单场景不再需要人工恢复。
|
||||
核心逻辑:仅汇总 source_conflict 行的候选源,优先取行匹配事实 detail_json 内的
|
||||
candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用
|
||||
库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
load_current_match_facts_by_task,
|
||||
)
|
||||
codes: list[str] = []
|
||||
# 兼容历史 multi_source_excel_block 任务。
|
||||
if bool(payload.get('multi_source_excel_block')):
|
||||
for code in payload.get('resolved_ok_source_codes') or []:
|
||||
for item in load_current_match_facts_by_task(getattr(task, 'id', None)).values():
|
||||
if str(item.get('match_result') or item.get('disposition') or '').strip().lower() != 'source_conflict':
|
||||
continue
|
||||
detail = dict(item.get('detail_json') or {}) if isinstance(item.get('detail_json'), dict) else {}
|
||||
candidates = list(detail.get('candidate_hit_source_codes') or [])
|
||||
if not candidates:
|
||||
# [STEP] 冲突行未记录候选源时兜底读取全部可用源,避免用户无可选项。
|
||||
candidates = [
|
||||
str(src.get('source_code') or '').strip().upper()
|
||||
for src in list_database_inventory_sources()
|
||||
if str(src.get('source_code') or '').strip()
|
||||
]
|
||||
for code in candidates:
|
||||
normalized = str(code or '').strip().upper()
|
||||
if normalized and normalized not in codes:
|
||||
codes.append(normalized)
|
||||
if codes:
|
||||
return codes
|
||||
resolutions = payload.get('line_inventory_resolutions')
|
||||
for collection in (
|
||||
resolutions,
|
||||
payload.get('match_line_results'),
|
||||
(payload.get('shortage_json') or {}).get('lines') if isinstance(payload.get('shortage_json'), dict) else None,
|
||||
):
|
||||
if not isinstance(collection, list):
|
||||
continue
|
||||
for item in collection:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('disposition') or '') != 'multi_file_conflict':
|
||||
continue
|
||||
for code in item.get('candidate_hit_source_codes') or []:
|
||||
normalized = str(code or '').strip().upper()
|
||||
if normalized and normalized not in codes:
|
||||
codes.append(normalized)
|
||||
return codes
|
||||
|
||||
|
||||
@@ -600,8 +549,17 @@ def apply_forced_match_source_filter(
|
||||
Returns:
|
||||
过滤后的库存行;无强制源时原样返回。
|
||||
"""
|
||||
if task.__class__.__name__ == 'ShippingOrderTask':
|
||||
from app.services.shipping_notice.inventory_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())
|
||||
if len(selected) == 1:
|
||||
selected_code = next(iter(selected))
|
||||
return [row for row in inventory_lines if not isinstance(row, dict) or not row.get('__source_code') or str(row.get('__source_code')).strip().upper() == selected_code]
|
||||
return inventory_lines
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
forced = str(payload.get('forced_match_source_code') or task.inventory_source_code or '').strip().upper()
|
||||
forced = str(payload.get('forced_match_source_code') or '').strip().upper()
|
||||
if not forced:
|
||||
return inventory_lines
|
||||
if not any(isinstance(row, dict) and row.get('__source_code') for row in inventory_lines):
|
||||
|
||||
Reference in new issue
Block a user