将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段; 统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认"; 新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成; 新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式; 更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
3071 lines
129 KiB
Python
3071 lines
129 KiB
Python
"""
|
||
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。
|
||
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
|
||
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
|
||
`/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404;
|
||
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
from io import BytesIO
|
||
from typing import Any
|
||
|
||
from flask import Blueprint, Response, current_app, g, 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 ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice
|
||
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.processing_ownership import assert_notice_task_ownership
|
||
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,
|
||
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_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
|
||
|
||
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: Any, *, status: int = 200):
|
||
"""
|
||
返回带 request_id 的成功 envelope,供工作台读写接口复用。
|
||
|
||
核心逻辑:委托 `app.core.response.ok`,统一 `{success, data, request_id, timestamp}`。
|
||
|
||
Args:
|
||
payload: 业务数据(dict / list / 其他可 JSON 序列化对象)。
|
||
status: HTTP 状态码,默认 200;异步受理可用 202。
|
||
|
||
Returns:
|
||
Flask `(Response, status)` 元组。
|
||
"""
|
||
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
|
||
def workspace_download_receipt_report_file(file_id: int):
|
||
"""下载当前接收人或管理员有权读取的原样收料报表。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
|
||
|
||
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
|
||
response = send_file(
|
||
stream, as_attachment=True, download_name=filename,
|
||
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||
)
|
||
response.call_on_close(stream.close)
|
||
return response
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
|
||
def workspace_list_receipt_report_files():
|
||
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
|
||
user = _require_user()
|
||
try:
|
||
limit = int(request.args.get('limit') or 100)
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError('limit must be an integer') from exc
|
||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||
|
||
return _ok({'items': list_receipt_report_files(user, limit=limit)})
|
||
|
||
|
||
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||
"""
|
||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
||
|
||
核心逻辑:委托 assert_notice_task_ownership;未携带期望字段时放行(兼容旧客户端)。
|
||
|
||
Args:
|
||
task: 已鉴权的 ShippingNotice。
|
||
user_id: 当前用户 id。
|
||
|
||
Raises:
|
||
ConflictError: 归属不匹配。
|
||
"""
|
||
data = request.get_json(silent=True) or {}
|
||
assert_notice_task_ownership(
|
||
task,
|
||
expected_order_task_no=(
|
||
str(data.get('expected_order_task_no') or data.get('order_task_no') or '').strip() or None
|
||
),
|
||
expected_review_case_no=(
|
||
str(data.get('expected_review_case_no') or data.get('case_no') or '').strip() or None
|
||
),
|
||
expected_run_no=(
|
||
str(data.get('expected_run_no') or data.get('run_no') or '').strip() or None
|
||
),
|
||
actor_id=user_id,
|
||
)
|
||
|
||
|
||
@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)
|
||
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 _ok(list_tasks_page_for_user(
|
||
user.id,
|
||
batch_no=batch_no,
|
||
lifecycle_status=lifecycle_status,
|
||
page=page,
|
||
page_size=page_size,
|
||
))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos', methods=['GET'])
|
||
def workspace_shipping_my_todos():
|
||
"""
|
||
分页列出当前用户「我的待办」(pending / processing / done)。
|
||
|
||
核心逻辑:委托 query_service.list_my_todos;管理员可读全局但 can_handle 仅创建者。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.query_service import list_my_todos
|
||
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
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
|
||
return _ok(list_my_todos(
|
||
user.id,
|
||
bucket=str(request.args.get('bucket') or 'pending'),
|
||
page=page,
|
||
page_size=page_size,
|
||
is_admin=is_admin,
|
||
todo_category=str(request.args.get('todo_category') or '').strip() or None,
|
||
customer=str(request.args.get('customer') or '').strip() or None,
|
||
task_no=str(request.args.get('task_no') or '').strip() or None,
|
||
))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/count', methods=['GET'])
|
||
def workspace_shipping_my_todos_count():
|
||
"""返回「我的待办」各 bucket 计数,供导航徽标使用。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.query_service import count_my_todos
|
||
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||
|
||
|
||
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: ShippingNotice) -> 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():
|
||
"""列出当前用户的发货批次摘要;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。"""
|
||
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-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 _ok(shipping_tools.create_task(payload))
|
||
|
||
|
||
@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 _ok(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 _ok(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(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
|
||
.filter(
|
||
ShippingOrderExtraction.id == extraction_id,
|
||
ShippingOrderIntake.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 ''),
|
||
commit=False,
|
||
)
|
||
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
|
||
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
|
||
if role == 'bill_to':
|
||
from app.models import (
|
||
ShippingOrderCandidate,
|
||
ShippingOrderReviewCase,
|
||
ShippingOrderReviewStream,
|
||
)
|
||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||
reconcile_single_case_for_auto_progress,
|
||
)
|
||
_TERMINAL = frozenset({
|
||
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
|
||
})
|
||
candidates = list(
|
||
ShippingOrderCandidate.query
|
||
.filter_by(order_extraction_id=int(extraction.id))
|
||
.all()
|
||
)
|
||
candidate_ids = {int(c.id) for c in candidates}
|
||
case = None
|
||
if candidate_ids:
|
||
case = (
|
||
ShippingOrderReviewCase.query
|
||
.join(
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||
)
|
||
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
|
||
.first()
|
||
)
|
||
if case is None and extraction.run_id:
|
||
case = (
|
||
ShippingOrderReviewCase.query
|
||
.join(
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||
)
|
||
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
|
||
.first()
|
||
)
|
||
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
|
||
reconcile_single_case_for_auto_progress(
|
||
case=case,
|
||
trigger='extraction_customer_confirmed',
|
||
refresh_validation=True,
|
||
)
|
||
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,再交给后台编排器。"""
|
||
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:
|
||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||
task = ShippingNotice.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 _ok({'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 / actions / steps,减少前端二次推导与竞态刷新。
|
||
"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||
if not task:
|
||
raise NotFoundError('Not found')
|
||
return _ok({
|
||
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
|
||
'ui_state': build_task_ui_state(task, include_stage_context=True),
|
||
})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
|
||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||
|
||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||
if not task:
|
||
raise NotFoundError('Not found')
|
||
page = request.args.get('page', 1, type=int)
|
||
page_size = request.args.get('page_size', 50, type=int)
|
||
payload = list_task_audit_timeline(
|
||
user_id=user.id,
|
||
task_no=str(task.task_no),
|
||
task=task,
|
||
page=page,
|
||
page_size=page_size,
|
||
)
|
||
record_access_audit(
|
||
action='view_task_audit_trail',
|
||
aggregate_type='shipping_task',
|
||
aggregate_id=str(task.task_no),
|
||
actor_id=user.id,
|
||
task_no=str(task.task_no),
|
||
)
|
||
db.session.commit()
|
||
return _ok(payload)
|
||
|
||
|
||
@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, include_stage_context=True))
|
||
|
||
@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 _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):
|
||
"""更新发货通知单头字段。"""
|
||
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'] = data.get('evidence')
|
||
payload['reason'] = str(data.get('reason') or '').strip()
|
||
comment = str(data.get('comment') or '').strip()
|
||
if comment:
|
||
payload['comment'] = comment
|
||
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 _ok(shipping_tools.update_notice_fields(payload))
|
||
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
|
||
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||
"""登记货代撤销回执并解除合法后继版本的履约阻断。"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.models import ShippingFreightCancellation
|
||
cancellation = ShippingFreightCancellation.query.filter_by(id=cancellation_id).one_or_none()
|
||
if cancellation is None:
|
||
raise NotFoundError('Not found')
|
||
old_task = db.session.get(ShippingNotice, cancellation.old_task_id)
|
||
if old_task is None or int(old_task.user_id or 0) != int(user.id):
|
||
raise NotFoundError('Not found')
|
||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||
row = complete_freight_cancellation(
|
||
cancellation_id=cancellation.id, actor_id=int(user.id),
|
||
freight_receipt_no=str(data.get('freight_receipt_no') or ''),
|
||
receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''),
|
||
)
|
||
db.session.commit()
|
||
return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id})
|
||
|
||
@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'] = data.get('evidence')
|
||
payload['reason'] = str(data.get('reason') or '').strip()
|
||
comment = str(data.get('comment') or '').strip()
|
||
if comment:
|
||
payload['comment'] = comment
|
||
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 _ok(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=data.get('evidence') if isinstance(data.get('evidence'), dict) else 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'] = data.get('evidence')
|
||
payload['reason'] = str(data.get('reason') or '').strip()
|
||
comment = str(data.get('comment') or '').strip()
|
||
if comment:
|
||
payload['comment'] = comment
|
||
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 _ok(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'] = data.get('evidence')
|
||
payload['reason'] = str(data.get('reason') or '').strip()
|
||
comment = str(data.get('comment') or '').strip()
|
||
if comment:
|
||
payload['comment'] = comment
|
||
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 _ok(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):
|
||
"""
|
||
系统/确认后调度兼容入口:内部委托统一决策器(continue_auto_progress=True)。
|
||
|
||
核心逻辑:用户界面不应再调用本接口;用户重试走 /retry 或对话级 API。
|
||
"""
|
||
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.progress_workflow import run_task_auto_progress
|
||
|
||
# 普通用户不提交 Gate;服务端从当前事实定位最早未通过 Gate。
|
||
result = run_task_auto_progress(
|
||
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
|
||
)
|
||
|
||
# 兼容旧前端:若仍有 export 路径则附带 download_url。
|
||
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
|
||
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
|
||
refreshed = get_task_for_user(task_no, user.id)
|
||
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None
|
||
if export_path:
|
||
result = {
|
||
**result,
|
||
'data': {
|
||
**dict(result.get('data') or {}),
|
||
'export_file_path': export_path,
|
||
'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export',
|
||
},
|
||
}
|
||
return _ok(result)
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||
def workspace_mark_manual_uploaded(task_no: str):
|
||
"""
|
||
登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。
|
||
|
||
核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。
|
||
"""
|
||
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)
|
||
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,
|
||
'actor_id': user.id,
|
||
'_trusted_user_id': user.id,
|
||
'event_source': 'workspace_api',
|
||
'evidence_asset_no': data.get('evidence_asset_no'),
|
||
'freight_ref_no': data.get('freight_ref_no'),
|
||
'artifact_id': data.get('artifact_id'),
|
||
}
|
||
result = shipping_tools.upload_to_freight(payload)
|
||
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
|
||
# 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。
|
||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||
|
||
run_task_auto_progress(
|
||
str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id),
|
||
)
|
||
return _ok(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
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
record_access_audit(
|
||
action='download_task_excel',
|
||
aggregate_type='shipping_task',
|
||
aggregate_id=str(task.task_no),
|
||
actor_id=user.id,
|
||
task_no=str(task.task_no),
|
||
reason_code='excel_downloaded',
|
||
metadata={'export': 'excel'},
|
||
)
|
||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/inventory-file', methods=['GET'])
|
||
def workspace_shipping_task_inventory_file(task_no: str):
|
||
"""下载当前任务实际关联的库存快照;无 active link 或托管文件时 fail-closed。"""
|
||
user = _require_user()
|
||
task = get_task_for_user(task_no, user.id)
|
||
if not task:
|
||
raise NotFoundError('Not found')
|
||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||
|
||
resolved = resolve_task_inventory_download(task)
|
||
if resolved is None:
|
||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||
path, download_name = resolved
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
record_access_audit(
|
||
action='download_task_inventory_file',
|
||
aggregate_type='shipping_task',
|
||
aggregate_id=str(task.task_no),
|
||
actor_id=user.id,
|
||
task_no=str(task.task_no),
|
||
reason_code='inventory_file_downloaded',
|
||
metadata={'inventory_file': download_name},
|
||
)
|
||
return send_file(path, as_attachment=True, download_name=download_name)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-tasks/<task_no>/inventory-files/<inventory_file_no>', methods=['GET'],
|
||
)
|
||
def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no: str):
|
||
"""下载当前任务明细已匹配引用的库存文件,禁止按任务或库存源宽泛猜测。"""
|
||
user = _require_user()
|
||
task = get_task_for_user(task_no, user.id)
|
||
if not task:
|
||
raise NotFoundError('Not found')
|
||
from pathlib import Path
|
||
|
||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||
|
||
requested_file_no = str(inventory_file_no or '').strip()
|
||
inventory_file = (
|
||
ShippingInventoryFile.query
|
||
.join(
|
||
ShippingNoticeLineInventoryMatch,
|
||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
||
)
|
||
.filter(
|
||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
||
)
|
||
.first()
|
||
)
|
||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||
path = Path(storage_path).resolve() if storage_path else None
|
||
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||
download_name = str(
|
||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
||
).strip()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
record_access_audit(
|
||
action='download_task_line_inventory_file',
|
||
aggregate_type='shipping_task',
|
||
aggregate_id=str(task.task_no),
|
||
actor_id=user.id,
|
||
task_no=str(task.task_no),
|
||
reason_code='inventory_file_downloaded',
|
||
metadata={'inventory_file': download_name, 'inventory_file_no': requested_file_no},
|
||
)
|
||
return send_file(path, as_attachment=True, download_name=download_name)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||
def workspace_list_shipping_order_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()
|
||
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
|
||
if not upload_batch_id:
|
||
raise ValidationError(
|
||
'upload_batch_id is required',
|
||
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
|
||
)
|
||
if len(upload_batch_id) > 36:
|
||
raise ValidationError(
|
||
'upload_batch_id is too long',
|
||
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
|
||
)
|
||
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,
|
||
upload_batch_id=upload_batch_id,
|
||
)
|
||
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-submissions', methods=['POST'])
|
||
def workspace_create_order_extraction_submission():
|
||
"""
|
||
统一订单抽取提交:后端事务内裁决追加或新建用户可见任务。
|
||
|
||
核心逻辑:校验 submission_id / intake_nos → 委托 submit_order_extraction →
|
||
返回 decision + processing 投影;前端不得本地选择 append/create。
|
||
"""
|
||
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()
|
||
submission_id = str(body.get('submission_id') or '').strip()
|
||
if not submission_id:
|
||
raise ValidationError(
|
||
'submission_id is required',
|
||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_SUBMISSION_ID_INVALID',
|
||
)
|
||
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',
|
||
)
|
||
upload_batch_id = str(body.get('upload_batch_id') or '').strip() or None
|
||
composer_context_id = str(body.get('composer_context_id') or '').strip() or None
|
||
focused_user_task_no = str(body.get('focused_user_task_no') or '').strip() or None
|
||
|
||
from app.services.shipping_notice.order_extraction_run_service import submit_order_extraction
|
||
|
||
payload = submit_order_extraction(
|
||
user=user,
|
||
agent_id=agent_id,
|
||
conversation_id=conversation_id,
|
||
intake_nos=intake_nos,
|
||
submission_id=submission_id,
|
||
composer_context_id=composer_context_id,
|
||
focused_user_task_no=focused_user_task_no,
|
||
upload_batch_id=upload_batch_id,
|
||
)
|
||
db.session.commit()
|
||
return ok(payload, request_id=getattr(g, 'request_id', None), status=202)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-processing/conversations/<conversation_id>',
|
||
methods=['GET'],
|
||
)
|
||
def workspace_get_shipping_processing_conversation(conversation_id: str):
|
||
"""
|
||
拉取会话级统一 ShippingProcessingProjection(唯一进度读源)。
|
||
|
||
核心逻辑:委托 project_conversation_processing_items;含 order_intake + order_task;
|
||
旧 /conversations/.../processing GET 已移除(无历史兼容)。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.shipping_processing_projection import (
|
||
project_conversation_processing_items,
|
||
)
|
||
|
||
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(
|
||
user_id=user.id,
|
||
conversation_id=str(conversation_id or '').strip(),
|
||
agent_id=agent_id,
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-processing/work-items/<work_item_type>/<work_item_no>',
|
||
methods=['GET'],
|
||
)
|
||
def workspace_get_shipping_processing_work_item(work_item_type: str, work_item_no: str):
|
||
"""
|
||
按工作项类型与编号拉取单个统一 ShippingProcessingProjection。
|
||
|
||
核心逻辑:委托 get_shipping_processing_work_item;鉴权与 conversation processing 相同。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.shipping_processing_projection import (
|
||
get_shipping_processing_work_item,
|
||
)
|
||
|
||
payload = get_shipping_processing_work_item(
|
||
user_id=user.id,
|
||
work_item_type=str(work_item_type or '').strip(),
|
||
work_item_no=str(work_item_no or '').strip(),
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/conversation-tasks/<task_no>/focus',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_focus_conversation_task(task_no: str):
|
||
"""标记用户可见任务为当前焦点,并返回刷新后的 processing。"""
|
||
user = _require_user()
|
||
body = request.get_json(silent=True) or {}
|
||
if body and not isinstance(body, dict):
|
||
raise ValidationError('Request body must be an object')
|
||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||
if not conversation_id:
|
||
raise ValidationError('conversation_id is required')
|
||
from app.services.shipping_notice.order_extraction_run_service import focus_conversation_task
|
||
|
||
payload = focus_conversation_task(
|
||
user_id=user.id,
|
||
conversation_id=conversation_id,
|
||
task_no=task_no,
|
||
)
|
||
db.session.commit()
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/conversation-tasks/<task_no>/viewed',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_mark_conversation_task_viewed(task_no: str):
|
||
"""标记用户可见任务详情已查看(viewed ≠ 业务已处理)。"""
|
||
user = _require_user()
|
||
body = request.get_json(silent=True) or {}
|
||
if body and not isinstance(body, dict):
|
||
raise ValidationError('Request body must be an object')
|
||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||
if not conversation_id:
|
||
raise ValidationError('conversation_id is required')
|
||
from app.services.shipping_notice.order_extraction_run_service import (
|
||
mark_conversation_task_viewed,
|
||
)
|
||
|
||
payload = mark_conversation_task_viewed(
|
||
user_id=user.id,
|
||
conversation_id=conversation_id,
|
||
task_no=task_no,
|
||
)
|
||
db.session.commit()
|
||
return _ok(payload)
|
||
|
||
|
||
@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.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_extraction_run_service import (
|
||
get_order_extraction_run,
|
||
serialize_order_extraction_run,
|
||
)
|
||
|
||
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
|
||
payload = serialize_order_extraction_run(run)
|
||
# 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。
|
||
record_access_audit(
|
||
action='view_order_extraction_run',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run.run_no),
|
||
actor_id=user.id,
|
||
run_no=str(run.run_no),
|
||
conversation_id=run.conversation_id,
|
||
metadata={'status': str(run.status or ''), 'poll': True},
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@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.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||
|
||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||
record_access_audit(
|
||
action='view_order_extraction_timeline',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run_no),
|
||
actor_id=user.id,
|
||
run_no=str(run_no),
|
||
metadata={'event_count': len(items or []), 'poll': True},
|
||
)
|
||
return _ok({'items': items})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/documents', methods=['GET'])
|
||
def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||
"""返回当前用户一次订单抽取的按 PDF 归并详情;访问留痕。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
|
||
|
||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||
record_access_audit(
|
||
action='view_order_extraction_documents',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run_no),
|
||
actor_id=user.id,
|
||
run_no=str(run_no),
|
||
metadata={'document_count': len(items or []), 'poll': True},
|
||
)
|
||
return _ok({'items': items})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/review', methods=['GET'])
|
||
def workspace_get_shipping_order_review_run(run_no: str):
|
||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||
|
||
payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin))
|
||
record_access_audit(
|
||
action='view_order_review_run',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run_no),
|
||
actor_id=user.id,
|
||
run_no=str(run_no),
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
|
||
def workspace_get_shipping_order_review_queue(run_no: str):
|
||
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||
|
||
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||
payload = serialize_review_queue(runs)
|
||
record_access_audit(
|
||
action='view_order_review_queue',
|
||
aggregate_type='conversation',
|
||
aggregate_id=str(payload.get('conversation_id') or ''),
|
||
actor_id=user.id,
|
||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||
run_no=str(run_no),
|
||
metadata={'item_count': len(payload.get('items') or [])},
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||
def workspace_get_shipping_order_review_case(case_no: str):
|
||
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_case_snapshot import (
|
||
build_order_review_case_snapshot,
|
||
)
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
|
||
# 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。
|
||
snapshot = build_order_review_case_snapshot(
|
||
get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin),
|
||
is_admin=is_admin,
|
||
)
|
||
record_access_audit(
|
||
action='view_order_review_case',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
run_no=(
|
||
str(((snapshot.get('case') or {}).get('run_no')) or '') or None
|
||
if isinstance(snapshot, dict)
|
||
else None
|
||
),
|
||
)
|
||
return _ok(snapshot)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/stp-auto-create/retry',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||
"""
|
||
显式重试 STP 自动建单入队(仅用于确认没有业务冲突后的技术重试 — Q6 职责严格区分)。
|
||
|
||
核心逻辑:
|
||
[Phase 2-4 前置校验] 先调 reconciliation_service.assert_case_not_blocked_manual,
|
||
如命中「业务阻断 waiting_human」(如 NOTICE_EXACT_DUPLICATE)直接抛 409,
|
||
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||
"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||
retry_stp_auto_create_for_case,
|
||
)
|
||
from app.services.shipping_notice.reconciliation_service import (
|
||
assert_case_not_blocked_manual,
|
||
)
|
||
|
||
case = get_review_case_visible_to_user(str(case_no), int(user.id), is_admin=is_admin)
|
||
# [DUPLICATE-GUARD-1] 第一道:retry API 前置校验 — 命中 duplicate 等业务阻断时直接 409,禁止普通 retry
|
||
assert_case_not_blocked_manual(case_no=str(case_no), case=case)
|
||
|
||
result = retry_stp_auto_create_for_case(user_id=int(user.id), case_no=str(case_no))
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||
"""
|
||
对账 → 复用 / 裁决 / 入队(Q6 与 retry-stp-auto-create 并存,职责严格区分)。
|
||
|
||
【Phase 2 正式入口】:
|
||
- 仅当用户点击了「处理重复任务」裁决按钮后或需要对账恢复的场景才调用;
|
||
- 按 Q7:operation_id + expected_case_version 双保险幂等;
|
||
- 按 Q1:内部调用 reconcile_queries 做 L1-L3 五级归属;
|
||
- 按 Q3:用户 create_revision / force_create 裁决后走资格刷新 → resume → STP,
|
||
禁止直改 duplicate_status 绕过门禁。
|
||
Body 字段:
|
||
operation_id: string(必填,客户端生成)
|
||
user_action: 'reuse_existing' | 'create_revision' | 'force_create' | 'adjudicate' | 'auto'(默认 auto)
|
||
expected_case_version: integer(可选,版本校验过期抛 409)
|
||
source_content_hash: string(可选,请求快照用于参数一致性)
|
||
"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
payload = request.get_json(silent=True) if request.is_json else None
|
||
if not isinstance(payload, dict):
|
||
payload = {}
|
||
from app.core.errors import ValidationError
|
||
operation_id = str(payload.get('operation_id') or '').strip()
|
||
if not operation_id:
|
||
raise ValidationError(
|
||
'operation_id required (client-generated idempotency component)',
|
||
code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED',
|
||
)
|
||
user_action_raw = str(payload.get('user_action') or 'auto').strip() or 'auto'
|
||
allowed = {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'}
|
||
if user_action_raw not in allowed:
|
||
raise ValidationError(
|
||
f'invalid user_action: {user_action_raw}',
|
||
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
|
||
details={'allowed': sorted(allowed)},
|
||
)
|
||
user_action = user_action_raw # type: ignore[assignment]
|
||
expected_case_version = payload.get('expected_case_version')
|
||
if expected_case_version is not None:
|
||
try:
|
||
expected_case_version = int(expected_case_version)
|
||
except (TypeError, ValueError):
|
||
raise ValidationError(
|
||
'expected_case_version must be integer if provided',
|
||
code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION',
|
||
)
|
||
else:
|
||
expected_case_version = None
|
||
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(
|
||
user_id=int(user.id),
|
||
case_no=str(case_no),
|
||
operation_id=operation_id,
|
||
user_action=user_action,
|
||
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())
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/access/version-history',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_audit_shipping_order_review_version_history(case_no: str):
|
||
"""
|
||
记录打开版本历史抽屉的访问审计。
|
||
|
||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||
"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
|
||
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
|
||
run_no = str(case.run.run_no) if getattr(case, 'run', None) is not None else None
|
||
record_access_audit(
|
||
action='view_order_review_version_history',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case.case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case.case_no),
|
||
run_no=run_no,
|
||
metadata={
|
||
'access_action': 'view_order_review_version_history',
|
||
'workbench_event': 'review_version_history_viewed',
|
||
},
|
||
)
|
||
record_fulfillment_audit(
|
||
event_type='review_version_history_viewed',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case.case_no),
|
||
action='view_order_review_version_history',
|
||
actor_type='user',
|
||
actor_id=user.id,
|
||
review_case_no=str(case.case_no),
|
||
run_no=run_no,
|
||
metadata={'panel': 'version_history'},
|
||
source='workspace_api',
|
||
sensitivity_level='sensitive',
|
||
)
|
||
db.session.commit()
|
||
return _ok({'audited': True, 'case_no': str(case.case_no)})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/access/eligibility-details',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
|
||
"""
|
||
记录打开完整建单检查抽屉的访问审计。
|
||
|
||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||
"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
|
||
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
|
||
run_no = str(case.run.run_no) if getattr(case, 'run', None) is not None else None
|
||
record_access_audit(
|
||
action='view_order_review_eligibility_details',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case.case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case.case_no),
|
||
run_no=run_no,
|
||
metadata={
|
||
'access_action': 'view_order_review_eligibility_details',
|
||
'workbench_event': 'review_eligibility_details_viewed',
|
||
},
|
||
)
|
||
record_fulfillment_audit(
|
||
event_type='review_eligibility_details_viewed',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case.case_no),
|
||
action='view_order_review_eligibility_details',
|
||
actor_type='user',
|
||
actor_id=user.id,
|
||
review_case_no=str(case.case_no),
|
||
run_no=run_no,
|
||
metadata={'panel': 'eligibility_details'},
|
||
source='workspace_api',
|
||
sensitivity_level='sensitive',
|
||
)
|
||
db.session.commit()
|
||
return _ok({'audited': True, 'case_no': str(case.case_no)})
|
||
|
||
|
||
def _review_draft_payload(
|
||
*,
|
||
user_id: int,
|
||
case_no: str,
|
||
action: str,
|
||
kind: str = 'draft',
|
||
) -> dict:
|
||
"""
|
||
读取复核写接口 JSON 请求体;非对象时按 Case 写拒绝审计。
|
||
|
||
核心逻辑:写接口统一要求对象;Case 可定位时落 rejected 审计再抛 VALIDATION.INVALID_PARAM,
|
||
避免路由层静默丢拒绝痕迹。confirm 走确认审计族,其余走草稿审计族。
|
||
"""
|
||
payload = request.get_json(silent=True)
|
||
if isinstance(payload, dict):
|
||
return payload
|
||
if kind == 'confirm':
|
||
from app.core.errors import ValidationError as _ValidationError
|
||
from app.services.shipping_notice.order_review_confirmation_service import reject_confirm_precondition
|
||
|
||
reject_confirm_precondition(
|
||
user_id=int(user_id),
|
||
case_no=case_no,
|
||
error=_ValidationError('Review draft payload must be an object', code='VALIDATION.INVALID_PARAM'),
|
||
)
|
||
from app.services.shipping_notice.order_review_draft_service import reject_invalid_draft_request_payload
|
||
|
||
reject_invalid_draft_request_payload(user_id=int(user_id), case_no=case_no, action=action)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/header-fields/<field_id>', methods=['PATCH'])
|
||
def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: str):
|
||
"""修改或恢复一个复核订单头字段;必须携带当前草稿版本。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='header_field_changed')
|
||
result = patch_header_field(
|
||
user_id=user.id, case_no=case_no, field_id=field_id, value=payload.get('value'),
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
restore_machine=bool(payload.get('restore_machine')),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/fields/<field_id>', methods=['PATCH'])
|
||
def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str):
|
||
"""修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import patch_line_field
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed')
|
||
result = patch_line_field(
|
||
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'),
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
restore_machine=bool(payload.get('restore_machine')),
|
||
override_reason_code=payload.get('override_reason_code'),
|
||
override_reason_text=payload.get('override_reason_text'),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines', methods=['POST'])
|
||
def workspace_add_shipping_order_review_line(case_no: str):
|
||
"""新增一条空人工复核行;当前阶段仅保存草稿,不执行确认建单。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import add_line
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_added')
|
||
result = add_line(user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'))
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/copy', methods=['POST'])
|
||
def workspace_copy_shipping_order_review_line(case_no: str, line_key: str):
|
||
"""复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import copy_line
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied')
|
||
result = copy_line(
|
||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>', methods=['DELETE'])
|
||
def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||
"""删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import delete_line
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted')
|
||
result = delete_line(
|
||
user_id=user.id, case_no=case_no, line_key=line_key,
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/validate', methods=['POST'])
|
||
def workspace_validate_shipping_order_review_draft(case_no: str):
|
||
"""显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_resume_service import (
|
||
attach_resume_outcome,
|
||
resume_after_review_change,
|
||
)
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
|
||
# 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 →
|
||
# Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。
|
||
resume = resume_after_review_change(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
trigger='draft_validated',
|
||
change_type=None,
|
||
skip_validate=False,
|
||
allow_auto_create=True,
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
)
|
||
return _ok(attach_resume_outcome({'case': resume.get('case')}, resume))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/draft/inventory-routing/reroute',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||
"""
|
||
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
|
||
|
||
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing
|
||
|
||
payload = _review_draft_payload(
|
||
user_id=user.id, case_no=case_no, action='inventory_routing_rerouted',
|
||
)
|
||
result = reroute_inventory_routing(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
idempotency_key=payload.get('idempotency_key'),
|
||
line_key=payload.get('line_key'),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/retry',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_retry_shipping_order_review_customer_resolution(case_no: str):
|
||
"""
|
||
重新识别客户(不重解析 PDF),供复核工作台「重新识别客户」按钮调用。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_customer_service import (
|
||
retry_review_case_customer_resolution,
|
||
)
|
||
|
||
return _ok(retry_review_case_customer_resolution(user_id=user.id, case_no=case_no))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/confirm',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||
"""
|
||
建单前确认标准客户;写 Bill-to match 并刷新建单资格。
|
||
"""
|
||
user = _require_user()
|
||
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
|
||
from app.services.shipping_notice.order_review_customer_service import (
|
||
confirm_review_case_customer,
|
||
)
|
||
|
||
return _ok(confirm_review_case_customer(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
customer_id=customer_id,
|
||
reason=str(data.get('reason') or '').strip() or None,
|
||
))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||
"""
|
||
显式重校验 Reservation 并触发统一恢复协调。
|
||
|
||
Body: expected_draft_version
|
||
"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.services.shipping_notice.order_review_reservation_service import (
|
||
revalidate_review_case_reservation,
|
||
)
|
||
|
||
result = revalidate_review_case_reservation(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
expected_draft_version=data.get('expected_draft_version'),
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/audit-timeline',
|
||
methods=['GET'],
|
||
)
|
||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||
|
||
case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
|
||
page = request.args.get('page', 1, type=int)
|
||
page_size = request.args.get('page_size', 50, type=int)
|
||
payload = list_review_case_audit_timeline(
|
||
user_id=user.id,
|
||
case_no=str(case.case_no),
|
||
page=page,
|
||
page_size=page_size,
|
||
)
|
||
record_access_audit(
|
||
action='view_order_review_audit_trail',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case.case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case.case_no),
|
||
)
|
||
db.session.commit()
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/decide',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||
"""
|
||
写入行级履约决定。
|
||
|
||
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version?
|
||
"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||
decide_review_line_fulfillment,
|
||
)
|
||
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
result = decide_review_line_fulfillment(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
line_key=str(data.get('line_key') or ''),
|
||
decision_code=str(data.get('decision_code') or ''),
|
||
reason=str(data.get('reason') or '').strip() or None,
|
||
release_field_values=(
|
||
data.get('release_field_values')
|
||
if isinstance(data.get('release_field_values'), dict) else None
|
||
),
|
||
expected_draft_version=data.get('expected_draft_version'),
|
||
actor_is_admin=is_admin,
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/wave',
|
||
methods=['POST'],
|
||
)
|
||
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,后续版本可收敛删除)。
|
||
"""
|
||
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,
|
||
)
|
||
|
||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||
formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False}
|
||
line_keys = list(data.get('line_keys') or [])
|
||
idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key')
|
||
reason = str(data.get('reason') or '').strip() or None
|
||
|
||
if formal.get('has_formal_ot'):
|
||
result = create_post_ot_fulfillment_wave(
|
||
case_no=str(case_no),
|
||
line_keys=line_keys,
|
||
decision_source='user',
|
||
actor_user_id=int(user.id),
|
||
reason=reason,
|
||
idempotency_key=idem,
|
||
)
|
||
from app.services.shipping_notice.post_ot_wave_progress_service import (
|
||
schedule_post_ot_wave_progress,
|
||
)
|
||
progress = schedule_post_ot_wave_progress(
|
||
task_no=str(result.get('task_no') or ''),
|
||
wave_no=result.get('wave_no'),
|
||
line_keys=list(result.get('accepted_line_keys') or line_keys),
|
||
review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None,
|
||
idempotency_row_id=result.get('idempotency_row_id'),
|
||
request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None,
|
||
created_by_id=int(user.id),
|
||
commit=False,
|
||
)
|
||
db.session.commit()
|
||
result = dict(result)
|
||
result['confirm_ok'] = True
|
||
result['confirm_outcome'] = 'post_ot_wave_progress_scheduled' if (
|
||
progress or {}
|
||
).get('auto_progress_started') else 'post_ot_wave_progress_not_scheduled'
|
||
result['wave_progress'] = progress
|
||
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),
|
||
)
|
||
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(
|
||
'/shipping-notice/order-review-cases/<case_no>/line-fulfillment/close',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||
"""
|
||
关闭行级或 Case 剩余开放行。
|
||
|
||
Body: reason, line_keys?, expected_draft_version?
|
||
"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||
close_remaining_fulfillment,
|
||
)
|
||
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
result = close_remaining_fulfillment(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
reason=str(data.get('reason') or ''),
|
||
line_keys=list(data.get('line_keys') or []) or None,
|
||
expected_draft_version=data.get('expected_draft_version'),
|
||
actor_is_admin=is_admin,
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/duplicate-refresh',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_refresh_shipping_order_review_duplicate(case_no: str):
|
||
"""重新检测建单前重复订单(复核工作台)。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_duplicate_service import (
|
||
refresh_review_case_duplicate,
|
||
)
|
||
|
||
return _ok(refresh_review_case_duplicate(user_id=user.id, case_no=case_no))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/duplicate-resolution',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_resolve_shipping_order_review_duplicate(case_no: str):
|
||
"""
|
||
裁决建单前重复订单:open_existing | create_revision | force_create。
|
||
|
||
Body: action, target_task_no?, reason?
|
||
"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.services.shipping_notice.order_review_duplicate_service import (
|
||
resolve_review_case_duplicate,
|
||
)
|
||
|
||
return _ok(resolve_review_case_duplicate(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
action=str(data.get('action') or '').strip(),
|
||
target_task_no=str(data.get('target_task_no') or '').strip() or None,
|
||
reason=str(data.get('reason') or '').strip() or None,
|
||
))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/field-conflicts',
|
||
methods=['GET'],
|
||
)
|
||
def workspace_list_shipping_order_review_field_conflicts(case_no: str):
|
||
"""列出建单前 Candidate 字段冲突(复核工作台集中裁决区)。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_field_conflict_service import (
|
||
list_review_case_field_conflicts,
|
||
)
|
||
|
||
return _ok(list_review_case_field_conflicts(user_id=user.id, case_no=case_no))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/field-conflicts/<path:conflict_key>/resolve',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_resolve_shipping_order_review_field_conflict(case_no: str, conflict_key: str):
|
||
"""
|
||
裁决建单前字段冲突:写入 Draft 人工值并清除 Candidate 冲突项。
|
||
|
||
Body: resolution=adopt_option|custom, option_index?, custom_value?,
|
||
expected_draft_version, reason?
|
||
"""
|
||
user = _require_user()
|
||
data = request.get_json(silent=True) or {}
|
||
from app.services.shipping_notice.order_review_field_conflict_service import (
|
||
resolve_review_case_field_conflict,
|
||
)
|
||
|
||
option_index = data.get('option_index')
|
||
if option_index is not None:
|
||
try:
|
||
option_index = int(option_index)
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError(
|
||
'option_index is invalid',
|
||
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
|
||
details={'field': 'option_index'},
|
||
) from exc
|
||
result = resolve_review_case_field_conflict(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
conflict_key=conflict_key,
|
||
resolution=str(data.get('resolution') or '').strip(),
|
||
option_index=option_index,
|
||
custom_value=data.get('custom_value'),
|
||
expected_draft_version=data.get('expected_draft_version'),
|
||
reason=str(data.get('reason') or '').strip() or None,
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/confirm', methods=['POST'])
|
||
def workspace_confirm_shipping_order_review_case(case_no: str):
|
||
"""
|
||
确认一份 PDF 草稿并独立建单;与确认同事务入队自动推进 Job。
|
||
|
||
契约:HTTP 200 + confirm_ok 仅表示建单成功;自动推进看 confirm_outcome /
|
||
auto_progress.status(enqueue_failed 等为可恢复失败,不是建单回滚)。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||
confirm_review_case,
|
||
finalize_sync_auto_progress_after_commit,
|
||
resolve_confirm_outcome,
|
||
schedule_auto_progress_after_review_confirm,
|
||
)
|
||
|
||
payload = _review_draft_payload(
|
||
user_id=user.id, case_no=case_no, action='confirm_review_case', kind='confirm',
|
||
)
|
||
result = confirm_review_case(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
idempotency_key=request.headers.get('Idempotency-Key') or payload.get('idempotency_key'),
|
||
confirm_note=payload.get('confirm_note'),
|
||
warning_acknowledgements=payload.get('warning_acknowledgements'),
|
||
)
|
||
# [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。
|
||
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,
|
||
)
|
||
# [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op)
|
||
if result.get('task_no') and not result.get('idempotent_replay'):
|
||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||
enqueue_post_ot_auto_fulfill_job,
|
||
)
|
||
enqueue_post_ot_auto_fulfill_job(
|
||
task_no=str(result.get('task_no')),
|
||
trigger='ot_created',
|
||
commit=False,
|
||
)
|
||
db.session.commit()
|
||
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
|
||
progress = finalize_sync_auto_progress_after_commit(progress)
|
||
result = dict(result)
|
||
result.pop('trigger_auto_progress', None)
|
||
result['confirm_ok'] = True
|
||
if progress is None:
|
||
result['auto_progress_started'] = False
|
||
result['auto_progress'] = {
|
||
'status': 'not_scheduled',
|
||
'message': '无需调度自动推进,或任务已离开待推进态',
|
||
}
|
||
else:
|
||
result['auto_progress_started'] = bool(progress.get('auto_progress_started'))
|
||
result['auto_progress'] = {
|
||
'status': progress.get('status'),
|
||
'message': progress.get('message'),
|
||
'enqueue_result': progress.get('enqueue_result'),
|
||
'checkpoint': progress.get('checkpoint'),
|
||
}
|
||
result['confirm_outcome'] = resolve_confirm_outcome(
|
||
{
|
||
'status': (result.get('auto_progress') or {}).get('status'),
|
||
'auto_progress_started': result.get('auto_progress_started'),
|
||
}
|
||
)
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/manual-draft', methods=['POST'])
|
||
def workspace_create_shipping_order_review_manual_draft(case_no: str):
|
||
"""启用无机器订单 PDF 的唯一人工草稿;不会创建第二个 Case、Candidate 或 Task。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_disposition_service import create_manual_draft
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='create_manual_draft')
|
||
result = create_manual_draft(user_id=user.id, case_no=case_no, comment=payload.get('comment'))
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/disposition/non-order', methods=['POST'])
|
||
def workspace_mark_shipping_order_review_non_order(case_no: str):
|
||
"""把一份 PDF 独立标记为非订单;后端拒绝已确认和已替代的终态 Case。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_disposition_service import mark_non_order
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='mark_non_order')
|
||
result = mark_non_order(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/disposition/quality-issue', methods=['POST'])
|
||
def workspace_mark_shipping_order_review_quality_issue(case_no: str):
|
||
"""保留当前 PDF 和机器证据地标记质量异常,后续可单文件重识别或补件。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='mark_quality_issue')
|
||
result = mark_quality_issue(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/reparse', methods=['POST'])
|
||
def workspace_reparse_shipping_order_review_document(case_no: str):
|
||
"""仅重识别当前 Case 的 PDF,永不借用整批 Run 重跑接口或覆盖原始文件。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='reparse_document')
|
||
run, reused = reparse_case_document(
|
||
user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'),
|
||
)
|
||
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-review-cases/<case_no>/evidence', methods=['GET'])
|
||
def workspace_list_shipping_order_review_evidence(case_no: str):
|
||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应;访问留痕。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_evidence_service import list_case_evidence
|
||
|
||
payload = list_case_evidence(user_id=user.id, case_no=case_no)
|
||
quality_counts: dict[str, int] = {}
|
||
for item in payload.get('items') or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
key = str(item.get('highlight_quality') or 'unavailable')
|
||
quality_counts[key] = quality_counts.get(key, 0) + 1
|
||
record_access_audit(
|
||
action='view_order_review_evidence_list',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'access_action': 'view_order_review_evidence_list',
|
||
'workbench_event': 'review_evidence_list_viewed',
|
||
'item_count': len(payload.get('items') or []),
|
||
'highlight_quality_counts': quality_counts,
|
||
},
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence/<evidence_id>', methods=['GET'])
|
||
def workspace_get_shipping_order_review_evidence(case_no: str, evidence_id: str):
|
||
"""读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用;访问留痕。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_evidence_service import (
|
||
build_highlight_audit_summary,
|
||
get_case_evidence,
|
||
)
|
||
|
||
payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id)
|
||
record_access_audit(
|
||
action='view_order_review_evidence',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'access_action': 'view_order_review_evidence',
|
||
'workbench_event': 'review_evidence_focused',
|
||
'highlight': build_highlight_audit_summary(payload),
|
||
},
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/evidence/<evidence_id>/highlight-diagnostic',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_view_shipping_order_review_highlight_diagnostic(case_no: str, evidence_id: str):
|
||
"""
|
||
记录坐标诊断面板查看审计;不返回 PDF 正文,不改变业务状态。
|
||
|
||
核心逻辑:复用 get_case_evidence 鉴权;写入 review_highlight_diagnostic_viewed。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_evidence_service import (
|
||
build_highlight_audit_summary,
|
||
get_case_evidence,
|
||
)
|
||
|
||
payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id)
|
||
summary = build_highlight_audit_summary(payload)
|
||
record_access_audit(
|
||
action='view_order_review_highlight_diagnostic',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'access_action': 'view_order_review_highlight_diagnostic',
|
||
'workbench_event': 'review_highlight_diagnostic_viewed',
|
||
'highlight': summary,
|
||
},
|
||
)
|
||
return _ok({'case_no': case_no, 'highlight': summary})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/field-locate',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||
"""
|
||
记录字段「定位原文」点击审计(含无 evidence 的红色诊断入口)。
|
||
|
||
核心逻辑:鉴权 Case owner;不返回 PDF 正文;写入 review_field_locate_attempted。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||
|
||
body = request.get_json(silent=True) or {}
|
||
field_id = str(body.get('field_id') or '').strip()[:128]
|
||
if not field_id:
|
||
from app.core.errors import ValidationError
|
||
raise ValidationError('field_id is required')
|
||
# 鉴权:确认 Case 归属当前用户
|
||
get_user_review_case(user_id=user.id, case_no=case_no)
|
||
line_index = body.get('line_index')
|
||
try:
|
||
line_index = int(line_index) if line_index is not None else None
|
||
except (TypeError, ValueError):
|
||
line_index = None
|
||
quality = str(body.get('highlight_quality') or 'unavailable').strip()[:32]
|
||
evidence_id = str(body.get('evidence_id') or '').strip()[:160] or None
|
||
has_evidence = bool(body.get('has_evidence'))
|
||
pdf_located = bool(body.get('pdf_located'))
|
||
issue_codes = body.get('coordinate_issue_codes') if isinstance(body.get('coordinate_issue_codes'), list) else []
|
||
record_access_audit(
|
||
action='attempt_order_review_field_locate',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'access_action': 'attempt_order_review_field_locate',
|
||
'workbench_event': 'review_field_locate_attempted',
|
||
'field_id': field_id,
|
||
'line_index': line_index,
|
||
'highlight_quality': quality,
|
||
'has_evidence': has_evidence,
|
||
'evidence_id': evidence_id,
|
||
'pdf_located': pdf_located,
|
||
'coordinate_issue_codes': [str(code)[:64] for code in issue_codes[:20]],
|
||
},
|
||
)
|
||
return _ok({
|
||
'case_no': case_no,
|
||
'field_id': field_id,
|
||
'highlight_quality': quality,
|
||
'has_evidence': has_evidence,
|
||
'pdf_located': pdf_located,
|
||
})
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/llm-suggestions', methods=['GET'])
|
||
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
|
||
|
||
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/llm-suggestions', methods=['POST'])
|
||
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.order_review_llm_service import request_field_suggestion
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='request_llm_suggestion')
|
||
result = request_field_suggestion(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
field_id=str(payload.get('field_id') or ''),
|
||
line_key=payload.get('line_key'),
|
||
evidence_level=payload.get('evidence_level'),
|
||
issue_code=payload.get('issue_code'),
|
||
allow_full_pdf=bool(payload.get('allow_full_pdf')),
|
||
is_admin=is_admin,
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/llm-suggestions/<suggestion_no>/adjudicate',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||
user = _require_user()
|
||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
|
||
|
||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
|
||
result = decide_suggestion(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
suggestion_no=suggestion_no,
|
||
decision=payload.get('decision'),
|
||
expected_draft_version=payload.get('expected_draft_version'),
|
||
value=payload.get('value'),
|
||
reason=payload.get('reason'),
|
||
note=payload.get('note'),
|
||
is_admin=is_admin,
|
||
)
|
||
db.session.commit()
|
||
return _ok(result)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/document-preview', methods=['GET'])
|
||
def workspace_preview_shipping_order_review_document(case_no: str):
|
||
"""应用代理当前用户的 PDF 预览流;禁止向浏览器下发 MinIO key 或直连地址;访问留痕。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_evidence_service import get_case_pdf_bytes
|
||
|
||
content, filename = get_case_pdf_bytes(user_id=user.id, case_no=case_no)
|
||
record_access_audit(
|
||
action='preview_order_review_document',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'preview': 'pdf',
|
||
'access_action': 'preview_order_review_document',
|
||
'workbench_event': 'sensitive_evidence_viewed',
|
||
},
|
||
)
|
||
return send_file(
|
||
BytesIO(content), mimetype='application/pdf', as_attachment=False, download_name=filename,
|
||
conditional=True,
|
||
)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-review-cases/<case_no>/intake-parse-context', methods=['GET'],
|
||
)
|
||
def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||
"""
|
||
返回当前 Case 所属 Intake 的受控解析上下文,并记录敏感读取访问审计。
|
||
|
||
核心逻辑:只委托 Case 边界服务构造附件/同 Intake 邮件正文 DTO;PDF 二进制仍必须通过
|
||
document-preview 代理读取,禁止把对象存储地址或资产内部定位下发至浏览器。
|
||
"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||
from app.services.shipping_notice.order_review_evidence_service import get_case_intake_parse_context
|
||
|
||
payload = get_case_intake_parse_context(user_id=user.id, case_no=case_no)
|
||
attachment = payload['attachment']
|
||
record_access_audit(
|
||
action='view_order_review_intake_parse_context',
|
||
aggregate_type='order_review_case',
|
||
aggregate_id=str(case_no),
|
||
actor_id=user.id,
|
||
document_id=attachment['document_id'],
|
||
review_case_no=str(case_no),
|
||
metadata={
|
||
'access_action': 'view_order_review_intake_parse_context',
|
||
'workbench_event': 'intake_parse_context_viewed',
|
||
'attachment_preview_kind': attachment['preview_kind'],
|
||
'has_email_context': payload['email'] is not None,
|
||
},
|
||
)
|
||
return _ok(payload)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-preview', methods=['GET'])
|
||
def workspace_preview_shipping_order_review_email(case_no: str):
|
||
"""消费 Case 绑定的短时令牌,返回强 CSP 隔离的 EML 原始 HTML 视觉预览。"""
|
||
from app.services.shipping_notice.eml_preview_service import consume_eml_preview_grant
|
||
|
||
user = get_current_user()
|
||
html = consume_eml_preview_grant(
|
||
token=str(request.args.get('preview_token') or ''), user_id=user.id if user else None, case_no=case_no,
|
||
)
|
||
if not html:
|
||
raise NotFoundError('Email preview is unavailable', code='SHIPPING.REVIEW_EMAIL_PREVIEW_NOT_FOUND')
|
||
response = Response(html, mimetype='text/html')
|
||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||
response.headers['Pragma'] = 'no-cache'
|
||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||
response.headers['Content-Security-Policy'] = (
|
||
"default-src 'none'; script-src 'none'; connect-src 'none'; img-src 'none'; media-src 'none'; "
|
||
"font-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; "
|
||
"style-src 'unsafe-inline'; navigate-to 'none'"
|
||
)
|
||
return response
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||
"""返回当前复核 Case 同 Intake 邮件正文的受控 HTML/文本证据预览。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.order_review_evidence_service import get_case_email_evidence_text
|
||
|
||
return _ok(get_case_email_evidence_text(
|
||
user_id=user.id,
|
||
case_no=case_no,
|
||
document_id=document_id,
|
||
evidence_id=str(request.args.get('evidence_id') or '').strip() or None,
|
||
))
|
||
|
||
|
||
@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.fulfillment_audit import record_fulfillment_audit
|
||
from app.services.shipping_notice.order_extraction_run_service import (
|
||
get_order_extraction_run,
|
||
mark_order_extraction_run_seen,
|
||
)
|
||
|
||
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
|
||
before = {'status': 'seen' if run.seen_at is not None else 'unseen'}
|
||
seen = mark_order_extraction_run_seen(user_id=user.id, run_no=run_no)
|
||
after_status = 'seen' if (seen or run.seen_at is not None) else before['status']
|
||
record_fulfillment_audit(
|
||
event_type='order_extraction_run_seen',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run.run_no),
|
||
action='mark_run_seen',
|
||
actor_type='user',
|
||
actor_id=user.id,
|
||
run_no=str(run.run_no),
|
||
conversation_id=run.conversation_id,
|
||
result='success' if seen else ('ignored' if before['status'] == after_status else 'success'),
|
||
before=before,
|
||
after={'status': after_status},
|
||
metadata={'first_seen': bool(seen)},
|
||
source='api',
|
||
strict=True,
|
||
)
|
||
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>/cancel', methods=['POST'])
|
||
def workspace_cancel_shipping_order_extraction_run(run_no: str):
|
||
"""
|
||
请求取消整批订单抽取。
|
||
|
||
核心逻辑:排队项立即取消,执行中项进入正在取消;已完成结果保留。管理员代取消必须写原因。
|
||
"""
|
||
user = _require_user()
|
||
body = request.get_json(silent=True) or {}
|
||
if body and not isinstance(body, dict):
|
||
raise ValidationError('Request body must be an object')
|
||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
|
||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||
|
||
run = cancel_order_extraction_run(
|
||
actor=user,
|
||
run_no=run_no,
|
||
reason=str(body.get('reason') or '') or None,
|
||
reason_code=str(body.get('reason_code') or '') or None,
|
||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||
)
|
||
db.session.commit()
|
||
return ok({'run': serialize_order_extraction_run(run)}, request_id=getattr(g, 'request_id', None), status=202)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route(
|
||
'/shipping-notice/order-extraction-runs/<run_no>/documents/<int:document_id>/cancel',
|
||
methods=['POST'],
|
||
)
|
||
def workspace_cancel_shipping_order_extraction_document(run_no: str, document_id: int):
|
||
"""请求取消单个 PDF Unit;权限与原因规则同整批取消。"""
|
||
user = _require_user()
|
||
body = request.get_json(silent=True) or {}
|
||
if body and not isinstance(body, dict):
|
||
raise ValidationError('Request body must be an object')
|
||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_unit
|
||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_documents
|
||
|
||
unit = cancel_order_extraction_unit(
|
||
actor=user,
|
||
run_no=run_no,
|
||
document_id=int(document_id),
|
||
reason=str(body.get('reason') or '') or None,
|
||
reason_code=str(body.get('reason_code') or '') or None,
|
||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||
)
|
||
run = unit.plan.run if unit.plan is not None else None
|
||
db.session.commit()
|
||
documents = serialize_workspace_run_documents(run) if run is not None else []
|
||
document = next((item for item in documents if int(item.get('document_id') or 0) == int(document_id)), None)
|
||
return ok(
|
||
{
|
||
'run': serialize_order_extraction_run(run) if run is not None else None,
|
||
'document': document,
|
||
},
|
||
request_id=getattr(g, 'request_id', None),
|
||
status=202,
|
||
)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/timeline', methods=['GET'])
|
||
def workspace_shipping_order_extraction_timeline(run_no: str):
|
||
"""返回用户可见的 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 list_user_order_extraction_progress_events
|
||
|
||
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
|
||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
|
||
record_access_audit(
|
||
action='view_order_extraction_timeline',
|
||
aggregate_type='order_extraction_run',
|
||
aggregate_id=str(run_no),
|
||
actor_id=user.id,
|
||
run_no=str(run_no),
|
||
metadata={'event_count': len(items or []), 'surface': 'timeline', 'poll': True},
|
||
)
|
||
return _ok({'items': items})
|
||
|
||
|
||
@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/<run_no>/reparse-batch', methods=['POST'])
|
||
def workspace_reparse_shipping_order_extraction_batch(run_no: str):
|
||
"""按 PDF 子任务重解析一个批次;已确认/履约文件由服务端预检排除。"""
|
||
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_review_disposition_service import reparse_batch_documents
|
||
|
||
result = reparse_batch_documents(
|
||
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(result, 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。
|
||
|
||
核心逻辑:可按会话过滤;传 page 时返回分页供任务中心续办,否则保持会话内短列表契约。
|
||
"""
|
||
user = _require_user()
|
||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||
status = str(request.args.get('status') or '').strip() or None
|
||
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,
|
||
)
|
||
|
||
if page_raw is not None or page_size_raw is not None:
|
||
try:
|
||
page = int(page_raw or 1)
|
||
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(
|
||
user_id=user.id,
|
||
conversation_id=conversation_id,
|
||
status=status,
|
||
page=page,
|
||
page_size=page_size,
|
||
)
|
||
assert isinstance(payload, dict)
|
||
return _ok({
|
||
'items': [serialize_order_extraction_run(row) for row in payload['items']],
|
||
'total': payload['total'],
|
||
'page': payload['page'],
|
||
'page_size': payload['page_size'],
|
||
})
|
||
|
||
try:
|
||
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(
|
||
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]})
|
||
|
||
|
||
@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
|
||
upload_batch_id = str(body.get('upload_batch_id') or '').strip()
|
||
if not upload_batch_id:
|
||
raise ValidationError(
|
||
'upload_batch_id is required',
|
||
code='SHIPPING_NOTICE.UPLOAD_BATCH_REQUIRED',
|
||
)
|
||
if len(upload_batch_id) > 36:
|
||
raise ValidationError(
|
||
'upload_batch_id is too long',
|
||
code='SHIPPING_NOTICE.UPLOAD_BATCH_INVALID',
|
||
)
|
||
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,
|
||
upload_batch_id=upload_batch_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 'selected' not in body:
|
||
raise ValidationError('selected 必须提供;订单字段请在人工复核工作台编辑')
|
||
if set(body) != {'selected'}:
|
||
raise ValidationError('订单候选不支持业务摘要覆盖,请在人工复核工作台编辑')
|
||
from app.services.shipping_notice.candidate_service import update_candidate
|
||
|
||
return _ok(
|
||
update_candidate(
|
||
user_id=user.id,
|
||
candidate_no=candidate_no,
|
||
selected=body['selected'],
|
||
)
|
||
)
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>/promote', methods=['POST'])
|
||
def workspace_promote_shipping_notice_candidate(candidate_no: str):
|
||
"""人工采纳 Dify 兜底识别的 Candidate。"""
|
||
user = _require_user()
|
||
from app.services.shipping_notice.candidate_service import promote_candidate
|
||
|
||
return _ok(promote_candidate(user_id=user.id, candidate_no=candidate_no))
|
||
|
||
|
||
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>/reject', methods=['POST'])
|
||
def workspace_reject_shipping_notice_candidate(candidate_no: str):
|
||
"""人工驳回尚未进入履约的 Candidate。"""
|
||
user = _require_user()
|
||
body = request.get_json(silent=True) or {}
|
||
if not isinstance(body, dict):
|
||
raise ValidationError('请求体必须为对象')
|
||
from app.services.shipping_notice.candidate_service import reject_candidate
|
||
|
||
return _ok(reject_candidate(user_id=user.id, candidate_no=candidate_no, reason=body.get('reason')))
|
||
|
||
|
||
@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,
|
||
)
|
||
)
|
||
|
||
|