Files
orion/app/modules/orders/routes/api/admin.py
Samir Boulahtit db56b34894 refactor: switch to full auto-discovery for module API routes
- Enhanced route discovery system with ROUTE_CONFIG support for custom
  prefix, tags, and priority
- Added get_admin_api_routes() and get_vendor_api_routes() helpers that
  return routes sorted by priority
- Added fallback discovery for routes/{frontend}.py when routes/api/
  doesn't exist
- Updated CMS module with ROUTE_CONFIG (prefix: /content-pages,
  priority: 100) to register last for catch-all routes
- Moved customers routes from routes/ to routes/api/ directory
- Updated orders module to aggregate exception routers into main routers
- Removed manual module router imports from admin and vendor API init
  files, replaced with auto-discovery loop

Modules now auto-discovered: billing, inventory, orders, marketplace,
cms, customers, analytics, loyalty, messaging, monitoring, dev-tools

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 12:42:25 +01:00

215 lines
6.5 KiB
Python

# app/modules/orders/routes/api/admin.py
"""
Admin order management endpoints.
Provides order management capabilities for administrators:
- View orders across all vendors
- View vendor-specific orders
- Update order status on behalf of vendors
- Order statistics and reporting
Admin Context: Uses admin JWT authentication.
Vendor selection is passed as a request parameter.
This router aggregates both order routes and exception routes.
"""
import logging
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_api, require_module_access
from app.core.database import get_db
from app.services.order_service import order_service
from models.schema.auth import UserContext
from app.modules.orders.schemas import (
AdminOrderItem,
AdminOrderListResponse,
AdminOrderStats,
AdminOrderStatusUpdate,
AdminVendorsWithOrdersResponse,
MarkAsShippedRequest,
OrderDetailResponse,
ShippingLabelInfo,
)
# Base router for orders
_orders_router = APIRouter(
prefix="/orders",
dependencies=[Depends(require_module_access("orders"))],
)
# Aggregate router that includes both orders and exceptions
admin_router = APIRouter()
logger = logging.getLogger(__name__)
# ============================================================================
# List & Statistics Endpoints
# ============================================================================
@_orders_router.get("", response_model=AdminOrderListResponse)
def get_all_orders(
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=500),
vendor_id: int | None = Query(None, description="Filter by vendor"),
status: str | None = Query(None, description="Filter by status"),
channel: str | None = Query(None, description="Filter by channel"),
search: str | None = Query(None, description="Search by order number or customer"),
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""
Get orders across all vendors with filtering.
Allows admins to view and filter orders across the platform.
"""
orders, total = order_service.get_all_orders_admin(
db=db,
skip=skip,
limit=limit,
vendor_id=vendor_id,
status=status,
channel=channel,
search=search,
)
return AdminOrderListResponse(
orders=[AdminOrderItem(**order) for order in orders],
total=total,
skip=skip,
limit=limit,
)
@_orders_router.get("/stats", response_model=AdminOrderStats)
def get_order_stats(
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""Get platform-wide order statistics."""
return order_service.get_order_stats_admin(db)
@_orders_router.get("/vendors", response_model=AdminVendorsWithOrdersResponse)
def get_vendors_with_orders(
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""Get list of vendors that have orders."""
vendors = order_service.get_vendors_with_orders_admin(db)
return AdminVendorsWithOrdersResponse(vendors=vendors)
# ============================================================================
# Order Detail & Update Endpoints
# ============================================================================
@_orders_router.get("/{order_id}", response_model=OrderDetailResponse)
def get_order_detail(
order_id: int,
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""Get order details including items and addresses."""
order = order_service.get_order_by_id_admin(db, order_id)
# Enrich with vendor info
response = OrderDetailResponse.model_validate(order)
if order.vendor:
response.vendor_name = order.vendor.name
response.vendor_code = order.vendor.vendor_code
return response
@_orders_router.patch("/{order_id}/status", response_model=OrderDetailResponse)
def update_order_status(
order_id: int,
status_update: AdminOrderStatusUpdate,
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""
Update order status.
Admin can update status and add tracking number.
Status changes are logged with optional reason.
"""
order = order_service.update_order_status_admin(
db=db,
order_id=order_id,
status=status_update.status,
tracking_number=status_update.tracking_number,
reason=status_update.reason,
)
logger.info(
f"Admin {current_admin.email} updated order {order.order_number} "
f"status to {status_update.status}"
)
db.commit()
return order
@_orders_router.post("/{order_id}/ship", response_model=OrderDetailResponse)
def mark_order_as_shipped(
order_id: int,
ship_request: MarkAsShippedRequest,
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""
Mark an order as shipped with optional tracking information.
This endpoint:
- Sets order status to 'shipped'
- Sets shipped_at timestamp
- Optionally stores tracking number, URL, and carrier
"""
order = order_service.mark_as_shipped_admin(
db=db,
order_id=order_id,
tracking_number=ship_request.tracking_number,
tracking_url=ship_request.tracking_url,
shipping_carrier=ship_request.shipping_carrier,
)
logger.info(
f"Admin {current_admin.email} marked order {order.order_number} as shipped"
)
db.commit()
return order
@_orders_router.get("/{order_id}/shipping-label", response_model=ShippingLabelInfo)
def get_shipping_label_info(
order_id: int,
db: Session = Depends(get_db),
current_admin: UserContext = Depends(get_current_admin_api),
):
"""
Get shipping label information for an order.
Returns the shipment number, carrier, and generated label URL
based on carrier settings.
"""
return order_service.get_shipping_label_info_admin(db, order_id)
# ============================================================================
# Aggregate routers
# ============================================================================
# Import exceptions router
from app.modules.orders.routes.api.admin_exceptions import admin_exceptions_router
# Include both routers into the aggregate admin_router
admin_router.include_router(_orders_router, tags=["admin-orders"])
admin_router.include_router(admin_exceptions_router, tags=["admin-order-exceptions"])