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

+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'])