Files
bakery-ia/services/orders/app/main.py

139 lines
4.9 KiB
Python
Raw Normal View History

2025-08-21 20:28:14 +02:00
# ================================================================
# services/orders/app/main.py
# ================================================================
"""
Orders Service - FastAPI Application
2025-10-30 21:08:07 +01:00
Customer orders management service
2025-08-21 20:28:14 +02:00
"""
from fastapi import FastAPI, Request
2025-09-30 08:12:45 +02:00
from sqlalchemy import text
2025-08-21 20:28:14 +02:00
from app.core.config import settings
2025-09-29 13:13:12 +02:00
from app.core.database import database_manager
2025-08-21 20:28:14 +02:00
from app.api.orders import router as orders_router
2025-10-06 15:27:01 +02:00
from app.api.customers import router as customers_router
from app.api.order_operations import router as order_operations_router
2025-12-13 23:57:54 +01:00
from app.api import audit, internal_demo
2025-09-29 13:13:12 +02:00
from shared.service_base import StandardFastAPIService
2025-08-21 20:28:14 +02:00
2025-09-29 13:13:12 +02:00
class OrdersService(StandardFastAPIService):
"""Orders Service with standardized setup"""
2025-08-21 20:28:14 +02:00
2025-09-30 21:58:10 +02:00
expected_migration_version = "00001"
2025-09-30 08:12:45 +02:00
async def on_startup(self, app):
"""Custom startup logic including migration verification"""
await self.verify_migrations()
await super().on_startup(app)
async def verify_migrations(self):
"""Verify database schema matches the latest migrations."""
try:
async with self.database_manager.get_session() as session:
result = await session.execute(text("SELECT version_num FROM alembic_version"))
version = result.scalar()
if version != self.expected_migration_version:
self.logger.error(f"Migration version mismatch: expected {self.expected_migration_version}, got {version}")
raise RuntimeError(f"Migration version mismatch: expected {self.expected_migration_version}, got {version}")
self.logger.info(f"Migration verification successful: {version}")
except Exception as e:
self.logger.error(f"Migration verification failed: {e}")
raise
2025-09-29 13:13:12 +02:00
def __init__(self):
# Define expected database tables for health checks
orders_expected_tables = [
'customers', 'customer_contacts', 'customer_orders', 'order_items',
2025-10-30 21:08:07 +01:00
'order_status_history', 'audit_logs'
2025-09-29 13:13:12 +02:00
]
super().__init__(
service_name="orders-service",
app_name=settings.APP_NAME,
description=settings.DESCRIPTION,
version=settings.VERSION,
2025-10-06 15:27:01 +02:00
api_prefix="", # Empty because RouteBuilder already includes /api/v1
2025-09-29 13:13:12 +02:00
database_manager=database_manager,
expected_tables=orders_expected_tables
)
async def on_startup(self, app: FastAPI):
"""Custom startup logic for orders service"""
2025-10-30 21:08:07 +01:00
# REMOVED: Procurement scheduler service initialization
# Procurement scheduling is now handled by the Orchestrator Service
# which calls the Procurement Service's /auto-generate endpoint
pass
2025-09-29 13:13:12 +02:00
async def on_shutdown(self, app: FastAPI):
"""Custom shutdown logic for orders service"""
2025-10-30 21:08:07 +01:00
# REMOVED: Scheduler service shutdown
pass
2025-08-21 20:28:14 +02:00
2025-09-29 13:13:12 +02:00
def get_service_features(self):
"""Return orders-specific features"""
return [
"customer_management",
"order_processing",
2025-10-30 21:08:07 +01:00
"order_tracking"
2025-09-29 13:13:12 +02:00
]
2025-08-21 20:28:14 +02:00
2025-09-29 13:13:12 +02:00
# Create service instance
service = OrdersService()
# Create FastAPI app with standardized setup
app = service.create_app()
# Setup standard endpoints
service.setup_standard_endpoints()
2025-10-06 15:27:01 +02:00
# Include routers - organized by ATOMIC and BUSINESS operations
2025-11-02 20:24:44 +01:00
# IMPORTANT: Register specific routes (audit, customers) BEFORE parameterized routes (orders)
# to avoid route matching conflicts where {order_id} would match literal paths like "audit-logs"
# AUDIT: Audit log retrieval endpoints - Must be registered FIRST
service.add_router(audit.router)
2025-10-06 15:27:01 +02:00
# ATOMIC: Direct CRUD operations
# NOTE: Register customers_router BEFORE orders_router to ensure /customers
# matches before the parameterized /{order_id} route
2025-10-06 15:27:01 +02:00
service.add_router(customers_router)
service.add_router(orders_router)
2025-10-06 15:27:01 +02:00
# BUSINESS: Complex operations and workflows
service.add_router(order_operations_router)
2025-08-21 20:28:14 +02:00
2025-12-13 23:57:54 +01:00
# INTERNAL: Service-to-service endpoints - DEPRECATED: Replaced by script-based seed data loading
service.add_router(internal_demo.router, tags=["internal-demo"])
2025-10-30 21:08:07 +01:00
# REMOVED: test_procurement_scheduler endpoint
# Procurement scheduling is now triggered by the Orchestrator Service
2025-08-21 20:28:14 +02:00
@app.middleware("http")
async def logging_middleware(request: Request, call_next):
"""Add request logging middleware"""
import time
2025-09-30 13:32:51 +02:00
2025-08-21 20:28:14 +02:00
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
2025-09-30 13:32:51 +02:00
service.logger.info("HTTP request processed",
2025-08-21 20:28:14 +02:00
method=request.method,
url=str(request.url),
status_code=response.status_code,
process_time=round(process_time, 4))
2025-09-30 13:32:51 +02:00
2025-08-21 20:28:14 +02:00
return response
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=settings.DEBUG
)