Files
syops/backend/app/api/workspace/shipping_notice.py
T

1279 lines
56 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/api/workspace/shipping_notice.py
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, g, jsonify, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingBatch, ShippingNoticeIntake, ShippingOrderExtraction, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import (
AUTO_CHAIN_FALLBACK,
CP_EXPORT_GENERATED,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
get_conversation_batch_workspace,
get_focus_task_for_batch,
get_task_for_user,
list_batches_for_user,
list_tasks_page_for_user,
list_tasks_for_batch,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.task_disposition_service import (
archive_task,
load_task_for_disposition,
move_task_to_recycle_bin,
purge_task_permanently,
restore_task_from_recycle_bin,
)
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
list_customer_options,
)
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
"""
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
Returns:
User 模型实例。
Raises:
UnauthorizedError: 无有效 JWT 或 legacy header。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _ok(payload: dict):
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
return ok(payload, request_id=getattr(g, 'request_id', None))
@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
process_status = str(request.args.get('process_status') 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)
page_size = int(request.args.get('page_size') or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
if page < 1 or not 1 <= page_size <= 100:
raise ValidationError('page must be positive and page_size must be between 1 and 100')
return jsonify(list_tasks_page_for_user(
user.id,
batch_no=batch_no,
process_status=process_status,
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
))
def _batch_task_nos(data: dict) -> list[str]:
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
raw_task_nos = data.get('task_nos')
if not isinstance(raw_task_nos, list) or not raw_task_nos:
raise ValidationError('task_nos must be a non-empty list', code='SHIPPING.TASK_SELECTION_INVALID')
normalized = list(dict.fromkeys(str(value or '').strip().upper() for value in raw_task_nos if str(value or '').strip()))
if not normalized or len(normalized) > 100:
raise ValidationError('task_nos must contain 1 to 100 task numbers', code='SHIPPING.TASK_SELECTION_INVALID')
return normalized
def _can_dispose_task(user, task: ShippingTask) -> bool:
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
def _batch_dispose(action: str):
"""在每条任务行锁下重算权限与资格,返回部分成功明细而不让一条失败回滚整批。"""
user = _require_user()
data = request.get_json(silent=True) or {}
task_nos = _batch_task_nos(data)
reason = str(data.get('reason') or '').strip()
if action == 'delete' and not reason:
raise ValidationError('reason is required', code='SHIPPING.TASK_DELETE_REASON_REQUIRED')
request_id = getattr(g, 'request_id', None)
results = []
for task_no in task_nos:
try:
task = load_task_for_disposition(task_no)
if not _can_dispose_task(user, task):
results.append({'task_no': task_no, 'status': 'blocked', 'code': 'AUTH.FORBIDDEN'})
db.session.rollback()
continue
if action == 'delete':
outcome = move_task_to_recycle_bin(task, actor_id=user.id, reason=reason, request_id=request_id)
elif action == 'archive':
archive_task(task, actor_id=user.id, request_id=request_id)
outcome = 'archived'
else:
restore_task_from_recycle_bin(task, actor_id=user.id, request_id=request_id)
outcome = 'restored'
db.session.commit()
results.append({'task_no': task_no, 'status': outcome})
except AppError as exc:
db.session.rollback()
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
except Exception:
db.session.rollback()
raise
return _ok({'results': results, 'requested_count': len(task_nos)})
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-purge', methods=['POST'])
def workspace_batch_purge_shipping_tasks():
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
user = _require_user()
if str(getattr(user, 'role', '')).lower() != 'admin':
from app.core.errors import ForbiddenError
raise ForbiddenError('Admin privilege required')
data = request.get_json(silent=True) or {}
task_nos = _batch_task_nos(data)
reason = str(data.get('reason') or '').strip()
if not reason:
raise ValidationError('reason is required', code='SHIPPING.TASK_PURGE_REASON_REQUIRED')
results = []
for task_no in task_nos:
try:
task = load_task_for_disposition(task_no)
purge_task_permanently(
task,
actor_id=user.id,
reason=reason,
request_id=getattr(g, 'request_id', None),
)
db.session.commit()
results.append({'task_no': task_no, 'status': 'purged'})
except AppError as exc:
db.session.rollback()
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
except Exception:
db.session.rollback()
raise
return _ok({'results': results, 'requested_count': len(task_nos)})
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-delete', methods=['POST'])
def workspace_batch_delete_shipping_tasks():
"""批量删除任务到回收站;服务端按行锁判定是否需要同时作废。"""
return _batch_dispose('delete')
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-archive', methods=['POST'])
def workspace_batch_archive_shipping_tasks():
"""批量归档任务,适用于已上传或外部处理中而不能作废的任务。"""
return _batch_dispose('archive')
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-restore', methods=['POST'])
def workspace_batch_restore_shipping_tasks():
"""批量恢复回收站内仍为 active 的纯误建任务。"""
return _batch_dispose('restore')
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。"""
user = _require_user()
limit = int(request.args.get('limit') or 100)
return jsonify(list_batches_for_user(user.id, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive():
"""按批次或显式任务号下载当前用户可访问的 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,
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@workspace_shipping_notice_bp.route('/shipping-customers', methods=['GET'])
def workspace_shipping_customers():
"""列出可供当前业务用户确认的启用标准客户。"""
_require_user()
query = str(request.args.get('q') or '').strip()
try:
limit = int(request.args.get('limit') or 100)
except (TypeError, ValueError) as exc:
raise ValidationError('Invalid customer limit') from exc
return jsonify(list_customer_options(query=query, limit=limit))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-customer', methods=['POST'])
def workspace_confirm_shipping_customer(task_no: str):
"""为当前用户任务确认标准客户,并原子生成正式业务编号。"""
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 {}
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
return jsonify(serialize_task_detail(updated))
@workspace_shipping_notice_bp.route(
'/shipping-order-extractions/<int:extraction_id>/customer-matches/<role>/confirm',
methods=['POST'],
)
def workspace_confirm_order_customer_match(extraction_id: int, role: str):
"""确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。"""
user = _require_user()
extraction = (
db.session.query(ShippingOrderExtraction)
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingOrderExtraction.intake_id)
.filter(
ShippingOrderExtraction.id == extraction_id,
ShippingNoticeIntake.user_id == user.id,
)
.one_or_none()
)
if extraction is None:
raise NotFoundError(
'Order extraction not found',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
site_id = int(data['site_id']) if data.get('site_id') is not None else None
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.ORDER_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
result = confirm_order_customer_match(
extraction.id,
role=role,
customer_id=customer_id,
site_id=site_id,
actor_id=user.id,
reason=str(data.get('reason') or ''),
)
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 会话下的多批次执行工作台快照。"""
user = _require_user()
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
def workspace_create_shipping_batch_from_notices():
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
user = _require_user()
uploads = request.files.getlist('files')
if not uploads:
single = request.files.get('file')
if single:
uploads = [single]
if not uploads:
raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.batch_from_notices import (
create_shipping_batch_from_notice_items,
intake_notice_uploads_for_batch,
)
from app.services.shipping_notice.batch_create_idempotency import (
normalize_create_idempotency_key,
warn_missing_create_idempotency_key,
)
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
conversation_id = str(request.form.get('conversation_id') or '').strip()
idempotency_key = normalize_create_idempotency_key(
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
)
if not idempotency_key:
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
temp_request_id = str(getattr(g, 'request_id', None) or 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)
created = create_shipping_batch_from_notice_items(
user_id=user.id,
conversation_id=conversation_id or None,
notice_items=notice_items,
file_summary=file_summary,
create_idempotency_key=idempotency_key,
)
return _ok(created)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""
返回批次详情与聚合 UI State。
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""
返回批次级 UI State。
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
"""返回指定批次下的任务列表。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str):
"""返回指定批次当前焦点任务的摘要。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
raise NotFoundError('Focus task not found')
return jsonify(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str):
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
comment = str(data.get('comment') or '').strip()
if not task_no:
raise ValidationError('task_no is required')
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
raise NotFoundError('Task not found in batch')
switch_batch_focus(
batch,
task,
source='workspace_api',
comment=comment or None,
extra={'actor_user_id': user.id},
)
db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user = _require_user()
data = request.get_json(silent=True) or {}
payload = {'user_id': user.id}
source_type = str(data.get('source_type') or '').strip()
if source_type:
payload['source_type'] = source_type
conversation_id = str(data.get('conversation_id') or '').strip()
if conversation_id:
payload['conversation_id'] = conversation_id
raw_content = str(data.get('raw_content') or '').strip()
if raw_content:
payload['raw_content'] = raw_content
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
user = _require_user()
upload = request.files.get('file')
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
filename = upload.filename or 'notice'
raw = upload.read() or b''
source_file_type = notice_source_file_type(upload)
source_type = guess_source_type(filename)
conversation_id = str(request.form.get('conversation_id') or '').strip()
payload = {'user_id': user.id, 'source_type': source_type}
if conversation_id:
payload['conversation_id'] = conversation_id
created = shipping_tools.create_task(payload)
task_id = str(created.get('task_id') or '').strip()
if not task_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
intake = intake_notice_attachment(
filename=filename,
raw=raw,
source_file_type=source_file_type,
storage='task',
task_no=task_id,
)
if not intake.accepted:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = intake.text
task.source_file_name = intake.filename or task.source_file_name
task.source_file_type = intake.source_file_type or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str):
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
upload = request.files.get('file')
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import task_workflow
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
intake = intake_notice_attachment(
filename=upload.filename or 'notice',
raw=upload.read() or b'',
source_file_type=notice_source_file_type(upload),
storage='task',
task_no=task.task_no,
)
task.source_type = intake.source_type or task.source_type
result = task_workflow.replace_task_notice(
task,
raw_text=intake.text,
source_file_name=intake.filename,
source_file_type=intake.source_file_type,
warnings=list(intake.warnings),
)
data = result.setdefault('data', {})
if isinstance(data, dict):
data['notice_upload'] = intake.to_notice_upload_meta()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
def workspace_shipping_task_detail(task_no: str):
"""
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok({
**serialize_task_detail(task),
'ui_state': build_task_ui_state(task),
})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
def workspace_shipping_task_ui_state(task_no: str):
"""
返回单票任务 UI State。
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
避免不同前端入口重复拼装按钮集合。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok(build_task_ui_state(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return jsonify(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):
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload = {'task_id': task.task_no}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
def workspace_confirm_shipping_inventory_source(task_no: str):
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
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 {}
source_code = str(data.get('source_code') or '').strip()
if not source_code:
raise ValidationError('source_code is required')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.confirm_inventory_source({
'task_id': task.task_no,
'source_code': source_code,
'_trusted_user_id': user.id,
}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
def workspace_submit_shipping_decision(task_no: str):
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
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 {}
decision = str(data.get('decision') or '').strip()
if not decision:
raise ValidationError('decision is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
def workspace_update_shipping_notice_fields(task_no: str):
"""更新发货通知单头字段。"""
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 {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
raise ValidationError('fields is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'fields': fields, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST'])
def workspace_freeze_shipping_order(task_no: str):
"""冻结已复核订单为不可编辑的强类型履约快照。"""
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 {}
try:
expected_version = int(data.get('expected_order_data_version'))
except (TypeError, ValueError) as exc:
raise ValidationError('expected_order_data_version is required') from exc
snapshot = freeze_order_snapshot(
task,
actor_id=int(user.id),
expected_order_data_version=expected_version,
rule_versions=data.get('rule_versions') if isinstance(data.get('rule_versions'), dict) else None,
)
db.session.commit()
return _ok({
'task_no': task.task_no,
'snapshot_id': snapshot.id,
'order_data_version': snapshot.order_data_version,
'frozen_at': snapshot.frozen_at.isoformat(),
})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
def workspace_update_shipping_notice_line(task_no: str):
"""更新发货通知中的指定订单行。"""
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 {}
try:
line_index = int(data.get('line_index'))
except (TypeError, ValueError):
raise ValidationError('line_index is required')
patch = data.get('patch')
if not isinstance(patch, dict) or not patch:
raise ValidationError('patch is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/field-conflicts', methods=['GET'])
def workspace_list_shipping_field_conflicts(task_no: str):
"""列出任务未解决字段冲突。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice.task_field_conflict_service import (
list_open_field_conflicts,
serialize_field_conflict,
)
rows = list_open_field_conflicts(task)
return _ok({
'task_no': task.task_no,
'order_data_version': int(task.order_data_version or 1),
'items': [serialize_field_conflict(row) for row in rows],
'open_count': len(rows),
})
@workspace_shipping_notice_bp.route(
'/shipping-tasks/<task_no>/field-conflicts/<int:conflict_id>/resolve',
methods=['POST'],
)
def workspace_resolve_shipping_field_conflict(task_no: str, conflict_id: int):
"""人工解决字段冲突并回写订单行。"""
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 {}
resolution = str(data.get('resolution') or '').strip()
if not resolution:
raise ValidationError('resolution is required')
def _optional_int(name: str) -> int | None:
raw = data.get(name)
if raw is None or raw == '':
return None
try:
return int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError(f'{name} is invalid') from exc
from app.services.shipping_notice.task_field_conflict_service import resolve_field_conflict
result = resolve_field_conflict(
task=task,
conflict_id=int(conflict_id),
resolution=resolution,
resolved_value=data.get('resolved_value'),
expected_conflict_version=_optional_int('expected_conflict_version'),
expected_order_data_version=_optional_int('expected_order_data_version'),
resolved_by_id=int(user.id),
evidence_ref=str(data.get('evidence_ref') or '').strip() or None,
reason=str(data.get('reason') or '').strip() or None,
idempotency_key=str(data.get('idempotency_key') or '').strip() or None,
)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
def workspace_add_shipping_notice_line(task_no: str):
"""为发货通知新增订单行。"""
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 {}
line = data.get('line')
if not isinstance(line, dict) or not line:
raise ValidationError('line is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line': line, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
def workspace_remove_shipping_notice_line(task_no: str):
"""删除发货通知中的指定订单行。"""
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 {}
try:
line_index = int(data.get('line_index'))
except (TypeError, ValueError):
raise ValidationError('line_index is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
def workspace_auto_progress_shipping_task(task_no: str):
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload: dict = {'task_id': task.task_no}
for key in ('lang', 'locale', 'language'):
if data.get(key):
payload[key] = data[key]
break
result = shipping_tools.auto_progress(payload)
if isinstance(result, dict) and result.get('status') == 'ok':
gen_data = result.get('data')
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
result = {**result, 'data': gen_data}
return jsonify(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
def workspace_match_shipping_inventory(task_no: str):
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
if not isinstance(matched, dict):
return jsonify(matched)
data = matched.get('data')
if isinstance(data, dict) and data.get('export_file_path'):
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
matched['checkpoint'] = checkpoint
if 'human_options' not in matched:
options = human_options_for_checkpoint(checkpoint)
if options is not None:
matched['human_options'] = options
if 'action_buttons' not in matched:
buttons = action_buttons_for_checkpoint(checkpoint)
if buttons:
matched['action_buttons'] = buttons
return jsonify(matched)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
def workspace_upload_shipping_inventory(task_no: str):
"""为当前任务上传正式库存文件;工作台直连既有确定性库存解析链路。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
upload = request.files.get('file')
if upload is None:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
def workspace_mark_manual_uploaded(task_no: str):
"""登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload = {
'task_id': task.task_no, 'mode': 'manual_confirm', 'operator_id': user.id,
'evidence_asset_no': data.get('evidence_asset_no'), 'freight_ref_no': data.get('freight_ref_no'),
'artifact_id': data.get('artifact_id'),
}
return jsonify(shipping_tools.upload_to_freight(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
def workspace_retry_shipping_upload(task_no: str):
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
def workspace_generate_shipping_excel(task_no: str):
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
result = shipping_tools.generate_excel({'task_id': task.task_no})
if isinstance(result, dict) and result.get('status') == 'ok':
data = result.get('data')
if not isinstance(data, dict):
data = {}
result['data'] = data
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
return jsonify(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
def workspace_list_shipping_notice_intakes():
"""列出当前会话下未消费的活跃接入记录。"""
user = _require_user()
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
status = str(request.args.get('status') or '').strip().lower()
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
if status and status != 'active':
return _ok({'items': []})
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
return _ok({'items': items})
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['POST'])
def workspace_create_shipping_order_extraction_run():
"""冻结当前会话的已解析 Intake 并创建异步订单抽取领域 Run。"""
user = _require_user()
body = request.get_json(silent=True)
if body is None:
body = {}
if not isinstance(body, dict):
raise ValidationError('JSON body must be an object')
try:
agent_id = int(body.get('agent_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'agent_id is required',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
) from exc
conversation_id = str(body.get('conversation_id') or '').strip()
intake_nos = body.get('intake_nos')
if not isinstance(intake_nos, list):
raise ValidationError(
'intake_nos must be a list',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID',
)
from app.services.shipping_notice.order_extraction_run_service import (
create_order_extraction_run,
serialize_order_extraction_run,
)
run, reused = create_order_extraction_run(
user=user,
agent_id=agent_id,
conversation_id=conversation_id,
intake_nos=intake_nos,
)
db.session.commit()
return ok(
{'run': serialize_order_extraction_run(run), 'reused': reused},
request_id=getattr(g, 'request_id', None),
status=202,
)
@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;正文快照不会暴露给前端。"""
user = _require_user()
from app.services.shipping_notice.order_extraction_run_service import (
get_order_extraction_run,
serialize_order_extraction_run,
)
return _ok(serialize_order_extraction_run(get_order_extraction_run(user_id=user.id, run_no=run_no)))
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/progress-events', methods=['GET'])
def workspace_list_shipping_order_extraction_progress_events(run_no: str):
"""返回当前用户展开状态卡时所需的脱敏业务阶段时间线。"""
user = _require_user()
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
return _ok({'items': list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)})
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
user = _require_user()
from app.services.shipping_notice.order_extraction_run_service import mark_order_extraction_run_seen
seen = mark_order_extraction_run_seen(user_id=user.id, run_no=run_no)
db.session.commit()
return _ok({'seen': seen})
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/retry', methods=['POST'])
def workspace_retry_shipping_order_extraction_run(run_no: str):
"""复用原附件与冻结快照,重新入队当前用户失败的订单抽取 Run。"""
user = _require_user()
from app.services.shipping_notice.order_extraction_run_service import (
retry_order_extraction_run,
serialize_order_extraction_run,
)
run, reused = retry_order_extraction_run(user_id=user.id, run_no=run_no)
db.session.commit()
return ok(
{'run': serialize_order_extraction_run(run), 'reused': reused},
request_id=getattr(g, 'request_id', None),
status=202,
)
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/reparse', methods=['POST'])
def workspace_reparse_shipping_order_extraction_run(run_no: str):
"""
使用当前发布规则重新识别一个终态订单抽取 Run。
核心逻辑:只接收受控原因与可选备注,服务层复用原始 Intake 创建新的版本化 Run;
不复用失败重试的冻结 Provider 缓存,也不允许前端传入 Schema、Binding 或附件内容。
"""
user = _require_user()
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('Request body must be an object')
from app.services.shipping_notice.order_extraction_run_service import (
reparse_order_extraction_run,
serialize_order_extraction_run,
)
run, reused = reparse_order_extraction_run(
user_id=user.id,
run_no=run_no,
reason=str(body.get('reason') or ''),
comment=str(body.get('comment') or '') or None,
)
db.session.commit()
return ok(
{'run': serialize_order_extraction_run(run), 'reused': reused},
request_id=getattr(g, 'request_id', None), status=202,
)
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
def workspace_list_shipping_order_extraction_runs():
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
user = _require_user()
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
try:
limit = int(request.args.get('limit') or 50)
except (TypeError, ValueError) as exc:
raise ValidationError('limit must be an integer') from exc
from app.services.shipping_notice.order_extraction_run_service import (
list_order_extraction_runs,
serialize_order_extraction_run,
)
rows = list_order_extraction_runs(user_id=user.id, conversation_id=conversation_id, limit=limit)
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
def workspace_create_shipping_notice_intake():
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
user = _require_user()
body = request.get_json(silent=True) or {}
asset_no = str(body.get('asset_no') or '').strip()
if not asset_no:
raise ValidationError('asset_no is required')
conversation_id = str(body.get('conversation_id') or '').strip() or None
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
data = create_shipping_notice_intake(
user_id=user.id,
asset_no=asset_no,
conversation_id=conversation_id,
)
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
def workspace_get_shipping_notice_intake(intake_no: str):
"""查询单个接入记录。"""
user = _require_user()
from app.services.shipping_notice.intake_service import get_intake_detail
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
def workspace_shipping_notice_intake_statuses():
"""批量查询接入状态。"""
user = _require_user()
body = request.get_json(silent=True) or {}
intake_nos = body.get('intake_nos')
if not isinstance(intake_nos, list):
raise ValidationError('intake_nos is required')
from app.services.shipping_notice.intake_service import get_intake_statuses
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
def workspace_retry_shipping_notice_intake(intake_no: str):
"""重试失败的预解析。"""
user = _require_user()
from app.services.shipping_notice.intake_service import retry_intake_parse
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
def workspace_cancel_shipping_notice_intake(intake_no: str):
"""取消未消费接入记录。"""
user = _require_user()
from app.services.shipping_notice.intake_service import cancel_intake
cancel_intake(user_id=user.id, intake_no=intake_no)
return _ok({'cancelled': True})
@workspace_shipping_notice_bp.route(
'/shipping-notice/intakes/<intake_no>/duplicate-resolution',
methods=['POST'],
)
def workspace_resolve_shipping_notice_duplicate(intake_no: str):
"""保存发货通知重复检测决策。"""
user = _require_user()
body = request.get_json(silent=True) or {}
action = str(body.get('action') or '').strip()
target_task_no = str(body.get('target_task_no') or '').strip() or None
reason = str(body.get('reason') or '').strip() or None
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
return _ok(
resolve_intake_duplicate(
user_id=user.id,
intake_no=intake_no,
action=action,
target_task_no=target_task_no,
reason=reason,
actor=user,
)
)
@workspace_shipping_notice_bp.route(
'/shipping-notice/intakes/<intake_no>/duplicate-refresh',
methods=['POST'],
)
def workspace_refresh_shipping_notice_duplicate(intake_no: str):
"""重新执行重复检测。"""
user = _require_user()
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>', methods=['PATCH'])
def workspace_update_shipping_notice_candidate(candidate_no: str):
"""更新订单候选的选择状态或人工修订业务摘要。"""
user = _require_user()
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
raise ValidationError('请求体必须为对象')
if 'selected' in body and not isinstance(body.get('selected'), bool):
raise ValidationError('selected 必须为布尔值')
if 'business_summary' in body and not isinstance(body.get('business_summary'), dict):
raise ValidationError('business_summary 必须为对象')
if 'selected' not in body and 'business_summary' not in body:
raise ValidationError('selected 或 business_summary 至少提供一项')
from app.services.shipping_notice.candidate_service import update_candidate
return _ok(
update_candidate(
user_id=user.id,
candidate_no=candidate_no,
selected=body.get('selected') if 'selected' in body else None,
business_summary=body.get('business_summary') if 'business_summary' in body else None,
)
)
@workspace_shipping_notice_bp.route(
'/shipping-notice/candidates/<candidate_no>/duplicate-refresh',
methods=['POST'],
)
def workspace_refresh_shipping_notice_candidate(candidate_no: str):
"""刷新单个订单候选的重复检测。"""
user = _require_user()
from app.services.shipping_notice.candidate_service import refresh_candidate_duplicate
return _ok(refresh_candidate_duplicate(user_id=user.id, candidate_no=candidate_no))
@workspace_shipping_notice_bp.route(
'/shipping-notice/candidates/<candidate_no>/duplicate-resolution',
methods=['POST'],
)
def workspace_resolve_shipping_notice_candidate(candidate_no: str):
"""保存单个订单候选的重复处理决策。"""
user = _require_user()
body = request.get_json(silent=True) or {}
from app.services.shipping_notice.candidate_service import resolve_candidate_duplicate
return _ok(
resolve_candidate_duplicate(
user_id=user.id,
candidate_no=candidate_no,
action=str(body.get('action') or ''),
target_task_no=str(body.get('target_task_no') or '').strip() or None,
reason=str(body.get('reason') or '').strip() or None,
actor=user,
)
)
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
def workspace_create_shipping_batch_from_intakes():
"""从已解析接入记录确认建批。"""
user = _require_user()
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
raise ValidationError('请求体必须为对象')
intake_nos = body.get('intake_nos')
if not isinstance(intake_nos, list) or not intake_nos:
raise ValidationError('intake_nos is required')
conversation_id = str(body.get('conversation_id') or '').strip() or None
candidate_nos = body.get('candidate_nos')
if candidate_nos is not None and not isinstance(candidate_nos, list):
raise ValidationError('candidate_nos must be a list')
from app.services.shipping_notice.batch_create_idempotency import (
normalize_create_idempotency_key,
warn_missing_create_idempotency_key,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
idempotency_key = normalize_create_idempotency_key(
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
)
if not idempotency_key:
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
result = create_shipping_batch_from_intakes(
user_id=user.id,
conversation_id=conversation_id,
intake_nos=[str(item) for item in intake_nos],
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
create_idempotency_key=idempotency_key,
)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return jsonify(retry_batch_pending_tasks(batch.batch_no))