Files
syops/backend/app/services/admin/linked_service_service.py

131 lines
3.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/admin/linked_service_service.py
用途:关联服务 CRUD 与侧栏只读列表。
依赖:models.LinkedService、app.core.errors。
逻辑:api/admin/linked_services.py 管理 CRUD;api/linked_services.py 返回已启用项。
"""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import LinkedService
def _normalize_name(value: Any) -> str:
"""校验并规范化显示名称。"""
name = str(value or '').strip()
if not name:
raise ValidationError('Name is required')
if len(name) > 100:
raise ValidationError('Name is too long')
return name
def _normalize_url(value: Any) -> str:
"""
校验并规范化访问地址。
核心逻辑:仅允许 http/https,且必须含主机;内网 IP 可用 http。
"""
url = str(value or '').strip()
if not url:
raise ValidationError('URL is required')
if len(url) > 500:
raise ValidationError('URL is too long')
parsed = urlparse(url)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise ValidationError('URL must be an absolute http(s) address')
return url
def serialize_linked_service(row: LinkedService, *, include_admin_fields: bool = False) -> dict:
"""LinkedService ORM → API dict。"""
payload = {
'id': row.id,
'name': row.name,
'url': row.url,
}
if include_admin_fields:
payload.update({
'is_enabled': bool(row.is_enabled),
'sort_order': int(row.sort_order or 0),
'created_at': row.created_at.isoformat() if row.created_at else None,
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
})
return payload
def list_enabled_linked_services() -> list[dict]:
"""返回已启用关联服务,供 Chat/工作台侧栏入口使用。"""
rows = (
db.session.query(LinkedService)
.filter(LinkedService.is_enabled.is_(True))
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row) for row in rows]
def list_linked_services() -> list[dict]:
"""管理端列表:含停用项与排序字段。"""
rows = (
db.session.query(LinkedService)
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row, include_admin_fields=True) for row in rows]
def create_linked_service(data: dict[str, Any]) -> dict:
"""
创建关联服务。
Args:
data: 含 name、url;可选 is_enabled、sort_order。
Returns:
{ id, message }
"""
row = LinkedService(
name=_normalize_name(data.get('name')),
url=_normalize_url(data.get('url')),
is_enabled=bool(data.get('is_enabled', True)),
sort_order=int(data.get('sort_order') or 0),
)
db.session.add(row)
db.session.commit()
return {'message': 'Created', 'id': row.id}
def update_linked_service(service_id: int, data: dict[str, Any]) -> dict:
"""
更新关联服务。
Raises:
NotFoundError: 记录不存在。
"""
row = db.session.get(LinkedService, service_id)
if not row:
raise NotFoundError('Not found')
row.name = _normalize_name(data.get('name'))
row.url = _normalize_url(data.get('url'))
if 'is_enabled' in data:
row.is_enabled = bool(data.get('is_enabled'))
if 'sort_order' in data:
row.sort_order = int(data.get('sort_order') or 0)
db.session.commit()
return {'message': 'Updated'}
def delete_linked_service(service_id: int) -> dict:
"""删除关联服务(不存在时静默成功)。"""
row = db.session.get(LinkedService, service_id)
if row:
db.session.delete(row)
db.session.commit()
return {'message': 'Deleted'}