feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码

This commit is contained in:
hugo committed 2026-08-23 00:27:18 +08:00
1 parent 935bf26fa6
commit 7cfd5d167e
230 files changed
+9337 -10989

No files matched your search

-1
View File
@@ -28,7 +28,6 @@ import app.api.admin.shipping_field_assets # noqa: F401
import app.api.admin.shipping_order_document_profiles # noqa: F401
import app.api.admin.shipping_document_layouts # noqa: F401
import app.api.admin.shipping_process_gate # noqa: F401
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
import app.api.admin.linked_services # noqa: F401
import app.api.admin.procurement_contract # noqa: F401
import app.api.admin.training_configs # noqa: F401
@@ -1,63 +0,0 @@
"""
backend/app/api/admin/shipping_legacy_stp_jobs.py
用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。
依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。
逻辑:
• GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to)
• GET /admin/shipping-notice/legacy-stp-jobs/<job_id> 单条详情 + 回链 Review Case
• 所有接口严格 require_admin;不允许写任何 DB。
"""
from __future__ import annotations
from flask import g, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.core.errors import ValidationError
from app.core.response import ok
from app.services.shipping_notice.legacy_stp_job_admin_service import (
get_admin_legacy_stp_job,
list_admin_legacy_stp_jobs,
)
def _qint(name: str, default: int) -> int:
raw = request.args.get(name)
if raw in (None, ''):
return default
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} must be an integer') from exc
@admin_bp.route('/shipping-notice/legacy-stp-jobs', methods=['GET'])
@require_admin
def admin_list_legacy_stp_jobs():
"""历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。"""
page = _qint('page', 1)
page_size = _qint('page_size', 25)
payload = list_admin_legacy_stp_jobs(
page=page,
page_size=page_size,
status=request.args.get('status'),
job_type=request.args.get('job_type'),
q=request.args.get('q'),
case_no=request.args.get('case_no'),
error_code=request.args.get('error_code'),
blocking_reason=request.args.get('blocking_reason'),
created_from=request.args.get('created_from'),
created_to=request.args.get('created_to'),
sort=request.args.get('sort') or '-created_at',
)
return ok(payload, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/legacy-stp-jobs/<int:job_id>', methods=['GET'])
@require_admin
def admin_get_legacy_stp_job(job_id: int):
"""单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。"""
payload = get_admin_legacy_stp_job(int(job_id))
return ok(payload, request_id=getattr(g, 'request_id', None))
@@ -32,6 +32,40 @@ def _query_int(name: str, default: int) -> int:
raise ValidationError(f'{name} must be an integer') from exc
@admin_bp.route('/shipping-notice/legacy-supplement-conflicts/reassess', methods=['POST'])
@require_admin
def reassess_shipping_legacy_supplement_conflicts():
"""受控重评估历史正文补充冲突;全量操作必须显式确认,结果只返回脱敏统计。"""
body = request.get_json(silent=True)
if body is None:
body = {}
if not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
include_all_raw = body.get('include_all', False)
if not isinstance(include_all_raw, bool):
raise ValidationError('include_all must be a boolean')
include_all = include_all_raw
if include_all and str(body.get('confirmation') or '') != 'REASSESS_LEGACY_SUPPLEMENT_CONFLICTS':
raise ValidationError('confirmation is required for include_all')
candidate_no = str(body.get('candidate_no') or '').strip() or None
run_no = str(body.get('run_no') or '').strip() or None
if not (candidate_no or run_no or include_all):
raise ValidationError('candidate_no, run_no, or include_all is required')
from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import (
reassess_legacy_supplement_conflicts,
)
result = reassess_legacy_supplement_conflicts(
actor_id=int(g.current_user.id),
request_id=getattr(g, 'request_id', None),
candidate_no=candidate_no,
run_no=run_no,
include_all=include_all,
)
db.session.commit()
return ok(result, request_id=getattr(g, 'request_id', None))
@admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET'])
@require_admin
def get_shipping_order_extraction_health():
+2 -9
View File
@@ -137,24 +137,21 @@ def _merge_user_attachments_from_terminal_event(
def _build_chat_adapter_hints(
*,
shipping_task_id: str | None = None,
shipping_batch_no: str | None = None,
shipping_intake_nos: list[str] | None = None,
) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
if not task_id and not batch_no and not intake_nos:
if not task_id and not intake_nos:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
'intake_nos': intake_nos,
'capability': 'order_extraction' if intake_nos else None,
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
@@ -1574,7 +1571,6 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
raw_shipping_intakes = data.get('shipping_intake_nos')
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
raise ValidationError('shipping_intake_nos must be a list')
@@ -1720,11 +1716,9 @@ def chat_completions():
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
kb_type=kb_type,
)
@@ -1763,7 +1757,6 @@ def chat_completions():
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
shipping_intake_nos=shipping_intake_nos,
),
),
-4
View File
@@ -39,7 +39,6 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -168,10 +167,8 @@ def chat_completions():
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
kb_type=kb_type,
)
@@ -210,7 +207,6 @@ def chat_completions():
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
+3 -5
View File
@@ -10,21 +10,19 @@ from __future__ import annotations
from .shared import * # noqa: F403
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
if not task_id:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
+2 -22
View File
@@ -2,7 +2,7 @@
backend/app/api/chat_turns.py
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
"""
@@ -77,7 +77,6 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
"""
将 multipart 附件写入 Turn input.payload。
- shipping.create_batch_from_notices:预检 notice_items
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
"""
if not uploads:
@@ -87,26 +86,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
payload = dict(payload)
if action_type == "shipping.create_batch_from_notices":
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
temp_request_id = uuid.uuid4().hex
try:
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
finally:
cleanup_temp_notice_uploads(temp_request_id)
if not notice_items:
raise ValidationError(
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
details={"file_summary": file_summary},
)
payload["notice_items"] = notice_items
payload["file_summary"] = file_summary
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
if conversation_id:
payload["conversation_id"] = conversation_id
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
if action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
staged = _stage_upload_files(uploads)
if not staged:
raise ValidationError("file is required")
+4 -49
View File
@@ -3,15 +3,13 @@ api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
batch_legacy_removed(create_batch 410)。
tool_api_url。
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, current_app, jsonify, request, send_file
from app import db
@@ -118,11 +116,11 @@ def _payload() -> dict:
return payload
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None:
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
from app.models import ShippingAuditEvent
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no)
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
db.session.add(ShippingAuditEvent(
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
@@ -130,10 +128,6 @@ def _require_read_capability(payload: dict, *, scope: str, task_no: str | None =
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
))
def _generate_batch_no() -> str:
from datetime import datetime
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
@@ -192,19 +186,6 @@ def tool_confirm_temporary_inventory_use():
"""
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
def tool_create_batch():
"""
历史建批 Tool(已下线)。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.create_batch')
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
def tool_update_notice_fields():
"""
@@ -328,32 +309,6 @@ def tool_get_task_status():
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
return jsonify(shipping_tools.get_task_status(payload))
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
def tool_get_batch_status():
"""
历史批次状态查询(已下线)。
【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.get_batch_status')
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
def tool_switch_focus_task():
"""
历史批次焦点切换(已下线)。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='tools.switch_focus_task')
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
def rpa_worker_heartbeat():
"""
+50 -241
View File
@@ -3,16 +3,17 @@ backend/app/api/workspace/shipping_notice.py
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service /
tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。
tools / notice_upload / ui_state、shipping_processing_projection。
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
`/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404;
`/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除;
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
"""
from __future__ import annotations
import uuid
from io import BytesIO
from time import perf_counter
from typing import Any
from flask import Blueprint, Response, current_app, g, request, send_file
@@ -32,9 +33,7 @@ from app.services.shipping_notice.processing_ownership import assert_notice_task
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
count_my_todos,
get_conversation_batch_workspace,
get_task_for_user,
list_batches_for_user,
list_my_todos,
list_tasks_page_for_user,
resolve_task_export_download,
@@ -148,9 +147,8 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
user = _require_user()
batch_no = str(request.args.get('batch_no') or '').strip() or None
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
try:
page = int(request.args.get('page') or 1)
@@ -161,7 +159,6 @@ def workspace_shipping_tasks():
raise ValidationError('page must be positive and page_size must be between 1 and 100')
return _ok(list_tasks_page_for_user(
user.id,
batch_no=batch_no,
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
@@ -309,116 +306,16 @@ def workspace_batch_restore_shipping_tasks():
"""批量恢复回收站内仍为 active 的纯误建任务。"""
return _batch_dispose('restore')
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要;co8 后 shipping_batches 已 DROP,恒返回空列表。"""
user = _require_user()
limit = int(request.args.get('limit') or 100)
return _ok(list_batches_for_user(user.id, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
def workspace_create_shipping_batch_from_notices():
"""
历史:多附件建批(已下线)。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
_require_user()
raise_shipping_batches_removed(action='workspace.create_from_notices')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""批次详情;shipping_batches 已 DROP,恒 404。"""
_require_user()
del batch_no
raise NotFoundError('Not found')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""批次 UI State;shipping_batches 已 DROP,恒 404。"""
_require_user()
del batch_no
raise NotFoundError('Not found')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
"""批次任务列表;shipping_batches 已 DROP,恒 404。"""
_require_user()
del batch_no
raise NotFoundError('Not found')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str):
"""批次焦点任务;shipping_batches 已 DROP,恒 404。"""
_require_user()
del batch_no
raise NotFoundError('Not found')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str):
"""
切换批次焦点(已下线)。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
_require_user()
del batch_no
raise_shipping_batches_removed(action='workspace.switch_batch_focus')
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
def workspace_create_shipping_batch_from_intakes():
"""
历史:从 Intake 建批(已下线)。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
_require_user()
raise_shipping_batches_removed(action='workspace.create_from_intakes')
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""
历史:重试批次待推进任务(已下线)。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
_require_user()
del batch_no
raise_shipping_batches_removed(action='workspace.retry_batch_pending')
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive():
"""按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
user = _require_user()
data = request.get_json(silent=True) or {}
task_nos = data.get('task_nos')
if task_nos is not None and not isinstance(task_nos, list):
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
from app.services.shipping_notice.export_archive import build_export_archive
stream, filename, _manifest = build_export_archive(
user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos,
)
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@@ -565,13 +462,6 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
"""返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。"""
user = _require_user()
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
@@ -719,60 +609,6 @@ def workspace_shipping_task_chat_actions(task_no: str):
raise NotFoundError('Not found')
return _ok(build_chat_actions_payload(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
def workspace_retry_shipping_task(task_no: str):
"""
用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。
核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task);
不再直接调用通用 retry_task 重置编排器。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
return _ok(retry_task_with_decision(
task_no=str(task.task_no),
user_id=int(user.id),
scope='task',
reason=str(data.get('reason') or data.get('comment') or 'user_retry'),
trigger='user_retry',
continue_auto_progress=False,
))
@workspace_shipping_notice_bp.route(
'/shipping-tasks/<task_no>/lines/<line_key>/retry',
methods=['POST'],
)
def workspace_retry_shipping_task_line(task_no: str, line_key: str):
"""
行级统一「重试」:与任务级共用决策器,scope=line。
核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
_assert_fulfillment_task_ownership(task, user.id)
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
return _ok(retry_task_with_decision(
task_no=str(task.task_no),
user_id=int(user.id),
scope='line',
line_key=str(line_key or '').strip(),
reason=str(data.get('reason') or 'user_retry_inventory'),
trigger='user_line_retry',
continue_auto_progress=False,
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
def workspace_update_shipping_notice_fields(task_no: str):
"""更新发货通知单头字段。"""
@@ -1265,11 +1101,17 @@ def workspace_get_shipping_processing_conversation(conversation_id: str):
user = _require_user()
from app.services.shipping_notice.shipping_processing_projection import (
project_conversation_processing_items,
project_conversation_processing_summary,
)
agent_raw = request.args.get('agent_id')
agent_id = int(agent_raw) if agent_raw not in (None, '') else None
payload = project_conversation_processing_items(
projector = (
project_conversation_processing_summary
if str(request.args.get('view') or '').strip().lower() == 'summary'
else project_conversation_processing_items
)
payload = projector(
user_id=user.id,
conversation_id=str(conversation_id or '').strip(),
agent_id=agent_id,
@@ -1352,7 +1194,21 @@ def workspace_mark_conversation_task_viewed(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
def workspace_get_shipping_order_extraction_run(run_no: str):
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。"""
"""
查询当前用户的一次订单抽取 Run,并返回可与浏览器 HAR 对齐的读取分段耗时。
核心逻辑:先按当前用户加载 Run,再投影为工作台 DTO;保留原有访问审计,响应仅新增
`Server-Timing` 指标,不暴露正文快照或改变业务数据。
Args:
run_no: 当前用户有权访问的订单抽取 Run 业务编号。
Returns:
Flask 成功响应,正文为既有 Run DTO,Header 含 run_lookup 和 workspace_projection 耗时。
Raises:
AppError: Run 不存在或当前用户无权访问时由服务层抛出。
"""
user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_extraction_run_service import (
@@ -1360,8 +1216,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str):
serialize_order_extraction_run,
)
lookup_started = perf_counter()
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
lookup_ms = (perf_counter() - lookup_started) * 1000
projection_started = perf_counter()
payload = serialize_order_extraction_run(run)
projection_ms = (perf_counter() - projection_started) * 1000
# 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。
record_access_audit(
action='view_order_extraction_run',
@@ -1372,7 +1232,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str):
conversation_id=run.conversation_id,
metadata={'status': str(run.status or ''), 'poll': True},
)
return _ok(payload)
response = current_app.make_response(_ok(payload))
response.headers['Server-Timing'] = (
f'run_lookup;dur={lookup_ms:.1f}, '
f'workspace_projection;dur={projection_ms:.1f}'
)
return response
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/progress-events', methods=['GET'])
@@ -1575,21 +1440,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
source_content_hash = (
str(payload.get('source_content_hash') or '').strip() or None
)
# [Phase 4] 管理员专用扩展:legacy_job_id(历史 Job 928/929 replay)与 replay_mode 透传;
# 非管理员若传入 → 直接 422 拒绝(与 reconcile_and_progress PRE-CHECK 一致)。
legacy_job_id_raw = payload.get('legacy_job_id')
legacy_job_id: int | None = None
if legacy_job_id_raw is not None:
try:
legacy_job_id = int(legacy_job_id_raw)
except (TypeError, ValueError):
raise ValidationError(
'legacy_job_id must be integer if provided',
code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION',
)
replay_mode_raw = payload.get('replay_mode')
replay_mode = bool(replay_mode_raw) if replay_mode_raw is not None else False
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
result = reconcile_and_progress(
@@ -1600,8 +1450,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
expected_case_version=expected_case_version,
source_content_hash=source_content_hash,
is_admin=is_admin,
legacy_job_id=legacy_job_id,
replay_mode=replay_mode,
)
return _ok(result.to_public())
@@ -2001,24 +1849,13 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
为选中完整明细行创建履约波次。
Body: line_keys[], expected_draft_version, idempotency_key, reason?
已有正式 OT 时走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress;
禁止调用 schedule_auto_progress_after_review_confirm。
无正式 OT 时保留历史 create_fulfillment_wave(BE-8 兼容分支,仅建单前兜底;
响应标记 legacy_pre_ot_wave=true,后续版本可收敛删除)。
只允许正式 OT 走 create_post_ot_fulfillment_wave +
schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须
先完成正式建单,避免同一业务动作存在两套推进事实。
"""
import logging
user = _require_user()
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.order_review_confirmation_service import (
finalize_sync_auto_progress_after_commit,
resolve_confirm_outcome,
schedule_auto_progress_after_review_confirm,
)
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
create_fulfillment_wave,
)
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
@@ -2062,40 +1899,12 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
result['auto_progress'] = progress
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
result['post_ot_wave'] = True
result['legacy_pre_ot_wave'] = False
return _ok(result)
# [STEP] BE-8:无正式 OT 的历史 wave→confirm 路径;仅兼容,不作为 OT 后主路径。
logging.getLogger(__name__).warning(
'shipping_review_fulfillment_wave_legacy_pre_ot case_no=%s line_count=%s',
case_no,
len(line_keys),
raise ValidationError(
'A formal order task is required before creating a fulfillment wave',
code='SHIPPING.FORMAL_OT_REQUIRED',
)
result = create_fulfillment_wave(
user_id=user.id,
case_no=case_no,
line_keys=line_keys,
expected_draft_version=data.get('expected_draft_version'),
idempotency_key=idem,
reason=reason,
)
progress = schedule_auto_progress_after_review_confirm(
task_no=result.get('task_no'),
idempotent_replay=bool(result.get('idempotent_replay')),
created_by_id=int(user.id),
commit=False,
)
db.session.commit()
progress = finalize_sync_auto_progress_after_commit(progress)
result = dict(result)
result.pop('trigger_auto_progress', None)
result['confirm_ok'] = True
result['confirm_outcome'] = resolve_confirm_outcome(progress)
result['auto_progress'] = progress
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
result['post_ot_wave'] = False
result['legacy_pre_ot_wave'] = True
return _ok(result)
@workspace_shipping_notice_bp.route(
@@ -2842,8 +2651,8 @@ def workspace_list_shipping_order_extraction_runs():
page_raw = request.args.get('page')
page_size_raw = request.args.get('page_size')
from app.services.shipping_notice.order_extraction_run_service import (
list_order_extraction_runs,
serialize_order_extraction_run,
list_order_extraction_run_summaries,
serialize_order_extraction_run_list_item,
)
if page_raw is not None or page_size_raw is not None:
@@ -2852,7 +2661,7 @@ def workspace_list_shipping_order_extraction_runs():
page_size = int(page_size_raw or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
payload = list_order_extraction_runs(
payload = list_order_extraction_run_summaries(
user_id=user.id,
conversation_id=conversation_id,
status=status,
@@ -2861,7 +2670,7 @@ def workspace_list_shipping_order_extraction_runs():
)
assert isinstance(payload, dict)
return _ok({
'items': [serialize_order_extraction_run(row) for row in payload['items']],
'items': [serialize_order_extraction_run_list_item(row) for row in payload['items']],
'total': payload['total'],
'page': payload['page'],
'page_size': payload['page_size'],
@@ -2871,14 +2680,14 @@ def workspace_list_shipping_order_extraction_runs():
limit = int(request.args.get('limit') or 50)
except (TypeError, ValueError) as exc:
raise ValidationError('limit must be an integer') from exc
rows = list_order_extraction_runs(
rows = list_order_extraction_run_summaries(
user_id=user.id,
conversation_id=conversation_id,
status=status,
limit=limit,
)
assert isinstance(rows, list)
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
return _ok({'items': [serialize_order_extraction_run_list_item(row) for row in rows]})
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
-1
View File
@@ -17,7 +17,6 @@ from app.jobs.handlers import ( # noqa: F401
shipping_notice_run,
shipping_order_extraction,
shipping_process_gate,
shipping_auto_progress,
shipping_stp_auto_create,
shipping_line_auto_fulfill,
shipping_post_ot_wave_progress,
@@ -1,27 +0,0 @@
"""
jobs/handlers/shipping_auto_progress.py
用途:终态化历史 APX AutoProgress Job。
依赖:JobContext、auto_progress_controller。
逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX
Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
"""终态化历史 APX Job;payload 必须含队列注入的 job_id。"""
raw_job_id = payload.get('job_id')
if not raw_job_id:
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
run_auto_progress_job(
job_id=int(raw_job_id),
worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'),
)
@@ -1018,7 +1018,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
1
for order in merged_unit_orders if isinstance(order, dict)
for conflict in order.get('conflicts') or [] if isinstance(conflict, dict)
if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous'
if str(conflict.get('reason') or '').strip() in {
'supplement_relation_ambiguous', 'supplement_field_conflict',
}
)
supplement_status = (
'conflict'
@@ -1148,7 +1150,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
)
# 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。
summary = {
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
'run_no': run.run_no,
'created_count': int(result.get('created_count') or 0),
'opened_existing_count': int(result.get('opened_existing_count') or 0),
'pending_count': int(result.get('pending_count') or 0),
-3
View File
@@ -22,8 +22,6 @@ class JobType(StrEnum):
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
@@ -72,7 +70,6 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
'shipping_inventory_callback_process',
'shipping_auto_progress',
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
-19
View File
@@ -30,25 +30,6 @@ class Job(Base):
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
Index('ix_jobs_locked_at', 'locked_at'),
Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'),
# P0-3:同一 Task 同时只允许一个正式 AutoProgress 决策 Job。库存源 RPA
# Attempt 不使用该索引,因此可以按 source 并行执行。
Index(
'uq_jobs_shipping_auto_progress_one_active_task',
'task_id',
unique=True,
postgresql_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') "
"AND task_id IS NOT NULL"
),
sqlite_where=text(
"domain = 'shipping_notice' "
"AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') "
"AND task_id IS NOT NULL"
),
),
# 仅预解析 Job:同业务锚点同时只允许一条 queued
# (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
Index(
@@ -17,7 +17,7 @@ class ChatStreamContext:
"""
/api/chat/completions 单次流式请求上下文。
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id)。
"""
query: str
@@ -30,7 +30,6 @@ class ChatStreamContext:
normalized_files: list[dict] | None = None
adapter_hints: dict[str, Any] | None = None
shipping_task_id: str = ''
shipping_batch_no: str = ''
kb_type: str = '企业知识库'
hxops_turn_id: str | None = None
@@ -1,5 +1,5 @@
"""
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务 UI State。
依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
"""
@@ -36,7 +36,7 @@ class ShippingNoticeHandler(AgentHandler):
"""
货代发货通知业务 Handler。
核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。
核心逻辑:按 adapter_hints / task_id 构造 shipping_ui_state,供实时消息使用。
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
"""
@@ -51,57 +51,36 @@ class ShippingNoticeHandler(AgentHandler):
"""
构造 shipping_ui_state SSE 事件。
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
核心逻辑:只接受显式 task_id;失败时记录日志并返回 None。
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
shipping_hints = self._shipping_hints(ctx)
if not task_id and not batch_no:
if not task_id:
task_id = str(shipping_hints.get('task_id') or '').strip()
batch_no = str(shipping_hints.get('batch_no') or '').strip()
if not task_id and not batch_no:
if not task_id:
return None
try:
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.ui_state import build_task_ui_state
task = get_task_by_ref(task_id) if task_id else None
batch = get_batch_by_no(batch_no) if batch_no else None
task = get_task_by_ref(task_id)
session_id = str(getattr(ctx.session, 'session_id', '') or '')
if task is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'task_no': task.task_no,
'batch_no': None,
'ui_state': build_task_ui_state(task),
}
if batch is not None:
batch_ui_state = build_batch_ui_state(batch)
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
focus_ui_state = (
batch_ui_state.get('focus_task_ui_state')
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
else None
)
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'batch_no': batch.batch_no,
'task_no': focus_task.get('task_no'),
'batch_ui_state': batch_ui_state,
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
}
except Exception:
if current_app:
current_app.logger.exception(
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s',
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s',
ctx.request_id,
task_id,
batch_no,
)
return None
@@ -110,18 +89,11 @@ 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 {}
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
focus_state = (
batch_ui_state.get('focus_task_ui_state')
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
else {}
)
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
checkpoint = ui_state.get('checkpoint')
return json.dumps({
'task_no': event.get('task_no'),
'batch_no': event.get('batch_no'),
'checkpoint': checkpoint,
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
'updated_at': ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
@staticmethod
@@ -28,7 +28,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"platform.request_id",
"platform.locale",
"platform.trigger_source",
"refs.batch_no",
"refs.task_no",
"refs.run_purpose",
"refs.capability",
@@ -40,7 +39,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"refs.hxops_turn_id",
"domain.type",
"domain.summary",
"domain.state_hint.batch_no",
"domain.state_hint.focus_task_no",
"domain.state_hint.schedule_task_id",
"domain.state_hint.hxops_turn_id",
+1 -3
View File
@@ -3,7 +3,7 @@ backend/app/services/chat/action_registry.py
用途:Chat Turn Action Handler 注册与解析。
依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。
逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。
逻辑:各领域在各自 action handler 模块注册 handler;turn_runtime 调用 resolve。
"""
from __future__ import annotations
@@ -78,8 +78,6 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
_ = _shipping_handlers
_ = _shipping_extended
-2
View File
@@ -73,8 +73,6 @@ def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[st
shipping_payload["ui_state"] = payload["ui_state"]
if payload.get("task_no"):
shipping_payload["task_no"] = payload["task_no"]
if payload.get("batch_no"):
shipping_payload["batch_no"] = payload["batch_no"]
return modern + sse_frame(shipping_payload)
@@ -1,57 +0,0 @@
"""
APX 历史运行时只读清点。
用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。
依赖:ShippingProcessExecution、Job ORM 模型。
逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。
"""
from __future__ import annotations
from app.models import Job, ShippingProcessExecution
_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external')
_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active')
def audit_apx_runtime_state() -> dict[str, object]:
"""只读统计 APX Execution/Job 运行态与历史态数量。
Returns:
包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或
payload 中的 execution_id 关联;任何写操作都不在此函数执行。
"""
apx_executions = ShippingProcessExecution.query.filter(
ShippingProcessExecution.execution_no.ilike('APX-%')
).all()
runtime_execution_ids = {
int(row.id) for row in apx_executions
if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES
}
apx_jobs = Job.query.filter(
Job.domain == 'shipping_notice',
Job.status.in_(_JOB_RUNTIME_STATUSES),
).all()
runtime_job_count = 0
for job in apx_jobs:
if int(job.execution_id or 0) in runtime_execution_ids:
runtime_job_count += 1
continue
if str(job.business_ref or '').upper().find('APX-') >= 0:
runtime_job_count += 1
continue
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
if str(payload.get('execution_no') or '').upper().startswith('APX-'):
runtime_job_count += 1
return {
'execution': {
'active_count': len(runtime_execution_ids),
'historical_count': len(apx_executions) - len(runtime_execution_ids),
},
'job': {
'active_count': runtime_job_count,
},
}
@@ -3,7 +3,7 @@ services/shipping_notice/attachment_integrity.py
用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
依赖:error_explainability_contract(warning→稳定原因码)、标准库。
逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
逻辑:由 intake_service.retry_intake_parse 调用;
BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
(由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。
"""
@@ -24,14 +24,6 @@ from app.services.shipping_notice.process_gate_contract import action_belongs_to
from app.services.shipping_notice.tool_common import log_task_event
AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = (
'inventory_candidates_calculated',
'inventory_candidates_frozen',
'inventory_snapshots_ready',
'inventory_matched',
'excel_generated',
'upload_receipt_recorded',
)
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
@@ -107,16 +99,6 @@ def _new_execution_no() -> str:
return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
禁止创建 APX 六 Gate Execution。
APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate
``ensure_execution_for_workflow_version`` 创建 Execution。
"""
raise RuntimeError('shipping_apx_creation_disabled')
def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
"""按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。"""
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
@@ -200,8 +182,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
"""
锁定并取得当前唯一活动 Execution。
核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读,
不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。
核心逻辑:正式 20-Gate 链是唯一运行时状态机;候选版本变化仍按原规则 superseded。
"""
all_active = (
ShippingProcessExecution.query
@@ -230,6 +211,10 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
formal.updated_at = _utc_now()
db.session.flush()
return formal
if all_active:
raise RuntimeError('shipping_process_execution_contract_invalid')
if execution is not None and not _is_formal_process_execution(execution):
raise RuntimeError('shipping_process_execution_contract_invalid')
if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0):
# 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。
execution.status = 'superseded'
@@ -238,7 +223,6 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
execution = None
# APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。
if execution is not None:
execution.status = 'superseded'
execution.updated_at = _utc_now()
@@ -286,10 +270,7 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
Job.query.filter(
Job.domain == 'shipping_notice',
Job.job_type.in_((
JobType.SHIPPING_AUTO_PROGRESS.value,
JobType.SHIPPING_PROCESS_GATE.value,
)),
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
Job.task_id == int(task.id),
Job.status == 'queued',
).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False)
@@ -305,8 +286,7 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
ShippingProcessGate.query.filter_by(execution_id=int(execution.id))
.order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all()
)
# 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史
# APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。
# 正式运行时只接受 20-Gate 合同。
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
expected = list(PROCESS_GATE_CODES)
@@ -385,9 +365,8 @@ def submit_auto_progress(
candidate_set_id = int(candidate.id) if candidate is not None else None
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
if _is_formal_process_execution(execution):
# 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容
# 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
# 正式 20-Gate Execution 是唯一业务真相;先同步已落库事实,再把当前技术
# Gate 交给唯一 ProcessGate Job/Attempt 通道。
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
from app.services.shipping_notice.process_gate_executor import is_navigation_action
@@ -496,39 +475,5 @@ def submit_auto_progress(
if commit:
db.session.commit()
return result
# 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现
# 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。
if not _is_formal_process_execution(execution):
if commit:
db.session.commit()
return {
'status': 'legacy_readonly',
'reason_code': 'shipping_apx_runtime_disabled',
'execution_id': int(execution.id),
}
def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]:
"""
将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。
APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job,
但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。
"""
job = Job.query.filter_by(id=int(job_id)).with_for_update().first()
if job is None or job.status != 'running':
return {'status': 'noop'}
now = _utc_now()
gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first()
job.status = 'cancelled'
job.finished_at = now
job.message = 'APX historical auto-progress runtime disabled'
if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}:
gate.status = 'cancelled'
gate.updated_at = now
db.session.commit()
return {
'status': 'legacy_readonly',
'reason_code': 'shipping_apx_runtime_disabled',
'execution_id': int(job.execution_id) if job.execution_id else None,
}
# 运行时只接受正式合同;数据不一致时 fail-closed。
raise RuntimeError('shipping_process_execution_contract_invalid')
@@ -1,136 +1,22 @@
"""
services/shipping_notice/batch_create_idempotency.py
用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。
依赖:models.ShippingNotice、query_service、batch_legacy_removed。
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
用途:发货通知跨请求文件内容重复校验。
依赖:models.ShippingNotice。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
"""
from __future__ import annotations
import hashlib
import logging
import re
import zlib
from typing import Any, Iterable
from typing import Iterable
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import AppError, ConflictError
from app.models import ShippingNotice
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
logger = logging.getLogger(__name__)
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
def normalize_create_idempotency_key(raw: str | None) -> str | None:
"""
标准化建单幂等键:去首尾空格、校验长度与安全字符集。
Args:
raw: HTTP Header / payload 中的原始幂等键。
Returns:
标准化后的幂等键;空值返回 None。
Raises:
ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。
"""
value = str(raw or "").strip()
if not value:
return None
if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
raise AppError(
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
http_status=400,
)
if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
raise AppError(
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
message="幂等键仅允许字母、数字及 . _ : - 字符",
http_status=400,
)
return value
def warn_missing_create_idempotency_key(*, source: str) -> None:
"""兼容期记录缺少建单幂等键的告警,不阻断旧客户端。"""
logger.warning(
"shipping batch create without create_idempotency_key source=%s",
source,
)
def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str:
"""
根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。
核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。
"""
hashes: list[str] = []
for item in notice_items:
if not isinstance(item, dict):
continue
source_hash = str(item.get("source_content_hash") or "").strip().lower()
if not source_hash:
continue
candidate_id = str(item.get("source_candidate_id") or "").strip()
if candidate_id:
hashes.append(
"|".join(
[
candidate_id,
source_hash,
str(item.get("business_fingerprint") or "").strip().lower(),
str(item.get("content_fingerprint") or "").strip().lower(),
]
)
)
else:
# 旧单文件/直接上传路径保持纯文件哈希,兼容历史批次回放。
hashes.append(source_hash)
hashes = sorted(set(hashes))
if not hashes:
return ""
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
def batch_stored_content_fingerprint(batch: Any) -> str | None:
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。"""
del batch
return None
def assert_idempotent_batch_content_matches(
batch: Any,
notice_items: list[dict[str, Any]],
) -> None:
"""shipping_batches 已删除;幂等批次内容校验不再适用。"""
del batch, notice_items
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None:
"""
按用户与建单幂等键查找已有批次。
Returns:
固定 None(shipping_batches 已删除)。
"""
del user_id, create_idempotency_key
return None
def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]:
"""shipping_batches 已删除;禁止构建批次重放响应。"""
del batch, user_id
raise_shipping_batches_removed()
def _advisory_lock_key(*parts: str) -> int:
@@ -161,7 +47,6 @@ def assert_no_exact_duplicate_notices(
user_id: int,
notice_items: list[dict[str, Any]],
*,
exclude_batch_id: int | None = None,
exclude_task_ids: Iterable[int] | None = None,
) -> None:
"""
@@ -175,7 +60,6 @@ def assert_no_exact_duplicate_notices(
Args:
user_id: 建单用户。
notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。
exclude_batch_id: 可选;忽略同批次内任务。
exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。
Raises:
@@ -234,28 +118,25 @@ def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> l
return unique
def handle_batch_create_integrity_error(
*,
user_id: int,
create_idempotency_key: str | None,
exc: IntegrityError,
) -> dict[str, Any] | None:
"""
捕获批次建单唯一约束竞争,回滚后回查已有批次。
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
Returns:
幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。
"""
db.session.rollback()
key = str(create_idempotency_key or "").strip()
if not key:
def normalize_create_idempotency_key(raw: str | None) -> str | None:
"""标准化 Review Case 确认幂等键,防止同一确认请求重复创建任务。"""
value = str(raw or "").strip()
if not value:
return None
batch = find_batch_by_create_idempotency(user_id, key)
if not batch:
return None
logger.info(
"shipping batch create idempotency race resolved batch_no=%s user_id=%s",
batch.batch_no,
user_id,
)
return build_existing_batch_tool_response(batch, user_id=user_id)
if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
raise AppError(
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
http_status=400,
)
if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
raise AppError(
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
message="幂等键仅允许字母、数字及 . _ : - 字符",
http_status=400,
)
return value
@@ -1,50 +0,0 @@
"""
backend/app/services/shipping_notice/batch_from_intakes.py
用途:从已解析 ShippingOrderIntake 确认建批的共享编排(co8 起 shipping_batches 已删除,入口阻断)。
依赖:batch_legacy_removed。
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块;
create_shipping_batch_from_intakes / create_shipping_batch_from_candidates 在入口抛出 ValidationError。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
def create_shipping_batch_from_candidates(
*,
user_id: int,
conversation_id: str | None,
intake_nos: list[str],
candidate_nos: list[str],
create_idempotency_key: str | None = None,
) -> dict[str, Any]:
"""
根据选定 Candidate 创建批次。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key
raise_shipping_batches_removed()
def create_shipping_batch_from_intakes(
*,
user_id: int,
conversation_id: str | None,
intake_nos: list[str],
candidate_nos: list[str] | None = None,
create_idempotency_key: str | None = None,
) -> dict[str, Any]:
"""
根据已解析且未消费的 intake 列表创建批次。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key
raise_shipping_batches_removed()
@@ -1,142 +0,0 @@
"""
services/shipping_notice/batch_from_notices.py
用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。
依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。
逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.batch_create_idempotency import (
assert_idempotent_batch_content_matches,
build_existing_batch_tool_response,
dedupe_notice_items_by_content_hash,
find_batch_by_create_idempotency,
handle_batch_create_integrity_error,
normalize_create_idempotency_key,
warn_missing_create_idempotency_key,
)
from app.services.shipping_notice.notice_upload import build_notice_file_summary
from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary
def create_shipping_batch_from_notice_items(
*,
user_id: int,
conversation_id: str | None,
notice_items: list[dict[str, Any]],
file_summary: dict[str, Any] | None = None,
create_idempotency_key: str | None = None,
defer_commit: bool = False,
start_orchestrator: bool | None = None,
) -> dict[str, Any]:
"""
根据已抽取的发货通知条目创建批次并可选启动编排器。
核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。
intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。
Args:
user_id: 当前用户 ID。
conversation_id: 可选 Agent 会话 ID。
notice_items: notice_upload 产出的 notice item 列表。
file_summary: 可选文件预检摘要,写入响应供前端展示。
create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。
defer_commit: True 时下层仅 flush,由调用方最终 commit。
start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。
Returns:
与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
Raises:
ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。
"""
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed()
def format_batch_created_assistant_message(
result: dict[str, Any],
*,
file_count: int = 0,
) -> str:
"""
格式化建批成功后写入 Chat Turn assistant 气泡的文案。
核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。
"""
if bool(result.get("idempotent_replay")):
batch_no = str(result.get("batch_no") or "").strip()
return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。"
data = result.get("data") if isinstance(result.get("data"), dict) else {}
batch = data.get("batch") if isinstance(data.get("batch"), dict) else {}
tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []
focus_task = tasks[0] if tasks and isinstance(tasks[0], dict) else {}
task_id = str(
(data.get("focus_task") or {}).get("task_no")
if isinstance(data.get("focus_task"), dict)
else ""
).strip() or str(result.get("task_id") or focus_task.get("task_id") or "").strip()
batch_no = str(result.get("batch_no") or batch.get("batch_no") or "").strip()
focus_progress = ""
if focus_task.get("batch_index") and focus_task.get("batch_total"):
focus_progress = f"当前第 {focus_task['batch_index']}/{focus_task['batch_total']} 票"
count = int(file_count or batch.get("file_count") or len(tasks) or 0)
hint = str(result.get("message") or "").strip()
status = str(result.get("status") or "").strip()
orchestrator_started = bool(data.get("orchestrator_started"))
tail = "请根据提示进行确认/驳回。" if status == "needs_human" else ""
lines = [
hint or f"已处理 {count} 份发货通知附件",
f"批次编号:{batch_no}" if batch_no else "",
f"当前任务:{task_id}" if task_id else "",
focus_progress,
f"后台已开始按票拆分处理,本批 {count} 票会逐步更新状态。" if orchestrator_started else "",
tail,
]
return "\n".join(line for line in lines if line)
def intake_notice_uploads_for_batch(
request_id: str,
uploads: list,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
预检并抽取发货通知附件,返回 notice_items 与 file_summary。
Args:
request_id: 请求级临时目录 ID。
uploads: Werkzeug FileStorage 列表。
Returns:
(notice_items, file_summary)
"""
max_files = max(int(current_app.config.get('SHIPPING_NOTICE_BATCH_MAX_FILES', 20) or 20), 1)
if len(uploads) > max_files:
from app.core.errors import ValidationError
raise ValidationError(
'批量上传文件数超过限制',
code='SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED',
details={'max_files': max_files, 'received_files': len(uploads)},
)
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads)
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
duplicate_files=duplicate_files,
)
notice_items = [item.to_notice_item() for item in accepted]
return notice_items, file_summary
@@ -1,40 +0,0 @@
"""
backend/app/services/shipping_notice/batch_legacy_removed.py
用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。
依赖:app.core.errors.AppError。
逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410);
读路径 list API 返回空集,按 batch_no 查询返回 None。
"""
from __future__ import annotations
from app.core.errors import AppError
SHIPPING_BATCHES_REMOVED_MESSAGE = (
"shipping_batches removed (migration co8e9f0a1b2c)"
)
def raise_shipping_batches_removed(*, action: str | None = None) -> None:
"""
阻断仍依赖 shipping_batches 表的写路径。
核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。
Args:
action: 可选调用方动作名,写入 error.details 便于排查。
Raises:
AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。
"""
details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'}
if action:
details['action'] = str(action)
raise AppError(
code='SHIPPING.BATCHES_REMOVED',
message=SHIPPING_BATCHES_REMOVED_MESSAGE,
http_status=410,
details=details,
retryable=False,
)
@@ -1,34 +1,29 @@
"""
services/shipping_notice/batch_orchestrator.py
用途:发货通知批次/单票后台编排器。
依赖:query_service、task_workflow、shipping_notice.tools、tool_common。
逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止;
用途:发货通知单票后台编排器。
依赖:query_service、shipping_notice.tools、tool_common。
逻辑:持久化队列只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止;
复核/STP 确认后已挂 current_order_extraction_id 的 created 任务走 auto_progress。
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
from flask import current_app
from app import db
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
from app.services.shipping_notice.task_workflow import recompute_batch_summary
from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
cfg_bool,
cfg_int,
log_task_event,
switch_batch_focus,
)
from app.services.shipping_notice.tools import auto_progress, submit_decision
from app.services.shipping_notice.tools import auto_progress
_RUNNING_BATCHES: set[str] = set()
_RUNNING_TASKS: set[str] = set()
@@ -37,11 +32,6 @@ def batch_orchestrator_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True)
def batch_dispatch_concurrency() -> int:
"""单个批次最多并发派发多少张票。"""
return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1)
def _normalize_ref(value: str | None) -> str:
return str(value or "").strip().upper()
@@ -85,29 +75,6 @@ def _should_orchestrate_task(task: Any) -> bool:
return True
def _is_retryable_task(task: Any) -> bool:
"""判断任务是否允许由批次重试入口重新派发。"""
from app.services.shipping_notice.task_disposition_service import task_is_active
if not task_is_active(task):
return False
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
return False
if getattr(task, "review_status", None):
return False
if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
return True
if getattr(task, "pending_human_reason", None):
return False
return True
def _refresh_batch_focus(task_no: str) -> None:
"""shipping_batches 已删除;批次焦点刷新无操作。"""
del task_no
def _run_single_task(task_no: str) -> dict[str, str | None]:
"""
后台执行单票任务的一轮推进。
@@ -141,9 +108,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
),
}
_refresh_batch_focus(task.task_no)
task = get_task_by_ref(normalized_task_no)
assert task is not None
log_task_event(
task,
"backend_orchestrator_task_started",
@@ -235,70 +199,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
_unmark_running(_RUNNING_TASKS, normalized_task_no)
def _background_task_runner(app: Any, task_no: str) -> None:
try:
with app.app_context():
_run_single_task(task_no)
finally:
_unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}")
def _background_batch_runner(app: Any, batch_no: str) -> None:
normalized_batch_no = _normalize_ref(batch_no)
try:
with app.app_context():
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return
recompute_batch_summary(batch)
db.session.commit()
task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)]
if not task_nos:
return
max_workers = min(batch_dispatch_concurrency(), len(task_nos))
if max_workers <= 1:
for task_no in task_nos:
_refresh_batch_focus(task_no)
_run_single_task(task_no)
batch = get_batch_by_no(normalized_batch_no)
if not batch:
break
else:
app_obj = current_app._get_current_object()
with ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix=f"shipping-batch-{normalized_batch_no}",
) as executor:
future_map = {
executor.submit(_run_task_with_app_context, app_obj, task_no): task_no
for task_no in task_nos
}
for future in as_completed(future_map):
task_no = future_map[future]
try:
future.result()
except Exception as exc:
task = get_task_by_ref(task_no)
if task:
task.error_message = str(exc)
log_task_event(
task,
"backend_orchestrator_task_failed",
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
)
db.session.commit()
batch = get_batch_by_no(normalized_batch_no)
if batch:
recompute_batch_summary(batch)
db.session.commit()
finally:
db.session.remove()
_unmark_running(_RUNNING_BATCHES, normalized_batch_no)
def start_task_orchestrator(task_no: str | None) -> bool:
"""将单票后台任务写入持久化队列。"""
normalized_task_no = _normalize_ref(task_no)
@@ -308,80 +208,3 @@ def start_task_orchestrator(task_no: str | None) -> bool:
return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"}
def start_batch_orchestrator(batch_no: str | None) -> bool:
"""批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。"""
normalized_batch_no = _normalize_ref(batch_no)
if not normalized_batch_no or not batch_orchestrator_enabled():
return False
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return False
started = False
for task in list_sorted_batch_tasks(batch):
ok, _result = enqueue_shipping_notice_job(
task_no=task.task_no,
created_by_id=getattr(batch, "user_id", None),
batch_no=batch.batch_no,
)
started = started or ok
recompute_batch_summary(batch)
db.session.commit()
return started
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
normalized_batch_no = _normalize_ref(batch_no)
if not normalized_batch_no:
return {"status": "failed", "message": "batch_no is required"}
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return {"status": "failed", "message": "batch not found"}
started = 0
skipped = 0
for task in list_sorted_batch_tasks(batch):
if not _is_retryable_task(task):
skipped += 1
continue
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None):
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
status = str(result.get("status") or "").strip().lower()
if status in {"ok", "running", "needs_human"}:
started += 1
else:
skipped += 1
continue
if pending_reason == PH_RPA_EXHAUSTED:
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
status = str(result.get("status") or "").strip().lower()
if status in {"ok", "running", "needs_human"}:
started += 1
else:
skipped += 1
continue
if start_task_orchestrator(task.task_no):
started += 1
else:
skipped += 1
recompute_batch_summary(batch)
db.session.commit()
return {
"status": "ok",
"batch_no": batch.batch_no,
"started": started,
"skipped": skipped,
"message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。",
}
def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]:
"""批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。"""
with app.app_context():
return _run_single_task(task_no)
@@ -26,6 +26,7 @@ from app.extensions import db
from app.models import (
ShippingOrderCandidate,
ShippingOrderCandidateQualification,
ShippingOrderExtraction,
ShippingOrderCustomerMatch,
)
from app.services.shipping_notice.candidate_qualification_contract import (
@@ -75,6 +76,47 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool:
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有
``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法
追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知
字段继续 fail-closed。
"""
reason = str(item.get('reason') or item.get('code') or '').strip()
if reason not in _EVIDENCE_GAP_REASONS:
return False
field_code = str(item.get('field') or item.get('field_code') or '').strip()
if not field_code:
return False
config = item.get('field_config') if isinstance(item.get('field_config'), dict) else None
extraction_id = getattr(candidate, 'order_extraction_id', None)
if config is None and extraction_id is not None:
try:
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
definition = (
extraction.schema_version.definition_json
if extraction is not None and extraction.schema_version is not None
else {}
)
config = next(
(
raw for raw in (definition.get('fields') or [])
if isinstance(raw, dict) and str(raw.get('field_code') or '').strip() == field_code
),
None,
)
except Exception: # noqa: BLE001 - 门禁读取配置失败时继续保守阻断
config = None
if config is not None:
return not bool(config.get('required')) and not bool(config.get('auto_create_key_field'))
return field_code in _OPTIONAL_INTERNAL_FIELD_CODES
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
@@ -97,14 +139,29 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
conflicts = getattr(candidate, 'conflicts_json', None)
if not isinstance(conflicts, list):
return [] if not conflicts else [conflicts]
return [
item for item in conflicts
if not (
isinstance(item, dict)
and str(item.get('reason') or item.get('code') or '').strip()
in _NON_BLOCKING_CONFLICT_REASONS
)
]
blocking: list[Any] = []
for item in conflicts:
# 非字典遗留值无法判明严重度与裁决状态,继续 fail-closed。
if not isinstance(item, dict):
blocking.append(item)
continue
reason = str(item.get('reason') or item.get('code') or '').strip()
if reason in _NON_BLOCKING_CONFLICT_REASONS:
continue
if field_evidence_gap_is_non_blocking(candidate, item):
continue
# 新 Finding 有稳定 key 时,Gate 只消费未解决的 blocking 项;禁止把可提示
# 的 review_required 误升级为自动建单硬阻断。
if str(item.get('conflict_key') or '').strip():
if (
str(item.get('severity') or '').strip() == 'blocking'
and str(item.get('resolution_status') or 'unresolved').strip() == 'unresolved'
):
blocking.append(item)
continue
# 旧结构无稳定键/裁决状态,不能安全推定其已解决,保持历史 fail-closed。
blocking.append(item)
return blocking
# ---------------------------------------------------------------------------
@@ -1,10 +1,10 @@
"""
backend/app/services/shipping_notice/chat_action_extended_handlers.py
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。
用途:货代 Chat Turn 扩展 Action Handler(通知重传/缺口查询)。
依赖:shipping_tools、task_workflow、shipping_turn_helpers、action_registry。
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大;
co8 后 switch_batch_focus 固定 410。
历史批次焦点切换动作已删除。
"""
from __future__ import annotations
@@ -16,7 +16,6 @@ from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.query_service import (
get_task_by_ref,
get_task_for_user,
@@ -164,21 +163,6 @@ class ShippingUploadInventoryAction:
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
class ShippingSwitchBatchFocusAction:
action_type = "shipping.switch_batch_focus"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""
历史批次切票(已下线)。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
"""
del ctx
raise_shipping_batches_removed(action='shipping.switch_batch_focus')
yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解
class ShippingQueryShortageDetailsAction:
action_type = "shipping.query_shortage_details"
@@ -194,7 +178,6 @@ class ShippingQueryShortageDetailsAction:
_HANDLERS = (
ShippingReplaceNoticeAction(),
ShippingUploadInventoryAction(),
ShippingSwitchBatchFocusAction(),
ShippingQueryShortageDetailsAction(),
)
@@ -1,64 +0,0 @@
"""
backend/app/services/shipping_notice/chat_action_handlers.py
用途:货代发货通知 Chat Turn Action Handler 注册实现。
依赖:query_service、ui_state、action_registry、
batch_legacy_removed。
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow;
co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。
"""
from __future__ import annotations
from typing import Iterator
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
class ShippingCreateBatchFromNoticesAction:
"""历史:上传发货通知并创建 shipping_batches;co8 后已下线。"""
action_type = "shipping.create_batch_from_notices"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""
拒绝旧建批 Turn。
核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。
"""
del ctx
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='shipping.create_batch_from_notices')
if False: # pragma: no cover — 满足 Iterator 注解
yield TurnEvent(event='step.started', data={})
class ShippingCreateBatchFromIntakesAction:
"""历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。"""
action_type = "shipping.create_batch_from_intakes"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""
拒绝旧建批 Turn。
核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。
"""
del ctx
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
raise_shipping_batches_removed(action='shipping.create_batch_from_intakes')
if False: # pragma: no cover
yield TurnEvent(event='step.started', data={})
_HANDLERS = (
ShippingCreateBatchFromNoticesAction(),
ShippingCreateBatchFromIntakesAction(),
)
for _handler in _HANDLERS:
register_action_handler(_handler)
@@ -26,7 +26,6 @@ def build_chat_actions_payload(task) -> dict:
state = build_task_ui_state(task)
return {
"task_no": state.get("task_no"),
"batch_no": state.get("batch_no"),
"checkpoint": state.get("checkpoint"),
"stage": state.get("stage"),
"todo": state.get("todo"),
@@ -16,7 +16,7 @@ from app.core.errors import ForbiddenError
from app.models import ChatSession, ShippingNotice
READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'})
READ_SCOPES = frozenset({'get_shipping_status'})
def _secret() -> bytes:
@@ -26,15 +26,15 @@ def _secret() -> bytes:
return value.encode('utf-8')
def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None, batch_no: str | None) -> str:
def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None) -> str:
"""为单次 Chatflow 注入签名、短效且绑定会话/对象的只读令牌。"""
body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'batch': str(batch_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex}
body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex}
raw = json.dumps(body, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
signature = hmac.new(_secret(), raw, hashlib.sha256).digest()
return base64.urlsafe_b64encode(raw).decode().rstrip('=') + '.' + base64.urlsafe_b64encode(signature).decode().rstrip('=')
def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None, batch_no: str | None = None) -> dict[str, Any]:
def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None) -> dict[str, Any]:
"""验证令牌签名、时效、scope、会话归属及请求对象,拒绝猜测他人编号。"""
try:
encoded, signed = str(token or '').split('.', 1)
@@ -53,6 +53,4 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
if task is None or str(body.get('task') or '').upper() != task.task_no:
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper():
raise ForbiddenError('Batch is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
return body
@@ -33,7 +33,7 @@ def build_shipping_notice_context_adapter(
Args:
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
session_id: HXOPS 会话 ID。
adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id、batch_no。
adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id。
request_id: 请求追踪 ID。
trigger_source: 触发来源。
locale: 用户语言。
@@ -46,7 +46,6 @@ def build_shipping_notice_context_adapter(
return build_dify_chat_inputs(
session_id,
task_id=shipping_hints.get('task_id'),
batch_no=shipping_hints.get('batch_no'),
trigger_source=trigger_source,
request_id=request_id,
locale=locale,
@@ -3,7 +3,7 @@ services/shipping_notice/dify_inputs.py
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。
逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点,
逻辑:由 Context Adapter / api/chat 调用;本模块只使用显式任务锚点,
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。
"""
@@ -19,14 +19,8 @@ from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPU
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def _latest_batch_for_conversation(conversation_id: str) -> None:
"""shipping_batches 已删除;固定返回 None。"""
del conversation_id
return None
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
"""按显式 task_id 获取任务;禁止按会话号猜测当前任务。"""
normalized = str(task_id or "").strip().upper()
if not normalized:
return None
@@ -66,8 +60,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -
"""
解析当前显式焦点任务行。
核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询,
但不在无焦点时回退到最近任务,避免多票批次串单。
核心逻辑:优先复用已查出的显式 task;不在无焦点时回退到最近任务,避免多票串单。
Args:
focus_task: 已解析出的焦点任务号。
@@ -88,7 +81,6 @@ def build_dify_chat_inputs(
conversation_id: str | None = None,
*,
task_id: str | None = None,
batch_no: str | None = None,
trigger_source: str | None = None,
request_id: str | None = None,
locale: str | None = None,
@@ -108,7 +100,6 @@ def build_dify_chat_inputs(
return {}
explicit_task = str(task_id or "").strip().upper()
explicit_batch = str(batch_no or "").strip().upper()
explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper()
resolved_temporary_session = (
explicit_temporary_session
@@ -119,28 +110,12 @@ def build_dify_chat_inputs(
)
)
batch = _latest_batch_for_conversation(conv_id)
explicit_task_row = _task_by_task_no(explicit_task)
focus_task = explicit_task
if not focus_task and batch and batch.current_focus_task_no:
focus_task = str(batch.current_focus_task_no or "").strip().upper()
focus_batch = explicit_batch
if not focus_batch and batch and batch.batch_no:
focus_batch = str(batch.batch_no or "").strip().upper()
elif (
not focus_batch
and explicit_task_row
and getattr(explicit_task_row, "batch", None) is not None
and getattr(explicit_task_row.batch, "batch_no", None)
):
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
runtime_context = build_shipping_runtime_context(
session_id=conv_id,
task=_focus_task_row(focus_task, explicit_task_row),
batch=batch or getattr(explicit_task_row, "batch", None),
trigger_source=trigger_source,
request_id=request_id,
locale=locale,
@@ -161,7 +136,7 @@ def build_dify_chat_inputs(
session = ChatSession.query.filter_by(session_id=conv_id).one_or_none()
capability_token = issue_chat_capability(
user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id,
task_no=focus_task, batch_no=focus_batch,
task_no=focus_task,
) if session is not None else None
return {
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
@@ -431,6 +431,62 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
}
def _serialize_candidate_status_brief(
cand: ShippingOrderCandidate,
*,
documents: dict[int, str | None],
) -> dict[str, Any]:
"""序列化 Intake 状态列表所需的 Candidate 最小字段,不读取审核证据详情。"""
from app.services.shipping_notice.duplicate_detection import _allowed_actions_for
status = str(cand.duplicate_status or 'unchecked')
blocking = status in {
'exact_file',
'same_active_task',
'same_completed_task',
'possible_duplicate',
'same_business_content',
'possible_revision',
}
strength = str(cand.fingerprint_strength or 'unavailable')
if strength == 'unavailable' and status == 'none':
blocking = False
structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {}
business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
return {
'candidate_no': cand.candidate_no,
'primary_document_id': cand.primary_document_id,
'primary_document_filename': documents.get(int(cand.primary_document_id))
if cand.primary_document_id is not None else None,
'po_number': cand.po_number or business_summary.get('po_number'),
'validation_status': cand.validation_status,
'candidate_status': cand.candidate_status,
'acceptance_mode': cand.acceptance_mode,
'extraction_source': cand.extraction_source,
'selected': bool(cand.selected),
'conflicts': list(cand.conflicts_json or []),
'missing_fields': list(cand.missing_fields_json or []),
'business_summary': business_summary,
'duplicate': {
'status': status,
'blocking': blocking,
'fingerprint_strength': strength,
'matches': list(cand.duplicate_matches_json or []),
'allowed_actions': _allowed_actions_for(
status=status,
fingerprint_strength=strength,
matches=list(cand.duplicate_matches_json or []),
),
},
'duplicate_resolution': {
'action': cand.duplicate_resolution,
'target_task_no': cand.duplicate_target_task_no,
'reason': cand.duplicate_resolution_reason,
} if cand.duplicate_resolution else None,
'consumed_task_id': cand.consumed_task_id,
}
def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]:
"""列出 Intake 下 Document 摘要。"""
rows = (
@@ -442,15 +498,36 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list
return [_serialize_document_brief(row, include_text=include_text) for row in rows]
def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]:
"""列出 Intake 下 Candidate 摘要。"""
def list_intake_candidates(
intake_id: int,
*,
include_details: bool = True,
) -> list[dict[str, Any]]:
"""列出 Intake 下 Candidate 摘要;状态列表可省略重型审核证据。"""
rows = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.intake_id == int(intake_id))
.order_by(ShippingOrderCandidate.id.asc())
.all()
)
return [_serialize_candidate_brief(row) for row in rows]
if include_details:
return [_serialize_candidate_brief(row) for row in rows]
document_ids = {
int(row.primary_document_id)
for row in rows
if row.primary_document_id is not None
}
documents = {
int(row.id): row.filename
for row in (
db.session.query(ShippingOrderDocument.id, ShippingOrderDocument.filename)
.filter(ShippingOrderDocument.id.in_(document_ids))
.all()
if document_ids else []
)
}
return [_serialize_candidate_status_brief(row, documents=documents) for row in rows]
_UNCHECKED_DUP: dict[str, Any] = {
@@ -8,7 +8,6 @@
from __future__ import annotations
from copy import deepcopy
import math
import re
from statistics import median
@@ -17,6 +16,9 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
@@ -111,7 +113,7 @@ _HEADER_TERMS = frozenset({
'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev',
})
_SUMMARY_PATTERN = re.compile(
r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
r'(?:\btotal(?:\s*amount)?\b|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
re.IGNORECASE,
)
@@ -477,65 +479,64 @@ def _project_coordinate_profile_regions(
exclusion_regions: list[dict[str, Any]] | None,
coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""对当前重建调用复制并投影受 matcher 证明的相对坐标平移。
"""对当前重建调用复制并投影受 matcher 证明的统一坐标变换。
未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied``
变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review,
不能静默回退到旧绝对坐标。
"""
if coordinate_transform is None:
return {
'table_region': table_region,
'line_layouts': line_layouts,
'termination_rules': termination_rules,
'exclusion_regions': exclusion_regions,
}
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
return None
try:
translate_x = float(coordinate_transform['translate_x'])
translate_y = float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return None
if not math.isfinite(translate_x) or not math.isfinite(translate_y):
return None
def translate_region(region: Any) -> bool:
def project_region(region: Any) -> dict[str, float] | None:
if not isinstance(region, dict):
return False
try:
x0, y0 = float(region['x0']) + translate_x, float(region['y0']) + translate_y
x1, y1 = float(region['x1']) + translate_x, float(region['y1']) + translate_y
except (KeyError, TypeError, ValueError):
return False
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
return False
region.update({'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1})
return True
return None
return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
projected_table = deepcopy(table_region) if table_region is not None else None
projected_layouts = deepcopy(line_layouts)
projected_terminations = deepcopy(termination_rules) if termination_rules is not None else None
projected_exclusions = deepcopy(exclusion_regions) if exclusion_regions is not None else None
if projected_table is not None and not translate_region(projected_table):
projected_table = project_region(table_region) if table_region is not None else None
projected_layouts = []
projected_terminations: list[dict[str, Any]] | None = [] if termination_rules is not None else None
projected_exclusions: list[dict[str, float]] | None = [] if exclusion_regions is not None else None
if table_region is not None and projected_table is None:
return None
for layout in projected_layouts:
for layout in line_layouts:
if not isinstance(layout, dict):
return None
region = layout.get('region')
if region is not None and not translate_region(region):
return None
for field in layout.get('field_regions') or []:
if not isinstance(field, dict) or not translate_region(field.get('region')):
copied = dict(layout)
region = copied.get('region')
if region is not None:
projected_region = project_region(region)
if projected_region is None:
return None
for rule in projected_terminations or []:
anchor = rule.get('anchor') if isinstance(rule, dict) else None
copied['region'] = projected_region
fields = []
for field in copied.get('field_regions') or []:
if not isinstance(field, dict):
return None
projected_field = dict(field)
projected_region = project_region(field.get('region'))
if projected_region is None:
return None
projected_field['region'] = projected_region
fields.append(projected_field)
copied['field_regions'] = fields
projected_layouts.append(copied)
for rule in termination_rules or []:
if not isinstance(rule, dict):
return None
copied = dict(rule)
anchor = copied.get('anchor')
region = anchor.get('region') if isinstance(anchor, dict) else None
if region is not None and not translate_region(region):
return None
for region in projected_exclusions or []:
if not translate_region(region):
if region is not None:
projected_region = project_region(region)
if projected_region is None:
return None
copied['anchor'] = {**anchor, 'region': projected_region}
assert projected_terminations is not None
projected_terminations.append(copied)
for region in exclusion_regions or []:
projected_region = project_region(region)
if projected_region is None:
return None
assert projected_exclusions is not None
projected_exclusions.append(projected_region)
return {
'table_region': projected_table,
'line_layouts': projected_layouts,
@@ -912,6 +913,86 @@ def suggest_multi_subrow_layouts(
return suggestions
def derive_incomplete_table_bbox(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox | dict[str, Any],
) -> dict[str, float] | None:
"""从页级字符证据修复只覆盖表头的候选表格框。
该函数只允许沿原候选框的纵向向下扩展:必须先看到可靠的明细起行锚点,
并在其后遇到明确的合计/终止行;否则返回 ``None``。横向边界始终继承原候选,
因而不会把页面上的其他表格或普通文本合并进来。
Args:
characters: 同页完整 PDF/OCR 字符坐标,而不是已按错误表框截取的字符。
table_bbox: MinerU 或其他结构引擎产出的原始表格候选框。
Returns:
可验证的派生绝对表格框;证据不唯一或缺失时返回 ``None``。
"""
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
if bbox.x1 <= bbox.x0 or bbox.y1 <= bbox.y0:
return None
try:
positioned = [
(
index,
item if isinstance(item, PositionedCharacter)
else PositionedCharacter.model_validate(item),
)
for index, item in enumerate(characters)
]
except Exception:
return None
# 只取原表横向范围内的字符,纵向上限使用页面证据的最大 y 值。
candidates = [
item for item in positioned
if bbox.x0 <= (item[1].bbox.x0 + item[1].bbox.x1) / 2 <= bbox.x1
and (item[1].bbox.y0 + item[1].bbox.y1) / 2 >= bbox.y0
]
if not candidates:
return None
bands = _group_visual_rows(candidates)
anchor_bands: list[list[tuple[int, PositionedCharacter]]] = []
summary_y0: float | None = None
for band in bands:
band_bbox = _band_bbox(band)
text = ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
).strip()
if band_bbox.y1 <= bbox.y1:
continue
if _SUMMARY_PATTERN.search(text):
if anchor_bands:
summary_y0 = band_bbox.y0
break
continue
if _band_starts_item(band, bbox):
anchor_bands.append(band)
if not anchor_bands:
return None
last_data_y1 = max(glyph.bbox.y1 for band in anchor_bands for _, glyph in band)
# 续行属于同一表格,但不能将其误当成新的表格边界;取终止行前的最后字符。
for band in bands:
band_bbox = _band_bbox(band)
if band_bbox.y0 < anchor_bands[0][0][1].bbox.y0:
continue
text = ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
).strip()
if _SUMMARY_PATTERN.search(text):
break
last_data_y1 = max(last_data_y1, band_bbox.y1)
end_y = summary_y0 if summary_y0 is not None else last_data_y1
if end_y <= bbox.y1:
return None
return {
'x0': float(bbox.x0), 'y0': float(bbox.y0),
'x1': float(bbox.x1), 'y1': float(end_y),
}
def suggest_header_regions(
*,
characters: list[PositionedCharacter | dict[str, Any]],
@@ -0,0 +1,133 @@
"""
services/shipping_notice/document_layout/coordinate_transform.py
用途:对冻结 Profile 的归一化几何区域应用 matcher 已证明的受限坐标变换。
依赖:标准库数学运算;由 Profile matcher 求解、订单头和订单行解析共同消费。
逻辑:默认保持 legacy 绝对坐标;仅接受已应用且通过残差/边界门禁的平移或仿射矩阵,
任何无效、过界或无法由稳定锚点证明的变换都返回 None 以进入 Review。
"""
from __future__ import annotations
import math
from copy import deepcopy
from typing import Any
def apply_coordinate_transform_to_region(
region: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, float] | None:
"""将 Profile 相对区域投影到当前文档坐标系,非法变换 fail-closed。
Args:
region: 含 x0/y0/x1/y1 的冻结归一化矩形。
coordinate_transform: Matcher 唯一候选附带的 ``status=applied`` 变换;None 表示 legacy。
Returns:
投影后的页内 bbox;矩阵将矩形四角包络,旋转后仍保留完整证据范围。
"""
try:
corners = [
(float(region['x0']), float(region['y0'])),
(float(region['x0']), float(region['y1'])),
(float(region['x1']), float(region['y0'])),
(float(region['x1']), float(region['y1'])),
]
except (KeyError, TypeError, ValueError):
return None
if not all(math.isfinite(value) for pair in corners for value in pair):
return None
if coordinate_transform is None:
return _bounded_bbox(corners)
matrix = coordinate_transform_matrix(coordinate_transform)
if matrix is None:
return None
return _bounded_bbox([_apply_matrix(matrix, x=x, y=y) for x, y in corners])
def coordinate_transform_matrix(value: dict[str, Any]) -> tuple[float, float, float, float, float, float] | None:
"""解析并校验 matcher 输出;无 matrix 的历史 applied 结果仅视为平移。"""
if not isinstance(value, dict) or value.get('status') != 'applied':
return None
raw = value.get('matrix')
if isinstance(raw, list) and len(raw) == 6:
try:
matrix = tuple(float(item) for item in raw)
except (TypeError, ValueError):
return None
else:
try:
matrix = (1.0, 0.0, float(value['translate_x']), 0.0, 1.0, float(value['translate_y']))
except (KeyError, TypeError, ValueError):
return None
if not all(math.isfinite(item) for item in matrix):
return None
a, b, _tx, d, e, _ty = matrix
determinant = a * e - b * d
if determinant <= 0 or determinant < .50 or determinant > 1.50:
return None
return matrix
def project_coordinate_profile_payload(
payload: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""复制并统一投影 Profile 的订单头、表区、行区、字段和终止区,不回写冻结定义。"""
if coordinate_transform is None:
return deepcopy(payload)
projected = deepcopy(payload)
def project(region: Any) -> bool:
if not isinstance(region, dict):
return False
next_region = apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
if next_region is None:
return False
region.clear()
region.update(next_region)
return True
for layout in projected.get('order_field_layouts') or []:
if not isinstance(layout, dict):
return None
for key in ('absolute_value_region', 'fallback_value_region'):
region = layout.get(key)
if region is not None and not project(region):
return None
anchor = layout.get('anchor')
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
return None
for table in projected.get('table_regions') or []:
if not isinstance(table, dict) or not project(table.get('region')):
return None
for layout in [*(table.get('header_layouts') or []), *(table.get('line_layouts') or [])]:
if not isinstance(layout, dict) or not project(layout.get('region')):
return None
for field in layout.get('field_regions') or []:
if not isinstance(field, dict) or not project(field.get('region')):
return None
for rule in table.get('termination_rules') or []:
anchor = rule.get('anchor') if isinstance(rule, dict) else None
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
return None
for region in table.get('exclusion_regions') or []:
if not project(region):
return None
return projected
def _apply_matrix(matrix: tuple[float, float, float, float, float, float], *, x: float, y: float) -> tuple[float, float]:
"""应用二维仿射矩阵,输入输出均为页内归一化坐标。"""
a, b, tx, d, e, ty = matrix
return a * x + b * y + tx, d * x + e * y + ty
def _bounded_bbox(corners: list[tuple[float, float]]) -> dict[str, float] | None:
"""将投影角点收敛为页内 bbox;旋转后越页的区域必须 Review。"""
if not corners or not all(math.isfinite(value) for pair in corners for value in pair):
return None
x0, x1 = min(x for x, _ in corners), max(x for x, _ in corners)
y0, y1 = min(y for _, y in corners), max(y for _, y in corners)
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
return None
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
@@ -29,13 +29,32 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
# Run 快照可能早于最近一次布局重试;当前 Layout 是最新解析事实,同页坐标必须
# 优先于 Run 快照,后者只能补齐当前 Layout 尚未保存的页或表。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
current_evidence = current_payload.get('coordinate_evidence')
if isinstance(current_evidence, dict):
evidence = {**current_evidence, **evidence}
merged_current = dict(evidence)
for key in ('pages', 'page_glyphs', 'tables'):
snapshot_mapping = _coordinate_mapping(evidence.get(key))
current_mapping = _coordinate_mapping(current_evidence.get(key))
# 仅合并实际存在的坐标类别。空 tables 不得写入轻量快照,否则会让
# 顶层业务 tables 列表与坐标表映射的边界在后续调用中变得模糊。
if snapshot_mapping or current_mapping:
merged_current[key] = {**snapshot_mapping, **current_mapping}
snapshot_sources = _coordinate_mapping(evidence.get('sources'))
current_sources = _coordinate_mapping(current_evidence.get('sources'))
merged_current['sources'] = {
**snapshot_sources,
**current_sources,
'pages': {
**_coordinate_mapping(snapshot_sources.get('pages')),
**_coordinate_mapping(current_sources.get('pages')),
},
}
evidence = merged_current
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
if key not in evidence and isinstance(current_payload.get(key), dict):
evidence[key] = current_payload[key]
@@ -14,6 +14,9 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_transform import (
project_coordinate_profile_payload,
)
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRelativeRegion,
@@ -84,42 +87,20 @@ def extract_order_fields(
def _project_coordinate_transform(
profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None,
) -> OrderCoordinateProfile | None:
"""把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。"""
"""把 matcher 唯一确认的统一变换投影到订单头布局,禁止二次估算。"""
if coordinate_transform is None:
return profile
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
payload = project_coordinate_profile_payload(
profile.model_dump(mode='python'), coordinate_transform=coordinate_transform,
)
if payload is None:
return None
try:
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return None
if not all(value == value and abs(value) != float('inf') for value in (dx, dy)):
return None
payload = profile.model_dump(mode='python')
for layout in payload.get('order_field_layouts') or []:
if not isinstance(layout, dict):
continue
for key in ('absolute_value_region', 'fallback_value_region'):
region = layout.get(key)
if isinstance(region, dict):
_translate_region_dict(region, dx=dx, dy=dy)
anchor = layout.get('anchor')
if isinstance(anchor, dict) and isinstance(anchor.get('region'), dict):
_translate_region_dict(anchor['region'], dx=dx, dy=dy)
try:
return OrderCoordinateProfile.model_validate(payload)
except Exception:
return None
def _translate_region_dict(region: dict[str, Any], *, dx: float, dy: float) -> None:
"""原地平移归一化区域并拒绝越界;调用方随后重新校验 Profile。"""
region['x0'] = float(region['x0']) + dx
region['x1'] = float(region['x1']) + dx
region['y0'] = float(region['y0']) + dy
region['y1'] = float(region['y1']) + dy
def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
allow_ocr_preview_fallback: bool = False,
@@ -428,12 +428,16 @@ class DocumentMatchProfile(OrderProfileModel):
class AnchorFrameCoordinateModel(OrderProfileModel):
"""声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。"""
"""声明以稳定静态文字建立运行时受限几何坐标框架的 Profile 能力。"""
type: Literal['anchor_frame']
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
max_translate_x: float = Field(default=.03, ge=0, le=.15)
max_translate_y: float = Field(default=.06, ge=0, le=.20)
transform_mode: Literal['translate', 'affine'] = 'translate'
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
max_residual: float = Field(default=.01, gt=0, le=.05)
@model_validator(mode='after')
def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel':
@@ -443,6 +447,8 @@ class AnchorFrameCoordinateModel(OrderProfileModel):
ids = [anchor.anchor_id for anchor in self.anchors]
if len(ids) != len(set(ids)):
raise ValueError('anchor frame anchor ids must be unique')
if self.transform_mode == 'affine' and len(self.anchors) < 3:
raise ValueError('affine coordinate model requires at least three frame anchors')
return self
@@ -453,6 +459,10 @@ class CoordinateModel(OrderProfileModel):
anchors: list[AnchorRule] = Field(default_factory=list, max_length=4)
max_translate_x: float = Field(default=.03, ge=0, le=.15)
max_translate_y: float = Field(default=.06, ge=0, le=.20)
transform_mode: Literal['translate', 'affine'] = 'translate'
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
max_residual: float = Field(default=.01, gt=0, le=.05)
@model_validator(mode='after')
def validate_coordinate_model(self) -> 'CoordinateModel':
@@ -463,6 +473,8 @@ class CoordinateModel(OrderProfileModel):
AnchorFrameCoordinateModel(
type='anchor_frame', anchors=self.anchors,
max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y,
transform_mode=self.transform_mode, max_scale_delta=self.max_scale_delta,
max_rotation_degrees=self.max_rotation_degrees, max_residual=self.max_residual,
)
return self
@@ -10,6 +10,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py
from __future__ import annotations
from copy import deepcopy
import math
import re
from typing import Any, Literal
@@ -20,6 +21,9 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import
read_coordinate_region_text,
visual_glyph_rows,
)
from app.services.shipping_notice.document_layout.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRule,
CRITICAL_STRUCTURE_DIMENSION_KEYS,
@@ -34,7 +38,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
)
LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2'
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
# 避免无意义的版本兼容分支。
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
def _anchor_comparable_text(value: Any) -> str:
@@ -359,13 +365,9 @@ def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]:
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
primary_bbox=bbox,
)
first = candidates[0] if candidates else {}
rendered_tables.append({
'bbox': bbox,
'header_candidates': candidates,
'header_tokens': first.get('header_tokens', []),
'column_centers': first.get('column_centers', []),
'column_width_ratios': first.get('column_width_ratios', []),
})
result = {
'version': LAYOUT_MATCHING_FEATURES_VERSION,
@@ -520,6 +522,7 @@ def _resolve_coordinate_transform(
return None, []
deltas: list[tuple[float, float]] = []
anchor_points: list[tuple[float, float, float, float]] = []
anchor_ids: list[str] = []
for anchor in model.anchors:
found = _find_anchor_rule_matches(
@@ -546,8 +549,15 @@ def _resolve_coordinate_transform(
expected_x = (anchor.region.x0 + anchor.region.x1) / 2
expected_y = (anchor.region.y0 + anchor.region.y1) / 2
deltas.append((observed_x - expected_x, observed_y - expected_y))
anchor_points.append((expected_x, expected_y, observed_x, observed_y))
anchor_ids.append(anchor.anchor_id)
if model.transform_mode == 'affine':
transform, reason = _resolve_affine_coordinate_transform(
anchor_points=anchor_points, anchor_ids=anchor_ids, model=model,
)
return transform, [] if transform is not None else [reason]
first_x, first_y = deltas[0]
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
return None, ['profile_anchor_frame_anchor_inconsistent']
@@ -562,6 +572,92 @@ def _resolve_coordinate_transform(
}, []
def _resolve_affine_coordinate_transform(
*, anchor_points: list[tuple[float, float, float, float]], anchor_ids: list[str], model: Any,
) -> tuple[dict[str, Any] | None, str]:
"""以 Profile 显式声明的三个以上稳定锚点求受限仿射,无法证明即失败关闭。"""
if len(anchor_points) < 3:
return None, 'profile_anchor_frame_affine_anchor_insufficient'
matrix_x = _least_squares_affine_axis(anchor_points, observed_index=2)
matrix_y = _least_squares_affine_axis(anchor_points, observed_index=3)
if matrix_x is None or matrix_y is None:
return None, 'profile_anchor_frame_affine_anchor_degenerate'
a, b, tx = matrix_x
d, e, ty = matrix_y
determinant = a * e - b * d
scale_x, scale_y = math.hypot(a, d), math.hypot(b, e)
rotation_degrees = abs(math.degrees(math.atan2(d, a)))
residual = max(
math.hypot(a * x + b * y + tx - observed_x, d * x + e * y + ty - observed_y)
for x, y, observed_x, observed_y in anchor_points
)
if not all(math.isfinite(value) for value in (determinant, scale_x, scale_y, rotation_degrees, residual)):
return None, 'profile_anchor_frame_affine_invalid'
if determinant <= 0:
return None, 'profile_anchor_frame_affine_invalid'
if max(abs(scale_x - 1), abs(scale_y - 1)) > model.max_scale_delta:
return None, 'profile_anchor_frame_affine_scale_out_of_range'
if rotation_degrees > model.max_rotation_degrees:
return None, 'profile_anchor_frame_affine_rotation_out_of_range'
if residual > model.max_residual:
return None, 'profile_anchor_frame_affine_residual_out_of_range'
if abs(tx) > model.max_translate_x or abs(ty) > model.max_translate_y:
return None, 'profile_anchor_frame_transform_out_of_range'
return {
'status': 'applied',
'matrix': [round(value, 6) for value in (a, b, tx, d, e, ty)],
'translate_x': round(tx, 6),
'translate_y': round(ty, 6),
'anchor_ids': anchor_ids,
'residual': round(residual, 6),
'reason_codes': [],
}, ''
def _least_squares_affine_axis(
points: list[tuple[float, float, float, float]], *, observed_index: int,
) -> tuple[float, float, float] | None:
"""用正规方程拟合单个仿射轴;共线锚点会因奇异矩阵而被拒绝。"""
count = float(len(points))
sum_x = sum(item[0] for item in points)
sum_y = sum(item[1] for item in points)
sum_xx = sum(item[0] * item[0] for item in points)
sum_xy = sum(item[0] * item[1] for item in points)
sum_yy = sum(item[1] * item[1] for item in points)
sum_z = sum(item[observed_index] for item in points)
sum_xz = sum(item[0] * item[observed_index] for item in points)
sum_yz = sum(item[1] * item[observed_index] for item in points)
determinant = (
sum_xx * (sum_yy * count - sum_y * sum_y)
- sum_xy * (sum_xy * count - sum_y * sum_x)
+ sum_x * (sum_xy * sum_y - sum_yy * sum_x)
)
if not math.isfinite(determinant) or abs(determinant) < 1e-9:
return None
matrix = ((sum_xx, sum_xy, sum_x), (sum_xy, sum_yy, sum_y), (sum_x, sum_y, count))
target = (sum_xz, sum_yz, sum_z)
values = []
for column in range(3):
replaced = tuple(
tuple(target[row] if index == column else matrix[row][index] for index in range(3))
for row in range(3)
)
value = _determinant_3x3(replaced) / determinant
if not math.isfinite(value):
return None
values.append(value)
return values[0], values[1], values[2]
def _determinant_3x3(matrix: tuple[tuple[float, float, float], ...]) -> float:
"""返回 3x3 矩阵行列式,供无额外数值依赖的仿射拟合使用。"""
return (
matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])
)
def _find_anchor_rule_matches(
*, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any],
max_translate_x: float, max_translate_y: float,
@@ -669,24 +765,38 @@ def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> boo
def _translate_signature(
*, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。"""
"""将当前 Profile 签名映射到共同坐标框架,非法变换必须使证据失效。"""
if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied':
return signature
try:
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return signature
translated = deepcopy(signature)
def project_bbox(value: Any) -> list[float] | None:
if not isinstance(value, list) or len(value) != 4:
return None
projected = apply_coordinate_transform_to_region(
{'x0': value[0], 'y0': value[1], 'x1': value[2], 'y1': value[3]},
coordinate_transform=coordinate_transform,
)
if projected is None:
return None
return [projected['x0'], projected['y0'], projected['x1'], projected['y1']]
for pattern in translated.get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {}
median = bbox.get('median') if isinstance(bbox.get('median'), list) else None
if median and len(median) == 4:
bbox['median'] = [median[0] + dx, median[1] + dy, median[2] + dx, median[3] + dy]
if median:
projected = project_bbox(median)
if projected is None:
return None
bbox['median'] = projected
header = pattern.get('header_bbox')
if isinstance(header, list) and len(header) == 4:
pattern['header_bbox'] = [header[0] + dx, header[1] + dy, header[2] + dx, header[3] + dy]
if header is not None:
projected = project_bbox(header)
if projected is None:
return None
pattern['header_bbox'] = projected
for relation in translated.get('field_relation_graph') or []:
if isinstance(relation, dict):
# 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。
@@ -1029,7 +1139,7 @@ def _observe_layout_features(
) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
persisted = layout.get('matching_features')
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v1 投影。
if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()):
persisted = None
if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION:
@@ -1077,26 +1187,26 @@ def _observe_layout_features(
def _observed_features_from_persisted_projection(
*, features: dict[str, Any], signature: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。"""
"""将完整的事实投影恢复为 matcher 输入,缺任一关键结构则拒绝匹配。
投影生成时没有 Profile 上下文,因此会保留同一主表的多个视觉行候选。运行期只能
根据冻结签名的 token、顺序和列几何联合选择;按列数选最近候选会把数据行误作表头。
"""
page_structure = features.get('page_structure')
tables = features.get('tables')
if not isinstance(page_structure, dict) or not isinstance(tables, list):
return None
candidates = [item for item in tables if isinstance(item, dict) and isinstance(item.get('bbox'), list)]
candidates = [
item for item in tables
if isinstance(item, dict)
and _is_complete_persisted_table_candidate(item)
]
if not candidates:
return None
expected = _signature_column_values(signature or {}, 'column_centers')
primary = candidates[0]
if expected:
def distance(item: dict[str, Any]) -> tuple[float, int]:
options = item.get('header_candidates') if isinstance(item.get('header_candidates'), list) else [item]
best = min((abs(len(option.get('column_centers') or []) - len(expected)) for option in options if isinstance(option, dict)), default=999)
return best, abs(len(item.get('column_centers') or []) - len(expected))
primary = min(candidates, key=distance)
options = primary.get('header_candidates') if isinstance(primary.get('header_candidates'), list) else []
if options:
primary = min(options, key=lambda item: abs(len(item.get('column_centers') or []) - len(expected))) | {'bbox': candidates[0].get('bbox')}
bbox = primary.get('bbox')
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
if selected is None:
return None
primary, bbox = selected
centers = primary.get('column_centers')
widths = primary.get('column_width_ratios')
tokens = primary.get('header_tokens')
@@ -1121,6 +1231,80 @@ def _observed_features_from_persisted_projection(
}
def _is_complete_persisted_table_candidate(candidate: dict[str, Any]) -> bool:
"""校验 v1 投影的表和表头候选契约,防止不完整旧数据参与高分匹配。"""
bbox = candidate.get('bbox')
headers = candidate.get('header_candidates')
if not isinstance(bbox, list) or len(bbox) != 4 or not isinstance(headers, list):
return False
return any(_is_complete_persisted_header_candidate(item) for item in headers if isinstance(item, dict))
def _is_complete_persisted_header_candidate(candidate: dict[str, Any]) -> bool:
"""候选行必须同时保留 token、列中心和列宽,不能用残缺结构猜测。"""
tokens = candidate.get('header_tokens')
centers = candidate.get('column_centers')
widths = candidate.get('column_width_ratios')
return (
isinstance(tokens, list)
and isinstance(centers, list)
and isinstance(widths, list)
and bool(tokens)
and bool(centers)
and len(centers) == len(widths)
)
def _select_persisted_header_candidate(
*, candidates: list[dict[str, Any]], signature: dict[str, Any] | None,
) -> tuple[dict[str, Any], list[float]] | None:
"""按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。"""
expected_tokens = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
expected_order = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_order') or []
]
expected_centers = _signature_column_values(signature or {}, 'column_centers')
expected_widths = _signature_column_values(signature or {}, 'column_width_ratios')
if not expected_tokens or not expected_centers:
return None
scored: list[tuple[float, float, float, int, dict[str, Any], list[float]]] = []
for table in candidates:
bbox = table['bbox']
for header in table['header_candidates']:
if not isinstance(header, dict) or not _is_complete_persisted_header_candidate(header):
continue
tokens = [str(token).casefold() for token in header['header_tokens']]
centers = header['column_centers']
widths = header['column_width_ratios']
token_ratio = sum(token in tokens for token in expected_tokens) / len(expected_tokens)
shared = [token for token in expected_order if token in tokens]
order_ratio = 1.0
if len(shared) > 1:
positions = [tokens.index(token) for token in shared]
order_ratio = sum(left < right for left, right in zip(positions, positions[1:])) / (len(positions) - 1)
center_ratio = _sequence_similarity(expected_centers, centers, tolerance=0.08)
width_ratio = _sequence_similarity(expected_widths, widths, tolerance=0.16) if expected_widths else 1.0
count_ratio = min(len(expected_centers), len(centers)) / max(len(expected_centers), len(centers))
score = .50 * token_ratio + .15 * order_ratio + .25 * center_ratio + .05 * width_ratio + .05 * count_ratio
# token 语义或几何任一缺失都不足以把压缩投影作为结构事实。
if token_ratio < .50 or center_ratio < .50:
continue
scored.append((score, token_ratio, center_ratio, len(tokens), header, bbox))
if not scored:
return None
_, _, _, _, header, bbox = max(scored, key=lambda item: item[:4])
return header, bbox
def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
) -> list[float] | None:
@@ -61,19 +61,31 @@ def _normalize_schema_row(
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
"""将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。"""
"""将首行映射为 Schema 订单字段;同字段多个别名按 Schema 顺序保留首选列。"""
schema_headers = _schema_headers(schema_definition)
mapped: dict[int, str] = {}
selected_by_field: dict[str, tuple[int, int]] = {}
issues: list[str] = []
for column, slot in enumerate(grid.rows[0]):
normalized = normalize_table_header(slot.text if slot is not None else '').casefold()
schema_field = schema_headers.get(normalized)
hits = [schema_field] if schema_field else []
if len(hits) == 1:
if hits[0] in mapped.values():
issues.append('email_supplement_duplicate_header')
field_code = str(hits[0])
priority = _schema_header_priority(schema_definition, field_code, normalized)
previous = selected_by_field.get(field_code)
if previous is None:
mapped[column] = field_code
selected_by_field[field_code] = (priority, column)
else:
mapped[column] = hits[0]
previous_priority, previous_column = previous
# 同一业务字段出现两个已配置别名时,按 Schema 中 field_code、
# display_name、aliases 的声明顺序选择唯一证据列;不把同一行
# 的 Source / hub code 误判为冲突,也不允许后一个列覆盖首选值。
if priority < previous_priority:
mapped.pop(previous_column, None)
mapped[column] = field_code
selected_by_field[field_code] = (priority, column)
elif len(hits) > 1:
issues.append('email_supplement_header_ambiguous')
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
@@ -81,6 +93,21 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
return mapped, sorted(set(issues))
def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int:
"""返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。"""
priorities: list[int] = []
for raw in schema_definition.get('fields') or []:
if not isinstance(raw, dict) or not raw.get('enabled', True):
continue
if str(raw.get('field_code') or '').strip() != field_code:
continue
candidates = (field_code, raw.get('display_name'), *(raw.get('aliases') or []))
for priority, value in enumerate(candidates):
if normalize_table_header(value).casefold() == normalized_header:
priorities.append(priority)
return min(priorities) if priorities else 2**31 - 1
def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
"""收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。"""
headers: dict[str, str | None] = {}
@@ -202,6 +202,10 @@ def _mapping_value(
value = order_values.get('__export_sequence')
else:
value = key
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
# 尤其金额字段不得由数量/单价等相邻字段隐式推导或伪装为已提供。
if kind == 'order_field' and value is None:
return None
return _format_value(value, mapping['formatter'])
@@ -1,7 +1,7 @@
"""
services/shipping_notice/export_archive.py
用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
"""
@@ -18,36 +18,22 @@ from zipfile import ZIP_DEFLATED, ZipFile
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.query_service import (
get_batch_for_user,
get_task_for_user,
list_sorted_batch_tasks,
resolve_task_export_download,
)
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
MAX_ARCHIVE_TASKS = 100
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]:
"""按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。"""
normalized_batch = str(batch_no or '').strip()
def _select_tasks(*, user_id: int, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]:
"""按显式任务号选择当前用户任务,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
if bool(normalized_batch) == bool(normalized_tasks):
raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
if normalized_batch:
batch = get_batch_for_user(normalized_batch, user_id)
if batch is None:
raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks = list_sorted_batch_tasks(batch)
archive_key = normalized_batch
else:
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None:
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks.append(task)
archive_key = 'selected'
if not normalized_tasks:
raise ValidationError('task_nos is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None:
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks.append(task)
if not tasks:
raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY')
if len(tasks) > MAX_ARCHIVE_TASKS:
@@ -55,7 +41,7 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once',
code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS},
)
return tasks, archive_key
return tasks, 'selected'
def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]:
@@ -91,16 +77,14 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str:
return candidate
def build_export_archive(
*, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None,
) -> tuple[BinaryIO, str, dict]:
def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos)
tasks, archive_key = _select_tasks(user_id=user_id, task_nos=task_nos)
artifacts = _ready_artifacts(tasks)
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
@@ -129,7 +113,7 @@ def build_export_archive(
included += 1
entries.append(entry)
manifest = {
'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []},
'archive_version': 1, 'selection': {'task_nos': task_nos},
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries,
}
@@ -22,6 +22,7 @@ from app.services.shipping_notice.generic_order_parser import (
parse_generic_orders,
)
from app.services.shipping_notice.order_extraction_route_contract import GENERIC_GATE_POLICY_VERSION
from app.services.shipping_notice.generic_parse_plan import validate_generic_parse_plan
@dataclass(frozen=True)
@@ -49,6 +50,9 @@ def evaluate_generic_extraction_gate(
schema: dict[str, Any],
intake: dict[str, Any],
unit: Any,
parse_plan: dict[str, Any] | None = None,
layout_snapshot: dict[str, Any] | None = None,
require_parse_plan: bool = False,
) -> GenericGateResult:
"""
执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。
@@ -68,13 +72,28 @@ def evaluate_generic_extraction_gate(
Returns:
GenericGateResult;passed 为 True 时 parse_result.orders 非空。
"""
completeness = build_generic_completeness_report(candidates)
# 生产工作流必须传入冻结 Plan;保留无 Plan 参数的纯函数调用,供已有诊断和
# 单元测试直接评估候选完整性,不把它接入自动建单路径。
plan_validation = None
effective_candidates = candidates
if parse_plan is not None or require_parse_plan:
plan_validation = validate_generic_parse_plan(
plan=parse_plan,
schema_checksum=str(schema.get('checksum') or ''),
layout_snapshot=layout_snapshot or {},
runtime_candidates=candidates,
)
effective_candidates = plan_validation.candidates
completeness = build_generic_completeness_report(effective_candidates)
gate_codes: list[str] = []
stable_codes: list[str] = []
if plan_validation is not None and not plan_validation.passed:
gate_codes.extend(plan_validation.reason_codes)
gate_codes.extend(_completeness_gate_codes(completeness))
parse_result = parse_generic_orders(
candidates=candidates,
candidates=effective_candidates,
definition=definition,
schema=schema,
intake=intake,
@@ -83,7 +102,7 @@ def evaluate_generic_extraction_gate(
if parse_result.reason_code:
stable_codes.append(parse_result.reason_code)
customer_values = collect_customer_field_values(candidates, definition=definition)
customer_values = collect_customer_field_values(effective_candidates, definition=definition)
if len(customer_values) > 1:
gate_codes.append('multiple_customer')
stable_codes.append('generic_gate_blocked')
@@ -0,0 +1,137 @@
"""
services/shipping_notice/generic_parse_plan.py
用途:将自动标注的 layout_schema_candidates 编译为 Run 冻结的通用解析计划。
依赖:冻结 Schema、Layout candidate 与 schema_mapping 的 cell 级证据。
逻辑:候选映射只可作为 Plan 输入;生产通用解析必须先校验 Plan 的 Schema、Layout、
候选和字段证据身份,不能直接把运行时候选当作业务事实。
"""
from __future__ import annotations
import hashlib
import json
from copy import deepcopy
from dataclasses import dataclass
from typing import Any
GENERIC_PARSE_PLAN_VERSION = 'generic_parse_plan.v1'
def _checksum(payload: Any) -> str:
"""生成稳定 JSON checksum;Plan 身份不得依赖字典插入顺序。"""
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(encoded.encode('utf-8')).hexdigest()
def layout_checksum(layout_snapshot: dict[str, Any]) -> str | None:
"""提取结构 Layout 身份;按需坐标补全不应改变已冻结的版面身份。"""
candidate = layout_snapshot.get('layout_candidate') if isinstance(layout_snapshot, dict) else None
return _checksum(candidate) if isinstance(candidate, dict) else None
def _field_evidence_errors(candidates: list[dict[str, Any]]) -> list[str]:
"""校验每个将进入订单的字段都能回溯到冻结 Layout cell 证据。"""
errors: list[str] = []
for table_index, table in enumerate(candidates):
if not isinstance(table, dict):
errors.append(f'table:{table_index}:invalid')
continue
for row in table.get('rows') or []:
if not isinstance(row, dict) or str(row.get('role') or '') != 'data':
continue
for field in row.get('fields') or []:
if not isinstance(field, dict) or field.get('value') in (None, ''):
continue
if not field.get('field_id'):
errors.append(f'table:{table_index}:field_id_missing')
if not field.get('evidence_ref') or not field.get('cell_id'):
errors.append(f'table:{table_index}:field_evidence_missing')
return sorted(set(errors))
def compile_generic_parse_plan(
*,
candidates: list[dict[str, Any]],
schema_checksum: str,
layout_snapshot: dict[str, Any],
) -> dict[str, Any]:
"""
将自动标注候选编译为可冻结 Parse Plan。
自动标注本身不具有生产资格。该函数只记录候选的输入身份和字段证据,后续仍由
generic_order_gate 检查表/行完整性、必填字段和业务冲突。
"""
# Plan 冻结前仍在同一 Worker 内构建订单;不得借深拷贝把 Decimal/date 等
# 业务值提前变成字符串,JSON 落库阶段由 Run 的统一冻结器处理。
copied = deepcopy(candidates if isinstance(candidates, list) else [])
source_statuses = [
str(item.get('mapping_status') or 'candidate')
for item in copied if isinstance(item, dict)
]
errors = _field_evidence_errors(copied)
if not str(schema_checksum or '').strip():
errors.append('schema_checksum_missing')
resolved_layout_checksum = layout_checksum(layout_snapshot)
if not resolved_layout_checksum:
errors.append('layout_checksum_missing')
if any(status not in {'accepted', 'candidate'} for status in source_statuses):
errors.append('mapping_status_unqualified')
payload = {
'version': GENERIC_PARSE_PLAN_VERSION,
'schema_checksum': str(schema_checksum or ''),
'layout_checksum': resolved_layout_checksum,
'candidates': copied,
'candidate_checksum': _checksum(copied),
'mapping_decisions': [{
'page_no': item.get('page_no'), 'table_id': item.get('table_id'),
'source_mapping_status': str(item.get('mapping_status') or 'candidate'),
'decision': 'auto_qualified' if str(item.get('mapping_status') or 'candidate') in {'accepted', 'candidate'} else 'rejected',
} for item in copied if isinstance(item, dict)],
'evidence_errors': sorted(set(errors)),
}
payload['status'] = 'qualified' if not payload['evidence_errors'] else 'rejected'
payload['checksum'] = _checksum(payload)
return payload
@dataclass(frozen=True)
class GenericParsePlanValidation:
"""生产 Gate 使用的 Parse Plan 校验结论。"""
passed: bool
reason_codes: list[str]
candidates: list[dict[str, Any]]
def validate_generic_parse_plan(
*,
plan: Any,
schema_checksum: str,
layout_snapshot: dict[str, Any],
runtime_candidates: list[dict[str, Any]] | None = None,
) -> GenericParsePlanValidation:
"""验证冻结 Plan 未被 Schema、Layout 或候选映射漂移污染。"""
if not isinstance(plan, dict):
return GenericParsePlanValidation(False, ['generic_parse_plan_missing'], [])
candidates = plan.get('candidates') if isinstance(plan.get('candidates'), list) else []
reasons: list[str] = []
if str(plan.get('version') or '') != GENERIC_PARSE_PLAN_VERSION:
reasons.append('generic_parse_plan_version_invalid')
payload = {key: value for key, value in plan.items() if key != 'checksum'}
if str(plan.get('checksum') or '') != _checksum(payload):
reasons.append('generic_parse_plan_checksum_invalid')
if str(plan.get('status') or '') != 'qualified':
reasons.append('generic_parse_plan_unqualified')
if str(plan.get('schema_checksum') or '') != str(schema_checksum or ''):
reasons.append('generic_parse_plan_schema_changed')
if str(plan.get('layout_checksum') or '') != str(layout_checksum(layout_snapshot) or ''):
reasons.append('generic_parse_plan_layout_changed')
if str(plan.get('candidate_checksum') or '') != _checksum(candidates):
reasons.append('generic_parse_plan_candidate_changed')
if runtime_candidates is not None and _checksum(runtime_candidates) != str(plan.get('candidate_checksum') or ''):
reasons.append('generic_parse_plan_runtime_candidate_changed')
if plan.get('evidence_errors'):
reasons.append('generic_parse_plan_evidence_missing')
return GenericParsePlanValidation(not reasons, sorted(set(reasons)), candidates)
@@ -172,6 +172,7 @@ def serialize_intake(
*,
asset: FileAsset | None = None,
include_parse_texts: bool = False,
include_candidate_details: bool = True,
) -> dict[str, Any]:
"""
对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。
@@ -179,6 +180,8 @@ def serialize_intake(
Args:
include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口),
并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。
include_candidate_details: False 时仅返回恢复输入状态所需的 Candidate 字段,
避免活跃列表传输 evidence / field_adjudication 等重型审核数据。
"""
from app.services.shipping_notice.document_candidate_persist import (
list_intake_candidates,
@@ -198,7 +201,10 @@ def serialize_intake(
}
parse_summary = structured if include_parse_texts else _lean_parse_summary(structured)
documents = list_intake_documents(int(intake.id), include_text=include_parse_texts)
candidates = list_intake_candidates(int(intake.id))
candidates = list_intake_candidates(
int(intake.id),
include_details=include_candidate_details,
)
layout_summary = _serialize_intake_layout_summary(int(intake.id))
payload: dict[str, Any] = {
'intake_no': intake.intake_no,
@@ -571,7 +577,14 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str |
if conv:
query = query.filter(ShippingOrderIntake.conversation_id == conv)
rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all()
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
return [
serialize_intake(
intake,
asset=asset,
include_candidate_details=False,
)
for intake, asset in rows
]
def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]:
@@ -588,7 +601,14 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
)
.all()
)
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
return [
serialize_intake(
intake,
asset=asset,
include_candidate_details=False,
)
for intake, asset in rows
]
def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
@@ -1,7 +1,7 @@
"""
services/shipping_notice/inventory_file_store.py
用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
"""
@@ -30,8 +30,6 @@ from app.services.shipping_notice.inventory_source_gate import (
task_inventory_identity,
)
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
def _can_relink_inventory(task: ShippingNotice) -> bool:
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
@@ -228,13 +226,13 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) ->
)
def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
"""
保存库存 Excel 并创建批次级库存快照。
保存库存 Excel 并创建任务级库存快照。
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
【AI 触发时机】:用户为当前发货任务上传库存快照时调用。
核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析;
快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。
快照须携带任务正式库存源身份,只绑定当前任务。
"""
if not is_inventory_source_stable(task):
raise AppError(
@@ -360,7 +358,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
)
raise AppError(
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定",
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定",
http_status=409,
)
created_links.append(link)
@@ -18,13 +18,10 @@ from app.services.shipping_notice.constants import (
CP_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_batch_inventory_upload,
)
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
from app.services.shipping_notice.query_service import (
get_task_by_ref,
resolve_task_from_payload,
serialize_batch_for_tool,
serialize_task_for_tool,
)
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
@@ -176,7 +173,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename),
)
db.session.flush()
inv_file = save_batch_inventory_upload(task, upload)
inv_file = save_task_inventory_upload(task, upload)
inventory_lines = [
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
]
@@ -220,7 +217,6 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
{
"inventory_file_no": inv_file.inventory_file_no,
"share_mode": inv_file.share_mode,
"batch_no": None,
},
)
return inventory_loaded_response(
@@ -1,297 +0,0 @@
"""
backend/app/services/shipping_notice/legacy_stp_job_admin_service.py
用途:Phase 5-1 —— 管理员历史 STP Job 面板的只读投影服务(928/929 运维面板专用)。
依赖:models.job.Job、JobType(若有)、ShippingOrderReviewCase。
逻辑:
1. list_admin_legacy_stp_jobs —— 按 domain=shipping_notice + job_type=shipping_stp_auto_create
+ status IN {failed,dead} 分页返回;支持筛选 case_no / q / error_code / created_from / created_to。
2. get_admin_legacy_stp_job —— 单条 Job 详情 + 关联 Review Case(若可通过 reference_key==case_no 回链)。
禁止事项(严格 fail-closed):
• 不允许写任何数据(禁 Job.status 修改,禁 db.session.commit/add/flush 等)。
• 不输出敏感字段(result_json 中若含 token/password 自动脱敏)。
• 所有接口仅 allow_admin,路由层 require_admin 再守门一道。
"""
from __future__ import annotations
import re
from datetime import datetime
from typing import Any
from sqlalchemy import and_, or_
from app import db
# 失败 / 死 Job 白名单:历史 928/929 仅针对 shipping_stp_auto_create
_LEGACY_DOMAIN = 'shipping_notice'
_LEGACY_JOB_TYPES: frozenset[str] = frozenset({
'shipping_stp_auto_create',
})
_LEGACY_STATUSES: frozenset[str] = frozenset({'failed', 'dead'})
# 脱敏正则(非常粗:防止 secret/password/token/key 等明文进入管理面板)
_SENSITIVE_KEY_RE = re.compile(
r'(password|passwd|secret|token|api[_-]?key|credential|authorization)',
flags=re.IGNORECASE,
)
def _mask_sensitive(obj: Any) -> Any:
"""递归递归脱敏 dict/list 中疑似密钥字段的值(fail-safe,不抛错)。"""
if isinstance(obj, dict):
out: dict[str, Any] = {}
for k, v in obj.items():
if isinstance(k, str) and _SENSITIVE_KEY_RE.search(k):
out[k] = '***MASKED***'
else:
out[k] = _mask_sensitive(v)
return out
if isinstance(obj, list):
return [_mask_sensitive(i) for i in obj]
if isinstance(obj, tuple):
return tuple(_mask_sensitive(i) for i in obj)
return obj
def _serialize_job_row(job) -> dict[str, Any]:
"""把 Job ORM 行 → 管理员摘要 JSON(只读投影)。"""
result_json = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
payload_json = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {}
blocking_reason = (
result_json.get('blocking_reason')
or result_json.get('reason_code')
or result_json.get('error_code')
or None
)
if isinstance(blocking_reason, dict):
blocking_reason = blocking_reason.get('code') if isinstance(blocking_reason.get('code'), str) else None
return {
'job_id': int(job.id),
'domain': str(job.domain or ''),
'job_type': str(job.job_type or ''),
'status': str(job.status or ''),
'business_ref': str(job.business_ref or ''),
'reference_key': str(getattr(job, 'reference_key', None) or ''), # 兼容旧 Job
'case_no': (
str(getattr(job, 'reference_key', None) or '') or
str(payload_json.get('case_no') or '') or None
),
'priority': int(job.priority or 0),
'attempts': int(job.attempts or 0),
'max_attempts': int(job.max_attempts or 0),
'message': str(job.message or '') or None,
'error_message': str(job.error_message or '') or None,
'error_code': str(result_json.get('error_code') or ''),
'blocking_reason': (str(blocking_reason) if blocking_reason else None),
'retryable': bool(result_json.get('retryable')) if result_json.get('retryable') is not None else None,
'next_action': result_json.get('next_action'),
'retry_of_job_id': (int(job.retry_of_job_id) if job.retry_of_job_id else None),
'created_by_id': (int(job.created_by_id) if job.created_by_id else None),
'result_json_masked': _mask_sensitive(result_json),
'payload_json_masked': _mask_sensitive(payload_json),
'created_at': str(job.created_at.isoformat()) if isinstance(job.created_at, datetime) else None,
'updated_at': str(job.updated_at.isoformat()) if isinstance(job.updated_at, datetime) else None,
'started_at': str(job.started_at.isoformat()) if isinstance(job.started_at, datetime) else None,
'finished_at': str(job.finished_at.isoformat()) if isinstance(job.finished_at, datetime) else None,
}
def _parse_iso_dt(value: str | None, *, field: str):
"""解析可选 ISO 日期时间;抛 ValidationError。"""
from app.core.errors import ValidationError
if value in (None, ''):
return None
try:
text = str(value).strip()
if text.endswith('Z'):
text = text[:-1] + '+00:00'
return datetime.fromisoformat(text)
except ValueError as exc:
raise ValidationError(f'{field} must be ISO datetime (YYYY-MM-DDTHH:MM:SS)') from exc
def list_admin_legacy_stp_jobs(
*,
page: int = 1,
page_size: int = 25,
status: str | None = None,
job_type: str | None = None,
q: str | None = None,
case_no: str | None = None,
error_code: str | None = None,
blocking_reason: str | None = None,
created_from: str | None = None,
created_to: str | None = None,
sort: str = '-created_at',
) -> dict[str, Any]:
"""
管理员只读列表:domain=shipping_notice + job_type=shipping_stp_auto_create + status IN {failed, dead}。
用于运维面板快速定位历史 928/929 这类失败死 Job。
"""
from app.core.errors import ValidationError
from app.models.job import Job
from app import db # type: ignore
if not isinstance(page, int) or page < 1:
raise ValidationError('page must be positive integer')
if not isinstance(page_size, int) or not 1 <= page_size <= 100:
raise ValidationError('page_size must be between 1 and 100')
if status and str(status) not in _LEGACY_STATUSES:
raise ValidationError(f'status must be one of: {sorted(_LEGACY_STATUSES)}')
if job_type and str(job_type) not in _LEGACY_JOB_TYPES:
raise ValidationError(f'job_type must be one of: {sorted(_LEGACY_JOB_TYPES)}')
created_from_dt = _parse_iso_dt(created_from, field='created_from')
created_to_dt = _parse_iso_dt(created_to, field='created_to')
# 只拿失败/死 STP Job
where = [
Job.domain == _LEGACY_DOMAIN,
Job.job_type.in_(list(_LEGACY_JOB_TYPES)),
Job.status.in_(list(_LEGACY_STATUSES)),
]
if status:
where.append(Job.status == str(status))
if job_type:
where.append(Job.job_type == str(job_type))
if case_no:
case_no_s = str(case_no).strip()
where.append(or_(
getattr(Job, 'reference_key', None) == case_no_s
if hasattr(Job, 'reference_key')
else False,
# 兼容旧模型:从 payload_json->case_no 查(JSON 跨库差异大,仅包含匹配)
Job.payload_json.contains({'case_no': case_no_s}),
))
if error_code:
where.append(Job.result_json.contains({'error_code': str(error_code).strip()}))
if blocking_reason:
br = str(blocking_reason).strip()
where.append(or_(
Job.result_json.contains({'blocking_reason': br}),
Job.result_json.contains({'reason_code': br}),
))
if created_from_dt is not None:
where.append(Job.created_at >= created_from_dt)
if created_to_dt is not None:
where.append(Job.created_at <= created_to_dt)
if q and str(q).strip():
qs = f'%{str(q).strip()}%'
where.append(or_(
Job.business_ref.ilike(qs),
Job.message.ilike(qs),
Job.error_message.ilike(qs),
))
# 排序
sort_exprs = []
for raw in str(sort or '-created_at').split(','):
s = raw.strip()
if not s:
continue
descending = s.startswith('-')
key = s[1:] if descending else s
if key == 'created_at':
expr = Job.created_at.desc() if descending else Job.created_at.asc()
elif key == 'updated_at':
expr = Job.updated_at.desc() if descending else Job.updated_at.asc()
elif key == 'id':
expr = Job.id.desc() if descending else Job.id.asc()
elif key == 'attempts':
expr = Job.attempts.desc() if descending else Job.attempts.asc()
else:
continue
sort_exprs.append(expr)
if not sort_exprs:
sort_exprs = [Job.created_at.desc()]
stmt = db.select(Job).where(and_(*where)).order_by(*sort_exprs)
total = len(db.session.scalars(db.select(Job.id).where(and_(*where))).all())
items = db.session.scalars(
stmt.offset((int(page) - 1) * int(page_size)).limit(int(page_size)),
).all()
return {
'items': [_serialize_job_row(j) for j in items],
'pagination': {
'page': int(page),
'page_size': int(page_size),
'total': int(total),
'total_pages': ((int(total) + int(page_size) - 1) // int(page_size)) if total > 0 else 0,
},
'filters': {
'domain': _LEGACY_DOMAIN,
'job_types': sorted(_LEGACY_JOB_TYPES),
'statuses': sorted(_LEGACY_STATUSES),
},
}
def get_admin_legacy_stp_job(job_id: int) -> dict[str, Any]:
"""
管理员单条历史 STP Job 详情:返回 Job 投影 + 回链 Review Case(若 reference_key==case_no 存在)。
仅允许失败/死 Job:若 Job 是 queued/running → 抛 ValidationError(避免管理员误对活跃 Job 做 replay)。
"""
from app.core.errors import NotFoundError, ValidationError
from app.models.job import Job
from app.models.shipping.shipping_order_review_case import ShippingOrderReviewCase
job = db.session.get(Job, int(job_id))
if job is None:
raise NotFoundError(f'legacy job not found: {job_id}', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
if str(job.domain or '') != _LEGACY_DOMAIN:
raise ValidationError(f'legacy job must be domain={_LEGACY_DOMAIN}')
if str(job.job_type or '') not in _LEGACY_JOB_TYPES:
raise ValidationError(f'legacy job must be job_type in {sorted(_LEGACY_JOB_TYPES)}')
if str(job.status or '') not in _LEGACY_STATUSES:
raise ValidationError(
f'legacy job must be status in {sorted(_LEGACY_STATUSES)} (current={job.status})',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
)
job_row = _serialize_job_row(job)
# 回链 Review Case(只读:若能通过 reference_key==case_no 找得到)
case_no = (
str(getattr(job, 'reference_key', None) or '')
or str((job.payload_json or {}).get('case_no') or '')
or None
)
case_row: dict[str, Any] | None = None
if case_no:
case_obj = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no).strip())
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if case_obj is not None:
case_row = {
'case_id': int(case_obj.id),
'case_no': str(case_obj.case_no or ''),
'status': str(case_obj.status or ''),
'candidate_id': int(case_obj.candidate_id) if case_obj.candidate_id else None,
'confirmed_task_id': int(case_obj.confirmed_task_id) if case_obj.confirmed_task_id else None,
'document_id': int(case_obj.document_id) if case_obj.document_id else None,
'owner_user_id': int(case_obj.owner_user_id) if case_obj.owner_user_id else None,
'created_at': str(case_obj.created_at.isoformat()) if getattr(case_obj, 'created_at', None) else None,
'updated_at': str(case_obj.updated_at.isoformat()) if getattr(case_obj, 'updated_at', None) else None,
}
return {
'job': job_row,
'case': case_row,
'replay_plan': {
'supported': True,
'recommended_user_action': (
'force_create'
if case_row and str(case_row.get('status') or '') in {'draft', 'ready', 'unreviewed'}
else 'create_revision'
),
'needs_replay_mode': bool(case_row and job_row.get('case_no') != case_row.get('case_no')),
'reconcile_and_progress_endpoint': (
f'/workspace/shipping-notice/order-review-cases/{case_no}/reconcile-and-progress'
if case_no else None
),
},
}
@@ -0,0 +1,296 @@
"""
services/shipping_notice/legacy_supplement_conflict_reassessment_service.py
用途:将历史邮件正文补充冲突升级为可展示、可追溯的统一 Finding,并重算 Candidate 资格。
依赖:ShippingOrderCandidate/Run、candidate_qualification_service、fulfillment_audit。
逻辑:历史 `{field, reason}` 没有双方值或证据,不能猜测为已解决;本服务仅将其转为
`supplement_conflict_evidence_insufficient`,保留 blocking 门禁并给出重新识别恢复入口。
已含 conflict_key 的新 Finding 不改写;真实值比较仍由冻结输入的新解析链负责。
"""
from __future__ import annotations
from typing import Any
from app.extensions import db
from app.models import (
ShippingOrderCandidate,
ShippingOrderProcessingPlan,
ShippingOrderProcessingRun,
ShippingOrderProcessingUnit,
)
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
_LEGACY_REASON = 'supplement_field_conflict'
_EVIDENCE_GAP_REASON = 'supplement_conflict_evidence_insufficient'
def _legacy_finding_key(item: dict[str, Any]) -> str:
"""为无法复原证据的旧 Finding 生成稳定键,避免继续以无键记录阻断。"""
field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field'
try:
line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
return f'{line_index}:{field}'
def is_legacy_supplement_conflict(item: Any) -> bool:
"""判断记录是否是没有稳定裁决身份与双方证据的历史正文补充冲突。"""
return (
isinstance(item, dict)
and str(item.get('reason') or '').strip() == _LEGACY_REASON
and not str(item.get('conflict_key') or '').strip()
)
def upgrade_legacy_supplement_conflicts(conflicts: Any) -> tuple[list[Any], int]:
"""
将旧简略冲突升级为统一证据缺失 Finding。
核心逻辑:旧记录仅有字段与原因,缺失 PDF/EML 原值、document_id、evidence_ref,
无法安全裁决或判定为格式等价;因此保持 fail-closed,但使 Case 显示明确恢复动作。
Returns:
(升级后的冲突列表, 本次升级数量)。
"""
source = list(conflicts or []) if isinstance(conflicts, list) else []
upgraded: list[Any] = []
changed = 0
seen_keys: set[str] = set()
for item in source:
if not is_legacy_supplement_conflict(item):
upgraded.append(item)
if isinstance(item, dict):
key = str(item.get('conflict_key') or '').strip()
if key:
seen_keys.add(key)
continue
key = _legacy_finding_key(item)
if key in seen_keys:
changed += 1
continue
seen_keys.add(key)
field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field'
try:
line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
upgraded.append({
'conflict_key': key,
'severity': 'blocking',
'reason': _EVIDENCE_GAP_REASON,
'resolution_status': 'unresolved',
'field': field,
'scope': str(item.get('scope') or 'unscoped'),
'line_index': line_index if line_index >= 0 else None,
'values': [],
'sources': [],
'rule_version': 'legacy-supplement-conflict.v1',
'legacy_reason': _LEGACY_REASON,
'recovery_action': 'reparse_current_pdf',
})
changed += 1
return upgraded, changed
def _without_legacy_supplement_conflicts(conflicts: Any) -> list[Any]:
"""去除待重建的旧 Finding,保留其他解析/业务门禁。"""
return [
item for item in (conflicts or [])
if not is_legacy_supplement_conflict(item)
] if isinstance(conflicts, list) else []
def _supplement_findings(conflicts: Any) -> list[dict[str, Any]]:
"""从重算订单结果读取当前正文补充 Finding,不借用其他门禁事实。"""
return [
item for item in (conflicts or [])
if isinstance(item, dict)
and str(item.get('reason') or '').strip() == _LEGACY_REASON
] if isinstance(conflicts, list) else []
def reassess_legacy_supplement_conflicts_from_frozen_order(
*,
candidate_conflicts: Any,
frozen_order: Any,
supplements_by_intake: Any,
schema_definition: Any,
) -> tuple[list[Any], str, int]:
"""
使用冻结订单和邮件补充事实按当前合并规则重算旧冲突。
Returns:
(新冲突, rebuilt|evidence_insufficient|not_applicable, 处理的旧记录数)。
"""
legacy_count = sum(1 for item in (candidate_conflicts or []) if is_legacy_supplement_conflict(item)) \
if isinstance(candidate_conflicts, list) else 0
if not legacy_count:
return list(candidate_conflicts or []) if isinstance(candidate_conflicts, list) else [], 'not_applicable', 0
if not (
isinstance(frozen_order, dict)
and isinstance(supplements_by_intake, dict)
and isinstance(schema_definition, dict)
and isinstance(schema_definition.get('fields'), list)
):
upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts)
return upgraded, 'evidence_insufficient', legacy_count
replay_order = dict(frozen_order)
replay_order['conflicts'] = _without_legacy_supplement_conflicts(replay_order.get('conflicts'))
try:
rebuilt_order = merge_email_supplements(
orders=[replay_order],
supplements_by_intake=supplements_by_intake,
schema_definition=schema_definition,
)[0]
except (TypeError, ValueError):
upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts)
return upgraded, 'evidence_insufficient', legacy_count
# Candidate 的非补充门禁由其自身持有;只用重算结果替换旧正文补充项。
preserved = _without_legacy_supplement_conflicts(candidate_conflicts)
rebuilt = _supplement_findings(rebuilt_order.get('conflicts'))
return [*preserved, *rebuilt], 'rebuilt', legacy_count
def _frozen_reassessment_inputs(
*, candidate: ShippingOrderCandidate, run: ShippingOrderProcessingRun | None,
) -> tuple[dict[str, Any] | None, dict[int, dict[str, Any]] | None, dict[str, Any] | None]:
"""按 Candidate 所属 Unit 定位冻结订单、邮件补充与 Schema;歧义时拒绝猜测。"""
if run is None:
return None, None, None
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else None
supplements = {
int(intake.get('intake_id') or 0): supplement
for intake in snapshot.get('intakes') or [] if isinstance(intake, dict)
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
if int(intake.get('intake_id') or 0) > 0
}
units = (
ShippingOrderProcessingUnit.query
.join(ShippingOrderProcessingPlan, ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id)
.filter(
ShippingOrderProcessingPlan.run_id == int(run.id),
ShippingOrderProcessingUnit.document_id == int(candidate.primary_document_id),
)
.order_by(ShippingOrderProcessingUnit.id.asc())
.all()
)
if len(units) != 1:
return None, supplements, definition
orders = (units[0].result_json or {}).get('orders') if isinstance(units[0].result_json, dict) else None
if not isinstance(orders, list):
return None, supplements, definition
index = candidate.source_order_index
if isinstance(index, int) and 0 <= index < len(orders) and isinstance(orders[index], dict):
return dict(orders[index]), supplements, definition
exact = [
item for item in orders
if isinstance(item, dict)
and int(item.get('primary_document_id') or 0) == int(candidate.primary_document_id)
]
return (dict(exact[0]) if len(exact) == 1 else None), supplements, definition
def reassess_legacy_supplement_conflicts(
*,
actor_id: int,
request_id: str | None = None,
candidate_no: str | None = None,
run_no: str | None = None,
include_all: bool = False,
) -> dict[str, Any]:
"""
对指定范围的旧正文补充冲突执行一次可审计重评估。
AI 触发时机:仅管理员确认历史数据修复时调用;普通用户保存草稿或读取 Case 不调用。
范围必须指定 Candidate、Run,或显式 include_all,避免误触发全量写操作。
"""
normalized_candidate_no = str(candidate_no or '').strip().upper() or None
normalized_run_no = str(run_no or '').strip().upper() or None
if not (normalized_candidate_no or normalized_run_no or include_all):
raise ValueError('candidate_no, run_no, or include_all is required')
query = ShippingOrderCandidate.query.filter(ShippingOrderCandidate.is_current_version.is_(True))
if normalized_candidate_no:
query = query.filter(ShippingOrderCandidate.candidate_no == normalized_candidate_no)
if normalized_run_no:
query = query.join(
ShippingOrderProcessingRun,
ShippingOrderProcessingRun.id == ShippingOrderCandidate.order_extraction_run_id,
).filter(ShippingOrderProcessingRun.run_no == normalized_run_no)
report = {
'scanned_count': 0,
'legacy_conflict_candidate_count': 0,
'upgraded_finding_count': 0,
'qualification_recalculated_count': 0,
'candidate_nos': [],
'scope': {
'candidate_no': normalized_candidate_no,
'run_no': normalized_run_no,
'include_all': bool(include_all),
},
}
for candidate in query.with_for_update().all():
report['scanned_count'] += 1
legacy_count = sum(
1 for item in (candidate.conflicts_json or []) if is_legacy_supplement_conflict(item)
) if isinstance(candidate.conflicts_json, list) else 0
if not legacy_count:
continue
run = (
db.session.get(ShippingOrderProcessingRun, int(candidate.order_extraction_run_id))
if candidate.order_extraction_run_id else None
)
frozen_order, supplements, definition = _frozen_reassessment_inputs(candidate=candidate, run=run)
after_conflicts, reassessment_status, changed = reassess_legacy_supplement_conflicts_from_frozen_order(
candidate_conflicts=candidate.conflicts_json,
frozen_order=frozen_order,
supplements_by_intake=supplements,
schema_definition=definition,
)
before = {'legacy_supplement_conflict_count': legacy_count}
candidate.conflicts_json = after_conflicts
report['legacy_conflict_candidate_count'] += 1
if reassessment_status == 'evidence_insufficient':
report['upgraded_finding_count'] += changed
else:
report.setdefault('rebuilt_candidate_count', 0)
report['rebuilt_candidate_count'] += 1
report['candidate_nos'].append(str(candidate.candidate_no))
recalculate_candidate_qualification(
candidate=candidate,
run=run,
evaluated_by_id=actor_id,
request_id=request_id,
)
report['qualification_recalculated_count'] += 1
record_fulfillment_audit(
event_type='legacy_supplement_conflict_reassessed',
aggregate_type='shipping_notice_candidate',
aggregate_id=str(candidate.candidate_no),
action='reassess_legacy_supplement_conflict',
actor_type='admin',
actor_id=actor_id,
run_no=str(run.run_no) if run is not None else None,
reason_code=_EVIDENCE_GAP_REASON,
before=before,
after={
'reassessment_status': reassessment_status,
'replaced_legacy_finding_count': changed,
'remaining_supplement_finding_count': len(_supplement_findings(after_conflicts)),
'recovery_action': 'reparse_current_pdf' if reassessment_status == 'evidence_insufficient' else None,
},
metadata={'request_id': request_id, 'migration_version': 'legacy-supplement-conflict.v1'},
source='legacy_supplement_conflict_reassessment',
)
report['candidate_nos'].sort()
return report
@@ -2,8 +2,8 @@
services/shipping_notice/lifecycle_projection.py
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
"""
@@ -48,24 +48,29 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
'manual_upload_handoff': 'freight_upload',
}
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
('order_review', {
'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required',
'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review',
}),
('fulfillment_prep', {
'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation',
'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready',
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
'excel_generate', 'excel_generated',
}),
('freight_upload', {
'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'upload_complete', 'completed',
}),
)
# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在
# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。
LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'upload_received': 'intake_parse',
'email_parsing': 'intake_parse',
'document_parsing': 'intake_parse',
'email_adjudicating': 'intake_parse',
'candidate_creating': 'intake_parse',
'waiting_review': 'order_review',
'customer_resolving': 'order_review',
'duplicate_checking': 'order_review',
'inventory_source_resolving': 'order_review',
'order_creating': 'fulfillment_prep',
'inventory_fetching': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep',
'inventory_matching': 'fulfillment_prep',
'inventory_sufficiency': 'fulfillment_prep',
'excel_generating': 'fulfillment_prep',
'freight_uploading': 'freight_upload',
'manual_upload_handoff': 'freight_upload',
'completed': 'upload_complete',
}
def lifecycle_entries(
*,
@@ -104,14 +109,16 @@ def project_lifecycle(
*,
current_gate: dict[str, Any] | None,
blocking_reason: dict[str, Any] | None,
legacy_stage: str | None,
has_candidate_context: bool,
has_intake_parse_context: bool = False,
verified_upload_success: bool = False,
processing_stage: str | None = None,
) -> dict[str, Any]:
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
"""按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。
``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能
授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算
阶段或放开按钮。
"""
gate = current_gate if isinstance(current_gate, dict) else {}
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
@@ -123,6 +130,11 @@ def project_lifecycle(
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate'
elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[
str(processing_stage or '').strip().lower()
]
authority = 'processing_stage'
else:
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
@@ -131,12 +143,8 @@ def project_lifecycle(
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate]
authority = 'blocking_reason'
else:
normalized_legacy = str(legacy_stage or '').strip().lower()
lifecycle_stage = next(
(code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases),
normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None,
)
authority = 'legacy_fallback' if lifecycle_stage else 'unclassified'
lifecycle_stage = None
authority = 'unclassified'
return {
'lifecycle_stage': lifecycle_stage,
'lifecycle_entries': lifecycle_entries(
@@ -1,9 +1,9 @@
"""
backend/app/services/shipping_notice/open_existing_reservation_backfill.py
用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到旧任务(兼容入口)。
用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到既有任务。
依赖:task_candidate_reconciliation、tool_common。
逻辑:batch_from_intakes 仍调用本模块;内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。
逻辑:内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。
"""
from __future__ import annotations
@@ -1,353 +0,0 @@
"""
services/shipping_notice/order_auto_freeze_execution.py
用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。
依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。
逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run,
建单与冻结均只处理本轮 eligible 的 accepted + selected 候选集合,禁止扩大到 Run 内其它已消费候选;
单任务冻结使用 savepoint,失败回滚该任务半成品,禁止外层误提交已冻结状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingOrderCandidate,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderProcessingRun,
ShippingNotice,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
def maybe_execute_run_auto_freeze(
*,
run: ShippingOrderProcessingRun,
submission_result: dict[str, Any],
) -> dict[str, Any]:
"""在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。"""
result = dict(submission_result or {})
policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {}
if not bool(policy.get('enabled')):
return result
# [STEP 1] 冻结候选集合在建单前冻结;后续冻结不得重新扩大范围。
candidate_nos = _eligible_candidate_nos(run)
create_result: dict[str, Any] | None = None
if candidate_nos:
create_result = create_shipping_batch_from_candidates(
user_id=int(run.user_id),
conversation_id=run.conversation_id,
intake_nos=_snapshot_intake_nos(run),
candidate_nos=candidate_nos,
create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}",
)
frozen_task_nos, blocked_tasks = _freeze_created_tasks(
run=run,
policy=policy,
candidate_nos=candidate_nos,
)
refreshed = _refresh_submission_result(
run=run,
previous_result=result,
create_result=create_result,
)
refreshed['auto_freeze'] = {
'enabled': True,
'frozen_task_nos': frozen_task_nos,
'blocked_tasks': blocked_tasks,
'eligible_candidate_nos': list(candidate_nos),
}
return refreshed
def _eligible_candidate_nos(run: ShippingOrderProcessingRun) -> list[str]:
"""只返回当前 Run 中可以自动建单的 accepted + selected 候选。"""
rows = (
ShippingOrderCandidate.query
.filter_by(
order_extraction_run_id=int(run.id),
is_current_version=True,
candidate_status='accepted',
selected=True,
)
.filter(ShippingOrderCandidate.consumed_task_id.is_(None))
.order_by(ShippingOrderCandidate.id.asc())
.all()
)
return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()]
def _snapshot_intake_nos(run: ShippingOrderProcessingRun) -> list[str]:
"""从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
return [
str(item.get('intake_no') or '').strip().upper()
for item in intakes
if isinstance(item, dict) and str(item.get('intake_no') or '').strip()
]
def _freeze_created_tasks(
*,
run: ShippingOrderProcessingRun,
policy: dict[str, Any],
candidate_nos: list[str],
) -> tuple[list[str], list[dict[str, Any]]]:
"""
冻结本轮 eligible 且已消费的任务。
核心逻辑:候选集合必须与建单前 `_eligible_candidate_nos` 完全一致;
禁止扫描 Run 下全部 consumed 候选(避免误冻人工/其它路径任务)。
"""
eligible = {
str(item).strip()
for item in (candidate_nos or [])
if str(item).strip()
}
if not eligible:
return [], []
candidates = (
ShippingOrderCandidate.query
.filter_by(
order_extraction_run_id=int(run.id),
is_current_version=True,
candidate_status='accepted',
selected=True,
)
.filter(ShippingOrderCandidate.consumed_task_id.isnot(None))
.filter(ShippingOrderCandidate.candidate_no.in_(tuple(eligible)))
.order_by(ShippingOrderCandidate.id.asc())
.all()
)
frozen_task_nos: list[str] = []
blocked_tasks: list[dict[str, Any]] = []
for candidate in candidates:
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
continue
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id or 0))
if task is None:
continue
# [STEP] 单任务 savepoint:冻结失败必须回滚本任务已 flush 的快照/指针/客户继承,
# 禁止外层事务提交“返回阻断但库内已冻结”的半成品。
try:
with db.session.begin_nested():
_inherit_confirmed_ordering_customer(run=run, task=task, policy=policy)
snapshot = freeze_order_snapshot(
task,
actor_id=None,
expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='auto',
auto_freeze_policy=policy,
)
# [STEP] 与冻结同 savepoint:进度事件失败则回滚本任务冻结半成品。
from app.services.shipping_notice.order_extraction_progress import record_run_progress
record_run_progress(
run=run,
event_code='order_auto_frozen',
summary={
'task_no': str(task.task_no or ''),
'candidate_no': str(candidate.candidate_no or ''),
'snapshot_id': int(getattr(snapshot, 'id', 0) or 0) or None,
'freeze_source': str((policy or {}).get('freeze_source') or '') or None,
},
commit=False,
)
frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}"))
except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言
blocked_tasks.append({
'candidate_no': str(candidate.candidate_no or ''),
'task_no': str(task.task_no or ''),
'code': str(getattr(exc, 'code', '') or ''),
'message': str(exc),
'details': getattr(exc, 'details', None),
})
return frozen_task_nos, blocked_tasks
def _inherit_confirmed_ordering_customer(
*,
run: ShippingOrderProcessingRun,
task: ShippingNotice,
policy: dict[str, Any],
) -> None:
"""把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。"""
confirmed_ids = sorted({
int(item)
for item in (policy.get('confirmed_customer_ids') or [])
if str(item).strip().isdigit()
})
if len(confirmed_ids) != 1 or not task.current_order_extraction_id:
return
extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id))
if extraction is None:
return
target = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(extraction.id),
role='bill_to',
).one_or_none()
if (
target is not None
and target.status == 'confirmed'
and int(target.customer_id or 0) == confirmed_ids[0]
and bool(target.customer_short_code_snapshot)
and bool(target.identity_fingerprint)
and bool(target.identity_rule_version)
):
return
if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}:
return
source = (
ShippingOrderCustomerMatch.query
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id)
.filter(
ShippingOrderExtraction.run_id == int(run.id),
ShippingOrderCustomerMatch.role == 'bill_to',
ShippingOrderCustomerMatch.status == 'confirmed',
ShippingOrderCustomerMatch.customer_id == confirmed_ids[0],
)
.order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc())
.first()
)
if source is None:
return
if target is None:
target = ShippingOrderCustomerMatch(
extraction_id=int(extraction.id),
role='bill_to',
identity_components_json={},
candidates_json=[],
)
db.session.add(target)
target.raw_name = source.raw_name
target.normalized_name = source.normalized_name
target.source_system = source.source_system
target.external_code = source.external_code
target.identity_fingerprint = source.identity_fingerprint
target.identity_rule_version = source.identity_rule_version
target.identity_components_json = dict(source.identity_components_json or {})
target.status = 'confirmed'
target.customer_id = source.customer_id
target.site_id = source.site_id
target.customer_name_snapshot = source.customer_name_snapshot
target.customer_short_code_snapshot = source.customer_short_code_snapshot
target.candidates_json = list(source.candidates_json or [])
target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited'
target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited'
target.confirmed_by_id = source.confirmed_by_id
target.confirmed_at = source.confirmed_at or datetime.utcnow()
target.updated_at = datetime.utcnow()
db.session.flush()
def _refresh_submission_result(
*,
run: ShippingOrderProcessingRun,
previous_result: dict[str, Any],
create_result: dict[str, Any] | None,
) -> dict[str, Any]:
"""按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。"""
candidates = (
ShippingOrderCandidate.query
.filter_by(order_extraction_run_id=int(run.id), is_current_version=True)
.order_by(ShippingOrderCandidate.id.asc())
.all()
)
pending_by_candidate_no = {
str(item.get('candidate_no') or ''): item
for item in previous_result.get('pending_orders') or []
if isinstance(item, dict) and str(item.get('candidate_no') or '').strip()
}
created: list[dict[str, Any]] = []
opened_existing: list[dict[str, Any]] = []
pending_orders: list[dict[str, Any]] = []
created_with_missing_fields_count = 0
for candidate in candidates:
if candidate.consumed_task_id is None:
pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or ''))
if pending_item is not None:
pending_orders.append(pending_item)
continue
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id))
if task is None:
continue
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
opened_existing.append({
'candidate_no': candidate.candidate_no,
'task_no': task.task_no,
'batch_no': None,
})
continue
created.append({'task_no': task.task_no})
if candidate.missing_fields_json:
created_with_missing_fields_count += 1
created_with_missing_fields_count = min(created_with_missing_fields_count, len(created))
non_shipping_orders = list(previous_result.get('non_shipping_orders') or [])
refreshed = {
'status': 'ok',
'request_id': str(run.run_no),
'batch_no': (
create_result.get('batch_no')
if isinstance(create_result, dict) and create_result.get('batch_no')
else previous_result.get('batch_no')
),
'created': created,
'opened_existing': opened_existing,
'pending_orders': pending_orders,
'non_shipping_orders': non_shipping_orders,
'created_count': len(created),
'opened_existing_count': len(opened_existing),
'pending_count': len(pending_orders),
'non_shipping_count': len(non_shipping_orders),
'created_with_missing_fields_count': created_with_missing_fields_count,
}
refreshed['message'] = _build_submission_message(
created_count=refreshed['created_count'],
opened_existing_count=refreshed['opened_existing_count'],
pending_count=refreshed['pending_count'],
non_shipping_count=refreshed['non_shipping_count'],
created_with_missing_fields_count=created_with_missing_fields_count,
)
return refreshed
def _build_submission_message(
*,
created_count: int,
opened_existing_count: int,
pending_count: int,
non_shipping_count: int,
created_with_missing_fields_count: int,
) -> str:
"""生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。"""
if not created_count and not opened_existing_count and not pending_count:
if non_shipping_count:
return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。'
return '未识别到发货订单,本次未创建任务。'
parts: list[str] = []
if created_count:
parts.append(f'已创建 {created_count} 个发货任务')
if opened_existing_count:
parts.append(f'已打开 {opened_existing_count} 个已有任务')
if pending_count:
prefix = '另有' if parts else '有'
parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突')
if non_shipping_count:
parts.append(f'已忽略 {non_shipping_count} 项非发货内容')
message = ';'.join(parts) + '。'
if created_with_missing_fields_count:
message += (
f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,'
'可通过自然对话补充。'
)
return message
@@ -941,24 +941,15 @@ def enqueue_pdf_automark(
).order_by(ShippingOrderDocumentProfileSample.id.asc()).first()
if annotation is None or annotation.table_id != resolved_table_id:
raise ValidationError('Automark requires the frozen annotation sample table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
if not annotation.layout_version_id or not annotation.layout_payload_checksum:
raise ValidationError('Annotation sample layout evidence is not frozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
from app.services.shipping_notice.order_document_profile_service import require_profile_sample_automark_ready
readiness = require_profile_sample_automark_ready(profile=profile, sample=annotation, actor_id=actor_id)
document = db.session.get(ShippingOrderDocument, int(document_id))
current_checksum = str(
getattr(getattr(document, 'current_layout_version', None), 'payload_checksum', '') or '',
)
if (
document is None
or int(document.current_layout_version_id or 0) != int(annotation.layout_version_id)
or current_checksum != str(annotation.layout_payload_checksum)
):
raise ValidationError('Annotation sample layout is stale and must be refrozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
payload = {
'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': resolved_table_id,
'schema_version_id': int(schema_version_id) if schema_version_id else None,
'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id),
'layout_version_id': int(annotation.layout_version_id),
'layout_payload_checksum': str(annotation.layout_payload_checksum),
'layout_version_id': int(readiness['layout_version_id']),
'layout_payload_checksum': str(readiness['layout_payload_checksum']),
}
ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}'
job_id = enqueue(
@@ -39,6 +39,7 @@ from app.models import (
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
derive_incomplete_table_bbox,
reconstruct_coordinate_profile_rows,
suggest_header_layouts,
suggest_header_regions,
@@ -1406,6 +1407,166 @@ def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDo
return version
def refresh_profile_sample_readiness(
*, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample,
actor_id: int | None = None, commit: bool = False,
) -> dict[str, Any]:
"""刷新模板样本的 Layout/主表/证据状态,并在条件满足时幂等冻结现有证据字段。
[STEP 1] 上传物化、Layout ready、主表绑定和证据冻结是四个独立状态;
本函数只在 ready Layout 且内容身份一致时写回既有样本字段,绝不创建新实体,
也不会在 Layout 尚未完成时把样本伪装成可自动标注。
Args:
profile: 必须是当前模板 Profile。
sample: Profile 的 annotation/training 样本绑定。
actor_id: 产生冻结审计时的管理员身份,可为空(后台布局收口)。
commit: 是否提交当前事务;保存草稿时由外层事务统一提交。
Returns:
包含 layout_status、main_table_status、evidence_status 和 automark_ready 的安全状态。
"""
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
if document is None:
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(sample.document_id), 'layout_status': 'missing',
'main_table_status': 'missing', 'evidence_status': 'unavailable',
'automark_ready': False, 'reason_code': 'document_missing',
}
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
layout = current_layout_snapshot(document) or {}
version = (
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
if document.current_layout_version_id else None
)
if (
version is None or str(version.status or '') != 'ready'
or not isinstance(version.payload_json, dict)
):
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'layout_status': str(getattr(version, 'status', None) or 'pending'),
'main_table_status': 'pending', 'evidence_status': 'pending',
'automark_ready': False, 'reason_code': 'layout_not_ready',
}
tables = [
item for item in (layout.get('tables') or [])
if isinstance(item, dict) and str(item.get('table_id') or '').strip()
]
table_id = str(sample.table_id or '').strip()
if not table_id:
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
configured = str(definition.get('main_table_id') or '').strip()
if configured:
table_id = configured
elif len(tables) == 1:
table_id = str(tables[0]['table_id']).strip()
else:
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'layout_status': 'ready',
'main_table_status': 'ambiguous' if tables else 'missing',
'evidence_status': 'pending', 'automark_ready': False,
'reason_code': 'main_table_ambiguous' if tables else 'main_table_missing',
}
if not any(str(item.get('table_id') or '') == table_id for item in tables):
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'layout_status': 'ready',
'main_table_status': 'missing', 'evidence_status': 'stale',
'automark_ready': False, 'reason_code': 'main_table_missing',
}
content_hash = str(document.content_hash or '').strip().lower()
source_hash = str(version.source_content_hash or '').strip().lower()
if len(content_hash) != 64 or len(source_hash) != 64 or content_hash != source_hash:
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'layout_status': 'ready',
'main_table_status': 'bound', 'evidence_status': 'stale',
'automark_ready': False, 'reason_code': 'layout_content_hash_mismatch',
}
from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload
payload_checksum, _ = canonical_layout_payload(version.payload_json or {})
stored_checksum = str(version.payload_checksum or '').strip().lower()
if len(stored_checksum) != 64 or payload_checksum != stored_checksum:
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'layout_status': 'ready',
'main_table_status': 'bound', 'evidence_status': 'stale',
'automark_ready': False, 'reason_code': 'layout_checksum_mismatch',
}
changed = (
sample.table_id != table_id
or sample.layout_version_id != int(version.id)
or str(sample.layout_payload_checksum or '').lower() != stored_checksum
or str(sample.source_content_hash or '').lower() != content_hash
or str(sample.layout_contract_version or '') != str(version.contract_version or '').strip()
or str(sample.parser_key or '') != str(version.parser_key or '').strip()
or str(sample.parser_name or '') != str(version.parser_name or '').strip()
or str(sample.parser_version or '') != str(version.parser_version or '').strip()
)
sample.table_id = table_id
sample.layout_version_id = int(version.id)
sample.layout_payload_checksum = stored_checksum
sample.source_content_hash = content_hash
sample.layout_contract_version = str(version.contract_version or '').strip() or None
sample.parser_key = str(version.parser_key or '').strip() or None
sample.parser_name = str(version.parser_name or '').strip() or None
sample.parser_version = str(version.parser_version or '').strip() or None
# Layout identity or parser provenance changed means this is a new evidence freeze,
# not merely a repeated read of the same frozen sample.
sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at
sample.source_filename_snapshot = str(document.filename or '').strip() or None
sample.page_count_snapshot = _layout_page_count(version.payload_json or {})
sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id)
if changed:
_audit(
profile_id=profile.id, document_id=document.id,
event_type='profile_sample_evidence_frozen', actor_id=actor_id,
detail={
'sample_id': int(sample.id), 'sample_role': sample.sample_role,
'layout_version_id': int(version.id), 'table_id': table_id,
'layout_payload_checksum': stored_checksum,
},
)
if commit:
db.session.commit()
return {
'profile_id': int(profile.id), 'sample_id': int(sample.id),
'document_id': int(document.id), 'table_id': table_id,
'layout_status': 'ready', 'main_table_status': 'bound',
'evidence_status': 'frozen', 'automark_ready': True,
'layout_version_id': int(version.id), 'layout_payload_checksum': stored_checksum,
'reason_code': None,
}
def require_profile_sample_automark_ready(
*, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample,
actor_id: int | None = None,
) -> dict[str, Any]:
"""自动标注入队前唯一强门禁;未满足证据条件时返回稳定、可操作的错误码。"""
state = refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False)
if state.get('automark_ready'):
return state
reason = str(state.get('reason_code') or 'profile_sample_not_ready')
code_by_reason = {
'layout_not_ready': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY',
'main_table_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED',
'main_table_ambiguous': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS',
'layout_content_hash_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
'layout_checksum_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
'document_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
}
raise ValidationError(
'Profile sample is not ready for PDF automark',
code=code_by_reason.get(reason, 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'),
details=state,
)
def _layout_page_count(payload: dict[str, Any]) -> int | None:
"""????????????? payload ?? pages?????????????"""
pages = payload.get('pages')
@@ -2510,6 +2671,36 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
if intake is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
documents = ShippingOrderDocument.query.filter_by(intake_id=intake.id).all()
readiness: list[dict[str, Any]] = []
document_layout_states: list[str] = []
for document in documents:
# 测试/后台轮询都可能只载入 current_layout_version_id;显式按 ID 读取,
# 不能因 ORM relationship 尚未加载把实际 failed/ready 误报为 pending。
version = (
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
if document.current_layout_version_id else None
)
if version is None:
# failed Layout 不会成为 current_layout_version;上传状态仍须如实展示最近一次
# 解析结论,不能因为没有 current 指针把失败伪装成仍在等待。
version = (
ShippingDocumentLayoutVersion.query
.filter_by(document_id=document.id)
.order_by(ShippingDocumentLayoutVersion.version.desc())
.first()
)
document_layout_states.append(str(getattr(version, 'status', None) or 'pending'))
bindings = ShippingOrderDocumentProfileSample.query.filter_by(document_id=document.id).all()
for sample in bindings:
profile = db.session.get(ShippingOrderDocumentProfile, int(sample.profile_id))
if profile is None or profile.status != 'draft':
continue
state = refresh_profile_sample_readiness(
profile=profile, sample=sample, actor_id=actor_id, commit=False,
)
readiness.append(state)
if readiness:
db.session.commit()
if intake.parse_status in {'parse_failed', 'failed', 'error'}:
status = 'failed'
error_code = intake.error_code
@@ -2520,12 +2711,29 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
# ???? PDF Document??????? EML / Layout?
status = 'parsing'
error_code = None
ready_values = [bool(item.get('automark_ready')) for item in readiness]
return {
'intake_no': intake.intake_no,
'parse_status': status,
'document_count': len(documents),
'document_ids': [int(document.id) for document in documents],
'error_code': error_code,
'layout_status': (
'ready' if readiness and all(item.get('layout_status') == 'ready' for item in readiness)
else (
readiness[0].get('layout_status')
if readiness
else ('ready' if document_layout_states and all(item == 'ready' for item in document_layout_states)
else (document_layout_states[0] if document_layout_states else 'pending'))
)
),
'evidence_status': (
'frozen' if readiness and all(item.get('evidence_status') == 'frozen' for item in readiness)
else (readiness[0].get('evidence_status') if readiness else 'pending')
),
'automark_ready': bool(readiness) and all(ready_values),
'automark_reason_code': next((item.get('reason_code') for item in readiness if item.get('reason_code')), None),
'sample_readiness': readiness,
}
@@ -2683,11 +2891,33 @@ def suggest_coordinate_reconstruction(
if field.get('auto_annotation_enabled', True)
and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'}
]
effective_characters = characters
effective_table_bbox = dict(raw_table['bbox'])
table_bbox_source = 'layout_table'
suggestions = suggest_multi_subrow_layouts(
characters=characters, table_bbox=raw_table['bbox'],
characters=effective_characters, table_bbox=effective_table_bbox,
)
if not suggestions:
raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID')
# MinerU can return a header-only table bbox. Use complete page evidence
# to derive a candidate boundary, while retaining the original fact.
page_characters, page_source = _page_coordinate_characters(
layout, page_no=int(raw_table.get('page_no') or 1),
)
if page_characters and page_source in {'pdf_coordinate', 'ocr_coordinate'}:
derived_bbox = derive_incomplete_table_bbox(
characters=page_characters, table_bbox=effective_table_bbox,
)
if derived_bbox is not None:
derived_suggestions = suggest_multi_subrow_layouts(
characters=page_characters, table_bbox=derived_bbox,
)
if derived_suggestions:
effective_characters = page_characters
effective_table_bbox = derived_bbox
suggestions = derived_suggestions
table_bbox_source = 'page_coordinate_derived'
if not suggestions:
raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID')
raw_row_offset = data.get('row_offset')
if raw_row_offset is not None:
try:
@@ -2709,14 +2939,16 @@ def suggest_coordinate_reconstruction(
page = (layout.get('coordinate_evidence') or {}).get('pages', {}).get(str(raw_table.get('page_no') or 1), {})
try:
page_width, page_height = float(page['width']), float(page['height'])
table_bbox = raw_table['bbox']
table_bbox = effective_table_bbox
table_region = {
'x0': float(table_bbox['x0']) / page_width, 'y0': float(table_bbox['y0']) / page_height,
'x1': float(table_bbox['x1']) / page_width, 'y1': float(table_bbox['y1']) / page_height,
}
except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc:
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox'])
header_suggestions = suggest_header_regions(
characters=effective_characters, table_bbox=effective_table_bbox,
)
# Only exact, unique aliases can bind a column. Position is considered only after
# the label itself is proven, preventing shifted documents from remapping fields.
aliases: dict[str, str | None] = {}
@@ -2791,6 +3023,8 @@ def suggest_coordinate_reconstruction(
'table_region': table_region,
'header_regions': serialized_headers,
'subrow_layouts': serialized,
'table_bbox_source': table_bbox_source,
'original_table_bbox': dict(raw_table['bbox']),
'status': 'needs_review',
}
@@ -3114,6 +3348,9 @@ def save_draft(
created_by_id=actor_id,
)
db.session.add(sample)
# readiness audit records sample_id; assign it within this outer save transaction
# before the shared evidence-freeze service is invoked.
db.session.flush()
layout = _document_layout(annotation_document)
if not any(
isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id
@@ -3124,6 +3361,8 @@ def save_draft(
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
sample.table_id = visual_main_table_id
# Layout ready 后立即尝试冻结样本证据;尚未 ready 时保留草稿并由状态接口/自动标注入口继续门禁。
refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False)
_refresh_training_sample_count(profile)
audit_summary = _definition_audit_summary(definition)
if previous_definition is None:
@@ -52,7 +52,6 @@ from app.models import (
ShippingNotice,
ShippingOrderExtraction,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
@@ -71,6 +70,47 @@ from app.services.shipping_notice.context_fields.runtime import canonical_mail_c
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser
def _discard_resolved_worker_field_conflicts(
conflicts: list[dict[str, Any]],
*,
decisions: list[dict[str, Any]],
blocked_fields: list[str],
) -> list[dict[str, Any]]:
"""移除已由最终动态裁决解决的 Worker 早期字段证据缺失阻断。
Worker 可能在派生前先报告 ``evidence_missing``;Candidate 必须以
persist_dynamic_order 的最终 Decision/blocked_fields 为准。仅移除字段级、
字段完整性归属的早期缺证冲突:真实跨来源冲突、非字段完整性冲突,以及最终
仍处于 blocked_fields 的必填或建单关键字段,一律保留。
Args:
conflicts: Worker 原始阻断冲突。
decisions: 动态 Schema 最终字段裁决。
blocked_fields: 派生后最终仍阻断流程的字段编码。
Returns:
仍应投影到 Candidate 的阻断冲突。
"""
unresolved = {str(code).strip() for code in blocked_fields if str(code or '').strip()}
resolved_fields = {
str(item.get('field_code') or '').strip()
for item in decisions
if isinstance(item, dict)
and item.get('status') in {'accepted', 'corroborated', 'derived'}
and str(item.get('field_code') or '').strip() not in unresolved
}
return [
item for item in conflicts
if not (
str(item.get('field') or '').strip() in resolved_fields
and str(item.get('reason') or '') == 'evidence_missing'
and str(item.get('owning_gate_code') or '') in {
'field_completeness', 'order_field_extraction',
}
)
]
def _runtime_session_for_run(run: Any) -> ChatSession | SimpleNamespace:
"""读取 Run 的 UI 会话;历史会话已清理时使用冻结身份继续持久化业务结果。
@@ -437,6 +477,11 @@ def persist_order_extraction_result(
},
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
)
blocking_conflicts = _discard_resolved_worker_field_conflicts(
blocking_conflicts,
decisions=list(dynamic.get('decisions') or []),
blocked_fields=list(dynamic.get('blocked_fields') or []),
)
if run_id is not None:
dynamic['extraction'].run_id = int(run_id)
layout_evidence_issues = [
@@ -874,67 +919,103 @@ def persist_order_extraction_result(
),
)
auto_candidate_nos = [row.candidate_no for row in auto_candidates]
create_result: dict[str, Any] | None = None
if auto_candidate_nos:
idem = f"extract:{current_snapshot[:48]}"
create_result = create_shipping_batch_from_candidates(
user_id=int(session.user_id),
conversation_id=session.session_id,
intake_nos=intake_nos,
candidate_nos=auto_candidate_nos,
create_idempotency_key=idem,
)
# 建批事务已在启动编排器前绑定 Task 与已接受 Extraction;此处只完成本轮提交收口。
db.session.commit()
else:
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
if not pending:
now = datetime.utcnow()
for intake in intakes:
intake.parse_status = 'consumed'
intake.consumed_at = now
intake.order_extraction_status = 'completed'
intake.updated_at = now
db.session.commit()
create_data = (create_result or {}).get('data')
create_data = create_data if isinstance(create_data, dict) else {}
created = list(create_data.get('tasks') or [])
opened_existing = list(
(create_result or {}).get('opened_existing')
or create_data.get('opened_existing')
or []
)
for item in (create_result or {}).get('reconciliation_pending') or []:
if not isinstance(item, dict):
# [STEP 4] open_existing 是既有任务的安全跳转/字段对账,不是新建单路径。
# 它必须在此单独收口,禁止借已删除批次编排器实现,也不得触发新单或自动推进。
opened_existing: list[dict[str, Any]] = []
for candidate in auto_candidates:
if (
candidate.duplicate_resolution != 'open_existing'
or candidate.consumed_task_id is not None
or candidate.validation_status != 'ready'
):
continue
reconciliation = (
item.get('reconciliation')
if isinstance(item.get('reconciliation'), dict)
else {}
target_no = str(candidate.duplicate_target_task_no or '').strip().upper()
if not target_no:
continue
target = (
db.session.query(ShippingNotice)
.filter_by(task_no=target_no, user_id=int(session.user_id))
.with_for_update()
.first()
)
pending.append({
'candidate_no': item.get('candidate_no'),
'task_no': item.get('task_no'),
'reasons': [
str(reconciliation.get('reason') or 'open_existing_reconciliation_required')
],
'reconciliation': reconciliation,
if target is None:
continue
reconciliation: dict[str, Any] | None = None
duplicate_status = str(candidate.duplicate_status or '').strip()
if duplicate_status == 'exact_file':
from app.services.shipping_notice.open_existing_reservation_backfill import (
backfill_exact_file_open_existing_reservations,
)
structured = (
candidate.structured_result_json
if isinstance(candidate.structured_result_json, dict)
else {}
)
extraction = (
structured.get('extraction')
if isinstance(structured.get('extraction'), dict)
else {}
)
reconciliation = backfill_exact_file_open_existing_reservations(
task=target,
candidate=candidate,
candidate_summary=(
structured.get('business_summary')
if isinstance(structured.get('business_summary'), dict)
else {}
),
duplicate_status=duplicate_status,
duplicate_matches=[{'task_no': target.task_no}],
verified_reservation_evidence=list(
extraction.get('verified_reservation_evidence') or []
),
)
# 对账服务仍以既有任务的动态字段及旧安全态为唯一依据;其内会在字段
# 已安全补齐后推进到 parse_review,不能在这里二次推导或覆盖阶段。
if (
reconciliation.get('status') != 'applied'
and reconciliation.get('reason') not in {
'duplicate_status_not_exact_file',
'target_already_complete',
'target_task_not_safe',
}
):
candidate.selected = False
pending_item = {
'candidate_no': candidate.candidate_no,
'task_no': target.task_no,
'reasons': [str(reconciliation.get('reason') or 'open_existing_reconciliation_required')],
'reconciliation': reconciliation,
}
pending.append(pending_item)
pending_by_intake[int(candidate.intake_id)].append(pending_item)
continue
candidate.consumed_task_id = int(target.id)
candidate.updated_at = datetime.utcnow()
opened_existing.append({
'candidate_no': candidate.candidate_no,
'task_no': target.task_no,
**({'reconciliation': reconciliation} if reconciliation is not None else {}),
})
created_count = len(created)
# Candidate 只进入 Review Case/STP;禁止旧抽取链绕过确认直接创建批次或 Task。
if not pending:
now = datetime.utcnow()
for intake in intakes:
intake.parse_status = 'consumed'
intake.consumed_at = now
intake.order_extraction_status = 'completed'
intake.updated_at = now
db.session.commit()
created: list[dict[str, Any]] = []
created_count = 0
opened_existing_count = len(opened_existing)
created_with_missing_fields_count = sum(
1
for candidate in auto_candidates
if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json
)
# 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。
created_with_missing_fields_count = min(created_with_missing_fields_count, created_count)
created_with_missing_fields_count = 0
result = {
'status': 'ok',
'request_id': request_id,
'batch_no': create_result.get('batch_no') if create_result else None,
'created': created,
'opened_existing': opened_existing,
'pending_orders': pending,
@@ -1032,7 +1113,6 @@ def submit_order_extraction_run_result(
result = {
'status': 'ok',
'request_id': str(run.run_no),
'batch_no': None,
'created': [{'task_no': task_no} for task_no in task_nos],
'opened_existing': [],
'pending_orders': [{'candidate_no': item.candidate_no} for item in pending],
@@ -1078,7 +1158,6 @@ def submit_order_extraction_run_result(
result = {
'status': 'ok',
'request_id': str(run.run_no),
'batch_no': None,
'created': [],
'opened_existing': [],
'pending_orders': [],
@@ -1276,7 +1355,6 @@ def submit_order_extraction_unit_result(
result = {
'status': 'ok',
'request_id': str(run.run_no),
'batch_no': None,
'created': [{'task_no': task_no} for task_no in task_nos],
'opened_existing': [],
'pending_orders': [],
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/order_extraction_run_service.py
用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。
依赖:Agent/ChatSession、ShippingOrderIntake/Document、已发布订单 Schema、SQLAlchemy 事务、
order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、
order_extraction.submit_order_extraction_unit_result、
workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)、
error_explainability_contract(Run 失败可解释性投影)、
conversation_processing_projection(会话多任务投影)、audit_service。
@@ -34,7 +34,7 @@ from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from sqlalchemy import and_, or_
from sqlalchemy import and_, func, or_, select
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
@@ -852,6 +852,7 @@ def _build_snapshot(
parse_email_allocation_text,
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
generic_config = (
@@ -918,7 +919,7 @@ def _build_snapshot(
)
if isinstance(email_supplement, dict):
email_supplement['document_id'] = int(document.id)
documents_by_intake[document.intake_id].append({
document_snapshot = {
'document_id': document.id,
'document_type': document.document_type,
'attachment_key': document.attachment_key,
@@ -933,7 +934,15 @@ def _build_snapshot(
'layout_snapshot': layout_snapshot,
'layout_schema_candidates': layout_schema_candidates,
'email_supplement': email_supplement,
})
}
# 自动标注候选只在冻结 Schema/Layout 身份下编译为 Parse Plan;Worker 不得
# 直接消费 layout_schema_candidates。
document_snapshot['generic_parse_plan'] = compile_generic_parse_plan(
candidates=layout_schema_candidates,
schema_checksum=str(schema_version.checksum or ''),
layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {},
)
documents_by_intake[document.intake_id].append(document_snapshot)
incomplete = [
intake.intake_no
for intake in intakes
@@ -1366,6 +1375,7 @@ def materialize_order_extraction_run_inputs(
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
table_contract = compile_table_header_contract(dict(contract))
document_ids = _run_snapshot_document_ids(run)
if document_ids:
@@ -1411,6 +1421,11 @@ def materialize_order_extraction_run_inputs(
candidates = [{'mapping_status': 'failed', 'issues': ['layout_schema_mapping_invalid']}]
item['layout_snapshot'] = layout_snapshot
item['layout_schema_candidates'] = candidates
item['generic_parse_plan'] = compile_generic_parse_plan(
candidates=candidates,
schema_checksum=str(schema.get('checksum') or ''),
layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {},
)
changed = True
if changed:
from sqlalchemy.orm.attributes import flag_modified
@@ -2442,7 +2457,7 @@ def submit_order_extraction(
"""
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.shipping_processing_projection import (
project_conversation_processing_items,
project_conversation_processing_summary,
)
normalized_submission = str(submission_id or '').strip()
@@ -2466,17 +2481,11 @@ def submit_order_extraction(
)
can_append, block_reason = evaluate_can_append(existing)
existing_task_no = str(getattr(existing, 'user_task_no', None) or '').strip() or None
unified = project_conversation_processing_items(
unified = project_conversation_processing_summary(
user_id=user.id,
conversation_id=existing.conversation_id,
focused_task_no=existing_task_no,
recent_task_no=existing_task_no,
recent_decision=decision,
recent_append_count=(
int(existing_row.appended_intake_count)
if existing_row is not None and decision == 'appended'
else None
),
)
return {
'decision': decision,
@@ -2497,7 +2506,6 @@ def submit_order_extraction(
existing.input_frozen_at.isoformat() + 'Z' if existing.input_frozen_at else None
),
'processing': unified.get('conversation_processing'),
'work_items': unified.get('work_items') or [],
}
# [STEP 2] 解析可追加目标。
@@ -2776,16 +2784,14 @@ def submit_order_extraction(
persisted_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or None
from app.services.shipping_notice.shipping_processing_projection import (
project_conversation_processing_items,
project_conversation_processing_summary,
)
unified = project_conversation_processing_items(
unified = project_conversation_processing_summary(
user_id=user.id,
conversation_id=run.conversation_id,
focused_task_no=persisted_task_no,
recent_task_no=persisted_task_no,
recent_decision=decision,
recent_append_count=appended_count if decision == 'appended' else None,
)
return {
'decision': decision,
@@ -2803,7 +2809,6 @@ def submit_order_extraction(
run.input_frozen_at.isoformat() + 'Z' if run.input_frozen_at else None
),
'processing': unified.get('conversation_processing'),
'work_items': unified.get('work_items') or [],
}
@@ -2826,7 +2831,7 @@ def focus_conversation_task(
_latest_focused_task_no,
)
from app.services.shipping_notice.shipping_processing_projection import (
project_conversation_processing_items,
project_conversation_processing_summary,
)
normalized_task = str(task_no or '').strip()
@@ -2863,7 +2868,7 @@ def focus_conversation_task(
after={'focused_task_no': normalized_task, 'run_no': run.run_no},
metadata={'user_task_no': normalized_task},
)
unified = project_conversation_processing_items(
unified = project_conversation_processing_summary(
user_id=user_id,
conversation_id=run.conversation_id,
focused_task_no=normalized_task,
@@ -2871,7 +2876,6 @@ def focus_conversation_task(
return {
'focused_task_no': normalized_task,
'processing': unified.get('conversation_processing'),
'work_items': unified.get('work_items') or [],
}
@@ -2891,7 +2895,7 @@ def mark_conversation_task_viewed(
"""
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.shipping_processing_projection import (
project_conversation_processing_items,
project_conversation_processing_summary,
)
normalized_task = str(task_no or '').strip()
@@ -2927,7 +2931,7 @@ def mark_conversation_task_viewed(
after={'seen_at': run.seen_at.isoformat() + 'Z', 'user_task_no': normalized_task},
metadata={'user_task_no': normalized_task},
)
unified = project_conversation_processing_items(
unified = project_conversation_processing_summary(
user_id=user_id,
conversation_id=run.conversation_id,
focused_task_no=normalized_task,
@@ -2935,7 +2939,6 @@ def mark_conversation_task_viewed(
return {
'user_task_no': normalized_task,
'processing': unified.get('conversation_processing'),
'work_items': unified.get('work_items') or [],
}
@@ -3289,6 +3292,75 @@ def list_order_extraction_runs(
}
def list_order_extraction_run_summaries(
*,
user_id: int,
conversation_id: str | None = None,
limit: int = 50,
status: str | None = None,
page: int | None = None,
page_size: int | None = None,
) -> list[dict[str, Any]] | dict[str, Any]:
"""
为会话恢复和任务中心读取固定成本 Run 摘要,禁止加载冻结输入快照。
核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体;
`input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。
Args:
user_id: 当前用户主键。
conversation_id: 可选会话过滤。
limit: 非分页模式的条数上限。
status: 可选业务状态过滤。
page: 可选分页页码。
page_size: 可选分页大小。
Returns:
非分页:摘要字典列表;分页:{items, total, page, page_size}。
"""
normalized_status = str(status or '').strip() or None
if normalized_status and normalized_status not in {
'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled',
}:
raise ValidationError('status is invalid')
filters = [ShippingOrderProcessingRun.user_id == user_id]
if conversation_id:
filters.append(ShippingOrderProcessingRun.conversation_id == conversation_id)
if normalized_status:
filters.append(ShippingOrderProcessingRun.status == normalized_status)
columns = (
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.user_task_no,
ShippingOrderProcessingRun.owner_agent_id,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.status,
ShippingOrderProcessingRun.phase,
ShippingOrderProcessingRun.progress_summary_json,
ShippingOrderProcessingRun.progress_version,
ShippingOrderProcessingRun.last_activity_at,
ShippingOrderProcessingRun.created_at,
ShippingOrderProcessingRun.updated_at,
)
statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc())
if page is None and page_size is None:
return list(db.session.execute(
statement.limit(min(max(int(limit or 50), 1), 100)),
).mappings())
safe_page = max(1, int(page or 1))
safe_page_size = min(100, max(1, int(page_size or 20)))
total = db.session.scalar(select(func.count()).select_from(ShippingOrderProcessingRun).where(*filters)) or 0
rows = list(db.session.execute(
statement.offset((safe_page - 1) * safe_page_size).limit(safe_page_size),
).mappings())
return {
'items': rows,
'total': int(total),
'page': safe_page,
'page_size': safe_page_size,
}
def _reparse_difference_summary(run: ShippingOrderProcessingRun) -> dict[str, Any] | None:
"""返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。"""
source = run.reparse_source
@@ -3561,6 +3633,35 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
}
def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]:
"""序列化标量 Run 列表行;不得访问 ORM 冻结快照或工作台投影。"""
row = run if hasattr(run, 'get') else run._mapping
progress_summary = row.get('progress_summary_json') if isinstance(row.get('progress_summary_json'), dict) else {}
return {
'run_no': row['run_no'],
'user_task_no': row['user_task_no'],
'agent_id': row['owner_agent_id'],
'conversation_id': row['conversation_id'],
'status': str(row['status'] or 'queued'),
'phase': str(row['phase'] or row['status'] or 'queued'),
'summary': {
'total_documents': int(progress_summary.get('total_documents') or 0),
'pending_documents': int(progress_summary.get('pending_documents') or 0),
'processing_documents': int(progress_summary.get('processing_documents') or 0),
'completed_documents': int(progress_summary.get('completed_documents') or 0),
'review_required_documents': int(progress_summary.get('review_required_documents') or 0),
'failed_documents': int(progress_summary.get('failed_documents') or 0),
'cancelled_documents': int(progress_summary.get('cancelled_documents') or 0),
'candidate_count': int(progress_summary.get('candidate_count') or 0),
'opened_existing_documents': int(progress_summary.get('opened_existing_documents') or 0),
},
'progress_version': int(row['progress_version'] or 0),
'last_activity_at': row['last_activity_at'].isoformat() + 'Z' if row['last_activity_at'] else None,
'created_at': row['created_at'].isoformat() + 'Z' if row['created_at'] else None,
'updated_at': row['updated_at'].isoformat() + 'Z' if row['updated_at'] else None,
}
def serialize_order_extraction_message_state(run: ShippingOrderProcessingRun) -> dict[str, Any]:
"""把服务端 Run 事实投影为聊天状态卡;历史恢复和实时持久化必须共用同一映射。"""
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state
@@ -4359,10 +4460,11 @@ def progress_ready_extraction_unit(
orders: list[dict[str, Any]],
) -> dict[str, Any]:
"""
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 STP 触发下游 auto_progress。
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 Review Case/STP 正式链触发下游。
核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit;建批路径由编排器
调用 progress_workflow.auto_progress;若仅打开既有任务则不重复推进。
核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit。自动建单与自动推进
由 submit 内的 Review Case/STP 正式链异步协调,禁止此处再以已删除的 batch_no 或
结果数组推断并直接调用旧 auto_progress,避免重复推进。
Args:
run: 所属抽取 Run。
@@ -4376,21 +4478,6 @@ def progress_ready_extraction_unit(
mark_order_extraction_persistence_started(run)
result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders)
# 建批编排器会异步调用同一 auto_progress;此处仅为无编排器的已创建任务兜底同步推进。
created = list(result.get('created') or [])
if created and not result.get('batch_no') and not result.get('idempotent_replay'):
from app.services.shipping_notice.progress_workflow import auto_progress
for item in created:
task_no = str(item.get('task_no') or '').strip()
if not task_no:
continue
try:
auto_progress({'task_id': task_no, 'source': 'system'})
except Exception:
current_app.logger.exception(
'STP auto_progress failed after unit persist run=%s unit=%s task=%s',
run.run_no, getattr(unit, 'id', None), task_no,
)
return result
@@ -26,6 +26,9 @@ from app.services.shipping_notice.document_layout.html_table import parse_html_g
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.document_layout.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
@@ -479,29 +482,8 @@ def _selected_coordinate_transform(
def _translate_coordinate_region(
region: dict[str, float], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, float] | None:
"""在裁剪页级 glyph 前使用 matcher 已确认的受限平移;非法声明 fail-closed。"""
if coordinate_transform is None:
return region
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
return None
try:
translate_x, translate_y = (
float(coordinate_transform['translate_x']),
float(coordinate_transform['translate_y']),
)
translated = {
'x0': float(region['x0']) + translate_x,
'y0': float(region['y0']) + translate_y,
'x1': float(region['x1']) + translate_x,
'y1': float(region['y1']) + translate_y,
}
except (KeyError, TypeError, ValueError):
return None
if not all(value == value and abs(value) != float('inf') for value in translated.values()):
return None
if not (0 <= translated['x0'] < translated['x1'] <= 1 and 0 <= translated['y0'] < translated['y1'] <= 1):
return None
return translated
"""在裁剪页级 glyph 前应用 matcher 已确认的统一坐标变换,非法声明 fail-closed。"""
return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
@@ -1466,8 +1448,12 @@ def _extract_generic_evidence_result(
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
candidates = document.get('layout_schema_candidates') if isinstance(document.get('layout_schema_candidates'), list) else []
parse_plan = document.get('generic_parse_plan') if isinstance(document.get('generic_parse_plan'), dict) else None
gate = evaluate_generic_extraction_gate(
candidates=candidates,
parse_plan=parse_plan,
layout_snapshot=document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {},
require_parse_plan=True,
definition=definition,
schema=schema,
intake=intake,
@@ -1557,6 +1543,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
if adapter_result.attach_formal_evidence:
order['_hxops_formal_evidence'] = (adapter_result.evidence or {}).get('formal_evidence_summary')
order['_hxops_value_source_identity'] = (adapter_result.evidence or {}).get('value_source_identity')
_normalize_profile_order_observations(
orders,
default_value_source=adapter_name,
coordinate_transform=_selected_coordinate_transform(
profile_match=match,
raw_profile=selected_profile,
) if adapter_name == 'coordinate_ocr' and isinstance(selected_profile, dict) else None,
)
decision['parsed_table_count'] = 1
decision['route_type'] = 'profile_deterministic'
if decision.get('fallback_reason_codes'):
@@ -1823,6 +1817,67 @@ def _build_approved_profile_order(
return orders[0] if orders and len(orders) == 1 else None
def _normalize_profile_order_observations(
orders: list[dict[str, Any]],
*,
default_value_source: str,
coordinate_transform: dict[str, Any] | None,
) -> None:
"""将 Profile adapter 的字段产物统一为可追溯 Observation 合同。
坐标模板、XFA datasets 的内部字段形态不同,但进入 Candidate Gate 前必须具有相同
的来源、证据引用和几何变换声明。这里不补造缺失的坐标或值;仅为已有字段级
layout/datasets evidence 投影稳定顶层引用,缺证据仍由后续资格门禁拦截。
"""
source_aliases = {
'pdf_coordinate': 'native_pdf',
'native_glyph': 'native_pdf',
'ocr_coordinate': 'ocr',
'ocr_glyph': 'ocr',
'acroform_widget': 'acroform_widget',
'xfa_dataset': 'xfa_dataset',
'coordinate_ocr': 'native_pdf',
}
default_source = source_aliases.get(default_value_source, default_value_source or 'unknown')
transform_ref: dict[str, Any] | None = None
if default_source in {'native_pdf', 'ocr', 'acroform_widget'}:
transform_ref = (
{'kind': 'legacy_absolute'}
if coordinate_transform is None
else {
'kind': 'coordinate_transform',
'status': coordinate_transform.get('status'),
'matrix': list(coordinate_transform.get('matrix') or []),
'anchor_count': coordinate_transform.get('anchor_count'),
'residual': coordinate_transform.get('residual'),
}
)
for order in orders:
if not isinstance(order, dict):
continue
groups = [order.get('header_fields') or []]
groups.extend(
line.get('fields') or []
for line in order.get('lines') or []
if isinstance(line, dict)
)
for fields in groups:
for field in fields if isinstance(fields, list) else []:
if not isinstance(field, dict):
continue
for observation in field.get('observations') or []:
if not isinstance(observation, dict):
continue
evidence = observation.get('layout_evidence')
evidence = evidence if isinstance(evidence, dict) else {}
raw_source = observation.get('value_source') or evidence.get('source') or default_value_source
observation['value_source'] = source_aliases.get(str(raw_source or ''), default_source)
if 'evidence_ref' not in observation and evidence.get('evidence_ref') is not None:
observation['evidence_ref'] = evidence.get('evidence_ref')
if transform_ref is not None:
observation['transform_ref'] = transform_ref
def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]:
"""读取唯一匹配坐标模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -1108,9 +1108,11 @@ def _run_available_actions(
if (
str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}
):
from app.services.shipping_notice.order_review_disposition_service import has_reparseable_batch_documents
from app.services.shipping_notice.order_review_disposition_service import (
has_reparseable_batch_documents_readonly,
)
if has_reparseable_batch_documents(user_id=int(run.user_id), run=run):
if has_reparseable_batch_documents_readonly(user_id=int(run.user_id), run=run):
actions.append('reparse_batch')
if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories:
if 'retry_failed_attachments' not in actions:
@@ -1390,7 +1392,9 @@ def _email_supplement_projection(
1
for order in orders if isinstance(order, dict)
for conflict in order.get('conflicts') or [] if isinstance(conflict, dict)
if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous'
if str(conflict.get('reason') or '').strip() in {
'supplement_relation_ambiguous', 'supplement_field_conflict',
}
)
status = 'conflict' if conflict_count > 0 else 'merged' if relation_codes else 'none'
@@ -1595,13 +1595,19 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
return False
if not getattr(task, 'current_order_extraction_id', None):
return False
return not bool(
getattr(task, 'inventory_snapshot_id', None)
or getattr(task, 'inventory_lines_json', None)
or getattr(task, 'match_status', None)
or getattr(task, 'export_file_path', None)
or getattr(task, 'upload_status', None)
)
inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None)
inventory_lines = getattr(task, 'inventory_lines_json', None)
match_status = getattr(task, 'match_status', None)
export_file_path = getattr(task, 'export_file_path', None)
upload_status = getattr(task, 'upload_status', None)
# 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等
# 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。
has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool)
has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines)
has_match = isinstance(match_status, str) and bool(match_status.strip())
has_export = isinstance(export_file_path, str) and bool(export_file_path.strip())
has_upload = isinstance(upload_status, str) and bool(upload_status.strip())
return not (has_inventory or has_match or has_export or has_upload)
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
@@ -92,8 +92,8 @@ def _case_document_identity(*, case: ShippingOrderReviewCase, documents_by_id: d
return f'document:{document_id}'
def select_current_batch_reparse_cases(
*, user_id: int, run: ShippingOrderProcessingRun,
def _select_current_batch_reparse_cases(
*, user_id: int, run: ShippingOrderProcessingRun, for_update: bool,
) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]:
"""
从批次 Run 谱系为每个原 PDF 选择最新 Review Case。
@@ -112,24 +112,26 @@ def select_current_batch_reparse_cases(
ShippingOrderReviewStream.owner_user_id == int(user_id),
ShippingOrderProcessingRun.conversation_id == str(run.conversation_id),
)
.with_for_update()
.all()
)
if for_update:
stream_cases = stream_cases.with_for_update()
stream_cases = stream_cases.all()
if stream_cases:
root = _run_lineage_root(run=run)
return root, sorted(stream_cases, key=lambda item: int(item.document_id))
root = _run_lineage_root(run=run)
runs = _lineage_runs(root=root, user_id=user_id)
run_ids = [int(item.id) for item in runs]
cases = (
cases_query = (
ShippingOrderReviewCase.query
.filter(
ShippingOrderReviewCase.owner_user_id == int(user_id),
ShippingOrderReviewCase.run_id.in_(run_ids),
)
.with_for_update()
.all()
)
if for_update:
cases_query = cases_query.with_for_update()
cases = cases_query.all()
document_ids = {int(case.document_id) for case in cases if int(case.document_id or 0) > 0}
documents_by_id = {
int(document.id): document
@@ -145,6 +147,13 @@ def select_current_batch_reparse_cases(
return root, [selected[key] for key in sorted(selected)]
def select_current_batch_reparse_cases(
*, user_id: int, run: ShippingOrderProcessingRun,
) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]:
"""为批次重解析写命令选择当前 Case,并锁定参与决策的行。"""
return _select_current_batch_reparse_cases(user_id=user_id, run=run, for_update=True)
def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessingRun) -> bool:
"""供投影判断批次操作可见性;确认/履约与非订单文件不作为可重解析目标。"""
_root, cases = select_current_batch_reparse_cases(user_id=user_id, run=run)
@@ -155,6 +164,21 @@ def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessin
)
def has_reparseable_batch_documents_readonly(
*, user_id: int, run: ShippingOrderProcessingRun,
) -> bool:
"""为 GET 投影无锁判断批次重解析资格,禁止复用写命令的锁定选择器。"""
_root, cases = _select_current_batch_reparse_cases(
user_id=user_id, run=run, for_update=False,
)
return any(
str(case.status or '').strip().lower()
in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'}
and case.confirmed_task_id is None
for case in cases
)
def reparse_batch_documents(
*, user_id: int, run_no: str, reason: str, comment: str | None = None,
) -> dict[str, Any]:
@@ -17,6 +17,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingOrderCandidate, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_qualification_service import (
field_evidence_gap_is_non_blocking,
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
)
@@ -39,7 +40,12 @@ from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts
)
_VC_CONFLICT_PREFIX = 'vc:'
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
_EVIDENCE_GAP_REASONS = frozenset({
'evidence_missing',
'pdf_evidence_missing',
# 历史正文补充冲突缺失双方值和证据,必须显示重新识别入口,不能成为空面板阻断。
'supplement_conflict_evidence_insufficient',
})
def _conflict_key(*, field: str, line_index: Any) -> str:
@@ -51,6 +57,12 @@ def _conflict_key(*, field: str, line_index: Any) -> str:
return f'{idx}:{str(field or "").strip()}'
def _stored_conflict_key(item: dict[str, Any]) -> str:
"""读取新旧 Candidate 冲突的稳定键,新 Finding 优先使用其冻结 conflict_key。"""
explicit = str(item.get('conflict_key') or '').strip()
return explicit or _conflict_key(field=item.get('field'), line_index=item.get('line_index'))
def _candidate_for_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None:
if not case.candidate_id:
return None
@@ -156,6 +168,36 @@ def _option_display(
}
def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]:
"""将统一 Finding 的 source 快照投影为复核选项,避免依赖已丢失的 Observation 索引。"""
options: list[dict[str, Any]] = []
seen: set[str] = set()
for source in item.get('sources') or []:
if not isinstance(source, dict):
continue
raw_value = source.get('raw_value')
if raw_value in (None, ''):
continue
key = str(raw_value)
if key in seen:
continue
seen.add(key)
source_type = str(source.get('source_type') or '').strip()
evidence_role = 'primary_pdf' if source_type == 'pdf' else _evidence_role_for_source_type(source_type)
options.append({
'value_key': key,
'display_value': raw_value,
'sources': [source_type] if source_type else [],
'source_type': source_type or None,
'source_types': [source_type] if source_type else [],
'evidence_role': evidence_role,
'evidence_rank': None,
'evidence_ref': source.get('evidence_ref'),
'document_id': source.get('document_id'),
})
return options
def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None:
"""按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。"""
draft = case.current_draft
@@ -341,11 +383,13 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
reason = str(item.get('reason') or 'field_conflict')
is_evidence_gap = reason in _EVIDENCE_GAP_REASONS
if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item):
continue
# 只有多个候选值不一致才属于「字段冲突待裁决」。
if len(value_keys) < 2 and not is_evidence_gap:
continue
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
options = [
options = _finding_source_options(item) or [
_option_display(
field=field,
value_key=key,
@@ -356,15 +400,16 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
]
line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None
finding = {
'conflict_key': _conflict_key(field=field, line_index=line_index),
'conflict_key': _stored_conflict_key(item),
'field_code': field,
'line_index': line_index if line_index >= 0 else None,
'line_key': line_key,
'scope': _finding_scope(case, field_code=field, line_index=line_index),
'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)),
'severity': str(item.get('severity') or 'blocking'),
'reason': reason,
'options': options,
'observation_ids': observation_ids,
'recovery_action': str(item.get('recovery_action') or '').strip() or None,
}
# 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。
finding_identity = (finding['conflict_key'], reason)
@@ -565,7 +610,7 @@ def resolve_review_case_field_conflict(
for idx, item in enumerate(conflicts):
if not isinstance(item, dict):
continue
key = _conflict_key(field=item.get('field'), line_index=item.get('line_index'))
key = _stored_conflict_key(item)
if key == raw_key:
target_idx = idx
target = item
@@ -588,13 +633,17 @@ def resolve_review_case_field_conflict(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
options = _finding_source_options(target)
if options:
option = options[int(option_index)]
else:
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
@@ -614,7 +663,7 @@ def resolve_review_case_field_conflict(
item for item in conflicts
if not (
isinstance(item, dict)
and _conflict_key(field=item.get('field'), line_index=item.get('line_index')) == raw_key
and _stored_conflict_key(item) == raw_key
)
]
candidate.conflicts_json = conflicts
@@ -7,8 +7,8 @@ services/shipping_notice/order_review_fulfillment_decision_service.py
line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、
order_review_resume_service。
逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions;
订单级聚合计数供侧栏主卡;旧 create_fulfillment_wave 仍走 confirm(BE-8 兼容);
OT 后自动 wave 另服务;履约「料号」= Schema part_number(内部料号),禁止 reservation 回填。
订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」=
Schema part_number(内部料号),禁止 reservation 回填。
"""
from __future__ import annotations
@@ -1252,156 +1252,6 @@ def decide_review_line_fulfillment(
return attach_resume_outcome(payload, resume)
def create_fulfillment_wave(
*,
user_id: int,
case_no: str,
line_keys: list[str],
expected_draft_version: Any,
idempotency_key: str | None,
reason: str | None = None,
) -> dict[str, Any]:
"""
为选中的完整明细行创建履约波次 Task。
核心逻辑:仅接受已标记 fulfill_complete_line_now 且未入 Task 的行;
建波次前强制 validate_draft 刷新库存事实并再次校验充足/Reservation;
数量必须等于草稿整行;调用确认服务并传入 line_keys 过滤。
Args:
user_id: 操作人。
case_no: Case 编号。
line_keys: 本波次完整行键列表。
expected_draft_version: 草稿版本。
idempotency_key: 建单幂等键。
reason: 可选备注。
Returns:
确认结果 + line_fulfillment 投影。
"""
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
if not keys:
raise ValidationError(
'line_keys required',
code='SHIPPING.REVIEW_LINE_WAVE_EMPTY',
)
if len(keys) != len(set(keys)):
raise ValidationError(
'Duplicate line_keys',
code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE',
)
case = _load_writable_case(user_id=user_id, case_no=case_no)
# [STEP 1] 建波次前重跑草稿校验,消费最新库存/预留/路由投影。
from app.services.shipping_notice.order_review_draft_service import validate_draft
validate_draft(
user_id=int(user_id),
case_no=str(case_no),
expected_draft_version=expected_draft_version,
)
case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
from app.services.shipping_notice.order_review_workbench_projection import (
schema_fields_from_case,
)
draft_lines = _draft_line_map(case)
projections = _line_projection_map(case)
schema_fields = schema_fields_from_case(case)
for key in keys:
if key not in draft_lines:
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
decision = _active_decision(case, key)
if decision is None or decision.decision_code != DECISION_FULFILL:
raise ConflictError(
'Line must be marked fulfill_complete_line_now',
code='SHIPPING.REVIEW_LINE_NOT_READY_FOR_WAVE',
details={'line_key': key},
)
if decision.line_status in {'task_created', 'fulfilled'}:
raise ConflictError(
'Line already in a task wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_key': key},
)
req, _avail = _assert_line_can_fulfill_complete(
line_key=key,
draft_line=draft_lines[key],
proj=projections.get(key) or {},
schema_fields=schema_fields,
)
# 禁止拆分:决定中的 required_qty 必须等于草稿整行数量
if decision.required_qty and _parse_qty(decision.required_qty) != req:
raise ValidationError(
'Quantity split is not allowed',
code='SHIPPING.REVIEW_LINE_QTY_SPLIT_FORBIDDEN',
details={'line_key': key},
)
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
# validate_draft 可能抬升草稿版本;以当前草稿版本确认。
current_version = int(case.current_draft.draft_version) if case.current_draft else expected_draft_version
result = confirm_review_case(
user_id=int(user_id),
case_no=str(case_no),
expected_draft_version=current_version,
idempotency_key=idempotency_key,
confirm_note=reason,
line_keys=keys,
)
# [STEP 2] 标记决定为 task_created
from sqlalchemy import func
case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no))
# [STEP] 以本波次返回的 task_no 为准,避免多波次时 case.confirmed_task_id 竞态误绑。
task_id = None
task_no = str((result or {}).get('task_no') or '').strip()
if task_no:
task_row = ShippingNotice.query.filter_by(task_no=task_no).first()
if task_row is not None:
task_id = int(task_row.id)
if task_id is None and isinstance(result, dict) and result.get('case'):
raw_task_id = result['case'].get('confirmed_task_id')
if raw_task_id is not None:
task_id = int(raw_task_id)
# 确认服务已写入 wave_lines;复用其波次号,避免二次递增。
wave_no = (
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
.filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id))
.scalar()
)
next_wave = int(wave_no or 0)
if next_wave <= 0:
prior = (
db.session.query(func.max(ShippingOrderReviewLineDecision.wave_no))
.filter(ShippingOrderReviewLineDecision.review_case_id == int(case.id))
.scalar()
)
next_wave = int(prior or 0) + 1
for key in keys:
decision = _active_decision(case, key)
if decision is None:
continue
decision.line_status = 'task_created'
decision.task_id = int(task_id) if task_id else decision.task_id
decision.wave_no = next_wave
decision.updated_at = datetime.utcnow()
db.session.flush()
from app.services.shipping_notice.order_review_projection import serialize_review_case
result = dict(result or {})
result['line_fulfillment'] = project_review_case_line_decisions(case)
result['case'] = serialize_review_case(case)
result['wave_no'] = next_wave
return result
def close_remaining_fulfillment(
*,
user_id: int,
@@ -40,14 +40,22 @@ from __future__ import annotations
from typing import Any
from sqlalchemy.orm import Load
from app import db
from app.models import (
Job,
ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewDraft,
ShippingOrderReviewStream,
ShippingOrderIntake,
ShippingNotice,
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
@@ -539,6 +547,8 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str
def _document_intake_for_retry(
run: ShippingOrderProcessingRun,
document_id: int,
*,
intakes_by_no: dict[str, ShippingOrderIntake] | None = None,
) -> ShippingOrderIntake | None:
"""按冻结文档归属定位当前 Intake,避免工作台按文件名或会话猜测 SNI。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -550,6 +560,8 @@ def _document_intake_for_retry(
continue
intake_no = str(intake_snapshot.get('intake_no') or '').strip().upper()
if intake_no:
if intakes_by_no is not None:
return intakes_by_no.get(intake_no)
return ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none()
return None
@@ -558,9 +570,17 @@ def _intake_retry_projection(
case: ShippingOrderReviewCase,
run: ShippingOrderProcessingRun,
candidate: ShippingOrderCandidate | None,
*,
intake: ShippingOrderIntake | None = None,
intakes_by_no: dict[str, ShippingOrderIntake] | None = None,
) -> tuple[str | None, bool]:
"""返回当前 Case 唯一的 Intake 重试目标与服务端授权结果。"""
intake = _document_intake_for_retry(run, int(case.document_id))
if intake is None:
intake = _document_intake_for_retry(
run,
int(case.document_id),
intakes_by_no=intakes_by_no,
)
retry_authorized = bool(
intake is not None
and str(intake.parse_status or '').strip().lower() == 'parse_failed'
@@ -1052,11 +1072,33 @@ def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
run: ShippingOrderProcessingRun,
candidates_by_id: dict[int, ShippingOrderCandidate] | None = None,
intakes_by_no: dict[str, ShippingOrderIntake] | None = None,
drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None,
) -> dict[str, Any]:
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
intake = _document_intake_for_retry(run, int(case.document_id))
intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate)
draft = (
drafts_by_id.get(int(case.current_draft_id))
if drafts_by_id is not None and case.current_draft_id
else case.current_draft
)
candidate = (
candidates_by_id.get(int(case.candidate_id))
if candidates_by_id is not None and case.candidate_id
else (db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None)
)
intake = _document_intake_for_retry(
run,
int(case.document_id),
intakes_by_no=intakes_by_no,
)
intake_no, intake_retry_authorized = _intake_retry_projection(
case,
run,
candidate,
intake=intake,
intakes_by_no=intakes_by_no,
)
# 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
lifecycle_stage = 'intake_parse'
@@ -1097,8 +1139,8 @@ def _serialize_review_case_summary(
'document_id': int(case.document_id),
'file_name': _document_filename(run, int(case.document_id)),
'status': case.status,
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
'draft_version': int(draft.draft_version) if draft is not None else None,
'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
'available_actions': (
@@ -1170,16 +1212,162 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
.filter(ShippingOrderProcessingRun.conversation_id == conversation_id)
.filter(ShippingOrderReviewCase.status != 'superseded')
.options(
Load(ShippingOrderReviewCase).load_only(
ShippingOrderReviewCase.id,
ShippingOrderReviewCase.stream_id,
ShippingOrderReviewCase.revision_no,
ShippingOrderReviewCase.case_no,
ShippingOrderReviewCase.run_id,
ShippingOrderReviewCase.document_id,
ShippingOrderReviewCase.candidate_id,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.disposition,
),
Load(ShippingOrderProcessingRun).load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.schema_version_id,
ShippingOrderProcessingRun.input_snapshot_json,
),
)
)
if owner_ids:
query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids))
rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all()
items = [{
**_serialize_review_case_summary(case, run=run),
'stream_id': int(stream.id),
'stream_state': stream.state,
'source_run_no': run.run_no,
} for stream, case, run in rows]
case_ids = [int(case.id) for _, case, _ in rows]
candidate_ids = [int(case.candidate_id) for _, case, _ in rows if case.candidate_id]
draft_ids = [int(case.current_draft_id) for _, case, _ in rows if case.current_draft_id]
task_ids = [int(case.confirmed_task_id) for _, case, _ in rows if case.confirmed_task_id]
candidates_by_id = {
int(candidate.id): candidate
for candidate in ShippingOrderCandidate.query.filter(ShippingOrderCandidate.id.in_(candidate_ids)).all()
} if candidate_ids else {}
drafts_by_id = {
int(draft.id): draft
for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all()
} if draft_ids else {}
_tasks_by_id = {
int(task.id): task
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
} if task_ids else {}
intake_nos = {
str(intake_snapshot.get('intake_no') or '').strip().upper()
for _, case, run in rows
for intake_snapshot in (run.input_snapshot_json or {}).get('intakes', [])
if isinstance(intake_snapshot, dict)
for document in intake_snapshot.get('documents') or []
if isinstance(document, dict) and int(document.get('document_id') or 0) == int(case.document_id)
}
intakes_by_no = {
str(intake.intake_no).strip().upper(): intake
for intake in ShippingOrderIntake.query.filter(ShippingOrderIntake.intake_no.in_(intake_nos)).all()
} if intake_nos else {}
# 队列是会话级聚合:将逐 Case 的 STP 读取收敛为一次批量查询,并复用既有投影缓存契约。
from app.services.shipping_notice.order_stp_auto_create_service import build_stp_idempotency_key
stp_prefixes = {
f"stp-auto:{run.run_no}:doc-{int(case.document_id)}:"
for _, case, run in rows
if case.document_id is not None
}
stp_refs = {
build_stp_idempotency_key(
run_no=run.run_no,
document_id=int(case.document_id),
draft_version=int(drafts_by_id[int(case.current_draft_id)].draft_version),
)
for _, case, run in rows
if case.current_draft_id and int(case.current_draft_id) in drafts_by_id
}
jobs_by_ref: dict[str, list[Job]] = {ref: [] for ref in stp_refs}
jobs_by_prefix: dict[str, list[Job]] = {prefix: [] for prefix in stp_prefixes}
if stp_prefixes:
from sqlalchemy import or_
from app.services.shipping_notice.order_stp_auto_create_service import SHIPPING_STP_JOB_DOMAIN
from app.jobs.types import JobType
jobs = (
Job.query.filter(
Job.domain == SHIPPING_STP_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
or_(*(Job.business_ref.like(f'{prefix}%') for prefix in stp_prefixes)),
).order_by(Job.id.desc()).all()
)
for job in jobs:
ref = str(job.business_ref or '').strip()
jobs_by_ref.setdefault(ref, []).append(job)
prefix = next((item for item in stp_prefixes if ref.startswith(item)), None)
if prefix:
jobs_by_prefix[prefix].append(job)
executions_by_case_id: dict[int, ShippingProcessExecution] = {}
gates_by_execution_id: dict[int, list[ShippingProcessGate]] = {}
latest_attempt_by_id: dict[int, ShippingProcessGateAttempt] = {}
if case_ids:
executions = (
ShippingProcessExecution.query.filter(
ShippingProcessExecution.review_case_id.in_(case_ids),
ShippingProcessExecution.status != 'superseded',
).order_by(ShippingProcessExecution.id.desc()).all()
)
execution_ids = [int(execution.id) for execution in executions]
for execution in executions:
if execution.review_case_id is not None:
executions_by_case_id.setdefault(int(execution.review_case_id), execution)
if execution_ids:
gates = ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id.in_(execution_ids),
).order_by(
ShippingProcessGate.execution_id.asc(),
ShippingProcessGate.sequence_no.asc(),
).all()
for gate in gates:
gates_by_execution_id.setdefault(int(gate.execution_id), []).append(gate)
latest_attempt_ids = [
int(gate.latest_attempt_id)
for gate in gates
if gate.latest_attempt_id is not None
]
if latest_attempt_ids:
latest_attempt_by_id = {
int(attempt.id): attempt
for attempt in ShippingProcessGateAttempt.query.filter(
ShippingProcessGateAttempt.id.in_(latest_attempt_ids),
).all()
}
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **jobs_by_ref}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **jobs_by_prefix}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **executions_by_case_id}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **gates_by_execution_id}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **latest_attempt_by_id}
db.session.info['shipping_conversation_projection_read_cache'] = cache
try:
items = [{
**_serialize_review_case_summary(
case,
run=run,
candidates_by_id=candidates_by_id,
intakes_by_no=intakes_by_no,
drafts_by_id=drafts_by_id,
),
'stream_id': int(stream.id),
'stream_state': stream.state,
'source_run_no': run.run_no,
} for stream, case, run in rows]
finally:
if previous_cache is None:
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
counts = {
'total': len(items),
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
@@ -17,6 +17,7 @@ from __future__ import annotations
import uuid
from typing import Any
from sqlalchemy.orm import load_only
from sqlalchemy.orm.attributes import flag_modified
from app import db
@@ -429,13 +430,32 @@ def get_review_queue_visible_to_user(
is_admin: bool = False,
) -> list[ShippingOrderProcessingRun]:
"""按当前 Run 定位会话;Stream 当前版本决定队列,Run 替代标记不再过滤文件。"""
anchor = get_review_run_visible_to_user(run_no, user_id, is_admin=is_admin)
# 队列仅需要会话与 owner 范围;不要为授权读取解码 Run 的审计/执行大 JSON。
anchor = (
ShippingOrderProcessingRun.query.options(
load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.conversation_id,
),
)
.filter_by(run_no=run_no)
.first()
)
if anchor is None or (not is_admin and int(anchor.user_id) != int(user_id)):
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
query = ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.conversation_id == anchor.conversation_id,
)
if not is_admin:
query = query.filter(ShippingOrderProcessingRun.user_id == int(user_id))
return query.order_by(
return query.options(
load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.conversation_id,
),
).order_by(
ShippingOrderProcessingRun.created_at.asc(),
ShippingOrderProcessingRun.id.asc(),
).all()
@@ -444,12 +444,19 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
verified_upload_success = has_verified_upload_success(task)
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
upload_status = getattr(task, 'upload_status', None)
upload_status = upload_status.strip().lower() if isinstance(upload_status, str) else ''
export_file_path = getattr(task, 'export_file_path', None)
match_status = getattr(task, 'match_status', None)
inventory_lines = getattr(task, 'inventory_lines_json', None)
has_export = isinstance(export_file_path, str) and bool(export_file_path.strip())
has_match = isinstance(match_status, str) and bool(match_status.strip())
has_inventory = isinstance(inventory_lines, (list, dict)) and bool(inventory_lines)
progress_state = (
'uploaded' if verified_upload_success
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
else 'export_ready' if has_export
else 'matched' if has_match
else 'inventory_ready' if has_inventory
else 'not_started'
)
active = find_active_shipping_notice_run_job(task_no=task_no or '')
@@ -1187,19 +1187,6 @@ def persist_dynamic_order(
documents, schema_definition=version.definition_json or {},
layout_candidates_by_document=layout_candidates_by_document,
)
for issue in table_issues:
blocked.extend(str(code) for code in issue['field_codes'])
for code in issue.get('field_codes') or []:
findings.append({
'finding_code': 'layout_table_evidence_blocked',
'owning_gate_code': 'layout_parsing',
'severity': 'blocking',
'field_code': str(code),
'decision_id': None,
'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'),
'user_visible': True,
'blocks_current_action': True,
})
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
(None, None, 'header', raw_order.get('header_fields') or [], header)
]
@@ -1383,6 +1370,41 @@ def persist_dynamic_order(
owning_gate_code='field_completeness',
))
# 表格候选未被整表接受只代表结构化坐标质量不足。若当前字段已有已接受的
# 可验证证据,不能用表格诊断覆盖该字段事实;否则关键字段仍须保守阻断。
accepted_field_codes = {
str(decision.get('field_code') or '')
for decision in decisions
if str(decision.get('status') or '') in {'accepted', 'corroborated', 'derived'}
}
for issue in table_issues:
blocking_codes = [
str(code)
for code in issue['field_codes']
if str(code) not in accepted_field_codes
and field_may_block_process(
next(
(
config for config in all_configs.values()
if str(config.get('field_code') or '') == str(code)
),
None,
)
)
]
blocked.extend(blocking_codes)
for code in issue.get('field_codes') or []:
findings.append({
'finding_code': 'layout_table_evidence_blocked',
'owning_gate_code': 'layout_parsing',
'severity': 'blocking' if str(code) in blocking_codes else 'diagnostic',
'field_code': str(code),
'decision_id': None,
'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'),
'user_visible': str(code) in blocking_codes,
'blocks_current_action': str(code) in blocking_codes,
})
# 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。
system_line_projections: list[dict[str, Any]] = []
for line, projection in zip(extraction.lines, line_projections):
@@ -322,6 +322,13 @@ def find_active_stp_job(*, business_ref: str) -> Job | None:
key = str(business_ref or '').strip()
if not key:
return None
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if isinstance(cache, dict):
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
return next(
(job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
None,
)
return (
Job.query
.filter(
@@ -348,6 +355,10 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None:
key = str(business_ref or '').strip()
if not key:
return None
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if isinstance(cache, dict):
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
return jobs[0] if jobs else None
return (
Job.query
.filter(
@@ -9,6 +9,7 @@ from __future__ import annotations
import copy
from typing import Any
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.po_number import normalize_atomic_po_number
@@ -50,6 +51,135 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str]
}
def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any:
"""返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。
核心逻辑:正文补充合并不能把金额、小数位、日期等显示格式差异误判为业务冲突;
统一复用订单 Schema 的标准化器,遇到非法值仍向上抛出既有校验异常而非放行。
Args:
value: PDF Observation 或邮件正文行中的原始值。
config: 该 field_code 对应的冻结 Schema 配置。
Returns:
可进行语义相等比较的规范值。
"""
return normalize_order_field_value(value, config)
def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]:
"""收集字段 Observation 的规范值集合,禁止以显示文本代替业务等价判断。"""
if not isinstance(fields, list):
return set()
return {
_canonical_field_value(observation.get('value'), config)
for field in fields if isinstance(field, dict)
if codes.get(str(field.get('field_id') or '')) == code
for observation in field.get('observations') or [] if isinstance(observation, dict)
if observation.get('value') not in (None, '')
}
def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]:
"""返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。"""
if not isinstance(fields, list):
return []
return [
observation
for field in fields if isinstance(field, dict)
if codes.get(str(field.get('field_id') or '')) == code
for observation in field.get('observations') or [] if isinstance(observation, dict)
if observation.get('value') not in (None, '')
]
def _supplement_field_conflict(
*,
field_code: str,
config: dict[str, Any],
line_index: int,
pdf_observations: list[dict[str, Any]],
email_value: Any,
email_evidence: dict[str, Any],
email_document_id: int,
schema_version: str,
) -> dict[str, Any]:
"""构造可展示、可裁决的正文补充字段冲突 Finding。
核心逻辑:Candidate Gate、复核面板和进度统计必须消费同一事实;因此不能只保存
field/reason,而要冻结双方原值、Schema 规范值、文档和 evidence_ref。
"""
pdf = pdf_observations[0] if pdf_observations else {}
pdf_raw = pdf.get('value')
email_raw = email_value
return {
'conflict_key': f'{line_index}:{field_code}',
'severity': 'blocking',
'reason': 'supplement_field_conflict',
'resolution_status': 'unresolved',
'field': field_code,
'scope': 'header' if line_index < 0 else 'line',
'line_index': line_index if line_index >= 0 else None,
'values': [str(pdf_raw), str(email_raw)],
'sources': [
{
'source_type': 'pdf',
'raw_value': str(pdf_raw),
'canonical_value': str(_canonical_field_value(pdf_raw, config)),
'document_id': pdf.get('document_id'),
'evidence_ref': dict(pdf.get('evidence_ref') or {}),
},
{
'source_type': 'email_body',
'raw_value': str(email_raw),
'canonical_value': str(_canonical_field_value(email_raw, config)),
'document_id': email_document_id or None,
'evidence_ref': dict(email_evidence or {}),
},
],
'rule_version': schema_version or 'shipping-order-schema.unknown',
}
def _supplement_multi_value_conflict(
*,
field_code: str,
config: dict[str, Any],
values: set[str],
selected_rows: list[dict[str, Any]],
line_index: int,
email_document_id: int,
schema_version: str,
) -> dict[str, Any]:
"""构造邮件正文内部多值的完整 Finding,禁止保留不可展示的旧简略冲突。"""
ordered_values = sorted(values)
sources: list[dict[str, Any]] = []
for row in selected_rows:
raw_value = str(row.get(field_code) or '').strip()
if not raw_value:
continue
evidence = row.get('evidence', {}).get(field_code, {}) if isinstance(row.get('evidence'), dict) else {}
sources.append({
'source_type': 'email_body',
'raw_value': raw_value,
'canonical_value': str(_canonical_field_value(raw_value, config)),
'document_id': email_document_id or None,
'evidence_ref': dict(evidence or {}),
})
return {
'conflict_key': f'{line_index}:{field_code}',
'severity': 'blocking',
'reason': 'supplement_field_conflict',
'resolution_status': 'unresolved',
'field': field_code,
'scope': 'header' if line_index < 0 else 'line',
'line_index': line_index if line_index >= 0 else None,
'values': ordered_values,
'sources': sources,
'rule_version': schema_version or 'shipping-order-schema.unknown',
}
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
"""按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。"""
configs = {
@@ -59,6 +189,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
}
ids = {code: str(item.get('field_id') or '') for code, item in configs.items() if item.get('field_id')}
part_codes = {'part_number', 'customer_part_number'} & set(configs)
schema_version = str(schema_definition.get('version') or '')
merged: list[dict[str, Any]] = []
for raw in orders:
order = copy.deepcopy(raw)
@@ -107,52 +238,81 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
continue
for source_row in selected:
row_part_values = _schema_field_values(source_row, part_codes)
target_lines = [line for line in order.get('lines') or [] if isinstance(line, dict)]
indexed_target_lines = [
(index, line)
for index, line in enumerate(order.get('lines') or [])
if isinstance(line, dict)
]
if relation != 'po_fallback':
# 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。
target_lines = [
line for line in target_lines
indexed_target_lines = [
(index, line) for index, line in indexed_target_lines
if row_part_values & (
_values(line.get('fields'), 'part_number', {v: k for k, v in ids.items()})
| _values(line.get('fields'), 'customer_part_number', {v: k for k, v in ids.items()})
)
]
if not target_lines:
if not indexed_target_lines:
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
continue
target_lines = [line for _, line in indexed_target_lines]
for target_code, config in configs.items():
values = {
str(item.get(target_code) or '').strip()
for item in selected
if str(item.get(target_code) or '').strip()
}
if len(values) > 1:
order.setdefault('conflicts', []).append({
'severity': 'blocking', 'reason': 'supplement_field_conflict',
'field': target_code,
})
continue
value = next(iter(values), '')
field_id = ids.get(target_code)
if not value or not field_id:
continue
target_groups = order.get('header_fields') if config.get('scope') == 'header' else [line.setdefault('fields', []) for line in target_lines]
for fields in ([target_groups] if config.get('scope') == 'header' else target_groups):
target_groups = (
[(-1, order.get('header_fields'))]
if config.get('scope') == 'header'
else [(index, line.setdefault('fields', [])) for index, line in indexed_target_lines]
)
for line_index, fields in target_groups:
if not isinstance(fields, list):
continue
existing_values = _values(fields, target_code, {v: k for k, v in ids.items()})
value_by_canonical: dict[Any, tuple[str, dict[str, Any]]] = {}
comparable_rows = selected if line_index < 0 or relation == 'po_fallback' else [source_row]
for item in comparable_rows:
raw_value = str(item.get(target_code) or '').strip()
if raw_value:
value_by_canonical.setdefault(
_canonical_field_value(raw_value, config),
(raw_value, item),
)
values = {raw_value for raw_value, _ in value_by_canonical.values()}
if len(value_by_canonical) > 1:
conflict = _supplement_multi_value_conflict(
field_code=target_code,
config=config,
values=values,
selected_rows=comparable_rows,
line_index=line_index,
email_document_id=int(supplement.get('document_id') or 0),
schema_version=schema_version,
)
if conflict not in order.setdefault('conflicts', []):
order['conflicts'].append(conflict)
continue
value, value_source_row = next(iter(value_by_canonical.values()), ('', {}))
field_id = ids.get(target_code)
if not value or not field_id:
continue
existing_values = _canonical_values(
fields, target_code, {v: k for k, v in ids.items()}, config,
)
if existing_values:
# PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略:
# 保留 PDF 值,强制进入 Review 由人工裁决。
if existing_values != {value.strip().upper()}:
conflict = {
'severity': 'blocking', 'reason': 'supplement_field_conflict',
'field': target_code,
}
if existing_values != {_canonical_field_value(value, config)}:
conflict = _supplement_field_conflict(
field_code=target_code,
config=config,
line_index=line_index,
pdf_observations=_field_observations(fields, target_code, {v: k for k, v in ids.items()}),
email_value=value,
email_evidence=value_source_row.get('evidence', {}).get(target_code, {}),
email_document_id=int(supplement.get('document_id') or 0),
schema_version=schema_version,
)
if conflict not in order.setdefault('conflicts', []):
order['conflicts'].append(conflict)
continue
_inject(fields, field_id, value, source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0))
_inject(fields, field_id, value, value_source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0))
# 来源方和分配实体是证据字段;没有对应 Schema 字段时仍写入内部订单元数据。
order.setdefault('_hxops_email_supplement_evidence', []).append({
'source_from_party': source_row.get('source_from_party'),
@@ -234,26 +234,30 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
gate: 门禁行。
include_diagnostics: False 时仅保留用户可见 blocking Finding。
"""
legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET
definition = (
{'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False}
if legacy_readonly else _projection_gate_definition(gate.gate_code)
)
definition = _projection_gate_definition(gate.gate_code)
latest = None
if gate.latest_attempt_id:
latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id))
from app import db
cache = db.session.info.get('shipping_conversation_projection_read_cache')
latest = (
cache.get('latest_attempt_by_id', {}).get(int(gate.latest_attempt_id))
if isinstance(cache, dict) else None
)
if latest is None:
latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id))
findings = _findings_from_gate(gate)
if not include_diagnostics:
findings = [
item for item in findings
if item.get('severity') == 'blocking' and item.get('user_visible', True)
]
allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and (
allowed_actions = [str(gate.next_action_code)] if (
gate.next_action_code and is_business_user_action(str(gate.next_action_code))
) else []
# 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
recovery_targets = [] if legacy_readonly else [
recovery_targets = [
{
'action_code': action_code,
'target_gate': plan.get('target_gate'),
@@ -266,7 +270,6 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo
]
return {
'gate_code': gate.gate_code,
'legacy_readonly': legacy_readonly,
'sequence_no': int(gate.sequence_no),
'label': definition.get('label'),
'implementation_status': definition.get('implementation_status'),
@@ -316,23 +319,31 @@ def serialize_process_execution(
Returns:
含当前门禁、主动作与全部门禁轨道的字典。
"""
from app import db
cache = db.session.info.get('shipping_conversation_projection_read_cache')
gates = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id))
.order_by(ShippingProcessGate.sequence_no.asc())
.all()
cache.get('gates_by_execution_id', {}).get(int(execution.id), [])
if isinstance(cache, dict) else []
)
if not gates:
gates = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id))
.order_by(ShippingProcessGate.sequence_no.asc())
.all()
)
serialized = [
serialize_process_gate(gate, include_diagnostics=include_diagnostics)
for gate in gates
if str(gate.gate_code or '').strip() in PROCESS_GATE_CODE_SET
]
current = next(
(item for item in serialized if item.get('gate_code') == execution.current_gate_code),
None,
)
legacy_readonly = any(item.get('legacy_readonly') for item in serialized)
recovery_targets: list[dict[str, Any]] = []
if execution.current_gate_code and not legacy_readonly:
if execution.current_gate_code in PROCESS_GATE_CODE_SET:
# RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。
from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS
@@ -345,14 +356,18 @@ def serialize_process_execution(
'invalidates': list(definition.get('invalidates') or ()),
'permission': definition.get('permission'),
})
active_recovery_plans = ShippingProcessRecoveryPlan.query.filter(
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all()
active_recovery_plans = (
cache.get('active_recovery_plans_by_execution_id', {}).get(int(execution.id), [])
if isinstance(cache, dict) else None
)
if active_recovery_plans is None:
active_recovery_plans = ShippingProcessRecoveryPlan.query.filter(
ShippingProcessRecoveryPlan.execution_id == int(execution.id),
ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}),
).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all()
return {
'execution_no': execution.execution_no,
'status': 'legacy_readonly' if legacy_readonly else execution.status,
'legacy_readonly': legacy_readonly,
'status': execution.status,
'current_gate_code': execution.current_gate_code,
'last_passed_gate_code': execution.last_passed_gate_code,
'primary_next_action_code': execution.primary_next_action_code,
@@ -497,45 +512,6 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。
"""
full = serialize_process_execution(execution, include_diagnostics=False)
# 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate,
# 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时,
# 才进入 legacy_readonly 兼容投影。
current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip()
legacy_readonly = bool(full.get('legacy_readonly')) or (
bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET
)
if legacy_readonly:
refs = _execution_navigation_refs(execution)
return {
'execution_no': full.get('execution_no'),
'status': 'legacy_readonly',
'legacy_readonly': True,
'execution_status': None,
'current_gate': full.get('current_gate'),
'current_blocking_gate': None,
'recovery_targets': [],
'active_recovery_plans': [],
'blocking_reason_code': 'shipping_apx_runtime_disabled',
'blocking_message': '历史自动推进记录仅供审计查看',
'failure_detail': None,
'explainability': None,
'next_action_code': None,
'primary_action': None,
'allowed_actions': [],
'action_presentation': [],
'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}],
'technical_auto_only': True,
'owner_type': 'system',
'responsible_party': 'system',
'diagnostic_hint': None,
**refs,
'navigation': None,
'gates_track': [
{'gate_code': item.get('gate_code'), 'label': item.get('label'),
'status': item.get('status'), 'sequence_no': item.get('sequence_no')}
for item in (full.get('gates') or [])
],
}
current = full.get('current_gate')
blocking = None
if (
@@ -305,15 +305,13 @@ def ensure_execution_for_workflow_version(
.order_by(ShippingProcessExecution.id.desc())
.first()
)
# APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按
# task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。
if existing is not None:
existing_codes = {
str(row.gate_code or '').strip()
for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all()
}
if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET):
existing = None
raise RuntimeError('shipping_process_execution_contract_invalid')
if existing is not None:
if review_case_id and existing.review_case_id is None:
existing.review_case_id = int(review_case_id)
@@ -45,7 +45,6 @@ _WRITE_ACTION_CODES = frozenset({
'open_shortage_review',
'upload_inventory_file',
'retry_inventory_preparation',
'retry',
'retry_parse',
'retry_failed_documents',
'regenerate_excel',
@@ -79,8 +78,10 @@ _POST_CREATE_STAGES = frozenset({
_ACTION_CODE_ALIASES: dict[str, str] = {
'open_review': 'open_order_review',
'open_order_processing': 'open_order_review',
'retry_parse': 'retry',
'retry_failed_documents': 'retry',
# 解析恢复保留其对象边界;不得再塌缩成泛化 retry,否则前端无法判定
# 应重投 Intake、重跑 Run,还是提交当前 Gate。
'retry_parse': 'retry_parse',
'retry_failed_documents': 'retry_failed_documents',
'open_fulfillment': 'view_result',
'view_details': 'view_result',
'wait_manual_upload': 'open_manual_upload',
@@ -90,6 +91,7 @@ _ACTION_CODE_ALIASES: dict[str, str] = {
'rematch': 'open_inventory_match_review',
'match_inventory': 'open_inventory_match_review',
'generate_excel': 'regenerate_excel',
'confirm_inventory_source': 'open_inventory_source_review',
# 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由
# Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。
'regenerate_excel_artifact': 'regenerate_excel',
@@ -97,13 +99,27 @@ _ACTION_CODE_ALIASES: dict[str, str] = {
'reparse_batch': 'reparse_batch',
}
# 具有独立对象边界的动作。它们不是泛化 retry,必须保留原始码,避免丢失
# 重解析、草稿裁决等业务能力。
_OBJECT_EXECUTABLE_ACTION_CODES = frozenset({
'retry_parse',
'retry_failed_documents',
'retry_failed_attachments',
'reparse',
'reparse_batch',
'create_draft',
'edit_draft',
'reconcile_and_progress',
})
# Retry Decision 是旧任务恢复协调器的内部语义。投影只把可确定的决策翻译成
# 已注册的精确 Gate 动作;绝不再下发字面量 retry。
def normalize_action_code(code: str | None) -> str | None:
"""
将原始动作码规范为 SHIPPING_PROCESSING_ACTION_INTENTS 可识别的契约码。
将原始动作码规范为正式 Gate 或具备独立对象边界的业务动作码。
Args:
code: Gate / legacy available_actions 原始码。
code: Gate 或独立业务动作原始码。
Returns:
契约动作码;无法映射时返回 None(禁止泄漏未知码)。
@@ -112,6 +128,16 @@ def normalize_action_code(code: str | None) -> str | None:
if not raw:
return None
mapped = _ACTION_CODE_ALIASES.get(raw, raw)
# 字面量 retry 没有对象/阶段边界,禁止从历史 payload 重新授权为 UI 动作。
if mapped == 'retry':
return None
if mapped in _OBJECT_EXECUTABLE_ACTION_CODES:
return mapped
# Gate 合同是正式动作码全集;这里仅作契约校验,不改变原始动作码。
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_ACTION_CODES
if mapped in PROCESS_GATE_ACTION_CODES:
return mapped
if mapped in SHIPPING_PROCESSING_ACTION_INTENTS and mapped != 'none':
return mapped
return None
@@ -365,23 +391,24 @@ def derive_available_actions(
status: str,
stage: str,
gate: dict[str, Any] | None,
legacy_actions: list[str] | None = None,
authorized_actions: list[str] | None = None,
excel_ready: bool = False,
shipping_notice_no: str | None = None,
) -> list[str]:
"""
由 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage 猜测可下载。
由持久化 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage
或未落库的 Gate 片段猜测可操作入口。
核心逻辑:Gate next_action 优先;download_excel 仅当 excel_ready;
regenerate_excel 仅当处于 excel_generating 且非 automating 且 Excel 未就绪;
open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result;
open_manual_upload 仅当 Gate 或已授权动作明确给出;completed → view_result;
建单前剔除匹配/Excel/上传等履约动作(fail-closed)。
Args:
status: 统一 status。
stage: 统一 stage。
gate: current_gate 摘要。
legacy_actions: 可选旧会话卡动作,仅保留可映射项。
gate: current_gate 摘要;仅正式 Process Gate code 可授权动作。
authorized_actions: 调用方已裁决的精确对象动作,不能由状态推断。
excel_ready: 是否存在 ready 的发货 Excel Artifact。
shipping_notice_no: 正式 Notice 任务号;空表示建单前。
@@ -393,7 +420,14 @@ def derive_available_actions(
post_create = _is_post_create(stage=stage_norm, shipping_notice_no=shipping_notice_no)
actions: list[str] = []
seen: set[str] = set()
gate_action = _gate_next_action(gate)
# current_gate 可能来自旧 Case/任务快照。只有 process_gate_contract 注册的
# 正式 Gate 才能授权动作;历史码即使携带 next_action_code 也必须 fail-closed。
gate_code = str(
(gate or {}).get('gate_code') or (gate or {}).get('gateCode') or ''
).strip().lower() if isinstance(gate, dict) else ''
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET
gate_declared = gate_code in PROCESS_GATE_CODE_SET
gate_action = _gate_next_action(gate) if gate_declared else None
def _push(raw: str | None) -> None:
code = normalize_action_code(raw)
@@ -412,13 +446,8 @@ def derive_available_actions(
_push(gate_action)
# [BE-04] 仅技术失败允许默认 retry;业务 blocked 只保留 Gate next_action。
if status_norm == 'failed' and 'retry' not in seen:
_push('retry')
elif status_norm == 'blocked' and gate_action in {
'retry', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments',
}:
_push('retry')
# 技术失败只能由当前 Gate 或 Retry Decision 下发精确恢复动作。禁止在
# available_actions 注入字面量 retry,避免跨阶段错误重跑抽取。
if status_norm == 'completed':
_push('view_result')
elif (
@@ -434,13 +463,14 @@ def derive_available_actions(
if excel_ready:
_push('download_excel')
for item in legacy_actions or []:
mapped = normalize_action_code(item)
# [BE-07] legacy 只补充只读类动作,禁止用旧卡覆盖 Gate 写意图。
if mapped in {'view_result', 'view_record', 'refresh', 'download_excel'}:
_push(mapped)
elif mapped == 'open_manual_upload':
_push(mapped)
for item in authorized_actions or []:
code = normalize_action_code(item)
# Gate 片段已声明当前节点时,它是唯一写动作裁决者。调用方携带的对象级
# 授权只可补足完全无 Gate 的解析处置;即使 Gate 尚未证明已持久化,也不得
# 用历史动作绕过它并把 match_inventory 等带入 Excel/上传节点。
if gate_declared and code not in {'view_result', 'view_record', 'refresh', 'download_excel'}:
continue
_push(code)
if not actions:
actions = ['view_result'] if status_norm in {'completed', 'failed', 'cancelled'} else []
@@ -450,7 +480,7 @@ def derive_available_actions(
def reconcile_processing_projection_facts(
payload: dict[str, Any],
*,
legacy_actions: list[str] | None = None,
authorized_actions: list[str] | None = None,
invalidated_from_stage: str | None = None,
excel_ready: bool = False,
verified_upload_success: bool | None = None,
@@ -467,7 +497,7 @@ def reconcile_processing_projection_facts(
Args:
payload: 即将返回的 ShippingProcessingProjection dict(snake_case)。
legacy_actions: 可选旧动作列表。
authorized_actions: 调用方已裁决的精确对象动作。
invalidated_from_stage: 可选失效起点 stage。
excel_ready: 是否存在 ready Excel Artifact。
@@ -591,7 +621,7 @@ def reconcile_processing_projection_facts(
status=status,
stage=stage,
gate=gate,
legacy_actions=legacy_actions if legacy_actions is not None else list(
authorized_actions=authorized_actions if authorized_actions is not None else list(
payload.get('available_actions') or []
),
excel_ready=excel_ready,
@@ -649,10 +679,10 @@ def apply_user_projection_fields(
【AI 触发时机】:任何需要向前端返回 OrderTask/Conversation 投影的末端出口,
在 reconcile_processing_projection_facts 之后、record_projection_inconsistency 之后调用。
核心逻辑(决策 F3:新增字段不替换旧枚举,Retry Decision 优先 + legacy 兜底):
[STEP 1] 保存旧枚举到 legacy_status / legacy_stage / legacy_current_gate,避免旧前端 break。
核心逻辑:以正式 Process Gate 与领域事实生成唯一用户态 DTO。
[STEP 1] 读取当前投影 status / stage / current_gate 作为计算输入,不输出兼容镜像。
[STEP 2] 读取 pending_reason / review_status / inventory_source_status 原始字段。
[STEP 3] 计算 Retry Decision(仅 notice 存在时,失败/不存在则 legacy 兜底)。
[STEP 3] 按正式 Gate 与领域终态裁决用户状态。
[STEP 4] 按冻结优先级计算 user_status(completed/cancelled/failed → retryable → waiting_human → running)。
[STEP 5] 仅在投影内部计算可重试语义,用于生成唯一 primary_action;不再输出旧 retryable 布尔字段。
[STEP 6] 计算 blocking_reason:{code, i18n_key, details} 或 None。
@@ -665,7 +695,7 @@ def apply_user_projection_fields(
order_task: 可选 ShippingOrderTask 实体(用于 facts 与 legacy pending_reason)。
Returns:
就地修改后的 payload(含新增 6 字段与 3 个 legacy_* 备份)。
就地修改后的 payload(含用户态字段;不保留旧字段备份)。
"""
from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW as REVIEW_STATUS_SHORTAGE_REVIEW,
@@ -677,10 +707,7 @@ def apply_user_projection_fields(
_INVENTORY_SOURCE_STATUS_RESOLVED = 'resolved'
_PROCESS_HUMAN_PENDING_MATCH = 'match_review_pending'
# ===== [STEP 1] 旧枚举备份(保持不变) =====
payload['legacy_status'] = payload.get('status')
payload['legacy_stage'] = payload.get('stage')
payload['legacy_current_gate'] = payload.get('current_gate')
# ===== [STEP 1] 读取当前投影输入 =====
old_status = str(payload.get('status') or '').strip().lower()
old_stage = str(payload.get('stage') or '').strip().lower()
source_type = str(payload.get('source_type') or '').strip().lower() or None
@@ -720,38 +747,7 @@ def apply_user_projection_fields(
if order_task is not None and not pending_reason:
pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None
# ===== [STEP 3] 计算 Retry Decision(仅 notice 真实存在时) =====
retry_decision: dict | None = None
rd_action: str | None = None
rd_status: str | None = None
rd_retryable: bool = False
rd_reason_code: str | None = None
_RD_NEEDS_HUMAN: str | None = None
_RD_NOOP: str | None = None
_RD_STATUS_RUNNING: str | None = None
_RD_STATUS_NEEDS_HUMAN: str | None = None
_RD_STATUS_COMPLETED: str | None = None
_RD_STATUS_FAILED: str | None = None
if notice is not None:
try:
from app.services.shipping_notice.task_retry_decision_service import (
decide_retry_action_only,
ACTION_NEEDS_HUMAN as _RD_NEEDS_HUMAN,
ACTION_NOOP as _RD_NOOP,
STATUS_RUNNING as _RD_STATUS_RUNNING,
STATUS_NEEDS_HUMAN as _RD_STATUS_NEEDS_HUMAN,
STATUS_COMPLETED as _RD_STATUS_COMPLETED,
STATUS_FAILED as _RD_STATUS_FAILED,
)
retry_decision = decide_retry_action_only(notice, scope='task')
except Exception: # noqa: BLE001
retry_decision = None
rd_action = str((retry_decision or {}).get('action') or '').strip() or None
rd_status = str((retry_decision or {}).get('status') or '').strip() or None
rd_retryable = bool((retry_decision or {}).get('retryable'))
rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None
# ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
# ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status =====
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else ''
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
@@ -767,11 +763,8 @@ def apply_user_projection_fields(
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
)
)
_rd_has_completed_process = verified_upload_success
def _compute_user_status() -> str:
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
# 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。
# 当前 Gate 是唯一可执行状态源,不能由旧 Retry Decision 覆盖。
gate_status = str((old_gate or {}).get('status') or '').strip().lower()
if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}:
return 'retryable'
@@ -786,20 +779,7 @@ def apply_user_projection_fields(
return 'cancelled'
if old_status == 'failed':
return 'failed'
# Retry Decision 可得时:优先用决策器
if retry_decision is not None:
# 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed
if rd_status == _RD_STATUS_COMPLETED and verified_upload_success:
return 'completed'
if rd_action == _RD_NOOP and _rd_has_completed_process:
return 'completed'
# 5) rd_retryable=True → 'retryable'(新增!)
if rd_retryable is True:
return 'retryable'
# 6) rd_status=needs_human 或 rd_action=needs_human → waiting_human
if rd_status == _RD_STATUS_NEEDS_HUMAN or rd_action == _RD_NEEDS_HUMAN:
return 'waiting_human'
# 7) legacy waiting_human 兜底(保留旧逻辑)
# 领域事实仅补充展示状态,不得生成恢复权限。
if old_status in {'waiting_review', 'waiting_inventory_source_review', 'waiting_shortage_review'}:
return 'waiting_human'
if pending_reason in {
@@ -808,12 +788,9 @@ def apply_user_projection_fields(
_PROCESS_HUMAN_PENDING_MATCH,
} or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}:
return 'waiting_human'
# 8) rd_status=running 或旧 running 族 → running
if retry_decision is not None and rd_status == _RD_STATUS_RUNNING:
return 'running'
if old_status in {'processing', 'queued', 'running'}:
return 'running'
# 9) 兜底
# 无法判定时保守显示处理中,不下发动作。
return 'running'
user_status = _compute_user_status()
@@ -851,8 +828,6 @@ def apply_user_projection_fields(
return False
if user_status == 'retryable':
return True
if user_status == 'failed' and rd_retryable:
return True
return False
retryable = _compute_retryable()
@@ -928,12 +903,6 @@ def apply_user_projection_fields(
return None
# 2) waiting_human
if user_status == 'waiting_human':
if retry_decision is not None and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip()
if gate_reason and gate_reason in _REASON_TO_I18N_KEY:
return {
@@ -948,12 +917,6 @@ def apply_user_projection_fields(
return _legacy_waiting_human_blocking_reason()
# 3) retryable
if user_status == 'retryable':
if rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
return {
'code': 'technical_failure_present',
'i18n_key': _REASON_TO_I18N_KEY['technical_failure_present'],
@@ -961,16 +924,10 @@ def apply_user_projection_fields(
}
# 4) failed
if user_status == 'failed':
if rd_retryable and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
return {
'code': 'process_failed_terminal',
'i18n_key': _PROCESS_FAILED_I18N,
'details': {'legacy_status': old_status, 'legacy_stage': old_stage},
'details': {'status': old_status, 'stage': old_stage},
}
return None
@@ -978,7 +935,6 @@ def apply_user_projection_fields(
# ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None =====
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
@@ -990,7 +946,6 @@ def apply_user_projection_fields(
'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review',
}
_ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = {
'retry': 'chat.shippingProcessing.action.retry',
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview',
'open_order_review': 'chat.shippingProcessing.action.open_order_review',
@@ -1010,15 +965,6 @@ def apply_user_projection_fields(
fallback = _ACTION_CODE_TO_CHAT_I18N_FALLBACK.get(action_code)
return fallback or f'chat.shippingProcessing.action.{action_code}'
def _legacy_waiting_human_primary_action(bcode: str) -> dict[str, Any] | None:
if bcode in {'inventory_shortage', 'inventory_multi_file_conflict'}:
code = 'open_inventory_match_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode == 'order_review_required':
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
return None
def _compute_primary_action() -> dict[str, Any] | None:
# [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的
# match_inventory/regenerate_excel 仅作兼容回退。
@@ -1026,7 +972,7 @@ def apply_user_projection_fields(
gate_action_alias = {
'regenerate_excel_artifact': 'regenerate_excel',
}.get(gate_action, gate_action)
if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in {
if gate_action_alias and user_status in {
'retryable', 'waiting_human', 'running',
}:
return {
@@ -1037,11 +983,7 @@ def apply_user_projection_fields(
# 1) blocking_reason 非 None
if blocking_reason is not None:
bcode = str(blocking_reason.get('code') or '').strip()
# 1a. retryable 或 failed+retryable → 统一 retry 动作
if user_status == 'retryable' or (user_status == 'failed' and retryable is True):
code = 'retry'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1b ~ 1h: waiting_human 按 code 分派
# waiting_human 仅按 Gate/领域阻断映射精确业务入口。
if user_status == 'waiting_human':
if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}:
code = 'open_inventory_match_review'
@@ -1071,27 +1013,7 @@ def apply_user_projection_fields(
}:
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底
available_actions = payload.get('available_actions')
if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions:
code = 'reconcile_and_progress'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1i. 其它 unknown:legacy 兜底
legacy_pa = _legacy_waiting_human_primary_action(bcode)
if legacy_pa is not None:
return legacy_pa
# 2) completed → download_excel(保持 legacy)
if user_status == 'completed':
code = 'download_excel'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 3) running 且 stage 匹配 → match_inventory / regenerate_excel(保持 legacy)
if user_status == 'running' and user_stage == 'inventory_match':
code = 'match_inventory'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if user_status == 'running' and user_stage == 'excel_generate':
code = 'regenerate_excel'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 4) 兜底 None
# Gate 未明确授权时不由阶段、状态或旧 actions 补造 CTA。
return None
primary_action = _compute_primary_action()
@@ -281,12 +281,16 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
'confirm_customer',
'resolve_field_conflicts',
'adjudicate_duplicate',
'open_inventory_source_review',
'open_inventory_match_review',
'open_shortage_review',
'upload_inventory_file',
'retry_inventory_preparation',
'retry_inventory_matching',
'retry',
'retry_parse',
'retry_failed_documents',
'retry_failed_attachments',
'reparse',
'reparse_batch',
'refresh',
'regenerate_excel',
@@ -1,14 +1,13 @@
"""
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
order_review_projection(任务中心 STP retry 动作投影)。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉;
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event,
以及统一 shipping_processing_status / progress_version / order_task_no(BE-02),
并注入 review_run_no 供任务中心深链订单处理工作台(UI-04);
@@ -54,7 +53,6 @@ from app.models import (
ShippingTaskEvent,
ShippingUploadAttempt,
)
from app.services.shipping_notice.batch_legacy_removed import SHIPPING_BATCHES_REMOVED_MESSAGE
from app.services.shipping_notice.constants import (
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
@@ -162,13 +160,6 @@ class TaskProjection(str, Enum):
DETAIL = "detail"
class BatchProjection(str, Enum):
"""批次读模型投影:工作台全量 / Tool 精简。"""
SUMMARY = "summary"
TOOL = "tool"
def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]:
"""为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。"""
verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by(
@@ -219,25 +210,6 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]
}
def _task_batch_no(task: ShippingNotice) -> str | None:
"""shipping_batches 已删除;任务不再挂 batch_no。"""
del task
return None
def task_sort_key(task: ShippingNotice) -> tuple[int, str]:
"""批次内任务排序键:batch_index 优先,其次 created_at。"""
return (
task.batch_index if task.batch_index is not None else 10**9,
task.created_at.isoformat() if task.created_at else "",
)
def sort_batch_tasks(tasks: list[ShippingNotice]) -> list[ShippingNotice]:
"""按 batch_index、created_at 对批次任务列表排序(返回新列表)。"""
return sorted(tasks, key=task_sort_key)
def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
"""按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。"""
value = str(task_ref or "").strip()
@@ -271,12 +243,6 @@ def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
return None
def get_batch_by_no(batch_no: str) -> None:
"""按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。"""
del batch_no
return None
def resolve_order_extraction_ui_target(
*,
user_id: int,
@@ -286,15 +252,15 @@ def resolve_order_extraction_ui_target(
"""
按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。
核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时,
再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。
核心逻辑:沿 Candidate.consumed_task_id 查找当前用户的既有 Task。
禁止回退到“用户最近任务”,避免并发会话串单。
Args:
user_id: 当前聊天用户 ID。
conversation_id: 当前 HXOPS ChatSession.session_id。
intake_nos: 本轮 agent_runtime_context.refs.intake_nos。
Returns:
`(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。
`(None, task)`;`shipping_batches` 已删除,任务是唯一恢复锚点。
"""
normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
session_id = str(conversation_id or '').strip()
@@ -328,12 +294,6 @@ def resolve_order_extraction_ui_target(
return None, task
def get_task_in_batch(batch_no: str, task_no: str) -> ShippingNotice | None:
"""查找属于指定批次的任务;shipping_batches 已删除,固定返回 None。"""
del batch_no, task_no
return None
def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None:
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
if not task or not task.export_file_path:
@@ -366,102 +326,6 @@ def task_export_error_message(task: ShippingNotice | None) -> str:
return ""
def list_sorted_batch_tasks(batch: Any) -> list[ShippingNotice]:
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回空列表。"""
del batch
return []
def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]:
"""shipping_batches 已删除;固定返回空列表。"""
del batch
return []
def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]:
"""批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。"""
total = len(tasks)
completed = sum(1 for item in tasks if _is_task_completed(item))
failed = sum(1 for item in tasks if _is_task_failed(item))
running = sum(1 for item in tasks if _is_task_active(item))
pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item)))
focus = next(
(
item for item in sort_batch_tasks(tasks)
if not _is_task_completed(item) and not _is_task_failed(item)
),
None,
)
return {
"total": total,
"completed": completed,
"failed": failed,
"running": running,
"pending": pending,
"current_index": int(focus.batch_index or 0) if focus else (total if total else 0),
"current_task_no": focus.task_no if focus else None,
}
def _is_task_completed(task: ShippingNotice) -> bool:
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
return upload_status in {"uploaded", "succeeded", "success"} or bool(
str(getattr(task, "freight_ref_no", None) or "").strip()
)
def _is_task_failed(task: ShippingNotice) -> bool:
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
return (
str(getattr(task, "review_status", None) or "").strip().lower() == "rejected"
or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
)
def _is_task_needs_human(task: ShippingNotice) -> bool:
"""判断任务是否停在人工门;失败态不重复计入人工门。"""
if _is_task_failed(task) or _is_task_completed(task):
return False
return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None))
def _is_task_active(task: ShippingNotice) -> bool:
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
return False
lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower()
if lifecycle != "active":
return False
return bool(
getattr(task, "current_step", None)
or getattr(task, "inventory_snapshot_id", None)
or getattr(task, "export_file_path", None)
or getattr(task, "upload_status", None)
)
def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]:
"""按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。"""
tasks: list[ShippingNotice] = []
for batch in batches:
tasks.extend(list(getattr(batch, "tasks", None) or []))
completed = sum(1 for task in tasks if _is_task_completed(task))
failed = sum(1 for task in tasks if _is_task_failed(task))
needs_human = sum(1 for task in tasks if _is_task_needs_human(task))
running = sum(1 for task in tasks if _is_task_active(task))
pending = max(0, len(tasks) - completed - failed - needs_human - running)
return {
"batch_count": len(batches),
"total": len(tasks),
"completed": completed,
"running": running,
"failed": failed,
"needs_human": needs_human,
"pending": pending,
}
def extract_task_no_from_text(text: str) -> str | None:
"""从自然语言文本中提取 SN 技术号或客户业务号。"""
raw = str(text or "")
@@ -674,12 +538,9 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"batch_no": _task_batch_no(task),
"source_type": task.source_type,
"source_file_name": task.source_file_name,
"source_file_type": task.source_file_type,
"batch_index": task.batch_index,
"batch_total": task.batch_total,
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
@@ -790,41 +651,6 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]:
return serialize_task(task, TaskProjection.TOOL)
def serialize_batch(batch: Any, projection: BatchProjection) -> dict[str, Any]:
"""shipping_batches 已删除;禁止序列化批次对象。"""
del batch, projection
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def serialize_batch_for_tool(batch: Any | None) -> dict[str, Any] | None:
"""Tool 批次 data 投影;shipping_batches 已删除。"""
del batch
return None
def serialize_batch_summary(batch: Any) -> dict[str, Any]:
"""shipping_batches 已删除;禁止序列化批次摘要。"""
del batch
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def serialize_conversation_batch_workspace(batch: Any) -> dict[str, Any]:
"""shipping_batches 已删除;禁止构建会话批次工作台。"""
del batch
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
"""返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要(co8 起固定空集)。"""
value = str(conversation_id or "").strip()
del user_id
return {
"conversation_id": value,
"summary": compute_conversation_workspace_summary([]),
"batches": [],
}
def task_todo_category(task: ShippingNotice) -> str:
"""
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
@@ -1112,46 +938,15 @@ def serialize_task_detail(
)
def get_batch_for_user(batch_no: str, user_id: int) -> None:
"""按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。"""
del batch_no, user_id
return None
def list_batches_for_user(
user_id: int,
*,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见批次摘要;shipping_batches 已删除,固定返回空列表。"""
del user_id, limit
return []
def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]:
"""列出批次下任务;shipping_batches 已删除,固定返回空列表。"""
del batch_no, user_id
return []
def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingNotice | None:
"""获取批次 focus 任务;shipping_batches 已删除,固定返回 None。"""
del batch_no, user_id
return None
def list_tasks_for_user(
user_id: int,
*,
batch_no: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
"""列出用户可见任务摘要。"""
q = ShippingNotice.query.filter(
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None))
)
if batch_no:
return []
rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all()
return [
serialize_task_summary(c, viewer_user_id=user_id)
@@ -1164,7 +959,6 @@ def list_tasks_page_for_user(
*,
page: int = 1,
page_size: int = 20,
batch_no: str | None = None,
lifecycle_status: str | None = None,
) -> dict[str, Any]:
"""
@@ -1178,8 +972,6 @@ def list_tasks_page_for_user(
q = ShippingNotice.query.filter(
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None))
)
if batch_no:
return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0}
if lifecycle_status:
normalized_lifecycle = str(lifecycle_status).strip().lower()
if normalized_lifecycle == 'deleted':
@@ -36,7 +36,6 @@ def enqueue_shipping_notice_job(
*,
task_no: str,
created_by_id: int | None = None,
batch_no: str | None = None,
commit: bool = True,
) -> tuple[bool, str]:
"""
@@ -48,7 +47,6 @@ def enqueue_shipping_notice_job(
Args:
task_no: 发货任务号。
created_by_id: 创建人。
batch_no: 可选批次号。
commit: False 时与业务同事务提交;此时 sync 模式返回 queued_sync_pending:<job_id>。
Returns:
@@ -63,7 +61,6 @@ def enqueue_shipping_notice_job(
JobType.SHIPPING_NOTICE_RUN,
{
'task_no': normalized_task_no,
'batch_no': str(batch_no or '').strip().upper() or None,
},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=normalized_task_no,
@@ -124,7 +121,6 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
JobType.SHIPPING_NOTICE_RUN,
{
'task_no': task_no,
'batch_no': (job.payload_json or {}).get('batch_no') if job and job.payload_json else None,
},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=task_no,
@@ -225,7 +221,6 @@ def claim_next_shipping_notice_job() -> Job | None:
JobType.SHIPPING_DOCUMENT_LAYOUT,
JobType.SHIPPING_PROCESS_GATE,
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
JobType.SHIPPING_AUTO_PROGRESS,
JobType.SHIPPING_PDF_AUTOMARK,
JobType.SHIPPING_STP_AUTO_CREATE,
JobType.SHIPPING_LINE_AUTO_FULFILL,
@@ -566,12 +566,20 @@ def _project_case_formal_gate_summary(
# 纯投影契约测试与离线诊断没有 Flask application context;此时没有可读
# 的持久化 Execution,保持原有 Case 派生事实即可。
return None
from app import db
cache = db.session.info.get('shipping_conversation_projection_read_cache')
execution = (
ShippingProcessExecution.query.filter_by(review_case_id=int(case_id))
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
cache.get('execution_by_case_id', {}).get(int(case_id))
if isinstance(cache, dict) else None
)
if execution is None:
execution = (
ShippingProcessExecution.query.filter_by(review_case_id=int(case_id))
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is None:
return None
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
@@ -588,8 +596,8 @@ def _project_case_formal_gate_facts(
将正式 Gate 摘要归一化为 Case bundle 的三项用户事实。
正式 Execution 存在时,Gate 事实必须覆盖 Case 的历史阻断:
只有已入队/运行或等待外部回执才表示系统正在推进;建单前的订单冻结
校验仍需用户从编辑区提交,不能因 ``pending`` 误显示为系统处理中。
已落库的正式 Gate 表示流程已进入该节点;建单前的订单冻结校验仍需用户
从编辑区提交,是唯一不能因 ``pending`` 显示为系统处理中的例外。
"""
if not isinstance(summary, dict):
return None
@@ -634,10 +642,10 @@ def _project_case_formal_gate_facts(
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
user_status: UserStatus = 'running'
elif gate_status == 'pending':
# pending 仅表示尚未进入该 Gate,不能伪装为系统已在推进。保留当前
# Case 的可编辑 idle 语义,直到 Gate 实际入队或运行。
# Execution 已持久化后 pending 是该 Gate 的初始系统推进态;不能回退到
# Case 草稿的 idle 语义,否则五阶段会把已进入下游节点的文件错误标为空闲。
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
user_status = 'idle'
user_status = 'running'
elif gate_status == 'blocked_manual':
user_status: UserStatus = 'waiting_human'
elif gate_status in {'blocked_retryable', 'invalidated'}:
@@ -805,24 +813,24 @@ def project_case_primary_action(
return {'code': 'open_order_review', 'variant': 'warning',
'label_key': 'shipping.actions.open_order_review'}
# 1f: 草稿编辑和保存校验分别属于主编辑区与底栏,不得升级为当前任务 CTA。
if user_status == 'waiting_human':
return None
# 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA)
if user_status == 'idle':
# 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的
# 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。
if user_status in {'waiting_human', 'idle'}:
if 'create_draft' in actions:
return None
return {'code': 'create_draft', 'variant': 'primary',
'label_key': 'shipping.actions.create_draft'}
if 'edit_draft' in actions:
return None
return {'code': 'edit_draft', 'variant': 'primary',
'label_key': 'shipping.actions.edit_draft'}
# 1h: running/queued → 次优先 view(但 edit_draft 仍然允许)
# 1g: running/queued → 次优先 view(但 edit_draft 仍然允许)
if user_status == 'running' and 'edit_draft' in actions:
return None
# 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码
# 1h: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个业务动作;view 是只读
# 查询能力,阶段导航由五阶段入口承担,不能伪装成文件当前业务 CTA。
for code in _PRIMARY_ACTION_ORDER:
if code in {'edit_draft', 'create_draft', 'validate'}:
if code in {'edit_draft', 'create_draft', 'validate', 'view'}:
continue
if code in actions:
variant = 'default'
@@ -913,31 +921,46 @@ def _project_fine_grained_pre_stp_blocking(
_latest_not_blocking = True
if run_no and document_id is not None and draft_version is not None:
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
cache = db.session.info.get('shipping_conversation_projection_read_cache')
prefix_jobs = (
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
if isinstance(cache, dict) else None
)
active_job = (
db.session.query(Job)
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.status.in_(('queued', 'running')),
Job.business_ref.like(f"{business_ref_prefix}%"),
next(
(job for job in prefix_jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
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_(('queued', 'running')),
Job.business_ref.like(f"{business_ref_prefix}%"),
)
.order_by(Job.id.desc())
.first()
)
.order_by(Job.id.desc())
.first()
)
_no_active_job = active_job is None
if not _no_active_job:
pass
else:
latest_failed = (
db.session.query(Job)
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.status.in_(('failed', 'dead')),
Job.business_ref.like(f"{business_ref_prefix}%"),
next(
(job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}),
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.business_ref.like(f"{business_ref_prefix}%"),
)
.order_by(Job.id.desc())
.first()
)
.order_by(Job.id.desc())
.first()
)
if latest_failed is not None:
rj = (
@@ -1036,16 +1059,24 @@ def _project_fine_grained_pre_stp_blocking(
queued_job = None
if run_no and document_id is not None and draft_version is not None:
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
cache = db.session.info.get('shipping_conversation_projection_read_cache')
prefix_jobs = (
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
if isinstance(cache, dict) else None
)
queued_job = (
db.session.query(Job)
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.status == 'queued',
Job.business_ref.like(f"{business_ref_prefix}%"),
next((job for job in prefix_jobs if str(job.status or '').strip().lower() == 'queued'), 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 == 'queued',
Job.business_ref.like(f"{business_ref_prefix}%"),
)
.order_by(Job.id.desc())
.first()
)
.order_by(Job.id.desc())
.first()
)
_worker_unavailable_hit = False
@@ -426,13 +426,11 @@ def reconcile_and_progress(
expected_case_version: int | None = None,
source_content_hash: str | None = None,
is_admin: bool = False,
legacy_job_id: int | None = None,
replay_mode: bool = False,
) -> ReconcileProgressResult:
"""
统一对账恢复总入口(Q6 reconcile-and-progress API 委托本函数)。
【AI 触发时机】:用户点击「处理重复任务」走自动化恢复、或历史 Job 928/929 的
受权限控制的管理入口、或前端 duplicate_decision_required 裁决后调用。
【AI 触发时机】:用户点击「处理重复任务」走自动化恢复,或前端
duplicate_decision_required 裁决后调用。
核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定):
1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验)
@@ -447,14 +445,9 @@ def reconcile_and_progress(
5. 写审计(fulfillment_audit + CaseEvent 幂等持久化)
6. commit 后触发 auto-progress post-commit 钩子
Phase 4-1 管理端扩展:
• legacy_job_id(int):历史 STP Job 928/929 锚点。管理员仅;必须真实、
必须 domain=shipping_notice、必须 status in {failed, dead}。
• replay_mode(bool):允许 legacy_job_id.reference_key != case_no。
默认 false(防跨 Case 错挂)。
• BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
→ 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
否则返回 outcome=ownership_anomaly_rejected。
BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
→ 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
否则返回 outcome=ownership_anomaly_rejected。
Args:
user_id: 操作人。
@@ -464,8 +457,6 @@ def reconcile_and_progress(
expected_case_version: 前端传来的草稿版本(过期抛 409 VERSION_CONFLICT)。
source_content_hash: 请求快照指纹(用于参数一致性比对)。
is_admin: 是否管理员(force_create 受权限控制)。
legacy_job_id: Phase 4 —— 历史 928/929 Job 锚点(管理员专用)。
replay_mode: Phase 4 —— 允许跨 case_no 重放 legacy_job(管理员专用)。
Returns:
ReconcileProgressResult(公开响应 to_public() 方法)。
@@ -493,61 +484,6 @@ def reconcile_and_progress(
details={'allowed': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']},
)
# [Phase 4 PRE-CHECK-A] replay_mode / legacy_job_id → 必须 admin
if replay_mode and not is_admin:
raise ValidationError(
'replay_mode requires admin',
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
details={'legacy_job_id': legacy_job_id, 'replay_mode': replay_mode},
)
if legacy_job_id is not None and not is_admin:
raise ValidationError(
'legacy_job_id requires admin',
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
details={'legacy_job_id': legacy_job_id},
)
# [Phase 4 PRE-CHECK-B] legacy_job_id 真实性、失败态、domain、reference 对齐
_legacy_job = None
if legacy_job_id is not None:
from app.models import Job, JobType
_legacy_job = db.session.get(Job, int(legacy_job_id))
if _legacy_job is None:
raise ValidationError(
f'legacy_job_id not found: {legacy_job_id}',
code='SHIPPING.REVIEW_CASE_NOT_FOUND',
details={'legacy_job_id': legacy_job_id},
)
if str(_legacy_job.domain or '').strip() != 'shipping_notice':
raise ValidationError(
'legacy_job must be shipping_notice domain',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'legacy_job_id': legacy_job_id, 'domain': str(getattr(_legacy_job, 'domain', None) or '')},
)
if str(getattr(_legacy_job, 'job_type', None) or '') not in {
JobType.SHIPPING_STP_AUTO_CREATE.value,
str(JobType.SHIPPING_STP_AUTO_CREATE.value),
'shipping_stp_auto_create',
}:
# 放宽兼容:允许 SHIPPING_STP_AUTO_CREATE,其它 928/929 类型 fail-closed
pass
if str(_legacy_job.status or '').strip().lower() not in {'failed', 'dead'}:
raise ValidationError(
f'legacy_job must be failed/dead to replay (current status={_legacy_job.status})',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'legacy_job_id': legacy_job_id, 'legacy_status': str(_legacy_job.status or '')},
)
if str(_legacy_job.reference_key or '') != str(case_no).strip() and not replay_mode:
raise ValidationError(
'legacy_job.reference_key mismatches case_no; enable replay_mode to override',
code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT',
details={
'legacy_job_id': legacy_job_id,
'legacy_reference_key': str(_legacy_job.reference_key or ''),
'case_no': str(case_no).strip(),
'replay_mode_required': True,
},
)
# [STEP 1] 加载 Case + 权限校验(短事务内 FOR UPDATE,Q11)
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
@@ -579,12 +515,6 @@ def reconcile_and_progress(
'contract_version': RECOVERY_CONTRACT_VERSION,
'owner_user_id': int(case.owner_user_id),
'document_id': int(case.document_id),
# Phase 4:将 legacy_job 纳入幂等键与审计链,保证 replay/同 operation 不被 Q7 误回返
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
'legacy_job_reference_key': (
str(_legacy_job.reference_key or '') if _legacy_job is not None else None
),
}
# [STEP 2] Q7 幂等校验(返回同 operation_id 第一次结果或抛 409)
@@ -757,8 +687,6 @@ def reconcile_and_progress(
'match_level_steps': match_result.get('match_level_steps'),
'user_action': user_action,
'case_version': case_ver,
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
}
record_fulfillment_audit(
user_id=int(user_id) if user else None,
@@ -1,7 +1,7 @@
"""
backend/app/services/shipping_notice/reference_context.py
用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。
用途:从发货通知任务/事件构建 shipping_notice 专用 reference_context。
依赖:models.ShippingNotice/ShippingTaskEvent、agent_runtime_context.reference。
逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。
"""
@@ -59,7 +59,7 @@ def _task_recency_key(task: ShippingNotice) -> tuple[datetime, int]:
return updated_at, int(getattr(task, "id", 0) or 0)
def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) -> list[ShippingNotice]:
def _collect_focus_task(focus_task: ShippingNotice | None) -> list[ShippingNotice]:
"""
汇总当前 reference_context 可见的任务集合。
@@ -72,9 +72,9 @@ def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) -
def _recent_events(tasks: list[ShippingNotice]) -> list[ShippingTaskEvent]:
"""
查询最近关键事件。
查询当前任务最近关键事件。
核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。
核心逻辑:只取当前任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。
"""
task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None]
if not task_ids:
@@ -210,7 +210,6 @@ def _candidate_refs(tasks: list[ShippingNotice], focus_task_no: str) -> list[dic
def _build_recent_activity_summary(
*,
batch: Any | None,
focus_task_no: str,
last_action_summary: str,
last_failed_summary: str,
@@ -226,8 +225,6 @@ def _build_recent_activity_summary(
pieces.append(last_action_summary)
if focus_task_no:
pieces.append(f"当前 focus 为 {focus_task_no}")
elif _clean_text(getattr(batch, "batch_no", None)):
pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}")
if last_failed_summary:
pieces.append(last_failed_summary)
if len(candidates) > 1:
@@ -243,7 +240,6 @@ def _build_recent_activity_summary(
def build_shipping_reference_context(
*,
batch: Any | None,
focus_task: ShippingNotice | None,
) -> dict[str, Any]:
"""
@@ -252,20 +248,17 @@ def build_shipping_reference_context(
【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时,
Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。
核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target /
核心逻辑:读取当前任务状态和最近少量事件,提炼 focus_object / last_action_target /
last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。
Args:
batch: 当前批次;可为空。
focus_task: 当前焦点任务;可为空。
Returns:
shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。
"""
tasks = _collect_batch_tasks(batch, focus_task)
tasks = _collect_focus_task(focus_task)
focus_task_no = _task_no(focus_task)
if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
focus_task_no = _clean_text(batch.current_focus_task_no).upper()
if not tasks and not focus_task_no:
return {}
@@ -278,7 +271,6 @@ def build_shipping_reference_context(
focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {}
recent_activity_summary = _build_recent_activity_summary(
batch=batch,
focus_task_no=focus_task_no,
last_action_summary=last_action_summary,
last_failed_summary=last_failed_summary,
@@ -34,20 +34,6 @@ def _clean_text(value: Any) -> str:
return str(value or "").strip()
def _batch_no(batch: Any | None, task: ShippingNotice | None) -> str:
"""
获取当前上下文的批次号。
核心逻辑:shipping_batches 已删除;仅保留显式传入 batch 对象的兼容读取。
Returns:
批次号;无法识别时返回空字符串。
"""
if batch and _clean_text(getattr(batch, "batch_no", None)):
return _clean_text(batch.batch_no).upper()
return ""
def _task_no(task: ShippingNotice | None) -> str:
"""
获取当前上下文的任务号。
@@ -66,7 +52,6 @@ def _task_no(task: ShippingNotice | None) -> str:
def _build_refs(
*,
task: ShippingNotice | None,
batch: Any | None,
run_purpose: str | None,
intake_nos: list[str] | None = None,
capability: str | None = None,
@@ -76,11 +61,10 @@ def _build_refs(
"""
构建新版 agent_runtime_context.refs。
核心逻辑:使用稳定业务字段名 task_no/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。
核心逻辑:使用稳定业务字段名 task_no/run_purpose/file_name。
Args:
task: 当前任务。
batch: 当前批次。
run_purpose: 本次 Dify run 的目的。
intake_nos: 点击发送时锁定的 Intake 编号集合。
capability: 当前固定画布能力,如 order_extraction。
@@ -90,13 +74,10 @@ def _build_refs(
"""
refs: dict[str, str] = {}
task_no = _task_no(task)
batch_no = _batch_no(batch, task)
file_name = _clean_text(getattr(task, "source_file_name", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
refs["task_no"] = task_no
if batch_no:
refs["batch_no"] = batch_no
if normalized_run_purpose:
refs["run_purpose"] = normalized_run_purpose
if file_name:
@@ -115,7 +96,7 @@ def _build_refs(
return refs
def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[str, Any]:
def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]:
"""
构建发货通知运行态提示。
@@ -123,7 +104,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st
Args:
task: 当前任务。
batch: 当前批次。
Returns:
状态提示字典。
@@ -132,8 +112,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st
task_no = _task_no(task)
if task_no:
state_hint["focus_task_no"] = task_no
elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper()
if task is not None:
for attr, key in (
@@ -147,26 +125,21 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st
if value:
state_hint[key] = value
batch_no = _batch_no(batch, task)
if batch_no:
state_hint["batch_no"] = batch_no
return state_hint
def _build_summary(
*,
task: ShippingNotice | None,
batch: Any | None,
run_purpose: str | None,
) -> str:
"""
构建给 Dify 阅读的短摘要。
核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。
核心逻辑:用自然语言说明当前 run 的任务、文件和状态,避免 Dify 依赖 conversation memory 猜现场。
Args:
task: 当前任务。
batch: 当前批次。
run_purpose: 本次 Dify run 的目的。
Returns:
@@ -174,14 +147,11 @@ def _build_summary(
"""
pieces: list[str] = []
task_no = _task_no(task)
batch_no = _batch_no(batch, task)
file_name = _clean_text(getattr(task, "source_file_name", None))
current_step = _clean_text(getattr(task, "current_step", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
pieces.append(f"当前任务 {task_no}")
if batch_no:
pieces.append(f"属于批次 {batch_no}")
if file_name:
pieces.append(f"来源文件 {file_name}")
if normalized_run_purpose:
@@ -189,7 +159,7 @@ def _build_summary(
if current_step:
pieces.append(f"当前步骤 {current_step}")
if not pieces:
return "当前为货代发货通知 Agent 会话,尚未解析出明确任务或批次锚点。"
return "当前为货代发货通知 Agent 会话,尚未解析出明确任务锚点。"
return ",".join(pieces) + "。"
@@ -197,7 +167,6 @@ def build_shipping_runtime_context(
*,
session_id: str,
task: ShippingNotice | None = None,
batch: Any | None = None,
trigger_source: str | None = None,
request_id: str | None = None,
locale: str | None = None,
@@ -211,13 +180,12 @@ def build_shipping_runtime_context(
"""
构建货代发货通知 Agent 的 agent_runtime_context。
核心逻辑:以 HXOPS DB 中的 task/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot,
核心逻辑:以 HXOPS DB 中的 task 为事实源,生成 refs/domain.state_hint/reference_context snapshot,
供 Dify 每次 run 显式识别现场。
Args:
session_id: HXOPS 本地 ChatSession.session_id。
task: 当前显式任务;禁止在本函数内按会话猜测。
batch: 当前批次。
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
request_id: 本次请求 ID。
locale: 用户语言。
@@ -233,14 +201,11 @@ def build_shipping_runtime_context(
"""
domain = {
"type": SHIPPING_NOTICE_AGENT_CODE,
"summary": _build_summary(task=task, batch=batch, run_purpose=run_purpose),
"state_hint": _build_state_hint(task, batch),
"summary": _build_summary(task=task, run_purpose=run_purpose),
"state_hint": _build_state_hint(task),
"available_actions_hint": [],
}
reference_context = build_shipping_reference_context(
batch=batch,
focus_task=task,
)
reference_context = build_shipping_reference_context(focus_task=task)
return build_agent_runtime_context(
agent_code=SHIPPING_NOTICE_AGENT_CODE,
scope=scope,
@@ -250,7 +215,6 @@ def build_shipping_runtime_context(
locale=locale,
refs=_build_refs(
task=task,
batch=batch,
run_purpose=run_purpose,
intake_nos=intake_nos,
capability=capability,
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,7 @@
"""
services/shipping_notice/shipping_turn_context.py
用途:货代 Chat Turn 领域上下文解析(task_no / batch_no 等 refs 键名约定)。
用途:货代 Chat Turn 领域上下文解析(task_no refs 键名约定)。
依赖:turn_context.TurnContext。
逻辑:chat_action_handlers 通过本模块解析货代专属锚点;平台 turn_context 不感知这些键名。
"""
@@ -14,12 +14,9 @@ from app.services.chat.turn_context import TurnContext
# 与 agent_runtime_context.refs 及前端 shipping 上下文对齐的键名约定。
SHIPPING_REF_TASK_NO = "task_no"
SHIPPING_REF_BATCH_NO = "batch_no"
_TASK_PAYLOAD_KEYS = ("task_no", "taskNo", "task_id", "taskId")
_TASK_REF_KEYS = (SHIPPING_REF_TASK_NO, "taskNo", "task_id", "taskId")
_BATCH_PAYLOAD_KEYS = ("batch_no", "batchNo")
_BATCH_REF_KEYS = (SHIPPING_REF_BATCH_NO, "batchNo")
def _first_non_empty(values: tuple[str, ...]) -> str:
@@ -57,19 +54,3 @@ def resolve_shipping_task_no(ctx: TurnContext) -> str:
from_refs = _first_non_empty(tuple(ctx.refs.get(key, "") for key in _TASK_REF_KEYS)).upper()
return from_refs
def resolve_shipping_batch_no(ctx: TurnContext) -> str:
"""
从 action payload 或 session refs 解析货代批次编号。
Args:
ctx: 当前 Chat Turn 上下文。
Returns:
batch_no 文本;无法解析时返回空串。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
from_payload = _read_payload_str(payload, *_BATCH_PAYLOAD_KEYS)
if from_payload:
return from_payload
return _first_non_empty(tuple(ctx.refs.get(key, "") for key in _BATCH_REF_KEYS))
@@ -3,7 +3,7 @@ services/shipping_notice/shipping_turn_helpers.py
用途:货代 Chat Turn handler 共用的 SSE 事件构造与 UI State 回写。
依赖:action_schema.TurnEvent、ui_state、query_service。
逻辑:chat_action_handlers 与 chat_action_extended_handlers 复用本模块,避免重复 yield 逻辑。
逻辑:Chat Turn handler 复用本模块,避免重复 yield 逻辑。
"""
from __future__ import annotations
@@ -11,8 +11,7 @@ from __future__ import annotations
from typing import Any, Iterator
from app.services.chat.action_schema import TurnEvent
from app.services.shipping_notice.query_service import get_batch_for_user
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
from app.services.shipping_notice.ui_state import build_task_ui_state
def stream_text_events(
@@ -46,43 +45,18 @@ def stream_text_events(
def shipping_task_ui_state_event(task) -> TurnEvent:
"""单票任务 ui_state.updated 事件。"""
ui_state = build_task_ui_state(task)
batch_no = None
return TurnEvent(
event="ui_state.updated",
data={
"domain": "shipping",
"task_no": task.task_no,
"batch_no": batch_no,
"payload": {
"task_no": task.task_no,
"batch_no": batch_no,
"ui_state": ui_state,
},
},
)
def shipping_batch_ui_state_event(batch_no: str, user_id: int) -> TurnEvent | None:
"""批次级 ui_state.updated 事件。"""
batch = get_batch_for_user(batch_no, user_id)
if batch is None:
return None
batch_state = build_batch_ui_state(batch)
focus_task_no = str(batch_state.get("current_focus_task_no") or "").strip()
return TurnEvent(
event="ui_state.updated",
data={
"domain": "shipping",
"batch_no": batch_no,
"task_no": focus_task_no or None,
"payload": {
"batch_no": batch_no,
"batch_ui_state": batch_state,
"task_no": focus_task_no or None,
},
},
)
def tool_result_message(result: dict[str, Any]) -> str:
return str(result.get("message") or "").strip()
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_candidate_reconciliation.py
用途:将 Candidate 订单行对账到既有 Task(字段级自动补齐 / 冲突落库)。
依赖:po_number、reservation_id、动态订单 FieldValue、task_field_conflict_service、state_machine。
逻辑:batch_from_intakes / open_existing 路径调用;仅安全态任务可自动补齐。
逻辑:open_existing 对账路径调用;仅安全态任务可自动补齐。
"""
from __future__ import annotations
File diff suppressed because it is too large. Load diff
@@ -21,7 +21,6 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingNotice
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.constants import CP_TASK_EXISTS
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.task_order_field_editor import (
@@ -37,12 +36,9 @@ from app.services.shipping_notice.reservation_gate import task_reservation_gate_
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.query_service import (
TaskProjection,
compute_batch_process_summary,
extract_task_no_from_text,
get_task_by_ref,
list_sorted_batch_tasks,
resolve_task_from_payload,
serialize_batch_for_tool,
serialize_task as qs_serialize_task,
serialize_task_for_tool,
)
@@ -53,14 +49,7 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.batch_create_idempotency import (
acquire_notice_create_locks,
assert_idempotent_batch_content_matches,
assert_no_exact_duplicate_notices,
build_existing_batch_tool_response,
compute_notice_items_content_fingerprint,
dedupe_notice_items_by_content_hash,
find_batch_by_create_idempotency,
handle_batch_create_integrity_error,
normalize_create_idempotency_key,
)
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.candidate_qualification_service import (
@@ -95,46 +84,6 @@ def start_task_orchestrator(task_no: str | None) -> bool:
return _start(task_no)
def recompute_batch_summary(batch: Any | None) -> None:
"""写路径:shipping_batches 已删除(co8),保留空操作供历史调用方兼容。"""
del batch
def sync_batch_after_task_change(task: ShippingNotice | None) -> None:
"""任务状态变更后刷新所属批次;shipping_batches 已删除,无操作。"""
del task
def create_batch(payload: dict[str, Any]) -> tuple[Any, bool]:
"""
创建或复用发货批次壳(不含 notice 解析)。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。
"""
del payload
raise_shipping_batches_removed(action='tools.create_batch')
def _create_single_task_batch(payload: dict[str, Any]) -> Any:
"""为单票任务创建标准批次容器;shipping_batches 已删除。"""
del payload
raise_shipping_batches_removed(action='tools.create_single_task_batch')
def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
"""
一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
Raises:
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。
"""
del payload
raise_shipping_batches_removed(action='tools.create_batch_tasks')
def create_task(payload: dict[str, Any]) -> dict[str, Any]:
"""
创建单个发货任务,或复用当前会话里已存在的进行中任务。
@@ -793,7 +742,6 @@ def replace_task_notice(
extra={"warnings": cleaned_warnings},
)
log_task_event(task, "notice_replace_extract_failed", {"warnings": cleaned_warnings})
sync_batch_after_task_change(task)
db.session.commit()
return tool_response(
status="needs_human",
@@ -834,7 +782,6 @@ def replace_task_notice(
"warnings": cleaned_warnings,
},
)
sync_batch_after_task_change(task)
db.session.commit()
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -1046,7 +993,6 @@ def _commit_notice_edit(
before_export_file_name=before_export_file_name,
before_order_data_version=before_order_data_version,
)
sync_batch_after_task_change(task)
db.session.commit()
return tool_response(
status="ok",
@@ -1450,7 +1396,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)},
source=event_source,
)
sync_batch_after_task_change(task)
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
@@ -19,7 +19,6 @@ from flask import current_app
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
@@ -267,12 +266,6 @@ def _clean_event_value(value: Any) -> str:
return str(value or "").strip()
def _task_batch_no(task: ShippingNotice | None) -> str:
"""从任务关系中提取批次号。"""
batch = getattr(task, "batch", None)
return _clean_event_value(getattr(batch, "batch_no", None))
def build_task_action_event_detail(
task: ShippingNotice,
*,
@@ -284,7 +277,7 @@ def build_task_action_event_detail(
"""
构建任务动作类事件详情。
核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。
核心逻辑:统一补齐 action/source/target/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。
Args:
task: 动作作用的目标任务。
@@ -301,7 +294,6 @@ def build_task_action_event_detail(
"source": _clean_event_value(source),
"target_type": "task",
"target_id": _clean_event_value(getattr(task, "task_no", None)),
"batch_no": _task_batch_no(task),
"conversation_id": _clean_event_value(getattr(task, "conversation_id", None)),
}
normalized_comment = _clean_event_value(comment)
@@ -588,21 +580,3 @@ def log_task_action_event(
)
def switch_batch_focus(
batch: Any,
task: ShippingNotice,
*,
source: str,
event_type: str = "focus_switched",
comment: str | None = None,
emit_when_unchanged: bool = True,
extra: dict[str, Any] | None = None,
) -> bool:
"""
切换批次焦点任务并写入标准事件。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del batch, task, source, event_type, comment, emit_when_unchanged, extra
raise_shipping_batches_removed()
@@ -93,7 +93,7 @@ def tool_response(
Args:
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
extra: 需要保留在顶层的兼容字段,例如 batch_no。
extra: 需要保留在顶层的额外业务字段。
"""
from app.services.shipping_notice.state_machine import resolve_task_ui_state
@@ -17,9 +17,7 @@ from app.services.shipping_notice import (
from app.services.shipping_notice import customer_identity_gate
# 任务 / 批次 / 决策
create_batch = task_workflow.create_batch
create_batch_tasks = task_workflow.create_batch_tasks
# 任务 / 决策
create_task = task_workflow.create_task
auto_progress = task_workflow.auto_progress
submit_decision = task_workflow.submit_decision
+12 -144
View File
@@ -1,7 +1,7 @@
"""
services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
@@ -10,7 +10,6 @@ services/shipping_notice/ui_state.py
stp_facts、progress_nodes);
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
"""
from __future__ import annotations
@@ -18,7 +17,6 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingNotice
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.constants import (
CP_COMPLETED,
CP_CUSTOMER_REVIEW,
@@ -53,13 +51,7 @@ from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import (
compute_batch_process_summary,
list_sorted_batch_tasks,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_summary,
)
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
from app.services.shipping_notice.state_machine import (
CheckpointKind,
resolve_task_ui_state,
@@ -75,38 +67,6 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
"step1_notice_submit": 0,
"step2_parse_confirm": 1,
"step3_inventory_prepare": 2,
"step2_inventory_prepare": 2,
"step4_align_confirm": 3,
"step5_match_inventory": 4,
"step3_inventory_match": 4,
"step4_shortage_review": 4,
"step6_generate_file": 5,
"step5_export_excel": 5,
"step7_upload_freight": 6,
"step6_upload_freight": 6,
"step7_finish": 6,
}
_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_CUSTOMER_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
}
_REVIEW_ENTRY_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
@@ -136,41 +96,11 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
}
# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
CP_CUSTOMER_REVIEW: "order_review",
CP_ORDER_FREEZE: "order_review",
CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep",
CP_INVENTORY_PENDING: "fulfillment_prep",
CP_READY_MATCH: "fulfillment_prep",
RS_SHORTAGE_REVIEW: "fulfillment_prep",
CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "freight_upload",
CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "freight_upload",
CP_UPLOAD_RESULT_UNKNOWN: "freight_upload",
CP_UPLOADED: "freight_upload",
CP_COMPLETED: "freight_upload",
CP_REJECTED: "order_review",
}
def _task_lifecycle(
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。"""
"""以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。"""
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
if legacy_stage is None:
legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
if legacy_stage is None:
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
legacy_index = _derive_current_step_index(task)
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index]
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return project_lifecycle(
@@ -180,7 +110,6 @@ def _task_lifecycle(
if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code')
else None
),
legacy_stage=legacy_stage,
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
has_candidate_context=True,
verified_upload_success=has_verified_upload_success(task),
@@ -188,9 +117,11 @@ def _task_lifecycle(
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
"""将共享生命周期结果包装为任务详情既有的阶段 DTO。"""
stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse')
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0)
"""将共享生命周期结果包装为任务详情阶段 DTO;无正式事实时不猜阶段。"""
stage_code = str(lifecycle.get('lifecycle_stage') or '')
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), None)
if index is None:
return {'code': 'unclassified', 'label': '状态待同步', 'index': 0, 'total': len(LIFECYCLE_STAGES)}
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
@@ -251,47 +182,6 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]:
return {"primary": primary, "secondary": secondary}
def _derive_current_step_index(task: ShippingNotice) -> int:
"""
根据任务领域事实推导五阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
legacy_index = _CURRENT_STEP_INDEX_MAP[current_step]
return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}:
return 3
if upload_status in {"pending", "uploading", "failed"} or has_export:
return 2
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
return 2
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 2
if task.inventory_lines_json or match_status:
return 2
if pending_reason in {
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
if review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
return 1
return 0
def build_shipping_workflow_steps(
task: ShippingNotice,
checkpoint: str | None,
@@ -308,34 +198,22 @@ def build_shipping_workflow_steps(
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
None,
)
# 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
# 五阶段只使用共享生命周期裁决;缺少正式事实时全部保持 pending。
current_index = lifecycle_index
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
# ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让
# 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。
if lifecycle_stage == "upload_complete":
status = "completed"
elif current_index is None:
status = "pending"
elif index < current_index:
status = "completed"
elif index == current_index:
status = "current"
else:
status = "pending"
inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
parse_blocked = index == 1 and (
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ}
)
prep_blocked = index == 2 and (
checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW}
or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE}
)
upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -986,7 +864,6 @@ def build_task_ui_state(
}
return {
"task_no": task.task_no,
"batch_no": None,
"stage": stage,
"lifecycle_stage": stage["code"],
"lifecycle_entries": lifecycle['lifecycle_entries'],
@@ -1053,12 +930,3 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
)
def build_batch_ui_state(batch: Any) -> dict[str, Any]:
"""
构建批次级会话上传集合摘要(非履约写操作面)。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del batch
raise_shipping_batches_removed()
@@ -0,0 +1,67 @@
"""移除已下线 APX 自动推进运行时。
用途:收口遗留 APX Execution/Job 并删除仅服务旧六门禁运行时的唯一索引。
依赖:shipping_process_executions、shipping_process_gates、jobs。
逻辑:正式 20-Gate 是唯一运行态;迁移只终止 APX 记录,绝不改写正式 Execution、STP、Excel 或 RPA Job。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'hm6n7o8p9q0r'
down_revision = 'hk5l6m7n8o9p'
branch_labels = None
depends_on = None
def _indexes(table: str) -> set[str]:
"""读取索引名,保证不同环境重复升级安全。"""
return {str(item.get('name') or '') for item in sa.inspect(op.get_bind()).get_indexes(table)}
def upgrade() -> None:
"""终态化 APX 旧运行记录,再删除旧类型唯一索引。"""
bind = op.get_bind()
bind.execute(sa.text("""
UPDATE jobs
SET status = 'cancelled', finished_at = COALESCE(finished_at, CURRENT_TIMESTAMP),
message = 'legacy APX auto-progress runtime removed'
WHERE domain = 'shipping_notice'
AND job_type = 'shipping_auto_progress'
AND status IN ('queued', 'running', 'active')
"""))
bind.execute(sa.text("""
UPDATE shipping_process_gates
SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP
WHERE execution_id IN (
SELECT id FROM shipping_process_executions WHERE execution_no LIKE 'APX-%'
)
AND status IN ('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated')
"""))
bind.execute(sa.text("""
UPDATE shipping_process_executions
SET status = 'superseded', updated_at = CURRENT_TIMESTAMP
WHERE execution_no LIKE 'APX-%'
AND status IN ('active', 'blocked', 'waiting_external')
"""))
if 'uq_jobs_shipping_auto_progress_one_active_task' in _indexes('jobs'):
op.drop_index('uq_jobs_shipping_auto_progress_one_active_task', table_name='jobs')
def downgrade() -> None:
"""仅恢复旧索引定义;已终态化的 APX 记录不应被自动复活。"""
if 'uq_jobs_shipping_auto_progress_one_active_task' not in _indexes('jobs'):
op.create_index(
'uq_jobs_shipping_auto_progress_one_active_task', 'jobs', ['task_id'], unique=True,
postgresql_where=sa.text(
"domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') AND task_id IS NOT NULL"
),
sqlite_where=sa.text(
"domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' "
"AND status IN ('queued', 'running') AND task_id IS NOT NULL"
),
)
@@ -1,25 +0,0 @@
"""
只读清点目标数据库中的 APX 运行态。
用法:在目标环境加载现有环境变量后执行 `python scripts/audit_apx_runtime_state.py`。
本脚本只执行查询并输出 JSON,不迁移、不取消、不删除任何记录。
"""
from __future__ import annotations
import json
from app import create_app
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
def main() -> None:
"""加载生产配置并输出 APX 只读清点结果。"""
app = create_app()
with app.app_context():
print(json.dumps(audit_apx_runtime_state(), ensure_ascii=False, indent=2, sort_keys=True))
if __name__ == '__main__':
main()
+1 -1
View File
@@ -36,7 +36,7 @@ def test_handler_error_rolls_back_before_mark_failed(monkeypatch):
class _Db:
session = _Session()
job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}}
job = {'id': 939, 'job_type': 'shipping_process_gate', 'attempts': 1, 'payload': {}}
monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job)
monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed')))
monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration)))
@@ -1,8 +1,8 @@
"""
tests/services/shipping_notice/test_reconciliation_phase34_contract.py
用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 +
BRANCH F ownership_anomaly rollback 的合同测试。
用途:Phase 3 统一 Projection 四事实 + Phase 4 BRANCH F
ownership_anomaly rollback 的合同测试。
依赖:recovery_contract、reconciliation_projector、
reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。
逻辑:
@@ -14,9 +14,6 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py
retryable/failed/running/idle)。
[P3 T4] project_case_primary_action 1a~1i CTA 分派矩阵。
[P3 T5] project_review_case_projection_bundle 六字段非空(Case + automation + actions)。
[P4 T6] reconcile_and_progress PRE-CHECK:
a) replay_mode=True + is_admin=False → SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED 422
b) legacy_job_id=999 + is_admin=False → 422
[P4 T7] ownership_anomaly BRANCH F:
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
(这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。
@@ -287,7 +284,7 @@ def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation(
# ============================================================
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
# [P4] BRANCH F 归属异常(通过 monkeypatch 替换锁 DB 查询)
# ============================================================
def _mock_case_for_p4(case_no='CASE-2608-0042'):
@@ -372,72 +369,6 @@ def _install_minimal_mocks(monkeypatch, case=None, app=None):
return case
@pytest.mark.pure_unit
def test_p4_t6a_replay_mode_without_admin_raises(monkeypatch):
"""[P4 T6a] replay_mode=True + is_admin=False → 422 SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
replay_mode=True,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6b_legacy_job_id_without_admin_raises(monkeypatch):
"""[P4 T6b] legacy_job_id=928 + is_admin=False → 422 权限拒绝。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
legacy_job_id=928,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
"""[P4 T6c] legacy_job 必须是 failed/dead,否则 422。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
bad_job = _fake_job(job_id=991, status='running') # 不是失败态
from app.services.shipping_notice import reconciliation_service as mod
def _get(coll, jid): # noqa: ARG001
if str(getattr(coll, '__name__', '')) == 'Job' and jid == 991:
return bad_job
return None
monkeypatch.setattr(mod.db.session, 'get', _get)
with pytest.raises(ValidationError):
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=True,
legacy_job_id=991,
)
# ============================================================
# [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段)
# ============================================================
@@ -26,7 +26,6 @@ def test_shipping_handler_builds_ui_state_event(app):
external_conversation_id=None,
request_id='req-1',
shipping_task_id='SN-TEST-001',
shipping_batch_no='SB-TEST',
)
event = handler.build_ui_state_event(ctx)
assert event is None or event.get('event') == 'shipping_ui_state'
+7 -123
View File
@@ -63,21 +63,11 @@ def _create_task_for_user(user_id: int) -> str:
return task.task_no
def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch):
def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
monkeypatch.setattr(
"app.services.shipping_notice.chat_action_handlers.submit_decision",
lambda payload: {
"status": "ok",
"message": "已确认,请继续下一步。",
"task_id": task_no,
"data": {},
},
)
res = client.post(
"/api/chat/turns/stream",
headers={
@@ -99,14 +89,8 @@ def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch)
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "step.started" in event_names
assert "message.completed" in event_names or "message_end" in event_names
assert "run.completed" in event_names
logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
assert len(logs) == 1
assert logs[0].query == "确认"
assert "已确认" in logs[0].answer
assert "run.failed" in event_names
assert "run.completed" not in event_names
def test_chat_turn_unknown_action_returns_failed(app, client):
@@ -154,11 +138,11 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_path):
def test_chat_turn_multipart_upload_rejects_removed_batch_action(app, client, tmp_path):
"""
multipart 上传时 agent_id 应从 form 字段解析;create_batch_from_notices 已下线为 410。
multipart 上传时 agent_id 应从 form 字段解析;旧建批 action 不再注册。
关键断言:form 带 agent_id 时 run 能启动;建批动作固定 BATCHES_REMOVED(非 agent 解析失败)。
关键断言:form 带 agent_id 时 run 能启动;旧 action 作为未知 action 失败。
"""
from io import BytesIO
@@ -191,8 +175,7 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_pa
assert "run.failed" in event_names
assert "run.completed" not in event_names
failed = next(item for item in events if item.get("event") == "run.failed")
# 关键断言:SSE run.failed 顶层带业务 code(非嵌套 data)。
assert failed.get("code") == "SHIPPING.BATCHES_REMOVED"
assert failed.get("code") == "RESOURCE.NOT_FOUND"
def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch):
@@ -239,102 +222,3 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie
assert all('schema_preview' not in payload for payload in assistant_payloads)
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
captured: dict = {}
def fake_create(**kwargs):
captured.update(kwargs)
return {
"status": "ok",
"batch_no": "SB-CHAT-IDEM-001",
"data": {
"tasks": [{"task_id": "SN-CHAT-IDEM-001"}],
"focus_task": {"task_no": "SN-CHAT-IDEM-001"},
},
}
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
fake_create,
)
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role},
data={
"agent_id": str(agent.id),
"input": json.dumps(
{
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {"idempotency_key": "chat-idem-001"},
},
ensure_ascii=False,
),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
},
content_type="multipart/form-data",
)
assert res.status_code == 200
res.get_data(as_text=True)
assert captured.get("create_idempotency_key") == "chat-idem-001"
notice_items = captured.get("notice_items") or []
assert notice_items
assert notice_items[0].get("source_content_hash")
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
"""相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
orchestrator_calls: list[str] = []
monkeypatch.setattr(
"app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator",
lambda batch_no: orchestrator_calls.append(batch_no) or True,
)
payload_input = {
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {"idempotency_key": "chat-replay-integration-001"},
}
headers = {"X-Username": user.username, "X-Role": user.role}
raw = "客户:ACME\nA001 x 10".encode("utf-8")
def _post_turn():
return client.post(
"/api/chat/turns/stream",
headers=headers,
data={
"agent_id": str(agent.id),
"input": json.dumps(payload_input, ensure_ascii=False),
"files": (BytesIO(raw), "notice.txt"),
},
content_type="multipart/form-data",
)
first = _post_turn()
assert first.status_code == 200
first_events = _parse_sse_events(first.get_data(as_text=True))
assert "run.failed" not in [item.get("event") for item in first_events]
second = _post_turn()
assert second.status_code == 200
second_events = _parse_sse_events(second.get_data(as_text=True))
completed = [item for item in second_events if item.get("event") == "message.completed"]
assert completed
assert "已恢复此前创建的批次" in str(completed[-1].get("content", ""))
assert len(orchestrator_calls) == 1
+154 -1
View File
@@ -6,6 +6,8 @@
from __future__ import annotations
import pytest
from app.services.shipping_notice.email_allocation_table_parser import (
parse_email_allocation_tables,
parse_email_allocation_text,
@@ -87,6 +89,19 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header(
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_uses_schema_alias_order_for_duplicate_source_headers():
"""同字段的两个邮件列按 Schema aliases 顺序取值,不能整表拒绝。"""
supplement = parse_email_allocation_tables(
content_hash='h' * 64,
schema_definition=SCHEMA,
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Source Type</th><th>hub code</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>FIRST-SOURCE</td><td>SECOND-HUB</td></tr></table>'''],
)
assert supplement['issues'] == []
assert supplement['rows'][0]['inventory_source_hint'] == 'FIRST-SOURCE'
assert supplement['rows'][0]['evidence']['inventory_source_hint']['column_index'] == 2
def test_email_supplement_ampn_alias_matches_customer_part_number():
"""邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。"""
order = _order()
@@ -139,7 +154,41 @@ def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pic
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)[0]
assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields'])
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
finding = next(item for item in merged['conflicts'] if item.get('field') == 'reservation_id')
assert finding['resolution_status'] == 'unresolved'
assert finding['scope'] == 'line'
assert finding['line_index'] == 0
assert finding['conflict_key'] == '0:reservation_id'
assert finding['values'] == ['33874', '33875']
assert [source['source_type'] for source in finding['sources']] == ['email_body', 'email_body']
@pytest.mark.pure_unit
def test_email_supplement_does_not_cross_compare_values_from_different_part_lines():
"""同 PO 的不同料号可有不同单价,补充合并只能比较同一目标行的关联正文行。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{'value': '10.00'}]})
order['lines'].append({'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
{'field_id': 'qty', 'observations': [{'value': 1}]},
{'field_id': 'unit-price', 'observations': [{'value': '20.00'}]},
]})
result = merge_email_supplements(
orders=[order],
supplements_by_intake={1: {'document_id': 304, 'rows': [
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '10.00', 'evidence': {}},
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000003', 'unit_price': '20.00', 'evidence': {}},
]}},
schema_definition=schema,
)[0]
assert not any(item.get('field') == 'unit_price' for item in result['conflicts'])
def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
@@ -166,6 +215,110 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
@pytest.mark.pure_unit
def test_email_supplement_treats_decimal_format_variants_as_the_same_value():
"""PDF 与邮件的金额仅格式不同,必须按 Schema decimal 语义比较而非制造冲突。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{'value': '1731.6'}],
})
supplement = {
'document_id': 44,
'rows': [{
'customer_po_number': '4518738152',
'part_number': 'D4-A08AR12000002',
'unit_price': '1,731.60',
'evidence': {},
}],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema,
)[0]
assert _value(merged['lines'][0]['fields'], 'unit-price') == '1731.6'
assert not any(item.get('field') == 'unit_price' for item in merged['conflicts'])
@pytest.mark.pure_unit
def test_email_supplement_decimal_difference_creates_a_complete_unresolved_finding():
"""真实金额不一致必须保留双方原值、规范值和邮件单元格证据,供复核直接裁决。"""
schema = {
'version': 'shipping-order-schema.v9',
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{
'value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'},
}],
})
supplement = {
'document_id': 304,
'rows': [{
'customer_po_number': '4518738152',
'part_number': 'D4-A08AR12000002',
'unit_price': '1732.00',
'evidence': {'unit_price': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}},
}],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema,
)[0]
finding = next(item for item in merged['conflicts'] if item.get('field') == 'unit_price')
assert finding['conflict_key'] == '0:unit_price'
assert finding['severity'] == 'blocking'
assert finding['resolution_status'] == 'unresolved'
assert finding['scope'] == 'line'
assert finding['line_index'] == 0
assert finding['values'] == ['1731.60', '1732.00']
assert finding['sources'] == [
{
'source_type': 'pdf', 'raw_value': '1731.60', 'canonical_value': '1731.60',
'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'},
},
{
'source_type': 'email_body', 'raw_value': '1732.00', 'canonical_value': '1732.00',
'document_id': 304,
'evidence_ref': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'},
},
]
assert finding['rule_version'] == 'shipping-order-schema.v9'
@pytest.mark.pure_unit
def test_email_supplement_duplicate_email_decimal_formats_do_not_create_a_conflict():
"""同一邮件补充行的等价金额格式必须按 decimal 归并,不能产生正文内部冲突。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
result = merge_email_supplements(
orders=[_order()],
supplements_by_intake={1: {'document_id': 304, 'rows': [
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1731.6', 'evidence': {}},
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1,731.60', 'evidence': {}},
]}},
schema_definition=schema,
)[0]
assert _value(result['lines'][0]['fields'], 'unit-price') == '1731.6'
assert not any(item.get('field') == 'unit_price' for item in result['conflicts'])
def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers():
"""邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。"""
scenarios = [
@@ -0,0 +1,108 @@
"""
tests/test_legacy_supplement_conflict_reassessment.py
用途:验证旧补充冲突不会被静默放行,而会升级为有稳定键的证据不足 Finding。
依赖:legacy_supplement_conflict_reassessment_service、pytest。
逻辑:纯函数层覆盖旧结构升级、非旧 Finding 保留以及重复旧记录收敛。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import (
reassess_legacy_supplement_conflicts_from_frozen_order,
upgrade_legacy_supplement_conflicts,
)
from tests.test_email_supplement_merge import SCHEMA, _order
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_keeps_blocking_but_makes_recovery_visible():
"""旧 `{field, reason}` 不能被直接清除,须变为可展示的证据不足 Finding。"""
upgraded, count = upgrade_legacy_supplement_conflicts([{
'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price',
}])
assert count == 1
assert upgraded == [{
'conflict_key': '-1:unit_price', 'severity': 'blocking',
'reason': 'supplement_conflict_evidence_insufficient', 'resolution_status': 'unresolved',
'field': 'unit_price', 'scope': 'unscoped', 'line_index': None,
'values': [], 'sources': [], 'rule_version': 'legacy-supplement-conflict.v1',
'legacy_reason': 'supplement_field_conflict', 'recovery_action': 'reparse_current_pdf',
}]
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_does_not_touch_complete_current_finding():
"""已有新 Finding 的证据与裁决状态不可被历史迁移覆盖。"""
current = {
'conflict_key': '0:unit_price', 'severity': 'blocking',
'reason': 'supplement_field_conflict', 'resolution_status': 'unresolved',
'field': 'unit_price', 'values': ['1', '2'], 'sources': [{'source_type': 'pdf'}],
}
upgraded, count = upgrade_legacy_supplement_conflicts([current])
assert count == 0
assert upgraded == [current]
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_collapses_duplicate_legacy_identity():
"""同字段重复旧阻断升级后只有一项,避免一次操作产生多个不可裁决卡片。"""
upgraded, count = upgrade_legacy_supplement_conflicts([
{'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'},
{'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'},
])
assert count == 2
assert len(upgraded) == 1
@pytest.mark.pure_unit
def test_reassess_legacy_conflict_from_frozen_order_clears_decimal_format_false_positive():
"""冻结证据可恢复时,1731.6 与 1,731.60 必须按当前 decimal 规则清除旧假冲突。"""
schema = {'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
]}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{'value': '1731.6'}],
})
conflicts, status, count = reassess_legacy_supplement_conflicts_from_frozen_order(
candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}],
frozen_order=order,
supplements_by_intake={1: {'document_id': 304, 'rows': [{
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
'unit_price': '1,731.60', 'evidence': {},
}]}},
schema_definition=schema,
)
assert status == 'rebuilt'
assert count == 1
assert conflicts == []
@pytest.mark.pure_unit
def test_reassess_legacy_conflict_from_frozen_order_rebuilds_real_conflict_with_evidence():
"""冻结证据可恢复时,真实金额差异必须变为当前完整 Finding,而不是笼统旧阻断。"""
schema = {'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
]}
order = _order()
order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{
'value': '10.00', 'document_id': 305, 'evidence_ref': {'page_no': 1},
}]})
conflicts, status, _ = reassess_legacy_supplement_conflicts_from_frozen_order(
candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}],
frozen_order=order,
supplements_by_intake={1: {'document_id': 304, 'rows': [{
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
'unit_price': '11.00', 'evidence': {'unit_price': {'row_index': 1}},
}]}},
schema_definition=schema,
)
assert status == 'rebuilt'
assert conflicts[0]['conflict_key'] == '0:unit_price'
assert [source['document_id'] for source in conflicts[0]['sources']] == [305, 304]
@@ -250,3 +250,30 @@ def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch):
assert calls['confirm'] == 0
assert out['post_ot_wave'] is True
assert out['wave_progress']['wave_no'] == 3
def test_post_ot_api_rejects_pre_ot_wave_without_legacy_fallback(app, monkeypatch):
"""无正式 OT 时必须拒绝,不能回落到历史建波/自动推进链路。"""
from app.api.workspace import shipping_notice as api
from app.core.errors import ValidationError
with app.app_context():
with app.test_request_context(
'/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave',
method='POST',
json={'line_keys': ['L1'], 'idempotency_key': 'k1'},
):
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1))
monkeypatch.setattr(
'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit',
lambda **_k: SimpleNamespace(id=1, case_no='RC-9'),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
lambda _c: {'has_formal_ot': False},
)
with pytest.raises(ValidationError, match='formal order task') as exc:
api.workspace_create_shipping_order_review_fulfillment_wave('RC-9')
assert exc.value.code == 'SHIPPING.FORMAL_OT_REQUIRED'
@@ -21,9 +21,7 @@ from app.models import (
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.auto_progress_controller import (
AUTO_PROGRESS_GATE_CODES,
determine_formal_start_gate,
run_auto_progress_job,
submit_auto_progress,
)
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
@@ -80,38 +78,21 @@ def test_submit_creates_formal_execution_for_task_without_case(app):
assert len(gate_codes) == 20
assert gate_codes[0] == 'document_materialization'
assert gate_codes[-1] == 'manual_upload_handoff'
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate'
def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app):
"""同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。"""
def test_submit_reuses_formal_case_execution(app):
"""同一 Task 已有正式 Case Execution 时必须复用该 20-Gate 链。"""
task = _task_with_candidate()
formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id))
duplicate = ShippingProcessExecution(
execution_no='APX-DUPLICATE', task_id=int(task.id),
candidate_set_id=task.active_inventory_candidate_set_id,
execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0],
lock_version=1,
)
db.session.add(duplicate)
db.session.flush()
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
db.session.add(ShippingProcessGate(
execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no,
status='pending', evaluation_version=1, lock_version=1,
))
task.active_process_execution_id = int(duplicate.id)
task.active_process_execution_id = int(formal.id)
db.session.commit()
result = submit_auto_progress(task=task, trigger='user_retry')
db.session.refresh(task)
db.session.refresh(duplicate)
assert result['execution_id'] == formal.id
assert task.active_process_execution_id == formal.id
assert duplicate.status == 'superseded'
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
def test_formal_execution_queues_one_gate_attempt_job(app):
@@ -202,66 +183,3 @@ def test_active_stp_job_without_retry_metadata_is_reused(app):
assert result['retry_of_job_id'] is None
def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app):
"""历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。"""
task = _task_with_candidate()
legacy = ShippingProcessExecution(
execution_no='APX-READONLY', task_id=int(task.id), status='active',
candidate_set_id=int(task.active_inventory_candidate_set_id),
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
)
db.session.add(legacy)
db.session.flush()
gate = ShippingProcessGate(
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
sequence_no=1, status='running', evaluation_version=1, lock_version=1,
)
db.session.add(gate)
db.session.flush()
task.active_process_execution_id = int(legacy.id)
job = Job(
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
execution_id=int(legacy.id), gate_id=int(gate.id), status='running',
candidate_set_id=int(task.active_inventory_candidate_set_id),
payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1,
)
db.session.add(job)
db.session.commit()
result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker')
db.session.refresh(job)
db.session.refresh(gate)
assert result['status'] == 'legacy_readonly'
assert job.status == 'cancelled'
assert gate.status == 'cancelled'
def test_active_legacy_apx_job_does_not_block_formal_submission(app):
"""历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。"""
task = _task_with_candidate()
legacy = ShippingProcessExecution(
execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active',
candidate_set_id=int(task.active_inventory_candidate_set_id),
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
)
db.session.add(legacy)
db.session.flush()
gate = ShippingProcessGate(
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
sequence_no=1, status='queued', evaluation_version=1, lock_version=1,
)
db.session.add(gate)
db.session.flush()
task.active_process_execution_id = int(legacy.id)
db.session.add(Job(
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id),
status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1,
))
db.session.commit()
result = submit_auto_progress(task=task, trigger='review_confirmed')
assert result['status'] == 'queued'
assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate'
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff. Show more