280 lines
9.5 KiB
Python
280 lines
9.5 KiB
Python
"""Service Request System - Main Application."""
|
|
|
|
import os
|
|
from pathlib import Path
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
from app.settings import get_settings
|
|
from app.core.database import init_db, engine, Base, SessionLocal
|
|
from app.core.middleware import add_security_headers, add_cors_middleware
|
|
from app.core.exception_handlers import app_exception_handler
|
|
from app.core.exceptions import AppException
|
|
from app.core.logging import setup_logging, logger
|
|
from app.api.v1.routes import tickets, users, auth, health, reference, notifications, emails, settings, notification_templates
|
|
|
|
# Setup logging
|
|
setup_logging()
|
|
|
|
# Background scheduler for periodic tasks
|
|
scheduler = BackgroundScheduler()
|
|
|
|
# Frontend build directory
|
|
FRONTEND_DIR = Path(__file__).parent.parent / "frontend" / "dist"
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title=get_settings().APP_NAME,
|
|
version=get_settings().APP_VERSION,
|
|
description="Service Request System - ITSM Platform",
|
|
docs_url=None,
|
|
redoc_url=None,
|
|
openapi_url="/openapi.json"
|
|
)
|
|
|
|
|
|
@app.get("/docs", include_in_schema=False)
|
|
async def custom_swagger_ui_html():
|
|
"""Swagger UI with local fallback."""
|
|
return HTMLResponse("""
|
|
<!DOCTYPE html>
|
|
<html><head>
|
|
<meta charset="utf-8">
|
|
<title>Service Request System - Swagger UI</title>
|
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css">
|
|
</head><body>
|
|
<div id="swagger-ui"></div>
|
|
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js"></script>
|
|
<script>
|
|
window.onload = function() {
|
|
try {
|
|
SwaggerUIBundle({
|
|
url: "/openapi.json",
|
|
dom_id: "#swagger-ui",
|
|
presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
|
|
layout: "BaseLayout"
|
|
});
|
|
} catch(e) {
|
|
document.getElementById("swagger-ui").innerHTML =
|
|
"<h2>Ошибка загрузки Swagger UI</h2><p>" + e.message + "</p>" +
|
|
"<p>Попробуйте обновить страницу или проверьте подключение к интернету (нужен доступ к CDN).</p>" +
|
|
"<p><a href='/openapi.json'>Скачать OpenAPI JSON</a></p>";
|
|
}
|
|
};
|
|
</script>
|
|
</body></html>
|
|
""")
|
|
|
|
# Add CORS middleware
|
|
add_cors_middleware(app)
|
|
|
|
# Add security headers
|
|
add_security_headers(app)
|
|
|
|
# Include routers
|
|
app.include_router(health.router, prefix="/api/v1")
|
|
app.include_router(auth.router, prefix="/api/v1/auth")
|
|
app.include_router(users.router, prefix="/api/v1/users")
|
|
app.include_router(tickets.router, prefix="/api/v1")
|
|
app.include_router(reference.router, prefix="/api/v1")
|
|
app.include_router(notifications.router, prefix="/api/v1")
|
|
app.include_router(emails.router, prefix="/api/v1")
|
|
app.include_router(settings.router, prefix="/api/v1")
|
|
app.include_router(notification_templates.router, prefix="/api/v1")
|
|
|
|
# Exception handlers
|
|
app.add_exception_handler(AppException, app_exception_handler)
|
|
|
|
# Serve frontend static files
|
|
if FRONTEND_DIR.exists():
|
|
app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIR / "assets")), name="assets")
|
|
|
|
@app.get("/")
|
|
async def serve_root():
|
|
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
|
|
|
# SPA routes - serve index.html for client-side routing
|
|
@app.get("/login")
|
|
@app.get("/tickets")
|
|
@app.get("/tickets/new")
|
|
@app.get("/tickets/{ticket_id}")
|
|
@app.get("/tickets/{ticket_id}/{path:path}")
|
|
@app.get("/users")
|
|
@app.get("/users/new")
|
|
@app.get("/users/{user_id}")
|
|
@app.get("/reference")
|
|
@app.get("/settings")
|
|
@app.get("/templates")
|
|
async def serve_spa():
|
|
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
|
|
|
# Static files (favicon, etc.)
|
|
@app.get("/vite.svg")
|
|
async def serve_vite_svg():
|
|
file_path = FRONTEND_DIR / "vite.svg"
|
|
if file_path.is_file():
|
|
return FileResponse(str(file_path))
|
|
return JSONResponse({"detail": "Not Found"}, status_code=404)
|
|
|
|
|
|
# --- TEST ONLY:简易登录页面 ---
|
|
@app.get("/test-login")
|
|
async def test_login_page():
|
|
"""Test login page - generates a JWT token for testing."""
|
|
from jose import jwt
|
|
from datetime import datetime, timedelta
|
|
|
|
payload = {
|
|
"sub": "1",
|
|
"email": "admin@company.com",
|
|
"first_name": "Админ",
|
|
"last_name": "Тестов",
|
|
"is_active": True,
|
|
"roles": ["admin", "support_agent"],
|
|
"exp": datetime.utcnow() + timedelta(hours=24),
|
|
}
|
|
token = jwt.encode(
|
|
payload,
|
|
get_settings().JWT_SECRET_KEY,
|
|
algorithm=get_settings().JWT_ALGORITHM,
|
|
)
|
|
|
|
html = f"""<!DOCTYPE html>
|
|
<html><head><meta charset="utf-8"><title>Test Login</title>
|
|
<style>
|
|
body {{ font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f3f4f6; }}
|
|
.card {{ background: white; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); text-align: center; max-width: 400px; }}
|
|
h1 {{ margin: 0 0 0.5rem; }}
|
|
p {{ color: #666; margin: 0 0 1.5rem; }}
|
|
a {{ display: inline-block; padding: 12px 32px; background: #2563eb; color: white; text-decoration: none; border-radius: 8px; font-weight: 500; }}
|
|
a:hover {{ background: #1d4ed8; }}
|
|
.token {{ background: #f9fafb; padding: 8px; border-radius: 6px; font-size: 11px; word-break: break-all; margin: 1rem 0; color: #666; }}
|
|
</style></head><body>
|
|
<div class="card">
|
|
<h1>Service Desk</h1>
|
|
<p>Тестовый вход выполнен</p>
|
|
<p style="font-size:14px"><b>Админ Тестов</b><br>admin@company.com<br>Роли: admin, support_agent</p>
|
|
<a href="/?token={token}">Открыть Service Desk</a>
|
|
<div class="token">JWT: {token[:50]}...</div>
|
|
</div>
|
|
</body></html>"""
|
|
return HTMLResponse(html)
|
|
|
|
|
|
@app.get("/quick-login")
|
|
async def quick_login():
|
|
"""Quick login - immediately redirect with token."""
|
|
from jose import jwt
|
|
from datetime import datetime, timedelta
|
|
from fastapi.responses import RedirectResponse
|
|
|
|
payload = {
|
|
"sub": "1",
|
|
"email": "admin@company.com",
|
|
"first_name": "Админ",
|
|
"last_name": "Тестов",
|
|
"is_active": True,
|
|
"roles": ["admin", "support_agent"],
|
|
"exp": datetime.utcnow() + timedelta(hours=24),
|
|
}
|
|
token = jwt.encode(
|
|
payload,
|
|
get_settings().JWT_SECRET_KEY,
|
|
algorithm=get_settings().JWT_ALGORITHM,
|
|
)
|
|
return RedirectResponse(url=f"/?token={token}", status_code=302)
|
|
# --- END TEST ---
|
|
|
|
|
|
def _run_email_fetch():
|
|
"""Background job: fetch emails from IMAP."""
|
|
try:
|
|
from app.workers.email_worker import fetch_incoming_emails
|
|
result = fetch_incoming_emails()
|
|
logger.info(f"Email fetch result: {result}")
|
|
except Exception as e:
|
|
logger.error(f"Email fetch error: {e}")
|
|
|
|
|
|
def _process_outbox():
|
|
"""Background job: try to send queued emails."""
|
|
try:
|
|
from app.services.email_outbox_service import EmailOutboxService
|
|
db = SessionLocal()
|
|
try:
|
|
svc = EmailOutboxService(db)
|
|
result = svc.process_queue()
|
|
if result["processed"] > 0:
|
|
logger.info(f"Outbox processed: {result}")
|
|
finally:
|
|
db.close()
|
|
except Exception as e:
|
|
logger.error(f"Outbox processing error: {e}")
|
|
|
|
|
|
def _get_fetch_interval() -> int:
|
|
"""Read fetch interval from DB (seconds)."""
|
|
from app.services.settings_service import SettingsService
|
|
db = SessionLocal()
|
|
try:
|
|
svc = SettingsService(db)
|
|
return max(60, int(svc.get_setting_value("email_fetch_interval", "300")))
|
|
except Exception:
|
|
return 300
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
"""Initialize database on startup."""
|
|
init_db()
|
|
|
|
from app.services.settings_service import SettingsService
|
|
db = SessionLocal()
|
|
try:
|
|
settings_service = SettingsService(db)
|
|
settings_service.initialize_defaults()
|
|
logger.info("Settings initialized")
|
|
except Exception as e:
|
|
logger.error(f"Settings initialization error: {e}")
|
|
finally:
|
|
db.close()
|
|
|
|
# Start background schedulers
|
|
interval = _get_fetch_interval()
|
|
scheduler.add_job(_run_email_fetch, "interval", seconds=interval, id="email_fetch", replace_existing=True)
|
|
scheduler.add_job(_process_outbox, "interval", seconds=120, id="email_outbox", replace_existing=True)
|
|
scheduler.start()
|
|
logger.info(f"Schedulers started: email_fetch({interval}s), outbox(120s)")
|
|
|
|
logger.info("Database initialized successfully!")
|
|
if FRONTEND_DIR.exists():
|
|
logger.info(f"Frontend served from: {FRONTEND_DIR}")
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
"""Cleanup on shutdown."""
|
|
scheduler.shutdown(wait=False)
|
|
logger.info("Application shutting down...")
|
|
|
|
|
|
def reschedule_email_fetch():
|
|
"""Reschedule email fetch job with current interval from DB. Call after settings change."""
|
|
interval = _get_fetch_interval()
|
|
scheduler.reschedule_job("email_fetch", trigger="interval", seconds=interval)
|
|
logger.info(f"Email fetch rescheduled (interval={interval}s)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(
|
|
"app.main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=get_settings().APP_DEBUG
|
|
)
|