Files
zpark-ems/backend/app/api/v1/settings.py
Du Wenbo 026c837b91 Squashed 'core/' content from commit 92ec910
git-subtree-dir: core
git-subtree-split: 92ec910a132e379a3a6e442a75bcb07cac0f0010
2026-04-04 18:17:10 +08:00

85 lines
3.1 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from pydantic import BaseModel
from app.core.database import get_db
from app.core.deps import get_current_user, require_roles
from app.models.user import User
from app.models.setting import SystemSetting
from app.services.audit import log_audit
router = APIRouter(prefix="/settings", tags=["系统设置"])
# Default settings — used when keys are missing from DB
DEFAULTS: dict[str, str] = {
"platform_name": "天普零碳园区智慧能源管理平台",
"data_retention_days": "365",
"alarm_auto_resolve_minutes": "30",
"simulator_interval_seconds": "15",
"notification_email_enabled": "false",
"notification_email_smtp": "",
"report_auto_schedule_enabled": "false",
"timezone": "Asia/Shanghai",
}
class SettingsUpdate(BaseModel):
platform_name: str | None = None
data_retention_days: int | None = None
alarm_auto_resolve_minutes: int | None = None
simulator_interval_seconds: int | None = None
notification_email_enabled: bool | None = None
notification_email_smtp: str | None = None
report_auto_schedule_enabled: bool | None = None
timezone: str | None = None
@router.get("")
async def get_settings(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Return all platform settings as a flat dict."""
result = await db.execute(select(SystemSetting))
db_settings = {s.key: s.value for s in result.scalars().all()}
# Merge defaults with DB values
merged = {**DEFAULTS, **db_settings}
# Cast types for frontend
return {
"platform_name": merged["platform_name"],
"data_retention_days": int(merged["data_retention_days"]),
"alarm_auto_resolve_minutes": int(merged["alarm_auto_resolve_minutes"]),
"simulator_interval_seconds": int(merged["simulator_interval_seconds"]),
"notification_email_enabled": merged["notification_email_enabled"] == "true",
"notification_email_smtp": merged["notification_email_smtp"],
"report_auto_schedule_enabled": merged["report_auto_schedule_enabled"] == "true",
"timezone": merged["timezone"],
}
@router.put("")
async def update_settings(
data: SettingsUpdate,
db: AsyncSession = Depends(get_db),
user: User = Depends(require_roles("admin")),
):
"""Update platform settings (admin only)."""
updates = data.model_dump(exclude_unset=True)
changed_keys = []
for key, value in updates.items():
str_value = str(value).lower() if isinstance(value, bool) else str(value)
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
setting = result.scalar_one_or_none()
if setting:
setting.value = str_value
else:
db.add(SystemSetting(key=key, value=str_value))
changed_keys.append(key)
await log_audit(
db, user.id, "update", "system",
detail=f"更新系统设置: {', '.join(changed_keys)}",
)
return {"message": "设置已更新"}