feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则
This commit is contained in:
1 parent
88408490d7
commit
34d489a2d1
167 files changed
+10365
-7978
No files matched your search
@@ -20,6 +20,7 @@ import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
|
||||
|
||||
@@ -162,23 +162,21 @@ def deactivate_shipping_customer(customer_id: int):
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/identifiers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_identifier(customer_id: int):
|
||||
"""为客户新增名称、邮箱、域名或模板指纹识别证据。"""
|
||||
return jsonify(shipping_customer_service.create_identifier(
|
||||
customer_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
)), 201
|
||||
"""拒绝旧固定类型证据写入口;新增证据必须选择已发布识别定义。"""
|
||||
raise ValidationError(
|
||||
'Legacy customer identifier writes are disabled',
|
||||
code='SHIPPING.CUSTOMER_LEGACY_IDENTIFIER_WRITE_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-identifiers/<int:identifier_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_customer_identifier(identifier_id: int):
|
||||
"""审核、停用或调整客户识别证据的自动匹配授权。"""
|
||||
return jsonify(shipping_customer_service.update_identifier(
|
||||
identifier_id,
|
||||
request.get_json(silent=True) or {},
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
"""拒绝旧固定类型证据写入口;历史记录仅供审计回看。"""
|
||||
raise ValidationError(
|
||||
'Legacy customer identifier writes are disabled',
|
||||
code='SHIPPING.CUSTOMER_LEGACY_IDENTIFIER_WRITE_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/external-refs', methods=['POST'])
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_identity_rules.py
|
||||
|
||||
用途:提供货代客户可配置识别定义、规则集和证据值的管理员 API。
|
||||
依赖:admin blueprint、require_admin、identity_rules.service。
|
||||
逻辑:路由只完成鉴权和参数读取;来源边界、版本化和事务由领域服务统一保证。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.identity_rules import service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""读取管理员身份,避免由客户端伪造审计操作者。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按统一成功 envelope 返回,并透传请求关联 ID。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_identity_definitions():
|
||||
"""读取识别定义、可选订单 Header 字段和受控规则能力目录。"""
|
||||
return _ok(service.list_definitions(
|
||||
target_type=request.args.get('target_type'),
|
||||
active_only=request.args.get('active_only') == 'true',
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/published-evidence-definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_published_identity_evidence_definitions():
|
||||
"""读取当前已发布规则中可由后台维护的客户或站点证据定义。"""
|
||||
return _ok(service.list_published_evidence_definitions(target_type=request.args.get('target_type')))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/definitions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_identity_definition():
|
||||
"""创建绑定平台受控来源适配器的业务识别定义。"""
|
||||
return _ok(service.save_definition(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/definitions/<definition_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_identity_definition(definition_id: str):
|
||||
"""更新业务识别定义;服务端校验来源适配器和自动化风险上限。"""
|
||||
return _ok(service.save_definition(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), definition_id=definition_id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/definitions/<definition_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_identity_definition(definition_id: str):
|
||||
"""退役业务识别定义,保留历史规则和证据审计。"""
|
||||
return _ok(service.retire_definition(
|
||||
definition_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/rule-sets', methods=['GET'])
|
||||
@require_admin
|
||||
def list_identity_rule_sets():
|
||||
"""读取识别规则集版本概要。"""
|
||||
return _ok(service.list_rule_sets())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/rule-sets', methods=['POST'])
|
||||
@require_admin
|
||||
def create_identity_rule_set():
|
||||
"""创建规则集草稿,可从历史发布/退役版本复制。"""
|
||||
return _ok(service.create_rule_set(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/rule-sets/<int:rule_set_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_identity_rule_set(rule_set_id: int):
|
||||
"""保存规则集草稿定义,服务端以锁版本阻止覆盖。"""
|
||||
return _ok(service.save_rule_set(
|
||||
rule_set_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-rules/rule-sets/<int:rule_set_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_identity_rule_set(rule_set_id: int):
|
||||
"""发布规则集并退役前一发布版本。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.publish_rule_set(
|
||||
rule_set_id, expected_lock_version=data.get('expected_lock_version'), actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/identity-evidences', methods=['POST'])
|
||||
@require_admin
|
||||
def create_customer_identity_evidence(customer_id: int):
|
||||
"""为客户主体新增按已发布定义约束的证据值。"""
|
||||
return _ok(service.create_evidence(
|
||||
target_type='customer', target_id=customer_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-sites/<int:site_id>/identity-evidences', methods=['POST'])
|
||||
@require_admin
|
||||
def create_site_identity_evidence(site_id: int):
|
||||
"""为送货站点新增按已发布定义约束的证据值。"""
|
||||
return _ok(service.create_evidence(
|
||||
target_type='site', target_id=site_id, data=request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-identity-evidences/<int:evidence_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_identity_evidence(evidence_id: int):
|
||||
"""审核、停用或调整证据自动化授权;服务端验证定义上限和审计原因。"""
|
||||
return _ok(service.update_evidence(
|
||||
evidence_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
@@ -79,6 +79,15 @@ def create_shipping_excel_template_version(template_id: int):
|
||||
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
|
||||
@require_admin
|
||||
def clone_shipping_excel_template(template_id: int):
|
||||
"""复制已有模板为使用新编码的独立 v1 草稿。"""
|
||||
return _ok(excel_template.clone_as_new_template(
|
||||
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_excel_template(template_id: int):
|
||||
@@ -156,6 +165,39 @@ def update_shipping_inventory_source(source_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_shipping_inventory_source_parsing_profile(source_id: int):
|
||||
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
rows = shipping_inventory_service.bind_source_parsing_profile(
|
||||
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='direct',
|
||||
)
|
||||
return _ok(rows[0])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bulk_bind_shipping_inventory_source_parsing_profile():
|
||||
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_ids = payload.get('source_ids')
|
||||
if not isinstance(source_ids, list):
|
||||
source_ids = []
|
||||
return _ok(shipping_inventory_service.bind_source_parsing_profile(
|
||||
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='bulk',
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
|
||||
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
|
||||
return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
|
||||
@require_admin
|
||||
def activate_shipping_inventory_source(source_id: int):
|
||||
@@ -187,6 +229,45 @@ def start_shipping_inventory_configuration_test(source_id: int):
|
||||
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_validation_batch():
|
||||
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_configuration_test.start_batch_test_export(
|
||||
payload.get('source_ids') or [], actor_id=_actor_id(),
|
||||
), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_active_shipping_inventory_validation_batch():
|
||||
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_latest_active_validation_batch())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_validation_batch(batch_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_shipping_inventory_configuration_test(source_id: int):
|
||||
@@ -249,7 +330,7 @@ def list_shipping_inventory_rules():
|
||||
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_routing_fields():
|
||||
"""返回已发布订单字段与受控系统事实;未发布时保留页面可加载的空目录。"""
|
||||
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
@@ -259,10 +340,8 @@ def list_shipping_inventory_routing_fields():
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'order_schema_published': published,
|
||||
})
|
||||
|
||||
@@ -313,8 +392,6 @@ def get_shipping_inventory_configuration_catalog():
|
||||
ALLOWED_SOURCE_KINDS,
|
||||
ALLOWED_SYSTEM_FACTS,
|
||||
)
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
@@ -327,7 +404,6 @@ def get_shipping_inventory_configuration_catalog():
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
'routing_system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'inventory_fields': inventory_field_catalog.list_fields(),
|
||||
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
|
||||
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
|
||||
|
||||
+16
-1
@@ -207,7 +207,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
if 'create_task' in value or 'get_task_status' in value or 'submit_order_extraction' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
@@ -1615,6 +1615,7 @@ def chat_completions():
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
should_recover_upstream_error,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
@@ -1638,6 +1639,20 @@ def chat_completions():
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
if event_name == 'error' and should_recover_upstream_error(relay_stream_ctx, event_data):
|
||||
current_app.logger.warning(
|
||||
'[chat-api] recover upstream error from persisted shipping extraction request_id=%s session_id=%s',
|
||||
request_id,
|
||||
local_session_id,
|
||||
)
|
||||
event_data = {
|
||||
**event_data,
|
||||
'event': 'message_end',
|
||||
'answer': '',
|
||||
'replace_answer': False,
|
||||
'recovered_upstream_error': True,
|
||||
}
|
||||
event_name = 'message_end'
|
||||
if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments:
|
||||
try:
|
||||
attachment_chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
|
||||
@@ -211,14 +211,6 @@ def tool_create_batch():
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
@@ -401,6 +393,22 @@ def rpa_inventory_configuration_test_ready():
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_ready():
|
||||
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_progress():
|
||||
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
|
||||
@@ -30,14 +30,21 @@ from app.services.shipping_notice.query_service import (
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_page_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.task_disposition_service import (
|
||||
archive_task,
|
||||
load_task_for_disposition,
|
||||
move_task_to_recycle_bin,
|
||||
purge_task_permanently,
|
||||
restore_task_from_recycle_bin,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
@@ -69,12 +76,130 @@ def _ok(payload: dict):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
return jsonify(list_tasks_page_for_user(
|
||||
user.id,
|
||||
batch_no=batch_no,
|
||||
process_status=process_status,
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
))
|
||||
|
||||
|
||||
def _batch_task_nos(data: dict) -> list[str]:
|
||||
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
|
||||
raw_task_nos = data.get('task_nos')
|
||||
if not isinstance(raw_task_nos, list) or not raw_task_nos:
|
||||
raise ValidationError('task_nos must be a non-empty list', code='SHIPPING.TASK_SELECTION_INVALID')
|
||||
normalized = list(dict.fromkeys(str(value or '').strip().upper() for value in raw_task_nos if str(value or '').strip()))
|
||||
if not normalized or len(normalized) > 100:
|
||||
raise ValidationError('task_nos must contain 1 to 100 task numbers', code='SHIPPING.TASK_SELECTION_INVALID')
|
||||
return normalized
|
||||
|
||||
|
||||
def _can_dispose_task(user, task: ShippingTask) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
"""在每条任务行锁下重算权限与资格,返回部分成功明细而不让一条失败回滚整批。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = _batch_task_nos(data)
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if action == 'delete' and not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_DELETE_REASON_REQUIRED')
|
||||
request_id = getattr(g, 'request_id', None)
|
||||
results = []
|
||||
for task_no in task_nos:
|
||||
try:
|
||||
task = load_task_for_disposition(task_no)
|
||||
if not _can_dispose_task(user, task):
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': 'AUTH.FORBIDDEN'})
|
||||
db.session.rollback()
|
||||
continue
|
||||
if action == 'delete':
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=user.id, reason=reason, request_id=request_id)
|
||||
elif action == 'archive':
|
||||
archive_task(task, actor_id=user.id, request_id=request_id)
|
||||
outcome = 'archived'
|
||||
else:
|
||||
restore_task_from_recycle_bin(task, actor_id=user.id, request_id=request_id)
|
||||
outcome = 'restored'
|
||||
db.session.commit()
|
||||
results.append({'task_no': task_no, 'status': outcome})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results, 'requested_count': len(task_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-purge', methods=['POST'])
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = _batch_task_nos(data)
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING.TASK_PURGE_REASON_REQUIRED')
|
||||
results = []
|
||||
for task_no in task_nos:
|
||||
try:
|
||||
task = load_task_for_disposition(task_no)
|
||||
purge_task_permanently(
|
||||
task,
|
||||
actor_id=user.id,
|
||||
reason=reason,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
results.append({'task_no': task_no, 'status': 'purged'})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'task_no': task_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results, 'requested_count': len(task_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-delete', methods=['POST'])
|
||||
def workspace_batch_delete_shipping_tasks():
|
||||
"""批量删除任务到回收站;服务端按行锁判定是否需要同时作废。"""
|
||||
return _batch_dispose('delete')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-archive', methods=['POST'])
|
||||
def workspace_batch_archive_shipping_tasks():
|
||||
"""批量归档任务,适用于已上传或外部处理中而不能作废的任务。"""
|
||||
return _batch_dispose('archive')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/batch-restore', methods=['POST'])
|
||||
def workspace_batch_restore_shipping_tasks():
|
||||
"""批量恢复回收站内仍为 active 的纯误建任务。"""
|
||||
return _batch_dispose('restore')
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
|
||||
Reference in new issue
Block a user