feat(shipping-notice): 收敛订单处理状态与履约门禁

This commit is contained in:
hugo committed 2026-09-07 09:42:12 +08:00
1 parent bffcd55b40
commit 70dd0051b8
153 files changed
+10916 -4296

No files matched your search

+17 -1
View File
@@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__)
# 子模块导入时在同一 Blueprint 上注册原有 URL。
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from .shared import ( # noqa: E402, F401
CHAT_USER_ATTACHMENT_LIMIT,
CHAT_USER_ATTACHMENT_MAX_SIZE,
CHAT_USER_ATTACHMENT_SOURCES,
CHAT_USER_ATTACHMENT_TYPES,
_merge_user_attachments_from_terminal_event,
_normalize_user_attachments,
)
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
register_chat_turn_routes(chat_bp)
__all__ = ['chat_bp']
__all__ = [
'chat_bp',
'CHAT_USER_ATTACHMENT_LIMIT',
'CHAT_USER_ATTACHMENT_MAX_SIZE',
'CHAT_USER_ATTACHMENT_SOURCES',
'CHAT_USER_ATTACHMENT_TYPES',
'_merge_user_attachments_from_terminal_event',
'_normalize_user_attachments',
]
+20 -6
View File
@@ -8,6 +8,7 @@ api/chat/sessions.py
from __future__ import annotations
from .shared import * # noqa: F403
from .shared import _normalize_user_attachments
from . import chat_bp
from .core import (
_chat_logs_for_session,
@@ -194,19 +195,32 @@ def get_chat_messages():
messages = []
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
raw_payload = log.payload if isinstance(log.payload, dict) else {}
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
assistant_payload = {
key: value
for key, value in raw_payload.items()
if key != 'user_attachments'
}
if log.query or user_attachments:
user_msg = {
'role': 'user',
'content': _user_facing_chat_query(log.query or '', agent_code=agent_code),
}
if user_attachments:
user_msg['attachments'] = user_attachments
messages.append(user_msg)
if (
not log.answer
and not log.message_type
and not log.payload
and not assistant_payload
):
continue
if (
log.query
and log.answer == log.query
and (not log.message_type or log.message_type == 'text')
and not log.payload
and not assistant_payload
):
continue
assistant_msg = {
@@ -220,8 +234,8 @@ def get_chat_messages():
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
assistant_msg['payload'] = log.payload
if assistant_payload:
assistant_msg['payload'] = assistant_payload
messages.append(assistant_msg)
return jsonify(messages)
+90
View File
@@ -12,6 +12,7 @@ import ntpath
import posixpath
import tempfile
import os
import re
import subprocess
import uuid
import json
@@ -41,6 +42,95 @@ from app.core.errors import (
)
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
"""
if not isinstance(value, list):
return []
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
basename = re.split(r'[\\/]+', raw_name)[-1]
name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255]
attachment_type = str(item.get('type') or '').strip().lower()
source = str(item.get('source') or '').strip().lower()
if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES:
continue
snapshot = {
'name': name,
'type': attachment_type,
'source': source,
}
extension = str(item.get('extension') or '').strip().lower()
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
snapshot['extension'] = extension
try:
size = int(item.get('size')) if item.get('size') is not None else None
except (TypeError, ValueError):
size = None
if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE:
snapshot['size'] = size
normalized.append(snapshot)
return normalized
def _merge_user_attachments_from_terminal_event(
event_data: dict,
*,
user_id: int,
agent_id: int,
session_id: str,
user_attachments: list[dict],
) -> bool:
"""
在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。
Args:
event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
session_id: 当前 HXOPS 本地会话 ID。
user_attachments: 已完成白名单校验的附件快照。
Returns:
找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。
"""
if not user_attachments:
return False
try:
chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
return False
if chat_log_id <= 0:
return False
from app.services.chat.log_service import merge_chat_log_payload
return merge_chat_log_payload(
chat_log_id=chat_log_id,
user_id=int(user_id or 0),
agent_id=int(agent_id or 0),
session_id=session_id,
payload_patch={'user_attachments': user_attachments},
)
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
-9
View File
@@ -256,15 +256,6 @@ def tool_match_inventory():
resume_gate_code='inventory_matching',
))
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
def tool_submit_decision():
"""
提交人工决策。
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
def tool_confirm_customer():
"""
+1 -1
View File
@@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
+31 -7
View File
@@ -26,8 +26,8 @@ from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNot
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import (
AUTO_CHAIN_FALLBACK,
CP_EXPORT_GENERATED,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
POSITION_EXPORT_GENERATED,
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
)
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
from app.services.shipping_notice.query_service import (
@@ -410,7 +410,7 @@ def workspace_create_shipping_task_from_notice():
task_no=task_id,
)
if not intake.accepted:
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED})
from app.models import ShippingOrderTask
from app.models import ShippingOrderIntake
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
@@ -462,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str):
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
@@ -470,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
# [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段,
# 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。
# [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich;
# 缺省/非法值一律回退 full,保持兼容。
view = str(request.args.get('view', 'full') or 'full').strip().lower()
if view not in ('full', 'workbench'):
view = 'full'
@@ -2331,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
'message': '无需调度自动推进,或任务已离开待推进态',
}
else:
# [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。
position = progress.get('position')
user_mode = progress.get('user_mode')
if not position or not user_mode:
try:
from app.models import ShippingOrderTask
from app.services.shipping_notice.progress_workflow import (
_entry_position,
_entry_user_mode,
)
ot = (
db.session.query(ShippingOrderTask)
.filter(
ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper()
)
.first()
)
if ot is not None:
position = position or _entry_position(ot)
user_mode = user_mode or _entry_user_mode(ot)
except Exception:
pass
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
result['auto_progress'] = {
'status': progress.get('status'),
'message': progress.get('message'),
'enqueue_result': progress.get('enqueue_result'),
'checkpoint': progress.get('checkpoint'),
'position': position,
'user_mode': user_mode,
}
result['confirm_outcome'] = resolve_confirm_outcome(
{
@@ -67,7 +67,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'snapshot_line_ids': list(frozen.get('snapshot_line_ids') or []),
'post_ot_wave': True,
'_orchestrator_internal_dispatch': True,
})
+18 -5
View File
@@ -23,7 +23,7 @@ from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import Session
from app import db
from app.core.errors import ValidationError
from app.core.errors import AppError, NotFoundError, ValidationError
from app.jobs.types import JobType
from app.models import Job
@@ -43,6 +43,19 @@ def _orm_session() -> Session:
return db.session()
def _is_retryable_exc(exc: BaseException) -> bool:
"""按异常类型分级判断任务失败是否可重试(通用裁定,不区分业务域)。
业务 NotFound / AppError.retryable=False(含 ValidationError)视为不可再排队;
仅瞬时基础设施异常(503 ServiceUnavailable 或未归类异常)才允许重试。
"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
def _ensure_outer_dbapi_transaction(session: Session) -> None:
"""
确保 begin_nested() 不会成为数据库最外层事务。
@@ -582,7 +595,7 @@ def recover_stale_jobs(
sibling: Job | None = None
rowcount = 0
if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts:
if snap_attempts < max_attempts:
if _subject_to_parse_queued_unique(str(job.job_type or "")):
try:
sibling = _resolve_safe_supersede_sibling(
@@ -1054,12 +1067,12 @@ def process_next_job(
return True, job_type_value
except Exception as exc:
db.session.rollback()
# 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。
# 其它领域维持既有技术重试策略。
# 失败收口的可重试性由异常类型分级裁定,不按业务域一刀切;
# handler 已自行 fail_job 收敛的绝不应进入此处,此处仅兜底 handler 逃逸的异常。
fail_job(
job_id,
error=str(exc),
retryable=(str(domain or '').strip() != 'shipping_notice'),
retryable=_is_retryable_exc(exc),
owned_attempt=owned_attempt,
)
raise
-2
View File
@@ -70,7 +70,6 @@ from app.models.shipping_order_schema import (
ShippingOrderSchemaVersion,
ShippingSchemaFamily,
)
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
from app.models.shipping_order_snapshot import (
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
@@ -253,7 +252,6 @@ __all__ = [
'ShippingOrderFieldObservation',
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderCustomerMatch',
'ShippingOrderSnapshot',
'ShippingOrderSnapshotLine',
'ShippingOrderReviewEvent',
@@ -1,9 +1,10 @@
"""
backend/app/models/shipping_customer_resolution.py
用途:保存订单候选的客户影子识别结果与人工标签。
用途:保存订单候选的正式客户识别结果、识别证据与人工标签。
依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。
逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。
逻辑:订单候选抽取后幂等刷新识别证据和候选;确认字段独立保存最终客户,
不得以订单中的任一字段(例如 bill_to)充当客户身份真相。
"""
from __future__ import annotations
@@ -11,19 +12,19 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy import CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingCustomerShadowResolution(Base):
"""每个订单候选唯一一条影子识别快照,可追加管理员真值标签。"""
"""每个订单候选唯一一条正式客户识别快照,可追加确认和质量标签。"""
__tablename__ = 'shipping_customer_shadow_resolutions'
__table_args__ = (
CheckConstraint(
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')",
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
name='ck_shipping_customer_shadow_status',
),
Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'),
@@ -56,6 +57,12 @@ class ShippingCustomerShadowResolution(Base):
resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
# 客户确认是识别结果的独立事实;不得覆盖 evidence_json 或原始身份指纹。
confirmed_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
confirmation_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
@@ -1,63 +0,0 @@
"""
backend/app/models/shipping_order_customer_match.py
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
依赖:ShippingOrderExtraction、ShippingCustomer、users。
逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderCustomerMatch(Base):
"""一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。"""
__tablename__ = 'shipping_order_customer_matches'
__table_args__ = (
UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'),
)
id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True,
)
role: Mapped[str] = mapped_column(String(16), nullable=False)
raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), 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)
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
extraction = relationship('ShippingOrderExtraction')
customer = relationship('ShippingCustomer')
site = relationship('ShippingCustomerSite')
@@ -89,10 +89,10 @@ class ShippingNoticeHandler(AgentHandler):
if str(event.get('event') or '') != 'shipping_ui_state':
return None
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
checkpoint = ui_state.get('checkpoint')
return json.dumps({
'task_no': event.get('task_no'),
'checkpoint': checkpoint,
'position': ui_state.get('position'),
'user_mode': ui_state.get('user_mode'),
'updated_at': ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
+5 -4
View File
@@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes(
expires_at=expires_at,
)
# [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
# [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。
# 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session
# 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。
try:
with db.session.begin_nested():
db.session.add(asset)
db.session.flush()
db.session.add(asset)
db.session.flush()
except IntegrityError:
raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
if raced is not None:
@@ -9,9 +9,9 @@
from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 2
ERP_QUERY_CONCURRENCY = 2
ERP_WRITE_CONCURRENCY = 1
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
@@ -2,7 +2,7 @@
services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py
用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_snapshot_line_ids。
逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op;
仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。
"""
@@ -18,7 +18,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import (
)
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
list_eligible_post_ot_line_keys,
list_eligible_post_ot_snapshot_line_ids,
)
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -63,7 +63,7 @@ def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]:
if scanned >= safe_limit:
break
scanned += 1
eligible = list_eligible_post_ot_line_keys(case)
eligible = list_eligible_post_ot_snapshot_line_ids(case)
if not eligible:
skipped += 1
continue
@@ -2,9 +2,11 @@
services/shipping_notice/auto_progress_controller.py
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll,
强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
from __future__ import annotations
@@ -18,18 +20,18 @@ from flask import current_app
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice.tool_common import log_task_event
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled'})
def audit_legacy_forwarded_entrypoint(
*, task: ShippingNotice, action_code: str, actor_id: int | None = None,
*, task: ShippingOrderTask, action_code: str, actor_id: int | None = None,
request_id: str | None = None,
) -> None:
"""记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。"""
@@ -51,9 +53,9 @@ def _utc_now() -> datetime:
return datetime.utcnow()
def _task_is_cancelled(task: ShippingNotice) -> bool:
def _task_is_cancelled(task: ShippingOrderTask) -> bool:
"""根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。"""
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES or str(getattr(task, 'status', '') or '').strip().lower() == 'cancelled'
def _recover_stale_active_job(job: Job) -> bool:
@@ -90,6 +92,17 @@ def _recover_stale_active_job(job: Job) -> bool:
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'technical_failure_present'
gate.updated_at = now
# [FIX] 同一事务内重算 Execution 指针并回写 OT.stage,避免 Gate 已被判为
# blocked_manual 而 execution.status / OT.stage 仍停在上一机械阶段(如 automating)。
execution_id = getattr(gate, 'execution_id', None)
execution = (
db.session.get(ShippingProcessExecution, int(execution_id))
if execution_id is not None else None
)
if execution is not None:
from app.services.shipping_notice.process_gate_service import _refresh_execution_pointers
_refresh_execution_pointers(execution)
db.session.flush()
return True
@@ -111,7 +124,7 @@ def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
def determine_formal_start_gate(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set: Any | None = None,
) -> str:
@@ -126,7 +139,8 @@ def determine_formal_start_gate(
return 'order_freeze_readiness'
# 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史
# Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
customer_status = str((customer_confirmation_facts(task) or {}).get('status') or '').strip().lower()
if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}:
return 'customer_resolution'
# 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。
@@ -139,7 +153,7 @@ def determine_formal_start_gate(
def _create_formal_execution_for_task(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set_id: int | None,
) -> ShippingProcessExecution:
@@ -178,7 +192,7 @@ def _supersede_duplicate_execution(
)
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
def _active_execution_for_task(task: ShippingOrderTask, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
锁定并取得当前唯一活动 Execution。
@@ -235,7 +249,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id)
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
def supersede_auto_progress_for_candidate_refreeze(task: ShippingOrderTask) -> None:
"""
在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。
@@ -309,9 +323,37 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
return None, None
def _auto_retry_blocked(
trigger: str | None,
has_failed_worker_attempt: bool,
resume_gate_code: str | None = None,
) -> bool:
"""[禁止自动重试] 裁决:已存在失败 Worker Attempt 时是否拒绝再入队。
核心逻辑:防止自动/后台 trigger 在外部依赖持续故障时无人值守空转重试;
但用户显式重试(user_retry / user_manual)或带 resume_gate_code 的显式定向推进
(如匹配工具调 run_task_auto_progress,其 trigger 为 tool_api_match_inventory_line
而非 user_retry)应放行,否则点"重新匹配库存"会因 has_failed_worker_attempt
被误拦、报"自动推进已无待处理 Gate"。
Args:
trigger: 触发类型(auto / user_retry / user_manual / worker_takeover / ...)。
has_failed_worker_attempt: 当前 Gate 是否已有带 job_id 的失败 Attempt。
resume_gate_code: 显式定向推进的目标 Gate;有值即视为用户/工具主动恢复,不拦。
Returns:
True 表示应禁止自动再入队;False 表示放行。
"""
user_initiated = str(trigger or '').strip() in {'user_retry', 'user_manual'}
explicit_resume = bool(str(resume_gate_code or '').strip())
return bool(has_failed_worker_attempt) and not user_initiated and not explicit_resume
def submit_auto_progress(
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
*, task: ShippingOrderTask, trigger: str, operator_id: int | None = None,
resume_gate_code: str | None = None, commit: bool = True,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
@@ -319,14 +361,12 @@ def submit_auto_progress(
"""
接收任何自动/用户触发并安全入队当前 Gate。
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
入口只接受 ShippingOrderTask;Execution 与 Gate 始终按 OT 任务身份推进。
"""
# ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN;
# PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。
locked_task = (
ShippingNotice.query
ShippingOrderTask.query
.filter_by(id=int(task.id))
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.first()
)
if locked_task is None:
@@ -373,14 +413,23 @@ def submit_auto_progress(
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
explicit_inventory_retry = (
str(inventory_mode or '').strip() == 'retry_rpa'
and str(resume_gate_code or '').strip() == 'inventory_preparation'
)
db.session.flush()
if not explicit_inventory_retry:
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
)
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = str(execution.current_gate_code or '').strip() or None
current_gate = (
'inventory_preparation'
if explicit_inventory_retry
else str(execution.current_gate_code or '').strip() or None
)
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=current_gate)
@@ -388,6 +437,53 @@ def submit_auto_progress(
.first()
if current_gate else None
)
if explicit_inventory_retry and gate is not None:
# [ROOT CAUSE] 显式 retry_rpa(含行级改源后重抓)必须覆盖残留的
# poll_inventory_preparation / waiting_external。否则只会再入队只读 poll:
# poll 遇到失败 Preparation 会直接收口,既不建新 RPA Attempt 也不写 trigger。
# passed / waiting_external / failed_terminal 一律放开为 blocked_retryable。
from app.services.shipping_notice.process_gate_job_service import (
cancel_inventory_external_wait_polls,
)
cancel_inventory_external_wait_polls(
gate_id=int(gate.id),
reason='显式库存重抓:终止外部等待轮询',
)
# 活动 Attempt 不得被复用;否则 queue_gate_attempt 会因 BUSY 失败,
# 或 active_attempt 早退把「强制重抓」吞成「继续轮询」。
for stale in (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.all()
):
stale.status = 'failed'
stale.error_code = 'superseded_by_explicit_retry'
stale.error_summary = '被显式库存重抓取代'
stale.finished_at = _utc_now()
if stale.job_id:
stale_job = db.session.get(Job, int(stale.job_id))
if stale_job is not None and str(stale_job.status or '') in _ACTIVE_JOB_STATUSES:
stale_job.status = 'cancelled'
stale_job.finished_at = _utc_now()
stale_job.message = '显式库存重抓:取消残留活动 Job'
gate.status = 'blocked_retryable'
gate.passed_at = None
gate.blocking_reason_code = 'inventory_rpa_retry_requested'
gate.next_action_code = 'retry_inventory_preparation'
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.lock_version = int(gate.lock_version) + 1
gate.updated_at = _utc_now()
execution.current_gate_code = 'inventory_preparation'
# 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate
# 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。
execution.responsible_party = 'worker'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.updated_at = _utc_now()
db.session.flush()
active_attempt = (
ShippingProcessGateAttempt.query
.filter(
@@ -398,7 +494,7 @@ def submit_auto_progress(
.first()
if gate is not None else None
)
if active_attempt is not None and active_attempt.job_id:
if active_attempt is not None and active_attempt.job_id and not explicit_inventory_retry:
if commit:
db.session.commit()
return {
@@ -410,6 +506,22 @@ def submit_auto_progress(
'reused': True,
}
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
# [禁止自动重试] 门禁一旦存在“Worker 真实执行失败”的 Attempt(failed 且 job_id 非空),
# 本次自动投递即属重试:任何 trigger(回调/聊天/批处理)都不得再入队,重试必须由
# 用户在当前 Gate 显式发起;否则外部依赖持续故障时,回调/轮询会形成无人值守的
# “失败→重试→再失败”空转环。仅存量内联投影 Attempt(job_id 为空)或无 Attempt
# 的首次投递不受影响,编排初始触发保持不变。
has_failed_worker_attempt = (
gate is not None
and db.session.query(ShippingProcessGateAttempt.id)
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status == 'failed',
ShippingProcessGateAttempt.job_id.isnot(None),
)
.first()
is not None
)
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
@@ -418,6 +530,7 @@ def submit_auto_progress(
if (
gate is not None
and action_code
and not _auto_retry_blocked(trigger, has_failed_worker_attempt, resume_gate_code)
and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code)
and not is_navigation_action(action_code)
and is_technical_gate_party(execution.responsible_party)
@@ -439,6 +552,8 @@ def submit_auto_progress(
'candidate_set_id': candidate_set_id,
'fencing_token': uuid.uuid4().hex,
'trigger': trigger,
'inventory_mode': inventory_mode,
'line_scope_key': line_scope_key,
'recovery_plan_id': recovery_plan_id,
'recovery_attempt_id': recovery_attempt_id,
'resume_after_gate': resume_after_gate,
@@ -2,11 +2,17 @@
services/shipping_notice/chat_actions.py
用途:发货通知聊天只读状态适配。
依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。
依赖:state_machine(位置/用户模式与内部状态迁移)、ui_state。
逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry
from app.services.shipping_notice.state_machine import (
TaskTransition,
apply_task_transition,
position_for_task,
resolve_task_ui_state,
validate_registry,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
@@ -14,19 +20,20 @@ def build_chat_actions_payload(task) -> dict:
"""
构建聊天气泡侧动作按钮兼容 payload。
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 position/user_mode/summary/process_gate;
业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。
Args:
task: ShippingNotice 模型实例。
Returns:
包含 task_no、checkpoint、process_gate、actions 与摘要的字典。
包含 task_no、position、user_mode、process_gate、actions 与摘要的字典。
"""
state = build_task_ui_state(task)
return {
"task_no": state.get("task_no"),
"checkpoint": state.get("checkpoint"),
"position": state.get("position"),
"user_mode": state.get("user_mode"),
"stage": state.get("stage"),
"todo": state.get("todo"),
"actions": state.get("actions"),
@@ -41,7 +48,7 @@ __all__ = [
"TaskTransition",
"apply_task_transition",
"build_chat_actions_payload",
"checkpoint_for_task",
"position_for_task",
"resolve_task_ui_state",
"validate_registry",
]
@@ -1,10 +1,10 @@
"""
services/shipping_notice/constants.py
用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量;
用途:发货通知 API 字段名、位置标签 POSITION_* / review_status / pending_human_reason 的规范常量;
并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。
依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移;
依赖:error_explainability_contract(分层原因码冻结集);state_machine / ui_state 引用 POSITION_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免位置标签漂移;
细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。
"""
@@ -36,28 +36,27 @@ from app.services.shipping_notice.error_explainability_contract import (
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_UPLOAD_REQ = "upload_req"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_CUSTOMER_REVIEW = "customer_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from domain facts)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
CP_ORDER_FREEZE = "order_freeze"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# 位置标签(原 CheckPoint 字面量;非状态机。derive_position / 文案表共用)
POSITION_UPLOAD_REQ = "upload_req"
POSITION_PARSE_OK = "parse_ok" # 转瞬态;新逻辑勿依赖
POSITION_PARSE_REVIEW = "parse_review"
POSITION_CUSTOMER_REVIEW = "customer_review"
POSITION_TASK_EXISTS = "task_exists" # 信息态;新逻辑勿依赖
POSITION_RSV_REQ = "rsv_req"
POSITION_UPLOAD_FAILED = "upload_failed"
POSITION_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
POSITION_WAITING_UPLOAD = "waiting_upload"
POSITION_REJECTED = "rejected"
POSITION_INVENTORY_PENDING = "inventory_pending"
POSITION_READY_MATCH = "ready_to_match"
POSITION_READY_EXPORT = "ready_to_export"
POSITION_EXPORT_READY = "export_ready"
POSITION_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
POSITION_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
POSITION_ORDER_FREEZE = "order_freeze"
POSITION_EXPORT_GENERATED = "export_generated"
POSITION_UPLOADED = "uploaded"
POSITION_COMPLETED = "completed"
# review_status
RS_PARSE_REVIEW = "parse_review"
@@ -68,13 +67,13 @@ RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_RSV_REQ = POSITION_RSV_REQ
PH_SHORTAGE = "shortage"
PH_RPA_EXHAUSTED = "rpa_exhausted"
PH_RPA_PENDING = "rpa_pending"
PH_INV_UNAVAIL = "inv_unavail"
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_NOTICE_TEXT_EXTRACTION_FAILED = POSITION_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
@@ -82,26 +81,26 @@ PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
# 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档)
__all__ = (
'AUTO_CHAIN_FALLBACK',
'CP_UPLOAD_REQ',
'CP_PARSE_OK',
'CP_PARSE_REVIEW',
'CP_CUSTOMER_REVIEW',
'CP_TASK_EXISTS',
'CP_RSV_REQ',
'CP_UPLOAD_FAILED',
'CP_UPLOAD_RESULT_UNKNOWN',
'CP_WAITING_UPLOAD',
'CP_REJECTED',
'CP_INVENTORY_PENDING',
'CP_READY_MATCH',
'CP_READY_EXPORT',
'CP_EXPORT_READY',
'CP_NOTICE_TEXT_EXTRACTION_FAILED',
'CP_INVENTORY_SOURCE_REVIEW',
'CP_ORDER_FREEZE',
'CP_EXPORT_GENERATED',
'CP_UPLOADED',
'CP_COMPLETED',
'POSITION_UPLOAD_REQ',
'POSITION_PARSE_OK',
'POSITION_PARSE_REVIEW',
'POSITION_CUSTOMER_REVIEW',
'POSITION_TASK_EXISTS',
'POSITION_RSV_REQ',
'POSITION_UPLOAD_FAILED',
'POSITION_UPLOAD_RESULT_UNKNOWN',
'POSITION_WAITING_UPLOAD',
'POSITION_REJECTED',
'POSITION_INVENTORY_PENDING',
'POSITION_READY_MATCH',
'POSITION_READY_EXPORT',
'POSITION_EXPORT_READY',
'POSITION_NOTICE_TEXT_EXTRACTION_FAILED',
'POSITION_INVENTORY_SOURCE_REVIEW',
'POSITION_ORDER_FREEZE',
'POSITION_EXPORT_GENERATED',
'POSITION_UPLOADED',
'POSITION_COMPLETED',
'RS_PARSE_REVIEW',
'RS_SHORTAGE_REVIEW',
'RS_RSV_REQ',
@@ -171,7 +171,7 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict
task=task,
message='标准客户尚未确认,请先选择正式客户后再继续。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
forbidden_next_tools=[
'ensure_inventory', 'parse_inventory', 'match_inventory',
@@ -204,7 +204,7 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message='请选择标准客户。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
)
updated = confirm_task_customer(
@@ -1,517 +0,0 @@
"""
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、
tool_common(操作人/生命周期快照)、fulfillment_audit。
逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照,
reject/close/confirm 同步写入 ShippingAuditEvent。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_PARSE_OK,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
adjudicate_and_apply_inventory_source,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
from app.services.shipping_notice.tool_common import (
log_task_action_event,
log_task_event,
merge_tool_payload,
payload_wants_auto_chain_fallback,
resolve_workspace_actor_id,
task_lifecycle_audit_snapshot,
prepend_tool_message,
)
from app.services.shipping_notice.tool_response import tool_response
def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
return _start(task_no)
def _reset_inventory_state_for_forced_rpa(task) -> None:
"""
清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。
【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。
"""
task.inventory_lines_json = None
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。
核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留
(review_status / pending_human_reason / error_message / upload 错误),
避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。
"""
task = kwargs.get('task')
if task is not None:
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
def _prepare_task_for_inventory_reupload(task) -> None:
"""
解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。
【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。
历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。
"""
if task.id is not None:
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all():
link.is_active = False
_reset_inventory_state_for_forced_rpa(task)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate
Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。
Args:
payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
Returns:
dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(
status="failed",
message=t("workflow.decision.task_not_found", lang="zh"),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
actor_id = resolve_workspace_actor_id(payload)
before_snapshot = task_lifecycle_audit_snapshot(task)
# Published parsing profiles are the only production mapping contract.
# Reject legacy task-level mapping decisions instead of reopening a manual
# mapping path that could override the source's configured profile.
if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。",
data=serialize_task_for_tool(task),
)
if decision == "reparse_inventory":
_prepare_task_for_inventory_reupload(task)
log_task_action_event(
task,
"inventory_reupload_requested",
action="reparse_inventory",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
data=serialize_task_for_tool(task),
checkpoint="upload_req",
stop_agent_turn=True,
)
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_rejected",
action="reject",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='reject',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'rejected'},
metadata={'decision': 'reject'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.rejected", lang=lang),
data=serialize_task_for_tool(task),
)
if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_closed",
action="close",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='close',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'closed'},
metadata={'decision': 'close'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.closed", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 2] 处理“确认继续”类决策。
# confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。
if decision in {"confirm", "confirmed", "confirm_parse"}:
if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
data=serialize_task_for_tool(task),
)
if (
decision == "confirm_parse"
or task.review_status == RS_PARSE_REVIEW
or task.pending_human_reason == PH_LOW_CONF
or not match_completed(task)
):
parse_validation = (
(task.step_payload_json or {}).get("parse_validation")
if isinstance(task.step_payload_json, dict)
else None
)
blocking_issues = [
item
for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or []
if isinstance(item, dict) and item.get("severity") == "blocking"
]
if blocking_issues:
return tool_response(
status="needs_human",
task=task,
message="解析结果仍包含不合法的关键字段,请修正后再确认。",
data={**serialize_task_for_tool(task), "parse_validation": parse_validation},
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
# 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
if (
not is_low_confidence_parse_confirm
and (
task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
or not is_inventory_source_stable(task)
)
):
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"parse_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_parse',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
if not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
return tool_response(
status="ok",
task=task,
message="解析内容已确认,请继续选择正式库存源。",
data={
**serialize_task_for_tool(task),
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
if not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.parse_confirmed_running", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="ok",
task=task,
message=t("workflow.decision.parse_confirmed_next", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_matched',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.matched_confirmed", lang=lang),
data=serialize_task_for_tool(task),
)
if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.inventory_preparing", lang=lang),
data=serialize_task_for_tool(task),
)
if task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.fulfillment_running", lang=lang),
data=serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.confirm_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 3] 处理重算型决策。
# retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路,
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
_reset_inventory_state_for_forced_rpa(task)
log_task_event(
task,
"decision_retry_rpa",
{"comment": comment, "force_refresh": True},
actor_id=actor_id,
source=event_source,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_preparation',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
if decision == "rematch":
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_action_event(
task,
"decision_rematch",
action="rematch",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
# flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_from_matching',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
if decision == "reparse":
candidate = (
db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
if task.source_candidate_id else None
)
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
if source_run_id:
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
run = db.session.get(ShippingOrderProcessingRun, source_run_id)
if run is not None:
replacement, reused = reparse_order_extraction_run(
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
)
log_task_action_event(
task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment,
extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused},
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human", task=task,
message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。",
data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no},
checkpoint=task.review_status or "parse_review", stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="needs_human",
task=task,
message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。",
data=serialize_task_for_tool(task),
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
)
@@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy(
dynamic_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
# dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
@@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows(
_absolute_relative_region(bbox, item)
for item in (exclusion_regions or []) if isinstance(item, dict)
]
marker_authorization_exclusions = exclusions
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
# 从而保留管理员配置的普通排除区。
@@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows(
continue
band_indices = {glyph_index for glyph_index, _glyph in band}
marker_indices.update(band_indices)
if exclusions and any(
if marker_authorization_exclusions and any(
_inside_region(glyph.bbox, region)
for _glyph_index, glyph in band
for region in exclusions
for region in marker_authorization_exclusions
):
authorized_marker_indices.update(band_indices)
# [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。
@@ -604,7 +606,8 @@ def reconstruct_coordinate_profile_rows(
# This mode is opt-in per table region. It supports documents whose stable
# columns stay put while optional descriptions move values across visual rows.
if row_reconstruction_mode == 'dynamic_x_columns':
return _reconstruct_dynamic_x_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_dynamic_x_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
if row_reconstruction_mode == 'adaptive_record_columns':
return _reconstruct_adaptive_record_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_adaptive_record_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
relative_y_rows = _reconstruct_relative_y_profile_rows(
@@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows(
schema_fields=schema_fields,
)
if relative_y_rows is not None:
return relative_y_rows
return _resolve_shifted_part_number_candidates(
rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def values_for(
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
@@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows(
current_issues.extend(continuation_issues)
next_offset += 1
flush()
return results if include_deleted else [row for row in results if row.role != 'deleted']
rows = results if include_deleted else [row for row in results if row.role != 'deleted']
return _resolve_shifted_part_number_candidates(
rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def _project_coordinate_profile_regions(
@@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows(
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
values: dict[str, str] = {}
issues: list[str] = []
deleted = any(
_DELETED_PATTERN.fullmatch(re.sub(
r'\s+', '', ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
),
))
for _row_index, band in record
)
for field in fields:
code = str(field['field_code'])
saved = _absolute_relative_region(table_bbox, field['region'])
# [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分,
# 保持 LayoutBBox 的非负原点和正面积契约。
shifted_y0 = max(0.0, saved.y0 + delta_y)
region = LayoutBBox(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
x0=saved.x0, y0=shifted_y0,
x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y),
)
selected_bands = [
band for _row_index, band in record
@@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows(
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _band in record],
role='data', issues=issues,
role='deleted' if deleted else 'data', issues=issues,
))
return results if include_deleted else [row for row in results if row.role != 'deleted']
@@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows(
start_region = _absolute_relative_region(table_bbox, start_field['region'])
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
results: list[CoordinateProfileLogicalRow] = []
sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)]
expected_indices = _calibrate_field_band_indices(
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
)
multiline_fields = {
id(field) for field in fields
if sum(
_regions_overlap_vertically(
_absolute_relative_region(table_bbox, field['region']), _band_bbox(band),
)
for _row_index, band in sample_record
) > 1
}
for anchor_index, start in enumerate(anchors):
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
record = usable_bands[start:end]
@@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
)
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if id(field) not in multiline_fields:
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else ''
if code == 'part_number':
expected_index = expected_indices.get(id(field), 0)
candidates: list[tuple[float, int, str]] = []
for candidate_index in range(expected_index, len(record)):
candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region)
if _is_structured_part_identifier(candidate_raw):
compact_candidate = re.sub(r'\s+', '', candidate_raw)
candidates.append((
_profile_field_band_score(
raw=candidate_raw, field_code=code,
extractor_key=str(field.get('extractor_key') or 'direct'),
),
candidate_index, candidate_raw,
))
if re.search(r'\d', compact_candidate):
candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:])
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
raw = candidates[0][2]
elif len(candidates) > 1:
best = candidates[0]
if best[0] > candidates[1][0] + .25:
raw = best[2]
else:
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
raw = ''
else:
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if not raw:
continue
extracted = extract_profile_field_value(
@@ -1890,6 +1964,112 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
return score
def _is_structured_part_identifier(raw: str) -> bool:
"""仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。"""
value = str(raw or '').strip()
compact = re.sub(r'\s+', '', value)
return bool(
not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE)
and
re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact)
and re.search(r'\d|[._:/-]', compact)
)
def _resolve_shifted_part_number_candidates(
*, rows: list[CoordinateProfileLogicalRow],
glyphs: list[tuple[int, PositionedCharacter]],
ordered_layouts: list[dict[str, Any]],
table_bbox: LayoutBBox,
line_start_field_code: str,
) -> list[CoordinateProfileLogicalRow]:
"""在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前
逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变
没有折行的其他模板。
"""
part_fields = [
field for layout in ordered_layouts
for field in (layout.get('field_regions') or [])
if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number'
and isinstance(field.get('region'), dict)
]
if not part_fields:
return rows
part_start_offset = min(
offset for offset, layout in enumerate(ordered_layouts)
if any(field in (layout.get('field_regions') or []) for field in part_fields)
)
# 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段,
# 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。
if part_start_offset == 0:
return rows
bands = _group_visual_rows(glyphs)
main_fields = ordered_layouts[0].get('field_regions') or []
start_field = next(
(
field for field in main_fields
if isinstance(field, dict)
and str(field.get('field_code') or '') == line_start_field_code
and isinstance(field.get('region'), dict)
),
None,
)
start_region = (
_absolute_relative_region(table_bbox, start_field['region'])
if start_field is not None else None
)
for row_position, row in enumerate(rows):
current = str(row.fields.get('part_number') or '').strip()
if not current or not row.source_row_indices:
continue
record_start = min(row.source_row_indices)
record_end = (
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
if row_position + 1 < len(rows) else len(bands)
)
candidates: list[tuple[float, int, str]] = []
# 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述,
# 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步,
# 因为自适应重建可能已把后续候选 band 一并吸收到当前行。
expected_index = record_start + part_start_offset
scan_start = expected_index
for index in range(scan_start, record_end):
# 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因
# 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。
if index > record_start and start_region is not None:
start_raw = _text_in_horizontal_region(bands[index], start_region)
if is_valid_line_start_value(start_raw):
break
for field in part_fields:
region = _absolute_relative_region(table_bbox, field['region'])
raw = _text_in_horizontal_region(bands[index], region)
if raw.strip() == current:
continue
if not _is_structured_part_identifier(raw):
continue
score = _profile_field_band_score(
raw=raw, field_code='part_number',
extractor_key=str(field.get('extractor_key') or 'direct'),
)
score -= abs(index - expected_index) * .5
if re.search(r'\d', re.sub(r'\s+', '', raw)):
score += .5
candidates.append((score, index, raw))
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
row.fields['part_number'] = candidates[0][2]
elif len(candidates) > 1:
if candidates[0][0] > candidates[1][0] + .25:
row.fields['part_number'] = candidates[0][2]
else:
row.fields.pop('part_number', None)
row.issues.append('coordinate_profile_field_band_ambiguous:part_number')
return rows
def _text_in_region(
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
) -> str:
@@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
# segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。
segment.pop('segment_id', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
@@ -464,10 +464,13 @@ def _map_data_row(
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
return HtmlMappedRow(row_index=row_index, role='repeated_header')
joined = ' '.join(normalized)
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
# 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。
marker_joined = joined.lower()
if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined:
return HtmlMappedRow(row_index=row_index, role='deleted')
first = next((item for item in normalized if item), '')
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
# 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()):
return HtmlMappedRow(row_index=row_index, role='summary')
if _has_explicit_zero_quantity(row, columns=columns):
return HtmlMappedRow(row_index=row_index, role='deleted')
@@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
if not texts:
return False
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
return all(text in markers for text in texts)
# 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。
return all(text.lower() in markers for text in texts)
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
@@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
if field_code == 'reservation_id':
value = validated_reservation_id(text)
return {field_code: value} if value else {}
if field_code == 'uom':
# 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。
stripped = re.sub(r'\d+', '', text).strip()
return {field_code: stripped} if stripped else {}
return {field_code: text}
if extractor_key == 'temp_internal_parts':
resolved = resolve_composite_part_numbers(text)
@@ -1383,6 +1383,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature(
*, band_tokens: list[str], signature: dict[str, Any] | None,
) -> bool:
"""判断冻结表头带读到的 token 是否足以代表签名表头。
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。
"""
expected = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
if not expected or not band_tokens:
return False
observed = [str(token).casefold() for token in band_tokens]
matched = sum(1 for token in expected if token in observed)
return matched / len(expected) >= 0.5
def _observe_primary_table_header(
*,
glyph_tables: dict[str, Any],
@@ -1391,7 +1413,13 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。"""
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
@@ -1419,11 +1447,28 @@ def _observe_primary_table_header(
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
return tokens, centers, widths
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
# 固定带有效 → 直接沿用(对正常模板零影响)。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
candidates = [{
'bbox': primary_bbox,
'header_candidates': _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
),
}]
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
if selected is not None:
header, _ = selected
return (
[str(token).casefold() for token in header['header_tokens']],
header['column_centers'], header['column_width_ratios'],
)
return band_tokens, band_centers, band_widths
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
@@ -14,6 +14,15 @@ from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
LayoutBBox,
_absolute_relative_region,
_group_visual_rows,
_inside_horizontal_region,
_table_glyphs,
_text_in_horizontal_region,
coordinate_profile_character_candidates,
)
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
@@ -84,12 +93,14 @@ def validate_profile_parse_candidate(
fields=header_bound, glyphs=glyphs, page=page,
)
# [STEP 2] Line 字段覆盖
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
line_fields = [
field for table in profile.table_regions for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line'
]
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
line_coverage = _line_region_coverage_shift_tolerant(
profile=profile, glyphs=glyphs, page=page, layout=layout,
)
# [STEP 3] 明细行数启发式
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
@@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None:
return None
def _line_region_coverage_shift_tolerant(
*,
profile: OrderCoordinateProfile,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
layout: dict[str, Any],
) -> dict[str, Any]:
"""按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。
核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体
纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致
``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段
区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。
此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行
做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。
Args:
profile: 当前候选 Profile(含 table_regions)。
glyphs: 当前页冻结坐标字符。
page: 当前页尺寸。
layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。
Returns:
{coverage_ratio, empty_region_count, total_region_count}。
"""
if not profile.table_regions:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
line_fields = [
field for table in profile.table_regions for layout_item in table.line_layouts
for field in layout_item.field_regions if field.scope == 'line'
]
if not line_fields:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
primary_region = next(
(table for table in profile.table_regions if table.line_layouts), None,
)
raw_table = _locate_overlapping_raw_table(
primary_region=primary_region, layout=layout, page=page, profile=profile,
)
width, height = float(page['width']), float(page['height'])
table_region = primary_region.region.model_dump() if primary_region is not None else None
reference_page_frame = _reference_page_frame_mapping(profile, page)
reconstruction_page_bbox = {
'x0': 0.0, 'y0': 0.0,
'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width,
'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height,
}
# 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。
characters, _ = coordinate_profile_character_candidates(
table_region=table_region or {},
page_size=page, reference_page_frame=reference_page_frame,
page_characters=glyphs if isinstance(glyphs, list) else None,
table_characters=(
page_glyph_tables.get(raw_table.get('table_id'))
if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list)
else None
),
raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None),
table_id=(raw_table.get('table_id') if raw_table is not None else None),
page_no=1, coordinate_transform=None, allow_table_fallback=True,
)
if not isinstance(characters, list) or not characters:
return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox)
glyphs_in_table = _table_glyphs(characters, page_bbox)
visual_rows = _group_visual_rows(glyphs_in_table)
non_empty = 0
measurable = 0
for field in line_fields:
relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
if not isinstance(relative, dict):
continue
measurable += 1
absolute = _absolute_relative_region(page_bbox, relative)
if _region_is_covered(visual_rows=visual_rows, region=absolute):
non_empty += 1
total = measurable
return {
'coverage_ratio': non_empty / total if total else 1.0,
'empty_region_count': total - non_empty,
'total_region_count': total,
}
def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None:
"""读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。"""
reference = profile.reference_page_frames.get(1)
if reference is None:
return None
return reference.model_dump() if hasattr(reference, 'model_dump') else reference
def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any:
"""将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。"""
if isinstance(value, LayoutBBox):
return value
return LayoutBBox.model_validate(value)
def _locate_overlapping_raw_table(
*,
primary_region: Any,
layout: dict[str, Any],
page: dict[str, Any],
profile: OrderCoordinateProfile,
) -> dict[str, Any] | None:
"""在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。
命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取,
避免把无物理表的场景误判为已定位到明细表。
"""
if primary_region is None:
return None
reference_page_frame = _reference_page_frame_mapping(profile, page)
width, height = float(page['width']), float(page['height'])
projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width
projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height
if projection_width <= 0 or projection_height <= 0:
return None
relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region
if not isinstance(relative, dict):
return None
try:
absolute_region = {
'x0': float(relative['x0']) * projection_width,
'y0': float(relative['y0']) * projection_height,
'x1': float(relative['x1']) * projection_width,
'y1': float(relative['y1']) * projection_height,
}
except (KeyError, TypeError, ValueError):
return None
best: dict[str, Any] | None = None
best_overlap = 0.0
for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1:
continue
bbox = raw_table.get('bbox')
if not isinstance(bbox, dict):
continue
overlap_x = (
min(float(bbox.get('x1', 0)), absolute_region['x1'])
- max(float(bbox.get('x0', 0)), absolute_region['x0'])
)
overlap_y = (
min(float(bbox.get('y1', 0)), absolute_region['y1'])
- max(float(bbox.get('y0', 0)), absolute_region['y0'])
)
if overlap_x <= 0 or overlap_y <= 0:
continue
overlap_area = overlap_x * overlap_y
if overlap_area > best_overlap:
best_overlap = overlap_area
best = raw_table
return best
def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool:
"""判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。"""
for band in visual_rows:
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
if _text_in_horizontal_region(selected, region).strip():
return True
return False
def _estimate_line_count(
*,
profile: OrderCoordinateProfile,
@@ -48,7 +48,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
upload = 'uploaded'
except Exception:
upload = None
if upload in {'uploaded', 'succeeded', 'success'}:
if upload == 'uploaded':
return 'completed'
return 'active'
+120 -6
View File
@@ -4,6 +4,8 @@ services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
"""
@@ -195,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo
)
def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None:
"""
从表头可写的 Notice 行推导唯一 Warehouse ID。
核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头,
多库位冲突时失败,避免把某一行的库位误写到整单表头。
Args:
notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。
Returns:
唯一非空库位码;全部为空时返回 None。
Raises:
ValueError: 多行存在多个不同库位。
"""
warehouses = {
str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper()
for line in (notice_lines or [])
if str(getattr(line, 'inventory_warehouse_id', None) or '').strip()
}
if len(warehouses) > 1:
raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头')
if len(warehouses) == 1:
return next(iter(warehouses))
return None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
@@ -286,6 +316,50 @@ def _match_text(value: Any) -> str:
return str(value).strip().casefold()
def _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines: list[dict[str, Any]],
*,
inventory_field_keys: list[str],
wanted_keys: set[tuple[str, ...]],
) -> list[dict[str, Any]]:
"""
仅保留与本单导出行 match_keys 命中的库存行。
核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入
逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。
Args:
inventory_lines: 活动库存快照行。
inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。
wanted_keys: 本单导出行规范化后的键元组集合。
Returns:
子集库存行;无候选时为空列表。
"""
if not inventory_lines or not inventory_field_keys or not wanted_keys:
return []
return [
row for row in inventory_lines
if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys
]
def _wanted_order_match_keys(
order_lines: list[dict[str, Any]],
*,
order_field_ids: list[str],
) -> set[tuple[str, ...]]:
"""从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。"""
wanted: set[tuple[str, ...]] = set()
if not order_lines or not order_field_ids:
return wanted
for order_line in order_lines:
key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids)
if all(key):
wanted.add(key)
return wanted
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
@@ -625,8 +699,38 @@ def generate_shipment_excel(
line_values.append(row)
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
# [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part)
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all()
} if match_field_ids else {}
order_field_ids: list[str] = []
inventory_field_keys: list[str] = []
for item in match_keys:
if not isinstance(item, dict):
continue
inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip())
if not inv_key:
continue
order_field_ids.append(str(item.get('order_field_id') or ''))
inventory_field_keys.append(inv_key)
if order_field_ids and inventory_field_keys:
wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids)
inventory_lines = _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines,
inventory_field_keys=inventory_field_keys,
wanted_keys=wanted_keys,
)
release_overrides_by_line = _release_overrides_for_export_lines(
line_values=line_values,
release_overrides_by_source_line=release_overrides_by_source_line,
@@ -679,26 +783,36 @@ def generate_shipment_excel(
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
# [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
header_warehouse_id: str | None = None
header_warehouse_resolved = False
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
# PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。
mapping_warehouse_id = None
if _template_requires_system_warehouse_id([mapping]):
raise ValueError('Warehouse ID 仅可作为发货通知行字段导出,模板不得将其映射为表头')
if not header_warehouse_resolved:
header_warehouse_id = _unique_notice_warehouse_id(notice_lines)
header_warehouse_resolved = True
if not header_warehouse_id:
raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头')
mapping_warehouse_id = header_warehouse_id
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
notice_line_no=None,
notice_line_warehouse_id=None,
notice_line_warehouse_id=mapping_warehouse_id,
field_id_by_code=field_id_by_code,
)
continue
row_count = max(len(line_values), 1)
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
for index in range(row_count):
order_line = line_values[index] if index < len(line_values) else {}
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
@@ -317,3 +317,60 @@ def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[
'warnings': warnings,
'can_publish': not blocked,
}
def _definition_field_code_map(definition: dict[str, Any] | None) -> dict[str, str]:
"""提取版本定义中 field_id → field_code 映射,用于字段语义键跨版本一致性校验。"""
if not isinstance(definition, dict):
return {}
result: dict[str, str] = {}
for item in (definition.get('fields') or []):
if not isinstance(item, dict):
continue
field_id = str(item.get('field_id') or '').strip()
field_code = str(item.get('field_code') or '').strip()
if field_id and field_code:
result[field_id] = field_code
return result
def analyze_published_field_code_changes(
previous_definition: dict[str, Any] | None,
next_definition: dict[str, Any] | None,
) -> dict[str, Any]:
"""
已发布 field_code 不可变门禁:同一 field_id 不应在下一发布版本中更换 field_code。
核心逻辑:只比较上一已发布版本与当前草稿「同一 field_id」的 field_code 是否变化;
同一 field_code 漂移到新 field_id(废弃旧字段 + 新建)属于合法路径,不阻断。
仅在语义键被重命名时阻断,要求走「退役 + 新建」而非原地改名,保证 field_code 是
跨版本稳定引用锚点(供身份识别 resolver 等按语义键匹配)。
Args:
previous_definition: 上一已发布版本 definition;无则视为首次发布,不校验。
next_definition: 即将发布的草稿 definition。
Returns:
含 blocked、changed(field_id / previous_field_code / next_field_code)与
changed_field_ids 的字典;changed 为空时 can_publish=True。
"""
if previous_definition is None:
return {'blocked': False, 'changed': [], 'changed_field_ids': [], 'can_publish': True}
previous_map = _definition_field_code_map(previous_definition)
next_map = _definition_field_code_map(next_definition)
changed: list[dict[str, Any]] = []
for field_id in sorted(set(previous_map) & set(next_map)):
previous_code = previous_map[field_id]
next_code = next_map[field_id]
if previous_code != next_code:
changed.append({
'field_id': field_id,
'previous_field_code': previous_code,
'next_field_code': next_code,
})
return {
'blocked': bool(changed),
'changed': changed,
'changed_field_ids': [item['field_id'] for item in changed],
'can_publish': not changed,
}
@@ -1,15 +1,16 @@
"""
services/shipping_notice/fulfillment_workflow.py
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与自动串联编排。
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
order_task_stage_machine。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload,
由 ProcessGate complete→enqueue 独立 artifact/freight Attempt;遗留非 Gate 路径仅
submit auto_progress(artifact_generation);
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel;
AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警);
开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传;
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认);
RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产;
@@ -29,7 +30,7 @@ from flask import current_app
from app import db
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask
from app.services.shipping_notice.constants import CP_UPLOADED
from app.services.shipping_notice.constants import POSITION_UPLOADED
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
@@ -61,7 +62,6 @@ from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
has_verified_upload_success,
latest_export_artifact,
latest_upload_attempt,
record_manual_upload,
start_rpa_attempt,
)
@@ -140,11 +140,9 @@ def _export_file_name(task: ShippingNotice) -> str | None:
def _upload_status(task: ShippingNotice) -> str | None:
attempt = latest_upload_attempt(task)
if attempt is not None:
return str(attempt.status or '').strip().lower() or None
artifact = _current_export_artifact(task)
return str(artifact.status or '').strip().lower() if artifact is not None else None
"""Notice 面 upload_status:经统一投影,成功只返回 uploaded。"""
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
return project_notice_upload_status(task)
def _cfg_bool(key: str, default: bool = False) -> bool:
@@ -360,7 +358,7 @@ def _reservation_gate_response(
**serialize_task_for_tool(task),
"reservation_id_required": detail,
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
forbidden_next_tools=forbidden_next_tools,
)
@@ -886,7 +884,7 @@ def excel_gate_error(task: ShippingNotice) -> str | None:
)
if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed':
return 'workflow.fulfillment.inventory_preparation_failed'
if _upload_status(task) in {"uploaded", "succeeded", "success"} and _export_file_path(task):
if _upload_status(task) == 'uploaded' and _export_file_path(task):
return None
# 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。
if not match_completed(task) and not exportable_snapshot_line_ids(task):
@@ -913,75 +911,51 @@ def try_auto_chain_after_match(
payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
匹配成功后自动串联 Excel 导出;AUTO_UPLOAD 开启时继续触发货代上传 RPA。
匹配成功后的下游衔接入口(履约编排)。
核心逻辑:match_result 为 ok 后默认自动生成 Excel;
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true 时调用 upload_to_freight(mode=auto);
关闭时停在 wait_manual_upload 待人工登记。
核心逻辑:
- Gate Attempt 路径(``_orchestrator_internal_dispatch=True``):**直接返回**匹配结果,
禁止同 Attempt 内嵌 ``generate_excel`` / ``upload_to_freight``;由
``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 入队独立
``artifact_generation`` / freight Attempt。
- 非 Gate 遗留路径(deprecated):仅 ``run_task_auto_progress(resume_gate_code=
artifact_generation)`` 提交下一 Attempt,仍禁止直跑 generate。
Args:
task: 当前 ShippingNotice。
task: 当前 ShippingNotice / OT。
match_result: match_inventory 的 Tool 响应。
payload: 原始请求体,用于读取 auto_chain_fallback 与 lang 等字段。
payload: 原始请求体;Gate 路径须含 ``_orchestrator_internal_dispatch``。
Returns:
dict[str, Any]: 串联后的 Tool 响应;未触发串联时原样返回 match_result。
dict[str, Any]: 未触发下游时原样返回 match_result;遗留路径返回 auto_progress 响应。
"""
if match_result.get("status") != "ok":
return match_result
# [STEP] Gate Attempt 内禁止跨门禁产物副作用(编排分离契约)。
if isinstance(payload, dict) and payload.get('_orchestrator_internal_dispatch'):
return match_result
if not should_auto_chain_after_match(payload):
return match_result
result = match_result
from app.services.shipping_notice.tool_common import merge_tool_payload
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
# [DEPRECATED] 非 Gate 聊天/Tool 兼容:只提交 artifact Attempt,不直跑 Excel。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
tool_payload = merge_tool_payload(task, payload)
# [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。
if _auto_generate_excel_enabled():
db.session.refresh(task)
if _current_export_artifact(task) is None and excel_gate_error(task) is None:
gen = generate_excel(tool_payload)
if gen.get("status") != "ok":
return gen
result = prepend_tool_message(gen, str(result.get("message") or ""))
# Excel 生成可能刚刚把 OT 物化为正式 Notice;后续上传必须使用 Notice 编号。
from app.services.shipping_notice.query_service import resolve_task_from_payload as _resolve_task
refreshed = _resolve_task({'task_no': task.task_no})
if refreshed is not None:
task = refreshed
tool_payload = merge_tool_payload(task, payload)
# [STEP 2] Excel 就绪后:开启 AUTO_UPLOAD 则触发货代 RPA,否则停待人工上传。
db.session.refresh(task)
ui = resolve_task_ui_state(task)
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
_export_file_path(task) and _upload_status(task) != 'uploaded'
trigger = str((payload or {}).get('source') or (payload or {}).get('trigger') or 'legacy_auto_chain').strip()
actor_raw = (payload or {}).get('operator_id') or (payload or {}).get('actor_id') or (payload or {}).get('_trusted_user_id')
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
str(task.task_no),
trigger=trigger,
expected_version=None,
idempotency_key=str((payload or {}).get('idempotency_key') or '').strip() or None,
resume_gate_code='artifact_generation',
operator_id=operator_id,
)
if excel_ready and _auto_upload_enabled():
upload_result = upload_to_freight({
**tool_payload,
'task_id': task.task_no,
'mode': 'auto',
})
return prepend_tool_message(upload_result, str(result.get('message') or ''))
if excel_ready:
return tool_response(
status="ok",
task=task,
message=str(
result.get("message")
or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。"
),
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
stop_agent_turn=True,
forbidden_next_tools=["upload_to_freight"],
)
return result
def _order_extraction_gate_response(
task: ShippingNotice,
@@ -1078,7 +1052,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
),
'primary_action': build_inventory_candidate_primary_action(),
},
checkpoint='inventory_source_review',
position='inventory_source_review',
stop_agent_turn=True,
)
# ownership & gates
@@ -1123,11 +1097,38 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
task, legacy_payload_lines=parse_inventory_lines(payload),
)
if not inventory_lines:
# 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义)
# 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义);
# 保留 Gate 内部调度标记,并尽量带上该行 source_codes,避免回退成整单 RPA。
inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_no': target_line_no}
if payload.get('_orchestrator_internal_dispatch'):
inv_payload['_orchestrator_internal_dispatch'] = True
scoped_codes = [
str(code).strip().upper()
for code in (payload.get('source_codes') or [])
if str(code).strip()
]
if not scoped_codes:
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
candidate_line = next(
(
line for line in get_active_candidate_lines(task)
if int(getattr(line, 'line_no', 0) or 0) == target_line_no
),
None,
)
scoped_codes = [
str(code).strip().upper()
for code in (getattr(candidate_line, 'source_codes_json', None) or [])
if str(code).strip()
] if candidate_line is not None else []
if scoped_codes:
inv_payload['source_codes'] = scoped_codes
lang_suffix = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
if lang_suffix:
inv_payload["lang"] = lang_suffix
for key in ('operator_id', 'actor_user_id', 'mode'):
if payload.get(key) is not None:
inv_payload[key] = payload.get(key)
return ensure_inventory(inv_payload)
if not is_inventory_source_stable(task):
return tool_response(
@@ -1135,7 +1136,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
task=task,
message="库存源尚未确定,无法执行行级库存匹配。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
position="inventory_source_review",
stop_agent_turn=True,
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
@@ -1294,7 +1295,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
task_id=task.task_no,
message=match_summary,
data=serialize_task_for_tool(task),
checkpoint=f'line_no:{target_line_no}:rematch:ok',
position=f'line_no:{target_line_no}:rematch:ok',
)
return try_auto_chain_after_match(task, match_result, payload=payload)
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
@@ -1324,7 +1325,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
task=task,
message=match_summary,
data=serialize_task_for_tool(task),
checkpoint=f'shortage_review:line_no:{target_line_no}',
position=f'shortage_review:line_no:{target_line_no}',
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
@@ -1655,7 +1656,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message="库存源尚未确定,无法执行库存匹配。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
position="inventory_source_review",
stop_agent_turn=True,
)
@@ -1799,7 +1800,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message=match_summary,
data=serialize_task_for_tool(task),
checkpoint="shortage_review",
position="shortage_review",
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
@@ -2323,7 +2324,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED if has_verified_upload_success(task) else None,
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
)
@@ -2374,7 +2375,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
可选 freight_ref_no、error_message。
Returns:
dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。
dict[str, Any]: 成功时 position=uploaded;失败时 needs_human 并附带 error_message。
"""
lang = resolve_lang(payload)
try:
@@ -2499,7 +2500,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED if has_verified_upload_success(task) else None,
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
)
if completed.status == 'unknown':
@@ -2556,7 +2557,7 @@ def run_auto_progress_fulfillment_steps(
核心逻辑:自动匹配与生成 Excel;AUTO_UPLOAD 开启时触发 upload_to_freight(mode=auto);
关闭时停在 wait_manual_upload 待人工登记。
"""
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
from app.services.shipping_notice.state_machine import resolve_task_ui_state
# [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。
if _auto_match_enabled() and not match_completed(task):
@@ -2573,10 +2574,8 @@ def run_auto_progress_fulfillment_steps(
steps.append("生成发货 Excel")
# [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。
ui = resolve_task_ui_state(task)
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
_export_file_path(task) and _upload_status(task) != 'uploaded'
)
# excel_ready 只读领域产物事实,禁止 UserMode/resolve_task_ui_state 裁决。
excel_ready = bool(_export_file_path(task)) and _upload_status(task) != 'uploaded'
if excel_ready and _auto_upload_enabled():
steps.append("触发货代上传 RPA")
return upload_to_freight({
@@ -2591,7 +2590,7 @@ def run_auto_progress_fulfillment_steps(
task=task,
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
position=resolve_task_ui_state(task).position,
stop_agent_turn=True,
forbidden_next_tools=["upload_to_freight"],
)
@@ -113,6 +113,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
"workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。",
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
"workflow.fulfillment.inventory_preparation_failed": "库存准备失败。请人工重试或上传库存文件后再继续。",
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
"workflow.fulfillment.generate_running": "正在生成发货 Excel",
@@ -238,6 +239,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
"workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.",
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
"workflow.fulfillment.inventory_preparation_failed": "Inventory preparation failed. Retry manually or upload an inventory file before continuing.",
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
"workflow.fulfillment.generate_running": "Generating shipment Excel.",
@@ -363,6 +365,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
"workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก",
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
"workflow.fulfillment.inventory_preparation_failed": "การเตรียมสต็อกล้มเหลว โปรดลองด้วยตนเองหรืออัปโหลดไฟล์สต็อกก่อนดำเนินการต่อ",
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
"workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel",
@@ -3,7 +3,9 @@ services/shipping_notice/inventory_file_store.py
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。
"""
from __future__ import annotations
@@ -141,8 +143,20 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
"""读取任务当前 active link 指向的库存快照。"""
task_id = getattr(task, 'id', None)
"""
读取任务当前 active link 指向的库存快照。
核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入
``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。
Args:
task: OT 或已绑定 ``order_task_id`` 的正式 Notice。
Returns:
当前有效库存文件;无 active Link 时返回 None。
"""
# [STEP] Link 归属 OT:Notice.id 与 OT.id 不同,禁止误用 Notice 主键查 Link。
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
link = (
@@ -214,15 +228,35 @@ def resolve_inventory_lines_for_execution(
legacy_payload_lines: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""
解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。
解析库存匹配与导出的统一运行输入。
核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源
ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File;
否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。
Args:
task: 当前正式发货通知。
task: 当前正式发货通知 / OT。
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
Returns:
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
"""
# [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
from app.services.shipping_notice.stp_line_inventory_match import (
prepare_candidate_inventory_lines,
)
if len(task_frozen_inventory_source_codes(task)) >= 1:
prep = prepare_candidate_inventory_lines(task)
if prep.get('status') == 'ready':
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
if rows:
return rows
# [STEP 2] 单源 / 无冻结:活动 Link 文件是行事实。
if active_inventory_file_for_task(task) is not None:
return active_inventory_lines_for_task(task)
if isinstance(legacy_payload_lines, list):
@@ -3,7 +3,8 @@ services/shipping_notice/inventory_mapping_workflow.py
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析;
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。
"""
from __future__ import annotations
@@ -13,6 +14,7 @@ from typing import Any
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
@@ -36,9 +38,14 @@ def inventory_loaded_response(
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
commit: bool = True,
persist_lines: bool = True,
) -> dict[str, Any]:
"""
写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。
将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。
核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库)
写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
禁止覆盖共享 File 上已有行缓存。
Args:
task: 当前正式发货任务。
@@ -50,13 +57,18 @@ def inventory_loaded_response(
field_mapping: published Profile 的字段映射快照。
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
commit: False 时仅 flush,供批量回调维持外层事务边界。
persist_lines: False 时不写 File.inventory_lines_json(复用路径)。
Returns:
Tool 标准响应;成功后任务可直接进入库存匹配。
"""
inv_file = active_inventory_file_for_task(task)
if inv_file is None:
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
# [STEP] 首次落库写 File;复用只推进状态,避免共享快照被 OT 私有/合并行覆盖。
linked_tasks: list[ShippingNotice] = []
if inv_file:
if persist_lines:
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
inv_file,
inventory_lines,
@@ -65,7 +77,11 @@ def inventory_loaded_response(
mapping_confirmed=True,
)
else:
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
linked_tasks = [
link.task
for link in (inv_file.links or [])
if link.is_active and link.task and _can_relink_inventory(link.task)
]
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
@@ -124,6 +140,7 @@ def inventory_loaded_response(
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
"persist_lines": bool(persist_lines),
},
)
if commit:
@@ -141,5 +158,6 @@ def inventory_loaded_response(
"inventory_row_count": len(inventory_lines),
"field_alignment": field_alignment,
"warnings": warnings or [],
"persist_lines": bool(persist_lines),
},
)
@@ -21,7 +21,7 @@ from typing import Any
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_snapshot_store import (
find_latest_ready_snapshot,
@@ -190,12 +190,14 @@ def _try_reuse_inventory_snapshot(
except (OSError, ValueError, AppError):
lines, column_meta = [], {}
if lines:
# 复用:行缓存已由 read_inventory_file_lines 保证;只 Link + 推进,不覆盖 File。
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="snapshot_reuse",
event_type="inventory_snapshot_reused",
persist_lines=False,
)
db.session.commit()
@@ -338,7 +340,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
task=task,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
@@ -835,7 +837,7 @@ def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None:
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
)
@@ -1114,12 +1116,19 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
return None
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retry: bool = True) -> dict[str, Any]:
def ensure_inventory_via_rpa(
task: ShippingNotice,
*,
mode: str,
allow_auto_retry: bool = True,
source_codes: list[str] | None = None,
) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。
Args:
allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。
poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
manual_retry_round = mode == "retry_rpa"
@@ -1158,7 +1167,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
)
@@ -1176,7 +1185,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
position=POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
@@ -1189,7 +1198,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr
if mode in {'auto', 'retry_rpa'}:
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
prepared = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry)
prepared = ensure_all_required_sources_prepared(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=source_codes,
)
db.session.flush()
if prepared.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
@@ -1299,7 +1313,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr
task=task,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
@@ -1403,7 +1417,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr
task=task,
message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
@@ -1563,7 +1577,7 @@ def _handle_rpa_inventory_skipped(
task=task,
message=message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
@@ -4,6 +4,7 @@ services/shipping_notice/inventory_source_gate.py
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet;
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
"""
@@ -101,10 +102,16 @@ def apply_inventory_source_adjudication(
"""
将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。
核心逻辑:仅 resolved / ambiguous / candidates_frozen 且候选非空时冻结;
unresolved/conflicted/invalid 即使误带候选也不得冻结(防全源兜底污染)。
Args:
execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前
正在执行的门禁链(否则会误 supersede 活动 Execution)。
"""
status = str(adjudication.status or '').strip().lower()
if status not in {'resolved', 'ambiguous', 'candidates_frozen'}:
return
if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)):
freeze_candidates_for_task(
task, adjudication=adjudication, execution_id=execution_id,
@@ -191,8 +198,8 @@ def transition_task_to_inventory_source_review(
"""
将任务持久化到库存源规则重算检查点,并写入候选裁决信息。
核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮;
解析复核必须在进入本检查点前完成,不保存延后复核标记。
核心逻辑:写入 INVENTORY_SOURCE_REVIEW 过渡与 stage,但不产生人工选源按钮;
解析复核必须在进入本阶段前完成,不保存延后复核标记。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -4,7 +4,8 @@ services/shipping_notice/inventory_source_rules.py
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行;
本模块仍负责任务级裁决与快照消歧(履约阶段);Warehouse 由 Source/匹配决定。
行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源;
Warehouse 由 Source/匹配决定。
"""
from __future__ import annotations
@@ -111,7 +112,12 @@ def _from_source(*, status: str, source: dict[str, Any], method: str, context: d
def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication:
"""将规则引擎候选集转换为可执行或待人工确认的裁决。"""
"""
将规则引擎候选集转换为可执行或待人工确认的裁决。
核心逻辑:只保留规则给出且当前仍可用的 Source;unresolved/空候选时 candidates
必须为空,禁止回退到全部启用库存源(否则会错误触发全源 RPA)。
"""
sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))]
evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}]
if result.status == 'resolved' and len(sources) == 1:
@@ -120,7 +126,7 @@ def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySo
status=result.status,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())],
candidates=[_candidate(item) for item in sources],
evidence=evidence,
reason='routing_rule_' + result.status,
)
@@ -235,19 +241,41 @@ def resolve_ambiguous_source_from_ready_snapshots(
def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
"""先评估任务级规则,再在所有订单行一致时接受行级规则结果。"""
"""
先评估任务级规则,再在订单行一致时接受行级规则结果。
核心逻辑:任务级有结论直接用;否则要求各行非 unresolved 且
(status, source_codes) 一致(含 ambiguous 多候选)才采纳行级结果。
仅「各行 resolved 到不同单源」时合并为 ambiguous;不得把 unresolved 扩成全源。
"""
context = extract_routing_context(task)
task_result = evaluate_inventory_source_rules(task=task)
if task_result.status != 'unresolved':
return _result_to_adjudication(task_result, context)
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in _task_routing_lines(task)]
resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1}
if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results):
return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context)
if len(resolved_codes) > 1:
# [STEP] 各行一致的非 unresolved(含 ambiguous)直接采纳,修复 PREFIX 多候选被丢弃。
if line_results and all(item.status != 'unresolved' for item in line_results):
first = line_results[0]
if all(
item.status == first.status and item.source_codes == first.source_codes
for item in line_results
):
return _result_to_adjudication(first, context)
resolved_codes = {
item.source_codes[0]
for item in line_results
if item.status == 'resolved' and len(item.source_codes) == 1
}
if len(resolved_codes) > 1 and all(item.status == 'resolved' for item in line_results):
return InventorySourceAdjudication(
'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes],
'ambiguous',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[
_candidate(item)
for item in list_database_inventory_sources()
if item['source_code'] in resolved_codes
],
reason='line_rules_resolve_different_sources',
)
return _result_to_adjudication(task_result, context)
@@ -2,8 +2,11 @@
services/shipping_notice/inventory_workflow.py
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、动态订单字段。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。
"""
from __future__ import annotations
@@ -15,7 +18,7 @@ from app import db
from app.core.errors import AppError
from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
POSITION_INVENTORY_SOURCE_REVIEW,
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
@@ -52,6 +55,107 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
return None
def _link_ready_candidate_prep_or_block(
task: ShippingOrderTask,
prep: dict[str, Any],
*,
lang: str,
) -> dict[str, Any] | None:
"""
STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human,
禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。
Args:
task: 已冻结候选源的订单任务。
prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。
lang: 文案语言。
Returns:
None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。
"""
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
# [STEP 1] 已绑定则无需重复 link。
if active_inventory_file_for_task(task) is not None:
return None
# [STEP 2] 从候选准备证据解析待绑定快照编号。
file_no = ''
for item in list(prep.get('evidence') or []):
if not isinstance(item, dict):
continue
if str(item.get('status') or '').strip().lower() != 'loaded':
continue
file_no = str(item.get('inventory_file_no') or '').strip()
if file_no:
break
if not file_no:
for row in list(prep.get('lines') or []):
if not isinstance(row, dict):
continue
file_no = str(row.get('__inventory_file_no') or '').strip()
if file_no:
break
inv_file = (
ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first()
if file_no
else None
)
link = None
if inv_file is not None:
link = link_snapshot_to_task(
task,
inv_file,
reason='stp_candidate_prep',
role='owner',
audit_payload={
'candidate_set_id': prep.get('candidate_set_id'),
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
},
)
if link is not None:
db.session.flush()
return None
# [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
step_title='获取库存',
status='needs_human',
message=t('workflow.inventory.unavailable', lang=lang),
progress_percent=0,
detail=t('workflow.inventory.unavailable', lang=lang),
)
log_task_event(
task,
'inventory_candidate_link_failed',
{
'inventory_file_no': file_no or None,
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
'candidate_set_id': prep.get('candidate_set_id'),
},
)
db.session.commit()
return tool_response(
status='needs_human',
task=task,
message=t('workflow.inventory.unavailable', lang=lang),
data={
**serialize_task_for_tool(task),
'blocking_reason': {'code': 'inventory_file_missing'},
'inventory_file_no': file_no or None,
},
)
def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None:
"""
库存入口统一检查订单侧 Reservation ID。
@@ -74,7 +178,7 @@ def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[st
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
forbidden_next_tools=[
"ensure_inventory",
@@ -102,7 +206,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
task=task,
message='订单解析已确认后必须先冻结订单快照,才能进入库存链路。',
data={**serialize_task_for_tool(task), 'error_code': 'SHIPPING.ORDER_SNAPSHOT_REQUIRED'},
checkpoint='order_freeze',
position='order_freeze',
stop_agent_turn=True,
forbidden_next_tools=['ensure_inventory', 'parse_inventory', 'match_inventory', 'generate_shipment_excel'],
)
@@ -143,9 +247,9 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
data={
**serialize_task_for_tool(task),
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
"checkpoint": CP_INVENTORY_SOURCE_REVIEW,
"position": POSITION_INVENTORY_SOURCE_REVIEW,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
position=POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"],
)
@@ -160,7 +264,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str,
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
return None
@@ -291,6 +395,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
resume_gate_code='inventory_preparation',
operator_id=operator_id,
inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto',
line_scope_key=(
str(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
or ''
).strip() or None
),
)
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
@@ -308,6 +420,11 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实,
# 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。
allow_auto_retry = bool(payload.get('allow_auto_retry', True))
scoped_source_codes = [
str(code).strip().upper()
for code in (payload.get('source_codes') or [])
if str(code).strip()
] or None
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
return inventory_loaded_response(
@@ -321,7 +438,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if mode == "retry_rpa":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
return ensure_inventory_via_rpa(
task, mode=mode, source_codes=scoped_source_codes,
)
if mode == "auto":
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
@@ -367,7 +486,12 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
from app.services.shipping_notice.per_source_rpa_service import (
ensure_all_required_sources_prepared,
)
probe = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry)
probe = ensure_all_required_sources_prepared(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=scoped_source_codes,
)
if probe.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
@@ -447,14 +571,17 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
'missing_source_codes': prep.get('missing_source_codes') or [],
},
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
# [STEP] ready 快照复用:先 Link,再只推进状态;不把合并行写进共享 File。
link_block = _link_ready_candidate_prep_or_block(task, prep, lang=lang)
if link_block is not None:
return link_block
return inventory_loaded_response(
task,
list(prep.get('lines') or []),
column_meta={'source': 'stp_candidate_prep'},
source='stp_candidate_prep',
event_type='inventory_candidates_prepared',
persist_lines=False,
)
reused = _try_reuse_inventory_snapshot(
@@ -469,7 +596,12 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 否则任务会错误停在人审且没有可执行的恢复动作。
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode, allow_auto_retry=allow_auto_retry)
return ensure_inventory_via_rpa(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=scoped_source_codes,
)
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
@@ -24,7 +24,7 @@ from app.services.shipping_notice.line_inventory_match_persistence import resolv
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
list_eligible_post_ot_line_keys,
list_eligible_post_ot_snapshot_line_ids,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
@@ -35,7 +35,7 @@ from app.services.shipping_notice.post_ot_wave_progress_service import schedule_
def _mark_auto_fulfill_failed(
case: ShippingOrderReviewCase,
*,
line_keys: list[str],
snapshot_line_ids: list[str],
error_code: str,
message: str,
) -> None:
@@ -46,12 +46,18 @@ def _mark_auto_fulfill_failed(
"""
now = datetime.utcnow()
formal_task_id = getattr(case, 'confirmed_task_id', None)
for key in line_keys:
projection = project_review_case_line_decisions(case)
draft_id_by_snapshot_id = {
str(item.get('snapshot_line_id')): str(item.get('draft_line_id') or '').strip()
for item in list(projection.get('lines') or [])
if isinstance(item, dict) and item.get('snapshot_line_id') is not None
}
for key in snapshot_line_ids:
key_s = str(key)
if formal_task_id is not None:
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True)
.filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True)
.first()
)
if fact is not None:
@@ -67,9 +73,12 @@ def _mark_auto_fulfill_failed(
fact.detail_json = detail
fact.updated_at = now
draft_line_id = draft_id_by_snapshot_id.get(key_s)
if not draft_line_id:
continue
row = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True)
.filter_by(review_case_id=int(case.id), draft_line_id=draft_line_id, is_active=True)
.first()
)
if row is None:
@@ -116,10 +125,10 @@ def coordinate_post_ot_auto_fulfill(
'case_no': case.case_no,
}
eligible = list_eligible_post_ot_line_keys(case)
eligible = list_eligible_post_ot_snapshot_line_ids(case)
projection = project_review_case_line_decisions(case)
unassigned = [
str(item.get('line_key') or '')
str(item.get('snapshot_line_id') or '')
for item in list(projection.get('lines') or [])
if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'}
]
@@ -129,7 +138,7 @@ def coordinate_post_ot_auto_fulfill(
'reason': 'no_eligible_lines',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
'accepted_snapshot_line_ids': [],
}
# [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并,
# 绝不静默替用户决定 Notice 的合并范围。
@@ -139,7 +148,7 @@ def coordinate_post_ot_auto_fulfill(
'reason': 'manual_wave_selection_required',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
'accepted_snapshot_line_ids': [],
}
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
@@ -147,7 +156,7 @@ def coordinate_post_ot_auto_fulfill(
# [STEP 1] 整波创建(失败则整波回滚)
result = create_post_ot_fulfillment_wave(
case_no=str(case.case_no),
line_keys=eligible,
snapshot_line_ids=[int(item) for item in eligible],
decision_source='system',
actor_user_id=None,
reason=f'auto_fulfill:{trigger}',
@@ -157,7 +166,7 @@ def coordinate_post_ot_auto_fulfill(
progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or eligible),
snapshot_line_ids=[int(item) for item in (result.get('accepted_snapshot_line_ids') or eligible)],
review_case_id=int(result.get('review_case_id') or case.id),
idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem_key),
@@ -170,7 +179,7 @@ def coordinate_post_ot_auto_fulfill(
'case_no': case.case_no,
'wave_progress': progress,
**{k: result.get(k) for k in (
'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys',
'task_no', 'wave_no', 'accepted_snapshot_line_ids', 'skipped_snapshot_line_ids',
'idempotency_row_id', 'idempotent_replay',
)},
}
@@ -185,7 +194,7 @@ def coordinate_post_ot_auto_fulfill(
if refreshed is not None:
_mark_auto_fulfill_failed(
refreshed,
line_keys=eligible,
snapshot_line_ids=eligible,
error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED',
message=str(exc)[:1000],
)
@@ -195,7 +204,7 @@ def coordinate_post_ot_auto_fulfill(
'trigger': trigger,
'case_no': case_no_hint,
'error': str(exc)[:500],
'eligible_line_keys': eligible,
'eligible_snapshot_line_ids': eligible,
}
@@ -6,7 +6,8 @@ services/shipping_notice/line_inventory_match_projection.py
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
ready+not_found→available=0;result_missing 不得转 0;
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task 在同一 HTTP 请求内按 task_id memo。
"""
from __future__ import annotations
@@ -415,12 +416,32 @@ def resolve_allowed_actions(
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
"""加载 OT 当前行匹配事实,键为冻结订单行 ID。"""
"""
加载 OT 当前行匹配事实,键为冻结订单行 ID。
同一 HTTP 请求内按 task_id memo,避免 SUMMARY / ui_state / stage_context 重复查库。
"""
if task_id is None:
return {}
key = int(task_id)
try:
from flask import g, has_app_context, has_request_context
if has_app_context() and has_request_context():
cache = getattr(g, '_shipping_match_facts_by_task', None)
if cache is None:
cache = {}
g._shipping_match_facts_by_task = cache
cached = cache.get(key)
if cached is not None:
return cached
else:
cache = None
except Exception:
cache = None
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter_by(task_id=key, is_current=True)
.all()
)
out: dict[int, dict[str, Any]] = {}
@@ -428,6 +449,8 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
if row.snapshot_line_id is None:
continue
out[int(row.snapshot_line_id)] = serialize_match_fact(row)
if cache is not None:
cache[key] = out
return out
@@ -470,6 +493,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'unit': row.unit,
'matching_rule_version': row.matching_rule_version,
'inventory_source_code': row.inventory_source_code,
'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_file_sha256': (
dict(row.detail_json or {}).get('file_sha256')
@@ -15,7 +15,7 @@ def _norm(value: Any) -> str:
return str(value or "").strip()
def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
def _match_identity(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
"""按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。"""
values = tuple(_norm(row.get(field)).casefold() for field in fields)
return values if values and all(values) else None
@@ -27,7 +27,7 @@ def _aggregate_inventory(
"""按用户配置的库存匹配字段组合汇总唯一数量字段。"""
totals: dict[tuple[str, ...], float] = {}
for row in inventory_lines:
key = _line_key(row, match_fields)
key = _match_identity(row, match_fields)
if key is None:
continue
try:
@@ -70,7 +70,7 @@ def match_notice_lines(
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
order_key = _line_key(line, order_fields)
order_key = _match_identity(line, order_fields)
try:
required = float(line.get("__required_qty") or 0)
except (TypeError, ValueError):
@@ -51,7 +51,7 @@ def _post_op(
"200": {
"description": (
"Tool response (status: ok|running|needs_human|failed). "
"May include checkpoint; business buttons are exposed only by ui_state.actions."
"May include position; business buttons are exposed only by ui_state.actions."
),
"content": {
"application/json": {
@@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"paths": {
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态;响应含库存连接器独立字段与候选结构",
"查询任务当前状态;响应含库存源状态与候选结构",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
@@ -94,8 +94,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", "shipping_chat_capability_token"],
description=(
"返回 inventory_source_code、inventory_connector_type、"
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
"返回 inventory_source_code、inventory_warehouse_id、"
"inventory_source_status(unresolved|ambiguous|resolved|"
"candidates_frozen|invalid|conflicted)、inventory_source_method、"
"inventory_source_config_version、inventory_routing_fingerprint、"
"以及 step_payload.inventory_source_resolution.candidates。"
@@ -1,289 +0,0 @@
"""
backend/app/services/shipping_notice/order_customer_matching.py
用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。
依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。
逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
)
from app.services.shipping_notice.customer_normalization import normalize_customer_name
ROLE_FIELDS = {
'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'},
'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'},
}
IDENTITY_RULE_VERSION = 'order-customer-fingerprint.v1'
def _normalized_code(value: Any) -> str:
"""规范外部客户/站点编码,保留业务符号并统一大小写。"""
return str(value or '').strip().upper()
def _identity_fingerprint(*, role: str, raw_name: str, external_code: str, source_system: str) -> tuple[str, dict[str, str]]:
"""用订单原文标准化值和固定规则版本生成稳定身份指纹,不写回或替换原始字段。"""
components = {
'role': role,
'normalized_name': normalize_customer_name(raw_name) if raw_name else '',
'external_code': _normalized_code(external_code),
'source_system': _normalized_code(source_system),
}
encoded = json.dumps(
{'rule_version': IDENTITY_RULE_VERSION, 'components': components},
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(encoded).hexdigest(), components
def _customer_candidates(raw_name: str) -> list[dict[str, Any]]:
"""按标准名称和 approved 名称别名返回稳定去重的启用客户候选。"""
normalized = normalize_customer_name(raw_name)
if not normalized:
return []
customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
for customer in customers:
if normalize_customer_name(customer.standard_name) == normalized:
matched[customer.id] = {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': ['standard_name'],
}
aliases = db.session.query(ShippingCustomerIdentifier).filter_by(
identifier_type='name_alias', normalized_value=normalized, status='approved',
).all()
active_by_id = {customer.id: customer for customer in customers}
for alias in aliases:
customer = active_by_id.get(int(alias.customer_id))
if customer is None:
continue
candidate = matched.setdefault(customer.id, {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': [],
})
if 'name_alias' not in candidate['matched_by']:
candidate['matched_by'].append('name_alias')
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id']))
def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
if code and source:
refs = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source, legacy_customer_key=code,
).all()
candidates = []
for ref in refs:
customer = db.session.get(ShippingCustomer, int(ref.customer_id))
if customer and customer.status == 'active':
candidates.append({
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': None, 'site_name': None,
'site_code': None, 'matched_by': ['external_customer_code'],
})
if candidates:
return candidates
return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)]
def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
matched_site_ids: dict[int, str] = {}
if code:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='external_code', source_system=source, normalized_value=code, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'external_site_code'
for site in sites:
if _normalized_code(site.site_code) == code:
matched_site_ids[site.id] = 'site_code'
if not matched_site_ids:
normalized = normalize_customer_name(raw_name) if raw_name else ''
for site in sites:
if normalized and normalize_customer_name(site.site_name) == normalized:
matched_site_ids[site.id] = 'site_name'
if normalized:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'site_name_alias'
by_id = {site.id: site for site in sites}
for site_id, matched_by in matched_site_ids.items():
site = by_id.get(site_id)
customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None
if site is None or customer is None or customer.status != 'active':
continue
matched[site.id] = {
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name,
'site_code': site.site_code, 'matched_by': [matched_by],
}
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id']))
def refresh_order_customer_matches(
extraction: ShippingOrderExtraction,
header: dict[str, Any],
) -> list[dict[str, Any]]:
"""
根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。
Args:
extraction: 已持久化的动态订单解析记录。
header: 已通过证据裁决的订单头字段投影。
Returns:
两种角色的匹配摘要;客户简称只来自客户主数据快照。
"""
results: list[dict[str, Any]] = []
for role, fields in ROLE_FIELDS.items():
raw_name = str(header.get(fields['name']) or '').strip()
external_code = _normalized_code(header.get(fields['code']))
source_system = _normalized_code(header.get(fields['source']))
fingerprint, components = _identity_fingerprint(
role=role, raw_name=raw_name, external_code=external_code, source_system=source_system,
)
candidates = (
_bill_to_candidates(raw_name, external_code, source_system)
if role == 'bill_to'
else _ship_to_candidates(raw_name, external_code, source_system)
)
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
extraction_id=extraction.id, role=role,
).one_or_none()
if row is None:
row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role)
db.session.add(row)
row.raw_name = raw_name or None
row.normalized_name = normalize_customer_name(raw_name) if raw_name else None
row.source_system = source_system or None
row.external_code = external_code or None
row.identity_fingerprint = fingerprint
row.identity_rule_version = IDENTITY_RULE_VERSION
row.identity_components_json = components
row.candidates_json = candidates
if len(candidates) == 1:
candidate = candidates[0]
row.status = 'unique_candidate'
row.customer_id = int(candidate['customer_id'])
row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None
row.customer_name_snapshot = str(candidate['standard_name'])
row.customer_short_code_snapshot = str(candidate['short_code'])
row.resolution_method = str(candidate['matched_by'][0])
else:
row.status = 'ambiguous' if candidates else 'unmatched'
row.customer_id = None
row.site_id = None
row.customer_name_snapshot = None
row.customer_short_code_snapshot = None
row.resolution_method = None
row.confirmed_by_id = None
row.confirmed_at = None
row.confirmation_reason = None
row.updated_at = datetime.utcnow()
db.session.flush()
results.append(serialize_order_customer_match(row))
return results
def confirm_order_customer_match(
extraction_id: int,
*,
role: str,
customer_id: int,
site_id: int | None = None,
actor_id: int | None,
reason: str,
commit: bool = True,
) -> dict[str, Any]:
"""
人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。
Args:
commit: True 时立即 db.session.commit();False 时仅 flush,由调用方统一控制事务
(用于同事务内追加 reconcile / Job 入队等后续步骤)。
"""
if role not in ROLE_FIELDS:
raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID')
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
extraction_id=extraction_id, role=role,
).one_or_none()
if row is None:
raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND')
reason_value = str(reason or '').strip()
if not reason_value:
raise ValidationError('Customer confirmation reason is required', code='SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE')
selected_site = None
if role == 'ship_to':
selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None
if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active':
raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID')
row.status = 'confirmed'
row.customer_id = customer.id
row.site_id = selected_site.id if selected_site else None
row.customer_name_snapshot = customer.standard_name
row.customer_short_code_snapshot = customer.short_code
row.resolution_method = 'manual'
row.confirmation_reason = reason_value
row.confirmed_by_id = actor_id
row.confirmed_at = datetime.utcnow()
if commit:
db.session.commit()
else:
db.session.flush()
return serialize_order_customer_match(row)
def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]:
"""输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。"""
return {
'id': row.id,
'extraction_id': row.extraction_id,
'role': row.role,
'raw_name': row.raw_name,
'status': row.status,
'customer_id': row.customer_id,
'site_id': row.site_id,
'source_system': row.source_system,
'external_code': row.external_code,
'identity_fingerprint': row.identity_fingerprint,
'identity_rule_version': row.identity_rule_version,
'standard_name': row.customer_name_snapshot,
'short_code': row.customer_short_code_snapshot,
'candidates': list(row.candidates_json or []),
'resolution_method': row.resolution_method,
'confirmation_reason': row.confirmation_reason,
}
@@ -1,10 +1,10 @@
"""
backend/app/services/shipping_notice/order_document_profile_service.py
??????????? Profile ?????????? Run ?????
???ShippingOrderDocumentProfile?????????? Schema ???document_layout.order_profile ????
??????????? field_code ???? field_id?????????? Schema ??????????
???????????????????????? CASCADE ???? 500?
Profile Run
ShippingOrderDocumentProfile Schema document_layout.order_profile
field_code field_id Schema
CASCADE 500?
"""
from __future__ import annotations
@@ -85,7 +85,7 @@ PDF_PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-pdf-preview:'
def _definition_hash(definition: dict[str, Any]) -> str:
"""?? v2 ??????????????????????? 7 ?????"""
""" v2 7 """
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
return hashlib.sha256(encoded).hexdigest()
@@ -102,7 +102,7 @@ def _profile_template_mode(profile: ShippingOrderDocumentProfile) -> str:
def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool:
"""???????????????????????????????????"""
""""""
required = (
sample.layout_version_id,
sample.source_content_hash,
@@ -116,7 +116,7 @@ def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) ->
def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]:
"""????????????????????????"""
""""""
return {
'id': sample.id,
'document_id': sample.document_id,
@@ -139,7 +139,7 @@ def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any
def _profile_frozen_evidence_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
"""???????????????????????????????"""
""""""
samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
total_count = len(samples)
ready_count = sum(1 for item in samples if _sample_frozen_evidence_ready(item))
@@ -200,16 +200,16 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]:
def _normalize_profile_customer_scope(customer_ids: Any) -> list[int] | None:
"""
?????????????????????????????????
Args:
customer_ids: ?????????????????
customer_ids:
Returns:
???????? ID ????????? None?
ID None?
Raises:
ValidationError: ?? ID ???????
ValidationError: ID
"""
if customer_ids is None:
return None
@@ -248,7 +248,7 @@ def _audit(
revision_no: int | None = None,
detail: dict[str, Any] | None = None,
) -> None:
"""?? Profile ?????detail ???????????? checksum ???????"""
""" Profile detail checksum """
db.session.add(ShippingOrderDocumentProfileAudit(
profile_id=profile_id, document_id=document_id, event_type=event_type,
actor_id=actor_id, request_id=str(request_id or '').strip() or None,
@@ -259,14 +259,14 @@ def _audit(
def _refresh_training_sample_count(profile: ShippingOrderDocumentProfile) -> None:
"""?? Profile ????????????????????????"""
""" Profile """
profile.training_sample_count = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=profile.id, sample_role='training',
).count()
def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
"""??????????????????????????????????"""
""""""
adapter_summary = get_value_adapter(definition).definition_audit_summary(definition)
if adapter_summary is not None:
return adapter_summary
@@ -300,7 +300,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDocument:
"""?????? Profile ???????????? ID ???????"""
""" Profile ID """
sample = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=int(profile_id), document_id=int(document_id),
).first()
@@ -362,12 +362,12 @@ def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id:
def _preview_grant_store() -> Any:
"""?????????????? Redis????????????????"""
""" Redis"""
return preview_grant_store()
def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
"""???? Schema ????????????????? field_code?"""
""" Schema field_code?"""
definition = version.definition_json if isinstance(version.definition_json, dict) else {}
result: dict[str, dict[str, Any]] = {}
for raw in definition.get('fields') or []:
@@ -385,7 +385,7 @@ def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, A
def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[str, str], dict[str, Any]]:
"""? ``(scope, field_code)`` ?? Profile ???????????????????"""
"""? ``(scope, field_code)`` Profile """
definition = version.definition_json if isinstance(version.definition_json, dict) else {}
result: dict[str, dict[str, Any]] = {}
for index, raw in enumerate(definition.get('fields') or []):
@@ -425,7 +425,7 @@ def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[st
def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion:
"""????? published/retired Schema??????? Profile ?????"""
""" published/retired Schema Profile """
try:
version_id = int(raw_id)
except (TypeError, ValueError) as exc:
@@ -449,13 +449,13 @@ def _normalize_definition(
preferred_template_mode: str | None = None,
) -> dict[str, Any]:
"""
?? v2 ????????? ID???? HTML ??/??????
v2 ID HTML /
Args:
raw: ????????????????????????????
schema_version: ?????????????????
raw:
schema_version:
Returns:
????? v2 ????????????? Schema ????????
v2 Schema
"""
if not isinstance(raw, dict):
raise ValidationError(
@@ -800,7 +800,7 @@ def _normalize_visual_definition_for_preview(
def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordinateProfile:
"""???????????????? v1 ???? Profile ??????? v2?"""
""" v1 Profile v2?"""
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
return OrderCoordinateProfile(
profile_code=profile.profile_code,
@@ -815,7 +815,7 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina
def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
"""????????? Profile ?? DTO?"""
""" Profile DTO?"""
schema = profile.schema_version
source_profile = profile.source_profile
compatibility = None
@@ -874,7 +874,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
def list_profiles() -> list[dict[str, Any]]:
"""?????????????? Profile?"""
""" Profile?"""
return [payload(item) for item in ShippingOrderDocumentProfile.query.order_by(
ShippingOrderDocumentProfile.profile_code.asc(),
ShippingOrderDocumentProfile.version.desc(),
@@ -882,7 +882,7 @@ def list_profiles() -> list[dict[str, Any]]:
def list_profile_samples(profile_id: int) -> list[dict[str, Any]]:
"""??????????????????????????"""
""""""
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -892,7 +892,7 @@ def list_profile_samples(profile_id: int) -> list[dict[str, Any]]:
def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample) -> str:
"""???????????????????????????????????"""
""""""
explicit = str(sample.table_id or '').strip()
if explicit:
return explicit
@@ -920,7 +920,7 @@ def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sampl
def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
"""???????????????????????? token?????????"""
""" token"""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
try:
@@ -965,7 +965,7 @@ def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | Non
def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> bytes:
"""?????????????? PNG????? PDF?HTML?????????"""
""" PNG PDF?HTML"""
store = _preview_grant_store()
raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}')
try:
@@ -1056,7 +1056,7 @@ def read_pdf_preview(*, token: str, actor_id: int | None) -> bytes:
def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, actor_id: int | None) -> dict[str, Any]:
"""???????????????? bbox?token ID?HTML ????????"""
""" bbox?token ID?HTML """
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
try:
@@ -1085,15 +1085,15 @@ def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, act
def read_preview_page_region_text(
profile_id: int, *, data: dict[str, Any], page_no: int, actor_id: int | None,
) -> dict[str, Any]:
"""????????????????????????-??????
"""-
Args:
profile_id: ??????????????????
data: ??? document_id ????? region???????????????
page_no: ?????????
actor_id: ??????????????????
profile_id:
data: document_id region
page_no:
actor_id:
Returns:
?????????????????????????????????
"""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
@@ -1182,7 +1182,7 @@ def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str:
def preview_profile_region(
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
) -> dict[str, Any]:
"""?????????? v2 ?????????????????????"""
""" v2 """
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
try:
@@ -1288,7 +1288,7 @@ def preview_profile_region(
)
if not isinstance(region_characters, list):
continue
# ??????????????????????????? Schema ???
# Schema
for line_layout in sorted(table_region.line_layouts, key=lambda item: item.row_offset):
for field_region in line_layout.field_regions:
ordered_codes = [field_region.field_code] + [
@@ -1311,16 +1311,16 @@ def preview_profile_region(
termination_rules=[item.model_dump() for item in table_region.termination_rules],
exclusion_regions=reconstruction_exclusions,
dynamic_exclusion_regions=reconstruction_exclusions,
# ?????????????????????????????????
#
include_deleted=not strict,
line_start_field_code=table_region.line_start_field_code,
schema_field_metadata=schema_field_metadata,
)
rows.extend(reconstructed_rows)
# ??????????????????????????????
#
if strict:
rows = [row for row in rows if not getattr(row, 'issues', None)]
# ?????????????? target_fields ???????????????
# target_fields
for row in rows:
for field_code in row.fields:
if field_code not in seen_field_codes:
@@ -1328,12 +1328,12 @@ def preview_profile_region(
involved_field_codes.append(field_code)
schema_field_codes = list(_schema_fields(profile.schema_version))
field_codes = [code for code in schema_field_codes if code in seen_field_codes]
# ??????????? Schema ?????????????? Schema ?????
# Schema Schema
field_codes.extend(code for code in involved_field_codes if code not in schema_field_codes)
result = {
'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0),
'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows],
# ???????????????????????? rows ?????
# rows
'field_codes': field_codes,
'row_roles': (['header'] if field_codes else []) + [row.role for row in rows],
'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows],
@@ -1350,10 +1350,10 @@ def suggest_profile_header(
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
) -> dict[str, Any]:
"""
??????????????????????????????? Schema ?????
Schema
????????????????? Profile??????????????????
?? Profile ?? Schema ?????? PDF/OCR ????????
Profile
Profile Schema PDF/OCR
"""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
@@ -1422,7 +1422,7 @@ def suggest_profile_header(
def generate_profile_ocr_evidence(
profile_id: int, *, document_id: Any, table_id: Any, actor_id: int | None,
) -> dict[str, Any]:
"""??????? PDF ??? OCR ?????????????????????"""
""" PDF OCR """
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
try:
@@ -1442,9 +1442,9 @@ def generate_profile_ocr_evidence(
def _matching_signature_status(profile: ShippingOrderDocumentProfile) -> str:
"""
?????????missing / valid / stale?
missing / valid / stale?
? run_id ? checksum ?? missing???????? valid ? missing?
? run_id ? checksum missing valid ? missing?
"""
if not profile.matching_signature_run_id or not profile.matching_signature_checksum:
return 'missing'
@@ -1459,16 +1459,16 @@ def clear_matching_signature_refs(
reason: str = 'definition_or_sample_changed',
) -> bool:
"""
?? Profile ?????????? ValidationRun ???
Profile ValidationRun
Args:
profile: ?? Profile ???
actor_id: ??????
operation_id: ????? ID?
reason: ??????
profile: Profile
actor_id:
operation_id: ID?
reason:
Returns:
??????????
"""
if not profile.matching_signature_run_id and not profile.matching_signature_checksum:
return False
@@ -1493,7 +1493,7 @@ def clear_matching_signature_refs(
def add_profile_sample(
profile_id: int, *, document_id: Any, table_id: Any, sample_role: Any, actor_id: int | None,
) -> list[dict[str, Any]]:
"""????????????????????????????"""
""""""
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -1537,7 +1537,7 @@ def add_profile_sample(
def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | None) -> list[dict[str, Any]]:
"""?????????????????????????????"""
""""""
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -1561,7 +1561,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No
def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]:
"""?????? Profile ? ready MinerU ??????????/??????"""
""" Profile ? ready MinerU /"""
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
layout = current_layout_snapshot(document) or {}
@@ -1599,7 +1599,7 @@ def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]:
def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion:
"""????????? ready Layout ???????????????????????"""
""" ready Layout """
version = document.current_layout_version
if (
version is None
@@ -1776,7 +1776,7 @@ def require_profile_sample_automark_ready(
def _layout_page_count(payload: dict[str, Any]) -> int | None:
"""????????????? payload ?? pages?????????????"""
""" payload pages"""
pages = payload.get('pages')
if isinstance(pages, list) and pages:
return len([item for item in pages if isinstance(item, dict)])
@@ -1792,7 +1792,7 @@ def _layout_page_count(payload: dict[str, Any]) -> int | None:
def _layout_table_identity_snapshot(payload: dict[str, Any], table_id: str | None) -> dict[str, Any] | None:
"""???????????????????????????????"""
""""""
safe_table_id = str(table_id or '').strip()
if not safe_table_id:
return None
@@ -1819,7 +1819,7 @@ def _profile_sample_coordinate_pages(
profile: ShippingOrderDocumentProfile, *, sample: ShippingOrderDocumentProfileSample,
layout_payload: dict[str, Any],
) -> set[int]:
"""????? definition ????????????"""
""" definition """
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
pages: set[int] = set()
for anchor in (definition.get('document_match') or {}).get('required_anchors') or []:
@@ -1835,7 +1835,7 @@ def _profile_sample_coordinate_pages(
def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: set[int]) -> bool:
"""?? layout ??????????????? table glyph??"""
""" layout table glyph"""
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
@@ -1850,7 +1850,7 @@ def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: s
def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen_at: datetime) -> int:
"""????????????? Layout/Schema/Parser ??????????????"""
""" Layout/Schema/Parser """
from app.services.shipping_notice.document_layout.lifecycle import (
canonical_layout_payload,
ensure_inline_xfa_structure_analysis_identity,
@@ -1955,9 +1955,9 @@ def _freeze_value_adapter_evidence(
def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int:
"""
???????????????? TTL ?????
TTL
? PDF ??? annotation/training ???? mark_asset_referenced?
? PDF annotation/training mark_asset_referenced?
"""
from app.services.file_assets.service import mark_asset_referenced
@@ -1981,7 +1981,7 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int:
def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]:
"""????????????????????????????????????"""
""""""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
characters = tables.get(table_id) if isinstance(tables.get(table_id), list) else []
@@ -1989,7 +1989,7 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s
def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]:
"""??????????????????????????????????"""
""""""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no))
source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no))
@@ -2090,7 +2090,7 @@ def _read_page_ocr_coordinate_evidence(
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]:
"""??????????????????????????????"""
""""""
rows: list[list[dict[str, Any]]] = []
for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))):
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
@@ -2131,14 +2131,14 @@ def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str,
def _anchor_text_key(value: str) -> str:
"""???????????????????????????"""
""""""
return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold()
def _inline_anchor_and_value_regions(
*, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float,
) -> tuple[dict[str, float], dict[str, float], str]:
"""??? bbox ?????????????????????????"""
""" bbox """
label_key = _anchor_text_key(label)
consumed: list[dict[str, Any]] = []
consumed_start = 0
@@ -2218,7 +2218,7 @@ def _inline_anchor_and_value_regions(
def _inline_value_text(*, text: str, label: str) -> str:
"""????????????????????????????? PDF?"""
""" PDF?"""
start = text.casefold().find(label.casefold())
suffix = text[start + len(label):] if start >= 0 else ''
suffix = suffix.lstrip(':? ').strip()
@@ -2230,10 +2230,10 @@ def _generic_order_label_candidates(
*, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float,
table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str,
) -> list[dict[str, Any]]:
"""????? Schema ??? ``LABEL: value`` ????????????"""
""" Schema ``LABEL: value`` """
candidates: list[dict[str, Any]] = []
for line_index, (text, bbox, glyphs) in enumerate(lines):
# ?????????????????? QUALITY/SHIPMENT ???????????
# QUALITY/SHIPMENT
if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18:
continue
match = re.match(r'^\s*([^:?]{2,42}?)[?:]', text)
@@ -2259,14 +2259,14 @@ def _generic_order_label_candidates(
def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
??????? v2 ??????????????????
v2
Args:
data: ???????Schema?????????? ``page_nos``?????????? ``page_no``?
actor_id: ????? ID????????????????????????
data: Schema ``page_nos`` ``page_no``?
actor_id: ID
Returns:
??????????????????????????????????? needs_review?
needs_review?
"""
try:
document_id = int(data.get('document_id'))
@@ -2302,7 +2302,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) ->
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
known_pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_nos = sorted(set(page_nos) | {int(item) for item in known_pages if str(item).isdigit() and int(item) > 0})
# [STEP 1] ????????????????????????????????????
# [STEP 1]
selected_layouts = [
item for item in profile.order_field_layouts
if any(
@@ -2313,7 +2313,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) ->
)
]
selected_profile = profile.model_copy(update={'order_field_layouts': selected_layouts})
# [STEP 2] ?????????????? all_pages ??????????????????
# [STEP 2] all_pages
for selected_page in page_nos:
layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=selected_page)
fields_by_id = {
@@ -2479,10 +2479,10 @@ def suggest_order_field_layouts(
record_audit: bool = True,
) -> dict[str, Any]:
"""
??? Schema ? Header ???????????????????????
Schema ? Header
PDF/OCR Schema
????? PDF/OCR ??????????????? Schema ??????????
??????????????
"""
try:
document_id = int(data.get('document_id'))
@@ -2565,18 +2565,18 @@ def generate_ocr_coordinate_evidence(
persist: bool = True,
) -> dict[str, Any]:
"""
??? PDF ?????????????????????????????? OCR?
PDF OCR?
Args:
document_id: ?????? ID????????? PDF ???
table_id: ??????? MinerU ?? ID?????????
actor_id: ???????? ID?????????
document_id: ID PDF
table_id: MinerU ID
actor_id: ID
force_ocr: True 时即使表内存在部分原生字符也重读渲染外观层;仅用于
视觉行/字段证据不足的受控回退,结果仍标为 ocr_coordinate 且 needs_review。
persist: False 时仅返回内存快照,供统一 automark 的多证据融合;禁止改变
Document 当前 Layout 或令冻结样本失效。
Returns:
??????? ID?source ? pdf ? ocr???????????
ID?source ? pdf ? ocr
"""
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
@@ -2655,13 +2655,13 @@ def generate_ocr_coordinate_evidence(
def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]:
"""
??????????????? PDF ????????????????
PDF
Args:
characters: PDFium ???????????
table_bbox: MinerU ????????????
characters: PDFium
table_bbox: MinerU
Returns:
??????????????????????????? OCR ???
OCR
"""
try:
x0, y0 = float(table_bbox['x0']), float(table_bbox['y0'])
@@ -2681,7 +2681,7 @@ def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str,
def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]:
"""? OCR ??????????????????OCR ????????????"""
"""? OCR OCR """
bbox = table_bbox
result: list[dict[str, Any]] = []
source_index = 0
@@ -2703,7 +2703,7 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) ->
def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]:
"""? OCR ????????????????????????? cell ?????"""
"""? OCR cell """
result: list[dict[str, Any]] = []
source_index = 0
for line in lines:
@@ -2724,7 +2724,7 @@ def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]:
def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict[str, Any]]:
"""??????????????????????????????"""
""""""
if actor_id is None:
return []
safe_limit = max(1, min(int(limit), 100))
@@ -2748,7 +2748,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict
if layout.get('status') != 'ready' or not tables:
continue
content_hash = str(document.content_hash or '').strip().lower()
# ??????????????????/???????????
# /
if content_hash and content_hash in seen_content_hashes:
continue
intake = db.session.get(ShippingOrderIntake, document.intake_id)
@@ -2785,7 +2785,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict
def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None:
"""???????????????????????????????????"""
""""""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
intake = ShippingOrderIntake.query.filter_by(
@@ -2848,7 +2848,7 @@ def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None:
def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]:
"""?????????? PDF/EML ?????? Intake???????????"""
""" PDF/EML Intake"""
if actor_id is None:
raise ValidationError(
'Profile sample requires an administrator identity',
@@ -2866,7 +2866,7 @@ def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, An
def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[str, Any]:
"""?????????????Intake ???????????????"""
"""Intake """
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
intake = ShippingOrderIntake.query.filter_by(
@@ -2913,7 +2913,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
status = 'parsed'
error_code = None
else:
# ???? PDF Document??????? EML / Layout?
# PDF Document EML / Layout?
status = 'parsing'
error_code = None
ready_values = [bool(item.get('automark_ready')) for item in readiness]
@@ -2943,7 +2943,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
def get_sample_tables(document_id: int) -> dict[str, Any]:
"""?????????????????? cell ?????? bbox?????? HTML?"""
""" cell bbox HTML?"""
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None:
raise NotFoundError(
@@ -3064,13 +3064,13 @@ def suggest_coordinate_reconstruction(
data: dict[str, Any], *, actor_id: int | None, layout_snapshot: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
???????????????????????????
Args:
data: document_id?table_id???????? row_offset??? row_offset ???????
actor_id: ????? ID????????????????
data: document_id?table_id row_offset row_offset
actor_id: ID
Returns:
????????????????????????????????????
"""
try:
document_id = int(data.get('document_id'))
@@ -3240,9 +3240,9 @@ def create_draft_from_sample(
operation_id: str | None = None, enforce_lease: bool = False,
) -> dict[str, Any]:
"""
??????? v2 ?????? Profile ???
v2 Profile
?????????????????????? HTML???????????
HTML
"""
try:
document_id = int(data.get('document_id'))
@@ -3259,7 +3259,7 @@ def create_draft_from_sample(
layout = _document_layout(document)
if not isinstance(data.get('definition'), dict):
raise ValidationError('Coordinate template definition is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
# ???????????????????? table/document ???????????
# table/document
if not any(isinstance(item, dict) for item in layout.get('tables') or []):
raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
saved = save_draft({
@@ -3295,21 +3295,21 @@ def save_draft(
enforce_lease: bool = False, commit: bool = True,
) -> dict[str, Any]:
"""
?????????????????????? Revision?
Revision?
Args:
data: ????????? Profile ?????????
actor_id: ????????
profile_id: ??????????????
browser_session_id: ??????????????????
lease_token: ?????????????????
operation_id: ????? Revision ????????
change_source: ????????????? restore?
enforce_lease: ? True ???????????????
commit: ? False ???????????????????????????
data: Profile
actor_id:
profile_id:
browser_session_id:
lease_token:
operation_id: Revision
change_source: restore?
enforce_lease: ? True
commit: ? False
Returns:
??????????? Profile DTO????? Revision ???
Profile DTO Revision
"""
operation = str(operation_id or secrets.token_hex(16)).strip()
profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None
@@ -3521,7 +3521,7 @@ def save_draft(
)
db.session.add(profile)
else:
# ?????????????????????? Revision???????????????
# Revision
if (
profile.structure_fingerprint != definition_checksum
or previous_display_name != next_display_name
@@ -3619,7 +3619,7 @@ def save_draft(
profile_id=profile.id, definition_checksum=profile.structure_fingerprint,
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
revision = retry_revision
# ?????????????????????? Revision???????????????
# Revision
has_effective_change = (
previous_definition is None
or previous_definition != definition
@@ -3628,7 +3628,7 @@ def save_draft(
or change_source == 'restore'
or latest_revision is None
)
# definition ????????????? ValidationRun ?? stale
# definition ValidationRun stale
if previous_definition is not None and previous_definition != definition:
clear_matching_signature_refs(
profile, actor_id=actor_id, operation_id=operation, reason='definition_changed',
@@ -3655,7 +3655,7 @@ def save_draft(
elif revision is None:
revision = latest_revision
if revision is None:
# ??????????????????????????????
#
raise ValidationError('Draft revision could not be created', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
_audit(profile_id=profile.id, event_type='draft_saved', actor_id=actor_id, operation_id=operation,
browser_session_id=str(browser_session_id or '').strip() or None, revision_no=revision.revision_no, detail={
@@ -3683,17 +3683,17 @@ def _resolve_annotation_document(
required: bool,
) -> ShippingOrderDocument | None:
"""
?? XFA ???????/?????
XFA /
Args:
profile: ???? Profile?
data: ?????? sample_document_id?
profile: Profile?
data: sample_document_id?
Returns:
ShippingOrderDocument ???
ShippingOrderDocument
Raises:
NotFoundError / ValidationError: ????????? Profile?
NotFoundError / ValidationError: Profile?
"""
document_id = data.get('sample_document_id')
if document_id not in (None, ''):
@@ -3736,7 +3736,7 @@ def _resolve_annotation_document(
def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""??????????????????????????????????????"""
""""""
source = db.session.get(ShippingOrderDocumentProfile, profile_id)
if source is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -3773,7 +3773,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
profile_id=source.id, sample_role='annotation',
).all()
for sample in annotation_samples:
# ??????? annotation ???? PDF??????????????????????
# annotation PDF
db.session.add(ShippingOrderDocumentProfileSample(
profile_id=clone.id,
document_id=sample.document_id,
@@ -3814,7 +3814,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
def create_schema_migration_draft(
profile_id: int, *, target_schema_version_id: int, resolutions: dict[str, Any], actor_id: int | None,
) -> dict[str, Any]:
"""???? Profile ???????????????????????"""
""" Profile """
source = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if source is None or source.status != 'published':
raise ValidationError(
@@ -4063,7 +4063,7 @@ def create_schema_migration_draft(
def publish(
profile_id: int, *, actor_id: int | None, expected_lock_version: Any, commit: bool = True,
) -> dict[str, Any]:
"""????????????????commit=False ???????????????"""
"""commit=False """
try:
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
if profile is None:
@@ -4099,7 +4099,7 @@ def publish(
'All draft order field layouts must be bound before publish',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
# ?????????/????????????????? manual_confirmation ???
# / manual_confirmation
from app.services.shipping_notice.document_profile_quality_service import (
assert_profile_publishable,
ensure_manual_confirmation_qualification,
@@ -4195,7 +4195,7 @@ def publish(
def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
"""????????????? Run ??????????"""
""" Run """
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -4213,10 +4213,10 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
def delete_draft(profile_id: int) -> None:
"""
???????????????/??????????/???????????
//
?????checksum ?????? profile ???? suites?? suites/auto_freeze
? profile_id ?? DB CASCADE??????????????? IntegrityError 500?
checksum profile suites suites/auto_freeze
? profile_id DB CASCADE IntegrityError 500?
"""
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
if profile is None:
@@ -4226,11 +4226,11 @@ def delete_draft(profile_id: int) -> None:
'Only draft order document profile can be deleted',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED',
)
# [STEP 1] ?????????quality_suite_id ? CASCADE???? suite ???
# [STEP 1] quality_suite_id ? CASCADE suite
ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
profile_id=profile.id,
).delete(synchronize_session=False)
# [STEP 2] ??? Profile ????????? superseded??samples/runs ? ORM cascade
# [STEP 2] Profile supersededsamples/runs ? ORM cascade
suites = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).all()
for suite in suites:
db.session.delete(suite)
@@ -4248,13 +4248,13 @@ def delete_draft(profile_id: int) -> None:
from app.services.file_assets.service import release_asset_reference
release_asset_reference(asset)
# [STEP 4] ???? Profile ????????? DB CASCADE?
# [STEP 4] Profile DB CASCADE?
db.session.delete(profile)
db.session.commit()
def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any]]:
"""???? Schema ??? Profile ?????????? field_id ?????"""
""" Schema Profile field_id """
target_schema = db.session.get(ShippingOrderSchemaVersion, int(schema_version_id))
if target_schema is None or target_schema.status != 'published':
return []
@@ -4334,7 +4334,7 @@ def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any
def _require_sample_document(document_id: int) -> ShippingOrderDocument:
"""? ID ??????????? NotFoundError?"""
"""? ID NotFoundError?"""
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None:
raise NotFoundError(
@@ -4506,12 +4506,18 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
Args:
job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。
"""
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'cancelled'}:
return
if job.status == 'queued' and run.status == 'processing':
transition_order_extraction_run(run, target_status='queued', phase='timeout_retry_queued')
elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'processing'}:
elif (
project_job_status_outcome(getattr(job, 'status', None)) == 'failed'
or str(getattr(job, 'status', None) or '').strip().lower() == 'cancelled'
) and run.status in {'queued', 'processing'}:
if run.status == 'queued':
transition_order_extraction_run(run, target_status='processing', phase='timeout_failing')
transition_order_extraction_run(
@@ -1280,7 +1280,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
candidate.consumed_task_id = int(task.id)
candidate.updated_at = datetime.utcnow()
# The review Case is the explicit human confirmation for this PDF. Do not
# recreate a low-confidence parse checkpoint on the newly materialized Task.
# recreate a low-confidence parse_review disposition on the newly materialized Task.
# [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结
# 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内
# 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。
@@ -12,6 +12,7 @@ backend/app/services/shipping_notice/order_review_projection.py
order_review_fulfillment_decision_service.project_review_case_line_decisions /
build_inventory_issue_fallback、
order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、
lifecycle_projection.project_lifecycle(队列摘要五阶段;禁止 build_task_ui_state)、
order_task_service.resolve_order_task_for_candidate、
schema_edit_policy.list_editable_formal_field_ids、
workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。
@@ -33,6 +34,7 @@ backend/app/services/shipping_notice/order_review_projection.py
普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback);
不返回会话级批量恢复动作;失败由当前 Gate 的具体动作恢复。
WorkflowItem 已关闭时 available_actions 仅保留 view;
会话队列摘要对正式 OT 仅用 project_lifecycle(OT.stage),禁止逐条 build_task_ui_state;
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
"""
@@ -57,6 +59,7 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingTaskInventoryRpaAttempt,
)
@@ -66,6 +69,30 @@ def _safe_filename(value: Any) -> str | None:
return name[:255] or None
def _inventory_rpa_is_running(task: Any) -> bool:
"""仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
自动推进 Job(shipping_notice_run)的 queued/running 只表示阶段推进,
不代表库存 RPA 已创建或正在执行;两者必须隔离,避免把明细行伪装成 acquiring_inventory。
"""
task_no = str(getattr(task, 'task_no', None) or '').strip()
if not task_no:
return False
try:
return (
ShippingTaskInventoryRpaAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
)
.first()
is not None
)
except Exception: # noqa: BLE001
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
return False
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。
@@ -273,6 +300,9 @@ def _project_case_automation_status(
}
# [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
job = None
latest = None
draft = getattr(case, 'current_draft', None)
@@ -325,7 +355,7 @@ def _project_case_automation_status(
'can_build': can_build,
'job_id': int(job.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed':
# 旧 Job(改造前写入)可能没有 retryable;缺失时按失败即停止处理。
result = latest.result_json if isinstance(latest.result_json, dict) else {}
raw_retryable = result.get('retryable')
@@ -356,7 +386,7 @@ def _project_case_automation_status(
'error_code': result.get('error_code') or blocking_reason,
'retry_of_job_id': int(latest.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'succeeded', 'success', 'completed'}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded':
return {
'status': 'completed',
'retryable': False,
@@ -933,10 +963,8 @@ def serialize_review_case(
# [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。
# waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。
auto_status = str((automation or {}).get('status') or '').strip().lower()
inventory_rpa_running = auto_status in {
'processing', 'queued', 'automating', 'running',
}
# 库存 RPA 运行态必须来自逐源 Attempt;阶段自动推进 Job 与库存 RPA 解耦。
inventory_rpa_running = _inventory_rpa_is_running(formal_ot.get('task'))
source_labels: dict[str, str] = {}
if isinstance(validation_snapshot, dict):
raw_labels = validation_snapshot.get('inventory_source_labels') or {}
@@ -1015,6 +1043,38 @@ def serialize_review_case(
}
def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
从会话级批量缓存取当前 Gate 码,供队列 lifecycle 在 OT.stage 为旧 step 码时兜底。
Args:
case: 当前复核 Case。
Returns:
``{'gate_code': ...}`` 或 None(无 Execution / 缓存未就绪时)。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return None
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return None
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
if gate_code:
return {'gate_code': gate_code}
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
for gate in gates:
status = str(getattr(gate, 'status', '') or '').strip().lower()
if status not in {
'blocked_manual', 'blocked_retryable', 'waiting_external', 'running', 'pending',
}:
continue
code = str(getattr(gate, 'gate_code', '') or '').strip().lower()
if code:
return {'gate_code': code}
return None
def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
@@ -1023,7 +1083,11 @@ def _serialize_review_case_summary(
intakes_by_no: dict[str, ShippingOrderIntake] | None = None,
drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None,
) -> dict[str, Any]:
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。
正式 OT 的五阶段:优先 OT.stage → project_lifecycle;旧 step* stage 不在映射表时
用批量缓存的 current Gate 兜底。禁止调用 build_task_ui_state。
"""
draft = (
drafts_by_id.get(int(case.current_draft_id))
if drafts_by_id is not None and case.current_draft_id
@@ -1059,17 +1123,25 @@ def _serialize_review_case_summary(
intake_parse_authorized = False
candidate_is_reviewable = False
if case.confirmed_task_id:
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.ui_state import build_task_ui_state
# 队列摘要只需五阶段 lifecycle;禁止走 build_task_ui_state(会拉 Gate/summary/
# 动作全量,会话多 OT 时 N 倍放大到数秒)。正式 OT 已存在即开放候选上下文入口。
# OT.stage 若仍是历史 step* 码,project_lifecycle 会忽略它并改用 current_gate 兜底。
formal_ot = resolve_formal_ot(case)
if formal_ot.get('has_formal_ot'):
task = formal_ot['task']
confirmed_task_no = str(getattr(task, 'task_no', None) or '').strip() or None
has_formal_ot = True
task_ui_state = build_task_ui_state(task)
lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage)
lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or [])
lifecycle = project_lifecycle(
current_gate=_queue_current_gate_hint(case),
blocking_reason=None,
has_candidate_context=True,
processing_stage=getattr(task, 'stage', None),
)
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or lifecycle_stage)
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
else:
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
@@ -3,13 +3,14 @@ backend/app/services/shipping_notice/order_review_workbench_projection.py
用途:复核工作台 Case 投影的阶段分层辅助——正式 OT 判定、用户态 profile_match、
field_completeness、completed_checks、OT 当前阶段与 automation 责任方;
以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐。
以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐;
另提供 Job.status → 单一 outcome 投影(project_job_status_outcome)。
依赖:ShippingNotice、ShippingOrderReviewCase、Job、order_review_draft_service._current_value、
process_gate_contract、processing_projection_invariants、queue_service 域常量。
逻辑:由 order_review_projection.serialize_review_case / shipping_processing_projection /
order_review_fulfillment_decision_service 调用;不新建状态模型;
project_stage_for_task 与 project_post_ot_automation_from_job 为 Case/Progress 同源;
禁止前端自行拼接里程碑。
Job 成功/失败同义词只在本模块翻译,调用方只判 succeeded/failed。
"""
from __future__ import annotations
@@ -20,6 +21,37 @@ from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderReviewCase, ShippingOrderTask
# Job 库内成功/失败词 → 单一 outcome;仅本模块持有 synonym 袋,禁止外溢。
JOB_FAILURE_STATUS_TOKENS: frozenset[str] = frozenset({'failed', 'dead'})
JOB_SUCCESS_STATUS_TOKENS: frozenset[str] = frozenset({'succeeded', 'success', 'completed'})
def project_job_status_outcome(raw_status: str | None) -> str:
"""将 Job.status 库内词投影为单一 outcome。
核心逻辑:failed/dead → failed;succeeded/success/completed → succeeded;
queued / running|processing 原样归类。调用方只允许 ``== 'failed'`` / ``== 'succeeded'``。
Args:
raw_status: Job.status 原值。
Returns:
failed | succeeded | queued | running | 其它小写透传 | 空串。
"""
status = str(raw_status or '').strip().lower()
if not status:
return ''
if status in JOB_FAILURE_STATUS_TOKENS:
return 'failed'
if status in JOB_SUCCESS_STATUS_TOKENS:
return 'succeeded'
if status == 'queued':
return 'queued'
if status in {'running', 'processing'}:
return 'running'
return status
# 正式 OT 创建后不得再作为「当前人工阻断」的建单前 Gate。
_PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({
'document_materialization',
@@ -547,11 +579,11 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
**_job_fields(active),
}
# [STEP 2] 最近 Job:failed/dead,或 success 但 OT 未推进。
# [STEP 2] 最近 Job:failed,或 succeeded 但 OT 未推进。
if latest is not None:
latest_status = str(latest.status or '').strip().lower()
latest_outcome = project_job_status_outcome(getattr(latest, 'status', None))
fields = _job_fields(latest)
if latest_status in {'failed', 'dead'}:
if latest_outcome == 'failed':
exhausted = _attempts_exhausted(latest)
return {
'status': 'manual_fallback' if exhausted else 'failed',
@@ -562,7 +594,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'reason_code': fields.get('error_code') or 'auto_progress_job_failed',
**fields,
}
if latest_status in {'succeeded', 'success', 'completed'}:
if latest_outcome == 'succeeded':
# Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。
if progress_state in {'', 'not_started'}:
exhausted = _attempts_exhausted(latest)
@@ -663,7 +695,6 @@ def project_stage_for_task(
from app.services.shipping_notice.upload_attempt_service import (
has_verified_upload_success,
latest_export_artifact,
latest_upload_attempt,
)
# 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影
@@ -672,7 +703,6 @@ def project_stage_for_task(
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
verified_upload_success = has_verified_upload_success(task)
raw_upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower()
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
@@ -707,7 +737,8 @@ def project_stage_for_task(
# freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。
if progress_state == 'uploaded':
return _with_label('completed', source='notice_terminal')
if raw_upload_status in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
if project_notice_upload_status(task) == 'uploaded':
return _with_label('freight_uploading', source='upload_success_unverified')
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
@@ -1,105 +0,0 @@
"""
services/shipping_notice/order_schema/derivation_engine.py
用途:执行 Schema 级字段派生规则(首期 copy_if_empty),供模拟与运行时共用。
依赖:field_rules(规则归一化与 line_no 格式)、统一 ValidationError。
逻辑:仅处理启用中的 line→line 规则;目标非空/来源空/格式非法时记录跳过原因;
不写库;调用方负责持久化与审计。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.order_schema.field_rules import (
derivation_rules_checksum,
is_valid_line_no_value,
normalize_derivation_rules,
)
def apply_derivation_rules_to_lines(
lines: list[dict[str, Any]],
rules: list[dict[str, Any]] | None,
*,
locked_targets: set[tuple[int, str]] | None = None,
) -> dict[str, Any]:
"""
对明细行集合执行派生规则,返回派生后行与逐行结果摘要。
核心逻辑:仅启用规则生效;copy_if_empty 仅在目标为空时复制来源;
目标已锁定(人工覆盖)时跳过;来源缺失或目标格式非法时跳过。
Args:
lines: 明细字段字典列表(按行可变副本由本函数新建)。
rules: Schema definition_json.derivation_rules 或草稿规则。
locked_targets: 可选 ``{(line_index, field_code)}`` 人工锁定集合。
Returns:
``{lines, results, rules_checksum, derived_count, skipped_count}``;
``results`` 每项含 line_index、rule_id、status(derived|skipped)、skip_reason、
source/target 前后值。
"""
normalized = normalize_derivation_rules(rules, adopted_line_field_codes=None)
checksum = derivation_rules_checksum(normalized)
enabled = [rule for rule in normalized if rule.get('enabled')]
output_lines = [dict(line) for line in lines]
results: list[dict[str, Any]] = []
locks = locked_targets or set()
for line_index, line in enumerate(output_lines):
for rule in enabled:
source_code = str(rule['source_field_code'])
target_code = str(rule['target_field_code'])
rule_id = str(rule['rule_id'])
before_target = line.get(target_code)
before_source = line.get(source_code)
entry: dict[str, Any] = {
'line_index': line_index,
'rule_id': rule_id,
'source_field_code': source_code,
'target_field_code': target_code,
'strategy': rule['strategy'],
'before_source': before_source,
'before_target': before_target,
'after_target': before_target,
'status': 'skipped',
'skip_reason': None,
}
if (line_index, target_code) in locks:
entry['skip_reason'] = 'manual_override_locked'
results.append(entry)
continue
if before_target not in (None, ''):
entry['skip_reason'] = 'target_not_empty'
results.append(entry)
continue
if before_source in (None, ''):
entry['skip_reason'] = 'source_empty'
results.append(entry)
continue
source_text = str(before_source).strip()
if target_code == 'line_no' and not is_valid_line_no_value(source_text):
entry['skip_reason'] = 'source_format_invalid'
results.append(entry)
continue
if rule['strategy'] != 'copy_if_empty':
entry['skip_reason'] = 'unsupported_strategy'
results.append(entry)
continue
line[target_code] = source_text
entry['after_target'] = source_text
entry['status'] = 'derived'
entry['skip_reason'] = None
results.append(entry)
derived_count = sum(1 for item in results if item['status'] == 'derived')
skipped_count = sum(1 for item in results if item['status'] == 'skipped')
return {
'lines': output_lines,
'results': results,
'rules': normalized,
'rules_checksum': checksum,
'derived_count': derived_count,
'skipped_count': skipped_count,
}
@@ -1,18 +1,15 @@
"""
backend/app/services/shipping_notice/order_schema/field_rules.py
用途:执行冻结订单 Schema 的通用字段归一化、validator,以及 Schema 级字段派生规则契约校验。
用途:执行冻结订单 Schema 的通用字段归一化和 validator。
依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。
逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则;
Header/Line Reservation 均可选,有效值由行优先回退头计算;
单价等字段必须已经由显式视觉框或拆分规则提供单值;derivation_rules 仅允许 line→line。
单价等字段必须已经由显式视觉框或拆分规则提供单值;订单项次由系统按单据内顺序生成。
"""
from __future__ import annotations
import hashlib
import json
import re
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
@@ -20,11 +17,7 @@ from typing import Any
from app.core.errors import ValidationError
from app.services.shipping_notice.reservation_id import validated_reservation_id
# Phase 0/1 派生规则契约常量。
DERIVATION_STRATEGIES = frozenset({'copy_if_empty'})
DERIVATION_ALLOWED_TARGETS = frozenset({'line_no'})
DERIVATION_LINE_NO_PATTERN = re.compile(r'^\d{1,6}$')
DEFAULT_DERIVATION_RULE_ID = 'R-LINE-NO-FROM-CUSTOMER-PO'
# 硬切换后不再提供 Schema 派生规则;订单项次由系统按单据顺序生成。
def compute_effective_reservation_id(
@@ -52,155 +45,6 @@ def compute_effective_reservation_id(
)
def default_derivation_rules() -> list[dict[str, Any]]:
"""
返回新草稿默认派生规则(关闭状态)。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
避免未评审规则自动改写内部项次。
Returns:
可写入 definition_json.derivation_rules 的规则列表。
"""
return [{
'rule_id': DEFAULT_DERIVATION_RULE_ID,
'enabled': False,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
'scope': 'line',
}]
def derivation_rules_checksum(rules: list[dict[str, Any]]) -> str:
"""
计算派生规则稳定校验和,供发布冻结与审计引用。
Args:
rules: 已归一化的派生规则列表。
Returns:
SHA-256 hex 摘要。
"""
payload = json.dumps(rules, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
def normalize_derivation_rules(
value: Any,
*,
adopted_line_field_codes: set[str] | None = None,
) -> list[dict[str, Any]]:
"""
归一化并校验 Schema definition_json.derivation_rules。
核心逻辑:仅允许 line→line;首期策略仅 copy_if_empty;目标仅 line_no;
禁止自引用;同一启用目标只允许一条规则;来源/目标须属于已采用明细字段(若提供)。
Args:
value: 原始 derivation_rules(None 时返回默认关闭预置)。
adopted_line_field_codes: 当前草稿已采用的明细 field_code 集合;None 表示跳过采用检查。
Returns:
归一化后的规则列表。
Raises:
ValidationError: 结构、策略、循环或竞争冲突。
"""
if value is None:
return default_derivation_rules()
if not isinstance(value, list):
raise ValidationError(
'derivation_rules must be a list',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
)
normalized: list[dict[str, Any]] = []
enabled_targets: set[str] = set()
for index, raw in enumerate(value):
if not isinstance(raw, dict):
raise ValidationError(
'derivation rule must be an object',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'index': index},
)
rule_id = str(raw.get('rule_id') or '').strip() or f'R-DERIVE-{index + 1}'
enabled = raw.get('enabled', False)
if not isinstance(enabled, bool):
raise ValidationError(
'derivation rule enabled must be boolean',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
source = str(raw.get('source_field_code') or '').strip()
target = str(raw.get('target_field_code') or '').strip()
strategy = str(raw.get('strategy') or '').strip()
scope = str(raw.get('scope') or 'line').strip()
if scope != 'line':
raise ValidationError(
'derivation rules only allow line scope',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
if strategy not in DERIVATION_STRATEGIES:
raise ValidationError(
'unsupported derivation strategy',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'strategy': strategy},
)
if target not in DERIVATION_ALLOWED_TARGETS:
raise ValidationError(
'derivation target is not allowed in this phase',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'target_field_code': target},
)
if not source or source == target:
raise ValidationError(
'derivation source/target must differ and be non-empty',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
if adopted_line_field_codes is not None:
missing = {code for code in (source, target) if code not in adopted_line_field_codes}
if missing:
raise ValidationError(
'derivation fields must be adopted line fields',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'missing_field_codes': sorted(missing)},
)
if enabled and target in enabled_targets:
raise ValidationError(
'only one enabled derivation rule is allowed per target',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'target_field_code': target},
)
if enabled:
enabled_targets.add(target)
normalized.append({
'rule_id': rule_id,
'enabled': enabled,
'source_field_code': source,
'target_field_code': target,
'strategy': strategy,
'scope': scope,
})
return normalized
def is_valid_line_no_value(value: Any) -> bool:
"""
校验内部项次格式:1–6 位数字,保留前导零。
Args:
value: 候选内部项次。
Returns:
是否符合契约。
"""
if value in (None, ''):
return False
return bool(DERIVATION_LINE_NO_PATTERN.fullmatch(str(value).strip()))
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
@@ -267,8 +111,6 @@ def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool:
field_code = str(config.get('field_code') or '')
if field_code == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value):
return False
if field_code == 'line_no' and value not in (None, '') and not is_valid_line_no_value(value):
return False
for key in config.get('validator_keys') or []:
if key == 'non_empty' and value in (None, ''):
return False
@@ -3,15 +3,15 @@ backend/app/services/shipping_notice/order_schema/runtime.py
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
依赖:订单 Schema 动态模型、standard_field_registry、ShippingOrderDocument、registry、
derivation_engine、audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、
audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、
pdf_priority_adjudication(阶段 2 PDF 优先冲突裁决)。
逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue;
逻辑:提交时先验证原文证据和字段规则并投影;内部项次由系统按行顺序生成;
Observation.source_type 按主 PDF / 其他 PDF / Excel / Word / 正文区分;
跨来源冲突时先尝试 PDF_PRIORITY_FIELD_POLICIES,未命中再回退 prefer_attachment/email;
Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条;
仅 required 或 auto_create_key_field 字段可进入 blocked_fields;
可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单;
必填门禁仅在派生后按最终投影判定;
必填门禁按最终投影判定;
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
"""
@@ -43,13 +43,11 @@ from app.services.shipping_notice.context_fields.runtime import (
canonical_mail_context,
persist_deterministic_context_fields,
)
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
from app.services.shipping_notice.order_schema.field_rules import (
compute_effective_reservation_id,
normalize_order_field_value,
validate_order_field_value,
)
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.pdf_priority_adjudication import choose_pdf_priority_value
@@ -413,11 +411,19 @@ def _verified_email_supplement_observation(
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
"""
只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。
anchor_bbox 仅锚点定位字段携带;模板固定值区字段(无锚点标签)由解析器合法返回
None,其冻结 value_bbox + 字符索引已是完整取值证据,不得因缺锚点丢弃观测,
否则账款客户/地址等固定区头字段永远无法落库,下游客户识别将空转。
"""
anchor_bbox = raw.get('anchor_bbox')
return (
str(raw.get('source') or '') == 'pdf_coordinate'
and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1
and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict)
and (anchor_bbox is None or isinstance(anchor_bbox, dict))
and isinstance(raw.get('value_bbox'), dict)
and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices'])
)
@@ -946,7 +952,7 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -
return result
def _persist_derived_line_field(
'''# Disabled legacy derivation helpers intentionally retained as inert source text.
*,
extraction: ShippingOrderExtraction,
line: ShippingOrderLine,
@@ -1034,7 +1040,6 @@ def _persist_derived_line_field(
'value': payload,
'reason_code': 'derived',
'rule_id': rule_id,
'derivation_rules_checksum': rules_checksum,
'observation_ids': [],
'confidence': 1.0,
}
@@ -1104,6 +1109,7 @@ def _derivation_evidence_refs(
return refs
'''
def persist_dynamic_order(
*,
raw_order: dict[str, Any],
@@ -1132,9 +1138,12 @@ def persist_dynamic_order(
str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or []
if item.get('enabled', True)
}
# line_no 是系统生成且只读的订单项次,不是解析出来的业务字段:不进 llm 字段裁决,
# 不落 FieldValue/Decision,只在 ShippingOrderLine.line_no 与 system_line_projections 体现。
configs = {
field_id: item for field_id, item in all_configs.items()
if item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
and str(item.get('field_code') or '').strip() != 'line_no'
}
context_configs = [
item for item in all_configs.values()
@@ -1196,7 +1205,8 @@ def persist_dynamic_order(
line = ShippingOrderLine(
extraction_id=extraction.id,
position=position,
line_key=str(uuid.uuid4()),
line_no=position + 1,
draft_line_id=str(uuid.uuid4()),
)
db.session.add(line)
db.session.flush()
@@ -1282,79 +1292,19 @@ def persist_dynamic_order(
owning_gate_code='order_field_extraction',
))
# [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。
derivation_outcome = apply_derivation_rules_to_lines(
line_projections,
(version.definition_json or {}).get('derivation_rules'),
)
line_projections = derivation_outcome['lines']
# [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。
field_lineage: list[dict[str, Any]] = []
for item in derivation_outcome['results']:
line_index = int(item['line_index'])
line_obj = extraction.lines[line_index] if line_index < len(extraction.lines) else None
lineage_row = {
'line_key': line_obj.line_key if line_obj is not None else None,
'field_code': item['target_field_code'],
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
'rule_id': item['rule_id'],
'rule_checksum': derivation_outcome['rules_checksum'],
'skip_reason': item.get('skip_reason'),
'before_value': item.get('before_target'),
'after_value': item.get('after_target'),
'source_field_code': item.get('source_field_code'),
'source_value': item.get('before_source'),
}
field_lineage.append(lineage_row)
if item['status'] == 'derived' and line_obj is not None:
target_config = _config_by_line_field_code(all_configs, str(item['target_field_code']))
if target_config is not None and item.get('after_target') not in (None, ''):
decisions.append(_persist_derived_line_field(
extraction=extraction,
line=line_obj,
config=target_config,
value=item.get('after_target'),
rule_id=str(item['rule_id']),
rules_checksum=str(derivation_outcome['rules_checksum']),
))
event_type = 'FIELD_DERIVED' if item['status'] == 'derived' else 'FIELD_DERIVATION_SKIPPED'
evidence_refs = _derivation_evidence_refs(
extraction_id=int(extraction.id),
line_id=int(line_obj.id) if line_obj is not None else None,
source_field_code=str(item.get('source_field_code') or '') or None,
all_configs=all_configs,
)
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_order_extraction',
aggregate_id=str(extraction.id),
intake_no=getattr(intake, 'intake_no', None),
actor_type='system',
actor_id='derivation_engine',
action='derive_line_field',
result='success' if item['status'] == 'derived' else 'ignored',
reason_code=item.get('skip_reason'),
evidence_refs=evidence_refs or None,
metadata={
'rule_id': item['rule_id'],
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
'field_code': item['target_field_code'],
'line_key': lineage_row['line_key'],
'source_field_code': item.get('source_field_code'),
'skip_reason': item.get('skip_reason'),
'schema_version_id': version.id,
},
before={'previous_value': item.get('before_target'), 'value_source': 'machine'},
after={
'new_value': item.get('after_target'),
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
},
)
# [STEP 4] 关键字段完整性仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。
# [STEP 4] 关键字段完整性按最终投影检查。
for config in all_configs.values():
if not field_may_block_process(config):
continue
code = str(config['field_code'])
# line_no 是系统生成且只读的订单项次(写入 ShippingOrderLine.line_no,并经
# system_line_projections 输出);业务行投影不重复携带它,因此不得用“required
# 但业务投影缺失”把这一系统字段误判为缺失阻断。
if code == 'line_no':
continue
missing = False
if config['scope'] == 'header' and code not in header:
missing = True
@@ -1405,11 +1355,12 @@ def persist_dynamic_order(
'blocks_current_action': str(code) in blocking_codes,
})
# 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。
# 行级辅助投影:输出草稿身份、系统项次与有效 Reservation。
system_line_projections: list[dict[str, Any]] = []
for line, projection in zip(extraction.lines, line_projections):
system_line_projections.append({
'line_key': line.line_key,
'draft_line_id': line.draft_line_id,
'line_no': int(line.line_no),
'effective_reservation_id': compute_effective_reservation_id(
line_reservation_id=projection.get('reservation_id'),
header_reservation_id=header.get('reservation_id'),
@@ -1437,7 +1388,6 @@ def persist_dynamic_order(
'header': header,
'lines': line_projections,
'field_lineage': field_lineage,
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
}
extraction.validation_result_json = {
'blocked_fields': blocked_unique,
@@ -1447,19 +1397,16 @@ def persist_dynamic_order(
extraction.status = 'needs_review' if blocked_unique else 'accepted'
extraction.updated_at = datetime.utcnow()
db.session.flush()
customer_matches = refresh_order_customer_matches(extraction, header)
return {
'extraction': extraction,
'header': header,
'lines': line_projections,
'system_line_projections': system_line_projections,
'field_lineage': field_lineage,
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
'blocked_fields': blocked_unique,
'findings': deduped_findings,
'observations': observations,
'decisions': decisions,
'customer_matches': customer_matches,
'auto_create_key_field_thresholds': {
str(item['field_code']): float(item['minimum_confidence'])
for item in all_configs.values()
@@ -3,8 +3,8 @@ backend/app/services/shipping_notice/order_schema/service.py
用途:管理唯一发货订单 Schema 的版本采用/发布与追加式配置审计;字段资产生命周期委托 field_asset_service。
依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、field_rules、registry、统一 AppError。
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、derivation_rules、
task_edit_policy);乐观锁阻止覆盖;发布冻结快照并追加审计事件。
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、task_edit_policy);
乐观锁阻止覆盖;发布冻结快照并追加审计事件。
"""
from __future__ import annotations
@@ -68,12 +68,6 @@ from app.services.shipping_notice.order_schema.registry import (
from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.order_schema.diff import compare_definitions
from app.services.shipping_notice.order_schema.field_rules import (
default_derivation_rules,
derivation_rules_checksum,
normalize_derivation_rules,
)
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
from app.services.shipping_notice.audit_service import append_shipping_audit_event
SCHEMA_CODE = DEFAULT_SCHEMA_FAMILY_CODE
@@ -836,7 +830,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
'raw_llm_output': _copy_json(extraction.raw_llm_output_json),
'normalized_result': _copy_json(extraction.normalized_result_json),
'validation_result': _copy_json(extraction.validation_result_json),
'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines],
'lines': [{'id': row.id, 'position': row.position, 'draft_line_id': row.draft_line_id} for row in lines],
'observations': [
identity(row.field_id) | {
'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id,
@@ -1018,12 +1012,6 @@ def create_draft(
definition if source else None,
fallback=schema.auto_creation_policy_json,
)
# [STEP] 派生规则:复制来源时归一化;全新草稿预置关闭状态的默认规则。
definition['derivation_rules'] = normalize_derivation_rules(
definition.get('derivation_rules') if source else None,
adopted_line_field_codes=None,
)
definition['derivation_rules_checksum'] = derivation_rules_checksum(definition['derivation_rules'])
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=next_version,
@@ -1123,6 +1111,23 @@ def save_draft(
raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
before = _definition(version)
ensure_standard_assets_seeded(actor_id=actor_id)
# line_no 是系统项次字段:调用方无需提交配置,服务端始终将其纳入 Schema。
line_no_asset = ShippingOrderField.query.filter_by(
field_code='line_no', scope='line', asset_kind='system_standard', status='active',
).one()
if not any(
isinstance(item, dict) and str(item.get('field_id') or '') == str(line_no_asset.id)
for item in configs
):
configs = [*configs, {
'field_id': str(line_no_asset.id),
'enabled': True,
'display_name': line_no_asset.display_name_default or '内部项次',
'required': True,
'normalizer_key': 'integer',
'comparator_key': 'integer',
'validator_keys': ['positive_integer'],
}]
seen: set[str] = set()
enabled_purposes: set[str] = set()
normalized_fields: list[dict[str, Any]] = []
@@ -1241,34 +1246,36 @@ def save_draft(
'on_revalidation_failure': sanitized['on_revalidation_failure'],
}
normalized_fields.append(field_entry)
# line_no 是订单项次系统字段:Schema 必须包含且启用为必填,但不得开放人工编辑或派生配置。
line_no_entries = [item for item in normalized_fields if item.get('field_code') == 'line_no' and item.get('scope') == 'line']
if len(line_no_entries) != 1:
raise ValidationError(
'line_no is required exactly once in schema fields',
code='SHIPPING.ORDER_SCHEMA_LINE_NO_REQUIRED',
)
line_no_entry = line_no_entries[0]
line_no_entry['enabled'] = True
line_no_entry['required'] = True
line_no_entry['auto_create_key_field'] = False
line_no_entry['aliases'] = []
line_no_entry['extraction_instruction'] = None
line_no_entry['task_edit_policy'] = {
'editable': False,
'editable_until': None,
'change_effect': 'none',
'on_revalidation_failure': 'block',
}
if 'auto_creation_policy' in data:
auto_creation_policy = _auto_creation_policy(data.get('auto_creation_policy'))
else:
auto_creation_policy = _resolve_auto_creation_policy_for_definition(
before, fallback=version.schema.auto_creation_policy_json,
)
adopted_line_codes = {
str(item.get('field_code'))
for item in normalized_fields
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line'
}
# 保存时未传 derivation_rules 则保留草稿既有规则;缺省时回退关闭预置。
raw_derivation_rules = data['derivation_rules'] if 'derivation_rules' in data else before.get('derivation_rules')
derivation_rules = normalize_derivation_rules(
raw_derivation_rules if raw_derivation_rules is not None else default_derivation_rules(),
adopted_line_field_codes=adopted_line_codes if any(
rule.get('enabled') for rule in (
raw_derivation_rules if isinstance(raw_derivation_rules, list) else default_derivation_rules()
)
) else None,
)
after = {
'schema_code': version.schema.schema_code,
'version': version.version,
'fields': normalized_fields,
'auto_creation_policy': auto_creation_policy,
'derivation_rules': derivation_rules,
'derivation_rules_checksum': derivation_rules_checksum(derivation_rules),
}
compile_table_header_contract(after)
version.definition_json = after
@@ -1334,21 +1341,6 @@ def publish(
enabled_configs = _enabled_fields(definition)
if not enabled_configs:
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
# [STEP] 发布前再次归一化派生规则;启用中的规则要求来源/目标已采用。
adopted_line_codes = {
str(item.get('field_code'))
for item in enabled_configs
if item.get('scope') == 'line' and item.get('field_code')
}
derivation_rules = normalize_derivation_rules(
definition.get('derivation_rules'),
adopted_line_field_codes=adopted_line_codes if any(
isinstance(rule, dict) and rule.get('enabled')
for rule in (definition.get('derivation_rules') or [])
) else None,
)
definition['derivation_rules'] = derivation_rules
definition['derivation_rules_checksum'] = derivation_rules_checksum(derivation_rules)
version.definition_json = definition
included_field_ids = {str(config.get('field_id')) for config in enabled_configs}
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
@@ -1470,134 +1462,11 @@ def simulate_derivation(
actor_id: int | None,
request_id: str | None = None,
) -> dict[str, Any]:
"""
对草稿或已发布 Schema 版本的派生规则做只读样本模拟。
核心逻辑:优先使用请求体 derivation_rules,否则读版本 definition;
lines 可直接提交,或通过 sample_ref=`extraction:<id>` 从历史 Extraction 加载明细投影;
模拟前仅对历史 Extraction 样本剔除规则目标字段,避免已派生结果恒跳过;
手工 JSON 保留目标字段以真实评估 copy_if_empty;
写入 DERIVATION_SIMULATED 审计(不 commit),不改订单。
Args:
version_id: Schema 版本 ID。
data: 含 lines 或 sample_ref(extraction:<id>)、可选 derivation_rules。
actor_id: 管理员 ID。
request_id: 请求追踪 ID。
Returns:
模拟结果摘要与逐行结果。
Raises:
ValidationError: lines / sample_ref 非法。
NotFoundError: 版本或 Extraction 不存在。
"""
from app.models import ShippingOrderExtraction
_, version = _resolve_schema_for_version(version_id)
sample_ref = str(data.get('sample_ref') or '').strip() or None
raw_lines = data.get('lines')
sample_source: dict[str, Any] | None = None
# [STEP] 支持可追溯样本:extraction:<id> → normalized_result_json.lines
# 历史样本可能已含派生后的目标字段;模拟前剔除规则目标,避免 copy_if_empty 恒跳过。
if sample_ref and sample_ref.startswith('extraction:'):
try:
extraction_id = int(sample_ref.split(':', 1)[1])
except (TypeError, ValueError) as exc:
raise ValidationError(
'sample_ref extraction id is invalid',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_INVALID',
) from exc
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None:
raise NotFoundError(
'Derivation sample extraction not found',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_NOT_FOUND',
)
normalized = extraction.normalized_result_json if isinstance(extraction.normalized_result_json, dict) else {}
loaded = list(normalized.get('lines') or [])
if not loaded or any(not isinstance(item, dict) for item in loaded):
raise ValidationError(
'extraction sample has no usable line projections',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_EMPTY',
)
raw_lines = loaded
sample_source = {
'kind': 'extraction',
'extraction_id': int(extraction.id),
'schema_version_id': int(extraction.schema_version_id),
'intake_id': int(extraction.intake_id),
'status': extraction.status,
'targets_stripped_for_simulate': True,
}
if not isinstance(raw_lines, list) or any(not isinstance(item, dict) for item in raw_lines):
raise ValidationError(
'lines must be a list of objects (or provide sample_ref=extraction:<id>)',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SIMULATE_INVALID',
)
definition = _definition(version)
rules = data.get('derivation_rules') if 'derivation_rules' in data else definition.get('derivation_rules')
normalized_rules = normalize_derivation_rules(rules if isinstance(rules, list) else None)
# 仅历史 Extraction 样本剔除目标字段;手工 JSON 保留原值以真实评估 copy_if_empty。
strip_targets = bool(sample_source and sample_source.get('targets_stripped_for_simulate'))
if strip_targets:
target_codes = {
str(rule.get('target_field_code') or '')
for rule in normalized_rules
if rule.get('target_field_code')
}
simulate_lines = []
for line in raw_lines:
cleaned = dict(line)
for code in target_codes:
cleaned.pop(code, None)
simulate_lines.append(cleaned)
else:
simulate_lines = [dict(line) for line in raw_lines]
outcome = apply_derivation_rules_to_lines(simulate_lines, normalized_rules)
append_shipping_audit_event(
event_type='DERIVATION_SIMULATED',
aggregate_type='shipping_order_schema_version',
aggregate_id=str(version.id),
actor_type='admin',
actor_id=actor_id,
request_id=request_id,
action='simulate_derivation',
result='success',
metadata={
'schema_version': version.version,
'schema_version_status': version.status,
'derivation_rules_checksum': outcome['rules_checksum'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'sample_ref': sample_ref,
'sample_source': sample_source,
'line_count': len(raw_lines),
},
after={
'derivation_rules_checksum': outcome['rules_checksum'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'sample_ref': sample_ref,
},
"""派生规则已硬切换下线;项次由系统生成,接口统一返回业务错误。"""
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
# 不在此 commit:由路由层统一提交,便于与样本读取等审计同事务。
return {
'schema_version_id': version.id,
'schema_version': version.version,
'schema_version_status': version.status,
'rules_checksum': outcome['rules_checksum'],
'rules': outcome['rules'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'results': outcome['results'],
'lines_after': outcome['lines'],
'sample_ref': sample_ref,
'sample_source': sample_source,
'mutates_orders': False,
}
def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]:
@@ -1637,4 +1506,4 @@ def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]:
})
if len(items) >= capped:
break
return {'items': items}
return {'items': items}
@@ -18,7 +18,7 @@ from app.core.errors import ValidationError
TABLE_FIELD_CODES = frozenset({
'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number',
'reservation_id', 'part_number', 'product_revision', 'customer_part_number',
'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom',
'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price',
'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate',
@@ -36,10 +36,16 @@ class TableHeaderContract:
def normalize_table_header(value: Any) -> str:
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。"""
# Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
# distinct configured labels, so a permissive match cannot silently bind a column.
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。
Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
distinct configured labels, so a permissive match cannot silently bind a column.
额外把 camelCase 相邻词拆出空格(``manufacturerPN`` -> ``manufacturer PN``),
使真实邮件/PDF 表头 ``manufacturerPN`` 能命中 Schema 的 ``Manufacturer PN`` 别名。
"""
text = unicodedata.normalize('NFKC', str(value or '')).strip()
# 在「小写/数字 后紧接大写」的边界插入空格,处理无分隔符的驼峰表头。
text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", ' ', text)
text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE)
return re.sub(r'[_\s]+', ' ', text).strip()
@@ -474,10 +474,16 @@ def ensure_stp_auto_create_for_case(
),
}
# [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
# [STEP] failed 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
latest = find_latest_stp_job(business_ref=idempotency_key)
retry_of_job_id = None
if latest is not None and str(latest.status or '') in {'failed', 'dead', 'cancelled'}:
latest_status = str(getattr(latest, 'status', None) or '').strip().lower() if latest is not None else ''
if latest is not None and (
project_job_status_outcome(latest_status) == 'failed' or latest_status == 'cancelled'
):
retry_of_job_id = int(latest.id)
elif force_retry and latest is not None:
retry_of_job_id = int(latest.id)
@@ -34,7 +34,7 @@ def schedule_post_ot_wave_progress(
*,
task_no: str,
wave_no: int | None,
line_keys: list[str],
snapshot_line_ids: list[int],
review_case_id: int | None = None,
idempotency_row_id: int | None = None,
request_idempotency_key: str | None = None,
@@ -49,7 +49,7 @@ def schedule_post_ot_wave_progress(
Args:
task_no: 正式 OT 编号。
wave_no: 本波次号;可为 None(仅跳过行时)。
line_keys: 本波行键。
snapshot_line_ids: 本波冻结订单行 ID。
review_case_id: 复核 Case id。
idempotency_row_id: wave 幂等行 id(用于回写 progress_*)。
request_idempotency_key: 原始 wave 请求幂等键。
@@ -61,7 +61,7 @@ def schedule_post_ot_wave_progress(
"""
_ = created_by_id
normalized = str(task_no or '').strip().upper()
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
ids = [int(k) for k in (snapshot_line_ids or [])]
if not normalized:
return {
'auto_progress_started': False,
@@ -69,7 +69,7 @@ def schedule_post_ot_wave_progress(
'reason': 'missing_task_no',
'wave_no': wave_no,
}
if wave_no is None and not keys:
if wave_no is None and not ids:
return {
'auto_progress_started': False,
'status': 'skipped',
@@ -105,7 +105,7 @@ def schedule_post_ot_wave_progress(
{
'task_no': normalized,
'wave_no': int(wave_no) if wave_no is not None else None,
'line_keys': keys,
'snapshot_line_ids': ids,
'review_case_id': int(review_case_id) if review_case_id is not None else None,
'idempotency_row_id': int(idempotency_row_id) if idempotency_row_id is not None else None,
'progress_idempotency_key': progress_key,
@@ -143,7 +143,7 @@ def schedule_post_ot_wave_progress(
'progress_status': 'scheduled' if job_id is not None else 'failed',
'progress_job_id': int(job_id) if job_id is not None else None,
'progress_idempotency_key': progress_key,
'line_keys': keys,
'snapshot_line_ids': ids,
}
@@ -10,7 +10,9 @@ services/shipping_notice/process_gate_bridge.py
co8 后仅按 review_case_id / task_id 创建 Execution,不再依赖 WorkflowItem;
复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details;
确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定;
禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code。
禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code;
建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation
供 ensure_inventory(复用未过期快照或触发 RPA)。
"""
from __future__ import annotations
@@ -21,6 +23,7 @@ import logging
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingOrderReviewCase,
ShippingOrderCandidate,
@@ -964,6 +967,7 @@ def sync_fulfillment_gates_from_task(
按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。
核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果;
建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数;
RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断
manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
@@ -1183,6 +1187,35 @@ def sync_fulfillment_gates_from_task(
force=True,
)
return
# [STEP 2B] 建单后尚无库存事实(derived=created)时,禁止把「未取数」投影成
# inventory_file_empty 失败。应保留 pending 并露出 Worker 动作,由
# submit_auto_progress → ensure_inventory:先复用未过期快照,否则触发 RPA。
if not has_inventory_lines and status == 'created':
prep_gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code='inventory_preparation')
.first()
)
if prep_gate is not None and str(prep_gate.status or '').strip().lower() in {
'pending', 'queued', 'running',
}:
if not str(prep_gate.next_action_code or '').strip():
from app.services.shipping_notice.process_gate_contract import (
primary_next_action_for_gate,
)
prep_gate.next_action_code = (
primary_next_action_for_gate(
gate_code='inventory_preparation',
status='blocked_retryable',
)
or 'retry_inventory_preparation'
)
prep_gate.updated_at = datetime.utcnow()
from app.services.shipping_notice.process_gate_service import (
_refresh_execution_pointers,
)
_refresh_execution_pointers(execution)
return
# 库存准备的成功事实只能是已验证并绑定的库存行。下游状态可能因历史脏数据、
# 并发投影或错误侧路动作残留,绝不能反向证明库存文件已经准备完成。
inv_prep_passed = has_inventory_lines
@@ -3,12 +3,14 @@ services/shipping_notice/process_gate_contract.py
用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、
阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格;
以及 Gate→粗分类/位置/待办(derive_*);
作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。
依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用;
细粒度错误可解释性分层码见 error_explainability_contract。
逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码;
同一根因只允许一个 owning_gate 产生用户阻断 Finding;
单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层。
单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层;
derive_user_mode / derive_position / derive_todo_category 供进度早停、待办与摘要消费。
"""
from __future__ import annotations
@@ -1306,6 +1308,89 @@ def user_mode_for_blocking_reason(reason_code: str | None) -> str | None:
return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip())
# review_status 人工复核处置 → must_human(在 auto_continue 默认之前)
_REVIEW_STATUS_MUST_HUMAN: Final[frozenset[str]] = frozenset({
'parse_review',
'rsv_req',
'quality_issue',
'customer_review',
'shortage_review',
})
def derive_user_mode(
*,
user_status: str | None,
gate_code: str | None,
review_status: str | None,
lifecycle_stage: str | None,
) -> str:
"""
粗分类(auto_continue / must_human / wait_manual_upload / complete)。
用途:从 Gate user_status/gate_code 与 review_status 推导用户模式;不投影领域标量。
核心逻辑:rejected→complete;复核处置(parse_review/rsv_req/quality_issue/
customer_review/shortage_review)→must_human;再按 Gate/user_status 分支。
"""
rs = str(review_status or '').strip()
if rs == 'rejected':
return 'complete'
if rs in _REVIEW_STATUS_MUST_HUMAN:
return 'must_human'
if str(user_status or '').strip() == 'completed':
return 'complete'
code = str(gate_code or '').strip()
stage = str(lifecycle_stage or '').strip()
status = str(user_status or '').strip()
if code == 'manual_upload_handoff' or (
stage in {'freight_upload', 'upload_complete'} and status == 'waiting_human'
):
return 'wait_manual_upload'
if status == 'waiting_human':
return 'must_human'
return 'auto_continue'
def derive_position(*, gate_code: str | None, review_status: str | None) -> str | None:
"""
位置标签(与 POSITION_* / 文案表 key 对齐),供待办/用户态/阶段摘要消费。
用途:复核处置优先读 review_status;履约位置读 current_gate_code。
"""
rs = str(review_status or '').strip()
if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}:
return rs
mapping = {
'order_field_extraction': 'parse_review',
'customer_resolution': 'customer_review',
'reservation_validation': 'rsv_req',
'inventory_preparation': 'inventory_pending',
'inventory_matching': 'ready_to_match',
'inventory_sufficiency': 'shortage_review',
'order_freeze_readiness': 'order_freeze',
'excel_readiness': 'ready_to_export',
'artifact_generation': 'export_ready',
'freight_upload_rpa': 'upload_failed',
'manual_upload_handoff': 'waiting_upload',
}
return mapping.get(str(gate_code or '').strip())
def derive_todo_category(*, user_mode: str, position: str | None = None) -> str:
"""
待办分类(review / exception / manual_upload / done / in_progress)。
用途:由 user_mode + position 推导待办分类(Gate-first 唯一口径)。
"""
if user_mode == 'wait_manual_upload':
return 'manual_upload'
if user_mode == 'complete':
return 'done'
if user_mode == 'must_human':
return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception'
return 'in_progress'
# ============================================================
# 阶段能力集(Stage Capabilities)——一期:通知准备阶段
# 能力可用性 = 阶段 + Excel 未生成 + 预条件(数据在场),不由门禁通过与否决定。
@@ -4,11 +4,13 @@ services/shipping_notice/process_gate_executor.py
用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。
依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、
inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、
document_layout.lifecycle、process_gate_contract、process_gate_bridge。
document_layout.lifecycle、process_gate_contract、process_gate_bridge、
inventory_candidate_projection、recovery_invalidation_service。
逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态;
库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径;
co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem;
人工入口动作返回 navigation 提示,保持 blocked_manual。
人工入口动作返回 navigation 提示,保持 blocked_manual;
行级库存重抓按 snapshot_line_id → candidate.source_codes_json 收窄 RPA/失效。
"""
from __future__ import annotations
@@ -76,6 +78,13 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({
'regenerate_manual_upload_todo',
})
# 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。
# poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。
_FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({
'retry_inventory_preparation',
'retry_inventory_from_preparation',
})
# 人工入口:前端应导航,不把业务状态改为 passed。
_NAVIGATION_ACTIONS: frozenset[str] = frozenset({
'open_order_review',
@@ -356,6 +365,71 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
}
def _resolve_line_inventory_scope(
task: ShippingOrderTask | ShippingNotice | None,
*,
line_scope_key: Any = None,
) -> dict[str, Any] | None:
"""
由 snapshot_line_id / line_scope_key 解析行级库存作用域。
核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。
Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。
Args:
task: 当前 OT / 兼容 Notice owner。
line_scope_key: 前端 snapshot_line_id 或已规范化的行 scope。
Returns:
{snapshot_line_id, line_no, source_codes};无法解析时 None。
"""
if task is None:
return None
raw = line_scope_key
if raw is None:
return None
try:
scoped_line_id = int(raw)
except (TypeError, ValueError):
return None
if scoped_line_id <= 0 or not getattr(task, 'order_snapshot_id', None):
return None
from app.models import ShippingOrderSnapshot
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
scoped_line = next(
(
line for line in (getattr(snapshot, 'lines', None) or [])
if int(getattr(line, 'id', 0) or 0) == scoped_line_id
),
None,
)
if scoped_line is None:
return None
line_no = int(getattr(scoped_line, 'line_no', 0) or 0)
candidate_line = next(
(
line for line in get_active_candidate_lines(task)
if int(getattr(line, 'line_no', 0) or 0) == line_no
),
None,
)
source_codes = [
str(code).strip().upper()
for code in (getattr(candidate_line, 'source_codes_json', None) or [])
if str(code).strip()
] if candidate_line is not None else []
if not source_codes:
return None
return {
'snapshot_line_id': scoped_line_id,
'line_no': line_no,
'source_codes': source_codes,
}
def _tool_outcome(
*,
action_code: str,
@@ -745,7 +819,19 @@ def _handle_retry_inventory_preparation(
"""
重试/轮询库存准备。
核心逻辑:调用 ensure_inventory 后按任务事实推导细粒度阻断码,再同步履约门禁。
核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation →
retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto);
若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄
RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导
细粒度阻断码,再同步履约门禁。
Args:
execution: 当前 ProcessExecution。
gate: 当前库存准备 Gate。
payload: 须含 action_code;可选 actor_user_id / line_scope_key / snapshot_line_id。
Returns:
Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。
"""
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_workflow import ensure_inventory
@@ -831,6 +917,14 @@ def _handle_retry_inventory_preparation(
str(payload.get('trigger') or '') == 'gate_attempt_passed'
and not is_manual_rpa_retry
)
line_scope = _resolve_line_inventory_scope(
task,
line_scope_key=(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
),
)
if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
@@ -854,6 +948,8 @@ def _handle_retry_inventory_preparation(
action_code=str(payload.get('action_code')),
attempt_id=payload.get('attempt_id'),
actor_id=actor_id,
source_codes=(line_scope or {}).get('source_codes'),
snapshot_line_id=(line_scope or {}).get('snapshot_line_id'),
)
preparation_round = create_inventory_preparation_round(
task=task,
@@ -870,10 +966,17 @@ def _handle_retry_inventory_preparation(
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
)
# 只有用户显式重试强制生成新 Attempt;首次自动投递应先尝试复用有效快照。
if payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:
if line_scope is not None:
# 行级重抓:只把该行 candidate.source_codes_json 交给 ensure_inventory / RPA。
inventory_payload['source_codes'] = list(line_scope['source_codes'])
inventory_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id'])
# [STEP] 按已有动作码映射 ensure_inventory mode(零新动作码)。
# 禁止「人工入口一律 retry_rpa」:仅显式强制 RPA 码写 retry_rpa;poll 只读轮询;
# 首次 gate_attempt_passed 自动投递保持默认 auto(先复用快照)。
action_code = str(payload.get('action_code') or '').strip()
if action_code in _FORCE_INVENTORY_RPA_ACTION_CODES and not is_initial_auto_dispatch:
inventory_payload['mode'] = 'retry_rpa'
if str(payload.get('action_code') or '') == 'poll_inventory_preparation':
if action_code == 'poll_inventory_preparation':
# [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试,
# 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。
inventory_payload['allow_auto_retry'] = False
@@ -1219,7 +1322,12 @@ def _handle_retry_inventory_from_field_mapping(
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。"""
"""
从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。
Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt,
禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。
"""
from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream
invalidate_inventory_downstream(
@@ -1257,12 +1365,29 @@ def _handle_retry_inventory_matching(
``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency;
当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的
满足性 Gate 归属并再次显示“进入库存匹配处理”。
行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退
ensure_inventory 时携带该行 source_codes。
"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import match_inventory
from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
response = match_inventory(_task_payload(execution, payload))
task = _resolve_order_task(execution)
match_payload = _task_payload(execution, payload)
line_scope = _resolve_line_inventory_scope(
task,
line_scope_key=(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
),
)
if line_scope is not None:
match_payload['source_codes'] = list(line_scope['source_codes'])
match_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id'])
match_payload['line_scope_key'] = int(line_scope['snapshot_line_id'])
response = match_inventory_line(match_payload, line_no=int(line_scope['line_no']))
else:
response = match_inventory(match_payload)
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
task = _resolve_order_task(execution)
from app.services.shipping_notice.fulfillment_workflow import (
@@ -41,6 +41,18 @@ def _auto_match_enabled() -> bool:
from app.services.shipping_notice.tool_common import auto_match_enabled
return bool(auto_match_enabled())
def _auto_generate_excel_enabled() -> bool:
"""是否自动入队 artifact_generation Attempt(SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED)。
关闭时匹配通过后停在「重新生成 Excel」人工入口,禁止静默投递 regenerate Job。
"""
from app.services.shipping_notice.tool_common import auto_generate_excel_enabled
return bool(auto_generate_excel_enabled())
from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
@@ -1017,6 +1029,10 @@ def _enqueue_auto_progress_after_gate_pass(
next_gate.next_action_code in {'retry_inventory_matching'}
and not _auto_match_enabled()
)
or (
next_gate.next_action_code == 'regenerate_excel_artifact'
and not _auto_generate_excel_enabled()
)
or str(next_gate.next_action_code).startswith('open_')
):
return
@@ -205,12 +205,32 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
Returns:
(ShippingProcessingStatus, ShippingProcessingStage)。
"""
step = str(getattr(notice, 'current_step', None) or '').strip().lower()
upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower()
export_path = str(getattr(notice, 'export_file_path', None) or '').strip()
pending = str(getattr(notice, 'pending_human_reason', None) or '').strip().lower()
review = str(getattr(notice, 'review_status', None) or '').strip().lower()
match = str(getattr(notice, 'match_status', None) or '').strip().lower()
owner = notice
if not hasattr(notice, 'current_step') and getattr(notice, 'order_task_id', None):
try:
from app import db
from app.models import ShippingOrderTask
owner = db.session.get(ShippingOrderTask, int(notice.order_task_id)) or notice
except Exception: # noqa: BLE001
owner = notice
step = str(getattr(owner, 'current_step', None) or '').strip().lower()
pending = str(getattr(owner, 'pending_human_reason', None) or '').strip().lower()
review = str(getattr(owner, 'review_status', None) or '').strip().lower()
match = ''
export_path = ''
projected_upload = None
try:
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else ''
from app.services.shipping_notice.upload_attempt_service import (
latest_export_artifact,
project_notice_upload_status,
)
artifact = latest_export_artifact(owner)
export_path = str(getattr(artifact, 'file_path', None) or '').strip()
projected_upload = project_notice_upload_status(owner)
except Exception: # noqa: BLE001
pass
lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower()
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
@@ -219,17 +239,17 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
return ('cancelled', 'cancelled')
if verified_upload_success:
ps = 'uploaded'
elif upload_st in {'uploaded', 'succeeded', 'success'}:
# 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。
elif projected_upload == 'uploaded':
# 有 Notice 面成功投影但未过三层验证:留在上传工作面核对。
ps = 'waiting_upload'
elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed'
elif projected_upload in {'uploading', 'pending', 'failed', 'unknown'} or pending in {
'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown',
}:
ps = 'waiting_upload' if projected_upload != 'failed' else 'upload_failed'
elif export_path:
ps = 'matched'
elif match:
ps = 'matched'
elif getattr(notice, 'inventory_lines_json', None):
ps = 'inventory_ready'
elif pending or review:
ps = 'pending_review'
else:
@@ -237,7 +257,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
if ps in {'uploaded', 'closed', 'completed'}:
return ('completed', 'completed')
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or upload_st == 'uploading':
if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading':
return ('automating', 'freight_uploading')
if 'upload' in step or step.startswith('step7'):
return ('automating', 'freight_uploading')
@@ -512,7 +532,7 @@ def reconcile_processing_projection_facts(
stage_idx = shipping_processing_stage_index(stage)
waiting_idx = shipping_processing_stage_index('waiting_review') or 8
# 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。
# 关键事实无法读取时 fail-closed:不能继续沿用遗留位置投影或写动作。
if payload.get('projection_data_inconsistent'):
payload['status'] = 'waiting_human'
payload['stage'] = 'waiting_review'
@@ -740,15 +760,25 @@ def apply_user_projection_fields(
pending_reason: str | None = None
review_status_raw: str | None = None
inventory_source_status_raw: str | None = None
if notice is not None:
pending_reason = str(getattr(notice, 'pending_human_reason', None) or '').strip() or None
review_status_raw = str(getattr(notice, 'review_status', None) or '').strip() or None
inventory_source_status_raw = str(getattr(notice, 'inventory_source_status', None) or '').strip() or None
if order_task is not None and not pending_reason:
if order_task is None and notice is not None and getattr(notice, 'order_task_id', None):
try:
from app import db
from app.models import ShippingOrderTask
order_task = db.session.get(ShippingOrderTask, int(notice.order_task_id))
except Exception: # noqa: BLE001
order_task = None
if order_task is not None:
pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None
review_status_raw = str(getattr(order_task, 'review_status', None) or '').strip() or None
# ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status =====
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else ''
projected_upload = None
if order_task is not None and notice is not None:
try:
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
projected_upload = project_notice_upload_status(notice)
except Exception: # noqa: BLE001
projected_upload = None
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
# 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed
@@ -760,7 +790,7 @@ def apply_user_projection_fields(
and (
old_status == 'completed'
or old_stage == 'completed'
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
or projected_upload == 'uploaded'
)
)
def _compute_user_status() -> str:
@@ -1018,6 +1048,41 @@ def apply_user_projection_fields(
primary_action = _compute_primary_action()
# ===== [STEP 8: flatten C→A] 复用唯一裁决 C(process_gate),不再二次推导 drift =====
# 契约 §2.1/§2.2:primary_action.code / blocking_reason.code 唯一来源是 C(project_user_gate_summary)。
# A(本函数)只把 C 已裁决的规范化码包成 ui_state DTO;禁止再走别名(D1: regenerate_excel_artifact→
# regenerate_excel)或坍缩(D2: inventory_preparation_failed→technical_failure_present)覆盖 C。
# 条件化:仅当 _project_order_task_work_item 已写入 payload['process_gate'](正式 OT 有 Execution)时
# 消费 C;Intake/min 投影路径(shipping_processing_projection.py:983/:4695)无 process_gate,保留现有推导。
# 该实现与前端右卡仅读 A(§2.4)同批上线,保证右卡/对话流/批次进度中心同源;此处不改 user_status
# (那是 A 独有的六值展示分组枚举,C/B 均不产出,留在 A)。
_process_gate = payload.get('process_gate') if isinstance(payload.get('process_gate'), dict) else None
if _process_gate is not None:
# D1: primary_action.code 取 C 规范码(去 A 的 regenerate_excel_artifact→regenerate_excel 别名)。
_c_primary_code = str((_process_gate.get('primary_action') or {}).get('code') or '').strip()
if not _c_primary_code:
_c_primary_code = str(_process_gate.get('next_action_code') or '').strip()
if _c_primary_code:
_a_primary_code = str((primary_action or {}).get('code') or '').strip()
if _a_primary_code != _c_primary_code:
primary_action = {
'code': _c_primary_code,
'i18n_key': _resolve_action_i18n_key(_c_primary_code),
'parameters': {},
}
# D2: blocking_reason.code 取 C 已裁决的具体码,不再坍缩为 technical_failure_present。
_c_reason_code = str(_process_gate.get('blocking_reason_code') or '').strip()
if _c_reason_code and isinstance(blocking_reason, dict):
_a_reason_code = str(blocking_reason.get('code') or '').strip()
if _a_reason_code != _c_reason_code:
blocking_reason = {
'code': _c_reason_code,
'i18n_key': _REASON_TO_I18N_KEY.get(_c_reason_code) or (
(blocking_reason or {}).get('i18n_key')
),
'details': dict((blocking_reason or {}).get('details') or {}),
}
# ===== [不变] facts 子事实计算(保持不动) =====
facts: dict[str, Any] = {
'inventory_source_status': inventory_source_status_raw or 'unresolved',
@@ -1055,25 +1120,13 @@ def apply_user_projection_fields(
if isinstance(cand, list):
facts['candidate_source_codes'] = [str(c or '').strip().upper() for c in cand if str(c or '').strip()]
if notice is not None:
step_payload = getattr(notice, 'step_payload_json', None)
if isinstance(step_payload, dict):
prep = step_payload.get('candidate_inventory_prep')
if isinstance(prep, dict):
facts['prepared_source_codes'] = list(prep.get('loaded_source_codes') or [])
facts['pending_source_codes'] = list(prep.get('missing_source_codes') or [])
resolutions = step_payload.get('line_inventory_resolutions')
if isinstance(resolutions, list):
facts['line_resolutions'] = resolutions[:]
fms = step_payload.get('forced_match_source_code')
if fms:
facts['forced_match_source_code'] = str(fms).strip().upper()
# 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧
# step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。
# 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate
# 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。
try:
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_facts,
)
candidate_facts = project_inventory_candidate_facts(notice)
candidate_facts = project_inventory_candidate_facts(order_task)
if candidate_facts.get('current_set') is not None:
facts['candidate_set_id'] = candidate_facts.get('candidate_set_id')
facts['candidate_set_version'] = candidate_facts.get('candidate_set_version')
@@ -1096,7 +1149,7 @@ def apply_user_projection_fields(
# P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。
try:
from app.models import ShippingTaskInventoryRpaAttempt
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(notice, 'task_no', '') or '')).all()
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all()
facts['rpa_attempts'] = [{
'source_code': a.source_code, 'attempt_no': a.attempt_no,
'source_run_no': a.source_run_no, 'status': a.status,
@@ -1107,11 +1160,17 @@ def apply_user_projection_fields(
} for a in attempts]
except Exception:
facts['rpa_attempts'] = []
if getattr(notice, 'export_artifact_id', None):
facts['export_state'] = 'created'
if getattr(notice, 'upload_status', None):
us = str(getattr(notice, 'upload_status') or '').strip().lower()
facts['upload_state'] = us if us else 'not_created'
try:
from app.services.shipping_notice.upload_attempt_service import (
latest_export_artifact,
project_facts_upload_state,
)
artifact = latest_export_artifact(order_task or notice)
if artifact is not None:
facts['export_state'] = str(getattr(artifact, 'status', None) or 'created')
facts['upload_state'] = project_facts_upload_state(order_task or notice)
except Exception: # noqa: BLE001
pass
if getattr(notice, 'wecom_sent_at', None):
facts['switch_state'] = 'sent'
@@ -523,8 +523,6 @@ PROCESS_GATE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'FIELD_DERIVED',
'FIELD_DERIVATION_SKIPPED',
'LINE_NO_OVERRIDDEN',
'LINE_NO_RESTORED',
'DERIVATION_SIMULATED',
'DERIVATION_RULES_CHANGED',
'ORDER_FROZEN',
@@ -823,7 +821,6 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
'validation_blocking_count',
'validation_warning_count',
'field_id',
'line_key',
'previous_value',
'new_value',
'value_source',
@@ -858,10 +855,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
# 字段派生 / 覆盖 / 导出血缘(脱敏摘要,禁止邮件/PDF 正文)。
'rule_id',
'rule_checksum',
'derivation_rules_checksum',
'skip_reason',
'override_reason_code',
'export_sequence',
'export_artifact_no',
'template_version',
'field_code',
@@ -874,7 +869,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
'suggestion_pending',
'idempotency_key',
'action_semantics',
'line_keys',
'draft_line_ids',
'snapshot_line_ids',
'routing_status',
# Process Gate 恢复摘要(禁止正文、规则 SQL、对象存储 URL)。
'gate_code',
@@ -3,10 +3,13 @@ services/shipping_notice/progress_workflow.py
用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
state_machine(CheckpointKind)、tool_response、process_gate_bridge。
process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、
state_machine(双读回退)、tool_response、process_gate_bridge。
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交
当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留
供兼容调用方,但不得再由本 facade 直接跨 Gate 调度。
供兼容调用方,但不得再由本 facade 直接跨 Gate 调度;
早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state;
inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。
"""
from __future__ import annotations
@@ -19,7 +22,7 @@ from app.services.shipping_notice import fulfillment_workflow
from app import db
from app.models.shipping_process_gate import ShippingProcessGateAttempt
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
POSITION_INVENTORY_SOURCE_REVIEW,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RSV_REQ,
@@ -32,12 +35,86 @@ from app.services.shipping_notice.inventory_source_gate import (
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
def _entry_user_mode(task) -> str:
"""
自动推进入口早停:从 Gate 推导用户处置模式。
无活动 Execution 时回退 resolve_task_ui_state.user_mode。
inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker
继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。
"""
from app.services.shipping_notice.process_gate_contract import (
derive_user_mode,
user_mode_for_blocking_reason,
)
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
gate = _process_gate_user_summary_for_task(task)
if not isinstance(gate, dict) or not gate:
return str(resolve_task_ui_state(task).user_mode)
gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {}
if not isinstance(gate_view, dict):
gate_view = {}
status = str(gate_view.get('status') or '').strip().lower()
summary_status = str(gate.get('status') or gate.get('gate_status') or '').strip().lower()
gate_code = str(gate.get('current_gate_code') or gate_view.get('gate_code') or '').strip()
reason_code = str(
gate_view.get('blocking_reason_code')
or gate.get('blocking_reason_code')
or ''
).strip()
# [STEP] 库存准备可自动恢复:候选已冻结但尚无快照时,sync 可能先投影
# blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由
# submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。
if (
gate_code == 'inventory_preparation'
and status == 'blocked_retryable'
and user_mode_for_blocking_reason(reason_code) == 'retryable_tech'
):
return 'auto_continue'
if summary_status in {'completed', 'done'}:
user_status = 'completed'
elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked':
user_status = 'waiting_human'
elif status == 'failed_terminal' or summary_status == 'failed':
user_status = 'failed'
else:
user_status = 'running'
return derive_user_mode(
user_status=user_status,
gate_code=gate_code or None,
review_status=getattr(task, 'review_status', None),
lifecycle_stage=gate.get('lifecycle_stage'),
)
def _entry_position(task) -> str | None:
"""
工具响应下发位置标签:优先 Gate derive_position,否则 resolve_task_ui_state。
"""
from app.services.shipping_notice.process_gate_contract import derive_position
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
gate = _process_gate_user_summary_for_task(task)
if isinstance(gate, dict) and gate:
gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {}
if not isinstance(gate_view, dict):
gate_view = {}
pos = derive_position(
gate_code=gate.get('current_gate_code') or gate_view.get('gate_code'),
review_status=getattr(task, 'review_status', None),
)
if pos:
return pos
return resolve_task_ui_state(task).position
# ---------------------------------------------------------------------------
# T5: 唯一 AutoProgress Orchestrator 入口 facade
# ---------------------------------------------------------------------------
@@ -56,7 +133,7 @@ from app.services.shipping_notice.customer_identity_gate import customer_gate_to
_RESUME_GATE_CODE_LEGACY_ENTRY = {
# inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现)
'inventory_preparation': 'ensure_inventory',
# inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key)
# inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次)
'inventory_matching': 'match_inventory',
# None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传)
'auto': 'auto_progress_full',
@@ -130,8 +207,12 @@ def _dispatch_legacy_orchestration(
resume_after_gate: str | None = None,
) -> dict[str, Any]:
"""
resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。
长期目标:每个 Gate 只在本函数内跑原子 run_one_gate_step();旧实现会逐步下线。
[DEPRECATED / P0-3 后不可达主路径] resume_gate_code → 旧跨 Gate 串联实现。
正式开心路径已改为 ProcessGate:``submit_auto_progress`` /
``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 只入队下一 Gate
Attempt;匹配成功不得在此函数内嵌 ``generate_excel`` / ``upload_to_freight``。
本函数体暂保留供兼容调用方与测试打桩,不得再作为新编排入口扩展。
"""
entry = _RESUME_GATE_CODE_LEGACY_ENTRY.get(resume_gate_code, 'auto_progress_full')
base_payload: dict[str, Any] = {
@@ -150,7 +231,49 @@ def _dispatch_legacy_orchestration(
)
frozen_sources = task_frozen_inventory_source_codes(task)
if frozen_sources and len(frozen_sources) >= 1:
prepare_result = ensure_all_required_sources_prepared(task, mode=inventory_mode)
scoped_source_codes: list[str] | None = None
scope_key = str(line_scope_key or '').strip()
if scope_key:
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
try:
scoped_line_id = int(scope_key)
except (TypeError, ValueError):
scoped_line_id = 0
from app.models import ShippingOrderSnapshot
snapshot = (
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if getattr(task, 'order_snapshot_id', None) else None
)
scoped_line = next(
(
line for line in (getattr(snapshot, 'lines', None) or [])
if int(getattr(line, 'id', 0) or 0) == scoped_line_id
),
None,
)
if scoped_line is not None:
candidate_lines = get_active_candidate_lines(task)
candidate_line = next(
(
line for line in candidate_lines
if int(getattr(line, 'line_no', 0) or 0) == int(getattr(scoped_line, 'line_no', 0) or 0)
),
None,
)
scoped_sources = [
str(code).strip().upper()
for code in (getattr(candidate_line, 'source_codes_json', None) or [])
if str(code).strip()
] if candidate_line is not None else []
if scoped_sources:
frozen_sources = scoped_sources
scoped_source_codes = scoped_sources
prepare_result = ensure_all_required_sources_prepared(
task, mode=inventory_mode, source_codes=scoped_source_codes,
)
if prepare_result.all_prepared:
return _legacy_ensure_inventory({**base_payload, '_prepared_sources': prepare_result.prepared_source_codes, '_orchestrator_internal_dispatch': True})
return tool_response(
@@ -178,7 +301,7 @@ def _dispatch_legacy_orchestration(
if norm_line_scope:
return fulfillment_workflow.match_inventory_line(
{**base_payload, '_orchestrator_internal_dispatch': True},
line_key=norm_line_scope,
line_no=int(norm_line_scope),
)
return fulfillment_workflow.match_inventory({**base_payload, '_orchestrator_internal_dispatch': True})
return _auto_progress_full(task, base_payload, trigger=trigger, operator_id=operator_id)
@@ -265,6 +388,8 @@ def run_task_auto_progress(
submitted = submit_auto_progress(
task=task, trigger=trigger, operator_id=operator_id,
resume_gate_code=resume_gate_code, commit=True,
inventory_mode=inventory_mode,
line_scope_key=line_scope_key,
recovery_plan_id=recovery_plan_id,
recovery_attempt_id=recovery_attempt_id,
resume_after_gate=resume_after_gate,
@@ -377,7 +502,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。
核心逻辑:先按 checkpoint_kind 处理早停;WAIT_MANUAL_UPLOAD 在 AUTO_UPLOAD 开启时
核心逻辑:先按 Gate derive_user_mode 处理早停(无 Execution 回退 user_mode);
WAIT_MANUAL_UPLOAD / wait_manual_upload 在 AUTO_UPLOAD 开启时
不早停、落入履约链触发货代 RPA;关闭时才对齐 manual_upload_pending 并禁止自动上传。
再检查解析门禁与客户/库存源,库存就绪后委托 fulfillment_workflow 同一编排链。
Args:
@@ -411,21 +537,22 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
# 正式 20-Gate 编排仍由后续分支负责;这里仅返回用户可执行的当前结果。
early_task = resolve_task_from_payload({'task_no': task_no}) if task_no else None
if early_task is not None:
early_ui = resolve_task_ui_state(early_task)
if early_ui.checkpoint_kind == CheckpointKind.MUST_HUMAN:
early_mode = _entry_user_mode(early_task)
early_position = _entry_position(early_task)
if early_mode == 'must_human':
return tool_response(
status='needs_human', task=early_task,
message='当前任务需要人工处理,已暂停自动推进。',
data=serialize_task_for_tool(early_task),
checkpoint=early_ui.checkpoint,
position=early_position,
stop_agent_turn=True,
)
if early_ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD and not fulfillment_workflow.is_auto_upload_enabled():
if early_mode == 'wait_manual_upload' and not fulfillment_workflow.is_auto_upload_enabled():
return tool_response(
status='ok', task=early_task,
message='Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。',
data=serialize_task_for_tool(early_task),
checkpoint=early_ui.checkpoint,
position=early_position,
stop_agent_turn=True,
forbidden_next_tools=['upload_to_freight'],
)
@@ -491,25 +618,26 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
steps: list[str] = []
# [STEP 0] STP 检查点早停:必须人工、待人工上传登记或已完成时不产生新副作用。
ui_early = resolve_task_ui_state(task)
if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN:
# [STEP 0] Gate 粗分类早停:必须人工、待人工上传登记或已完成时不产生新副作用。
early_mode = _entry_user_mode(task)
early_position = _entry_position(task)
if early_mode == 'must_human':
return tool_response(
status="needs_human",
task=task,
message="当前任务需要人工处理,已暂停自动推进。",
data=serialize_task_for_tool(task),
checkpoint=ui_early.checkpoint,
position=early_position,
stop_agent_turn=True,
)
if ui_early.checkpoint_kind == CheckpointKind.COMPLETE:
if early_mode == 'complete':
return tool_response(
status="ok",
task=task,
message="任务已结束,无需自动推进。",
data=serialize_task_for_tool(task),
)
if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
if early_mode == 'wait_manual_upload':
pending = str(getattr(task, 'pending_human_reason', '') or '').strip()
# RPA 已触发/失败:只对齐细粒度投影,不再重复编排。
if pending in {'upload_rpa_pending', 'upload_rpa_failed'}:
@@ -539,7 +667,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
else '货代上传 RPA 失败,请在对话侧恢复或改人工登记。'
),
data=serialize_task_for_tool(task),
checkpoint=ui_early.checkpoint,
position=early_position,
stop_agent_turn=True,
)
# AUTO_UPLOAD 开启:与 fulfillment 链统一,继续向下触发上传,禁止在此早停。
@@ -569,7 +697,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
data=serialize_task_for_tool(task),
checkpoint=ui_early.checkpoint,
position=early_position,
stop_agent_turn=True,
forbidden_next_tools=["upload_to_freight"],
)
@@ -583,29 +711,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
threshold = 0.7
confidence = None
try:
confidence = float(task.parse_confidence) if task.parse_confidence is not None else None
parse_validation = (task.step_payload_json or {}).get('parse_validation') if isinstance(getattr(task, 'step_payload_json', None), dict) else None
raw_confidence = parse_validation.get('confidence') if isinstance(parse_validation, dict) else None
confidence = float(raw_confidence) if raw_confidence is not None else None
except (TypeError, ValueError):
confidence = None
if task.review_status == RS_RSV_REQ or task.pending_human_reason == PH_RSV_REQ:
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
blocking_reason = task_blocking_reason(task)
if task.review_status == RS_RSV_REQ or blocking_reason == PH_RSV_REQ:
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="订单仍缺少后续处理必需字段,请先补充后再继续。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
position=ui.position,
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
if task.review_status == RS_PARSE_REVIEW or blocking_reason == PH_LOW_CONF:
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="发货通知解析需要人工确认后才能自动推进。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
position=ui.position,
stop_agent_turn=True,
)
if confidence is not None and confidence < threshold:
@@ -615,7 +748,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message=f"解析置信度 {confidence:.2f} 低于阈值 {threshold:.2f},请人工确认后再自动推进。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
position=ui.position,
stop_agent_turn=True,
)
@@ -623,7 +756,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
if customer_gate is not None:
return customer_gate
if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
if blocking_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
if not is_inventory_source_stable(task):
@@ -639,12 +772,13 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
# [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。
if not task.inventory_lines_json:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if not has_ready_inventory_file_for_task(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
@@ -660,7 +794,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
else:
steps.append("载入库存")
# [STEP 3] 库存就绪后进入履约侧自动推进(与 try_auto_chain 同一语义:可含货代 RPA)。
# [STEP 3] 库存就绪后进入履约侧自动推进。
# [DEPRECATED] 旧语义曾与 try_auto_chain 同 Attempt 串联 generate±upload;
# P0-3 / 编排分离后正式路径为独立 Gate Attempt,本 legacy 体仅兼容残留入口。
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
# [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。
File diff suppressed because it is too large. Load diff
@@ -92,10 +92,13 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool:
if not task_is_active(task):
return False
pending_reason = str(task.pending_human_reason or '').strip()
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
pending_reason = str(task_blocking_reason(task) or '').strip()
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
return (
pending_reason == PH_RPA_PENDING
and not task.inventory_lines_json
and not has_ready_inventory_file_for_task(task)
) or pending_reason == PH_UPLOAD_RPA_PENDING
@@ -107,7 +110,8 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
from app.services.shipping_notice.query_service import get_task_by_ref
task = get_task_by_ref(task_no)
if task and str(task.pending_human_reason or '').strip() == PH_RPA_PENDING:
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING:
from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at
scheduled_at = next_inventory_rpa_recheck_at(task)
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/reconcile_queries.py
用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。
依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument
/ ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、
/ ShippingOrderTask、business_fingerprint.build_business_fingerprint、
duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。
逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询,
不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no /
@@ -19,8 +19,8 @@ from typing import Any
from app import db
from app.models import (
FileAsset,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderTask,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderProcessingUnit,
@@ -61,7 +61,7 @@ def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult:
def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None:
"""
L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。
L1:Case.confirmed_task_id → 直接查 ShippingOrderTask 拿到 task_no。
【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。
"""
steps: list[dict[str, Any]] = []
@@ -70,7 +70,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
# 1a. confirmed_task_id 有值且指向存在的 Task
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is not None:
task = db.session.get(ShippingNotice, int(task_id))
task = db.session.get(ShippingOrderTask, int(task_id))
if task is not None and task.task_no:
steps.append({'step': 'L1a-confirmed_task_id', 'passed': True,
'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}})
@@ -83,15 +83,15 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
lifecycle=classify_task_lifecycle(task)),
)
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False,
'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no',
'reason': 'confirmed_task_id 指向的 ShippingOrderTask 不存在或无 task_no',
'evidence': {'task_id': int(task_id)}})
else:
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'})
# 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性
# 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingOrderTask 校验存在性
confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip()
if confirmed_task_no:
task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first()
task = ShippingOrderTask.query.filter_by(task_no=confirmed_task_no).first()
if task is not None:
steps.append({'step': 'L1b-confirmed_task_no', 'passed': True,
'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}})
@@ -104,7 +104,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
lifecycle=classify_task_lifecycle(task)),
)
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False,
'reason': 'confirmed_task_no 反向查无 ShippingNotice',
'reason': 'confirmed_task_no 反向查无 ShippingOrderTask',
'evidence': {'task_no': confirmed_task_no}})
else:
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'})
@@ -141,7 +141,7 @@ def _step_l1cde_downstream_links(
) -> ReconcileMatchResult | None:
"""
L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。
L1d: Document → ShippingNotice.source_document_id / document_id 外键。
L1d: Document → Candidate.primary_document_id → ShippingOrderTask 外键。
L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。
"""
steps: list[dict[str, Any]] = []
@@ -151,7 +151,7 @@ def _step_l1cde_downstream_links(
if candidate is not None:
fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None)
if fulfilled_task_id is not None:
task = db.session.get(ShippingNotice, int(fulfilled_task_id))
task = db.session.get(ShippingOrderTask, int(fulfilled_task_id))
if task is not None and task.task_no:
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True,
'evidence': {'candidate_id': int(candidate.id),
@@ -183,7 +183,7 @@ def _step_l1cde_downstream_links(
)
wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None]
if len(wave_task_ids) == 1:
task = db.session.get(ShippingNotice, wave_task_ids[0])
task = db.session.get(ShippingOrderTask, wave_task_ids[0])
if task is not None and task.task_no:
steps.append({'step': 'L1c-wave_line_task', 'passed': True,
'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}})
@@ -204,14 +204,14 @@ def _step_l1cde_downstream_links(
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'})
steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'})
# -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)--------
# -------- L1d:Document 外键链:Unit → Intake → Candidate → OT --------
document_id = int(case.document_id)
# 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联)
# 路径 A:Candidate.primary_document_id == document_id(PDF 级直接关联)
doc_task_a = (
ShippingNotice.query
.filter((ShippingNotice.source_document_id == document_id) |
(ShippingNotice.document_id == document_id))
.order_by(ShippingNotice.id.desc())
ShippingOrderTask.query
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderCandidate.primary_document_id == document_id)
.order_by(ShippingOrderTask.id.desc())
.limit(5)
.all()
)
@@ -240,15 +240,19 @@ def _step_l1cde_downstream_links(
intake = db.session.get(ShippingOrderIntake, int(unit.intake_id))
asset_id = getattr(intake, 'asset_id', None) if intake is not None else None
if asset_id is not None:
# FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级)
# FileAsset.content_hash == Intake/Document.content_hash(文件哈希级)
asset = db.session.get(FileAsset, int(asset_id))
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
if content_hash:
file_tasks = (
ShippingNotice.query
.filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash)
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
ShippingOrderTask.query
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderTask.intake_id)
.filter(
ShippingOrderTask.user_id == int(case.owner_user_id),
ShippingOrderIntake.asset_id == int(asset_id),
)
.filter(ShippingOrderTask.lifecycle_status == 'active')
.order_by(ShippingOrderTask.id.desc())
.limit(5)
.all()
)
@@ -400,11 +404,12 @@ def _step_l2_structural_match(
if (payload['business_fingerprint']
and payload['fingerprint_strength'] in {'strong', 'medium'}):
same_fp_tasks = (
ShippingNotice.query
.filter(ShippingNotice.user_id == int(case.owner_user_id),
ShippingNotice.business_fingerprint == payload['business_fingerprint'])
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
ShippingOrderTask.query
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(case.owner_user_id),
ShippingOrderCandidate.business_fingerprint == payload['business_fingerprint'])
.filter(ShippingOrderTask.lifecycle_status == 'active')
.order_by(ShippingOrderTask.id.desc())
.limit(5)
.all()
)
@@ -435,21 +440,21 @@ def _step_l2_structural_match(
# L2b:同用户 + PO 精确一致 + customer_code 精确一致
if payload['po_numbers'] and payload['customer_code']:
# ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code
# Candidate 结构化摘要:查 structured_result_json.business_summary.po_numbers / customer_code
# 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向
same_customer_tasks = (
ShippingNotice.query
.filter_by(user_id=int(case.owner_user_id))
.filter(ShippingNotice.customer_code == payload['customer_code']
if hasattr(ShippingNotice, 'customer_code') else True)
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
ShippingOrderTask.query
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(case.owner_user_id))
.filter(ShippingOrderTask.lifecycle_status == 'active')
.order_by(ShippingOrderTask.id.desc())
.limit(20)
.all()
)
po_matched: list[ShippingNotice] = []
po_matched: list[ShippingOrderTask] = []
for task in same_customer_tasks:
structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None
candidate_row = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(task.id)).order_by(ShippingOrderCandidate.id.desc()).first()
structured = getattr(candidate_row, 'structured_result_json', None) if candidate_row is not None else None
summary = structured.get('business_summary') if isinstance(structured, dict) else None
task_pos: set[str] = set()
if isinstance(summary, dict):
@@ -460,7 +465,7 @@ def _step_l2_structural_match(
po_matched.append(task)
if len(po_matched) == 1:
task = po_matched[0]
steps.append({'step': 'L2b-po_customer_match', 'passed': True,
steps.append({'step': 'L2b-po_customer_identity', 'passed': True,
'evidence': {'customer_code': payload['customer_code'],
'pos_matched': sorted(set(payload['po_numbers']) &
{str(x).strip().upper() for x in
@@ -474,11 +479,11 @@ def _step_l2_structural_match(
confidence=ReconcileConfidence.PROBABLE,
evidence=evidence,
)
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
steps.append({'step': 'L2b-po_customer_identity', 'passed': False,
'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)',
'evidence': {'matched_count': len(po_matched)}})
else:
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
steps.append({'step': 'L2b-po_customer_identity', 'passed': False,
'reason': 'PO 或 customer_code 缺失,无法联合匹配',
'evidence': {'pos_count': len(payload['po_numbers']),
'customer_code_empty': not bool(payload['customer_code'])}})
@@ -487,11 +492,11 @@ def _step_l2_structural_match(
# 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous
document_id = int(case.document_id)
doc_tasks_multi = (
ShippingNotice.query
.filter((ShippingNotice.source_document_id == document_id) |
(ShippingNotice.document_id == document_id))
.filter(ShippingNotice.lifecycle_status == 'active')
.order_by(ShippingNotice.id.desc())
ShippingOrderTask.query
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderCandidate.primary_document_id == document_id)
.filter(ShippingOrderTask.lifecycle_status == 'active')
.order_by(ShippingOrderTask.id.desc())
.limit(5)
.all()
)
@@ -25,8 +25,8 @@ backend/app/services/shipping_notice/reconciliation_projector.py
从 automation.reason_code / blocking_reason 拆出 {code, i18n_key, details}
与 invariants._REASON_TO_I18N_KEY 一致映射。
⑤ project_case_user_status(case, automation)
返回七值归一化 completed / cancelled / waiting_human / retryable /
failed / running / idle(与 shipping-processing user_status 同域)。
返回 F2 六值 completed / cancelled / waiting_human / retryable /
failed / running(与 USER_FACING_TASK_STATUSES 同域;禁止 idle)。
⑥ project_case_primary_action(user_status, blocking_reason, available_actions, user_stage)
完整复刻 invariants._compute_primary_action 逻辑(1a~1i)。
⑦ 总入口 project_review_case_projection_bundle(...)
@@ -51,7 +51,7 @@ from app.models import (
UserStatus = Literal[
'completed', 'cancelled', 'waiting_human',
'retryable', 'failed', 'running', 'idle',
'retryable', 'failed', 'running',
]
@@ -142,7 +142,11 @@ def project_case_automation_status(
job_id / error_code / reason_code / blocking_reason / next_action
的字典(与详情页 automation 同构)。
"""
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.order_review_workbench_projection import (
JOB_FAILURE_STATUS_TOKENS,
project_job_status_outcome,
resolve_formal_ot,
)
from app.services.shipping_notice.order_stp_auto_create_service import (
build_stp_idempotency_key,
find_active_stp_job,
@@ -281,7 +285,7 @@ def project_case_automation_status(
'can_build': can_build,
'job_id': int(job.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed':
result = latest.result_json if isinstance(latest.result_json, dict) else {}
raw_retryable = result.get('retryable')
if raw_retryable is None:
@@ -313,9 +317,7 @@ def project_case_automation_status(
'error_code': result.get('error_code') or blocking_reason_raw,
'retry_of_job_id': int(latest.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {
'succeeded', 'success', 'completed',
}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded':
return {
'status': 'completed',
'retryable': False,
@@ -707,7 +709,7 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR
# ============================================================
# [5] user_status(七值归一化)
# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle)
# ============================================================
def project_case_user_status(
@@ -715,11 +717,12 @@ def project_case_user_status(
automation: dict[str, Any] | None,
) -> UserStatus:
"""
与 shipping-processing invariants 的 user_status 七值同域映射。
与 USER_FACING_TASK_STATUSES / shipping-processing user_status 同域(F2 六值)。
Case 草稿待处置默认 waiting_human;禁止再输出 idle。
"""
auto_status = str((automation or {}).get('status') or '').strip().lower()
case_status = str(case.status or '').strip().lower()
if auto_status in {'completed', 'success'}:
if auto_status == 'completed':
return 'completed'
if case_status in {'cancelled', 'superseded', 'non_order'}:
return 'cancelled'
@@ -734,7 +737,7 @@ def project_case_user_status(
return 'waiting_human'
if auto_status in {'waiting_to_start'}:
return 'running' # waiting = 尚未运行,但系统已负责
return 'idle'
return 'waiting_human'
# ============================================================
@@ -815,7 +818,7 @@ def project_case_primary_action(
# 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的
# 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。
if user_status in {'waiting_human', 'idle'}:
if user_status == 'waiting_human':
if 'create_draft' in actions:
return {'code': 'create_draft', 'variant': 'primary',
'label_key': 'shipping.actions.create_draft'}
@@ -861,6 +864,10 @@ def _project_fine_grained_pre_stp_blocking(
from app.extensions import db
from app.models import Job
from app.jobs.types import JobType
from app.services.shipping_notice.order_review_workbench_projection import (
JOB_FAILURE_STATUS_TOKENS,
project_job_status_outcome,
)
from app.services.shipping_notice.order_stp_auto_create_service import (
build_stp_idempotency_key,
)
@@ -948,14 +955,17 @@ def _project_fine_grained_pre_stp_blocking(
else:
latest_failed = (
next(
(job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}),
(
job for job in prefix_jobs
if project_job_status_outcome(getattr(job, 'status', None)) == 'failed'
),
None,
) if prefix_jobs is not None else (
db.session.query(Job)
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.status.in_(('failed', 'dead')),
Job.status.in_(tuple(JOB_FAILURE_STATUS_TOKENS)),
Job.business_ref.like(f"{business_ref_prefix}%"),
)
.order_by(Job.id.desc())
@@ -1189,10 +1199,17 @@ def project_review_case_projection_bundle(
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
# 草稿状态重算 order_review_build/idle,会覆盖批次投影已读取的
# field_completeness / required_field_missing,造成同一文件前后端状态冲突。
# 但该裁决权只适用于已确认(post-OT)的正式 Gate;未确认(unreviewed/draft/ready
# 且无 confirmed_task_id)的 Case 仍停留在建单前,其当前 Gate / 用户态必须由
# Case 派生事实(order_review_build / waiting_human)裁决,不得被正式 Gate 的
# reservation_validation / running 反向覆盖。
formal_gate_facts = _project_case_formal_gate_facts(
_project_case_formal_gate_summary(case),
)
if formal_gate_facts is not None:
if (
formal_gate_facts is not None
and str(case.status or '').strip().lower() == 'confirmed'
):
current_gate, blocking_reason, user_status = formal_gate_facts
# [STEP 6] primary_action
# 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp;
@@ -34,6 +34,7 @@ from app.jobs.types import JobType
from app.models import (
Job,
ShippingNotice,
ShippingOrderTask,
ShippingOrderCandidate,
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
@@ -326,14 +327,15 @@ def _write_reconcile_audit_and_event(
def _write_back_case_task_binding(
*,
case: ShippingOrderReviewCase,
task: ShippingNotice,
task: ShippingOrderTask,
actor_type: str,
) -> None:
"""
Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。
1. Case.confirmed_task_id / confirmed_task_no
2. Candidate.fulfilled_task_id(若存在当前 Candidate)
3. Document → Task 外键(ShippingNotice.source_document_id 如空则补)
3. 来源文档继续由 Case.document_id / Candidate.primary_document_id 承载;
OT 只保存 intake/candidate 指针,不写入已移除的 source_document_id 投影。
"""
case.confirmed_task_id = int(task.id)
# confirmed_task_no 通常为 property,但实际存字段若可写则同步
@@ -350,12 +352,6 @@ def _write_back_case_task_binding(
cand.fulfilled_task_id = int(task.id)
except Exception: # noqa: BLE001 — 模型无列则降级
pass
# Document → Task 外键
if not getattr(task, 'source_document_id', None) and getattr(case, 'document_id', None):
try:
task.source_document_id = int(case.document_id)
except Exception: # noqa: BLE001
pass
# ============================================================
@@ -537,8 +533,8 @@ def reconcile_and_progress(
mlvl: str = match_result['match_level']
confidence: str = match_result['confidence']
matched_task_no: str | None = match_result.get('task_no')
matched_task: ShippingNotice | None = (
ShippingNotice.query.filter_by(task_no=matched_task_no).first()
matched_task: ShippingOrderTask | None = (
ShippingOrderTask.query.filter_by(task_no=matched_task_no).first()
if matched_task_no else None
)
@@ -775,12 +771,23 @@ def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCas
return
rj = latest.result_json if isinstance(latest.result_json, dict) else {}
retryable_flag = bool(rj.get('retryable', True))
error_code = str(rj.get('error_code') or '').strip()
blocking_reason_raw = rj.get('blocking_reason')
blocking_reason = (
{'code': str(blocking_reason_raw)}
if isinstance(blocking_reason_raw, str) and blocking_reason_raw
else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None
)
# 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false,
# 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通
# retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。
effective_error_code = error_code or (
blocking_reason.get('code')
if isinstance(blocking_reason, dict)
else str(blocking_reason or '').strip()
)
if not retryable_flag and effective_error_code == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
return
if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason):
raise ConflictError(
'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create',
@@ -4,11 +4,13 @@ services/shipping_notice/recovery_invalidation_service.py
用途:按恢复动作精确失效库存下游事实及正式 Gate。
依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。
逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。
行级 scope(source_codes)时:只失效对应源链接与未发通知行的匹配,禁止触碰已有 Notice Artifact。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import false
from app import db
from app.models import (
@@ -19,21 +21,72 @@ from app.models import (
ShippingProcessExecution,
ShippingTaskInventoryLink,
ShippingUploadAttempt,
ShippingNotice,
)
from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates
def _noticed_snapshot_line_ids(task_id: int) -> set[int]:
"""
返回该 OT 下已写入正式发货通知行的 snapshot_line_id 集合。
核心逻辑:ShippingNoticeLine 是「已产生发货通知」的权威事实;行级重抓不得改写这些行。
"""
from app.models.shipping_notice_line import ShippingNoticeLine
rows = (
db.session.query(ShippingNoticeLine.snapshot_line_id)
.join(ShippingNotice, ShippingNotice.id == ShippingNoticeLine.notice_id)
.filter(ShippingNotice.order_task_id == int(task_id))
.all()
)
return {int(row[0]) for row in rows if row[0] is not None}
def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]:
"""从匹配事实抽取规范化库存源集合,供行级失效过滤。"""
codes: set[str] = set()
primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper()
if primary:
codes.add(primary)
for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []):
code = str(raw or '').strip().upper()
if code:
codes.add(code)
return codes
def invalidate_inventory_downstream(
*, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None,
actor_id: int | str | None = None,
source_codes: list[str] | None = None,
snapshot_line_id: int | None = None,
) -> dict[str, list[int] | list[str]]:
"""失效库存恢复受影响事实,并返回可审计的对象 ID。"""
"""
失效库存恢复受影响事实,并返回可审计的对象 ID。
核心逻辑:整单恢复保持原行为;若传入 source_codes(行级重抓),则:
- 只停用对应源的库存链接;
- 只作废「未产生发货通知」且命中该源/该行的匹配事实;
- 禁止 supersede 已有 Notice 的 Artifact/Upload。
Args:
execution: 当前 ProcessExecution。
action_code: 恢复动作码,决定失效深度。
attempt_id: 可选 Gate Attempt ID。
actor_id: 可选操作人。
source_codes: 行级库存源;有值即进入行级收窄模式。
snapshot_line_id: 可选被点击的冻结行 ID,用于精确命中该行匹配事实。
Returns:
各类被失效对象 ID 列表。
"""
task_id = int(execution.task_id or 0)
if not task_id:
return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
now = datetime.utcnow()
from app.models import ShippingNotice
task = db.session.get(ShippingNotice, task_id)
from app.models import ShippingOrderTask
task = db.session.get(ShippingOrderTask, task_id)
result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []}
change_type = {
'retry_inventory_preparation': 'inventory_file_changed',
@@ -42,26 +95,43 @@ def invalidate_inventory_downstream(
'retry_inventory_from_matching': 'inventory_matching_changed',
}.get(action_code, 'inventory_matching_changed')
result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id)
scoped_codes = {
str(code).strip().upper()
for code in (source_codes or [])
if str(code).strip()
}
line_scoped = bool(scoped_codes)
protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set()
scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None
if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}:
links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all()
for link in links:
link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper()
if line_scoped and link_code and link_code not in scoped_codes:
continue
if line_scoped and not link_code:
# 无源码的历史链接在行级重抓时不误伤;整单路径仍会停用。
continue
link.is_active = False
link.invalidated_at = now
link.invalidated_by_attempt_id = attempt_id
link.invalidation_reason = action_code
result['links'].append(int(link.id))
active_file_ids = [
affected_file_ids = [
int(link.inventory_file_id)
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all()
if link.inventory_file_id
if link.inventory_file_id and (
not line_scoped
or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes
)
]
if action_code in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
} and active_file_ids:
} and affected_file_ids:
mappings = ShippingInventoryMapping.query.filter(
ShippingInventoryMapping.inventory_file_id.in_(active_file_ids),
ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids),
ShippingInventoryMapping.status == 'active',
).with_for_update().all()
for mapping in mappings:
@@ -69,47 +139,40 @@ def invalidate_inventory_downstream(
result['mappings'].append(int(mapping.id))
matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all()
for row in matches:
row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0)
if line_scoped and row_line_id in protected_line_ids:
continue
if line_scoped:
row_codes = _match_row_source_codes(row)
hit_scoped_line = scoped_snapshot_line_id is not None and row_line_id == scoped_snapshot_line_id
hit_scoped_source = bool(row_codes.intersection(scoped_codes))
if not hit_scoped_line and not hit_scoped_source:
continue
row.is_current = False
row.invalidated_at = now
row.invalidated_by_attempt_id = attempt_id
row.invalidation_reason = action_code
result['matches'].append(int(row.id))
verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
for verification in verifications:
verification.status = 'superseded'
result['verifications'].append(int(verification.id))
artifacts = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task_id,
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).with_for_update().all()
for artifact in artifacts:
artifact.status = 'superseded'
result['artifacts'].append(int(artifact.id))
uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter(
ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}),
if not line_scoped:
verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all()
for verification in verifications:
verification.status = 'superseded'
result['verifications'].append(int(verification.id))
notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()]
artifacts = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(),
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).with_for_update().all()
for upload in uploads:
upload.invalidated_at = now
upload.invalidation_reason = action_code
result['uploads'].append(int(upload.id))
if task is not None and action_code in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
'retry_inventory_from_matching',
}:
# [BE-放行-恢复] 本动作已把当前匹配行置 is_current=False(上方),必须同步清空任务级
# 派生状态,否则 UI 与 Gate 在下一轮重匹配前仍读到旧 match_status/shortage/line_results,
# 出现"已重试却仍显示旧缺货"的矛盾。
task.match_status = None
task.shortage_json = None
task.line_results_json = None
if task is not None and (
action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}
):
# 仅库存文件级重试才清空导出指针;匹配/字段映射级重试只作废匹配,不改已生成文件。
task.export_file_path = None
task.export_file_name = None
for artifact in artifacts:
artifact.status = 'superseded'
result['artifacts'].append(int(artifact.id))
uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter(
ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}),
).with_for_update().all()
for upload in uploads:
upload.invalidated_at = now
upload.invalidation_reason = action_code
result['uploads'].append(int(upload.id))
db.session.flush()
return result
@@ -132,15 +195,16 @@ def invalidate_excel_regeneration_only(
if not task_id:
return result
from app.models import ShippingNotice, ShippingReservation
from app.models import ShippingOrderTask, ShippingReservation
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
task = db.session.get(ShippingNotice, task_id)
task = db.session.get(ShippingOrderTask, task_id)
if task is None:
return result
now = datetime.utcnow()
notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()]
artifacts = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task_id,
ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(),
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).with_for_update().all()
for artifact in artifacts:
@@ -195,9 +259,6 @@ def invalidate_excel_regeneration_only(
metadata={'execution_no': execution.execution_no, 'attempt_id': attempt_id},
source='process_gate',
)
if artifacts:
task.export_file_path = None
task.export_file_name = None
result['gates'] = invalidate_downstream_gates(
execution=execution,
change_type='excel_regeneration_only',
@@ -97,12 +97,21 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
if not task_no:
return None
review_status = _clean_text(getattr(task, "review_status", None)).lower()
match_status = _clean_text(getattr(task, "match_status", None)).lower()
pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower()
upload_status = _clean_text(getattr(task, "upload_status", None)).lower()
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
from app import db
from app.models import ShippingOrderTask
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
review_status = _clean_text(getattr(owner, "review_status", None)).lower()
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower()
pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower()
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
upload_attempt = latest_upload_attempt(task) if isinstance(task, ShippingNotice) else None
upload_status = _clean_text(getattr(upload_attempt, "status", None)).lower()
if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None):
if match_status == "shortage" or pending_reason == "shortage":
return {
"reason": "shortage",
"label": "异常:库存不足",
@@ -120,7 +129,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
"label": "异常:上传失败",
"summary": f"{task_no} 上传失败",
}
if _clean_text(getattr(task, "error_message", None)):
if _clean_text(getattr(owner, "error_message", None)):
return {
"reason": "error",
"label": "异常:处理失败",
@@ -19,8 +19,10 @@ INTERNAL_UUID_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
re.IGNORECASE,
)
# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{10}|\d{5})\b")
# Reservation 本体后可带一段半角或全角括号备注;普通尾随文本不属于合法值。
RESERVATION_VALUE_RE = re.compile(r"^(\d{10}|\d{5})(?!\d)\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$")
# ``@`` 是预约号与前缀说明的显式分隔,后缀复用 Reservation 值的括号备注契约。
RESERVATION_AT_SUFFIX_RE = re.compile(r"@\s*(\d{10}|\d{5})(?!\d)(?=\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$)")
PR_NUMBER_LINE_RE = re.compile(
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
re.IGNORECASE,
@@ -57,29 +59,36 @@ def normalize_reservation_id(value: Any) -> str:
def extract_reservation_id(value: Any) -> str:
"""从原值提取 Reservation ID 候选;合法性必须另由 `is_valid_reservation_id` 判断。"""
"""标准化 Reservation ID,并识别 ``@`` 后带可选括号备注的预约号。
Args:
value: Reservation ID 字段原始值;仅允许整体纯数字,或明确 ``@`` 分隔后可带括号备注的纯数字。
Returns:
str: 已确认的五位或十位纯数字 Reservation ID;普通尾随文本或金额文本返回空字符串。
"""
text = str(value or "").strip()
if not text:
return ""
direct = normalize_reservation_id(text)
if looks_like_reservation_id(direct):
return direct
direct_match = RESERVATION_VALUE_RE.fullmatch(direct)
if direct_match:
return direct_match.group(1)
match = RESERVATION_AT_SUFFIX_RE.search(text)
if match:
return match.group(1)
if "@" in text:
tail = normalize_reservation_id(text.rsplit("@", 1)[-1])
if looks_like_reservation_id(tail):
return tail
return direct
return match.group(1) if match else ""
def find_reservation_id_in_document(text: str) -> str:
"""扫描全文 PR Number 行或 @1000140351 后缀,提取文档级 Reservation ID。"""
"""扫描全文 PR Number 行或 ``@`` 分隔、可带括号备注的 Reservation ID。
Args:
text: 文档原始文本;仅接受 ``@`` 后可带括号备注的完整五位或十位纯数字。
Returns:
str: 已验证的五位或十位纯数字 Reservation ID;无明确分隔证据时返回空字符串。
"""
body = str(text or "")
if not body.strip():
return ""
@@ -19,6 +19,7 @@ from app.models import (
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingOrderSnapshot,
ShippingOrderTask,
ShippingReservation,
ShippingNotice,
)
@@ -38,7 +39,7 @@ def _decimal(value: Any) -> Decimal:
return result
def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]:
def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]:
"""由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
@@ -72,11 +73,18 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]:
code='SHIPPING.RESERVATION_PO_CONFLICT',
details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized},
)
elif row.task_id != task.id or row.snapshot_line_id != line.id:
elif (
row.task_id != task.id
or row.snapshot_line_id != line.id
or row.part_number != part_number
or row.required_qty != _decimal(line.qty)
):
if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}:
raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED')
if row.part_number != part_number or row.required_qty != _decimal(line.qty):
if task.supersedes_task_id == row.task_id:
# 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version),
# Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。
if row.task_id == task.id:
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number)
registered.append(row)
continue
@@ -96,20 +104,40 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]:
return registered
def _owner_task(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask:
"""将 Notice/OT 输入统一解析为该任务所属的 OT(shipping_order_tasks 聚合根)。"""
if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None)
owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id is not None else None
if owner is None:
raise ConflictError('Shipping notice has no order task', code='SHIPPING.ORDER_TASK_REQUIRED')
return owner
def _transfer_confirmed_revision(
reservation: ShippingReservation,
*, task: ShippingNotice,
*, task: ShippingOrderTask,
line: Any,
part_number: str,
) -> None:
"""仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。"""
"""
同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。
核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``,
Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。
"""
owner = _owner_task(task)
previous = {
'task_id': reservation.task_id,
'snapshot_line_id': reservation.snapshot_line_id,
'part_number': reservation.part_number,
'qty': str(reservation.required_qty),
}
reservation.task_id = task.id
# 保留同一 ShippingOrderTask:版本 bump,Reservation/事件仍指向该 OT。
owner.order_data_version = int(owner.order_data_version or 1) + 1
owner.progress_version = int(owner.progress_version or 0) + 1
reservation.task_id = owner.id
reservation.snapshot_line_id = line.id
reservation.part_number = part_number
reservation.required_qty = _decimal(line.qty)
@@ -119,16 +147,13 @@ def _transfer_confirmed_revision(
'reservation_id': reservation.reservation_id,
'previous': previous,
'proposed': {
'task_id': task.id,
'task_id': owner.id,
'snapshot_line_id': line.id,
'part_number': part_number,
'qty': str(reservation.required_qty),
},
}
log_task_event(task, 'reservation_revision_confirmed', details)
parent = db.session.get(ShippingNotice, task.supersedes_task_id)
if parent is not None:
log_task_event(parent, 'reservation_revision_superseded', details)
log_task_event(owner, 'reservation_revision_confirmed', details)
def record_inventory_verification(
@@ -204,7 +229,7 @@ def reserve_available_for_artifact(
released_reservation_ids = {
int(row.id)
for row in ShippingReservation.query.filter(
ShippingReservation.task_id == task.id,
ShippingReservation.task_id == _inventory_task_id(task),
ShippingReservation.id.in_(verification_reservation_ids),
ShippingReservation.snapshot_line_id.in_(released_ids),
).all()
@@ -220,7 +245,7 @@ def reserve_available_for_artifact(
}
rows = (
ShippingReservation.query.filter(
ShippingReservation.task_id == task.id,
ShippingReservation.task_id == _inventory_task_id(task),
ShippingReservation.status.in_({'available', 'pending'}),
ShippingReservation.id.in_(set(verification_lines)),
)
@@ -268,7 +293,7 @@ def current_available_snapshot_line_ids(
(最新核验轮次, 本次可导出的冻结订单行 ID)。
"""
verification = (
ShippingInventoryVerification.query.filter_by(task_id=task.id, status='completed')
ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed')
.order_by(ShippingInventoryVerification.id.desc()).first()
)
if verification is None:
@@ -278,7 +303,7 @@ def current_available_snapshot_line_ids(
released_reservation_ids = {
int(row.id)
for row in ShippingReservation.query.filter(
ShippingReservation.task_id == task.id,
ShippingReservation.task_id == _inventory_task_id(task),
ShippingReservation.id.in_(verification_reservation_ids),
ShippingReservation.snapshot_line_id.in_(released_ids),
).all()
@@ -293,7 +318,7 @@ def current_available_snapshot_line_ids(
)
}
reservations = ShippingReservation.query.filter(
ShippingReservation.task_id == task.id,
ShippingReservation.task_id == _inventory_task_id(task),
ShippingReservation.id.in_(reservation_ids),
ShippingReservation.status.in_({'available', 'pending'}),
).all() if reservation_ids else []
@@ -305,3 +330,7 @@ def current_available_snapshot_line_ids(
if not line_ids:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
return verification, line_ids
def _inventory_task_id(task: Any) -> int:
"""返回库存事实所属 OT ID;正式 Notice 通过 order_task_id 关联 OT。"""
linked = getattr(task, 'order_task_id', None)
return int(linked) if linked is not None else int(task.id)
@@ -12,7 +12,8 @@ from __future__ import annotations
import json
from typing import Any
from app.models import ShippingNotice
from app import db
from app.models import ShippingNotice, ShippingOrderIntake, ShippingOrderTask
from app.services.agent_runtime_context.builder import build_agent_runtime_context
from app.services.shipping_notice.reference_context import build_shipping_reference_context
@@ -74,7 +75,9 @@ def _build_refs(
"""
refs: dict[str, str] = {}
task_no = _task_no(task)
file_name = _clean_text(getattr(task, "source_file_name", None))
file_name = ''
if getattr(task, 'source_intake_id', None):
file_name = _clean_text(getattr(db.session.get(ShippingOrderIntake, int(task.source_intake_id)), 'filename', None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
refs["task_no"] = task_no
@@ -114,16 +117,26 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]:
state_hint["focus_task_no"] = task_no
if task is not None:
owner = task
if isinstance(task, ShippingNotice) and task.order_task_id:
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or ''
upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip()
for attr, key in (
("current_step", "current_step"),
("review_status", "review_status"),
("match_status", "match_status"),
("pending_human_reason", "pending_human_reason"),
("upload_status", "upload_status"),
(None, "match_status"),
(None, "upload_status"),
):
value = _clean_text(getattr(task, attr, None))
value = match_status if key == 'match_status' else upload_status if key == 'upload_status' else _clean_text(getattr(owner, attr, None))
if value:
state_hint[key] = value
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
pending_reason = _clean_text(task_blocking_reason(task))
if pending_reason:
state_hint['pending_human_reason'] = pending_reason
return state_hint
@@ -145,10 +158,16 @@ def _build_summary(
Returns:
200 字以内的现场摘要。
"""
owner = task
if isinstance(task, ShippingNotice) and task.order_task_id:
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
pieces: list[str] = []
task_no = _task_no(task)
file_name = _clean_text(getattr(task, "source_file_name", None))
current_step = _clean_text(getattr(task, "current_step", None))
file_name = ''
if getattr(owner, 'intake_id', None):
intake = db.session.get(ShippingOrderIntake, int(owner.intake_id))
file_name = _clean_text(getattr(intake, 'filename', None))
current_step = _clean_text(getattr(owner, "current_step", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
pieces.append(f"当前任务 {task_no}")
File diff suppressed because it is too large. Load diff
@@ -94,7 +94,8 @@ def _spec(
)
# [STEP 1] 锁定的 58 项标准目录。Reservation 可同时位于订单头和订单行,
# [STEP 1] 锁定的 58 项标准目录。line_no 是系统生成且只读的订单项次,
# 不参与 Schema 派生规则配置;Reservation 可同时位于订单头和订单行,
# 由行级值覆盖订单头值;所有标准字段均可按 Schema 配置抽取规则。
_STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
_spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'),
@@ -121,12 +122,8 @@ _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = (
_spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'),
_spec('order_remark', 'header', 'string', '订单备注', '订单头备注'),
_spec('reservation_id', 'header', 'string', '预约单号', '可选的订单级库存占用/预约单标识;明细可覆盖'),
_spec(
'line_no', 'line', 'string', '内部项次',
'内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;'
'仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关',
),
_spec('reservation_id', 'line', 'string', '预约单号', '可选的行级库存占用/预约单标识;优先于订单头', fulfillment_role='reservation_identity'),
_spec('line_no', 'line', 'integer', '内部项次', '订单明细的系统项次;按订单从 1 开始生成,创建后不可编辑或覆盖'),
_spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'),
_spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'),
_spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'),
@@ -1,18 +1,16 @@
"""
services/shipping_notice/state_machine.py
用途:发货通知检查点(checkpoint)与内部流程状态映射,负责任务 DB 字段与流程事实映射。
依赖:models.ShippingNotice、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind;
resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台,
Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。
扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
(导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记)
- 用户动作的定义、授权与审计统一由 process_gate_contract / Gate Attempt 负责;
checkpoint 不得派生、下发或执行用户按钮。
用途:发货通知任务 DB 字段迁移(TaskTransition)与位置/用户模式解析(Gate + review 回退)。
依赖:models.ShippingNotice/ShippingOrderTask、constants(RS_*/PH_*)、
process_gate_contract.derive_*(Gate-first)。
逻辑:tools/workspace 经 apply_task_transition 写库;resolve_task_ui_state 仅:
(1) 有活动 Execution 时用 Gate derive_position / derive_user_mode;
(2) 否则仅凭 review_status 做薄回退。
禁止领域标量/OT stage 级联裁决;无 checkpoint API 别名;非独立 CP 状态机。
POSITION_USER_MODE 仅为可选位置→UserMode 查找表,不是状态机。
build_task_ui_state 可传入已查 Gate 摘要,经 _ui_state_from_process_gate 派生,避免二次查库。
履约写操作入口为任务处理工作台;Chat 仅通知与跳转。
"""
from __future__ import annotations
@@ -21,27 +19,8 @@ from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app import db
from app.models import ShippingOrderExtraction, ShippingOrderLine, ShippingNotice
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
CP_CUSTOMER_REVIEW,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
@@ -52,36 +31,31 @@ from app.services.shipping_notice.constants import (
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
PH_UPLOAD_RESULT_UNKNOWN,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
RS_RSV_REQ,
RS_SHORTAGE_REVIEW,
RS_CONFIRMED,
)
def _task_has_dynamic_order_lines(task: ShippingNotice) -> bool:
"""判断当前已接受 Extraction 是否有订单行,用于在冻结前显示唯一的冻结入口。"""
extraction_id = task.current_order_extraction_id
if not extraction_id:
return False
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None or extraction.status != "accepted":
return False
return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None
def _workflow_owner(task: ShippingNotice):
"""Notice 查询流程状态时统一回到其 OT;Notice 不再作为流程状态事实源。"""
from app import db
if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None)
return db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else task
# ---------------------------------------------------------------------------
# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射)
# 用户模式枚举(与 derive_user_mode 值域对齐;不是 CheckPoint 状态机)
# ---------------------------------------------------------------------------
class CheckpointKind(StrEnum):
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传登记 / 完成。
CP_EXPORT_READY/GENERATED 映射为 WAIT_MANUAL_UPLOAD(Excel 后须登记凭据,非终态)。
"""
class UserMode(StrEnum):
"""用户处置粗分类:auto_continue / must_human / wait_manual_upload / complete。"""
AUTO_CONTINUE = "auto_continue"
MUST_HUMAN = "must_human"
@@ -89,188 +63,179 @@ class CheckpointKind(StrEnum):
COMPLETE = "complete"
# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue)
CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN,
CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN,
CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE,
# 库存源由规则自动裁决;未稳定只表示内部重算/治理等待,不能形成用户确认停点。
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.AUTO_CONTINUE,
CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE,
CP_RSV_REQ: CheckpointKind.MUST_HUMAN,
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN,
CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN,
CP_WAITING_UPLOAD: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE,
CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE,
CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_REJECTED: CheckpointKind.COMPLETE,
CP_UPLOADED: CheckpointKind.COMPLETE,
CP_COMPLETED: CheckpointKind.COMPLETE,
# 位置标签 → 用户模式(无 Gate 时的可选查找;键为 derive_position 字面量,非状态机)
POSITION_USER_MODE: dict[str, UserMode] = {
'parse_review': UserMode.MUST_HUMAN,
'customer_review': UserMode.MUST_HUMAN,
'upload_req': UserMode.MUST_HUMAN,
'inventory_pending': UserMode.AUTO_CONTINUE,
'inventory_source_review': UserMode.AUTO_CONTINUE,
'order_freeze': UserMode.AUTO_CONTINUE,
'rsv_req': UserMode.MUST_HUMAN,
'shortage_review': UserMode.MUST_HUMAN,
'notice_text_extraction_failed': UserMode.MUST_HUMAN,
'quality_issue': UserMode.MUST_HUMAN,
'upload_failed': UserMode.MUST_HUMAN,
'waiting_upload': UserMode.WAIT_MANUAL_UPLOAD,
'upload_result_unknown': UserMode.WAIT_MANUAL_UPLOAD,
'ready_to_match': UserMode.AUTO_CONTINUE,
'ready_to_export': UserMode.AUTO_CONTINUE,
'export_ready': UserMode.WAIT_MANUAL_UPLOAD,
'export_generated': UserMode.WAIT_MANUAL_UPLOAD,
'rejected': UserMode.COMPLETE,
'uploaded': UserMode.COMPLETE,
'completed': UserMode.COMPLETE,
}
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_KIND_REGISTRY.keys())
@dataclass(frozen=True)
class TaskUiState:
"""统一任务流程状态:checkpoint + STP kind,不包含用户动作。"""
"""位置标签 + 用户模式派生视图(非独立状态机事实)。"""
checkpoint: str | None
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
position: str | None
user_mode: UserMode = UserMode.AUTO_CONTINUE
def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
def user_mode_for_position(position: str | None) -> UserMode:
"""
按 checkpoint id 解析 STP 检查点分类。
按位置标签解析用户模式(查找表,非状态机)。
核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。
核心逻辑:查 POSITION_USER_MODE;无位置视为 auto_continue;未知位置默认 must_human。
Args:
position: derive_position / 位置字符串;可为 None。
Returns:
UserMode 枚举值。
"""
if not checkpoint:
return CheckpointKind.AUTO_CONTINUE
return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN)
if not position:
return UserMode.AUTO_CONTINUE
return POSITION_USER_MODE.get(str(position).strip(), UserMode.MUST_HUMAN)
def _task_ui_state(checkpoint: str | None) -> TaskUiState:
"""构造只含内部流程事实的 TaskUiState。"""
def _task_ui_state(position: str | None) -> TaskUiState:
"""构造位置 + 用户模式派生视图。"""
return TaskUiState(
checkpoint=checkpoint,
checkpoint_kind=checkpoint_kind_for(checkpoint),
position=position,
user_mode=user_mode_for_position(position),
)
def resolve_task_ui_state_from_fields(
*,
review_status: str | None,
pending_human_reason: str | None,
customer_resolution_status: str | None,
order_snapshot_id: int | None,
inventory_lines_json: Any,
match_status: str | None,
export_file_path: str | None,
has_dynamic_order_lines: bool,
upload_req_options: list[str] | None = None,
upload_req_task: ShippingNotice | None = None,
) -> TaskUiState:
def _ui_state_from_process_gate(
task: ShippingNotice,
gate: dict[str, Any] | None,
) -> TaskUiState | None:
"""
由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。
由已查得的 Gate 用户摘要派生 position/user_mode。
核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算,
供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。
upload_req_options / upload_req_task 是已废弃的兼容入参;checkpoint 不再解析用户动作。
核心逻辑:与 ``_gate_task_ui_state`` 同源;``build_task_ui_state`` 复用同一次
Gate 查询结果,禁止再调 ``resolve_task_ui_state`` 二次查 Execution。
Args:
task: ShippingNotice 或 ShippingOrderTask(取 review_status)。
gate: ``_process_gate_user_summary_for_task`` 返回值;无 Gate 时为 None。
Returns:
可派生时返回 TaskUiState;否则 None(调用方走 review_status 薄回退)。
"""
from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode
del upload_req_options
if not isinstance(gate, dict) or not gate.get('current_gate_code'):
return None
gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {}
if not isinstance(gate_view, dict):
gate_view = {}
status = str(gate_view.get('status') or '').strip().lower()
summary_status = str(gate.get('status') or '').strip().lower()
if summary_status in {'completed', 'done'}:
user_status = 'completed'
elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked':
user_status = 'waiting_human'
elif status == 'failed_terminal' or summary_status == 'failed':
user_status = 'failed'
else:
user_status = 'running'
gate_code = gate.get('current_gate_code') or gate_view.get('gate_code')
mode = derive_user_mode(
user_status=user_status,
gate_code=gate_code,
review_status=getattr(task, 'review_status', None),
lifecycle_stage=gate.get('lifecycle_stage'),
)
pos = derive_position(
gate_code=gate_code,
review_status=getattr(task, 'review_status', None),
)
try:
user_mode = UserMode(str(mode))
except ValueError:
user_mode = user_mode_for_position(pos)
return TaskUiState(position=pos, user_mode=user_mode)
upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower()
has_export = bool(str(export_file_path or "").strip())
# [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。
if upload_status in {"uploaded", "succeeded", "success"}:
return _task_ui_state(CP_UPLOADED)
if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}:
return _task_ui_state(CP_COMPLETED)
def _review_status_fallback_ui_state(task: ShippingNotice) -> TaskUiState:
"""
无活动 Gate 时仅凭 review_status 薄回退派生 position/user_mode。
if review_status == "rejected":
return _task_ui_state(CP_REJECTED)
核心逻辑:与 ``resolve_task_ui_state`` 无 Gate 分支同源。
"""
from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
reason = pending_human_reason
if reason == PH_RSV_REQ or review_status == RS_RSV_REQ:
return _task_ui_state(CP_RSV_REQ)
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
return _task_ui_state(CP_PARSE_REVIEW)
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED)
owner = _workflow_owner(task)
review_status = getattr(owner, 'review_status', None)
pos = derive_position(gate_code=None, review_status=review_status)
mode = derive_user_mode(
user_status=None,
gate_code=None,
review_status=review_status,
lifecycle_stage=None,
)
try:
user_mode = UserMode(str(mode))
except ValueError:
user_mode = user_mode_for_position(pos)
return TaskUiState(position=pos, user_mode=user_mode)
if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}:
return _task_ui_state(CP_CUSTOMER_REVIEW)
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
if not order_snapshot_id and has_dynamic_order_lines:
return _task_ui_state(CP_ORDER_FREEZE)
def _gate_task_ui_state(task: ShippingNotice) -> TaskUiState | None:
"""
有活动 Execution 时用 Gate derive_*;否则 None(调用方走 review_status 薄回退)。
# Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status,
# 也不能退回“处理中”或丢失下载/登记动作。
if has_export:
return _task_ui_state(CP_EXPORT_READY)
懒导入 ui_state,避免与 resolve 循环依赖。
"""
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return _task_ui_state(CP_UPLOAD_REQ)
if (
inventory_lines_json
and not review_status
and not pending_human_reason
and not match_status
):
return _task_ui_state(CP_READY_MATCH)
if (
not inventory_lines_json
and not review_status
and not pending_human_reason
and has_dynamic_order_lines
):
return _task_ui_state(CP_INVENTORY_PENDING)
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
if has_export:
return _task_ui_state(CP_EXPORT_READY)
return _task_ui_state(CP_READY_EXPORT)
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_INV_UNAVAIL:
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
return _task_ui_state(CP_INVENTORY_SOURCE_REVIEW)
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
return _task_ui_state(RS_SHORTAGE_REVIEW)
if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed":
return _task_ui_state(CP_UPLOAD_FAILED)
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return _task_ui_state(CP_UPLOAD_RESULT_UNKNOWN)
if reason == PH_RPA_PENDING:
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}:
return _task_ui_state(CP_WAITING_UPLOAD)
return _task_ui_state(None)
return _ui_state_from_process_gate(task, _process_gate_user_summary_for_task(task))
def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
"""
将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind。
解析位置 + 用户模式:优先 Gate derive_*,否则仅凭 review_status 薄回退。
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
履约写操作由 Gate 投影生成 ui_state.actions;Chat 不再作为写入口。
核心逻辑:无活动 Execution 时调用 derive_position(gate_code=None) /
derive_user_mode(仅 review_status);禁止 match_status / export_file_path /
pending_human / OT stage 级联充当状态机。
Args:
task: ShippingNotice 或 ShippingOrderTask。
Returns:
TaskUiState(position + user_mode)。
"""
return resolve_task_ui_state_from_fields(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
inventory_lines_json=task.inventory_lines_json,
match_status=task.match_status,
export_file_path=task.export_file_path,
has_dynamic_order_lines=_task_has_dynamic_order_lines(task),
upload_req_task=task,
)
gated = _gate_task_ui_state(task)
if gated is not None:
return gated
return _review_status_fallback_ui_state(task)
def checkpoint_for_task(task: ShippingNotice) -> str | None:
"""从 ShippingNotice DB 字段解析当前 checkpoint id。"""
return resolve_task_ui_state(task).checkpoint
def position_for_task(task: ShippingNotice) -> str | None:
"""返回当前派生位置标签。"""
return resolve_task_ui_state(task).position
def validate_registry() -> list[str]:
"""校验每个内部 checkpoint 都有确定的流程分类;测试用。"""
return [] if ALL_CHECKPOINT_IDS == frozenset(CHECKPOINT_KIND_REGISTRY) else ["checkpoint registry mismatch"]
"""校验位置→用户模式查找表非空;测试用。"""
return [] if POSITION_USER_MODE else ["POSITION_USER_MODE is empty"]
# ---------------------------------------------------------------------------
@@ -406,12 +371,15 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
transition: TaskTransition 枚举值。
"""
spec = TASK_TRANSITIONS[transition]
if spec.review_status is not _UNSET:
task.review_status = spec.review_status
if spec.pending_human_reason is not _UNSET:
task.pending_human_reason = spec.pending_human_reason
if spec.clear_error_message:
task.error_message = None
owner = _workflow_owner(task)
# 流程状态事实只写入 OT。正式 Notice 仅作为履约实体关联入口,
# 不再动态挂载 review/pending/error 等已删除的历史工作流字段。
if isinstance(owner, ShippingOrderTask) and spec.review_status is not _UNSET:
owner.review_status = spec.review_status
if isinstance(owner, ShippingOrderTask) and spec.pending_human_reason is not _UNSET:
owner.pending_human_reason = spec.pending_human_reason
if isinstance(owner, ShippingOrderTask) and spec.clear_error_message:
owner.error_message = None
# [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。
try:
@@ -4,9 +4,10 @@ services/shipping_notice/stp_line_inventory_match.py
用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。
依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、
inventory_source_rules、ShippingOrderSnapshot。
逻辑:ensure_inventory 合并候选快照行;match 仅在冻结候选集内检索;多文件命中为冲突;
唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);
人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
"""
from __future__ import annotations
@@ -272,23 +273,25 @@ def match_order_lines_across_candidates(
"""
跨候选库存行按有效 Reservation + Part Number + Unit 匹配。
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
Args:
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
inventory_lines: 已打 ``__source_code`` 的库存行。
inventory_lines: 库存行;``__source_code`` 可选(多源合并时用于冲突裁决)。
header_reservation_id: 头级 Reservation,用于行级回退。
Returns:
match_status、line_results、shortage_json、resolutions。
"""
# [STEP 1] 按 (reservation, part, unit, source) 聚合可用量与样例行。
# 无 __source_code 时 source='':表示“当前已载入 Excel 内的行”,不得因缺标签跳过。
buckets: dict[tuple[str, str, str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = _inventory_row_key(row)
if key is None:
continue
source = str(row.get('__source_code') or '').strip().upper()
if not source:
continue
bucket_key = (key[0], key[1], key[2], source)
bucket = buckets.get(bucket_key)
if bucket is None:
@@ -336,10 +339,11 @@ def match_order_lines_across_candidates(
] if effective and part else []
# 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。
# 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。
# 无源标签的库存行视为“当前 Excel 已选源”,不因候选源列表再剔除。
source_hits = [
item for item in all_source_hits
if (
item['source_code'] in allowed_source_codes
(not item['source_code'] or item['source_code'] in allowed_source_codes)
if has_candidate_scope
else True
)
@@ -412,6 +416,10 @@ def match_order_lines_across_candidates(
else:
hit = source_hits[0]
available = hit['available_qty']
# 库存行无源标签时,回退到该行唯一候选源(选源阶段已确定)。
resolved_source = hit['source_code'] or (
allowed_source_codes[0] if len(allowed_source_codes) == 1 else ''
)
if available >= required and required > 0:
disposition = 'ok'
sample = hit['sample_row']
@@ -425,13 +433,13 @@ def match_order_lines_across_candidates(
'shortage_qty': 0.0,
'line_status': 'ok',
'disposition': disposition,
'resolved_inventory_source_code': hit['source_code'],
'resolved_inventory_source_code': resolved_source,
'inventory_file_no': sample.get('__inventory_file_no'),
'inventory_row_ref': {
'reservation_id': effective,
'part_number': part,
'unit': unit or None,
'source_code': hit['source_code'],
'source_code': resolved_source,
},
}
has_ok = True
@@ -447,7 +455,7 @@ def match_order_lines_across_candidates(
'shortage_qty': float(max(required - available, Decimal('0'))),
'line_status': 'partial' if available > 0 else 'shortage',
'disposition': disposition,
'resolved_inventory_source_code': hit['source_code'],
'resolved_inventory_source_code': resolved_source,
}
has_block = True
has_partial = available > 0
@@ -87,17 +87,53 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
Returns:
[{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。
"""
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower()
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
# 客户确认 / 人工阻断:迁移后 Task 直传事实字段为权威来源;缺失时回退 DB 投影。
customer_status = str(
getattr(task, 'customer_resolution_status', None)
or customer_confirmation_facts(task)['status']
or ''
).strip().lower()
pending = str(
getattr(task, 'pending_human_reason', None)
or task_blocking_reason(task)
or ''
).strip().lower()
direct_match_status = getattr(task, 'match_status', None)
if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask':
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values())
match_status = 'matched' if match_facts and all(
str(row.get('match_result') or '').strip().lower() == 'matched'
and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'}
for row in match_facts
) else ('shortage' if match_facts else '')
elif direct_match_status is None:
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower()
else:
match_status = str(direct_match_status or '').strip().lower()
review_status = str(getattr(task, 'review_status', '') or '').strip().lower()
has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip())
upload_status = str(getattr(task, 'upload_status', '') or '').strip().lower()
from app.services.shipping_notice.upload_attempt_service import (
latest_export_artifact,
project_notice_upload_status,
)
direct_export_file = getattr(task, 'export_file_name', None)
if direct_export_file:
has_export = True
else:
artifact = latest_export_artifact(task)
has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip())
projected_upload = project_notice_upload_status(task)
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} else
'upload_failed' if upload_status == 'failed' else
'uploaded' if projected_upload == 'uploaded' else
'upload_failed' if projected_upload == 'failed' else
'matched' if match_status or has_export else
'inventory_ready' if getattr(task, 'inventory_lines_json', None) else
'inventory_ready' if has_ready_inventory_file_for_task(task) else
'pending_review' if pending or review_status else 'created'
)
@@ -74,7 +74,7 @@ def field_conflict_gate_response(
'issues': open_field_conflict_issues(task),
},
},
checkpoint='parse_review',
position='parse_review',
stop_agent_turn=True,
forbidden_next_tools=blocked,
)
@@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake
from app.services.shipping_notice.constants import CP_TASK_EXISTS
from app.services.shipping_notice.constants import POSITION_TASK_EXISTS
from app.services.shipping_notice.task_order_field_editor import (
current_header_field_values,
retire_current_order_extraction,
@@ -129,7 +129,7 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
task_id=existing_by_no.task_no,
message=f"已找到发货任务 {existing_by_no.task_no},将继续处理该任务。",
data=qs_serialize_task(existing_by_no, TaskProjection.TOOL_INTERNAL),
checkpoint=CP_TASK_EXISTS,
position=POSITION_TASK_EXISTS,
)
if conv_id:
existing = (
@@ -146,7 +146,7 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。"
),
data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL),
checkpoint=CP_TASK_EXISTS,
position=POSITION_TASK_EXISTS,
)
# [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。
@@ -2,7 +2,7 @@
services/shipping_notice/tool_response.py
用途:统一构建发货通知 Tool 的 JSON 响应结构。
依赖:state_machine 中的 checkpoint 解析能力;ShippingProcessExecution。
依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。
"""
@@ -83,7 +83,7 @@ def tool_response(
data: dict[str, Any] | None = None,
human_options: list[str] | None = None,
action_buttons: list[dict[str, str]] | None = None,
checkpoint: str | None = None,
position: str | None = None,
next_required_action: str | None = None,
forbidden_next_tools: list[str] | None = None,
stop_agent_turn: bool = False,
@@ -92,11 +92,12 @@ def tool_response(
"""
构建发货通知 Tool 标准 JSON 响应。
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint;
显式 checkpoint 优先(如 parse_ok、task_exists)。
若任务已有 ProcessExecution:不再填充旧动作字段,避免与 Gate 双真相。
核心逻辑:未显式传 position 时从 task 派生位置;显式 position 优先
(如 parse_ok、task_exists)。若任务已有 ProcessExecution:不再填充旧动作字段,
避免与 Gate 双真相。
Args:
position: 进程位置标签;None 时从 resolve_task_ui_state(task).position 推导。
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
extra: 需要保留在顶层的额外业务字段。
@@ -109,12 +110,12 @@ def tool_response(
gate_owns_recovery = _task_has_process_execution(task)
# action_buttons 是历史调用参数,仅为兼容调用方签名;绝不进入对外响应。
del action_buttons
resolved_checkpoint = checkpoint
resolved_position = position
# 旧 human_options 参数仅保留调用签名兼容,绝不返回。用户动作必须由 Gate DTO 授权。
del human_options
if checkpoint is None and task is not None:
if position is None and task is not None:
ui = resolve_task_ui_state(task)
resolved_checkpoint = ui.checkpoint
resolved_position = ui.position
payload: dict[str, Any] = {
"status": status,
@@ -124,8 +125,8 @@ def tool_response(
if task_id:
payload["task_id"] = task_id
# [STEP] 业务按钮统一由 ui_state.actions 返回;Tool 响应不再生成旧 human_options/action_buttons。
if resolved_checkpoint:
payload["checkpoint"] = resolved_checkpoint
if resolved_position:
payload["position"] = resolved_position
if next_required_action and not gate_owns_recovery:
payload["next_required_action"] = _sanitize_user_facing_text(next_required_action)
if forbidden_next_tools:
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,13 @@
"""
services/shipping_notice/upload_attempt_service.py
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,任务工作面通过 Attempt 查询结果。
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认;并提供
Notice 面 upload_status / facts.upload_state 的唯一投影归一。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机、
process_gate_contract.PROJECTION_UPLOAD_STATES(facts 词汇)。
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded。
Attempt 内成功词为 succeeded,Artifact 为 uploaded;对外 API 字段经
project_notice_upload_status 统一为 uploaded,禁止调用方再扩同义词集合。
"""
from __future__ import annotations
@@ -22,6 +26,9 @@ from app.models import (
ShippingUploadAttempt,
)
# Attempt 在途词 → Notice 面 uploading;成功词在投影内按层翻译,不对外暴露别名。
_UPLOAD_IN_FLIGHT_TOKENS = frozenset({'running', 'uploading', 'triggered', 'queued'})
def _formal_notice(task: ShippingNotice | Any) -> ShippingNotice | None:
"""解析上传事实所属的正式 Notice;OT 在 Notice 生成前不产生上传事实。"""
@@ -105,6 +112,78 @@ def latest_upload_attempt(task: ShippingNotice) -> ShippingUploadAttempt | None:
).first()
def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
"""投影 Notice 面 upload_status(货代聚合/任务详情对外字段)。
核心逻辑:优先读最新 Attempt,缺则回退 Artifact。
Attempt 成功词 succeeded、Artifact 成功词 uploaded → 一律输出 uploaded。
调用方只允许判断 ``== 'uploaded'`` 或使用 has_verified_upload_success;禁止再读 Attempt 原词做成败。
Args:
task: 正式 Notice,或可解析到 Notice 的 OT。
Returns:
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
"""
attempt = latest_upload_attempt(task)
if attempt is not None:
status = str(getattr(attempt, 'status', None) or '').strip().lower()
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
if status == 'succeeded':
return 'uploaded'
if status in _UPLOAD_IN_FLIGHT_TOKENS:
return 'uploading'
if status == 'pending':
return 'pending'
if status == 'failed':
return 'failed'
if status in {'timed_out', 'unknown'}:
return 'unknown'
return status or None
artifact = latest_export_artifact(task)
if artifact is None:
return None
status = str(getattr(artifact, 'status', None) or '').strip().lower()
if status == 'uploaded':
return 'uploaded'
if status == 'uploading':
return 'uploading'
if status == 'ready':
return 'pending'
return status or None
def project_facts_upload_state(task: ShippingNotice | Any) -> str:
"""投影 facts.upload_state,取值必须落在 PROJECTION_UPLOAD_STATES。
核心逻辑:与 Notice upload_status 同源读取;成功按 facts 契约输出 succeeded
(Attempt.succeeded / Artifact.uploaded → succeeded)。
Args:
task: 正式 Notice 或可解析到 Notice 的 OT。
Returns:
not_created | uploading | succeeded | failed | manual_upload_pending。
"""
attempt = latest_upload_attempt(task)
artifact = latest_export_artifact(task)
if attempt is None:
if artifact is not None and str(getattr(artifact, 'status', None) or '').strip().lower() == 'uploaded':
return 'succeeded'
return 'not_created'
status = str(getattr(attempt, 'status', None) or '').strip().lower()
if status == 'succeeded':
return 'succeeded'
if status in _UPLOAD_IN_FLIGHT_TOKENS or status == 'pending':
return 'uploading'
if status == 'failed':
return 'failed'
if status in {'timed_out', 'unknown'}:
return 'manual_upload_pending'
return 'not_created'
def has_verified_upload_success(task: ShippingNotice) -> bool:
"""判断任务是否具备可审计的货代上传成功事实。
@@ -2,8 +2,11 @@
services/shipping_notice/user_facing_status.py
用途:将任务 DB / 状态机内部码转为面向用户的中文阶段描述,并过滤 Tool 响应中的内部字段。
依赖:models.ShippingNotice、constants、state_machine.resolve_task_ui_state。
逻辑:get_task_status 与 tool_response 序列化时调用;STP 多源阻断优先于通用 shortage 文案。
依赖:models.ShippingNotice、constants、process_gate_contract.derive_position、
ui_state._process_gate_user_summary_for_task、state_machine.resolve_task_ui_state(回退)。
逻辑:get_task_status 与 tool_response 序列化时调用;阶段标签优先 Gate position,
无 Execution 时回退 ui.position;STP 多源阻断优先于通用 shortage 文案;
user_facing_stage_label_for_position 供已持有 position 的调用方免二次查 Gate。
"""
from __future__ import annotations
@@ -11,18 +14,18 @@ from __future__ import annotations
from app import db
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
POSITION_EXPORT_READY,
POSITION_INVENTORY_PENDING,
POSITION_PARSE_REVIEW,
POSITION_READY_EXPORT,
POSITION_READY_MATCH,
POSITION_REJECTED,
POSITION_RSV_REQ,
POSITION_UPLOADED,
POSITION_COMPLETED,
POSITION_UPLOAD_FAILED,
POSITION_UPLOAD_REQ,
POSITION_WAITING_UPLOAD,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_SHORTAGE,
@@ -39,20 +42,23 @@ TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
}
)
_CHECKPOINT_LABELS: dict[str, str] = {
CP_PARSE_REVIEW: "待确认发货通知解析",
CP_UPLOAD_REQ: "待上传或获取库存",
CP_INVENTORY_PENDING: "待上传库存",
CP_RSV_REQ: "待补充 Reservation ID",
# 键对齐 Gate derive_position / 位置标签。
_POSITION_LABELS: dict[str, str] = {
POSITION_PARSE_REVIEW: "待确认发货通知解析",
POSITION_UPLOAD_REQ: "待上传或获取库存",
POSITION_INVENTORY_PENDING: "待上传库存",
POSITION_RSV_REQ: "待补充 Reservation ID",
"customer_review": "待确认客户",
"quality_issue": "质量异常待处理",
"shortage_review": "库存不足,无法发货",
CP_READY_MATCH: "待匹配库存",
CP_READY_EXPORT: "待生成发货 Excel",
CP_EXPORT_READY: "待人工上传登记",
CP_WAITING_UPLOAD: "待人工上传登记",
CP_UPLOAD_FAILED: "货代上传失败,待处理",
CP_REJECTED: "任务已驳回",
CP_UPLOADED: "已完成上传",
CP_COMPLETED: "任务已完成",
POSITION_READY_MATCH: "待匹配库存",
POSITION_READY_EXPORT: "待生成发货 Excel",
POSITION_EXPORT_READY: "待人工上传登记",
POSITION_WAITING_UPLOAD: "待人工上传登记",
POSITION_UPLOAD_FAILED: "货代上传失败,待处理",
POSITION_REJECTED: "任务已驳回",
POSITION_UPLOADED: "已完成上传",
POSITION_COMPLETED: "任务已完成",
}
_PROCESS_STATUS_LABELS: dict[str, str] = {
@@ -79,12 +85,49 @@ _PENDING_REASON_LABELS: dict[str, str] = {
}
def user_facing_stage_label_for_position(
task: ShippingNotice,
*,
position: str | None,
) -> str | None:
"""
在调用方已持有 position 时生成标题,避免再查 Gate。
核心逻辑:多源阻断与 pending_human_reason 优先;否则用位置标签表。
无法判定时返回 None,由调用方回退 ``user_facing_task_stage``。
Args:
task: 任务实体(读 step_payload / pending_human_reason)。
position: 已派生的位置码。
Returns:
中文阶段标题;无法仅凭已知事实判定时为 None。
"""
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
payload = getattr(owner, 'step_payload_json', None)
payload = payload if isinstance(payload, dict) else {}
if payload.get('multi_source_excel_block'):
return '多库存源冲突,待人工处理'
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
reason = str(task_blocking_reason(owner) or '').strip()
if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason]
pos = str(position or '').strip()
if pos and pos in _POSITION_LABELS:
return _POSITION_LABELS[pos]
return None
def user_facing_task_stage(task: ShippingNotice) -> str:
"""
Short Chinese label for chat / get_task_status — no snake_case codes.
核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending`
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖;
这类细粒度状态被通用位置文案(如“待上传或获取库存”)覆盖;
其次 Gate derive_position;无 Gate 回退 resolve_task_ui_state.position;
STP 多源 Excel 阻断覆盖通用 shortage 文案。
"""
# Notice 只承载正式单据;流程/UI 状态归属关联 OT。
@@ -100,9 +143,23 @@ def user_facing_task_stage(task: ShippingNotice) -> str:
reason = str(task_blocking_reason(owner) or '').strip()
if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason]
# [STEP] Gate-first:位置标签查找。
from app.services.shipping_notice.process_gate_contract import derive_position
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
gate = _process_gate_user_summary_for_task(owner)
if isinstance(gate, dict) and gate:
pos = derive_position(
gate_code=gate.get('current_gate_code'),
review_status=getattr(owner, 'review_status', None),
)
if pos and pos in _POSITION_LABELS:
return _POSITION_LABELS[pos]
ui = resolve_task_ui_state(owner)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
if ui.position and ui.position in _POSITION_LABELS:
return _POSITION_LABELS[ui.position]
lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active")
return lifecycle == "active" and "处理中" or "已结束"
+123 -90
View File
@@ -26,38 +26,6 @@ def pytest_configure(config):
)
@pytest.fixture(autouse=True)
def _capture_legacy_order_rows_for_tests(monkeypatch):
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
from app.models import ShippingNotice
original_init = ShippingNotice.__init__
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
def _init(self, **kwargs):
rows = kwargs.pop('lines_json', None)
kwargs.pop('order_lines_migration_status', None)
header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs}
original_init(self, **kwargs)
if rows is not None:
self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)]
for key, value in header_values.items():
setattr(self, f'_test_{key}', value)
monkeypatch.setattr(ShippingNotice, '__init__', _init)
for key in (*legacy_headers, 'lines_json'):
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
monkeypatch.setattr(
ShippingNotice,
key,
property(
lambda task, name=storage: getattr(task, name, None),
lambda task, value, name=storage: setattr(task, name, value),
),
raising=False,
)
def parse_api_error(body: dict) -> dict:
"""
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
@@ -193,12 +161,17 @@ def seed_task_inventory_source(
*,
source_code: str = "DSV360_AWSDU",
) -> None:
"""测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。"""
"""测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。"""
_ensure_test_task_dynamic_order(task)
from app.services.shipping_notice.inventory_source_rules import (
compute_routing_fingerprint,
extract_routing_context,
)
from app import db
from app.models import ShippingOrderTask
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
_ensure_test_task_dynamic_order(task)
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task
from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
@@ -207,35 +180,39 @@ def seed_task_inventory_source(
source = get_database_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
context = extract_routing_context(task)
resolution = resolve_inventory_source_identity(source, context)
if not resolution.ok or not resolution.identity:
raise ValueError(
f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
)
identity = resolution.identity
task.inventory_source_code = identity.source_code
task.inventory_connector_type = identity.connector_type
task.inventory_warehouse_id = identity.warehouse_id
task.inventory_source_status = "resolved"
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id:
freeze_test_task_order_snapshot(task)
if not owner.order_snapshot_id:
raise ValueError('test task must have a frozen order snapshot before inventory source selection')
freeze_candidates_for_task(
owner,
adjudication=InventorySourceAdjudication(
status='resolved',
method='test_fixture',
source_code=str(source.get('source_code') or source_code).strip().upper(),
candidates=[source],
config_version=inventory_sources_runtime_version(),
),
)
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
if task.order_snapshot_id:
from app import db
from app.models import ShippingOrderTask
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
_ensure_test_task_dynamic_order(task)
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
if owner.order_snapshot_id:
return
rows = list(getattr(task, '_test_order_rows', []) or [])
if not rows:
lines = task.lines_json if isinstance(task.lines_json, list) else []
lines = getattr(task, 'lines_json', None)
lines = lines if isinstance(lines, list) else []
rows = [
{
'part_number': row.get('part_number'),
@@ -244,33 +221,19 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
}
for row in lines if isinstance(row, dict)
]
task._test_order_rows = rows
_ensure_test_task_dynamic_order(task)
task.order_data_version = int(task.order_data_version or 1)
from app import db
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
owner._test_order_rows = rows
_ensure_test_task_dynamic_order(owner)
owner.order_data_version = int(owner.order_data_version or 1)
from app.models import ShippingOrderExtraction
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
customer = getattr(task, 'customer', None)
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
extraction_id=extraction.id, role='bill_to',
).one_or_none() is None:
db.session.add(ShippingOrderCustomerMatch(
extraction_id=extraction.id, role='bill_to',
raw_name=customer.standard_name,
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
identity_fingerprint='r' * 64,
identity_rule_version='test.v1', resolution_method='manual',
confirmation_reason='测试确认', confirmed_by_id=None,
))
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
customer = getattr(owner, 'customer', None)
if extraction is not None and customer is not None:
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
freeze_order_snapshot(
task,
owner,
actor_id=None,
expected_order_data_version=int(task.order_data_version),
expected_order_data_version=int(owner.order_data_version),
freeze_mode='auto',
auto_freeze_policy={
'test_fixture': True,
@@ -284,6 +247,47 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
db.session.flush()
def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None:
"""为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。"""
from app import db
from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake
candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None
if candidate is None:
intake = ShippingOrderIntake(
intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id),
user_id=int(task.user_id), parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id,
primary_document_id=1, candidate_key=f'test-resolution-{task.id}',
candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task.candidate_id = candidate.id
if extraction is not None:
candidate.order_extraction_id = int(extraction.id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none()
if resolution is None:
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=candidate.intake_id,
resolution_version='test.v1', status='confirmed',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
identity_rule_set_checksum='t' * 64,
)
db.session.add(resolution)
resolution.status = 'confirmed'
resolution.confirmed_customer_id = customer.id
resolution.confirmation_method = 'test_fixture'
db.session.flush()
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
from decimal import Decimal
@@ -292,16 +296,35 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
from app.models import (
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchemaVersion,
ShippingOrderTask, User,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
if task.current_order_extraction_id is not None:
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
if task.id is None:
db.session.add(task)
db.session.flush()
user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first()
user_id = user_id[0] if isinstance(user_id, tuple) else user_id
owner = ShippingOrderTask(
task_no=f'OT-TEST-{task.task_no}',
user_id=int(user_id or 1),
status='ready',
current_step='customer_review',
)
db.session.add(owner)
db.session.flush()
task.order_task_id = owner.id
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
if owner.current_order_extraction_id is not None:
return
rows = list(getattr(task, '_test_order_rows', []) or [])
if not rows:
return
if task.id is None:
db.session.add(task)
if owner.id is None:
db.session.add(owner)
db.session.flush()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
@@ -335,11 +358,11 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
required = {'part_number', 'reservation_id', 'qty'}
if not required.issubset(field_ids):
raise ValueError('RPA test schema lacks required order business purposes')
extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
for position, row in enumerate(rows):
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
db.session.add(line)
db.session.flush()
for code in required:
@@ -358,7 +381,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=json_value,
))
task.current_order_extraction_id = extraction.id
owner.current_order_extraction_id = extraction.id
db.session.flush()
@@ -425,9 +448,14 @@ def inventory_csv_with_warehouse(
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"source_code": str(task.inventory_source_code or ""),
"warehouse_id": str(task.inventory_warehouse_id or ""),
"source_code": str(source_code or ""),
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
}
@@ -464,6 +492,11 @@ def rpa_callback_payload(
status: str = "success",
) -> dict:
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"test-callback:{run_no}",
@@ -472,8 +505,8 @@ def rpa_callback_payload(
"file_path": str(file_path),
"run_no": run_no,
"source_run_no": run_no,
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
"source_code": source_code,
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
"attempt_no": 1,
"lease_token": "test-lease-token",
"candidate_set_id": 1,
@@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s
('failed', False, 'failed', '业务阻断失败 → failed'),
('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'),
('failed', True, 'retryable', '技术失败 retryable → retryable'),
('idle', False, 'idle', 'Idle → idle(默认)'),
('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'),
],
ids=lambda t: t[3] if isinstance(t, tuple) else '',
)
def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label):
"""[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。"""
def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label):
"""[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。"""
from app.services.shipping_notice.reconciliation_projector import project_case_user_status
case = _fake_case(status='draft')
+2 -2
View File
@@ -80,7 +80,7 @@ def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.submit_decision",
"action_type": "shipping.match_inventory",
"payload": {"task_no": task_no, "decision": "confirm"},
},
},
@@ -128,7 +128,7 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.submit_decision",
"action_type": "shipping.match_inventory",
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
},
},
+154 -1
View File
@@ -106,13 +106,14 @@ def test_export_scheduled_report_flow(monkeypatch):
def _download(*args, **kwargs):
calls.append("download")
captured["download_description"] = kwargs.get("description", "")
captured["download_dir"] = kwargs.get("download_dir", "")
return "download-object"
monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download)
result = module.export_crane_inventory_report(
page,
{"parameters": [], "source_code": "CRANE_TZR2"},
{"parameters": [], "source_code": "CRANE_TZR2", "__download_dir": "D:/tmp/crane-drop"},
trigger={"task_no": "SN-1001"},
env=lambda name, default="": default,
browser_timeout_ms=5_000,
@@ -124,6 +125,7 @@ def test_export_scheduled_report_flow(monkeypatch):
assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"]
assert captured["description"] == "HXOPS-CRANE_TZR2-TEST"
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
assert captured["download_dir"] == "D:/tmp/crane-drop"
def test_should_run_report_before_schedule_uses_driver_environment_only():
@@ -443,3 +445,154 @@ def test_resolve_download_mode_uses_driver_environment_only():
module = _load_export()
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
"""
expect_download 超时后,应短窗口扫描 downloads_path 并返回目录文件适配器。
断言意图:主路径事件丢失时复用 DSV 同款兜底,而不是直接失败。
"""
module = _load_export()
page = MagicMock()
locator = MagicMock()
fallback = MagicMock()
fallback.suggested_filename = "OnHandDetails.xlsx"
fallback_calls: list[dict] = []
class _TimeoutDownloadExpect:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
return False
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
@property
def value(self):
raise AssertionError("download event should not resolve")
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
monkeypatch.setattr(
module,
"_probe_scheduled_download_status",
lambda *_a, **_k: ("Download", locator),
)
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
def _fake_wait(*, download_dir, baseline_names, timeout_seconds):
fallback_calls.append(
{
"download_dir": str(download_dir),
"baseline_names": set(baseline_names),
"timeout_seconds": timeout_seconds,
}
)
return fallback
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
result = module._wait_and_click_scheduled_download(
page,
env=lambda name, default="": default,
browser_timeout_ms=1_000,
description="abc123",
expected_report_name="OnHandDetails.xlsx",
download_dir=str(tmp_path),
)
assert result is fallback
assert fallback_calls == [
{
"download_dir": str(tmp_path),
"baseline_names": set(),
"timeout_seconds": module._CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS,
}
]
def test_wait_and_click_scheduled_download_reraises_when_fallback_misses(tmp_path, monkeypatch):
"""
expect_download 超时且目录无新文件时,应继续抛出原超时。
断言意图:兜底失败不能吞掉异常。
"""
module = _load_export()
page = MagicMock()
class _TimeoutDownloadExpect:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
return False
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
monkeypatch.setattr(
module,
"_probe_scheduled_download_status",
lambda *_a, **_k: ("Download", MagicMock()),
)
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
monkeypatch.setattr(module, "_wait_for_new_download_file", lambda **_k: None)
with pytest.raises(TimeoutError, match="download"):
module._wait_and_click_scheduled_download(
page,
env=lambda name, default="": default,
browser_timeout_ms=1_000,
description="abc123",
download_dir=str(tmp_path),
)
def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_path, monkeypatch):
"""
Download 链接点击失败时不应进入目录兜底。
断言意图:避免点击失败后空等 15s。
"""
module = _load_export()
page = MagicMock()
fallback_called = {"value": False}
class _DownloadExpect:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return False
@property
def value(self):
raise AssertionError("should not reach download value")
page.expect_download.side_effect = lambda timeout=None: _DownloadExpect()
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
monkeypatch.setattr(
module,
"_probe_scheduled_download_status",
lambda *_a, **_k: ("Download", MagicMock()),
)
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: False)
def _fake_wait(**_kwargs):
fallback_called["value"] = True
return MagicMock()
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
with pytest.raises(RuntimeError, match="Download link click failed"):
module._wait_and_click_scheduled_download(
page,
env=lambda name, default="": default,
browser_timeout_ms=1_000,
description="abc123",
download_dir=str(tmp_path),
)
assert fallback_called["value"] is False
@@ -430,3 +430,60 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>'''],
)
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict():
"""邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。
回归:ZNE 邮件正文 PO 表把客户件号(504-006043-001)放进 PN 列并映射到
`part_number`,而 PDF 同一行的 `part_number` 是内部件号(D4-A08AR12000001)、
`customer_part_number` 是 504-006043-001。邮件值命中 PDF 的客户件号即同一料号,
不得判成 `part_number` 的 `supplement_field_conflict`。
"""
order = _order() # header PO 4518738152;line part D4-A08AR12000002
order['lines'][0]['fields'].append({
'field_id': 'customer-part', 'observations': [{'value': '504-006043-001'}],
})
supplement = {
'document_id': 44,
'rows': [{
'customer_po_number': '4518738152',
'part_number': '504-006043-001', # 邮件 PN 列,实为客户件号(MPN)
'evidence': {},
}],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)[0]
# PDF 内部件号保持不变,且不再误判 part_number 冲突
assert _value(merged['lines'][0]['fields'], 'part') == 'D4-A08AR12000002'
assert not any(item.get('field') == 'part_number' for item in merged['conflicts'])
def test_supplement_field_conflict_pdf_string_evidence_ref_does_not_crash():
"""坐标 PDF observation 的 evidence_ref 是字符串时不得崩溃(dict.update length1 回归)。
回归:`_supplement_field_conflict` 曾用 `dict(pdf.get('evidence_ref') or {})` 直接构造证据,
而坐标 PDF observation 的 `evidence_ref` 是字符串(如 `layout:...:row-7:qty`),
`dict(<字符串>)` 会按字符拆成长度 1 序列 → `dictionary update sequence element #0 has length 1; 2 is required`。
修复后改用 observation 的证据 dict(`layout_evidence`,或 `evidence_ref` 为 dict 时用其本身)。
"""
from app.services.shipping_notice.order_supplement_merge import _supplement_field_conflict
conflict = _supplement_field_conflict(
field_code='qty', config={'field_id': 'qty', 'field_code': 'qty'}, line_index=0,
pdf_observations=[{
'value': '30', 'document_id': 305,
'evidence_ref': 'layout:305:p1:t1:row-1:qty', # 字符串(坐标 evidence_ref,触发旧崩溃)
'layout_evidence': {'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty'},
}],
email_value='99', email_evidence={'table_index': 0, 'row_index': 1},
email_document_id=44, schema_version='v1',
)
assert conflict['conflict_key'] == '0:qty'
# evidence_ref 保持 dict 契约,并取 observation 的证据 dict(layout_evidence)
assert conflict['sources'][0]['evidence_ref'] == {
'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty',
}
assert conflict['sources'][1]['evidence_ref'] == {'table_index': 0, 'row_index': 1}
+83 -6
View File
@@ -14,6 +14,7 @@ import json
import os
import re
import sys
import time
from pathlib import Path
import pytest
@@ -648,9 +649,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
return _FakePlaywright()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
temp_roots: list[Path] = []
@@ -1346,7 +1349,7 @@ def test_summarize_inventory_batch_results_all_skipped_is_success():
assert summary["has_success"] is False
assert summary["status"] not in {"failed", "partial_failed"}
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
"""关闭会话复用时,每次都应在配置目录下生成新的 run_* 临时 profile。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
@@ -1371,9 +1374,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
@@ -1392,8 +1397,8 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
}
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monkeypatch, tmp_path):
"""会话复用开启时按 connector+rpa_profile 固定目录,且不得当作临时目录清理。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
@@ -1417,20 +1422,92 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser(
tmp_path / "downloads", reuse_dsv_session=True
tmp_path / "downloads",
reuse_session=True,
connector_type="crane_footprint",
profile_code="CRANE-MAIN",
)
assert context is not None
assert page is not None
assert profile_dir == tmp_path / "profile" / "dsv360_session"
assert profile_dir == tmp_path / "profile" / "crane_footprint__CRANE-MAIN_session"
assert observed["profile"] == str(profile_dir)
assert worker._should_cleanup_browser_profile(profile_dir) is False
assert (profile_dir / ".hxops_rpa_session_meta.json").is_file()
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
"""兼容旧参数 reuse_dsv_session:开启复用时落到 dsv360__* 持久目录。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
class _FakePage:
def set_default_timeout(self, value: int) -> None:
observed["timeout"] = value
class _FakeContext:
pages = [_FakePage()]
class _FakeChromium:
def launch_persistent_context(self, profile: str, **kwargs):
observed["profile"] = profile
return _FakeContext()
class _FakePlaywright:
chromium = _FakeChromium()
class _FakeStarter:
def start(self):
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser(
tmp_path / "downloads",
reuse_dsv_session=True,
connector_type="dsv360",
profile_code="DSV-A",
)
assert context is not None
assert page is not None
assert profile_dir == tmp_path / "profile" / "dsv360__DSV-A_session"
assert observed["profile"] == str(profile_dir)
assert worker._should_cleanup_browser_profile(profile_dir) is False
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
worker = _load_freight_rpa_worker()
profile_dir = tmp_path / "dsv360__OLD_session"
profile_dir.mkdir(parents=True)
stale_marker = profile_dir / "stale.txt"
stale_marker.write_text("keep-me", encoding="utf-8")
created = time.time() - (25 * 3600)
(profile_dir / ".hxops_rpa_session_meta.json").write_text(
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
encoding="utf-8",
)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
prepared = worker._prepare_reusable_session_profile(
profile_dir,
connector_type="dsv360",
profile_code="OLD",
)
assert prepared == profile_dir
assert not stale_marker.exists()
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
assert float(meta["created_at_unix"]) > created
def test_is_dsv_username_page_ignores_login_method_page_text():
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
worker = _load_freight_rpa_worker()
+414
View File
@@ -0,0 +1,414 @@
"""
backend/tests/test_gate_derivation.py
用途:验收 Gate 推导的粗分类 / 位置 / 待办分类,替代旧 checkpoint_kind。
依赖:process_gate_contract.derive_*、query_service._todo_category_from_gate、
ui_state._derived_*、user_facing_status、pytest。
逻辑:Task1–6 契约纯函数与消费点迁移断言;SQL CASE 双读过渡不在此覆盖。
"""
from __future__ import annotations
from app.services.shipping_notice.process_gate_contract import (
derive_position,
derive_todo_category,
derive_user_mode,
)
def test_user_mode_complete_when_rejected():
assert derive_user_mode(
user_status='completed',
gate_code=None,
review_status='rejected',
lifecycle_stage=None,
) == 'complete'
def test_user_mode_wait_upload_handoff():
assert derive_user_mode(
user_status='waiting_human',
gate_code='manual_upload_handoff',
review_status=None,
lifecycle_stage='freight_upload',
) == 'wait_manual_upload'
def test_user_mode_must_human():
assert derive_user_mode(
user_status='waiting_human',
gate_code='inventory_matching',
review_status=None,
lifecycle_stage='fulfillment_prep',
) == 'must_human'
def test_user_mode_auto():
assert derive_user_mode(
user_status='running',
gate_code='inventory_preparation',
review_status=None,
lifecycle_stage='fulfillment_prep',
) == 'auto_continue'
def test_position_review_dispositions():
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req'
def test_position_fulfillment():
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
def test_todo_category():
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception'
assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload'
assert derive_todo_category(user_mode='complete') == 'done'
assert derive_todo_category(user_mode='auto_continue') == 'in_progress'
def test_fetch_gate_positions_empty():
from app.services.shipping_notice.query_service import fetch_gate_positions
assert fetch_gate_positions([]) == {}
def test_fetch_gate_positions_batched(app):
"""关键断言:一次查询按 task_id 返回 current_gate_code / status。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.query_service import fetch_gate_positions
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='GATE-POS')
ot_a = ShippingOrderTask(
task_no='OT-GATE-POS-A',
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='step5_match_inventory',
progress_version=1,
)
ot_b = ShippingOrderTask(
task_no='OT-GATE-POS-B',
user_id=user.id,
conversation_id=session.session_id,
status='processing',
stage='inventory_fetching',
progress_version=1,
)
db.session.add_all([ot_a, ot_b])
db.session.flush()
db.session.add_all([
ShippingProcessExecution(
execution_no='SPE-GATE-POS-A',
task_id=int(ot_a.id),
status='blocked',
current_gate_code='inventory_sufficiency',
),
ShippingProcessExecution(
execution_no='SPE-GATE-POS-B',
task_id=int(ot_b.id),
status='active',
current_gate_code='inventory_preparation',
),
])
db.session.commit()
result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999])
assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency'
assert result[int(ot_a.id)]['status'] == 'blocked'
assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation'
assert 999999 not in result
def test_early_stop_uses_derive_user_mode(monkeypatch):
from app.services.shipping_notice import progress_workflow as pw
class FakeTask:
task_no = 'SN-1'
review_status = None
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda t: {
'current_gate': {
'status': 'blocked_manual',
'blocking_reason_code': 'inventory_shortage_review_required',
'gate_code': 'inventory_sufficiency',
},
'responsible_party': 'owner',
'lifecycle_stage': 'fulfillment_prep',
'current_gate_code': 'inventory_sufficiency',
'status': 'blocked',
},
)
assert pw._entry_user_mode(FakeTask()) == 'must_human'
def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch):
"""
回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为
blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停,
否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。
"""
from app.services.shipping_notice import progress_workflow as pw
class FakeTask:
task_no = 'OT-INV-EMPTY'
review_status = None
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda t: {
'current_gate': {
'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_file_empty',
'gate_code': 'inventory_preparation',
},
'current_blocking_gate': {
'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_file_empty',
'gate_code': 'inventory_preparation',
},
'responsible_party': 'worker',
'lifecycle_stage': 'fulfillment_prep',
'current_gate_code': 'inventory_preparation',
'status': 'blocked',
'blocking_reason_code': 'inventory_file_empty',
},
)
assert pw._entry_user_mode(FakeTask()) == 'auto_continue'
def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch):
"""RPA 耗尽属 needs_human,入口仍须早停,不能自动空转重试。"""
from app.services.shipping_notice import progress_workflow as pw
class FakeTask:
task_no = 'OT-INV-EXHAUSTED'
review_status = None
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda t: {
'current_blocking_gate': {
'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_rpa_exhausted',
'gate_code': 'inventory_preparation',
},
'lifecycle_stage': 'fulfillment_prep',
'current_gate_code': 'inventory_preparation',
'status': 'blocked',
'blocking_reason_code': 'inventory_rpa_exhausted',
},
)
assert pw._entry_user_mode(FakeTask()) == 'must_human'
def test_position_inventory_sufficiency():
assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review'
def test_todo_category_from_gate_positions():
from app.services.shipping_notice.query_service import _todo_category_from_gate
assert (
_todo_category_from_gate(
{'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'},
None,
)
== 'review'
)
assert (
_todo_category_from_gate(
{'current_gate_code': 'inventory_preparation', 'status': 'active'},
None,
)
== 'in_progress'
)
assert (
_todo_category_from_gate(
{'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'},
None,
)
== 'exception'
)
def test_user_facing_stage_uses_position(monkeypatch):
from app.services.shipping_notice import user_facing_status as ufs
class FakeTask:
step_payload_json = {}
pending_human_reason = None
lifecycle_status = 'active'
review_status = None
order_task_id = None
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
lambda t: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda t: {'current_gate_code': 'inventory_preparation'},
)
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
def test_derived_entry_surface_review():
from app.services.shipping_notice.ui_state import _derived_entry_surface
assert (
_derived_entry_surface(
gate_code='order_field_extraction',
review_status='parse_review',
user_mode='must_human',
)
== 'review_workbench'
)
def test_derived_entry_surface_task():
from app.services.shipping_notice.ui_state import _derived_entry_surface
assert (
_derived_entry_surface(
gate_code='artifact_generation',
review_status=None,
user_mode='wait_manual_upload',
)
== 'task_workbench'
)
def test_summary_prefers_gate_shortage_over_freeze(monkeypatch):
"""关键断言:Gate 短缺时摘要不再沿用 OT 默认 order_freeze 文案。"""
from app.services.shipping_notice import ui_state as us
class FakeTask:
task_no = 'OT-SHORT'
review_status = None
order_task_id = None
updated_at = None
error_message = None
step_payload_json = {}
monkeypatch.setattr(us, '_build_stp_facts', lambda t: None)
monkeypatch.setattr(us, '_collect_parse_stage_issues', lambda *a, **k: [])
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
lambda t: 'inventory_shortage_review_required',
)
monkeypatch.setattr(us, 'user_facing_task_stage', lambda t: '库存不足,无法发货')
monkeypatch.setattr(
'app.services.shipping_notice.stp_progress_contract.project_task_progress_nodes',
lambda t: [],
)
summary = us._build_task_summary(
FakeTask(),
'shortage_review',
user_mode='must_human',
gate_code='inventory_sufficiency',
)
assert '缺口' in summary['message'] or '库存' in summary['message']
assert summary['user_mode'] == 'must_human'
assert summary['entry_surface'] == 'task_workbench'
assert summary['next_auto_step'] is None
def test_rejected_maps_to_review_disposition():
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
def test_notice_text_failure_maps_to_quality_issue():
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
"""关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE')
ot = ShippingOrderTask(
task_no='OT-SQL-GATE-SHORT',
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='step5_match_inventory',
progress_version=1,
)
db.session.add(ot)
db.session.flush()
db.session.add(
ShippingProcessExecution(
execution_no='SPE-SQL-GATE-SHORT',
task_id=int(ot.id),
status='blocked',
current_gate_code='inventory_sufficiency',
)
)
db.session.commit()
cat = (
db.session.query(_order_task_todo_category_sql_expr())
.filter(ShippingOrderTask.id == ot.id)
.scalar()
)
assert cat == 'exception'
def test_sql_todo_category_prefers_gate_manual_upload(app):
"""关键断言:manual_upload_handoff → manual_upload。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE-MU')
ot = ShippingOrderTask(
task_no='OT-SQL-GATE-MU',
user_id=user.id,
conversation_id=session.session_id,
status='waiting_upload',
stage='freight_upload',
progress_version=1,
)
db.session.add(ot)
db.session.flush()
db.session.add(
ShippingProcessExecution(
execution_no='SPE-SQL-GATE-MU',
task_id=int(ot.id),
status='blocked',
current_gate_code='manual_upload_handoff',
)
)
db.session.commit()
cat = (
db.session.query(_order_task_todo_category_sql_expr())
.filter(ShippingOrderTask.id == ot.id)
.scalar()
)
assert cat == 'manual_upload'
def test_user_mode_review_status_must_human():
"""复核处置 review_status 在默认 auto 之前映射为 must_human。"""
for rs in ('parse_review', 'rsv_req', 'quality_issue', 'customer_review', 'shortage_review'):
assert derive_user_mode(
user_status='running',
gate_code=None,
review_status=rs,
lifecycle_stage=None,
) == 'must_human'
@@ -14,6 +14,8 @@ import pytest
from app.extensions import db
from app.models import (
FileAsset,
ShippingOrderDocument,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
@@ -59,6 +61,9 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
assert created['definition']['main_table_id'] == 'sample-table'
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
asset = db.session.get(FileAsset, db.session.get(ShippingOrderDocument, sample.document_id).asset_id)
assert asset.lifecycle_status == 'referenced'
assert int(asset.reference_count or 0) >= 1
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
@@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_preview_service.py
from __future__ import annotations
import gzip
import json
from types import SimpleNamespace
import numpy as np
@@ -15,7 +17,13 @@ import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User
from app.models import (
FileAsset,
ShippingDocumentLayoutVersion,
ShippingOrderDocumentProfileSample,
ShippingOrderDocument,
User,
)
from app.services.shipping_notice import document_profile_quality_service as quality_service
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
from app.services.shipping_notice import order_document_profile_service as profile_service
@@ -120,6 +128,62 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc
assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND'
def test_frozen_sample_preview_recovers_legacy_table_page_count_when_frozen_evidence_has_all_pages(
app, monkeypatch, admin_headers_factory,
):
"""历史快照把页数误记为表格页数时,仅可由同一冻结证据中的完整物理页数修复预览。"""
with app.app_context():
monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None)
schema = _schema_version()
draft = profile_service.save_draft(_data(schema.id), actor_id=None)
sample = _bind_ready_profile_sample(
draft['id'],
sample_role='annotation',
physical_page_count=2,
include_top_level_pages=False,
)
published = profile_service.publish(
draft['id'], actor_id=None, expected_lock_version=draft['lock_version'],
)
profile_id = int(published['id'])
sample_id = int(sample.id)
# 模拟修复上线前已发布的历史记录:页数被退化为仅第一页业务表。
sample.page_count_snapshot = 1
layout_version = db.session.get(ShippingDocumentLayoutVersion, sample.layout_version_id)
evidence_ref = (layout_version.payload_json or {}).get('coordinate_evidence_ref')
assert isinstance(evidence_ref, dict)
evidence_asset_no = str(evidence_ref['asset_no'])
db.session.commit()
preview_store = _PreviewStore()
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
coordinate_evidence_bytes = gzip.compress(json.dumps({
'pages': {'1': {'width': 200, 'height': 100}, '2': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
'tables': {'sample-table': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
}).encode('utf-8'))
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes',
lambda asset: coordinate_evidence_bytes if asset.asset_no == evidence_asset_no else b'%PDF-frozen-preview',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content, render_scale: [
SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
SimpleNamespace(page_no=2, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
],
)
client = app.test_client()
response = client.post(
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
headers=admin_headers_factory('frozen-preview-legacy-page-count'),
)
assert response.status_code == 200
assert parse_api_data(response.get_json())['page_count'] == 2
def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch):
"""发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。"""
profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
@@ -336,6 +336,9 @@ def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_
'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=draft['id'], sample_role='annotation',
).first().document_id,
# 本变更将 bind-po-001 改名为 bind-po-002(字段/值源未变),
# 正式 XFA 按 binding_id 身份识别删除,故显式确认该身份变更。
'allow_formal_binding_deletions': ['bind-po-001'],
}, actor_id=user.id, profile_id=draft['id'],
browser_session_id='xfa-p4-tab',
lease_token=lease['lease_token'],
+2 -2
View File
@@ -175,12 +175,12 @@ def test_same_po_conflicting_reservations_do_not_merge_lines():
def test_same_po_conflicting_line_no_does_not_merge_same_part_number():
"""料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。"""
"""料号一致但双方都有不同客户项次(customer_po_line_no)时,不能忽略项次而错误补入 Reservation。"""
pdf_line = _partial_line(1, part='PN-1', qty=30)
pdf_line['fields'].append(_field('line-id', '00010', 1))
email_line = _partial_line(2, part='PN-1', reservation='1000123456')
email_line['fields'].append(_field('line-id', '00020', 2))
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]}
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'customer_po_line_no'}]}
merged = merge_unit_orders(
orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])],
@@ -4,7 +4,8 @@ tests/test_shipping_auto_progress_p0_3.py
用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。
依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。
逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链;
显式 retry_rpa 覆盖 waiting_external 残留 poll。
"""
from __future__ import annotations
@@ -207,6 +208,62 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
"""waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。
回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa)
后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队
poll;poll 遇失败 Preparation 直接收口,表现为「改源已保存但 RPA 不触发」。
"""
task = _task_with_candidate()
execution = ensure_execution_for_workflow_version(review_case_id=905, task_id=int(task.id))
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_source_routing',
reason='test_review_confirmed',
)
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'waiting_external'
gate.blocking_reason_code = 'inventory_rpa_export_failed'
gate.next_action_code = 'poll_inventory_preparation'
execution.status = 'waiting_external'
execution.current_gate_code = 'inventory_preparation'
execution.primary_next_action_code = 'poll_inventory_preparation'
execution.responsible_party = 'worker'
task.active_process_execution_id = int(execution.id)
db.session.commit()
with patch(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
), patch(
'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls',
return_value=0,
):
result = submit_auto_progress(
task=task,
trigger='manual_override_source',
resume_gate_code='inventory_preparation',
inventory_mode='retry_rpa',
commit=True,
)
db.session.refresh(gate)
# 关键断言:显式重抓必须入队 retry_inventory_preparation(而非残留 poll)。
assert result['status'] == 'queued'
assert result.get('reused') is False
queued = (
ShippingProcessGateAttempt.query
.filter_by(gate_id=int(gate.id), status='queued')
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
.first()
)
assert queued is not None
assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation'
assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa'
def test_active_stp_job_without_retry_metadata_is_reused(app):
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
from types import SimpleNamespace
@@ -319,7 +376,7 @@ def test_retry_inventory_matching_fulfillable_passes():
query = MagicMock(get=MagicMock(return_value=_Task()))
with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None,
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'position': None,
}), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
@@ -78,6 +78,26 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac
]) is True
def test_unique_notice_warehouse_id_for_header_mapping():
"""Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。"""
from types import SimpleNamespace
from app.services.shipping_notice.export import _unique_notice_warehouse_id
assert _unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id='AWSSG'),
SimpleNamespace(inventory_warehouse_id='awssg'),
]) == 'AWSSG'
assert _unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id=None),
SimpleNamespace(inventory_warehouse_id=''),
]) is None
with pytest.raises(ValueError, match='多库位'):
_unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id='AWSSG'),
SimpleNamespace(inventory_warehouse_id='MOW'),
])
def _freeze_export_snapshot(
task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
@@ -0,0 +1,348 @@
"""
tests/test_shipping_gate_orchestration_separation.py
用途:锁定履约 Gate「匹配 Attempt 不内嵌 Excel / 匹配通过后续跑独立 artifact Attempt」。
依赖:pytest、fulfillment_workflow.try_auto_chain_after_match、process_gate_executor、
process_gate_bridge、process_gate_service、auto_progress fixtures。
逻辑:Gate 路径(_orchestrator_internal_dispatch)禁止 generate/upload;
match pass + sync 后须留下可自动投递的 artifact_generation Attempt。
"""
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import (
Job,
ShippingInventoryCandidateSet,
ShippingOrderTask,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match
from app.services.shipping_notice.process_gate_bridge import (
mark_gates_passed_through,
sync_fulfillment_gates_from_task,
)
from app.services.shipping_notice.process_gate_service import (
complete_gate_attempt,
ensure_execution_for_workflow_version,
queue_gate_attempt,
)
def _task_with_candidate(*, task_no: str = 'OT-ORCH-SEP-001') -> ShippingOrderTask:
"""创建带冻结候选集的正式 OT,供 20-Gate Execution 绑定。"""
task = ShippingOrderTask(task_no=task_no, user_id=1)
db.session.add(task)
db.session.flush()
candidate = ShippingInventoryCandidateSet(
task_id=task.id,
set_version=1,
lifecycle_status='frozen',
input_fingerprint='b' * 64,
)
db.session.add(candidate)
db.session.flush()
task.active_inventory_candidate_set_id = candidate.id
task.current_order_extraction_id = 101
task.order_snapshot_id = 201
db.session.commit()
return task
def _patch_fulfillable_inventory(monkeypatch) -> None:
"""让 sync_fulfillment 能越过 prep,到达 excel_readiness / artifact。"""
inv_file = SimpleNamespace(
id=1,
snapshot_status='ready',
invalidated_at=None,
mapping_confirmed=True,
source_query_json={},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
lambda _task: inv_file,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.active_inventory_lines_for_task',
lambda _task: [{'reservation_id': 'R1', 'part_number': 'P1'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status',
lambda _task: 'matched',
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_completed',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
lambda _task: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: None,
)
def test_try_auto_chain_gate_path_does_not_call_generate_or_upload(app, monkeypatch) -> None:
"""Gate Attempt 路径:try_auto_chain 不得同 Attempt 内嵌 generate_excel / upload。"""
with app.app_context():
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
task = ShippingOrderTask(task_no='OT-ORCH-CHAIN-0', user_id=1)
db.session.add(task)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow._current_export_artifact',
lambda _task: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
lambda _task: None,
)
generate_calls: list[dict] = []
upload_calls: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.upload_to_freight',
lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'},
)
result = try_auto_chain_after_match(
task,
{'status': 'ok', 'message': 'matched'},
payload={
'task_id': task.task_no,
'_orchestrator_internal_dispatch': True,
'source': 'process_gate',
},
)
assert result['status'] == 'ok'
assert generate_calls == []
assert upload_calls == []
def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch) -> None:
"""inventory_matching Handler 成功履约时不得调用 generate_excel。"""
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
with app.app_context():
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
_patch_fulfillable_inventory(monkeypatch)
task = _task_with_candidate(task_no='OT-ORCH-SEP-HANDLER')
execution = ensure_execution_for_workflow_version(review_case_id=9201, task_id=int(task.id))
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_field_mapping',
reason='test_orch_sep',
)
task.active_process_execution_id = int(execution.id)
db.session.commit()
generate_calls: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
lambda payload: try_auto_chain_after_match(
task,
{'status': 'ok', 'message': 'matched', 'task_id': task.task_no},
payload=payload,
),
)
monkeypatch.setattr(
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
)
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='inventory_matching',
).one()
result = _handle_retry_inventory_matching(
execution=execution,
gate=gate,
payload={'actor_user_id': 1},
)
assert result['outcome'] == 'passed'
assert generate_calls == []
db.session.refresh(execution)
artifact_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='artifact_generation',
).one()
assert artifact_gate.status != 'passed'
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> None:
"""匹配事实就绪且无 Artifact 时,submit_auto_progress 须入队 artifact Attempt。"""
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
with app.app_context():
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
app.config['SHIPPING_NOTICE_AUTO_MATCH_ENABLED'] = True
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
_patch_fulfillable_inventory(monkeypatch)
task = _task_with_candidate(task_no='OT-ORCH-SEP-ENQ')
execution = ensure_execution_for_workflow_version(review_case_id=9202, task_id=int(task.id))
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_field_mapping',
reason='test_orch_sep_enqueue',
)
task.active_process_execution_id = int(execution.id)
db.session.commit()
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=None,
)
matching_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='inventory_matching',
).one()
if matching_gate.status != 'passed':
attempt = queue_gate_attempt(
execution_no=str(execution.execution_no),
gate_code='inventory_matching',
trigger_type='auto',
actor_type='system',
actor_id=None,
idempotency_key=f'test-orch-sep-match:{execution.id}',
expected_gate_version=int(matching_gate.evaluation_version),
input_snapshot={'action_code': 'retry_inventory_matching', 'payload': {}},
)
assert attempt is not None
complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='passed',
output_snapshot={'action_code': 'retry_inventory_matching'},
effective_result_json={'match_status': 'fulfillable'},
)
db.session.refresh(execution)
artifact_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='artifact_generation',
).one()
assert artifact_gate.status != 'passed'
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
queued = submit_auto_progress(task=task, trigger='user_retry', commit=True)
assert queued.get('status') in {'queued', 'running'}
assert queued.get('gate_code') == 'artifact_generation'
attempt = db.session.get(ShippingProcessGateAttempt, int(queued['attempt_id']))
assert attempt is not None
assert isinstance(attempt.input_snapshot_json, dict)
assert attempt.input_snapshot_json.get('action_code') == 'regenerate_excel_artifact'
assert Job.query.filter_by(id=int(queued['job_id'])).one().job_type == 'shipping_process_gate'
def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) -> None:
"""端到端:match Handler 不生成;artifact Handler 才调用 generate_excel 一次。"""
from app.services.shipping_notice.process_gate_executor import (
_handle_regenerate_excel,
_handle_retry_inventory_matching,
)
with app.app_context():
app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False
_patch_fulfillable_inventory(monkeypatch)
task = _task_with_candidate(task_no='OT-ORCH-SEP-E2E')
execution = ensure_execution_for_workflow_version(review_case_id=9203, task_id=int(task.id))
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_field_mapping',
reason='test_orch_sep_e2e',
)
task.active_process_execution_id = int(execution.id)
db.session.commit()
generate_calls: list[dict] = []
def _fake_generate(payload):
generate_calls.append(dict(payload or {}))
artifact = SimpleNamespace(
id=99,
file_path='/tmp/orch-sep.xlsx',
file_name='orch-sep.xlsx',
status='ready',
)
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: artifact,
)
return {'status': 'ok', 'message': 'excel-ok'}
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
_fake_generate,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
lambda payload: try_auto_chain_after_match(
task,
{'status': 'ok', 'message': 'matched', 'task_id': task.task_no},
payload=payload,
),
)
monkeypatch.setattr(
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
)
matching_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='inventory_matching',
).one()
match_result = _handle_retry_inventory_matching(
execution=execution,
gate=matching_gate,
payload={'actor_user_id': 1},
)
assert match_result['outcome'] == 'passed'
assert generate_calls == []
# match handler 内 sync 已投影 artifact;禁止再 force sync matching(会 allow_repass
# 入队 artifact Attempt,把 next_action 清成 queued→None)。
db.session.refresh(execution)
artifact_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id),
gate_code='artifact_generation',
).one()
assert artifact_gate.status != 'passed'
assert artifact_gate.next_action_code == 'regenerate_excel_artifact'
artifact_result = _handle_regenerate_excel(
execution=execution,
gate=artifact_gate,
payload={'actor_user_id': 1},
)
assert artifact_result.get('outcome') == 'passed'
assert len(generate_calls) == 1
assert generate_calls[0].get('_orchestrator_internal_dispatch') is True
@@ -0,0 +1,75 @@
"""
tests/test_shipping_inventory_link_ot_owner.py
用途:锁定库存 Link 挂在正式 OT 上;传入 ShippingNotice 时仍须解析到该 OT 的 active link。
依赖:pytest、inventory_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。
逻辑:复现「Notice.id ≠ OT.id → Excel 导出读到 0 行库存」回归。
"""
from __future__ import annotations
from app import db
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.inventory_file_store import (
active_inventory_file_for_task,
resolve_inventory_lines_for_execution,
)
def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) -> None:
"""Notice 导出路径必须通过 order_task_id 找到挂在 OT 上的库存 Link。"""
with app.app_context():
inventory_path = tmp_path / 'ot-owned-inventory.xlsx'
inventory_path.write_bytes(b'inventory-rows')
# 先占用 Notice 自增 id=1,确保后续正式 Notice.id ≠ OT.id(复现生产错位)。
db.session.add(ShippingNotice(
task_no='SN-INV-LINK-BURN',
user_id=1,
source_type='manual',
))
db.session.flush()
ot = ShippingOrderTask(task_no='OT-INV-LINK-OWNER', user_id=1, source_type='direct_pdf')
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INV-LINK-OWNER',
storage_path=str(inventory_path),
source_file_name='ot-owned-inventory.xlsx',
snapshot_status='ready',
inventory_lines_json=[
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001'},
],
line_count=1,
)
db.session.add_all([ot, inventory_file])
db.session.flush()
notice = ShippingNotice(
task_no='SN-INV-LINK-OWNER',
user_id=1,
source_type='inventory_gate',
order_task_id=int(ot.id),
)
db.session.add(notice)
db.session.flush()
assert int(notice.id) != int(ot.id)
db.session.add(ShippingTaskInventoryLink(
task_id=int(ot.id),
inventory_file_id=int(inventory_file.id),
is_active=True,
access_mode='readonly',
))
db.session.commit()
# 断言:不得用 Notice.id 查 Link(会 miss);必须落到 OT Link。
assert active_inventory_file_for_task(ot) is not None
assert active_inventory_file_for_task(ot).id == inventory_file.id
assert active_inventory_file_for_task(notice) is not None
assert active_inventory_file_for_task(notice).id == inventory_file.id
assert len(resolve_inventory_lines_for_execution(notice)) == 1
@@ -0,0 +1,152 @@
"""
tests/test_shipping_inventory_source_adjudication.py
用途:锁定库存源裁决不得在 unresolved/空候选时兜底全部启用源,并采纳行级 ambiguous。
依赖:inventory_source_rules、inventory_routing_engine、pytest monkeypatch。
逻辑:用可控引擎结果复现 OT-C68 类缺陷——行级 PREFIX 多候选被丢弃后膨胀为全源。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.inventory_routing_engine import InventoryRoutingResult
from app.services.shipping_notice import inventory_source_rules as rules
def _source(code: str) -> dict:
"""构造最小可裁决库存源字典。"""
return {
'source_code': code,
'display_name': code,
'connector_type': 'dbs',
'warehouse_resolution_mode': 'fixed',
'fixed_warehouse_id': code,
}
def test_result_to_adjudication_unresolved_keeps_empty_candidates(monkeypatch):
"""
unresolved 且规则候选为空时,candidates 必须为空。
关键断言:禁止 list_database_inventory_sources 全源兜底(OT-C68 根因之一)。
"""
all_sources = [_source(f'SRC_{i}') for i in range(9)]
called = {'list_all': False}
monkeypatch.setattr(
rules,
'list_database_inventory_sources',
lambda: (called.__setitem__('list_all', True) or all_sources),
)
monkeypatch.setattr(rules, 'get_database_inventory_source', lambda code: None)
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
result = InventoryRoutingResult(
'unresolved',
(),
(),
{'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []},
)
adjudication = rules._result_to_adjudication(result, context={})
assert adjudication.status == 'unresolved'
assert adjudication.reason == 'routing_rule_unresolved'
assert adjudication.candidates == []
assert called['list_all'] is False
def test_result_to_adjudication_ambiguous_only_keeps_rule_sources(monkeypatch):
"""
ambiguous 多候选只保留规则给出的源;缺失 DB 配置的源不得用全库补齐。
"""
monkeypatch.setattr(
rules,
'list_database_inventory_sources',
lambda: [_source('SHOULD_NOT_APPEAR'), _source('ALSO_NO')],
)
monkeypatch.setattr(
rules,
'get_database_inventory_source',
lambda code: _source(code) if code in {'A', 'B'} else None,
)
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
result = InventoryRoutingResult(
'ambiguous',
('A', 'B', 'MISSING'),
(33,),
{
'priority': 100,
'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'],
'raw_source_codes': ['A', 'B', 'MISSING'],
},
)
adjudication = rules._result_to_adjudication(result, context={})
assert adjudication.status == 'ambiguous'
assert [item['source_code'] for item in adjudication.candidates] == ['A', 'B']
def test_adjudicate_accepts_unanimous_line_ambiguous(monkeypatch):
"""
任务级 unresolved、各行一致 ambiguous 时,必须采纳行级候选,不得回落全源。
复现:Reservation 前缀规则给出 3 源 ambiguous,旧逻辑返回 9 个启用源。
"""
line_ambiguous = InventoryRoutingResult(
'ambiguous',
('DSV360_AWSBI_BYAWSCMH01', 'DSV360_AWSBI_BYAWSFRA01', 'DSV360_AWSCV'),
(33,),
{
'priority': 100,
'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'],
'raw_source_codes': [
'DSV360_AWSBI_BYAWSCMH01',
'DSV360_AWSBI_BYAWSFRA01',
'DSV360_AWSCV',
],
},
)
task_unresolved = InventoryRoutingResult(
'unresolved',
(),
(),
{'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []},
)
def _evaluate(*, task, line=None, now=None):
del task, now
return task_unresolved if line is None else line_ambiguous
monkeypatch.setattr(rules, 'evaluate_inventory_source_rules', _evaluate)
monkeypatch.setattr(rules, 'extract_routing_context', lambda _task: {})
monkeypatch.setattr(
rules,
'_task_routing_lines',
lambda _task, required=None: [{'reservation_id': '2000488715', '_position': 0}],
)
monkeypatch.setattr(
rules,
'get_database_inventory_source',
lambda code: _source(code),
)
monkeypatch.setattr(
rules,
'list_database_inventory_sources',
lambda: [_source(f'EXTRA_{i}') for i in range(9)],
)
monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1')
monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp')
adjudication = rules.adjudicate_inventory_source(SimpleNamespace(id=1))
assert adjudication.status == 'ambiguous'
assert [item['source_code'] for item in adjudication.candidates] == [
'DSV360_AWSBI_BYAWSCMH01',
'DSV360_AWSBI_BYAWSFRA01',
'DSV360_AWSCV',
]
assert adjudication.reason == 'routing_rule_ambiguous'
@@ -0,0 +1,245 @@
"""
tests/test_shipping_line_scoped_inventory_retry.py
用途:守门明细行重抓/重匹配按行 source_codes 收窄,且不伤已发通知行。
依赖:pytest pure_unit、process_gate_executor、recovery_invalidation_service。
逻辑:与 display-and-button-contract §6.1 行级收窄约定对齐;不启 Flask/DB。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.pure_unit
def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
"""行级重抓必须把该行 source_codes 交给 ensure_inventory,并收窄失效范围。"""
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-SCOPE')
captured: list[dict] = []
invalidate_calls: list[dict] = []
line = SimpleNamespace(source_codes_json=['DBS'])
candidate_set = SimpleNamespace(id=1)
sources = [SimpleNamespace(source_code='DBS')]
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
lambda _execution: task,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: candidate_set,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
lambda _task: [line],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
lambda _task: sources,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope',
lambda _task, *, line_scope_key=None: {
'snapshot_line_id': 1001,
'line_no': 2,
'source_codes': ['WH_A'],
} if line_scope_key not in (None, '') else None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
lambda **kwargs: invalidate_calls.append(dict(kwargs)) or {},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_preparation_failed',
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True},
)
_handle_retry_inventory_preparation(
execution=SimpleNamespace(task_id=1, id=21, candidate_set_id=None),
gate=SimpleNamespace(gate_code='inventory_preparation'),
payload={
'action_code': 'retry_inventory_preparation',
'actor_user_id': 5,
'snapshot_line_id': 1001,
},
)
# 关键断言:行级强制 RPA 只带该行源,失效也按同行源收窄。
assert captured[-1].get('mode') == 'retry_rpa'
assert captured[-1].get('source_codes') == ['WH_A']
assert captured[-1].get('snapshot_line_id') == 1001
assert invalidate_calls[-1].get('source_codes') == ['WH_A']
assert invalidate_calls[-1].get('snapshot_line_id') == 1001
def test_inventory_matching_line_scope_uses_match_inventory_line(monkeypatch):
"""行级重匹配必须走 match_inventory_line,并携带该行 source_codes。"""
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-MATCH')
match_calls: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
lambda _execution: task,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope',
lambda _task, *, line_scope_key=None: {
'snapshot_line_id': 1002,
'line_no': 3,
'source_codes': ['WH_B'],
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory_line',
lambda payload, *, line_no: match_calls.append({'payload': dict(payload), 'line_no': line_no})
or {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
lambda _payload: (_ for _ in ()).throw(AssertionError('整单 match_inventory 不应被行级点击调用')),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_completed',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
lambda _task_id: {},
)
result = _handle_retry_inventory_matching(
execution=SimpleNamespace(task_id=1, id=21),
gate=SimpleNamespace(gate_code='inventory_matching'),
payload={'action_code': 'retry_inventory_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5},
)
assert match_calls and match_calls[0]['line_no'] == 3
assert match_calls[0]['payload'].get('source_codes') == ['WH_B']
assert result['outcome'] == 'passed'
def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch):
"""行级失效不得改写已发通知行匹配,也不得 supersede 已有 Notice Artifact。"""
from app.services.shipping_notice import recovery_invalidation_service as svc
link_a = SimpleNamespace(
id=11, inventory_file_id=101, matched_source_code='WH_A',
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
)
link_b = SimpleNamespace(
id=12, inventory_file_id=102, matched_source_code='WH_B',
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
)
match_open = SimpleNamespace(
id=21, snapshot_line_id=1001, inventory_source_code='WH_A',
allowed_source_codes_snapshot=['WH_A'], is_current=True,
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
)
match_noticed = SimpleNamespace(
id=22, snapshot_line_id=1002, inventory_source_code='WH_A',
allowed_source_codes_snapshot=['WH_A'], is_current=True,
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
)
class _Query:
def __init__(self, rows):
self._rows = rows
def filter_by(self, **_kwargs):
return self
def with_for_update(self):
return self
def all(self):
return list(self._rows)
def filter(self, *_a, **_k):
return self
monkeypatch.setattr(svc, '_noticed_snapshot_line_ids', lambda _task_id: {1002})
monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['inventory_matching'])
monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: SimpleNamespace(id=1))
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
# 纯单测不启 Flask:替换模块内模型符号,避免触碰 Flask-SQLAlchemy query 描述符。
monkeypatch.setattr(
svc,
'ShippingTaskInventoryLink',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([link_a, link_b]))),
)
monkeypatch.setattr(
svc,
'ShippingNoticeLineInventoryMatch',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([match_open, match_noticed]))),
)
monkeypatch.setattr(
svc,
'ShippingInventoryMapping',
SimpleNamespace(
inventory_file_id=SimpleNamespace(in_=lambda _ids: True),
status='active',
query=SimpleNamespace(filter=lambda *_a, **_k: _Query([])),
),
)
monkeypatch.setattr(
svc,
'ShippingNotice',
SimpleNamespace(
query=SimpleNamespace(
filter_by=lambda **_: (_ for _ in ()).throw(AssertionError('行级失效不得查询 Notice Artifact'))
)
),
)
result = svc.invalidate_inventory_downstream(
execution=SimpleNamespace(task_id=1),
action_code='retry_inventory_preparation',
attempt_id=9,
source_codes=['WH_A'],
snapshot_line_id=1001,
)
assert link_a.is_active is False
assert link_b.is_active is True
assert match_open.is_current is False
assert match_noticed.is_current is True
assert result['links'] == [11]
assert result['matches'] == [21]
assert result['artifacts'] == []
assert result['uploads'] == []
@@ -306,6 +306,86 @@ def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatc
assert synced == [task, linked_task]
def test_inventory_loaded_response_reuse_skips_file_line_overwrite(monkeypatch):
"""[断言] persist_lines=False 时只推进状态,禁止调用写回 File.inventory_lines_json。"""
from app.services.shipping_notice import inventory_mapping_workflow as workflow
owner_task = SimpleNamespace(id=1, task_no='OT-REUSE-NO-WRITE')
linked_task = SimpleNamespace(id=2, task_no='OT-REUSE-LINKED')
inventory_file = SimpleNamespace(
inventory_file_no='INV-SHARED',
inventory_lines_json=[{'part_number': 'KEEP', 'qty': 9}],
links=[
SimpleNamespace(is_active=True, task=owner_task),
SimpleNamespace(is_active=True, task=linked_task),
],
)
apply_calls: list[object] = []
monkeypatch.setattr(workflow, 'active_inventory_file_for_task', lambda _task: inventory_file)
monkeypatch.setattr(
workflow,
'apply_inventory_parse_result_to_linked_tasks',
lambda *args, **kwargs: apply_calls.append((args, kwargs)) or [owner_task],
)
monkeypatch.setattr(workflow, '_can_relink_inventory', lambda _task: True)
monkeypatch.setattr(workflow, 'task_line_purpose_values', lambda _task: [])
monkeypatch.setattr(workflow, 'build_field_alignment_preview', lambda *_a, **_k: {})
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_a, **_k: None)
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_a, **_k: None)
monkeypatch.setattr(workflow, 'log_task_event', lambda *_a, **_k: None)
monkeypatch.setattr(workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(workflow.db.session, 'flush', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice',
lambda _notice: None,
)
response = workflow.inventory_loaded_response(
owner_task,
[{'part_number': 'MERGED', 'qty': 1, '__source_code': 'SRC_A'}],
source='snapshot_reuse',
event_type='inventory_snapshot_reused',
commit=False,
persist_lines=False,
)
assert apply_calls == []
assert inventory_file.inventory_lines_json == [{'part_number': 'KEEP', 'qty': 9}]
assert response['status'] == 'ok'
assert response['data']['persist_lines'] is False
def test_resolve_inventory_lines_prefers_candidate_prep_when_frozen(monkeypatch):
"""[断言] 冻结候选 OT 匹配输入取 prepare 合并行,不依赖 active File 上的单源缓存。"""
from app.services.shipping_notice import inventory_file_store as store
task = SimpleNamespace(id=88, task_no='OT-RESOLVE-CAND')
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['SRC_A', 'SRC_B'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'ready',
'lines': [
{'part_number': 'P1', '__source_code': 'SRC_A'},
{'part_number': 'P2', '__source_code': 'SRC_B'},
],
},
)
monkeypatch.setattr(
store,
'active_inventory_file_for_task',
lambda _task: (_ for _ in ()).throw(AssertionError('must not fall back to active file')),
)
rows = store.resolve_inventory_lines_for_execution(task)
assert [row['__source_code'] for row in rows] == ['SRC_A', 'SRC_B']
def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
"""库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。"""
from app.services.shipping_notice import inventory_mapping_workflow as workflow
@@ -2191,7 +2271,7 @@ def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app)
},
)
def _fake_probe(actual_task, *, mode, allow_auto_retry=True):
def _fake_probe(actual_task, *, mode, allow_auto_retry=True, source_codes=None):
probe_calls.append((actual_task, mode))
return SimpleNamespace(
pending_source_codes=['SRC_A', 'SRC_B'],
@@ -2254,7 +2334,7 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat
)
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
lambda actual_task, *, mode, allow_auto_retry=True: SimpleNamespace(
lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: SimpleNamespace(
pending_source_codes=[],
prepared_source_codes=[],
failed_source_codes=['SRC_A'],
@@ -2271,3 +2351,168 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat
assert result['status'] == 'needs_human'
assert result['data']['blocking_reason']['code'] == 'inventory_preparation_failed'
def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, app):
"""[断言] 冻结源 ready 复用必须先 link;禁止未绑定直接 inventory_loaded_response 抛 ValueError。"""
from app.services.shipping_notice import inventory_workflow
task = SimpleNamespace(
task_no='OT-STP-READY-LINK',
id=701,
inventory_lines_json=None,
inventory_source_status='candidates_frozen',
active_inventory_candidate_set_id=9,
)
snapshot = SimpleNamespace(
inventory_file_no='INV-READY-001',
source_code='SRC_A',
warehouse_id='WH1',
)
call_order: list[str] = []
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['SRC_A'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'ready',
'candidate_set_id': 9,
'lines': [{'part_number': 'P1', '__source_code': 'SRC_A', '__inventory_file_no': 'INV-READY-001'}],
'missing_source_codes': [],
'loaded_source_codes': ['SRC_A'],
'evidence': [{
'source_code': 'SRC_A',
'status': 'loaded',
'inventory_file_no': 'INV-READY-001',
'line_count': 1,
'required': True,
}],
'required_source_codes': ['SRC_A'],
},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
lambda _task: None,
)
monkeypatch.setattr(
ShippingInventoryFile,
'query',
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
)
def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None):
call_order.append(f'link:{reason}')
assert actual_task is task
assert inv_file is snapshot
assert reason == 'stp_candidate_prep'
return SimpleNamespace(id=1)
def _fake_loaded(actual_task, lines, **kwargs):
call_order.append('loaded')
assert actual_task is task
assert lines
assert kwargs.get('persist_lines') is False
return {'status': 'ok', 'message': 'linked-and-loaded'}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
_fake_link,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
_fake_loaded,
)
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert result['status'] == 'ok'
assert call_order == ['link:stp_candidate_prep', 'loaded']
def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
"""[断言] ready 快照无法绑定 OT 时返回 needs_human,不得抛未绑定 ValueError。"""
from app.services.shipping_notice import inventory_workflow
task = SimpleNamespace(
task_no='OT-STP-LINK-FAIL',
id=702,
inventory_lines_json=None,
inventory_source_status='candidates_frozen',
active_inventory_candidate_set_id=10,
)
snapshot = SimpleNamespace(inventory_file_no='INV-MISMATCH', source_code='SRC_A', warehouse_id='WH1')
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(inventory_workflow, 'apply_task_transition', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['SRC_A'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'ready',
'candidate_set_id': 10,
'lines': [{'part_number': 'P1', '__inventory_file_no': 'INV-MISMATCH'}],
'missing_source_codes': [],
'loaded_source_codes': ['SRC_A'],
'evidence': [{
'source_code': 'SRC_A',
'status': 'loaded',
'inventory_file_no': 'INV-MISMATCH',
'required': True,
}],
'required_source_codes': ['SRC_A'],
},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
lambda _task: None,
)
monkeypatch.setattr(
ShippingInventoryFile,
'query',
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
lambda *_a, **_k: None,
)
def _boom(*_a, **_k):
raise AssertionError('inventory_loaded_response must not run when link failed')
monkeypatch.setattr(
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
_boom,
)
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _boom)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert result['status'] == 'needs_human'
assert result['data']['blocking_reason']['code'] == 'inventory_file_missing'
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more