chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

+322 -48
View File
@@ -49,9 +49,14 @@ from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
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,
)
@@ -66,8 +71,8 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"},
{"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
@@ -132,36 +137,6 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
}
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
{"code": "intake_parse", "label": "接收解析"},
{"code": "order_review", "label": "订单复核"},
{"code": "fulfillment_prep", "label": "发货准备"},
{"code": "upload_complete", "label": "上传完成"},
)
_STAGE_GATE_CODES: dict[str, str] = {
"document_materialization": "intake_parse",
"layout_parsing": "intake_parse",
"document_profile_routing": "intake_parse",
"order_field_extraction": "intake_parse",
"field_completeness": "order_review",
"reservation_validation": "order_review",
"customer_resolution": "order_review",
"duplicate_detection": "order_review",
"field_conflict_resolution": "order_review",
"order_freeze_readiness": "order_review",
"task_creation": "order_review",
"inventory_source_routing": "fulfillment_prep",
"inventory_preparation": "fulfillment_prep",
"inventory_field_mapping": "fulfillment_prep",
"inventory_matching": "fulfillment_prep",
"inventory_sufficiency": "fulfillment_prep",
"excel_readiness": "fulfillment_prep",
"artifact_generation": "fulfillment_prep",
"freight_upload_rpa": "upload_complete",
"manual_upload_handoff": "upload_complete",
}
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
@@ -184,17 +159,36 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = {
}
def _business_stage(
def _task_lifecycle(
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
gate_code = str(gate.get("gate_code") or "").strip()
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
if not stage_code:
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
"""以共享裁决器投影正式任务生命周期;旧 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 = 'upload_complete' 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', 'upload_complete')[legacy_index]
return project_lifecycle(
current_gate=gate if isinstance(gate, dict) else None,
blocking_reason=(
{'code': process_gate.get('blocking_reason_code')}
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,
)
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)
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
@@ -289,14 +283,24 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
return 0
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
def build_shipping_workflow_steps(
task: ShippingNotice,
checkpoint: str | None,
*,
lifecycle_stage: str | None = None,
) -> list[dict[str, str]]:
"""
构造四阶段流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
current_index = _derive_current_step_index(task)
lifecycle_index = next(
(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()
steps: list[dict[str, str]] = []
@@ -359,7 +363,17 @@ def _action_buttons_for_task(task: ShippingNotice) -> list[dict[str, str]]:
# 保留重试/重匹配/驳回,但把指定源放在首位作为主恢复入口。
rest = [btn for btn in (ui.action_buttons or []) if str(btn.get('id') or '') != 'confirm_inventory_source']
return [confirm_btn, *rest]
return ui.action_buttons
action_buttons = list(ui.action_buttons or [])
# [AUTHORITY] ``export_file_name`` 只是历史字段,不能作为下载授权或文件存在的证据。
# 只有任务当前 Artifact 已由后端解析为可下载文件时,才把 download_excel 下发给
# 任一前端;下载 API 仍会在真正读取文件时再次校验,抵御页面快照过期。
if any(str((button or {}).get('id') or '') == 'download_excel' for button in action_buttons):
if resolve_task_export_download(task) is None:
action_buttons = [
button for button in action_buttons
if str((button or {}).get('id') or '') != 'download_excel'
]
return action_buttons
_PARSE_STAGE_CHECKPOINTS = {
CP_PARSE_REVIEW,
@@ -690,7 +704,235 @@ def _build_task_summary(
return summary
def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
def _build_stage_context(
task: ShippingNotice,
*,
lifecycle_stage: str,
stp_facts: dict[str, Any] | None,
process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
"""
from app.models.shipping_excel_template import ShippingExportArtifact
from app.models.shipping_fulfillment import (
ShippingInventoryVerification,
ShippingUploadAttempt,
)
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.models.shipping_notice_line import ShippingNoticeLine
facts = stp_facts if isinstance(stp_facts, dict) else {}
raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else []
fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else []
fact_by_key = {
str(row.get('line_key') or ''): row
for row in fact_rows
if isinstance(row, dict) and str(row.get('line_key') or '')
}
# 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。
current_match_rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=task.id, is_current=True)
.order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id)
.all()
if getattr(task, 'id', None) is not None else []
)
match_by_key = {
str(row.line_key or ''): row
for row in current_match_rows
if str(row.line_key or '')
}
match_by_index = {
int(row.line_index): row
for row in current_match_rows
if row.line_index is not None
}
verification_rows: dict[str, dict[str, Any]] = {}
latest_verification = (
ShippingInventoryVerification.query
.filter_by(task_id=task.id, status='completed')
.order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc())
.first()
if getattr(task, 'id', None) is not None else None
)
if latest_verification is not None:
# 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。
for position, verification_line in enumerate(latest_verification.lines):
verification_rows[str(position)] = {
'required_qty': verification_line.required_qty,
'available_qty': verification_line.available_qty,
'shortage_qty': (
max(verification_line.required_qty - verification_line.available_qty, 0)
if verification_line.required_qty is not None and verification_line.available_qty is not None
else None
),
'status': verification_line.status,
}
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
frozen_order_lines: list[dict[str, Any]] = []
preparation_lines: list[dict[str, Any]] = []
notice_lines = (
ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all()
if getattr(task, 'id', None) is not None else []
)
for line in notice_lines:
frozen_order_lines.append({
'line_key': getattr(line, 'line_key', None),
'reservation_id': getattr(line, 'reservation_id', None),
'part_number': getattr(line, 'part_number', None),
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
})
# 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON
# 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。
row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows))
for index in range(row_count):
line = notice_lines[index] if index < len(notice_lines) else None
match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index)
structured = ({
'line_key': match_row.line_key,
'reservation_id': match_row.reservation_id,
'part_number': match_row.part_number,
'required_qty': match_row.required_qty,
'available_qty': match_row.matched_qty or match_row.available_qty,
'shortage_qty': match_row.shortage_qty,
'resolved_inventory_source_code': match_row.inventory_source_code,
'disposition': match_row.match_result,
} if match_row is not None else {})
legacy_source = fact_by_key.get(
str(getattr(line, 'line_key', '') or ''),
fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {},
)
# 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。
source = {
**(legacy_source if isinstance(legacy_source, dict) else {}),
**{
key: value
for key, value in structured.items()
if value is not None and value != ''
},
}
verification = verification_rows.get(str(index), {})
result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {}
required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None))))
available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty'))))
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
preparation_lines.append({
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
'required_qty': required_qty,
'available_qty': available_qty,
'shortage_qty': shortage_qty,
'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'),
'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None,
})
has_match_result = bool(current_match_rows or raw_rows or any(
row.get('matched_qty') is not None
or row.get('shortage_qty') is not None
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
for row in fact_rows if isinstance(row, dict)
))
gate = process_gate if isinstance(process_gate, dict) else {}
gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '')
preparation_status = (
'ready' if has_match_result else
'blocked' if gate_code else
'processing'
)
inventory_sources: list[dict[str, Any]] = []
latest_preparation = None
if getattr(task, 'id', None):
from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt
latest_preparation = (
ShippingInventoryPreparationAttempt.query
.filter_by(task_id=task.id)
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
.first()
)
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
downloadable_inventory = resolve_task_inventory_download(task)
for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []):
inventory_sources.append({
'source_code': source_attempt.source_code,
'status': source_attempt.status,
'inventory_file_id': source_attempt.inventory_file_id,
})
artifact = None
attempts = []
if getattr(task, 'id', None):
artifact = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
).first()
attempts = ShippingUploadAttempt.query.join(
ShippingExportArtifact,
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
).filter(
ShippingExportArtifact.task_id == task.id,
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
latest_attempt = attempts[0] if attempts else None
latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
upload_outcome = (
'succeeded' if latest_status == 'succeeded' else
'failed' if latest_status in {'failed', 'timed_out'} else
'unknown' if latest_status == 'unknown' else
'running' if latest_status in {'pending', 'running'} else
'awaiting_manual' if lifecycle_stage == 'upload_complete' else
'not_started'
)
return {
'preparation': {
'status': preparation_status,
'reason_code': gate.get('blocking_reason_code') or None,
'frozen_order': {
'task_no': task.task_no,
'snapshot_id': task.order_snapshot_id,
},
'inventory_source_code': facts.get('inventory_source_code'),
'match_status': facts.get('match_status'),
'frozen_order_lines': frozen_order_lines,
'lines': preparation_lines,
'has_match_result': has_match_result,
# 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。
'inventory_sources': inventory_sources,
'inventory_file': {
'available': downloadable_inventory is not None,
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
},
'artifact': {
'file_name': artifact.file_name if artifact is not None else None,
'status': artifact.status if artifact is not None else 'not_generated',
},
},
'upload': {
'outcome': upload_outcome,
'latest_attempt': ({
'id': latest_attempt.id,
'status': latest_attempt.status,
'mode': latest_attempt.mode,
'freight_ref_no': latest_attempt.freight_ref_no,
'error_code': latest_attempt.error_code,
'finished_at': latest_attempt.finished_at.isoformat() if latest_attempt.finished_at else None,
} if latest_attempt is not None else None),
},
}
def build_task_ui_state(
task: ShippingNotice,
*,
include_stage_context: bool = False,
) -> dict[str, Any]:
"""
构建单票任务 UI State。
@@ -712,8 +954,10 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
button for button in action_buttons
if str((button or {}).get('id') or '') in _non_recovery_action_ids
]
steps = build_shipping_workflow_steps(task, ui.checkpoint)
current_index = _derive_current_step_index(task)
lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
stage = _business_stage(lifecycle)
steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code'])
current_index = int(stage['index']) - 1
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
summary = _build_task_summary(
task,
@@ -732,8 +976,32 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
if process_gate.get('current_blocking_gate'):
summary['allowed_actions'] = []
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
if resolve_task_export_download(task) is not None:
download_action = _unified_action({
'id': 'download_excel',
'label': '下载 Excel',
'kind': 'view',
'enabled': True,
}, default_kind='view')
action_codes = {
str((action or {}).get('code') or '')
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
}
if download_action['code'] not in action_codes:
actions['secondary'].append(download_action)
stage_context = (
_build_stage_context(
task,
lifecycle_stage=stage['code'],
stp_facts=summary.get('stp_facts'),
process_gate=process_gate,
)
if include_stage_context else None
)
checkpoint_payload = {
"code": ui.checkpoint,
"kind": str(ui.checkpoint_kind),
@@ -749,6 +1017,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
"task_no": task.task_no,
"batch_no": None,
"stage": stage,
"lifecycle_stage": stage["code"],
"lifecycle_entries": lifecycle['lifecycle_entries'],
"lifecycle_authority": lifecycle['lifecycle_authority'],
"checkpoint": checkpoint_payload,
"checkpoint_view": checkpoint_payload,
"todo": {
@@ -756,6 +1027,8 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
"message": summary.get("message"),
},
"actions": actions,
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
**({'stage_context': stage_context} if stage_context is not None else {}),
"reason": reason,
"lifecycle_status": task.lifecycle_status,
"checkpoint_code": ui.checkpoint,
@@ -797,6 +1070,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
execution = (
ShippingProcessExecution.query
.filter_by(task_id=task_pk)
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
)