feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -15,6 +15,7 @@ from flask import g, request, send_file
|
||||
from app import db
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ForbiddenError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import order_document_profile_audit_service as audit_service
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
@@ -170,13 +171,6 @@ def get_order_document_profile_sample_tables(document_id: int):
|
||||
return _ok(service.get_sample_tables(document_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_order_document_profile_coordinate_reconstruction():
|
||||
"""根据管理员确认的相对列边界返回只读坐标重建候选。"""
|
||||
return _ok(service.preview_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', methods=['POST'])
|
||||
@require_admin
|
||||
def suggest_order_document_profile_coordinate_reconstruction():
|
||||
@@ -230,8 +224,18 @@ def create_order_document_profile():
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_order_document_profile(profile_id: int):
|
||||
"""按乐观锁整体更新模板 Profile 草稿。"""
|
||||
"""按乐观锁整体更新模板 Profile 草稿;变更 split_rules 需 xfa_split_rule_edit。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.extensions import db as _db
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
profile_row = _db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
incoming_def = data.get('definition') if isinstance(data.get('definition'), dict) else {}
|
||||
previous_def = (
|
||||
profile_row.definition_json
|
||||
if profile_row is not None and isinstance(profile_row.definition_json, dict)
|
||||
else {}
|
||||
)
|
||||
return _ok(service.save_draft(
|
||||
data, actor_id=_actor_id(), profile_id=profile_id, **_write_context(data), enforce_lease=True,
|
||||
))
|
||||
@@ -400,14 +404,28 @@ def create_order_document_profile_publish_check(profile_id: int):
|
||||
@require_admin
|
||||
def get_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""读取发布检查报告及失效、阻断和逐项警告确认状态。"""
|
||||
return _ok(publish_check_service.get_report(profile_id, report_no))
|
||||
payload = publish_check_service.get_report(profile_id, report_no)
|
||||
_log_profile_view_event(profile_id, event_type='publish_check_viewed', detail={'report_no': report_no})
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish-checks/<string:report_no>/confirm', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""消费有效报告并原子发布,警告必须逐项确认。"""
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
entity = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
definition = dict((entity.definition_json or {}) if entity is not None else {})
|
||||
if str(definition.get('template_mode') or '') == 'xfa_dataset':
|
||||
user = getattr(g, 'current_user', None)
|
||||
if not bool(user and user.has_feature_permission('shipping_notice.xfa_split_rule_publish')):
|
||||
raise ForbiddenError(
|
||||
'XFA split rule publish permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
details={'permission': 'shipping_notice.xfa_split_rule_publish'},
|
||||
)
|
||||
return _ok(publish_check_service.consume_report(profile_id, report_no, data=data, actor_id=_actor_id(), **_write_context(data)))
|
||||
|
||||
|
||||
@@ -615,6 +633,34 @@ def run_order_document_profile_current_sample(profile_id: int):
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/layout-signature', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_layout_signature(profile_id: int):
|
||||
"""
|
||||
生成当前草稿的版面签名 ValidationRun,并更新 Profile 轻量签名引用。
|
||||
|
||||
前端不得提交 Matcher 分数或签名正文;服务端仅消费租约与 operation_id。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_layout_signature(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/cross-template-overlap', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_cross_template_overlap(profile_id: int):
|
||||
"""
|
||||
执行跨模板唯一性 ValidationRun;要求当前草稿已有有效 layout_signature 或请求体允许自动生成。
|
||||
|
||||
前端不得提交 matcher 分数或 layout 正文;服务端只返回安全摘要与 conflict_profiles。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_cross_template_overlap(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/ocr-coordinate-evidence', methods=['POST'])
|
||||
@require_admin
|
||||
def generate_bound_order_document_profile_ocr_coordinate_evidence(profile_id: int):
|
||||
@@ -672,7 +718,9 @@ def confirm_order_document_profile_test_reviews(suite_id: int):
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(quality.confirm_sample_reviews(
|
||||
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''),
|
||||
row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'), actor_id=_actor_id(),
|
||||
row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'),
|
||||
layout_version_id=data.get('layout_version_id'),
|
||||
layout_payload_checksum=data.get('layout_payload_checksum'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@@ -698,3 +746,88 @@ def approve_order_document_profile_test_suite(suite_id: int):
|
||||
"""批准最新合格盲测,使该模板可参与确定性自动建单。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
return _ok(quality.approve_suite(suite_id=suite_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/field-tree',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_xfa_field_tree(document_id: int):
|
||||
"""返回 XFA 字段树安全投影;不含 XML/PDF 正文。"""
|
||||
return _private_ok(service.get_xfa_field_tree(document_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/collections',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_xfa_collections(document_id: int):
|
||||
"""返回 XFA 重复集合候选摘要。"""
|
||||
return _private_ok(service.get_xfa_collections(document_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/value-preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_value(document_id: int):
|
||||
"""按 path_id 返回分级样本值;完整值读取要求敏感权限并由服务层留痕。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
reveal = bool(data.get('reveal'))
|
||||
user = getattr(g, 'current_user', None)
|
||||
if reveal and not bool(user and user.has_feature_permission('shipping_notice.audit_sensitive_read')):
|
||||
raise ForbiddenError(
|
||||
'XFA sample full value permission is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN',
|
||||
)
|
||||
return _private_ok(service.preview_xfa_sample_value(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
actor_id=_actor_id(),
|
||||
include_full_value=reveal,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profile-samples/<int:document_id>/xfa/split-rules/preview',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def preview_order_document_profile_sample_xfa_split_rules(document_id: int):
|
||||
"""预览拆分规则执行结果;默认脱敏,完整值需敏感读权限。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
reveal = bool(data.get('reveal'))
|
||||
rule_set = data.get('rule_set') if isinstance(data.get('rule_set'), dict) else {}
|
||||
profile_id = data.get('profile_id')
|
||||
return _private_ok(service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=str(data.get('path_id') or ''),
|
||||
rule_set=rule_set,
|
||||
actor_id=_actor_id(),
|
||||
profile_id=int(profile_id) if profile_id not in (None, '') else None,
|
||||
include_full_values=reveal,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/split-rules/validate',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def validate_order_document_profile_xfa_split_rules(profile_id: int):
|
||||
"""校验 Profile 拆分规则契约与 Schema 映射;不持久化。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
split_rules = data.get('split_rules')
|
||||
if split_rules is not None and not isinstance(split_rules, list):
|
||||
raise ValidationError(
|
||||
'split_rules must be a list',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return _private_ok(service.validate_xfa_split_rules(
|
||||
profile_id,
|
||||
split_rules=split_rules,
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
@@ -389,3 +389,23 @@ def export_shipping_notice_audit_events():
|
||||
'X-Exported-Count': str(exported['exported']),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-snapshots/<string:snapshot_ref>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_notice_xfa_audit_snapshot(snapshot_ref: str):
|
||||
"""
|
||||
读取 XFA 加密完整审计快照。
|
||||
|
||||
核心逻辑:仅 shipping_notice.audit_sensitive_read 可获明文;每次读取再写访问审计;
|
||||
无权限时仅返回脱敏摘要。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_query_service import get_xfa_audit_full_snapshot
|
||||
|
||||
payload = get_xfa_audit_full_snapshot(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
snapshot_ref=snapshot_ref,
|
||||
include_sensitive=_caller_can_read_audit_sensitive(),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
+98
-19
@@ -2,8 +2,10 @@
|
||||
backend/app/api/chat.py
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
依赖: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。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -28,7 +30,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, ShippingOrderExtractionRun
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderProcessingRun
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
@@ -237,14 +239,14 @@ def _order_extraction_attention_by_conversation(
|
||||
'cancelled': 'error',
|
||||
}
|
||||
rows = db.session.query(
|
||||
ShippingOrderExtractionRun.conversation_id,
|
||||
ShippingOrderExtractionRun.status,
|
||||
ShippingOrderProcessingRun.conversation_id,
|
||||
ShippingOrderProcessingRun.status,
|
||||
).filter(
|
||||
ShippingOrderExtractionRun.user_id == user_id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == agent_id,
|
||||
ShippingOrderExtractionRun.conversation_id.in_(conversation_ids),
|
||||
ShippingOrderExtractionRun.attention_generated_at.isnot(None),
|
||||
ShippingOrderExtractionRun.seen_at.is_(None),
|
||||
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:
|
||||
@@ -1087,30 +1089,75 @@ def get_chat_sessions():
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
删除当前用户与当前 Agent 的所有历史会话。
|
||||
|
||||
核心逻辑:批量清理 ChatLog / Feedback / ChatSession;shipping_notice 写审计;
|
||||
返回标准 success envelope。
|
||||
|
||||
Returns:
|
||||
Flask JSON:`{ success, data: { deleted: true } }`。
|
||||
"""
|
||||
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 jsonify({'status': 'ok'})
|
||||
return ok({'deleted': True, 'session_count': int(session_count)})
|
||||
|
||||
@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:
|
||||
@@ -1134,6 +1181,9 @@ 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)
|
||||
@@ -1141,9 +1191,38 @@ 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 jsonify({'status': 'ok'})
|
||||
return ok({
|
||||
'deleted': True,
|
||||
'conversation_id': session_id_for_audit or str(conversation_id),
|
||||
})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -1180,11 +1259,11 @@ def get_chat_messages():
|
||||
if run_nos:
|
||||
order_extraction_runs = {
|
||||
run.run_no: run
|
||||
for run in db.session.query(ShippingOrderExtractionRun).filter(
|
||||
ShippingOrderExtractionRun.user_id == g.current_user.id,
|
||||
ShippingOrderExtractionRun.owner_agent_id == g.current_agent.id,
|
||||
ShippingOrderExtractionRun.conversation_id == (session.session_id if session else conversation_id),
|
||||
ShippingOrderExtractionRun.run_no.in_(run_nos),
|
||||
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()
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
||||
batch_legacy_removed(create_batch 410)。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计。
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
||||
co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,17 +26,11 @@ from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
get_focus_task_for_batch,
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
@@ -205,20 +201,15 @@ def tool_confirm_temporary_inventory_use():
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
历史建批 Tool(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch, _created = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.create_batch')
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
@@ -334,44 +325,28 @@ def tool_get_task_status():
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
历史批次状态查询(已下线)。
|
||||
【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
_require_read_capability(payload, scope='get_batch_status', batch_no=batch_no)
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.get_batch_status')
|
||||
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
历史批次焦点切换(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||
if not batch_no or not task_no:
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
raise NotFoundError("task not found in batch")
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.switch_focus_task')
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
|
||||
@@ -3,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))
|
||||
Reference in new issue
Block a user