Files
tianpu-ems/backend/app/api/v1/settings.py
Du Wenbo ef9b5d055f feat: add system settings, audit log, device detail, dark mode, i18n, email notifications
System Management:
- System Settings page with 8 configurable parameters (admin only)
- Audit Log page with filterable table (user, action, resource, date range)
- Audit logging wired into auth, devices, users, alarms, reports API handlers
- SystemSetting model + migration (002)

Device Detail:
- Dedicated /devices/:id page with 4 tabs (realtime, historical trends, alarm history, device info)
- ECharts historical charts with granularity/time range selectors
- Device name clickable in Devices and Monitoring tables → navigates to detail

Email & Scheduling:
- Email service with SMTP support (STARTTLS/SSL/plain)
- Alarm email notification with professional HTML template
- Report scheduler using APScheduler for cron-based auto-generation
- Scheduled report task seeded (daily at 8am)

UI Enhancements:
- Dark mode toggle (persisted to localStorage, Ant Design darkAlgorithm)
- Data comparison view in Analysis page (dual date range, side-by-side metrics)
- i18n framework (i18next) with zh/en translations for menu and common UI
- Language switcher in header (中文/English)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 19:42:22 +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": "设置已更新"}