feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码
This commit is contained in:
1 parent
935bf26fa6
commit
7cfd5d167e
230 files changed
+9337
-10989
No files matched your search
@@ -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():
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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,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")
|
||||
|
||||
@@ -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():
|
||||
"""
|
||||
|
||||
@@ -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'])
|
||||
|
||||
Reference in new issue
Block a user