refactor(shipping-notice): 收紧通知单与导出上传事实边界
This commit is contained in:
1 parent
b5d894a923
commit
8ec028e6a3
12 files changed
+312
-318
No files matched your search
@@ -3,7 +3,7 @@ services/shipping_notice/batch_create_idempotency.py
|
||||
|
||||
用途:发货通知跨请求文件内容重复校验。
|
||||
依赖:models.ShippingNotice。
|
||||
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
|
||||
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingUploadAttempt.idempotency_key(货代上传幂等)语义分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -83,10 +83,17 @@ def assert_no_exact_duplicate_notices(
|
||||
return
|
||||
|
||||
for content_hash, _filename in hashes:
|
||||
query = ShippingNotice.query.filter(
|
||||
ShippingNotice.user_id == user_id,
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
from app.models import ShippingOrderTask, ShippingOrderIntake, FileAsset
|
||||
query = (
|
||||
ShippingNotice.query
|
||||
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
|
||||
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
|
||||
.filter(
|
||||
ShippingOrderTask.user_id == user_id,
|
||||
FileAsset.content_hash == content_hash,
|
||||
ShippingOrderTask.lifecycle_status == 'active',
|
||||
)
|
||||
)
|
||||
if skipped_ids:
|
||||
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
|
||||
@@ -14,7 +14,9 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -55,22 +57,25 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
|
||||
if has_verified_upload_success(task):
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if (
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
not has_ready_inventory_file_for_task(task)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
if task_blocking_reason(task):
|
||||
return False
|
||||
if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}:
|
||||
latest_attempt = latest_upload_attempt(task) if hasattr(task, 'id') else None
|
||||
if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {"pending", "running", "failed", "unknown", "timed_out"}:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -95,6 +100,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
return {"status": "skipped", "message": "task already running"}
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
if not task:
|
||||
return {"status": "missing", "message": "task not found"}
|
||||
@@ -102,30 +109,38 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": (
|
||||
f"skip stage={getattr(task, 'current_step', '') or ''}"
|
||||
f" pending_human_reason={task.pending_human_reason or ''}"
|
||||
f" review_status={task.review_status or ''}"
|
||||
f"skip stage={getattr(task, 'stage', '') or ''}"
|
||||
f" pending_human_reason={task_blocking_reason(task) or ''}"
|
||||
f" review_status={getattr(task, 'review_status', '') or ''}"
|
||||
),
|
||||
}
|
||||
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_started",
|
||||
{"current_step": task.current_step, "lifecycle_status": task.lifecycle_status},
|
||||
{"stage": task.stage, "lifecycle_status": task.lifecycle_status},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
pending_reason = str(task.pending_human_reason or "").strip().lower()
|
||||
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
|
||||
if (
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
not has_ready_inventory_file_for_task(task)
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
):
|
||||
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
|
||||
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
# [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
|
||||
# rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
|
||||
|
||||
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
|
||||
recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator')
|
||||
if recheck is not None:
|
||||
result = recheck
|
||||
else:
|
||||
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
|
||||
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
@@ -134,7 +149,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif (
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
not has_ready_inventory_file_for_task(task)
|
||||
and pending_reason == ""
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
@@ -166,7 +181,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
task.current_step,
|
||||
task.stage,
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
|
||||
@@ -178,7 +193,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
{
|
||||
"result_status": str(result.get("status") or ""),
|
||||
"lifecycle_status": refreshed.lifecycle_status,
|
||||
"current_step": refreshed.current_step,
|
||||
"stage": refreshed.stage,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -190,7 +205,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
db.session.rollback()
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
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
|
||||
if hasattr(owner, 'error_message'):
|
||||
owner.error_message = str(exc)
|
||||
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
|
||||
db.session.commit()
|
||||
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
|
||||
|
||||
@@ -15,7 +15,7 @@ from sqlalchemy import update
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice
|
||||
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
|
||||
|
||||
BUSINESS_TYPE = "shipping_notice"
|
||||
@@ -121,13 +121,19 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
|
||||
return int(value)
|
||||
|
||||
|
||||
def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str:
|
||||
def assign_notice_business_number(
|
||||
notice: ShippingNotice,
|
||||
*,
|
||||
moment: datetime | None = None,
|
||||
customer_id_override: int | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
|
||||
|
||||
Args:
|
||||
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
|
||||
moment: 可选时刻,测试时用于固定上海业务日期。
|
||||
customer_id_override: 纠错替代单使用的新客户;仅用于编号,不修改原 OT 的历史匹配事实。
|
||||
|
||||
Returns:
|
||||
分配或已存在的 business_no。
|
||||
@@ -137,12 +143,18 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
|
||||
"""
|
||||
if notice.business_no:
|
||||
return str(notice.business_no)
|
||||
if notice.customer_id is None:
|
||||
owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None
|
||||
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
|
||||
resolution = customer_resolution_facts(owner) if owner is not None else {'customer_id': None}
|
||||
customer_id = int(customer_id_override) if customer_id_override is not None else (
|
||||
int(resolution['customer_id']) if resolution['customer_id'] is not None else None
|
||||
)
|
||||
if customer_id is None:
|
||||
raise ConflictError(
|
||||
'Shipping notice customer must be confirmed before numbering',
|
||||
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED',
|
||||
)
|
||||
customer = db.session.get(ShippingCustomer, int(notice.customer_id))
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None or customer.status != 'active':
|
||||
raise ConflictError(
|
||||
'Active customer is required before numbering',
|
||||
@@ -160,7 +172,5 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
|
||||
notice.business_date = business_date
|
||||
notice.business_sequence_value = sequence_value
|
||||
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION
|
||||
notice.customer_name_snapshot = customer.standard_name
|
||||
notice.customer_short_code_snapshot = short_code
|
||||
db.session.flush()
|
||||
return str(notice.business_no)
|
||||
@@ -37,7 +37,8 @@ def _select_tasks(
|
||||
tasks = []
|
||||
for task_no in normalized_tasks:
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None or (
|
||||
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
|
||||
if not isinstance(task, ShippingNotice) or (
|
||||
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
|
||||
):
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
@@ -61,7 +62,6 @@ def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExpo
|
||||
artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
|
||||
ShippingExportArtifact.file_path == task.export_file_path,
|
||||
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
|
||||
if artifact is not None:
|
||||
result[int(task.id)] = [artifact]
|
||||
|
||||
@@ -16,8 +16,9 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
|
||||
|
||||
def complete_freight_cancellation(
|
||||
@@ -59,11 +60,16 @@ def complete_freight_cancellation(
|
||||
old.voided_at = datetime.utcnow()
|
||||
old.voided_by_id = int(actor_id)
|
||||
old.void_reason = 'freight_cancellation_completed'
|
||||
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required':
|
||||
new.lifecycle_status = 'active'
|
||||
new.pending_human_reason = None
|
||||
# Notice 不再承载旧工作流阻断字段;解除修订阻断时更新其 OT 生命周期,
|
||||
# 由 OT 的 Gate/状态投影重新计算当前工作面。
|
||||
new_owner = (
|
||||
db.session.get(ShippingOrderTask, int(new.order_task_id))
|
||||
if new.order_task_id is not None else None
|
||||
)
|
||||
if new_owner is not None and new_owner.status == 'blocked':
|
||||
new_owner.status = 'processing'
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=old.id,
|
||||
task_id=task_event_task_id(old),
|
||||
event_type='freight_cancellation_completed',
|
||||
actor_id=actor_id,
|
||||
detail_json={
|
||||
@@ -74,7 +80,7 @@ def complete_freight_cancellation(
|
||||
},
|
||||
))
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=new.id,
|
||||
task_id=task_event_task_id(new),
|
||||
event_type='supersession_unblocked',
|
||||
actor_id=actor_id,
|
||||
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
|
||||
@@ -109,12 +115,19 @@ def complete_freight_cancellation(
|
||||
|
||||
def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""构造取消处置前后快照(白名单字段)。"""
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
artifact = latest_export_artifact(task)
|
||||
owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
if task.order_task_id is not None else None
|
||||
)
|
||||
return {
|
||||
'task_no': str(task.task_no),
|
||||
'lifecycle_status': str(task.lifecycle_status or ''),
|
||||
'export_file_name': task.export_file_name,
|
||||
'export_file_name': getattr(artifact, 'file_name', None),
|
||||
'void_reason': task.void_reason,
|
||||
'pending_human_reason': task.pending_human_reason,
|
||||
'owner_lifecycle_status': getattr(owner, 'lifecycle_status', None),
|
||||
'owner_void_reason': getattr(owner, 'void_reason', None),
|
||||
}
|
||||
|
||||
|
||||
@@ -150,11 +163,10 @@ def mark_cancelled_task_readonly(
|
||||
if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}:
|
||||
task.lifecycle_status = 'pending_void'
|
||||
task.void_reason = reason_text
|
||||
task.pending_human_reason = 'pending_void'
|
||||
# co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。
|
||||
after = _task_cancel_snapshot(task)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=int(task.id),
|
||||
task_id=task_event_task_id(task),
|
||||
event_type='task_pending_void',
|
||||
actor_id=int(actor_id),
|
||||
detail_json={
|
||||
|
||||
@@ -3,8 +3,10 @@ services/shipping_notice/lifecycle_projection.py
|
||||
|
||||
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
|
||||
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
|
||||
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
|
||||
兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作;
|
||||
阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -36,6 +38,9 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
|
||||
'duplicate_detection': 'order_review',
|
||||
'field_conflict_resolution': 'order_review',
|
||||
'order_freeze_readiness': 'order_review',
|
||||
# 建单前已存在当前有效 Candidate 的未确认 Review Case 仍属「订单复核」工作面:
|
||||
# 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。
|
||||
'order_review_build': 'order_review',
|
||||
'task_creation': 'order_review',
|
||||
'inventory_source_routing': 'fulfillment_prep',
|
||||
'inventory_preparation': 'fulfillment_prep',
|
||||
@@ -49,8 +54,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
|
||||
}
|
||||
|
||||
# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于
|
||||
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在
|
||||
# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。
|
||||
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。[B''] 它是阶段的唯一
|
||||
# 权威;正式 Gate 仅在技术阶段缺失时提供兜底,不能覆盖有效处理阶段。
|
||||
LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'upload_received': 'intake_parse',
|
||||
'email_parsing': 'intake_parse',
|
||||
@@ -60,7 +65,7 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'waiting_review': 'order_review',
|
||||
'customer_resolving': 'order_review',
|
||||
'duplicate_checking': 'order_review',
|
||||
'inventory_source_resolving': 'order_review',
|
||||
'inventory_source_resolving': 'fulfillment_prep',
|
||||
'order_creating': 'fulfillment_prep',
|
||||
'inventory_fetching': 'fulfillment_prep',
|
||||
'inventory_preparation': 'fulfillment_prep',
|
||||
@@ -114,11 +119,12 @@ def project_lifecycle(
|
||||
verified_upload_success: bool = False,
|
||||
processing_stage: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。
|
||||
"""按成功事实 → 已持久化阶段 → 正式 Gate → 阻断归属的固定优先级裁决生命周期。
|
||||
|
||||
``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能
|
||||
授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算
|
||||
阶段或放开按钮。
|
||||
[B''] 阶段唯一权威:只要 ``processing_stage``(OT.stage / Run.processing_stage)是合法
|
||||
15 阶成员,就直接映射五阶段,正式 Gate 不能覆盖或升降它。``gate_code`` 只在处理
|
||||
阶段缺失时兜底(如任务详情无 OT.stage 上下文),且仅用于「订单检查」面板诊断;
|
||||
它不再能改变阶段。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
|
||||
"""
|
||||
gate = current_gate if isinstance(current_gate, dict) else {}
|
||||
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
|
||||
@@ -127,14 +133,16 @@ def project_lifecycle(
|
||||
if verified_upload_success:
|
||||
lifecycle_stage = 'upload_complete'
|
||||
authority = 'verified_upload_success'
|
||||
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
authority = 'process_gate'
|
||||
# [B''] 处理阶段是阶段唯一权威。合法 15 阶直接映射五阶段;Gate 不再覆盖它。
|
||||
elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[
|
||||
str(processing_stage or '').strip().lower()
|
||||
]
|
||||
authority = 'processing_stage'
|
||||
# [B''] 正式 Gate 仅在处理阶段缺失时兜底,用于「订单检查」面板,不改变阶段。
|
||||
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
authority = 'process_gate'
|
||||
else:
|
||||
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
|
||||
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/upload_attempt_service.py
|
||||
|
||||
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。
|
||||
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。
|
||||
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。
|
||||
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,任务工作面通过 Attempt 查询结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,8 +23,22 @@ from app.models import (
|
||||
)
|
||||
|
||||
|
||||
def _formal_notice(task: ShippingNotice | Any) -> ShippingNotice | None:
|
||||
"""解析上传事实所属的正式 Notice;OT 在 Notice 生成前不产生上传事实。"""
|
||||
if isinstance(task, ShippingNotice):
|
||||
return task if getattr(task, 'id', None) is not None else None
|
||||
order_task_id = getattr(task, 'id', None)
|
||||
if order_task_id is None:
|
||||
return None
|
||||
return ShippingNotice.query.filter_by(order_task_id=int(order_task_id)).order_by(
|
||||
ShippingNotice.id.desc(),
|
||||
).first()
|
||||
|
||||
|
||||
def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact:
|
||||
"""返回本次上传目标 Artifact;调用方不能借 Task 旧文件指针绕过分轮履约。"""
|
||||
if not isinstance(task, ShippingNotice) or getattr(task, 'id', None) is None:
|
||||
raise ValidationError('Formal shipping notice is required before upload', code='SHIPPING.NOTICE_REQUIRED')
|
||||
query = ShippingExportArtifact.query.filter_by(task_id=task.id)
|
||||
if artifact_id is not None:
|
||||
artifact = query.filter_by(id=artifact_id).one_or_none()
|
||||
@@ -68,24 +82,35 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
||||
return attempt
|
||||
|
||||
|
||||
def _aggregate_task_upload_status(task: ShippingNotice) -> None:
|
||||
"""从预约单真相刷新兼容 Task 投影,不能由单个旧回调直接覆盖。"""
|
||||
reservations = ShippingReservation.query.filter_by(task_id=task.id).all()
|
||||
if reservations and all(item.status == 'uploaded' for item in reservations):
|
||||
task.upload_status = 'uploaded'
|
||||
task.upload_finished_at = datetime.utcnow()
|
||||
elif any(item.status == 'uploaded' for item in reservations):
|
||||
task.upload_status = 'partial'
|
||||
else:
|
||||
task.upload_status = 'pending'
|
||||
def latest_export_artifact(task: ShippingNotice) -> ShippingExportArtifact | None:
|
||||
"""返回当前 Notice 最新有效导出 Artifact;不回读 Notice 的旧文件投影。"""
|
||||
notice = _formal_notice(task)
|
||||
if notice is None:
|
||||
return None
|
||||
return ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == notice.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading', 'uploaded'}),
|
||||
).order_by(
|
||||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||||
).first()
|
||||
|
||||
|
||||
def latest_upload_attempt(task: ShippingNotice) -> ShippingUploadAttempt | None:
|
||||
"""返回当前 Notice 最近一次有效 Artifact 的最近上传尝试。"""
|
||||
artifact = latest_export_artifact(task)
|
||||
if artifact is None:
|
||||
return None
|
||||
return ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).order_by(
|
||||
ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc(),
|
||||
).first()
|
||||
|
||||
|
||||
def has_verified_upload_success(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否具备可审计的货代上传成功事实。
|
||||
|
||||
业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、
|
||||
单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次
|
||||
已完成分组与停止轮询共用的唯一成功谓词。
|
||||
当前 Excel Artifact 标为 uploaded 即代表 Notice 业务完成;成功 Attempt 只作为上传
|
||||
审计证据。预约单属于行级履约事实,不参与 Notice 完成判定。该函数是 UI 生命周期、
|
||||
批次已完成分组与停止轮询共用的唯一成功谓词。
|
||||
"""
|
||||
try:
|
||||
from flask import has_app_context
|
||||
@@ -99,18 +124,15 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
|
||||
'voided', 'archived', 'deleted', 'cancelled',
|
||||
}:
|
||||
return False
|
||||
if getattr(task, 'id', None) is None or str(task.upload_status or '').strip().lower() != 'uploaded':
|
||||
# OT 在正式 Notice 创建前没有上传字段;只能由正式 Notice 进入该谓词。
|
||||
if not isinstance(task, ShippingNotice):
|
||||
return False
|
||||
reservations = ShippingReservation.query.filter_by(task_id=task.id).all()
|
||||
if not reservations or any(row.status != 'uploaded' for row in reservations):
|
||||
if getattr(task, 'id', None) is None:
|
||||
return False
|
||||
return db.session.query(ShippingUploadAttempt.id).join(
|
||||
ShippingExportArtifact,
|
||||
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
|
||||
).filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingUploadAttempt.status == 'succeeded',
|
||||
).first() is not None
|
||||
artifact = latest_export_artifact(task)
|
||||
if artifact is None or artifact.status != 'uploaded':
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _normalize_callback_result(result: str | None, success: bool) -> str:
|
||||
@@ -180,11 +202,8 @@ def complete_attempt(
|
||||
ShippingReservation.query.filter(ShippingReservation.id.in_(reservation_ids)).update(
|
||||
{'status': 'uploaded'}, synchronize_session=False,
|
||||
)
|
||||
# 批量更新绕开 ORM identity map;立即失效以确保同一事务的 Task 聚合读取最新预约单状态。
|
||||
# 批量更新绕开 ORM identity map;立即失效以确保同一事务的预约单事实读取最新状态。
|
||||
db.session.expire_all()
|
||||
if task is not None:
|
||||
task.freight_ref_no = attempt.freight_ref_no
|
||||
_aggregate_task_upload_status(task)
|
||||
else:
|
||||
# A missing callback may conceal a completed freight submission. A late
|
||||
# transport error is not enough to safely release or retry that Artifact.
|
||||
@@ -200,11 +219,6 @@ def complete_attempt(
|
||||
error_message
|
||||
or '无法判断上传是否成功/失败:RPA 结果未确认,可能已上传成功但未出现成功提示,或上传配置(result_selector/success_texts)有误;请人工核查或确认已上传'
|
||||
)[:500]
|
||||
# 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status,
|
||||
# 因为迟到的成功回调仍可解除该未知态)。
|
||||
if task is not None:
|
||||
task.upload_error_code = attempt.error_code
|
||||
task.upload_error_message = attempt.error_message
|
||||
db.session.flush()
|
||||
return attempt
|
||||
attempt.status = 'failed'
|
||||
@@ -212,11 +226,6 @@ def complete_attempt(
|
||||
attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED'
|
||||
attempt.error_message = message
|
||||
artifact.status = 'ready'
|
||||
if task is not None:
|
||||
task.upload_status = 'failed'
|
||||
# 逐单状态展示:把失败原因落到 Notice,供「按发货通知单展示状态」读取。
|
||||
task.upload_error_code = attempt.error_code
|
||||
task.upload_error_message = message
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
Reference in new issue
Block a user