feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

+485 -323
View File
@@ -3,9 +3,11 @@ 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、workflow_progress_projection / workflow_ledger_service。
tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint。
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
`/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404;
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
"""
from __future__ import annotations
@@ -19,27 +21,22 @@ from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingBatch, ShippingNoticeIntake, ShippingOrderExtraction, ShippingTask
from app.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.tool_common import switch_batch_focus
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
count_my_todos,
get_batch_for_user,
get_conversation_batch_workspace,
get_focus_task_for_batch,
get_task_for_user,
list_batches_for_user,
list_my_todos,
list_tasks_page_for_user,
list_tasks_for_batch,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
@@ -51,7 +48,7 @@ from app.services.shipping_notice.task_disposition_service import (
purge_task_permanently,
restore_task_from_recycle_bin,
)
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
from app.services.shipping_notice.ui_state import build_task_ui_state
from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
list_customer_options,
@@ -165,7 +162,7 @@ def _batch_task_nos(data: dict) -> list[str]:
return normalized
def _can_dispose_task(user, task: ShippingTask) -> bool:
def _can_dispose_task(user, task: ShippingNotice) -> bool:
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
@@ -259,12 +256,102 @@ def workspace_batch_restore_shipping_tasks():
@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。"""
@@ -282,6 +369,25 @@ def workspace_shipping_export_archive():
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():
"""列出可供当前业务用户确认的启用标准客户。"""
@@ -323,10 +429,10 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
user = _require_user()
extraction = (
db.session.query(ShippingOrderExtraction)
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingOrderExtraction.intake_id)
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
.filter(
ShippingOrderExtraction.id == extraction_id,
ShippingNoticeIntake.user_id == user.id,
ShippingOrderIntake.user_id == user.id,
)
.one_or_none()
)
@@ -357,144 +463,10 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
"""返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。"""
user = _require_user()
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
def workspace_create_shipping_batch_from_notices():
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
user = _require_user()
uploads = request.files.getlist('files')
if not uploads:
single = request.files.get('file')
if single:
uploads = [single]
if not uploads:
raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.batch_from_notices import (
create_shipping_batch_from_notice_items,
intake_notice_uploads_for_batch,
)
from app.services.shipping_notice.batch_create_idempotency import (
normalize_create_idempotency_key,
warn_missing_create_idempotency_key,
)
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
conversation_id = str(request.form.get('conversation_id') or '').strip()
idempotency_key = normalize_create_idempotency_key(
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
)
if not idempotency_key:
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
try:
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
finally:
cleanup_temp_notice_uploads(temp_request_id)
created = create_shipping_batch_from_notice_items(
user_id=user.id,
conversation_id=conversation_id or None,
notice_items=notice_items,
file_summary=file_summary,
create_idempotency_key=idempotency_key,
)
return _ok(created)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""
返回批次详情与聚合 UI State。
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""
返回批次级 UI State。
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
"""返回指定批次下的任务列表。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
def workspace_shipping_batch_focus_task(batch_no: str):
"""返回指定批次当前焦点任务的摘要。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
raise NotFoundError('Focus task not found')
return _ok(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
def workspace_switch_shipping_batch_focus_task(batch_no: str):
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
comment = str(data.get('comment') or '').strip()
if not task_no:
raise ValidationError('task_no is required')
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
raise NotFoundError('Task not found in batch')
switch_batch_focus(
batch,
task,
source='workspace_api',
comment=comment or None,
extra={'actor_user_id': user.id},
)
db.session.commit()
return _ok({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user = _require_user()
data = request.get_json(silent=True) or {}
payload = {'user_id': user.id}
source_type = str(data.get('source_type') or '').strip()
if source_type:
payload['source_type'] = source_type
conversation_id = str(data.get('conversation_id') or '').strip()
if conversation_id:
payload['conversation_id'] = conversation_id
raw_content = str(data.get('raw_content') or '').strip()
if raw_content:
payload['raw_content'] = raw_content
from app.services.shipping_notice import tools as shipping_tools
return _ok(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice():
@@ -527,7 +499,7 @@ def workspace_create_shipping_task_from_notice():
if not intake.accepted:
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
task = ShippingTask.query.filter_by(task_no=task_id).first()
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
@@ -589,6 +561,38 @@ def workspace_shipping_task_detail(task_no: str):
})
@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):
"""
@@ -755,7 +759,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
cancellation = ShippingFreightCancellation.query.filter_by(id=cancellation_id).one_or_none()
if cancellation is None:
raise NotFoundError('Not found')
old_task = db.session.get(ShippingTask, cancellation.old_task_id)
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
@@ -1062,7 +1066,7 @@ def workspace_shipping_task_export(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
def workspace_list_shipping_notice_intakes():
def workspace_list_shipping_order_intakes():
"""列出当前会话下未消费的活跃接入记录。"""
user = _require_user()
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
@@ -1129,6 +1133,159 @@ def workspace_create_shipping_order_extraction_run():
)
@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;正文快照不会暴露给前端;访问留痕。"""
@@ -1433,16 +1590,28 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
@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_draft_service import validate_draft
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')
result = validate_draft(
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'),
)
db.session.commit()
return _ok(result)
resume = resume_after_review_change(
user_id=user.id,
case_no=case_no,
trigger='draft_validated',
change_type=None,
skip_validate=True,
allow_auto_create=True,
)
return _ok(attach_resume_outcome({'case': result}, resume))
@workspace_shipping_notice_bp.route(
@@ -1594,6 +1763,169 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
))
@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?, 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,
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):
"""
为选中完整明细行创建履约波次 Task。
Body: line_keys[], expected_draft_version, idempotency_key, reason?
与确认建单同样在同事务入队自动推进。
"""
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_fulfillment_decision_service import (
create_fulfillment_wave,
)
result = create_fulfillment_wave(
user_id=user.id,
case_no=case_no,
line_keys=list(data.get('line_keys') or []),
expected_draft_version=data.get('expected_draft_version'),
idempotency_key=data.get('idempotency_key') or request.headers.get('Idempotency-Key'),
reason=str(data.get('reason') or '').strip() or None,
)
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'))
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'],
@@ -2272,132 +2604,6 @@ def workspace_list_shipping_order_extraction_runs():
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
@workspace_shipping_notice_bp.route('/shipping-notice/workflows', methods=['GET'])
def workspace_list_shipping_notice_workflows():
"""列出会话开放 Workflow 与 Items;版面阶段 Item 已存在;访问留痕。"""
user = _require_user()
conversation_id = str(request.args.get('conversation_id') or '').strip()
if not conversation_id:
raise ValidationError('conversation_id is required')
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.workflow_progress_projection import project_conversation_workflows
payload = project_conversation_workflows(user_id=user.id, conversation_id=conversation_id)
record_access_audit(
action='view_workflows',
aggregate_type='shipping_notice_workflow',
aggregate_id=conversation_id,
actor_id=user.id,
conversation_id=conversation_id,
metadata={
'workflow_count': len(payload.get('workflows') or []),
'poll': True,
},
)
return _ok(payload)
@workspace_shipping_notice_bp.route('/shipping-notice/workflows/<workflow_no>', methods=['GET'])
def workspace_get_shipping_notice_workflow(workflow_no: str):
"""读取当前用户的 Workflow 详情与 Items;访问留痕。"""
user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.workflow_progress_projection import (
get_workflow_for_user,
serialize_workflow,
)
workflow = get_workflow_for_user(user_id=user.id, workflow_no=workflow_no)
payload = serialize_workflow(workflow, user_id=user.id, include_items=True)
record_access_audit(
action='view_workflow',
aggregate_type='shipping_notice_workflow',
aggregate_id=str(workflow.workflow_no),
actor_id=user.id,
conversation_id=workflow.conversation_id,
metadata={'status': str(workflow.status or ''), 'poll': True},
)
return _ok(payload)
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>', methods=['GET'])
def workspace_get_shipping_notice_workflow_item(item_no: str):
"""读取当前用户的 WorkflowItem 详情(含事件);访问留痕。"""
user = _require_user()
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.workflow_progress_projection import get_workflow_item_dto_for_user
payload = get_workflow_item_dto_for_user(user_id=user.id, item_no=item_no, include_events=True)
record_access_audit(
action='view_workflow_item',
aggregate_type='shipping_notice_workflow_item',
aggregate_id=str(payload.get('item_no') or item_no),
actor_id=user.id,
conversation_id=str(payload.get('conversation_id') or '') or None,
metadata={
'lifecycle_status': str(payload.get('lifecycle_status') or ''),
'poll': True,
},
)
return _ok(payload)
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/cancel', methods=['POST'])
def workspace_cancel_shipping_notice_workflow_item(item_no: str):
"""
用户取消单个 WorkflowItem。
核心逻辑:必填 reason;委托 cancel_workflow_item_for_user;返回关闭后的 Item 投影。
"""
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.workflow_ledger_service import cancel_workflow_item_for_user
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
item = cancel_workflow_item_for_user(
user_id=user.id,
item_no=item_no,
reason=body.get('reason'),
expected_lock_version=body.get('expected_lock_version'),
request_id=str(getattr(g, 'request_id', '') or '') or None,
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
)
db.session.commit()
return _ok({'item': serialize_workflow_item(item, include_events=False)})
@workspace_shipping_notice_bp.route('/shipping-notice/workflow-items/<item_no>/reparse', methods=['POST'])
def workspace_reparse_shipping_notice_workflow_item(item_no: str):
"""
用户对单个 WorkflowItem 发起重试/重新识别。
核心逻辑:必填 reason;有 Case 走单 PDF 重识别(新 Version);无 Case 且 Run 失败则重试入队;
返回最新 Item 投影与 reused 标记。
"""
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.workflow_ledger_service import reparse_workflow_item_for_user
from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item
item, reused = reparse_workflow_item_for_user(
user_id=user.id,
item_no=item_no,
reason=body.get('reason'),
comment=body.get('comment'),
request_id=str(getattr(g, 'request_id', '') or '') or None,
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
)
db.session.commit()
return _ok({
'item': serialize_workflow_item(item, include_events=False),
'reused': bool(reused),
})
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
def workspace_create_shipping_notice_intake():
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
@@ -2585,47 +2791,3 @@ def workspace_resolve_shipping_notice_candidate(candidate_no: str):
)
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
def workspace_create_shipping_batch_from_intakes():
"""从已解析接入记录确认建批。"""
user = _require_user()
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
raise ValidationError('请求体必须为对象')
intake_nos = body.get('intake_nos')
if not isinstance(intake_nos, list) or not intake_nos:
raise ValidationError('intake_nos is required')
conversation_id = str(body.get('conversation_id') or '').strip() or None
candidate_nos = body.get('candidate_nos')
if candidate_nos is not None and not isinstance(candidate_nos, list):
raise ValidationError('candidate_nos must be a list')
from app.services.shipping_notice.batch_create_idempotency import (
normalize_create_idempotency_key,
warn_missing_create_idempotency_key,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
idempotency_key = normalize_create_idempotency_key(
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
)
if not idempotency_key:
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
result = create_shipping_batch_from_intakes(
user_id=user.id,
conversation_id=conversation_id,
intake_nos=[str(item) for item in intake_nos],
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
create_idempotency_key=idempotency_key,
)
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return _ok(retry_batch_pending_tasks(batch.batch_no))