feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相
纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断, Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b352c281d5
commit
323928626b
92 files changed
+11930
-458
No files matched your search
@@ -5,11 +5,11 @@ backend/app/services/shipping_notice/audit_service.py
|
||||
写入 Workflow 软引用与哈希链字段。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、
|
||||
SQLAlchemy 会话。
|
||||
逻辑:Run、Task、Workflow Item、库存和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt 和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
写入前投影白名单快照 → 计算 diff → 解析同聚合 previous_event_hash → 计算 event_hash;
|
||||
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
|
||||
证据引用、Workflow 软引用(非 session_item)、属主;货代全业务审计事件永久保留
|
||||
(retention_expires_at=None),清理 Job 仅处理历史遗留的到期行。IP / User-Agent 仅持久化哈希。
|
||||
证据引用、Workflow 软引用(非 session_item)、属主;actor_type 含 worker(门禁 Job);
|
||||
货代全业务审计事件永久保留(retention_expires_at=None),清理 Job 仅处理历史遗留到期行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -245,7 +245,8 @@ def append_shipping_audit_event(
|
||||
resolve_previous_event_hash,
|
||||
)
|
||||
|
||||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'}
|
||||
# worker:门禁 Attempt / Job 租约路径的执行主体(Phase 4+)。
|
||||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'}
|
||||
if actor_type not in allowed_actor_types:
|
||||
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
|
||||
if result is not None and result not in {'success', 'failure', 'rejected', 'ignored'}:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
冻结前履约就绪门禁。
|
||||
services/shipping_notice/freeze_readiness_service.py
|
||||
|
||||
用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。
|
||||
依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及固定履约契约。
|
||||
逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。
|
||||
阶段 5 自动冻结入口接入后,同一服务继续负责把 Run 级自动冻结门禁摘要折叠为冻结阻断原因。
|
||||
用途:冻结前履约就绪门禁;输出标准 Gate 结果、稳定原因码与诊断 Finding。
|
||||
依赖:订单 Extraction、字段裁决、冲突门禁、固定履约契约、process_gate_contract。
|
||||
逻辑:order_freeze_service 在创建 Snapshot 前调用 assert_freeze_readiness;
|
||||
evaluate_freeze_readiness_gate 供统一 Gate 接线消费;
|
||||
自动冻结策略资格/客户范围/场景/紧急停止统一归属 order_freeze_readiness。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,10 +14,135 @@ from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask
|
||||
from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import required_field_configs
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
build_process_finding,
|
||||
owning_gate_for_reason,
|
||||
)
|
||||
from app.services.shipping_notice.task_field_gate import open_field_conflict_issues
|
||||
|
||||
_OWNING_GATE = 'order_freeze_readiness'
|
||||
|
||||
|
||||
def evaluate_freeze_readiness_gate(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
extraction: ShippingOrderExtraction,
|
||||
configs: dict[str, dict[str, Any]],
|
||||
freeze_mode: str = 'manual',
|
||||
auto_freeze_policy: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
评估订单冻结就绪门禁,返回标准 Gate 结果。
|
||||
|
||||
核心逻辑:收集 blocking / diagnostic Finding;仅 blocking 决定 passed;
|
||||
自动冻结路径额外消费 Run 级 policy 并折叠为唯一 owning_gate 原因。
|
||||
|
||||
Args:
|
||||
task / extraction / configs: 冻结上下文。
|
||||
freeze_mode: manual | auto。
|
||||
auto_freeze_policy: Run 冻结策略摘要。
|
||||
|
||||
Returns:
|
||||
passed、status、blocking_reason_code、findings、issues。
|
||||
"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
findings: list[dict[str, Any]] = []
|
||||
|
||||
if extraction.status != 'accepted':
|
||||
issue = {'reason': 'extraction_not_accepted', 'owning_gate_code': 'order_field_extraction'}
|
||||
issues.append(issue)
|
||||
findings.append(_issue_finding(issue, severity='blocking'))
|
||||
|
||||
for conflict in open_field_conflict_issues(task):
|
||||
item = dict(conflict)
|
||||
item.setdefault('owning_gate_code', 'field_conflict_resolution')
|
||||
item.setdefault('reason', item.get('reason') or 'field_conflict')
|
||||
issues.append(item)
|
||||
findings.append(_issue_finding(item, severity='blocking'))
|
||||
|
||||
auto_issues = _auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy)
|
||||
issues.extend(auto_issues)
|
||||
for item in auto_issues:
|
||||
findings.append(_issue_finding(item, severity='blocking'))
|
||||
|
||||
required = required_field_configs(extraction.schema_version.definition_json or {})
|
||||
required_codes = {'reservation_id', 'part_number', 'qty'}
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
|
||||
value_map = {(item.line_id, str(item.field_id)): item.value_json for item in values}
|
||||
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
|
||||
if not lines:
|
||||
issue = {'reason': 'missing_order_lines', 'owning_gate_code': 'field_completeness'}
|
||||
issues.append(issue)
|
||||
findings.append(_issue_finding(issue, severity='blocking'))
|
||||
for line in lines:
|
||||
for code in required_codes:
|
||||
config = required[code]
|
||||
key = (line.id, str(config['field_id']))
|
||||
value = value_map.get(key)
|
||||
if value in (None, ''):
|
||||
issue = {
|
||||
'reason': 'required_field_missing',
|
||||
'field': code,
|
||||
'line_index': line.position,
|
||||
'owning_gate_code': 'field_completeness',
|
||||
}
|
||||
issues.append(issue)
|
||||
findings.append(_issue_finding(issue, severity='blocking'))
|
||||
continue
|
||||
if code == 'qty':
|
||||
try:
|
||||
if Decimal(str(value)) <= 0:
|
||||
raise InvalidOperation
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
issue = {
|
||||
'reason': 'quantity_not_positive',
|
||||
'field': code,
|
||||
'line_index': line.position,
|
||||
'owning_gate_code': 'field_completeness',
|
||||
}
|
||||
issues.append(issue)
|
||||
findings.append(_issue_finding(issue, severity='blocking'))
|
||||
# 值已存在即视为可冻结;Decision 细节由 field_* Gate 负责。
|
||||
|
||||
po_config = configs.get('customer_po_number')
|
||||
if po_config:
|
||||
po_key = (None, str(po_config['field_id']))
|
||||
if value_map.get(po_key) in (None, ''):
|
||||
issue = {
|
||||
'reason': 'required_field_missing',
|
||||
'field': 'customer_po_number',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
}
|
||||
issues.append(issue)
|
||||
findings.append(_issue_finding(issue, severity='blocking'))
|
||||
|
||||
# 策略内诊断 Finding 一并透出(若已有)。
|
||||
policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {}
|
||||
for item in policy.get('findings') or []:
|
||||
if isinstance(item, dict) and item.get('finding_code'):
|
||||
if not any(f.get('finding_code') == item.get('finding_code') for f in findings):
|
||||
findings.append(dict(item))
|
||||
|
||||
blocking = [f for f in findings if f.get('severity') == 'blocking' and f.get('blocks_current_action')]
|
||||
primary = blocking[0] if blocking else None
|
||||
passed = not blocking
|
||||
return {
|
||||
'passed': passed,
|
||||
'status': 'passed' if passed else 'blocked_manual',
|
||||
'gate_code': _OWNING_GATE,
|
||||
'blocking_reason_code': (primary or {}).get('reason_code') or (None if passed else 'freeze_not_ready'),
|
||||
'findings': findings,
|
||||
'issues': issues,
|
||||
'next_action_code': None if passed else 'open_order_review',
|
||||
}
|
||||
|
||||
|
||||
def assert_freeze_readiness(
|
||||
*,
|
||||
@@ -26,44 +152,25 @@ def assert_freeze_readiness(
|
||||
freeze_mode: str = 'manual',
|
||||
auto_freeze_policy: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""校验当前任务是否可冻结;自动冻结额外消费 Run 级门禁摘要并折叠为统一 issues。"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
if extraction.status != 'accepted':
|
||||
issues.append({'reason': 'extraction_not_accepted'})
|
||||
issues.extend(open_field_conflict_issues(task))
|
||||
issues.extend(_auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy))
|
||||
"""
|
||||
校验当前任务是否可冻结;失败抛出结构化 ValidationError。
|
||||
|
||||
required = required_field_configs(extraction.schema_version.definition_json or {})
|
||||
required_codes = {'reservation_id', 'part_number', 'qty'}
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all()
|
||||
accepted = {(item.line_id, str(item.field_id)): item for item in decisions if item.decision_status in {'accepted', 'corroborated'}}
|
||||
value_map = {(item.line_id, str(item.field_id)): item.value_json for item in values}
|
||||
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
|
||||
if not lines:
|
||||
issues.append({'reason': 'missing_order_lines'})
|
||||
for line in lines:
|
||||
for code in required_codes:
|
||||
config = required[code]
|
||||
key = (line.id, str(config['field_id']))
|
||||
value = value_map.get(key)
|
||||
if value in (None, ''):
|
||||
issues.append({'reason': 'required_field_missing_or_unreviewed', 'field': code, 'line_index': line.position})
|
||||
continue
|
||||
if code == 'qty':
|
||||
try:
|
||||
if Decimal(str(value)) <= 0:
|
||||
raise InvalidOperation
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
issues.append({'reason': 'quantity_not_positive', 'field': code, 'line_index': line.position})
|
||||
# Header PO is the version identity and cannot be empty or unresolved.
|
||||
po_config = configs.get('customer_po_number')
|
||||
if po_config:
|
||||
po_key = (None, str(po_config['field_id']))
|
||||
if value_map.get(po_key) in (None, ''):
|
||||
issues.append({'reason': 'customer_po_missing_or_unreviewed', 'field': 'customer_po_number'})
|
||||
if issues:
|
||||
raise ValidationError('Order is not ready to freeze', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'issues': issues})
|
||||
核心逻辑:委托 evaluate_freeze_readiness_gate;自动冻结额外消费 Run 级门禁摘要。
|
||||
"""
|
||||
result = evaluate_freeze_readiness_gate(
|
||||
task=task,
|
||||
extraction=extraction,
|
||||
configs=configs,
|
||||
freeze_mode=freeze_mode,
|
||||
auto_freeze_policy=auto_freeze_policy,
|
||||
)
|
||||
if result.get('passed'):
|
||||
return
|
||||
raise ValidationError(
|
||||
'Order is not ready to freeze',
|
||||
code='SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
details={'issues': result.get('issues') or [], 'findings': result.get('findings') or []},
|
||||
)
|
||||
|
||||
|
||||
def _auto_freeze_blocking_issues(
|
||||
@@ -77,15 +184,44 @@ def _auto_freeze_blocking_issues(
|
||||
policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {}
|
||||
issues: list[dict[str, Any]] = []
|
||||
if not policy:
|
||||
return [{'reason': 'auto_freeze_policy_missing'}]
|
||||
return [{
|
||||
'reason': 'auto_freeze_policy_missing',
|
||||
'owning_gate_code': _OWNING_GATE,
|
||||
}]
|
||||
if not bool(policy.get('enabled')):
|
||||
issues.append({
|
||||
'reason': 'auto_freeze_not_enabled',
|
||||
'owning_gate_code': _OWNING_GATE,
|
||||
'mode': str(policy.get('mode') or '') or None,
|
||||
'qualification_status': str(policy.get('qualification_status') or '') or None,
|
||||
'customer_scope_status': str(policy.get('customer_scope_status') or '') or None,
|
||||
})
|
||||
for code in policy.get('blocking_reason_codes') or []:
|
||||
if str(code).strip():
|
||||
issues.append({'reason': 'auto_freeze_blocked', 'blocking_reason_code': str(code)})
|
||||
issues.append({
|
||||
'reason': 'auto_freeze_blocked',
|
||||
'blocking_reason_code': str(code),
|
||||
'owning_gate_code': owning_gate_for_reason(str(code)) or _OWNING_GATE,
|
||||
})
|
||||
return issues
|
||||
|
||||
|
||||
def _issue_finding(issue: dict[str, Any], *, severity: str) -> dict[str, Any]:
|
||||
"""将内部 issue 转为标准 Finding。"""
|
||||
reason = str(issue.get('blocking_reason_code') or issue.get('reason') or 'freeze_not_ready')
|
||||
owning = str(issue.get('owning_gate_code') or owning_gate_for_reason(reason) or _OWNING_GATE)
|
||||
mapped = owning_gate_for_reason(reason)
|
||||
stable_reason = reason if mapped else ('freeze_not_ready' if owning == _OWNING_GATE else 'required_field_missing' if owning == 'field_completeness' else 'extraction_incomplete' if owning == 'order_field_extraction' else 'field_conflict' if owning == 'field_conflict_resolution' else 'freeze_not_ready')
|
||||
return build_process_finding(
|
||||
finding_code=f'freeze_{reason}',
|
||||
owning_gate_code=owning,
|
||||
severity=severity,
|
||||
reason_code=stable_reason,
|
||||
field_code=str(issue.get('field') or '') or None,
|
||||
user_visible=severity == 'blocking',
|
||||
blocks_current_action=severity == 'blocking',
|
||||
details={
|
||||
**{k: v for k, v in issue.items() if k not in {'reason', 'owning_gate_code'}},
|
||||
'raw_reason': reason,
|
||||
},
|
||||
)
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/generic_order_gate.py
|
||||
|
||||
用途:通用确定性解析统一 fail-closed 门禁,产出稳定原因码与完整性摘要。
|
||||
依赖:generic_order_completeness、generic_order_parser、order_extraction_route_contract。
|
||||
逻辑:parse_generic_orders 之后由 order_extraction_workflow 调用;任一阻断条件成立则禁止 generic_deterministic。
|
||||
逻辑:parse_generic_orders 之后由 order_extraction_workflow 调用;任一完整性或证据阻断条件成立则禁止 generic_deterministic。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,7 +22,6 @@ from app.services.shipping_notice.generic_order_parser import (
|
||||
parse_generic_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_route_contract import GENERIC_GATE_POLICY_VERSION
|
||||
from app.services.shipping_notice.order_schema.table_contract import TABLE_FIELD_CODES
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -52,7 +51,7 @@ def evaluate_generic_extraction_gate(
|
||||
unit: Any,
|
||||
) -> GenericGateResult:
|
||||
"""
|
||||
执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与 LLM 字段。
|
||||
执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。
|
||||
|
||||
核心逻辑:
|
||||
1. 先构建 completeness 报告;
|
||||
@@ -74,8 +73,6 @@ def evaluate_generic_extraction_gate(
|
||||
stable_codes: list[str] = []
|
||||
|
||||
gate_codes.extend(_completeness_gate_codes(completeness))
|
||||
gate_codes.extend(_llm_involvement_codes(definition))
|
||||
|
||||
parse_result = parse_generic_orders(
|
||||
candidates=candidates,
|
||||
definition=definition,
|
||||
@@ -141,28 +138,6 @@ def _completeness_gate_codes(report: GenericCompletenessReport) -> list[str]:
|
||||
return _dedupe(codes)
|
||||
|
||||
|
||||
def _llm_involvement_codes(definition: dict[str, Any]) -> list[str]:
|
||||
"""
|
||||
必填字段无法由表格/layout 确定性映射时必须阻断通用路径。
|
||||
|
||||
核心逻辑:collection_mode=deterministic_context 的 Header 可来自邮件上下文;
|
||||
不在 TABLE_FIELD_CODES 的必填 Line/Header 字段意味着需要 LLM 补全。
|
||||
"""
|
||||
for item in definition.get('fields') or []:
|
||||
if not isinstance(item, dict) or not item.get('enabled', True) or not item.get('required'):
|
||||
continue
|
||||
field_code = str(item.get('field_code') or '')
|
||||
collection_mode = str(item.get('collection_mode') or 'llm_extraction')
|
||||
if collection_mode == 'deterministic_context':
|
||||
continue
|
||||
scope = str(item.get('scope') or 'line')
|
||||
if scope == 'header' and field_code not in TABLE_FIELD_CODES:
|
||||
return ['llm_involvement']
|
||||
if scope == 'line' and field_code not in TABLE_FIELD_CODES:
|
||||
return ['llm_involvement']
|
||||
return []
|
||||
|
||||
|
||||
def _map_gate_codes_to_stable(codes: list[str]) -> list[str]:
|
||||
"""内部 gate 码映射到 STABLE_ROUTE_REASON_CODES 子集。"""
|
||||
mapping = {
|
||||
@@ -174,7 +149,6 @@ def _map_gate_codes_to_stable(codes: list[str]) -> list[str]:
|
||||
'multiple_customer': 'generic_gate_blocked',
|
||||
'multiple_business_tables': 'multiple_business_tables',
|
||||
'missing_data_rows': 'business_table_not_found',
|
||||
'llm_involvement': 'generic_gate_blocked',
|
||||
'html_table_columns_ambiguous': 'generic_gate_blocked',
|
||||
'html_table_duplicate_field_columns': 'generic_gate_blocked',
|
||||
'html_table_header_value_contamination': 'generic_gate_blocked',
|
||||
|
||||
@@ -5,6 +5,7 @@ services/shipping_notice/inventory_routing_engine.py
|
||||
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
|
||||
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。
|
||||
输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,12 +28,14 @@ class InventoryRoutingResult:
|
||||
|
||||
status 保留历史取值(resolved/ambiguous/unresolved/conflicted)供任务级裁决兼容;
|
||||
建单资格请以 can_build / block_reason 为准——ambiguous(多候选)允许建单。
|
||||
source_codes 为规则原始候选(未做库存源启停/解析 Profile 过滤)。
|
||||
"""
|
||||
|
||||
status: str
|
||||
source_codes: tuple[str, ...]
|
||||
matched_rule_ids: tuple[int, ...]
|
||||
evidence: dict[str, Any]
|
||||
matched_rules: tuple[dict[str, Any], ...] = ()
|
||||
|
||||
@property
|
||||
def can_build(self) -> bool:
|
||||
@@ -48,6 +51,34 @@ class InventoryRoutingResult:
|
||||
return 'no_inventory_source_candidates'
|
||||
return None
|
||||
|
||||
@property
|
||||
def rule_versions(self) -> tuple[dict[str, Any], ...]:
|
||||
"""命中规则的 code+version 摘要,供重路由审计前后快照。"""
|
||||
return tuple(
|
||||
{
|
||||
'rule_id': int(item.get('rule_id') or 0),
|
||||
'rule_code': str(item.get('rule_code') or ''),
|
||||
'version': int(item.get('version') or 0),
|
||||
}
|
||||
for item in self.matched_rules
|
||||
if isinstance(item, dict)
|
||||
)
|
||||
|
||||
|
||||
def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]:
|
||||
"""将命中规则折叠为可审计、可序列化的摘要元组。"""
|
||||
return tuple(
|
||||
{
|
||||
'rule_id': int(rule.id),
|
||||
'rule_code': str(rule.rule_code or ''),
|
||||
'version': int(rule.version or 0),
|
||||
'priority': int(rule.priority or 0),
|
||||
'action_type': str(rule.action_type or ''),
|
||||
'scope': str(rule.scope or ''),
|
||||
}
|
||||
for rule in rules
|
||||
)
|
||||
|
||||
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
|
||||
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
|
||||
@@ -105,18 +136,30 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr
|
||||
将同优先级命中规则折叠为候选集合与建单资格。
|
||||
|
||||
核心逻辑:add/exclude 合并候选;任一 require_manual_review → conflicted 且不可建单;
|
||||
多候选标记 ambiguous 但仍 can_build。
|
||||
多候选标记 ambiguous 但仍 can_build;同时附带规则版本与命中摘要。
|
||||
"""
|
||||
source_codes: set[str] = set()
|
||||
excluded: set[str] = set()
|
||||
manual = False
|
||||
matched = _matched_rule_summaries(top_rules)
|
||||
for rule in top_rules:
|
||||
if rule.action_type not in ALLOWED_ACTIONS:
|
||||
return InventoryRoutingResult(
|
||||
'conflicted',
|
||||
(),
|
||||
tuple(item.id for item in top_rules),
|
||||
{'reason': 'unsupported_action', 'priority': priority},
|
||||
{
|
||||
'reason': 'unsupported_action',
|
||||
'priority': priority,
|
||||
'matched_rules': [rule.rule_code for rule in top_rules],
|
||||
'matched_rule_summaries': list(matched),
|
||||
'rule_versions': list(
|
||||
{'rule_id': item['rule_id'], 'rule_code': item['rule_code'], 'version': item['version']}
|
||||
for item in matched
|
||||
),
|
||||
'raw_source_codes': [],
|
||||
},
|
||||
matched_rules=matched,
|
||||
)
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()}
|
||||
@@ -127,12 +170,23 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr
|
||||
else:
|
||||
manual = True
|
||||
source_codes.difference_update(excluded)
|
||||
ordered = tuple(sorted(source_codes))
|
||||
status = 'conflicted' if manual else ('resolved' if len(source_codes) == 1 else 'ambiguous' if source_codes else 'unresolved')
|
||||
return InventoryRoutingResult(
|
||||
status,
|
||||
tuple(sorted(source_codes)),
|
||||
ordered,
|
||||
tuple(rule.id for rule in top_rules),
|
||||
{'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
|
||||
{
|
||||
'priority': priority,
|
||||
'matched_rules': [rule.rule_code for rule in top_rules],
|
||||
'matched_rule_summaries': list(matched),
|
||||
'rule_versions': list(
|
||||
{'rule_id': item['rule_id'], 'rule_code': item['rule_code'], 'version': item['version']}
|
||||
for item in matched
|
||||
),
|
||||
'raw_source_codes': list(ordered),
|
||||
},
|
||||
matched_rules=matched,
|
||||
)
|
||||
|
||||
|
||||
@@ -155,7 +209,7 @@ def _evaluate_with_reader(*, scope: str, value_reader, now: datetime | None = No
|
||||
rules = _published_rules(scope=scope, now=moment)
|
||||
matched = [rule for rule in rules if _rule_matches(rule, value_reader=value_reader)]
|
||||
if not matched:
|
||||
return InventoryRoutingResult('unresolved', (), (), {'matched_rules': []})
|
||||
return InventoryRoutingResult('unresolved', (), (), {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []})
|
||||
priority = matched[0].priority
|
||||
top_rules = [rule for rule in matched if rule.priority == priority]
|
||||
return _evaluate_matched_rules(top_rules, priority=priority)
|
||||
@@ -176,7 +230,7 @@ def evaluate_inventory_source_rules(
|
||||
now: 测试可注入的评估时间,默认当前 UTC 时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult: 含 status / source_codes / can_build。
|
||||
InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。
|
||||
"""
|
||||
scope = 'line' if line is not None else 'task'
|
||||
return _evaluate_with_reader(
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
services/shipping_notice/order_auto_freeze_policy.py
|
||||
|
||||
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关。
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关;
|
||||
process_gate_contract(原因唯一归属 order_freeze_readiness)。
|
||||
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按模板资格、通用 STP 直通路径、
|
||||
技术失败、预算停止、紧急停止和复核状态刷新门禁摘要。
|
||||
通用路径仅 route_decision=straight_through 可冻结;禁止任何 LLM 路径自动冻结。
|
||||
通用路径仅 route_decision=straight_through 可冻结;禁止任何 LLM 路径自动冻结;
|
||||
资格、客户范围、场景范围与紧急停止统一归属 owning_gate=order_freeze_readiness。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,12 +22,17 @@ from app.models import (
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
build_process_finding,
|
||||
owning_gate_for_reason,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
generic_auto_freeze_enabled,
|
||||
)
|
||||
|
||||
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
|
||||
_OWNING_GATE = 'order_freeze_readiness'
|
||||
|
||||
|
||||
def build_initial_auto_freeze_policy(*, schema_policy_version: str | None) -> dict[str, Any]:
|
||||
@@ -67,11 +74,14 @@ def evaluate_run_auto_freeze_policy(
|
||||
# [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。
|
||||
if extraction_emergency_stop_enabled():
|
||||
blocking_reason_codes.append('extraction_emergency_stop')
|
||||
findings = [_freeze_finding('extraction_emergency_stop')]
|
||||
policy.update({
|
||||
'enabled': False,
|
||||
'emergency_stop': True,
|
||||
'freeze_source': None,
|
||||
'owning_gate_code': _OWNING_GATE,
|
||||
'blocking_reason_codes': sorted(set(blocking_reason_codes)),
|
||||
'findings': findings,
|
||||
'evaluated_from_run': True,
|
||||
})
|
||||
return policy
|
||||
@@ -157,11 +167,15 @@ def evaluate_run_auto_freeze_policy(
|
||||
if requires_customer_confirmation and freeze_source == 'profile_deterministic':
|
||||
blocking_reason_codes.append('customer_confirmation_required')
|
||||
|
||||
unique_codes = sorted(set(code for code in blocking_reason_codes if code))
|
||||
findings = [_freeze_finding(code) for code in unique_codes]
|
||||
|
||||
policy.update({
|
||||
'enabled': enabled,
|
||||
'mode': 'auto_freeze' if enabled else 'manual_confirmation',
|
||||
'freeze_source': freeze_source,
|
||||
'emergency_stop': False,
|
||||
'owning_gate_code': _OWNING_GATE,
|
||||
'selected_profile_id': int(selected_route.selected_profile_id) if selected_route and selected_route.selected_profile_id else None,
|
||||
'selected_profile_code': str(selected_route.selected_profile_code or '') or None if selected_route else None,
|
||||
'selected_profile_checksum': str(selected_route.selected_profile_checksum or '') or None if selected_route else None,
|
||||
@@ -174,12 +188,36 @@ def evaluate_run_auto_freeze_policy(
|
||||
'business_scenario': current_business_scenario,
|
||||
'business_scenario_status': business_scenario_status,
|
||||
'customer_confirmation_required': requires_customer_confirmation,
|
||||
'blocking_reason_codes': sorted(set(code for code in blocking_reason_codes if code)),
|
||||
'blocking_reason_codes': unique_codes,
|
||||
'findings': findings,
|
||||
'evaluated_from_run': True,
|
||||
})
|
||||
return policy
|
||||
|
||||
|
||||
def _freeze_finding(reason_code: str) -> dict[str, Any]:
|
||||
"""
|
||||
将自动冻结原因投影为 order_freeze_readiness 所属 Finding。
|
||||
|
||||
Args:
|
||||
reason_code: 稳定阻断原因码。
|
||||
|
||||
Returns:
|
||||
标准 Finding;原因未知时仍归属冻结就绪门禁。
|
||||
"""
|
||||
code = str(reason_code or '').strip() or 'auto_freeze_not_enabled'
|
||||
owning = owning_gate_for_reason(code) or _OWNING_GATE
|
||||
return build_process_finding(
|
||||
finding_code=f'auto_freeze_{code}',
|
||||
owning_gate_code=owning,
|
||||
severity='blocking',
|
||||
reason_code=code,
|
||||
user_visible=True,
|
||||
blocks_current_action=True,
|
||||
details={'message': '自动建单策略尚未放行'},
|
||||
)
|
||||
|
||||
|
||||
def _route_contract(route: ShippingOrderExtractionRouteDecision) -> dict[str, Any]:
|
||||
"""从 candidate_summary_json 尾部提取阶段 0 路由契约摘要。"""
|
||||
items = route.candidate_summary_json if isinstance(route.candidate_summary_json, list) else []
|
||||
|
||||
@@ -2,18 +2,22 @@
|
||||
services/shipping_notice/order_build_eligibility_service.py
|
||||
|
||||
用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及
|
||||
自动建单五门禁(批准模板 / 字段完整 / 证据通过 / 无冲突重复 / 质量门禁)。
|
||||
自动建单内部检查(批准模板 / 字段完整 / 证据 / 冲突重复 / 质量门禁)。
|
||||
依赖:candidate_validation、field_rules、inventory_routing_engine、inventory_source_repository、
|
||||
ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun。
|
||||
ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun、
|
||||
ShippingInventorySource、process_gate_contract(原因唯一归属)。
|
||||
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断;
|
||||
人工已选候选(含原因)可覆盖规则零候选;五门禁失败仅阻断自动建单,落入 Review Case,
|
||||
不替代人工确认路径的 can_build(库存/Reservation)门禁。
|
||||
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
|
||||
停用或无已发布解析 Profile 的 Source 不进入有效候选;
|
||||
旧五门禁不再平行产生用户阻断,失败映射到唯一 owning_gate Finding;
|
||||
自动冻结资格/客户范围/场景/紧急停止统一归属 order_freeze_readiness。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
InventoryRoutingResult,
|
||||
@@ -24,9 +28,13 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
AUTO_BUILD_LEGACY_GATE_OWNING_MAP,
|
||||
build_process_finding,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
# 自动建单五门禁稳定键;失败 → 仅 Review Case,禁止 STP 自动建单。
|
||||
# 自动建单内部检查键(仅用于 can_auto_create);禁止平行投影为五个用户阻断。
|
||||
AUTO_BUILD_GATE_KEYS: tuple[str, ...] = (
|
||||
'approved_template',
|
||||
'fields_complete',
|
||||
@@ -35,6 +43,15 @@ AUTO_BUILD_GATE_KEYS: tuple[str, ...] = (
|
||||
'quality_gate_passed',
|
||||
)
|
||||
|
||||
# 旧五门 → 稳定原因码(用户可见阻断只折叠到冻结就绪一次)。
|
||||
_AUTO_BUILD_GATE_REASON_CODES: dict[str, str] = {
|
||||
'approved_template': 'profile_not_auto_freeze_approved',
|
||||
'fields_complete': 'required_field_missing',
|
||||
'evidence_passed': 'evidence_missing',
|
||||
'no_conflict_or_duplicate': 'duplicate_unresolved',
|
||||
'quality_gate_passed': 'auto_freeze_not_enabled',
|
||||
}
|
||||
|
||||
|
||||
def _field_id_maps(
|
||||
*,
|
||||
@@ -76,19 +93,105 @@ def _normalize_manual_codes(raw: Any) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
|
||||
"""
|
||||
按最新启停与解析 Profile 状态拆分原始候选。
|
||||
|
||||
核心逻辑:仅「已启用 + RPA 可读 + 已发布解析 Profile」进入 available;
|
||||
其余进入 unavailable,并给出稳定 reason 码。
|
||||
|
||||
Args:
|
||||
codes: 规则或人工给出的库存源编码。
|
||||
|
||||
Returns:
|
||||
available / unavailable / unavailable_reasons。
|
||||
"""
|
||||
available: list[str] = []
|
||||
unavailable: list[str] = []
|
||||
reasons: dict[str, str] = {}
|
||||
for code in _normalize_manual_codes(codes):
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code).first()
|
||||
if source is None:
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'source_not_found'
|
||||
continue
|
||||
if not bool(source.enabled):
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'source_disabled'
|
||||
continue
|
||||
runtime = get_database_inventory_source(code, enabled_only=True)
|
||||
if runtime is None:
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'source_runtime_unavailable'
|
||||
continue
|
||||
parsing = source.parsing_profile
|
||||
if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published':
|
||||
unavailable.append(code)
|
||||
reasons[code] = 'parsing_profile_unavailable'
|
||||
continue
|
||||
available.append(code)
|
||||
return {
|
||||
'available': available,
|
||||
'unavailable': unavailable,
|
||||
'unavailable_reasons': reasons,
|
||||
}
|
||||
|
||||
|
||||
def _validate_enabled_sources(codes: list[str]) -> tuple[list[str], list[str]]:
|
||||
"""
|
||||
校验库存源已启用;返回 (valid_codes, invalid_codes)。
|
||||
校验库存源已启用且具备有效解析 Profile;返回 (valid_codes, invalid_codes)。
|
||||
"""
|
||||
valid: list[str] = []
|
||||
invalid: list[str] = []
|
||||
for code in codes:
|
||||
source = get_database_inventory_source(code)
|
||||
if source is None:
|
||||
invalid.append(code)
|
||||
else:
|
||||
valid.append(code)
|
||||
return valid, invalid
|
||||
classified = classify_inventory_source_codes(codes)
|
||||
return list(classified['available']), list(classified['unavailable'])
|
||||
|
||||
|
||||
def _rule_suggestion_from_result(rule_result: InventoryRoutingResult) -> dict[str, Any]:
|
||||
"""
|
||||
将引擎原始结果折叠为「规则建议」:过滤不可用源后重算建议状态。
|
||||
|
||||
核心逻辑:conflicted 保留强制人工语义;其余按可用候选数映射
|
||||
resolved / ambiguous / unresolved。
|
||||
"""
|
||||
raw_codes = list(rule_result.source_codes)
|
||||
classified = classify_inventory_source_codes(raw_codes)
|
||||
available = list(classified['available'])
|
||||
unavailable = list(classified['unavailable'])
|
||||
if rule_result.status == 'conflicted':
|
||||
suggestion_status = 'conflicted'
|
||||
suggestion_codes = available
|
||||
block_reason = 'require_manual_review'
|
||||
elif not available:
|
||||
suggestion_status = 'unresolved'
|
||||
suggestion_codes = []
|
||||
block_reason = 'no_inventory_source_candidates'
|
||||
elif len(available) == 1:
|
||||
suggestion_status = 'resolved'
|
||||
suggestion_codes = available
|
||||
block_reason = None
|
||||
else:
|
||||
suggestion_status = 'ambiguous'
|
||||
suggestion_codes = available
|
||||
block_reason = None
|
||||
matched_rules = [dict(item) for item in (getattr(rule_result, 'matched_rules', None) or ())]
|
||||
rule_versions = [dict(item) for item in (getattr(rule_result, 'rule_versions', None) or ())]
|
||||
return {
|
||||
'source_codes': suggestion_codes,
|
||||
'raw_source_codes': raw_codes,
|
||||
'unavailable_source_codes': unavailable,
|
||||
'unavailable_reasons': dict(classified['unavailable_reasons']),
|
||||
'routing_status': suggestion_status,
|
||||
'block_reason': block_reason,
|
||||
'can_build': bool(suggestion_codes) and suggestion_status != 'conflicted',
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'matched_rules': matched_rules,
|
||||
'rule_versions': rule_versions,
|
||||
'evidence': dict(rule_result.evidence),
|
||||
}
|
||||
|
||||
|
||||
def _codes_equal(left: list[str] | tuple[str, ...] | None, right: list[str] | tuple[str, ...] | None) -> bool:
|
||||
"""比较两组库存源编码是否集合相等。"""
|
||||
return set(_normalize_manual_codes(left)) == set(_normalize_manual_codes(right))
|
||||
|
||||
|
||||
def project_line_inventory_candidates(
|
||||
@@ -101,21 +204,23 @@ def project_line_inventory_candidates(
|
||||
"""
|
||||
为单条明细投影库存源候选与建单库存门禁。
|
||||
|
||||
核心逻辑:先跑行级规则;行级 unresolved 时回退任务级规则;人工选择优先于规则零候选。
|
||||
核心逻辑:先跑行级规则;行级 unresolved 时回退任务级规则;人工选择优先于规则建议,
|
||||
重路由只更新规则建议、不静默覆盖人工决定;有效候选仅含可用库存源。
|
||||
|
||||
Args:
|
||||
fields: 冻结 Schema 字段。
|
||||
header_by_code / line_by_code: 当前头/行值。
|
||||
line_meta: Draft 行上可选的 inventory_routing 人工覆盖。
|
||||
line_meta: Draft 行上可选的 inventory_routing 人工覆盖与待确认建议。
|
||||
|
||||
Returns:
|
||||
含 candidate_inventory_source_codes、can_build、routing_status、证据摘要的字典。
|
||||
含有效候选、原始候选、不可用候选、规则建议与建单门禁的字典。
|
||||
"""
|
||||
meta = line_meta if isinstance(line_meta, dict) else {}
|
||||
routing_overlay = meta.get('inventory_routing') if isinstance(meta.get('inventory_routing'), dict) else {}
|
||||
manual_codes = _normalize_manual_codes(routing_overlay.get('candidate_inventory_source_codes'))
|
||||
manual_reason = str(routing_overlay.get('manual_reason') or '').strip()
|
||||
selection_mode = str(routing_overlay.get('selection_mode') or '').strip().lower()
|
||||
stored_pending = bool(routing_overlay.get('suggestion_pending'))
|
||||
|
||||
header_ids, line_ids = _field_id_maps(
|
||||
fields=fields, header_by_code=header_by_code, line_by_code=line_by_code,
|
||||
@@ -132,56 +237,80 @@ def project_line_inventory_candidates(
|
||||
)
|
||||
# [STEP 1] 行级有结论优先;否则用任务级规则。
|
||||
rule_result: InventoryRoutingResult = line_result if line_result.status != 'unresolved' else task_result
|
||||
suggestion = _rule_suggestion_from_result(rule_result)
|
||||
|
||||
base_fields = {
|
||||
'raw_rule_source_codes': list(suggestion['raw_source_codes']),
|
||||
'rule_suggestion_source_codes': list(suggestion['source_codes']),
|
||||
'unavailable_source_codes': list(suggestion['unavailable_source_codes']),
|
||||
'unavailable_reasons': dict(suggestion['unavailable_reasons']),
|
||||
'matched_rule_ids': list(suggestion['matched_rule_ids']),
|
||||
'matched_rules': list(suggestion['matched_rules']),
|
||||
'rule_versions': list(suggestion['rule_versions']),
|
||||
'rule_source_codes': list(suggestion['source_codes']),
|
||||
'rule_suggestion': {
|
||||
'source_codes': list(suggestion['source_codes']),
|
||||
'raw_source_codes': list(suggestion['raw_source_codes']),
|
||||
'unavailable_source_codes': list(suggestion['unavailable_source_codes']),
|
||||
'unavailable_reasons': dict(suggestion['unavailable_reasons']),
|
||||
'routing_status': suggestion['routing_status'],
|
||||
'matched_rule_ids': list(suggestion['matched_rule_ids']),
|
||||
'matched_rules': list(suggestion['matched_rules']),
|
||||
'rule_versions': list(suggestion['rule_versions']),
|
||||
},
|
||||
}
|
||||
|
||||
if selection_mode == 'manual' and manual_codes:
|
||||
valid, invalid = _validate_enabled_sources(manual_codes)
|
||||
suggestion_pending = stored_pending and not _codes_equal(valid, suggestion['source_codes'])
|
||||
if not manual_reason:
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'conflicted',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_reason_required',
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': invalid,
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
if invalid or not valid:
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'unresolved',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_invalid',
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': invalid,
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'resolved' if len(valid) == 1 else 'ambiguous',
|
||||
'can_build': True,
|
||||
'block_reason': None,
|
||||
'manual_reason': manual_reason,
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'invalid_source_codes': [],
|
||||
'evidence': {'manual_override': True, 'rule': rule_result.evidence},
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
|
||||
# [STEP 2] 无人工决定:规则建议直接成为有效结果(唯一命中即可建单)。
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'rule',
|
||||
'candidate_inventory_source_codes': list(rule_result.source_codes),
|
||||
'routing_status': rule_result.status,
|
||||
'can_build': rule_result.can_build,
|
||||
'block_reason': rule_result.block_reason,
|
||||
'matched_rule_ids': list(rule_result.matched_rule_ids),
|
||||
'rule_source_codes': list(rule_result.source_codes),
|
||||
'candidate_inventory_source_codes': list(suggestion['source_codes']),
|
||||
'routing_status': suggestion['routing_status'],
|
||||
'can_build': bool(suggestion['can_build']),
|
||||
'block_reason': suggestion['block_reason'],
|
||||
'invalid_source_codes': [],
|
||||
'evidence': dict(rule_result.evidence),
|
||||
'suggestion_pending': False,
|
||||
'evidence': dict(suggestion['evidence']),
|
||||
}
|
||||
|
||||
|
||||
@@ -193,10 +322,11 @@ def assess_auto_build_gates(
|
||||
run: Any | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
评估自动建单五门禁;任一失败则只能进入 Review Case,禁止 STP 自动建单。
|
||||
评估自动建单内部五检查;任一失败则只能进入 Review Case,禁止 STP 自动建单。
|
||||
|
||||
核心逻辑:批准模板读 Unit 路由;字段完整由调用方汇总;证据/冲突/重复读 Candidate;
|
||||
质量门禁读 Run 冻结的 auto_freeze_policy.enabled(经质量批次批准后才为 True)。
|
||||
质量门禁读 Run 冻结的 auto_freeze_policy.enabled。
|
||||
返回 findings 按 owning_gate 去重;冻结资格类原因折叠为单一 order_freeze_readiness 用户阻断。
|
||||
|
||||
Args:
|
||||
fields_complete: Schema 必填与建单字段是否已齐备。
|
||||
@@ -205,7 +335,7 @@ def assess_auto_build_gates(
|
||||
run: 可选 ShippingOrderExtractionRun(含 auto_freeze_policy_json)。
|
||||
|
||||
Returns:
|
||||
gates(五键 bool)、can_auto_create、failed_gates。
|
||||
gates、can_auto_create、failed_gates、findings、user_blocking_finding。
|
||||
"""
|
||||
# [STEP 1] 批准模板:Unit 路由 auto_create_approved,或 Candidate 已 automatic 接受。
|
||||
route = {}
|
||||
@@ -236,10 +366,16 @@ def assess_auto_build_gates(
|
||||
|
||||
# [STEP 4] 质量门禁:Run 冻结策略 enabled=True 才视为通过;缺 Run 时视为未通过。
|
||||
quality_gate_passed = False
|
||||
policy_blocking_codes: list[str] = []
|
||||
if run is not None:
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
quality_gate_passed = bool(policy.get('enabled'))
|
||||
policy_blocking_codes = [
|
||||
str(code).strip()
|
||||
for code in (policy.get('blocking_reason_codes') or [])
|
||||
if str(code or '').strip()
|
||||
]
|
||||
|
||||
gates = {
|
||||
'approved_template': bool(approved_template),
|
||||
@@ -249,10 +385,65 @@ def assess_auto_build_gates(
|
||||
'quality_gate_passed': bool(quality_gate_passed),
|
||||
}
|
||||
failed = [key for key in AUTO_BUILD_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
# [STEP 5] 映射到 owning_gate Finding;冻结类折叠为一次用户阻断。
|
||||
# 优先使用 Run policy 的具体原因码,避免被通用 auto_freeze_not_enabled 抢占。
|
||||
findings: list[dict[str, Any]] = []
|
||||
freeze_reasons: list[str] = list(policy_blocking_codes)
|
||||
for key in failed:
|
||||
owning = AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key, 'order_freeze_readiness')
|
||||
reason = _AUTO_BUILD_GATE_REASON_CODES.get(key, 'auto_freeze_not_enabled')
|
||||
if owning == 'order_freeze_readiness':
|
||||
freeze_reasons.append(reason)
|
||||
continue
|
||||
findings.append(build_process_finding(
|
||||
finding_code=f'auto_build_{key}_failed',
|
||||
owning_gate_code=owning,
|
||||
severity='diagnostic',
|
||||
reason_code=reason,
|
||||
user_visible=False,
|
||||
blocks_current_action=False,
|
||||
details={'legacy_auto_build_gate': key},
|
||||
))
|
||||
|
||||
# 去重保持稳定顺序(policy 原因优先)
|
||||
seen_freeze: set[str] = set()
|
||||
freeze_unique: list[str] = []
|
||||
for code in freeze_reasons:
|
||||
if code in seen_freeze:
|
||||
continue
|
||||
seen_freeze.add(code)
|
||||
freeze_unique.append(code)
|
||||
|
||||
user_blocking_finding: dict[str, Any] | None = None
|
||||
if freeze_unique or any(
|
||||
key in failed for key in ('approved_template', 'quality_gate_passed')
|
||||
):
|
||||
primary_reason = freeze_unique[0] if freeze_unique else 'auto_freeze_not_enabled'
|
||||
user_blocking_finding = build_process_finding(
|
||||
finding_code='auto_freeze_policy_not_approved',
|
||||
owning_gate_code='order_freeze_readiness',
|
||||
severity='blocking',
|
||||
reason_code=primary_reason,
|
||||
user_visible=True,
|
||||
blocks_current_action=True,
|
||||
details={
|
||||
'blocking_reason_codes': freeze_unique,
|
||||
'message': '自动建单策略尚未放行',
|
||||
'legacy_failed_gates': [
|
||||
key for key in failed
|
||||
if AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key) == 'order_freeze_readiness'
|
||||
],
|
||||
},
|
||||
)
|
||||
findings.append(user_blocking_finding)
|
||||
|
||||
return {
|
||||
'gates': gates,
|
||||
'failed_gates': failed,
|
||||
'can_auto_create': not failed,
|
||||
'findings': findings,
|
||||
'user_blocking_finding': user_blocking_finding,
|
||||
}
|
||||
|
||||
|
||||
@@ -268,11 +459,11 @@ def assess_order_build_eligibility(
|
||||
run: Any | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总整单建单资格与自动建单五门禁。
|
||||
汇总整单建单资格与自动建单内部检查。
|
||||
|
||||
核心逻辑:复用 Candidate 基础评估;逐行补有效 Reservation 与库存源候选门禁;
|
||||
任一阻断则 can_build=False(人工确认仍可读该门禁);五门禁失败仅置
|
||||
can_auto_create=False,强制落入 Review Case,禁止自动建单。
|
||||
任一阻断则 can_build=False(人工确认仍可读该门禁);自动建单失败仅置
|
||||
can_auto_create=False,并投影唯一 owning_gate Finding,禁止旧五门禁平行用户阻断。
|
||||
|
||||
Args:
|
||||
fields: Schema field_id → 配置。
|
||||
@@ -280,10 +471,10 @@ def assess_order_build_eligibility(
|
||||
lines: 行 field_code → 值列表(与 line_metas 对齐)。
|
||||
line_metas: Draft 行原始对象(含 line_key / inventory_routing)。
|
||||
customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。
|
||||
candidate / unit / run: 可选门禁上下文(自动建单五门)。
|
||||
candidate / unit / run: 可选门禁上下文(自动建单检查)。
|
||||
|
||||
Returns:
|
||||
can_build、can_auto_create、gates、issues、line_projections、assessment 摘要。
|
||||
can_build、can_auto_create、gates、issues、findings、line_projections、assessment 摘要。
|
||||
"""
|
||||
metas = list(line_metas or [])
|
||||
while len(metas) < len(lines):
|
||||
@@ -295,7 +486,11 @@ def assess_order_build_eligibility(
|
||||
issues: list[dict[str, Any]] = []
|
||||
|
||||
if not customer_resolved:
|
||||
issues.append({'code': 'customer_unresolved', 'severity': 'blocking'})
|
||||
issues.append({
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
})
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
raw_line = dict(line) if isinstance(line, dict) else {}
|
||||
@@ -330,6 +525,7 @@ def assess_order_build_eligibility(
|
||||
'line_key': meta.get('line_key'),
|
||||
'line_index': index,
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'reservation_validation',
|
||||
})
|
||||
if not routing.get('can_build'):
|
||||
issues.append({
|
||||
@@ -337,7 +533,9 @@ def assess_order_build_eligibility(
|
||||
'line_key': meta.get('line_key'),
|
||||
'line_index': index,
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'inventory_source_routing',
|
||||
'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [],
|
||||
'unavailable_source_codes': routing.get('unavailable_source_codes') or [],
|
||||
})
|
||||
|
||||
assessment = assess_candidate_business_summary({**header_by_code, 'lines': enriched_lines})
|
||||
@@ -346,9 +544,15 @@ def assess_order_build_eligibility(
|
||||
'code': str(item.get('code') or 'invalid_order_line'),
|
||||
'line_index': item.get('line_index'),
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
})
|
||||
for field_code in assessment.get('missing_required_fields') or []:
|
||||
issues.append({'code': 'required_field_missing', 'field_code': field_code, 'severity': 'blocking'})
|
||||
issues.append({
|
||||
'code': 'required_field_missing',
|
||||
'field_code': field_code,
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
})
|
||||
|
||||
# 有效 Reservation 已在上方按行检查;不再用 line-only process_field_missing 重复阻断。
|
||||
reservations = [
|
||||
@@ -357,7 +561,11 @@ def assess_order_build_eligibility(
|
||||
if validated_reservation_id(item.get('effective_reservation_id'))
|
||||
]
|
||||
if len(reservations) != len(set(reservations)):
|
||||
issues.append({'code': 'reservation_duplicated_in_order', 'severity': 'blocking'})
|
||||
issues.append({
|
||||
'code': 'reservation_duplicated_in_order',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'reservation_validation',
|
||||
})
|
||||
|
||||
can_build = (
|
||||
bool(customer_resolved)
|
||||
@@ -372,7 +580,7 @@ def assess_order_build_eligibility(
|
||||
and not assessment.get('invalid_lines')
|
||||
and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues)
|
||||
)
|
||||
# [STEP] 五门禁:失败只阻断自动建单,不改写人工确认 can_build。
|
||||
# [STEP] 自动建单检查:失败只阻断自动建单;用户投影折叠到唯一 owning_gate。
|
||||
gate_result = assess_auto_build_gates(
|
||||
fields_complete=fields_complete and can_build,
|
||||
candidate=candidate,
|
||||
@@ -380,13 +588,18 @@ def assess_order_build_eligibility(
|
||||
run=run,
|
||||
)
|
||||
can_auto_create = bool(can_build and gate_result.get('can_auto_create'))
|
||||
if not gate_result.get('can_auto_create'):
|
||||
for gate_key in gate_result.get('failed_gates') or []:
|
||||
issues.append({
|
||||
'code': f'auto_build_gate_{gate_key}',
|
||||
'severity': 'auto_create_blocking',
|
||||
'gate': gate_key,
|
||||
})
|
||||
findings = list(gate_result.get('findings') or [])
|
||||
# 禁止再写 auto_build_gate_* 平行用户阻断;仅保留一条冻结就绪用户 Finding。
|
||||
user_finding = gate_result.get('user_blocking_finding')
|
||||
if user_finding and can_build and not can_auto_create:
|
||||
issues.append({
|
||||
'code': 'auto_freeze_policy_not_approved',
|
||||
'severity': 'auto_create_blocking',
|
||||
'owning_gate_code': 'order_freeze_readiness',
|
||||
'reason_code': user_finding.get('reason_code'),
|
||||
'finding_code': user_finding.get('finding_code'),
|
||||
'message': '自动建单策略尚未放行',
|
||||
})
|
||||
|
||||
enabled_codes = [
|
||||
str(item.get('source_code') or '').strip().upper()
|
||||
@@ -398,6 +611,8 @@ def assess_order_build_eligibility(
|
||||
'can_auto_create': can_auto_create,
|
||||
'gates': dict(gate_result.get('gates') or {}),
|
||||
'failed_gates': list(gate_result.get('failed_gates') or []),
|
||||
'findings': findings,
|
||||
'user_blocking_finding': user_finding,
|
||||
'status': 'ready' if can_build else 'needs_review',
|
||||
'issues': issues,
|
||||
'line_projections': line_projections,
|
||||
@@ -440,10 +655,153 @@ def apply_manual_inventory_candidates(
|
||||
valid, invalid = _validate_enabled_sources(codes)
|
||||
if invalid or not valid:
|
||||
raise ValueError('manual_inventory_source_invalid')
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
overlay = {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'manual_reason': text,
|
||||
# 人工改选后清除待确认建议,避免静默与旧建议混用。
|
||||
'suggestion_pending': False,
|
||||
}
|
||||
if isinstance(previous.get('rule_suggestion'), dict):
|
||||
overlay['rule_suggestion'] = previous.get('rule_suggestion')
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def apply_rule_suggestion_as_effective(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
suggestion: dict[str, Any],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将规则建议采用为当前有效候选(明确动作,非静默覆盖)。
|
||||
|
||||
核心逻辑:写入 selection_mode=rule 的有效编码;记录 adopt 动作语义与原因;
|
||||
清除 suggestion_pending。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象。
|
||||
suggestion: 规则建议片段(须含 source_codes)。
|
||||
reason: 采用原因或动作说明。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing。
|
||||
|
||||
Raises:
|
||||
ValueError: 建议无效。
|
||||
"""
|
||||
codes = _normalize_manual_codes(suggestion.get('source_codes'))
|
||||
text = str(reason or '').strip() or 'adopt_rule_suggestion'
|
||||
if not codes:
|
||||
raise ValueError('rule_suggestion_empty')
|
||||
valid, invalid = _validate_enabled_sources(codes)
|
||||
if invalid or not valid:
|
||||
raise ValueError('rule_suggestion_invalid')
|
||||
overlay = {
|
||||
'selection_mode': 'rule',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'manual_reason': text,
|
||||
'adopted_from_rule': True,
|
||||
'suggestion_pending': False,
|
||||
'rule_suggestion': {
|
||||
'source_codes': valid,
|
||||
'raw_source_codes': list(suggestion.get('raw_source_codes') or valid),
|
||||
'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []),
|
||||
'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}),
|
||||
'routing_status': str(
|
||||
suggestion.get('routing_status') or ('resolved' if len(valid) == 1 else 'ambiguous')
|
||||
),
|
||||
'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []),
|
||||
'matched_rules': list(suggestion.get('matched_rules') or []),
|
||||
'rule_versions': list(suggestion.get('rule_versions') or []),
|
||||
},
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def mark_keep_manual_inventory_decision(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
明确保留人工库存源决定并拒绝当前规则建议。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象(须已有 manual 覆盖)。
|
||||
reason: 保留原因或动作说明。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing。
|
||||
|
||||
Raises:
|
||||
ValueError: 当前无人工决定。
|
||||
"""
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
if str(previous.get('selection_mode') or '').strip().lower() != 'manual':
|
||||
raise ValueError('manual_inventory_decision_missing')
|
||||
codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes'))
|
||||
if not codes:
|
||||
raise ValueError('manual_inventory_decision_missing')
|
||||
text = str(reason or '').strip() or 'keep_manual_inventory_decision'
|
||||
overlay = {
|
||||
**previous,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': codes,
|
||||
'suggestion_pending': False,
|
||||
'rejected_rule_suggestion': previous.get('rule_suggestion'),
|
||||
'keep_manual_reason': text[:500],
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def attach_rule_suggestion_without_override(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
suggestion: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重路由后写入规则建议;若存在人工决定则不覆盖有效候选。
|
||||
|
||||
核心逻辑:人工决定存在时仅更新 rule_suggestion 与 suggestion_pending;
|
||||
无人工决定时清除残留覆盖层,有效结果由实时规则投影得出。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象。
|
||||
suggestion: 最新规则建议。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing;无人工决定时返回空 dict。
|
||||
"""
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
suggestion_payload = {
|
||||
'source_codes': list(suggestion.get('source_codes') or []),
|
||||
'raw_source_codes': list(suggestion.get('raw_source_codes') or []),
|
||||
'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []),
|
||||
'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}),
|
||||
'routing_status': str(suggestion.get('routing_status') or 'unresolved'),
|
||||
'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []),
|
||||
'matched_rules': list(suggestion.get('matched_rules') or []),
|
||||
'rule_versions': list(suggestion.get('rule_versions') or []),
|
||||
}
|
||||
selection_mode = str(previous.get('selection_mode') or '').strip().lower()
|
||||
manual_codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes'))
|
||||
if selection_mode == 'manual' and manual_codes:
|
||||
pending = not _codes_equal(manual_codes, suggestion_payload['source_codes'])
|
||||
overlay = {
|
||||
**previous,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': manual_codes,
|
||||
'rule_suggestion': suggestion_payload,
|
||||
'suggestion_pending': pending,
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
if previous:
|
||||
line_meta.pop('inventory_routing', None)
|
||||
return {}
|
||||
@@ -4,11 +4,11 @@ backend/app/services/shipping_notice/order_extraction_run_service.py
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
|
||||
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、
|
||||
workflow_ledger_service(物化后幂等建 WorkflowItem)。
|
||||
workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run;
|
||||
同会话跨上传批次的完整附件内容指纹相同时,复用活跃或待处理 Workflow Item,避免重复 Workflow;
|
||||
progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进;
|
||||
Document 物化后立即 ensure WorkflowItem,使版面阶段即有 Item(解决 Run>0 / Item=0)。
|
||||
Document 物化后立即 ensure WorkflowItem 与 Process Execution,使版面阶段即有 Item 与 Gate。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -407,11 +407,9 @@ def _build_snapshot(
|
||||
and isinstance(document.order_extraction_result_json, dict)
|
||||
else None
|
||||
)
|
||||
# [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的预解析
|
||||
# 可能使用较早 Schema;优先复用 Intake 保存的 HTML 表,避免表格展平后丢失列关系。
|
||||
if document.document_type == 'email_body' and (
|
||||
not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or [])
|
||||
):
|
||||
# [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的部分解析
|
||||
# 可能使用较早 Schema,不能因已有部分行而遮蔽新增表头别名。
|
||||
if document.document_type == 'email_body':
|
||||
intake = next((item for item in intakes if int(item.id) == int(document.intake_id)), None)
|
||||
structured = intake.structured_result_json if intake and isinstance(intake.structured_result_json, dict) else {}
|
||||
email = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
@@ -422,13 +420,14 @@ def _build_snapshot(
|
||||
content_hash=str(document.content_hash or ''),
|
||||
schema_definition=dict(schema_version.definition_json or {}),
|
||||
)
|
||||
else:
|
||||
elif not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or []):
|
||||
email_supplement = parse_email_allocation_text(
|
||||
body_text=str(document.extracted_text or ''),
|
||||
content_hash=str(document.content_hash or ''),
|
||||
schema_definition=dict(schema_version.definition_json or {}),
|
||||
)
|
||||
email_supplement['document_id'] = int(document.id)
|
||||
if isinstance(email_supplement, dict):
|
||||
email_supplement['document_id'] = int(document.id)
|
||||
documents_by_intake[document.intake_id].append({
|
||||
'document_id': document.id,
|
||||
'document_type': document.document_type,
|
||||
@@ -682,6 +681,32 @@ def ensure_workflow_items_for_run(
|
||||
actor_id=run.user_id,
|
||||
reason='ensure_workflow_items_for_run',
|
||||
)
|
||||
# [STEP] 幂等创建 Process Execution;Gate 为业务真相,Workflow 仅聚合。
|
||||
try:
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
ensure_execution_for_workflow_item,
|
||||
sync_early_pipeline_gates,
|
||||
)
|
||||
|
||||
execution = ensure_execution_for_workflow_item(
|
||||
item,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
start_gate_code='document_materialization',
|
||||
)
|
||||
if execution is not None:
|
||||
sync_early_pipeline_gates(
|
||||
execution=execution,
|
||||
layouts_ready=not layouts_pending,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'ensure process execution failed run_no=%s item_id=%s',
|
||||
run.run_no,
|
||||
getattr(item, 'id', None),
|
||||
)
|
||||
items.append(item)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
@@ -1032,6 +1057,7 @@ def create_order_extraction_run(
|
||||
reparse_comment: str | None = None,
|
||||
selected_document_id: int | None = None,
|
||||
reparse_case_no: str | None = None,
|
||||
reparse_attempt_no: int = 0,
|
||||
) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。
|
||||
@@ -1046,6 +1072,7 @@ def create_order_extraction_run(
|
||||
reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。
|
||||
selected_document_id: 指定时只冻结该附件;仅供 PDF 级重识别使用,禁止扩大为同邮件全量附件。
|
||||
reparse_case_no: 可选来源复核 Case 编号;仅作为 PDF 级版本谱系的冻结审计标识。
|
||||
reparse_attempt_no: 同一 Case 失败后的重试序号;只参与幂等边界,不改变来源版本谱系。
|
||||
Returns:
|
||||
`(run, reused)`;Run 与通用 Job 在同一事务创建。
|
||||
"""
|
||||
@@ -1137,6 +1164,8 @@ def create_order_extraction_run(
|
||||
'document_id': int(selected_document_id),
|
||||
'source_case_no': str(reparse_case_no or '').strip().upper() or None,
|
||||
}
|
||||
if int(reparse_attempt_no or 0) > 0:
|
||||
snapshot['review_reparse']['attempt_no'] = int(reparse_attempt_no)
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
@@ -1150,6 +1179,7 @@ def create_order_extraction_run(
|
||||
'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None,
|
||||
'selected_document_id': selected_document_id,
|
||||
'reparse_case_no': str(reparse_case_no or '').strip().upper() or None,
|
||||
'reparse_attempt_no': int(reparse_attempt_no or 0),
|
||||
})
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
|
||||
@@ -4,12 +4,12 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、stp_inventory_freeze、
|
||||
customer_auto_resolution、fulfillment_audit、order_review_progress_bridge、
|
||||
workflow_ledger_service、progress_workflow.auto_progress。
|
||||
workflow_ledger_service、progress_workflow.auto_progress、process_gate_bridge。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与
|
||||
可自动确认的客户;物化人工 Candidate 与 accepted Extraction(保留派生 field_lineage);
|
||||
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
|
||||
building_order(不关闭);API commit 后触发 auto_progress(库存源已冻结时跳过
|
||||
inventory_source_review),止于 manual_upload_pending。
|
||||
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
|
||||
避免重复冻结资格阻断;API commit 后触发 auto_progress,止于 manual_upload_pending。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -896,6 +896,10 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
)
|
||||
# [STEP] 统一门禁:绑定 Task,推进至 task_creation,避免重复冻结资格阻断。
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_execution_after_review_confirm
|
||||
|
||||
sync_execution_after_review_confirm(case=case, task=task, actor_id=int(user_id))
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
workflow_refs = _workflow_refs_for_case(case)
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_access_service.py
|
||||
|
||||
用途:全门禁恢复 API 的可见性与写权限校验,并在 403 时写入 process_gate_permission_denied 审计。
|
||||
依赖:ShippingProcessExecution、ShippingTask、ShippingOrderReviewCase、
|
||||
ShippingNoticeWorkflowItem / ShippingNoticeWorkflow、User.agents、fulfillment_audit。
|
||||
逻辑:Workspace 路由调用 assert_execution_visible_to_user;读路径允许 owner / admin /
|
||||
同 Workflow.owner_agent 授权人员;写路径仅 owner / admin;Admin 路由由 @require_admin 保护;
|
||||
拒绝访问时记录审计后抛出 ForbiddenError(SHIPPING.PROCESS_GATE_PERMISSION_DENIED)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import (
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingProcessExecution,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
def is_shipping_admin(user: User) -> bool:
|
||||
"""货代管理员:当前仓库以 platform admin 角色表示 shipping admin 能力。"""
|
||||
return str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
|
||||
|
||||
def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set[int]:
|
||||
"""
|
||||
解析 Execution 关联的业务属主用户 ID 集合。
|
||||
|
||||
核心逻辑:Task 创建者、Review Case owner、WorkflowItem owner 任一匹配即视为 owner。
|
||||
"""
|
||||
owners: set[int] = set()
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingTask, 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:
|
||||
case = db.session.get(ShippingOrderReviewCase, int(execution.review_case_id))
|
||||
if case is not None and case.owner_user_id is not None:
|
||||
owners.add(int(case.owner_user_id))
|
||||
item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id))
|
||||
if item is not None and item.owner_user_id is not None:
|
||||
owners.add(int(item.owner_user_id))
|
||||
return owners
|
||||
|
||||
|
||||
def user_has_agent_authorization(user: User, execution: ShippingProcessExecution) -> bool:
|
||||
"""
|
||||
判断用户是否为 Workflow 所属 Agent 的授权人员(契约「其他授权人员」只读路径)。
|
||||
|
||||
核心逻辑:经 WorkflowItem → ShippingNoticeWorkflow.owner_agent_id,
|
||||
若该 Agent 落在 user.agents 中即视为授权;未绑定 Agent 时不开放此路径。
|
||||
|
||||
Args:
|
||||
user: 当前登录用户。
|
||||
execution: 目标 Execution。
|
||||
|
||||
Returns:
|
||||
True 表示可只读查看;不等于可恢复写权限。
|
||||
"""
|
||||
item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id))
|
||||
if item is None or item.workflow_id is None:
|
||||
return False
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
|
||||
if workflow is None or workflow.owner_agent_id is None:
|
||||
return False
|
||||
agent_id = int(workflow.owner_agent_id)
|
||||
agents = getattr(user, 'agents', None) or []
|
||||
for agent in agents:
|
||||
if agent is not None and int(getattr(agent, 'id', 0) or 0) == agent_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def user_may_read_execution(user: User, execution: ShippingProcessExecution) -> bool:
|
||||
"""
|
||||
当前用户是否可读 Execution。
|
||||
|
||||
核心逻辑:admin / owner / 同 Agent 授权人员。
|
||||
"""
|
||||
if is_shipping_admin(user):
|
||||
return True
|
||||
if int(user.id) in resolve_execution_owner_user_ids(execution):
|
||||
return True
|
||||
return user_has_agent_authorization(user, execution)
|
||||
|
||||
|
||||
def user_may_write_execution(user: User, execution: ShippingProcessExecution) -> bool:
|
||||
"""
|
||||
当前用户是否可对 Execution 发起恢复写操作。
|
||||
|
||||
核心逻辑:仅 admin 或业务 owner;授权人员默认只读。
|
||||
"""
|
||||
if is_shipping_admin(user):
|
||||
return True
|
||||
return int(user.id) in resolve_execution_owner_user_ids(execution)
|
||||
|
||||
|
||||
def user_may_access_execution(user: User, execution: ShippingProcessExecution) -> bool:
|
||||
"""
|
||||
兼容旧调用:等价于可读权限。
|
||||
|
||||
写路径请使用 user_may_write_execution 或 assert_execution_visible_to_user(write=True)。
|
||||
"""
|
||||
return user_may_read_execution(user, execution)
|
||||
|
||||
|
||||
def assert_execution_visible_to_user(
|
||||
user: User,
|
||||
execution: ShippingProcessExecution,
|
||||
*,
|
||||
write: bool = False,
|
||||
gate_code: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验 Workspace 用户对 Execution 的读/写权限。
|
||||
|
||||
Args:
|
||||
user: 当前登录用户。
|
||||
execution: 目标 Execution。
|
||||
write: True 表示 POST 恢复等写路径(仅 owner/admin);False 为读路径
|
||||
(owner/admin/同 Agent 授权人员)。
|
||||
gate_code: 可选,用于权限拒绝审计上下文。
|
||||
|
||||
Raises:
|
||||
ForbiddenError: 无权访问,并已写入 process_gate_permission_denied 审计。
|
||||
"""
|
||||
allowed = user_may_write_execution(user, execution) if write else user_may_read_execution(user, execution)
|
||||
if allowed:
|
||||
return
|
||||
_record_permission_denied(
|
||||
user=user,
|
||||
execution=execution,
|
||||
gate_code=gate_code,
|
||||
write=write,
|
||||
)
|
||||
raise ForbiddenError(
|
||||
'Process gate access denied',
|
||||
code='SHIPPING.PROCESS_GATE_PERMISSION_DENIED',
|
||||
)
|
||||
|
||||
|
||||
def _record_permission_denied(
|
||||
*,
|
||||
user: User,
|
||||
execution: ShippingProcessExecution,
|
||||
gate_code: str | None,
|
||||
write: bool,
|
||||
) -> None:
|
||||
"""
|
||||
写入 process_gate_permission_denied 审计并提交。
|
||||
|
||||
核心逻辑:权限拒绝必须落库;审计失败向上抛出(禁止静默忽略后仍返回普通 403)。
|
||||
"""
|
||||
item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id))
|
||||
task_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingTask, 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',
|
||||
aggregate_type='process_execution',
|
||||
aggregate_id=str(execution.execution_no),
|
||||
action='write' if write else 'read',
|
||||
actor_type='user',
|
||||
actor_id=int(user.id),
|
||||
workflow_item_id=str(item.item_no) if item is not None else None,
|
||||
task_no=task_no,
|
||||
result='rejected',
|
||||
error_code='SHIPPING.PROCESS_GATE_PERMISSION_DENIED',
|
||||
metadata={
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': str(gate_code or ''),
|
||||
'write': bool(write),
|
||||
},
|
||||
source='process_gate',
|
||||
strict=True,
|
||||
)
|
||||
# [STEP] 403 路径不会走到业务成功提交,此处单独提交以保证拒绝审计落库。
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def execution_audit_scope_keys(execution: ShippingProcessExecution) -> dict[str, str | None]:
|
||||
"""
|
||||
构造 Execution 相关审计查询键。
|
||||
|
||||
Returns:
|
||||
workflow_item_id(item_no)、task_no、execution_no 前缀等。
|
||||
"""
|
||||
item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id))
|
||||
task_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingTask, int(execution.task_id))
|
||||
task_no = str(task.task_no) if task is not None else None
|
||||
return {
|
||||
'workflow_item_id': str(item.item_no) if item is not None else None,
|
||||
'task_no': task_no,
|
||||
'execution_no': str(execution.execution_no),
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_api_service.py
|
||||
|
||||
用途:Phase 5 统一恢复 API 的查询与序列化(Workspace / Admin 共用)。
|
||||
依赖:ShippingProcessExecution/Gate/Attempt、process_gate_projection、process_gate_access_service、
|
||||
audit_query_service、progress_audit_contract。
|
||||
逻辑:Workspace 路由委托用户安全投影;Admin 路由返回诊断投影与 Attempt 列表;
|
||||
审计事件按 Execution 关联键过滤 PROCESS_GATE_AUDIT_EVENT_TYPES。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTask,
|
||||
)
|
||||
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
|
||||
from app.services.shipping_notice.process_gate_projection import (
|
||||
project_admin_gate_diagnostics,
|
||||
project_workbench_gate_summary,
|
||||
serialize_gate_attempt,
|
||||
serialize_process_execution,
|
||||
serialize_process_gate,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import PROCESS_GATE_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
def _parse_iso_datetime(value: str | None, *, field: str) -> datetime | None:
|
||||
"""解析可选 ISO8601 时间;非法值抛 ValidationError。"""
|
||||
raw = str(value or '').strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(raw.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f'{field} must be ISO8601 datetime') from exc
|
||||
|
||||
|
||||
def _snapshot_key_diff(before: Any, after: Any) -> dict[str, Any]:
|
||||
"""
|
||||
计算两个快照字典的浅层键差,供管理员 Attempt Diff 使用。
|
||||
|
||||
Returns:
|
||||
added / removed / changed 键列表;非 dict 输入返回 empty。
|
||||
"""
|
||||
left = before if isinstance(before, dict) else {}
|
||||
right = after if isinstance(after, dict) else {}
|
||||
left_keys = set(left.keys())
|
||||
right_keys = set(right.keys())
|
||||
changed = sorted(
|
||||
key for key in (left_keys & right_keys)
|
||||
if left.get(key) != right.get(key)
|
||||
)
|
||||
return {
|
||||
'added': sorted(right_keys - left_keys),
|
||||
'removed': sorted(left_keys - right_keys),
|
||||
'changed': changed,
|
||||
}
|
||||
|
||||
|
||||
def serialize_execution_admin_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""管理员列表行:不含 Gate 正文快照;附当前 Gate 阻断原因便于筛选回显。"""
|
||||
current_gate = None
|
||||
if execution.current_gate_code:
|
||||
current_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=str(execution.current_gate_code),
|
||||
).first()
|
||||
task_no = None
|
||||
if execution.task_id is not None:
|
||||
task = db.session.get(ShippingTask, int(execution.task_id))
|
||||
task_no = str(task.task_no) if task is not None else None
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'status': execution.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
'primary_next_action_code': execution.primary_next_action_code,
|
||||
'responsible_party': execution.responsible_party,
|
||||
'blocking_reason_code': current_gate.blocking_reason_code if current_gate else None,
|
||||
'task_no': task_no,
|
||||
'workflow_item_id': int(execution.workflow_item_id),
|
||||
'workflow_item_version_id': int(execution.workflow_item_version_id),
|
||||
'review_case_id': int(execution.review_case_id) if execution.review_case_id else None,
|
||||
'task_id': int(execution.task_id) if execution.task_id else None,
|
||||
'lock_version': int(execution.lock_version),
|
||||
'updated_at': execution.updated_at.isoformat() if execution.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_admin_process_executions(
|
||||
*,
|
||||
page: int = 1,
|
||||
page_size: int = 25,
|
||||
status: str | None = None,
|
||||
gate_code: str | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
responsible_party: str | None = None,
|
||||
q: str | None = None,
|
||||
updated_from: str | None = None,
|
||||
updated_to: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出 Process Execution 管理员摘要(支持运维筛选)。
|
||||
|
||||
Args:
|
||||
page / page_size: 分页。
|
||||
status: Execution 状态。
|
||||
gate_code: 当前 Gate 编码。
|
||||
blocking_reason_code: 当前 Gate 阻断原因码。
|
||||
responsible_party: 责任方。
|
||||
q: 模糊搜索 execution_no / task_no。
|
||||
updated_from / updated_to: 更新时间闭区间(ISO8601)。
|
||||
|
||||
Returns:
|
||||
items / total / page / page_size。
|
||||
"""
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 25)))
|
||||
query = ShippingProcessExecution.query
|
||||
if status:
|
||||
query = query.filter(ShippingProcessExecution.status == str(status).strip())
|
||||
if gate_code:
|
||||
query = query.filter(ShippingProcessExecution.current_gate_code == str(gate_code).strip())
|
||||
if responsible_party:
|
||||
query = query.filter(
|
||||
ShippingProcessExecution.responsible_party == str(responsible_party).strip(),
|
||||
)
|
||||
if blocking_reason_code:
|
||||
reason = str(blocking_reason_code).strip()
|
||||
query = (
|
||||
query.join(
|
||||
ShippingProcessGate,
|
||||
db.and_(
|
||||
ShippingProcessGate.execution_id == ShippingProcessExecution.id,
|
||||
ShippingProcessGate.gate_code == ShippingProcessExecution.current_gate_code,
|
||||
),
|
||||
)
|
||||
.filter(ShippingProcessGate.blocking_reason_code == reason)
|
||||
)
|
||||
start_at = _parse_iso_datetime(updated_from, field='updated_from')
|
||||
end_at = _parse_iso_datetime(updated_to, field='updated_to')
|
||||
if start_at is not None:
|
||||
query = query.filter(ShippingProcessExecution.updated_at >= start_at)
|
||||
if end_at is not None:
|
||||
query = query.filter(ShippingProcessExecution.updated_at <= end_at)
|
||||
keyword = str(q or '').strip()
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
task_ids = [
|
||||
int(row.id)
|
||||
for row in ShippingTask.query.filter(ShippingTask.task_no.ilike(like)).limit(200).all()
|
||||
]
|
||||
filters = [ShippingProcessExecution.execution_no.ilike(like)]
|
||||
if task_ids:
|
||||
filters.append(ShippingProcessExecution.task_id.in_(task_ids))
|
||||
query = query.filter(or_(*filters))
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingProcessExecution.updated_at.desc(), ShippingProcessExecution.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_execution_admin_summary(row) for row in rows],
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
}
|
||||
|
||||
|
||||
def get_workspace_process_execution(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""Workspace GET execution:工作台安全投影。"""
|
||||
return project_workbench_gate_summary(execution)
|
||||
|
||||
|
||||
def list_workspace_process_gates(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""Workspace GET gates:用户安全 Gate 列表。"""
|
||||
payload = serialize_process_execution(execution, include_diagnostics=False)
|
||||
return {
|
||||
'execution_no': payload.get('execution_no'),
|
||||
'gates': payload.get('gates') or [],
|
||||
}
|
||||
|
||||
|
||||
def list_workspace_process_gate_audit_events(
|
||||
execution: ShippingProcessExecution,
|
||||
*,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按 Execution 关联键分页返回 PROCESS_GATE 审计事件(用户可见字段,不含敏感快照正文)。
|
||||
|
||||
Args:
|
||||
execution: 已校验可见性的 Execution。
|
||||
page / page_size: 分页参数。
|
||||
|
||||
Returns:
|
||||
items / total / page / page_size。
|
||||
"""
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 50)))
|
||||
scope = execution_audit_scope_keys(execution)
|
||||
prefix = f"{scope['execution_no']}:"
|
||||
filters = [ShippingAuditEvent.event_type.in_(tuple(PROCESS_GATE_AUDIT_EVENT_TYPES))]
|
||||
association_filters = [ShippingAuditEvent.aggregate_id.like(f'{prefix}%')]
|
||||
if scope.get('workflow_item_id'):
|
||||
association_filters.append(
|
||||
ShippingAuditEvent.workflow_item_id == scope['workflow_item_id'],
|
||||
)
|
||||
if scope.get('task_no'):
|
||||
association_filters.append(ShippingAuditEvent.task_no == scope['task_no'])
|
||||
query = ShippingAuditEvent.query.filter(*filters).filter(or_(*association_filters))
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows],
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
}
|
||||
|
||||
|
||||
def get_admin_process_execution(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""Admin GET execution:完整诊断投影。"""
|
||||
return project_admin_gate_diagnostics(execution)
|
||||
|
||||
|
||||
def _gate_for_execution(execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate:
|
||||
"""按 execution + gate_code 定位 Gate;不存在抛 NotFound。"""
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=str(gate_code or '').strip(),
|
||||
).first()
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
return gate
|
||||
|
||||
|
||||
def list_admin_gate_attempts(
|
||||
execution: ShippingProcessExecution,
|
||||
gate_code: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Admin GET gate attempts:按 attempt_no 降序返回 Attempt 摘要与相对上一 Attempt 的浅 Diff。"""
|
||||
gate = _gate_for_execution(execution, gate_code)
|
||||
attempts = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(gate_id=int(gate.id))
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.all()
|
||||
)
|
||||
# 同时返回 items(契约)与 attempts(前端兼容别名),避免管理端空列表。
|
||||
serialized: list[dict[str, Any]] = []
|
||||
ascending = list(reversed(attempts))
|
||||
previous: ShippingProcessGateAttempt | None = None
|
||||
by_id_diff: dict[int, dict[str, Any]] = {}
|
||||
for item in ascending:
|
||||
if previous is not None:
|
||||
by_id_diff[int(item.id)] = {
|
||||
'previous_attempt_no': int(previous.attempt_no),
|
||||
'input': _snapshot_key_diff(previous.input_snapshot_json, item.input_snapshot_json),
|
||||
'output': _snapshot_key_diff(previous.output_snapshot_json, item.output_snapshot_json),
|
||||
'input_hash_changed': previous.input_snapshot_hash != item.input_snapshot_hash,
|
||||
'output_hash_changed': previous.output_snapshot_hash != item.output_snapshot_hash,
|
||||
}
|
||||
previous = item
|
||||
for item in attempts:
|
||||
row = serialize_gate_attempt(item, include_snapshots=True) or {}
|
||||
row['snapshot_diff'] = by_id_diff.get(int(item.id))
|
||||
row['audit_query'] = {
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': gate.gate_code,
|
||||
'attempt_id': int(item.id),
|
||||
'event_type_prefix': 'process_gate_',
|
||||
}
|
||||
serialized.append(row)
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': gate.gate_code,
|
||||
'gate': serialize_process_gate(gate, include_diagnostics=True),
|
||||
'items': serialized,
|
||||
'attempts': serialized,
|
||||
}
|
||||
|
||||
|
||||
def get_admin_gate_attempt(attempt_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
Admin GET attempt by id:含 Gate / Execution 上下文与 Attempt 摘要。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Attempt 不存在。
|
||||
"""
|
||||
attempt = db.session.get(ShippingProcessGateAttempt, int(attempt_id))
|
||||
if attempt is None:
|
||||
raise NotFoundError(
|
||||
'Process gate attempt not found',
|
||||
code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND',
|
||||
)
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
payload = serialize_gate_attempt(attempt) or {}
|
||||
payload['gate_code'] = gate.gate_code if gate else None
|
||||
payload['execution_no'] = execution.execution_no if execution else None
|
||||
if gate is not None:
|
||||
payload['gate_status'] = gate.status
|
||||
payload['gate_evaluation_version'] = int(gate.evaluation_version)
|
||||
return payload
|
||||
@@ -0,0 +1,648 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_bridge.py
|
||||
|
||||
用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、
|
||||
将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。
|
||||
依赖:process_gate_service、process_gate_contract、ShippingProcessExecution、
|
||||
ShippingNoticeWorkflowItem、ShippingOrderReviewCase、ShippingTask。
|
||||
逻辑:由 order_extraction_run_service / order_review_confirmation_service /
|
||||
order_review_draft_service / progress_workflow / process_gate_executor 调用;
|
||||
禁止业务代码直接改 Gate.status。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
bind_execution_task,
|
||||
ensure_execution_for_workflow_version,
|
||||
sync_gate_from_business_result,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _stable_fingerprint(value: Any) -> str:
|
||||
"""对业务输入快照生成稳定指纹。"""
|
||||
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def ensure_execution_for_workflow_item(
|
||||
item: ShippingNoticeWorkflowItem,
|
||||
*,
|
||||
review_case_id: int | None = None,
|
||||
task_id: int | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
start_gate_code: str = 'document_materialization',
|
||||
) -> ShippingProcessExecution | None:
|
||||
"""
|
||||
为 WorkflowItem 当前 Version 幂等创建 Process Execution。
|
||||
|
||||
核心逻辑:无 current_version_id 时跳过;已存在则绑定 case/task 指针。
|
||||
|
||||
Args:
|
||||
item: WorkflowItem。
|
||||
review_case_id / task_id: 可选业务指针。
|
||||
actor_type / actor_id: 创建审计主体。
|
||||
start_gate_code: 首个待执行门禁。
|
||||
|
||||
Returns:
|
||||
Execution;无法创建时 None。
|
||||
"""
|
||||
version_id = getattr(item, 'current_version_id', None)
|
||||
if version_id is None:
|
||||
return None
|
||||
case_id = review_case_id
|
||||
if case_id is None and getattr(item, 'current_case_id', None):
|
||||
case_id = int(item.current_case_id)
|
||||
return ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version_id),
|
||||
review_case_id=int(case_id) if case_id else None,
|
||||
task_id=int(task_id) if task_id else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
start_gate_code=start_gate_code,
|
||||
)
|
||||
|
||||
|
||||
def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExecution | None:
|
||||
"""
|
||||
按 ReviewCase 查找绑定的 Execution(优先 review_case_id,其次 WorkflowItem Version)。
|
||||
|
||||
Returns:
|
||||
最新匹配的 Execution 或 None。
|
||||
"""
|
||||
by_case = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if by_case is not None:
|
||||
return by_case
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
if item is None or not item.current_version_id:
|
||||
return None
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(workflow_item_version_id=int(item.current_version_id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def find_execution_for_task(task: ShippingTask) -> ShippingProcessExecution | None:
|
||||
"""按 Task 查找绑定的 Execution。"""
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def apply_gate_outcome(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
gate_code: str,
|
||||
passed: bool,
|
||||
effective_result: dict[str, Any] | None = None,
|
||||
recommendation: dict[str, Any] | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
blocking_reason_json: dict[str, Any] | None = None,
|
||||
input_fingerprint: str | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
invalidate_change_type: str | None = None,
|
||||
force: bool = False,
|
||||
outcome: str | None = None,
|
||||
) -> ShippingProcessGate | None:
|
||||
"""
|
||||
将业务评估结果写入指定 Gate;已通过且输入指纹未变时跳过。
|
||||
|
||||
核心逻辑:指纹写入 effective_result_json.input_fingerprint;
|
||||
passed 且指纹相同则不重跑;可选在通过后失效下游。
|
||||
|
||||
Args:
|
||||
execution: 目标 Execution。
|
||||
gate_code: 契约内门禁码。
|
||||
passed: 是否通过。
|
||||
effective_result / recommendation / blocking_*: 结果载荷。
|
||||
input_fingerprint: 可选输入指纹;缺省时对 effective_result 计算。
|
||||
actor_type / actor_id: 操作主体。
|
||||
idempotency_key: 幂等键。
|
||||
invalidate_change_type: 通过后失效类型(覆盖默认)。
|
||||
force: True 时忽略指纹跳过。
|
||||
outcome: 可选显式结果(waiting_external 等);缺省由 passed 推导。
|
||||
|
||||
Returns:
|
||||
更新后的 Gate;未知 gate_code 返回 None。
|
||||
"""
|
||||
code = str(gate_code or '').strip()
|
||||
if code not in PROCESS_GATE_CODES:
|
||||
_LOGGER.warning('apply_gate_outcome ignored unknown gate_code=%s', code)
|
||||
return None
|
||||
|
||||
result_payload = dict(effective_result or {})
|
||||
fingerprint = str(input_fingerprint or '').strip() or _stable_fingerprint(result_payload)
|
||||
result_payload['input_fingerprint'] = fingerprint
|
||||
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code=code)
|
||||
.first()
|
||||
)
|
||||
if (
|
||||
not force
|
||||
and gate is not None
|
||||
and gate.status == 'passed'
|
||||
and isinstance(gate.effective_result_json, dict)
|
||||
and str(gate.effective_result_json.get('input_fingerprint') or '') == fingerprint
|
||||
):
|
||||
return gate
|
||||
|
||||
key = str(idempotency_key or '').strip() or f'bridge:{execution.execution_no}:{code}:{fingerprint[:16]}'
|
||||
return sync_gate_from_business_result(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=code,
|
||||
passed=passed,
|
||||
effective_result_json=result_payload,
|
||||
recommendation_json=recommendation,
|
||||
blocking_reason_code=blocking_reason_code,
|
||||
blocking_reason_json=blocking_reason_json,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=key,
|
||||
invalidate_change_type=invalidate_change_type,
|
||||
allow_repass=True,
|
||||
outcome=outcome,
|
||||
)
|
||||
|
||||
|
||||
def mark_gates_passed_through(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
through_gate_code: str,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
reason: str = 'upstream_satisfied',
|
||||
) -> list[str]:
|
||||
"""
|
||||
将 sequence 不大于 through_gate_code 且仍为 pending/skipped 的门禁标记为 passed。
|
||||
|
||||
核心逻辑:用于人工确认建单后一次性推进到 task_creation;已阻断门禁不静默覆盖。
|
||||
|
||||
Returns:
|
||||
实际推进的 gate_code 列表。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_contract import get_process_gate_definition
|
||||
|
||||
target_seq = int(get_process_gate_definition(through_gate_code)['sequence_no'])
|
||||
advanced: list[str] = []
|
||||
gates = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc())
|
||||
.all()
|
||||
)
|
||||
for gate in gates:
|
||||
if int(gate.sequence_no) > target_seq:
|
||||
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':
|
||||
continue
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code=gate.gate_code,
|
||||
passed=True,
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'manual_confirmation': True,
|
||||
'reason': reason,
|
||||
},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'manual-pass:{execution.execution_no}:{gate.gate_code}:{gate.evaluation_version}',
|
||||
force=True,
|
||||
)
|
||||
advanced.append(gate.gate_code)
|
||||
return advanced
|
||||
|
||||
|
||||
def sync_execution_after_review_confirm(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
task: ShippingTask,
|
||||
actor_id: int,
|
||||
) -> ShippingProcessExecution | None:
|
||||
"""
|
||||
人工确认建单后:绑定 Task、推进至 task_creation 通过,避免重复冻结阻断。
|
||||
|
||||
核心逻辑:确保 Execution 存在;bind_execution_task;将前置门禁与
|
||||
order_freeze_readiness / task_creation 标为 passed(人工确认语义)。
|
||||
|
||||
Returns:
|
||||
更新后的 Execution;无法定位时 None。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
execution = find_execution_for_case(case)
|
||||
if execution is None and item is not None:
|
||||
execution = ensure_execution_for_workflow_item(
|
||||
item,
|
||||
review_case_id=int(case.id),
|
||||
task_id=int(task.id),
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
start_gate_code='document_materialization',
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
|
||||
if execution.review_case_id is None:
|
||||
execution.review_case_id = int(case.id)
|
||||
bind_execution_task(
|
||||
execution_no=str(execution.execution_no),
|
||||
task_id=int(task.id),
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
)
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='task_creation',
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
reason='review_confirmed',
|
||||
)
|
||||
# [STEP] 建单后立即按 Task 状态投影履约门禁,避免 13–19 长期停留 pending。
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
)
|
||||
return execution
|
||||
|
||||
|
||||
def sync_inventory_routing_gate_for_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
passed: bool,
|
||||
actor_id: int,
|
||||
details: dict[str, Any] | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
) -> ShippingProcessGate | None:
|
||||
"""
|
||||
将库存源路由业务结果同步到 inventory_source_routing Gate。
|
||||
|
||||
Returns:
|
||||
更新后的 Gate;无 Execution 时尝试创建后同步。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case
|
||||
|
||||
execution = find_execution_for_case(case)
|
||||
if execution is None:
|
||||
item = find_item_by_current_case(case_id=int(case.id))
|
||||
if item is None:
|
||||
return None
|
||||
execution = ensure_execution_for_workflow_item(
|
||||
item,
|
||||
review_case_id=int(case.id),
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
if execution.review_case_id is None:
|
||||
execution.review_case_id = int(case.id)
|
||||
|
||||
return apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_source_routing',
|
||||
passed=passed,
|
||||
effective_result={
|
||||
'findings': [] if passed else [{
|
||||
'finding_code': 'inventory_source_routing_blocked',
|
||||
'owning_gate_code': 'inventory_source_routing',
|
||||
'severity': 'blocking',
|
||||
'reason_code': blocking_reason_code or 'no_inventory_source_candidates',
|
||||
'user_visible': True,
|
||||
'blocks_current_action': True,
|
||||
}],
|
||||
'details': details or {},
|
||||
},
|
||||
blocking_reason_code=None if passed else (blocking_reason_code or 'no_inventory_source_candidates'),
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'inv-route:{case.case_no}:{case.current_draft.draft_version if case.current_draft else 0}',
|
||||
invalidate_change_type='inventory_source_changed' if passed else None,
|
||||
force=True,
|
||||
)
|
||||
|
||||
|
||||
def sync_early_pipeline_gates(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
layouts_ready: bool,
|
||||
profile_routed: bool = True,
|
||||
extraction_ok: bool = True,
|
||||
blocked_fields: list[str] | None = None,
|
||||
findings: list[dict[str, Any]] | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
同步抽取流水线早期门禁(文档/版面/路由/抽取/完整性)。
|
||||
|
||||
核心逻辑:按布尔与 blocked_fields 写入 passed/blocked;诊断 Finding 写入
|
||||
effective_result 但不单独阻断非关键字段。
|
||||
"""
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='document_materialization',
|
||||
passed=True,
|
||||
effective_result={'findings': [], 'stage': 'materialized'},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'early:doc:{execution.execution_no}',
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='layout_parsing',
|
||||
passed=layouts_ready,
|
||||
effective_result={'findings': [], 'layouts_ready': layouts_ready},
|
||||
blocking_reason_code=None if layouts_ready else 'layout_parse_failed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'early:layout:{execution.execution_no}:{layouts_ready}',
|
||||
force=True,
|
||||
)
|
||||
if not layouts_ready:
|
||||
return
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='document_profile_routing',
|
||||
passed=profile_routed,
|
||||
effective_result={'findings': [], 'routed': profile_routed},
|
||||
blocking_reason_code=None if profile_routed else 'profile_not_matched',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'early:profile:{execution.execution_no}:{profile_routed}',
|
||||
force=True,
|
||||
)
|
||||
if not profile_routed:
|
||||
return
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='order_field_extraction',
|
||||
passed=extraction_ok,
|
||||
effective_result={'findings': list(findings or []), 'extraction_ok': extraction_ok},
|
||||
blocking_reason_code=None if extraction_ok else 'extraction_incomplete',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'early:extract:{execution.execution_no}:{extraction_ok}',
|
||||
force=True,
|
||||
)
|
||||
blocked = [str(x).strip() for x in (blocked_fields or []) if str(x).strip()]
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='field_completeness',
|
||||
passed=not blocked,
|
||||
effective_result={
|
||||
'findings': [
|
||||
item for item in (findings or [])
|
||||
if isinstance(item, dict) and str(item.get('owning_gate_code') or '') == 'field_completeness'
|
||||
],
|
||||
'blocked_fields': blocked,
|
||||
},
|
||||
blocking_reason_code=None if not blocked else 'required_field_missing',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'early:complete:{execution.execution_no}:{",".join(sorted(blocked)) or "ok"}',
|
||||
force=True,
|
||||
)
|
||||
|
||||
|
||||
def sync_fulfillment_gates_from_task(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
按 ShippingTask 履约状态同步 inventory_preparation→manual_upload_handoff 门禁。
|
||||
|
||||
核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果;
|
||||
仅阻断当前业务真实卡住的第一道履约门禁,已满足的上游门禁标为 passed。
|
||||
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
|
||||
|
||||
Args:
|
||||
execution: 已绑定 task_id 的 Execution。
|
||||
actor_type / actor_id: 操作主体。
|
||||
"""
|
||||
if not execution.task_id:
|
||||
return
|
||||
task = ShippingTask.query.get(int(execution.task_id))
|
||||
if task is None:
|
||||
return
|
||||
|
||||
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
|
||||
|
||||
status = str(task.process_status or '').strip()
|
||||
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)
|
||||
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
|
||||
# [STEP 1] 优先读匹配/短缺实体;process_status 仅作库存准备与上传阶段辅助。
|
||||
done_statuses = {'uploaded', 'closed'}
|
||||
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,
|
||||
}
|
||||
# 仅当存在活跃库存文件且未确认映射时阻断;无文件但已有解析行视为映射已由 Profile 固化。
|
||||
mapping_needed = (
|
||||
inv_file is not None
|
||||
and not mapping_confirmed
|
||||
and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses}
|
||||
)
|
||||
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='task_creation',
|
||||
passed=True,
|
||||
effective_result={'findings': [], 'task_no': task.task_no},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:task:{execution.execution_no}:{task.id}',
|
||||
force=True,
|
||||
)
|
||||
|
||||
# [STEP 2] inventory_preparation
|
||||
if status == 'waiting_inventory':
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_preparation',
|
||||
passed=False,
|
||||
outcome='waiting_external',
|
||||
effective_result={'findings': [], 'process_status': status},
|
||||
blocking_reason_code='inventory_preparation_waiting',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}',
|
||||
force=True,
|
||||
)
|
||||
return
|
||||
inv_prep_passed = status in post_inventory or has_inventory_lines
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_preparation',
|
||||
passed=inv_prep_passed,
|
||||
outcome=None if inv_prep_passed else 'blocked_retryable',
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'process_status': status,
|
||||
'has_inventory_lines': has_inventory_lines,
|
||||
},
|
||||
blocking_reason_code=None if inv_prep_passed else 'inventory_preparation_failed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}:{inv_prep_passed}',
|
||||
force=True,
|
||||
)
|
||||
if not inv_prep_passed:
|
||||
return
|
||||
|
||||
# [STEP 3] inventory_field_mapping — 以 mapping_confirmed 为准
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_field_mapping',
|
||||
passed=not mapping_needed,
|
||||
outcome='blocked_manual' if mapping_needed else None,
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'mapping_confirmed': mapping_confirmed,
|
||||
'inventory_file_id': int(inv_file.id) if inv_file else None,
|
||||
},
|
||||
blocking_reason_code='inventory_mapping_required' if mapping_needed else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:map:{execution.execution_no}:{mapping_confirmed}:{mapping_needed}',
|
||||
force=True,
|
||||
)
|
||||
if mapping_needed:
|
||||
return
|
||||
|
||||
# [STEP 4] inventory_matching — 以 match_status 为准
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_matching',
|
||||
passed=match_passed,
|
||||
outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None,
|
||||
effective_result={'findings': [], 'match_status': match_status or None},
|
||||
blocking_reason_code=None if match_passed else 'inventory_match_failed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:match:{execution.execution_no}:{match_status or status}',
|
||||
force=True,
|
||||
)
|
||||
if not match_passed:
|
||||
return
|
||||
|
||||
# [STEP 5] inventory_sufficiency — 以 match_completed / shortage_json 为准
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_sufficiency',
|
||||
passed=sufficiency_ok,
|
||||
outcome='blocked_manual' if shortage else None,
|
||||
effective_result={
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None,
|
||||
},
|
||||
blocking_reason_code=None if sufficiency_ok else 'inventory_insufficient',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}',
|
||||
force=True,
|
||||
)
|
||||
if not sufficiency_ok:
|
||||
return
|
||||
|
||||
# [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离
|
||||
excel_error = excel_gate_error(task)
|
||||
excel_ready = excel_error is None
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='excel_readiness',
|
||||
passed=excel_ready,
|
||||
effective_result={'findings': [], 'excel_gate_error': excel_error},
|
||||
blocking_reason_code=None if excel_ready else 'excel_not_ready',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:excelready:{execution.execution_no}:{excel_ready}',
|
||||
force=True,
|
||||
)
|
||||
if not excel_ready:
|
||||
return
|
||||
|
||||
artifact_ok = has_export or status in done_statuses
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='artifact_generation',
|
||||
passed=artifact_ok,
|
||||
effective_result={'findings': [], 'has_export': has_export},
|
||||
blocking_reason_code=None if artifact_ok else 'artifact_generation_failed',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:artifact:{execution.execution_no}:{has_export}:{status}',
|
||||
force=True,
|
||||
)
|
||||
if not artifact_ok:
|
||||
return
|
||||
|
||||
# [STEP 7] manual_upload_handoff
|
||||
uploaded = status in done_statuses
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='manual_upload_handoff',
|
||||
passed=uploaded,
|
||||
outcome=None if uploaded else (
|
||||
'waiting_external' if status == 'waiting_upload' else 'blocked_manual'
|
||||
),
|
||||
effective_result={'findings': [], 'process_status': status},
|
||||
blocking_reason_code=None if uploaded else 'manual_upload_pending',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}',
|
||||
force=True,
|
||||
)
|
||||
@@ -0,0 +1,596 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_contract.py
|
||||
|
||||
用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、
|
||||
阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格;
|
||||
作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。
|
||||
依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用。
|
||||
逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码;
|
||||
同一根因只允许一个 owning_gate 产生用户阻断 Finding。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Final
|
||||
|
||||
|
||||
# 契约版本;投影、OpenAPI 与 i18n 必须与此对齐。
|
||||
PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v1'
|
||||
|
||||
# Finding 严重级别:仅 blocking 可改变 Gate 状态;diagnostic 供管理员诊断。
|
||||
PROCESS_GATE_FINDING_SEVERITIES: Final[frozenset[str]] = frozenset({
|
||||
'blocking',
|
||||
'diagnostic',
|
||||
})
|
||||
|
||||
PROCESS_GATE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'pending',
|
||||
'queued',
|
||||
'running',
|
||||
'passed',
|
||||
'blocked_retryable',
|
||||
'blocked_manual',
|
||||
'waiting_external',
|
||||
'failed_terminal',
|
||||
'invalidated',
|
||||
'skipped',
|
||||
})
|
||||
|
||||
PROCESS_GATE_TERMINAL_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'passed',
|
||||
'failed_terminal',
|
||||
'skipped',
|
||||
})
|
||||
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'blocked_retryable',
|
||||
'blocked_manual',
|
||||
'waiting_external',
|
||||
'invalidated',
|
||||
'failed_terminal',
|
||||
})
|
||||
|
||||
PROCESS_GATE_RESPONSIBLE_PARTIES: Final[frozenset[str]] = frozenset({
|
||||
'system',
|
||||
'worker',
|
||||
'owner',
|
||||
'admin',
|
||||
'external',
|
||||
})
|
||||
|
||||
PROCESS_GATE_TRIGGER_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'auto',
|
||||
'user_retry',
|
||||
'user_manual',
|
||||
'worker_takeover',
|
||||
'upstream_invalidation',
|
||||
'system_requeue',
|
||||
})
|
||||
|
||||
PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
{
|
||||
'gate_code': 'document_materialization',
|
||||
'sequence_no': 1,
|
||||
'label': '文档和附件可用性',
|
||||
'responsible_party': 'system',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'rematerialize_document',
|
||||
'failed_terminal': None,
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'layout_parsing',
|
||||
'sequence_no': 2,
|
||||
'label': 'PDF 版面解析',
|
||||
'responsible_party': 'worker',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_layout_parsing',
|
||||
'failed_terminal': None,
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'document_profile_routing',
|
||||
'sequence_no': 3,
|
||||
'label': 'Profile/模板路由',
|
||||
'responsible_party': 'system',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'reroute_document_profile',
|
||||
'blocked_manual': 'open_profile_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'order_field_extraction',
|
||||
'sequence_no': 4,
|
||||
'label': '订单字段抽取',
|
||||
'responsible_party': 'worker',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_order_extraction',
|
||||
'blocked_manual': 'open_order_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'field_completeness',
|
||||
'sequence_no': 5,
|
||||
'label': '必填字段完整性',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'edit_order_fields',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'reservation_validation',
|
||||
'sequence_no': 6,
|
||||
'label': 'Reservation 格式和证据',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'revalidate_reservation',
|
||||
'blocked_manual': 'edit_reservation',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'customer_resolution',
|
||||
'sequence_no': 7,
|
||||
'label': '客户身份识别',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_customer_resolution',
|
||||
'blocked_manual': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'duplicate_detection',
|
||||
'sequence_no': 8,
|
||||
'label': '重复订单/修订判断',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_duplicate_detection',
|
||||
'blocked_manual': 'adjudicate_duplicate',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'field_conflict_resolution',
|
||||
'sequence_no': 9,
|
||||
'label': '字段冲突',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'resolve_field_conflicts',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'sequence_no': 10,
|
||||
'label': '库存源路由',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_with_latest_rules',
|
||||
'blocked_manual': 'open_inventory_source_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'sequence_no': 11,
|
||||
'label': '订单冻结资格',
|
||||
'responsible_party': 'system',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_freeze_readiness',
|
||||
'blocked_manual': 'open_order_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'task_creation',
|
||||
'sequence_no': 12,
|
||||
'label': 'ShippingTask 创建',
|
||||
'responsible_party': 'system',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_task_creation',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_preparation',
|
||||
'sequence_no': 13,
|
||||
'label': '库存文件或快照准备',
|
||||
'responsible_party': 'worker',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_preparation',
|
||||
'waiting_external': 'poll_inventory_preparation',
|
||||
'blocked_manual': 'upload_inventory_file',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_field_mapping',
|
||||
'sequence_no': 14,
|
||||
'label': '库存字段映射',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_field_mapping',
|
||||
'blocked_manual': 'confirm_inventory_field_mapping',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_matching',
|
||||
'sequence_no': 15,
|
||||
'label': 'Reservation + 料号匹配',
|
||||
'responsible_party': 'worker',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'retry_inventory_matching',
|
||||
'blocked_manual': 'open_inventory_match_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'sequence_no': 16,
|
||||
'label': '库存满足性',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_inventory_sufficiency',
|
||||
'blocked_manual': 'open_shortage_review',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'excel_readiness',
|
||||
'sequence_no': 17,
|
||||
'label': 'Excel 生成资格',
|
||||
'responsible_party': 'system',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'recheck_excel_readiness',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'artifact_generation',
|
||||
'sequence_no': 18,
|
||||
'label': 'Excel Artifact',
|
||||
'responsible_party': 'worker',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_retryable': 'regenerate_excel_artifact',
|
||||
},
|
||||
},
|
||||
{
|
||||
'gate_code': 'manual_upload_handoff',
|
||||
'sequence_no': 19,
|
||||
'label': '人工上传交接',
|
||||
'responsible_party': 'owner',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'regenerate_manual_upload_todo',
|
||||
'waiting_external': None,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
PROCESS_GATE_CODES: Final[tuple[str, ...]] = tuple(
|
||||
str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS
|
||||
)
|
||||
|
||||
PROCESS_GATE_CODE_SET: Final[frozenset[str]] = frozenset(PROCESS_GATE_CODES)
|
||||
|
||||
PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'rematerialize_document',
|
||||
'retry_layout_parsing',
|
||||
'reroute_document_profile',
|
||||
'open_profile_review',
|
||||
'retry_order_extraction',
|
||||
'open_order_review',
|
||||
'edit_order_fields',
|
||||
'revalidate_reservation',
|
||||
'edit_reservation',
|
||||
'retry_customer_resolution',
|
||||
'confirm_customer',
|
||||
'retry_duplicate_detection',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'retry_with_latest_rules',
|
||||
'open_inventory_source_review',
|
||||
'adopt_rule_suggestion',
|
||||
'keep_manual_inventory_decision',
|
||||
'recheck_freeze_readiness',
|
||||
'retry_task_creation',
|
||||
'retry_inventory_preparation',
|
||||
'poll_inventory_preparation',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_field_mapping',
|
||||
'confirm_inventory_field_mapping',
|
||||
'retry_inventory_matching',
|
||||
'open_inventory_match_review',
|
||||
'recheck_inventory_sufficiency',
|
||||
'open_shortage_review',
|
||||
'recheck_excel_readiness',
|
||||
'regenerate_excel_artifact',
|
||||
'regenerate_manual_upload_todo',
|
||||
})
|
||||
|
||||
PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'document_unavailable',
|
||||
'layout_parse_failed',
|
||||
'profile_ambiguous',
|
||||
'profile_drift',
|
||||
'profile_not_matched',
|
||||
'extraction_incomplete',
|
||||
'evidence_missing',
|
||||
'required_field_missing',
|
||||
'reservation_invalid',
|
||||
'customer_unresolved',
|
||||
'customer_ambiguous',
|
||||
'duplicate_unresolved',
|
||||
'field_conflict',
|
||||
'cross_source_conflict',
|
||||
'no_inventory_source_candidates',
|
||||
'require_manual_review',
|
||||
'inventory_source_unavailable',
|
||||
'freeze_not_ready',
|
||||
'profile_not_auto_freeze_approved',
|
||||
'profile_manual_confirmation_required',
|
||||
'profile_auto_freeze_qualification_missing',
|
||||
'profile_auto_freeze_suspended',
|
||||
'customer_confirmation_required',
|
||||
'customer_scope_unmatched',
|
||||
'customer_scope_not_configured',
|
||||
'customer_scope_out_of_scope',
|
||||
'multiple_customers_detected',
|
||||
'multiple_profiles_detected',
|
||||
'business_scenario_unmatched',
|
||||
'business_scenario_not_configured',
|
||||
'business_scenario_out_of_scope',
|
||||
'extraction_emergency_stop',
|
||||
'generic_auto_freeze_disabled',
|
||||
'llm_path_cannot_auto_freeze',
|
||||
'auto_freeze_not_enabled',
|
||||
'technical_failure_present',
|
||||
'unit_review_required',
|
||||
'budget_stopped',
|
||||
'review_required',
|
||||
'run_failed',
|
||||
'run_cancelled',
|
||||
'pending_orders_present',
|
||||
'task_creation_failed',
|
||||
'inventory_preparation_failed',
|
||||
'inventory_preparation_waiting',
|
||||
'inventory_mapping_required',
|
||||
'inventory_match_failed',
|
||||
'inventory_insufficient',
|
||||
'excel_not_ready',
|
||||
'artifact_generation_failed',
|
||||
'manual_upload_pending',
|
||||
'gate_invalidated',
|
||||
'lease_conflict',
|
||||
'version_conflict',
|
||||
'not_recoverable',
|
||||
})
|
||||
|
||||
# 原因码 → 唯一 owning_gate;同一根因禁止多门禁平行产生用户阻断。
|
||||
PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'document_unavailable': 'document_materialization',
|
||||
'layout_parse_failed': 'layout_parsing',
|
||||
'profile_ambiguous': 'document_profile_routing',
|
||||
'profile_drift': 'document_profile_routing',
|
||||
'profile_not_matched': 'document_profile_routing',
|
||||
'extraction_incomplete': 'order_field_extraction',
|
||||
'evidence_missing': 'order_field_extraction',
|
||||
'required_field_missing': 'field_completeness',
|
||||
'reservation_invalid': 'reservation_validation',
|
||||
'customer_unresolved': 'customer_resolution',
|
||||
'customer_ambiguous': 'customer_resolution',
|
||||
'duplicate_unresolved': 'duplicate_detection',
|
||||
'field_conflict': 'field_conflict_resolution',
|
||||
'cross_source_conflict': 'field_conflict_resolution',
|
||||
'no_inventory_source_candidates': 'inventory_source_routing',
|
||||
'require_manual_review': 'inventory_source_routing',
|
||||
'inventory_source_unavailable': 'inventory_source_routing',
|
||||
'freeze_not_ready': 'order_freeze_readiness',
|
||||
'profile_not_auto_freeze_approved': 'order_freeze_readiness',
|
||||
'profile_manual_confirmation_required': 'order_freeze_readiness',
|
||||
'profile_auto_freeze_qualification_missing': 'order_freeze_readiness',
|
||||
'profile_auto_freeze_suspended': 'order_freeze_readiness',
|
||||
'customer_confirmation_required': 'order_freeze_readiness',
|
||||
'customer_scope_unmatched': 'order_freeze_readiness',
|
||||
'customer_scope_not_configured': 'order_freeze_readiness',
|
||||
'customer_scope_out_of_scope': 'order_freeze_readiness',
|
||||
'multiple_customers_detected': 'order_freeze_readiness',
|
||||
'multiple_profiles_detected': 'order_freeze_readiness',
|
||||
'business_scenario_unmatched': 'order_freeze_readiness',
|
||||
'business_scenario_not_configured': 'order_freeze_readiness',
|
||||
'business_scenario_out_of_scope': 'order_freeze_readiness',
|
||||
'extraction_emergency_stop': 'order_freeze_readiness',
|
||||
'generic_auto_freeze_disabled': 'order_freeze_readiness',
|
||||
'llm_path_cannot_auto_freeze': 'order_freeze_readiness',
|
||||
'auto_freeze_not_enabled': 'order_freeze_readiness',
|
||||
'technical_failure_present': 'order_freeze_readiness',
|
||||
'unit_review_required': 'order_freeze_readiness',
|
||||
'budget_stopped': 'order_freeze_readiness',
|
||||
'review_required': 'order_freeze_readiness',
|
||||
'run_failed': 'order_freeze_readiness',
|
||||
'run_cancelled': 'order_freeze_readiness',
|
||||
'pending_orders_present': 'order_freeze_readiness',
|
||||
'task_creation_failed': 'task_creation',
|
||||
'inventory_preparation_failed': 'inventory_preparation',
|
||||
'inventory_preparation_waiting': 'inventory_preparation',
|
||||
'inventory_mapping_required': 'inventory_field_mapping',
|
||||
'inventory_match_failed': 'inventory_matching',
|
||||
'inventory_insufficient': 'inventory_sufficiency',
|
||||
'excel_not_ready': 'excel_readiness',
|
||||
'artifact_generation_failed': 'artifact_generation',
|
||||
'manual_upload_pending': 'manual_upload_handoff',
|
||||
}
|
||||
|
||||
# 旧自动建单五门禁键 → 唯一 owning_gate(禁止平行用户投影)。
|
||||
AUTO_BUILD_LEGACY_GATE_OWNING_MAP: Final[dict[str, str]] = {
|
||||
'approved_template': 'order_freeze_readiness',
|
||||
'fields_complete': 'field_completeness',
|
||||
'evidence_passed': 'order_field_extraction',
|
||||
'no_conflict_or_duplicate': 'duplicate_detection',
|
||||
'quality_gate_passed': 'order_freeze_readiness',
|
||||
}
|
||||
|
||||
PROCESS_EXECUTION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'active',
|
||||
'blocked',
|
||||
'waiting_external',
|
||||
'completed',
|
||||
'cancelled',
|
||||
'failed',
|
||||
})
|
||||
|
||||
PROCESS_GATE_ATTEMPT_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'queued',
|
||||
'running',
|
||||
'succeeded',
|
||||
'failed',
|
||||
'cancelled',
|
||||
'superseded',
|
||||
})
|
||||
|
||||
|
||||
def get_process_gate_definition(gate_code: str) -> dict[str, Any]:
|
||||
"""
|
||||
按 gate_code 返回门禁定义副本。
|
||||
|
||||
Args:
|
||||
gate_code: 稳定门禁编码。
|
||||
|
||||
Returns:
|
||||
定义字典。
|
||||
|
||||
Raises:
|
||||
KeyError: 未知门禁码。
|
||||
"""
|
||||
code = str(gate_code or '').strip()
|
||||
for item in PROCESS_GATE_DEFINITIONS:
|
||||
if item['gate_code'] == code:
|
||||
return dict(item)
|
||||
raise KeyError(f'unknown process gate: {code}')
|
||||
|
||||
|
||||
def primary_next_action_for_gate(*, gate_code: str, status: str) -> str | None:
|
||||
"""
|
||||
返回指定门禁状态下的唯一主要恢复动作;无动作返回 None。
|
||||
|
||||
核心逻辑:每种状态最多一个主要 next_action;前端禁止本地推导。
|
||||
"""
|
||||
definition = get_process_gate_definition(gate_code)
|
||||
actions = definition.get('default_next_actions') if isinstance(definition.get('default_next_actions'), dict) else {}
|
||||
value = actions.get(str(status or '').strip())
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def owning_gate_for_reason(reason_code: str) -> str | None:
|
||||
"""
|
||||
返回阻断/诊断原因码的唯一 owning_gate;未知原因返回 None。
|
||||
|
||||
Args:
|
||||
reason_code: 稳定原因码。
|
||||
|
||||
Returns:
|
||||
gate_code 或 None。
|
||||
"""
|
||||
code = str(reason_code or '').strip()
|
||||
return PROCESS_GATE_REASON_OWNING_GATE.get(code)
|
||||
|
||||
|
||||
def field_quality_may_block(*, required: bool = False, auto_create_key_field: bool = False) -> bool:
|
||||
"""
|
||||
字段质量问题是否允许阻断当前动作。
|
||||
|
||||
核心逻辑:仅 required 或 auto_create_key_field 可阻断;否则只允许 diagnostic Finding。
|
||||
"""
|
||||
return bool(required) or bool(auto_create_key_field)
|
||||
|
||||
|
||||
def build_process_finding(
|
||||
*,
|
||||
finding_code: str,
|
||||
owning_gate_code: str,
|
||||
severity: str,
|
||||
reason_code: str,
|
||||
field_code: str | None = None,
|
||||
decision_id: int | None = None,
|
||||
user_visible: bool | None = None,
|
||||
blocks_current_action: bool | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造标准 Finding 结构。
|
||||
|
||||
Args:
|
||||
finding_code: Finding 稳定编码。
|
||||
owning_gate_code: 唯一所属门禁。
|
||||
severity: blocking | diagnostic。
|
||||
reason_code: 原因码(须能映射到 owning_gate)。
|
||||
field_code / decision_id: 可选字段定位。
|
||||
user_visible / blocks_current_action: 缺省由 severity 推导。
|
||||
details: 管理员诊断附加信息。
|
||||
|
||||
Returns:
|
||||
Finding 字典。
|
||||
"""
|
||||
sev = str(severity or '').strip()
|
||||
if sev not in PROCESS_GATE_FINDING_SEVERITIES:
|
||||
raise ValueError(f'invalid finding severity: {sev}')
|
||||
gate = str(owning_gate_code or '').strip()
|
||||
if gate not in PROCESS_GATE_CODE_SET:
|
||||
raise ValueError(f'unknown owning_gate_code: {gate}')
|
||||
visible = bool(user_visible) if user_visible is not None else sev == 'blocking'
|
||||
blocks = bool(blocks_current_action) if blocks_current_action is not None else sev == 'blocking'
|
||||
payload: dict[str, Any] = {
|
||||
'finding_code': str(finding_code),
|
||||
'owning_gate_code': gate,
|
||||
'severity': sev,
|
||||
'reason_code': str(reason_code or '').strip(),
|
||||
'field_code': str(field_code).strip() if field_code else None,
|
||||
'decision_id': int(decision_id) if decision_id is not None else None,
|
||||
'user_visible': visible,
|
||||
'blocks_current_action': blocks,
|
||||
}
|
||||
if details:
|
||||
payload['details'] = dict(details)
|
||||
return payload
|
||||
|
||||
|
||||
def assert_process_gate_contract_integrity() -> None:
|
||||
"""
|
||||
校验契约内无重复 gate_code、动作与状态闭环,以及原因码唯一归属。
|
||||
|
||||
Raises:
|
||||
AssertionError: 契约不一致。
|
||||
"""
|
||||
codes = [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS]
|
||||
assert len(codes) == len(set(codes)), 'duplicate process gate_code'
|
||||
sequences = [int(item['sequence_no']) for item in PROCESS_GATE_DEFINITIONS]
|
||||
assert sequences == sorted(sequences), 'process gate sequence_no must be ascending'
|
||||
assert set(sequences) == set(range(1, len(sequences) + 1)), 'process gate sequence_no must be contiguous'
|
||||
for item in PROCESS_GATE_DEFINITIONS:
|
||||
assert item['responsible_party'] in PROCESS_GATE_RESPONSIBLE_PARTIES
|
||||
actions = item.get('default_next_actions') or {}
|
||||
assert isinstance(actions, dict)
|
||||
for status, action in actions.items():
|
||||
assert status in PROCESS_GATE_STATUSES
|
||||
if action is not None:
|
||||
assert action in PROCESS_GATE_ACTION_CODES
|
||||
if item.get('recoverable'):
|
||||
assert any(value for value in actions.values()), f'{item["gate_code"]} missing recovery action'
|
||||
|
||||
# [STEP] 原因码唯一归属:每个 reason 恰好一个 owning gate,且 gate 必须存在。
|
||||
for reason, gate in PROCESS_GATE_REASON_OWNING_GATE.items():
|
||||
assert reason in PROCESS_GATE_BLOCKING_REASON_CODES, f'reason {reason} missing from blocking codes'
|
||||
assert gate in PROCESS_GATE_CODE_SET, f'reason {reason} owns unknown gate {gate}'
|
||||
owned_reasons = list(PROCESS_GATE_REASON_OWNING_GATE.keys())
|
||||
assert len(owned_reasons) == len(set(owned_reasons)), 'duplicate reason ownership'
|
||||
|
||||
for legacy_key, gate in AUTO_BUILD_LEGACY_GATE_OWNING_MAP.items():
|
||||
assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate'
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_dependency.py
|
||||
|
||||
用途:冻结门禁依赖图与上游输入变化时的下游精确失效范围。
|
||||
依赖:process_gate_contract.PROCESS_GATE_CODE_SET。
|
||||
逻辑:由门禁恢复服务在提交 Attempt 结果或上游字段变化时调用;前端禁止本地推导失效范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Final
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET, PROCESS_GATE_CODES
|
||||
|
||||
|
||||
# 上游变化类型 → 必须失效的下游门禁(不含变化源自身)。
|
||||
PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'pdf_or_extraction_changed': (
|
||||
'field_completeness',
|
||||
'reservation_validation',
|
||||
'customer_resolution',
|
||||
'duplicate_detection',
|
||||
'field_conflict_resolution',
|
||||
'inventory_source_routing',
|
||||
'order_freeze_readiness',
|
||||
'task_creation',
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'reservation_changed': (
|
||||
'duplicate_detection',
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'part_number_changed': (
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'quantity_changed': (
|
||||
'order_freeze_readiness',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'customer_changed': (
|
||||
'duplicate_detection',
|
||||
'order_freeze_readiness',
|
||||
'task_creation',
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_source_changed': (
|
||||
'inventory_preparation',
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_file_changed': (
|
||||
'inventory_field_mapping',
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'inventory_field_mapping_changed': (
|
||||
'inventory_matching',
|
||||
'inventory_sufficiency',
|
||||
'excel_readiness',
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
'excel_regeneration_only': (
|
||||
'artifact_generation',
|
||||
'manual_upload_handoff',
|
||||
),
|
||||
}
|
||||
|
||||
# 显式前置依赖:gate 必须等待这些上游 passed(或 skipped)。
|
||||
PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
|
||||
'layout_parsing': ('document_materialization',),
|
||||
'document_profile_routing': ('layout_parsing',),
|
||||
'order_field_extraction': ('document_profile_routing',),
|
||||
'field_completeness': ('order_field_extraction',),
|
||||
'reservation_validation': ('field_completeness',),
|
||||
'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',),
|
||||
'inventory_field_mapping': ('inventory_preparation',),
|
||||
'inventory_matching': ('inventory_field_mapping',),
|
||||
'inventory_sufficiency': ('inventory_matching',),
|
||||
'excel_readiness': ('inventory_sufficiency',),
|
||||
'artifact_generation': ('excel_readiness',),
|
||||
'manual_upload_handoff': ('artifact_generation',),
|
||||
}
|
||||
|
||||
|
||||
def compute_invalidated_gates(change_type: str) -> tuple[str, ...]:
|
||||
"""
|
||||
计算上游变化必须失效的下游门禁列表(保序、去重)。
|
||||
|
||||
Args:
|
||||
change_type: PROCESS_GATE_INVALIDATION_RULES 键。
|
||||
|
||||
Returns:
|
||||
下游 gate_code 元组;未知变化类型返回空元组。
|
||||
"""
|
||||
key = str(change_type or '').strip()
|
||||
gates = PROCESS_GATE_INVALIDATION_RULES.get(key, ())
|
||||
ordered = [code for code in PROCESS_GATE_CODES if code in set(gates)]
|
||||
return tuple(ordered)
|
||||
|
||||
|
||||
def prerequisites_for(gate_code: str) -> tuple[str, ...]:
|
||||
"""
|
||||
返回指定门禁的直接前置依赖。
|
||||
|
||||
Args:
|
||||
gate_code: 门禁编码。
|
||||
|
||||
Returns:
|
||||
前置 gate_code 元组。
|
||||
"""
|
||||
code = str(gate_code or '').strip()
|
||||
return tuple(PROCESS_GATE_PREREQUISITES.get(code, ()))
|
||||
|
||||
|
||||
def assert_process_gate_dependency_integrity() -> None:
|
||||
"""
|
||||
校验依赖图与失效规则仅引用已知门禁,且无环。
|
||||
|
||||
Raises:
|
||||
AssertionError: 依赖图不一致。
|
||||
"""
|
||||
for gate_code, deps in PROCESS_GATE_PREREQUISITES.items():
|
||||
assert gate_code in PROCESS_GATE_CODE_SET, f'unknown gate in prerequisites: {gate_code}'
|
||||
for dep in deps:
|
||||
assert dep in PROCESS_GATE_CODE_SET, f'unknown prerequisite {dep} for {gate_code}'
|
||||
assert PROCESS_GATE_CODES.index(dep) < PROCESS_GATE_CODES.index(gate_code), (
|
||||
f'prerequisite {dep} must precede {gate_code}'
|
||||
)
|
||||
for change_type, gates in PROCESS_GATE_INVALIDATION_RULES.items():
|
||||
for gate_code in gates:
|
||||
assert gate_code in PROCESS_GATE_CODE_SET, (
|
||||
f'unknown gate {gate_code} in invalidation rule {change_type}'
|
||||
)
|
||||
# 仅重新生成 Excel 不得失效库存匹配。
|
||||
excel_only = set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only'])
|
||||
assert 'inventory_matching' not in excel_only
|
||||
assert 'artifact_generation' in excel_only
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_error_sanitizer.py
|
||||
|
||||
用途:门禁 Attempt / blocking_reason / 投影中的异常摘要统一脱敏与截断。
|
||||
依赖:标准库 re。
|
||||
逻辑:由 process_gate_executor / process_gate_service / process_gate_projection 在写入或
|
||||
对外序列化前调用;剥离 URL、连接串、路径、凭据片段后截断,避免外部系统异常泄漏。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_URL_RE = re.compile(r'https?://[^\s\'\"]+', re.IGNORECASE)
|
||||
_CONN_RE = re.compile(
|
||||
r'(?:postgres(?:ql)?|mysql|mssql|oracle|redis|amqp|mongodb)://[^\s\'\"]+',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_DSN_RE = re.compile(
|
||||
r'(?:password|pwd|secret|token|api[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;\'\"]+',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_WIN_PATH_RE = re.compile(r'[A-Za-z]:\\[^\s\'\"]+')
|
||||
_UNIX_PATH_RE = re.compile(r'(?:/[\w.\-]+){2,}')
|
||||
_IPV4_RE = re.compile(r'\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{2,5})?\b')
|
||||
_BEARER_RE = re.compile(r'(?i)\b(?:bearer|authorization)\s+[A-Za-z0-9._\-+=/]+')
|
||||
|
||||
|
||||
def sanitize_gate_error_text(value: object | None, *, max_len: int = 500) -> str | None:
|
||||
"""
|
||||
将异常/工具错误文本脱敏并截断,供 Attempt.error_summary 与诊断投影使用。
|
||||
|
||||
核心逻辑:依次遮蔽 URL、连接串、凭据键值、文件系统路径、IPv4 与 Bearer;
|
||||
再压缩空白并截断到 max_len。空输入返回 None。
|
||||
|
||||
Args:
|
||||
value: 原始错误对象或字符串。
|
||||
max_len: 最大保留字符数(默认 500,Attempt 持久化可用更大上限)。
|
||||
|
||||
Returns:
|
||||
脱敏后的摘要;无有效内容时 None。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
# [STEP 1] 遮蔽高风险片段,避免连接串 / 路径 / Token 落库或下发。
|
||||
text = _URL_RE.sub('[url]', text)
|
||||
text = _CONN_RE.sub('[connection]', text)
|
||||
text = _DSN_RE.sub(lambda m: f"{m.group(0).split('=')[0].split(':')[0]}=[redacted]", text)
|
||||
text = _BEARER_RE.sub('[auth]', text)
|
||||
text = _WIN_PATH_RE.sub('[path]', text)
|
||||
text = _UNIX_PATH_RE.sub('[path]', text)
|
||||
text = _IPV4_RE.sub('[host]', text)
|
||||
text = re.sub(r'\s+', ' ', text).strip()
|
||||
limit = max(32, int(max_len or 500))
|
||||
if len(text) > limit:
|
||||
text = text[: limit - 1].rstrip() + '…'
|
||||
return text
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,403 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_job_service.py
|
||||
|
||||
用途:门禁 Attempt 的 Job 入队、租约心跳、陈旧租约接管、外部等待轮询与 Worker 执行入口。
|
||||
依赖:app.jobs.queue、JobType、ShippingProcessGateAttempt、process_gate_executor、
|
||||
process_gate_service、fulfillment_audit。
|
||||
逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用
|
||||
claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job;
|
||||
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
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.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
from app.services.shipping_notice.process_gate_service import mark_attempt_running
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 与发货通知共用 domain,便于 shipping worker 一并领取。
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN = 'shipping_notice'
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
"""naive UTC。"""
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _lease_seconds() -> int:
|
||||
"""租约时长(秒),默认 60。"""
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_LEASE_SECONDS', 60) or 60), 15)
|
||||
|
||||
|
||||
def _takeover_seconds() -> int:
|
||||
"""接管阈值(秒),默认 120。"""
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS', 120) or 120), 30)
|
||||
|
||||
|
||||
def _heartbeat_seconds() -> int:
|
||||
"""心跳间隔(秒),默认 15。"""
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5)
|
||||
|
||||
|
||||
def enqueue_gate_attempt_job(
|
||||
*,
|
||||
attempt_id: int,
|
||||
created_by_id: int | None = None,
|
||||
delay_seconds: int = 0,
|
||||
force_new: bool = False,
|
||||
) -> int:
|
||||
"""
|
||||
为 Attempt 入队 Gate Job,并回写 attempt.job_id。
|
||||
|
||||
核心逻辑:默认仅对 queued 去重,绝不复用仍 running 的同 business_ref Job;
|
||||
force_new 时使用带时间戳的 business_ref,保证重试/轮询一定新建可领取 Job。
|
||||
|
||||
Args:
|
||||
attempt_id: Attempt 主键。
|
||||
created_by_id: 可选创建人。
|
||||
delay_seconds: 延迟入队秒数。
|
||||
force_new: True 时强制新建 Job(重试/外部等待轮询)。
|
||||
|
||||
Returns:
|
||||
Job 主键。
|
||||
"""
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.job_id and not force_new:
|
||||
return int(attempt.job_id)
|
||||
|
||||
scheduled_at = None
|
||||
if delay_seconds and int(delay_seconds) > 0:
|
||||
scheduled_at = _utc_now() + timedelta(seconds=int(delay_seconds))
|
||||
|
||||
max_attempts = int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3)
|
||||
# [STEP] force_new 用独立 business_ref,避免与刚结束/仍残留的 Job 去重冲突。
|
||||
if force_new:
|
||||
business_ref = f'attempt:{int(attempt.id)}:r{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}'
|
||||
else:
|
||||
business_ref = f'attempt:{int(attempt.id)}'
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
{'attempt_id': int(attempt.id)},
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
business_ref=business_ref,
|
||||
created_by_id=created_by_id,
|
||||
message='等待执行门禁恢复 Attempt',
|
||||
max_attempts=max(max_attempts, 1),
|
||||
scheduled_at=scheduled_at,
|
||||
# 仅匹配 queued:禁止复用仍 running 的旧 Job(重试场景)。
|
||||
dedupe_statuses=('queued',),
|
||||
dedupe_active=not force_new,
|
||||
commit=False,
|
||||
)
|
||||
attempt.job_id = int(job_id)
|
||||
db.session.flush()
|
||||
return int(job_id)
|
||||
|
||||
|
||||
def schedule_waiting_external_poll(
|
||||
*,
|
||||
attempt_id: int,
|
||||
gate_code: str | None = None,
|
||||
) -> int | None:
|
||||
"""
|
||||
waiting_external 成功后调度下一次 poll Attempt;超时则转入 blocked_manual。
|
||||
|
||||
核心逻辑:读取 Gate.effective_result_json.waiting_since;超过
|
||||
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS(默认 1800)则不再入队,
|
||||
而是将 Gate 置为 blocked_manual 并写入超时原因。
|
||||
|
||||
Returns:
|
||||
新 Job id;超时或无需调度时 None。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_contract import primary_next_action_for_gate
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt, complete_gate_attempt
|
||||
|
||||
finished = db.session.get(ShippingProcessGateAttempt, int(attempt_id))
|
||||
if finished is None:
|
||||
return None
|
||||
gate = db.session.get(ShippingProcessGate, int(finished.gate_id))
|
||||
if gate is None or gate.status != 'waiting_external':
|
||||
return None
|
||||
|
||||
effective = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {}
|
||||
waiting_since_raw = effective.get('waiting_since')
|
||||
now = _utc_now()
|
||||
if waiting_since_raw:
|
||||
try:
|
||||
waiting_since = datetime.fromisoformat(str(waiting_since_raw))
|
||||
except ValueError:
|
||||
waiting_since = gate.updated_at or now
|
||||
else:
|
||||
waiting_since = gate.updated_at or now
|
||||
effective = {**effective, 'waiting_since': waiting_since.isoformat()}
|
||||
gate.effective_result_json = effective
|
||||
db.session.flush()
|
||||
|
||||
timeout_sec = max(
|
||||
int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS', 1800) or 1800),
|
||||
60,
|
||||
)
|
||||
if (now - waiting_since).total_seconds() >= timeout_sec:
|
||||
# [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
poll_attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-timeout',
|
||||
idempotency_key=f'wait-timeout:{gate.id}:{gate.evaluation_version}',
|
||||
input_snapshot={
|
||||
'action_code': primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='blocked_manual',
|
||||
) or 'open_order_review',
|
||||
'payload': {'reason': 'external_wait_timeout'},
|
||||
},
|
||||
)
|
||||
if poll_attempt.status in {'queued', 'running'}:
|
||||
mark_attempt_running(attempt_id=int(poll_attempt.id), worker_id='system-timeout')
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(poll_attempt.id),
|
||||
outcome='blocked_manual',
|
||||
blocking_reason_code=gate.blocking_reason_code or 'gate_invalidated',
|
||||
blocking_reason_json={
|
||||
'message': '外部等待超时,请人工处理',
|
||||
'waiting_since': waiting_since.isoformat(),
|
||||
'timeout_seconds': timeout_sec,
|
||||
},
|
||||
effective_result_json={
|
||||
'findings': [],
|
||||
'external_wait_timeout': True,
|
||||
'waiting_since': waiting_since.isoformat(),
|
||||
},
|
||||
output_snapshot={'action_code': 'external_wait_timeout'},
|
||||
)
|
||||
return None
|
||||
|
||||
poll_seconds = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
|
||||
action = gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='waiting_external',
|
||||
)
|
||||
if not action:
|
||||
action = 'poll_inventory_preparation'
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
poll_attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-poll',
|
||||
idempotency_key=f'wait-poll:{gate.id}:{gate.evaluation_version}:{int(now.timestamp())}',
|
||||
input_snapshot={'action_code': action, 'payload': {'poll': True}},
|
||||
)
|
||||
if poll_attempt.status not in {'queued', 'running'}:
|
||||
return int(poll_attempt.job_id) if poll_attempt.job_id else None
|
||||
return enqueue_gate_attempt_job(
|
||||
attempt_id=int(poll_attempt.id),
|
||||
delay_seconds=poll_seconds,
|
||||
force_new=True,
|
||||
)
|
||||
|
||||
|
||||
def heartbeat_gate_attempt(
|
||||
*,
|
||||
attempt_id: int,
|
||||
worker_id: str,
|
||||
lease_token: str,
|
||||
) -> ShippingProcessGateAttempt:
|
||||
"""
|
||||
续租并刷新心跳;不写业务审计。
|
||||
|
||||
Raises:
|
||||
ConflictError: 租约不匹配。
|
||||
"""
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.status != 'running':
|
||||
raise ConflictError('Attempt is not running', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE')
|
||||
if str(attempt.lease_token or '') != str(lease_token or '') or str(attempt.worker_id or '') != str(worker_id or ''):
|
||||
raise ConflictError('Lease token mismatch', code='SHIPPING.PROCESS_GATE_LEASE_CONFLICT')
|
||||
now = _utc_now()
|
||||
attempt.heartbeat_at = now
|
||||
attempt.lease_expires_at = now + timedelta(seconds=_lease_seconds())
|
||||
# [STEP] 立即提交,使其他 Worker 的接管扫描能看到最新心跳。
|
||||
db.session.commit()
|
||||
return attempt
|
||||
|
||||
|
||||
def recover_stale_gate_attempts(*, worker_id: str) -> list[int]:
|
||||
"""
|
||||
回收心跳超时的 running Attempt:释放租约并重新入队。
|
||||
|
||||
核心逻辑:heartbeat_at 超过接管阈值则标记可接管,写入审计并 enqueue 新 Job。
|
||||
|
||||
Returns:
|
||||
被接管的 attempt_id 列表。
|
||||
"""
|
||||
cutoff = _utc_now() - timedelta(seconds=_takeover_seconds())
|
||||
query = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.status == 'running',
|
||||
ShippingProcessGateAttempt.heartbeat_at.isnot(None),
|
||||
ShippingProcessGateAttempt.heartbeat_at < cutoff,
|
||||
)
|
||||
.limit(20)
|
||||
)
|
||||
# PostgreSQL 用 SKIP LOCKED 避免双 Worker 抢同一陈旧行;SQLite 测试库直接查询。
|
||||
bind = db.session.get_bind()
|
||||
dialect = str(getattr(getattr(bind, 'dialect', None), 'name', '') or '')
|
||||
if dialect == 'postgresql':
|
||||
stale = query.with_for_update(skip_locked=True).all()
|
||||
else:
|
||||
stale = query.all()
|
||||
taken: list[int] = []
|
||||
for attempt in stale:
|
||||
old_worker = attempt.worker_id
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if gate else None
|
||||
attempt.status = 'queued'
|
||||
attempt.worker_id = None
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
attempt.job_id = None
|
||||
if gate is not None:
|
||||
gate.status = 'queued'
|
||||
gate.updated_at = _utc_now()
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_lease_taken_over',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(attempt.id),
|
||||
action='lease_takeover',
|
||||
actor_type='worker',
|
||||
actor_id=worker_id,
|
||||
before={'status': 'running', 'worker_id': old_worker, 'gate_code': gate.gate_code if gate else None},
|
||||
after={'status': 'queued', 'worker_id': None, 'gate_code': gate.gate_code if gate else None},
|
||||
metadata={'execution_no': execution.execution_no if execution else None},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
taken.append(int(attempt.id))
|
||||
return taken
|
||||
|
||||
|
||||
def claim_and_run_gate_attempt(
|
||||
*,
|
||||
attempt_id: int,
|
||||
worker_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Worker 领取 Attempt 租约并执行 execute_queued_attempt。
|
||||
|
||||
Returns:
|
||||
含 gate_code / outcome 的摘要。
|
||||
"""
|
||||
recover_stale_gate_attempts(worker_id=worker_id)
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
return {
|
||||
'attempt_id': int(attempt.id),
|
||||
'status': attempt.status,
|
||||
'skipped': True,
|
||||
}
|
||||
|
||||
lease_token = uuid.uuid4().hex
|
||||
now = _utc_now()
|
||||
lease_expires = now + timedelta(seconds=_lease_seconds())
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id=str(worker_id)[:64],
|
||||
lease_token=lease_token,
|
||||
lease_expires_at=lease_expires,
|
||||
)
|
||||
# [STEP] 领取后立即提交,保证租约对其他 Worker 可见。
|
||||
db.session.commit()
|
||||
db.session.refresh(attempt)
|
||||
|
||||
# [STEP] 长任务周期心跳:独立线程续租,避免超过接管阈值被双执行。
|
||||
app = current_app._get_current_object()
|
||||
stop_heartbeat = threading.Event()
|
||||
hb_attempt_id = int(attempt.id)
|
||||
hb_worker = str(worker_id)[:64]
|
||||
hb_token = lease_token
|
||||
hb_interval = _heartbeat_seconds()
|
||||
|
||||
def _heartbeat_loop() -> None:
|
||||
while not stop_heartbeat.wait(hb_interval):
|
||||
try:
|
||||
with app.app_context():
|
||||
heartbeat_gate_attempt(
|
||||
attempt_id=hb_attempt_id,
|
||||
worker_id=hb_worker,
|
||||
lease_token=hb_token,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'process_gate heartbeat failed attempt_id=%s worker=%s',
|
||||
hb_attempt_id,
|
||||
hb_worker,
|
||||
)
|
||||
|
||||
hb_thread = threading.Thread(
|
||||
target=_heartbeat_loop,
|
||||
name=f'gate-hb-{hb_attempt_id}',
|
||||
daemon=True,
|
||||
)
|
||||
hb_thread.start()
|
||||
try:
|
||||
gate = execute_queued_attempt(
|
||||
attempt=attempt,
|
||||
worker_id=worker_id,
|
||||
lease_token=lease_token,
|
||||
lease_expires_at=lease_expires,
|
||||
)
|
||||
return {
|
||||
'attempt_id': int(attempt_id),
|
||||
'gate_code': gate.gate_code,
|
||||
'gate_status': gate.status,
|
||||
'skipped': False,
|
||||
'heartbeat_interval_seconds': hb_interval,
|
||||
}
|
||||
finally:
|
||||
stop_heartbeat.set()
|
||||
hb_thread.join(timeout=max(hb_interval, 2))
|
||||
@@ -0,0 +1,404 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_projection.py
|
||||
|
||||
用途:将 Execution / Gate / Attempt 投影为前后端共享的只读恢复视图。
|
||||
依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract。
|
||||
逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影;
|
||||
用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES,
|
||||
get_process_gate_definition,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
|
||||
|
||||
# 前端仅导航、不 POST 的人工入口动作(与 process_gate_executor._SYNC_ACTIONS 子集对齐)。
|
||||
_PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: frozenset[str] = frozenset({
|
||||
'open_order_review',
|
||||
'open_inventory_source_review',
|
||||
'open_profile_review',
|
||||
'edit_order_fields',
|
||||
'edit_reservation',
|
||||
'confirm_customer',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts',
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'confirm_inventory_field_mapping',
|
||||
})
|
||||
|
||||
_PROCESS_GATE_TASK_NAVIGATION_ACTIONS: frozenset[str] = frozenset({
|
||||
'upload_inventory_file',
|
||||
})
|
||||
|
||||
_ACTION_NAVIGATION_FOCUS: dict[str, str] = {
|
||||
'open_profile_review': 'draft',
|
||||
'open_order_review': 'draft',
|
||||
'edit_order_fields': 'draft',
|
||||
'edit_reservation': 'draft',
|
||||
'confirm_customer': 'draft',
|
||||
'adjudicate_duplicate': 'draft',
|
||||
'resolve_field_conflicts': 'evidence',
|
||||
'open_inventory_source_review': 'draft',
|
||||
'open_inventory_match_review': 'draft',
|
||||
'open_shortage_review': 'draft',
|
||||
'confirm_inventory_field_mapping': 'draft',
|
||||
'upload_inventory_file': 'manual_upload',
|
||||
}
|
||||
|
||||
|
||||
def serialize_gate_attempt(
|
||||
attempt: ShippingProcessGateAttempt | None,
|
||||
*,
|
||||
include_snapshots: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
序列化 Attempt 摘要。
|
||||
|
||||
Args:
|
||||
attempt: Attempt 行。
|
||||
include_snapshots: True 时附带输入/输出快照 JSON(管理员诊断用)。
|
||||
"""
|
||||
if attempt is None:
|
||||
return None
|
||||
payload = {
|
||||
'id': int(attempt.id),
|
||||
'attempt_no': int(attempt.attempt_no),
|
||||
'status': attempt.status,
|
||||
'trigger_type': attempt.trigger_type,
|
||||
'actor_type': attempt.actor_type,
|
||||
'actor_id': attempt.actor_id,
|
||||
'idempotency_key': attempt.idempotency_key,
|
||||
'job_id': int(attempt.job_id) if attempt.job_id else None,
|
||||
'worker_id': attempt.worker_id,
|
||||
'lease_expires_at': attempt.lease_expires_at.isoformat() if attempt.lease_expires_at else None,
|
||||
'heartbeat_at': attempt.heartbeat_at.isoformat() if attempt.heartbeat_at else None,
|
||||
'started_at': attempt.started_at.isoformat() if attempt.started_at else None,
|
||||
'finished_at': attempt.finished_at.isoformat() if attempt.finished_at else None,
|
||||
'error_code': attempt.error_code,
|
||||
# 读路径再脱敏一次,兼容历史未清洗数据。
|
||||
'error_summary': sanitize_gate_error_text(attempt.error_summary, max_len=2000),
|
||||
'input_snapshot_hash': attempt.input_snapshot_hash,
|
||||
'rule_snapshot_hash': attempt.rule_snapshot_hash,
|
||||
'output_snapshot_hash': attempt.output_snapshot_hash,
|
||||
}
|
||||
if include_snapshots:
|
||||
payload['input_snapshot'] = attempt.input_snapshot_json
|
||||
payload['rule_snapshot'] = attempt.rule_snapshot_json
|
||||
payload['output_snapshot'] = attempt.output_snapshot_json
|
||||
return payload
|
||||
|
||||
|
||||
def _findings_from_gate(gate: ShippingProcessGate) -> list[dict[str, Any]]:
|
||||
"""从 Gate.effective_result_json 提取 Finding 列表。"""
|
||||
payload = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {}
|
||||
raw = payload.get('findings') if isinstance(payload.get('findings'), list) else []
|
||||
return [dict(item) for item in raw if isinstance(item, dict)]
|
||||
|
||||
|
||||
def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bool = True) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单门禁投影。
|
||||
|
||||
Args:
|
||||
gate: 门禁行。
|
||||
include_diagnostics: False 时仅保留用户可见 blocking Finding。
|
||||
"""
|
||||
definition = get_process_gate_definition(gate.gate_code)
|
||||
latest = None
|
||||
if gate.latest_attempt_id:
|
||||
latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id))
|
||||
findings = _findings_from_gate(gate)
|
||||
if not include_diagnostics:
|
||||
findings = [
|
||||
item for item in findings
|
||||
if item.get('severity') == 'blocking' and item.get('user_visible', True)
|
||||
]
|
||||
return {
|
||||
'gate_code': gate.gate_code,
|
||||
'sequence_no': int(gate.sequence_no),
|
||||
'label': definition.get('label'),
|
||||
'status': gate.status,
|
||||
'evaluation_version': int(gate.evaluation_version),
|
||||
'input_fingerprint': gate.input_fingerprint,
|
||||
'blocking_reason_code': gate.blocking_reason_code,
|
||||
'blocking_reason': gate.blocking_reason_json if include_diagnostics else (
|
||||
{'reason_code': gate.blocking_reason_code} if gate.blocking_reason_code else None
|
||||
),
|
||||
'recommendation': gate.recommendation_json if include_diagnostics else None,
|
||||
'effective_result': gate.effective_result_json if include_diagnostics else None,
|
||||
'findings': findings,
|
||||
'next_action_code': gate.next_action_code,
|
||||
'responsible_party': definition.get('responsible_party'),
|
||||
'recoverable': bool(definition.get('recoverable')),
|
||||
'passed_at': gate.passed_at.isoformat() if gate.passed_at else None,
|
||||
'invalidated_at': gate.invalidated_at.isoformat() if gate.invalidated_at else None,
|
||||
'latest_attempt': serialize_gate_attempt(latest) if include_diagnostics else (
|
||||
{'attempt_no': latest.attempt_no, 'status': latest.status} if latest else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def serialize_process_execution(
|
||||
execution: ShippingProcessExecution,
|
||||
*,
|
||||
include_diagnostics: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化 Execution 恢复投影。
|
||||
|
||||
Returns:
|
||||
含当前门禁、主动作与全部门禁轨道的字典。
|
||||
"""
|
||||
gates = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc())
|
||||
.all()
|
||||
)
|
||||
serialized = [
|
||||
serialize_process_gate(gate, include_diagnostics=include_diagnostics)
|
||||
for gate in gates
|
||||
]
|
||||
current = next(
|
||||
(item for item in serialized if item.get('gate_code') == execution.current_gate_code),
|
||||
None,
|
||||
)
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'status': execution.status,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
'last_passed_gate_code': execution.last_passed_gate_code,
|
||||
'primary_next_action_code': execution.primary_next_action_code,
|
||||
'responsible_party': execution.responsible_party,
|
||||
'lock_version': int(execution.lock_version),
|
||||
'workflow_item_id': int(execution.workflow_item_id),
|
||||
'workflow_item_version_id': int(execution.workflow_item_version_id),
|
||||
'review_case_id': int(execution.review_case_id) if execution.review_case_id else None,
|
||||
'task_id': int(execution.task_id) if execution.task_id else None,
|
||||
'current_gate': current,
|
||||
'gates': serialized,
|
||||
'updated_at': execution.updated_at.isoformat() if execution.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _execution_navigation_refs(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""
|
||||
解析 Execution 关联的业务编号,供前端 router 深链。
|
||||
|
||||
Returns:
|
||||
case_no / review_case_no / review_run_no / task_no。
|
||||
"""
|
||||
case_no = None
|
||||
review_run_no = None
|
||||
task_no = None
|
||||
if execution.review_case_id:
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
case = ShippingOrderReviewCase.query.get(int(execution.review_case_id))
|
||||
if case is not None:
|
||||
case_no = str(case.case_no)
|
||||
run = getattr(case, 'run', None)
|
||||
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 ShippingTask
|
||||
|
||||
task = ShippingTask.query.get(int(execution.task_id))
|
||||
if task is not None:
|
||||
task_no = str(task.task_no)
|
||||
return {
|
||||
'case_no': case_no,
|
||||
'review_case_no': case_no,
|
||||
'review_run_no': review_run_no,
|
||||
'task_no': task_no,
|
||||
}
|
||||
|
||||
|
||||
def _navigation_for_action(action_code: str | None, refs: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""按主动作码生成前端导航提示;缺关键编号时返回 None。"""
|
||||
code = str(action_code or '').strip()
|
||||
if not code:
|
||||
return None
|
||||
if code in _PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS:
|
||||
run_no = refs.get('review_run_no')
|
||||
case_no = refs.get('case_no')
|
||||
if not run_no and not case_no:
|
||||
return None
|
||||
return {
|
||||
'target': 'order_review',
|
||||
'focus': _ACTION_NAVIGATION_FOCUS.get(code, 'draft'),
|
||||
'run_no': run_no,
|
||||
'case_no': case_no,
|
||||
}
|
||||
if code in _PROCESS_GATE_TASK_NAVIGATION_ACTIONS:
|
||||
task_no = refs.get('task_no')
|
||||
if not task_no:
|
||||
return None
|
||||
return {
|
||||
'target': 'task_workspace',
|
||||
'focus': _ACTION_NAVIGATION_FOCUS.get(code),
|
||||
'task_no': task_no,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""
|
||||
用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。
|
||||
|
||||
Returns:
|
||||
current_blocking_gate、reason、next_action、diagnostic_hint(可选非阻断提示)。
|
||||
"""
|
||||
full = serialize_process_execution(execution, include_diagnostics=False)
|
||||
current = full.get('current_gate')
|
||||
blocking = None
|
||||
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
|
||||
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
|
||||
}:
|
||||
blocking = current
|
||||
diagnostic_hint = None
|
||||
for gate in full.get('gates') or []:
|
||||
for finding in gate.get('findings') or []:
|
||||
if finding.get('severity') == 'diagnostic':
|
||||
diagnostic_hint = '其他可选字段存在证据不足,不影响当前处理'
|
||||
break
|
||||
if diagnostic_hint:
|
||||
break
|
||||
reason_code = (blocking or {}).get('blocking_reason_code')
|
||||
next_action = full.get('primary_next_action_code') or (
|
||||
primary_next_action_for_gate(
|
||||
gate_code=str((blocking or {}).get('gate_code') or ''),
|
||||
status=str((blocking or {}).get('status') or ''),
|
||||
) if blocking else None
|
||||
)
|
||||
refs = _execution_navigation_refs(execution)
|
||||
navigation = _navigation_for_action(next_action, refs)
|
||||
return {
|
||||
'execution_no': full.get('execution_no'),
|
||||
'status': full.get('status'),
|
||||
'current_blocking_gate': blocking,
|
||||
'blocking_reason_code': reason_code,
|
||||
'blocking_message': _user_facing_blocking_message(reason_code),
|
||||
'next_action_code': next_action,
|
||||
'responsible_party': full.get('responsible_party'),
|
||||
'diagnostic_hint': diagnostic_hint,
|
||||
'case_no': refs.get('case_no'),
|
||||
'review_case_no': refs.get('review_case_no'),
|
||||
'review_run_no': refs.get('review_run_no'),
|
||||
'task_no': refs.get('task_no'),
|
||||
'navigation': navigation,
|
||||
'gates_track': [
|
||||
{
|
||||
'gate_code': item.get('gate_code'),
|
||||
'label': item.get('label'),
|
||||
'status': item.get('status'),
|
||||
'sequence_no': item.get('sequence_no'),
|
||||
}
|
||||
for item in (full.get('gates') or [])
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _user_facing_blocking_message(reason_code: str | None) -> str | None:
|
||||
"""
|
||||
将内部原因码映射为用户可读业务文案;未知码不回落展示原码。
|
||||
|
||||
Args:
|
||||
reason_code: Gate.blocking_reason_code。
|
||||
|
||||
Returns:
|
||||
可读文案;无法映射时 None(前端展示门禁标签 + 通用提示)。
|
||||
"""
|
||||
code = str(reason_code or '').strip()
|
||||
if not code:
|
||||
return None
|
||||
messages = {
|
||||
'auto_freeze_not_enabled': '自动建单策略尚未放行,需人工确认',
|
||||
'profile_not_auto_freeze_approved': '自动建单策略尚未放行,需人工确认',
|
||||
'profile_manual_confirmation_required': '自动建单策略尚未放行,需人工确认',
|
||||
'freeze_not_ready': '订单尚未满足冻结建单条件,请先完成复核确认',
|
||||
'document_unavailable': '发货通知文档不可用,请重新上传或物化文档',
|
||||
'layout_parse_failed': 'PDF 版面解析失败,请重试解析',
|
||||
'profile_not_matched': '未能匹配文档模板,请人工确认 Profile',
|
||||
'profile_ambiguous': '文档模板存在歧义,请人工确认 Profile',
|
||||
'extraction_incomplete': '订单字段抽取未完成,请重试或进入复核',
|
||||
'required_field_missing': '存在必填字段缺失,请补充订单信息',
|
||||
'reservation_invalid': 'Reservation 校验未通过,请修正后重试',
|
||||
'customer_unresolved': '客户身份未识别,请确认客户',
|
||||
'customer_ambiguous': '客户身份存在歧义,请确认客户',
|
||||
'duplicate_unresolved': '疑似重复订单,请裁定后继续',
|
||||
'field_conflict': '订单字段存在冲突,请解决冲突后继续',
|
||||
'cross_source_conflict': '跨来源字段冲突,请解决冲突后继续',
|
||||
'no_inventory_source_candidates': '暂无可用库存源候选,请重算或人工指定',
|
||||
'require_manual_review': '库存源需人工确认',
|
||||
'inventory_source_unavailable': '库存源不可用,请更换或重试',
|
||||
'task_creation_failed': '履约任务创建失败,请重试或联系管理员',
|
||||
'inventory_preparation_failed': '库存准备失败,请重试或上传库存文件',
|
||||
'inventory_preparation_waiting': '库存准备进行中,请稍后刷新',
|
||||
'inventory_mapping_required': '库存字段映射待确认',
|
||||
'inventory_match_failed': '库存匹配失败,请复核匹配结果',
|
||||
'inventory_insufficient': '库存不足,请处理缺料后继续',
|
||||
'excel_not_ready': '暂不满足 Excel 生成条件',
|
||||
'artifact_generation_failed': 'Excel 生成失败,请重试',
|
||||
'manual_upload_pending': '请下载 Excel 并在货代平台上传后登记凭据',
|
||||
'gate_invalidated': '上游结果已变化,当前门禁需重新评估',
|
||||
'review_required': '需要人工复核后才能继续',
|
||||
}
|
||||
return messages.get(code)
|
||||
|
||||
|
||||
def project_admin_gate_diagnostics(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""管理员诊断投影:全部 Gate、Finding、Attempt 摘要与有效结果。"""
|
||||
return serialize_process_execution(execution, include_diagnostics=True)
|
||||
|
||||
|
||||
def project_workbench_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""
|
||||
业务工作台投影:用户阻断摘要 + 当前 Gate 下的业务可见 findings。
|
||||
|
||||
核心逻辑:不暴露 Attempt 快照哈希与完整 effective_result 内部结构。
|
||||
"""
|
||||
user = project_user_gate_summary(execution)
|
||||
current = user.get('current_blocking_gate') or {}
|
||||
return {
|
||||
**user,
|
||||
'current_findings': list(current.get('findings') or []),
|
||||
}
|
||||
|
||||
|
||||
def find_execution_projection_for_case(case_id: int) -> dict[str, Any] | None:
|
||||
"""按 Review Case 查找 Execution 投影;无则 None。"""
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case_id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
return serialize_process_execution(execution)
|
||||
|
||||
|
||||
def find_execution_projection_for_task(task_id: int) -> dict[str, Any] | None:
|
||||
"""按 ShippingTask 查找 Execution 投影;无则 None。"""
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task_id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
return serialize_process_execution(execution)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_recovery_service.py
|
||||
|
||||
用途:处理客户端门禁恢复动作请求(幂等、版本校验、权限边界由 API 层配合)。
|
||||
依赖:process_gate_service、process_gate_executor、process_gate_contract、
|
||||
ShippingProcessExecution。
|
||||
逻辑:只接受契约内 action_code;排队 Attempt 后同步动作立即执行,异步动作入队 Job;
|
||||
库存源路由的 retry_with_latest_rules / adopt / keep 委托 Draft 服务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_ACTION_CODES,
|
||||
get_process_gate_definition,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
def get_execution_by_no(execution_no: str) -> ShippingProcessExecution:
|
||||
"""按编号读取 Execution;不存在抛 NotFound。"""
|
||||
row = ShippingProcessExecution.query.filter_by(
|
||||
execution_no=str(execution_no or '').strip().upper(),
|
||||
).first()
|
||||
if row is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def request_gate_action(
|
||||
*,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
action_code: str,
|
||||
expected_gate_version: int,
|
||||
idempotency_key: str,
|
||||
actor_type: str,
|
||||
actor_id: int | str | None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
请求执行服务端下发的门禁恢复动作。
|
||||
|
||||
核心逻辑:校验 action 属于契约且与当前门禁主要动作一致(或为同门禁允许的附属动作);
|
||||
创建 queued Attempt 后,同步动作立即 execute_queued_attempt,异步动作入队 Gate Job。
|
||||
客户端禁止提交起始阶段/目标状态/Worker 名。
|
||||
|
||||
Args:
|
||||
execution_no / gate_code: 定位目标。
|
||||
action_code: 契约内动作。
|
||||
expected_gate_version: 乐观锁。
|
||||
idempotency_key: 幂等键。
|
||||
actor_type / actor_id: 操作主体。
|
||||
payload: 可选附加参数(如 reason),不得含目标状态。
|
||||
|
||||
Returns:
|
||||
含 attempt / gate 摘要的字典。
|
||||
"""
|
||||
action = str(action_code or '').strip()
|
||||
if action not in PROCESS_GATE_ACTION_CODES:
|
||||
raise ValidationError('Unknown process gate action', code='SHIPPING.PROCESS_GATE_ACTION_INVALID')
|
||||
forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql'}
|
||||
body = dict(payload) if isinstance(payload, dict) else {}
|
||||
if forbidden.intersection(set(body.keys())):
|
||||
raise ValidationError('Client must not submit execution controls', code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN')
|
||||
|
||||
# 同步适配器需要操作人;从 actor 注入,禁止客户端伪造目标状态。
|
||||
if actor_id is not None and 'actor_user_id' not in body:
|
||||
try:
|
||||
body['actor_user_id'] = int(actor_id)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
body.setdefault('idempotency_key', str(idempotency_key or ''))
|
||||
|
||||
execution = get_execution_by_no(execution_no)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=str(gate_code or '').strip(),
|
||||
).first()
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
|
||||
primary = gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status=gate.status,
|
||||
)
|
||||
# [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。
|
||||
allowed_side: set[str] = set()
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
allowed_side = {
|
||||
'adopt_rule_suggestion',
|
||||
'keep_manual_inventory_decision',
|
||||
}
|
||||
if primary and action != primary and action not in allowed_side:
|
||||
raise ValidationError(
|
||||
'Action is not the primary recovery action for this gate',
|
||||
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
|
||||
details={'expected': primary, 'got': action, 'gate_code': gate.gate_code},
|
||||
)
|
||||
|
||||
definition = get_process_gate_definition(gate.gate_code)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=idempotency_key,
|
||||
expected_gate_version=expected_gate_version,
|
||||
input_snapshot={'action_code': action, 'payload': body},
|
||||
)
|
||||
|
||||
# 幂等回放且已终态:直接返回,不二次执行。
|
||||
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
|
||||
db_gate = ShippingProcessGate.query.get(int(attempt.gate_id))
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': gate.gate_code,
|
||||
'action_code': action,
|
||||
'responsible_party': definition.get('responsible_party'),
|
||||
'dispatch': 'idempotent_replay',
|
||||
'attempt': {
|
||||
'id': int(attempt.id),
|
||||
'attempt_no': int(attempt.attempt_no),
|
||||
'status': attempt.status,
|
||||
'idempotency_key': attempt.idempotency_key,
|
||||
},
|
||||
'gate_status': db_gate.status if db_gate else gate.status,
|
||||
'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version),
|
||||
}
|
||||
|
||||
if action_requires_async_worker(action):
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=(
|
||||
int(actor_id) if actor_type == 'user' and actor_id is not None else None
|
||||
))
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': gate.gate_code,
|
||||
'action_code': action,
|
||||
'responsible_party': definition.get('responsible_party'),
|
||||
'dispatch': 'async_job',
|
||||
'job_id': job_id,
|
||||
'attempt': {
|
||||
'id': int(attempt.id),
|
||||
'attempt_no': int(attempt.attempt_no),
|
||||
'status': attempt.status,
|
||||
'idempotency_key': attempt.idempotency_key,
|
||||
},
|
||||
'gate_evaluation_version': int(gate.evaluation_version),
|
||||
}
|
||||
|
||||
updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery')
|
||||
return {
|
||||
'execution_no': execution.execution_no,
|
||||
'gate_code': updated_gate.gate_code,
|
||||
'action_code': action,
|
||||
'responsible_party': definition.get('responsible_party'),
|
||||
'dispatch': 'sync',
|
||||
'attempt': {
|
||||
'id': int(attempt.id),
|
||||
'attempt_no': int(attempt.attempt_no),
|
||||
'status': attempt.status,
|
||||
'idempotency_key': attempt.idempotency_key,
|
||||
},
|
||||
'gate_status': updated_gate.status,
|
||||
'gate_evaluation_version': int(updated_gate.evaluation_version),
|
||||
'next_action_code': updated_gate.next_action_code,
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
"""
|
||||
services/shipping_notice/process_gate_service.py
|
||||
|
||||
用途:门禁推进、结果提交与下游失效的唯一写入入口。
|
||||
依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract、process_gate_dependency、
|
||||
fulfillment_audit、workflow_ledger_service。
|
||||
逻辑:创建 Execution 与全部门禁行;queue_gate_attempt 按幂等键复用前校验
|
||||
Execution/Gate/action/输入指纹;状态变更与 Attempt 结果、Execution 指针、
|
||||
下游失效、审计在同一事务提交;禁止业务路径绕过本服务改 Gate 状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_RECOVERABLE_STATUSES,
|
||||
get_process_gate_definition,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates
|
||||
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
"""naive UTC,与模型默认一致。"""
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _stable_hash(value: Any) -> str:
|
||||
"""对受控快照生成 SHA-256。"""
|
||||
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def _new_execution_no() -> str:
|
||||
"""生成业务可读 Execution 编号。"""
|
||||
return f"SPE-{_utc_now().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _locked_execution(execution_no: str) -> ShippingProcessExecution:
|
||||
"""按 execution_no 行锁加载 Execution。"""
|
||||
row = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(execution_no=str(execution_no or '').strip().upper())
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _locked_gate(*, execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate:
|
||||
"""按 gate_code 行锁加载门禁。"""
|
||||
code = str(gate_code or '').strip()
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code=code)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
return gate
|
||||
|
||||
|
||||
def _assert_idempotent_replay_matches(
|
||||
*,
|
||||
replay: ShippingProcessGateAttempt,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
action_code: str | None,
|
||||
input_snapshot: dict[str, Any] | None,
|
||||
) -> None:
|
||||
"""
|
||||
校验幂等键命中的 Attempt 与当前请求属于同一 Execution/Gate/Action。
|
||||
|
||||
核心逻辑:同键仅允许「相同请求」复用;跨 Execution、跨 Gate、跨 action_code
|
||||
或输入指纹不一致时抛 ConflictError,禁止误复用其他上下文的 Attempt。
|
||||
|
||||
Args:
|
||||
replay: 已存在的 Attempt。
|
||||
execution_no: 本次请求的 Execution 编号。
|
||||
gate_code: 本次请求的门禁编码。
|
||||
action_code: 本次请求的动作码(可空,表示未声明)。
|
||||
input_snapshot: 本次请求输入快照;双方均有 hash 时额外比对。
|
||||
|
||||
Raises:
|
||||
ConflictError: 上下文不一致。
|
||||
NotFoundError: Attempt 关联的 Gate/Execution 丢失。
|
||||
"""
|
||||
gate = db.session.get(ShippingProcessGate, int(replay.gate_id))
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
|
||||
expected_execution = str(execution_no or '').strip().upper()
|
||||
actual_execution = str(execution.execution_no or '').strip().upper()
|
||||
expected_gate = str(gate_code or '').strip()
|
||||
actual_gate = str(gate.gate_code or '').strip()
|
||||
stored_snapshot = replay.input_snapshot_json if isinstance(replay.input_snapshot_json, dict) else {}
|
||||
stored_action = str(stored_snapshot.get('action_code') or '').strip() or None
|
||||
requested_action = str(action_code or '').strip() or None
|
||||
|
||||
mismatches: list[str] = []
|
||||
if expected_execution and actual_execution != expected_execution:
|
||||
mismatches.append('execution_no')
|
||||
if expected_gate and actual_gate != expected_gate:
|
||||
mismatches.append('gate_code')
|
||||
if requested_action != stored_action:
|
||||
# 任一方声明了 action 且不一致即冲突;双方皆空则视为未声明动作,允许复用。
|
||||
if requested_action is not None or stored_action is not None:
|
||||
mismatches.append('action_code')
|
||||
if input_snapshot is not None and replay.input_snapshot_hash:
|
||||
if _stable_hash(input_snapshot) != str(replay.input_snapshot_hash):
|
||||
mismatches.append('input_fingerprint')
|
||||
|
||||
if mismatches:
|
||||
raise ConflictError(
|
||||
'Idempotency key conflicts with a different gate request',
|
||||
code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT',
|
||||
details={'mismatched_fields': mismatches, 'idempotency_key': replay.idempotency_key},
|
||||
)
|
||||
|
||||
|
||||
def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
"""
|
||||
根据 Gate 列表重算 Execution 当前门禁与主恢复动作。
|
||||
|
||||
核心逻辑:取第一个非 passed/skipped 门禁为 current;全部通过则 completed。
|
||||
"""
|
||||
gates = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc())
|
||||
.all()
|
||||
)
|
||||
last_passed = None
|
||||
current = None
|
||||
for gate in gates:
|
||||
if gate.status == 'passed':
|
||||
last_passed = gate.gate_code
|
||||
continue
|
||||
if gate.status == 'skipped':
|
||||
continue
|
||||
current = gate
|
||||
break
|
||||
execution.last_passed_gate_code = last_passed
|
||||
if current is None:
|
||||
execution.current_gate_code = None
|
||||
execution.primary_next_action_code = None
|
||||
execution.responsible_party = None
|
||||
if execution.status not in {'cancelled', 'failed'}:
|
||||
execution.status = 'completed'
|
||||
return
|
||||
execution.current_gate_code = current.gate_code
|
||||
execution.primary_next_action_code = current.next_action_code
|
||||
definition = get_process_gate_definition(current.gate_code)
|
||||
execution.responsible_party = str(definition.get('responsible_party') or '') or None
|
||||
if current.status == 'waiting_external':
|
||||
execution.status = 'waiting_external'
|
||||
elif current.status in {'blocked_retryable', 'blocked_manual', 'invalidated', 'failed_terminal'}:
|
||||
execution.status = 'blocked'
|
||||
elif execution.status in {'completed', 'cancelled', 'failed'}:
|
||||
execution.status = 'active'
|
||||
else:
|
||||
execution.status = 'active'
|
||||
|
||||
|
||||
def ensure_execution_for_workflow_version(
|
||||
*,
|
||||
workflow_item_id: int,
|
||||
workflow_item_version_id: int,
|
||||
review_case_id: int | None = None,
|
||||
task_id: int | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
start_gate_code: str = 'document_materialization',
|
||||
) -> ShippingProcessExecution:
|
||||
"""
|
||||
为 WorkflowItemVersion 幂等创建 Execution 与全部门禁行。
|
||||
|
||||
核心逻辑:同一 version 仅一个 Execution;已存在则绑定 review_case/task 指针后返回。
|
||||
|
||||
Args:
|
||||
workflow_item_id / workflow_item_version_id: 台账外键。
|
||||
review_case_id / task_id: 建单前/后可选绑定。
|
||||
actor_type / actor_id: 创建审计主体。
|
||||
start_gate_code: 首个待执行门禁;之前门禁标记 skipped。
|
||||
|
||||
Returns:
|
||||
ShippingProcessExecution。
|
||||
"""
|
||||
existing = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(workflow_item_version_id=int(workflow_item_version_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if review_case_id and existing.review_case_id is None:
|
||||
existing.review_case_id = int(review_case_id)
|
||||
if task_id and existing.task_id is None:
|
||||
existing.task_id = int(task_id)
|
||||
existing.updated_at = _utc_now()
|
||||
db.session.flush()
|
||||
return existing
|
||||
|
||||
now = _utc_now()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no=_new_execution_no(),
|
||||
workflow_item_id=int(workflow_item_id),
|
||||
workflow_item_version_id=int(workflow_item_version_id),
|
||||
review_case_id=int(review_case_id) if review_case_id else None,
|
||||
task_id=int(task_id) if task_id else None,
|
||||
status='active',
|
||||
lock_version=1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
start_seq = get_process_gate_definition(start_gate_code)['sequence_no']
|
||||
for item in PROCESS_GATE_DEFINITIONS:
|
||||
seq = int(item['sequence_no'])
|
||||
code = str(item['gate_code'])
|
||||
if seq < start_seq:
|
||||
status = 'skipped'
|
||||
next_action = None
|
||||
elif seq == start_seq:
|
||||
status = 'pending'
|
||||
next_action = None
|
||||
else:
|
||||
status = 'pending'
|
||||
next_action = None
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id),
|
||||
gate_code=code,
|
||||
sequence_no=seq,
|
||||
status=status,
|
||||
evaluation_version=1,
|
||||
next_action_code=next_action,
|
||||
lock_version=1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
))
|
||||
db.session.flush()
|
||||
_refresh_execution_pointers(execution)
|
||||
record_fulfillment_audit(
|
||||
event_type='process_execution_created',
|
||||
aggregate_type='process_execution',
|
||||
aggregate_id=str(execution.execution_no),
|
||||
action='create_execution',
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'rpa', 'chatflow', 'admin'} else 'system',
|
||||
actor_id=actor_id,
|
||||
workflow_item_id=None,
|
||||
before=None,
|
||||
after={
|
||||
'execution_no': execution.execution_no,
|
||||
'status': execution.status,
|
||||
'gate_code': execution.current_gate_code,
|
||||
'lifecycle_status': execution.status,
|
||||
},
|
||||
metadata={'workflow_item_id': int(workflow_item_id), 'workflow_item_version_id': int(workflow_item_version_id)},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return execution
|
||||
|
||||
|
||||
def bind_execution_task(
|
||||
*,
|
||||
execution_no: str,
|
||||
task_id: int,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessExecution:
|
||||
"""建单后绑定 ShippingTask;幂等覆盖空 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')
|
||||
execution.task_id = int(task_id)
|
||||
execution.updated_at = _utc_now()
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
db.session.flush()
|
||||
return execution
|
||||
|
||||
|
||||
def queue_gate_attempt(
|
||||
*,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
trigger_type: str,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
idempotency_key: str,
|
||||
expected_gate_version: int | None = None,
|
||||
input_snapshot: dict[str, Any] | None = None,
|
||||
rule_snapshot: dict[str, Any] | None = None,
|
||||
) -> ShippingProcessGateAttempt:
|
||||
"""
|
||||
为指定门禁创建 queued Attempt;同幂等键重放首次结果。
|
||||
|
||||
Raises:
|
||||
ConflictError: 版本冲突或已有活动 Attempt。
|
||||
ValidationError: 门禁不可恢复。
|
||||
"""
|
||||
key = str(idempotency_key or '').strip()
|
||||
if not key:
|
||||
raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED')
|
||||
requested_action = None
|
||||
if isinstance(input_snapshot, dict):
|
||||
requested_action = str(input_snapshot.get('action_code') or '').strip() or None
|
||||
|
||||
replay = ShippingProcessGateAttempt.query.filter_by(idempotency_key=key).first()
|
||||
if replay is not None:
|
||||
# [STEP] 幂等复用前校验 Execution / Gate / action 一致,防止跨上下文误复用。
|
||||
_assert_idempotent_replay_matches(
|
||||
replay=replay,
|
||||
execution_no=str(execution_no or '').strip(),
|
||||
gate_code=str(gate_code or '').strip(),
|
||||
action_code=requested_action,
|
||||
input_snapshot=input_snapshot,
|
||||
)
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_idempotent_replay',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(replay.id),
|
||||
action='idempotent_replay',
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'admin', 'worker'} else 'system',
|
||||
actor_id=actor_id,
|
||||
result='ignored',
|
||||
before={'status': replay.status, 'gate_code': gate_code, 'idempotency_key': key},
|
||||
after={'status': replay.status, 'gate_code': gate_code, 'idempotency_key': key, 'attempt_no': replay.attempt_no},
|
||||
metadata={'execution_no': execution_no},
|
||||
source='process_gate',
|
||||
)
|
||||
return replay
|
||||
|
||||
execution = _locked_execution(execution_no)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
if expected_gate_version is not None and int(gate.evaluation_version) != int(expected_gate_version):
|
||||
raise ConflictError('Process gate version mismatch', code='SHIPPING.PROCESS_GATE_VERSION_MISMATCH')
|
||||
if gate.status not in PROCESS_GATE_RECOVERABLE_STATUSES | {'pending', 'queued'}:
|
||||
if gate.status in {'running'}:
|
||||
raise ConflictError('Process gate already running', code='SHIPPING.PROCESS_GATE_BUSY')
|
||||
if gate.status == 'passed':
|
||||
raise ValidationError('Process gate already passed', code='SHIPPING.PROCESS_GATE_ALREADY_PASSED')
|
||||
|
||||
active = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if active is not None:
|
||||
raise ConflictError('Process gate already has an active attempt', code='SHIPPING.PROCESS_GATE_BUSY')
|
||||
|
||||
last = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(gate_id=int(gate.id))
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
attempt_no = int(last.attempt_no) + 1 if last else 1
|
||||
now = _utc_now()
|
||||
attempt = ShippingProcessGateAttempt(
|
||||
gate_id=int(gate.id),
|
||||
attempt_no=attempt_no,
|
||||
status='queued',
|
||||
trigger_type=str(trigger_type or 'auto'),
|
||||
actor_type=str(actor_type or 'system'),
|
||||
actor_id=str(actor_id) if actor_id is not None else None,
|
||||
idempotency_key=key,
|
||||
input_snapshot_json=dict(input_snapshot or {}) or None,
|
||||
input_snapshot_hash=_stable_hash(input_snapshot or {}) if input_snapshot is not None else None,
|
||||
rule_snapshot_json=dict(rule_snapshot or {}) or None,
|
||||
rule_snapshot_hash=_stable_hash(rule_snapshot or {}) if rule_snapshot is not None else None,
|
||||
created_at=now,
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
|
||||
before_status = gate.status
|
||||
gate.status = 'queued'
|
||||
gate.next_action_code = primary_next_action_for_gate(gate_code=gate.gate_code, status='queued')
|
||||
gate.latest_attempt_id = int(attempt.id)
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_recovery_requested',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
action=str(trigger_type or 'recovery'),
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'admin', 'worker'} else 'system',
|
||||
actor_id=actor_id,
|
||||
before={'status': before_status, 'gate_code': gate.gate_code, 'draft_version': None},
|
||||
after={
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'attempt_no': attempt_no,
|
||||
'idempotency_key': key,
|
||||
'execution_no': execution.execution_no,
|
||||
'next_action_code': gate.next_action_code,
|
||||
},
|
||||
metadata={'trigger_type': trigger_type},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def mark_attempt_running(
|
||||
*,
|
||||
attempt_id: int,
|
||||
worker_id: str | None = None,
|
||||
lease_token: str | None = None,
|
||||
lease_expires_at: datetime | None = None,
|
||||
) -> ShippingProcessGateAttempt:
|
||||
"""将 Attempt 置为 running 并写入租约字段。"""
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
raise ConflictError('Attempt is not runnable', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE')
|
||||
now = _utc_now()
|
||||
attempt.status = 'running'
|
||||
attempt.worker_id = str(worker_id)[:64] if worker_id else attempt.worker_id
|
||||
attempt.lease_token = str(lease_token)[:64] if lease_token else attempt.lease_token
|
||||
attempt.lease_expires_at = lease_expires_at
|
||||
attempt.heartbeat_at = now
|
||||
attempt.started_at = attempt.started_at or now
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
gate.status = 'running'
|
||||
gate.updated_at = now
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is not None:
|
||||
_refresh_execution_pointers(execution)
|
||||
execution.updated_at = now
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_attempt_started',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(attempt.id),
|
||||
action='start_attempt',
|
||||
actor_type='worker' if worker_id else 'system',
|
||||
actor_id=worker_id,
|
||||
before={'status': 'queued', 'gate_code': gate.gate_code},
|
||||
after={'status': 'running', 'gate_code': gate.gate_code, 'attempt_no': attempt.attempt_no},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def complete_gate_attempt(
|
||||
*,
|
||||
attempt_id: int,
|
||||
outcome: str,
|
||||
output_snapshot: dict[str, Any] | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
blocking_reason_json: dict[str, Any] | None = None,
|
||||
recommendation_json: dict[str, Any] | None = None,
|
||||
effective_result_json: dict[str, Any] | None = None,
|
||||
error_code: str | None = None,
|
||||
error_summary: str | None = None,
|
||||
invalidate_change_type: str | None = None,
|
||||
) -> ShippingProcessGate:
|
||||
"""
|
||||
提交 Attempt 终态并更新 Gate / Execution;可选触发下游失效。
|
||||
|
||||
Args:
|
||||
outcome: passed / blocked_retryable / blocked_manual / waiting_external / failed_terminal。
|
||||
invalidate_change_type: 若通过且需失效下游,传入依赖图变化类型。
|
||||
"""
|
||||
allowed = {
|
||||
'passed', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
|
||||
}
|
||||
if outcome not in allowed:
|
||||
raise ValidationError('Invalid gate attempt outcome', code='SHIPPING.PROCESS_GATE_OUTCOME_INVALID')
|
||||
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
|
||||
# 不可变:终态 Attempt 拒绝覆盖业务结果。
|
||||
raise ConflictError('Attempt already finished', code='SHIPPING.PROCESS_GATE_ATTEMPT_IMMUTABLE')
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
raise ConflictError('Attempt is not active', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE')
|
||||
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(id=int(attempt.gate_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(id=int(gate.execution_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
|
||||
now = _utc_now()
|
||||
before = {
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'blocking_reason_code': gate.blocking_reason_code,
|
||||
}
|
||||
attempt.output_snapshot_json = dict(output_snapshot or {}) or None
|
||||
attempt.output_snapshot_hash = _stable_hash(output_snapshot or {}) if output_snapshot is not None else None
|
||||
attempt.finished_at = now
|
||||
attempt.error_code = str(error_code)[:64] if error_code else None
|
||||
# [STEP] 持久化前脱敏,避免 URL/路径/连接信息进入 Attempt 与后续投影。
|
||||
attempt.error_summary = sanitize_gate_error_text(error_summary, max_len=2000)
|
||||
# waiting_external 表示 Attempt 本身成功完成并进入外部等待,不应记为 failed。
|
||||
attempt.status = 'succeeded' if outcome in {'passed', 'waiting_external'} else 'failed'
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
|
||||
gate.status = outcome
|
||||
gate.blocking_reason_code = str(blocking_reason_code)[:64] if blocking_reason_code else None
|
||||
reason_payload = dict(blocking_reason_json or {}) or None
|
||||
if isinstance(reason_payload, dict) and reason_payload.get('message') is not None:
|
||||
reason_payload['message'] = sanitize_gate_error_text(reason_payload.get('message'), max_len=500)
|
||||
gate.blocking_reason_json = reason_payload
|
||||
gate.recommendation_json = dict(recommendation_json or {}) or None
|
||||
result_payload = dict(effective_result_json or {})
|
||||
# [STEP] 首次进入外部等待时写入 waiting_since,供超时轮询判定。
|
||||
if outcome == 'waiting_external' and not result_payload.get('waiting_since'):
|
||||
prev = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {}
|
||||
result_payload['waiting_since'] = prev.get('waiting_since') or now.isoformat()
|
||||
gate.effective_result_json = result_payload or None
|
||||
gate.next_action_code = primary_next_action_for_gate(gate_code=gate.gate_code, status=outcome)
|
||||
gate.latest_attempt_id = int(attempt.id)
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
if outcome == 'passed':
|
||||
gate.passed_at = now
|
||||
gate.invalidated_at = None
|
||||
gate.blocking_reason_code = None
|
||||
|
||||
invalidated: list[str] = []
|
||||
if outcome == 'passed' and invalidate_change_type:
|
||||
invalidated = list(invalidate_downstream_gates(
|
||||
execution=execution,
|
||||
change_type=str(invalidate_change_type),
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
))
|
||||
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
|
||||
event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked'
|
||||
record_fulfillment_audit(
|
||||
event_type=event_type,
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
action=outcome,
|
||||
actor_type='system',
|
||||
result='success' if outcome == 'passed' else 'failure',
|
||||
error_code=attempt.error_code,
|
||||
before=before,
|
||||
after={
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'attempt_no': attempt.attempt_no,
|
||||
'blocking_reason_code': gate.blocking_reason_code,
|
||||
'next_action_code': gate.next_action_code,
|
||||
'execution_no': execution.execution_no,
|
||||
'invalidated_downstream_gates': invalidated,
|
||||
},
|
||||
metadata={'outcome': outcome},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return gate
|
||||
|
||||
|
||||
def invalidate_downstream_gates(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
change_type: str,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
将依赖图指定的下游已通过门禁标记为 invalidated。
|
||||
|
||||
Returns:
|
||||
实际失效的 gate_code 列表。
|
||||
"""
|
||||
targets = set(compute_invalidated_gates(change_type))
|
||||
if not targets:
|
||||
return []
|
||||
now = _utc_now()
|
||||
invalidated: list[str] = []
|
||||
gates = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc())
|
||||
.all()
|
||||
)
|
||||
for gate in gates:
|
||||
if gate.gate_code not in targets:
|
||||
continue
|
||||
if gate.status not in {'passed', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external'}:
|
||||
continue
|
||||
before = gate.status
|
||||
gate.status = 'invalidated'
|
||||
gate.invalidated_at = now
|
||||
gate.next_action_code = primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='invalidated',
|
||||
) or 'retry_with_latest_rules'
|
||||
# invalidated 默认动作:多数门禁走 blocked_retryable 语义;若契约无显式项则置 pending 重跑入口。
|
||||
if gate.next_action_code is None:
|
||||
gate.next_action_code = primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='blocked_retryable',
|
||||
)
|
||||
gate.blocking_reason_code = 'gate_invalidated'
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
invalidated.append(gate.gate_code)
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_downstream_invalidated',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
action='invalidate',
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'admin'} else 'system',
|
||||
actor_id=actor_id,
|
||||
before={'status': before, 'gate_code': gate.gate_code},
|
||||
after={
|
||||
'status': 'invalidated',
|
||||
'gate_code': gate.gate_code,
|
||||
'blocking_reason_code': 'gate_invalidated',
|
||||
'execution_no': execution.execution_no,
|
||||
},
|
||||
metadata={'change_type': change_type},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return invalidated
|
||||
|
||||
|
||||
def sync_gate_from_business_result(
|
||||
*,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
passed: bool,
|
||||
effective_result_json: dict[str, Any] | None = None,
|
||||
recommendation_json: dict[str, Any] | None = None,
|
||||
blocking_reason_code: str | None = None,
|
||||
blocking_reason_json: dict[str, Any] | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
invalidate_change_type: str | None = None,
|
||||
allow_repass: bool = True,
|
||||
outcome: str | None = None,
|
||||
) -> ShippingProcessGate:
|
||||
"""
|
||||
业务路径(如复核库存重路由)将结果同步进 Gate:创建 Attempt 并 complete。
|
||||
|
||||
核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。
|
||||
已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。
|
||||
|
||||
Args:
|
||||
invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。
|
||||
allow_repass: 允许对已通过门禁重新评估。
|
||||
outcome: 可选显式 Attempt 结果(如 waiting_external);缺省由 passed/reason 推导。
|
||||
"""
|
||||
key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}'
|
||||
execution = _locked_execution(execution_no)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
if allow_repass and gate.status == 'passed':
|
||||
gate.status = 'invalidated'
|
||||
gate.invalidated_at = _utc_now()
|
||||
gate.blocking_reason_code = 'gate_invalidated'
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = _utc_now()
|
||||
db.session.flush()
|
||||
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution_no,
|
||||
gate_code=gate_code,
|
||||
trigger_type='user_manual' if actor_type == 'user' else 'auto',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=key,
|
||||
input_snapshot=effective_result_json,
|
||||
rule_snapshot=recommendation_json,
|
||||
)
|
||||
if attempt.status in {'succeeded', 'failed'}:
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
return gate
|
||||
mark_attempt_running(attempt_id=int(attempt.id), worker_id='inline-sync')
|
||||
allowed_outcomes = {
|
||||
'passed', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
|
||||
}
|
||||
if outcome and str(outcome) in allowed_outcomes:
|
||||
outcome = str(outcome)
|
||||
else:
|
||||
outcome = 'passed' if passed else (
|
||||
'blocked_manual' if blocking_reason_code else 'blocked_retryable'
|
||||
)
|
||||
resolved_invalidate = invalidate_change_type
|
||||
if resolved_invalidate is None and passed and gate_code == 'inventory_source_routing':
|
||||
resolved_invalidate = 'inventory_source_changed'
|
||||
return complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome=outcome,
|
||||
output_snapshot=effective_result_json,
|
||||
blocking_reason_code=blocking_reason_code,
|
||||
blocking_reason_json=blocking_reason_json,
|
||||
recommendation_json=recommendation_json,
|
||||
effective_result_json=effective_result_json,
|
||||
invalidate_change_type=resolved_invalidate,
|
||||
)
|
||||
@@ -4,7 +4,8 @@ services/shipping_notice/progress_audit_contract.py
|
||||
用途:冻结货代发货通知进度审计与 Workflow(批次/PDF 项)领域契约词典。
|
||||
依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。
|
||||
逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期、模板评分/
|
||||
通用解析/LLM 建议/人工裁决事件码、审计事件字典与敏感键黑名单的唯一代码源;
|
||||
通用解析/LLM 建议/人工裁决事件码、全门禁(Process Gate)恢复审计事件码、
|
||||
审计事件字典与敏感键黑名单的唯一代码源;
|
||||
UI 与 Worker 行为变更在后续阶段接线,本模块只冻结名称与规则。
|
||||
SESSION_* 别名保留供过渡期测试引用。
|
||||
"""
|
||||
@@ -102,6 +103,27 @@ WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
# 过渡期别名。
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = WORKFLOW_ITEM_AUDIT_EVENT_TYPES
|
||||
|
||||
# 全门禁中断恢复(ShippingProcessExecution / Gate / Attempt)审计事件字典。
|
||||
# 阶段 1 仅冻结事件码;写路径与投影在后续阶段接线,禁止前端或 Worker 私自发明事件名。
|
||||
PROCESS_GATE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'process_execution_created',
|
||||
'process_gate_created',
|
||||
'process_gate_attempt_started',
|
||||
'process_gate_passed',
|
||||
'process_gate_blocked',
|
||||
'process_gate_recovery_requested',
|
||||
'process_gate_idempotent_replay',
|
||||
'process_gate_manual_override',
|
||||
'process_gate_rule_suggestion_generated',
|
||||
'process_gate_suggestion_adopted',
|
||||
'process_gate_suggestion_rejected',
|
||||
'process_gate_downstream_invalidated',
|
||||
'process_gate_technical_retry',
|
||||
'process_gate_lease_taken_over',
|
||||
'process_gate_artifact_superseded',
|
||||
'process_gate_permission_denied',
|
||||
})
|
||||
|
||||
# 字段派生 / 人工覆盖 / 规则模拟 / Excel 导出等项次相关审计事件词典(语义分组)。
|
||||
# 自 2026-07-30 起:货代统一审计账本全部事件永久保留;本集合仅作事件分类引用。
|
||||
LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -343,6 +365,25 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'export_artifact_no',
|
||||
'template_version',
|
||||
'field_code',
|
||||
'candidate_inventory_source_codes',
|
||||
'raw_rule_source_codes',
|
||||
'rule_suggestion_source_codes',
|
||||
'unavailable_source_codes',
|
||||
'rule_versions',
|
||||
'selection_mode',
|
||||
'suggestion_pending',
|
||||
'idempotency_key',
|
||||
'action_semantics',
|
||||
'line_keys',
|
||||
'routing_status',
|
||||
# Process Gate 恢复摘要(禁止正文、规则 SQL、对象存储 URL)。
|
||||
'gate_code',
|
||||
'attempt_no',
|
||||
'execution_no',
|
||||
'next_action_code',
|
||||
'blocking_reason_code',
|
||||
'input_fingerprint',
|
||||
'responsible_party',
|
||||
})
|
||||
|
||||
# 四语言 i18n key 清单(阶段 2 补齐文案;此处仅冻结路径,禁止前端硬编码)。
|
||||
|
||||
@@ -3,9 +3,10 @@ services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
|
||||
state_machine(CheckpointKind)、tool_response。
|
||||
state_machine(CheckpointKind)、tool_response、process_gate_bridge。
|
||||
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
|
||||
STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内;
|
||||
退出前将 Task 履约状态同步到统一 Process Gate(13–19);
|
||||
系统触发时事件 actor_id=None 且 detail.source=system。
|
||||
"""
|
||||
|
||||
@@ -110,6 +111,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_sync_process_gates_after_progress(task, payload)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
@@ -203,14 +205,20 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inv = ensure_inventory(inv_payload)
|
||||
if inv.get("status") == "running":
|
||||
steps.append("等待库存准备")
|
||||
_sync_process_gates_after_progress(task, payload)
|
||||
return inv
|
||||
if inv.get("status") != "ok":
|
||||
_sync_process_gates_after_progress(task, payload)
|
||||
return inv
|
||||
else:
|
||||
steps.append("载入库存")
|
||||
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进(止于 Excel 就绪)。
|
||||
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
|
||||
|
||||
# [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。
|
||||
_sync_process_gates_after_progress(task, payload)
|
||||
|
||||
if fulfillment_result is not None:
|
||||
return fulfillment_result
|
||||
|
||||
@@ -221,3 +229,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=f"自动推进已完成{suffix}",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
|
||||
def _sync_process_gates_after_progress(task: Any, payload: dict[str, Any]) -> None:
|
||||
"""
|
||||
auto_progress 结束后把 Task 状态桥接到统一门禁。
|
||||
|
||||
核心逻辑:存在 Execution 时必须同步成功;失败向上抛出,避免 Workflow/Task 与 Gate 双真相。
|
||||
尚无 Execution(历史任务)时跳过,不阻断推进。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 实例。
|
||||
payload: 原自动推进载荷(取 operator)。
|
||||
"""
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return
|
||||
actor_id = payload.get('operator_id') or payload.get('user_id')
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
actor_id=actor_id,
|
||||
)
|
||||
db.session.flush()
|
||||
@@ -2,9 +2,12 @@
|
||||
services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract。
|
||||
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract、
|
||||
process_gate_projection(统一 Gate 用户摘要)。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts);
|
||||
若存在 ProcessExecution 且当前有 blocking Gate,则清空 action_buttons,
|
||||
恢复动作仅由 process_gate 驱动(Gate 为唯一业务真相);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
@@ -546,13 +549,35 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
构建单票任务 UI State。
|
||||
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
|
||||
禁止 Chat、通知卡与任务中心分别推导状态。
|
||||
禁止 Chat、通知卡与任务中心分别推导状态;有 Execution 时附带统一 Gate 用户摘要;
|
||||
存在 current_blocking_gate 时清空 STP action_buttons,恢复仅走 process_gate。
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = _action_buttons_for_task(task)
|
||||
process_gate = _process_gate_user_summary_for_task(task)
|
||||
# [STEP] Gate 阻断时旧 action_buttons 不再作为业务恢复真相,避免双卡片/双动作。
|
||||
if isinstance(process_gate, dict) and process_gate.get('current_blocking_gate'):
|
||||
action_buttons = []
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint)
|
||||
current_index = _derive_current_step_index(task)
|
||||
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
|
||||
summary = _build_task_summary(
|
||||
task,
|
||||
ui.checkpoint,
|
||||
checkpoint_kind=ui.checkpoint_kind,
|
||||
action_buttons=action_buttons,
|
||||
)
|
||||
if process_gate is not None:
|
||||
summary['process_gate'] = process_gate
|
||||
# 仅输出当前 Gate;删除旧门禁重复摘要键(若历史调用方写入)。
|
||||
summary.pop('auto_build_gates', None)
|
||||
summary.pop('failed_gates', None)
|
||||
if process_gate.get('blocking_message'):
|
||||
summary['current_blocking_message'] = process_gate['blocking_message']
|
||||
if process_gate.get('diagnostic_hint'):
|
||||
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
|
||||
if process_gate.get('current_blocking_gate'):
|
||||
summary['allowed_actions'] = []
|
||||
return {
|
||||
"task_no": task.task_no,
|
||||
"batch_no": task.batch.batch_no if task.batch is not None else None,
|
||||
@@ -564,17 +589,34 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
"match_status": task.match_status,
|
||||
"current_step": current_step,
|
||||
"steps": steps,
|
||||
"summary": _build_task_summary(
|
||||
task,
|
||||
ui.checkpoint,
|
||||
checkpoint_kind=ui.checkpoint_kind,
|
||||
action_buttons=action_buttons,
|
||||
),
|
||||
"summary": summary,
|
||||
"action_buttons": action_buttons,
|
||||
"process_gate": process_gate,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _process_gate_user_summary_for_task(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
按 Task 查找活动 Execution 的用户 Gate 摘要。
|
||||
|
||||
Returns:
|
||||
project_user_gate_summary;无 Execution 时 None。
|
||||
"""
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
return project_user_gate_summary(execution)
|
||||
|
||||
|
||||
def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
|
||||
"""
|
||||
构建批次级会话上传集合摘要(非履约写操作面)。
|
||||
|
||||
@@ -3,11 +3,12 @@ services/shipping_notice/workflow_progress_projection.py
|
||||
|
||||
用途:将 Workflow / WorkflowItem / WorkflowEvent 投影为工作台只读 DTO(计数、阶段、摘要)。
|
||||
依赖:ShippingNoticeWorkflow* 模型、ShippingNoticeDocument、ShippingOrderExtractionRun、
|
||||
workflow_ledger_service、progress_audit_contract。
|
||||
workflow_ledger_service、progress_audit_contract、process_gate_projection。
|
||||
逻辑:由 workspace/shipping_notice 工作流读接口调用;解决「Run 已建但 Item=0」——
|
||||
Item 在版面阶段即存在;会话投影返回全部 open Workflow(非仅第一条);
|
||||
counts.waiting_manual_upload 单独统计,不得并入 completed;
|
||||
available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导。
|
||||
available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导;
|
||||
用户提示优先消费统一 Gate 摘要(唯一当前阻断),不再平行拼旧五门禁文案。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -224,7 +225,8 @@ def serialize_workflow_item(
|
||||
序列化 WorkflowItem 用户态投影。
|
||||
|
||||
核心逻辑:附带当前/根 Document 文件名,供工作台列表直接展示 PDF 名;
|
||||
附带 available_actions / reparse_kind,供前端按权威契约展示按钮。
|
||||
附带 available_actions / reparse_kind,供前端按权威契约展示按钮;
|
||||
若存在活动 ProcessExecution,附带统一 Gate 用户摘要(唯一阻断)。
|
||||
|
||||
Args:
|
||||
item: WorkflowItem ORM。
|
||||
@@ -261,6 +263,14 @@ def serialize_workflow_item(
|
||||
'available_actions': available_actions,
|
||||
'reparse_kind': reparse_kind,
|
||||
}
|
||||
gate_summary = _process_gate_user_summary_for_item(item)
|
||||
if gate_summary is not None:
|
||||
payload['process_gate'] = gate_summary
|
||||
# 工作台提示只展示当前唯一阻断,避免旧检查点平行文案。
|
||||
if gate_summary.get('blocking_message'):
|
||||
payload['gate_user_hint'] = gate_summary.get('blocking_message')
|
||||
elif gate_summary.get('diagnostic_hint'):
|
||||
payload['gate_user_hint'] = gate_summary.get('diagnostic_hint')
|
||||
if include_events:
|
||||
events = (
|
||||
ShippingNoticeWorkflowEvent.query
|
||||
@@ -272,6 +282,26 @@ def serialize_workflow_item(
|
||||
return payload
|
||||
|
||||
|
||||
def _process_gate_user_summary_for_item(item: ShippingNoticeWorkflowItem) -> dict[str, Any] | None:
|
||||
"""
|
||||
按 WorkflowItem 当前版本查找活动 Execution 的用户 Gate 摘要。
|
||||
|
||||
Returns:
|
||||
project_user_gate_summary 结果;无 Execution 时 None。
|
||||
"""
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
version_id = getattr(item, 'current_version_id', None)
|
||||
query = ShippingProcessExecution.query.filter_by(workflow_item_id=int(item.id))
|
||||
if version_id is not None:
|
||||
query = query.filter_by(workflow_item_version_id=int(version_id))
|
||||
execution = query.order_by(ShippingProcessExecution.id.desc()).first()
|
||||
if execution is None:
|
||||
return None
|
||||
return project_user_gate_summary(execution)
|
||||
|
||||
|
||||
def serialize_workflow(
|
||||
workflow: ShippingNoticeWorkflow,
|
||||
*,
|
||||
|
||||
Reference in new issue
Block a user