Refactor all main.py

This commit is contained in:
Urtzi Alfaro
2025-09-29 13:13:12 +02:00
parent 4777e59e7a
commit befcc126b0
35 changed files with 2537 additions and 1993 deletions

View File

@@ -4,151 +4,51 @@ Supplier & Procurement Service FastAPI Application
"""
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import structlog
# Import core modules
from fastapi import FastAPI
from app.core.config import settings
from app.core.database import init_db, close_db
from app.core.database import database_manager
from app.api import suppliers, purchase_orders, deliveries
from shared.monitoring.health import router as health_router
from shared.monitoring.metrics import setup_metrics_early
# from shared.auth.decorators import setup_auth_middleware
logger = structlog.get_logger()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan management"""
# Startup
logger.info("Starting Supplier Service", version=settings.VERSION)
try:
# Initialize database
await init_db()
logger.info("Database initialized successfully")
yield
except Exception as e:
logger.error("Startup failed", error=str(e))
raise
finally:
# Shutdown
logger.info("Shutting down Supplier Service")
try:
await close_db()
logger.info("Database connections closed")
except Exception as e:
logger.error("Shutdown error", error=str(e))
# Create FastAPI application
app = FastAPI(
title=settings.APP_NAME,
description=settings.DESCRIPTION,
version=settings.VERSION,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url=f"{settings.API_V1_STR}/docs",
redoc_url=f"{settings.API_V1_STR}/redoc",
lifespan=lifespan
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Setup metrics
try:
setup_metrics_early(app, "suppliers-service")
logger.info("Metrics setup completed")
except Exception as e:
logger.error("Metrics setup failed", error=str(e))
# Setup authentication middleware (commented out - not implemented)
# setup_auth_middleware(app)
# Exception handlers
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
"""Handle validation errors"""
return JSONResponse(
status_code=400,
content={
"error": "Validation Error",
"detail": str(exc),
"type": "value_error"
}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
"""Handle general exceptions"""
logger.error(
"Unhandled exception",
error=str(exc),
path=request.url.path,
method=request.method
)
return JSONResponse(
status_code=500,
content={
"error": "Internal Server Error",
"detail": "An unexpected error occurred",
"type": "internal_error"
}
)
# Include routers
app.include_router(health_router, prefix="/health", tags=["health"])
app.include_router(suppliers.router, prefix=settings.API_V1_STR)
app.include_router(purchase_orders.router, prefix=settings.API_V1_STR)
app.include_router(deliveries.router, prefix=settings.API_V1_STR)
from shared.service_base import StandardFastAPIService
# Include enhanced performance tracking router
from app.api.performance import router as performance_router
app.include_router(performance_router, prefix=settings.API_V1_STR)
# Root endpoint
@app.get("/")
async def root():
"""Root endpoint with service information"""
return {
"service": settings.SERVICE_NAME,
"version": settings.VERSION,
"description": settings.DESCRIPTION,
"status": "running",
"docs_url": f"{settings.API_V1_STR}/docs",
"health_url": "/health"
}
class SuppliersService(StandardFastAPIService):
"""Suppliers Service with standardized setup"""
def __init__(self):
# Define expected database tables for health checks
suppliers_expected_tables = [
'suppliers', 'supplier_price_lists', 'purchase_orders', 'purchase_order_items',
'deliveries', 'delivery_items', 'supplier_quality_reviews', 'supplier_invoices',
'supplier_performance_metrics', 'supplier_alerts', 'supplier_scorecards',
'supplier_benchmarks', 'alert_rules'
]
# Service info endpoint
@app.get(f"{settings.API_V1_STR}/info")
async def service_info():
"""Service information endpoint"""
return {
"service": settings.SERVICE_NAME,
"version": settings.VERSION,
"description": settings.DESCRIPTION,
"api_version": "v1",
"environment": settings.ENVIRONMENT,
"features": [
super().__init__(
service_name="suppliers-service",
app_name=settings.APP_NAME,
description=settings.DESCRIPTION,
version=settings.VERSION,
cors_origins=settings.CORS_ORIGINS,
api_prefix=settings.API_V1_STR,
database_manager=database_manager,
expected_tables=suppliers_expected_tables
)
async def on_startup(self, app: FastAPI):
"""Custom startup logic for suppliers service"""
# Custom startup completed
pass
async def on_shutdown(self, app: FastAPI):
"""Custom shutdown logic for suppliers service"""
# Database cleanup is handled by the base class
pass
def get_service_features(self):
"""Return suppliers-specific features"""
return [
"supplier_management",
"vendor_onboarding",
"purchase_orders",
@@ -168,7 +68,22 @@ async def service_info():
"risk_assessment",
"benchmarking"
]
}
# Create service instance
service = SuppliersService()
# Create FastAPI app with standardized setup
app = service.create_app()
# Setup standard endpoints
service.setup_standard_endpoints()
# Include routers
service.add_router(suppliers.router)
service.add_router(purchase_orders.router)
service.add_router(deliveries.router)
service.add_router(performance_router)
if __name__ == "__main__":