Files
poona-ams/backend/app/main.py
T

129 lines
3.9 KiB
Python

import logging
import os
import sys
import traceback
from contextlib import asynccontextmanager
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .core.db import SessionLocal, engine, get_scheduler_db
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
from .models import Base
from .routers import (
assets,
attachments,
auth,
calibration,
complaints,
contracts,
dashboard,
demo_equipment,
health,
insurance,
masters,
notifications,
pm,
reports,
settings,
users,
visits,
warranties,
)
from .services.alerts import run_alert_check
from .services.settings_service import ensure_default_settings
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
level=logging.INFO,
)
logger = logging.getLogger("poona_ams")
def _scheduled_alert_job() -> None:
try:
with get_scheduler_db() as db:
res = run_alert_check(db)
logger.info("Scheduled alert check finished: %s", res)
except Exception:
logger.exception("Scheduled alert check failed.")
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
ensure_default_settings(db)
db.commit()
logger.info("Database tables created/verified.")
scheduler: BackgroundScheduler | None = None
is_testing = bool(os.environ.get("PYTEST_CURRENT_TEST") or "pytest" in sys.modules)
if not is_testing:
_scheduled_alert_job()
scheduler = BackgroundScheduler(timezone="Asia/Kolkata")
scheduler.add_job(
_scheduled_alert_job,
trigger=CronTrigger(hour=6, minute=0, timezone="Asia/Kolkata"),
id="daily_alert_check",
replace_existing=True,
)
scheduler.start()
logger.info("APScheduler daily alert check started (06:00 Asia/Kolkata).")
logger.info("Poona Hospital AMS started.")
try:
yield
finally:
if scheduler is not None:
scheduler.shutdown(wait=False)
logger.info("APScheduler stopped.")
app = FastAPI(
title="Poona Hospital AMS",
version="0.1.0",
docs_url="/docs",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_exception_handler(CodedHTTPException, coded_http_exception_handler)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"Unhandled exception: {traceback.format_exc()}")
return JSONResponse(
status_code=500,
content={"detail": "An internal error occurred.", "code": "INTERNAL_ERROR"},
)
app.include_router(health.router, prefix="/api")
app.include_router(auth.router, prefix="/api")
app.include_router(settings.router, prefix="/api")
app.include_router(masters.router, prefix="/api")
app.include_router(users.router, prefix="/api")
app.include_router(assets.router, prefix="/api")
app.include_router(attachments.router, prefix="/api")
app.include_router(complaints.router, prefix="/api")
app.include_router(pm.router, prefix="/api")
app.include_router(calibration.router, prefix="/api")
app.include_router(contracts.router, prefix="/api")
app.include_router(warranties.router, prefix="/api")
app.include_router(insurance.router, prefix="/api")
app.include_router(demo_equipment.router, prefix="/api")
app.include_router(visits.router, prefix="/api")
app.include_router(notifications.router, prefix="/api")
app.include_router(dashboard.router, prefix="/api")
app.include_router(reports.router, prefix="/api")