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。 依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列; 逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches); Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
ShippingNotice.idempotency_key 为货代上传幂等; ShippingUploadAttempt.idempotency_key 为货代上传幂等;
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放; 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 记录正式建单来源; Document/Candidate 承载「一邮件多订单」识别;ShippingNotice.source_candidate_id 记录正式建单来源;
ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性; ShippingNotice.order_task_id 挂接建单前 OT(shipping_order_tasks);ShippingNotice.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本; OT 的 order_data_version/current_order_extraction_id/order_snapshot_id 仅作为任务流程指针;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实;
阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions; 阶段 1:Intake.source_type / order_submission_id 挂接 shipping_order_submissions;
建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。 建单前接入层表名为 shipping_order_intakes / documents / candidates(类名 ShippingOrder*)。
""" """
@@ -53,18 +52,7 @@ class ShippingNotice(Base):
__tablename__ = 'shipping_notices' __tablename__ = 'shipping_notices'
__table_args__ = ( __table_args__ = (
Index('ix_shipping_notices_conversation', 'conversation_id'), 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_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 不冲突) # 线性版本链:同一父任务至多一个后继(NULL 不冲突)
UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'), UniqueConstraint('supersedes_task_id', name='uq_shipping_notices_supersedes_task_id'),
Index('ix_shipping_notices_duplicate_source_task_id', 'duplicate_source_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) id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=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 的不同波次各自拥有独立编号。 # 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=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) 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) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual') 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_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
source_intake_id: Mapped[Optional[int]] = mapped_column( source_intake_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_intakes.id'), ForeignKey('shipping_order_intakes.id'),
@@ -113,10 +93,6 @@ class ShippingNotice(Base):
nullable=True, nullable=True,
index=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) document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
supersedes_task_id: Mapped[Optional[int]] = mapped_column( supersedes_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'), ForeignKey('shipping_notices.id'),
@@ -128,99 +104,6 @@ class ShippingNotice(Base):
) )
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), 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( lifecycle_status: Mapped[str] = mapped_column(
@@ -241,17 +124,6 @@ class ShippingNotice(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) 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): class ShippingTaskEvent(Base):
@@ -260,7 +132,10 @@ class ShippingTaskEvent(Base):
__tablename__ = 'shipping_task_events' __tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True) 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) event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_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) request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, 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): class ShippingTaskPurgeAudit(Base):
@@ -397,7 +272,7 @@ class ShippingTaskInventoryLink(Base):
) )
id: Mapped[int] = mapped_column(primary_key=True) 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) inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
link_role: Mapped[str] = mapped_column(String(32), default='member') link_role: Mapped[str] = mapped_column(String(32), default='member')
access_mode: Mapped[str] = mapped_column(String(32), default='readonly') 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_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=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( inventory_file: Mapped['ShippingInventoryFile'] = relationship(
'ShippingInventoryFile', 'ShippingInventoryFile',
back_populates='links', back_populates='links',
@@ -515,7 +390,7 @@ class ShippingOrderIntake(Base):
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_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;消费绑定仅保留任务侧。 # 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) create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=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_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
consumed_task_id: Mapped[Optional[int]] = mapped_column( consumed_task_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_notices.id'), ForeignKey('shipping_order_tasks.id'),
nullable=True, nullable=True,
) )
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=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。 依赖:models.ShippingNotice。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingUploadAttempt.idempotency_key(货代上传幂等)语义分离。
""" """
from __future__ import annotations from __future__ import annotations
@@ -83,10 +83,17 @@ def assert_no_exact_duplicate_notices(
return return
for content_hash, _filename in hashes: for content_hash, _filename in hashes:
query = ShippingNotice.query.filter( from app.models import ShippingOrderTask, ShippingOrderIntake, FileAsset
ShippingNotice.user_id == user_id, query = (
ShippingNotice.source_content_hash == content_hash, ShippingNotice.query
ShippingNotice.lifecycle_status == 'active', .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: if skipped_ids:
query = query.filter(ShippingNotice.id.notin_(list(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 flask import current_app
from app import db 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.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.queue_service import enqueue_shipping_notice_job
from app.services.shipping_notice.query_service import get_task_by_ref from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.tool_common import ( 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: def _should_orchestrate_task(task: Any) -> bool:
from app.services.shipping_notice.task_disposition_service import task_is_active 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): if not task_is_active(task):
return False return False
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() pending_reason = str(task_blocking_reason(task) or '').strip().lower()
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}: from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
if has_verified_upload_success(task):
return False return False
if getattr(task, "review_status", None): if getattr(task, "review_status", None):
return False return False
if ( if (
not getattr(task, "inventory_lines_json", None) not has_ready_inventory_file_for_task(task)
and pending_reason in {"", PH_RPA_PENDING} and pending_reason in {"", PH_RPA_PENDING}
): ):
return True return True
if getattr(task, "pending_human_reason", None): if task_blocking_reason(task):
return False 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 False
return True return True
@@ -95,6 +100,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {"status": "skipped", "message": "task already running"} return {"status": "skipped", "message": "task already running"}
try: try:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
task = get_task_by_ref(normalized_task_no) task = get_task_by_ref(normalized_task_no)
if not task: if not task:
return {"status": "missing", "message": "task not found"} return {"status": "missing", "message": "task not found"}
@@ -102,30 +109,38 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return { return {
"status": "skipped", "status": "skipped",
"message": ( "message": (
f"skip stage={getattr(task, 'current_step', '') or ''}" f"skip stage={getattr(task, 'stage', '') or ''}"
f" pending_human_reason={task.pending_human_reason or ''}" f" pending_human_reason={task_blocking_reason(task) or ''}"
f" review_status={task.review_status or ''}" f" review_status={getattr(task, 'review_status', '') or ''}"
), ),
} }
log_task_event( log_task_event(
task, task,
"backend_orchestrator_task_started", "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() db.session.commit()
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id} 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 ( if (
not getattr(task, "inventory_lines_json", None) not has_ready_inventory_file_for_task(task)
and pending_reason == PH_RPA_PENDING and pending_reason == PH_RPA_PENDING
): ):
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询 # [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。 # rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress 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: if current_app:
current_app.logger.info( current_app.logger.info(
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s", "[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], str(result.get("message") or "")[:300],
) )
elif ( elif (
not getattr(task, "inventory_lines_json", None) not has_ready_inventory_file_for_task(task)
and pending_reason == "" and pending_reason == ""
): ):
payload["mode"] = "auto" 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", "[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
task.task_no, task.task_no,
result.get("status"), result.get("status"),
task.current_step, task.stage,
str(result.get("message") or "")[:300], 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 ""), "result_status": str(result.get("status") or ""),
"lifecycle_status": refreshed.lifecycle_status, "lifecycle_status": refreshed.lifecycle_status,
"current_step": refreshed.current_step, "stage": refreshed.stage,
}, },
) )
db.session.commit() db.session.commit()
@@ -190,7 +205,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
db.session.rollback() db.session.rollback()
task = get_task_by_ref(normalized_task_no) task = get_task_by_ref(normalized_task_no)
if task: 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]}) log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
db.session.commit() db.session.commit()
return {"status": "failed", "message": str(exc)[:500] or "background task failed"} 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 import db
from app.core.errors import ConflictError 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 from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
BUSINESS_TYPE = "shipping_notice" BUSINESS_TYPE = "shipping_notice"
@@ -121,13 +121,19 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
return int(value) 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 的不同通知单不会复用编号。 为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
Args: Args:
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。 notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
moment: 可选时刻,测试时用于固定上海业务日期。 moment: 可选时刻,测试时用于固定上海业务日期。
customer_id_override: 纠错替代单使用的新客户;仅用于编号,不修改原 OT 的历史匹配事实。
Returns: Returns:
分配或已存在的 business_no。 分配或已存在的 business_no。
@@ -137,12 +143,18 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
""" """
if notice.business_no: if notice.business_no:
return str(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( raise ConflictError(
'Shipping notice customer must be confirmed before numbering', 'Shipping notice customer must be confirmed before numbering',
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED', 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': if customer is None or customer.status != 'active':
raise ConflictError( raise ConflictError(
'Active customer is required before numbering', '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_date = business_date
notice.business_sequence_value = sequence_value notice.business_sequence_value = sequence_value
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION 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() db.session.flush()
return str(notice.business_no) return str(notice.business_no)
@@ -37,7 +37,8 @@ def _select_tasks(
tasks = [] tasks = []
for task_no in normalized_tasks: for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id) 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() 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') 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( artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id, ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploaded'}), ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
ShippingExportArtifact.file_path == task.export_file_path,
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first() ).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
if artifact is not None: if artifact is not None:
result[int(task.id)] = [artifact] result[int(task.id)] = [artifact]
@@ -16,8 +16,9 @@ from typing import Any
from app import db from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError 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.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.tool_common import task_event_task_id
def complete_freight_cancellation( def complete_freight_cancellation(
@@ -59,11 +60,16 @@ def complete_freight_cancellation(
old.voided_at = datetime.utcnow() old.voided_at = datetime.utcnow()
old.voided_by_id = int(actor_id) old.voided_by_id = int(actor_id)
old.void_reason = 'freight_cancellation_completed' old.void_reason = 'freight_cancellation_completed'
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required': # Notice 不再承载旧工作流阻断字段;解除修订阻断时更新其 OT 生命周期,
new.lifecycle_status = 'active' # 由 OT 的 Gate/状态投影重新计算当前工作面。
new.pending_human_reason = None 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( db.session.add(ShippingTaskEvent(
task_id=old.id, task_id=task_event_task_id(old),
event_type='freight_cancellation_completed', event_type='freight_cancellation_completed',
actor_id=actor_id, actor_id=actor_id,
detail_json={ detail_json={
@@ -74,7 +80,7 @@ def complete_freight_cancellation(
}, },
)) ))
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=new.id, task_id=task_event_task_id(new),
event_type='supersession_unblocked', event_type='supersession_unblocked',
actor_id=actor_id, actor_id=actor_id,
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}, 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]: 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 { return {
'task_no': str(task.task_no), 'task_no': str(task.task_no),
'lifecycle_status': str(task.lifecycle_status or ''), '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, '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'}: if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}:
task.lifecycle_status = 'pending_void' task.lifecycle_status = 'pending_void'
task.void_reason = reason_text task.void_reason = reason_text
task.pending_human_reason = 'pending_void'
# co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。 # co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。
after = _task_cancel_snapshot(task) after = _task_cancel_snapshot(task)
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=int(task.id), task_id=task_event_task_id(task),
event_type='task_pending_void', event_type='task_pending_void',
actor_id=int(actor_id), actor_id=int(actor_id),
detail_json={ detail_json={
@@ -3,8 +3,10 @@ services/shipping_notice/lifecycle_projection.py
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。 用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。 逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 [B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作;
阶段入口与实际动作权限必须分开。
""" """
from __future__ import annotations from __future__ import annotations
@@ -36,6 +38,9 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
'duplicate_detection': 'order_review', 'duplicate_detection': 'order_review',
'field_conflict_resolution': 'order_review', 'field_conflict_resolution': 'order_review',
'order_freeze_readiness': 'order_review', 'order_freeze_readiness': 'order_review',
# 建单前已存在当前有效 Candidate 的未确认 Review Case 仍属「订单复核」工作面:
# 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。
'order_review_build': 'order_review',
'task_creation': 'order_review', 'task_creation': 'order_review',
'inventory_source_routing': 'fulfillment_prep', 'inventory_source_routing': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep', 'inventory_preparation': 'fulfillment_prep',
@@ -49,8 +54,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
} }
# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于 # 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在 # 读模型展示,不推进订单、不创建任务,也不授予任何动作。[B''] 它是阶段的唯一
# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。 # 权威;正式 Gate 仅在技术阶段缺失时提供兜底,不能覆盖有效处理阶段。
LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'upload_received': 'intake_parse', 'upload_received': 'intake_parse',
'email_parsing': 'intake_parse', 'email_parsing': 'intake_parse',
@@ -60,7 +65,7 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'waiting_review': 'order_review', 'waiting_review': 'order_review',
'customer_resolving': 'order_review', 'customer_resolving': 'order_review',
'duplicate_checking': 'order_review', 'duplicate_checking': 'order_review',
'inventory_source_resolving': 'order_review', 'inventory_source_resolving': 'fulfillment_prep',
'order_creating': 'fulfillment_prep', 'order_creating': 'fulfillment_prep',
'inventory_fetching': 'fulfillment_prep', 'inventory_fetching': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep', 'inventory_preparation': 'fulfillment_prep',
@@ -114,11 +119,12 @@ def project_lifecycle(
verified_upload_success: bool = False, verified_upload_success: bool = False,
processing_stage: str | None = None, processing_stage: str | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。 """按成功事实 → 已持久化阶段 → 正式 Gate → 阻断归属的固定优先级裁决生命周期。
``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能 [B''] 阶段唯一权威:只要 ``processing_stage``(OT.stage / Run.processing_stage)是合法
授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算 15 阶成员,就直接映射五阶段,正式 Gate 不能覆盖或升降它。``gate_code`` 只在处理
阶段或放开按钮。 阶段缺失时兜底(如任务详情无 OT.stage 上下文),且仅用于「订单检查」面板诊断;
它不再能改变阶段。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
""" """
gate = current_gate if isinstance(current_gate, dict) else {} gate = current_gate if isinstance(current_gate, dict) else {}
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() 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: if verified_upload_success:
lifecycle_stage = 'upload_complete' lifecycle_stage = 'upload_complete'
authority = 'verified_upload_success' authority = 'verified_upload_success'
elif gate_code in LIFECYCLE_STAGE_BY_GATE: # [B''] 处理阶段是阶段唯一权威。合法 15 阶直接映射五阶段;Gate 不再覆盖它。
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate'
elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[ lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[
str(processing_stage or '').strip().lower() str(processing_stage or '').strip().lower()
] ]
authority = 'processing_stage' 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: else:
reason = blocking_reason if isinstance(blocking_reason, dict) else {} reason = blocking_reason if isinstance(blocking_reason, dict) else {}
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip() 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 为边界管理货代上传尝试、回调幂等和人工确认。 用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。 依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。 逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,任务工作面通过 Attempt 查询结果。
""" """
from __future__ import annotations 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: def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact:
"""返回本次上传目标 Artifact;调用方不能借 Task 旧文件指针绕过分轮履约。""" """返回本次上传目标 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) query = ShippingExportArtifact.query.filter_by(task_id=task.id)
if artifact_id is not None: if artifact_id is not None:
artifact = query.filter_by(id=artifact_id).one_or_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 return attempt
def _aggregate_task_upload_status(task: ShippingNotice) -> None: def latest_export_artifact(task: ShippingNotice) -> ShippingExportArtifact | None:
"""从预约单真相刷新兼容 Task 投影,不能由单个旧回调直接覆盖。""" """返回当前 Notice 最新有效导出 Artifact;不回读 Notice 的旧文件投影。"""
reservations = ShippingReservation.query.filter_by(task_id=task.id).all() notice = _formal_notice(task)
if reservations and all(item.status == 'uploaded' for item in reservations): if notice is None:
task.upload_status = 'uploaded' return None
task.upload_finished_at = datetime.utcnow() return ShippingExportArtifact.query.filter(
elif any(item.status == 'uploaded' for item in reservations): ShippingExportArtifact.task_id == notice.id,
task.upload_status = 'partial' ShippingExportArtifact.status.in_({'ready', 'uploading', 'uploaded'}),
else: ).order_by(
task.upload_status = 'pending' 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: def has_verified_upload_success(task: ShippingNotice) -> bool:
"""判断任务是否具备可审计的货代上传成功事实。 """判断任务是否具备可审计的货代上传成功事实。
业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、 当前 Excel Artifact 标为 uploaded 即代表 Notice 业务完成;成功 Attempt 只作为上传
单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 审计证据。预约单属于行级履约事实,不参与 Notice 完成判定。该函数是 UI 生命周期、
已完成分组与停止轮询共用的唯一成功谓词。 批次已完成分组与停止轮询共用的唯一成功谓词。
""" """
try: try:
from flask import has_app_context from flask import has_app_context
@@ -99,18 +124,15 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
'voided', 'archived', 'deleted', 'cancelled', 'voided', 'archived', 'deleted', 'cancelled',
}: }:
return False 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 return False
reservations = ShippingReservation.query.filter_by(task_id=task.id).all() if getattr(task, 'id', None) is None:
if not reservations or any(row.status != 'uploaded' for row in reservations):
return False return False
return db.session.query(ShippingUploadAttempt.id).join( artifact = latest_export_artifact(task)
ShippingExportArtifact, if artifact is None or artifact.status != 'uploaded':
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, return False
).filter( return True
ShippingExportArtifact.task_id == task.id,
ShippingUploadAttempt.status == 'succeeded',
).first() is not None
def _normalize_callback_result(result: str | None, success: bool) -> str: 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( ShippingReservation.query.filter(ShippingReservation.id.in_(reservation_ids)).update(
{'status': 'uploaded'}, synchronize_session=False, {'status': 'uploaded'}, synchronize_session=False,
) )
# 批量更新绕开 ORM identity map;立即失效以确保同一事务的 Task 聚合读取最新预约单状态。 # 批量更新绕开 ORM identity map;立即失效以确保同一事务的预约单事实读取最新状态。
db.session.expire_all() db.session.expire_all()
if task is not None:
task.freight_ref_no = attempt.freight_ref_no
_aggregate_task_upload_status(task)
else: else:
# A missing callback may conceal a completed freight submission. A late # A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact. # transport error is not enough to safely release or retry that Artifact.
@@ -200,11 +219,6 @@ def complete_attempt(
error_message error_message
or '无法判断上传是否成功/失败:RPA 结果未确认,可能已上传成功但未出现成功提示,或上传配置(result_selector/success_texts)有误;请人工核查或确认已上传' or '无法判断上传是否成功/失败:RPA 结果未确认,可能已上传成功但未出现成功提示,或上传配置(result_selector/success_texts)有误;请人工核查或确认已上传'
)[:500] )[: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() db.session.flush()
return attempt return attempt
attempt.status = 'failed' 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_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED'
attempt.error_message = message attempt.error_message = message
artifact.status = 'ready' 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() db.session.flush()
return attempt return attempt
@@ -12,7 +12,17 @@ import pytest
from app import db from app import db
from app.core.errors import ConflictError from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.models import (
ShippingBusinessSequence,
ShippingCustomer,
ShippingNotice,
ShippingTaskEvent,
ShippingOrderTask,
ShippingOrderExtraction,
ShippingCustomerShadowResolution,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.business_numbering_service import ( from app.services.shipping_notice.business_numbering_service import (
assign_notice_business_number, assign_notice_business_number,
format_business_no, format_business_no,
@@ -22,23 +32,42 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus
from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001", customer: ShippingCustomer | None = None):
"""创建待客户确认的 Notice 和启用客户。""" """创建带客户识别结果的待确认 Notice。"""
customer = ShippingCustomer( if customer is None:
standard_name=f"编号测试客户 {short_code}", customer = ShippingCustomer(
short_code=short_code, standard_name=f"编号测试客户 {short_code}",
status="active", short_code=short_code,
) status="active",
db.session.add(customer) )
db.session.add(customer)
db.session.flush()
schema = ShippingOrderSchema(schema_code=f'SHIPPING_ORDER_{task_no}', display_name='Order')
db.session.add(schema)
db.session.flush() db.session.flush()
task = ShippingNotice( version = ShippingOrderSchemaVersion(
task_no=task_no, schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='a' * 64,
customer_resolution_status="pending",
source_type="manual",
) )
db.session.add(task) db.session.add(version)
db.session.flush()
owner = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='ready', current_step='customer_review')
db.session.add(owner)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
owner.current_order_extraction_id = extraction.id
from tests.conftest import confirm_test_customer_resolution
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
resolution.status = 'unique_candidate'
resolution.confirmed_customer_id = None
notice = ShippingNotice(task_no=task_no, source_type='manual', order_task_id=owner.id)
db.session.add(notice)
db.session.commit() db.session.commit()
return task, customer return notice, customer
def test_number_format_and_shanghai_date_boundary(app): def test_number_format_and_shanghai_date_boundary(app):
@@ -54,31 +83,31 @@ def test_confirmation_assigns_idempotent_business_number(app):
"""重复确认同一客户不得重复占用流水,正式编号保持不变。""" """重复确认同一客户不得重复占用流水,正式编号保持不变。"""
with app.app_context(): with app.app_context():
task, customer = _seed_notice() task, customer = _seed_notice()
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None) confirm_task_customer(task, customer_id=customer.id, actor_id=None)
first_no = first.business_no first_no = assign_notice_business_number(task)
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None) confirm_task_customer(task, customer_id=customer.id, actor_id=None)
second = task
assert first_no assert first_no
assert second.business_no == first_no assert second.business_no == first_no
assert ShippingBusinessSequence.query.one().current_value == 1 assert ShippingBusinessSequence.query.one().current_value == 1
assert second.customer_short_code_snapshot == "WYC" resolution = ShippingCustomerShadowResolution.query.one()
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1 assert resolution.confirmed_customer_id == customer.id
def test_each_notice_gets_a_distinct_business_number_for_same_customer(app): def test_each_notice_gets_a_distinct_business_number_for_same_customer(app):
"""同一客户 PO 的不同发货通知必须各自占用独立业务流水。""" """同一客户 PO 的不同发货通知必须各自占用独立业务流水。"""
with app.app_context(): with app.app_context():
customer = ShippingCustomer( customer = ShippingCustomer(standard_name='通知单波次客户', short_code='WVC', status='active')
standard_name='通知单波次客户', short_code='WVC', status='active',
)
db.session.add(customer) db.session.add(customer)
db.session.flush() db.session.flush()
first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed') first, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-1', customer=customer)
second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed') second, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-2', customer=customer)
db.session.add_all([first, second]) for notice in (first, second):
db.session.flush() owner = db.session.get(ShippingOrderTask, notice.order_task_id)
first.customer_id = customer.id resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
second.customer_id = customer.id resolution.confirmed_customer_id = customer.id
resolution.status = 'confirmed'
db.session.flush() db.session.flush()
first_no = assign_notice_business_number(first) first_no = assign_notice_business_number(first)
@@ -95,21 +124,17 @@ def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app):
customer = ShippingCustomer( customer = ShippingCustomer(
standard_name='Notice 自持客户', short_code='NHC', status='active', standard_name='Notice 自持客户', short_code='NHC', status='active',
) )
task = ShippingNotice( task, _ = _seed_notice(short_code='NHC', task_no='SN-NOTICE-SELF-CUSTOMER')
task_no='SN-NOTICE-SELF-CUSTOMER', customer = ShippingCustomer.query.filter_by(short_code='NHC').one()
customer_resolution_status='pending',
source_type='manual',
)
db.session.add_all([customer, task])
db.session.commit()
confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7) confirm_task_customer(task, customer_id=customer.id, actor_id=7)
assign_notice_business_number(task)
confirmed = task
assert confirmed.customer_id == customer.id owner = db.session.get(ShippingOrderTask, confirmed.order_task_id)
assert confirmed.customer_name_snapshot == 'Notice 自持客户' resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
assert confirmed.customer_short_code_snapshot == 'NHC' assert resolution.confirmed_customer_id == customer.id
assert confirmed.business_no assert confirmed.business_no
assert confirmed.customer_resolution_status == 'confirmed'
def test_replacement_notice_uses_next_sequence(app): def test_replacement_notice_uses_next_sequence(app):
@@ -117,16 +142,18 @@ def test_replacement_notice_uses_next_sequence(app):
with app.app_context(): with app.app_context():
task, customer = _seed_notice() task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None) confirm_task_customer(task, customer_id=customer.id, actor_id=None)
assign_notice_business_number(task)
revision = ShippingNotice( revision = ShippingNotice(
task_no="SN-NUMBER-REV", task_no="SN-NUMBER-REV",
supersedes_task_id=task.id, supersedes_task_id=task.id,
customer_resolution_status="pending", order_task_id=task.order_task_id,
source_type="manual", source_type="manual",
) )
db.session.add(revision) db.session.add(revision)
db.session.commit() db.session.commit()
confirm_task_customer(revision, customer_id=customer.id, actor_id=None) confirm_task_customer(revision, customer_id=customer.id, actor_id=None)
assign_notice_business_number(revision)
assert revision.business_no[:-2] == task.business_no[:-2] assert revision.business_no[:-2] == task.business_no[:-2]
assert task.business_no.endswith("01") assert task.business_no.endswith("01")
assert revision.business_no.endswith("02") assert revision.business_no.endswith("02")
@@ -144,8 +171,7 @@ def test_daily_sequence_blocks_one_hundredth_case(app):
current_value=99, current_value=99,
)) ))
db.session.commit() db.session.commit()
task.customer_id = customer.id confirm_task_customer(task, customer_id=customer.id, actor_id=None)
with pytest.raises(ConflictError) as exc_info: with pytest.raises(ConflictError) as exc_info:
assign_notice_business_number(task) assign_notice_business_number(task)
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED" assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED"
@@ -165,14 +191,17 @@ def test_numbering_failure_rolls_back_customer_confirmation(app):
)) ))
db.session.commit() db.session.commit()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
with pytest.raises(ConflictError): with pytest.raises(ConflictError):
confirm_task_customer(task, customer_id=customer.id, actor_id=None) assign_notice_business_number(task)
db.session.rollback() db.session.rollback()
db.session.expire_all() db.session.expire_all()
persisted_task = db.session.get(ShippingNotice, task.id) persisted_task = db.session.get(ShippingNotice, task.id)
assert persisted_task.customer_id is None owner = db.session.get(ShippingOrderTask, persisted_task.order_task_id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
assert resolution.confirmed_customer_id == customer.id
assert resolution.status == 'confirmed'
assert persisted_task.business_no is None assert persisted_task.business_no is None
assert persisted_task.customer_resolution_status == "pending"
def test_business_number_query_returns_exact_notice(app): def test_business_number_query_returns_exact_notice(app):
@@ -180,11 +209,12 @@ def test_business_number_query_returns_exact_notice(app):
with app.app_context(): with app.app_context():
task, customer = _seed_notice() task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None) confirm_task_customer(task, customer_id=customer.id, actor_id=None)
assign_notice_business_number(task)
revision = ShippingNotice( revision = ShippingNotice(
task_no="SN-NUMBER-QUERY-REV", task_no="SN-NUMBER-QUERY-REV",
supersedes_task_id=task.id, supersedes_task_id=task.id,
document_version=2, document_version=2,
customer_resolution_status="pending", order_task_id=task.order_task_id,
source_type="manual", source_type="manual",
) )
db.session.add(revision) db.session.add(revision)
@@ -199,7 +229,7 @@ def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app)
"""客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。""" """客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。"""
with app.app_context(): with app.app_context():
task, customer = _seed_notice() task, customer = _seed_notice()
task.customer_id = customer.id confirm_task_customer(task, customer_id=customer.id, actor_id=None)
customer.short_code = "W1" customer.short_code = "W1"
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。 # 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info: with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
@@ -1,52 +1,42 @@
""" """
用途:验证人工上传必须引用用户私有回执资产。 用途:验证人工上传不再要求回执/截图证据,仅记录目标 Excel Artifact 与服务端操作人。
依赖:上传 Attempt 服务、FileAsset 服务、滚动履约测试夹具。 依赖:上传 Attempt 服务、滚动履约测试夹具。
逻辑:无回执请求被拒;有已上传资产时创建 manual Attempt 并锁定预约单。 逻辑:人工确认无需回执资产即成功创建 manual Attempt 并锁定预约单。
""" """
from __future__ import annotations from __future__ import annotations
from io import BytesIO
import pytest import pytest
from werkzeug.datastructures import FileStorage
from app import db from app import db
from app.core.errors import ValidationError
from app.models import ShippingUploadAttempt, User from app.models import ShippingUploadAttempt, User
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.upload_attempt_service import record_manual_upload from app.services.shipping_notice.upload_attempt_service import record_manual_upload
from tests.test_shipping_upload_attempt import _ready_artifact from tests.test_shipping_upload_attempt import _ready_artifact
def test_manual_upload_requires_receipt_asset(app): def test_manual_upload_requires_no_receipt_asset(app):
"""人工确认不可仅凭文本或参考号,缺少回执文件必须返回专用业务错误。""" """人工确认不再采集回执/截图证据;仅凭操作者与目标 Excel 即可成功。"""
with app.app_context(): with app.app_context():
task, artifact, _reservation = _ready_artifact() task, artifact, _reservation = _ready_artifact()
user = User(username='manual-evidence', email='manual-evidence@example.test', password_hash='x') user = User(username='manual-evidence', email='manual-evidence@example.test', password_hash='x')
db.session.add(user); db.session.flush() db.session.add(user); db.session.flush()
with pytest.raises(ValidationError) as exc_info: attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id)
record_manual_upload(task, artifact_id=artifact.id, evidence_asset_no='', operator_id=user.id) assert attempt.mode == 'manual'
assert exc_info.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED' assert attempt.evidence_asset_id is None
assert attempt.freight_ref_no is None
def test_manual_upload_records_receipt_asset(app): def test_manual_upload_records_operator_and_locks_reservation(app):
"""已上传的私有截图资产会成为 manual Attempt 的不可变证据。""" """人工确认记录操作者并完成上传事实;不产生任何截图/PDF 证据。"""
with app.app_context(): with app.app_context():
task, artifact, reservation = _ready_artifact() task, artifact, reservation = _ready_artifact()
user = User(username='manual-evidence-ok', email='manual-evidence-ok@example.test', password_hash='x') user = User(username='manual-evidence-ok', email='manual-evidence-ok@example.test', password_hash='x')
db.session.add(user); db.session.commit() db.session.add(user); db.session.commit()
payload = upload_file_asset( attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id)
user_id=user.id,
upload=FileStorage(stream=BytesIO(b'receipt'), filename='receipt.png', content_type='image/png'),
)
attempt = record_manual_upload(
task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id,
freight_ref_no='FREIGHT-RECEIPT-1',
)
assert attempt.mode == 'manual' assert attempt.mode == 'manual'
assert attempt.status == 'succeeded' assert attempt.status == 'succeeded'
assert attempt.evidence_asset_id is not None assert attempt.evidence_asset_id is None
assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1' assert attempt.freight_ref_no is None
assert attempt.operator_id == user.id
assert db.session.get(type(reservation), reservation.id).status == 'uploaded' assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
assert ShippingUploadAttempt.query.count() == 1 assert ShippingUploadAttempt.query.count() == 1
@@ -53,9 +53,14 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app):
task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual') task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual')
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
# 冻结的逐源 Attempt 须携带完整 v2 身份(lease_token / candidate_set / execution / gate),
# 否则回调会先在 _validate_callback_attempt_identity 被 identity_mismatch 拒绝,
# 无法走到失败分支去写 callback_id。
first = ShippingTaskInventoryRpaAttempt( first = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='SRC-A', attempt_no=1, task_no=task.task_no, source_code='SRC-A', attempt_no=1,
source_run_no='PSR-FIRST', status='failed', callback_id=None, source_run_no='PSR-FIRST', status='failed', callback_id=None,
lease_token='lease-first',
extra_json={'candidate_set_id': 1, 'execution_id': 1, 'gate_id': 1},
) )
second = ShippingTaskInventoryRpaAttempt( second = ShippingTaskInventoryRpaAttempt(
task_no='SN-CB-ID-OTHER', source_code='SRC-B', attempt_no=1, task_no='SN-CB-ID-OTHER', source_code='SRC-B', attempt_no=1,
@@ -64,23 +69,43 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app):
db.session.add_all([first, second]) db.session.add_all([first, second])
db.session.flush() db.session.flush()
def _payload(run_no: str, source_code: str, attempt_no: int) -> dict:
"""构造完整 v2 身份围栏的回调 payload。
与 _validate_callback_attempt_identity 的 required 字段一一对应,
使失败回调(error_code)能通过身份校验并回写 callback_id。
"""
return {
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'cb-unique',
'task_no': task.task_no,
'source_code': source_code,
'source_run_no': run_no,
'attempt_no': attempt_no,
'lease_token': 'lease-first',
'candidate_set_id': 1,
'execution_id': 1,
'gate_id': 1,
'error_code': 'RPA_TIMEOUT',
}
result, handled = per_source_callback_handler( result, handled = per_source_callback_handler(
task, source_code='SRC-A', run_no='PSR-FIRST', task, source_code='SRC-A', run_no='PSR-FIRST',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, callback_payload=_payload('PSR-FIRST', 'SRC-A', 1),
) )
assert result == 'failed' assert result == 'failed'
assert handled.id == first.id assert handled.id == first.id
result, handled = per_source_callback_handler( result, handled = per_source_callback_handler(
task, source_code='SRC-A', run_no='PSR-FIRST', task, source_code='SRC-A', run_no='PSR-FIRST',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, callback_payload=_payload('PSR-FIRST', 'SRC-A', 1),
) )
assert result == 'idempotent_ok' assert result == 'idempotent_ok'
assert handled.id == first.id assert handled.id == first.id
result, handled = per_source_callback_handler( result, handled = per_source_callback_handler(
task, source_code='SRC-B', run_no='PSR-SECOND', task, source_code='SRC-B', run_no='PSR-SECOND',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, callback_payload=_payload('PSR-SECOND', 'SRC-B', 1),
) )
assert result == 'callback_conflict' assert result == 'callback_conflict'
assert handled.id == first.id assert handled.id == first.id
@@ -13,12 +13,12 @@ tests/test_shipping_uploaded_gate_closure.py
from __future__ import annotations from __future__ import annotations
from app import db from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate from app.models import ShippingNotice, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, User
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution: def _mk_execution(task: ShippingOrderTask) -> ShippingProcessExecution:
"""建正式 20-Gate Execution,并把 inventory_sufficiency 置为人工阻断,让任务停留在「通知准备」。""" """建正式 20-Gate Execution,并把 inventory_sufficiency 置为人工阻断,让任务停留在「通知准备」。"""
execution = ensure_execution_for_workflow_version(task_id=int(task.id)) execution = ensure_execution_for_workflow_version(task_id=int(task.id))
task.active_process_execution_id = int(execution.id) task.active_process_execution_id = int(execution.id)
@@ -33,12 +33,18 @@ def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution:
return execution return execution
def test_step1a_closes_all_gates_when_uploaded(app): def test_step1a_closes_all_gates_when_uploaded(app, monkeypatch):
"""upload_status=uploaded → STEP 1A 收口全部前置 Gate,Execution 落到 completed。""" """upload_status=uploaded → STEP 1A 收口全部前置 Gate,Execution 落到 completed。"""
task = ShippingNotice(task_no='SN-UPLOADED-GATE', upload_status='uploaded', match_status='fulfillable') user = User(username='uploaded-gate-user', email='uploaded-gate@example.com', password_hash='x')
db.session.add(user); db.session.flush()
task = ShippingOrderTask(task_no='OT-UPLOADED-GATE', user_id=user.id)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
execution = _mk_execution(task) execution = _mk_execution(task)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status',
lambda _task: 'uploaded',
)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1) sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit() db.session.commit()
@@ -53,17 +59,18 @@ def test_step1a_closes_all_gates_when_uploaded(app):
assert execution.status == 'completed' assert execution.status == 'completed'
def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app): def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app, monkeypatch):
"""上传已成功时,历史 upload_rpa_pending 不得将正式 Gate 重新投影为阻断。""" """上传已成功时,历史 upload_rpa_pending 不得将正式 Gate 重新投影为阻断。"""
task = ShippingNotice( user = User(username='uploaded-stale-user', email='uploaded-stale@example.com', password_hash='x')
task_no='SN-UPLOADED-STALE-PENDING', db.session.add(user); db.session.flush()
upload_status='uploaded', task = ShippingOrderTask(task_no='OT-UPLOADED-STALE-PENDING', user_id=user.id, pending_human_reason='upload_rpa_pending')
pending_human_reason='upload_rpa_pending',
match_status='fulfillable',
)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
execution = _mk_execution(task) execution = _mk_execution(task)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status',
lambda _task: 'uploaded',
)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1) sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit() db.session.commit()
@@ -75,7 +82,9 @@ def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app):
def test_missing_upload_status_keeps_gate_stuck(app): def test_missing_upload_status_keeps_gate_stuck(app):
"""upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。""" """upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。"""
task = ShippingNotice(task_no='SN-UPLOAD-NOT-SET', upload_status='partial', match_status='fulfillable') user = User(username='upload-not-set-user', email='upload-not-set@example.com', password_hash='x')
db.session.add(user); db.session.flush()
task = ShippingOrderTask(task_no='OT-UPLOAD-NOT-SET', user_id=user.id)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
execution = _mk_execution(task) execution = _mk_execution(task)