- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划
3304 lines
147 KiB
Python
3304 lines
147 KiB
Python
"""
|
||
services/shipping_notice/query_service.py
|
||
|
||
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||
依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
|
||
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
|
||
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
|
||
order_review_projection(任务中心 STP retry 动作投影)。
|
||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||
tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉;
|
||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event,
|
||
以及统一 shipping_processing_status / progress_version / order_task_no(BE-02),
|
||
直接序列化 ShippingOrderTask 时 order_task_no 取自身 task_no(禁止经 order_task_id 冲 null),
|
||
并注入 review_run_no 供任务中心深链订单处理工作台(UI-04);
|
||
list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办;
|
||
serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create;
|
||
客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与确认客户/来源文档;
|
||
待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);
|
||
无 Execution fail-closed 进 pending(复核位 review,有 Excel 则 manual_upload,否则 exception),禁止默认 in_progress;
|
||
SQL CASE 与 derive_todo_category / F2 running 同序,处理中桶只对应系统在跑;
|
||
list 与 count 都以 CASE 为权威,禁止再用「有原因/有产物」粗筛漏掉 fail-closed 项;
|
||
list 用 UNION ALL + COUNT/OFFSET/LIMIT,仅水合当前页(禁止 500 截断冒充总数);
|
||
fetch_gate_positions 批量读 Execution.current_gate_code,供 Gate 推导待办避免 N+1;
|
||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact);
|
||
view=workbench 跳过 SUMMARY/DETAIL 重投影,仅身份壳 + enrich(ui_state),禁止算完再删;
|
||
co8 起 WorkflowItem 账本已下线,不再附加 workflow_item 投影(BE-06);
|
||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from enum import Enum
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from sqlalchemy import String, asc, case, cast, desc, exists, func, literal, select, union_all
|
||
from sqlalchemy.orm import aliased
|
||
|
||
from app import db
|
||
from app.core.errors import ValidationError
|
||
from app.models import (
|
||
FileAsset,
|
||
ShippingExportArtifact,
|
||
ShippingExportArtifactLine,
|
||
ShippingInventoryVerification,
|
||
ShippingInventoryFile,
|
||
ShippingOrderCandidate,
|
||
ShippingOrderDocument,
|
||
ShippingOrderIntake,
|
||
ShippingOrderExtraction,
|
||
ShippingOrderProcessingRun,
|
||
ShippingOrderProcessingRunIntake,
|
||
ShippingOrderLine,
|
||
ShippingOrderReviewCase,
|
||
ShippingOrderSnapshot,
|
||
ShippingOrderSnapshotLine,
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderSubmission,
|
||
ShippingReservation,
|
||
ShippingNotice,
|
||
ShippingOrderTask,
|
||
ShippingCustomer,
|
||
ShippingCustomerShadowResolution,
|
||
ShippingProcessExecution,
|
||
ShippingProcessGate,
|
||
ShippingTaskInventoryLink,
|
||
ShippingNoticeLine,
|
||
ShippingNoticeLineInventoryMatch,
|
||
ShippingTaskEvent,
|
||
ShippingUploadAttempt,
|
||
)
|
||
from app.services.shipping_notice.constants import (
|
||
PH_INV_UNAVAIL,
|
||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||
PH_LOW_CONF,
|
||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
PH_RPA_EXHAUSTED,
|
||
PH_RPA_PENDING,
|
||
PH_RSV_REQ,
|
||
PH_SHORTAGE,
|
||
PH_UPLOAD_RESULT_UNKNOWN,
|
||
PH_UPLOAD_RPA_FAILED,
|
||
PH_UPLOAD_RPA_PENDING,
|
||
RS_PARSE_REVIEW,
|
||
RS_REJECTED,
|
||
RS_RSV_REQ,
|
||
RS_SHORTAGE_REVIEW,
|
||
)
|
||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||
from app.services.shipping_notice.lifecycle_projection import (
|
||
LIFECYCLE_STAGE_BY_GATE,
|
||
LIFECYCLE_STAGE_BY_PROCESSING_STAGE,
|
||
)
|
||
from app.services.shipping_notice.process_gate_contract import (
|
||
PROCESS_GATE_REASON_OWNING_GATE,
|
||
)
|
||
from app.services.shipping_notice.state_machine import (
|
||
UserMode,
|
||
resolve_task_ui_state,
|
||
)
|
||
from app.services.shipping_notice.task_order_field_editor import (
|
||
current_header_field_values_or_empty,
|
||
current_line_field_values_or_empty,
|
||
current_order_field_display_or_empty,
|
||
)
|
||
from app.services.shipping_notice.po_number import normalize_po_number
|
||
|
||
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||
|
||
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
|
||
_BUSINESS_NO_RE = re.compile(r"(?<![A-Z0-9])[A-Z]{2,6}\d{8}(?![A-Z0-9])", re.IGNORECASE)
|
||
|
||
# 人工复核入口位置 / 处置 → todo_category=review;其余 must_human → exception
|
||
_REVIEW_TODO_POSITIONS = frozenset({
|
||
'parse_review',
|
||
'rsv_req',
|
||
'customer_review',
|
||
'notice_text_extraction_failed',
|
||
'quality_issue',
|
||
})
|
||
_REVIEW_TODO_GATE_CODES = frozenset({
|
||
'order_field_extraction',
|
||
'customer_resolution',
|
||
'reservation_validation',
|
||
})
|
||
_EXCEPTION_TODO_GATE_CODES = frozenset({
|
||
'inventory_sufficiency',
|
||
'freight_upload_rpa',
|
||
'inventory_source_routing',
|
||
'excel_readiness',
|
||
})
|
||
_RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'})
|
||
_BLOCKED_OR_FAILED_EXECUTION_STATUSES = frozenset({'blocked', 'failed'})
|
||
_PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload", "intake_parse"})
|
||
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||
"pending": _PENDING_TODO_CATEGORIES,
|
||
"processing": frozenset({"in_progress"}),
|
||
"done": frozenset({"done"}),
|
||
}
|
||
|
||
# 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」属 done 桶终态,不做筛选维度。
|
||
_ACTIONABLE_TODO_STAGES: tuple[str, ...] = (
|
||
"intake_parse", "order_review", "fulfillment_prep", "freight_upload",
|
||
)
|
||
# 无 processing_stage 且人工原因不可映射时的 todo_category 粗兜底(与 Gate 映射语义对齐)。
|
||
_TODO_STAGE_BY_CATEGORY_FALLBACK: dict[str, str] = {
|
||
"review": "order_review",
|
||
"exception": "fulfillment_prep",
|
||
"manual_upload": "freight_upload",
|
||
}
|
||
|
||
# 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。
|
||
_ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({
|
||
"created",
|
||
"queued",
|
||
"parsing",
|
||
"parse_failed",
|
||
})
|
||
|
||
# 建单前人工复核 Case 仍开放写操作的状态(未确认建单)。
|
||
_OPEN_REVIEW_CASE_STATUSES = frozenset({
|
||
"unreviewed",
|
||
"draft",
|
||
"ready",
|
||
"quality_issue",
|
||
"reparse_pending",
|
||
})
|
||
|
||
|
||
_REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||
"unreviewed": "订单 PDF 待人工复核确认",
|
||
"draft": "复核草稿待继续编辑",
|
||
"ready": "复核草稿已就绪,可确认建单",
|
||
"quality_issue": "复核标记为质量问题,待处置",
|
||
"reparse_pending": "复核要求重识别,处理中",
|
||
}
|
||
|
||
|
||
def _current_reviewable_candidate_for_document(
|
||
document_id: int | None,
|
||
) -> ShippingOrderCandidate | None:
|
||
"""
|
||
定位同一文件当前可复核 Candidate,不依赖单个 Case 的 ``candidate_id``。
|
||
|
||
触发时机:Review Case 的生命周期投影需要裁决「是否已进入订单复核」时,遇到
|
||
重解析时序(doc67)——Stream.current_case 可能仍是空的旧 Case(``candidate_id=None``),
|
||
而真正带可复核 Candidate 的是同文档另一 Case。若只读当前 Case 的 candidate_id,
|
||
会把「PO + 订单明细已识别、仅被阻塞需人工复核」的文档误压回「接收解析」。
|
||
|
||
核心逻辑:先按 document_id 遍历同文档已回链 Candidate 的 Case,找到满足
|
||
``is_current_reviewable_candidate`` 的 Candidate;回退时按主文档直查。空、过期或
|
||
被替代 Candidate 一律不开放候选上下文。
|
||
|
||
Args:
|
||
document_id: Review Case 的源文档 ID。
|
||
|
||
Returns:
|
||
当前可复核 Candidate;无有效候选时返回 None。
|
||
"""
|
||
from app.services.shipping_notice.candidate_service import (
|
||
is_current_reviewable_candidate,
|
||
)
|
||
|
||
if document_id is None:
|
||
return None
|
||
for sibling in (
|
||
ShippingOrderReviewCase.query
|
||
.filter(
|
||
ShippingOrderReviewCase.document_id == int(document_id),
|
||
ShippingOrderReviewCase.candidate_id.isnot(None),
|
||
)
|
||
.order_by(ShippingOrderReviewCase.id.desc())
|
||
.all()
|
||
):
|
||
candidate = db.session.get(ShippingOrderCandidate, int(sibling.candidate_id))
|
||
if is_current_reviewable_candidate(candidate):
|
||
return candidate
|
||
candidate = (
|
||
ShippingOrderCandidate.query
|
||
.filter(ShippingOrderCandidate.primary_document_id == int(document_id))
|
||
.order_by(ShippingOrderCandidate.id.desc())
|
||
.first()
|
||
)
|
||
return candidate if is_current_reviewable_candidate(candidate) else None
|
||
|
||
|
||
def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||
"""复用统一生命周期投影裁决 Review Case 的当前阶段与入口。
|
||
|
||
当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。
|
||
此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。
|
||
候选上下文按「文件」粒度裁决:当前 Case 落到空旧 Case(``candidate_id=None``)
|
||
时,回退定位该文件真实可复核 Candidate,避免已识别+阻塞文档被压回接收解析。
|
||
"""
|
||
candidate = (
|
||
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||
if case.candidate_id is not None
|
||
else None
|
||
)
|
||
from app.services.shipping_notice.candidate_service import (
|
||
is_current_reviewable_candidate,
|
||
)
|
||
|
||
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
|
||
|
||
has_candidate_context = is_current_reviewable_candidate(candidate)
|
||
if not has_candidate_context:
|
||
# doc67 类重解析时序:Stream.current_case 可能是空旧 Case,真实可复核
|
||
# Candidate 在同文档另一 Case。按文件粒度回退定位,禁止把已解析+阻塞
|
||
# 文档误投影为「接收解析」。
|
||
candidate = _current_reviewable_candidate_for_document(
|
||
getattr(case, 'document_id', None),
|
||
)
|
||
has_candidate_context = candidate is not None
|
||
if has_candidate_context:
|
||
return project_lifecycle(
|
||
current_gate=None,
|
||
blocking_reason=None,
|
||
has_candidate_context=True,
|
||
processing_stage='waiting_review',
|
||
)
|
||
return project_lifecycle(
|
||
current_gate=None,
|
||
blocking_reason=None,
|
||
has_candidate_context=False,
|
||
has_intake_parse_context=False,
|
||
processing_stage='document_parsing',
|
||
)
|
||
|
||
|
||
class TaskProjection(str, Enum):
|
||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||
|
||
TOOL = "tool"
|
||
TOOL_INTERNAL = "tool_internal"
|
||
SUMMARY = "summary"
|
||
DETAIL = "detail"
|
||
|
||
|
||
def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]:
|
||
"""为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。"""
|
||
inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id)
|
||
verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by(
|
||
ShippingInventoryVerification.created_at, ShippingInventoryVerification.id,
|
||
).all()
|
||
artifacts = []
|
||
if isinstance(task, ShippingNotice):
|
||
artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
|
||
ShippingExportArtifact.created_at, ShippingExportArtifact.id,
|
||
).all()
|
||
artifact_ids = [item.id for item in artifacts]
|
||
artifact_lines = ShippingExportArtifactLine.query.filter(
|
||
ShippingExportArtifactLine.artifact_id.in_(artifact_ids),
|
||
).all() if artifact_ids else []
|
||
reservation_ids = {
|
||
item.id: item.reservation_id
|
||
for item in ShippingReservation.query.filter(ShippingReservation.task_id == inventory_task_id).all()
|
||
}
|
||
reservations_by_artifact: dict[int, list[str]] = {}
|
||
for line in artifact_lines:
|
||
reservations_by_artifact.setdefault(int(line.artifact_id), []).append(
|
||
reservation_ids.get(int(line.reservation_id), str(line.reservation_id))
|
||
)
|
||
attempts = ShippingUploadAttempt.query.filter(
|
||
ShippingUploadAttempt.artifact_id.in_(artifact_ids),
|
||
).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else []
|
||
return {
|
||
'inventory_verifications': [{
|
||
'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id,
|
||
'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None,
|
||
'lines': [{
|
||
'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty),
|
||
'available_qty': str(line.available_qty), 'status': line.status,
|
||
} for line in item.lines],
|
||
} for item in verifications],
|
||
'export_artifacts': [{
|
||
'id': item.id, 'artifact_no': item.artifact_no, 'status': item.status, 'file_name': item.file_name,
|
||
'file_size': item.file_size, 'created_at': item.created_at.isoformat() if item.created_at else None,
|
||
'reservation_ids': reservations_by_artifact.get(int(item.id), []),
|
||
} for item in artifacts],
|
||
'upload_attempts': [{
|
||
'id': item.id, 'artifact_id': item.artifact_id, 'attempt_no': item.attempt_no, 'mode': item.mode,
|
||
'status': item.status, 'callback_id': item.callback_id, 'freight_ref_no': item.freight_ref_no,
|
||
'error_code': item.error_code, 'error_message': item.error_message,
|
||
'evidence_asset_id': item.evidence_asset_id, 'operator_id': item.operator_id,
|
||
'started_at': item.started_at.isoformat() if item.started_at else None,
|
||
'finished_at': item.finished_at.isoformat() if item.finished_at else None,
|
||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||
} for item in attempts],
|
||
}
|
||
|
||
|
||
def get_task_by_ref(task_ref: str) -> ShippingOrderTask | ShippingNotice | None:
|
||
"""按 OT task_no 查找订单任务;业务编号/Notice 主键仅用于正式通知专用查询。"""
|
||
value = str(task_ref or "").strip()
|
||
if not value:
|
||
return None
|
||
task = ShippingOrderTask.query.filter_by(task_no=value).first()
|
||
if task:
|
||
return task
|
||
task = ShippingNotice.query.filter_by(task_no=value).first()
|
||
if task:
|
||
return task
|
||
task = ShippingNotice.query.filter_by(business_no=value.upper()).first()
|
||
if task:
|
||
return task
|
||
if value.isdigit():
|
||
return db.session.get(ShippingOrderTask, int(value)) or db.session.get(ShippingNotice, int(value))
|
||
return None
|
||
|
||
|
||
def resolve_order_extraction_ui_target(
|
||
*,
|
||
user_id: int,
|
||
conversation_id: str,
|
||
intake_nos: list[str],
|
||
) -> tuple[None, ShippingNotice | None]:
|
||
"""
|
||
按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。
|
||
|
||
核心逻辑:沿 Candidate.consumed_task_id 查找当前用户的既有 Task。
|
||
禁止回退到“用户最近任务”,避免并发会话串单。
|
||
|
||
Args:
|
||
user_id: 当前聊天用户 ID。
|
||
conversation_id: 当前 HXOPS ChatSession.session_id。
|
||
intake_nos: 本轮 agent_runtime_context.refs.intake_nos。
|
||
Returns:
|
||
`(None, task)`;`shipping_batches` 已删除,任务是唯一恢复锚点。
|
||
"""
|
||
normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
|
||
session_id = str(conversation_id or '').strip()
|
||
if not normalized or not session_id:
|
||
return None, None
|
||
|
||
intakes = (
|
||
db.session.query(ShippingOrderIntake)
|
||
.filter(
|
||
ShippingOrderIntake.user_id == int(user_id),
|
||
ShippingOrderIntake.conversation_id == session_id,
|
||
ShippingOrderIntake.intake_no.in_(normalized),
|
||
)
|
||
.order_by(ShippingOrderIntake.id.asc())
|
||
.all()
|
||
)
|
||
if {item.intake_no for item in intakes} != set(normalized):
|
||
return None, None
|
||
|
||
# co8 起 Intake.consumed_batch_id 已删除;仅通过 Candidate→Task 反查已有任务。
|
||
task = (
|
||
db.session.query(ShippingOrderTask)
|
||
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
|
||
.filter(
|
||
ShippingOrderCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||
ShippingOrderTask.user_id == int(user_id),
|
||
)
|
||
.order_by(ShippingOrderCandidate.id.asc(), ShippingOrderTask.id.asc())
|
||
.first()
|
||
)
|
||
return None, task
|
||
|
||
|
||
def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None:
|
||
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
|
||
if not task or isinstance(task, ShippingOrderTask) or getattr(task, 'id', None) is None:
|
||
return None
|
||
from app.models import ShippingExportArtifact
|
||
# 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel;
|
||
# 不能因履约完成将 status=uploaded 排除在下载解析之外。
|
||
artifact = ShippingExportArtifact.query.filter(
|
||
ShippingExportArtifact.task_id == task.id,
|
||
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
|
||
).order_by(
|
||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||
).first()
|
||
if artifact is None:
|
||
return None
|
||
path = Path(artifact.file_path)
|
||
if not path.is_file():
|
||
return None
|
||
return path, artifact.file_name or path.name
|
||
|
||
|
||
def task_export_error_message(task: ShippingNotice | None) -> str:
|
||
"""导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。"""
|
||
if not task or task.id is None:
|
||
return "export file not found"
|
||
resolved = resolve_task_export_download(task)
|
||
if resolved is None:
|
||
return "export file missing on disk"
|
||
return ""
|
||
|
||
|
||
def extract_task_no_from_text(text: str) -> str | None:
|
||
"""从自然语言文本中提取 SN 技术号或客户业务号。"""
|
||
raw = str(text or "")
|
||
match = _TASK_NO_RE.search(raw) or _BUSINESS_NO_RE.search(raw)
|
||
return match.group(0).upper() if match else None
|
||
|
||
|
||
def resolve_task_from_payload(
|
||
payload: dict[str, Any],
|
||
*,
|
||
allow_conversation_fallback: bool = True,
|
||
) -> ShippingOrderTask | ShippingNotice | None:
|
||
"""
|
||
按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。
|
||
|
||
核心逻辑:显式任务号永远优先;conversation_id 仅在同会话下只有一票可操作任务时回退,
|
||
多票场景返回 None,避免用户只说“确认/继续”时误推进最近一票。
|
||
"""
|
||
if not isinstance(payload, dict):
|
||
return None
|
||
|
||
for key in ("task_id", "task_no"):
|
||
task = get_task_by_ref(str(payload.get(key) or ""))
|
||
if task:
|
||
return task
|
||
|
||
for key in ("comment", "user_message", "raw_text", "query"):
|
||
hint = extract_task_no_from_text(str(payload.get(key) or ""))
|
||
if hint:
|
||
task = get_task_by_ref(hint)
|
||
if task:
|
||
return task
|
||
|
||
if not allow_conversation_fallback:
|
||
return None
|
||
|
||
conv_id = str(payload.get("conversation_id") or "").strip()
|
||
if conv_id:
|
||
candidates = (
|
||
ShippingOrderTask.query.filter_by(conversation_id=conv_id)
|
||
.filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'}))
|
||
.order_by(ShippingOrderTask.id.desc())
|
||
.limit(2)
|
||
.all()
|
||
)
|
||
if len(candidates) == 1:
|
||
return candidates[0]
|
||
return None
|
||
|
||
|
||
def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||
"""Tool data 基础字段(裁剪前)。"""
|
||
if isinstance(task, ShippingOrderTask):
|
||
header, lines, _field_display = _order_values_for_projection(task)
|
||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||
|
||
match_facts = list(load_current_match_facts_by_task(task.id).values())
|
||
customer = _order_task_customer_projection(task)
|
||
inventory = _order_task_inventory_projection(task)
|
||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||
shortage = {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}
|
||
return {
|
||
'task_no': task.task_no,
|
||
'order_task_no': task.task_no,
|
||
'current_step': task.stage,
|
||
'stage': task.stage,
|
||
'status': task.status,
|
||
'customer_name': header.get('customer_name'),
|
||
'customer_code': header.get('customer_code'),
|
||
'customer_resolution_status': customer['status'],
|
||
'customer_resolution_method': customer['resolution_method'],
|
||
'customer_id': customer['customer_id'],
|
||
'customer_name_snapshot': customer['customer_name_snapshot'],
|
||
'customer_short_code_snapshot': customer['customer_short_code_snapshot'],
|
||
'ship_to': header.get('ship_to') or header.get('ship_to_address'),
|
||
'po_number': header.get('po_number'),
|
||
'required_date': header.get('required_date'),
|
||
'lines': lines,
|
||
'shortage': shortage,
|
||
'line_results': match_facts,
|
||
'pending_human_reason': task_blocking_reason(task),
|
||
'error_message': task.error_message,
|
||
'conversation_id': task.conversation_id,
|
||
'step_payload': task.step_payload_json or {},
|
||
**inventory,
|
||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||
}
|
||
from app.services.shipping_notice.notice_upload import max_notice_chars
|
||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||
|
||
workflow_owner = (
|
||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||
if getattr(task, 'order_task_id', None) else task
|
||
)
|
||
match_projection = _current_match_projection(workflow_owner)
|
||
artifact, upload_attempt = _latest_export_upload_facts(task)
|
||
step_payload = getattr(workflow_owner, 'step_payload_json', None) or {}
|
||
header = current_header_field_values_or_empty(workflow_owner)
|
||
customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {}
|
||
payload: dict[str, Any] = {
|
||
"task_no": task.task_no,
|
||
"business_no": getattr(task, 'business_no', None),
|
||
"current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None),
|
||
"review_status": getattr(workflow_owner, 'review_status', None),
|
||
"match_status": match_projection['match_status'],
|
||
"pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None),
|
||
"customer_name": header.get('customer_name'),
|
||
"customer_code": header.get('customer_code'),
|
||
"customer_resolution_status": customer_projection.get('status'),
|
||
"customer_resolution_method": customer_projection.get('resolution_method'),
|
||
"customer_id": customer_projection.get('customer_id'),
|
||
"customer_name_snapshot": customer_projection.get('customer_name_snapshot'),
|
||
"customer_short_code_snapshot": customer_projection.get('customer_short_code_snapshot'),
|
||
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
|
||
"po_number": header.get('po_number'),
|
||
"required_date": header.get('required_date'),
|
||
"lines": current_line_field_values_or_empty(workflow_owner),
|
||
"shortage": match_projection['shortage'],
|
||
"line_results": match_projection['line_results'],
|
||
"export_file_name": getattr(artifact, 'file_name', None),
|
||
"freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None),
|
||
"error_message": getattr(workflow_owner, 'error_message', None),
|
||
"conversation_id": task.conversation_id,
|
||
"step_payload": getattr(workflow_owner, 'step_payload_json', None) or {},
|
||
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
|
||
}
|
||
raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip()
|
||
lines = payload["lines"]
|
||
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
|
||
|
||
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
|
||
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
|
||
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:
|
||
payload["raw_text_truncated"] = True
|
||
return payload
|
||
|
||
|
||
def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
|
||
"""从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。"""
|
||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||
|
||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||
rows = list(load_current_match_facts_by_task(task_id).values())
|
||
shortage_rows = [
|
||
row for row in rows
|
||
if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
|
||
or str(row.get('match_result') or '').strip().lower() != 'matched'
|
||
]
|
||
return {
|
||
'match_status': 'unfulfillable' if shortage_rows else ('fulfillable' if rows else None),
|
||
'shortage': {'lines': shortage_rows},
|
||
'line_results': rows,
|
||
}
|
||
def _latest_export_upload_facts(task: ShippingNotice) -> tuple[Any | None, Any | None]:
|
||
"""读取最新导出 Artifact 与上传 Attempt,作为正式 Notice 的只读运行投影。"""
|
||
artifact = latest_export_artifact(task)
|
||
attempt = (
|
||
ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id))
|
||
.order_by(ShippingUploadAttempt.attempt_no.desc(), ShippingUploadAttempt.id.desc()).first()
|
||
if artifact is not None else None
|
||
)
|
||
return artifact, attempt
|
||
|
||
|
||
def _snapshot_order_values(snapshot: ShippingOrderSnapshot) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||
"""按冻结时的 Schema 还原订单头、订单行及展示契约,禁止回读可变 Extraction。"""
|
||
fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or [])
|
||
header_configs = [item for item in fields if item.get('scope') == 'header']
|
||
line_configs = [item for item in fields if item.get('scope') == 'line']
|
||
|
||
def _display(config: dict[str, Any]) -> dict[str, Any]:
|
||
return {
|
||
'field_code': str(config.get('field_code') or ''),
|
||
'display_name': str(config.get('display_name') or config.get('field_code') or ''),
|
||
'scope': str(config.get('scope') or ''),
|
||
'value_type': str(config.get('value_type') or 'string'),
|
||
'sequence': int(config.get('sequence') or 0),
|
||
}
|
||
|
||
header_values = dict(snapshot.header_values_json or {})
|
||
header = {
|
||
str(config.get('field_code') or ''): header_values.get(str(config.get('field_id') or ''))
|
||
for config in header_configs
|
||
if str(config.get('field_code') or '')
|
||
}
|
||
lines = [
|
||
{
|
||
str(config.get('field_code') or ''): dict(line.field_values_json or {}).get(str(config.get('field_id') or ''))
|
||
for config in line_configs
|
||
if str(config.get('field_code') or '')
|
||
}
|
||
for line in sorted(snapshot.lines, key=lambda item: (int(item.position), int(item.id)))
|
||
]
|
||
return header, lines, {
|
||
'header_fields': [_display(config) for config in header_configs],
|
||
'line_fields': [_display(config) for config in line_configs],
|
||
}
|
||
|
||
|
||
def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||
"""冻结后统一读取 Snapshot;冻结前才允许读取当前已接受的 Extraction。"""
|
||
owner = task
|
||
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
|
||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
|
||
snapshot_id = getattr(owner, 'order_snapshot_id', None)
|
||
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
|
||
if snapshot is not None:
|
||
return _snapshot_order_values(snapshot)
|
||
return (
|
||
current_header_field_values_or_empty(owner),
|
||
current_line_field_values_or_empty(owner),
|
||
current_order_field_display_or_empty(owner),
|
||
)
|
||
|
||
|
||
def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""工作台任务摘要中的库存快照投影。"""
|
||
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
|
||
|
||
return serialize_inventory_snapshot_link(task)
|
||
|
||
|
||
def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]:
|
||
"""从正式客户识别结果读取 OT 客户确认事实。"""
|
||
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
|
||
|
||
facts = customer_resolution_facts(task)
|
||
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
|
||
resolution = facts['resolution']
|
||
return {
|
||
'customer_id': facts['customer_id'],
|
||
'customer_name_snapshot': getattr(customer, 'standard_name', None),
|
||
'customer_short_code_snapshot': getattr(customer, 'short_code', None),
|
||
'status': facts['status'],
|
||
'resolution_method': getattr(resolution, 'confirmation_method', None),
|
||
}
|
||
|
||
|
||
def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]:
|
||
"""从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。"""
|
||
from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts
|
||
|
||
facts = project_inventory_candidate_facts(task)
|
||
sources = list(facts.get('sources') or [])
|
||
source_codes = [str(item.get('source_code') or '').strip().upper() for item in sources]
|
||
source_codes = [item for item in source_codes if item]
|
||
single_source = source_codes[0] if len(source_codes) == 1 else None
|
||
versions = {
|
||
str(item.get('source_config_version') or '').strip()
|
||
for item in sources if str(item.get('source_config_version') or '').strip()
|
||
}
|
||
return {
|
||
'inventory_source_code': single_source,
|
||
'inventory_source_status': 'candidates_frozen' if facts.get('current_set') else 'unresolved',
|
||
'inventory_source_method': 'candidate_set' if facts.get('current_set') else None,
|
||
'inventory_source_config_version': next(iter(versions)) if len(versions) == 1 else None,
|
||
'inventory_routing_fingerprint': (
|
||
(facts.get('current_set') or {}).get('input_fingerprint')
|
||
if isinstance(facts.get('current_set'), dict) else None
|
||
),
|
||
}
|
||
|
||
|
||
def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]:
|
||
"""
|
||
组装任务版本链与重复决策投影字段。
|
||
|
||
核心逻辑:查 supersedes / 被谁 supersede / duplicate_source,供工作台与 Chat 导航。
|
||
"""
|
||
supersedes_task_no = None
|
||
if task.supersedes_task_id:
|
||
prev = db.session.get(ShippingNotice, int(task.supersedes_task_id))
|
||
if prev is not None:
|
||
supersedes_task_no = prev.task_no
|
||
superseded_by = (
|
||
db.session.query(ShippingNotice)
|
||
.filter(ShippingNotice.supersedes_task_id == int(task.id))
|
||
.order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc())
|
||
.first()
|
||
)
|
||
duplicate_source_task_no = None
|
||
if task.duplicate_source_task_id:
|
||
src = db.session.get(ShippingNotice, int(task.duplicate_source_task_id))
|
||
if src is not None:
|
||
duplicate_source_task_no = src.task_no
|
||
candidate = db.session.get(ShippingOrderCandidate, task.source_candidate_id) if getattr(task, 'source_candidate_id', None) else None
|
||
return {
|
||
'document_version': int(task.document_version or 1),
|
||
'supersedes_task_no': supersedes_task_no,
|
||
'superseded_by_task_no': superseded_by.task_no if superseded_by else None,
|
||
'duplicate_source_task_no': duplicate_source_task_no,
|
||
'duplicate_resolution_type': task.duplicate_resolution_type,
|
||
'duplicate_override_reason': task.duplicate_override_reason,
|
||
'business_fingerprint': getattr(candidate, 'business_fingerprint', None),
|
||
'fingerprint_version': getattr(candidate, 'fingerprint_version', None),
|
||
}
|
||
|
||
|
||
def _dict_or_none(value: Any) -> dict[str, Any] | None:
|
||
"""将 step_payload 内对象投影为 dict;非 dict 时返回 None。"""
|
||
return dict(value) if isinstance(value, dict) else None
|
||
|
||
|
||
def _serialize_open_field_conflicts(task: ShippingNotice) -> list[dict[str, Any]]:
|
||
"""投影未解决字段冲突,供工作台冲突复核 UI。"""
|
||
from app.services.shipping_notice.task_field_conflict_service import (
|
||
list_open_field_conflicts,
|
||
serialize_field_conflict,
|
||
)
|
||
|
||
return [serialize_field_conflict(row) for row in list_open_field_conflicts(task)]
|
||
|
||
|
||
def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""
|
||
投影建单来源 Candidate 的只读审计字段。
|
||
|
||
核心逻辑:按 source_candidate_id 取落库 evidence / missing_fields / field_confidence,
|
||
并投影当前字段裁决与不可变 Observation 历史;
|
||
Candidate 已清理或不存在时返回 None,不阻断 Task Detail。
|
||
"""
|
||
if not getattr(task, 'source_candidate_id', None):
|
||
return None
|
||
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
|
||
if candidate is None:
|
||
return None
|
||
field_confidence = candidate.field_confidence_json
|
||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||
extraction = structured.get("extraction") if isinstance(structured.get("extraction"), dict) else {}
|
||
adjudication = (
|
||
extraction.get("field_adjudication")
|
||
if isinstance(extraction.get("field_adjudication"), dict)
|
||
else {}
|
||
)
|
||
return {
|
||
"candidate_no": candidate.candidate_no,
|
||
"missing_fields": list(candidate.missing_fields_json or []),
|
||
"field_confidence": dict(field_confidence) if isinstance(field_confidence, dict) else {},
|
||
"evidence": list(candidate.evidence_json or []),
|
||
"conflicts": list(candidate.conflicts_json or []),
|
||
"field_adjudication": {
|
||
"schema_version": adjudication.get("schema_version"),
|
||
"decisions": list(adjudication.get("decisions") or []),
|
||
"observations": list(adjudication.get("observations") or []),
|
||
"observation_history": list(adjudication.get("observation_history") or []),
|
||
"conflicts": list(adjudication.get("conflicts") or []),
|
||
} if adjudication else None,
|
||
}
|
||
|
||
|
||
def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str, Any]:
|
||
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
|
||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||
|
||
workflow_owner = (
|
||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||
if getattr(task, 'order_task_id', None) else task
|
||
)
|
||
|
||
if projection == TaskProjection.TOOL:
|
||
from app.services.shipping_notice.user_facing_status import strip_internal_task_fields
|
||
|
||
return strip_internal_task_fields(_task_tool_payload(task))
|
||
if projection == TaskProjection.TOOL_INTERNAL:
|
||
return _task_tool_payload(task)
|
||
if projection == TaskProjection.SUMMARY:
|
||
if isinstance(task, ShippingOrderTask):
|
||
header, _lines, _field_display = _order_values_for_projection(task)
|
||
customer = _order_task_customer_projection(task)
|
||
inventory = _order_task_inventory_projection(task)
|
||
from app.services.shipping_notice.task_disposition_service import task_disposition_capability
|
||
disposition_capabilities = {
|
||
action: {
|
||
'allowed': result.allowed,
|
||
'code': result.code,
|
||
'reason': result.reason,
|
||
}
|
||
for action in ('delete', 'void', 'archive', 'restore')
|
||
for result in (task_disposition_capability(task, action),)
|
||
}
|
||
step_payload = task.step_payload_json or {}
|
||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||
|
||
match_facts = list(load_current_match_facts_by_task(task.id).values())
|
||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||
has_shortage = any(
|
||
str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
|
||
or str(row.get('match_result') or '').strip().lower() != 'matched'
|
||
for row in match_facts
|
||
)
|
||
return {
|
||
'id': task.id,
|
||
'task_no': task.task_no,
|
||
'order_task_no': task.task_no,
|
||
'source_type': task.source_type,
|
||
'customer_name': header.get('customer_name'),
|
||
'customer_id': customer['customer_id'],
|
||
'customer_name_snapshot': customer['customer_name_snapshot'],
|
||
'customer_short_code_snapshot': customer['customer_short_code_snapshot'],
|
||
'current_step': task.stage,
|
||
'stage': task.stage,
|
||
'status': task.status,
|
||
'lifecycle_status': str(getattr(task, 'lifecycle_status', 'active') or 'active'),
|
||
'deleted_at': task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None,
|
||
'voided_at': task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None,
|
||
'void_reason': getattr(task, 'void_reason', None),
|
||
'archived_at': task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None,
|
||
'match_status': ('unfulfillable' if has_shortage else ('fulfillable' if match_facts else None)),
|
||
'pending_human_reason': task_blocking_reason(task),
|
||
'error_message': task.error_message,
|
||
'conversation_id': task.conversation_id,
|
||
'step_payload': step_payload,
|
||
'destination_code': header.get('destination_code'),
|
||
'destination_city': header.get('destination_city'),
|
||
'destination_country': header.get('destination_country'),
|
||
'warehouse_hint': header.get('warehouse_hint'),
|
||
**inventory,
|
||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||
'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]},
|
||
'line_results': match_facts,
|
||
'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None),
|
||
'progress_version': task.progress_version,
|
||
'created_at': task.created_at.isoformat() if task.created_at else None,
|
||
'updated_at': task.updated_at.isoformat() if task.updated_at else None,
|
||
'disposition_capabilities': disposition_capabilities,
|
||
}
|
||
workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {}
|
||
step_payload = workflow_payload
|
||
header = current_header_field_values_or_empty(workflow_owner)
|
||
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
|
||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||
|
||
inventory_facts = active_inventory_runtime_facts(workflow_owner)
|
||
source_codes = task_frozen_inventory_source_codes(workflow_owner)
|
||
routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {})
|
||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||
match_task_id = getattr(workflow_owner, 'id', None) or task.id
|
||
match_facts = list(load_current_match_facts_by_task(match_task_id).values())
|
||
match_status_projection = (
|
||
'unfulfillable' if any(
|
||
str(row.get('match_result') or '').strip().lower() != 'matched'
|
||
or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
|
||
for row in match_facts
|
||
) else ('fulfillable' if match_facts else None)
|
||
)
|
||
artifact, upload_attempt = _latest_export_upload_facts(task)
|
||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||
upload_status_projection = project_notice_upload_status(task)
|
||
customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {}
|
||
source_candidate = db.session.get(ShippingOrderCandidate, workflow_owner.candidate_id) if isinstance(workflow_owner, ShippingOrderTask) and workflow_owner.candidate_id else None
|
||
source_document = db.session.get(ShippingOrderDocument, source_candidate.primary_document_id) if source_candidate and source_candidate.primary_document_id else None
|
||
data = {
|
||
"id": task.id,
|
||
"task_no": task.task_no,
|
||
"business_no": task.business_no,
|
||
"source_type": task.source_type,
|
||
"source_file_name": getattr(source_document, 'filename', None),
|
||
"source_file_type": getattr(workflow_owner, 'source_type', None),
|
||
"customer_name": header.get('customer_name'),
|
||
"customer_resolution_status": customer_projection.get('status'),
|
||
"customer_resolution_method": customer_projection.get('resolution_method'),
|
||
"customer_id": customer_projection.get('customer_id'),
|
||
"customer_name_snapshot": customer_projection.get('customer_name_snapshot'),
|
||
"customer_short_code_snapshot": customer_projection.get('customer_short_code_snapshot'),
|
||
"current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None),
|
||
"review_status": getattr(workflow_owner, 'review_status', None),
|
||
"match_status": match_status_projection,
|
||
"upload_status": upload_status_projection,
|
||
"upload_mode": getattr(upload_attempt, 'mode', None),
|
||
"upload_attempt": getattr(upload_attempt, 'attempt_no', None),
|
||
"pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None),
|
||
"error_message": getattr(workflow_owner, 'error_message', None) or getattr(upload_attempt, 'error_message', None),
|
||
"lifecycle_status": str(getattr(task, 'lifecycle_status', 'active') or 'active'),
|
||
"deleted_at": task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None,
|
||
"voided_at": task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None,
|
||
"void_reason": getattr(task, 'void_reason', None),
|
||
"archived_at": task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None,
|
||
"conversation_id": task.conversation_id,
|
||
"export_file_name": getattr(artifact, 'file_name', None),
|
||
"freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None),
|
||
"export_version": getattr(artifact, 'id', None),
|
||
"idempotency_key": getattr(upload_attempt, 'idempotency_key', None),
|
||
"step_payload": step_payload,
|
||
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
|
||
"rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None,
|
||
"inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None,
|
||
"destination_code": header.get('destination_code'),
|
||
"destination_city": header.get('destination_city'),
|
||
"destination_country": header.get('destination_country'),
|
||
"warehouse_hint": header.get('warehouse_hint'),
|
||
"inventory_source_code": source_codes[0] if len(source_codes) == 1 else None,
|
||
"inventory_warehouse_id": (_serialize_inventory_snapshot(workflow_owner) or {}).get("warehouse_id"),
|
||
"inventory_source_status": 'resolved' if len(source_codes) == 1 else ('candidates_frozen' if source_codes else 'unresolved'),
|
||
"inventory_source_method": routing.get('adjudication_method'),
|
||
"inventory_source_config_version": inventory_facts.get('source_config_version'),
|
||
"inventory_routing_fingerprint": routing.get('routing_fingerprint'),
|
||
"inventory_snapshot": _serialize_inventory_snapshot(workflow_owner),
|
||
"shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]},
|
||
"line_results": match_facts,
|
||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||
}
|
||
data.update(_task_version_chain_fields(task))
|
||
from app.services.shipping_notice.task_disposition_service import task_disposition_capability
|
||
|
||
data['disposition_capabilities'] = {
|
||
action: {
|
||
'allowed': result.allowed,
|
||
'code': result.code,
|
||
'reason': result.reason,
|
||
}
|
||
for action in ('delete', 'void', 'archive', 'restore')
|
||
for result in (task_disposition_capability(task, action),)
|
||
}
|
||
return data
|
||
if projection == TaskProjection.DETAIL:
|
||
if isinstance(task, ShippingOrderTask):
|
||
from app.services.shipping_notice.task_disposition_service import task_disposition_capability
|
||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||
header, lines, field_display = _order_values_for_projection(task)
|
||
data.update({
|
||
'lines': lines,
|
||
'order_header': header,
|
||
'order_header_fields': field_display['header_fields'],
|
||
'order_line_fields': field_display['line_fields'],
|
||
'order_snapshot_id': task.order_snapshot_id,
|
||
'order_data_version': int(task.order_data_version or 1),
|
||
'parse_validation': _dict_or_none((task.step_payload_json or {}).get('parse_validation')),
|
||
'process_field_gate': _dict_or_none((task.step_payload_json or {}).get('process_field_gate')),
|
||
})
|
||
data['disposition_capabilities'] = data.get('disposition_capabilities') or {
|
||
action: {
|
||
'allowed': result.allowed,
|
||
'code': result.code,
|
||
'reason': result.reason,
|
||
}
|
||
for action in ('delete', 'void', 'archive', 'restore')
|
||
for result in (task_disposition_capability(task, action),)
|
||
}
|
||
return data
|
||
step_payload = getattr(workflow_owner, 'step_payload_json', None) if isinstance(getattr(workflow_owner, 'step_payload_json', None), dict) else {}
|
||
header = current_header_field_values_or_empty(workflow_owner)
|
||
order_field_display = current_order_field_display_or_empty(workflow_owner)
|
||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||
match_projection = _current_match_projection(task)
|
||
data.update({
|
||
"customer_code": header.get('customer_code'),
|
||
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
|
||
"po_number": header.get('po_number'),
|
||
"required_date": header.get('required_date'),
|
||
"step_payload": step_payload,
|
||
"export_version": getattr(_latest_export_upload_facts(task)[0], 'id', None),
|
||
"idempotency_key": getattr(_latest_export_upload_facts(task)[1], 'idempotency_key', None),
|
||
"lines": current_line_field_values_or_empty(workflow_owner),
|
||
"order_header": header,
|
||
"order_header_fields": order_field_display['header_fields'],
|
||
"order_line_fields": order_field_display['line_fields'],
|
||
"shortage": match_projection['shortage'],
|
||
"line_results": match_projection['line_results'],
|
||
"parse_confidence": getattr(workflow_owner, 'parse_confidence', None),
|
||
"error_message": getattr(workflow_owner, 'error_message', None),
|
||
# [STEP] 稳定顶层投影解析门禁与来源 Candidate 审计,供工作台持久只读展示。
|
||
"parse_validation": _dict_or_none(step_payload.get("parse_validation")),
|
||
"process_field_gate": _dict_or_none(step_payload.get("process_field_gate")),
|
||
"source_candidate": _serialize_source_candidate_projection(task),
|
||
# 工作台据此隐藏冻结按钮;是否可冻结仍由写路径重算,不能信任前端状态。
|
||
"order_snapshot_id": getattr(workflow_owner, 'order_snapshot_id', None),
|
||
"order_data_version": int(getattr(workflow_owner, 'order_data_version', 1) or 1),
|
||
"field_conflicts": _serialize_open_field_conflicts(task),
|
||
**_fulfillment_timeline(task),
|
||
"events": [
|
||
{
|
||
"event_type": e.event_type,
|
||
"detail_json": e.detail_json,
|
||
"actor_id": e.actor_id,
|
||
"request_id": e.request_id,
|
||
"source": e.source,
|
||
"before_json": e.before_json,
|
||
"after_json": e.after_json,
|
||
"created_at": e.created_at.isoformat() if e.created_at else None,
|
||
}
|
||
for e in sorted(getattr(task, 'events', None) or [], key=lambda x: x.created_at or "")
|
||
],
|
||
})
|
||
return data
|
||
raise ValueError(f"unsupported task projection: {projection}")
|
||
|
||
|
||
def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]:
|
||
"""Dify Tool `data` 投影(剔除内部状态码)。"""
|
||
return serialize_task(task, TaskProjection.TOOL)
|
||
|
||
|
||
def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||
"""
|
||
一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。
|
||
|
||
核心逻辑:``ShippingProcessExecution.task_id IN (...)``;同 task 多 Execution 时
|
||
后写入覆盖前写入(调用方若需 active-only 可再滤 status)。
|
||
|
||
Args:
|
||
task_ids: OT 主键列表。
|
||
|
||
Returns:
|
||
``{task_id: {'current_gate_code', 'status'}}``;无命中的 id 不出现。
|
||
"""
|
||
from app.models import ShippingProcessExecution
|
||
|
||
ids = [int(i) for i in task_ids if i is not None]
|
||
if not ids:
|
||
return {}
|
||
rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all()
|
||
return {
|
||
int(getattr(r, 'task_id', 0)): {
|
||
'current_gate_code': getattr(r, 'current_gate_code', None),
|
||
'status': getattr(r, 'status', None),
|
||
}
|
||
for r in rows
|
||
if getattr(r, 'task_id', None) is not None
|
||
}
|
||
|
||
|
||
def _user_status_from_gate_pos(gate_pos: dict[str, Any] | None) -> str:
|
||
"""
|
||
将 Execution / Gate 摘要 status 粗映射为 derive_user_mode 的 user_status。
|
||
|
||
核心逻辑:blocked* → waiting_human;completed/done → completed;failed* → failed;其余 running。
|
||
"""
|
||
if not isinstance(gate_pos, dict):
|
||
return 'running'
|
||
status = str(gate_pos.get('status') or '').strip().lower()
|
||
if status in {'blocked_manual', 'blocked_retryable', 'blocked'}:
|
||
return 'waiting_human'
|
||
if status in {'completed', 'done'}:
|
||
return 'completed'
|
||
if status in {'failed_terminal', 'failed'}:
|
||
return 'failed'
|
||
return 'running'
|
||
|
||
|
||
def _todo_category_from_gate(
|
||
gate_pos: dict[str, Any] | None,
|
||
review_status: Any,
|
||
*,
|
||
lifecycle_stage: str | None = None,
|
||
) -> str:
|
||
"""
|
||
从 Gate 位置推导 todo_category(替代 user_mode 路径)。
|
||
|
||
核心逻辑:derive_user_mode + derive_position → derive_todo_category;
|
||
无 Gate 时不得经本函数默认 in_progress。
|
||
|
||
Args:
|
||
gate_pos: ``{'current_gate_code', 'status'}``;可为 None(仅靠 review_status)。
|
||
review_status: 任务复核处置。
|
||
lifecycle_stage: 可选生命周期,供 wait_manual_upload 判定。
|
||
|
||
Returns:
|
||
review | exception | manual_upload | in_progress | done
|
||
"""
|
||
from app.services.shipping_notice.process_gate_contract import (
|
||
derive_position,
|
||
derive_todo_category,
|
||
derive_user_mode,
|
||
)
|
||
|
||
pos_payload = gate_pos if isinstance(gate_pos, dict) else {}
|
||
user_mode = derive_user_mode(
|
||
user_status=_user_status_from_gate_pos(pos_payload),
|
||
gate_code=pos_payload.get('current_gate_code'),
|
||
review_status=review_status,
|
||
lifecycle_stage=lifecycle_stage,
|
||
)
|
||
position = derive_position(
|
||
gate_code=pos_payload.get('current_gate_code'),
|
||
review_status=review_status,
|
||
)
|
||
return derive_todo_category(user_mode=user_mode, position=position)
|
||
|
||
|
||
def _todo_category_from_process_gate(
|
||
process_gate: dict[str, Any] | None,
|
||
review_status: Any,
|
||
) -> str | None:
|
||
"""
|
||
从用户 Gate 摘要推导 todo_category;无 current_gate_code 时返回 None 供回退。
|
||
|
||
核心逻辑:优先 current_blocking_gate.status,否则摘要 status / current_gate。
|
||
"""
|
||
if not isinstance(process_gate, dict) or not process_gate.get('current_gate_code'):
|
||
return None
|
||
gate_view = process_gate.get('current_blocking_gate') or process_gate.get('current_gate') or {}
|
||
if not isinstance(gate_view, dict):
|
||
gate_view = {}
|
||
status = (
|
||
gate_view.get('status')
|
||
or process_gate.get('status')
|
||
or process_gate.get('gate_status')
|
||
)
|
||
return _todo_category_from_gate(
|
||
{
|
||
'current_gate_code': process_gate.get('current_gate_code') or gate_view.get('gate_code'),
|
||
'status': status,
|
||
},
|
||
review_status,
|
||
lifecycle_stage=process_gate.get('lifecycle_stage'),
|
||
)
|
||
|
||
|
||
def task_todo_category(task: ShippingNotice) -> str:
|
||
"""
|
||
推导待办分类(服务端唯一口径):优先 Gate;无 Execution 时 fail-closed。
|
||
|
||
核心逻辑:wait_manual_upload→manual_upload;complete→done;
|
||
must_human 且属复核入口→review,其余 must_human→exception;
|
||
auto_continue 且有 Gate 推进中→in_progress;无 Gate 禁止默认 in_progress。
|
||
|
||
Returns:
|
||
review | exception | manual_upload | in_progress | done
|
||
"""
|
||
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
|
||
|
||
gated = _todo_category_from_process_gate(
|
||
_process_gate_user_summary_for_task(task),
|
||
getattr(task, 'review_status', None),
|
||
)
|
||
if gated is not None:
|
||
return gated
|
||
# Gate 投影无 current_gate_code(常见于仅有 Execution 指针、尚无 Gate 行)时,
|
||
# 与 SQL CASE 同源读最新 Execution,避免列表 hydrate 与 COUNT 分叉。
|
||
gated = _todo_category_from_latest_execution(task)
|
||
if gated is not None:
|
||
return gated
|
||
ui = resolve_task_ui_state(task)
|
||
return _todo_category_after_missing_gate(task, position=ui.position, user_mode=ui.user_mode)
|
||
|
||
|
||
def _todo_category_from_ui(position: str | None, kind: UserMode) -> str:
|
||
"""将 user_mode(及复核入口位置集合)映射为 todo_category。"""
|
||
if kind == UserMode.WAIT_MANUAL_UPLOAD:
|
||
return "manual_upload"
|
||
if kind == UserMode.COMPLETE:
|
||
return "done"
|
||
if kind == UserMode.MUST_HUMAN:
|
||
if str(position or "") in _REVIEW_TODO_POSITIONS:
|
||
return "review"
|
||
return "exception"
|
||
return "in_progress"
|
||
|
||
|
||
def _todo_category_without_gate(*, position: str | None, user_mode: Any) -> str:
|
||
"""
|
||
无 Gate 时的待办分类:保留人工/完成细类,禁止把未知态当成系统处理中。
|
||
|
||
核心逻辑:先走 ``_todo_category_from_ui``;若得到 in_progress 则按复核位
|
||
降为 review,否则 exception。
|
||
"""
|
||
kind = user_mode if isinstance(user_mode, UserMode) else UserMode(
|
||
str(user_mode or UserMode.AUTO_CONTINUE),
|
||
)
|
||
category = _todo_category_from_ui(position, kind)
|
||
if category != "in_progress":
|
||
return category
|
||
if str(position or "") in _REVIEW_TODO_POSITIONS:
|
||
return "review"
|
||
return "exception"
|
||
|
||
|
||
def _notice_current_export_artifact(task: Any):
|
||
"""
|
||
取 Notice 当前可上传链路上的最新 Excel Artifact。
|
||
|
||
核心逻辑:``ShippingExportArtifact.task_id`` 是 Notice.id;OT 根实体返回 None。
|
||
"""
|
||
if isinstance(task, ShippingOrderTask):
|
||
return None
|
||
notice_id = getattr(task, 'id', None)
|
||
if notice_id is None:
|
||
return None
|
||
return (
|
||
ShippingExportArtifact.query.filter(
|
||
ShippingExportArtifact.task_id == int(notice_id),
|
||
ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')),
|
||
)
|
||
.order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc())
|
||
.first()
|
||
)
|
||
|
||
|
||
def _todo_category_after_missing_gate(task: Any, *, position: str | None, user_mode: Any) -> str:
|
||
"""
|
||
无 Gate 摘要时的待办分类。
|
||
|
||
核心逻辑:与 SQL 同序——当前 Artifact 已 uploaded→done;否则先走
|
||
``_todo_category_without_gate``;仍为 exception 且有 ready/uploading Excel→manual_upload。
|
||
"""
|
||
artifact = _notice_current_export_artifact(task)
|
||
if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() == 'uploaded':
|
||
return 'done'
|
||
category = _todo_category_without_gate(position=position, user_mode=user_mode)
|
||
if category != "exception":
|
||
return category
|
||
if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() in {
|
||
'ready', 'uploading',
|
||
}:
|
||
return "manual_upload"
|
||
return category
|
||
|
||
|
||
def _todo_category_from_latest_execution(task: Any) -> str | None:
|
||
"""
|
||
Gate 行缺失时按最新 Execution 指针推导 todo_category,与 SQL CASE 对齐。
|
||
|
||
核心逻辑:Execution.task_id 只认 OT.id;有 ``current_gate_code`` 则走
|
||
``_todo_category_from_gate``;否则返回 None 供无 Gate fail-closed。
|
||
"""
|
||
if isinstance(task, ShippingOrderTask):
|
||
order_task_id = getattr(task, 'id', None)
|
||
else:
|
||
order_task_id = getattr(task, 'order_task_id', None)
|
||
if order_task_id is None:
|
||
return None
|
||
execution = (
|
||
ShippingProcessExecution.query
|
||
.filter(
|
||
ShippingProcessExecution.task_id == int(order_task_id),
|
||
ShippingProcessExecution.status != 'superseded',
|
||
)
|
||
.order_by(ShippingProcessExecution.id.desc())
|
||
.first()
|
||
)
|
||
if execution is None or not str(getattr(execution, 'current_gate_code', '') or '').strip():
|
||
return None
|
||
return _todo_category_from_gate(
|
||
{
|
||
'current_gate_code': execution.current_gate_code,
|
||
'status': getattr(execution, 'status', None),
|
||
},
|
||
getattr(task, 'review_status', None),
|
||
)
|
||
|
||
|
||
def _todo_category_from_task_row(
|
||
row: Any,
|
||
*,
|
||
extractions_with_lines: set[int],
|
||
gate_pos: dict[str, Any] | None = None,
|
||
) -> str:
|
||
"""
|
||
用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。
|
||
|
||
核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退,
|
||
且 fail-closed 不得默认 in_progress。
|
||
"""
|
||
del extractions_with_lines # 领域行事实不再参与位置裁决
|
||
if gate_pos is not None and gate_pos.get('current_gate_code'):
|
||
return _todo_category_from_gate(
|
||
gate_pos,
|
||
getattr(row, 'review_status', None),
|
||
)
|
||
from app.services.shipping_notice.process_gate_contract import (
|
||
derive_position,
|
||
derive_user_mode,
|
||
)
|
||
review_status = getattr(row, 'review_status', None)
|
||
position = derive_position(gate_code=None, review_status=review_status)
|
||
user_mode = derive_user_mode(
|
||
user_status=None,
|
||
gate_code=None,
|
||
review_status=review_status,
|
||
lifecycle_stage=None,
|
||
)
|
||
return _todo_category_after_missing_gate(row, position=position, user_mode=user_mode)
|
||
|
||
|
||
def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]:
|
||
"""
|
||
批量返回「已接受且至少有一行」的 extraction_id 集合。
|
||
|
||
核心逻辑:两次 IN 查询替代逐任务 get Extraction + first Line。
|
||
"""
|
||
if not extraction_ids:
|
||
return set()
|
||
accepted_ids = {
|
||
int(row[0])
|
||
for row in db.session.query(ShippingOrderExtraction.id).filter(
|
||
ShippingOrderExtraction.id.in_(tuple(extraction_ids)),
|
||
ShippingOrderExtraction.status == "accepted",
|
||
).all()
|
||
}
|
||
if not accepted_ids:
|
||
return set()
|
||
return {
|
||
int(row[0])
|
||
for row in db.session.query(ShippingOrderLine.extraction_id).filter(
|
||
ShippingOrderLine.extraction_id.in_(tuple(accepted_ids)),
|
||
).distinct().all()
|
||
}
|
||
|
||
|
||
def task_can_handle(task: ShippingNotice, user_id: int, *, is_admin: bool = False) -> bool:
|
||
"""
|
||
判断当前用户是否可对该任务执行写操作。
|
||
|
||
核心逻辑:仅创建者可处理(task.user_id == user_id 且非空);
|
||
user_id IS NULL 一律不可写;管理员代操作首期不开放(他人任务 can_handle=False,
|
||
若管理员本人是创建者仍可处理)。is_admin 保留供调用方显式传参,不单独绕过归属。
|
||
|
||
Args:
|
||
task: 目标任务。
|
||
user_id: 当前操作者用户 ID。
|
||
is_admin: 是否管理员视图;不改变归属判定。
|
||
|
||
Returns:
|
||
是否允许写操作。
|
||
"""
|
||
del is_admin # 首期管理员不可代操作;保留参数以对齐 API 契约。
|
||
return task.user_id is not None and int(task.user_id) == int(user_id)
|
||
|
||
|
||
def _latest_task_event_summary(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""
|
||
取任务最近一条 ShippingTaskEvent 摘要;无事件时返回 None。
|
||
|
||
核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。
|
||
"""
|
||
if isinstance(task, ShippingOrderTask) or task.id is None:
|
||
return None
|
||
event = (
|
||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||
.order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc())
|
||
.first()
|
||
)
|
||
if event is None:
|
||
return None
|
||
return {
|
||
"event_type": event.event_type,
|
||
"created_at": event.created_at.isoformat() if event.created_at else None,
|
||
"detail_json": event.detail_json,
|
||
"actor_id": event.actor_id,
|
||
}
|
||
|
||
|
||
def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""
|
||
投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。
|
||
|
||
核心逻辑:只读取 ShippingExportArtifact;Notice 不保存导出文件投影。
|
||
"""
|
||
artifact = latest_export_artifact(task)
|
||
file_name = str(getattr(artifact, 'file_name', '') or "").strip() or None
|
||
file_path = str(getattr(artifact, 'file_path', '') or "").strip() or None
|
||
if not file_name and not file_path:
|
||
return None
|
||
return {
|
||
"export_file_name": file_name,
|
||
"export_file_path": file_path,
|
||
}
|
||
|
||
|
||
def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||
"""
|
||
投影发货通知列表需要的项次、料号、数量与当前库存事实。
|
||
|
||
核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次直接读取
|
||
ShippingNoticeLine.line_no。该值在通知创建时按本通知从 1 开始编号,
|
||
不允许由订单字段、客户 PO 行号或展示序号派生。
|
||
当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确
|
||
返回 null,禁止由前端估算库存。
|
||
"""
|
||
if task.id is None:
|
||
return []
|
||
if isinstance(task, ShippingOrderTask):
|
||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None
|
||
return [{
|
||
'line_no': int(line.line_no),
|
||
'part_number': line.part_number,
|
||
'customer_part_number': (line.field_values_json or {}).get('customer_part_number'),
|
||
'reservation_id': line.reservation_id,
|
||
'shipment_qty': str(line.qty) if line.qty is not None else None,
|
||
'available_qty': None,
|
||
'shortage_qty': None,
|
||
'inventory_status': None,
|
||
} for line in (getattr(snapshot, 'lines', None) or [])]
|
||
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) if getattr(task, 'order_task_id', None) else None
|
||
snapshot = db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id)) if owner and owner.order_snapshot_id else None
|
||
if snapshot is not None:
|
||
matches_by_snapshot_line_id = {
|
||
int(item.snapshot_line_id): item
|
||
for item in ShippingNoticeLineInventoryMatch.query.filter(
|
||
ShippingNoticeLineInventoryMatch.task_id == int(owner.id),
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
).all()
|
||
if item.snapshot_line_id is not None
|
||
}
|
||
# Snapshot 仅提供订单冻结事实;正式通知的项次、料号、发运数量和预约号
|
||
# 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。
|
||
matches_by_snapshot_line_id = {
|
||
int(item.snapshot_line_id): item
|
||
for item in ShippingNoticeLineInventoryMatch.query.filter(
|
||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
).all()
|
||
if item.snapshot_line_id is not None
|
||
}
|
||
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
|
||
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
|
||
).all()
|
||
return [{
|
||
'line_no': int(item.line_no),
|
||
'part_number': item.part_number,
|
||
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
|
||
'reservation_id': item.reservation_id,
|
||
'shipment_qty': str(item.required_qty) if item.required_qty is not None else None,
|
||
'available_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).available_qty
|
||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||
'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty
|
||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||
'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status
|
||
if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None,
|
||
} for item in rows]
|
||
|
||
|
||
def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None:
|
||
"""
|
||
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
|
||
|
||
核心逻辑:实体本身若是 ShippingOrderTask,直接以自身为 OT(禁止再经
|
||
order_task_id 反查——OT 无该字段,否则会把 SUMMARY 已写入的 order_task_no
|
||
冲成 null,导致工作台右卡 work-item 投影永不启动);Notice 则经
|
||
order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为
|
||
shipping_processing_status(与 shipping_processing_projection 同源),
|
||
并注入 shipping_processing_stage / progress_version / order_task_no;
|
||
另附带 review_run_no / review_case_no / owner_agent_id / conversation_id(经 OT.extraction_run
|
||
与 OT 反查确认 Case),供任务中心「进入订单处理」深链。
|
||
|
||
Args:
|
||
task: ShippingNotice 或 ShippingOrderTask。
|
||
data: 就地写入的序列化字典。
|
||
"""
|
||
from app.models import ShippingOrderProcessingRun, ShippingOrderTask
|
||
from app.services.shipping_notice.shipping_processing_projection import (
|
||
_notice_domain_progress_stage,
|
||
)
|
||
|
||
# [STEP 1] 解析权威 OT:OT 实体即自身;Notice 经 order_task_id 反查。
|
||
order_task: ShippingOrderTask | None = None
|
||
if isinstance(task, ShippingOrderTask):
|
||
order_task = task
|
||
status = str(getattr(task, 'status', '') or '').strip() or 'processing'
|
||
stage = str(getattr(task, 'stage', '') or '').strip() or None
|
||
else:
|
||
order_task_id = getattr(task, 'order_task_id', None)
|
||
if order_task_id is not None:
|
||
order_task = db.session.get(ShippingOrderTask, int(order_task_id))
|
||
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
|
||
)
|
||
data['progress_version'] = int(
|
||
getattr(order_task, 'progress_version', None)
|
||
or getattr(task, 'progress_version', None)
|
||
or 1
|
||
)
|
||
# [STEP 2] order_task_no 必须恒为 OT 编号;OT 自序列化时不得落成 null。
|
||
data['order_task_no'] = (
|
||
str(getattr(order_task, 'task_no', None) or '').strip() or None
|
||
)
|
||
# [UI-04] 任务中心仅作列表入口;深链订单处理工作台需要 Run 编号与 Agent。
|
||
if order_task is not None and getattr(order_task, 'extraction_run_id', None):
|
||
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
|
||
if run is not None:
|
||
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
|
||
if run_no:
|
||
data['review_run_no'] = run_no
|
||
if not str(data.get('conversation_id') or '').strip():
|
||
cid = str(getattr(run, 'conversation_id', None) or '').strip() or None
|
||
if cid:
|
||
data['conversation_id'] = cid
|
||
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
|
||
data['owner_agent_id'] = int(run.owner_agent_id)
|
||
# [STEP 3] 注入确认 Case 号:工作台以 case_no 绑定工作项,OT 直链缺失该字段时
|
||
# 选法 2 不会拉 Case,任务详情身份链断裂、五阶段页签全锁(2026-09-17 工作台直链修复)。
|
||
# confirmed_task_id 唯一约束保证 OT→Case 至多一条,点查代价可忽略。
|
||
if order_task is not None and not str(data.get('review_case_no') or '').strip():
|
||
confirmed_case = (
|
||
ShippingOrderReviewCase.query
|
||
.filter_by(confirmed_task_id=int(order_task.id))
|
||
.first()
|
||
)
|
||
if confirmed_case is not None:
|
||
case_no = str(confirmed_case.case_no or '').strip()
|
||
if case_no:
|
||
data['review_case_no'] = case_no
|
||
|
||
|
||
def _enrich_task_center_fields(
|
||
task: ShippingNotice,
|
||
data: dict[str, Any],
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
include_stage_context: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||
|
||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||
recent_event / artifact_summary / ui_state 懒加载同源状态;
|
||
注入 shipping_processing_status / progress_version / order_task_no(统一进度)。
|
||
``include_stage_context`` 直接透传给 ``build_task_ui_state``,使 DETAIL 一次投影即可携带
|
||
工作面只读事实,避免调用方在同一请求里再 build 一次被覆盖。
|
||
|
||
Args:
|
||
task: 源任务。
|
||
data: 已构建的序列化字典。
|
||
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
|
||
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
|
||
include_stage_context: 是否让内嵌 ui_state 附带 stage_context。
|
||
|
||
Returns:
|
||
同一 data 引用(已 enrich)。
|
||
"""
|
||
data["item_kind"] = "task"
|
||
data["todo_ref"] = task.task_no
|
||
data["created_by"] = task.user_id
|
||
if viewer_user_id is not None:
|
||
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
|
||
# 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。
|
||
data["can_download_export"] = can_download_task_export(
|
||
task, user_id=int(viewer_user_id), is_admin=is_admin,
|
||
)
|
||
data["recent_event"] = _latest_task_event_summary(task)
|
||
data["artifact_summary"] = _artifact_summary_for_task(task)
|
||
data['notice_line_summary'] = _notice_line_summary_for_task(task)
|
||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||
|
||
ui_state = build_task_ui_state(
|
||
task,
|
||
include_stage_context=include_stage_context,
|
||
viewer_user_id=viewer_user_id,
|
||
viewer_is_admin=is_admin,
|
||
)
|
||
data["ui_state"] = ui_state
|
||
# [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution);
|
||
# 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。
|
||
gated = _todo_category_from_process_gate(
|
||
ui_state.get("process_gate") if isinstance(ui_state, dict) else None,
|
||
ui_state.get("review_status") if isinstance(ui_state, dict) else getattr(task, 'review_status', None),
|
||
)
|
||
if gated is None:
|
||
gated = _todo_category_from_latest_execution(task)
|
||
if gated is not None:
|
||
data["todo_category"] = gated
|
||
else:
|
||
data["todo_category"] = _todo_category_after_missing_gate(
|
||
task,
|
||
position=ui_state.get("position") if isinstance(ui_state, dict) else None,
|
||
user_mode=(ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE,
|
||
)
|
||
_inject_unified_processing_fields(task, data)
|
||
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
|
||
data['workflow_item'] = None
|
||
return data
|
||
|
||
|
||
def serialize_task_summary(
|
||
task: ShippingNotice,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
工作台任务列表用的 SUMMARY 投影(含任务中心 enrich)。
|
||
|
||
Args:
|
||
task: 源任务。
|
||
viewer_user_id: 当前查看者;用于 can_handle;缺省时省略该字段。
|
||
is_admin: 是否管理员视图。
|
||
"""
|
||
data = serialize_task(task, TaskProjection.SUMMARY)
|
||
return _enrich_task_center_fields(
|
||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||
)
|
||
|
||
|
||
def _serialize_task_workbench_shell(task: ShippingNotice) -> dict[str, Any]:
|
||
"""
|
||
订单生命周期工作台身份壳:不跑 SUMMARY/DETAIL 重投影。
|
||
|
||
核心逻辑:工作台只消费 task_no / business_no / export_artifacts 等身份字段,
|
||
以及 enrich 写入的 ui_state(含 stage_context)与行摘要;禁止先算 DETAIL 再 pop。
|
||
|
||
Args:
|
||
task: ShippingNotice 或 ShippingOrderTask。
|
||
|
||
Returns:
|
||
供 ``_enrich_task_center_fields`` 就地补全的最小字典。
|
||
"""
|
||
created_at = getattr(task, 'created_at', None)
|
||
updated_at = getattr(task, 'updated_at', None)
|
||
stage = getattr(task, 'stage', None) or getattr(task, 'current_step', None)
|
||
data: dict[str, Any] = {
|
||
'id': getattr(task, 'id', None),
|
||
'task_no': task.task_no,
|
||
'source_type': getattr(task, 'source_type', None),
|
||
'status': getattr(task, 'status', None),
|
||
'stage': stage,
|
||
'current_step': getattr(task, 'current_step', None) or stage,
|
||
'progress_version': getattr(task, 'progress_version', None),
|
||
'conversation_id': getattr(task, 'conversation_id', None),
|
||
'created_at': created_at.isoformat() if created_at else None,
|
||
'updated_at': updated_at.isoformat() if updated_at else None,
|
||
}
|
||
if isinstance(task, ShippingOrderTask):
|
||
data['order_task_no'] = task.task_no
|
||
data['order_snapshot_id'] = getattr(task, 'order_snapshot_id', None)
|
||
data['order_data_version'] = int(getattr(task, 'order_data_version', 1) or 1)
|
||
data['business_no'] = None
|
||
return data
|
||
data['business_no'] = getattr(task, 'business_no', None)
|
||
# Notice 人工上传弹窗仍读 export_artifacts;比整份 DETAIL 轻一个数量级。
|
||
data.update(_fulfillment_timeline(task))
|
||
return data
|
||
|
||
|
||
def serialize_task_detail(
|
||
task: ShippingNotice,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
include_stage_context: bool = False,
|
||
view: str = 'full',
|
||
) -> dict[str, Any]:
|
||
"""
|
||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||
|
||
Args:
|
||
task: 源任务。
|
||
viewer_user_id: 当前查看者;用于 can_handle。
|
||
is_admin: 是否管理员视图。
|
||
include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。
|
||
view: 投影视图。``full`` 返回完整详情(含复核编辑器数据);``workbench`` 为
|
||
订单生命周期工作台首屏投影:只建身份壳再 enrich(ui_state / 行摘要 / 产物),
|
||
**不**进入 SUMMARY/DETAIL 重投影,避免先算 lines/header/match 再剔除。
|
||
"""
|
||
# [PERF] workbench:算之前就轻;禁止 DETAIL 后再 pop。
|
||
if view == 'workbench':
|
||
data = _serialize_task_workbench_shell(task)
|
||
else:
|
||
data = serialize_task(task, TaskProjection.DETAIL)
|
||
return _enrich_task_center_fields(
|
||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||
include_stage_context=include_stage_context,
|
||
)
|
||
|
||
|
||
def list_tasks_for_user(
|
||
user_id: int,
|
||
*,
|
||
limit: int = 100,
|
||
) -> list[dict[str, Any]]:
|
||
"""列出用户可见任务摘要。"""
|
||
safe_limit = max(1, min(limit, 500))
|
||
notice_refs = ShippingNotice.query.filter(
|
||
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)),
|
||
ShippingNotice.deleted_at.is_(None),
|
||
).with_entities(
|
||
literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'),
|
||
ShippingNotice.created_at.label('sort_at'), ShippingNotice.task_no.label('sort_ref'),
|
||
).statement
|
||
ot_refs = ShippingOrderTask.query.filter(
|
||
ShippingOrderTask.user_id == int(user_id),
|
||
ShippingOrderTask.deleted_at.is_(None),
|
||
).with_entities(
|
||
literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'),
|
||
ShippingOrderTask.created_at.label('sort_at'), ShippingOrderTask.task_no.label('sort_ref'),
|
||
).statement
|
||
combined = union_all(notice_refs, ot_refs).subquery('task_refs')
|
||
refs = db.session.execute(
|
||
select(combined.c.kind, combined.c.entity_id)
|
||
.order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id))
|
||
.limit(safe_limit)
|
||
).all()
|
||
notice_ids = [int(entity_id) for kind, entity_id in refs if kind == 'shipping_notice']
|
||
ot_ids = [int(entity_id) for kind, entity_id in refs if kind == 'order_task']
|
||
notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {}
|
||
ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {}
|
||
rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in refs]
|
||
rows = [row for row in rows if row is not None]
|
||
return [
|
||
serialize_task_summary(c, viewer_user_id=user_id)
|
||
for c in rows
|
||
]
|
||
|
||
|
||
def list_tasks_page_for_user(
|
||
user_id: int,
|
||
*,
|
||
page: int = 1,
|
||
page_size: int = 20,
|
||
lifecycle_status: str | None = None,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
分页列出当前用户可见的发货任务摘要。
|
||
|
||
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
|
||
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
|
||
``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export),
|
||
不扩大列表可见范围(仍为本人 + 无主 Notice)。
|
||
"""
|
||
normalized_page = max(1, int(page))
|
||
normalized_page_size = max(1, min(int(page_size), 100))
|
||
notice_q = ShippingNotice.query.filter(
|
||
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None))
|
||
)
|
||
ot_q = ShippingOrderTask.query.filter(ShippingOrderTask.user_id == int(user_id))
|
||
normalized_lifecycle = str(lifecycle_status or 'active').strip().lower()
|
||
if normalized_lifecycle == 'deleted':
|
||
notice_q = notice_q.filter(ShippingNotice.deleted_at.is_not(None))
|
||
ot_q = ot_q.filter(ShippingOrderTask.deleted_at.is_not(None))
|
||
elif normalized_lifecycle == 'active':
|
||
notice_upload_success = exists(select(1).select_from(ShippingUploadAttempt).join(
|
||
ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
|
||
).where(
|
||
ShippingExportArtifact.task_id == ShippingNotice.id,
|
||
ShippingUploadAttempt.status == 'succeeded',
|
||
))
|
||
notice_q = notice_q.filter(
|
||
ShippingNotice.deleted_at.is_(None),
|
||
ShippingNotice.lifecycle_status == 'active',
|
||
~notice_upload_success,
|
||
)
|
||
ot_q = ot_q.filter(
|
||
ShippingOrderTask.deleted_at.is_(None),
|
||
ShippingOrderTask.lifecycle_status == 'active',
|
||
ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}),
|
||
)
|
||
else:
|
||
notice_q = notice_q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle)
|
||
ot_q = ot_q.filter(ShippingOrderTask.lifecycle_status == normalized_lifecycle)
|
||
|
||
union_stmt = union_all(
|
||
notice_q.with_entities(
|
||
literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'),
|
||
func.coalesce(ShippingNotice.created_at, ShippingNotice.updated_at).label('sort_at'),
|
||
ShippingNotice.task_no.label('sort_ref'),
|
||
).statement,
|
||
ot_q.with_entities(
|
||
literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'),
|
||
func.coalesce(ShippingOrderTask.created_at, ShippingOrderTask.updated_at).label('sort_at'),
|
||
ShippingOrderTask.task_no.label('sort_ref'),
|
||
).statement,
|
||
).subquery('task_union')
|
||
total = int(db.session.execute(select(func.count()).select_from(union_stmt)).scalar_one() or 0)
|
||
offset = (normalized_page - 1) * normalized_page_size
|
||
page_refs = db.session.execute(
|
||
select(union_stmt.c.kind, union_stmt.c.entity_id)
|
||
.order_by(desc(union_stmt.c.sort_at), desc(union_stmt.c.sort_ref), desc(union_stmt.c.entity_id))
|
||
.offset(offset).limit(normalized_page_size)
|
||
).all() if offset < total else []
|
||
notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'shipping_notice']
|
||
ot_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'order_task']
|
||
notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {}
|
||
ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {}
|
||
rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in page_refs]
|
||
rows = [row for row in rows if row is not None]
|
||
return {
|
||
"items": [
|
||
serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin)
|
||
for item in rows
|
||
],
|
||
"page": normalized_page,
|
||
"page_size": normalized_page_size,
|
||
"total": total,
|
||
}
|
||
|
||
|
||
def get_task_for_user(task_no: str, user_id: int) -> ShippingOrderTask | ShippingNotice | None:
|
||
"""
|
||
按 task_no 查找任务并校验写路径归属(严格创建者)。
|
||
|
||
核心逻辑:仅当 task.user_id == user_id 时返回;user_id IS NULL 一律拒绝,
|
||
避免历史无主任务被任意登录用户写入。管理员只读请用 get_task_visible_to_user。
|
||
"""
|
||
task = get_task_by_ref(task_no)
|
||
if not task:
|
||
return None
|
||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||
return None
|
||
return task
|
||
|
||
|
||
def get_task_visible_to_user(
|
||
task_no: str,
|
||
user_id: int,
|
||
*,
|
||
is_admin: bool = False,
|
||
) -> ShippingOrderTask | ShippingNotice | None:
|
||
"""
|
||
按 task_no 查找当前用户可见的任务(创建者或管理员只读)。
|
||
|
||
核心逻辑:管理员可读全部;普通用户仅可读自己创建且 user_id 非空的任务。
|
||
写操作仍须经 get_task_for_user / task_can_handle 门禁。
|
||
|
||
Args:
|
||
task_no: 任务编号。
|
||
user_id: 当前用户。
|
||
is_admin: 为 True 时允许管理员只读可见。
|
||
|
||
Returns:
|
||
可见任务或 None。
|
||
"""
|
||
task = get_task_by_ref(task_no)
|
||
if not task:
|
||
return None
|
||
if is_admin:
|
||
return task
|
||
if task.user_id is None or int(task.user_id) != int(user_id):
|
||
return None
|
||
return task
|
||
|
||
|
||
def can_download_task_export(
|
||
task: ShippingOrderTask | ShippingNotice | None,
|
||
*,
|
||
user_id: int,
|
||
is_admin: bool = False,
|
||
) -> bool:
|
||
"""
|
||
导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。
|
||
|
||
核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、
|
||
can_download_export 字段都必须消费本谓词,禁止各处另行推导归属;
|
||
管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。
|
||
无主任务(user_id IS NULL)仅管理员可下载。
|
||
|
||
Args:
|
||
task: 已加载的任务实体(可为 None)。
|
||
user_id: 当前查看/下载用户。
|
||
is_admin: 是否平台管理员。
|
||
|
||
Returns:
|
||
当前用户是否允许下载该任务的正式 Excel。
|
||
"""
|
||
if task is None:
|
||
return False
|
||
if is_admin:
|
||
return True
|
||
return task.user_id is not None and int(task.user_id) == int(user_id)
|
||
|
||
|
||
def list_freight_notice_groups_for_task(
|
||
task: ShippingNotice,
|
||
*,
|
||
user_id: int,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。
|
||
|
||
核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的
|
||
Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未
|
||
分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。
|
||
|
||
Args:
|
||
task: 当前订单工作台已授权读取的正式 Notice。
|
||
user_id: 当前用户;非管理员仅返回其创建的 Notice。
|
||
is_admin: 管理员只读可见范围。
|
||
|
||
Returns:
|
||
包含 PO 及一行一个 business_no 的货代上传聚合投影。
|
||
"""
|
||
po_number = _notice_po_number(task)
|
||
if not po_number:
|
||
return {'po_number': None, 'items': [], 'reason': 'po_missing'}
|
||
|
||
candidates = ShippingNotice.query.filter(
|
||
ShippingNotice.deleted_at.is_(None),
|
||
ShippingNotice.lifecycle_status == 'active',
|
||
ShippingNotice.business_no.isnot(None),
|
||
)
|
||
if not is_admin:
|
||
candidates = candidates.filter(ShippingNotice.user_id == int(user_id))
|
||
|
||
items: list[dict[str, Any]] = []
|
||
for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all():
|
||
if _notice_po_number(notice) != po_number:
|
||
continue
|
||
business_no = str(notice.business_no or '').strip()
|
||
if not business_no:
|
||
continue
|
||
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
|
||
# 轻量投影仅返回动作码,避免逐张 Notice 跑完整 build_task_ui_state 造成 N 倍放大。
|
||
from app.services.shipping_notice.ui_state import project_notice_available_actions
|
||
available_actions = project_notice_available_actions(notice)
|
||
# [STEP] upload_mode/upload_attempt 从 ShippingUploadAttempt 权威事实解析。
|
||
# denormalized Notice.upload_mode 恒为 None,不能作为「人工/RPA」展示来源。
|
||
upload_mode, upload_attempt = _task_upload_attempt_facts(notice.id)
|
||
latest_attempt = (
|
||
ShippingUploadAttempt.query
|
||
.join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id)
|
||
.filter(ShippingExportArtifact.task_id == int(notice.id))
|
||
.order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc())
|
||
.first()
|
||
)
|
||
artifact = (
|
||
ShippingExportArtifact.query
|
||
.filter(ShippingExportArtifact.task_id == int(notice.id))
|
||
.order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc())
|
||
.first()
|
||
)
|
||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||
items.append({
|
||
'business_no': business_no,
|
||
'po_number': po_number,
|
||
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
||
'upload_status': project_notice_upload_status(notice),
|
||
'upload_mode': upload_mode,
|
||
'upload_attempt': upload_attempt,
|
||
'upload_error_code': getattr(latest_attempt, 'error_code', None),
|
||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
|
||
'export_file_name': getattr(artifact, 'file_name', None),
|
||
'available_actions': available_actions,
|
||
'lines': _notice_line_summary_for_task(notice),
|
||
})
|
||
return {
|
||
'po_number': po_number,
|
||
'items': items,
|
||
'reason': None if items else 'no_business_notice',
|
||
}
|
||
|
||
|
||
def _task_upload_attempt_facts(task_id: int | None) -> tuple[str | None, int]:
|
||
"""从 ShippingUploadAttempt 权威事实解析任务上传方式与尝试次数。
|
||
|
||
读取侧不再消费 denormalized 的 Notice.upload_mode / upload_attempt(这两个列从未被
|
||
写入真实值,恒为 None/0)。成功态的 mode 优先(通知完成面以此区分人工/RPA),
|
||
否则回退最近一条 attempt 的 mode,与 ui_state._build_stage_context 的判定保持一致。
|
||
|
||
Args:
|
||
task_id: 正式 Notice 主键;为空时返回 (None, 0)。
|
||
|
||
Returns:
|
||
tuple[str | None, int]: (mode, attempt_count);无任何 attempt 时返回 (None, 0)。
|
||
"""
|
||
if not task_id:
|
||
return None, 0
|
||
attempts = (
|
||
ShippingUploadAttempt.query
|
||
.join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id)
|
||
.filter(ShippingExportArtifact.task_id == int(task_id))
|
||
.order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc())
|
||
.all()
|
||
)
|
||
if not attempts:
|
||
return None, 0
|
||
succeeded = next(
|
||
(item for item in attempts if str(item.status or '').strip().lower() == 'succeeded'),
|
||
None,
|
||
)
|
||
anchor = succeeded or attempts[0]
|
||
return (anchor.mode if anchor is not None else None), len(attempts)
|
||
|
||
|
||
def _notice_po_number(notice: ShippingNotice) -> str:
|
||
"""读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。"""
|
||
header = current_header_field_values_or_empty(notice)
|
||
for field_code in ('customer_po_number', 'po_number'):
|
||
normalized = normalize_po_number(header.get(field_code))
|
||
if normalized:
|
||
return normalized
|
||
|
||
owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None
|
||
snapshot = None
|
||
snapshot_id = getattr(owner, 'order_snapshot_id', None)
|
||
if snapshot_id:
|
||
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id)
|
||
if snapshot:
|
||
for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')):
|
||
normalized = normalize_po_number(value)
|
||
if normalized:
|
||
return normalized
|
||
|
||
candidate = (
|
||
db.session.get(ShippingOrderCandidate, notice.source_candidate_id)
|
||
if notice.source_candidate_id else None
|
||
)
|
||
normalized = normalize_po_number(getattr(candidate, 'po_number', None))
|
||
return normalized
|
||
|
||
|
||
def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool:
|
||
"""待办列表客户关键字过滤:匹配确认客户快照、来源文档或当前订单头证据。"""
|
||
needle = str(customer or "").strip().lower()
|
||
if not needle:
|
||
return True
|
||
candidates: list[str] = []
|
||
owner = task if isinstance(task, ShippingOrderTask) else (
|
||
db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else None
|
||
)
|
||
if owner is not None:
|
||
customer = _order_task_customer_projection(owner)
|
||
for value in (customer['customer_name_snapshot'], customer['customer_short_code_snapshot']):
|
||
if value:
|
||
candidates.append(str(value))
|
||
docs = db.session.query(ShippingOrderDocument.filename).join(
|
||
ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id,
|
||
).filter(ShippingOrderCandidate.id == owner.candidate_id).all() if owner.candidate_id else []
|
||
candidates.extend(str(row[0]) for row in docs if row[0])
|
||
header = current_header_field_values_or_empty(task)
|
||
for key in ("customer_name", "ship_to_customer", "customer_code"):
|
||
value = header.get(key)
|
||
if value:
|
||
candidates.append(str(value))
|
||
return any(needle in item.lower() for item in candidates)
|
||
|
||
|
||
def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False):
|
||
"""构造正式 ShippingNotice 的待办查询;OT 由 `_visible_order_tasks_query_for_todos` 提供。"""
|
||
q = ShippingNotice.query.filter(
|
||
ShippingNotice.deleted_at.is_(None),
|
||
ShippingNotice.lifecycle_status == "active",
|
||
)
|
||
if not is_admin:
|
||
# 待办中心拒绝无主任务;仅创建者可见。
|
||
q = q.filter(ShippingNotice.user_id == user_id)
|
||
return q
|
||
|
||
|
||
def _visible_order_tasks_query_for_todos(user_id: int, *, is_admin: bool = False):
|
||
"""构造库存准备前 OT 待办查询;OT 是正式 Notice 创建前唯一可见根实体。"""
|
||
query = ShippingOrderTask.query.filter(
|
||
ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}),
|
||
~exists(
|
||
select(1).select_from(ShippingNotice).where(
|
||
ShippingNotice.order_task_id == ShippingOrderTask.id,
|
||
)
|
||
),
|
||
)
|
||
if not is_admin:
|
||
query = query.filter(ShippingOrderTask.user_id == int(user_id))
|
||
return query
|
||
|
||
|
||
def _latest_process_execution_field_sql(task_id_column, field_name: str):
|
||
"""
|
||
最新非 superseded Execution 的指定列(scalar subquery),供待办 SQL Gate-first。
|
||
|
||
Args:
|
||
task_id_column: OT 主键列表达式(Notice.order_task_id 或 OrderTask.id)。
|
||
field_name: ``current_gate_code`` 或 ``status``。
|
||
"""
|
||
column = getattr(ShippingProcessExecution, field_name)
|
||
return (
|
||
select(column)
|
||
.where(
|
||
ShippingProcessExecution.task_id == task_id_column,
|
||
ShippingProcessExecution.status != 'superseded',
|
||
)
|
||
.order_by(ShippingProcessExecution.id.desc())
|
||
.limit(1)
|
||
.scalar_subquery()
|
||
)
|
||
|
||
|
||
def _gate_todo_category_sql_whens(task_id_column):
|
||
"""
|
||
Gate 优先的 todo_category CASE when 列表(对齐 derive_todo_category)。
|
||
|
||
核心逻辑:Execution.status 区分系统在跑与阻断;复核 gate 仅在 blocked/failed
|
||
时进 review;人工上传 handoff→manual_upload;短缺/失败类 gate→exception;
|
||
active/waiting_external→in_progress。禁止无状态默认 in_progress。
|
||
"""
|
||
gate_code = _latest_process_execution_field_sql(task_id_column, 'current_gate_code')
|
||
gate_exec_status = _latest_process_execution_field_sql(task_id_column, 'status')
|
||
blocked_or_failed = gate_exec_status.in_(tuple(sorted(_BLOCKED_OR_FAILED_EXECUTION_STATUSES)))
|
||
running_exec = gate_exec_status.in_(tuple(sorted(_RUNNING_EXECUTION_STATUSES)))
|
||
return [
|
||
(
|
||
db.and_(
|
||
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
|
||
blocked_or_failed,
|
||
),
|
||
literal('review'),
|
||
),
|
||
(
|
||
db.and_(
|
||
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
|
||
running_exec,
|
||
),
|
||
literal('in_progress'),
|
||
),
|
||
(
|
||
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
|
||
literal('review'),
|
||
),
|
||
(
|
||
gate_code.in_(('manual_upload_handoff',)),
|
||
literal('manual_upload'),
|
||
),
|
||
(
|
||
db.and_(
|
||
gate_code.in_(('artifact_generation',)),
|
||
gate_exec_status.in_(('blocked', 'completed')),
|
||
),
|
||
literal('manual_upload'),
|
||
),
|
||
(
|
||
db.and_(
|
||
gate_code.in_(tuple(sorted(_EXCEPTION_TODO_GATE_CODES))),
|
||
blocked_or_failed,
|
||
),
|
||
literal('exception'),
|
||
),
|
||
(
|
||
gate_exec_status.in_(('failed',)),
|
||
literal('exception'),
|
||
),
|
||
(
|
||
gate_exec_status.in_(('blocked',)),
|
||
literal('exception'),
|
||
),
|
||
(
|
||
running_exec,
|
||
literal('in_progress'),
|
||
),
|
||
]
|
||
|
||
|
||
def _order_task_todo_category_sql_expr():
|
||
"""按 Gate 优先、再领域事实投影 OT 待办;无判定时 fail-closed 为 exception。"""
|
||
stage = db.func.lower(db.func.coalesce(ShippingOrderTask.stage, ""))
|
||
reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, ""))
|
||
ready_file = exists(
|
||
select(1)
|
||
.select_from(ShippingTaskInventoryLink)
|
||
.join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id)
|
||
.where(
|
||
ShippingTaskInventoryLink.task_id == ShippingOrderTask.id,
|
||
ShippingTaskInventoryLink.is_active.is_(True),
|
||
ShippingTaskInventoryLink.invalidated_at.is_(None),
|
||
ShippingInventoryFile.snapshot_status == 'ready',
|
||
ShippingInventoryFile.invalidated_at.is_(None),
|
||
ShippingInventoryFile.line_count > 0,
|
||
)
|
||
)
|
||
incomplete_match = exists(
|
||
select(1)
|
||
.select_from(ShippingOrderSnapshotLine)
|
||
.where(
|
||
ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id,
|
||
~exists(
|
||
select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||
ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id,
|
||
ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id,
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
ShippingNoticeLineInventoryMatch.match_result != 'preparing',
|
||
)
|
||
),
|
||
)
|
||
)
|
||
has_shortage = exists(
|
||
select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||
ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id,
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
db.or_(
|
||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||
db.and_(
|
||
ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None),
|
||
ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')),
|
||
),
|
||
),
|
||
)
|
||
)
|
||
manual_gate = exists(
|
||
select(1)
|
||
.select_from(ShippingProcessExecution)
|
||
.join(ShippingProcessGate, ShippingProcessGate.execution_id == ShippingProcessExecution.id)
|
||
.where(
|
||
ShippingProcessExecution.task_id == ShippingOrderTask.id,
|
||
ShippingProcessExecution.status.notin_(('completed', 'cancelled', 'superseded')),
|
||
ShippingProcessGate.status.in_(('blocked_manual', 'failed_terminal')),
|
||
)
|
||
)
|
||
return case(
|
||
*_gate_todo_category_sql_whens(ShippingOrderTask.id),
|
||
(
|
||
db.or_(
|
||
reason.in_((PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_INVENTORY_SOURCE_UNRESOLVED, PH_SHORTAGE)),
|
||
manual_gate,
|
||
db.and_(ShippingOrderTask.order_snapshot_id.isnot(None), ~incomplete_match, has_shortage),
|
||
),
|
||
literal("exception"),
|
||
),
|
||
(
|
||
db.and_(
|
||
ShippingOrderTask.order_snapshot_id.isnot(None),
|
||
ready_file,
|
||
incomplete_match,
|
||
),
|
||
literal("in_progress"),
|
||
),
|
||
(stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")),
|
||
else_=literal("exception"),
|
||
)
|
||
|
||
def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False):
|
||
"""
|
||
构造建单前开放 Review Case 查询(尚未确认建单)。
|
||
|
||
核心逻辑:排除已确认/非订单/已替代 Case;非管理员仅 owner_user_id==user_id。
|
||
"""
|
||
q = ShippingOrderReviewCase.query.join(
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||
).filter(
|
||
ShippingOrderReviewCase.status.in_(tuple(_OPEN_REVIEW_CASE_STATUSES)),
|
||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||
)
|
||
if not is_admin:
|
||
q = q.filter(ShippingOrderReviewCase.owner_user_id == int(user_id))
|
||
return q
|
||
|
||
|
||
def serialize_review_case_todo(
|
||
case: ShippingOrderReviewCase,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
将建单前 Review Case 投影为「我的待办」列表项,供打开人工复核深链。
|
||
|
||
核心逻辑:附带 review_run_no / review_case_no / owner_agent_id / conversation_id;
|
||
todo_category 固定 review;entry_surface=review_workbench;
|
||
STP failed/manual_fallback 时投影 retry_stp_auto_create(与工作台底栏同一幂等键)。
|
||
|
||
Args:
|
||
case: 开放中的 Review Case。
|
||
viewer_user_id: 当前查看者;用于 can_handle。
|
||
is_admin: 是否管理员视图(不开放代操作)。
|
||
|
||
Returns:
|
||
与任务 SUMMARY 兼容的待办字典。
|
||
"""
|
||
del is_admin
|
||
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
|
||
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
|
||
lifecycle = _review_case_lifecycle_projection(case)
|
||
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified')
|
||
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
|
||
from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES
|
||
stage_index = next(
|
||
(index for index, item in enumerate(LIFECYCLE_STAGES)
|
||
if item.get('code') == lifecycle_stage),
|
||
0,
|
||
)
|
||
stage_definition = next(
|
||
(item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage),
|
||
{'code': lifecycle_stage, 'label': '状态待同步'},
|
||
)
|
||
source_name = None
|
||
if document is not None:
|
||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||
current_todo = _REVIEW_CASE_STATUS_TODO.get(str(case.status), "订单 PDF 待人工复核")
|
||
can_handle = (
|
||
viewer_user_id is not None
|
||
and case.owner_user_id is not None
|
||
and int(case.owner_user_id) == int(viewer_user_id)
|
||
)
|
||
allowed_actions: list[str] = []
|
||
action_buttons: list[str] = []
|
||
automation_status: str | None = None
|
||
# [STEP] 任务中心与底栏共用 STP 重试入口:仅 failed/manual_fallback + 可处理人。
|
||
try:
|
||
from app.services.shipping_notice.order_review_projection import (
|
||
_project_case_automation_status,
|
||
_project_post_confirm_auto_progress,
|
||
)
|
||
|
||
draft = case.current_draft
|
||
automation = _project_case_automation_status(
|
||
case,
|
||
validation=dict(draft.validation_result_json or {}) if draft is not None else None,
|
||
post_confirm=_project_post_confirm_auto_progress(case),
|
||
)
|
||
if isinstance(automation, dict):
|
||
automation_status = str(automation.get('status') or '').strip() or None
|
||
if (
|
||
can_handle
|
||
and automation.get('retryable')
|
||
and automation_status in {'failed', 'manual_fallback'}
|
||
and not case.confirmed_task_id
|
||
):
|
||
allowed_actions.append('retry_stp_auto_create')
|
||
action_buttons.append('retry_stp_auto_create')
|
||
current_todo = '自动建单推进失败,可重试自动推进'
|
||
except Exception: # noqa: BLE001
|
||
automation_status = None
|
||
run_no = str(getattr(run, "run_no", None) or "").strip() or None
|
||
conversation_id = str(getattr(run, "conversation_id", None) or "").strip() or None
|
||
owner_agent_id = getattr(run, "owner_agent_id", None)
|
||
item: dict[str, Any] = {
|
||
"item_kind": "review_case",
|
||
"todo_ref": case.case_no,
|
||
"task_no": None,
|
||
"todo_category": "review",
|
||
"review_run_no": run_no,
|
||
"review_case_no": case.case_no,
|
||
"review_case_status": case.status,
|
||
"conversation_id": conversation_id,
|
||
"owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None,
|
||
"created_by": case.owner_user_id,
|
||
"source_file_name": source_name,
|
||
"customer_name": 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": {
|
||
"stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)},
|
||
# [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影;
|
||
# 前端不得按 Case 状态或待办类别补造订单复核权限。
|
||
"lifecycle_stage": lifecycle_stage,
|
||
"lifecycle_entries": lifecycle_entries,
|
||
"intake_parse_authorized": lifecycle_stage == "intake_parse",
|
||
"position": lifecycle_stage,
|
||
"user_mode": str(UserMode.MUST_HUMAN),
|
||
"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,
|
||
"summary": {
|
||
"title": "待人工复核",
|
||
"message": current_todo,
|
||
"stage": "待人工复核",
|
||
"user_mode": str(UserMode.MUST_HUMAN),
|
||
"current_todo": current_todo,
|
||
"pause_reason": current_todo,
|
||
"pause_reason_code": (
|
||
f"stp_automation_{automation_status}"
|
||
if automation_status in {'failed', 'manual_fallback'}
|
||
else f"review_case_{case.status}"
|
||
),
|
||
"next_auto_step": None,
|
||
"event_at": case.updated_at.isoformat() if case.updated_at else None,
|
||
"entry_surface": "review_workbench",
|
||
"allowed_actions": allowed_actions,
|
||
"automation_status": automation_status,
|
||
"issues": [],
|
||
"error_message": None,
|
||
},
|
||
},
|
||
}
|
||
if viewer_user_id is not None:
|
||
item["can_handle"] = can_handle
|
||
return item
|
||
|
||
|
||
def _linked_active_ot_intake_ids_subquery():
|
||
"""
|
||
已挂接到有效 Processing Run(已有 user_task_no)的 Intake id 子查询。
|
||
|
||
核心逻辑:未释放的 RunIntake 即视为已进入 order_task,不再作为孤儿 Intake 待办。
|
||
"""
|
||
return (
|
||
db.session.query(ShippingOrderProcessingRunIntake.intake_id.label("intake_id"))
|
||
.join(
|
||
ShippingOrderProcessingRun,
|
||
ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id,
|
||
)
|
||
.filter(
|
||
ShippingOrderProcessingRunIntake.released_at.is_(None),
|
||
ShippingOrderProcessingRun.user_task_no.isnot(None),
|
||
)
|
||
.distinct()
|
||
.subquery()
|
||
)
|
||
|
||
|
||
def _visible_orphan_intakes_query(user_id: int, *, is_admin: bool = False):
|
||
"""
|
||
可见的尚未建 OT Intake 查询(解析中/解析失败)。
|
||
|
||
核心逻辑:purpose=shipping_notice 且 parse_status ∈ 孤儿集合;排除已挂 OT;
|
||
非管理员仅本人。
|
||
|
||
Args:
|
||
user_id: 当前用户。
|
||
is_admin: 管理员可读全局。
|
||
|
||
Returns:
|
||
SQLAlchemy Query[ShippingOrderIntake]。
|
||
"""
|
||
linked = _linked_active_ot_intake_ids_subquery()
|
||
q = ShippingOrderIntake.query.filter(
|
||
ShippingOrderIntake.purpose == "shipping_notice",
|
||
ShippingOrderIntake.parse_status.in_(tuple(sorted(_ORPHAN_INTAKE_TODO_PARSE_STATUSES))),
|
||
~ShippingOrderIntake.id.in_(db.session.query(linked.c.intake_id)),
|
||
)
|
||
if not is_admin:
|
||
q = q.filter(ShippingOrderIntake.user_id == int(user_id))
|
||
return q
|
||
|
||
|
||
def _apply_orphan_intake_customer_filter(
|
||
query,
|
||
*,
|
||
customer_needle: str,
|
||
customer_like: str,
|
||
):
|
||
"""
|
||
按来源文件名 / Intake 编号模糊过滤孤儿 Intake。
|
||
|
||
核心逻辑:无关键字时原样返回;否则 JOIN FileAsset 匹配 original_filename 或 intake_no。
|
||
"""
|
||
if not customer_needle:
|
||
return query
|
||
return (
|
||
query.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
|
||
.filter(
|
||
db.or_(
|
||
FileAsset.original_filename.ilike(customer_like),
|
||
ShippingOrderIntake.intake_no.ilike(customer_like),
|
||
)
|
||
)
|
||
)
|
||
|
||
|
||
def serialize_intake_todo(
|
||
intake: ShippingOrderIntake,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
将尚未建 OT 的 Intake 投影为「我的待办」列表项,供对话恢复卡深链。
|
||
|
||
核心逻辑:todo_category=intake_parse;entry_surface=conversation_processing;
|
||
失败态附带 error_code;可经 conversation_id + owner_agent_id 打开会话。
|
||
|
||
Args:
|
||
intake: ShippingOrderIntake。
|
||
viewer_user_id: 当前查看者。
|
||
is_admin: 管理员视图标记(不开放代操作)。
|
||
|
||
Returns:
|
||
与任务 SUMMARY 兼容的待办字典。
|
||
"""
|
||
del is_admin
|
||
asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None
|
||
source_name = None
|
||
if asset is not None:
|
||
source_name = str(getattr(asset, "original_filename", None) or "").strip() or None
|
||
submission = None
|
||
if intake.order_submission_id:
|
||
submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id))
|
||
owner_agent_id = getattr(submission, "owner_agent_id", None) if submission is not None else None
|
||
parse_status = str(intake.parse_status or "").strip().lower()
|
||
failed = parse_status == "parse_failed"
|
||
title = "材料解析失败" if failed else "材料解析中"
|
||
message = (
|
||
str(intake.error_message or "").strip()
|
||
or str(intake.error_code or "").strip()
|
||
or ("请从失败节点重试解析" if failed else "材料仍在解析,请稍后在对话中查看进度")
|
||
)
|
||
can_handle = (
|
||
viewer_user_id is not None
|
||
and int(intake.user_id) == int(viewer_user_id)
|
||
)
|
||
item: dict[str, Any] = {
|
||
"item_kind": "order_intake",
|
||
"todo_ref": intake.intake_no,
|
||
"task_no": None,
|
||
"todo_category": "intake_parse",
|
||
"intake_no": intake.intake_no,
|
||
"intake_parse_status": parse_status,
|
||
"conversation_id": str(intake.conversation_id or "").strip() or None,
|
||
"owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None,
|
||
"created_by": intake.user_id,
|
||
"source_file_name": source_name,
|
||
"source_type": str(intake.source_type or "").strip() or None,
|
||
"customer_name": None,
|
||
"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": {
|
||
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
|
||
# Intake 尚未有当前有效订单 Candidate;只能进入对话查看解析,不能进入生命周期工作台。
|
||
"lifecycle_stage": "intake_parse",
|
||
"lifecycle_entries": [],
|
||
"position": "order_field_extraction",
|
||
"user_mode": str(
|
||
UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE
|
||
),
|
||
"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,
|
||
"summary": {
|
||
"title": title,
|
||
"message": message,
|
||
"stage": title,
|
||
"user_mode": str(
|
||
UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE
|
||
),
|
||
"current_todo": title,
|
||
"pause_reason": message if failed else None,
|
||
"pause_reason_code": (
|
||
str(intake.error_code or "").strip() or "intake_parse_failed"
|
||
if failed
|
||
else f"intake_{parse_status}"
|
||
),
|
||
"next_auto_step": None if failed else "document_parsing",
|
||
"event_at": intake.updated_at.isoformat() if intake.updated_at else None,
|
||
"entry_surface": "conversation_processing",
|
||
"allowed_actions": ["retry_parse"] if failed else [],
|
||
"issues": [],
|
||
"error_message": str(intake.error_message or "").strip() or None,
|
||
},
|
||
},
|
||
}
|
||
if viewer_user_id is not None:
|
||
item["can_handle"] = can_handle
|
||
return item
|
||
|
||
|
||
def _todo_category_sql_filter(allowed: frozenset[str]):
|
||
"""
|
||
将待办类别粗筛下推到 SQL,缩小活跃任务读取面。
|
||
|
||
核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。
|
||
"""
|
||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||
workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||
workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||
workflow_customer_pending = exists(
|
||
select(1).select_from(ShippingCustomerShadowResolution)
|
||
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
|
||
.where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
ShippingCustomerShadowResolution.status != 'confirmed',
|
||
)
|
||
)
|
||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||
upload_success = _verified_upload_success_sql_expr()
|
||
upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown'))))
|
||
clauses = []
|
||
if "manual_upload" in allowed:
|
||
# wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。
|
||
clauses.append(
|
||
db.or_(
|
||
upload_pending,
|
||
db.and_(
|
||
artifact_exists,
|
||
db.or_(
|
||
~upload_success,
|
||
),
|
||
ShippingNotice.lifecycle_status == "active",
|
||
),
|
||
)
|
||
)
|
||
if "done" in allowed:
|
||
# 已上传/关闭/驳回终态(不含待人工上传登记)。
|
||
clauses.append(
|
||
db.or_(
|
||
upload_success,
|
||
workflow_review_status == RS_REJECTED,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
)
|
||
)
|
||
if "review" in allowed:
|
||
clauses.append(
|
||
db.or_(
|
||
workflow_review_status.isnot(None),
|
||
workflow_pending_reason.isnot(None),
|
||
)
|
||
)
|
||
if "exception" in allowed:
|
||
clauses.append(workflow_pending_reason.isnot(None))
|
||
if "in_progress" in allowed:
|
||
clauses.append(
|
||
db.or_(
|
||
workflow_current_step.isnot(None),
|
||
exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||
ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id,
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
|
||
)),
|
||
artifact_exists,
|
||
upload_pending,
|
||
)
|
||
)
|
||
if not clauses:
|
||
return None
|
||
return db.or_(*clauses)
|
||
|
||
|
||
def _task_has_dynamic_order_lines_sql():
|
||
"""
|
||
SQL 版「已接受 Extraction 且至少有一行」。
|
||
|
||
核心逻辑:关联 EXISTS,对齐 _task_has_dynamic_order_lines,供分类 CASE 复用。
|
||
"""
|
||
return exists(
|
||
select(1)
|
||
.select_from(ShippingOrderExtraction)
|
||
.where(
|
||
ShippingOrderExtraction.id == select(ShippingOrderTask.current_order_extraction_id).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery(),
|
||
ShippingOrderExtraction.status == "accepted",
|
||
exists(
|
||
select(1)
|
||
.select_from(ShippingOrderLine)
|
||
.where(ShippingOrderLine.extraction_id == ShippingOrderExtraction.id)
|
||
),
|
||
)
|
||
)
|
||
|
||
|
||
def _sql_json_falsy(column):
|
||
"""
|
||
JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。
|
||
|
||
核心逻辑:Postgres `json` 无等号运算符(`json = json` 会 UndefinedFunction);
|
||
转为 text 再与紧凑字面量比较,兼容 SQLite 测试库。
|
||
"""
|
||
as_text = cast(column, String)
|
||
return db.or_(column.is_(None), as_text == '[]', as_text == '{}')
|
||
|
||
|
||
def _sql_str_blank(column):
|
||
"""字符串列空白:NULL 或空串。"""
|
||
return db.or_(column.is_(None), column == "")
|
||
|
||
|
||
def _task_todo_category_sql_expr():
|
||
"""
|
||
待办 todo_category 的 SQL CASE:Gate 优先,再 review_status / 领域标量回退。
|
||
|
||
核心逻辑:不再与 resolve_task_ui_state「同序」;与 ORM
|
||
``task_todo_category`` / ``derive_todo_category`` 对齐。无 Gate 且无法判定时
|
||
fail-closed 为 exception,禁止 else in_progress。
|
||
"""
|
||
has_lines = _task_has_dynamic_order_lines_sql()
|
||
reason = select(ShippingOrderTask.pending_human_reason).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery()
|
||
review_status = select(ShippingOrderTask.review_status).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery()
|
||
snapshot_id = select(ShippingOrderTask.order_snapshot_id).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery()
|
||
customer_pending = exists(
|
||
select(1).select_from(ShippingCustomerShadowResolution)
|
||
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
|
||
.where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
ShippingCustomerShadowResolution.status != 'confirmed',
|
||
)
|
||
)
|
||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded"))))
|
||
upload_success = _verified_upload_success_sql_expr()
|
||
upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown"))))
|
||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(
|
||
ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id,
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
))
|
||
return case(
|
||
(upload_success, literal("done")),
|
||
(ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")),
|
||
(
|
||
db.or_(
|
||
review_status == RS_REJECTED,
|
||
),
|
||
literal("done"),
|
||
),
|
||
# [STEP] Gate-first(经 order_task_id 关联最新 Execution)
|
||
*_gate_todo_category_sql_whens(ShippingNotice.order_task_id),
|
||
(
|
||
db.or_(reason == PH_RSV_REQ, review_status == RS_RSV_REQ),
|
||
literal("review"),
|
||
),
|
||
(
|
||
db.or_(reason == PH_LOW_CONF, review_status == RS_PARSE_REVIEW),
|
||
literal("review"),
|
||
),
|
||
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
|
||
(
|
||
db.and_(
|
||
customer_pending,
|
||
),
|
||
literal("exception"),
|
||
),
|
||
(
|
||
db.and_(
|
||
snapshot_id.is_(None),
|
||
has_lines,
|
||
),
|
||
literal("in_progress"),
|
||
),
|
||
(reason == PH_RPA_EXHAUSTED, literal("exception")),
|
||
# Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。
|
||
(artifact_exists, literal("manual_upload")),
|
||
(
|
||
db.and_(
|
||
match_exists,
|
||
artifact_exists,
|
||
),
|
||
literal("manual_upload"),
|
||
),
|
||
(reason == PH_INV_UNAVAIL, literal("exception")),
|
||
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
|
||
(
|
||
db.or_(reason == PH_SHORTAGE, review_status == RS_SHORTAGE_REVIEW),
|
||
literal("exception"),
|
||
),
|
||
(
|
||
db.or_(
|
||
reason == PH_UPLOAD_RPA_FAILED,
|
||
exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status == "failed")),
|
||
),
|
||
literal("exception"),
|
||
),
|
||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("manual_upload")),
|
||
(reason == PH_RPA_PENDING, literal("exception")),
|
||
(reason == PH_UPLOAD_RPA_PENDING, literal("exception")),
|
||
# Excel 后待人工上传登记。
|
||
(upload_pending, literal("manual_upload")),
|
||
else_=literal("exception"),
|
||
)
|
||
|
||
def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]:
|
||
"""待办排序键:updated_at 降序 + 稳定引用(测试/调试辅助)。"""
|
||
if hasattr(value, "isoformat"):
|
||
stamp = value.isoformat()
|
||
else:
|
||
stamp = str(value or "")
|
||
return (stamp, str(ref or ""))
|
||
|
||
|
||
def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, customer_like: str):
|
||
"""对开放 Review Case 查询追加客户关键字过滤。"""
|
||
if not customer_needle:
|
||
return cases_q
|
||
matching_document_ids = db.session.query(ShippingOrderDocument.id).filter(
|
||
ShippingOrderDocument.filename.ilike(customer_like),
|
||
)
|
||
matching_candidate_ids = db.session.query(ShippingOrderCandidate.id).filter(
|
||
ShippingOrderCandidate.po_number.ilike(customer_like),
|
||
)
|
||
return cases_q.filter(
|
||
db.or_(
|
||
ShippingOrderReviewCase.case_no.ilike(customer_like),
|
||
ShippingOrderReviewCase.document_id.in_(matching_document_ids),
|
||
ShippingOrderReviewCase.candidate_id.in_(matching_candidate_ids),
|
||
)
|
||
)
|
||
|
||
|
||
def _verified_upload_success_sql_expr():
|
||
"""以当前 Excel Artifact 已上传这一唯一事实判定 Notice 已完成。"""
|
||
artifact = aliased(ShippingExportArtifact)
|
||
current_artifact_id = (
|
||
select(artifact.id)
|
||
.where(
|
||
artifact.task_id == ShippingNotice.id,
|
||
artifact.status.in_(("ready", "uploading", "uploaded")),
|
||
)
|
||
.order_by(artifact.created_at.desc(), artifact.id.desc())
|
||
.limit(1)
|
||
.correlate(ShippingNotice)
|
||
.scalar_subquery()
|
||
)
|
||
return exists(
|
||
select(1)
|
||
.select_from(ShippingExportArtifact)
|
||
.where(
|
||
ShippingExportArtifact.id == current_artifact_id,
|
||
ShippingExportArtifact.status == "uploaded",
|
||
)
|
||
)
|
||
|
||
|
||
def _todo_tasks_base_query(
|
||
user_id: int,
|
||
*,
|
||
is_admin: bool,
|
||
allowed: frozenset[str],
|
||
normalized_bucket: str,
|
||
customer_needle: str,
|
||
customer_like: str,
|
||
task_no: str | None,
|
||
terminal_kind: str | None = None,
|
||
):
|
||
"""
|
||
构造带精确 category CASE 过滤的 Task 待办查询。
|
||
|
||
核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed);
|
||
done 桶另加终态粗筛;terminal_kind 进一步拆分 done 子视图(通知完成 / 驳回作废)。
|
||
pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
|
||
"""
|
||
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||
upload_success = _verified_upload_success_sql_expr()
|
||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True)))
|
||
if task_no:
|
||
q = q.filter(ShippingNotice.task_no == str(task_no).strip())
|
||
if customer_needle:
|
||
q = q.filter(
|
||
db.or_(
|
||
exists(
|
||
select(1).select_from(ShippingCustomerShadowResolution)
|
||
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
|
||
.join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id)
|
||
.where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
ShippingCustomerShadowResolution.status == 'confirmed',
|
||
db.or_(
|
||
ShippingCustomer.standard_name.ilike(customer_like),
|
||
ShippingCustomer.short_code.ilike(customer_like),
|
||
),
|
||
)
|
||
),
|
||
exists(
|
||
select(1).select_from(ShippingOrderDocument)
|
||
# Candidate 使用 primary_document_id 关联来源文档;不能读取已移除的 document_id 投影。
|
||
.join(ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id)
|
||
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingOrderCandidate.id)
|
||
.where(ShippingOrderTask.id == ShippingNotice.order_task_id, ShippingOrderDocument.filename.ilike(customer_like))
|
||
),
|
||
)
|
||
)
|
||
|
||
# [STEP] 精确分类由 CASE 下推。pending 含无 Gate fail-closed,禁止再用
|
||
# 「有原因/有产物/有 Execution」粗筛把裸 Notice 漏掉,否则 list 与 count 分叉。
|
||
if normalized_bucket == "done":
|
||
# Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。
|
||
q = q.filter(
|
||
db.or_(
|
||
upload_success,
|
||
workflow_review_status == RS_REJECTED,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
db.and_(
|
||
match_exists,
|
||
artifact_exists,
|
||
),
|
||
)
|
||
)
|
||
# [STEP] 终态子视图过滤:前端「通知完成 / 复核驳回·已作废」子 tab 各取所需;
|
||
# 口径与分类 CASE 的 done 分支保持一致(上传成功优先,二者互斥)。
|
||
if terminal_kind == "upload_complete":
|
||
q = q.filter(upload_success)
|
||
elif terminal_kind == "reject_void":
|
||
q = q.filter(
|
||
db.or_(
|
||
workflow_review_status == RS_REJECTED,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
)
|
||
)
|
||
return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed))))
|
||
|
||
|
||
def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
|
||
"""徽标统计用的活跃 Task 范围;分类 CASE 负责排除 done。"""
|
||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
|
||
|
||
def _classify_todo_lifecycle_stage(
|
||
category: str,
|
||
*,
|
||
pending_human_reason: Any = None,
|
||
processing_stage: Any = None,
|
||
) -> str | None:
|
||
"""
|
||
按统一生命周期口径归类待办条目的阶段 tab(仅供计数,不替代 ui_state)。
|
||
|
||
核心逻辑:与 ``project_lifecycle`` 同优先级——processing_stage 权威 → 人工原因
|
||
归属 Gate 兜底 → todo_category 粗兜底;结果若不是四个可动作阶段(如 completed
|
||
映射出的 upload_complete)则返回 None,由调用方跳过,避免污染阶段 tab 计数。
|
||
|
||
Args:
|
||
category: 待办分类 CASE 结果(review/exception/manual_upload/in_progress)。
|
||
pending_human_reason: OT ``pending_human_reason`` 人工原因码(可空)。
|
||
processing_stage: OT ``stage`` 已持久化处理阶段(可空)。
|
||
|
||
Returns:
|
||
四个可动作阶段码之一;不可归入时 None。
|
||
"""
|
||
stage_key = str(processing_stage or '').strip().lower()
|
||
if stage_key in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||
stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[stage_key]
|
||
else:
|
||
gate = PROCESS_GATE_REASON_OWNING_GATE.get(str(pending_human_reason or '').strip())
|
||
if gate in LIFECYCLE_STAGE_BY_GATE:
|
||
stage = LIFECYCLE_STAGE_BY_GATE[gate]
|
||
else:
|
||
stage = _TODO_STAGE_BY_CATEGORY_FALLBACK.get(str(category or ''), 'fulfillment_prep')
|
||
return stage if stage in _ACTIONABLE_TODO_STAGES else None
|
||
|
||
|
||
def _my_todo_stage_counts(user_id: int, *, is_admin: bool) -> dict[str, int]:
|
||
"""
|
||
统计待处理桶在四个可动作阶段的分布,供前端阶段筛选 tab 展示全量计数。
|
||
|
||
核心逻辑:Review Case 走统一生命周期投影(候选有效性裁决 接收解析 vs 订单复核);
|
||
孤儿 Intake 恒为接收解析;Notice / OT 分支一次取回「分类 CASE + OT stage +
|
||
人工原因」后在 Python 侧归类,避免为计数复制一份 SQL 阶段状态机。
|
||
|
||
Returns:
|
||
{intake_parse, order_review, fulfillment_prep, freight_upload}(含 0 值键)。
|
||
"""
|
||
counts: dict[str, int] = {code: 0 for code in _ACTIONABLE_TODO_STAGES}
|
||
|
||
def _bump(stage: str | None) -> None:
|
||
if stage in counts:
|
||
counts[str(stage)] += 1
|
||
|
||
# [STEP 1] 开放 Review Case:复用统一投影,禁止另写候选有效性判断。
|
||
for case_row in _visible_open_review_cases_query(user_id, is_admin=is_admin).all():
|
||
projection = _review_case_lifecycle_projection(case_row)
|
||
_bump(str(projection.get('lifecycle_stage') or '').strip() or None)
|
||
|
||
# [STEP 2] 孤儿 Intake(未建 OT 的解析待办)恒为接收解析。
|
||
counts["intake_parse"] += int(
|
||
_visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
|
||
)
|
||
|
||
# [STEP 3] Notice 分支:分类 CASE 直接作为列取回,连同 OT stage / 人工原因归类。
|
||
category_expr = _task_todo_category_sql_expr()
|
||
ot_stage_subquery = select(ShippingOrderTask.stage).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery()
|
||
ot_reason_subquery = select(ShippingOrderTask.pending_human_reason).where(
|
||
ShippingOrderTask.id == ShippingNotice.order_task_id,
|
||
).scalar_subquery()
|
||
notice_rows = (
|
||
_active_todo_tasks_scope(user_id, is_admin=is_admin)
|
||
.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
|
||
.with_entities(
|
||
category_expr.label("category"),
|
||
ot_stage_subquery.label("ot_stage"),
|
||
ot_reason_subquery.label("ot_reason"),
|
||
)
|
||
.all()
|
||
)
|
||
for category, ot_stage, ot_reason in notice_rows:
|
||
_bump(_classify_todo_lifecycle_stage(
|
||
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
|
||
))
|
||
|
||
# [STEP 4] OT 分支(库存准备尚未建正式 Notice)同理。
|
||
ot_category_expr = _order_task_todo_category_sql_expr()
|
||
ot_rows = (
|
||
_visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
.filter(ot_category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))))
|
||
.with_entities(
|
||
ot_category_expr.label("category"),
|
||
ShippingOrderTask.stage.label("ot_stage"),
|
||
ShippingOrderTask.pending_human_reason.label("ot_reason"),
|
||
)
|
||
.all()
|
||
)
|
||
for category, ot_stage, ot_reason in ot_rows:
|
||
_bump(_classify_todo_lifecycle_stage(
|
||
category, pending_human_reason=ot_reason, processing_stage=ot_stage,
|
||
))
|
||
return counts
|
||
|
||
|
||
def list_my_todos(
|
||
user_id: int,
|
||
*,
|
||
bucket: str = "pending",
|
||
page: int = 1,
|
||
page_size: int = 20,
|
||
is_admin: bool = False,
|
||
todo_category: str | None = None,
|
||
customer: str | None = None,
|
||
task_no: str | None = None,
|
||
terminal_kind: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
分页列出「我的待办」:建单前 Review Case + 未建 OT Intake + 建单后 Task。
|
||
|
||
核心逻辑:pending 桶合并开放 Review Case、孤儿 Intake(intake_parse)与 Task;
|
||
Task 分类下推为与状态机同序的 SQL CASE;多端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT,
|
||
仅水合当前页 id(禁止 limit(500) 截断冒充总数)。
|
||
|
||
Args:
|
||
user_id: 当前用户。
|
||
bucket: pending(review|exception|manual_upload|intake_parse)| processing | done。
|
||
page / page_size: 分页参数。
|
||
is_admin: 管理员全局只读视图。
|
||
todo_category: 可选细分类覆盖 bucket。
|
||
customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。
|
||
task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。
|
||
terminal_kind: done 桶终态子视图过滤(upload_complete | reject_void);其余 bucket 忽略。
|
||
|
||
Returns:
|
||
{items, page, page_size, total}
|
||
"""
|
||
normalized_page = max(1, int(page))
|
||
normalized_page_size = max(1, min(int(page_size), 100))
|
||
normalized_bucket = str(bucket or "pending").strip().lower()
|
||
allowed = _TODO_BUCKET_CATEGORIES.get(normalized_bucket, _PENDING_TODO_CATEGORIES)
|
||
if todo_category:
|
||
cat = str(todo_category).strip().lower()
|
||
allowed = frozenset({cat}) if cat in {
|
||
"review", "exception", "manual_upload", "intake_parse", "in_progress", "done",
|
||
} else allowed
|
||
|
||
customer_needle = str(customer or "").strip()
|
||
customer_like = f"%{customer_needle}%" if customer_needle else ""
|
||
include_review_cases = "review" in allowed and not task_no
|
||
include_orphan_intakes = "intake_parse" in allowed and not task_no
|
||
normalized_terminal_kind = str(terminal_kind or "").strip().lower() or None
|
||
|
||
# [STEP 1] 多端投影为统一列:kind / entity_id / sort_at / sort_ref。
|
||
branches = []
|
||
if include_review_cases:
|
||
cases_q = _apply_review_case_customer_filter(
|
||
_visible_open_review_cases_query(user_id, is_admin=is_admin),
|
||
customer_needle=customer_needle,
|
||
customer_like=customer_like,
|
||
)
|
||
branches.append(
|
||
cases_q.with_entities(
|
||
literal("review_case").label("kind"),
|
||
ShippingOrderReviewCase.id.label("entity_id"),
|
||
ShippingOrderReviewCase.updated_at.label("sort_at"),
|
||
ShippingOrderReviewCase.case_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
if include_orphan_intakes:
|
||
intakes_q = _apply_orphan_intake_customer_filter(
|
||
_visible_orphan_intakes_query(user_id, is_admin=is_admin),
|
||
customer_needle=customer_needle,
|
||
customer_like=customer_like,
|
||
)
|
||
branches.append(
|
||
intakes_q.with_entities(
|
||
literal("order_intake").label("kind"),
|
||
ShippingOrderIntake.id.label("entity_id"),
|
||
func.coalesce(
|
||
ShippingOrderIntake.updated_at, ShippingOrderIntake.created_at,
|
||
).label("sort_at"),
|
||
ShippingOrderIntake.intake_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
# Task 分支:exclusive intake_parse 细筛时跳过,避免无 category 子句扫出全量 Task。
|
||
task_allowed = frozenset(cat for cat in allowed if cat != "intake_parse")
|
||
if task_allowed:
|
||
tasks_q = _todo_tasks_base_query(
|
||
user_id,
|
||
is_admin=is_admin,
|
||
allowed=task_allowed,
|
||
normalized_bucket=normalized_bucket,
|
||
customer_needle=customer_needle,
|
||
customer_like=customer_like,
|
||
task_no=task_no,
|
||
terminal_kind=normalized_terminal_kind,
|
||
)
|
||
branches.append(
|
||
tasks_q.with_entities(
|
||
literal("task").label("kind"),
|
||
ShippingNotice.id.label("entity_id"),
|
||
func.coalesce(ShippingNotice.updated_at, ShippingNotice.created_at).label("sort_at"),
|
||
ShippingNotice.task_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
# 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败/复核任务会从任务中心消失。
|
||
ot_allowed = frozenset(
|
||
cat for cat in task_allowed
|
||
if cat in {"exception", "in_progress", "review", "manual_upload"}
|
||
)
|
||
if ot_allowed:
|
||
ot_q = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
if task_no:
|
||
ot_q = ot_q.filter(ShippingOrderTask.task_no == str(task_no).strip())
|
||
if customer_needle:
|
||
ot_q = ot_q.filter(
|
||
exists(
|
||
select(1).select_from(ShippingCustomerShadowResolution)
|
||
.join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id)
|
||
.where(
|
||
ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id,
|
||
ShippingCustomerShadowResolution.status == 'confirmed',
|
||
db.or_(
|
||
ShippingCustomer.standard_name.ilike(customer_like),
|
||
ShippingCustomer.short_code.ilike(customer_like),
|
||
),
|
||
)
|
||
)
|
||
)
|
||
ot_q = ot_q.filter(_order_task_todo_category_sql_expr().in_(tuple(sorted(ot_allowed))))
|
||
branches.append(
|
||
ot_q.with_entities(
|
||
literal("order_task").label("kind"),
|
||
ShippingOrderTask.id.label("entity_id"),
|
||
func.coalesce(ShippingOrderTask.updated_at, ShippingOrderTask.created_at).label("sort_at"),
|
||
ShippingOrderTask.task_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
if not branches:
|
||
return {
|
||
"items": [],
|
||
"page": normalized_page,
|
||
"page_size": normalized_page_size,
|
||
"total": 0,
|
||
}
|
||
|
||
# [STEP 2] UNION ALL → COUNT 真总数 → OFFSET/LIMIT 仅取当前页引用。
|
||
if len(branches) == 1:
|
||
union_stmt = branches[0].order_by(None).statement
|
||
else:
|
||
union_stmt = union_all(*[branch.order_by(None).statement for branch in branches])
|
||
combined = union_stmt.subquery("todo_union")
|
||
total = int(
|
||
db.session.execute(select(func.count()).select_from(combined)).scalar_one() or 0
|
||
)
|
||
offset = (normalized_page - 1) * normalized_page_size
|
||
page_refs = (
|
||
db.session.execute(
|
||
select(combined.c.kind, combined.c.entity_id)
|
||
.order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id))
|
||
.offset(offset)
|
||
.limit(normalized_page_size)
|
||
).all()
|
||
if total and offset < total
|
||
else []
|
||
)
|
||
|
||
# [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。
|
||
page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"]
|
||
page_intake_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_intake"]
|
||
page_notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"]
|
||
page_order_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_task"]
|
||
cases_by_id: dict[int, ShippingOrderReviewCase] = {}
|
||
if page_case_ids:
|
||
for case in ShippingOrderReviewCase.query.filter(
|
||
ShippingOrderReviewCase.id.in_(page_case_ids),
|
||
).all():
|
||
cases_by_id[int(case.id)] = case
|
||
intakes_by_id: dict[int, ShippingOrderIntake] = {}
|
||
if page_intake_ids:
|
||
for intake in ShippingOrderIntake.query.filter(
|
||
ShippingOrderIntake.id.in_(page_intake_ids),
|
||
).all():
|
||
intakes_by_id[int(intake.id)] = intake
|
||
notices_by_id: dict[int, ShippingNotice] = {}
|
||
if page_notice_ids:
|
||
for notice in ShippingNotice.query.filter(ShippingNotice.id.in_(page_notice_ids)).all():
|
||
notices_by_id[int(notice.id)] = notice
|
||
order_tasks_by_id: dict[int, ShippingOrderTask] = {}
|
||
if page_order_task_ids:
|
||
for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(page_order_task_ids)).all():
|
||
order_tasks_by_id[int(task.id)] = task
|
||
|
||
page_rows: list[dict[str, Any]] = []
|
||
for kind, entity_id in page_refs:
|
||
entity_id_int = int(entity_id)
|
||
if kind == "review_case":
|
||
case = cases_by_id.get(entity_id_int)
|
||
if case is None:
|
||
continue
|
||
page_rows.append(
|
||
serialize_review_case_todo(
|
||
case, viewer_user_id=user_id, is_admin=is_admin,
|
||
)
|
||
)
|
||
continue
|
||
if kind == "order_intake":
|
||
intake = intakes_by_id.get(entity_id_int)
|
||
if intake is None:
|
||
continue
|
||
page_rows.append(
|
||
serialize_intake_todo(
|
||
intake, viewer_user_id=user_id, is_admin=is_admin,
|
||
)
|
||
)
|
||
continue
|
||
notice = notices_by_id.get(entity_id_int)
|
||
if kind == "order_task":
|
||
order_task = order_tasks_by_id.get(entity_id_int)
|
||
if order_task is not None:
|
||
page_rows.append(serialize_task_summary(order_task, viewer_user_id=user_id, is_admin=is_admin))
|
||
elif notice is not None:
|
||
page_rows.append(serialize_task_summary(notice, viewer_user_id=user_id, is_admin=is_admin))
|
||
|
||
return {
|
||
"items": page_rows,
|
||
"page": normalized_page,
|
||
"page_size": normalized_page_size,
|
||
"total": total,
|
||
}
|
||
|
||
|
||
def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]:
|
||
"""
|
||
统计「我的待办」各 bucket 数量,供导航徽标与阶段筛选 tab 使用。
|
||
|
||
核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT;
|
||
阶段 tab 计数与 done 终态拆分见 _my_todo_stage_counts / done_counts 组装。
|
||
|
||
Returns:
|
||
{pending, processing, done, total_pending_badge,
|
||
stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload},
|
||
done_counts: {upload_complete, reject_void}}
|
||
"""
|
||
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
|
||
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
|
||
upload_success = _verified_upload_success_sql_expr()
|
||
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True)))
|
||
pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count()
|
||
pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count()
|
||
category_expr = _task_todo_category_sql_expr()
|
||
active = _active_todo_tasks_scope(user_id, is_admin=is_admin)
|
||
task_pending_cats = tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"}))
|
||
pending += active.filter(category_expr.in_(task_pending_cats)).count()
|
||
ot_active = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
ot_category = _order_task_todo_category_sql_expr()
|
||
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count()
|
||
processing = active.filter(category_expr == "in_progress").count()
|
||
processing += ot_active.filter(ot_category == "in_progress").count()
|
||
done_base = (
|
||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
.filter(
|
||
db.or_(
|
||
upload_success,
|
||
workflow_review_status == RS_REJECTED,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
db.and_(
|
||
match_exists,
|
||
artifact_exists,
|
||
),
|
||
)
|
||
)
|
||
.filter(category_expr == "done")
|
||
)
|
||
done = done_base.count()
|
||
# done 拆分:已核验上传成功 vs 复核驳回/作废归档;分类 CASE 中上传成功优先,
|
||
# 故二者互斥,reject_void 用差值即无重叠计数。
|
||
done_upload = done_base.filter(upload_success).count()
|
||
return {
|
||
"pending": pending,
|
||
"processing": processing,
|
||
"done": done,
|
||
"total_pending_badge": pending,
|
||
"stage_counts": _my_todo_stage_counts(user_id, is_admin=is_admin),
|
||
"done_counts": {
|
||
"upload_complete": done_upload,
|
||
"reject_void": max(0, done - done_upload),
|
||
},
|
||
}
|