feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -15,7 +15,7 @@ import uuid
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, current_app, g, request, send_file
|
||||
from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
@@ -55,7 +55,6 @@ from app.services.shipping_notice.customer_identity_gate import (
|
||||
list_customer_options,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
@@ -90,6 +89,34 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
|
||||
def workspace_download_receipt_report_file(file_id: int):
|
||||
"""下载当前接收人或管理员有权读取的原样收料报表。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
|
||||
|
||||
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
|
||||
response = send_file(
|
||||
stream, as_attachment=True, download_name=filename,
|
||||
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
|
||||
def workspace_list_receipt_report_files():
|
||||
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
|
||||
user = _require_user()
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
|
||||
return _ok({'items': list_receipt_report_files(user, limit=limit)})
|
||||
|
||||
|
||||
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||||
"""
|
||||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
||||
@@ -491,7 +518,11 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
# [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.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
@@ -508,13 +539,21 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
if candidate_ids:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
|
||||
.first()
|
||||
)
|
||||
if case is None and extraction.run_id:
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(run_id=int(extraction.run_id))
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
|
||||
.first()
|
||||
)
|
||||
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
|
||||
@@ -533,89 +572,6 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-conversations/<conversation_id>/retry-auto-progress',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_conversation_auto_progress(conversation_id: str):
|
||||
"""
|
||||
对话级「重试自动推进」:扫描会话下可恢复 Case/正式 OT 并逐对象重试。
|
||||
|
||||
核心逻辑:委托 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 {}
|
||||
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': {},
|
||||
}],
|
||||
}
|
||||
|
||||
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'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
@@ -645,7 +601,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
@@ -817,62 +773,6 @@ def workspace_retry_shipping_task_line(task_no: str, line_key: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""
|
||||
确认当前任务的库存 RPA 来源,并继续触发库存导出。
|
||||
|
||||
核心逻辑:注入可信操作人 ID,供库存源确认事件与统一审计双写。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return _ok(shipping_tools.confirm_inventory_source({
|
||||
'task_id': task.task_no,
|
||||
'source_code': source_code,
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""
|
||||
以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。
|
||||
|
||||
核心逻辑:注入操作人与 event_source=workspace_api,保证决策审计非匿名。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {
|
||||
'task_id': task.task_no,
|
||||
'decision': decision,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
'event_source': 'workspace_api',
|
||||
'operator_id': user.id,
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'user_id': user.id,
|
||||
}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return _ok(shipping_tools.submit_decision(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
@@ -899,32 +799,6 @@ def workspace_update_shipping_notice_fields(task_no: str):
|
||||
return _ok(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST'])
|
||||
def workspace_freeze_shipping_order(task_no: str):
|
||||
"""冻结已复核订单为不可编辑的强类型履约快照。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
expected_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('expected_order_data_version is required') from exc
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_version,
|
||||
rule_versions=data.get('rule_versions') if isinstance(data.get('rule_versions'), dict) else None,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({
|
||||
'task_no': task.task_no,
|
||||
'snapshot_id': snapshot.id,
|
||||
'order_data_version': snapshot.order_data_version,
|
||||
'frozen_at': snapshot.frozen_at.isoformat(),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
|
||||
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
@@ -1121,46 +995,6 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
}
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""兼容旧匹配入口:只提交当前 Gate 自动推进,不直接执行库存匹配。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='match_inventory', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_match_inventory', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""兼容旧导出入口:只提交当前 Gate 自动推进,不直接生成 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
from app.services.shipping_notice.auto_progress_controller import (
|
||||
audit_legacy_forwarded_entrypoint,
|
||||
submit_auto_progress,
|
||||
)
|
||||
audit_legacy_forwarded_entrypoint(
|
||||
task=task, action_code='generate_excel', actor_id=user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
result = submit_auto_progress(task=task, trigger='legacy_generate_excel', operator_id=user.id)
|
||||
return _ok({'deprecated': True, 'projection_refresh_required': True, **result})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""
|
||||
@@ -1197,24 +1031,6 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""
|
||||
货代上传重试入口;首期若全局禁用 RPA 则返回明确错误码。
|
||||
|
||||
核心逻辑:先做归属校验;若平台禁用 RPA 再抛 ValidationError,避免跳过归属门禁。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
raise ValidationError(
|
||||
'首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。',
|
||||
code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
@@ -1265,6 +1081,54 @@ def workspace_shipping_task_inventory_file(task_no: str):
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-tasks/<task_no>/inventory-files/<inventory_file_no>', methods=['GET'],
|
||||
)
|
||||
def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no: str):
|
||||
"""下载当前任务明细已匹配引用的库存文件,禁止按任务或库存源宽泛猜测。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from pathlib import Path
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
|
||||
requested_file_no = str(inventory_file_no or '').strip()
|
||||
inventory_file = (
|
||||
ShippingInventoryFile.query
|
||||
.join(
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
||||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||||
path = Path(storage_path).resolve() if storage_path else None
|
||||
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
download_name = str(
|
||||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
||||
).strip()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_line_inventory_file',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
reason_code='inventory_file_downloaded',
|
||||
metadata={'inventory_file': download_name, 'inventory_file_no': requested_file_no},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_order_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
@@ -1656,79 +1520,6 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
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'],
|
||||
@@ -2039,41 +1830,13 @@ def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
return _ok(attach_resume_outcome({'case': result}, resume))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-candidates',
|
||||
methods=['PUT'],
|
||||
)
|
||||
def workspace_set_shipping_order_review_inventory_candidates(case_no: str, line_key: str):
|
||||
"""
|
||||
人工为明细选择一个或多个已启用库存源候选。
|
||||
|
||||
核心逻辑:强制 reason;写入 Draft 行级覆盖后重跑资格校验。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import set_line_inventory_candidates
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='line_inventory_candidates_selected',
|
||||
)
|
||||
result = set_line_inventory_candidates(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
source_codes=list(payload.get('source_codes') or []),
|
||||
reason=str(payload.get('reason') or ''),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/inventory-routing/reroute',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
"""
|
||||
按最新已发布规则重算库存源路由;不重新识别 PDF,不静默覆盖人工决定。
|
||||
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
|
||||
|
||||
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。
|
||||
"""
|
||||
@@ -2094,54 +1857,6 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-routing/adopt-suggestion',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_adopt_shipping_order_review_inventory_routing_suggestion(case_no: str, line_key: str):
|
||||
"""采用当前规则建议为有效库存源候选。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import adopt_inventory_routing_suggestion
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='inventory_routing_suggestion_adopted',
|
||||
)
|
||||
result = adopt_inventory_routing_suggestion(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=payload.get('idempotency_key'),
|
||||
reason=payload.get('reason'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/inventory-routing/keep-manual',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_keep_shipping_order_review_inventory_routing_manual(case_no: str, line_key: str):
|
||||
"""明确保留人工库存源决定并拒绝规则建议。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import keep_manual_inventory_routing
|
||||
|
||||
payload = _review_draft_payload(
|
||||
user_id=user.id, case_no=case_no, action='inventory_routing_manual_kept',
|
||||
)
|
||||
result = keep_manual_inventory_routing(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_key=line_key,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=payload.get('idempotency_key'),
|
||||
reason=payload.get('reason'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer-resolution/retry',
|
||||
methods=['POST'],
|
||||
@@ -2253,7 +1968,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
"""
|
||||
写入行级履约决定。
|
||||
|
||||
Body: line_key, decision_code, reason?, expected_draft_version?
|
||||
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version?
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
@@ -2268,6 +1983,10 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
line_key=str(data.get('line_key') or ''),
|
||||
decision_code=str(data.get('decision_code') or ''),
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
release_field_values=(
|
||||
data.get('release_field_values')
|
||||
if isinstance(data.get('release_field_values'), dict) else None
|
||||
),
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
actor_is_admin=is_admin,
|
||||
)
|
||||
@@ -2628,33 +2347,6 @@ def workspace_reparse_shipping_order_review_document(case_no: str):
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_intake(case_no: str):
|
||||
"""绑定已上传的新 PDF 为替代 Intake;原 PDF/Case 保留到替代识别成功后才被替代。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_upload_intake
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_intake')
|
||||
intake = create_replacement_upload_intake(user_id=user.id, case_no=case_no, asset_no=payload.get('asset_no'))
|
||||
db.session.commit()
|
||||
return _ok(intake, status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-runs', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_run(case_no: str):
|
||||
"""替代 Intake 解析完成后只为其唯一 PDF 创建新 Run;不覆盖旧文档证据。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='replacement_run')
|
||||
run, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case_no, intake_no=payload.get('intake_no'),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence', methods=['GET'])
|
||||
def workspace_list_shipping_order_review_evidence(case_no: str):
|
||||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应;访问留痕。"""
|
||||
@@ -2920,13 +2612,41 @@ def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-preview', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email(case_no: str):
|
||||
"""消费 Case 绑定的短时令牌,返回强 CSP 隔离的 EML 原始 HTML 视觉预览。"""
|
||||
from app.services.shipping_notice.eml_preview_service import consume_eml_preview_grant
|
||||
|
||||
user = get_current_user()
|
||||
html = consume_eml_preview_grant(
|
||||
token=str(request.args.get('preview_token') or ''), user_id=user.id if user else None, case_no=case_no,
|
||||
)
|
||||
if not html:
|
||||
raise NotFoundError('Email preview is unavailable', code='SHIPPING.REVIEW_EMAIL_PREVIEW_NOT_FOUND')
|
||||
response = Response(html, mimetype='text/html')
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Security-Policy'] = (
|
||||
"default-src 'none'; script-src 'none'; connect-src 'none'; img-src 'none'; media-src 'none'; "
|
||||
"font-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; "
|
||||
"style-src 'unsafe-inline'; navigate-to 'none'"
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控 HTML/文本证据预览。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_email_evidence_text
|
||||
|
||||
return _ok(get_case_email_evidence_text(user_id=user.id, case_no=case_no, document_id=document_id))
|
||||
return _ok(get_case_email_evidence_text(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
document_id=document_id,
|
||||
evidence_id=str(request.args.get('evidence_id') or '').strip() or None,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
@@ -3092,6 +2812,25 @@ def workspace_reparse_shipping_order_extraction_run(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/reparse-batch', methods=['POST'])
|
||||
def workspace_reparse_shipping_order_extraction_batch(run_no: str):
|
||||
"""按 PDF 子任务重解析一个批次;已确认/履约文件由服务端预检排除。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_batch_documents
|
||||
|
||||
result = reparse_batch_documents(
|
||||
user_id=user.id,
|
||||
run_no=run_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
comment=str(body.get('comment') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(result, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user