refactor(shipping-notice): 收紧通知单与导出上传事实边界

This commit is contained in:
hugo committed 2026-09-04 20:49:03 +08:00
1 parent b5d894a923
commit 8ec028e6a3
12 files changed
+312 -318

No files matched your search

+12 -137
View File
@@ -5,13 +5,12 @@ backend/app/models/shipping.py
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
ShippingNotice.idempotency_key 为货代上传幂等;
ShippingUploadAttempt.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
Intake/Notice/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Intake/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
OT 的 order_data_version/current_order_extraction_id/order_snapshot_id 仅作为任务流程指针;
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
"""
@@ -53,18 +52,7 @@ class ShippingNotice(Base):
__tablename__ = 'shipping_notices'
__table_args__ = (
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
Index('ix_shipping_notices_business_no', 'business_no'),
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'),
Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'),
Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'),
Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'),
Index('ix_shipping_notices_user_content_fingerprint', 'user_id', 'content_fingerprint'),
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_task_id'),
@@ -72,11 +60,6 @@ class ShippingNotice(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'), index=True, nullable=True,
)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
# 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True)
@@ -85,9 +68,6 @@ class ShippingNotice(Base):
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
source_intake_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_intakes.id'),
@@ -113,10 +93,6 @@ class ShippingNotice(Base):
nullable=True,
index=True,
)
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'),
@@ -128,99 +104,6 @@ class ShippingNotice(Base):
)
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_inventory_candidate_sets.id',
name='fk_shipping_notices_active_inventory_candidate_set_id',
use_alter=True,
),
nullable=True,
)
# P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_process_executions.id',
name='fk_shipping_notices_active_process_execution_id',
use_alter=True,
),
nullable=True,
)
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 动态订单 FieldValue 编辑的乐观锁版本。
order_data_version: Mapped[int] = mapped_column(
Integer,
default=1,
server_default=text('1'),
nullable=False,
)
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_extractions.id',
name='fk_shipping_notices_current_order_extraction_id',
use_alter=True,
),
nullable=True,
index=True,
)
# 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_snapshots.id',
name='fk_shipping_notices_order_snapshot_id',
use_alter=True,
),
nullable=True,
unique=True,
index=True,
)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
export_version: Mapped[int] = mapped_column(Integer, default=1)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 任务处置与业务阶段正交:生命周期负责作废/归档。
lifecycle_status: Mapped[str] = mapped_column(
@@ -241,17 +124,6 @@ class ShippingNotice(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined')
events: Mapped[List['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent',
back_populates='task',
cascade='all, delete-orphan',
)
field_conflicts: Mapped[List['ShippingTaskFieldConflict']] = relationship(
'ShippingTaskFieldConflict',
back_populates='task',
cascade='all, delete-orphan',
)
class ShippingTaskEvent(Base):
@@ -260,7 +132,10 @@ class ShippingTaskEvent(Base):
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_tasks.id', name='fk_shipping_task_events_task_id_order_task'),
index=True,
)
event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
@@ -271,7 +146,7 @@ class ShippingTaskEvent(Base):
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', back_populates='events')
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', back_populates='events')
class ShippingTaskPurgeAudit(Base):
@@ -397,7 +272,7 @@ class ShippingTaskInventoryLink(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
@@ -418,7 +293,7 @@ class ShippingTaskInventoryLink(Base):
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped['ShippingNotice'] = relationship('ShippingNotice', foreign_keys=[task_id])
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile',
back_populates='links',
@@ -515,7 +390,7 @@ class ShippingOrderIntake(Base):
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
# co8e9f0a1b2c 已 DROP shipping_batches 与 consumed_batch_id;消费绑定仅保留任务侧。
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -697,7 +572,7 @@ class ShippingOrderCandidate(Base):
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'),
ForeignKey('shipping_order_tasks.id'),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -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