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
@@ -12,7 +12,17 @@ import pytest
from app import db
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 (
assign_notice_business_number,
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
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
"""创建待客户确认的 Notice 和启用客户。"""
customer = ShippingCustomer(
standard_name=f"编号测试客户 {short_code}",
short_code=short_code,
status="active",
)
db.session.add(customer)
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001", customer: ShippingCustomer | None = None):
"""创建带客户识别结果的待确认 Notice。"""
if customer is None:
customer = ShippingCustomer(
standard_name=f"编号测试客户 {short_code}",
short_code=short_code,
status="active",
)
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()
task = ShippingNotice(
task_no=task_no,
customer_resolution_status="pending",
source_type="manual",
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='a' * 64,
)
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()
return task, customer
return notice, customer
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():
task, customer = _seed_notice()
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None)
first_no = first.business_no
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None)
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
first_no = assign_notice_business_number(task)
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
second = task
assert first_no
assert second.business_no == first_no
assert ShippingBusinessSequence.query.one().current_value == 1
assert second.customer_short_code_snapshot == "WYC"
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1
resolution = ShippingCustomerShadowResolution.query.one()
assert resolution.confirmed_customer_id == customer.id
def test_each_notice_gets_a_distinct_business_number_for_same_customer(app):
"""同一客户 PO 的不同发货通知必须各自占用独立业务流水。"""
with app.app_context():
customer = ShippingCustomer(
standard_name='通知单波次客户', short_code='WVC', status='active',
)
customer = ShippingCustomer(standard_name='通知单波次客户', short_code='WVC', status='active')
db.session.add(customer)
db.session.flush()
first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed')
second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed')
db.session.add_all([first, second])
db.session.flush()
first.customer_id = customer.id
second.customer_id = customer.id
first, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-1', customer=customer)
second, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-2', customer=customer)
for notice in (first, second):
owner = db.session.get(ShippingOrderTask, notice.order_task_id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
resolution.confirmed_customer_id = customer.id
resolution.status = 'confirmed'
db.session.flush()
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(
standard_name='Notice 自持客户', short_code='NHC', status='active',
)
task = ShippingNotice(
task_no='SN-NOTICE-SELF-CUSTOMER',
customer_resolution_status='pending',
source_type='manual',
)
db.session.add_all([customer, task])
db.session.commit()
task, _ = _seed_notice(short_code='NHC', task_no='SN-NOTICE-SELF-CUSTOMER')
customer = ShippingCustomer.query.filter_by(short_code='NHC').one()
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
assert confirmed.customer_name_snapshot == 'Notice 自持客户'
assert confirmed.customer_short_code_snapshot == 'NHC'
owner = db.session.get(ShippingOrderTask, confirmed.order_task_id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
assert resolution.confirmed_customer_id == customer.id
assert confirmed.business_no
assert confirmed.customer_resolution_status == 'confirmed'
def test_replacement_notice_uses_next_sequence(app):
@@ -117,16 +142,18 @@ def test_replacement_notice_uses_next_sequence(app):
with app.app_context():
task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
assign_notice_business_number(task)
revision = ShippingNotice(
task_no="SN-NUMBER-REV",
supersedes_task_id=task.id,
customer_resolution_status="pending",
order_task_id=task.order_task_id,
source_type="manual",
)
db.session.add(revision)
db.session.commit()
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 task.business_no.endswith("01")
assert revision.business_no.endswith("02")
@@ -144,8 +171,7 @@ def test_daily_sequence_blocks_one_hundredth_case(app):
current_value=99,
))
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:
assign_notice_business_number(task)
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()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
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.expire_all()
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.customer_resolution_status == "pending"
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():
task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
assign_notice_business_number(task)
revision = ShippingNotice(
task_no="SN-NUMBER-QUERY-REV",
supersedes_task_id=task.id,
document_version=2,
customer_resolution_status="pending",
order_task_id=task.order_task_id,
source_type="manual",
)
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():
task, customer = _seed_notice()
task.customer_id = customer.id
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
customer.short_code = "W1"
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
@@ -1,52 +1,42 @@
"""
用途:验证人工上传必须引用用户私有回执资产。
依赖:上传 Attempt 服务、FileAsset 服务、滚动履约测试夹具。
逻辑:无回执请求被拒;有已上传资产时创建 manual Attempt 并锁定预约单。
用途:验证人工上传不再要求回执/截图证据,仅记录目标 Excel Artifact 与服务端操作人。
依赖:上传 Attempt 服务、滚动履约测试夹具。
逻辑:人工确认无需回执资产即成功创建 manual Attempt 并锁定预约单。
"""
from __future__ import annotations
from io import BytesIO
import pytest
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import ValidationError
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 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():
task, artifact, _reservation = _ready_artifact()
user = User(username='manual-evidence', email='manual-evidence@example.test', password_hash='x')
db.session.add(user); db.session.flush()
with pytest.raises(ValidationError) as exc_info:
record_manual_upload(task, artifact_id=artifact.id, evidence_asset_no='', operator_id=user.id)
assert exc_info.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED'
attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id)
assert attempt.mode == 'manual'
assert attempt.evidence_asset_id is None
assert attempt.freight_ref_no is None
def test_manual_upload_records_receipt_asset(app):
"""已上传的私有截图资产会成为 manual Attempt 的不可变证据。"""
def test_manual_upload_records_operator_and_locks_reservation(app):
"""人工确认记录操作者并完成上传事实;不产生任何截图/PDF 证据。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
user = User(username='manual-evidence-ok', email='manual-evidence-ok@example.test', password_hash='x')
db.session.add(user); db.session.commit()
payload = upload_file_asset(
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',
)
attempt = record_manual_upload(task, artifact_id=artifact.id, operator_id=user.id)
assert attempt.mode == 'manual'
assert attempt.status == 'succeeded'
assert attempt.evidence_asset_id is not None
assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1'
assert attempt.evidence_asset_id is None
assert attempt.freight_ref_no is None
assert attempt.operator_id == user.id
assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
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')
db.session.add(task)
db.session.flush()
# 冻结的逐源 Attempt 须携带完整 v2 身份(lease_token / candidate_set / execution / gate),
# 否则回调会先在 _validate_callback_attempt_identity 被 identity_mismatch 拒绝,
# 无法走到失败分支去写 callback_id。
first = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='SRC-A', attempt_no=1,
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(
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.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(
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 handled.id == first.id
result, handled = per_source_callback_handler(
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 handled.id == first.id
result, handled = per_source_callback_handler(
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 handled.id == first.id
@@ -13,12 +13,12 @@ tests/test_shipping_uploaded_gate_closure.py
from __future__ import annotations
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_service import ensure_execution_for_workflow_version
def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution:
def _mk_execution(task: ShippingOrderTask) -> ShippingProcessExecution:
"""建正式 20-Gate Execution,并把 inventory_sufficiency 置为人工阻断,让任务停留在「通知准备」。"""
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
task.active_process_execution_id = int(execution.id)
@@ -33,12 +33,18 @@ def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution:
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。"""
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.flush()
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)
db.session.commit()
@@ -53,17 +59,18 @@ def test_step1a_closes_all_gates_when_uploaded(app):
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 重新投影为阻断。"""
task = ShippingNotice(
task_no='SN-UPLOADED-STALE-PENDING',
upload_status='uploaded',
pending_human_reason='upload_rpa_pending',
match_status='fulfillable',
)
user = User(username='uploaded-stale-user', email='uploaded-stale@example.com', password_hash='x')
db.session.add(user); db.session.flush()
task = ShippingOrderTask(task_no='OT-UPLOADED-STALE-PENDING', user_id=user.id, pending_human_reason='upload_rpa_pending')
db.session.add(task)
db.session.flush()
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)
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):
"""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.flush()
execution = _mk_execution(task)