2026-04-02 18:46:42 +08:00
|
|
|
import logging
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
import uuid
|
2026-04-01 13:36:06 +08:00
|
|
|
from contextlib import asynccontextmanager
|
2026-04-02 18:46:42 +08:00
|
|
|
from typing import Optional
|
|
|
|
|
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
from fastapi import FastAPI, Request
|
2026-04-01 13:36:06 +08:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
from fastapi.responses import JSONResponse
|
2026-04-01 13:36:06 +08:00
|
|
|
from app.api.router import api_router
|
2026-04-02 18:46:42 +08:00
|
|
|
from app.api.v1.websocket import start_broadcast_task, stop_broadcast_task
|
2026-04-01 13:36:06 +08:00
|
|
|
from app.core.config import get_settings
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
from app.core.cache import get_redis, close_redis
|
2026-04-01 13:36:06 +08:00
|
|
|
from app.services.simulator import DataSimulator
|
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
|
|
|
from app.services.report_scheduler import start_scheduler, stop_scheduler
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
from app.services.aggregation import start_aggregation_scheduler, stop_aggregation_scheduler
|
2026-04-02 18:46:42 +08:00
|
|
|
from app.collectors.manager import CollectorManager
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
from app.collectors.queue import IngestionWorker
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
settings = get_settings()
|
|
|
|
|
simulator = DataSimulator()
|
2026-04-02 18:46:42 +08:00
|
|
|
collector_manager: Optional[CollectorManager] = None
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
ingestion_worker: Optional[IngestionWorker] = None
|
2026-04-02 18:46:42 +08:00
|
|
|
|
|
|
|
|
logger = logging.getLogger("app")
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
|
async def lifespan(app: FastAPI):
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
global collector_manager, ingestion_worker
|
|
|
|
|
|
|
|
|
|
# Initialize Redis cache
|
|
|
|
|
if settings.REDIS_ENABLED:
|
|
|
|
|
redis = await get_redis()
|
|
|
|
|
if redis:
|
|
|
|
|
logger.info("Redis cache initialized")
|
|
|
|
|
|
|
|
|
|
# Start aggregation scheduler
|
|
|
|
|
if settings.AGGREGATION_ENABLED:
|
|
|
|
|
await start_aggregation_scheduler()
|
|
|
|
|
logger.info("Aggregation scheduler started")
|
|
|
|
|
|
|
|
|
|
# Start ingestion worker
|
|
|
|
|
if settings.INGESTION_QUEUE_ENABLED:
|
|
|
|
|
ingestion_worker = IngestionWorker()
|
|
|
|
|
await ingestion_worker.start()
|
|
|
|
|
logger.info("Ingestion worker started")
|
|
|
|
|
|
2026-04-02 18:46:42 +08:00
|
|
|
if settings.USE_SIMULATOR:
|
|
|
|
|
logger.info("Starting in SIMULATOR mode")
|
|
|
|
|
await simulator.start()
|
|
|
|
|
else:
|
|
|
|
|
logger.info("Starting in COLLECTOR mode (real IoT devices)")
|
|
|
|
|
collector_manager = CollectorManager()
|
|
|
|
|
await collector_manager.start()
|
|
|
|
|
start_broadcast_task()
|
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
|
|
|
await start_scheduler()
|
2026-04-01 13:36:06 +08:00
|
|
|
yield
|
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
|
|
|
await stop_scheduler()
|
2026-04-02 18:46:42 +08:00
|
|
|
stop_broadcast_task()
|
|
|
|
|
if settings.USE_SIMULATOR:
|
|
|
|
|
await simulator.stop()
|
|
|
|
|
else:
|
|
|
|
|
if collector_manager:
|
|
|
|
|
await collector_manager.stop()
|
|
|
|
|
collector_manager = None
|
2026-04-01 13:36:06 +08:00
|
|
|
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
# Stop ingestion worker
|
|
|
|
|
if ingestion_worker:
|
|
|
|
|
await ingestion_worker.stop()
|
|
|
|
|
ingestion_worker = None
|
|
|
|
|
|
|
|
|
|
# Stop aggregation scheduler
|
|
|
|
|
if settings.AGGREGATION_ENABLED:
|
|
|
|
|
await stop_aggregation_scheduler()
|
|
|
|
|
|
|
|
|
|
# Close Redis
|
|
|
|
|
if settings.REDIS_ENABLED:
|
|
|
|
|
await close_redis()
|
|
|
|
|
logger.info("Redis cache closed")
|
|
|
|
|
|
2026-04-01 13:36:06 +08:00
|
|
|
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
title="天普零碳园区智慧能源管理平台",
|
|
|
|
|
description="Tianpu Zero-Carbon Park Smart Energy Management System",
|
|
|
|
|
version="1.0.0",
|
|
|
|
|
lifespan=lifespan,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=["http://localhost:3000", "http://localhost:5173", "http://127.0.0.1:3000", "http://127.0.0.1:5173"],
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
)
|
|
|
|
|
|
feat: enterprise-level enhancement — 12 modules complete
New modules:
- Energy Quota Management (定额管理)
- Cost/Expense Analysis with TOU pricing (费用分析)
- Sub-item Energy Analysis (分项分析)
- EV Charging Station Management (充电桩管理) — 8 models, 6 pages
- Enhanced Energy Analysis — loss, YoY, MoM comparison
- Alarm Analytics — trends, MTTR, top devices, rule toggle
- Maintenance & Work Orders (运维管理) — inspections, repair orders, duty
- Data Query Module (数据查询)
- Equipment Topology (设备拓扑)
- Management System (管理体系) — regulations, standards, processes
Infrastructure:
- Redis caching layer with decorator
- Redis Streams data ingestion buffer
- Hourly/daily/monthly aggregation engine
- Rate limiting & request ID middleware
- 6 Alembic migrations (003-008), 21 new tables
- Extended seed data for all modules
Stats: 120+ API routes, 12 pages, 27 tabs, 37 database tables
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:06:16 +08:00
|
|
|
|
|
|
|
|
@app.middleware("http")
|
|
|
|
|
async def request_id_middleware(request: Request, call_next):
|
|
|
|
|
"""Add a unique X-Request-ID header to every response."""
|
|
|
|
|
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
|
|
|
|
|
request.state.request_id = request_id
|
|
|
|
|
response = await call_next(request)
|
|
|
|
|
response.headers["X-Request-ID"] = request_id
|
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
|
|
|
async def global_exception_handler(request: Request, exc: Exception):
|
|
|
|
|
"""Global exception handler for consistent error responses."""
|
|
|
|
|
request_id = getattr(request.state, "request_id", "unknown")
|
|
|
|
|
logger.error("Unhandled exception [request_id=%s]: %s", request_id, exc, exc_info=True)
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=500,
|
|
|
|
|
content={
|
|
|
|
|
"detail": "Internal server error",
|
|
|
|
|
"request_id": request_id,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-04-01 13:36:06 +08:00
|
|
|
app.include_router(api_router)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/health")
|
|
|
|
|
async def health():
|
|
|
|
|
return {"status": "ok", "app": settings.APP_NAME}
|