feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码

This commit is contained in:
hugo committed 2026-08-23 00:27:18 +08:00
1 parent 935bf26fa6
commit 7cfd5d167e
230 files changed
+9337 -10989

No files matched your search

+12 -144
View File
@@ -1,7 +1,7 @@
"""
services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
@@ -10,7 +10,6 @@ services/shipping_notice/ui_state.py
stp_facts、progress_nodes);
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
"""
from __future__ import annotations
@@ -18,7 +17,6 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingNotice
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.constants import (
CP_COMPLETED,
CP_CUSTOMER_REVIEW,
@@ -53,13 +51,7 @@ from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import (
compute_batch_process_summary,
list_sorted_batch_tasks,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_summary,
)
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
from app.services.shipping_notice.state_machine import (
CheckpointKind,
resolve_task_ui_state,
@@ -75,38 +67,6 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
"step1_notice_submit": 0,
"step2_parse_confirm": 1,
"step3_inventory_prepare": 2,
"step2_inventory_prepare": 2,
"step4_align_confirm": 3,
"step5_match_inventory": 4,
"step3_inventory_match": 4,
"step4_shortage_review": 4,
"step6_generate_file": 5,
"step5_export_excel": 5,
"step7_upload_freight": 6,
"step6_upload_freight": 6,
"step7_finish": 6,
}
_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_CUSTOMER_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
}
_REVIEW_ENTRY_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
@@ -136,41 +96,11 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
}
# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
CP_CUSTOMER_REVIEW: "order_review",
CP_ORDER_FREEZE: "order_review",
CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep",
CP_INVENTORY_PENDING: "fulfillment_prep",
CP_READY_MATCH: "fulfillment_prep",
RS_SHORTAGE_REVIEW: "fulfillment_prep",
CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "freight_upload",
CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "freight_upload",
CP_UPLOAD_RESULT_UNKNOWN: "freight_upload",
CP_UPLOADED: "freight_upload",
CP_COMPLETED: "freight_upload",
CP_REJECTED: "order_review",
}
def _task_lifecycle(
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。"""
"""以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。"""
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
if legacy_stage is None:
legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
if legacy_stage is None:
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
legacy_index = _derive_current_step_index(task)
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index]
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return project_lifecycle(
@@ -180,7 +110,6 @@ def _task_lifecycle(
if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code')
else None
),
legacy_stage=legacy_stage,
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
has_candidate_context=True,
verified_upload_success=has_verified_upload_success(task),
@@ -188,9 +117,11 @@ def _task_lifecycle(
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
"""将共享生命周期结果包装为任务详情既有的阶段 DTO。"""
stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse')
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0)
"""将共享生命周期结果包装为任务详情阶段 DTO;无正式事实时不猜阶段。"""
stage_code = str(lifecycle.get('lifecycle_stage') or '')
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), None)
if index is None:
return {'code': 'unclassified', 'label': '状态待同步', 'index': 0, 'total': len(LIFECYCLE_STAGES)}
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
@@ -251,47 +182,6 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]:
return {"primary": primary, "secondary": secondary}
def _derive_current_step_index(task: ShippingNotice) -> int:
"""
根据任务领域事实推导五阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
legacy_index = _CURRENT_STEP_INDEX_MAP[current_step]
return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}:
return 3
if upload_status in {"pending", "uploading", "failed"} or has_export:
return 2
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
return 2
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 2
if task.inventory_lines_json or match_status:
return 2
if pending_reason in {
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
if review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
return 1
return 0
def build_shipping_workflow_steps(
task: ShippingNotice,
checkpoint: str | None,
@@ -308,34 +198,22 @@ def build_shipping_workflow_steps(
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
None,
)
# 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
# 五阶段只使用共享生命周期裁决;缺少正式事实时全部保持 pending。
current_index = lifecycle_index
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
# ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让
# 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。
if lifecycle_stage == "upload_complete":
status = "completed"
elif current_index is None:
status = "pending"
elif index < current_index:
status = "completed"
elif index == current_index:
status = "current"
else:
status = "pending"
inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
parse_blocked = index == 1 and (
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ}
)
prep_blocked = index == 2 and (
checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW}
or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE}
)
upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -986,7 +864,6 @@ def build_task_ui_state(
}
return {
"task_no": task.task_no,
"batch_no": None,
"stage": stage,
"lifecycle_stage": stage["code"],
"lifecycle_entries": lifecycle['lifecycle_entries'],
@@ -1053,12 +930,3 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
)
def build_batch_ui_state(batch: Any) -> dict[str, Any]:
"""
构建批次级会话上传集合摘要(非履约写操作面)。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del batch
raise_shipping_batches_removed()