refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

+1 -1
View File
@@ -141,7 +141,7 @@ def openapi_spec():
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
def checkpoint_catalog():
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
"""返回检查点目录,供开发联调和文档核对 human_options;业务按钮以 ui_state.actions 为准。"""
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
return jsonify(build_checkpoint_catalog())
+11 -5
View File
@@ -124,7 +124,6 @@ def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
user = _require_user()
batch_no = str(request.args.get('batch_no') or '').strip() or None
process_status = str(request.args.get('process_status') or '').strip() or None
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
try:
page = int(request.args.get('page') or 1)
@@ -136,7 +135,6 @@ def workspace_shipping_tasks():
return _ok(list_tasks_page_for_user(
user.id,
batch_no=batch_no,
process_status=process_status,
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
@@ -647,8 +645,7 @@ def workspace_create_shipping_task_from_notice():
task_no=task_id,
)
if not intake.accepted:
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
task = ShippingNotice.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = intake.text
@@ -697,7 +694,7 @@ def workspace_shipping_task_detail(task_no: str):
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
@@ -2841,6 +2838,15 @@ def workspace_preview_shipping_order_review_document(case_no: str):
)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
user = _require_user()
from app.services.shipping_notice.order_review_evidence_service import get_case_email_evidence_text
return _ok(get_case_email_evidence_text(user_id=user.id, case_no=case_no, document_id=document_id))
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
"""确认当前用户已加载终态订单识别卡片;写入已读状态变更审计。"""
@@ -242,16 +242,21 @@ def _pending_snapshot_batches(run: ShippingOrderProcessingRun, plan: ShippingOrd
def _should_expand_after_wave(*, wave_units: list[ShippingOrderProcessingUnit], wave_orders: list[dict]) -> bool:
"""仅在可通过更多附件补证的业务缺口出现时才扩下一轮。"""
"""兼容旧诊断调用:返回本轮业务缺口,不能作为兄弟附件执行门控。"""
return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders))
def _should_activate_planned_batches(*, pending_batches: list[int]) -> bool:
"""计划内后续附件必须独立执行,不受首轮字段结果或兄弟附件状态门控。"""
return bool(pending_batches)
def _expansion_trigger_reason_codes(
*,
wave_units: list[ShippingOrderProcessingUnit],
wave_orders: list[dict],
) -> list[str]:
"""汇总当前批次触发扩批的业务原因码,供事件与工作台共享。"""
"""汇总当前批次业务缺口原因,供事件、交叉裁决与工作台共享。"""
if not wave_units:
return []
reason_codes = {
@@ -318,7 +323,7 @@ def _mark_expandable_business_gaps(
*,
orders: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""把可由后续附件补证的业务缺口标记到订单上,供扩批决策复用。"""
"""标记跨附件裁决可补证的业务缺口;该事实不影响附件执行。"""
field_ids_by_code = _schema_field_ids_by_code(run)
reservation_field_ids = field_ids_by_code.get('reservation_id', set())
if not reservation_field_ids:
@@ -340,7 +345,7 @@ def _wave_orders_for_expansion(
*,
orders: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""为当前批次生成扩批判定所需的业务事实视图。"""
"""为当前批次生成交叉附件裁决所需的业务事实视图。"""
if not orders:
return []
schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {}
@@ -804,7 +809,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders)
next_existing_batch = _next_existing_batch(plan, after_batch=current_batch)
if expansion_reason_codes and next_existing_batch is not None:
if next_existing_batch is not None:
source_batch = current_batch
current_batch = next_existing_batch
if current_batch not in expansion_events_emitted:
@@ -817,6 +822,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'unit_count': len(_units_for_batch(plan, selection_batch=current_batch)),
'triggered_by_batch': source_batch,
'reason_codes': expansion_reason_codes,
'activation_reason': 'planned_attachment_batch',
},
job_id=job.id,
commit=False,
@@ -826,7 +832,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
continue
pending_batches = _pending_snapshot_batches(run, plan)
if expansion_reason_codes and pending_batches:
if _should_activate_planned_batches(pending_batches=pending_batches):
next_batch = pending_batches[0]
created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch)
db.session.flush()
@@ -841,6 +847,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'unit_count': len(_units_for_batch(plan, selection_batch=next_batch)),
'triggered_by_batch': current_batch,
'reason_codes': expansion_reason_codes,
'activation_reason': 'planned_attachment_batch',
},
job_id=job.id,
commit=False,
+1 -3
View File
@@ -51,7 +51,6 @@ class ShippingNotice(Base):
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_notices_user_status', 'user_id', 'process_status'),
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
@@ -191,7 +190,6 @@ class ShippingNotice(Base):
index=True,
)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
@@ -217,7 +215,7 @@ class ShippingNotice(Base):
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 任务处置与流程状态正交:process_status 继续驱动履约工作流,生命周期负责作废/归档。
# 任务处置与业务阶段正交:生命周期负责作废/归档。
lifecycle_status: Mapped[str] = mapped_column(
String(16),
nullable=False,
@@ -32,7 +32,7 @@ AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = (
'upload_receipt_recorded',
)
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'})
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
def audit_legacy_forwarded_entrypoint(
@@ -59,8 +59,8 @@ def _utc_now() -> datetime:
def _task_is_cancelled(task: ShippingNotice) -> bool:
"""根据服务端 Task 事实判断取消/关闭任务,旧 Job 不得将其复活。"""
return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES
"""根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。"""
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES
def _recover_stale_active_job(job: Job) -> bool:
@@ -27,7 +27,6 @@ logger = logging.getLogger(__name__)
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
_TERMINAL_TASK_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
def normalize_create_idempotency_key(raw: str | None) -> str | None:
@@ -203,7 +202,7 @@ def assert_no_exact_duplicate_notices(
query = ShippingNotice.query.filter(
ShippingNotice.user_id == user_id,
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
ShippingNotice.lifecycle_status == 'active',
)
if skipped_ids:
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -30,7 +30,6 @@ from app.services.shipping_notice.tools import auto_progress, submit_decision
_RUNNING_BATCHES: set[str] = set()
_RUNNING_TASKS: set[str] = set()
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
def batch_orchestrator_enabled() -> bool:
@@ -69,21 +68,19 @@ def _should_orchestrate_task(task: Any) -> bool:
if not task_is_active(task):
return False
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if process_status in _TERMINAL_PROCESS_STATUSES:
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
return False
if getattr(task, "review_status", None):
return False
if (
process_status == "waiting_inventory"
and not getattr(task, "inventory_lines_json", None)
not getattr(task, "inventory_lines_json", None)
and pending_reason in {"", PH_RPA_PENDING}
):
return True
if getattr(task, "pending_human_reason", None):
return False
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}:
return False
return True
@@ -94,13 +91,12 @@ def _is_retryable_task(task: Any) -> bool:
if not task_is_active(task):
return False
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if process_status in _TERMINAL_PROCESS_STATUSES:
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
return False
if getattr(task, "review_status", None):
return False
if process_status == "waiting_inventory" and pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
return True
if getattr(task, "pending_human_reason", None):
return False
@@ -139,7 +135,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {
"status": "skipped",
"message": (
f"skip process_status={task.process_status or ''}"
f"skip stage={getattr(task, 'current_step', '') or ''}"
f" pending_human_reason={task.pending_human_reason or ''}"
f" review_status={task.review_status or ''}"
),
@@ -151,16 +147,14 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
log_task_event(
task,
"backend_orchestrator_task_started",
{"process_status": task.process_status, "current_step": task.current_step},
{"current_step": task.current_step, "lifecycle_status": task.lifecycle_status},
)
db.session.commit()
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
process_status = str(task.process_status or "").strip().lower()
pending_reason = str(task.pending_human_reason or "").strip().lower()
if (
process_status == "waiting_inventory"
and not getattr(task, "inventory_lines_json", None)
not getattr(task, "inventory_lines_json", None)
and pending_reason == PH_RPA_PENDING
):
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
@@ -176,8 +170,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
str(result.get("message") or "")[:300],
)
elif (
process_status == "waiting_inventory"
and not getattr(task, "inventory_lines_json", None)
not getattr(task, "inventory_lines_json", None)
and pending_reason == ""
):
payload["mode"] = "auto"
@@ -189,7 +182,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
result.get("status"),
str(result.get("message") or "")[:300],
)
elif process_status == "created":
elif not getattr(task, "current_order_extraction_id", None):
# [STEP] 复核/STP 确认建单后任务仍为 created,但已挂正式 Extraction;须走 auto_progress。
# 无抽取的历史壳任务仍停在人工,避免误入 Chatflow。
if getattr(task, "current_order_extraction_id", None):
@@ -206,10 +199,9 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
result = auto_progress(payload)
if current_app:
current_app.logger.info(
"[shipping-orchestrator] auto-progress task_no=%s status=%s process_status_before=%s current_step_before=%s message=%s",
"[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
task.task_no,
result.get("status"),
task.process_status,
task.current_step,
str(result.get("message") or "")[:300],
)
@@ -221,7 +213,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
"backend_orchestrator_task_finished",
{
"result_status": str(result.get("status") or ""),
"process_status": refreshed.process_status,
"lifecycle_status": refreshed.lifecycle_status,
"current_step": refreshed.current_step,
},
)
@@ -353,9 +345,8 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
if not _is_retryable_task(task):
skipped += 1
continue
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None):
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
@@ -366,7 +357,7 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
else:
skipped += 1
continue
if process_status == "waiting_inventory" and pending_reason == PH_RPA_EXHAUSTED:
if pending_reason == PH_RPA_EXHAUSTED:
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
status = str(result.get("status") or "").strip().lower()
if status in {"ok", "running", "needs_human"}:
@@ -76,17 +76,22 @@ def _format_decision_message(decision: str, result: dict[str, Any], task_no: str
def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any]:
"""构建匹配结果展示 payload;按钮统一来自后端 ui_state.actions。"""
data = result.get("data") if isinstance(result.get("data"), dict) else {}
line_results = data.get("line_results") if isinstance(data.get("line_results"), list) else []
shortage = data.get("shortage") if isinstance(data.get("shortage"), dict) else {}
shortage_lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
action_buttons = result.get("action_buttons") if isinstance(result.get("action_buttons"), list) else []
ui_state = result.get("ui_state") if isinstance(result.get("ui_state"), dict) else {}
actions = ui_state.get("actions") if isinstance(ui_state.get("actions"), dict) else {
"primary": None,
"secondary": [],
}
return {
"taskId": task_no,
"match_status": data.get("match_status"),
"line_results": line_results,
"shortage_lines": shortage_lines,
"action_buttons": action_buttons,
"actions": actions,
}
@@ -39,27 +39,26 @@ def build_chat_actions_payload(task) -> dict:
构建聊天气泡侧动作按钮兼容 payload。
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
action_buttons 已由 ui_state 在存在 ProcessExecution 时按 Gate 规则收缩(阻断清零)。
业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。
Args:
task: ShippingNotice 模型实例。
Returns:
包含 task_no、checkpoint、process_gate、action_buttons 与摘要的字典。
包含 task_no、checkpoint、process_gate、actions 与摘要的字典。
"""
state = build_task_ui_state(task)
return {
"task_no": state.get("task_no"),
"batch_no": state.get("batch_no"),
"checkpoint": state.get("checkpoint"),
"process_status": state.get("process_status"),
"review_status": state.get("review_status"),
"pending_human_reason": state.get("pending_human_reason"),
"match_status": state.get("match_status"),
"current_step": state.get("current_step"),
"stage": state.get("stage"),
"todo": state.get("todo"),
"actions": state.get("actions"),
"reason": state.get("reason"),
"lifecycle_status": state.get("lifecycle_status"),
"summary": state.get("summary"),
"process_gate": state.get("process_gate"),
"action_buttons": state.get("action_buttons") or [],
"updated_at": state.get("updated_at"),
}
@@ -47,7 +47,7 @@ CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
# Derived UI checkpoints (no separate pending_human_reason; from domain facts)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
@@ -441,7 +441,7 @@ def correct_numbered_task_customer(
code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING",
)
if any(
version.process_status == "uploaded"
str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}
or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"}
for version in versions
):
@@ -520,7 +520,6 @@ def correct_numbered_task_customer(
latest.upload_error_message = None
latest.upload_receipt_json = None
latest.idempotency_key = None
latest.process_status = "parsed"
latest.current_step = None
latest.review_status = None
latest.pending_human_reason = None
@@ -245,10 +245,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
decision == "confirm_parse"
or task.review_status == RS_PARSE_REVIEW
or task.pending_human_reason == PH_LOW_CONF
or (
task.process_status in {"parsed", "pending_review", "created"}
and not match_completed(task)
)
or not match_completed(task)
):
parse_validation = (
(task.step_payload_json or {}).get("parse_validation")
@@ -395,9 +392,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
if task.process_status == "waiting_inventory" or (
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
):
if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
@@ -406,7 +401,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
if task.inventory_lines_json or task.process_status == "inventory_ready":
if task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
@@ -351,11 +351,6 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
else {}
)
document = db.session.get(ShippingOrderDocument, int(cand.primary_document_id))
action_buttons: list[str] = []
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
action_buttons.extend(['edit', 'evidence', 'reject'])
if cand.validation_status == 'ready' and not blocking:
action_buttons.append('promote')
return {
'candidate_no': cand.candidate_no,
'primary_document_id': cand.primary_document_id,
@@ -370,7 +365,6 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
'acceptance_reason': cand.acceptance_reason,
'acceptance_policy_version': cand.acceptance_policy_version,
'extraction_source': cand.extraction_source,
'action_buttons': action_buttons,
'selected': bool(cand.selected),
'business_fingerprint': cand.business_fingerprint,
'fingerprint_strength': cand.fingerprint_strength,
@@ -32,41 +32,22 @@ from app.services.shipping_notice.business_fingerprint import (
)
from app.services.shipping_notice.reservation_id import validated_reservation_id
# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
_ACTIVE_PROCESS_STATUSES = frozenset(
{
'created',
'parsed',
'pending_review',
'inventory_ready',
'waiting_inventory',
'matched',
'waiting_upload',
'upload_failed',
}
)
_COMPLETED_PROCESS_STATUSES = frozenset({'uploaded', 'completed'})
_CLOSED_PROCESS_STATUSES = frozenset({'closed', 'rejected'})
_IRREVERSIBLE_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed', 'rejected'})
def classify_task_lifecycle(process_status: str | None) -> str:
"""将 process_status 归类为 active / completed / closed / unknown。"""
status = str(process_status or '').strip().lower()
if status in _ACTIVE_PROCESS_STATUSES:
return 'active'
if status in _COMPLETED_PROCESS_STATUSES:
return 'completed'
if status in _CLOSED_PROCESS_STATUSES:
def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str:
"""根据生命周期/上传结果事实归类 active / completed / closed。"""
if task is None:
return 'unknown'
get = task.get if isinstance(task, dict) else lambda key, default=None: getattr(task, key, default)
lifecycle = str(get('lifecycle_status', '') or '').strip().lower()
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
return 'closed'
return 'unknown'
upload = str(get('upload_status', '') or '').strip().lower()
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'):
return 'completed'
return 'active'
def is_irreversible_task(task: ShippingNotice) -> bool:
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
status = str(task.process_status or '').strip().lower()
if status in _IRREVERSIBLE_PROCESS_STATUSES:
return True
upload_status = str(task.upload_status or '').strip().lower()
return upload_status in {'uploaded', 'succeeded', 'success'}
@@ -74,11 +55,10 @@ def is_irreversible_task(task: ShippingNotice) -> bool:
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
return {
'task_no': task.task_no,
'process_status': task.process_status,
'document_version': int(task.document_version or 1),
'match_type': match_type,
'matched_fields': list(matched_fields),
'lifecycle': classify_task_lifecycle(task.process_status),
'lifecycle': classify_task_lifecycle(task),
'created_at': utc_iso(task.created_at),
'content_fingerprint': task.content_fingerprint,
'content_fingerprint_version': task.content_fingerprint_version,
@@ -181,7 +161,7 @@ def detect_duplicates_for_intake(
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
ShippingNotice.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(10)
@@ -235,7 +215,7 @@ def detect_duplicates_for_intake(
else 'possible_revision'
)
else:
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
primary_life = str(matches[0].get('lifecycle') or 'unknown')
if primary_life == 'active':
status = 'same_active_task'
elif primary_life == 'completed':
@@ -253,7 +233,7 @@ def detect_duplicates_for_intake(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
ShippingNotice.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(5)
@@ -521,7 +501,7 @@ def detect_duplicates_for_candidate(
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
ShippingNotice.lifecycle_status == 'active',
)
)
if skipped_ids:
@@ -574,7 +554,7 @@ def detect_duplicates_for_candidate(
else 'possible_revision'
)
else:
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
primary_life = str(matches[0].get('lifecycle') or 'unknown')
if primary_life == 'active':
status = 'same_active_task'
elif primary_life == 'completed':
@@ -588,7 +568,7 @@ def detect_duplicates_for_candidate(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
ShippingNotice.lifecycle_status == 'active',
)
)
if skipped_ids:
@@ -572,12 +572,12 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'),
'manual_upload_pending': _meta('owner', 'regenerate_manual_upload_todo', '请下载 Excel 后在货代平台上传并登记结果'),
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'),
'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'),
'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'),
'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'),
'upload_platform_rejected': _meta('owner', 'retry_freight_upload_rpa', '货代平台拒绝上传,请核对文件后重试'),
'upload_result_unknown': _meta('owner', 'regenerate_manual_upload_todo', '上传结果暂时无法确认'),
'upload_result_unknown': _meta('owner', 'mark_manual_uploaded', '上传结果暂时无法确认'),
'review_required': _meta('owner', 'open_order_review', '需要人工复核后才能继续'),
'gate_invalidated': _meta('system', 'recheck_freeze_readiness', '上游结果已变化,当前门禁需重新评估'),
'technical_failure_present': _meta('system', 'open_order_review', '存在技术失败,需处理后继续'),
@@ -595,7 +595,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'),
'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'),
'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'),
'close_blocked_missing_receipt': _meta('owner', 'regenerate_manual_upload_todo', '缺少上传回执,暂不可关闭'),
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'),
'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'),
'excel_downloaded': _meta('owner', '', '已下载发货 Excel'),
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
@@ -116,7 +116,6 @@ def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
return {
'task_no': str(task.task_no),
'lifecycle_status': str(task.lifecycle_status or ''),
'process_status': str(task.process_status or ''),
'export_file_name': task.export_file_name,
'void_reason': task.void_reason,
'pending_human_reason': task.pending_human_reason,
@@ -532,8 +532,8 @@ def _trigger_freight_upload_rpa(
actor_type='system',
task_no=task.task_no,
conversation_id=task.conversation_id,
before={'process_status': 'waiting_upload'},
after={'process_status': str(task.process_status or ''), 'pending_human_reason': 'upload_rpa_pending'},
before={'upload_status': str(task.upload_status or '')},
after={'upload_status': str(task.upload_status or 'pending'), 'pending_human_reason': 'upload_rpa_pending'},
metadata={'attempt_id': int(attempt.id), 'artifact_id': int(attempt.artifact_id)},
source='system',
)
@@ -678,7 +678,7 @@ def _match_step_progress_fields(
def excel_gate_error(task: ShippingNotice) -> str | None:
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
if task.process_status == "uploaded" and task.export_file_path:
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path:
return None
if not match_completed(task):
return "workflow.fulfillment.excel_gate_unmatched"
@@ -742,7 +742,7 @@ def try_auto_chain_after_match(
db.session.refresh(task)
ui = resolve_task_ui_state(task)
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
task.export_file_path and task.process_status != "uploaded"
task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded'
)
if excel_ready and _auto_upload_enabled():
upload_result = upload_to_freight({
@@ -1970,7 +1970,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
operator_id = payload.get('operator_id')
evidence_asset_no = str(payload.get('evidence_asset_no') or '')
freight_ref_no = str(payload.get('freight_ref_no') or '')
before_status = str(task.process_status or '')
before_upload_status = str(task.upload_status or '')
try:
attempt = record_manual_upload(
task,
@@ -2000,8 +2000,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
task_no=task.task_no,
conversation_id=task.conversation_id,
reason_code='task_closed_after_upload',
before={'process_status': before_status or 'waiting_upload'},
after={'process_status': str(task.process_status or 'uploaded')},
before={'upload_status': before_upload_status or 'pending'},
after={'upload_status': str(task.upload_status or 'uploaded')},
metadata={
'attempt_id': attempt.id,
'artifact_id': attempt.artifact_id,
@@ -2034,8 +2034,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
human_options=[] if task.process_status == 'uploaded' else None,
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
)
@@ -2194,8 +2194,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
human_options=[] if task.process_status == 'uploaded' else None,
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
)
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
@@ -2255,7 +2255,7 @@ def run_auto_progress_fulfillment_steps(
# [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。
ui = resolve_task_ui_state(task)
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
task.export_file_path and task.process_status != "uploaded"
task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded'
)
if excel_ready and _auto_upload_enabled():
steps.append("触发货代上传 RPA")
@@ -714,6 +714,7 @@ def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[
与 cancel 同序持锁再改 Candidate,避免并发删除导致 StaleDataError/死锁。
"""
from app.services.shipping_notice.duplicate_detection import (
classify_task_lifecycle,
refresh_candidates_and_aggregate_intake,
)
from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
@@ -810,7 +811,10 @@ def resolve_intake_duplicate(
)
# 目标状态相对检测结果漂移
match_row = next((m for m in matches if str(m.get('task_no') or '').upper() == target_no), None)
if match_row and str(match_row.get('process_status') or '') != str(target_task.process_status or ''):
if match_row and (
str(match_row.get('lifecycle') or '').strip().lower()
!= str(classify_task_lifecycle(target_task) or '').strip().lower()
):
raise ConflictError(
code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED',
message='目标任务状态已变化,请重新确认',
@@ -32,12 +32,10 @@ from app.services.shipping_notice.inventory_source_gate import (
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
def _can_relink_inventory(task: ShippingNotice) -> bool:
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
return str(task.process_status or "").strip().lower() not in _TERMINAL_PROCESS_STATUSES
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
def _safe_ref(value: str) -> str:
@@ -551,7 +549,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
task = link.task
if not link.is_active or not task:
continue
if task.task_no in task_nos and task.process_status in {"inventory_ready", "parsed", "waiting_inventory"}:
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
set_task_step_progress(
task,
step_key="step5_match_inventory",
@@ -270,7 +270,6 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
"""
if (
task.pending_human_reason != PH_RPA_PENDING
or task.process_status != "waiting_inventory"
or task.inventory_lines_json
):
return None, None, None
@@ -1167,7 +1166,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
task.review_status = None
task.error_message = None
task.current_step = "step3_inventory_prepare"
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的 process_status / phase。
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的领域事实 / phase。
log_task_event(
task,
"inventory_source_confirmed",
@@ -1296,7 +1295,6 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
timeout_seconds = rpa_inventory_timeout_seconds()
if (
task.pending_human_reason == PH_RPA_PENDING
and task.process_status == "waiting_inventory"
and not task.inventory_lines_json
):
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
@@ -2492,7 +2490,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
**(inv_file.schema_preview_json or {}),
'structure_validation': column_meta['structure_validation'],
}
if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
if lines and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
inventory_loaded_response(
task,
lines,
@@ -37,7 +37,6 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
@@ -143,7 +142,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
if gate_resp is not None:
return gate_resp
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
return tool_response(
status="failed",
task=task,
@@ -51,7 +51,7 @@ def _post_op(
"200": {
"description": (
"Tool response (status: ok|running|needs_human|failed). "
"May include checkpoint, human_options, action_buttons."
"May include checkpoint and human_options; business buttons are exposed only by ui_state.actions."
),
"content": {
"application/json": {
@@ -1366,7 +1366,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version,
content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version,
document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text,
customer_resolution_status='pending', process_status='created', current_order_extraction_id=int(extraction.id),
customer_resolution_status='pending', current_order_extraction_id=int(extraction.id),
)
db.session.add(task)
db.session.flush()
@@ -1579,8 +1579,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
"""
判断确认建单后的任务是否仍需自动推进。
核心逻辑:已挂正式 Extraction,且仍停在确认后早期态(created / parsed)。
确认路径会先 CONFIRM_PARSE→parsed,故不得仅认 created,否则永远不会入队。
核心逻辑:已挂正式 Extraction,且仍未进入库存/通知事实链路。
重复调度依赖 enqueue 幂等(同 business_ref 有效 Job 不重复入队)。
Args:
@@ -1593,9 +1592,13 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
return False
if not getattr(task, 'current_order_extraction_id', None):
return False
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
# created:尚未 CONFIRM_PARSE;parsed:刚确认仍待库存推进。
return process_status in {'', 'created', 'parsed'}
return not bool(
getattr(task, 'inventory_snapshot_id', None)
or getattr(task, 'inventory_lines_json', None)
or getattr(task, 'match_status', None)
or getattr(task, 'export_file_path', None)
or getattr(task, 'upload_status', None)
)
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
@@ -403,6 +403,12 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
for line_index, line in enumerate(orders[0].get('lines') or []):
if isinstance(line, dict):
fields.extend({**field, '_line_index': line_index} for field in line.get('fields') or [] if isinstance(field, dict))
case_document = db.session.get(ShippingOrderDocument, int(case.document_id))
intake_id = int(case_document.intake_id) if case_document is not None else None
intake_document_types = {
int(document.id): str(document.document_type or '').strip()
for document in ShippingOrderDocument.query.filter_by(intake_id=intake_id).all()
}
items: list[dict[str, Any]] = []
for field in fields:
if not isinstance(field, dict):
@@ -457,11 +463,22 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
cell_id = (
str(observation.get('cell_id') or layout_evidence.get('cell_id') or '')[:128] or None
)
evidence_document_id = observation.get('document_id') or layout_evidence.get('document_id')
try:
evidence_document_id = int(evidence_document_id) if evidence_document_id is not None else int(case.document_id)
except (TypeError, ValueError):
evidence_document_id = int(case.document_id)
# Observation 只能引用同一 Intake 的受控 Document;异常引用安全回退到当前 Case PDF。
if evidence_document_id not in intake_document_types:
evidence_document_id = int(case.document_id)
items.append({
'evidence_id': f"{field.get('field_id') or 'field'}:{field.get('_line_index', 'header')}:{index}",
'field_id': str(field.get('field_id') or ''),
'line_index': field.get('_line_index'),
'machine_value': observation.get('value'),
'document_id': evidence_document_id,
'document_type': intake_document_types.get(evidence_document_id) or 'attachment',
'source_type': str(observation.get('source_type') or '')[:64] or None,
'quote': quote,
'page_no': resolved_page,
'table_id': table_id,
@@ -572,3 +589,23 @@ def get_case_pdf_bytes(*, user_id: int, case_no: str) -> tuple[bytes, str]:
if mime_type != 'application/pdf' and not str(document.filename or '').lower().endswith('.pdf'):
raise ConflictError('Review document is not a PDF', code='SHIPPING.REVIEW_PREVIEW_INVALID')
return read_asset_bytes(asset), str(document.filename or 'document.pdf').replace('\n', '').replace('\r', '')[:255]
def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int) -> dict[str, Any]:
"""返回同一 Intake 邮件正文的已解析文本,禁止读取原始 EML、附件或存储地址。"""
case = get_user_review_case(user_id=user_id, case_no=case_no)
case_document = db.session.get(ShippingOrderDocument, int(case.document_id))
document = db.session.get(ShippingOrderDocument, int(document_id))
if (
case_document is None
or document is None
or int(document.intake_id) != int(case_document.intake_id)
or str(document.document_type or '') != 'email_body'
):
raise NotFoundError('Email evidence preview is unavailable', code='SHIPPING.REVIEW_EVIDENCE_PREVIEW_NOT_FOUND')
return {
'document_id': int(document.id),
'document_type': 'email_body',
'filename': str(document.filename or 'email.eml')[:255],
'text': str(document.extracted_text or '')[:20_000],
}
@@ -82,7 +82,7 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
'needs_retry': False,
'status': 'task_missing',
'message': '正式任务关联异常,请联系管理员',
'task_process_status': None,
'task_progress_state': None,
'job_id': None,
'error_code': 'task_missing',
'recovery_available': False,
@@ -113,7 +113,7 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
else '任务自动推进进行中或已完成'
)
),
'task_process_status': auto.get('task_process_status'),
'task_progress_state': auto.get('task_progress_state'),
'job_id': auto.get('job_id'),
'error_code': auto.get('error_code'),
'reason_code': auto.get('reason_code'),
@@ -123,7 +123,6 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
'recovery_available': False if formal_ot.get('task_missing') else None,
}
def _stp_waiting_timeout_seconds() -> int:
"""STP waiting_to_start 超时秒数(服务端配置,禁止前端硬编码)。"""
try:
@@ -159,9 +158,9 @@ def _project_case_automation_status(
投影用户可见的自动建单/推进状态;资格达标不等于正在推进。
核心逻辑:
- 已有正式 OT:只消费 post_confirm / OT process_status(禁止再读 STP 主态)
- 已有正式 OT:只消费 post_confirm / OT 领域事实(禁止再读 STP 主态)
- post_confirm needs_retry → failed(可重试)
- 正式 OT + process_status created/空 → waiting_to_start(无 Job)或 queued
- 正式 OT + 尚无领域事实 → waiting_to_start(无 Job)或 queued
- 无正式 OT:查 STP Job queued/running/failed;can_auto_create 未入队 → waiting_to_start
- phase / owner_type 由 enrich_automation_status 在 serialize 时补齐
@@ -181,7 +180,7 @@ def _project_case_automation_status(
can_build = bool((validation or {}).get('can_build'))
formal_ot = resolve_formal_ot(case)
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读 process_status。
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读旧字段。
if formal_ot.get('has_formal_ot') or formal_ot.get('task_missing') or (
isinstance(post_confirm, dict) and (
post_confirm.get('task_no') or str(post_confirm.get('status') or '') == 'task_missing'
@@ -875,7 +874,7 @@ def serialize_review_case(
'label_key': 'task_missing',
'source': 'formal_ot',
'inconsistent': True,
'process_status': None,
'progress_state': None,
'current_step': None,
'stage_node': None,
}
@@ -418,7 +418,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
Returns:
status / retryable / job_id / error_code / needs_retry / reason_code /
task_no / task_process_status / completed_at。
task_no / task_progress_state / completed_at。
"""
if task is None:
return {
@@ -428,7 +428,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'job_id': None,
'error_code': None,
'task_no': None,
'task_process_status': None,
'task_progress_state': None,
'attempts': None,
'max_attempts': None,
'completed_at': None,
@@ -436,7 +436,14 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
}
task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
else 'not_started'
)
active = find_active_shipping_notice_run_job(task_no=task_no or '')
latest = active or find_latest_shipping_notice_run_job(task_no=task_no or '')
@@ -504,7 +511,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'retryable': False,
'needs_retry': False,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': None,
**_job_fields(active),
}
@@ -520,13 +527,13 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'retryable': True,
'needs_retry': True,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': fields.get('error_code') or 'auto_progress_job_failed',
**fields,
}
if latest_status in {'succeeded', 'success', 'completed'}:
# Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。
if process_status in {'', 'created'}:
if progress_state in {'', 'not_started'}:
exhausted = _attempts_exhausted(latest)
reason = 'auto_progress_job_succeeded_but_task_not_advanced'
return {
@@ -534,7 +541,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'retryable': True,
'needs_retry': True,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': reason,
'error_code': reason,
'job_id': fields['job_id'],
@@ -547,29 +554,29 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'retryable': False,
'needs_retry': False,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': None,
**fields,
}
# [STEP 3] 无 Job:created → waiting_to_start;其余按 OT 态,禁止仅凭 process_status 伪装 running。
if process_status in {'', 'created'}:
# [STEP 3] 无 Job:尚无领域事实 → waiting_to_start;其余按 OT 态。
if progress_state in {'', 'not_started'}:
return {
'status': 'waiting_to_start',
'retryable': False,
'needs_retry': False,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': 'auto_progress_not_enqueued_yet',
**_job_fields(None),
}
if process_status in {'completed', 'closed', 'done', 'uploaded'}:
if progress_state in {'completed', 'closed', 'done', 'uploaded'}:
return {
'status': 'completed',
'retryable': False,
'needs_retry': False,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': None,
**_job_fields(None),
}
@@ -579,7 +586,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'retryable': False,
'needs_retry': False,
'task_no': task_no,
'task_process_status': process_status,
'task_progress_state': progress_state,
'reason_code': 'auto_progress_not_enqueued_yet',
**_job_fields(None),
}
@@ -602,7 +609,7 @@ def project_stage_for_task(
default_code: 无 OT 时的阶段码。
Returns:
{code, label_key, source, inconsistent, process_status, current_step, stage_node}
{code, label_key, source, inconsistent, progress_state, current_step, stage_node}
"""
if task is None:
return {
@@ -610,7 +617,7 @@ def project_stage_for_task(
'label_key': default_code,
'source': 'fallback',
'inconsistent': False,
'process_status': None,
'progress_state': None,
'current_step': None,
'stage_node': None,
}
@@ -621,7 +628,14 @@ def project_stage_for_task(
map_notice_to_processing_status_stage,
)
process_status = str(getattr(task, 'process_status', None) or '').strip().lower() or None
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
else 'not_started'
)
current_step = str(getattr(task, 'current_step', None) or '').strip() or None
def _with_label(code: str, *, source: str) -> dict[str, Any]:
@@ -632,14 +646,14 @@ def project_stage_for_task(
'label_key': label_key,
'source': source,
'inconsistent': False,
'process_status': process_status,
'progress_state': progress_state,
'current_step': current_step,
'stage_node': None,
}
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。
if process_status in {'uploaded', 'closed', 'completed'}:
if progress_state in {'uploaded', 'closed', 'completed'}:
return _with_label('completed', source='notice_terminal')
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
@@ -662,19 +676,19 @@ def project_stage_for_task(
# [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。
# Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。
if ot_stage == 'order_creating':
if process_status in {'waiting_inventory', 'parsed', 'fetching_inventory', 'inventory_fetching'}:
if progress_state in {'inventory_ready'}:
return _with_label('inventory_fetching', source='notice_inventory')
if process_status in {'inventory_ready', 'matching', 'matched'}:
if progress_state in {'matched', 'export_ready'}:
_status, mapped = map_notice_to_processing_status_stage(task)
code = str(mapped or 'inventory_matching').strip() or 'inventory_matching'
return _with_label(code, source='notice_map')
if process_status in {None, '', 'created'}:
if progress_state in {None, '', 'not_started'}:
return _with_label('inventory_fetching', source='post_ot_inventory')
return _with_label(ot_stage, source='order_task')
# [STEP 2] Notice 尚停在 created:统一 order_creating(与 Progress 词典同源,禁止冒充库存匹配)。
if process_status in {None, '', 'created'}:
return _with_label('order_creating', source='process_status')
# [STEP 2] Notice 尚无履约领域事实:统一 order_creating。
if progress_state in {None, '', 'not_started'}:
return _with_label('order_creating', source='domain_facts')
# [STEP 3] 领域映射(与 sync_order_task_stage_for_notice 同源)。
_status, stage = map_notice_to_processing_status_stage(task)
@@ -587,7 +587,7 @@ def per_source_callback_handler(
# [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态)
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses:
if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or str(getattr(task, 'upload_status', '') or '').strip().lower() in {'uploaded', 'succeeded', 'success'}:
attempt.status = 'superseded'
attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal')
attempt.callback_payload_json = dict(callback_payload or {})
@@ -37,6 +37,30 @@ from app.services.shipping_notice.process_gate_service import (
_LOGGER = logging.getLogger(__name__)
def _derived_fulfillment_status(task: ShippingNotice) -> str:
"""从领域结果事实推导履约分支,不读取旧流程状态字段。"""
pending = str(getattr(task, 'pending_human_reason', None) or '').strip()
if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}:
return 'waiting_inventory'
if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
return 'waiting_upload'
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if upload_status in {'uploaded', 'succeeded', 'success'}:
return 'uploaded'
if upload_status == 'failed':
return 'upload_failed'
if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json:
return 'shortage_review'
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
if match_status in {'fulfillable', 'partial', 'unfulfillable'}:
return 'matched'
if str(getattr(task, 'export_file_path', None) or '').strip():
return 'inventory_ready'
if isinstance(getattr(task, 'inventory_lines_json', None), list) and task.inventory_lines_json:
return 'inventory_ready'
return 'created'
def inventory_preparation_reason_code(task: ShippingNotice) -> str:
"""
由任务事实推导库存准备门禁阻断原因码。
@@ -125,7 +149,7 @@ def manual_upload_reason_code(task: ShippingNotice) -> str:
)
pending = str(task.pending_human_reason or '').strip()
status = str(task.process_status or '').strip()
status = _derived_fulfillment_status(task)
if pending == PH_UPLOAD_RPA_PENDING:
return 'upload_rpa_pending'
if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed':
@@ -687,7 +711,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
if (
str(task.process_status or '').strip() != 'waiting_inventory'
_derived_fulfillment_status(task) != 'waiting_inventory'
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
):
return
@@ -744,7 +768,7 @@ def sync_fulfillment_gates_from_task(
"""
按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。
核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果;
核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果;
RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断
manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
@@ -769,13 +793,13 @@ def sync_fulfillment_gates_from_task(
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()
status = _derived_fulfillment_status(task)
match_status = str(task.match_status or '').strip()
has_export = bool(str(task.export_file_path or '').strip())
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
inv_file = active_inventory_file_for_task(task)
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
# [STEP 1] 优先读匹配/短缺实体;process_status 仅作库存准备与上传阶段辅助。
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
done_statuses = {'uploaded', 'closed'}
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
sufficiency_ok = match_completed(task)
@@ -812,7 +836,7 @@ def sync_fulfillment_gates_from_task(
# [STEP 2] inventory_preparation — 等待与失败使用细粒度原因码 + Finding 事实
task_facts = {
'process_status': status or None,
'derived_fulfillment_status': status or None,
'task_no': str(task.task_no or '') or None,
'has_inventory_lines': has_inventory_lines,
}
@@ -883,7 +907,7 @@ def sync_fulfillment_gates_from_task(
pending_reason = str(task.pending_human_reason or '').strip()
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或次数耗尽时
# 必须退出自动处理中,回到可恢复 Gate,不能因 process_status 相同再次自动入队。
# 必须退出自动处理中,回到可恢复 Gate,不能因同一等待事实再次自动入队。
if pending_reason == PH_RPA_PENDING:
outcome = 'waiting_external'
waiting_reason = 'inventory_rpa_queued'
@@ -904,7 +928,7 @@ def sync_fulfillment_gates_from_task(
reason_code=waiting_reason,
details=task_facts,
),
'process_status': status,
'derived_fulfillment_status': status,
},
blocking_reason_code=waiting_reason,
actor_type=actor_type,
@@ -928,7 +952,7 @@ def sync_fulfillment_gates_from_task(
details=task_facts,
)
),
'process_status': status,
'derived_fulfillment_status': status,
'has_inventory_lines': has_inventory_lines,
},
blocking_reason_code=inv_prep_reason,
@@ -1109,7 +1133,7 @@ def sync_fulfillment_gates_from_task(
uploaded = status in done_statuses
upload_reason = None if uploaded else manual_upload_reason_code(task)
task_details = {
'process_status': status or None,
'derived_fulfillment_status': status or None,
'task_no': str(task.task_no or '') or None,
}
if uploaded:
@@ -1117,7 +1141,7 @@ def sync_fulfillment_gates_from_task(
execution=execution,
gate_code='freight_upload_rpa',
passed=True,
effective_result={'process_status': status, 'findings': []},
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:passed',
@@ -1127,7 +1151,7 @@ def sync_fulfillment_gates_from_task(
execution=execution,
gate_code='manual_upload_handoff',
passed=True,
effective_result={'process_status': status, 'findings': []},
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:passed',
@@ -1153,7 +1177,7 @@ def sync_fulfillment_gates_from_task(
reason_code=str(upload_reason),
details=task_details,
),
'process_status': status,
'derived_fulfillment_status': status,
},
blocking_reason_code=upload_reason,
actor_type=actor_type,
@@ -1169,7 +1193,7 @@ def sync_fulfillment_gates_from_task(
gate_code='freight_upload_rpa',
passed=True,
effective_result={
'process_status': status,
'derived_fulfillment_status': status,
'findings': [],
'handoff': 'manual_upload',
},
@@ -1189,7 +1213,7 @@ def sync_fulfillment_gates_from_task(
reason_code=str(upload_reason or 'manual_upload_pending'),
details=task_details,
),
'process_status': status,
'derived_fulfillment_status': status,
},
blocking_reason_code=upload_reason or 'manual_upload_pending',
actor_type=actor_type,
@@ -313,7 +313,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'implementation_status': 'implemented',
'recoverable': True,
'default_next_actions': {
'blocked_manual': 'regenerate_manual_upload_todo',
'blocked_manual': 'mark_manual_uploaded',
'waiting_external': None,
},
},
@@ -363,6 +363,8 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'poll_freight_upload_rpa',
'retry_freight_upload_rpa',
'regenerate_manual_upload_todo',
# 仅驱动前端打开人工上传凭据登记;不得通过普通 Gate POST 直接确认。
'mark_manual_uploaded',
})
# Gate 卡只展示服务端冻结合同中的动作码。每次点击仍受 Workspace API 的
@@ -141,6 +141,10 @@ def execute_queued_attempt(
action = str(snapshot.get('action_code') or gate.next_action_code or '').strip()
payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {}
payload = {**payload, 'action_code': action, 'attempt_id': int(attempt.id)}
# Attempt 创建时记录的 actor 是 Gate Worker 的最后可信操作人来源;
# 客户端 payload 未携带 actor_user_id 时仍必须传给订单冻结/审计链。
if getattr(attempt, 'actor_id', None) is not None:
payload.setdefault('actor_user_id', attempt.actor_id)
if attempt.recovery_plan_id:
payload.setdefault('recovery_plan_id', int(attempt.recovery_plan_id))
@@ -354,7 +358,10 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
return {
'task_id': str(task.task_no),
'source': 'process_gate',
'operator_id': payload.get('actor_user_id') or payload.get('user_id'),
# Gate Attempt 的调用方可能来自 Worker(operator_id)或 Workspace(actor_user_id)。
# 统一注入两种字段,避免正式库存重试冻结订单快照时丢失操作人。
'operator_id': payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id'),
'actor_user_id': payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id'),
'_orchestrator_internal_dispatch': True,
}
@@ -817,10 +824,15 @@ def _handle_retry_inventory_preparation(
outcome = _tool_outcome(
action_code='retry_inventory_preparation',
response=response,
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
# 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成;
# Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分
# 人工重试动作本身与系统自动轮询动作。
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}
if payload.get('action_code') == 'poll_inventory_preparation'
else {'waiting', 'waiting_external', 'pending'},
blocking_reason_code=prep_reason,
)
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
return outcome
@@ -98,7 +98,7 @@ def _resolve_recovery_next_action(
[STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发
``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」
分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。
[STEP 2] 货代上传 RPA / 人工交接失败保持统一 RPA 重试入口。
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
"""
@@ -132,7 +132,7 @@ def _resolve_recovery_next_action(
blocking_gate_code == 'manual_upload_handoff'
and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'}
):
return 'retry_freight_upload_rpa', False
return 'mark_manual_uploaded', False
# [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导)。
next_action = full.get('primary_next_action_code') or _projection_primary_next_action(
@@ -578,6 +578,8 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
if blocking:
if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action))
# 库存文件可通过受控 Gate 工作台补传,但批次中心仅消费 ui_state.primary_action,
# 因而不会把线外上传入口提升为文件卡主按钮。
if (
str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation'
and next_action == 'retry_inventory_preparation'
@@ -610,10 +612,20 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
)
refs = _execution_navigation_refs(execution)
navigation = _navigation_for_action(next_action, refs)
current_gate_code = str((current or {}).get('gate_code') or '').strip() or None
gate_status = str((current or {}).get('status') or '').strip() or None
expected_gate_version = (
int((current or {}).get('evaluation_version'))
if (current or {}).get('evaluation_version') is not None
else None
)
return {
'execution_no': full.get('execution_no'),
'status': full.get('status'),
'execution_status': execution_status,
'current_gate_code': current_gate_code,
'gate_status': gate_status,
'expected_gate_version': expected_gate_version,
# 当前执行 Gate 与人工阻断分开投影:queued/running 不生成待办,但阶段游标必须
# 仍来自正式 Gate,避免旧 OT stage 把页面停留在库存匹配。
'current_gate': current,
@@ -785,7 +797,6 @@ _USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({
'field_code',
'technical_retry_exhausted',
'request_id',
'process_status',
'match_status',
'task_no',
'has_inventory_lines',
@@ -220,6 +220,15 @@ def request_gate_action(
details={'action_code': action},
)
# Gate 20 的确认必须走 mark-manual-uploaded:该 API 强制校验截图/PDF 凭据与货代回执号。
# 禁止复用普通 Gate POST,避免调用方绕过人工上传证据门槛。
if action == 'mark_manual_uploaded':
raise ValidationError(
'Manual upload confirmation requires evidence registration',
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
details={'action_code': action, 'gate_code': gate.gate_code},
)
definition = get_process_gate_definition(gate.gate_code)
if (
str(actor_type or '') == 'user'
@@ -233,15 +242,6 @@ def request_gate_action(
)
primary = _primary_recovery_action(execution=execution, gate=gate)
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
if (
gate.gate_code == 'manual_upload_handoff'
and gate.blocking_reason_code in {'manual_upload_pending', 'upload_result_unknown'}
and action == 'retry_freight_upload_rpa'
):
primary = action
# [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。
allowed_side: set[str] = set()
if gate.gate_code == 'inventory_source_routing':
@@ -33,6 +33,13 @@ from app.services.shipping_notice.process_gate_contract import (
get_process_gate_definition,
primary_next_action_for_gate,
)
def _auto_match_enabled() -> bool:
"""读取全量自动推进的库存匹配开关,缺失时保持现有默认开启语义。"""
from app.services.shipping_notice.tool_common import auto_match_enabled
return bool(auto_match_enabled())
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
@@ -765,13 +772,15 @@ def _enqueue_auto_progress_after_gate_pass(
if next_gate is None or not next_gate.next_action_code:
return
definition = get_process_gate_definition(next_gate.gate_code)
# default_next_actions 中可恢复不等于可自动执行。库存匹配等动作必须由
# 用户明确点击;否则库存准备通过后会立刻消费“重试库存匹配”按钮,页面
# 只剩被自动执行后的结果,用户无法控制重试时机。
# 默认动作可恢复不等于永远禁止自动执行。全量自动推进开启时,库存准备
# 通过后必须继续进入库存匹配;关闭自动匹配时才保留人工恢复入口。
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
return
if (
next_gate.next_action_code in {'retry_inventory_matching'}
(
next_gate.next_action_code in {'retry_inventory_matching'}
and not _auto_match_enabled()
)
or str(next_gate.next_action_code).startswith('open_')
):
return
@@ -45,6 +45,7 @@ _WRITE_ACTION_CODES = frozenset({
'open_inventory_match_review',
'open_shortage_review',
'upload_inventory_file',
'retry_inventory_preparation',
'retry',
'retry_parse',
'retry_failed_documents',
@@ -174,15 +175,32 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
Args:
notice: ShippingNotice 或具备 process_status/current_step/upload_status 的对象。
notice: ShippingNotice 或具备领域事实/current_step/upload_status 的对象。
Returns:
(ShippingProcessingStatus, ShippingProcessingStage)。
"""
ps = str(getattr(notice, 'process_status', None) or '').strip().lower()
step = str(getattr(notice, 'current_step', None) or '').strip().lower()
upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower()
export_path = str(getattr(notice, 'export_file_path', None) or '').strip()
pending = str(getattr(notice, 'pending_human_reason', None) or '').strip().lower()
review = str(getattr(notice, 'review_status', None) or '').strip().lower()
match = str(getattr(notice, 'match_status', None) or '').strip().lower()
lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower()
if upload_st in {'uploaded', 'succeeded', 'success'} or lifecycle in {'archived', 'deleted'}:
ps = 'uploaded'
elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed'
elif export_path:
ps = 'matched'
elif match:
ps = 'matched'
elif getattr(notice, 'inventory_lines_json', None):
ps = 'inventory_ready'
elif pending or review:
ps = 'pending_review'
else:
ps = 'created'
if ps in {'uploaded', 'closed', 'completed'}:
return ('completed', 'completed')
@@ -708,13 +726,8 @@ def apply_user_projection_fields(
rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None
# ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
notice_process_status = None
if notice is not None:
notice_process_status = str(getattr(notice, 'process_status', None) or '').strip().lower() or None
_rd_has_completed_process = bool(
notice is not None
and notice_process_status in {'completed', 'fulfilled', 'closed'}
)
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else ''
_rd_has_completed_process = notice_upload_status in {'uploaded', 'succeeded', 'success'}
def _compute_user_status() -> str:
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
@@ -910,6 +923,7 @@ def apply_user_projection_fields(
# ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None =====
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review',
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
@@ -921,6 +935,7 @@ def apply_user_projection_fields(
}
_ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = {
'retry': 'chat.shippingProcessing.action.retry',
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
'open_inventory_source_review': 'chat.shippingProcessing.action.open_inventory_source_review',
'open_inventory_match_review': 'chat.shippingProcessing.action.open_inventory_match_review',
'open_order_review': 'chat.shippingProcessing.action.open_order_review',
@@ -290,6 +290,7 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
'open_inventory_match_review',
'open_shortage_review',
'upload_inventory_file',
'retry_inventory_preparation',
'retry_inventory_matching',
'retry',
'refresh',
@@ -837,7 +838,6 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
'export_file_name',
'order_data_version',
'order_snapshot_id',
'process_status',
'changed_field_paths',
'draft_version',
'validation_blocking_count',
@@ -403,6 +403,30 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
except (TypeError, ValueError):
operator_id = None
# [STEP 0] 公开入口先执行 STP 早停,避免仅为查询/人工节点创建新的 Gate Attempt。
# 正式 20-Gate 编排仍由后续分支负责;这里仅返回用户可执行的当前结果。
early_task = resolve_task_from_payload({'task_no': task_no}) if task_no else None
if early_task is not None:
early_ui = resolve_task_ui_state(early_task)
if early_ui.checkpoint_kind == CheckpointKind.MUST_HUMAN:
return tool_response(
status='needs_human', task=early_task,
message='当前任务需要人工处理,已暂停自动推进。',
data=serialize_task_for_tool(early_task),
human_options=early_ui.human_options,
checkpoint=early_ui.checkpoint,
stop_agent_turn=True,
)
if early_ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD and not fulfillment_workflow.is_auto_upload_enabled():
return tool_response(
status='ok', task=early_task,
message='Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。',
data=serialize_task_for_tool(early_task),
human_options=early_ui.human_options,
checkpoint=early_ui.checkpoint,
stop_agent_turn=True,
forbidden_next_tools=['upload_to_freight'],
)
return run_task_auto_progress(
task_no, trigger=trigger,
expected_version=expected_version,
@@ -435,7 +459,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
"auto_progress_started",
{
"source": source,
"process_status": task.process_status,
"lifecycle_status": task.lifecycle_status,
"current_step": task.current_step,
"reason_code": "auto_progress_started",
},
@@ -359,14 +359,14 @@ def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]:
def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]:
"""批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。"""
total = len(tasks)
completed = sum(1 for item in tasks if item.process_status in {"uploaded", "completed", "closed"})
failed = sum(1 for item in tasks if item.process_status in {"rejected"} or item.upload_status == "failed")
running = sum(1 for item in tasks if item.process_status not in {"uploaded", "completed", "closed", "rejected"})
pending = sum(1 for item in tasks if item.process_status in {"created", "pending_review"} or not item.current_step)
completed = sum(1 for item in tasks if _is_task_completed(item))
failed = sum(1 for item in tasks if _is_task_failed(item))
running = sum(1 for item in tasks if _is_task_active(item))
pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item)))
focus = next(
(
item for item in sort_batch_tasks(tasks)
if item.process_status not in {"uploaded", "completed", "closed", "rejected"}
if not _is_task_completed(item) and not _is_task_failed(item)
),
None,
)
@@ -383,14 +383,17 @@ def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]
def _is_task_completed(task: ShippingNotice) -> bool:
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
return str(task.process_status or "").strip().lower() in {"uploaded", "completed", "closed"}
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
return upload_status in {"uploaded", "succeeded", "success"} or bool(
str(getattr(task, "freight_ref_no", None) or "").strip()
)
def _is_task_failed(task: ShippingNotice) -> bool:
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
return (
str(task.process_status or "").strip().lower() in {"rejected"}
or str(task.upload_status or "").strip().lower() == "failed"
str(getattr(task, "review_status", None) or "").strip().lower() == "rejected"
or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
)
@@ -405,8 +408,15 @@ def _is_task_active(task: ShippingNotice) -> bool:
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
return False
status = str(task.process_status or "").strip().lower()
return status not in {"created", "pending_review"} and bool(status)
lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower()
if lifecycle != "active":
return False
return bool(
getattr(task, "current_step", None)
or getattr(task, "inventory_snapshot_id", None)
or getattr(task, "export_file_path", None)
or getattr(task, "upload_status", None)
)
def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]:
@@ -470,7 +480,7 @@ def resolve_task_from_payload(
if conv_id:
candidates = (
ShippingNotice.query.filter_by(conversation_id=conv_id)
.filter(ShippingNotice.process_status.notin_(["rejected", "closed", "uploaded"]))
.filter(ShippingNotice.lifecycle_status == "active")
.order_by(ShippingNotice.id.desc())
.limit(2)
.all()
@@ -492,7 +502,6 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"process_status": task.process_status,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
@@ -523,7 +532,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"):
if raw_content and not lines:
limit = max_notice_chars()
payload["raw_text"] = raw_content[:limit] if len(raw_content) > limit else raw_content
if len(raw_content) > limit:
@@ -656,7 +665,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
"current_step": task.current_step,
"process_status": task.process_status,
"review_status": task.review_status,
"match_status": task.match_status,
"upload_status": task.upload_status,
@@ -841,8 +849,10 @@ def _todo_category_from_task_row(
extraction_id is not None
and int(extraction_id) in extractions_with_lines
)
upload_status = str(getattr(row, "upload_status", None) or "").strip().lower()
if upload_status in {"uploaded", "succeeded", "success"}:
return "done"
ui = resolve_task_ui_state_from_fields(
process_status=getattr(row, "process_status", None),
review_status=getattr(row, "review_status", None),
pending_human_reason=getattr(row, "pending_human_reason", None),
shipping_case_id=getattr(row, "shipping_case_id", None),
@@ -945,11 +955,11 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
"""
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用 Notice 履约
process_status 映射为 shipping_processing_status(与 shipping_processing_projection 同源),
核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用领域事实
映射为 shipping_processing_status(与 shipping_processing_projection 同源),
并注入 shipping_processing_stage / progress_version / order_task_no;
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
供任务中心「进入订单处理」深链;无 OT 时仍按 Notice.process_status 映射。
供任务中心「进入订单处理」深链。
Args:
task: ShippingNotice(正式发货任务)。
@@ -957,7 +967,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
"""
from app.models import ShippingOrderProcessingRun, ShippingOrderTask
from app.services.shipping_notice.shipping_processing_projection import (
_notice_processing_status_stage,
_notice_domain_progress_stage,
)
order_task = None
@@ -973,7 +983,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
.first()
)
status, stage = _notice_processing_status_stage(task)
status, stage = _notice_domain_progress_stage(task)
data['shipping_processing_status'] = status
data['shipping_processing_stage'] = (
str(getattr(order_task, 'stage', None) or '').strip() or stage
@@ -1114,7 +1124,6 @@ def list_tasks_for_user(
user_id: int,
*,
batch_no: str | None = None,
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
@@ -1123,14 +1132,6 @@ def list_tasks_for_user(
)
if batch_no:
return []
if process_status:
if process_status == "shortage_review":
q = q.filter(
(ShippingNotice.review_status == "shortage_review")
| (ShippingNotice.pending_human_reason.in_(("shortage", "shortage_review")))
)
else:
q = q.filter(ShippingNotice.process_status == process_status)
rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all()
return [
serialize_task_summary(c, viewer_user_id=user_id)
@@ -1144,7 +1145,6 @@ def list_tasks_page_for_user(
page: int = 1,
page_size: int = 20,
batch_no: str | None = None,
process_status: str | None = None,
lifecycle_status: str | None = None,
) -> dict[str, Any]:
"""
@@ -1160,20 +1160,19 @@ def list_tasks_page_for_user(
)
if batch_no:
return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0}
if process_status:
if process_status == "shortage_review":
q = q.filter(
(ShippingNotice.review_status == "shortage_review")
| (ShippingNotice.pending_human_reason.in_(("shortage", "shortage_review")))
)
else:
q = q.filter(ShippingNotice.process_status == process_status)
if lifecycle_status:
normalized_lifecycle = str(lifecycle_status).strip().lower()
if normalized_lifecycle == 'deleted':
q = q.filter(ShippingNotice.deleted_at.is_not(None))
elif normalized_lifecycle == 'active':
q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == 'active')
q = q.filter(
ShippingNotice.deleted_at.is_(None),
ShippingNotice.lifecycle_status == 'active',
db.or_(
ShippingNotice.upload_status.is_(None),
db.func.lower(ShippingNotice.upload_status).notin_(('uploaded', 'succeeded', 'success')),
),
)
elif normalized_lifecycle == 'voided':
# 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。
q = q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle)
@@ -1373,13 +1372,18 @@ def serialize_review_case_todo(
"created_by": case.owner_user_id,
"source_file_name": source_name,
"customer_name": None,
"process_status": None,
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
"created_at": case.created_at.isoformat() if case.created_at else None,
"ui_state": {
"checkpoint": "order_review",
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
"todo": {"title": current_todo, "message": current_todo},
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
"reason": {"code": f"review_case_{case.status}", "message": current_todo},
"lifecycle_status": "active",
"process_gate": None,
"checkpoint_code": "order_review",
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
"action_buttons": action_buttons,
"summary": {
"title": "待人工复核",
"message": current_todo,
@@ -1531,15 +1535,22 @@ def serialize_intake_todo(
"source_file_name": source_name,
"source_type": str(intake.source_type or "").strip() or None,
"customer_name": None,
"process_status": parse_status,
"updated_at": intake.updated_at.isoformat() if intake.updated_at else None,
"created_at": intake.created_at.isoformat() if intake.created_at else None,
"ui_state": {
"checkpoint": "intake_parse",
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
"checkpoint": {"code": "order_field_extraction", "kind": str(
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
), "label": "订单解析"},
"todo": {"title": title, "message": message},
"actions": {"primary": ({"code": "retry_parse", "label": "重新解析", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if failed else None), "secondary": []},
"reason": ({"code": str(intake.error_code or "intake_parse_failed"), "message": message} if failed else None),
"lifecycle_status": "active",
"process_gate": None,
"checkpoint_code": "order_field_extraction",
"checkpoint_kind": str(
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
),
"action_buttons": ["retry_parse"] if failed else [],
"summary": {
"title": title,
"message": message,
@@ -1579,31 +1590,42 @@ def _todo_category_sql_filter(allowed: frozenset[str]):
# wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。
clauses.append(
db.or_(
ShippingNotice.process_status.in_(("waiting_upload", "upload_failed")),
ShippingNotice.upload_status.in_(("pending", "uploading", "failed")),
db.and_(
ShippingNotice.export_file_path.isnot(None),
ShippingNotice.process_status.notin_(("uploaded", "closed", "rejected")),
db.or_(
ShippingNotice.upload_status.is_(None),
db.func.lower(ShippingNotice.upload_status).notin_(("uploaded", "succeeded", "success")),
),
ShippingNotice.lifecycle_status == "active",
),
)
)
if "done" in allowed:
# 已上传/关闭/驳回终态(不含待人工上传登记)。
clauses.append(
ShippingNotice.process_status.in_(("uploaded", "closed", "rejected"))
db.or_(
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
ShippingNotice.review_status == RS_REJECTED,
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
)
)
if "review" in allowed:
clauses.append(
db.or_(
ShippingNotice.process_status == "pending_review",
ShippingNotice.review_status.isnot(None),
ShippingNotice.pending_human_reason.isnot(None),
)
)
if "exception" in allowed:
clauses.append(ShippingNotice.pending_human_reason.isnot(None))
if "in_progress" in allowed:
clauses.append(
ShippingNotice.process_status.in_(
("created", "parsed", "matched", "inventory_ready")
db.or_(
ShippingNotice.current_step.isnot(None),
ShippingNotice.inventory_snapshot_id.isnot(None),
ShippingNotice.export_file_path.isnot(None),
ShippingNotice.upload_status.isnot(None),
)
)
if not clauses:
@@ -1657,12 +1679,13 @@ def _task_todo_category_sql_expr():
"""
has_lines = _task_has_dynamic_order_lines_sql()
reason = ShippingNotice.pending_human_reason
upload_status = db.func.lower(db.func.coalesce(ShippingNotice.upload_status, ""))
match_status = db.func.lower(db.func.coalesce(ShippingNotice.match_status, ""))
return case(
(ShippingNotice.process_status == "uploaded", literal("done")),
(ShippingNotice.process_status == "closed", literal("done")),
(upload_status.in_(("uploaded", "succeeded", "success")), literal("done")),
(ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")),
(
db.or_(
ShippingNotice.process_status == "rejected",
ShippingNotice.review_status == RS_REJECTED,
),
literal("done"),
@@ -1691,9 +1714,10 @@ def _task_todo_category_sql_expr():
literal("in_progress"),
),
(reason == PH_RPA_EXHAUSTED, literal("exception")),
# Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。
(ShippingNotice.export_file_path.isnot(None), literal("manual_upload")),
(
db.and_(
ShippingNotice.process_status == "parsed",
_sql_str_blank(ShippingNotice.review_status),
_sql_str_blank(reason),
_sql_json_falsy(ShippingNotice.inventory_lines_json),
@@ -1702,7 +1726,6 @@ def _task_todo_category_sql_expr():
),
(
db.and_(
ShippingNotice.process_status == "inventory_ready",
_sql_str_blank(ShippingNotice.review_status),
_sql_str_blank(reason),
_sql_str_blank(ShippingNotice.match_status),
@@ -1712,12 +1735,12 @@ def _task_todo_category_sql_expr():
),
(
db.and_(
ShippingNotice.process_status == "matched",
match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
ShippingNotice.export_file_path.isnot(None),
),
literal("manual_upload"),
),
(ShippingNotice.process_status == "matched", literal("in_progress")),
(match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), literal("in_progress")),
(reason == PH_INV_UNAVAIL, literal("exception")),
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
(
@@ -1727,7 +1750,7 @@ def _task_todo_category_sql_expr():
(
db.or_(
reason == PH_UPLOAD_RPA_FAILED,
ShippingNotice.process_status == "upload_failed",
upload_status == "failed",
),
literal("exception"),
),
@@ -1735,7 +1758,7 @@ def _task_todo_category_sql_expr():
(reason == PH_RPA_PENDING, literal("exception")),
(reason == PH_UPLOAD_RPA_PENDING, literal("exception")),
# Excel 后待人工上传登记。
(ShippingNotice.process_status == "waiting_upload", literal("manual_upload")),
(upload_status.in_(("pending", "uploading")), literal("manual_upload")),
else_=literal("in_progress"),
)
@@ -1803,28 +1826,20 @@ def _todo_tasks_base_query(
ShippingNotice.pending_human_reason.isnot(None),
ShippingNotice.review_status.isnot(None),
ShippingNotice.export_file_path.isnot(None),
ShippingNotice.process_status.in_(
(
"pending_review",
"matched",
"waiting_upload",
"upload_failed",
"parsed",
"inventory_ready",
"created",
)
),
ShippingNotice.current_step.isnot(None),
ShippingNotice.inventory_snapshot_id.isnot(None),
ShippingNotice.upload_status.isnot(None),
)
)
elif normalized_bucket == "done":
# Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。
q = q.filter(
db.or_(
ShippingNotice.process_status.in_(
("uploaded", "closed", "rejected", "waiting_upload")
),
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
ShippingNotice.review_status == RS_REJECTED,
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
db.and_(
ShippingNotice.process_status == "matched",
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
ShippingNotice.export_file_path.isnot(None),
),
)
@@ -1833,25 +1848,8 @@ def _todo_tasks_base_query(
def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
"""徽标统计用的活跃 Task 粗筛范围(不含 done)。"""
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter(
db.or_(
ShippingNotice.pending_human_reason.isnot(None),
ShippingNotice.review_status.isnot(None),
ShippingNotice.export_file_path.isnot(None),
ShippingNotice.process_status.in_(
(
"pending_review",
"matched",
"waiting_upload",
"upload_failed",
"parsed",
"inventory_ready",
"created",
)
),
)
)
"""徽标统计用的活跃 Task 范围;分类 CASE 负责排除 done。"""
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
def list_my_todos(
@@ -2062,11 +2060,11 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(
db.or_(
ShippingNotice.process_status.in_(
("uploaded", "closed", "rejected", "waiting_upload")
),
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
ShippingNotice.review_status == RS_REJECTED,
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
db.and_(
ShippingNotice.process_status == "matched",
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
ShippingNotice.export_file_path.isnot(None),
),
)
@@ -95,16 +95,11 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool:
if not task_is_active(task):
return False
process_status = str(task.process_status or '').strip()
pending_reason = str(task.pending_human_reason or '').strip()
return (
process_status == 'waiting_inventory'
and pending_reason == PH_RPA_PENDING
pending_reason == PH_RPA_PENDING
and not task.inventory_lines_json
) or (
process_status == 'waiting_upload'
and pending_reason == PH_UPLOAD_RPA_PENDING
)
) or pending_reason == PH_UPLOAD_RPA_PENDING
def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
@@ -280,7 +275,7 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
hang_created = bool(
refreshed is not None
and getattr(refreshed, 'current_order_extraction_id', None)
and str(getattr(refreshed, 'process_status', None) or '').strip().lower() in {'', 'created'}
and not getattr(refreshed, 'order_snapshot_id', None)
and status in {'ok', 'needs_human', 'skipped'}
)
if hang_created:
@@ -80,7 +80,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
confirmed_task_id=int(task_id),
lifecycle=classify_task_lifecycle(task.process_status)),
lifecycle=classify_task_lifecycle(task)),
)
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False,
'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no',
@@ -101,7 +101,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
confirmed_task_no=confirmed_task_no,
lifecycle=classify_task_lifecycle(task.process_status)),
lifecycle=classify_task_lifecycle(task)),
)
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False,
'reason': 'confirmed_task_no 反向查无 ShippingNotice',
@@ -165,7 +165,7 @@ def _step_l1cde_downstream_links(
case_no=case_no, match_level_steps=steps,
candidate_id=int(candidate.id),
linked_candidate_task_id=int(fulfilled_task_id),
lifecycle=classify_task_lifecycle(task.process_status),
lifecycle=classify_task_lifecycle(task),
),
)
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False,
@@ -194,7 +194,7 @@ def _step_l1cde_downstream_links(
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
wave_linked_task_id=wave_task_ids[0],
lifecycle=classify_task_lifecycle(task.process_status),
lifecycle=classify_task_lifecycle(task),
),
)
steps.append({'step': 'L1c-wave_line_task', 'passed': False,
@@ -226,7 +226,7 @@ def _step_l1cde_downstream_links(
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
source_document_id=document_id,
lifecycle=classify_task_lifecycle(task.process_status),
lifecycle=classify_task_lifecycle(task),
),
)
steps.append({'step': 'L1d-document_foreign_key', 'passed': False,
@@ -247,7 +247,7 @@ def _step_l1cde_downstream_links(
file_tasks = (
ShippingNotice.query
.filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash)
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
@@ -264,7 +264,7 @@ def _step_l1cde_downstream_links(
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
content_hash=content_hash,
lifecycle=classify_task_lifecycle(task.process_status),
lifecycle=classify_task_lifecycle(task),
),
)
steps.append({'step': 'L1d-file_hash_match', 'passed': False,
@@ -403,7 +403,7 @@ def _step_l2_structural_match(
ShippingNotice.query
.filter(ShippingNotice.user_id == int(case.owner_user_id),
ShippingNotice.business_fingerprint == payload['business_fingerprint'])
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
@@ -415,7 +415,7 @@ def _step_l2_structural_match(
'recalculated': payload['fingerprint_recalculated'],
'task_no': str(task.task_no)}})
evidence['match_level_steps'] = steps
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
evidence['lifecycle'] = classify_task_lifecycle(task)
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L2,
task_no=str(task.task_no),
@@ -442,7 +442,7 @@ def _step_l2_structural_match(
.filter_by(user_id=int(case.owner_user_id))
.filter(ShippingNotice.customer_code == payload['customer_code']
if hasattr(ShippingNotice, 'customer_code') else True)
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
.limit(20)
.all()
@@ -467,7 +467,7 @@ def _step_l2_structural_match(
((task.structured_result_json or {}).get('business_summary') or {}).get('po_numbers') or []}),
'task_no': str(task.task_no)}})
evidence['match_level_steps'] = steps
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
evidence['lifecycle'] = classify_task_lifecycle(task)
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L2,
task_no=str(task.task_no),
@@ -490,7 +490,7 @@ def _step_l2_structural_match(
ShippingNotice.query
.filter((ShippingNotice.source_document_id == document_id) |
(ShippingNotice.document_id == document_id))
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
@@ -501,7 +501,7 @@ def _step_l2_structural_match(
'count': len(doc_tasks_multi)}})
evidence['match_level_steps'] = steps
evidence['candidate_matches'] = [
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t.process_status)}
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t)}
for t in doc_tasks_multi
]
return ReconcileMatchResult(
@@ -81,7 +81,7 @@ class ReconcileProgressResult:
outcome: Literal[
'reused_existing', # L1 命中,已绑定到既有 Task
'duplicate_decision_required', # L2/L3 命中,等待人工裁决
'ownership_anomaly_rejected', # 归属异常(Q13),process_status=rejected
'ownership_anomaly_rejected', # 归属异常(Q13),进入人工隔离
'stp_enqueued', # 无冲突或用户裁决后,已入队 STP
'resume_result', # 仅 resume 结果(未到入队)
'idempotent_replay', # 同 operation_id 幂等回返
@@ -453,7 +453,7 @@ def reconcile_and_progress(
• replay_mode(bool):允许 legacy_job_id.reference_key != case_no。
默认 false(防跨 Case 错挂)。
• BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
→ ReviewCase 无 process_status 列则抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
→ 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
否则返回 outcome=ownership_anomaly_rejected。
Args:
@@ -732,7 +732,7 @@ def reconcile_and_progress(
pending_reason = 'ownership_anomaly'
# [Phase 4 Q13 硬隔离] — 先回滚 BRANCH B/C 半写(_write_back_case_task_binding)
# 避免把 Case 的 candidate_id / confirmed_task_id / fulfilled_task_id 留痕;
# 再单独写 sensitive 审计;再根据 ReviewCase 是否有 process_status 列返回
# 再单独写 sensitive 审计;ReviewCase 不承担履约阶段字段
# outcome=ownership_anomaly_rejected 或抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY。
try:
db.session.rollback()
@@ -777,34 +777,13 @@ def reconcile_and_progress(
pass
msg = (f'ambiguous ownership: match_level={match_result.get("match_level")} '
f'user_action={user_action}; marked ownership_anomaly pending human review')
case_attr_writable = hasattr(case_after, 'process_status')
if not case_attr_writable:
# ReviewCase 没有 process_status(process_status 属于 CaseEvent/Wave 层)
# → 降级:抛 422 给前端显式提示 hard_isolation=True(让前端走裁决面板)
raise ValidationError(
msg,
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
details={
'hard_isolation': True,
'match': {
k: match_result.get(k)
for k in ('match_level', 'confidence', 'task_no')
},
'user_action': user_action,
'next_suggested_actions': [
'reuse_existing', 'create_revision', 'force_create',
],
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
},
)
final_result = ReconcileProgressResult(
outcome='ownership_anomaly_rejected',
case_no=str(case_after.case_no), match=match_result,
task_no=None, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
)
# 用 case_after 替换引用,防止后续审计写已失效对象
# 用 case_after 替换引用,防止后续审计写入已失效对象。
case = case_after
user = db.session.get(User, int(user_id))
@@ -98,7 +98,6 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
if not task_no:
return None
process_status = _clean_text(getattr(task, "process_status", None)).lower()
review_status = _clean_text(getattr(task, "review_status", None)).lower()
match_status = _clean_text(getattr(task, "match_status", None)).lower()
pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower()
@@ -110,13 +109,13 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
"label": "异常:库存不足",
"summary": f"{task_no} 库存匹配失败",
}
if process_status == "rejected" or review_status == "rejected":
if review_status == "rejected" or str(getattr(task, "lifecycle_status", "") or "").lower() in {"voided", "archived"}:
return {
"reason": "rejected",
"label": "已驳回",
"summary": f"{task_no} 已被驳回",
}
if process_status == "upload_failed" or upload_status == "failed" or pending_reason == "upload_rpa_failed":
if upload_status == "failed" or pending_reason == "upload_rpa_failed":
return {
"reason": "upload_failed",
"label": "异常:上传失败",
@@ -138,7 +138,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st
if task is not None:
for attr, key in (
("current_step", "current_step"),
("process_status", "status"),
("review_status", "review_status"),
("match_status", "match_status"),
("pending_human_reason", "pending_human_reason"),
@@ -177,7 +176,6 @@ def _build_summary(
task_no = _task_no(task)
batch_no = _batch_no(batch, task)
file_name = _clean_text(getattr(task, "source_file_name", None))
status = _clean_text(getattr(task, "process_status", None))
current_step = _clean_text(getattr(task, "current_step", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
@@ -188,8 +186,6 @@ def _build_summary(
pieces.append(f"来源文件 {file_name}")
if normalized_run_purpose:
pieces.append(f"本次执行目的为 {normalized_run_purpose}")
if status:
pieces.append(f"当前状态 {status}")
if current_step:
pieces.append(f"当前步骤 {current_step}")
if not pieces:
@@ -34,6 +34,7 @@ from app.models import (
ShippingOrderIntake,
ShippingOrderProcessingRun,
ShippingOrderProcessingRunIntake,
ShippingOrderProcessingUnit,
ShippingOrderReviewCase,
ShippingOrderSubmission,
ShippingOrderTask,
@@ -268,12 +269,13 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str:
将 Intake.parse_status 映射为统一 status。
核心逻辑:parse_failed→failed;parsing/queued/created→processing;
parsed 且已消费→completed,否则仍 processing。
direct_pdf 已消费可完成;EML 交接后若无替代 OT 仍保持处理中。
"""
parse_status = str(intake.parse_status or '').strip().lower()
extraction_status = str(
getattr(intake, 'order_extraction_status', None) or ''
).strip().lower()
source_type = str(intake.source_type or '').strip().lower()
if extraction_status in {'failed', 'error', 'fatal'}:
return 'failed'
if extraction_status in {'cancelled', 'canceled'}:
@@ -282,7 +284,12 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str:
return 'failed'
if parse_status in {'cancelled', 'expired'}:
return 'cancelled'
if parse_status == 'consumed' or intake.consumed_at is not None:
# EML 的 consumed_at 只是进入订单识别链路的内部交接标记。未有 OT/Candidate
# 且提取仅部分完成时,不能把用户卡误报为已完成。
if (
source_type != 'eml'
and (parse_status == 'consumed' or intake.consumed_at is not None)
):
return 'completed'
if parse_status == 'parsed':
return 'completed' if intake.consumed_at is not None else 'processing'
@@ -294,12 +301,20 @@ def _intake_processing_stage(intake: ShippingOrderIntake) -> str:
将 Intake 解析阶段映射为统一 stage。
核心逻辑:direct_pdf 全程用 document_parsing(禁止 email_*);
eml 在解析中用 email_parsing;已解析/消费用 completed 或 candidate_creating。
EML 在解析中用 email_parsing,部分完成/已交接但无 OT 时停在 candidate_creating。
"""
source = str(intake.source_type or '').strip().lower() or None
parse_status = str(intake.parse_status or '').strip().lower()
if parse_status in {'consumed'} or intake.consumed_at is not None:
extraction_status = str(
getattr(intake, 'order_extraction_status', None) or ''
).strip().lower()
if (
source != 'eml'
and (parse_status in {'consumed'} or intake.consumed_at is not None)
):
return _clamp_processing_stage('completed', source_type=source)
if source == 'eml' and extraction_status in {'partially_completed', 'partial', 'interrupted'}:
return _clamp_processing_stage('candidate_creating', source_type=source)
if parse_status == 'parsed':
return _clamp_processing_stage('candidate_creating', source_type=source)
if parse_status == 'created':
@@ -410,19 +425,18 @@ def _intake_source_summary(
if isinstance(structured.get('business_summary'), dict)
else {}
)
document_count = (
db.session.query(ShippingOrderDocument.id)
.filter(ShippingOrderDocument.intake_id == int(intake.id))
.count()
)
parsed_document_count = (
db.session.query(ShippingOrderDocument.id)
.filter(
ShippingOrderDocument.intake_id == int(intake.id),
ShippingOrderDocument.parse_status == 'parsed',
)
.count()
)
document_filters = [ShippingOrderDocument.intake_id == int(intake.id)]
# EML 正文是邮件上下文而非可处理文件。父卡数量必须与后续展开附件同源,
# 否则会出现“3 个文件、只有 2 个(甚至 0 个)叶子”的假象。
if str(intake.source_type or '').strip().lower() == 'eml':
document_filters.append(ShippingOrderDocument.document_type != 'email_body')
document_count = db.session.query(ShippingOrderDocument.id).filter(
*document_filters,
).count()
parsed_document_count = db.session.query(ShippingOrderDocument.id).filter(
*document_filters,
ShippingOrderDocument.parse_status == 'parsed',
).count()
from app.models import ShippingOrderCandidate
candidate_count = (
@@ -495,7 +509,15 @@ def project_intake_work_item(
extraction_status = str(
getattr(intake, 'order_extraction_status', None) or ''
).strip().lower()
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
unit_by_document_id = _latest_intake_run_unit_outcomes(intake)
unit_statuses = {
str(unit.status or '').strip().lower()
for unit in unit_by_document_id.values()
}
if (
source_type != 'eml'
and extraction_status in {'partially_completed', 'partial', 'interrupted'}
):
intake_status = 'waiting_human'
intake_stage = _clamp_processing_stage(
'waiting_review', source_type=source_type,
@@ -515,6 +537,19 @@ def project_intake_work_item(
intake_status = 'failed'
elif extraction_status in {'partially_completed', 'partial', 'interrupted'}:
intake_status = 'waiting_human'
# EML 尚未形成 Candidate/OT 时,Run Unit 仍是附件处理的正式裁决来源。
# 不能用 Intake 的 partial 状态把已判定的失败/复核降级为“系统处理中”。
if source_type == 'eml':
if 'failed' in unit_statuses:
intake_status = 'failed'
intake_stage = _clamp_processing_stage(
'document_parsing', source_type=source_type,
)
elif 'review_required' in unit_statuses:
intake_status = 'waiting_review'
intake_stage = _clamp_processing_stage(
'waiting_review', source_type=source_type,
)
payload = reconcile_processing_projection_facts(
{
'work_item_type': 'order_intake',
@@ -537,21 +572,105 @@ def project_intake_work_item(
},
legacy_actions=legacy_actions,
)
# Intake 与 OT 同样是 Processing Projection 的输出边界。补齐用户态字段后,
# 会话卡无需从 legacy status 再次猜测“处理中/待人工”。
payload = apply_user_projection_fields(payload)
# 尚未建 OT 的 EML 也必须进入统一聚合状态区,不能走「待处理材料」旁路。
status = str(payload.get('status') or '').strip().lower()
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
if (
source_type != 'eml'
and extraction_status in {'partially_completed', 'partial', 'interrupted'}
):
payload['status'] = 'waiting_human'
payload['user_status'] = 'waiting_human'
payload['user_stage'] = 'waiting_review'
status = 'waiting_human'
# 尚无 OT 的 EML 也要以 ShippingOrderDocument 为唯一附件真相输出叶子;
# 没有 Candidate 只说明订单识别尚未形成,不是前端应展示的异常或人工 Gate。
if source_type == 'eml':
aggregate_children = _eml_aggregate_document_children(
intake=intake,
order_task_children=[],
unit_by_document_id=unit_by_document_id,
)
aggregate_states = [
str(child.get('user_status') or child.get('status') or '').strip().lower()
for child in aggregate_children
]
upload_states = [
str((child.get('facts') or {}).get('upload_state') or '').strip().lower()
for child in aggregate_children
if isinstance(child.get('facts'), dict)
]
failed_count = sum(state in {'failed', 'retryable'} for state in aggregate_states)
waiting_count = sum(state == 'waiting_human' for state in aggregate_states)
completed_count = sum(
state == 'completed' and upload_state == 'succeeded'
for state, upload_state in zip(aggregate_states, upload_states)
)
payload['aggregate_children'] = aggregate_children
payload['aggregate_summary'] = {
'intake_no': str(intake.intake_no),
'total': len(aggregate_children),
'completed': completed_count,
'processing': len(aggregate_children) - failed_count - waiting_count - completed_count,
'needs_action': waiting_count,
'failed': failed_count,
'stages': sorted({
str(child.get('user_stage') or child.get('stage') or '').strip()
for child in aggregate_children
if str(child.get('user_stage') or child.get('stage') or '').strip()
}),
'reason_codes': sorted({
str((child.get('blocking_reason') or {}).get('code') or '').strip()
for child in aggregate_children
if isinstance(child.get('blocking_reason'), dict)
and str((child.get('blocking_reason') or {}).get('code') or '').strip()
}),
'upload_states': sorted(set(upload_states)),
}
payload['user_group'] = (
'failed' if status in {'failed', 'blocked'}
else 'waiting_human' if status == 'waiting_human'
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
else 'processing'
)
return payload
def _latest_intake_run_unit_outcomes(
intake: ShippingOrderIntake,
) -> dict[int, ShippingOrderProcessingUnit]:
"""读取 Intake 最新 Run 的冻结 Unit 裁决,兼容已释放的历史 Run Intake 链接。"""
links = (
ShippingOrderProcessingRunIntake.query.join(
ShippingOrderProcessingRun,
ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id,
)
.filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id))
.order_by(
ShippingOrderProcessingRun.created_at.desc(),
ShippingOrderProcessingRunIntake.created_at.desc(),
)
.all()
)
for link in links:
run = db.session.get(ShippingOrderProcessingRun, int(link.run_id))
plan = run.extraction_plan if run is not None else None
if plan is None:
continue
units = (
ShippingOrderProcessingUnit.query.filter(
ShippingOrderProcessingUnit.plan_id == int(plan.id),
ShippingOrderProcessingUnit.intake_id == int(intake.id),
)
.order_by(ShippingOrderProcessingUnit.position.asc())
.all()
)
if units:
return {int(unit.document_id): unit for unit in units}
return {}
def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None:
"""
从 Run 关联的首个 Intake 推断 source_type。
@@ -779,9 +898,9 @@ def _order_task_source_summary(
}
def _notice_processing_status_stage(notice: ShippingNotice) -> tuple[str, str]:
def _notice_domain_progress_stage(notice: ShippingNotice) -> tuple[str, str]:
"""
将正式 Notice 履约 process_status 映射为统一投影 (status, stage)。
将正式 Notice 领域事实映射为统一进度投影 (status, stage)。
核心逻辑:委托领域映射 map_notice_to_processing_status_stage,投影不再私有维护规则。
"""
@@ -865,6 +984,8 @@ def _order_task_current_gate(
or blocking.get('blocking_reason_code')
),
'attempt_no': int(blocking.get('attempt_no') or 0),
# 外层单独透传完整摘要;current_gate 保持轻量展示形状。
'_process_gate_summary': summary,
}
return {
'gate_code': 'order_freeze_readiness',
@@ -911,6 +1032,8 @@ def _order_task_current_gate(
or blocking.get('blocking_reason_code')
),
'attempt_no': int(blocking.get('attempt_no') or 0),
# 写动作的 execution_no / Gate version 只能来自正式摘要。
'_process_gate_summary': summary,
}
status = (
@@ -1090,7 +1213,13 @@ def _project_order_task_work_item(
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。
notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else ''
if notice_process_status in {'uploaded', 'closed', 'completed'}:
notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else ''
notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else ''
if (
notice_process_status in {'uploaded', 'closed', 'completed'}
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
or notice_lifecycle in {'voided', 'archived', 'deleted'}
):
status = 'completed'
stage = 'completed'
stage_label_key = 'completed'
@@ -1170,6 +1299,10 @@ def _project_order_task_work_item(
and getattr(order_task, 'shipping_notice_id', None) is not None
and notice_no_for_task is not None
)
current_gate = _order_task_current_gate(run, order_task)
process_gate = None
if isinstance(current_gate, dict):
process_gate = current_gate.pop('_process_gate_summary', None)
payload = reconcile_processing_projection_facts(
{
'work_item_type': 'order_task',
@@ -1199,7 +1332,9 @@ def _project_order_task_work_item(
or getattr(run, 'last_activity_at', None)
or getattr(run, 'updated_at', None)
) or '',
'current_gate': _order_task_current_gate(run, order_task),
'current_gate': current_gate,
# Gate 执行上下文与当前轻量节点分离,前端不得从 OT / 文件名猜写入目标。
'process_gate': process_gate,
'available_actions': legacy_actions,
'source_summary': _order_task_source_summary(
run,
@@ -1560,6 +1695,127 @@ def _eml_aggregate_user_group(
return 'processing'
def _eml_aggregate_document_children(
*,
intake: ShippingOrderIntake | None,
order_task_children: list[dict[str, Any]],
unit_by_document_id: dict[int, ShippingOrderProcessingUnit] | None = None,
) -> list[dict[str, Any]]:
"""以 EML Intake 的真实业务附件构建展开叶子,并仅叠加已存在 OT 的领域裁决。
核心逻辑:`ShippingOrderDocument` 是邮件附件集合的唯一事实;order_task 只在其
`source_summary.document_id` 命中时提供 Gate、动作与履约状态。尚未建 OT 的附件
保留真实解析状态,不能为方便前端展示而伪造可执行动作。
Args:
intake: 当前 EML Intake;不存在时保留旧工作项,兼容纯 DTO 测试与历史数据。
order_task_children: 同 Intake 已投影的真实 order_task 工作项。
unit_by_document_id: 尚未形成 OT 时,最新 Run 记录的附件正式裁决。
Returns:
按 Document.id 稳定排序的业务附件叶子;排除 email_body。
"""
if intake is None:
return [
{**child, 'ui_state': _processing_ui_state_from_item(child)}
for child in order_task_children
]
documents = (
ShippingOrderDocument.query.filter(
ShippingOrderDocument.intake_id == int(intake.id),
ShippingOrderDocument.document_type != 'email_body',
)
.order_by(ShippingOrderDocument.id.asc())
.all()
)
if not documents:
return [
{**child, 'ui_state': _processing_ui_state_from_item(child)}
for child in order_task_children
]
children_by_document_id: dict[int, dict[str, Any]] = {}
for child in order_task_children:
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
document_id = int(summary.get('document_id') or 0)
if document_id > 0 and document_id not in children_by_document_id:
children_by_document_id[document_id] = child
unit_by_document_id = unit_by_document_id or {}
result: list[dict[str, Any]] = []
for document in documents:
existing = children_by_document_id.get(int(document.id))
if existing is not None:
leaf = dict(existing)
summary = dict(existing.get('source_summary') or {})
else:
parse_status = str(document.parse_status or '').strip().lower()
failed = parse_status in {'failed', 'parse_failed'}
unit = unit_by_document_id.get(int(document.id))
unit_status = str(unit.status or '').strip().lower() if unit is not None else ''
review_required = unit_status == 'review_required'
unit_failed = unit_status == 'failed'
failure_reason_code = (
str(unit.reason_code or unit.error_code or 'unit_failed').strip()
if unit_failed and unit is not None else None
)
review_reason_code = (
str(unit.reason_code or unit.error_code or 'unit_review_required').strip()
if review_required and unit is not None else None
)
review_case = (
ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).one_or_none()
if review_required and unit is not None else None
)
run = db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) if review_case is not None else None
leaf = {
'work_item_type': 'document',
'work_item_no': f'DOCUMENT:{document.id}',
'has_formal_ot': False,
'source_type': 'eml',
'root_order_task_no': None,
'shipping_notice_no': None,
# 只有正式存在的 Review Case 才允许暴露「进入订单处理」;不能因
# waiting_human 状态而前端猜测或补造可执行入口。
'run_no': str(run.run_no) if run is not None else None,
'case_no': str(review_case.case_no) if review_case is not None else None,
'conversation_id': str(intake.conversation_id or '').strip() or None,
'submission_no': '',
'intake_no': str(intake.intake_no),
'status': 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
'stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
'stage_label_key': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
'progress_version': int(getattr(intake, 'progress_version', None) or 1),
'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '',
'current_gate': None,
'available_actions': ['open_order_review'] if review_case is not None else [],
'blocking_reason': (
{'code': failure_reason_code, 'details': {}}
if unit_failed else
{'code': review_reason_code, 'details': {}}
if review_required else None
),
'primary_action': {'code': 'open_order_review'} if review_case is not None else None,
'user_status': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'running',
'user_stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
'user_group': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
'facts': {'upload_state': 'not_created'},
'child_order_tasks': [],
}
summary = {}
summary.update({
'document_id': int(document.id),
'filename': str(document.filename or '').strip() or None,
'document_count': 1,
'parsed_document_count': 1 if str(document.parse_status or '').strip().lower() == 'parsed' else 0,
})
leaf['source_summary'] = summary
leaf['ui_state'] = _processing_ui_state_from_item(leaf)
result.append(leaf)
return result
def _aggregate_eml_order_task_work_items(
work_items: list[dict[str, Any]],
) -> list[dict[str, Any]]:
@@ -1583,7 +1839,12 @@ def _aggregate_eml_order_task_work_items(
or str(item.get('source_type') or '').strip().lower() != 'eml'
or not str(item.get('intake_no') or '').strip()
):
passthrough.append(item)
# [USER-STAGE] 建单前内部码不得透传到任何用户展示节点,非 EML 叶子
# 也与 EML 聚合使用同一映射,避免左右两侧出现不同阶段名称。
normalized = dict(item)
if str(normalized.get('user_stage') or '').strip().lower() == 'pre_ot_stp':
normalized['user_stage'] = 'order_creating'
passthrough.append(normalized)
continue
grouped.setdefault(str(item['intake_no']).strip(), []).append(item)
@@ -1596,8 +1857,18 @@ def _aggregate_eml_order_task_work_items(
result = list(passthrough)
for intake_no, children in grouped.items():
states = [_state(item) for item in children]
upload_states = [_upload_state(item) for item in children]
# EML 的计数、状态及展开明细必须基于同一组业务附件,而不是仅基于已创建 OT。
intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none()
aggregate_children = _eml_aggregate_document_children(
intake=intake,
order_task_children=children,
unit_by_document_id=(
_latest_intake_run_unit_outcomes(intake)
if intake is not None else None
),
)
states = [_state(item) for item in aggregate_children]
upload_states = [_upload_state(item) for item in aggregate_children]
failed_count = sum(state in {'failed', 'retryable'} for state in states)
waiting_count = sum(state == 'waiting_human' for state in states)
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
@@ -1605,7 +1876,7 @@ def _aggregate_eml_order_task_work_items(
state == 'completed' and upload_state == 'succeeded'
for state, upload_state in zip(states, upload_states)
)
processing_count = len(children) - failed_count - waiting_count - completed_count
processing_count = len(aggregate_children) - failed_count - waiting_count - completed_count
all_uploaded = bool(upload_states) and all(state == 'succeeded' for state in upload_states)
aggregate_group = _eml_aggregate_user_group(
states=states,
@@ -1641,10 +1912,17 @@ def _aggregate_eml_order_task_work_items(
key=lambda item: str(item.get('last_activity_at') or ''),
)
source_summary = dict(representative.get('source_summary') or {})
source_summary['document_count'] = sum(
int((item.get('source_summary') or {}).get('document_count') or 0)
for item in children
)
# EML 聚合卡的标题必须来自 Intake 的原始邮件资产,不能随机使用一个附件 PDF。
if intake is not None and intake.asset_id:
parent_asset = db.session.get(FileAsset, int(intake.asset_id))
if parent_asset is not None:
source_summary['filename'] = str(parent_asset.original_filename or '').strip() or source_summary.get('filename')
if intake is not None:
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
email = structured.get('email') if isinstance(structured.get('email'), dict) else {}
source_summary['email_subject'] = str(email.get('subject') or '').strip() or source_summary.get('email_subject')
# 父卡文件数必须与展开叶子来自同一组真实业务附件,不能再累计 OT 的历史摘要。
source_summary['document_count'] = len(aggregate_children)
aggregate = dict(representative)
aggregate['work_item_no'] = f'INTAKE:{intake_no}'
aggregate['root_order_task_no'] = representative.get('root_order_task_no') or representative.get('work_item_no')
@@ -1656,18 +1934,31 @@ def _aggregate_eml_order_task_work_items(
aggregate['source_summary'] = source_summary
aggregate['facts'] = dict(representative.get('facts') or {})
aggregate['facts']['upload_state'] = aggregate_upload_state
blocking_child = next(
(
item for item in children
if _state(item) in {'failed', 'retryable', 'waiting_human'}
and isinstance(item.get('blocking_reason'), dict)
),
# EML 父卡的状态、原因和动作必须来自同一优先级的附件。此前按输入顺序
# 取首个阻断附件:当「待人工」排在「失败」前面时,会得到“失败状态 +
# 待人工按钮”的矛盾组合。
actionable_states = (
{'failed', 'retryable'} if aggregate_group == 'failed'
else {'waiting_human'} if aggregate_group == 'waiting_human'
else set()
)
actionable_child = next(
(item for item in children if _state(item) in actionable_states),
None,
)
if blocking_child is not None:
aggregate['blocking_reason'] = dict(blocking_child['blocking_reason'])
aggregate['primary_action'] = blocking_child.get('primary_action')
aggregate['aggregate_children'] = children
if actionable_child is not None:
reason = actionable_child.get('blocking_reason')
aggregate['blocking_reason'] = dict(reason) if isinstance(reason, dict) else None
primary = actionable_child.get('primary_action')
aggregate['primary_action'] = dict(primary) if isinstance(primary, dict) else None
aggregate['available_actions'] = list(actionable_child.get('available_actions') or [])
else:
# 处理中和终态不能从最近一个附件继承陈旧的人工动作。
aggregate['blocking_reason'] = None
aggregate['primary_action'] = None
aggregate['available_actions'] = []
# 子文件来自 Intake 文档真相;已有 OT 只覆盖自己的叶子裁决,未建 OT 不伪造动作。
aggregate['aggregate_children'] = aggregate_children
summary_stages = {
(
'order_creating'
@@ -1679,7 +1970,7 @@ def _aggregate_eml_order_task_work_items(
}
aggregate['aggregate_summary'] = {
'intake_no': intake_no,
'total': len(children),
'total': len(aggregate_children),
'completed': completed_count,
'processing': processing_count,
'needs_action': waiting_count,
@@ -1723,22 +2014,36 @@ def _conversation_task_row_from_work_item(
source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
document_count = int(source_summary.get('document_count') or 0)
filename = str(source_summary.get('filename') or '').strip() or None
title = filename if document_count == 1 and filename else None
# EML 聚合根无论附件数多少都必须保留邮件标题;否则多附件邮件会退化成
# INTAKE 编号,与批次中心的 EML 标题不一致。
is_eml_aggregate = bool(
str(item.get('source_type') or '').strip().lower() == 'eml'
and str(item.get('intake_no') or '').strip()
)
email_subject = str(source_summary.get('email_subject') or '').strip() or None
eml_filename = filename if filename and filename.lower().endswith('.eml') else None
title = (
eml_filename or email_subject
if is_eml_aggregate
else (filename if document_count == 1 and filename else None)
)
display_kind = 'single_document_task' if document_count == 1 else 'multi_document_task'
group = _conversation_processing_group_for_work_item(item)
# 聚合 Intake 卡仍必须透传真实 Run/Case/文档上下文;前端不能用 INTAKE 编号反查写操作目标。
run_no = str(item.get('run_no') or '').strip() or None
workflow_no = None
resolved_primary: str | None = None
# Intake 行没有真实 OT 编号;对其反查 OT/Run 必定无命中,只会放大首屏 SQL。
is_order_task = str(item.get('work_item_type') or '').strip() == 'order_task'
order_task = (
ShippingOrderTask.query.filter_by(task_no=user_task_no).first()
if user_task_no
if is_order_task and user_task_no
else None
)
run = None
if order_task is not None and order_task.extraction_run_id:
if is_order_task and order_task is not None and order_task.extraction_run_id:
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
if run is None and user_task_no:
if is_order_task and run is None and user_task_no:
# [ROOT-3 FIX] fallback:拿代表 Run(与旧 embedded 投影同选择规则)
run_candidate = (
ShippingOrderProcessingRun.query.filter(
@@ -1810,6 +2115,16 @@ def _conversation_task_row_from_work_item(
'document_id': source_document_id,
'filename': filename,
})
user_group = str(item.get('user_group') or '').strip().lower()
if not user_group:
user_status = str(item.get('user_status') or item.get('status') or '').strip().lower()
user_group = (
'failed' if user_status in {'failed', 'retryable'}
else 'waiting_human' if user_status in {'waiting_human', 'waiting_review'}
else 'completed' if user_status == 'completed'
else 'cancelled' if user_status == 'cancelled'
else 'processing'
)
return {
'user_task_no': user_task_no,
'submission_ordinal': None,
@@ -1842,7 +2157,193 @@ def _conversation_task_row_from_work_item(
'primary_action': item.get('primary_action'),
'facts': item.get('facts'),
'aggregate_summary': item.get('aggregate_summary'),
'user_group': item.get('user_group'),
# [AUTHORITY] EML 子文件已在后端聚合;会话/批次 UI 直接透传,禁止前端再按
# intake_no、状态或历史 Run 文档列表重新构建。
'aggregate_children': item.get('aggregate_children') or [],
'user_group': user_group,
'ui_state': _processing_ui_state_from_item(item),
}
def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
"""将最终 Processing 投影封装为用户展示状态与已授权动作。
核心逻辑:status/stage/reason/action 均复用 work_item 已完成的领域裁决;本函数
只做稳定 DTO 封装,禁止依据前端展示需要重新推导动作或补造按钮。
Args:
item: 已经过 reconcile 与 user projection 的单项或 EML 聚合项。
Returns:
可被聊天卡、批次中心和工作台直接渲染的 ui_state。
"""
primary_raw = item.get('primary_action')
primary = dict(primary_raw) if isinstance(primary_raw, dict) else None
primary_code = str((primary or {}).get('code') or '').strip()
secondary: list[dict[str, Any]] = []
for raw_code in item.get('available_actions') or []:
code = str(raw_code or '').strip()
if not code or code == primary_code:
continue
secondary.append({'code': code, 'enabled': True})
return {
'status': str(item.get('user_status') or item.get('status') or 'running'),
'stage': str(item.get('user_stage') or item.get('stage') or ''),
'blocking_reason': (
dict(item['blocking_reason'])
if isinstance(item.get('blocking_reason'), dict)
else None
),
'primary_action': primary,
'secondary_actions': secondary,
}
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""从最终用户态工作项构建批次四阶段主进度。
业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
绝不要求前端通过 stage 索引再计算四阶段。
"""
ranges = (
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
('order_review', {'order_creating', 'review_required', 'waiting_review', 'pre_ot_stp'}),
('fulfillment_prep', {'inventory_fetching', 'inventory_matching', 'excel_generating'}),
('upload_complete', {'freight_uploading', 'completed'}),
)
ranked_items = sorted(
work_items,
key=lambda item: {
'failed': 0,
'retryable': 0,
'waiting_human': 1,
'running': 2,
'completed': 3,
'cancelled': 4,
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
)
selected = ranked_items[0] if ranked_items else {}
active_index = 0
selected_status = str(selected.get('user_status') or selected.get('status') or '').strip().lower()
stage = str(selected.get('user_stage') or selected.get('stage') or '').strip().lower()
for index, (_, stage_codes) in enumerate(ranges):
if stage in stage_codes:
active_index = index
break
all_completed = bool(work_items) and all(
str(item.get('user_status') or item.get('status') or '').strip().lower()
in {'completed', 'cancelled'}
for item in work_items
)
for item in work_items:
stage = str(item.get('user_stage') or item.get('stage') or '').strip().lower()
for index, (_, stage_codes) in enumerate(ranges):
if stage in stage_codes:
break
nodes: list[dict[str, Any]] = []
for index, (code, _) in enumerate(ranges):
status = 'passed' if all_completed or index < active_index else 'pending'
if not all_completed and index == active_index:
status = 'blocked' if selected_status in {'failed', 'retryable', 'waiting_human'} else 'running'
nodes.append({'code': code, 'label_key': code, 'status': status})
return nodes
def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""投影本次已就绪产出物;只暴露后端确认可下载的正式 Excel。"""
artifacts: list[dict[str, Any]] = []
seen: set[str] = set()
for item in work_items:
task_no = str(item.get('root_order_task_no') or '').strip()
if not task_no or task_no in seen:
continue
task = ShippingOrderTask.query.filter_by(task_no=task_no).first()
notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None
notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None
filename = str(getattr(notice, 'export_file_name', None) or '').strip() if notice else ''
path = str(getattr(notice, 'export_file_path', None) or '').strip() if notice else ''
if not filename or not path:
continue
seen.add(task_no)
artifacts.append({
'order_task_no': task_no,
'filename': filename,
'type': 'xlsx',
'status': 'ready',
'action': {'code': 'download_excel', 'enabled': True},
})
return artifacts
def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, Any]:
"""裁决会话批次的用户状态与唯一主动作。
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
"""
ranked = sorted(
work_items,
key=lambda item: {
'failed': 0,
'retryable': 0,
'waiting_human': 1,
'running': 2,
'completed': 3,
'cancelled': 4,
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
)
selected = ranked[0] if ranked else {}
return {
'status': str(selected.get('user_status') or selected.get('status') or 'running'),
'stage': str(selected.get('user_stage') or selected.get('stage') or ''),
'blocking_reason': (
dict(selected['blocking_reason'])
if isinstance(selected.get('blocking_reason'), dict)
else None
),
'primary_action': (
dict(selected['primary_action'])
if isinstance(selected.get('primary_action'), dict)
else None
),
'secondary_actions': [
{'code': str(code), 'enabled': True}
for code in selected.get('available_actions') or []
if str(code).strip()
and str(code).strip() != str((selected.get('primary_action') or {}).get('code') or '').strip()
],
}
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
"""按后端最终 EML 聚合结果统计业务文件,EML 容器永不计数。"""
groups = {'failed': set(), 'waiting_human': set(), 'processing': set(), 'completed': set()}
for item in work_items:
group = str(item.get('user_group') or '').strip().lower()
if group not in groups:
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
group = 'failed' if status in {'failed', 'retryable'} else (
'waiting_human' if status in {'waiting_human', 'waiting_review'} else (
'completed' if status == 'completed' else 'processing'
)
)
for child in item.get('aggregate_children') or [item]:
if not isinstance(child, dict):
continue
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
filename = str(summary.get('filename') or '').strip().lower()
if filename.endswith('.eml'):
continue
document_id = int(summary.get('document_id') or 0)
key = f'document:{document_id}' if document_id else f'filename:{filename}'
if filename or document_id:
groups[group].add(key)
return {
'total_files': len(set().union(*groups.values())),
'failed_files': len(groups['failed']),
'waiting_human_files': len(groups['waiting_human']),
'processing_files': len(groups['processing']),
'completed_files': len(groups['completed']),
}
@@ -1870,6 +2371,7 @@ def _conversation_processing_from_work_items(
needs_action: list[dict[str, Any]] = []
processing: list[dict[str, Any]] = []
completed: list[dict[str, Any]] = []
all_rows: list[dict[str, Any]] = []
focused = str(focused_task_no or '').strip() or None
recent = str(recent_task_no or '').strip() or None
@@ -1879,6 +2381,7 @@ def _conversation_processing_from_work_items(
if str(item.get('work_item_type') or '') not in {'order_task', 'order_intake'}:
continue
row = _conversation_task_row_from_work_item(item, focused_task_no=focused)
all_rows.append(row)
if recent and row['user_task_no'] == recent:
row['recently_created'] = True
bucket = row['group']
@@ -1901,15 +2404,19 @@ def _conversation_processing_from_work_items(
int(summary.get('document_id'))
for item in work_items
if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task'
for summary in [item.get('source_summary')]
for child in (item.get('aggregate_children') or [item])
if isinstance(child, dict)
for summary in [child.get('source_summary')]
if isinstance(summary, dict) and int(summary.get('document_id') or 0) > 0
}
total_files = (
file_counts = _batch_file_counts(work_items)
total_files = file_counts['total_files'] or (
len(document_ids)
if document_ids
else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
)
return {
'projection_version': 1,
'summary': {
'total_tasks': total,
'total_files': total_files,
@@ -1917,6 +2424,7 @@ def _conversation_processing_from_work_items(
'needs_action': len(needs_action),
'completed': len(completed),
'history': 0,
**file_counts,
},
'focused_task_no': focused,
'recent_task_no': recent,
@@ -1924,6 +2432,17 @@ def _conversation_processing_from_work_items(
'processing': processing,
'completed': completed,
'history': [],
'status_groups': {
'failed': [row for row in all_rows if row.get('user_group') == 'failed'],
'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'],
'processing': [row for row in all_rows if row.get('user_group') == 'processing'],
'completed': [row for row in all_rows if row.get('user_group') == 'completed'],
'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'],
'archived': [row for row in all_rows if row.get('user_group') == 'archived'],
},
'four_stage_nodes': _batch_four_stage_nodes(work_items),
'ui_state': _batch_ui_state_from_items(work_items),
'output_artifacts': _batch_output_artifacts(work_items),
}
@@ -2001,33 +2520,8 @@ def project_conversation_processing_items(
)
work_items: list[dict[str, Any]] = []
# [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则
# (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task,
# 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。
from app.services.shipping_notice.conversation_processing_projection import (
_RIGHT_PANEL_RUN_STATUSES,
)
legacy_seed_runs = (
ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.user_id == int(user_id),
ShippingOrderProcessingRun.conversation_id == normalized,
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
ShippingOrderProcessingRun.user_task_no.isnot(None),
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
)
.order_by(
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
ShippingOrderProcessingRun.created_at.desc(),
)
.all()
)
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
for seed_run in legacy_seed_runs:
seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip()
if seed_task_no and seed_task_no not in latest_by_task:
latest_by_task[seed_task_no] = seed_run
# STEP 1b:会话内 OT 实体列表(保留 updated_at desc 排序,前端卡片顺序仍靠 OT 更新时间)
# STEP 1a:会话内 OT 实体列表。代表 Run 只服务于这些真实 OT,
# 必须先取得其编号,避免刚上传/仅 Intake 会话扫描全部历史 Run。
order_tasks = (
ShippingOrderTask.query.filter(
ShippingOrderTask.user_id == int(user_id),
@@ -2037,6 +2531,40 @@ def project_conversation_processing_items(
.limit(200)
.all()
)
order_task_nos = [
str(task.task_no or '').strip()
for task in order_tasks
if str(task.task_no or '').strip()
]
# [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则
# (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task,
# 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。
legacy_seed_runs: list[ShippingOrderProcessingRun] = []
if order_task_nos:
from app.services.shipping_notice.conversation_processing_projection import (
_RIGHT_PANEL_RUN_STATUSES,
)
legacy_seed_runs = (
ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.user_id == int(user_id),
ShippingOrderProcessingRun.conversation_id == normalized,
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
ShippingOrderProcessingRun.user_task_no.in_(order_task_nos),
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
)
.order_by(
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
ShippingOrderProcessingRun.created_at.desc(),
)
.all()
)
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
for seed_run in legacy_seed_runs:
seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip()
if seed_task_no and seed_task_no not in latest_by_task:
latest_by_task[seed_task_no] = seed_run
# STEP 1b:会话内 OT 已在上方按更新时间加载,前端卡片顺序保持不变。
run_ids = {
int(task.extraction_run_id)
for task in order_tasks
@@ -2244,6 +2772,13 @@ def project_conversation_processing_items(
# 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前,
# 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。
work_items = _aggregate_eml_order_task_work_items(work_items)
# [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用
# 相同的展示 DTO。否则 direct PDF / EML 聚合根会缺 ui_state,迫使前端从旧
# gate 或 available_actions 重新裁决状态与按钮。
work_items = [
{**item, 'ui_state': _processing_ui_state_from_item(item)}
for item in work_items
]
recent_override = str(recent_task_no or '').strip() or None
rebuilt = _conversation_processing_from_work_items(
@@ -68,7 +68,7 @@ def _recover_auto_progress_jobs() -> int:
)
.filter(
ShippingProcessExecution.status == 'active',
ShippingNotice.process_status.notin_(('cancelled', 'canceled', 'closed', 'rejected')),
ShippingNotice.lifecycle_status == 'active',
).limit(50).all()
)
recovered = 0
@@ -324,7 +324,6 @@ def human_options_for_task_or_checkpoint(
def resolve_task_ui_state_from_fields(
*,
process_status: str | None,
review_status: str | None,
pending_human_reason: str | None,
shipping_case_id: int | None,
@@ -352,13 +351,16 @@ def resolve_task_ui_state_from_fields(
return upload_req_options_for_task(upload_req_task)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
if process_status == "uploaded":
upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower()
has_export = bool(str(export_file_path or "").strip())
# [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。
if upload_status in {"uploaded", "succeeded", "success"}:
return _task_ui_state(CP_UPLOADED, [])
if process_status == "closed":
if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}:
return _task_ui_state(CP_COMPLETED, [])
if process_status == "rejected" or review_status == "rejected":
if review_status == "rejected":
return _task_ui_state(CP_REJECTED, [])
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
@@ -380,30 +382,34 @@ def resolve_task_ui_state_from_fields(
if not order_snapshot_id and has_dynamic_order_lines:
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
# Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status,
# 也不能退回“处理中”或丢失下载/登记动作。
if has_export:
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
if (
process_status == "parsed"
and not review_status
and not pending_human_reason
and not inventory_lines_json
):
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
if (
process_status == "inventory_ready"
inventory_lines_json
and not review_status
and not pending_human_reason
and not match_status
and has_dynamic_order_lines
):
return _task_ui_state(CP_READY_MATCH, list(CHECKPOINT_REGISTRY[CP_READY_MATCH]))
if (
not inventory_lines_json
and not review_status
and not pending_human_reason
and has_dynamic_order_lines
):
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
if process_status == "matched":
if export_file_path:
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
if has_export:
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
return _task_ui_state(CP_READY_EXPORT, list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]))
@@ -417,18 +423,16 @@ def resolve_task_ui_state_from_fields(
)
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
return _task_ui_state(RS_SHORTAGE_REVIEW, list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]))
if reason == PH_UPLOAD_RPA_FAILED or process_status == "upload_failed":
if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed":
return _task_ui_state(CP_UPLOAD_FAILED, list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]))
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return _task_ui_state(
CP_UPLOAD_RESULT_UNKNOWN,
list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
)
if reason == PH_RPA_PENDING or (
process_status == "waiting_inventory" and reason == PH_RPA_PENDING
):
if reason == PH_RPA_PENDING:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
if reason == PH_UPLOAD_RPA_PENDING or process_status == "waiting_upload":
if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}:
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
return _task_ui_state(None, None)
@@ -439,10 +443,9 @@ def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
履约写操作由任务处理工作台消费 action_buttons;Chat 不再作为写入口。
履约写操作由任务处理工作台消费 ui_state.actions;Chat 不再作为写入口。
"""
return resolve_task_ui_state_from_fields(
process_status=task.process_status,
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
shipping_case_id=task.shipping_case_id,
@@ -471,12 +474,14 @@ def build_checkpoint_catalog() -> dict[str, Any]:
checkpoints = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
buttons = build_action_buttons(list(option_ids))
primary = next((button for button in buttons if button.get('variant') == 'primary'), None)
secondary = [button for button in buttons if button is not primary]
checkpoints.append(
{
"id": checkpoint_id,
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
"human_options": list(option_ids),
"action_buttons": buttons,
"actions": {"primary": primary, "secondary": secondary},
}
)
return {
@@ -513,7 +518,6 @@ _UNSET = object()
@dataclass(frozen=True)
class _TransitionSpec:
process_status: Any = _UNSET
review_status: Any = _UNSET
pending_human_reason: Any = _UNSET
clear_error_message: bool = False
@@ -546,69 +550,56 @@ class TaskTransition(StrEnum):
TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
TaskTransition.PARSED: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
),
TaskTransition.INVENTORY_READY: _TransitionSpec(
process_status="inventory_ready",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_EXHAUSTED,
),
TaskTransition.RPA_PENDING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_PENDING,
),
TaskTransition.INV_UNAVAIL: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_INV_UNAVAIL,
),
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
process_status="pending_review",
review_status=None,
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
),
TaskTransition.RSV_REQUIRED: _TransitionSpec(
process_status="pending_review",
review_status=RS_RSV_REQ,
pending_human_reason=PH_RSV_REQ,
),
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
process_status="pending_review",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason=PH_SHORTAGE,
),
TaskTransition.REJECTED: _TransitionSpec(
process_status="rejected",
review_status=RS_REJECTED,
pending_human_reason=None,
),
TaskTransition.CLOSED: _TransitionSpec(
process_status="closed",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
@@ -617,27 +608,22 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
pending_human_reason=None,
),
TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec(
process_status="pending_review",
review_status=None,
pending_human_reason=PH_NOTICE_TEXT_EXTRACTION_FAILED,
),
TaskTransition.REMATCH_REQUESTED: _TransitionSpec(
process_status="inventory_ready",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
TaskTransition.WAITING_UPLOAD: _TransitionSpec(),
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
process_status="waiting_upload",
pending_human_reason=PH_UPLOAD_RPA_PENDING,
),
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
process_status="upload_failed",
pending_human_reason=PH_UPLOAD_RPA_FAILED,
),
TaskTransition.UPLOADED: _TransitionSpec(
process_status="uploaded",
pending_human_reason=None,
clear_error_message=True,
),
@@ -646,7 +632,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> None:
"""
将命名状态迁移写入 ShippingNotice 的 process_status / review_status / pending_human_reason。
将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
@@ -656,8 +642,6 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
transition: TaskTransition 枚举值。
"""
spec = TASK_TRANSITIONS[transition]
if spec.process_status is not _UNSET:
task.process_status = spec.process_status
if spec.review_status is not _UNSET:
task.review_status = spec.review_status
if spec.pending_human_reason is not _UNSET:
@@ -78,7 +78,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
"""
将 Task 投影为固定顺序的 progress_nodes(不含进度百分比)。
核心逻辑:按客户确认 / 进程状态 / pending_human_reason 映射 WorkflowNodeStatus;
核心逻辑:按客户确认 / 领域事实 / pending_human_reason 映射 WorkflowNodeStatus;
货代上传节点在 Excel 就绪后为 manual_takeover(首期不启 RPA)。
Args:
@@ -88,21 +88,28 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
[{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。
"""
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
process_status = str(getattr(task, 'process_status', '') or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower()
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
review_status = str(getattr(task, 'review_status', '') or '').strip().lower()
has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip())
upload_status = str(getattr(task, 'upload_status', '') or '').strip().lower()
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} else
'upload_failed' if upload_status == 'failed' else
'matched' if match_status or has_export else
'inventory_ready' if getattr(task, 'inventory_lines_json', None) else
'pending_review' if pending or review_status else 'created'
)
terminal = process_status in {'uploaded', 'closed'}
freight_ready = process_status in {
terminal = progress_state in {'uploaded', 'closed'}
freight_ready = progress_state in {
'waiting_upload', 'upload_failed', 'export_ready', 'export_generated',
} or has_export
matched = process_status in {'matched', 'export_ready', 'export_generated', 'waiting_upload', 'upload_failed', 'uploaded', 'closed'} or has_export
inventory_ready = matched or process_status in {'inventory_ready', 'matching'}
inventory_preparing = process_status in {'waiting_inventory', 'parsed', 'created'}
matched = progress_state in {'matched', 'export_ready', 'export_generated', 'waiting_upload', 'upload_failed', 'uploaded', 'closed'} or has_export
inventory_ready = matched or progress_state in {'inventory_ready', 'matching'}
inventory_preparing = progress_state in {'waiting_inventory', 'parsed', 'created'}
rpa_active = pending in {'rpa_pending', 'rpa_exhausted'} or (
process_status == 'waiting_inventory' and pending in {'rpa_pending', 'inv_unavail', 'rpa_exhausted'}
pending in {'rpa_pending', 'inv_unavail', 'rpa_exhausted'}
)
match_blocked = (
review_status == 'shortage_review'
@@ -116,7 +123,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
elif customer_status in {'ambiguous', 'conflicted'} or pending in {'customer_review', 'customer_ambiguous'}:
customer_node = 'manual_takeover'
elif customer_status in {'pending', 'unresolved', ''}:
customer_node = 'pending' if process_status in {'created', ''} else 'manual_takeover'
customer_node = 'pending' if progress_state in {'created', ''} else 'manual_takeover'
else:
customer_node = 'pending'
@@ -138,7 +145,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
inventory_prepare_node = 'manual_takeover'
inventory_match_node = 'pending'
inventory_rpa_node = 'retrying' if pending == 'rpa_pending' else 'manual_takeover'
elif inventory_ready and process_status in {'inventory_ready', 'matching'}:
elif inventory_ready and progress_state in {'inventory_ready', 'matching'}:
inventory_prepare_node = 'succeeded'
inventory_match_node = 'running'
inventory_rpa_node = 'succeeded'
@@ -158,7 +165,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
# [STEP 6] 货代上传:RPA 进行中为 running/retrying;否则人工接管或成功。
if terminal:
freight_node = 'succeeded'
elif process_status == 'upload_failed' or pending == 'upload_rpa_failed':
elif progress_state == 'upload_failed' or pending == 'upload_rpa_failed':
freight_node = 'failed'
elif pending == 'upload_rpa_pending':
freight_node = 'running'
@@ -89,8 +89,6 @@ def _target_is_safe(task: ShippingNotice) -> bool:
核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。
"""
if str(task.process_status or '').strip().lower() != 'pending_review':
return False
if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ:
return False
if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no:
@@ -1,7 +1,7 @@
"""
services/shipping_notice/task_disposition_service.py
用途:集中处理发货任务的回收站、作废与归档生命周期,避免复用 process_status 的业务含义。
用途:集中处理发货任务的回收站、作废与归档生命周期,避免混用业务阶段和生命周期。
依赖:ShippingNotice / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、
SQLAlchemy 行锁、ShippingCase 生命周期事实。
逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent
@@ -49,7 +49,7 @@ def task_is_active(task: ShippingNotice) -> bool:
"""
判断任务是否仍可触发履约副作用。
核心逻辑:回收站、作废和归档都不是 process_status,因此所有异步入口必须统一调用本函数。
核心逻辑:回收站、作废和归档都不是业务阶段,因此所有异步入口必须统一调用本函数。
Args:
task: 已加载的发货任务。
@@ -112,12 +112,10 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
def _has_external_fulfillment(task: ShippingNotice) -> bool:
"""识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。"""
upload_status = str(task.upload_status or '').strip().lower()
process_status = str(task.process_status or '').strip().lower()
return bool(
task.freight_ref_no
or task.upload_receipt_json
or upload_status in _EXTERNAL_UPLOAD_STATUSES
or process_status in _EXTERNAL_PROCESS_STATUSES
)
@@ -242,7 +240,7 @@ def _write_disposition_event(
result='success',
after={
'lifecycle_status': getattr(task, 'lifecycle_status', None),
'process_status': getattr(task, 'process_status', None),
'upload_status': getattr(task, 'upload_status', None),
},
metadata={
'dual_write': 'shipping_task_event',
@@ -315,7 +313,6 @@ def move_task_to_recycle_bin(
detail={
'outcome': outcome,
'reason': normalized_reason,
'process_status_before': task.process_status,
'lifecycle_status_after': task.lifecycle_status,
},
)
@@ -346,7 +343,7 @@ def void_task(
event_type='task_voided',
actor_id=actor_id,
request_id=request_id,
detail={'reason': normalized_reason, 'process_status_before': task.process_status},
detail={'reason': normalized_reason, 'lifecycle_status_before': 'active'},
)
@@ -356,7 +353,7 @@ def archive_task(
actor_id: int,
request_id: str | None = None,
) -> None:
"""归档任务以隐藏默认列表,不改变外部或 process_status 业务事实。"""
"""归档任务以隐藏默认列表,不改变订单/通知领域事实。"""
capability = task_disposition_capability(task, 'archive')
if not capability.allowed:
raise ConflictError(capability.reason or 'Task archive is blocked', code=capability.code or 'SHIPPING.TASK_ARCHIVE_BLOCKED')
@@ -368,7 +365,7 @@ def archive_task(
event_type='task_archived',
actor_id=actor_id,
request_id=request_id,
detail={'process_status': task.process_status},
detail={'lifecycle_status': task.lifecycle_status},
)
@@ -464,7 +461,6 @@ def purge_task_permanently(
request_id=str(request_id or '').strip()[:64] or None,
snapshot_json={
'task_no': task.task_no,
'process_status': task.process_status,
'lifecycle_status': task.lifecycle_status,
'deleted_at': task.deleted_at.isoformat() if task.deleted_at else None,
'deletion_reason': task.deletion_reason,
@@ -246,14 +246,15 @@ def _decide(
"""
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
# 题2B:统一直接用入参 latest_active(调用方已查逐源 Attempt);无入参时回落旧实现
active = latest_active if isinstance(latest_active, dict) else (
summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
)
if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}:
lifecycle_status = str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower()
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if lifecycle_status in {'voided', 'archived', 'deleted'} or upload_status in {'uploaded', 'succeeded', 'success'}:
return {
'action': ACTION_NOOP,
'status': STATUS_COMPLETED,
@@ -769,7 +770,7 @@ def _result_payload(
'task_no': task.task_no,
'idempotent_replay': bool(idempotent_replay),
'action': action,
'stage': str(getattr(task, 'process_status', None) or '') or None,
'stage': None,
'status': status,
'retryable': bool(retryable),
'job_id': job_id,
@@ -1024,7 +1025,7 @@ def _audit_decision(
'scope': scope,
'line_key': line_key,
'trigger': trigger,
'previous_stage': str(getattr(task, 'process_status', None) or '') or None,
'previous_stage': None,
'next_stage': result.get('stage'),
'action': action,
'decision_version': result.get('decision_version'),
@@ -18,7 +18,7 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
if not task_is_active(old):
return
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'} or old.process_status == 'uploaded')
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'})
if external:
existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none()
if existing is None:
@@ -173,10 +173,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
checkpoint=CP_TASK_EXISTS,
)
if conv_id:
terminal_statuses = {"uploaded", "rejected", "closed"}
existing = (
ShippingNotice.query.filter_by(conversation_id=conv_id)
.filter(ShippingNotice.process_status.notin_(list(terminal_statuses)))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
.first()
)
@@ -214,7 +213,6 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
customer_resolution_method=(
'inherited' if shipping_case.customer_id is not None else None
),
process_status="created",
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type})
@@ -624,7 +622,6 @@ def _record_formal_task_edit_audits(
'match_status': task.match_status,
'export_file_name': task.export_file_name,
'order_data_version': task.order_data_version,
'process_status': task.process_status,
}
field_changes = _formal_edit_field_diff_summary(
before_header=before_header,
@@ -815,7 +812,6 @@ def replace_task_notice(
task.review_status = None
task.pending_human_reason = None
task.error_message = None
task.process_status = "created"
_reset_notice_edit_downstream(task)
set_task_step_progress(
task,
@@ -1413,7 +1409,7 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
event_source = str(payload.get("event_source") or ("workspace_api" if actor_id else "system")).strip() or "system"
before = task_lifecycle_audit_snapshot(task)
# [STEP 1] 清理阻断态并恢复到可续跑 process_status。
# [STEP 1] 清理阻断事实并恢复到可续跑 Gate。
task.review_status = None
task.pending_human_reason = None
task.error_message = None
@@ -1422,17 +1418,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
order_lines = current_line_field_values(task)
except ConflictError:
order_lines = []
if not task.raw_content and not order_lines:
task.process_status = "created"
elif order_lines:
if task.export_file_path:
task.process_status = "matched"
elif task.inventory_lines_json:
task.process_status = "inventory_ready"
else:
task.process_status = "parsed"
else:
task.process_status = "created"
after = task_lifecycle_audit_snapshot(task)
log_task_event(
@@ -1440,7 +1425,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
"task_retry_requested",
{
"comment": comment,
"restored_process_status": task.process_status,
"reason_code": "task_retry_requested",
},
actor_id=actor_id,
@@ -1463,7 +1447,7 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
reason=comment or None,
before=before,
after=after,
metadata={'restored_process_status': task.process_status},
metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)},
source=event_source,
)
sync_batch_after_task_change(task)
@@ -496,7 +496,7 @@ def log_task_event(
reason_code=reason_code,
result='failure' if is_failure else 'success',
before=safe_before,
after=safe_after or {'status': getattr(task, 'process_status', None)},
after=safe_after or {'phase': getattr(task, 'current_step', None)},
metadata=meta,
source=str(source or 'system')[:32],
strict=True,
@@ -570,7 +570,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]:
可写入 before/after 的受控快照 dict(可能为空)。
"""
snapshot = {
'status': getattr(task, 'process_status', None),
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'reason_code': getattr(task, 'pending_human_reason', None),
}
@@ -2,9 +2,9 @@
services/shipping_notice/tool_response.py
用途:统一构建发货通知 Tool 的 JSON 响应结构。
依赖:state_machine 中的 checkpoint/human_options/action_buttons 解析能力;ShippingProcessExecution。
依赖:state_machine 中的 checkpoint/human_options 解析能力;ShippingProcessExecution。
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
已绑定 ProcessExecution 的任务不再下发旧 action_buttons / next_required_action(恢复仅由 Gate 驱动)。
已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。
"""
from __future__ import annotations
@@ -85,37 +85,30 @@ def tool_response(
"""
构建发货通知 Tool 标准 JSON 响应。
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options/action_buttons;
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options;
显式 checkpoint 优先(如 parse_ok、task_exists)。
若任务已有 ProcessExecution:不再填充 action_buttons / next_required_action,避免与 Gate 双真相。
若任务已有 ProcessExecution:不再填充旧动作字段,避免与 Gate 双真相。
Args:
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
extra: 需要保留在顶层的兼容字段,例如 batch_no。
"""
from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
build_action_buttons,
resolve_task_ui_state,
)
from app.services.shipping_notice.state_machine import resolve_task_ui_state
if task is not None and not task_id:
task_id = task.task_no
gate_owns_recovery = _task_has_process_execution(task)
# action_buttons 是历史调用参数,仅为兼容调用方签名;绝不进入对外响应。
del action_buttons
resolved_checkpoint = checkpoint
resolved_human_options = human_options
resolved_action_buttons = action_buttons
if checkpoint is None and task is not None:
ui = resolve_task_ui_state(task)
resolved_checkpoint = ui.checkpoint
if human_options is None:
resolved_human_options = ui.human_options
# [STEP] Gate 绑定任务:忽略状态机推导的旧动作按钮。
if not gate_owns_recovery and action_buttons is None and ui.action_buttons:
resolved_action_buttons = ui.action_buttons
payload: dict[str, Any] = {
"status": status,
@@ -127,17 +120,7 @@ def tool_response(
if resolved_human_options is not None:
payload["human_options"] = resolved_human_options
# [STEP] ProcessExecution 存在时业务调用清零旧动作字段(含调用方显式传入)。
if gate_owns_recovery:
payload["action_buttons"] = []
elif resolved_action_buttons is not None:
payload["action_buttons"] = resolved_action_buttons
elif resolved_human_options is not None:
payload["action_buttons"] = build_action_buttons(resolved_human_options)
elif resolved_checkpoint:
buttons = action_buttons_for_checkpoint(resolved_checkpoint)
if buttons:
payload["action_buttons"] = buttons
# [STEP] 业务按钮统一由 ui_state.actions 返回;Tool 响应不再生成旧 action_buttons。
if resolved_checkpoint:
payload["checkpoint"] = resolved_checkpoint
if next_required_action and not gate_owns_recovery:
@@ -148,8 +131,7 @@ def tool_response(
payload["stop_agent_turn"] = True
if extra:
payload.update(extra)
# [STEP] extra 不得绕过 Gate 绑定任务的旧动作清零。
# [STEP] extra 不得绕过 Gate 绑定任务的旧 next_required_action 约束。
if gate_owns_recovery:
payload["action_buttons"] = []
payload.pop("next_required_action", None)
return payload
+176 -47
View File
@@ -5,14 +5,10 @@ services/shipping_notice/ui_state.py
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions,
再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes);
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
[兼容] action_buttons 为只读兼容字段:权威可恢复操作入口已统一为
process_gate.next_action_code(如 retry_inventory_preparation),本字段仅保留供
任务详情 / 聊天状态 / 旧入口消费,禁止再向其新增恢复动作;待确认无活跃消费者后删除。
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
"""
@@ -68,13 +64,10 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"},
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
@@ -138,41 +131,157 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
}
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
{"code": "intake_parse", "label": "接收解析"},
{"code": "order_review", "label": "订单复核"},
{"code": "fulfillment_prep", "label": "发货准备"},
{"code": "upload_complete", "label": "上传完成"},
)
_STAGE_GATE_CODES: dict[str, str] = {
"document_materialization": "intake_parse",
"layout_parsing": "intake_parse",
"document_profile_routing": "intake_parse",
"order_field_extraction": "intake_parse",
"field_completeness": "order_review",
"reservation_validation": "order_review",
"customer_resolution": "order_review",
"duplicate_detection": "order_review",
"field_conflict_resolution": "order_review",
"order_freeze_readiness": "order_review",
"task_creation": "order_review",
"inventory_source_routing": "fulfillment_prep",
"inventory_preparation": "fulfillment_prep",
"inventory_field_mapping": "fulfillment_prep",
"inventory_matching": "fulfillment_prep",
"inventory_sufficiency": "fulfillment_prep",
"excel_readiness": "fulfillment_prep",
"artifact_generation": "fulfillment_prep",
"freight_upload_rpa": "upload_complete",
"manual_upload_handoff": "upload_complete",
}
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
CP_CUSTOMER_REVIEW: "order_review",
CP_ORDER_FREEZE: "order_review",
CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep",
CP_INVENTORY_PENDING: "fulfillment_prep",
CP_READY_MATCH: "fulfillment_prep",
RS_SHORTAGE_REVIEW: "fulfillment_prep",
CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "upload_complete",
CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "upload_complete",
CP_UPLOAD_RESULT_UNKNOWN: "upload_complete",
CP_UPLOADED: "upload_complete",
CP_COMPLETED: "upload_complete",
CP_REJECTED: "order_review",
}
def _business_stage(
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
gate_code = str(gate.get("gate_code") or "").strip()
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
if not stage_code:
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
"""规范 Gate/旧状态机动作,前端只渲染该统一结构。"""
item = dict(action or {})
code = str(item.get("code") or item.get("id") or "").strip()
dispatch = str(item.get("dispatch") or "").strip()
kind = str(item.get("kind") or "").strip()
if kind in {"current_gate", ""}:
kind = "view" if dispatch in {"navigation", "refresh"} and code.startswith("view_") else default_kind
return {
"code": code,
"label": item.get("label") or item.get("label_key") or code,
"kind": kind,
"enabled": bool(item.get("enabled", True)),
"requires_confirmation": bool(item.get("requires_confirmation", False)),
"target_surface": item.get("target_surface") or ("shipping_task_workbench" if dispatch == "navigation" else None),
"disabled_reason": item.get("disabled_reason"),
"expected_gate_version": item.get("expected_gate_version"),
}
def _unified_actions(
*, process_gate: dict[str, Any] | None, action_buttons: list[dict[str, str]],
) -> dict[str, Any]:
"""统一输出唯一主动作与次动作;动作来源优先为 Gate。"""
gate_actions = list((process_gate or {}).get("action_presentation") or [])
if process_gate and (process_gate.get("primary_action") or gate_actions):
primary_raw = process_gate.get("primary_action") or gate_actions[0]
primary_code = str((primary_raw or {}).get("code") or (primary_raw or {}).get("id") or "").strip()
secondary_raw = [
item for item in gate_actions
if str((item or {}).get("code") or (item or {}).get("id") or "").strip() != primary_code
]
else:
primary_raw = action_buttons[0] if action_buttons else None
secondary_raw = action_buttons[1:] if action_buttons else []
gate_view = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
expected_version = gate_view.get("evaluation_version") or (process_gate or {}).get("lock_version")
def normalize(item: dict[str, Any] | None) -> dict[str, Any] | None:
if not item:
return None
result = _unified_action(item)
if result.get("expected_gate_version") is None and expected_version is not None:
result["expected_gate_version"] = int(expected_version)
return result
primary = normalize(primary_raw)
secondary = [normalized for item in secondary_raw if (normalized := normalize(item))]
return {"primary": primary, "secondary": secondary}
def _derive_current_step_index(task: ShippingNotice) -> int:
"""
根据任务字段推导七步流程当前索引。
根据任务领域事实推导四阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底,
保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
return _CURRENT_STEP_INDEX_MAP[current_step]
legacy_index = _CURRENT_STEP_INDEX_MAP[current_step]
return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2
process_status = str(task.process_status or "").strip()
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if process_status in _TERMINAL_PROCESS_STATUSES:
return 6
if process_status in {"waiting_upload", "upload_failed"} or has_export:
return 5
if process_status == "matched":
return 4
if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}:
return 3
if upload_status in {"pending", "uploading", "failed"} or has_export:
return 2
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
return 2
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 4
if process_status == "inventory_ready" or match_status:
return 4
if process_status == "waiting_inventory" or pending_reason in {
return 2
if task.inventory_lines_json or match_status:
return 2
if pending_reason in {
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
if process_status in {"parsed", "pending_review"} or review_status in {
if review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
@@ -182,18 +291,17 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
"""
构造七步流程状态。
构造四阶段流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
current_index = _derive_current_step_index(task)
process_status = str(task.process_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
if process_status in _TERMINAL_PROCESS_STATUSES:
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
status = "completed"
elif index < current_index:
status = "completed"
@@ -201,15 +309,17 @@ def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None)
status = "current"
else:
status = "pending"
inventory_blocked = (
index == 2
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
)
inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
parse_blocked = index == 1 and (
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ}
)
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
prep_blocked = index == 2 and (
checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW}
or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE}
)
upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -584,9 +694,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
"""
构建单票任务 UI State。
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary,
禁止 Chat、通知卡与任务中心分别推导状态;有 Execution 时附带统一 Gate 用户摘要;
存在 current_blocking_gate 时清空 STP action_buttons,恢复仅走 process_gate。
存在 current_blocking_gate 时只输出 Gate actions,禁止旧动作列表穿透。
"""
ui = resolve_task_ui_state(task)
action_buttons = _action_buttons_for_task(task)
@@ -622,21 +732,40 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
if process_gate.get('current_blocking_gate'):
summary['allowed_actions'] = []
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
checkpoint_payload = {
"code": ui.checkpoint,
"kind": str(ui.checkpoint_kind),
"label": str(ui.checkpoint or "") or None,
}
reason = None
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
reason = {
"code": process_gate.get("blocking_reason_code"),
"message": process_gate.get("blocking_message"),
}
return {
"task_no": task.task_no,
"batch_no": None,
"checkpoint": ui.checkpoint,
"stage": stage,
"checkpoint": checkpoint_payload,
"checkpoint_view": checkpoint_payload,
"todo": {
"title": summary.get("current_todo") or summary.get("title"),
"message": summary.get("message"),
},
"actions": actions,
"reason": reason,
"lifecycle_status": task.lifecycle_status,
"checkpoint_code": ui.checkpoint,
"checkpoint_kind": str(ui.checkpoint_kind),
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"match_status": task.match_status,
"current_step": current_step,
"steps": steps,
"summary": summary,
# [兼容] action_buttons 为只读兼容字段(见模块 docstring);新 UI 应消费
# summary.process_gate.next_action_code,本字段仅作历史消费者过渡,不再扩展。
"action_buttons": action_buttons,
"process_gate": process_gate,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
@@ -74,10 +74,8 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None:
if reservations and all(item.status == 'uploaded' for item in reservations):
task.upload_status = 'uploaded'
task.upload_finished_at = datetime.utcnow()
task.process_status = 'uploaded'
elif any(item.status == 'uploaded' for item in reservations):
task.upload_status = 'partial'
task.process_status = 'waiting_upload'
else:
task.upload_status = 'pending'
@@ -34,10 +34,6 @@ from app.services.shipping_notice.state_machine import resolve_task_ui_state
# Fields omitted from Dify Tool `data` — Agent must not parrot these to users.
TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
{
"process_status",
"review_status",
"match_status",
"pending_human_reason",
"error_message",
}
)
@@ -99,10 +95,9 @@ def user_facing_task_stage(task: ShippingNotice) -> str:
ui = resolve_task_ui_state(task)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
process = str(task.process_status or "").strip()
return _PROCESS_STATUS_LABELS.get(process, "处理中")
return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束"
def strip_internal_task_fields(data: dict) -> dict:
"""从 Tool data 投影中移除 process_status 等内部字段,避免 Agent 复述给用户。"""
"""从 Tool data 投影中移除内部执行字段,避免 Agent 复述给用户。"""
return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT}
@@ -22,7 +22,6 @@ from app.models import ShippingOrderProcessingRun, ShippingOrderReviewCase, Ship
# 确认后可撤销窗口(小时);保留常量供历史引用,账本下线后无实际作用。
CONFIRM_REVOKE_WINDOW_HOURS = 24
# 已进入库存匹配或更后履约阶段的 process_status。
_INVENTORY_MATCHED_OR_LATER = frozenset({
'matched',
'waiting_upload',
@@ -329,7 +328,7 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
"""
判断任务是否已进入库存匹配或更后履约阶段。
核心逻辑:仅读 Task.process_status,不访问 Workflow 表。
核心逻辑:使用库存匹配、Excel、上传等领域事实,不读取旧流程状态字段。
Args:
task: 发货任务。
@@ -337,7 +336,12 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
Returns:
True 表示已进入 matched 或更后阶段。
"""
return str(task.process_status or '').strip().lower() in _INVENTORY_MATCHED_OR_LATER
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool(
str(getattr(task, 'export_file_path', None) or '').strip()
or str(getattr(task, 'freight_ref_no', None) or '').strip()
or str(getattr(task, 'upload_status', None) or '').strip()
)
def revoke_review_confirmation(**_kwargs: Any) -> None: