feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -28,5 +28,6 @@ import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
import app.api.admin.shipping_document_layouts # noqa: F401
|
||||
import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_legacy_stp_jobs.py
|
||||
|
||||
用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。
|
||||
依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。
|
||||
逻辑:
|
||||
• GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to)
|
||||
• GET /admin/shipping-notice/legacy-stp-jobs/<job_id> 单条详情 + 回链 Review Case
|
||||
• 所有接口严格 require_admin;不允许写任何 DB。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.legacy_stp_job_admin_service import (
|
||||
get_admin_legacy_stp_job,
|
||||
list_admin_legacy_stp_jobs,
|
||||
)
|
||||
|
||||
|
||||
def _qint(name: str, default: int) -> int:
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ''):
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f'{name} must be an integer') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/legacy-stp-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def admin_list_legacy_stp_jobs():
|
||||
"""历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。"""
|
||||
page = _qint('page', 1)
|
||||
page_size = _qint('page_size', 25)
|
||||
payload = list_admin_legacy_stp_jobs(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status=request.args.get('status'),
|
||||
job_type=request.args.get('job_type'),
|
||||
q=request.args.get('q'),
|
||||
case_no=request.args.get('case_no'),
|
||||
error_code=request.args.get('error_code'),
|
||||
blocking_reason=request.args.get('blocking_reason'),
|
||||
created_from=request.args.get('created_from'),
|
||||
created_to=request.args.get('created_to'),
|
||||
sort=request.args.get('sort') or '-created_at',
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/legacy-stp-jobs/<int:job_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def admin_get_legacy_stp_job(job_id: int):
|
||||
"""单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。"""
|
||||
payload = get_admin_legacy_stp_job(int(job_id))
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
+9
-176
@@ -2,10 +2,8 @@
|
||||
backend/app/api/chat.py
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、app.core.response、services.dify、integrations、
|
||||
shipping_notice.audit_service(货代会话删除审计)。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError;
|
||||
shipping_notice 会话删除写不可变审计并返回标准 envelope。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -30,7 +28,7 @@ from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderProcessingRun
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
@@ -206,12 +204,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(
|
||||
session: ChatSession,
|
||||
*, unseen_order_extraction_count: int = 0,
|
||||
unseen_order_extraction_severity: str | None = None,
|
||||
) -> dict:
|
||||
"""输出会话摘要及订单抽取待查看聚合,不返回 Run 内容或错误正文。"""
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
@@ -219,46 +212,9 @@ def _serialize_session(
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
'unseen_order_extraction_count': max(0, int(unseen_order_extraction_count or 0)),
|
||||
'unseen_order_extraction_severity': unseen_order_extraction_severity,
|
||||
}
|
||||
|
||||
|
||||
def _order_extraction_attention_by_conversation(
|
||||
*, user_id: int, agent_id: int, conversation_ids: set[str],
|
||||
) -> dict[str, tuple[int, str]]:
|
||||
"""聚合同用户同 Agent 尚未确认的终态订单抽取提醒,防止跨会话泄露。"""
|
||||
if not conversation_ids:
|
||||
return {}
|
||||
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
|
||||
status_severity = {
|
||||
'completed': 'info',
|
||||
'partially_completed': 'warning',
|
||||
'review_required': 'warning',
|
||||
'failed': 'error',
|
||||
'cancelled': 'error',
|
||||
}
|
||||
rows = db.session.query(
|
||||
ShippingOrderProcessingRun.conversation_id,
|
||||
ShippingOrderProcessingRun.status,
|
||||
).filter(
|
||||
ShippingOrderProcessingRun.user_id == user_id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == agent_id,
|
||||
ShippingOrderProcessingRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderProcessingRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderProcessingRun.seen_at.is_(None),
|
||||
).all()
|
||||
aggregate: dict[str, tuple[int, str]] = {}
|
||||
for conversation_id, status in rows:
|
||||
severity = status_severity.get(str(status or ''), 'info')
|
||||
count, existing = aggregate.get(conversation_id, (0, severity))
|
||||
aggregate[conversation_id] = (
|
||||
count + 1,
|
||||
severity if severity_rank[severity] >= severity_rank[existing] else existing,
|
||||
)
|
||||
return aggregate
|
||||
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
@@ -1074,90 +1030,36 @@ def get_chat_sessions():
|
||||
})
|
||||
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
attention_by_conversation = _order_extraction_attention_by_conversation(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_ids={str(item['conversation_id']) for item in sessions if item.get('conversation_id')},
|
||||
)
|
||||
for item in sessions:
|
||||
count, severity = attention_by_conversation.get(str(item.get('conversation_id') or ''), (0, None))
|
||||
item['unseen_order_extraction_count'] = count
|
||||
item['unseen_order_extraction_severity'] = severity
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话。
|
||||
|
||||
核心逻辑:批量清理 ChatLog / Feedback / ChatSession;shipping_notice 写审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true } }`。
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_count = (
|
||||
db.session.query(ChatSession)
|
||||
.filter_by(user_id=user.id, agent_id=agent.id)
|
||||
.count()
|
||||
)
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_sessions_deleted_all',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=f'user:{int(user.id)}:agent:{int(agent.id)}',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
action='delete_all_chat_sessions',
|
||||
reason_code='user_deleted_all_sessions',
|
||||
before={'session_count': int(session_count), 'chat_log_count': len(chat_log_ids)},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return ok({'deleted': True, 'session_count': int(session_count)})
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_chat_session(conversation_id):
|
||||
"""
|
||||
删除指定的会话记录。
|
||||
|
||||
核心逻辑:清理 ChatLog / Feedback;shipping_notice Agent 额外写不可变审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Args:
|
||||
conversation_id: 会话 ID(路径参数)。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true, conversation_id } }`。
|
||||
删除指定的会话记录
|
||||
"""
|
||||
from app.core.response import ok
|
||||
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
@@ -1181,9 +1083,6 @@ def delete_chat_session(conversation_id):
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
session_id_for_audit = str(
|
||||
getattr(session, 'session_id', None) or conversation_id or ''
|
||||
).strip()
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
@@ -1191,38 +1090,9 @@ def delete_chat_session(conversation_id):
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
|
||||
# [BE-16] 货代会话删除必须留审计;与业务删除同事务提交。
|
||||
if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='conversation_session_deleted',
|
||||
aggregate_type='chat_session',
|
||||
aggregate_id=session_id_for_audit or str(conversation_id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
conversation_id=session_id_for_audit or str(conversation_id),
|
||||
action='delete_chat_session',
|
||||
reason_code='user_deleted_session',
|
||||
before={
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
'chat_log_count': len(chat_log_ids),
|
||||
},
|
||||
after={'deleted': True},
|
||||
metadata={'agent_id': int(agent.id), 'chat_log_count': len(chat_log_ids)},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
request_id=str(getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return ok({
|
||||
'deleted': True,
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
})
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -1243,29 +1113,6 @@ def get_chat_messages():
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
def _is_order_extraction_state_card(payload):
|
||||
"""只识别正式 Run 状态卡;用户上传锚点不得回放为重复的助手卡。"""
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
run_no = str(payload.get('order_extraction_run_no') or '').strip()
|
||||
return bool(run_no and payload.get('formId') == f'shipping-order-extraction-run:{run_no}')
|
||||
|
||||
run_nos = {
|
||||
str(log.payload.get('order_extraction_run_no') or '').strip()
|
||||
for log in logs if _is_order_extraction_state_card(log.payload)
|
||||
}
|
||||
order_extraction_runs = {}
|
||||
if run_nos:
|
||||
order_extraction_runs = {
|
||||
run.run_no: run
|
||||
for run in db.session.query(ShippingOrderProcessingRun).filter(
|
||||
ShippingOrderProcessingRun.user_id == g.current_user.id,
|
||||
ShippingOrderProcessingRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderProcessingRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderProcessingRun.run_no.in_(run_nos),
|
||||
).all()
|
||||
}
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
@@ -1277,20 +1124,11 @@ def get_chat_messages():
|
||||
for key, value in raw_payload.items()
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
run_no = str(assistant_payload.get('order_extraction_run_no') or '').strip()
|
||||
if _is_order_extraction_state_card(raw_payload) and run_no in order_extraction_runs:
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_message_state
|
||||
|
||||
assistant_payload['shipping_order_extraction_state'] = serialize_order_extraction_message_state(
|
||||
order_extraction_runs[run_no],
|
||||
)
|
||||
if log.query or user_attachments:
|
||||
user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)}
|
||||
if user_attachments:
|
||||
user_msg['attachments'] = user_attachments
|
||||
messages.append(user_msg)
|
||||
if str(raw_payload.get('formId') or '').strip() == f'shipping-order-extraction-user:{run_no}':
|
||||
continue
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
@@ -1851,12 +1689,7 @@ def chat_completions():
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
|
||||
payload = {
|
||||
'event': 'error',
|
||||
'message': '当前服务暂时无法完成回答,请稍后重试。',
|
||||
'conversation_id': local_session_id,
|
||||
'session_status': 'error',
|
||||
}
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
|
||||
@@ -375,6 +375,13 @@ def rpa_inventory_batch_ready():
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
@@ -409,6 +416,14 @@ def repair_task_inventory_attachment(task_no: str):
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
|
||||
def rpa_inventory_repair():
|
||||
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
|
||||
payload = _payload()
|
||||
payload['repair'] = True
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
|
||||
@@ -11,6 +11,7 @@ from app.api.workspace.schedule import workspace_schedule_bp
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
import app.api.workspace.shipping_process_gate # noqa: F401
|
||||
import app.api.workspace.shipping_inventory_candidates # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_inventory_candidates.py
|
||||
|
||||
用途:正式 Task 库存候选只读详情 API。
|
||||
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
|
||||
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
|
||||
不把可恢复业务阻断误报成 404。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
project_inventory_candidate_detail,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_for_user
|
||||
|
||||
|
||||
def _parse_version_arg() -> str | int:
|
||||
"""解析 version 查询参数,仅允许 current 或正整数。"""
|
||||
raw = str(request.args.get('version') or 'current').strip().lower()
|
||||
if raw == 'current':
|
||||
return 'current'
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('version must be "current" or an integer') from exc
|
||||
if value <= 0:
|
||||
raise ValidationError('version must be positive')
|
||||
return value
|
||||
|
||||
|
||||
def _parse_bool_arg(name: str, *, default: bool) -> bool:
|
||||
"""解析布尔查询参数。"""
|
||||
raw = request.args.get(name)
|
||||
if raw is None:
|
||||
return default
|
||||
return str(raw).strip().lower() in {'1', 'true', 'yes', 'on'}
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/tasks/<task_no>/inventory-candidates',
|
||||
methods=['GET'],
|
||||
)
|
||||
def workspace_get_task_inventory_candidates(task_no: str):
|
||||
"""返回正式 Task 当前候选版本、历史摘要与行级详情。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
version = _parse_version_arg()
|
||||
include_history = _parse_bool_arg('include_history', default=True)
|
||||
include_drafts = _parse_bool_arg('include_drafts', default=False)
|
||||
payload = project_inventory_candidate_detail(
|
||||
task,
|
||||
version=version,
|
||||
include_history=include_history,
|
||||
include_drafts=include_drafts,
|
||||
)
|
||||
return _ok({
|
||||
'task_no': task.task_no,
|
||||
'current_set': payload.get('current_set'),
|
||||
'sources': payload.get('sources') or [],
|
||||
'lines': payload.get('lines') or [],
|
||||
'history': payload.get('history') or [],
|
||||
'blocking_reason': payload.get('blocking_reason'),
|
||||
'primary_action': payload.get('primary_action'),
|
||||
})
|
||||
@@ -488,7 +488,44 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
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
|
||||
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
|
||||
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
|
||||
.first()
|
||||
)
|
||||
if case is None and extraction.run_id:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(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'])
|
||||
@@ -508,18 +545,77 @@ def workspace_retry_conversation_auto_progress(conversation_id: str):
|
||||
|
||||
核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表;
|
||||
返回 summary + items;写 conversation_retry_auto_progress 汇总审计。
|
||||
|
||||
异常保护:
|
||||
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
|
||||
不冒泡为裸 500(与 conversation_retry_auto_progress_service 内部
|
||||
三分支 _execute_* 的 import 级 try/except 形成双层防护)。
|
||||
[STEP R-2] AppError 正常 re-raise,交给 @app.errorhandler(AppError);
|
||||
SyntaxError/ImportError/其他 Exception 统一转为 SHIPPING.RETRY_AUTO_PROGRESS_FAILED
|
||||
并返回 summary={failed:1} 的骨架,避免前端 JSON 解析失败。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
retry_auto_progress_for_conversation,
|
||||
)
|
||||
normalized_conv_id = str(conversation_id or '').strip()
|
||||
fallback_payload = {
|
||||
'conversation_id': normalized_conv_id,
|
||||
'summary': {'total': 1, 'retried': 0, 'skipped': 0, 'failed': 1},
|
||||
'items': [{
|
||||
'object_type': 'conversation',
|
||||
'object_ref': normalized_conv_id,
|
||||
'action': 'retry_auto_progress',
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'metadata': {},
|
||||
}],
|
||||
}
|
||||
|
||||
return _ok(retry_auto_progress_for_conversation(
|
||||
user_id=int(user.id),
|
||||
conversation_id=str(conversation_id or '').strip(),
|
||||
reason=str(data.get('reason') or 'user_retry_auto_progress'),
|
||||
))
|
||||
try:
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
retry_auto_progress_for_conversation,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress module import error conversation_id=%s err=%s',
|
||||
normalized_conv_id, type(mod_err).__name__,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback_payload['items'][0]['metadata']['import_error'] = type(mod_err).__name__
|
||||
return _ok(fallback_payload)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress import unexpected error conversation_id=%s',
|
||||
normalized_conv_id,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = (
|
||||
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
|
||||
)
|
||||
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_payload)
|
||||
|
||||
try:
|
||||
result = retry_auto_progress_for_conversation(
|
||||
user_id=int(user.id),
|
||||
conversation_id=normalized_conv_id,
|
||||
reason=str(data.get('reason') or 'user_retry_auto_progress'),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'retry_conversation_auto_progress execution error conversation_id=%s',
|
||||
normalized_conv_id,
|
||||
)
|
||||
fallback_payload['items'][0]['reason_code'] = (
|
||||
'SHIPPING.RETRY_AUTO_PROGRESS_FAILED'
|
||||
)
|
||||
fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_payload)
|
||||
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
@@ -1005,15 +1101,11 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
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
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
result = retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='task',
|
||||
reason=str(data.get('reason') or 'system_auto_progress'),
|
||||
trigger='system_auto_progress',
|
||||
continue_auto_progress=True,
|
||||
# 普通用户不提交 Gate;服务端从当前事实定位最早未通过 Gate。
|
||||
result = run_task_auto_progress(
|
||||
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
|
||||
)
|
||||
|
||||
# 兼容旧前端:若仍有 export 路径则附带 download_url。
|
||||
@@ -1120,7 +1212,15 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
'freight_ref_no': data.get('freight_ref_no'),
|
||||
'artifact_id': data.get('artifact_id'),
|
||||
}
|
||||
return _ok(shipping_tools.upload_to_freight(payload))
|
||||
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>/retry-upload', methods=['POST'])
|
||||
@@ -1471,15 +1571,17 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
|
||||
@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 越权访问;访问留痕。"""
|
||||
"""读取当前用户的一份 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_projection import serialize_review_case
|
||||
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)。
|
||||
payload = serialize_review_case(
|
||||
snapshot = build_order_review_case_snapshot(
|
||||
get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin),
|
||||
is_admin=is_admin,
|
||||
)
|
||||
@@ -1489,9 +1591,13 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case_no),
|
||||
run_no=str(payload.get('run_no') or '') or None if isinstance(payload, dict) else None,
|
||||
run_no=(
|
||||
str(((snapshot.get('case') or {}).get('run_no')) or '') or None
|
||||
if isinstance(snapshot, dict)
|
||||
else None
|
||||
),
|
||||
)
|
||||
return _ok(payload)
|
||||
return _ok(snapshot)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
@@ -1500,20 +1606,190 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
)
|
||||
def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
"""
|
||||
显式重试 STP 自动建单入队(failed / manual_fallback)。
|
||||
显式重试 STP 自动建单入队(仅用于确认没有业务冲突后的技术重试 — Q6 职责严格区分)。
|
||||
|
||||
核心逻辑:委托 retry_stp_auto_create_for_case;成功返回 queued/reused+job_id;
|
||||
失败抛结构化业务错误,禁止伪装成功。
|
||||
核心逻辑:
|
||||
[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>/retry-auto-progress',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_shipping_order_case_auto_progress(case_no: str):
|
||||
"""
|
||||
单个 Case 精确自动推进恢复入口。适用于 Projection primary_action.code = retry_auto_progress。
|
||||
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验。
|
||||
|
||||
核心逻辑:
|
||||
[可见性] get_review_case_visible_to_user → [业务阻断] assert_case_not_blocked_manual
|
||||
→ [终态幂等] confirmed_task_id/status 终态 → [协调器] reconcile_single_case_for_auto_progress
|
||||
→ [审计] case_retry_auto_progress_invoked → 返回 success+case_no+reconcile_result+serialized case。
|
||||
|
||||
异常保护:
|
||||
[STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError
|
||||
不冒泡为裸 500(与 case_retry_auto_progress_service 内部双校验
|
||||
形成双层防护)。
|
||||
[STEP R-2] AppError 正常 re-raise;SyntaxError/ImportError/其他 Exception 转为
|
||||
success=false + error_code,前端统一消费 retry 结果投影。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
normalized_case_no = str(case_no or '').strip()
|
||||
fallback_result = {
|
||||
'success': False,
|
||||
'case_no': normalized_case_no,
|
||||
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'enqueue_status': 'not_eligible',
|
||||
}
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.case_retry_auto_progress_service import (
|
||||
case_retry_auto_progress,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
normalized_case_no, type(mod_err).__name__,
|
||||
)
|
||||
fallback_result['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback_result['import_error'] = type(mod_err).__name__
|
||||
return _ok(fallback_result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress import unexpected error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback_result['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_result)
|
||||
|
||||
try:
|
||||
result = case_retry_auto_progress(
|
||||
user_id=int(user.id),
|
||||
case_no=normalized_case_no,
|
||||
is_admin=bool(is_admin),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress execution error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback_result['error_type'] = type(exc).__name__
|
||||
return _ok(fallback_result)
|
||||
|
||||
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'],
|
||||
@@ -2506,9 +2782,10 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||||
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))
|
||||
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'])
|
||||
@@ -2540,6 +2817,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
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')
|
||||
@@ -2552,6 +2830,7 @@ def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, sugg
|
||||
value=payload.get('value'),
|
||||
reason=payload.get('reason'),
|
||||
note=payload.get('note'),
|
||||
is_admin=is_admin,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
Reference in new issue
Block a user