""" services/shipping_notice/ui_state.py 用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract。 逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons, 再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts); 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 """ from __future__ import annotations from typing import Any from app.models import ShippingBatch, ShippingTask from app.services.shipping_notice.constants import ( CP_COMPLETED, CP_CUSTOMER_REVIEW, CP_EXPORT_GENERATED, CP_EXPORT_READY, CP_INVENTORY_PENDING, CP_INVENTORY_SOURCE_REVIEW, CP_ORDER_FREEZE, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_REVIEW, CP_READY_EXPORT, CP_READY_MATCH, CP_REJECTED, CP_RSV_REQ, CP_UPLOADED, CP_UPLOAD_FAILED, CP_UPLOAD_RESULT_UNKNOWN, CP_UPLOAD_REQ, CP_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_RSV_REQ, PH_SHORTAGE, PH_UPLOAD_RPA_PENDING, RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable from app.services.shipping_notice.query_service import ( compute_batch_process_summary, list_sorted_batch_tasks, serialize_batch_summary, serialize_task_summary, ) from app.services.shipping_notice.state_machine import ( CheckpointKind, inventory_source_action_buttons, resolve_task_ui_state, ) from app.services.shipping_notice.user_facing_status import user_facing_task_stage 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": "上传货代"}, ) _CURRENT_STEP_INDEX_MAP: dict[str, int] = { "step1_notice_submit": 0, "step2_parse_confirm": 1, "step3_inventory_prepare": 2, "step2_inventory_prepare": 2, "step4_align_confirm": 3, "step5_match_inventory": 4, "step3_inventory_match": 4, "step4_shortage_review": 4, "step6_generate_file": 5, "step5_export_excel": 5, "step7_upload_freight": 6, "step6_upload_freight": 6, "step7_finish": 6, } _TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"} _BLOCKED_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_ORDER_FREEZE, RS_SHORTAGE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_UPLOAD_REQ, CP_UPLOAD_FAILED, CP_UPLOAD_RESULT_UNKNOWN, CP_CUSTOMER_REVIEW, CP_EXPORT_READY, CP_EXPORT_GENERATED, } _REVIEW_ENTRY_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED, } _NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = { CP_INVENTORY_PENDING: "ensure_inventory", CP_ORDER_FREEZE: "freeze_order", CP_READY_MATCH: "match_inventory", CP_READY_EXPORT: "generate_excel", } _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"), CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"), CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"), CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"), CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源尚未唯一确定"), CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"), RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"), CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"), CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), } def _derive_current_step_index(task: ShippingTask) -> int: """ 根据任务字段推导七步流程当前索引。 核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底, 保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。 """ current_step = str(task.current_step or "").strip() if current_step in _CURRENT_STEP_INDEX_MAP: return _CURRENT_STEP_INDEX_MAP[current_step] 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() 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 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 { PH_RPA_PENDING, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, }: return 2 if process_status in {"parsed", "pending_review"} or review_status in { RS_PARSE_REVIEW, PH_RSV_REQ, } or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}: return 1 return 0 def build_shipping_workflow_steps(task: ShippingTask, 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: status = "completed" elif index < current_index: status = "completed" elif index == current_index: status = "current" else: status = "pending" 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} ) if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked): status = "blocked" steps.append({**step, "status": status}) return steps def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]: """ 从状态机解析当前任务可用动作按钮;多源匹配阻断时前置「人工指定库存源」。 核心逻辑:库存源确认场景补充 source_code;shortage + multi_source/multi_file 冲突时 注入 confirm_inventory_source,使工作台可打开候选选择对话框。 """ from app.services.shipping_notice.state_machine import ACTION_SPECS from app.services.shipping_notice.stp_line_inventory_match import ( multi_source_recovery_source_codes, needs_multi_source_manual_recovery, ) ui = resolve_task_ui_state(task) if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW: return inventory_source_action_buttons(task) if ui.checkpoint == RS_SHORTAGE_REVIEW and needs_multi_source_manual_recovery(task): codes = multi_source_recovery_source_codes(task) confirm_spec = dict(ACTION_SPECS.get('confirm_inventory_source') or {}) confirm_btn: dict[str, str] = { 'id': 'confirm_inventory_source', 'label': str(confirm_spec.get('label') or '人工指定库存源'), 'message': '请选择单一库存源后继续匹配', 'variant': str(confirm_spec.get('variant') or 'primary'), } if len(codes) == 1: confirm_btn['source_code'] = codes[0] confirm_btn['label'] = f"指定库存源:{codes[0]}" confirm_btn['message'] = f"使用库存源 {codes[0]} 重新匹配" else: confirm_btn['label'] = '人工指定库存源' # 保留重试/重匹配/驳回,但把指定源放在首位作为主恢复入口。 rest = [btn for btn in (ui.action_buttons or []) if str(btn.get('id') or '') != 'confirm_inventory_source'] return [confirm_btn, *rest] return ui.action_buttons _PARSE_STAGE_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_ORDER_FREEZE, CP_NOTICE_TEXT_EXTRACTION_FAILED, } _WARNING_DISPLAY_ALIASES: dict[str, str] = { "parse_fallback_heuristic": "解析引擎回退到启发式规则,请人工核对字段。", "heuristic_no_lines_detected": "启发式解析未识别到订单行,请核对通知内容。", } def _normalize_issue_text(raw: Any) -> str: """将 warnings / error 原文规范化为可展示短文案,过滤空值。""" text = str(raw or "").strip() if not text: return "" return _WARNING_DISPLAY_ALIASES.get(text, text) def _append_unique_issue(issues: list[str], raw: Any) -> None: """追加去重后的问题文案,保持首次出现顺序。""" text = _normalize_issue_text(raw) if text and text not in issues: issues.append(text) def _parse_validation_issue_text(issue: dict[str, Any]) -> str: """把关键字段问题转换成工作台文案,并保留行号、内部料号与原始值。""" line_no = int(issue.get("line_index") or 0) + 1 part_number = str(issue.get("part_number") or "-").strip() or "-" raw_value = str(issue.get("raw_value") or "").strip() resolved_value = str(issue.get("resolved_value") or "").strip() reason = str(issue.get("reason") or "").strip() if reason == "value_corrected": return f"第 {line_no} 行料号 {part_number}:Reservation ID 已由 {raw_value or '空值'} 纠正为 {resolved_value}。" if reason == "source_conflict": values = ", ".join(str(item) for item in issue.get("evidence_values") or []) return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 与原文列证据 {values or '-'} 冲突。" if reason == "invalid_format": return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 格式不合法。" return f"第 {line_no} 行料号 {part_number}:缺少合法的 Reservation ID。" def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> list[str]: """ 汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发; 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。 """ checkpoint_value = str(checkpoint or "").strip() if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS: return [] issues: list[str] = [] if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW: _append_unique_issue( issues, task.error_message or "无法根据发货通知唯一确定库存查询来源", ) elif checkpoint_value == CP_RSV_REQ: _append_unique_issue( issues, task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)", ) elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED: _append_unique_issue( issues, task.error_message or "未能从发货通知中解析到可审核内容", ) elif checkpoint_value == CP_PARSE_REVIEW: _append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。") if not is_inventory_source_stable(task): _append_unique_issue( issues, "解析确认通过后,若库存源仍无法唯一命中,还需选择正式库存源。", ) payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} progress = payload.get("current_step_progress") if isinstance(payload, dict) else None extra = progress.get("extra") if isinstance(progress, dict) else None warnings = extra.get("warnings") if isinstance(extra, dict) else None if isinstance(warnings, list): for item in warnings: _append_unique_issue(issues, item) parse_validation = payload.get("parse_validation") if isinstance(payload, dict) else None structured_issues = parse_validation.get("issues") if isinstance(parse_validation, dict) else None if isinstance(structured_issues, list): for item in structured_issues: if isinstance(item, dict): _append_unique_issue(issues, _parse_validation_issue_text(item)) return issues def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str: """ 解析当前操作应进入的工作台类型。 Returns: review_workbench | task_workbench | none """ # Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。 if str(checkpoint or "") in {CP_EXPORT_READY, CP_EXPORT_GENERATED}: return "task_workbench" if kind == CheckpointKind.COMPLETE: return "none" if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS: return "review_workbench" if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}: return "task_workbench" if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in { CP_ORDER_FREEZE, CP_READY_MATCH, CP_READY_EXPORT, CP_INVENTORY_PENDING, }: # 自动链可继续,但仍允许工作台手动兜底 return "task_workbench" return "none" def _current_todo_label(checkpoint: str | None, action_buttons: list[dict[str, str]]) -> str | None: """从当前动作按钮推导「当前待办」文案;无人工动作时返回 None。""" if not action_buttons: pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) return pause[1] if pause else None primary = next((b for b in action_buttons if b.get("variant") == "primary"), action_buttons[0]) label = str(primary.get("label") or "").strip() return label or None def _build_stp_facts(task: ShippingTask) -> dict[str, Any] | None: """ 投影 STP 履约事实供 Chat/工作台/待办同源消费。 核心逻辑:只读 task + step_payload;无 STP 痕迹时返回 None,避免普通任务噪声。 Args: task: 发货任务。 Returns: stp_facts 字典或 None。 """ from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} status = str(task.inventory_source_status or '').strip() method = str(task.inventory_source_method or '').strip() candidates = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {} resolutions_raw = payload.get('line_inventory_resolutions') resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else [] multi_block = bool(payload.get('multi_source_excel_block')) frozen_codes = list(candidates.get('source_codes') or []) or task_frozen_inventory_source_codes(task) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') or bool(frozen_codes) or bool(resolutions) or multi_block or bool(payload.get('line_inventory_candidates')) ) if not has_stp: return None counts: dict[str, int] = {} compact_resolutions: list[dict[str, Any]] = [] for item in resolutions: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 compact_resolutions.append({ 'line_index': item.get('line_index'), 'line_key': item.get('line_key'), 'disposition': disposition, 'effective_reservation_id': item.get('effective_reservation_id'), 'part_number': item.get('part_number'), 'resolved_inventory_source_code': item.get('resolved_inventory_source_code'), 'inventory_file_no': item.get('inventory_file_no'), 'inventory_row_ref': item.get('inventory_row_ref'), }) recovery_codes = multi_source_recovery_source_codes(task) facts = { 'inventory_source_status': status or None, 'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None, 'inventory_source_method': method or None, 'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()], 'resolution_counts': counts, 'line_resolutions': compact_resolutions, 'multi_source_excel_block': multi_block, 'resolved_ok_source_codes': [ str(code).strip().upper() for code in (payload.get('resolved_ok_source_codes') or []) if str(code or '').strip() ], 'recovery_source_codes': recovery_codes, 'match_status': str(task.match_status or '').strip() or None, } return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts} def _build_task_summary( task: ShippingTask, checkpoint: str | None, *, checkpoint_kind: CheckpointKind, action_buttons: list[dict[str, str]], ) -> dict[str, Any]: """ 输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。 核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、 pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts。 """ title = user_facing_task_stage(task) message_by_checkpoint: dict[str, str] = { CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。", CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。", CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。", CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。", CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。", RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。", CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。", CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", CP_REJECTED: "任务已驳回,无需继续处理。", CP_UPLOADED: "任务已完成上传。", CP_COMPLETED: "任务已关闭。", } issues = _collect_parse_stage_issues(task, checkpoint) pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) pause_reason_code = pause[0] if pause else (task.pending_human_reason or None) pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None) message = message_by_checkpoint.get(str(checkpoint or ""), title) stp_facts = _build_stp_facts(task) current_todo_override: str | None = None # [STEP] STP 多源 Excel 阻断:覆盖通用 shortage 文案,并提示可指定库存源。 if stp_facts and stp_facts.get('multi_source_excel_block'): pause_reason_code = 'multi_source_excel_block' pause_reason = '订单行命中多个不同库存源,首期无法生成单一发货 Excel,请拆单或人工指定库存源后继续' message = pause_reason title = '多库存源冲突,待人工处理' issue_text = pause_reason if issue_text not in issues: issues = [*issues, issue_text] current_todo_override = '请拆单或人工指定库存源后继续' elif stp_facts and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' and checkpoint_kind == CheckpointKind.AUTO_CONTINUE: message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。' if checkpoint_kind == CheckpointKind.AUTO_CONTINUE and not (stp_facts and stp_facts.get('multi_source_excel_block')): pause_reason = None pause_reason_code = None allowed_actions = [str(btn.get("id")) for btn in action_buttons if btn.get("id")] event_at = None if task.updated_at is not None: event_at = task.updated_at.isoformat() summary: dict[str, Any] = { "title": title, "message": message, "error_message": task.error_message or task.upload_error_message, "issues": issues, "stage": title, "checkpoint_kind": str(checkpoint_kind), "current_todo": ( current_todo_override if current_todo_override is not None else ( pause_reason if stp_facts and stp_facts.get('multi_source_excel_block') else _current_todo_label(checkpoint, action_buttons) ) ), "pause_reason": pause_reason, "pause_reason_code": pause_reason_code, "next_auto_step": ( _NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or "")) if checkpoint_kind == CheckpointKind.AUTO_CONTINUE else None ), "event_at": event_at, "entry_surface": _entry_surface_for(checkpoint, checkpoint_kind), "allowed_actions": allowed_actions, } if stp_facts is not None: summary['stp_facts'] = stp_facts return summary def build_task_ui_state(task: ShippingTask) -> dict[str, Any]: """ 构建单票任务 UI State。 核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary, 禁止 Chat、通知卡与任务中心分别推导状态。 """ ui = resolve_task_ui_state(task) action_buttons = _action_buttons_for_task(task) steps = build_shipping_workflow_steps(task, ui.checkpoint) current_index = _derive_current_step_index(task) current_step = steps[current_index] if 0 <= current_index < len(steps) else None return { "task_no": task.task_no, "batch_no": task.batch.batch_no if task.batch is not None else None, "checkpoint": 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": _build_task_summary( task, ui.checkpoint, checkpoint_kind=ui.checkpoint_kind, action_buttons=action_buttons, ), "action_buttons": action_buttons, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]: """ 构建批次级会话上传集合摘要(非履约写操作面)。 核心逻辑:批次仅聚合各 PDF/Task 的同源 ui_state,供会话右侧「本次上传」摘要消费; 履约写操作一律进入任务处理工作台。 """ tasks = list_sorted_batch_tasks(batch) focus_task_no = str(batch.current_focus_task_no or "").strip() focus_task = next((task for task in tasks if task.task_no == focus_task_no), None) if focus_task is None and tasks: focus_task = tasks[0] task_states = [ { **serialize_task_summary(task), "ui_state": build_task_ui_state(task), } for task in tasks ] return { **serialize_batch_summary(batch), "role": "upload_session_summary", "process_summary": batch.process_summary_json or compute_batch_process_summary(tasks), "focus_task": serialize_task_summary(focus_task) if focus_task else None, "focus_task_ui_state": build_task_ui_state(focus_task) if focus_task else None, "tasks": task_states, }